diff --git a/AGENTS.md b/AGENTS.md index 3306cd92..9935238f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1137,6 +1137,30 @@ sources: `docs/postpartum-breastfeeding-research.md`. switching off takes exactly that back. - **No F*cking Health jokes here**: postpartum text is on the voice's safety list. +## Lab reports: read once, checked by the user, never a diagnosis + +**Read this before touching `service/LabReports.kt`, `ui/screens/LabReportsUi.kt` or the coach's +`labs` block.** Any lab report (blood, urine, hormones, anything) is added as a PDF from +My Health → Lab reports, and every marker is charted exam by exam. + +- **Pages go to the model as images, not as a PDF** (`PdfRenderer`, 1600 px, up to 10 pages), so + every coach provider reads them, the custom/local one included. The PDF is sent once, when the + user adds it; afterwards the coach reads the stored values (`LabContext`), never the file. +- **Nothing is saved until the user checks it.** The read lands on a review screen where every + value, unit and range is editable and rows can be removed. Don't add an auto-save path. +- **The flag is computed, not taken from the model**: a numeric value with a printed range is judged + against that range (`LabReports.flagFor`); the model's marking only stands when there is no number + or no range. The range is the lab's own and is stored per result, because labs and methods differ. +- **One marker, one key, across labs and languages** (`markerKey`, from the model's snake_case + English `key`, normalised). The chart follows the key, so a key change splits a marker's history. +- **It never diagnoses.** No condition named, no value called fine or dangerous beyond "inside / outside + the lab's range", anything outside the range or trending badly goes to "your doctor", and never a + medication, supplement or dose. The coach's `LabContext.note` and its prompt line say the same; keep + them in step. Goals change only through `set_goal` after the user agrees to the exact numbers. +- **The coach's use of the results is a switch on the Lab reports screen** (`LabPrefs.coachUses`). +- **Reports, results and each PDF (as base64) ride in the backup archive**, and the switch rides in + `ArchivedSettings`. Deleting a report removes its results (FK cascade) and its PDF file. + ## The design files and the app move together, both ways **Every change to the app's UI updates the design files in the same piece of work, and every diff --git a/app/src/main/assets/i18n/pt-BR.json b/app/src/main/assets/i18n/pt-BR.json index 11ee3f47..3aa70270 100644 --- a/app/src/main/assets/i18n/pt-BR.json +++ b/app/src/main/assets/i18n/pt-BR.json @@ -131,8 +131,10 @@ "Activity type": "Tipo de atividade", "Add": "Adicionar", "Add Widget": "Adicionar widget", + "Add a lab report (PDF)": "Adicionar laudo (PDF)", "Add a ring": "Adicionar um anel", "Add a workout you forgot to record": "Adicione um treino que você esqueceu de gravar", + "Add any lab report as a PDF: blood, urine, hormones or anything else. The coach reads it, you check the values, and every marker gets a chart across your exams.": "Adicione qualquer laudo em PDF: sangue, urina, hormônios ou qualquer outro. O coach lê, você confere os valores, e cada marcador ganha um gráfico ao longo dos seus exames.", "Add by hand": "Adicionar manualmente", "Add medication or supplement": "Adicionar medicamento ou suplemento", "Add stravaClientId and stravaClientSecret to local.properties to enable Strava integration.": "Adicione stravaClientId e stravaClientSecret ao local.properties para ativar a integração com o Strava.", @@ -190,6 +192,7 @@ "Arroz branco": "Arroz branco", "Ask the coach": "Perguntar ao coach", "Ask the coach about it": "Pergunte ao coach", + "Ask the coach for a plan": "Pedir um plano ao coach", "Ask the coach...": "Pergunte ao coach...", "Asleep {0}": "Dormindo {0}", "At 1% of body weight a week this takes about {0} days.": "A 1% do peso corporal por semana, isso leva cerca de {0} dias.", @@ -250,6 +253,7 @@ "Below the typical resting range. Often fine, but worth noting if you feel faint.": "Abaixo da faixa típica em repouso. Geralmente tudo bem, mas vale atenção se você sentir tontura.", "Beta-blockers": "Betabloqueadores", "Beta-blockers lower heart rate; this is expected on that medication.": "Betabloqueadores reduzem a frequência cardíaca; isso é esperado com esse medicamento.", + "Blood": "Sangue", "Blood Pressure": "Pressão arterial", "Blood glucose": "Glicose no sangue", "Blood oxygen": "Oxigênio no sangue", @@ -261,6 +265,7 @@ "Blood pressure of 160/110 or higher is an emergency. A ring's blood pressure isn't validated: confirm with a cuff, and never let a normal ring reading reassure you.": "Pressão de 160/110 ou mais é uma emergência. A pressão medida pelo anel não é validada: confirme com um medidor de braço e nunca se tranquilize com uma leitura normal do anel.", "Blood sugar": "Glicemia", "Blood sugar calibration": "Calibração da glicemia", + "Blood, urine and any other lab report, charted exam by exam": "Sangue, urina e qualquer outro laudo, em gráficos exame a exame", "Bluetooth access needed": "Acesso ao Bluetooth necessário", "Bluetooth is off": "Bluetooth desativado", "Body clock": "Relógio biológico", @@ -319,6 +324,7 @@ "Charge before bed": "Carregue antes de dormir", "Charge your ring before bed": "Carregue seu anel antes de dormir", "Chart": "Gráfico", + "Check every value against the PDF before saving. Fix anything the coach misread.": "Confira cada valor com o PDF antes de salvar. Corrija o que o coach leu errado.", "Check finished: resume Health Connect export": "Verificação concluída: retomar exportação para o Health Connect", "Choose": "Escolher", "Choose Metric": "Escolher métrica", @@ -339,6 +345,7 @@ "Coach is thinking…": "O coach está pensando…", "Cocktail": "Coquetel", "Collapsed": "Recolhido", + "Collected on": "Coletado em", "Collecting: needs {0} days with at least {1} steps on both. Carry your phone as usual.": "Coletando: são necessários {0} dias com pelo menos {1} passos em ambos. Leve o celular como de costume.", "Compare my ring with this": "Comparar meu anel com isto", "Compare with my phone": "Comparar com meu celular", @@ -376,11 +383,13 @@ "Cost estimates aren't available for on-device or custom models.": "Estimativas de custo não estão disponíveis para modelos locais ou personalizados.", "Could not export diagnostics.": "Não foi possível exportar os diagnósticos.", "Could not open browser": "Não foi possível abrir o navegador", + "Couldn't copy that file.": "Não foi possível copiar esse arquivo.", "Couldn't delete this record": "Não foi possível excluir este registro", "Couldn't get a steady reading. Keep the ring snug and your hand still, then try again.": "Não foi possível obter uma leitura estável. Mantenha o anel justo e a mão parada, e tente de novo.", "Couldn't load your health history.": "Não foi possível carregar seu histórico de saúde.", "Couldn't load {0} trends.": "Não foi possível carregar as tendências de {0}.", "Couldn't look up that barcode. Check your connection or enter the meal manually.": "Não foi possível consultar esse código de barras. Verifique sua conexão ou insira a refeição manualmente.", + "Couldn't open that PDF. It may be protected by a password or damaged.": "Não foi possível abrir esse PDF. Ele pode ter senha ou estar danificado.", "Couldn't process that photo. Try again or describe the meal.": "Não foi possível processar essa foto. Tente de novo ou descreva a refeição.", "Couldn't reach the server.": "Não foi possível acessar o servidor.", "Couldn't read Health Connect. Try again in a moment.": "Não foi possível ler o Health Connect. Tente de novo em instantes.", @@ -441,12 +450,14 @@ "Delete meal?": "Excluir refeição?", "Delete memory?": "Excluir memória?", "Delete old data & import": "Excluir dados antigos e importar", + "Delete report": "Excluir laudo", "Delete this activity record": "Excluir este registro de atividade", "Delete this activity record?": "Excluir este registro de atividade?", "Delete this reading": "Excluir esta leitura", "Delete this reading?": "Excluir esta leitura?", "Delete this record": "Excluir este registro", "Delete this record?": "Excluir este registro?", + "Delete this report?": "Excluir este laudo?", "Delete workout": "Excluir treino", "Delete workout?": "Excluir treino?", "Delete {0}": "Excluir {0}", @@ -468,6 +479,7 @@ "Diastolic": "Diastólica", "Dinner": "Jantar", "Disabled": "Desativado", + "Discard": "Descartar", "Disconnect": "Desconectar", "Disconnect Strava?": "Desconectar o Strava?", "Disconnected": "Desconectado", @@ -502,6 +514,7 @@ "Edit": "Editar", "Edit goals": "Editar metas", "Edit life stage": "Editar fase da vida", + "Edit marker": "Editar marcador", "Edit sleep record": "Editar registro de sono", "Edit this record's times": "Editar os horários deste registro", "Edit workout": "Editar treino", @@ -547,6 +560,7 @@ "Evening": "Noite", "Evening check-in": "Check-in da noite", "Evening type": "Vespertino", + "Every exam": "Todos os exames", "Every {0} min": "A cada {0} min", "Everything compared agrees within its band.": "Tudo o que foi comparado está dentro da faixa.", "Excellent": "Excelente", @@ -621,6 +635,7 @@ "Fresh": "Descansado", "From the next-meal suggestion": "Da sugestão de próxima refeição", "From the user's smart scale via Health Connect. Day-to-day weight swings are mostly water; talk about the trend only.": "Da balança inteligente do usuário via Health Connect. As oscilações diárias de peso são principalmente água; fale apenas da tendência.", + "From these results, with goals you approve": "A partir destes resultados, com metas que você aprova", "From {0}": "De {0}", "Gemini": "Gemini", "Gemini API Key": "Chave de API do Gemini", @@ -703,6 +718,7 @@ "High stress score. Wellness estimate, not a diagnosis.": "Pontuação de estresse alta. Estimativa de bem-estar, não um diagnóstico.", "Higher risk": "Risco maior", "Hiking": "Trilha", + "Hormones": "Hormônios", "How am I doing on my goal? What should I focus on this week?": "Como estou indo na minha meta? No que devo focar esta semana?", "How am I doing today?": "Como estou hoje?", "How can I sleep better?": "Como posso dormir melhor?", @@ -744,6 +760,7 @@ "In between": "Intermediário", "In drinks, roughly": "Em doses, aproximadamente", "In line with your usual {0} ms": "Dentro do seu habitual de {0} ms", + "In range": "Na faixa", "In sync": "Em sincronia", "In the Oura app: Settings → Health Connect, and turn on sharing. Then come back and look again.": "No app Oura: Configurações → Health Connect, e ative o compartilhamento. Depois volte e verifique novamente.", "Inactivity": "Inatividade", @@ -754,7 +771,9 @@ "Install Health Connect": "Instalar Health Connect", "Iogurte natural": "Iogurte natural", "It changes what PulseLoop shows and what it works out from it (zones, resting baseline, calorie estimate). Your ring's stored readings and what goes to Health Connect stay as measured.": "Isso muda o que o PulseLoop mostra e o que ele calcula a partir disso (zonas, linha de base em repouso, estimativa de calorias). As leituras guardadas do anel e o que vai para o Health Connect ficam como foram medidos.", + "It reads the values you saved, never the PDF again.": "Ele lê os valores que você salvou, nunca mais o PDF.", "It's at {0}%. A short charge now keeps tonight's sleep tracked.": "Está em {0}%. Uma carga rápida agora garante o registro do sono desta noite.", + "Its markers and its PDF are removed from this phone.": "Os marcadores e o PDF dele são removidos deste celular.", "Journal": "Diário", "Keep": "Manter", "Keep going": "Continue", @@ -771,6 +790,9 @@ "LAST NIGHT": "ONTEM À NOITE", "LEFT METRIC": "MÉTRICA DA ESQUERDA", "LIFE STAGE": "FASE DA VIDA", + "Lab report": "Laudo", + "Lab reports": "Laudos", + "Laboratory": "Laboratório", "Language": "Idioma", "Laranja": "Laranja", "Last 14 nights, recent nights weigh more": "Últimas 14 noites, as mais recentes pesam mais", @@ -794,6 +816,7 @@ "Later than your usual cycle length. Log it when it starts.": "Mais tarde que a duração habitual do seu ciclo. Registre quando começar.", "Latest": "Mais recente", "Latest {0}: {1} {2} · average {3} {4}": "{0} mais recente: {1} {2} · média {3} {4}", + "Latest: {0}": "Último: {0}", "Lean {0} {1}": "Massa magra {0} {1}", "Learned from nights you woke recovered": "Aprendido com noites em que você acordou recuperado", "Learning": "Aprendendo", @@ -806,6 +829,7 @@ "Less": "Menos", "Less than monthly": "Menos de uma vez por mês", "Let my goal manage these": "Deixar minha meta gerenciar isso", + "Let the coach use these results": "Deixar o coach usar estes resultados", "Lets the coach read your data. Detect sets this for you; turn it off if your server rejects tools (vLLM needs --enable-auto-tool-choice).": "Permite que o coach leia seus dados. Detectar define isso para você; desative se o seu servidor rejeitar ferramentas (o vLLM precisa de --enable-auto-tool-choice).", "Library": "Biblioteca", "License": "Licença", @@ -860,6 +884,8 @@ "MOOD CHECK-IN": "CHECK-IN DE HUMOR", "MY WEEK": "MINHA SEMANA", "Major signs": "Sinais fortes", + "Make me a plan from my lab reports, starting with {0}.": "Monte um plano para mim a partir dos meus laudos, começando por {0}.", + "Make me a plan from my lab reports.": "Monte um plano para mim a partir dos meus laudos.", "Male": "Masculino", "Mamão papaia": "Mamão papaia", "Manage in Android settings": "Gerenciar nas configurações do Android", @@ -936,6 +962,7 @@ "Never": "Nunca", "Never mind": "Deixa pra lá", "New chat": "Nova conversa", + "New lab report": "Novo laudo", "Next": "Próximo", "Next day": "Próximo dia", "Next period around {0} (in {1} day{2}), from your usual {3}-day cycle.": "Próxima menstruação por volta de {0} (em {1} dia{2}), com base no seu ciclo habitual de {3} dias.", @@ -954,6 +981,7 @@ "No access granted. You can allow it in Health Connect's settings.": "Acesso não concedido. Você pode permitir nas configurações do Health Connect.", "No accuracy check for this ring yet. Corrections from another ring don't carry over.": "Ainda não há verificação de precisão para este anel. Correções de outro anel não são aproveitadas.", "No activity records synced for {0} yet.": "Nenhum registro de atividade sincronizado para {0} ainda.", + "No app on this phone opens PDFs.": "Nenhum app deste celular abre PDFs.", "No app wrote health data in the last {0} days.": "Nenhum app gravou dados de saúde nos últimos {0} dias.", "No blood pressure data yet.": "Ainda não há dados de pressão arterial.", "No blood sugar data yet.": "Ainda não há dados de glicemia.", @@ -974,8 +1002,10 @@ "No obvious signs in your biometrics of something straining your body.": "Nenhum sinal claro nos seus dados biométricos de algo sobrecarregando seu corpo.", "No other app wrote readable data in the last {0} days.": "Nenhum outro app gravou dados legíveis nos últimos {0} dias.", "No period since 8 weeks after birth": "Sem menstruação desde 8 semanas após o parto", + "No range": "Sem faixa", "No readiness today: {0}. Wear the ring snugly tonight.": "Sem prontidão hoje: {0}. Use o anel bem ajustado esta noite.", "No reading": "Sem leitura", + "No results were found in that report.": "Nenhum resultado foi encontrado nesse laudo.", "No ring connected": "Nenhum anel conectado", "No ring paired": "Nenhum anel pareado", "No rings found yet": "Nenhum anel encontrado ainda", @@ -1014,6 +1044,7 @@ "Not enough yearly data": "Dados anuais insuficientes", "Not enough {0} data for this view yet.": "Ainda não há dados de {0} suficientes para esta visualização.", "Not enough {0} data yet": "Ainda não há dados de {0} suficientes", + "Not found: set the date": "Não encontrada: defina a data", "Not imported yet": "Ainda não importado", "Not measured": "Não medido", "Not now": "Agora não", @@ -1045,6 +1076,7 @@ "Only needed if you started the server with --api-key. Leave blank otherwise.": "Só é necessário se você iniciou o servidor com --api-key. Caso contrário, deixe em branco.", "Only new data from now on": "Apenas dados novos daqui em diante", "Only providers that don't retain data": "Apenas provedores que não retêm dados", + "Only the first {0} pages were read.": "Só as primeiras {0} páginas foram lidas.", "Only {0} day(s) of food logged this week; intake may be incomplete.": "Só {0} dia(s) com refeições registradas nesta semana; o consumo pode estar incompleto.", "Only {0} kcal left: ": "Restam só {0} kcal: ", "Open": "Abrir", @@ -1075,6 +1107,8 @@ "Out of sync": "Fora de sincronia", "Outdoor or treadmill runs": "Corridas ao ar livre ou na esteira", "Output tokens": "Tokens de saída", + "Outside range": "Fora da faixa", + "Outside the lab's range on {0}. Worth bringing to your doctor.": "Fora da faixa do laboratório em {0}. Vale levar ao seu médico.", "Outside your usual last night: {0}": "Fora do seu normal na noite passada: {0}", "Overwhelming tiredness": "Cansaço extremo", "Ovos mexidos": "Ovos mexidos", @@ -1162,11 +1196,15 @@ "REM sleep": "Sono REM", "REM sleep supports memory and mood. It usually makes up 20 to 25% of a night, about 90 minutes or more.": "O sono REM ajuda a memória e o humor. Normalmente ocupa de 20 a 25% da noite, cerca de 90 minutos ou mais.", "RIGHT METRIC": "MÉTRICA DA DIREITA", + "Range high": "Faixa máxima", + "Range low": "Faixa mínima", "Raw Packets": "Pacotes brutos", "Re-analyze": "Reanalisar", "Readiness": "Prontidão", "Readiness is estimated by PulseLoop from your ring's sleep, heart rate, HRV and activity, compared with your own recent nights. It is not a medical measurement.": "A Prontidão é estimada pelo PulseLoop a partir do sono, da frequência cardíaca, da HRV e da atividade medidos pelo anel, comparados com suas próprias noites recentes. Não é uma medida médica.", "Reading (mg/dL)": "Medição (mg/dL)", + "Reading a report needs the coach enabled with a configured provider (Settings → AI Coach).": "Ler um laudo precisa do coach ligado e com um provedor configurado (Configurações → Coach de IA).", + "Reading failed: {0}": "A leitura falhou: {0}", "Reading your drinks…": "Lendo suas bebidas…", "Reading your history…": "Lendo seu histórico…", "Ready to start the day? Take a measurement and I'll help you plan it.": "Pronto para começar o dia? Faça uma medição e eu ajudo você a planejá-lo.", @@ -1181,6 +1219,7 @@ "Recovery time": "Tempo de recuperação", "Recovery, nights, mood check-in and warning signs": "Recuperação, noites, check-in de humor e sinais de alerta", "Reference device": "Dispositivo de referência", + "Reference: {0}": "Referência: {0}", "Refresh": "Atualizar", "Relaxed": "Relaxado", "Reliable background sync": "Sincronização em segundo plano confiável", @@ -1196,6 +1235,7 @@ "Replace all data?": "Substituir todos os dados?", "Report": "Relatório", "Report ready": "Relatório pronto", + "Reports": "Laudos", "Reseed": "Recriar", "Reseed Demo Data": "Recriar dados de demonstração", "Reseed Demo Data?": "Recriar dados de demonstração?", @@ -1263,8 +1303,10 @@ "Save measurement settings": "Salvar configurações de medição", "Save plan": "Salvar plano", "Save profile": "Salvar perfil", + "Save {0} markers": "Salvar {0} marcadores", "Saved": "Salvo", "Saved & sent to ring ✓": "Salvo e enviado ao anel ✓", + "Saved {0} markers": "{0} marcadores salvos", "Saved — will sync on next connect": "Salvo — será sincronizado na próxima conexão", "Saved ✓": "Salvo ✓", "Saves the same file as Export to a folder you choose, and keeps the latest 5.": "Salva o mesmo arquivo de Exportar em uma pasta que você escolher e mantém os 5 mais recentes.", @@ -1308,6 +1350,7 @@ "Severe range (diastolic >120). Seek care if confirmed.": "Faixa grave (diastólica >120). Procure atendimento se confirmado.", "Severe range (systolic >180). Seek care if confirmed.": "Faixa grave (sistólica >180). Procure atendimento se confirmado.", "Sex": "Sexo", + "Shaded: the lab's reference range. Amber points are outside it.": "Área pontilhada: a faixa de referência do laboratório. Pontos em amarelo estão fora dela.", "Shaded: your usual range over the last 30 days": "Área sombreada: sua faixa habitual nos últimos 30 dias", "Share": "Compartilhar", "Share accuracy report": "Compartilhar relatório de precisão", @@ -1415,6 +1458,7 @@ "Steps a day": "Passos por dia", "Steps collected": "Passos coletados", "Steps {0}{1}%": "Passos {0}{1}%", + "Stool": "Fezes", "Stop scanning": "Parar busca", "Stop using Health Connect": "Parar de usar o Health Connect", "Stored securely in Android Keystore. Never leaves your device except to call the model. Provider changes apply from your next message.": "Armazenada com segurança no Android Keystore. Nunca sai do seu dispositivo, exceto para chamar o modelo. Mudanças de provedor valem a partir da sua próxima mensagem.", @@ -1468,6 +1512,8 @@ "Take the check": "Fazer o teste", "Taken": "Tomado", "Talk it through": "Conversar sobre isso", + "Tap a report to open its PDF.": "Toque em um laudo para abrir o PDF.", + "Tap a row to fix or remove it.": "Toque em uma linha para corrigir ou remover.", "Tap to start": "Toque para começar", "Tapioca com ovo": "Tapioca com ovo", "Tatá, te amo!": "Tatá, te amo!", @@ -1476,6 +1522,7 @@ "Temperature": "Temperatura", "Temperature trend": "Tendência de temperatura", "Ten quick questions about the last 7 days, used by health services worldwide to spot postpartum depression early.": "Dez perguntas rápidas sobre os últimos 7 dias, usadas por serviços de saúde no mundo todo para identificar cedo a depressão pós-parto.", + "That PDF has no pages to read.": "Esse PDF não tem páginas para ler.", "That app shares nothing PulseLoop can compare.": "Esse app não compartilha nada que o PulseLoop possa comparar.", "That looks like PulseLoop's own data coming back through a sync app, so this report would compare the ring with itself. Check the sync direction in that app.": "Parecem ser dados do próprio PulseLoop voltando por um app de sincronização, então este relatório compararia o anel com ele mesmo. Verifique a direção da sincronização nesse app.", "The AI didn't return a usable estimate. Try again or enter the meal manually.": "A IA não retornou uma estimativa utilizável. Tente novamente ou insira a refeição manualmente.", @@ -1483,10 +1530,13 @@ "The WHO's short alcohol check (AUDIT-C). Three questions, under a minute. A screen, not a diagnosis.": "O teste rápido sobre álcool da OMS (AUDIT-C). Três perguntas, menos de um minuto. Uma triagem, não um diagnóstico.", "The activity must end in the past.": "A atividade precisa terminar no passado.", "The coach also replies in the language you choose.": "O coach também responde no idioma que você escolher.", + "The coach couldn't read results from that report. Try again, or try a clearer PDF.": "O coach não conseguiu ler os resultados desse laudo. Tente de novo, ou use um PDF mais nítido.", + "The coach is reading the report. This can take a minute.": "O coach está lendo o laudo. Isso pode levar um minuto.", "The coach will forget \"{0}\". This can't be undone.": "O Coach vai esquecer \"{0}\". Isso não pode ser desfeito.", "The date needs more of a deficit than is safe; the suggestion is held at the floor.": "A data exige um déficit maior do que o seguro; a sugestão fica no limite mínimo.", "The import failed. Try again in a moment.": "A importação falhou. Tente novamente em instantes.", "The report covers the days so far. You'll then choose what happens to the paused Health Connect export.": "O relatório abrange os dias até agora. Depois você escolherá o que acontece com a exportação pausada para o Health Connect.", + "The report printed no range for this marker.": "O laudo não trouxe faixa de referência para este marcador.", "The ring disconnected during measurement.": "O anel se desconectou durante a medição.", "The ring isn't detecting your finger. Put it on snugly, then try again.": "O anel não está detectando seu dedo. Coloque-o bem justo e tente novamente.", "The ring recorded this as one record": "O anel registrou isto como um único registro", @@ -1510,6 +1560,7 @@ "This permanently deletes everything currently in the app and replaces it with the contents of this file. This can't be undone.": "Isso exclui permanentemente tudo o que está no app e substitui pelo conteúdo deste arquivo. Não é possível desfazer.", "This permanently erases all your data — metrics, sleep, activity, coach history, settings, and saved API keys — and can't be undone.": "Isso apaga permanentemente todos os seus dados — métricas, sono, atividade, histórico do coach, configurações e chaves de API salvas — e não pode ser desfeito.", "This record runs {0} – {1}. You can only shorten it.": "Este registro vai de {0} a {1}. Você só pode encurtá-lo.", + "This report's PDF isn't on this phone.": "O PDF deste laudo não está neste celular.", "This score suggests depression is likely. Please talk to your doctor, nurse or midwife this week.": "Esta pontuação sugere que a depressão é provável. Por favor, converse com seu médico, enfermeira ou obstetriz ainda esta semana.", "This score suggests possible depression. Talk to your doctor, nurse or midwife soon.": "Esta pontuação sugere possível depressão. Converse em breve com seu médico, enfermeira ou obstetriz.", "This unbinds the ring and removes it from the app. Your synced data is kept, but you'll need to pair the ring again to keep syncing.": "Isso desvincula o anel e o remove do app. Seus dados sincronizados são mantidos, mas você precisará parear o anel novamente para continuar sincronizando.", @@ -1574,6 +1625,7 @@ "Under 100 steps in an hour, 9:00 to 20:00, at most every two hours. Off in Rest Mode.": "Menos de 100 passos em uma hora, das 9:00 às 20:00, no máximo a cada duas horas. Desativado no Modo descanso.", "Under 100 steps in the last hour. A few minutes on your feet helps your energy and your sleep.": "Menos de 100 passos na última hora. Alguns minutos de pé ajudam sua energia e seu sono.", "Undo": "Desfazer", + "Unit": "Unidade", "Units": "Unidades", "Unpair & Reset": "Desparear e redefinir", "Unpair & reset": "Desparear e redefinir", @@ -1591,6 +1643,7 @@ "Upload failed: {0}": "Falha no envio: {0}", "Uploaded 1 workout": "1 treino enviado", "Uploaded {0} workouts": "{0} treinos enviados", + "Urine": "Urina", "Usage & cost": "Uso e custo", "Use location & weather": "Usar localização e clima", "Use the device you already wear": "Use o dispositivo que você já usa", @@ -1608,6 +1661,9 @@ "Usual price of a drink (optional)": "Preço habitual de uma bebida (opcional)", "Usual sleep midpoint {0} · this week {1}": "Ponto médio habitual do sono {0} · esta semana {1}", "VO₂ max": "VO₂ máx", + "Value": "Valor", + "Values": "Valores", + "Values come from your reports as you checked them. PulseLoop doesn't diagnose; the ranges are the lab's own.": "Os valores vêm dos seus laudos, como você os conferiu. O PulseLoop não faz diagnóstico; as faixas são as do próprio laboratório.", "Variable nights": "Noites irregulares", "Version": "Versão", "Very high": "Muito alto", @@ -1751,10 +1807,12 @@ "Your workout is still recording. Finish it now, or keep recording?": "Seu treino ainda está sendo gravado. Finalizar agora ou continuar gravando?", "a {0} fits.": "cabe um(a) {0}.", "above": "acima", + "above {0}": "acima de {0}", "any meal": "qualquer refeição", "avg {0} bpm": "média {0} bpm", "bed {0}": "deitar {0}", "below": "abaixo", + "below {0}": "abaixo de {0}", "compared over the {0} h both were on": "comparado nas {0} h em que os dois estavam ligados", "daily calories": "calorias diárias", "daily calories {0} kcal": "calorias diárias {0} kcal", @@ -1780,6 +1838,7 @@ "nothing logged yet": "nada registrado ainda", "of {0}": "de {0}", "of {0} this week": "de {0} esta semana", + "reports · {0} markers tracked": "laudos · {0} marcadores acompanhados", "resting HR {0}{1}": "HR em repouso {0}{1}", "resting heart rate {0} bpm {1}": "frequência cardíaca em repouso {0} bpm {1}", "resting heart rate {0}{1} bpm": "frequência cardíaca em repouso {0}{1} bpm", @@ -1825,6 +1884,9 @@ "{0} inactive {1} since {2}:00": "{0} {1} sem se mexer desde as {2}:00", "{0} is retiring this model on {1}.": "{0} vai descontinuar este modelo em {1}.", "{0} left this week": "Restam {0} esta semana", + "{0} markers": "{0} marcadores", + "{0} markers found": "{0} marcadores encontrados", + "{0} markers outside the lab's range in your latest report. Talk them over with your doctor.": "{0} marcadores fora da faixa do laboratório no seu último laudo. Converse sobre eles com seu médico.", "{0} min a night less than your usual over the last 7 nights.": "{0} min por noite a menos que o seu habitual nas últimas 7 noites.", "{0} min a night more than your usual over the last 7 nights.": "{0} min por noite a mais que o seu habitual nas últimas 7 noites.", "{0} min {1} sleep": "{0} min de sono {1}", @@ -1844,6 +1906,7 @@ "{0} of {1} tracked": "{0} de {1} registrados", "{0} over your limit": "{0} acima do seu limite", "{0} packets captured": "{0} pacotes capturados", + "{0} pages · read by the coach": "{0} páginas · lido pelo coach", "{0} pts": "{0} pts", "{0} recent": "{0} recentes", "{0} rest {1} in the last 7": "{0} {1} de descanso nos últimos 7", @@ -1863,6 +1926,7 @@ "{0} years": "{0} anos", "{0} {1} in the last 7 days": "{0} {1} nos últimos 7 dias", "{0} · ring {1} · {2} {3}": "{0} · anel {1} · {2} {3}", + "{0} · the lab's range is {1}": "{0} · a faixa do laboratório é {1}", "{0} · {1} drink": "{0} · {1} bebida", "{0} · {1} readings · {2} on average": "{0} · {1} leituras · {2} em média", "{0} – {1} leaves tonight's totals and the hypnogram, and it won't come back on re-sync.": "{0} – {1} sai dos totais desta noite e do hipnograma, e não volta numa nova sincronização.", diff --git a/app/src/main/java/com/pulseloop/PulseLoopApplication.kt b/app/src/main/java/com/pulseloop/PulseLoopApplication.kt index ad83d4c1..39434c54 100644 --- a/app/src/main/java/com/pulseloop/PulseLoopApplication.kt +++ b/app/src/main/java/com/pulseloop/PulseLoopApplication.kt @@ -28,6 +28,7 @@ class PulseLoopApplication : Application() { CrashLogger.install(this) com.pulseloop.service.DrinkPrefs.init(this) com.pulseloop.service.Postpartum.init(this) + com.pulseloop.service.LabPrefs.init(this) com.pulseloop.ui.theme.FairyMode.init(this) com.pulseloop.ui.i18n.L10n.init(this) com.pulseloop.health.source.HealthConnectSource.isEnabled(this) // warms [HealthConnectSource.enabledNow] diff --git a/app/src/main/java/com/pulseloop/coach/context/CoachContextBuilder.kt b/app/src/main/java/com/pulseloop/coach/context/CoachContextBuilder.kt index f645d463..dff3f219 100644 --- a/app/src/main/java/com/pulseloop/coach/context/CoachContextBuilder.kt +++ b/app/src/main/java/com/pulseloop/coach/context/CoachContextBuilder.kt @@ -111,6 +111,7 @@ object CoachContextBuilder { primaryGoal = runCatching { com.pulseloop.service.GoalPlan.load(db, now) }.getOrNull(), drinks = com.pulseloop.service.DrinksContext.build(db, now), postpartum = com.pulseloop.service.PostpartumContext.build(), + labs = runCatching { com.pulseloop.service.LabContext.build(db) }.getOrNull(), ) } diff --git a/app/src/main/java/com/pulseloop/coach/context/CoachPromptBuilder.kt b/app/src/main/java/com/pulseloop/coach/context/CoachPromptBuilder.kt index 861b03cc..05a90ef6 100644 --- a/app/src/main/java/com/pulseloop/coach/context/CoachPromptBuilder.kt +++ b/app/src/main/java/com/pulseloop/coach/context/CoachPromptBuilder.kt @@ -29,6 +29,7 @@ Core behavior: - When a goal exists, tie advice to it. Call get_goal for anything about progress, calories or what to eat or do; start from its `levers` marked short, and use its numbers as given: the scale's trend, the suggested intake against what they burn and log, protein, sleep and steps. Name the one or two levers that matter most this week (e.g. "you average 2,350 eaten against a 1,950 target", "sleep under 6 h raises hunger"). Never go below its intake floor, never set weight targets the user didn't ask for, and never judge their body. - Meal suggestions: the Nutrition screen shows a next-meal idea (call suggest_next_meal to see the same one). When the user wants alternatives, offer two or three everyday Brazilian options or common fruits that fit the calories left and the protein gap, with rough kcal. When they push back with something they prefer, check it against the goal (get_goal) and the calories left: if it fits, agree and call save_food_preference so future suggestions use it; if it doesn't, say why and offer a version that fits (a smaller portion, a different time). Don't save a preference the user didn't agree to. - Drinks: when the packet has a `drinks` block, the user is cutting down on alcohol and tracks it. Be warm and matter-of-fact, never moralising; no "relapse", "sober" or labels. Use their own numbers (this week against the limit, dry days, tonight's plan, what drinking did to their nights from `lastNightEffect`) and say these effects are a pattern in their data, not proof. Help them plan: a number for tonight decided in advance (set_drink_plan once they agree), alternating with water or something alcohol-free, eating first, a set time to stop, a first drink that isn't alcohol. Log a drink with log_drink only when they tell you they had one. If they describe drinking most days, heavy amounts, morning drinking, or shakes or sweating when they stop, tell them not to stop all at once (withdrawal can be dangerous) and to see a doctor; in Brazil, CAPS AD gives free care. Without a `drinks` block, don't bring alcohol up unless they do. +- Lab results: when the packet has a `labs` block, the user added their own lab reports and checked the values. Follow its `note`. Use the numbers as given, with the date and the lab's own range; say how a marker moved across reports (`earlier`). Never diagnose or name what a result means medically, and never call a value fine or dangerous beyond whether it is inside the printed range; anything outside the range or moving the wrong way is for their doctor, so say so plainly. Never suggest a medication, supplement or dose. When they ask for a plan, link the markers to habits in their own data (steps, sleep, active minutes, meals), propose exact daily goals, and call set_goal only after they agree to those numbers; food changes are suggestions, not goals. - When the context packet includes an `environment` block (the user's city + current weather), use it to ground practical suggestions — outdoor vs indoor workouts, hydration on hot days, planning around rain. Never reference the user's location more precisely than the city. Data limitations: @@ -77,6 +78,8 @@ data class CoachContextPacket( val drinks: com.pulseloop.service.DrinksContext? = null, /** The postpartum life stage, when she switched it on in her profile; null otherwise. */ val postpartum: com.pulseloop.service.PostpartumContext? = null, + /** Lab results the user added and checked; null when none, or when they switched it off. */ + val labs: com.pulseloop.service.LabContext? = null, ) { @kotlinx.serialization.Serializable data class ProfileContext( diff --git a/app/src/main/java/com/pulseloop/data/ArchivedSettings.kt b/app/src/main/java/com/pulseloop/data/ArchivedSettings.kt index 231c078a..10ca0372 100644 --- a/app/src/main/java/com/pulseloop/data/ArchivedSettings.kt +++ b/app/src/main/java/com/pulseloop/data/ArchivedSettings.kt @@ -41,6 +41,8 @@ object ArchivedSettings { "activity_detection" to emptySet(), // Rest Mode, while it lasts. "rest_mode" to emptySet(), + // Whether the coach may use the lab results. + "lab_reports" to emptySet(), ) /** diff --git a/app/src/main/java/com/pulseloop/data/DataArchive.kt b/app/src/main/java/com/pulseloop/data/DataArchive.kt index 20b43d49..eb3d27a0 100644 --- a/app/src/main/java/com/pulseloop/data/DataArchive.kt +++ b/app/src/main/java/com/pulseloop/data/DataArchive.kt @@ -69,6 +69,22 @@ data class PulseArchive( * before it existed, and a restore then leaves this phone's own values alone. */ val settings: Map> = emptyMap(), + /** Lab reports (v37), each with its PDF as base64 so a new phone can open it again. */ + val labReports: List = emptyList(), + val labResults: List = emptyList(), +) + +@Serializable data class LabReportDTO( + val id: String, val collectedDay: Long, val lab: String? = null, val kindsCsv: String = "", + val fileName: String? = null, val pdfFile: String? = null, val pageCount: Int = 0, val createdAt: Long, + val pdfBase64: String? = null, +) + +@Serializable data class LabResultDTO( + val id: String, val reportId: String, val panel: String, val name: String, val markerKey: String, + val valueNum: Double? = null, val valueText: String? = null, val unit: String? = null, + val refLow: Double? = null, val refHigh: Double? = null, val refText: String? = null, + val flag: String = "UNKNOWN", val position: Int = 0, ) @Serializable data class AccuracyCheckDTO( diff --git a/app/src/main/java/com/pulseloop/data/DataArchiveService.kt b/app/src/main/java/com/pulseloop/data/DataArchiveService.kt index e85fffa6..9a420598 100644 --- a/app/src/main/java/com/pulseloop/data/DataArchiveService.kt +++ b/app/src/main/java/com/pulseloop/data/DataArchiveService.kt @@ -358,6 +358,26 @@ object DataArchiveService { ) }, settings = context?.let { ArchivedSettings.export(it) } ?: emptyMap(), + labReports = collect("lab_reports") { c -> + val pdf = c.strOrNull("pdfFile") + LabReportDTO( + id = c.str("id"), collectedDay = c.long("collectedDay"), lab = c.strOrNull("lab"), + kindsCsv = c.strOrNull("kindsCsv") ?: "", fileName = c.strOrNull("fileName"), pdfFile = pdf, + pageCount = c.intOrNull("pageCount") ?: 0, createdAt = c.long("createdAt"), + pdfBase64 = if (context != null && pdf != null) runCatching { + com.pulseloop.service.LabReports.pdfFile(context, pdf).takeIf { it.exists() } + ?.readBytes()?.let { android.util.Base64.encodeToString(it, android.util.Base64.NO_WRAP) } + }.getOrNull() else null, + ) + }, + labResults = collect("lab_results") { c -> + LabResultDTO( + id = c.str("id"), reportId = c.str("reportId"), panel = c.str("panel"), name = c.str("name"), + markerKey = c.str("markerKey"), valueNum = c.dblOrNull("valueNum"), valueText = c.strOrNull("valueText"), + unit = c.strOrNull("unit"), refLow = c.dblOrNull("refLow"), refHigh = c.dblOrNull("refHigh"), + refText = c.strOrNull("refText"), flag = c.strOrNull("flag") ?: "UNKNOWN", position = c.intOrNull("position") ?: 0, + ) + }, accuracyCorrections = collect("accuracy_corrections") { c -> AccuracyCorrectionDTO( deviceKey = c.str("deviceKey"), metric = c.str("metric"), kind = c.str("kind"), @@ -516,6 +536,27 @@ object DataArchiveService { for (p in archive.periods) { db.periodDao().upsert(PeriodEntity(id = p.id, startDay = p.startDay, endDay = p.endDay, createdAt = p.createdAt)) } + for (r in archive.labReports) { + // The PDF goes back to the app's own storage before its row points at it. + val b64 = r.pdfBase64 + val name = r.pdfFile + val pdf = if (b64 != null && name != null) runCatching { + com.pulseloop.service.LabReports.pdfFile(context, name) + .writeBytes(android.util.Base64.decode(b64, android.util.Base64.NO_WRAP)) + name + }.getOrNull() else null + db.labDao().upsertReport(LabReportEntity( + id = r.id, collectedDay = r.collectedDay, lab = r.lab, kindsCsv = r.kindsCsv, + fileName = r.fileName, pdfFile = pdf, pageCount = r.pageCount, createdAt = r.createdAt, + )) + } + if (archive.labResults.isNotEmpty()) db.labDao().upsertResults(archive.labResults.map { x -> + LabResultEntity( + id = x.id, reportId = x.reportId, panel = x.panel, name = x.name, markerKey = x.markerKey, + valueNum = x.valueNum, valueText = x.valueText, unit = x.unit, refLow = x.refLow, + refHigh = x.refHigh, refText = x.refText, flag = x.flag, position = x.position, + ) + }) for (d in archive.drinks) { db.drinkDao().upsert(DrinkEntryEntity( id = d.id, timestamp = d.timestamp, day = d.day, type = d.type, volumeMl = d.volumeMl, diff --git a/app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt b/app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt index a34b9441..e97d10e9 100644 --- a/app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt +++ b/app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt @@ -56,8 +56,10 @@ import com.pulseloop.data.entity.* AccuracyPausedUnitEntity::class, AccuracyCheckDayEntity::class, AccuracyCorrectionEntity::class, + LabReportEntity::class, + LabResultEntity::class, ], - version = 36, + version = 37, exportSchema = false, ) abstract class PulseLoopDatabase : RoomDatabase() { @@ -105,6 +107,8 @@ abstract class PulseLoopDatabase : RoomDatabase() { abstract fun foodProductDao(): FoodProductDao /** Journal tags for "what affects you" insights. */ abstract fun journalDao(): JournalDao + /** Lab reports the user added as PDFs, and the markers read from them (v37). */ + abstract fun labDao(): LabDao /** * Empty every table, atomically. Goes through Room's [withTransaction] rather than a raw @@ -149,6 +153,7 @@ abstract class PulseLoopDatabase : RoomDatabase() { "periods", "meds", "med_doses", "accuracy_checks", "accuracy_paused_units", "accuracy_check_days", "accuracy_corrections", + "lab_reports", "lab_results", ) @Volatile private var INSTANCE: PulseLoopDatabase? = null @@ -691,6 +696,26 @@ abstract class PulseLoopDatabase : RoomDatabase() { } } + /** v36 → v37: lab reports added as PDFs, and the markers read from them. */ + private val MIGRATION_36_37 = object : Migration(36, 37) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL( + "CREATE TABLE IF NOT EXISTS `lab_reports` (`id` TEXT NOT NULL, `collectedDay` INTEGER NOT NULL, " + + "`lab` TEXT, `kindsCsv` TEXT NOT NULL, `fileName` TEXT, `pdfFile` TEXT, `pageCount` INTEGER NOT NULL, " + + "`createdAt` INTEGER NOT NULL, PRIMARY KEY(`id`))" + ) + db.execSQL("CREATE INDEX IF NOT EXISTS `index_lab_reports_collectedDay` ON `lab_reports` (`collectedDay`)") + db.execSQL( + "CREATE TABLE IF NOT EXISTS `lab_results` (`id` TEXT NOT NULL, `reportId` TEXT NOT NULL, `panel` TEXT NOT NULL, " + + "`name` TEXT NOT NULL, `markerKey` TEXT NOT NULL, `valueNum` REAL, `valueText` TEXT, `unit` TEXT, " + + "`refLow` REAL, `refHigh` REAL, `refText` TEXT, `flag` TEXT NOT NULL, `position` INTEGER NOT NULL, " + + "PRIMARY KEY(`id`), FOREIGN KEY(`reportId`) REFERENCES `lab_reports`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )" + ) + db.execSQL("CREATE INDEX IF NOT EXISTS `index_lab_results_reportId` ON `lab_results` (`reportId`)") + db.execSQL("CREATE INDEX IF NOT EXISTS `index_lab_results_markerKey` ON `lab_results` (`markerKey`)") + } + } + private fun adoptStableMeasurementIdentities(db: SupportSQLiteDatabase) { db.execSQL("DROP INDEX IF EXISTS `index_measurements_kindRaw_timestamp_sourceRaw`") db.execSQL( @@ -793,6 +818,7 @@ abstract class PulseLoopDatabase : RoomDatabase() { MIGRATION_33_34, MIGRATION_34_35, MIGRATION_35_36, + MIGRATION_36_37, ) // Downgrades only (sideloading an older APK). A blanket destructive // fallback would silently wipe every measurement, sleep session, and diff --git a/app/src/main/java/com/pulseloop/data/dao/Daos.kt b/app/src/main/java/com/pulseloop/data/dao/Daos.kt index 8b909a99..7cfbfb4c 100644 --- a/app/src/main/java/com/pulseloop/data/dao/Daos.kt +++ b/app/src/main/java/com/pulseloop/data/dao/Daos.kt @@ -1106,3 +1106,33 @@ interface AccuracyDao { @Query("DELETE FROM accuracy_corrections WHERE deviceKey = :deviceKey AND metric = :metric") suspend fun deleteCorrection(deviceKey: String, metric: String) } + +@Dao +interface LabDao { + @Query("SELECT * FROM lab_reports ORDER BY collectedDay DESC, createdAt DESC") + fun reportsFlow(): Flow> + + @Query("SELECT * FROM lab_reports ORDER BY collectedDay DESC, createdAt DESC") + suspend fun reports(): List + + @Query("SELECT * FROM lab_reports WHERE id = :id") + suspend fun report(id: String): LabReportEntity? + + @Query("SELECT * FROM lab_results ORDER BY position ASC") + fun resultsFlow(): Flow> + + @Query("SELECT * FROM lab_results") + suspend fun results(): List + + @Query("SELECT * FROM lab_results WHERE markerKey = :key") + suspend fun resultsFor(key: String): List + + @Upsert + suspend fun upsertReport(report: LabReportEntity) + + @Upsert + suspend fun upsertResults(results: List) + + @Query("DELETE FROM lab_reports WHERE id = :id") + suspend fun deleteReport(id: String) +} diff --git a/app/src/main/java/com/pulseloop/data/entity/LabEntities.kt b/app/src/main/java/com/pulseloop/data/entity/LabEntities.kt new file mode 100644 index 00000000..72e1e162 --- /dev/null +++ b/app/src/main/java/com/pulseloop/data/entity/LabEntities.kt @@ -0,0 +1,61 @@ +package com.pulseloop.data.entity + +import androidx.room.Entity +import androidx.room.ForeignKey +import androidx.room.Index +import androidx.room.PrimaryKey + +/** + * One lab report the user added as a PDF (docs: AGENTS.md, lab reports). [collectedDay] is the + * local start of the day the sample was collected, which is what a marker's chart is plotted by; + * [pdfFile] names the copy kept in `filesDir/lab_reports/`. + */ +@Entity(tableName = "lab_reports", indices = [Index("collectedDay")]) +data class LabReportEntity( + @PrimaryKey val id: String, + val collectedDay: Long, + val lab: String? = null, + /** Kinds found in the report, comma-separated: blood, urine, hormones, stool, other. */ + val kindsCsv: String = "", + /** The name the file had when the user picked it, for display. */ + val fileName: String? = null, + val pdfFile: String? = null, + val pageCount: Int = 0, + val createdAt: Long = System.currentTimeMillis(), +) + +/** + * One marker read from a report, as the user checked it. [markerKey] is the same for one marker + * across labs and languages ("ldl_cholesterol"), so a chart can follow it from report to report. + * The range is the lab's own, carried with each result because labs and methods differ. + */ +@Entity( + tableName = "lab_results", + foreignKeys = [ForeignKey( + entity = LabReportEntity::class, + parentColumns = ["id"], + childColumns = ["reportId"], + onDelete = ForeignKey.CASCADE, + )], + indices = [Index("reportId"), Index("markerKey")], +) +data class LabResultEntity( + @PrimaryKey val id: String, + val reportId: String, + /** The group the lab printed it under ("Lipids", "Blood count", "Urine"…). */ + val panel: String, + /** The marker's name as printed on the report. */ + val name: String, + val markerKey: String, + val valueNum: Double? = null, + /** For a result that isn't a number ("Negative", "Clear"), or the printed form of one. */ + val valueText: String? = null, + val unit: String? = null, + val refLow: Double? = null, + val refHigh: Double? = null, + /** The reference as printed, when it isn't a plain low–high pair. */ + val refText: String? = null, + /** HIGH, LOW, NORMAL, ABNORMAL (outside a non-numeric reference) or UNKNOWN. */ + val flag: String = "UNKNOWN", + val position: Int = 0, +) diff --git a/app/src/main/java/com/pulseloop/service/LabReports.kt b/app/src/main/java/com/pulseloop/service/LabReports.kt new file mode 100644 index 00000000..fe9853d0 --- /dev/null +++ b/app/src/main/java/com/pulseloop/service/LabReports.kt @@ -0,0 +1,437 @@ +package com.pulseloop.service + +import android.content.Context +import android.content.SharedPreferences +import android.graphics.Bitmap +import android.graphics.Color +import android.graphics.pdf.PdfRenderer +import android.net.Uri +import android.os.ParcelFileDescriptor +import android.util.Base64 +import com.pulseloop.coach.attachments.CoachImagePayload +import com.pulseloop.coach.config.CoachClientResolver +import com.pulseloop.coach.config.CoachProviderSettingsStore +import com.pulseloop.coach.openai.OpenAIRequestBuilder +import com.pulseloop.data.PulseLoopDatabase +import com.pulseloop.data.entity.LabReportEntity +import com.pulseloop.data.entity.LabResultEntity +import com.pulseloop.settings.ApiKeyStore +import com.pulseloop.ui.i18n.tr +import com.pulseloop.ui.i18n.trf +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import java.io.ByteArrayOutputStream +import java.io.File +import java.text.Normalizer +import java.time.Instant +import java.time.LocalDate +import java.time.ZoneId +import java.util.UUID + +/** + * Lab reports (AGENTS.md, "Lab reports"): a PDF of any laboratory report is rendered page by page + * on the phone, read by the user's own coach provider into structured markers, checked by the + * user, and stored. Charts follow each marker from report to report by [LabResultEntity.markerKey]. + * + * Pages go to the model as images, not as a PDF, so every provider the coach supports reads them, + * a self-hosted one included. The PDF is sent once, when the user adds it; the coach reads the + * stored values from then on. + */ +object LabReports { + + /** Pages read per report. Longer reports are rare, and every page is billed as an image. */ + const val MAX_PAGES = 10 + + /** Longest page edge sent to the model, in pixels: sharp enough for a dense results table. */ + private const val PAGE_EDGE = 1600 + + // ── Storage ────────────────────────────────────────────────────────────── + + fun directory(context: Context): File = + File(context.applicationContext.filesDir, "lab_reports").apply { mkdirs() } + + fun pdfFile(context: Context, name: String): File = File(directory(context), name) + + /** Copies the picked PDF into the app's own storage, named after the new report's id. */ + suspend fun copyIn(context: Context, uri: Uri, reportId: String): File? = withContext(Dispatchers.IO) { + runCatching { + val out = pdfFile(context, "$reportId.pdf") + context.contentResolver.openInputStream(uri)?.use { input -> out.outputStream().use { input.copyTo(it) } } ?: return@runCatching null + out + }.getOrNull() + } + + suspend fun delete(context: Context, db: PulseLoopDatabase, report: LabReportEntity) { + db.labDao().deleteReport(report.id) + report.pdfFile?.let { runCatching { pdfFile(context, it).delete() } } + } + + // ── Reading a report ───────────────────────────────────────────────────── + + /** Renders up to [MAX_PAGES] pages as JPEG payloads; also returns the page count. */ + private fun renderPages(file: File): Pair, Int> { + val fd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY) + val renderer = try { PdfRenderer(fd) } catch (e: Exception) { fd.close(); throw e } + try { + val count = renderer.pageCount + val pages = (0 until minOf(count, MAX_PAGES)).map { i -> + val page = renderer.openPage(i) + try { + val scale = PAGE_EDGE.toFloat() / maxOf(page.width, page.height) + val w = (page.width * scale).toInt().coerceAtLeast(1) + val h = (page.height * scale).toInt().coerceAtLeast(1) + val bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888) + // A PDF page is transparent where nothing is printed; JPEG would turn that black. + bmp.eraseColor(Color.WHITE) + page.render(bmp, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY) + val out = ByteArrayOutputStream() + bmp.compress(Bitmap.CompressFormat.JPEG, 85, out) + bmp.recycle() + val b64 = Base64.encodeToString(out.toByteArray(), Base64.NO_WRAP) + CoachImagePayload("data:image/jpeg;base64,$b64", b64, "image/jpeg") + } finally { + page.close() + } + } + return pages to count + } finally { + renderer.close() + fd.close() + } + } + + sealed class ReadResult { + data class Success(val draft: Draft) : ReadResult() + data class Failure(val message: String) : ReadResult() + } + + /** A report as read, before the user saves it. Every field is editable on the review screen. */ + data class Draft( + val reportId: String, + val pdfFile: String, + val fileName: String?, + val pageCount: Int, + val collectedOn: LocalDate?, + val lab: String, + val kinds: List, + val results: List, + /** Pages beyond [MAX_PAGES] that weren't read. */ + val pagesSkipped: Int = 0, + ) + + data class DraftResult( + val panel: String, + val name: String, + val key: String, + val valueNum: Double?, + val valueText: String, + val unit: String, + val refLow: Double?, + val refHigh: Double?, + val refText: String, + val modelFlag: String, + ) { + val flag: String get() = flagFor(valueNum, refLow, refHigh, modelFlag) + } + + suspend fun read(context: Context, file: File, reportId: String, fileName: String?): ReadResult = withContext(Dispatchers.IO) { + val appContext = context.applicationContext + val keyStore = ApiKeyStore(appContext) + val providerStore = CoachProviderSettingsStore(appContext) + val resolution = CoachClientResolver.resolve(providerStore, keyStore) + if (!keyStore.coachEnabled || resolution.key == null) { + return@withContext ReadResult.Failure( + tr("Reading a report needs the coach enabled with a configured provider (Settings → AI Coach)."), + ) + } + val (pages, pageCount) = try { + renderPages(file) + } catch (e: Exception) { + return@withContext ReadResult.Failure(tr("Couldn't open that PDF. It may be protected by a password or damaged.")) + } + if (pages.isEmpty()) return@withContext ReadResult.Failure(tr("That PDF has no pages to read.")) + val model = CoachClientResolver.activeModel(providerStore.snapshot(), keyStore.model) + val input = JsonArray(listOf( + OpenAIRequestBuilder.message("system", SYSTEM_PROMPT), + OpenAIRequestBuilder.message("user", "Read every result in this laboratory report.", pages), + )) + val body = JsonObject(mapOf( + "model" to JsonPrimitive(model), + "input" to input, + "text" to JsonObject(mapOf("format" to textFormat())), + ) + OpenAIRequestBuilder.reasoningParams(CoachClientResolver.resolvedReasoningEffort(providerStore.snapshot(), model), model)) + try { + val response = resolution.client.send(body.toString().toByteArray()) + val extracted = decode(response.outputText) + ?: return@withContext ReadResult.Failure(tr("The coach couldn't read results from that report. Try again, or try a clearer PDF.")) + if (extracted.results.isEmpty()) { + return@withContext ReadResult.Failure(tr("No results were found in that report.")) + } + ReadResult.Success(Draft( + reportId = reportId, + pdfFile = file.name, + fileName = fileName, + pageCount = pageCount, + collectedOn = runCatching { LocalDate.parse(extracted.collectedOn.trim()) }.getOrNull(), + lab = extracted.laboratory.trim(), + kinds = extracted.kinds.map { it.lowercase() }.filter { it in KINDS }.distinct(), + results = extracted.results.filter { it.name.isNotBlank() }.map { r -> + DraftResult( + panel = r.panel.trim(), name = r.name.trim(), + key = normalizeKey(r.key.ifBlank { r.name }), + valueNum = r.valueNumber, valueText = r.valueText.trim(), unit = r.unit.trim(), + refLow = r.refLow, refHigh = r.refHigh, refText = r.refText.trim(), modelFlag = r.flag, + ) + }, + pagesSkipped = (pageCount - MAX_PAGES).coerceAtLeast(0), + )) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + ReadResult.Failure(trf("Reading failed: {0}", e.message ?: e.javaClass.simpleName)) + } + } + + suspend fun save(db: PulseLoopDatabase, draft: Draft, zone: ZoneId = ZoneId.systemDefault()) { + val day = (draft.collectedOn ?: LocalDate.now(zone)).atStartOfDay(zone).toInstant().toEpochMilli() + db.labDao().upsertReport(LabReportEntity( + id = draft.reportId, collectedDay = day, lab = draft.lab.ifBlank { null }, + kindsCsv = draft.kinds.joinToString(","), fileName = draft.fileName, + pdfFile = draft.pdfFile, pageCount = draft.pageCount, + )) + db.labDao().upsertResults(draft.results.mapIndexed { i, r -> + LabResultEntity( + id = UUID.randomUUID().toString(), reportId = draft.reportId, panel = r.panel.ifBlank { "Other" }, + name = r.name, markerKey = normalizeKey(r.key.ifBlank { r.name }), + valueNum = r.valueNum, valueText = r.valueText.ifBlank { null }, unit = r.unit.ifBlank { null }, + refLow = r.refLow, refHigh = r.refHigh, refText = r.refText.ifBlank { null }, + flag = r.flag, position = i, + ) + }) + } + + // ── Rules ──────────────────────────────────────────────────────────────── + + val KINDS = listOf("blood", "urine", "hormones", "stool", "other") + + /** One key per analyte, whatever the language or the lab: lowercase ASCII words joined by "_". */ + fun normalizeKey(raw: String): String = + Normalizer.normalize(raw, Normalizer.Form.NFD).replace(Regex("\\p{M}+"), "") + .lowercase().replace(Regex("[^a-z0-9]+"), "_").trim('_').ifBlank { "marker" } + + /** + * Where a result sits against the lab's own printed range. A numeric value with a range is + * judged here, not taken from the model; without one the report's own marking (as read) stands. + */ + fun flagFor(value: Double?, low: Double?, high: Double?, modelFlag: String): String = when { + value != null && high != null && value > high -> "HIGH" + value != null && low != null && value < low -> "LOW" + value != null && (low != null || high != null) -> "NORMAL" + else -> when (modelFlag.lowercase()) { + "high" -> "HIGH" + "low" -> "LOW" + "abnormal" -> "ABNORMAL" + "normal" -> "NORMAL" + else -> "UNKNOWN" + } + } + + fun isOutside(flag: String) = flag == "HIGH" || flag == "LOW" || flag == "ABNORMAL" + + /** "148", "14.6", "0.85": no trailing zeros, at most two decimals. */ + fun formatValue(v: Double): String = + if (v == Math.floor(v) && kotlin.math.abs(v) < 1e9) v.toLong().toString() + else java.math.BigDecimal(v).setScale(2, java.math.RoundingMode.HALF_UP).stripTrailingZeros().toPlainString() + + fun valueLabel(num: Double?, text: String?): String = + num?.let(::formatValue) ?: text?.takeIf { it.isNotBlank() } ?: "—" + + fun referenceLabel(low: Double?, high: Double?, text: String?, unit: String?): String? { + val u = unit?.takeIf { it.isNotBlank() }?.let { " $it" } ?: "" + return when { + low != null && high != null -> "${formatValue(low)}–${formatValue(high)}$u" + high != null -> trf("below {0}", formatValue(high) + u) + low != null -> trf("above {0}", formatValue(low) + u) + else -> text?.takeIf { it.isNotBlank() } + } + } + + // ── Series, for the screens and the coach ─────────────────────────────── + + data class Point( + val day: Long, val reportId: String, val valueNum: Double?, val valueText: String?, val unit: String?, + val refLow: Double?, val refHigh: Double?, val refText: String?, val flag: String, + ) + + data class Marker(val key: String, val name: String, val panel: String, val points: List) { + val latest: Point get() = points.last() + val numeric: Boolean get() = points.count { it.valueNum != null } >= 1 + } + + /** One series per marker, oldest point first, named and grouped as in its latest report. */ + fun markers(reports: List, results: List): List { + val day = reports.associate { it.id to it.collectedDay } + return results.filter { it.reportId in day }.groupBy { it.markerKey }.map { (key, rows) -> + val sorted = rows.sortedWith(compareBy({ day.getValue(it.reportId) }, { it.position })) + val last = sorted.last() + Marker(key, last.name, last.panel, sorted.map { + Point(day.getValue(it.reportId), it.reportId, it.valueNum, it.valueText, it.unit, it.refLow, it.refHigh, it.refText, it.flag) + }) + }.sortedWith(compareBy({ it.panel.lowercase() }, { it.name.lowercase() })) + } + + // ── Prompt and schema ──────────────────────────────────────────────────── + + private const val SYSTEM_PROMPT = + "You read laboratory reports (blood, urine, hormones, stool or any other lab test) from page images. " + + "Extract every result exactly as printed; never add, guess or interpret one. For each result: " + + "panel = the section heading it is printed under; name = the analyte as printed; key = a stable " + + "snake_case English identifier for the analyte, the same for the same analyte whatever the language " + + "or lab (e.g. ldl_cholesterol, hdl_cholesterol, triglycerides, hemoglobin, ferritin, tsh, " + + "vitamin_d_25oh, glucose_fasting, hba1c, creatinine, urine_protein); value_number = the numeric value " + + "with a decimal point, or null when the result isn't a plain number (then put it in value_text, e.g. " + + "\"Negative\", \"<5\"); value_text = the printed result; unit = as printed; ref_low/ref_high = the " + + "printed reference limits as numbers, null when absent; ref_text = the printed reference when it isn't " + + "a plain range; flag = high, low, abnormal or normal from the report's own marking or the printed " + + "reference, unknown when there is neither. collected_on = the sample collection date as YYYY-MM-DD, " + + "or empty. laboratory = the lab's name, or empty. Return only JSON matching the schema." + + private fun textFormat(): JsonObject { + fun str() = JsonObject(mapOf("type" to JsonPrimitive("string"))) + fun numOrNull() = JsonObject(mapOf("type" to JsonArray(listOf(JsonPrimitive("number"), JsonPrimitive("null"))))) + fun enumOf(vararg v: String) = JsonObject(mapOf("type" to JsonPrimitive("string"), "enum" to JsonArray(v.map { JsonPrimitive(it) }))) + fun obj(props: Map) = JsonObject(mapOf( + "type" to JsonPrimitive("object"), + "properties" to JsonObject(props), + "required" to JsonArray(props.keys.map { JsonPrimitive(it) }), + "additionalProperties" to JsonPrimitive(false), + )) + val result = obj(linkedMapOf( + "panel" to str(), "name" to str(), "key" to str(), + "value_number" to numOrNull(), "value_text" to str(), "unit" to str(), + "ref_low" to numOrNull(), "ref_high" to numOrNull(), "ref_text" to str(), + "flag" to enumOf("high", "low", "abnormal", "normal", "unknown"), + )) + val schema = obj(linkedMapOf( + "collected_on" to str(), + "laboratory" to str(), + "kinds" to JsonObject(mapOf("type" to JsonPrimitive("array"), "items" to enumOf(*KINDS.toTypedArray()))), + "results" to JsonObject(mapOf("type" to JsonPrimitive("array"), "items" to result)), + )) + return JsonObject(mapOf( + "type" to JsonPrimitive("json_schema"), + "name" to JsonPrimitive("lab_report"), + "strict" to JsonPrimitive(true), + "schema" to schema, + )) + } + + @Serializable + data class Extracted( + @SerialName("collected_on") val collectedOn: String = "", + val laboratory: String = "", + val kinds: List = emptyList(), + val results: List = emptyList(), + ) + + @Serializable + data class ExtractedResult( + val panel: String = "", + val name: String = "", + val key: String = "", + @SerialName("value_number") val valueNumber: Double? = null, + @SerialName("value_text") val valueText: String = "", + val unit: String = "", + @SerialName("ref_low") val refLow: Double? = null, + @SerialName("ref_high") val refHigh: Double? = null, + @SerialName("ref_text") val refText: String = "", + val flag: String = "unknown", + ) + + private val json = Json { ignoreUnknownKeys = true; coerceInputValues = true } + + /** Fence- and prose-tolerant, like the meal estimate's decode. */ + fun decode(text: String): Extracted? { + val t = text.trim() + if (t.startsWith("{")) runCatching { return json.decodeFromString(Extracted.serializer(), t) } + val start = t.indexOf('{') + val end = t.lastIndexOf('}') + if (start < 0 || end <= start) return null + return runCatching { json.decodeFromString(Extracted.serializer(), t.substring(start, end + 1)) }.getOrNull() + } +} + +/** Whether the coach may use the lab results. On by default; the switch is on the Lab reports screen. */ +object LabPrefs { + @Volatile private var prefs: SharedPreferences? = null + + /** From the Application, so the coach's context builder (no Context) can read the switch. */ + fun init(context: Context) { + if (prefs == null) prefs = context.applicationContext.getSharedPreferences("lab_reports", Context.MODE_PRIVATE) + } + + var coachUses: Boolean + get() = prefs?.getBoolean("coachUses", true) ?: true + set(v) { prefs?.edit()?.putBoolean("coachUses", v)?.apply() } +} + +/** + * The lab results as the coach sees them: each marker's latest value with its range and the two + * before it, so it can speak to a trend. Null when there are none or the user switched it off. + */ +@Serializable +data class LabContext( + val reports: Int, + val latestReport: String, + val markers: List, + val note: String = "Lab results the user added from their own reports and checked themselves. You are not a " + + "doctor: never diagnose, never name a condition the results 'mean', never say a value is fine or dangerous " + + "beyond whether it sits inside the lab's printed range. For anything outside the range or trending badly, " + + "say it is worth discussing with their doctor. Never suggest starting, stopping or dosing a medication or " + + "supplement. You may suggest everyday habits (activity, sleep, food) linked to a marker in general terms, " + + "and propose daily goals; change a goal only with set_goal and only after the user says yes to the exact numbers.", +) { + companion object { + suspend fun build(db: PulseLoopDatabase): LabContext? { + if (!LabPrefs.coachUses) return null + val reports = db.labDao().reports() + if (reports.isEmpty()) return null + val markers = LabReports.markers(reports, db.labDao().results()) + val zone = ZoneId.systemDefault() + fun date(ms: Long) = Instant.ofEpochMilli(ms).atZone(zone).toLocalDate().toString() + return LabContext( + reports = reports.size, + latestReport = date(reports.maxOf { it.collectedDay }), + markers = markers.take(80).map { m -> + val l = m.latest + LabMarkerContext( + name = m.name, panel = m.panel, + latest = LabReports.valueLabel(l.valueNum, l.valueText) + (l.unit?.let { " $it" } ?: ""), + date = date(l.day), + reference = LabReports.referenceLabel(l.refLow, l.refHigh, l.refText, l.unit), + flag = l.flag.lowercase(), + earlier = m.points.dropLast(1).takeLast(2).map { "${date(it.day)}: ${LabReports.valueLabel(it.valueNum, it.valueText)}" }, + ) + }, + ) + } + } +} + +@Serializable +data class LabMarkerContext( + val name: String, + val panel: String, + val latest: String, + val date: String, + val reference: String? = null, + val flag: String, + val earlier: List = emptyList(), +) diff --git a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt index dd264c20..bbfbc1b1 100644 --- a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt +++ b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt @@ -1,6 +1,7 @@ package com.pulseloop.ui import com.pulseloop.ui.i18n.tr +import com.pulseloop.ui.i18n.trf import android.content.res.Configuration import androidx.compose.foundation.layout.* @@ -780,6 +781,28 @@ fun PulseLoopApp() { onCycle = { navController.navigate("cycle") }, onMeds = { navController.navigate("meds") }, onPostpartum = { navController.navigate("postpartum") }, + onLabReports = { navController.navigate("lab_reports") }, + ) + } + paddedComposable("lab_reports") { + com.pulseloop.ui.screens.LabReportsScreen( + onBack = { navController.popBackStack() }, + onMarker = { key -> navController.navigate("lab_reports/marker/$key") }, + onAskCoach = { + com.pulseloop.ui.LaunchRequests.coachMessage.value = tr("Make me a plan from my lab reports.") + navController.navigate("coach") { launchSingleTop = true } + }, + ) + } + paddedComposable("lab_reports/marker/{key}") { entry -> + val key = entry.arguments?.getString("key") ?: return@paddedComposable + com.pulseloop.ui.screens.LabMarkerScreen( + markerKey = key, + onBack = { navController.popBackStack() }, + onAskCoach = { name -> + com.pulseloop.ui.LaunchRequests.coachMessage.value = trf("Make me a plan from my lab reports, starting with {0}.", name) + navController.navigate("coach") { launchSingleTop = true } + }, ) } paddedComposable("postpartum") { diff --git a/app/src/main/java/com/pulseloop/ui/screens/LabReportsUi.kt b/app/src/main/java/com/pulseloop/ui/screens/LabReportsUi.kt new file mode 100644 index 00000000..075b49ed --- /dev/null +++ b/app/src/main/java/com/pulseloop/ui/screens/LabReportsUi.kt @@ -0,0 +1,593 @@ +package com.pulseloop.ui.screens + +import android.content.ActivityNotFoundException +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.provider.OpenableColumns +import android.widget.Toast +import androidx.activity.compose.BackHandler +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.AutoAwesome +import androidx.compose.material.icons.filled.Delete +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.drawText +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.rememberTextMeasurer +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.core.content.FileProvider +import com.pulseloop.data.PulseLoopDatabase +import com.pulseloop.data.entity.LabReportEntity +import com.pulseloop.service.LabPrefs +import com.pulseloop.service.LabReports +import com.pulseloop.ui.i18n.tr +import com.pulseloop.ui.i18n.trf +import com.pulseloop.ui.theme.PulseColors +import com.pulseloop.ui.theme.dither +import com.pulseloop.ui.theme.ditherBrush +import kotlinx.coroutines.launch +import java.time.Instant +import java.time.LocalDate +import java.time.ZoneId +import java.time.format.DateTimeFormatter +import java.time.format.FormatStyle +import java.util.UUID + +// Lab reports (AGENTS.md, "Lab reports"): any lab report added as a PDF, read by the coach, +// checked by the user, and each marker charted report by report. + +private fun dayLabel(ms: Long): String = + Instant.ofEpochMilli(ms).atZone(ZoneId.systemDefault()).toLocalDate() + .format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)) + +private fun shortDay(ms: Long): String = + Instant.ofEpochMilli(ms).atZone(ZoneId.systemDefault()).toLocalDate() + .format(DateTimeFormatter.ofPattern("MMM yy")) + +private fun flagColor(flag: String): Color = + if (LabReports.isOutside(flag)) PulseColors.warning else if (flag == "NORMAL") PulseColors.accent else PulseColors.textMuted + +private fun flagLabel(flag: String): String = when (flag) { + "HIGH" -> tr("High") + "LOW" -> tr("Low") + "ABNORMAL" -> tr("Outside range") + "NORMAL" -> tr("In range") + else -> tr("No range") +} + +private fun kindLabel(kind: String): String = when (kind) { + "blood" -> tr("Blood") + "urine" -> tr("Urine") + "hormones" -> tr("Hormones") + "stool" -> tr("Stool") + else -> tr("Other") +} + +private fun displayName(context: Context, uri: Uri): String? = runCatching { + context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c -> + if (c.moveToFirst()) c.getString(0) else null + } +}.getOrNull() + +private fun openPdf(context: Context, report: LabReportEntity) { + val name = report.pdfFile ?: return + val file = LabReports.pdfFile(context, name) + if (!file.exists()) { + Toast.makeText(context, tr("This report's PDF isn't on this phone."), Toast.LENGTH_SHORT).show() + return + } + val uri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file) + val intent = Intent(Intent.ACTION_VIEW).setDataAndType(uri, "application/pdf") + .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + try { + context.startActivity(intent) + } catch (_: ActivityNotFoundException) { + Toast.makeText(context, tr("No app on this phone opens PDFs."), Toast.LENGTH_SHORT).show() + } +} + +/** A warning line on an amber dither, the app's notice. */ +@Composable +private fun LabNotice(text: String) { + Row( + Modifier.fillMaxWidth().clip(RoundedCornerShape(4.dp)).border(1.dp, PulseColors.warning, RoundedCornerShape(4.dp)) + .dither(PulseColors.warning, 0.12f).padding(horizontal = 12.dp, vertical = 10.dp), + ) { + Text(text, fontSize = 13.sp, color = PulseColors.textPrimary) + } +} + +@Composable +private fun LabCard(content: @Composable ColumnScope.() -> Unit) { + Column( + Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card).padding(16.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + content = content, + ) +} + +@Composable +private fun Overline(text: String, color: Color = PulseColors.textMuted) { + Text(text.uppercase(), fontSize = 11.sp, letterSpacing = 1.6.sp, color = color) +} + +@Composable +fun LabReportsScreen(onBack: () -> Unit, onMarker: (String) -> Unit, onAskCoach: () -> Unit) { + val context = LocalContext.current + val db = remember { PulseLoopDatabase.getInstance(context) } + val scope = rememberCoroutineScope() + val reports by remember(db) { db.labDao().reportsFlow() }.collectAsState(initial = null) + val results by remember(db) { db.labDao().resultsFlow() }.collectAsState(initial = null) + val markers = remember(reports, results) { LabReports.markers(reports.orEmpty(), results.orEmpty()) } + + var reading by remember { mutableStateOf(false) } + var readError by remember { mutableStateOf(null) } + var draft by remember { mutableStateOf(null) } + var coachUses by remember { mutableStateOf(LabPrefs.coachUses) } + var deleting by remember { mutableStateOf(null) } + + val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> + if (uri == null) return@rememberLauncherForActivityResult + scope.launch { + reading = true + readError = null + val id = UUID.randomUUID().toString() + val file = LabReports.copyIn(context, uri, id) + if (file == null) { + readError = tr("Couldn't copy that file.") + } else when (val r = LabReports.read(context, file, id, displayName(context, uri))) { + is LabReports.ReadResult.Success -> draft = r.draft + is LabReports.ReadResult.Failure -> { readError = r.message; file.delete() } + } + reading = false + } + } + + fun discard() { + draft?.let { LabReports.pdfFile(context, it.pdfFile).delete() } + draft = null + } + + val current = draft + if (current != null) { + BackHandler { discard() } + LabReviewScreen( + draft = current, + onChange = { draft = it }, + onDiscard = ::discard, + onSave = { + scope.launch { + LabReports.save(db, current) + draft = null + Toast.makeText(context, trf("Saved {0} markers", current.results.size), Toast.LENGTH_SHORT).show() + } + }, + ) + return + } + + SettingsSubScreen(title = tr("Lab reports"), onBack = onBack) { + val all = reports.orEmpty() + val latest = all.firstOrNull() + LabCard { + Overline(tr("Lab reports")) + if (all.isEmpty()) { + Text(tr("Add any lab report as a PDF: blood, urine, hormones or anything else. The coach reads it, you check the values, and every marker gets a chart across your exams."), + fontSize = 14.sp, color = PulseColors.textSecondary) + } else { + Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Text("${all.size}", fontSize = 26.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(trf("reports · {0} markers tracked", markers.size), fontSize = 14.sp, color = PulseColors.textMuted, + modifier = Modifier.padding(bottom = 4.dp)) + } + latest?.let { r -> + Text(listOfNotNull(trf("Latest: {0}", dayLabel(r.collectedDay)), r.lab, r.kindsCsv.split(",").filter { it.isNotBlank() }.joinToString(", ") { kindLabel(it).lowercase() }.ifBlank { null }) + .joinToString(" · "), fontSize = 12.sp, color = PulseColors.textMuted) + } + } + Button( + onClick = { picker.launch(arrayOf("application/pdf")) }, + enabled = !reading, + modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), + colors = ButtonDefaults.buttonColors(containerColor = PulseColors.accent, contentColor = PulseColors.onAccent), + ) { + Icon(Icons.Filled.Add, null) + Spacer(Modifier.width(8.dp)) + Text(tr("Add a lab report (PDF)")) + } + if (reading) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) { + CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp, color = PulseColors.accent) + Text(tr("The coach is reading the report. This can take a minute."), fontSize = 13.sp, color = PulseColors.textSecondary) + } + } + readError?.let { Text(it, fontSize = 13.sp, color = PulseColors.danger) } + } + + if (latest != null) { + val outside = results.orEmpty().filter { it.reportId == latest.id && LabReports.isOutside(it.flag) } + if (outside.isNotEmpty()) { + LabNotice(trf("{0} markers outside the lab's range in your latest report. Talk them over with your doctor.", outside.size)) + } + } + + if (markers.isNotEmpty()) { + Row( + Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card) + .clickable(role = Role.Button, onClick = onAskCoach).padding(16.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Icon(Icons.Filled.AutoAwesome, null, tint = PulseColors.accent) + Column(Modifier.weight(1f)) { + Text(tr("Ask the coach for a plan"), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(tr("From these results, with goals you approve"), fontSize = 12.sp, color = PulseColors.textMuted) + } + Text("›", fontSize = 22.sp, color = PulseColors.textMuted) + } + Row(verticalAlignment = Alignment.CenterVertically) { + Column(Modifier.weight(1f)) { + Text(tr("Let the coach use these results"), fontSize = 14.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(tr("It reads the values you saved, never the PDF again."), fontSize = 12.sp, color = PulseColors.textMuted) + } + Switch(checked = coachUses, onCheckedChange = { coachUses = it; LabPrefs.coachUses = it }) + } + + markers.groupBy { it.panel }.forEach { (panel, list) -> + Overline(panel) + Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card)) { + list.forEachIndexed { i, m -> + if (i > 0) Box(Modifier.fillMaxWidth().height(1.dp).background(PulseColors.borderSubtle)) + MarkerRow(m) { onMarker(m.key) } + } + } + } + } + + if (all.isNotEmpty()) { + Overline(tr("Reports")) + Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card)) { + all.forEachIndexed { i, r -> + if (i > 0) Box(Modifier.fillMaxWidth().height(1.dp).background(PulseColors.borderSubtle)) + val count = results.orEmpty().count { it.reportId == r.id } + Row( + Modifier.fillMaxWidth().clickable { openPdf(context, r) }.padding(start = 16.dp, top = 8.dp, bottom = 8.dp, end = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Text(listOfNotNull(dayLabel(r.collectedDay), r.lab).joinToString(" · "), fontSize = 14.sp, + fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(listOfNotNull( + r.kindsCsv.split(",").filter { it.isNotBlank() }.joinToString(", ") { kindLabel(it) }.ifBlank { null }, + trf("{0} markers", count), + ).joinToString(" · "), fontSize = 12.sp, color = PulseColors.textMuted) + } + IconButton(onClick = { deleting = r }) { + Icon(Icons.Filled.Delete, tr("Delete report"), tint = PulseColors.textMuted) + } + } + } + } + Text(tr("Tap a report to open its PDF."), fontSize = 11.sp, color = PulseColors.textMuted) + } + + Text(tr("Values come from your reports as you checked them. PulseLoop doesn't diagnose; the ranges are the lab's own."), + fontSize = 11.sp, color = PulseColors.textMuted) + } + + deleting?.let { r -> + AlertDialog( + onDismissRequest = { deleting = null }, + title = { Text(tr("Delete this report?")) }, + text = { Text(tr("Its markers and its PDF are removed from this phone.")) }, + confirmButton = { + TextButton(onClick = { + scope.launch { LabReports.delete(context, db, r) } + deleting = null + }) { Text(tr("Delete"), color = PulseColors.danger) } + }, + dismissButton = { TextButton(onClick = { deleting = null }) { Text(tr("Cancel")) } }, + ) + } +} + +@Composable +private fun MarkerRow(m: LabReports.Marker, onClick: () -> Unit) { + val l = m.latest + Row( + Modifier.fillMaxWidth().clickable(role = Role.Button, onClick = onClick).padding(horizontal = 16.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + Column(Modifier.weight(1f)) { + Text(m.name, fontSize = 14.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary, maxLines = 2, overflow = TextOverflow.Ellipsis) + Text(LabReports.valueLabel(l.valueNum, l.valueText) + (l.unit?.let { " $it" } ?: ""), fontSize = 12.sp, color = PulseColors.textMuted) + } + val nums = m.points.mapNotNull { it.valueNum } + if (nums.size >= 2) { + val color = flagColor(l.flag) + Canvas(Modifier.size(width = 56.dp, height = 20.dp)) { + val lo = nums.min(); val hi = nums.max(); val span = (hi - lo).takeIf { it > 0 } ?: 1.0 + val path = Path() + nums.forEachIndexed { i, v -> + val x = size.width * i / (nums.size - 1) + val y = size.height - ((v - lo) / span * size.height).toFloat() + if (i == 0) path.moveTo(x, y) else path.lineTo(x, y) + } + drawPath(path, color, style = Stroke(width = 2.dp.toPx())) + } + } + Text(flagLabel(l.flag), fontSize = 12.sp, fontWeight = FontWeight.Bold, color = flagColor(l.flag)) + Text("›", fontSize = 20.sp, color = PulseColors.textMuted) + } +} + +// ── One marker over time ───────────────────────────────────────────────────── + +@Composable +fun LabMarkerScreen(markerKey: String, onBack: () -> Unit, onAskCoach: (markerName: String) -> Unit) { + val context = LocalContext.current + val db = remember { PulseLoopDatabase.getInstance(context) } + val reports by remember(db) { db.labDao().reportsFlow() }.collectAsState(initial = null) + val results by remember(db) { db.labDao().resultsFlow() }.collectAsState(initial = null) + val marker = remember(reports, results) { + LabReports.markers(reports.orEmpty(), results.orEmpty()).firstOrNull { it.key == markerKey } + } + SettingsSubScreen(title = marker?.name ?: tr("Lab reports"), onBack = onBack) { + val m = marker ?: return@SettingsSubScreen + val l = m.latest + LabCard { + Overline(m.panel) + Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Text(LabReports.valueLabel(l.valueNum, l.valueText), fontSize = 40.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(listOfNotNull(l.unit, dayLabel(l.day)).joinToString(" · "), fontSize = 14.sp, color = PulseColors.textMuted, + modifier = Modifier.padding(bottom = 6.dp)) + } + val ref = LabReports.referenceLabel(l.refLow, l.refHigh, l.refText, l.unit) + Text( + when { + LabReports.isOutside(l.flag) && ref != null -> trf("{0} · the lab's range is {1}", flagLabel(l.flag), ref) + ref != null -> trf("{0} · the lab's range is {1}", flagLabel(l.flag), ref) + else -> tr("The report printed no range for this marker.") + }, + fontSize = 13.sp, color = flagColor(l.flag), + ) + } + + if (m.points.count { it.valueNum != null } >= 1) { + LabCard { + Overline(tr("Every exam")) + LabChart(m) + Text(tr("Shaded: the lab's reference range. Amber points are outside it."), fontSize = 11.sp, color = PulseColors.textMuted) + } + } + + LabCard { + Overline(tr("Values")) + m.points.reversed().forEach { p -> + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Text(dayLabel(p.day), fontSize = 14.sp, color = PulseColors.textSecondary, modifier = Modifier.weight(1f)) + Text(LabReports.valueLabel(p.valueNum, p.valueText) + (p.unit?.let { " $it" } ?: ""), fontSize = 14.sp, + fontWeight = FontWeight.Bold, color = if (LabReports.isOutside(p.flag)) PulseColors.warning else PulseColors.textPrimary) + } + } + } + + if (LabReports.isOutside(l.flag)) { + LabNotice(trf("Outside the lab's range on {0}. Worth bringing to your doctor.", dayLabel(l.day))) + } + + OutlinedButton(onClick = { onAskCoach(m.name) }, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)) { + Icon(Icons.Filled.AutoAwesome, null, tint = PulseColors.accent) + Spacer(Modifier.width(8.dp)) + Text(tr("Ask the coach for a plan"), color = PulseColors.accent) + } + } +} + +/** + * One point per exam, evenly spaced and labelled with its date, over the lab's range drawn as an + * accent dither band. Points outside the range are amber. A text result has no point. + */ +@Composable +private fun LabChart(m: LabReports.Marker) { + val pts = m.points.filter { it.valueNum != null } + val measurer = rememberTextMeasurer() + val l = m.latest + val values = pts.map { it.valueNum!! } + val bounds = values + listOfNotNull(l.refLow, l.refHigh) + val lo0 = bounds.min(); val hi0 = bounds.max() + val pad = ((hi0 - lo0).takeIf { it > 0 } ?: (kotlin.math.abs(hi0).takeIf { it > 0 } ?: 1.0)) * 0.15 + val lo = lo0 - pad; val hi = hi0 + pad + val label = TextStyle(fontSize = 11.sp, color = PulseColors.textPrimary, fontWeight = FontWeight.Bold) + val tick = TextStyle(fontSize = 10.sp, color = PulseColors.textMuted) + val description = pts.joinToString(", ") { "${dayLabel(it.day)}: ${LabReports.valueLabel(it.valueNum, null)}" } + Canvas(Modifier.fillMaxWidth().height(200.dp).semantics { contentDescription = description }) { + val top = 24.dp.toPx(); val bottom = size.height - 22.dp.toPx(); val side = 24.dp.toPx() + fun y(v: Double) = (bottom - (v - lo) / (hi - lo) * (bottom - top)).toFloat() + fun x(i: Int) = if (pts.size == 1) size.width / 2 else side + (size.width - 2 * side) * i / (pts.size - 1) + // The lab's range from the latest report: open-ended ranges run to the chart's edge. + if (l.refLow != null || l.refHigh != null) { + val bandTop = l.refHigh?.let { y(it) } ?: top + val bandBottom = l.refLow?.let { y(it) } ?: bottom + ditherBrush(PulseColors.accent, 0.14f)?.let { + drawRect(it, Offset(0f, bandTop), Size(size.width, (bandBottom - bandTop).coerceAtLeast(1f))) + } + } + if (pts.size >= 2) { + val path = Path() + pts.forEachIndexed { i, p -> if (i == 0) path.moveTo(x(i), y(p.valueNum!!)) else path.lineTo(x(i), y(p.valueNum!!)) } + drawPath(path, PulseColors.accent, style = Stroke(width = 2.dp.toPx())) + } + pts.forEachIndexed { i, p -> + val c = Offset(x(i), y(p.valueNum!!)) + drawCircle(PulseColors.background, 6.dp.toPx(), c) + drawCircle(if (LabReports.isOutside(p.flag)) PulseColors.warning else PulseColors.accent, 4.5.dp.toPx(), c) + val v = measurer.measure(LabReports.valueLabel(p.valueNum, null), label) + drawText(v, topLeft = Offset(c.x - v.size.width / 2, c.y - v.size.height - 8.dp.toPx())) + val d = measurer.measure(shortDay(p.day), tick) + drawText(d, topLeft = Offset((c.x - d.size.width / 2).coerceIn(0f, size.width - d.size.width), size.height - d.size.height)) + } + } +} + +// ── Reviewing a report the coach read ─────────────────────────────────────── + +@Composable +private fun LabReviewScreen( + draft: LabReports.Draft, + onChange: (LabReports.Draft) -> Unit, + onDiscard: () -> Unit, + onSave: () -> Unit, +) { + val context = LocalContext.current + var editing by remember { mutableStateOf(null) } + SettingsSubScreen(title = tr("New lab report"), onBack = onDiscard) { + LabCard { + Text(draft.fileName ?: tr("Lab report"), fontSize = 14.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(trf("{0} pages · read by the coach", draft.pageCount), fontSize = 12.sp, color = PulseColors.textMuted) + if (draft.pagesSkipped > 0) { + Text(trf("Only the first {0} pages were read.", LabReports.MAX_PAGES), fontSize = 12.sp, color = PulseColors.warning) + } + } + LabNotice(tr("Check every value against the PDF before saving. Fix anything the coach misread.")) + LabCard { + Overline(tr("Report")) + Row(verticalAlignment = Alignment.CenterVertically) { + Column(Modifier.weight(1f)) { + Text(tr("Collected on"), fontSize = 12.sp, color = PulseColors.textMuted) + Text(draft.collectedOn?.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)) ?: tr("Not found: set the date"), + fontSize = 15.sp, fontWeight = FontWeight.Bold, + color = if (draft.collectedOn == null) PulseColors.warning else PulseColors.textPrimary) + } + TextButton(onClick = { + val d = draft.collectedOn ?: LocalDate.now() + android.app.DatePickerDialog(context, { _, y, mo, day -> + onChange(draft.copy(collectedOn = LocalDate.of(y, mo + 1, day))) + }, d.year, d.monthValue - 1, d.dayOfMonth).show() + }) { Text(tr("Change")) } + } + OutlinedTextField( + value = draft.lab, onValueChange = { onChange(draft.copy(lab = it)) }, + label = { Text(tr("Laboratory")) }, singleLine = true, modifier = Modifier.fillMaxWidth(), + ) + if (draft.kinds.isNotEmpty()) { + Text(draft.kinds.joinToString(", ") { kindLabel(it) }, fontSize = 12.sp, color = PulseColors.textMuted) + } + } + LabCard { + Overline(trf("{0} markers found", draft.results.size)) + draft.results.forEachIndexed { i, r -> + if (i > 0) Box(Modifier.fillMaxWidth().height(1.dp).background(PulseColors.borderSubtle)) + Row( + Modifier.fillMaxWidth().clickable(role = Role.Button) { editing = i }.padding(vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Column(Modifier.weight(1f)) { + Text(r.name, fontSize = 14.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + LabReports.referenceLabel(r.refLow, r.refHigh, r.refText, r.unit)?.let { + Text(trf("Reference: {0}", it), fontSize = 12.sp, color = PulseColors.textMuted) + } + } + Text(LabReports.valueLabel(r.valueNum, r.valueText) + (r.unit.takeIf { it.isNotBlank() }?.let { " $it" } ?: ""), + fontSize = 14.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + if (LabReports.isOutside(r.flag)) Text(flagLabel(r.flag), fontSize = 12.sp, color = PulseColors.warning) + } + } + Text(tr("Tap a row to fix or remove it."), fontSize = 12.sp, color = PulseColors.accent) + } + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) { + OutlinedButton(onClick = onDiscard, modifier = Modifier.weight(1f).heightIn(min = 48.dp)) { Text(tr("Discard")) } + Button( + onClick = onSave, + enabled = draft.results.isNotEmpty(), + modifier = Modifier.weight(1f).heightIn(min = 48.dp), + colors = ButtonDefaults.buttonColors(containerColor = PulseColors.accent, contentColor = PulseColors.onAccent), + ) { Text(trf("Save {0} markers", draft.results.size)) } + } + } + + editing?.let { index -> + val r = draft.results.getOrNull(index) ?: return@let + var name by remember(index) { mutableStateOf(r.name) } + var value by remember(index) { mutableStateOf(LabReports.valueLabel(r.valueNum, r.valueText).takeIf { it != "—" } ?: "") } + var unit by remember(index) { mutableStateOf(r.unit) } + var low by remember(index) { mutableStateOf(r.refLow?.let(LabReports::formatValue) ?: "") } + var high by remember(index) { mutableStateOf(r.refHigh?.let(LabReports::formatValue) ?: "") } + fun num(s: String) = s.trim().replace(',', '.').toDoubleOrNull() + AlertDialog( + onDismissRequest = { editing = null }, + title = { Text(tr("Edit marker")) }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedTextField(name, { name = it }, label = { Text(tr("Name")) }, singleLine = true) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedTextField(value, { value = it }, label = { Text(tr("Value")) }, singleLine = true, modifier = Modifier.weight(1f)) + OutlinedTextField(unit, { unit = it }, label = { Text(tr("Unit")) }, singleLine = true, modifier = Modifier.weight(1f)) + } + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedTextField(low, { low = it }, label = { Text(tr("Range low")) }, singleLine = true, modifier = Modifier.weight(1f)) + OutlinedTextField(high, { high = it }, label = { Text(tr("Range high")) }, singleLine = true, modifier = Modifier.weight(1f)) + } + } + }, + confirmButton = { + TextButton(onClick = { + val n = num(value) + val updated = r.copy( + name = name.trim().ifBlank { r.name }, + valueNum = n, valueText = value.trim(), unit = unit.trim(), + refLow = num(low), refHigh = num(high), + ) + onChange(draft.copy(results = draft.results.toMutableList().also { it[index] = updated })) + editing = null + }) { Text(tr("Save")) } + }, + dismissButton = { + Row { + TextButton(onClick = { + onChange(draft.copy(results = draft.results.filterIndexed { i, _ -> i != index })) + editing = null + }) { Text(tr("Remove"), color = PulseColors.danger) } + TextButton(onClick = { editing = null }) { Text(tr("Cancel")) } + } + }, + ) + } +} diff --git a/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt b/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt index f3623c42..12f7f153 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt @@ -167,7 +167,7 @@ private fun Sparkline(values: List, color: Color, modifier: Modifier = M } @Composable -fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit, onWhatChanged: () -> Unit = {}, onCycle: () -> Unit = {}, onMeds: () -> Unit = {}, onPostpartum: () -> Unit = {}) { +fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit, onWhatChanged: () -> Unit = {}, onCycle: () -> Unit = {}, onMeds: () -> Unit = {}, onPostpartum: () -> Unit = {}, onLabReports: () -> Unit = {}) { val context = LocalContext.current val db = remember { PulseLoopDatabase.getInstance(context) } var refresh by remember { mutableIntStateOf(0) } @@ -251,6 +251,18 @@ fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit, onWhatChanged: () } Text("›", fontSize = 22.sp, color = PulseColors.textMuted) } + // Lab reports (LabReportsUi.kt): the PDFs the user added, every marker charted by exam. + Row( + Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card) + .clickable(onClick = onLabReports).padding(16.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Text(tr("Lab reports"), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(tr("Blood, urine and any other lab report, charted exam by exam"), fontSize = 12.sp, color = PulseColors.textMuted) + } + Text("›", fontSize = 22.sp, color = PulseColors.textMuted) + } Text( tr("Estimates from your ring compared with your own recent normal, not medical measurements."), fontSize = 11.sp, color = PulseColors.textMuted, diff --git a/app/src/main/res/xml/file_paths.xml b/app/src/main/res/xml/file_paths.xml index 5529992d..9f36ee3f 100644 --- a/app/src/main/res/xml/file_paths.xml +++ b/app/src/main/res/xml/file_paths.xml @@ -4,4 +4,6 @@ + + diff --git a/app/src/test/java/com/pulseloop/service/LabReportsTest.kt b/app/src/test/java/com/pulseloop/service/LabReportsTest.kt new file mode 100644 index 00000000..4c7e6c10 --- /dev/null +++ b/app/src/test/java/com/pulseloop/service/LabReportsTest.kt @@ -0,0 +1,85 @@ +package com.pulseloop.service + +import com.pulseloop.data.entity.LabReportEntity +import com.pulseloop.data.entity.LabResultEntity +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** The pure rules behind lab reports: flags against the lab's range, marker keys, decode, series. */ +class LabReportsTest { + + @Test + fun aNumericValueIsJudgedAgainstThePrintedRangeNotTheModelsFlag() { + // The model said normal; 148 is above the printed 130, so it is high. + assertEquals("HIGH", LabReports.flagFor(148.0, null, 130.0, "normal")) + assertEquals("LOW", LabReports.flagFor(22.0, 30.0, 100.0, "normal")) + assertEquals("NORMAL", LabReports.flagFor(52.0, 40.0, null, "high")) + // On the limit is inside. + assertEquals("NORMAL", LabReports.flagFor(130.0, null, 130.0, "unknown")) + } + + @Test + fun withoutANumberOrARangeTheReportsOwnMarkingStands() { + assertEquals("ABNORMAL", LabReports.flagFor(null, null, null, "abnormal")) + assertEquals("NORMAL", LabReports.flagFor(null, null, null, "Normal")) + assertEquals("UNKNOWN", LabReports.flagFor(5.0, null, null, "whatever")) + assertEquals("HIGH", LabReports.flagFor(5.0, null, null, "high")) + } + + @Test + fun oneKeyPerAnalyteWhateverTheAccentsOrPunctuation() { + assertEquals("colesterol_ldl", LabReports.normalizeKey("Colesterol LDL")) + assertEquals("vitamina_d_25_oh", LabReports.normalizeKey("Vitamina D (25-OH)")) + assertEquals("hemoglobina_glicada", LabReports.normalizeKey("Hemoglobina glicada ")) + assertEquals("proteinas_urina", LabReports.normalizeKey("Proteínas — urina")) + assertEquals("marker", LabReports.normalizeKey(" () ")) + } + + @Test + fun valuesShowWithoutTrailingZeros() { + assertEquals("148", LabReports.formatValue(148.0)) + assertEquals("14.6", LabReports.formatValue(14.6)) + assertEquals("0.85", LabReports.formatValue(0.8500001)) + assertEquals("Negative", LabReports.valueLabel(null, "Negative")) + assertEquals("—", LabReports.valueLabel(null, " ")) + } + + @Test + fun decodeToleratesFencesAndProse() { + val body = """{"collected_on":"2026-10-12","laboratory":"Lab","kinds":["blood"],"results":[ + {"panel":"Lipids","name":"LDL","key":"ldl_cholesterol","value_number":148,"value_text":"148","unit":"mg/dL", + "ref_low":null,"ref_high":130,"ref_text":"","flag":"high"}]}""" + val fenced = "Here it is:\n```json\n$body\n```\nLet me know." + val d = LabReports.decode(fenced) + assertNotNull(d) + assertEquals("2026-10-12", d!!.collectedOn) + assertEquals(148.0, d.results.single().valueNumber!!, 0.0) + assertNull(d.results.single().refLow) + assertNull(LabReports.decode("no json here")) + } + + @Test + fun aMarkerFollowsItsKeyAcrossReportsOldestFirst() { + val reports = listOf( + LabReportEntity(id = "b", collectedDay = 2_000L, createdAt = 0), + LabReportEntity(id = "a", collectedDay = 1_000L, createdAt = 0), + ) + fun r(id: String, report: String, v: Double, flag: String, name: String = "LDL") = LabResultEntity( + id = id, reportId = report, panel = "Lipids", name = name, markerKey = "ldl_cholesterol", + valueNum = v, refHigh = 130.0, flag = flag, + ) + // A result whose report is gone is left out rather than plotted on no date. + val orphan = r("x", "gone", 999.0, "HIGH") + val markers = LabReports.markers(reports, listOf(r("2", "b", 148.0, "HIGH", "Colesterol LDL"), r("1", "a", 126.0, "NORMAL"), orphan)) + val m = markers.single() + assertEquals(listOf(126.0, 148.0), m.points.map { it.valueNum }) + // Named as in the latest report. + assertEquals("Colesterol LDL", m.name) + assertTrue(LabReports.isOutside(m.latest.flag)) + assertFalse(LabReports.isOutside("NORMAL")) + } +}