Compare commits
126 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fab0c937cf | |||
| e3790d41e7 | |||
| 95288a7e83 | |||
| 88da2564a1 | |||
| a9f82f52d2 | |||
| da147f3325 | |||
| 70c5d034a8 | |||
| e942404213 | |||
| 7c13ec3de9 | |||
| 624ae47cfd | |||
| 2589c664ec | |||
| e0a4f71953 | |||
| 1190e2d079 | |||
| 9d63c33fa7 | |||
| 6c2c365a69 | |||
| 3cd04e60dc | |||
| a79b0175d5 | |||
| abd8793e60 | |||
| d56edbc413 | |||
| 9a0cc89941 | |||
| 51a31579c8 | |||
| 5add5fa55f | |||
| ffd30b0476 | |||
| 893eea4901 | |||
| eec847bb6c | |||
| 0c76dfd839 | |||
| 801d7a0199 | |||
| 86e702b5e2 | |||
| 9663738843 | |||
| 0fbedaeecf | |||
| 1c2fb2e451 | |||
| 098ed29ec7 | |||
| c02d9b2ea4 | |||
| 801a0b4bab | |||
| a936d07a7e | |||
| 03b6a455cb | |||
| b0c556b745 | |||
| 26d6a68ac0 | |||
| e6322f7f3e | |||
| 642467dc1d | |||
| 6cd3470502 | |||
| 3d8d358abd | |||
| a3d089fee3 | |||
| 3ce43b56df | |||
| 15a0899119 | |||
| eb6a9cf8c3 | |||
| 49144a2c49 | |||
| dfd60d4f7b | |||
| f793545468 | |||
| 76d4e58641 | |||
| 617e1ec879 | |||
| 649a324f8a | |||
| 4eca59bac9 | |||
| f4b4a034b7 | |||
| 57d304600e | |||
| ded7486244 | |||
| 8068205d0c | |||
| 91a9ee5295 | |||
| 0982565fdc | |||
| 957ddc7ddc | |||
| e7ef648757 | |||
| dc2799e36a | |||
| 2dc502bbb6 | |||
| c9c30b1ee5 | |||
| ff12f4e171 | |||
| 43e4b4070d | |||
| 45627f7075 | |||
| 60ce1a6d71 | |||
| 445712dea3 | |||
| 752c3704b2 | |||
| f25d22da20 | |||
| 737d09d37c | |||
| 83d05c637a | |||
| 07e5d2149c | |||
| 832f9ab7da | |||
| 3b200b60e7 | |||
| 4e44dd0eae | |||
| 1af80a6525 | |||
| 89055d91cd | |||
| e3af1f571b | |||
| 97af520fdd | |||
| 64841009a5 | |||
| cba89bcacb | |||
| bbef894195 | |||
| b82ff7c040 | |||
| a30628ab96 | |||
| 2a674774bb | |||
| 3960fb8ca0 | |||
| 1b5e201136 | |||
| e75e2bc89a | |||
| bda76b495d | |||
| 8957d51432 | |||
| 66650ca3cc | |||
| 84c78a0b1d | |||
| e7219571bd | |||
| eec7856664 | |||
| 8eb72647d5 | |||
| ee81788ed6 | |||
| e6432d5b9d | |||
| 8b82faf8f9 | |||
| 6587258da9 | |||
| 419ada929a | |||
| f2606fe0ca | |||
| a118120047 | |||
| 2d468bf5f8 | |||
| cb8028bd22 | |||
| 6dd52a11ae | |||
| b2176f8b69 | |||
| a9aa379a13 | |||
| 4e5c6b453e | |||
| f83938bfe3 | |||
| c310861855 | |||
| a6fcd3266e | |||
| 8bc1812147 | |||
| 5cd89a4e99 | |||
| a7e3685963 | |||
| 11173c7088 | |||
| 357bdb7e94 | |||
| f0623d0c44 | |||
| bf35afbdf5 | |||
| f1c6a26f18 | |||
| 908fbd2d1e | |||
| e761926df4 | |||
| 4b1de83e27 | |||
| 49b3ea4d57 | |||
| d11d323a04 |
62
.github/workflows/dependency-freshness.yml
vendored
@ -1,62 +0,0 @@
|
|||||||
name: dependency freshness
|
|
||||||
|
|
||||||
# Every dependency on its ecosystem's newest STABLE release, enforced on push
|
|
||||||
# as well as at commit time. The local pre-commit hook only sees the manifests
|
|
||||||
# in a commit and can be skipped entirely by a fresh clone that never ran
|
|
||||||
# `pre-commit install`; this runs `--all` over the whole repo.
|
|
||||||
#
|
|
||||||
# `--strict` is CI-only. Offline the gate degrades to its cached answer and
|
|
||||||
# passes, because `--no-verify` is banned locally and a hook that hard-failed
|
|
||||||
# on a flaky connection would leave no way to commit. A runner is always
|
|
||||||
# online, so here an undeterminable answer is a real failure.
|
|
||||||
#
|
|
||||||
# Expect this to go red for reasons this repo's commit did not cause: an
|
|
||||||
# upstream release overnight is enough. That is the chosen behaviour -- the
|
|
||||||
# alternative is a gate that only notices staleness when someone remembers to
|
|
||||||
# look.
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: [main]
|
|
||||||
pull_request:
|
|
||||||
workflow_dispatch:
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
dependency-freshness:
|
|
||||||
name: dependencies on newest stable
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
# The gate lives in the shared utils repo so every repo resolves the
|
|
||||||
# same "latest stable" the same way. Checking it out beats vendoring a
|
|
||||||
# copy, which is exactly how a gate and its survey start disagreeing.
|
|
||||||
- name: Check out the shared gate
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
repository: kuhyx/utils
|
|
||||||
path: .utils
|
|
||||||
|
|
||||||
# "3.x", never a pinned minor: the Python target IS the interpreter the
|
|
||||||
# gate runs under (registries/toolchain.python_installed), so a runner
|
|
||||||
# held a release behind this machine reports a repo's `requires-python`
|
|
||||||
# as excluding "latest" while the same check passes locally. flax-docs-mcp
|
|
||||||
# hit exactly that -- `>=3.14` green here, red on a 3.13 runner.
|
|
||||||
- name: Set up Python
|
|
||||||
uses: actions/setup-python@v5
|
|
||||||
with:
|
|
||||||
python-version: "3.x"
|
|
||||||
|
|
||||||
- name: Install the gate's two runtime dependencies
|
|
||||||
run: python -m pip install --upgrade pyyaml packaging
|
|
||||||
|
|
||||||
- name: Cache registry lookups
|
|
||||||
uses: actions/cache@v4
|
|
||||||
with:
|
|
||||||
path: ~/.cache/dep-freshness
|
|
||||||
key: dep-freshness-${{ hashFiles('**/pubspec.yaml', '**/pyproject.toml',
|
|
||||||
'**/requirements*.txt', '**/package.json', '**/Cargo.toml', '**/go.mod') }}
|
|
||||||
restore-keys: dep-freshness-
|
|
||||||
|
|
||||||
- name: Every dependency is on newest stable
|
|
||||||
run: bash .utils/scripts/check_dependency_freshness.sh --all --strict
|
|
||||||
14
.github/workflows/pre-commit.yml
vendored
@ -25,14 +25,14 @@ jobs:
|
|||||||
skip: ""
|
skip: ""
|
||||||
- group: rest
|
- group: rest
|
||||||
hooks: ""
|
hooks: ""
|
||||||
skip: mypy,pylint
|
skip: mypy,pylint,dependency-freshness
|
||||||
name: pre-commit (${{ matrix.group }})
|
name: pre-commit (${{ matrix.group }})
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
# The file-length, md-naming and dependency-freshness hooks delegate to
|
# The file-length and md-naming hooks delegate to the shared gates in
|
||||||
# the shared gates in kuhyx/utils, which a runner does not have at
|
# kuhyx/utils, which a runner does not have at $HOME/src/utils. Only
|
||||||
# $HOME/src/utils. Only the rest group runs them.
|
# the rest group runs them.
|
||||||
- name: Check out the shared gates
|
- name: Check out the shared gates
|
||||||
if: matrix.group == 'rest'
|
if: matrix.group == 'rest'
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
@ -59,9 +59,9 @@ jobs:
|
|||||||
# mypy and pylint bring their own hook environments, so they need only
|
# mypy and pylint bring their own hook environments, so they need only
|
||||||
# pre-commit. The rest group's language: system patch-targets hook
|
# pre-commit. The rest group's language: system patch-targets hook
|
||||||
# imports diet_guard and every patched module (requests, gatelock,
|
# imports diet_guard and every patched module (requests, gatelock,
|
||||||
# crdt_sync, freedays, mcp, pydantic), and dependency-freshness needs
|
# crdt_sync, freedays, mcp, pydantic) -- so it keeps the full
|
||||||
# pyyaml and packaging -- so it keeps the full requirements.txt. That
|
# requirements.txt. That install used to run in the one job, with plain
|
||||||
# install used to run in the one job, with plain pip, for ~24 s.
|
# pip, for ~24 s.
|
||||||
- name: Install pre-commit and the system hooks' imports
|
- name: Install pre-commit and the system hooks' imports
|
||||||
run: |
|
run: |
|
||||||
if [[ "${{ matrix.group }}" == rest ]]; then
|
if [[ "${{ matrix.group }}" == rest ]]; then
|
||||||
|
|||||||
8
.github/workflows/python-tests.yml
vendored
@ -31,13 +31,15 @@ jobs:
|
|||||||
# The gate's keyboard and layout tests drive real Tk: widget heights and
|
# The gate's keyboard and layout tests drive real Tk: widget heights and
|
||||||
# the focus ring come from the font engine, and no mock can answer what
|
# the focus ring come from the font engine, and no mock can answer what
|
||||||
# they ask. Without a display they do not skip -- they fail, which is how
|
# they ask. Without a display they do not skip -- they fail, which is how
|
||||||
# this job stayed red while the tests themselves were fine.
|
# this job stayed red while the tests themselves were fine. pytest-xvfb
|
||||||
|
# (requirements.txt, geometry in pyproject) starts one Xvfb per xdist
|
||||||
|
# worker: a shared display let workers steal each other's focus.
|
||||||
# ubuntu-latest already ships xvfb, so the unconditional
|
# ubuntu-latest already ships xvfb, so the unconditional
|
||||||
# `apt-get update && install` spent ~7 s to report "already the newest
|
# `apt-get update && install` spent ~7 s to report "already the newest
|
||||||
# version"; it now installs only on an image that lacks it.
|
# version"; it now installs only on an image that lacks it.
|
||||||
- name: Install a virtual X display
|
- name: Install a virtual X display
|
||||||
run: |
|
run: |
|
||||||
command -v xvfb-run >/dev/null \
|
command -v Xvfb >/dev/null \
|
||||||
|| { sudo apt-get update && sudo apt-get install -y xvfb; }
|
|| { sudo apt-get update && sudo apt-get install -y xvfb; }
|
||||||
|
|
||||||
# -n auto spreads the suite over every runner core (pytest-xdist is in
|
# -n auto spreads the suite over every runner core (pytest-xdist is in
|
||||||
@ -46,7 +48,7 @@ jobs:
|
|||||||
# printed all ~1050 test ids.
|
# printed all ~1050 test ids.
|
||||||
- name: Run tests with coverage
|
- name: Run tests with coverage
|
||||||
run: |
|
run: |
|
||||||
xvfb-run -a -s "-screen 0 1600x1200x24" python -m pytest \
|
python -m pytest \
|
||||||
-n auto \
|
-n auto \
|
||||||
-p no:sugar \
|
-p no:sugar \
|
||||||
-q
|
-q
|
||||||
|
|||||||
16
.github/workflows/release-apk.yml
vendored
@ -3,6 +3,14 @@ name: release-apk
|
|||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [main]
|
branches: [main]
|
||||||
|
# A publisher, not a gate: build only when something that ends up in
|
||||||
|
# the APK changed. versionCode is the commit count, so skipped pushes
|
||||||
|
# still leave it monotonic.
|
||||||
|
paths:
|
||||||
|
- 'app/**'
|
||||||
|
- '.fvmrc'
|
||||||
|
- '.versioncode-offset'
|
||||||
|
- '.github/workflows/release-apk.yml'
|
||||||
# Lets a release be rebuilt from the current main without a dummy commit.
|
# Lets a release be rebuilt from the current main without a dummy commit.
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
@ -47,10 +55,12 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
distribution: temurin
|
distribution: temurin
|
||||||
java-version: "17"
|
java-version: "17"
|
||||||
|
# ~/.gradle caches + wrapper, keyed on the Gradle files.
|
||||||
|
cache: gradle
|
||||||
|
|
||||||
- uses: subosito/flutter-action@v2
|
- uses: subosito/flutter-action@v2
|
||||||
with:
|
with:
|
||||||
flutter-version: 3.47.5
|
flutter-version: 3.50.1
|
||||||
channel: stable
|
channel: stable
|
||||||
cache: true
|
cache: true
|
||||||
|
|
||||||
@ -98,7 +108,9 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
flutter build apk --release \
|
flutter build apk --release \
|
||||||
--build-name="${{ steps.ver.outputs.semver }}" \
|
--build-name="${{ steps.ver.outputs.semver }}" \
|
||||||
--build-number="${{ steps.vc.outputs.code }}"
|
--build-number="${{ steps.vc.outputs.code }}" \
|
||||||
|
--dart-define=APP_BUILD="${{ steps.vc.outputs.code }}" \
|
||||||
|
--dart-define=APP_VERSION="${{ steps.ver.outputs.semver }}"
|
||||||
|
|
||||||
# Fail closed. `findByName("release") ?: debug` silently falls back to
|
# Fail closed. `findByName("release") ?: debug` silently falls back to
|
||||||
# the debug key if key.properties is misplaced, producing a green build
|
# the debug key if key.properties is misplaced, producing a green build
|
||||||
|
|||||||
25
.github/workflows/repo-contract.yml
vendored
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
name: repo-contract
|
||||||
|
|
||||||
|
# The local pre-commit hook can be skipped (a fresh clone has no hooks), so the
|
||||||
|
# contract is enforced on push too. Mirrors md-naming.yml.
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
pull_request:
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
repo-contract:
|
||||||
|
name: repo contract
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Check out the shared gate
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
repository: kuhyx/utils
|
||||||
|
path: .utils
|
||||||
|
|
||||||
|
- name: Enforce the repo contract
|
||||||
|
run: bash .utils/scripts/check_repo_contract.sh
|
||||||
@ -9,6 +9,7 @@ default_language_version:
|
|||||||
default_stages: [pre-commit]
|
default_stages: [pre-commit]
|
||||||
fail_fast: false
|
fail_fast: false
|
||||||
|
|
||||||
|
default_install_hook_types: [pre-commit, pre-push, post-commit, post-merge, post-rewrite]
|
||||||
repos:
|
repos:
|
||||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||||
rev: v4.6.0
|
rev: v4.6.0
|
||||||
@ -28,7 +29,7 @@ repos:
|
|||||||
args: [--pytest-test-first]
|
args: [--pytest-test-first]
|
||||||
# Shared fakes and fixtures, not test modules. Split out of conftest.py
|
# Shared fakes and fixtures, not test modules. Split out of conftest.py
|
||||||
# and test_sync.py only because those files passed the 250-line cap.
|
# and test_sync.py only because those files passed the 250-line cap.
|
||||||
exclude: ^diet_guard/tests/_(tk_fakes(_containers|_canvas)?|gate_layout_probe|gate_focus_probe|gate_measurement|gate_keyboard_probe|gate_fixtures|sync_fakes|kuchnia_fakes)\.py$
|
exclude: ^diet_guard/tests/_(tk_fakes(_containers|_canvas)?|gate_layout_probe|gate_focus_probe|gate_measurement|gate_keyboard_probe|gate_fixtures|sync_fakes|kuchnia_fakes|state_redirects|claude_redirects|claude_fakes|claude_worker_fakes)\.py$
|
||||||
- id: check-ast
|
- id: check-ast
|
||||||
- id: mixed-line-ending
|
- id: mixed-line-ending
|
||||||
args: [--fix=lf]
|
args: [--fix=lf]
|
||||||
@ -95,6 +96,10 @@ repos:
|
|||||||
rev: v3.3.2
|
rev: v3.3.2
|
||||||
hooks:
|
hooks:
|
||||||
- id: pylint
|
- id: pylint
|
||||||
|
# pre-commit itself runs on 3.15 and `python3` resolves to it; this
|
||||||
|
# pylint's --jobs=4 pickles with dill, which crashes there
|
||||||
|
# (no `co_lnotab`). The repo targets 3.14.
|
||||||
|
language_version: python3.14
|
||||||
args:
|
args:
|
||||||
- --rcfile=pyproject.toml
|
- --rcfile=pyproject.toml
|
||||||
- --fail-under=10
|
- --fail-under=10
|
||||||
@ -106,11 +111,17 @@ repos:
|
|||||||
# direct URLs for one distribution, so any pin that drifts from
|
# direct URLs for one distribution, so any pin that drifts from
|
||||||
# the manifest becomes an unresolvable hook environment rather
|
# the manifest becomes an unresolvable hook environment rather
|
||||||
# than merely an old one.
|
# than merely an old one.
|
||||||
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.8.2#subdirectory=gatelock
|
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.0#subdirectory=gatelock
|
||||||
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.1#subdirectory=crdt-sync
|
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
|
||||||
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.2.0#subdirectory=freedays
|
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays
|
||||||
|
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.8#subdirectory=sickdays
|
||||||
|
- kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.1#subdirectory=kuhy_credit
|
||||||
|
- rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.2.1#subdirectory=rtdb_relay
|
||||||
|
- claude-agent-sdk==0.2.184
|
||||||
|
- httpx==0.28.1
|
||||||
- mcp>=2,<3
|
- mcp>=2,<3
|
||||||
- pydantic
|
- pydantic
|
||||||
|
- defusedxml==0.7.1
|
||||||
# Test suites intentionally use patterns (protected-access, magic-value
|
# Test suites intentionally use patterns (protected-access, magic-value
|
||||||
# comparisons) that don't belong in the source-code 10/10 gate.
|
# comparisons) that don't belong in the source-code 10/10 gate.
|
||||||
exclude: ^(\.venv/)|(^|/)(tests/|conftest\.py)
|
exclude: ^(\.venv/)|(^|/)(tests/|conftest\.py)
|
||||||
@ -130,9 +141,130 @@ repos:
|
|||||||
|
|
||||||
- repo: local
|
- repo: local
|
||||||
hooks:
|
hooks:
|
||||||
- id: ci-mirror
|
# Split into <60 s steps (run in this order); no-arg ci_mirror.sh is the CI form.
|
||||||
name: CI mirror (clean-venv pytest + pre-commit --all-files)
|
- id: ci-mirror-venv
|
||||||
entry: bash scripts/ci_mirror.sh
|
name: CI mirror 1 (clean venv)
|
||||||
|
entry: bash scripts/ci_mirror.sh venv
|
||||||
|
language: system
|
||||||
|
pass_filenames: false
|
||||||
|
always_run: true
|
||||||
|
require_serial: true
|
||||||
|
stages: [manual]
|
||||||
|
- id: ci-mirror-precommit
|
||||||
|
name: CI mirror 2 (pre-commit --all-files)
|
||||||
|
entry: bash scripts/ci_mirror.sh precommit
|
||||||
|
language: system
|
||||||
|
pass_filenames: false
|
||||||
|
always_run: true
|
||||||
|
require_serial: true
|
||||||
|
stages: [manual]
|
||||||
|
- id: ci-mirror-pytest
|
||||||
|
name: CI mirror 3 (pytest, xvfb, 100% cov)
|
||||||
|
entry: bash scripts/ci_mirror.sh pytest
|
||||||
|
language: system
|
||||||
|
pass_filenames: false
|
||||||
|
always_run: true
|
||||||
|
require_serial: true
|
||||||
|
stages: [manual]
|
||||||
|
- id: ci-mirror-flutter-analyze
|
||||||
|
name: CI mirror 4 (flutter analyze)
|
||||||
|
entry: bash scripts/ci_mirror.sh flutter-analyze
|
||||||
|
language: system
|
||||||
|
pass_filenames: false
|
||||||
|
always_run: true
|
||||||
|
require_serial: true
|
||||||
|
stages: [manual]
|
||||||
|
- id: ci-mirror-flutter-test-1
|
||||||
|
name: CI mirror 5 (flutter test 1/12)
|
||||||
|
entry: bash scripts/ci_mirror.sh flutter-test --shard 0/12
|
||||||
|
language: system
|
||||||
|
pass_filenames: false
|
||||||
|
always_run: true
|
||||||
|
require_serial: true
|
||||||
|
stages: [manual]
|
||||||
|
- id: ci-mirror-flutter-test-2
|
||||||
|
name: CI mirror 6 (flutter test 2/12)
|
||||||
|
entry: bash scripts/ci_mirror.sh flutter-test --shard 1/12
|
||||||
|
language: system
|
||||||
|
pass_filenames: false
|
||||||
|
always_run: true
|
||||||
|
require_serial: true
|
||||||
|
stages: [manual]
|
||||||
|
- id: ci-mirror-flutter-test-3
|
||||||
|
name: CI mirror 7 (flutter test 3/12)
|
||||||
|
entry: bash scripts/ci_mirror.sh flutter-test --shard 2/12
|
||||||
|
language: system
|
||||||
|
pass_filenames: false
|
||||||
|
always_run: true
|
||||||
|
require_serial: true
|
||||||
|
stages: [manual]
|
||||||
|
- id: ci-mirror-flutter-test-4
|
||||||
|
name: CI mirror 8 (flutter test 4/12)
|
||||||
|
entry: bash scripts/ci_mirror.sh flutter-test --shard 3/12
|
||||||
|
language: system
|
||||||
|
pass_filenames: false
|
||||||
|
always_run: true
|
||||||
|
require_serial: true
|
||||||
|
stages: [manual]
|
||||||
|
- id: ci-mirror-flutter-test-5
|
||||||
|
name: CI mirror 9 (flutter test 5/12)
|
||||||
|
entry: bash scripts/ci_mirror.sh flutter-test --shard 4/12
|
||||||
|
language: system
|
||||||
|
pass_filenames: false
|
||||||
|
always_run: true
|
||||||
|
require_serial: true
|
||||||
|
stages: [manual]
|
||||||
|
- id: ci-mirror-flutter-test-6
|
||||||
|
name: CI mirror 10 (flutter test 6/12)
|
||||||
|
entry: bash scripts/ci_mirror.sh flutter-test --shard 5/12
|
||||||
|
language: system
|
||||||
|
pass_filenames: false
|
||||||
|
always_run: true
|
||||||
|
require_serial: true
|
||||||
|
stages: [manual]
|
||||||
|
- id: ci-mirror-flutter-test-7
|
||||||
|
name: CI mirror 11 (flutter test 7/12)
|
||||||
|
entry: bash scripts/ci_mirror.sh flutter-test --shard 6/12
|
||||||
|
language: system
|
||||||
|
pass_filenames: false
|
||||||
|
always_run: true
|
||||||
|
require_serial: true
|
||||||
|
stages: [manual]
|
||||||
|
- id: ci-mirror-flutter-test-8
|
||||||
|
name: CI mirror 12 (flutter test 8/12)
|
||||||
|
entry: bash scripts/ci_mirror.sh flutter-test --shard 7/12
|
||||||
|
language: system
|
||||||
|
pass_filenames: false
|
||||||
|
always_run: true
|
||||||
|
require_serial: true
|
||||||
|
stages: [manual]
|
||||||
|
- id: ci-mirror-flutter-test-9
|
||||||
|
name: CI mirror 13 (flutter test 9/12)
|
||||||
|
entry: bash scripts/ci_mirror.sh flutter-test --shard 8/12
|
||||||
|
language: system
|
||||||
|
pass_filenames: false
|
||||||
|
always_run: true
|
||||||
|
require_serial: true
|
||||||
|
stages: [manual]
|
||||||
|
- id: ci-mirror-flutter-test-10
|
||||||
|
name: CI mirror 14 (flutter test 10/12)
|
||||||
|
entry: bash scripts/ci_mirror.sh flutter-test --shard 9/12
|
||||||
|
language: system
|
||||||
|
pass_filenames: false
|
||||||
|
always_run: true
|
||||||
|
require_serial: true
|
||||||
|
stages: [manual]
|
||||||
|
- id: ci-mirror-flutter-test-11
|
||||||
|
name: CI mirror 15 (flutter test 11/12)
|
||||||
|
entry: bash scripts/ci_mirror.sh flutter-test --shard 10/12
|
||||||
|
language: system
|
||||||
|
pass_filenames: false
|
||||||
|
always_run: true
|
||||||
|
require_serial: true
|
||||||
|
stages: [manual]
|
||||||
|
- id: ci-mirror-flutter-test-12
|
||||||
|
name: CI mirror 16 (flutter test 12/12)
|
||||||
|
entry: bash scripts/ci_mirror.sh flutter-test --shard 11/12
|
||||||
language: system
|
language: system
|
||||||
pass_filenames: false
|
pass_filenames: false
|
||||||
always_run: true
|
always_run: true
|
||||||
@ -145,6 +277,8 @@ repos:
|
|||||||
- id: codespell
|
- id: codespell
|
||||||
args:
|
args:
|
||||||
- --skip=*.json,*.lock,.git,__pycache__,.venv
|
- --skip=*.json,*.lock,.git,__pycache__,.venv
|
||||||
|
# Devine: the 1974 ideal-body-weight formula's author, not "define".
|
||||||
|
- --ignore-words-list=devine
|
||||||
|
|
||||||
- repo: local
|
- repo: local
|
||||||
hooks:
|
hooks:
|
||||||
@ -196,7 +330,7 @@ repos:
|
|||||||
# patch target statically so a stale path fails the commit instead.
|
# patch target statically so a stale path fails the commit instead.
|
||||||
- id: patch-targets
|
- id: patch-targets
|
||||||
name: test patch targets resolve
|
name: test patch targets resolve
|
||||||
entry: python3 scripts/check_patch_targets.py
|
entry: python3 scripts/check_patch_targets.py diet_guard
|
||||||
language: system
|
language: system
|
||||||
pass_filenames: false
|
pass_filenames: false
|
||||||
files: ^diet_guard/
|
files: ^diet_guard/
|
||||||
@ -211,6 +345,30 @@ repos:
|
|||||||
language: system
|
language: system
|
||||||
files: \.(md|markdown)$
|
files: \.(md|markdown)$
|
||||||
|
|
||||||
|
- id: todo-closer
|
||||||
|
name: close Todo trailer tasks
|
||||||
|
entry: scripts/todo_hooks.sh closer
|
||||||
|
language: system
|
||||||
|
stages: [post-commit]
|
||||||
|
always_run: true
|
||||||
|
pass_filenames: false
|
||||||
|
|
||||||
|
- id: todo-import-pr-merge
|
||||||
|
name: import PR Todo sections (pull)
|
||||||
|
entry: scripts/todo_hooks.sh import-pr post-merge
|
||||||
|
language: system
|
||||||
|
stages: [post-merge]
|
||||||
|
always_run: true
|
||||||
|
pass_filenames: false
|
||||||
|
|
||||||
|
- id: todo-import-pr-rewrite
|
||||||
|
name: import PR Todo sections (pull --rebase)
|
||||||
|
entry: scripts/todo_hooks.sh import-pr post-rewrite
|
||||||
|
language: system
|
||||||
|
stages: [post-rewrite]
|
||||||
|
always_run: true
|
||||||
|
pass_filenames: false
|
||||||
|
|
||||||
# Every dependency on its ecosystem's newest STABLE release, exact-pinned
|
# Every dependency on its ecosystem's newest STABLE release, exact-pinned
|
||||||
# so the question is mechanically answerable at all.
|
# so the question is mechanically answerable at all.
|
||||||
#
|
#
|
||||||
@ -246,3 +404,9 @@ repos:
|
|||||||
pass_filenames: false
|
pass_filenames: false
|
||||||
always_run: true
|
always_run: true
|
||||||
stages: [pre-push]
|
stages: [pre-push]
|
||||||
|
- id: repo-contract
|
||||||
|
name: repo contract (CLAUDE.md Commands + test_changed)
|
||||||
|
entry: scripts/check_repo_contract.sh
|
||||||
|
language: system
|
||||||
|
pass_filenames: false
|
||||||
|
files: ^(CLAUDE\.md|AGENTS\.md|scripts/test_changed\.sh)$|(^|/)(AndroidManifest\.xml|build\.gradle(\.kts)?|strings\.xml|pubspec\.yaml|repo-contract\.toml|[^/]+\.desktop|assets/icon/[^/]+\.png)$
|
||||||
|
|||||||
166
AGENTS.md
@ -1,52 +1,57 @@
|
|||||||
# CLAUDE.md — diet_guard
|
# CLAUDE.md — diet_guard
|
||||||
|
|
||||||
A log-to-unlock gate. Every ~30 min `diet-guard-gate.timer` checks whether a
|
A log-to-unlock gate. Every ~15 min `diet-guard-gate.timer` checks whether a meal slot (08:00,
|
||||||
meal slot (08:00, 12:00, 16:00, 20:00 by default — the schedule is
|
12:00, 16:00, 20:00 by default — the schedule is user-configurable, see below) elapsed unlogged; if
|
||||||
user-configurable, see below) elapsed unlogged; if so it opens a
|
so it opens a fullscreen Tk window that blocks the desktop until the user logs what they ate. It
|
||||||
fullscreen Tk window that blocks the desktop until the user logs what they
|
also tracks a daily calorie/macro budget, seeded from biometrics at `init` and freely editable
|
||||||
ate. It also tracks a daily calorie/macro budget, seeded from biometrics at
|
afterward on either device. A History tab (`_gatelock_calendar.py`) and the phone's Calendar screen
|
||||||
`init` and freely editable afterward on either device. A History tab
|
show adherence, streaks, a YTD tally and weekly/monthly averages, all derived from `_daystatus.py` /
|
||||||
(`_gatelock_calendar.py`) and the phone's Calendar screen show adherence,
|
`day_status_service.dart` and `_averages.py` / `average_service.dart`.
|
||||||
streaks, a YTD tally and weekly/monthly averages, all derived from
|
|
||||||
`_daystatus.py` / `day_status_service.dart` and `_averages.py` /
|
|
||||||
`average_service.dart`.
|
|
||||||
|
|
||||||
`docs/DOCS-design.md` holds the original spec (slot timing, the Tue/Wed/Thu
|
`docs/DOCS-design.md` holds the original spec (slot timing, the Tue/Wed/Thu catch-up rule).
|
||||||
catch-up rule).
|
|
||||||
|
|
||||||
## Commands
|
## Commands
|
||||||
|
|
||||||
- Tests: `python -m pytest diet_guard/tests/ --cov=diet_guard --cov-branch --cov-fail-under=100`
|
|
||||||
- Lint: `pre-commit run --all-files`
|
|
||||||
- Test the lock (safe, closeable): `python -m diet_guard gate --demo`
|
|
||||||
- One sync tick: `python -m diet_guard sync`
|
- One sync tick: `python -m diet_guard sync`
|
||||||
- Averages: `python -m diet_guard averages`
|
- Averages: `python -m diet_guard averages`; Body: `body`, `weight KG`, `profile`, `plan-week`
|
||||||
- Prune dead sync peers (dry run): `python -m diet_guard prune-peers`
|
- Prune dead sync peers (dry run): `python -m diet_guard prune-peers`
|
||||||
- Install for production: `bash install.sh`
|
- "Send to Claude" worker: `python -m diet_guard claude-worker` ([relay](docs/DOCS-claude-relay.md), [screen](docs/DOCS-log-screen.md))
|
||||||
- App tests: `cd app && flutter test`
|
- Install: `bash install.sh` (production); app: `cd app && bash install_arch.sh`; run app: `bash run.sh`; phone: `flutter build apk --release`
|
||||||
- Desktop app: `cd app && bash run.sh`
|
- run: `python -m diet_guard gate --demo`
|
||||||
- Install desktop app: `cd app && bash install_arch.sh`
|
- test: `python -m pytest -n auto -p no:sugar -q` (python, 100% branch bar from pyproject) then `cd app && flutter test --reporter=compact`
|
||||||
- Phone build: `cd app && flutter build apk --release`
|
- test-changed: `scripts/test_changed.sh` (maps py and app/ dart changes to their tests, no coverage)
|
||||||
|
- lint: `pre-commit run --all-files`
|
||||||
|
- coverage: `python -m pytest -n auto -p no:sugar -q` (writes coverage.lcov)
|
||||||
|
- deploy: `bash scripts/deploy.sh` (pull ~/src/diet-guard, system-Python install, desktop app; health-checked)
|
||||||
|
- coverage-gaps: `coverage-gaps coverage.lcov`
|
||||||
|
|
||||||
## Scheduling
|
## Scheduling
|
||||||
|
|
||||||
`diet-guard-gate.timer` is wall-clock (`OnCalendar=*-*-* *:00/30:00`,
|
`diet-guard-gate.timer` is wall-clock (`OnCalendar=*-*-* *:00/15:00`, `Persistent=true`), not
|
||||||
`Persistent=true`), not boot-relative — a boot-relative timer collided with
|
boot-relative — a boot-relative timer collided with fullscreen games grabbing input.
|
||||||
fullscreen games grabbing input. `diet-guard-gate.service` is `Type=oneshot`
|
`diet-guard-gate.service` is `Type=oneshot` and exits 0 at once when no lock is due (free/sick day:
|
||||||
and exits 0 immediately when no lock is due. It needs `DISPLAY`/`XAUTHORITY`;
|
[docs/DOCS-sick-days.md](docs/DOCS-sick-days.md)). Needs `DISPLAY`/`XAUTHORITY`; see the unit file
|
||||||
see the unit file's comments and `wait_for_display()`.
|
and `wait_for_display()`.
|
||||||
|
|
||||||
## Cross-device sync
|
## Cross-device sync
|
||||||
|
|
||||||
A sync tick pulls every other device's log from `kuhyx/syncs`
|
A sync tick pulls every other device's log from `kuhyx/syncs` (`diet-guard-sync/`, dumb file storage
|
||||||
(`diet-guard-sync/`, dumb file storage via the REST Contents API), merges
|
via the REST Contents API), merges (`_sync_merge.merge_logs`: union by `id`, tombstone wins, legacy
|
||||||
(`_sync_merge.merge_logs`: union by `id`, tombstone wins, legacy
|
`(time, desc)` dedup), **re-signs every persisted entry**, rebuilds the food bank, pushes back.
|
||||||
`(time, desc)` dedup), **re-signs every persisted entry**, rebuilds the food
|
|
||||||
bank, pushes back.
|
|
||||||
|
|
||||||
**On the PC, sync is event-driven — there is no periodic timer.** The old
|
**End-to-end encrypted** (since 2026-11-12, `_sync_e2e.py` / `app/lib/services/sync_e2e.dart`):
|
||||||
`diet-guard-sync.timer` (~15 min) was deleted: it paid a network round-trip on
|
everything lives on `diet-guard-sync/devices-e2e` (revs `revs-e2e`, header `diet-guard-sync/e2e`),
|
||||||
every idle tick to approximate the two moments state actually changes here.
|
fields sealed with a key from the shared passphrase (`~/.config/crdt-sync/password`; keystore + lock
|
||||||
|
icon in Settings on the phone). Record ids, tombstones and clocks stay clear, so the food banks' ids
|
||||||
|
(food names) are visible. The old plaintext `diet-guard-sync/devices` (and its `export_keys.json`
|
||||||
|
keyring) is copied over and never written or deleted. Locked = `SyncError` / `SyncLockedException`:
|
||||||
|
nothing is pulled or pushed. The PC keeps its derived key and copy memo in
|
||||||
|
`~/.local/share/diet_guard/e2e`. The wake-alarm weigh-ins come from `wake-alarm-sync/devices-e2e`
|
||||||
|
(own header).
|
||||||
|
|
||||||
|
**On the PC, sync is event-driven — there is no periodic timer.** The old `diet-guard-sync.timer`
|
||||||
|
(~15 min) was deleted: it paid a network round-trip on every idle tick to approximate the two
|
||||||
|
moments state actually changes here.
|
||||||
|
|
||||||
- **Before a lock** — `_cli_gate._should_lock` runs the cheap local
|
- **Before a lock** — `_cli_gate._should_lock` runs the cheap local
|
||||||
`gate_is_due()` first and pulls *only* when a lock is otherwise due, so a
|
`gate_is_due()` first and pulls *only* when a lock is otherwise due, so a
|
||||||
@ -67,8 +72,8 @@ every idle tick to approximate the two moments state actually changes here.
|
|||||||
demo already writes real entries through `log_meal` (only the *slot* is
|
demo already writes real entries through `log_meal` (only the *slot* is
|
||||||
synthetic).
|
synthetic).
|
||||||
- `pull_shared_log()` is misnamed: it runs a *full* tick (pull, merge, re-sign,
|
- `pull_shared_log()` is misnamed: it runs a *full* tick (pull, merge, re-sign,
|
||||||
persist, **push**, budget, both food banks, and last the phone's weigh-in
|
persist, **push**, budget, both food banks, the Body doc via `_sync_body`,
|
||||||
into `w` via `_phone_weight`: `wake_alarm._weight`, lazy, never raises).
|
and last the newest logged weight into `w` via `_phone_weight`).
|
||||||
`_sync_refresh.pull_peer_logs()` is for anything a user waits on. What must
|
`_sync_refresh.pull_peer_logs()` is for anything a user waits on. What must
|
||||||
follow every tick goes in `run_sync`, not `cmd_sync` (the PC never runs it).
|
follow every tick goes in `run_sync`, not `cmd_sync` (the PC never runs it).
|
||||||
- Accepted trade: a PC neither logging nor locking does not pull.
|
- Accepted trade: a PC neither logging nor locking does not pull.
|
||||||
@ -79,8 +84,8 @@ every idle tick to approximate the two moments state actually changes here.
|
|||||||
`_sync_refresh.py`, the fetch button, or the publish paths.
|
`_sync_refresh.py`, the fetch button, or the publish paths.
|
||||||
- Every test that logs a meal would otherwise hit the network through these new
|
- Every test that logs a meal would otherwise hit the network through these new
|
||||||
call sites; `conftest._isolate_state` patches each one
|
call sites; `conftest._isolate_state` patches each one
|
||||||
(`_cli_log.publish_after_log_detached`, `_cli_gate.publish_after_log`,
|
(listed in `tests/_state_redirects.py`: `_cli_log`, `_cli_gate`, `_mcp`,
|
||||||
`_mcp.publish_after_log`, `_cli_gate.pull_peer_logs`) — not on
|
`_cli_body`, `_cli_kuchnia` publish sites and `_cli_gate.pull_peer_logs`) — not on
|
||||||
`_sync_events`, so a direct test still exercises the real helper. A new
|
`_sync_events`, so a direct test still exercises the real helper. A new
|
||||||
network entry point missing from that list reaches the real remote.
|
network entry point missing from that list reaches the real remote.
|
||||||
|
|
||||||
@ -110,19 +115,18 @@ every idle tick to approximate the two moments state actually changes here.
|
|||||||
|
|
||||||
## Production dependency installation
|
## Production dependency installation
|
||||||
|
|
||||||
`diet-guard-gate.service` runs `/usr/bin/python`, **not** a venv. Any new
|
`diet-guard-gate.service` runs `/usr/bin/python`, **not** a venv. Any new non-stdlib dependency must
|
||||||
non-stdlib dependency must go into system Python's user site-packages:
|
go into system Python's user site-packages:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
/usr/bin/python3 -m pip install --user --break-system-packages -e .
|
/usr/bin/python3 -m pip install --user --break-system-packages -e .
|
||||||
```
|
```
|
||||||
|
|
||||||
Verify against `/usr/bin/python3 -c "import <dep>"`, not the dev venv.
|
Verify against `/usr/bin/python3 -c "import <dep>"`, not the dev venv. Installing only into `.venv`
|
||||||
Installing only into `.venv` caused a 3-day production outage (2026-06-19).
|
caused a 3-day production outage (2026-06-19).
|
||||||
|
|
||||||
Run `install.sh` from a **durable** clone (`~/src/diet-guard`), never a scratch
|
Run `install.sh` from a **durable** clone (`~/src/diet-guard`), never a scratch dir — it does `pip
|
||||||
dir — it does `pip install -e`, so the clone must persist for `git pull` to
|
install -e`, so the clone must persist for `git pull` to reach the running service.
|
||||||
reach the running service.
|
|
||||||
|
|
||||||
## Operational gotchas
|
## Operational gotchas
|
||||||
|
|
||||||
@ -139,14 +143,15 @@ reach the running service.
|
|||||||
`test_budget_history.py`; it syncs as `hist:<YYYY-MM-DD>` fields on the
|
`test_budget_history.py`; it syncs as `hist:<YYYY-MM-DD>` fields on the
|
||||||
existing `budget` record, so devices predating the feature relay them
|
existing `budget` record, so devices predating the feature relay them
|
||||||
untouched.
|
untouched.
|
||||||
- **Biometrics are used once and discarded** — only the computed budget is
|
- **Offline first**: save locally before any network call; store fetched data on disk (`kuchnia_delivery.json`, both devices).
|
||||||
persisted.
|
- **Body data persists and syncs** (profile, weight log, PC workouts) as
|
||||||
|
`body.json`; its tables are informational. [docs/DOCS-body.md](docs/DOCS-body.md).
|
||||||
- **PC and phone share one source of truth for everything**: food log, budget,
|
- **PC and phone share one source of truth for everything**: food log, budget,
|
||||||
budget history, body weight (`w`), curated food bank. If you add a stored
|
budget history, body weight (`w`), Body doc, curated food bank. If you add a stored
|
||||||
field, sync it or comment why it physically cannot be.
|
field, sync it or comment why it physically cannot be.
|
||||||
- **State lives entirely under `~/.local/share/diet_guard/`** — no cross-repo
|
- **State lives entirely under `~/.local/share/diet_guard/`** — no cross-repo
|
||||||
file coupling. Exception: the sync timer touches `kuhyx/syncs` and
|
file coupling. Exceptions: sync (`kuhyx/syncs`, `~/.config/diet_guard/`) and
|
||||||
`~/.config/diet_guard/sync_token`.
|
read-only workout sources (RunnerUp drop, screen-locker: `_activity_sources`).
|
||||||
- **Every device pushes under a persisted per-install uuid**, not a role
|
- **Every device pushes under a persisted per-install uuid**, not a role
|
||||||
constant. `_device.py` / `sync_device_id.dart` (`crdt.nodeId`). The old role
|
constant. `_device.py` / `sync_device_id.dart` (`crdt.nodeId`). The old role
|
||||||
constant survives as the legacy id so `devices/<legacy>/` is skipped as this
|
constant survives as the legacy id so `devices/<legacy>/` is skipped as this
|
||||||
@ -157,16 +162,14 @@ reach the running service.
|
|||||||
|
|
||||||
## The companion app's desktop target is a web build
|
## The companion app's desktop target is a web build
|
||||||
|
|
||||||
`app/` builds for **Android** and **web** only. There is no `app/linux/` —
|
`app/` builds for **Android** and **web** only. There is no `app/linux/` — Flutter's GTK embedder
|
||||||
Flutter's GTK embedder manages ~20fps at 3840x2160 where the same Dart in
|
manages ~20fps at 3840x2160 where the same Dart in Chrome sustains ~144fps
|
||||||
Chrome sustains ~144fps (`~/src/todo/docs/DOCS-desktop-performance-findings.md`). The
|
(`~/src/todo/docs/DOCS-desktop-performance-findings.md`). The desktop app is the web build served by
|
||||||
desktop app is the web build served by `bin/diet_guard_desktop.dart` in a
|
`bin/diet_guard_desktop.dart` in a Chrome `--app` window.
|
||||||
Chrome `--app` window.
|
|
||||||
|
|
||||||
Enforced by `app/test/repo_invariants_test.dart`: no `app/linux/`, `dart:io`
|
Enforced by `app/test/repo_invariants_test.dart`: no `app/linux/`, `dart:io` only in `*_io.dart`
|
||||||
only in `*_io.dart` seams and `lib/desktop/`, port 8732 and the
|
seams and `lib/desktop/`, port 8732 and the `diet-guard-desktop` Chrome profile pinned (IndexedDB is
|
||||||
`diet-guard-desktop` Chrome profile pinned (IndexedDB is keyed by origin, so
|
keyed by origin, so changing either hides the entire local food log).
|
||||||
changing either hides the entire local food log).
|
|
||||||
|
|
||||||
- Branch on `kIsWeb` *before* any `Platform.is…`, which itself throws on web.
|
- Branch on `kIsWeb` *before* any `Platform.is…`, which itself throws on web.
|
||||||
`dart:io` does not fail a web compile — it throws at runtime, so the symptom
|
`dart:io` does not fail a web compile — it throws at runtime, so the symptom
|
||||||
@ -179,18 +182,17 @@ changing either hides the entire local food log).
|
|||||||
|
|
||||||
## The meal schedule
|
## The meal schedule
|
||||||
|
|
||||||
The slot hours are user-configurable: a first meal, a last meal, and how
|
Slots are **minutes of day**: a first meal and a last meal (any `HH:MM`) and how many meals fall
|
||||||
many meals fall between them, evenly divided. Default `(8, 20, 4)` is the
|
between them; interior slots round to the 15-min grid. Default `(480, 1200, 4)` is the old hardcoded
|
||||||
old hardcoded 08/12/16/20. Four load-bearing rules (integer-only
|
08/12/16/20. The load-bearing rules (integer-only arithmetic, the additive `slot`+`slot_min` /
|
||||||
arithmetic, whole-hour slots, the count clamp, the `last + 2h` cutoff), the
|
`f`/`l`/`n`+`fm`/`lm` wire, the count clamp, the `last + 120 min` cutoff, nearest-slot
|
||||||
forward-only history, and the two edit surfaces are documented in
|
satisfaction), the forward-only history, and the two edit surfaces are in
|
||||||
[docs/DOCS-meal-schedule.md](docs/DOCS-meal-schedule.md) — read it before touching
|
[docs/DOCS-meal-schedule.md](docs/DOCS-meal-schedule.md) — read it before touching `_slots.py` /
|
||||||
`_slots.py` / `slot.dart`.
|
`_slot_wire.py` / `slot.dart`.
|
||||||
|
|
||||||
## Averages (`_averages.py` / `average_service.dart`)
|
## Averages (`_averages.py` / `average_service.dart`)
|
||||||
|
|
||||||
Three load-bearing rules; changing any silently changes what "under budget"
|
Three load-bearing rules; changing any silently changes what "under budget" means:
|
||||||
means:
|
|
||||||
|
|
||||||
- **Denominator is logged days, not elapsed days.** An unlogged day is not a
|
- **Denominator is logged days, not elapsed days.** An unlogged day is not a
|
||||||
zero-kcal day.
|
zero-kcal day.
|
||||||
@ -200,10 +202,9 @@ means:
|
|||||||
week" is empty on a Monday, and reports `no logged days yet` rather than a
|
week" is empty on a Monday, and reports `no logged days yet` rather than a
|
||||||
fake average.
|
fake average.
|
||||||
|
|
||||||
Band boundaries reuse `_daystatus.OVER_BUDGET_YELLOW_CEILING` /
|
Band boundaries reuse `_daystatus.OVER_BUDGET_YELLOW_CEILING` / `kOverBudgetYellowCeiling` **by
|
||||||
`kOverBudgetYellowCeiling` **by import, not by copy**. The MCP `get_averages`
|
import, not by copy**. The MCP `get_averages` tool drops `avg_budget` (budget secrecy on the network
|
||||||
tool drops `avg_budget` (budget secrecy on the network only); the CLI, gate and
|
only); the CLI, gate and phone show both.
|
||||||
phone show both.
|
|
||||||
|
|
||||||
## Do NOT
|
## Do NOT
|
||||||
|
|
||||||
@ -217,18 +218,18 @@ phone show both.
|
|||||||
(`2.5.round() == 3`), so a float path silently desyncs the two devices —
|
(`2.5.round() == 3`), so a float path silently desyncs the two devices —
|
||||||
and a slot one device offers while the other does not is a checkpoint that
|
and a slot one device offers while the other does not is a checkpoint that
|
||||||
can never be satisfied, i.e. a permanent lock. Integer `//` and `~/` only.
|
can never be satisfied, i.e. a permanent lock. Integer `//` and `~/` only.
|
||||||
- Don't re-add the meal builder, "repeat last meal", the reward prompt, or
|
- Don't re-add the meal builder, "repeat last meal" or the reward prompt
|
||||||
**meal photos** — all removed deliberately, enforced by
|
(removed deliberately, `app/test/repo_invariants_test.dart`). A meal photo is
|
||||||
`app/test/repo_invariants_test.dart`. Photos also took `image_picker`, the
|
transient input to Claude only (2026-11-17): never stored, on a `FoodEntry`
|
||||||
blob stores, the `/blobs/` route and the `CAMERA` permission; re-adding them
|
or synced; the invariants test asserts no image bytes reach a record.
|
||||||
means syncing image blobs too.
|
|
||||||
- Don't strip the `components` field: nothing writes it, but historical
|
- Don't strip the `components` field: nothing writes it, but historical
|
||||||
composite entries and the food bank read it, and it is part of the sync wire
|
composite entries and the food bank read it, and it is part of the sync wire
|
||||||
format.
|
format.
|
||||||
- Don't let the catering import log unattended (delivered ≠ eaten), don't let
|
- Catering logs itself since 2026-11-17 (kuhy overrode "delivered ≠ eaten":
|
||||||
its Python and Dart halves drift (one shared fixture gates them), and don't
|
"LOG EVEN WITHOUT TAP"): v5 ids `kuchnia:<date>:<dishId>`, undo tombstones.
|
||||||
make the synced password machine-local — the phone could not then fetch.
|
Don't let its Python and Dart halves drift (shared fixtures) or make the
|
||||||
[docs](docs/DOCS-kuchnia-wikinga.md), [phone](docs/DOCS-kuchnia-wikinga-phone.md).
|
synced password machine-local. [docs](docs/DOCS-kuchnia-wikinga.md),
|
||||||
|
[phone](docs/DOCS-kuchnia-wikinga-phone.md).
|
||||||
- Don't add a dependency without the production install-path check above.
|
- Don't add a dependency without the production install-path check above.
|
||||||
- Don't reintroduce a seal/`chattr +i` on the budget file.
|
- Don't reintroduce a seal/`chattr +i` on the budget file.
|
||||||
- Don't re-add a Linux embedder target, and don't change the wrapper's port or
|
- Don't re-add a Linux embedder target, and don't change the wrapper's port or
|
||||||
@ -240,8 +241,7 @@ phone show both.
|
|||||||
## Flutter/Dart AI rules
|
## Flutter/Dart AI rules
|
||||||
|
|
||||||
_Vendored from [flutter/flutter docs/rules/rules.md](https://github.com/flutter/flutter/blob/main/docs/rules/rules.md)
|
_Vendored from [flutter/flutter docs/rules/rules.md](https://github.com/flutter/flutter/blob/main/docs/rules/rules.md)
|
||||||
via `~/.claude/CLAUDE.md` Flutter AI tooling setup. Re-fetch periodically.
|
via `~/.claude/CLAUDE.md`. Re-fetch periodically. Split across five files for the 250-line cap._
|
||||||
Split across five files to stay under the 250-line cap._
|
|
||||||
|
|
||||||
- [Language, style and architecture](docs/DOCS-flutter-rules-language.md)
|
- [Language, style and architecture](docs/DOCS-flutter-rules-language.md)
|
||||||
- [Architecture, lint rules, state and data](docs/DOCS-flutter-rules-state-and-data.md)
|
- [Architecture, lint rules, state and data](docs/DOCS-flutter-rules-state-and-data.md)
|
||||||
|
|||||||
20
DOCS-dopamine-ux.md
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
# diet-guard dopamine-ux: context
|
||||||
|
|
||||||
|
## context you would otherwise rediscover
|
||||||
|
|
||||||
|
- This app has **no `design_system` dependency** — `app/lib/ui/theme.dart` is a
|
||||||
|
hand-transcription of the shared tokens (values are byte-identical, names in
|
||||||
|
comments). Motion tokens from prompt 01 must be **transcribed into that local
|
||||||
|
theme file**, matching the existing convention. Do not add the dependency here;
|
||||||
|
that is a separate, larger refactor.
|
||||||
|
- Capability baseline, verified 2026-08-16: **no audio package, no `assets:`
|
||||||
|
block, no `vibration` package, no VIBRATE permission.** The only existing
|
||||||
|
audio-adjacent thing is the `diet_guard_due_slot` notification channel
|
||||||
|
(`app/lib/services/notification_backend_io.dart` ~:17-18, :52-55) at
|
||||||
|
`Importance.high` with no explicit sound/vibration override — leave it alone.
|
||||||
|
- The app already computes both a **logging streak** and an **adherence streak**
|
||||||
|
(`_daystatus.py:144`/`:153` on the Python side, mirrored in Dart). You are
|
||||||
|
making existing true data feel like something, not inventing a new metric.
|
||||||
|
- diet-guard state lives under XDG (`~/.local/share/diet_guard`), unlike
|
||||||
|
screen-locker's in-repo JSON. Tests isolate it via
|
||||||
|
`~/src/diet-guard/diet_guard/tests/conftest.py:97` `_isolate_state`.
|
||||||
30
DOCS-lock-order.md
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
# Lock order
|
||||||
|
|
||||||
|
When several locks are due at once, gatelock shows the one with the highest
|
||||||
|
rank first. Each lower lock waits, with no window, until every higher lock has
|
||||||
|
been cleared. kuhy fixed this order on 2026-11-21:
|
||||||
|
|
||||||
|
| Order | Lock | gatelock app | Rank | Repo |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| 1 | workout | screen_locker | 200 | screen-locker |
|
||||||
|
| 2 | book | book_guard | 175 | book-guard |
|
||||||
|
| 3 | tutor | tutor_gate | 150 | tutor |
|
||||||
|
| 4 | diet | diet_guard | 130 | diet-guard |
|
||||||
|
| 5 | focus | focus_guard | 128 | focus-guard |
|
||||||
|
| 6 | leetcode | leetcode_guard | 125 | leetcode-guard |
|
||||||
|
|
||||||
|
LeetCode goes last. Each rank is a literal in its own repo, not a
|
||||||
|
`gatelock.RANK_*` constant, so changing one does not need a gatelock release.
|
||||||
|
Every repo keeps a copy of this file, and its tests fail when its own number
|
||||||
|
differs from its row here. Change the rank, this table and the copies in the
|
||||||
|
other repos together.
|
||||||
|
|
||||||
|
Not in the table:
|
||||||
|
|
||||||
|
- The wake alarm (300) outranks everything.
|
||||||
|
- The evening chain (`gatelock.evening_chain`) runs its rungs one at a time,
|
||||||
|
in the order book, tutor, LeetCode. Its book rung locks at 150, which ties
|
||||||
|
the tutor. Ranks only order locks that are due at the same moment.
|
||||||
|
- All of these lock with a global grab and VT switching disabled, so no
|
||||||
|
higher rank is ever a weaker lock. `gatelock/scripts/verify_all_lockers.py`
|
||||||
|
checks this order on a private X server.
|
||||||
11
README.md
@ -46,7 +46,7 @@ The band boundaries are the calendar's own (at or under budget / up to 20%
|
|||||||
over / more than 20% over), so a period and its day cells can never disagree
|
over / more than 20% over), so a period and its day cells can never disagree
|
||||||
about what "over" means.
|
about what "over" means.
|
||||||
|
|
||||||
The timer runs the gate automatically every ~30 minutes; no manual
|
The timer runs the gate automatically every ~15 minutes; no manual
|
||||||
invocation is needed once installed.
|
invocation is needed once installed.
|
||||||
|
|
||||||
## MCP server
|
## MCP server
|
||||||
@ -87,6 +87,15 @@ bash scripts/setup_mcp.sh # create the venv and install diet_guard[mcp]
|
|||||||
Then restart Claude Code in this repo and approve the project MCP server
|
Then restart Claude Code in this repo and approve the project MCP server
|
||||||
(registered in `.mcp.json`).
|
(registered in `.mcp.json`).
|
||||||
|
|
||||||
|
## Error reports
|
||||||
|
|
||||||
|
Every uncaught, thread or Tk callback error, and any freeze of the gate window
|
||||||
|
over 1 s, goes to the shared app-errors spool as app `diet-guard-gate`
|
||||||
|
through `gatelock.error_report` (`diet_guard/_errors.py`, installed by the
|
||||||
|
CLI). The PC's `app-errors` timer turns each one into a ticket on the
|
||||||
|
todoImplementer board (kuhyx/utils `DOCS-app-errors.md`). Nothing shows on
|
||||||
|
screen. The Flutter app reports on its own, as `diet-guard`.
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
@ -39,7 +39,8 @@ android {
|
|||||||
applicationId = "com.kuhy.diet_guard_app"
|
applicationId = "com.kuhy.diet_guard_app"
|
||||||
// You can update the following values to match your application needs.
|
// You can update the following values to match your application needs.
|
||||||
// For more information, see: https://flutter.dev/to/review-gradle-config.
|
// For more information, see: https://flutter.dev/to/review-gradle-config.
|
||||||
minSdk = flutter.minSdkVersion
|
// Health Connect (the `health` plugin) needs API 26.
|
||||||
|
minSdk = maxOf(26, flutter.minSdkVersion)
|
||||||
targetSdk = flutter.targetSdkVersion
|
targetSdk = flutter.targetSdkVersion
|
||||||
versionCode = flutter.versionCode
|
versionCode = flutter.versionCode
|
||||||
versionName = flutter.versionName
|
versionName = flutter.versionName
|
||||||
|
|||||||
@ -1,6 +1,8 @@
|
|||||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
<!-- Sync (github_client.dart) needs raw socket access. -->
|
<!-- Sync (github_client.dart) needs raw socket access. -->
|
||||||
<uses-permission android:name="android.permission.INTERNET"/>
|
<uses-permission android:name="android.permission.INTERNET"/>
|
||||||
|
<!-- HapticFeedback on a successful meal log (log_meal_screen.dart). -->
|
||||||
|
<uses-permission android:name="android.permission.VIBRATE"/>
|
||||||
<!-- Android 13+ requires runtime opt-in to post notifications; requested
|
<!-- Android 13+ requires runtime opt-in to post notifications; requested
|
||||||
at launch via NotificationService.requestPermission(). -->
|
at launch via NotificationService.requestPermission(). -->
|
||||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
|
||||||
@ -13,6 +15,16 @@
|
|||||||
(permission_handler's ignoreBatteryOptimizations) to actually show
|
(permission_handler's ignoreBatteryOptimizations) to actually show
|
||||||
the system dialog instead of silently returning denied. -->
|
the system dialog instead of silently returning denied. -->
|
||||||
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
|
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
|
||||||
|
<!-- Health Connect steps for the Body screen (health_steps.dart). Read
|
||||||
|
only, foreground only: no READ_HEALTH_DATA_IN_BACKGROUND, so the
|
||||||
|
WorkManager isolate never reads Health Connect. -->
|
||||||
|
<uses-permission android:name="android.permission.health.READ_STEPS"/>
|
||||||
|
<!-- Camera for the meal photo sent to Claude (meal_photo_source.dart); the
|
||||||
|
runtime permission is requested before the camera opens. A photo is
|
||||||
|
transient input: it is never stored or synced. Not every device has a
|
||||||
|
camera, and the gallery path works without one. -->
|
||||||
|
<uses-permission android:name="android.permission.CAMERA"/>
|
||||||
|
<uses-feature android:name="android.hardware.camera" android:required="false"/>
|
||||||
<!-- Deliberately NOT requesting SCHEDULE_EXACT_ALARM: the background
|
<!-- Deliberately NOT requesting SCHEDULE_EXACT_ALARM: the background
|
||||||
check is a 15-minute WorkManager periodic task, not exact alarms
|
check is a 15-minute WorkManager periodic task, not exact alarms
|
||||||
(more robust against OEM background-kill; +/-15 min is accepted, see
|
(more robust against OEM background-kill; +/-15 min is accepted, see
|
||||||
@ -20,7 +32,7 @@
|
|||||||
perceived lateness, which trades robustness for precision we don't
|
perceived lateness, which trades robustness for precision we don't
|
||||||
need. -->
|
need. -->
|
||||||
<application
|
<application
|
||||||
android:label="diet_guard_app"
|
android:label="DietGuard"
|
||||||
android:name="${applicationName}"
|
android:name="${applicationName}"
|
||||||
android:icon="@mipmap/ic_launcher">
|
android:icon="@mipmap/ic_launcher">
|
||||||
<activity
|
<activity
|
||||||
@ -44,7 +56,23 @@
|
|||||||
<action android:name="android.intent.action.MAIN"/>
|
<action android:name="android.intent.action.MAIN"/>
|
||||||
<category android:name="android.intent.category.LAUNCHER"/>
|
<category android:name="android.intent.category.LAUNCHER"/>
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
|
<!-- Health Connect (Android 13 and below) opens this to show why
|
||||||
|
the app wants steps; see the `health` plugin README. -->
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE"/>
|
||||||
|
</intent-filter>
|
||||||
</activity>
|
</activity>
|
||||||
|
<!-- Health Connect (Android 14+) links "view permission usage" here. -->
|
||||||
|
<activity-alias
|
||||||
|
android:name="ViewPermissionUsageActivity"
|
||||||
|
android:exported="true"
|
||||||
|
android:targetActivity=".MainActivity"
|
||||||
|
android:permission="android.permission.START_VIEW_PERMISSION_USAGE">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.VIEW_PERMISSION_USAGE"/>
|
||||||
|
<category android:name="android.intent.category.HEALTH_PERMISSIONS"/>
|
||||||
|
</intent-filter>
|
||||||
|
</activity-alias>
|
||||||
<!-- Don't delete the meta-data below.
|
<!-- Don't delete the meta-data below.
|
||||||
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
|
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
|
||||||
<meta-data
|
<meta-data
|
||||||
@ -61,5 +89,10 @@
|
|||||||
<action android:name="android.intent.action.PROCESS_TEXT"/>
|
<action android:name="android.intent.action.PROCESS_TEXT"/>
|
||||||
<data android:mimeType="text/plain"/>
|
<data android:mimeType="text/plain"/>
|
||||||
</intent>
|
</intent>
|
||||||
|
<!-- Lets the `health` plugin see whether Health Connect is installed. -->
|
||||||
|
<package android:name="com.google.android.apps.healthdata"/>
|
||||||
|
<intent>
|
||||||
|
<action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE"/>
|
||||||
|
</intent>
|
||||||
</queries>
|
</queries>
|
||||||
</manifest>
|
</manifest>
|
||||||
|
|||||||
@ -1,5 +1,8 @@
|
|||||||
package com.kuhy.diet_guard_app
|
package com.kuhy.diet_guard_app
|
||||||
|
|
||||||
import io.flutter.embedding.android.FlutterActivity
|
import io.flutter.embedding.android.FlutterFragmentActivity
|
||||||
|
|
||||||
class MainActivity : FlutterActivity()
|
// FlutterFragmentActivity, not FlutterActivity: the `health` plugin requests
|
||||||
|
// Health Connect permissions through registerForActivityResult, which needs a
|
||||||
|
// ComponentActivity (see the plugin README, "Android 14").
|
||||||
|
class MainActivity : FlutterFragmentActivity()
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 5.3 KiB After Width: | Height: | Size: 5.6 KiB |
|
Before Width: | Height: | Size: 5.2 KiB After Width: | Height: | Size: 5.4 KiB |
|
Before Width: | Height: | Size: 3.3 KiB After Width: | Height: | Size: 3.5 KiB |
|
Before Width: | Height: | Size: 3.3 KiB After Width: | Height: | Size: 3.5 KiB |
|
Before Width: | Height: | Size: 6.5 KiB After Width: | Height: | Size: 6.9 KiB |
|
Before Width: | Height: | Size: 6.0 KiB After Width: | Height: | Size: 6.5 KiB |
|
Before Width: | Height: | Size: 9.5 KiB After Width: | Height: | Size: 10 KiB |
|
Before Width: | Height: | Size: 8.3 KiB After Width: | Height: | Size: 8.8 KiB |
|
Before Width: | Height: | Size: 13 KiB After Width: | Height: | Size: 14 KiB |
|
Before Width: | Height: | Size: 11 KiB After Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 1.9 KiB After Width: | Height: | Size: 2.0 KiB |
|
Before Width: | Height: | Size: 1.1 KiB After Width: | Height: | Size: 1.2 KiB |
|
Before Width: | Height: | Size: 2.2 KiB After Width: | Height: | Size: 2.3 KiB |
|
Before Width: | Height: | Size: 3.5 KiB After Width: | Height: | Size: 3.7 KiB |
|
Before Width: | Height: | Size: 4.3 KiB After Width: | Height: | Size: 4.6 KiB |
@ -1,4 +1,7 @@
|
|||||||
org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
|
org.gradle.jvmargs=-Xmx2G -XX:MaxMetaspaceSize=1G -XX:ReservedCodeCacheSize=256m -XX:+UseSerialGC -XX:TieredStopAtLevel=1
|
||||||
|
org.gradle.caching=true
|
||||||
|
org.gradle.parallel=true
|
||||||
|
kotlin.compiler.execution.strategy=in-process
|
||||||
android.useAndroidX=true
|
android.useAndroidX=true
|
||||||
# This newDsl flag was added by the Flutter template
|
# This newDsl flag was added by the Flutter template
|
||||||
android.newDsl=false
|
android.newDsl=false
|
||||||
|
|||||||
@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME
|
|||||||
distributionPath=wrapper/dists
|
distributionPath=wrapper/dists
|
||||||
zipStoreBase=GRADLE_USER_HOME
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
zipStorePath=wrapper/dists
|
zipStorePath=wrapper/dists
|
||||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-all.zip
|
distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.2-all.zip
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 22 KiB After Width: | Height: | Size: 23 KiB |
@ -1,6 +1,6 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
|
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
|
||||||
<rect width="1024" height="1024" fill="#211D1B"/>
|
<rect width="1024" height="1024" fill="#211D1B"/>
|
||||||
<g fill="none" stroke="#B8862E" stroke-width="72" stroke-linecap="round" stroke-linejoin="round" transform="translate(0,-2)">
|
<g fill="none" stroke="#B8862E" stroke-width="66.7417" stroke-linecap="round" stroke-linejoin="round" transform="translate(-40.3384,-42.496) scale(1.07879)">
|
||||||
<path d="M 512 275 L 752 366 L 752 544 C 752 655 646 723 512 753 C 378 723 272 655 272 544 L 272 366 Z"/>
|
<path d="M 512 275 L 752 366 L 752 544 C 752 655 646 723 512 753 C 378 723 272 655 272 544 L 272 366 Z"/>
|
||||||
<g transform="translate(356,362) scale(13)" fill="#B8862E" stroke="none">
|
<g transform="translate(356,362) scale(13)" fill="#B8862E" stroke="none">
|
||||||
<path d="M11 9H9V2H7v7H5V2H3v7c0 2.12 1.66 3.84 3.75 3.97V22h2.5v-9.03C11.34 12.84 13 11.12 13 9V2h-2v7z"/>
|
<path d="M11 9H9V2H7v7H5V2H3v7c0 2.12 1.66 3.84 3.75 3.97V22h2.5v-9.03C11.34 12.84 13 11.12 13 9V2h-2v7z"/>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 656 B After Width: | Height: | Size: 688 B |
|
Before Width: | Height: | Size: 24 KiB After Width: | Height: | Size: 26 KiB |
@ -1,5 +1,5 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
|
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
|
||||||
<g fill="none" stroke="#B8862E" stroke-width="72" stroke-linecap="round" stroke-linejoin="round" transform="translate(0,-2)">
|
<g fill="none" stroke="#B8862E" stroke-width="66.7417" stroke-linecap="round" stroke-linejoin="round" transform="translate(-40.3384,-42.496) scale(1.07879)">
|
||||||
<path d="M 512 275 L 752 366 L 752 544 C 752 655 646 723 512 753 C 378 723 272 655 272 544 L 272 366 Z"/>
|
<path d="M 512 275 L 752 366 L 752 544 C 752 655 646 723 512 753 C 378 723 272 655 272 544 L 272 366 Z"/>
|
||||||
<g transform="translate(356,362) scale(13)" fill="#B8862E" stroke="none">
|
<g transform="translate(356,362) scale(13)" fill="#B8862E" stroke="none">
|
||||||
<path d="M11 9H9V2H7v7H5V2H3v7c0 2.12 1.66 3.84 3.75 3.97V22h2.5v-9.03C11.34 12.84 13 11.12 13 9V2h-2v7z"/>
|
<path d="M11 9H9V2H7v7H5V2H3v7c0 2.12 1.66 3.84 3.75 3.97V22h2.5v-9.03C11.34 12.84 13 11.12 13 9V2h-2v7z"/>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 604 B After Width: | Height: | Size: 636 B |
|
Before Width: | Height: | Size: 20 KiB After Width: | Height: | Size: 21 KiB |
@ -1,5 +1,5 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
|
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
|
||||||
<g fill="none" stroke="#FFFFFF" stroke-width="72" stroke-linecap="round" stroke-linejoin="round" transform="translate(0,-2)">
|
<g fill="none" stroke="#FFFFFF" stroke-width="66.7417" stroke-linecap="round" stroke-linejoin="round" transform="translate(-40.3384,-42.496) scale(1.07879)">
|
||||||
<path d="M 512 275 L 752 366 L 752 544 C 752 655 646 723 512 753 C 378 723 272 655 272 544 L 272 366 Z"/>
|
<path d="M 512 275 L 752 366 L 752 544 C 752 655 646 723 512 753 C 378 723 272 655 272 544 L 272 366 Z"/>
|
||||||
<g transform="translate(356,362) scale(13)" fill="#FFFFFF" stroke="none">
|
<g transform="translate(356,362) scale(13)" fill="#FFFFFF" stroke="none">
|
||||||
<path d="M11 9H9V2H7v7H5V2H3v7c0 2.12 1.66 3.84 3.75 3.97V22h2.5v-9.03C11.34 12.84 13 11.12 13 9V2h-2v7z"/>
|
<path d="M11 9H9V2H7v7H5V2H3v7c0 2.12 1.66 3.84 3.75 3.97V22h2.5v-9.03C11.34 12.84 13 11.12 13 9V2h-2v7z"/>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 604 B After Width: | Height: | Size: 636 B |
BIN
app/assets/sounds/log_confirm.ogg
Normal file
@ -163,6 +163,11 @@ Future<bool> _launchBrowser(String home, int port) async {
|
|||||||
// a browser icon instead of diet_guard's.
|
// a browser icon instead of diet_guard's.
|
||||||
'--class=diet_guard_app',
|
'--class=diet_guard_app',
|
||||||
'--no-first-run',
|
'--no-first-run',
|
||||||
|
// The distro wrapper appends ~/.config/chromium-flags.conf to every launch,
|
||||||
|
// which here carries `--load-extension` for Claude in Chrome. Logged out in
|
||||||
|
// this profile, it opened a claude.ai login tab in a second, normal browser
|
||||||
|
// window on every start. This flag also drops command-line extensions.
|
||||||
|
'--disable-extensions',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
final started = DateTime.now();
|
final started = DateTime.now();
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 2.6 KiB After Width: | Height: | Size: 2.7 KiB |
|
Before Width: | Height: | Size: 380 B After Width: | Height: | Size: 403 B |
|
Before Width: | Height: | Size: 542 B After Width: | Height: | Size: 584 B |
|
Before Width: | Height: | Size: 4.8 KiB After Width: | Height: | Size: 5.1 KiB |
|
Before Width: | Height: | Size: 726 B After Width: | Height: | Size: 794 B |
|
Before Width: | Height: | Size: 1.0 KiB After Width: | Height: | Size: 1.1 KiB |
|
Before Width: | Height: | Size: 9.8 KiB After Width: | Height: | Size: 10 KiB |
|
Before Width: | Height: | Size: 1.4 KiB After Width: | Height: | Size: 1.5 KiB |
@ -77,7 +77,7 @@ install_desktop_entry() {
|
|||||||
cat > "$DESKTOP_DIR/$ICON_NAME.desktop" <<EOF
|
cat > "$DESKTOP_DIR/$ICON_NAME.desktop" <<EOF
|
||||||
[Desktop Entry]
|
[Desktop Entry]
|
||||||
Type=Application
|
Type=Application
|
||||||
Name=diet guard
|
Name=DietGuard
|
||||||
Comment=Diet logging and budget companion
|
Comment=Diet logging and budget companion
|
||||||
Exec=$LAUNCHER
|
Exec=$LAUNCHER
|
||||||
Icon=$ICON_NAME
|
Icon=$ICON_NAME
|
||||||
|
|||||||
35
app/lib/desktop/error_page.dart
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
/// A wordless page for an error the window itself loaded: Chrome would
|
||||||
|
/// otherwise paint its own "This page isn't working" sentences over an
|
||||||
|
/// empty error body. Only the title carries the app's name (OS-level label).
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
/// HTML page with only an icon — no words painted by the browser.
|
||||||
|
const String errorIconPage =
|
||||||
|
'<!doctype html><html><head><meta charset="utf-8"> '
|
||||||
|
'<title>Diet Guard</title> '
|
||||||
|
'<style>html,body{margin:0;height:100%; '
|
||||||
|
'background:#211D1B;display:flex;align-items:center; '
|
||||||
|
'justify-content:center}</style></head><body> '
|
||||||
|
'<svg width="96" height="96" viewBox="0 0 24 24" fill="none" '
|
||||||
|
'stroke="#A39892" stroke-width="2" stroke-linecap="round" '
|
||||||
|
'aria-hidden="true"><circle cx="12" cy="12" r="9"/> '
|
||||||
|
'<line x1="5.6" y1="18.4" x2="18.4" y2="5.6"/></svg></body></html>';
|
||||||
|
|
||||||
|
/// Whether [request] is the window loading a page, not the app's fetch().
|
||||||
|
bool isNavigation(HttpRequest request) =>
|
||||||
|
request.headers.value('sec-fetch-mode') == 'navigate';
|
||||||
|
|
||||||
|
/// Replaces an error answer to a page load with [errorIconPage]. Does
|
||||||
|
/// nothing for fetch() calls, successes, or a response already written.
|
||||||
|
void paintErrorIcon(HttpRequest request) {
|
||||||
|
final response = request.response;
|
||||||
|
if (!isNavigation(request) || response.statusCode < 400) return;
|
||||||
|
try {
|
||||||
|
response.headers.contentType = ContentType.html;
|
||||||
|
response.write(errorIconPage);
|
||||||
|
} on Exception {
|
||||||
|
return; // body already sent: leave it alone
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -19,6 +19,7 @@ library;
|
|||||||
import 'dart:convert';
|
import 'dart:convert';
|
||||||
import 'dart:io';
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/desktop/error_page.dart' show isNavigation;
|
||||||
import 'package:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
|
|
||||||
/// GitHub's REST API base, which [GitHubProxy] fronts.
|
/// GitHub's REST API base, which [GitHubProxy] fronts.
|
||||||
@ -177,8 +178,13 @@ class GitHubProxy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void _passThrough(HttpRequest request, http.Response response) {
|
void _passThrough(HttpRequest request, http.Response response) {
|
||||||
|
request.response.statusCode = response.statusCode;
|
||||||
|
if (isNavigation(request)) {
|
||||||
|
// Top-level navigation (window load) must not paint error JSON; the app's
|
||||||
|
// own fetch() calls never send 'navigate', so they still get the body.
|
||||||
|
return;
|
||||||
|
}
|
||||||
request.response
|
request.response
|
||||||
..statusCode = response.statusCode
|
|
||||||
..headers.contentType = ContentType.json
|
..headers.contentType = ContentType.json
|
||||||
..add(response.bodyBytes);
|
..add(response.bodyBytes);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -24,6 +24,7 @@ import 'dart:io';
|
|||||||
import 'package:crdt_sync/crdt_sync.dart';
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
|
||||||
import 'package:diet_guard_app/desktop/content_types.dart' as content_types;
|
import 'package:diet_guard_app/desktop/content_types.dart' as content_types;
|
||||||
|
import 'package:diet_guard_app/desktop/error_page.dart';
|
||||||
import 'package:diet_guard_app/desktop/github_proxy.dart';
|
import 'package:diet_guard_app/desktop/github_proxy.dart';
|
||||||
import 'package:diet_guard_app/services/desktop_wrapper.dart';
|
import 'package:diet_guard_app/services/desktop_wrapper.dart';
|
||||||
import 'package:path/path.dart' as p;
|
import 'package:path/path.dart' as p;
|
||||||
@ -91,6 +92,7 @@ class WrapperServer {
|
|||||||
} on Exception {
|
} on Exception {
|
||||||
request.response.statusCode = HttpStatus.internalServerError;
|
request.response.statusCode = HttpStatus.internalServerError;
|
||||||
}
|
}
|
||||||
|
paintErrorIcon(request);
|
||||||
await request.response.close();
|
await request.response.close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -3,12 +3,21 @@
|
|||||||
library;
|
library;
|
||||||
|
|
||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart'
|
||||||
|
show AppErrors, AppErrorsConfig, AppErrorsRouteObserver, installAppErrors;
|
||||||
import 'package:diet_guard_app/screens/log_meal_screen.dart';
|
import 'package:diet_guard_app/screens/log_meal_screen.dart';
|
||||||
import 'package:diet_guard_app/services/app_settings_service.dart';
|
import 'package:diet_guard_app/services/app_settings_service.dart';
|
||||||
import 'package:diet_guard_app/services/background_tasks.dart';
|
import 'package:diet_guard_app/services/background_tasks.dart';
|
||||||
|
import 'package:diet_guard_app/services/body_service.dart';
|
||||||
import 'package:diet_guard_app/services/budget_history_service.dart';
|
import 'package:diet_guard_app/services/budget_history_service.dart';
|
||||||
|
import 'package:diet_guard_app/services/claude_relay_client.dart';
|
||||||
|
import 'package:diet_guard_app/services/claude_relay_firebase.dart';
|
||||||
|
import 'package:diet_guard_app/services/document_store_factory.dart';
|
||||||
|
import 'package:diet_guard_app/services/firebase_client.dart' show openFirebase;
|
||||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||||
import 'package:diet_guard_app/services/frame_stats.dart';
|
import 'package:diet_guard_app/services/frame_stats.dart';
|
||||||
|
import 'package:diet_guard_app/services/kuchnia_autolog.dart';
|
||||||
import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
|
import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
|
||||||
import 'package:diet_guard_app/services/kuchnia_queue.dart';
|
import 'package:diet_guard_app/services/kuchnia_queue.dart';
|
||||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
@ -16,20 +25,43 @@ import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
|||||||
import 'package:diet_guard_app/services/notification_service.dart';
|
import 'package:diet_guard_app/services/notification_service.dart';
|
||||||
import 'package:diet_guard_app/services/sync_device_id.dart';
|
import 'package:diet_guard_app/services/sync_device_id.dart';
|
||||||
import 'package:diet_guard_app/ui/theme.dart';
|
import 'package:diet_guard_app/ui/theme.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
Future<void> main() async {
|
Future<void> main() async {
|
||||||
WidgetsFlutterBinding.ensureInitialized();
|
WidgetsFlutterBinding.ensureInitialized();
|
||||||
|
// Every error and every wait over 1 s goes to the PC's app-errors ingest,
|
||||||
|
// which files a board ticket (kuhyx/utils DOCS-app-errors.md). The release
|
||||||
|
// build passes the versionCode and name as dart-defines (release-apk.yml).
|
||||||
|
final errors = await installAppErrors(
|
||||||
|
const AppErrorsConfig(
|
||||||
|
app: 'diet-guard',
|
||||||
|
repo: 'kuhyx/diet-guard',
|
||||||
|
package: 'diet_guard_app',
|
||||||
|
// 0 unless the release build passes --dart-define=APP_BUILD.
|
||||||
|
// ignore: avoid_redundant_argument_values
|
||||||
|
build: int.fromEnvironment('APP_BUILD'),
|
||||||
|
version: String.fromEnvironment('APP_VERSION'),
|
||||||
|
),
|
||||||
|
);
|
||||||
// Before anything that stamps an Hlc or syncs: until this resolves, the
|
// Before anything that stamps an Hlc or syncs: until this resolves, the
|
||||||
// device id falls back to the pre-migration role constant.
|
// device id falls back to the pre-migration role constant.
|
||||||
await initSyncDeviceId();
|
final deviceId = await initSyncDeviceId();
|
||||||
|
errors.connect(
|
||||||
|
sink: () async => (await openFirebase())?.patchValues,
|
||||||
|
deviceId: () async => deviceId,
|
||||||
|
);
|
||||||
await LogStorageService.init();
|
await LogStorageService.init();
|
||||||
await AppSettingsService.init();
|
await AppSettingsService.init();
|
||||||
await BudgetHistoryService.init();
|
await BudgetHistoryService.init();
|
||||||
await MealScheduleService.init();
|
await MealScheduleService.init();
|
||||||
await FoodBankService.init();
|
await FoodBankService.init();
|
||||||
await KuchniaCredentialService.init();
|
await KuchniaCredentialService.init();
|
||||||
|
await BodyService.init();
|
||||||
await KuchniaQueueService.init();
|
await KuchniaQueueService.init();
|
||||||
|
// Offline first: the day's catering dishes survive a restart.
|
||||||
|
KuchniaAutoLog.instance = KuchniaAutoLog(store: await openDocumentStore());
|
||||||
|
// The sparkle button's transport; until this line it fails closed.
|
||||||
|
claudeRelay = RtdbClaudeRelay.firebase();
|
||||||
final notifications = await NotificationService.init();
|
final notifications = await NotificationService.init();
|
||||||
// Deliberately *not* awaited before the first frame: the browser's
|
// Deliberately *not* awaited before the first frame: the browser's
|
||||||
// `Notification.requestPermission()` does not complete until the user
|
// `Notification.requestPermission()` does not complete until the user
|
||||||
@ -49,19 +81,25 @@ Future<void> main() async {
|
|||||||
// coverage:ignore-start
|
// coverage:ignore-start
|
||||||
if (frameStatsEnabled) startFrameStats();
|
if (frameStatsEnabled) startFrameStats();
|
||||||
// coverage:ignore-end
|
// coverage:ignore-end
|
||||||
runApp(const DietGuardApp());
|
runApp(DietGuardApp(errors: errors));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Root widget for the Diet Guard companion app.
|
/// Root widget for the Diet Guard companion app.
|
||||||
class DietGuardApp extends StatelessWidget {
|
class DietGuardApp extends StatelessWidget {
|
||||||
/// Creates the [DietGuardApp] root widget.
|
/// Creates the [DietGuardApp] root widget.
|
||||||
const DietGuardApp({super.key});
|
const DietGuardApp({this.errors, super.key});
|
||||||
|
|
||||||
|
/// App-wide error reporting; null in widget tests.
|
||||||
|
final AppErrors? errors;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return MaterialApp(
|
return MaterialApp(
|
||||||
title: 'Diet Guard',
|
title: 'Diet Guard',
|
||||||
theme: buildAppTheme(),
|
theme: buildAppTheme(),
|
||||||
|
navigatorObservers: [
|
||||||
|
if (errors case final errors?) AppErrorsRouteObserver(errors),
|
||||||
|
],
|
||||||
home: const LogMealScreen(),
|
home: const LogMealScreen(),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
142
app/lib/models/body_document.dart
Normal file
@ -0,0 +1,142 @@
|
|||||||
|
/// The synced Body document: profile, per-day weights, published workouts.
|
||||||
|
///
|
||||||
|
/// Same JSON shape as `~/.local/share/diet_guard/body.json` on the PC (see
|
||||||
|
/// `docs/DOCS-body.md`). Every field carries its own edit stamp `t`, which is
|
||||||
|
/// what the sync merge derives its clocks from. Parsing is tolerant: a
|
||||||
|
/// malformed part is dropped, never raised, so one bad field from a peer
|
||||||
|
/// cannot take out the rest.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/models/body_entries.dart';
|
||||||
|
|
||||||
|
export 'package:diet_guard_app/models/body_entries.dart';
|
||||||
|
|
||||||
|
/// Profile field names.
|
||||||
|
const String profileBirth = 'birth';
|
||||||
|
|
||||||
|
/// Profile height field.
|
||||||
|
const String profileHeight = 'height_cm';
|
||||||
|
|
||||||
|
/// Profile sex field (`m` / `f`).
|
||||||
|
const String profileSex = 'sex';
|
||||||
|
|
||||||
|
/// The whole document.
|
||||||
|
class BodyDocument {
|
||||||
|
/// Creates a document.
|
||||||
|
const BodyDocument({
|
||||||
|
this.profile = const {},
|
||||||
|
this.weights = const {},
|
||||||
|
this.bodyFat = const {},
|
||||||
|
this.steps = const {},
|
||||||
|
this.activity,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Parses the local document JSON (already decoded).
|
||||||
|
factory BodyDocument.fromJson(Object? raw) {
|
||||||
|
if (raw is! Map) return const BodyDocument();
|
||||||
|
final profile = <String, Stamped>{};
|
||||||
|
final rawProfile = raw['profile'];
|
||||||
|
// Every stamped field is kept, known or not: a field a newer peer added
|
||||||
|
// (the table prefs were one) must survive this device's re-push.
|
||||||
|
if (rawProfile is Map) {
|
||||||
|
rawProfile.forEach((name, field) {
|
||||||
|
if (name is String && field is Map && field['t'] is String) {
|
||||||
|
profile[name] = Stamped(field['v'], field['t'] as String);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
final weights = <String, WeightEntry>{};
|
||||||
|
final rawWeights = raw['weights'];
|
||||||
|
if (rawWeights is Map) {
|
||||||
|
rawWeights.forEach((day, value) {
|
||||||
|
final entry = parseWeightValue(value, value is Map ? value['t'] : null);
|
||||||
|
if (isDateKey(day) && entry != null) weights[day as String] = entry;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
final bodyFat = <String, BodyFatEntry>{};
|
||||||
|
final rawFat = raw['bodyfat'];
|
||||||
|
if (rawFat is Map) {
|
||||||
|
rawFat.forEach((day, value) {
|
||||||
|
final t = value is Map ? value['t'] : null;
|
||||||
|
final entry = parseBodyFatValue(value, t);
|
||||||
|
if (isDateKey(day) && entry != null) bodyFat[day as String] = entry;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
final steps = <String, StepsEntry>{};
|
||||||
|
final rawSteps = raw['steps'];
|
||||||
|
if (rawSteps is Map) {
|
||||||
|
rawSteps.forEach((day, value) {
|
||||||
|
final t = value is Map ? value['t'] : null;
|
||||||
|
final entry = parseStepsValue(value, t);
|
||||||
|
if (isDateKey(day) && entry != null) steps[day as String] = entry;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
final rawActivity = raw['activity'];
|
||||||
|
ActivityData? activity;
|
||||||
|
if (rawActivity is Map &&
|
||||||
|
rawActivity['sessions'] is List &&
|
||||||
|
rawActivity['t'] is String) {
|
||||||
|
activity = ActivityData(
|
||||||
|
sessions: List<Object?>.from(rawActivity['sessions'] as List),
|
||||||
|
t: rawActivity['t'] as String,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return BodyDocument(
|
||||||
|
profile: profile,
|
||||||
|
weights: weights,
|
||||||
|
bodyFat: bodyFat,
|
||||||
|
steps: steps,
|
||||||
|
activity: activity,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Profile fields by name.
|
||||||
|
final Map<String, Stamped> profile;
|
||||||
|
|
||||||
|
/// Weights by `YYYY-MM-DD`.
|
||||||
|
final Map<String, WeightEntry> weights;
|
||||||
|
|
||||||
|
/// Body fat readings by `YYYY-MM-DD`.
|
||||||
|
final Map<String, BodyFatEntry> bodyFat;
|
||||||
|
|
||||||
|
/// Steps outside workouts by `YYYY-MM-DD` (written by the phone).
|
||||||
|
final Map<String, StepsEntry> steps;
|
||||||
|
|
||||||
|
/// Workouts published by the PC, or null when none ever were.
|
||||||
|
final ActivityData? activity;
|
||||||
|
|
||||||
|
/// Returns a copy with the given parts replaced.
|
||||||
|
BodyDocument copyWith({
|
||||||
|
Map<String, Stamped>? profile,
|
||||||
|
Map<String, WeightEntry>? weights,
|
||||||
|
Map<String, BodyFatEntry>? bodyFat,
|
||||||
|
Map<String, StepsEntry>? steps,
|
||||||
|
ActivityData? activity,
|
||||||
|
}) => BodyDocument(
|
||||||
|
profile: profile ?? this.profile,
|
||||||
|
weights: weights ?? this.weights,
|
||||||
|
bodyFat: bodyFat ?? this.bodyFat,
|
||||||
|
steps: steps ?? this.steps,
|
||||||
|
activity: activity ?? this.activity,
|
||||||
|
);
|
||||||
|
|
||||||
|
/// JSON form of the local document.
|
||||||
|
Map<String, Object?> toJson() => {
|
||||||
|
'v': 1,
|
||||||
|
'profile': {
|
||||||
|
for (final entry in profile.entries)
|
||||||
|
entry.key: {'v': entry.value.value, 't': entry.value.t},
|
||||||
|
},
|
||||||
|
'weights': {
|
||||||
|
for (final entry in weights.entries) entry.key: entry.value.toJson(),
|
||||||
|
},
|
||||||
|
'bodyfat': {
|
||||||
|
for (final entry in bodyFat.entries) entry.key: entry.value.toJson(),
|
||||||
|
},
|
||||||
|
'steps': {
|
||||||
|
for (final entry in steps.entries) entry.key: entry.value.toJson(),
|
||||||
|
},
|
||||||
|
if (activity != null)
|
||||||
|
'activity': {'sessions': activity!.sessions, 't': activity!.t},
|
||||||
|
};
|
||||||
|
}
|
||||||
132
app/lib/models/body_entries.dart
Normal file
@ -0,0 +1,132 @@
|
|||||||
|
/// The Body document's parts: stamped values, dated entries, parsers.
|
||||||
|
///
|
||||||
|
/// Split out of `body_document.dart` for the 250-line cap; that file
|
||||||
|
/// re-exports this one, so importers see no change. Parsing is tolerant: a
|
||||||
|
/// malformed part is dropped (null), never raised.
|
||||||
|
library;
|
||||||
|
|
||||||
|
/// A value and the ISO time it was last edited.
|
||||||
|
class Stamped {
|
||||||
|
/// Creates a stamped value.
|
||||||
|
const Stamped(this.value, this.t);
|
||||||
|
|
||||||
|
/// The value.
|
||||||
|
final Object? value;
|
||||||
|
|
||||||
|
/// ISO-8601 edit time.
|
||||||
|
final String t;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One day's weight. [kg] null is a tombstone (a deleted day).
|
||||||
|
class WeightEntry {
|
||||||
|
/// Creates an entry.
|
||||||
|
const WeightEntry({required this.kg, required this.src, required this.t});
|
||||||
|
|
||||||
|
/// Kilograms, or null when deleted.
|
||||||
|
final double? kg;
|
||||||
|
|
||||||
|
/// `phone`, `manual` or `init`.
|
||||||
|
final String src;
|
||||||
|
|
||||||
|
/// ISO-8601 edit time.
|
||||||
|
final String t;
|
||||||
|
|
||||||
|
/// JSON form of the local document.
|
||||||
|
Map<String, Object?> toJson() => {'kg': kg, 'src': src, 't': t};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One day's body fat %. [pct] null is a tombstone (a deleted day).
|
||||||
|
class BodyFatEntry {
|
||||||
|
/// Creates an entry.
|
||||||
|
const BodyFatEntry({required this.pct, required this.t});
|
||||||
|
|
||||||
|
/// Percent, or null when deleted.
|
||||||
|
final double? pct;
|
||||||
|
|
||||||
|
/// ISO-8601 edit time.
|
||||||
|
final String t;
|
||||||
|
|
||||||
|
/// JSON form of the local document.
|
||||||
|
Map<String, Object?> toJson() => {'pct': pct, 't': t};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One day's steps outside workouts, as the phone read them.
|
||||||
|
class StepsEntry {
|
||||||
|
/// Creates an entry.
|
||||||
|
const StepsEntry({required this.n, required this.t});
|
||||||
|
|
||||||
|
/// Step count.
|
||||||
|
final int n;
|
||||||
|
|
||||||
|
/// ISO-8601 edit time.
|
||||||
|
final String t;
|
||||||
|
|
||||||
|
/// JSON form of the local document.
|
||||||
|
Map<String, Object?> toJson() => {'n': n, 't': t};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Workouts published by the PC.
|
||||||
|
class ActivityData {
|
||||||
|
/// Creates the published activity.
|
||||||
|
const ActivityData({required this.sessions, required this.t});
|
||||||
|
|
||||||
|
/// Raw session objects, as on the wire.
|
||||||
|
final List<Object?> sessions;
|
||||||
|
|
||||||
|
/// ISO-8601 time the PC last changed them.
|
||||||
|
final String t;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parses an ISO stamp to epoch milliseconds; unparsable -> 0 (the epoch).
|
||||||
|
int stampMillis(String t) => DateTime.tryParse(t)?.millisecondsSinceEpoch ?? 0;
|
||||||
|
|
||||||
|
/// Whether [raw] is a usable weight in kilograms.
|
||||||
|
bool plausibleKg(Object? raw) => raw is num && raw >= 20 && raw <= 400;
|
||||||
|
|
||||||
|
/// Body fat below/above this (%) is a typo, not a measurement.
|
||||||
|
const double minBodyFat = 3;
|
||||||
|
|
||||||
|
/// Upper bound of a plausible body fat %.
|
||||||
|
const double maxBodyFat = 70;
|
||||||
|
|
||||||
|
/// Whether [raw] is a usable body fat %.
|
||||||
|
bool plausibleBodyFat(Object? raw) =>
|
||||||
|
raw is num && raw >= minBodyFat && raw <= maxBodyFat;
|
||||||
|
|
||||||
|
final RegExp _dateKey = RegExp(r'^\d{4}-\d{2}-\d{2}$');
|
||||||
|
|
||||||
|
/// Whether [raw] is a `YYYY-MM-DD` date key.
|
||||||
|
bool isDateKey(Object? raw) => raw is String && _dateKey.hasMatch(raw);
|
||||||
|
|
||||||
|
/// Parses a weight value `{kg, src}` stamped [t], or null when malformed.
|
||||||
|
///
|
||||||
|
/// `kg` must be null (a tombstone) or a plausible number.
|
||||||
|
WeightEntry? parseWeightValue(Object? value, Object? t) {
|
||||||
|
if (value is! Map || t is! String) return null;
|
||||||
|
final kg = value['kg'];
|
||||||
|
if (kg != null && !plausibleKg(kg)) return null;
|
||||||
|
final src = value['src'];
|
||||||
|
return WeightEntry(
|
||||||
|
kg: (kg as num?)?.toDouble(),
|
||||||
|
src: src is String ? src : 'manual',
|
||||||
|
t: t,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parses a body-fat value `{pct}` stamped [t], or null when malformed.
|
||||||
|
///
|
||||||
|
/// `pct` must be null (a tombstone) or a plausible number.
|
||||||
|
BodyFatEntry? parseBodyFatValue(Object? value, Object? t) {
|
||||||
|
if (value is! Map || t is! String) return null;
|
||||||
|
final pct = value['pct'];
|
||||||
|
if (pct != null && !plausibleBodyFat(pct)) return null;
|
||||||
|
return BodyFatEntry(pct: (pct as num?)?.toDouble(), t: t);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parses a steps value `{n}` stamped [t], or null when malformed.
|
||||||
|
StepsEntry? parseStepsValue(Object? value, Object? t) {
|
||||||
|
if (value is! Map || t is! String) return null;
|
||||||
|
final n = value['n'];
|
||||||
|
if (n is! num || n < 0) return null;
|
||||||
|
return StepsEntry(n: n.toInt(), t: t);
|
||||||
|
}
|
||||||
@ -2,6 +2,8 @@
|
|||||||
library;
|
library;
|
||||||
|
|
||||||
import 'package:diet_guard_app/models/meal_component.dart';
|
import 'package:diet_guard_app/models/meal_component.dart';
|
||||||
|
import 'package:diet_guard_app/models/meal_schedule.dart';
|
||||||
|
import 'package:diet_guard_app/models/slot.dart';
|
||||||
|
|
||||||
/// One logged meal, as stored in `food_log.json` under its date key.
|
/// One logged meal, as stored in `food_log.json` under its date key.
|
||||||
///
|
///
|
||||||
@ -20,7 +22,7 @@ class FoodEntry {
|
|||||||
required this.fatG,
|
required this.fatG,
|
||||||
required this.source,
|
required this.source,
|
||||||
this.id,
|
this.id,
|
||||||
this.slot,
|
this.slotMinute,
|
||||||
this.hmac,
|
this.hmac,
|
||||||
this.components,
|
this.components,
|
||||||
this.deleted = false,
|
this.deleted = false,
|
||||||
@ -40,7 +42,7 @@ class FoodEntry {
|
|||||||
carbsG: (json['carbs_g'] as num?)?.toDouble() ?? 0,
|
carbsG: (json['carbs_g'] as num?)?.toDouble() ?? 0,
|
||||||
fatG: (json['fat_g'] as num?)?.toDouble() ?? 0,
|
fatG: (json['fat_g'] as num?)?.toDouble() ?? 0,
|
||||||
source: json['source'] as String? ?? 'manual',
|
source: json['source'] as String? ?? 'manual',
|
||||||
slot: json['slot'] as int?,
|
slotMinute: entrySlotMinute(json),
|
||||||
hmac: json['hmac'] as String?,
|
hmac: json['hmac'] as String?,
|
||||||
components: (json['components'] as List?)
|
components: (json['components'] as List?)
|
||||||
?.cast<Map<String, dynamic>>()
|
?.cast<Map<String, dynamic>>()
|
||||||
@ -79,16 +81,26 @@ class FoodEntry {
|
|||||||
/// Provenance label (e.g. `"manual"`, `"food bank"`, `"meal"`).
|
/// Provenance label (e.g. `"manual"`, `"food bank"`, `"meal"`).
|
||||||
final String source;
|
final String source;
|
||||||
|
|
||||||
/// The meal-slot hour this entry satisfies (8/12/16/20), or null for a
|
/// The meal-slot minute of day this entry was logged against (480 for
|
||||||
/// snack that counts toward calories but satisfies no slot.
|
/// 08:00, 435 for 07:15), or null for a snack that satisfies no slot.
|
||||||
|
///
|
||||||
|
/// A *recorded* minute, not a live checkpoint: which slot it satisfies is
|
||||||
|
/// decided at read time by `satisfiedSlots`, so an entry written under an
|
||||||
|
/// older schedule still counts after the schedule moves.
|
||||||
|
///
|
||||||
|
/// Read through `entrySlotMinute` (`slot_min` wins, else `slot` x 60) and
|
||||||
|
/// written back through `slotFields`, so a PC entry carrying `slot_min`
|
||||||
|
/// survives a round trip through this device. Keeping only the hour would
|
||||||
|
/// make every edit or tombstone republish a stripped copy, and the merge
|
||||||
|
/// would spread that lossy copy back to the PC.
|
||||||
///
|
///
|
||||||
/// Nothing writes null any more -- the "Snack" chip was removed on
|
/// Nothing writes null any more -- the "Snack" chip was removed on
|
||||||
/// 2026-08-14 and every remaining writer resolves a concrete hour through
|
/// 2026-08-14 and every remaining writer resolves a concrete slot through
|
||||||
/// `slotForLog`/`slot_for_log` -- but entries already on disk and arriving
|
/// `slotForLog`/`slot_for_log` -- but entries already on disk and arriving
|
||||||
/// over sync still carry no `slot` key, so the null case and every
|
/// over sync still carry no `slot` key, so the null case and every
|
||||||
/// `slot != null` filter built on it are load-bearing. Dropping them would
|
/// `slot != null` filter built on it are load-bearing. Dropping them would
|
||||||
/// make those historical entries retroactively satisfy meal slots.
|
/// make those historical entries retroactively satisfy meal slots.
|
||||||
final int? slot;
|
final int? slotMinute;
|
||||||
|
|
||||||
/// HMAC signature, present on entries that have passed through the PC's
|
/// HMAC signature, present on entries that have passed through the PC's
|
||||||
/// signing step. Never computed on the phone -- it never holds the key.
|
/// signing step. Never computed on the phone -- it never holds the key.
|
||||||
@ -122,7 +134,7 @@ class FoodEntry {
|
|||||||
'carbs_g': carbsG,
|
'carbs_g': carbsG,
|
||||||
'fat_g': fatG,
|
'fat_g': fatG,
|
||||||
'source': source,
|
'source': source,
|
||||||
if (slot != null) 'slot': slot,
|
..._slotJson(slotMinute),
|
||||||
if (components != null)
|
if (components != null)
|
||||||
'components': components!.map((c) => c.toJson()).toList(),
|
'components': components!.map((c) => c.toJson()).toList(),
|
||||||
if (deleted) 'deleted': true,
|
if (deleted) 'deleted': true,
|
||||||
@ -139,9 +151,26 @@ class FoodEntry {
|
|||||||
carbsG: carbsG,
|
carbsG: carbsG,
|
||||||
fatG: fatG,
|
fatG: fatG,
|
||||||
source: source,
|
source: source,
|
||||||
slot: slot,
|
slotMinute: slotMinute,
|
||||||
hmac: hmac,
|
hmac: hmac,
|
||||||
components: components,
|
components: components,
|
||||||
deleted: true,
|
deleted: true,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns the wire fields for [minute], total over every value it can hold.
|
||||||
|
///
|
||||||
|
/// [slotFields] throws outside the day, but [entrySlotMinute] does not
|
||||||
|
/// range-check what a peer sent. A single `slot: 24` arriving over sync would
|
||||||
|
/// otherwise make every later `writeLog` throw -- one bad entry blocking all
|
||||||
|
/// logging. Such a value is echoed back unrepaired, by the same whole-hour
|
||||||
|
/// rule (so a legacy `slot: 24` stays byte-identical), with `~/` only on a
|
||||||
|
/// non-negative operand -- a negative value travels as `slot_min` alone.
|
||||||
|
Map<String, int> _slotJson(int? minute) {
|
||||||
|
if (minute == null) return const {};
|
||||||
|
if (minute >= 0 && minute < kMinutesPerDay) return slotFields(minute);
|
||||||
|
return {
|
||||||
|
if (minute >= 0) 'slot': minute ~/ 60,
|
||||||
|
if (minute < 0 || minute % 60 != 0) 'slot_min': minute,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|||||||
@ -20,8 +20,35 @@ class KuchniaDish {
|
|||||||
required this.grams,
|
required this.grams,
|
||||||
required this.priority,
|
required this.priority,
|
||||||
required this.slotLabel,
|
required this.slotLabel,
|
||||||
|
this.dishId = '',
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/// Rebuilds a dish stored by [toJson]; throws on a malformed record.
|
||||||
|
factory KuchniaDish.fromJson(Map<String, Object?> json) => KuchniaDish(
|
||||||
|
name: json['name']! as String,
|
||||||
|
kcal: (json['kcal']! as num).toDouble(),
|
||||||
|
proteinG: (json['protein_g']! as num).toDouble(),
|
||||||
|
carbsG: (json['carbs_g']! as num).toDouble(),
|
||||||
|
fatG: (json['fat_g']! as num).toDouble(),
|
||||||
|
grams: (json['grams']! as num).toDouble(),
|
||||||
|
priority: json['priority']! as int,
|
||||||
|
slotLabel: json['slot_label']! as String,
|
||||||
|
dishId: json['dish_id'] as String? ?? '',
|
||||||
|
);
|
||||||
|
|
||||||
|
/// The stored form; the keys follow the PC's `kuchnia_delivery.json`.
|
||||||
|
Map<String, Object?> toJson() => {
|
||||||
|
'name': name,
|
||||||
|
'kcal': kcal,
|
||||||
|
'protein_g': proteinG,
|
||||||
|
'carbs_g': carbsG,
|
||||||
|
'fat_g': fatG,
|
||||||
|
'grams': grams,
|
||||||
|
'priority': priority,
|
||||||
|
'slot_label': slotLabel,
|
||||||
|
'dish_id': dishId,
|
||||||
|
};
|
||||||
|
|
||||||
/// The dish itself (`menuMealName`), e.g. "Kaszotto grzybowe...".
|
/// The dish itself (`menuMealName`), e.g. "Kaszotto grzybowe...".
|
||||||
///
|
///
|
||||||
/// Not `mealName`, which is the slot label ("Kolacja") and would collapse
|
/// Not `mealName`, which is the slot label ("Kolacja") and would collapse
|
||||||
@ -52,6 +79,17 @@ class KuchniaDish {
|
|||||||
/// The caterer's slot label ("Śniadanie", "Obiad", ...), for display only.
|
/// The caterer's slot label ("Śniadanie", "Obiad", ...), for display only.
|
||||||
final String slotLabel;
|
final String slotLabel;
|
||||||
|
|
||||||
|
/// The panel's own id for this meal (`deliveryMealId`), as a string, or ''
|
||||||
|
/// when the payload carried none.
|
||||||
|
///
|
||||||
|
/// Never written to the bank record or the log: it only feeds [autologKey].
|
||||||
|
final String dishId;
|
||||||
|
|
||||||
|
/// The dish half of the auto-log entry id: [dishId], else [bankKey].
|
||||||
|
///
|
||||||
|
/// Mirrors the fixture `tests/fixtures/kuchnia_autolog_ids.json`.
|
||||||
|
String get autologKey => dishId.isNotEmpty ? dishId : bankKey;
|
||||||
|
|
||||||
/// The curated-bank record for this dish.
|
/// The curated-bank record for this dish.
|
||||||
///
|
///
|
||||||
/// Mirrors `_kuchnia_import.dish_to_record`. `count` is 0: the bank's count
|
/// Mirrors `_kuchnia_import.dish_to_record`. `count` is 0: the bank's count
|
||||||
|
|||||||
@ -1,9 +1,15 @@
|
|||||||
/// The user's eating window and meal count, and the slot hours they imply.
|
/// The user's eating window and meal count, and the slot minutes they imply.
|
||||||
///
|
///
|
||||||
/// A schedule is three numbers -- the first meal hour, the last meal hour, and
|
/// A schedule is three numbers -- the first meal's minute of day, the last
|
||||||
/// how many meals fall between them inclusive -- from which the intermediate
|
/// meal's minute of day, and how many meals fall between them inclusive --
|
||||||
/// checkpoints are derived by even division. `MealSchedule(8, 20, 5)` yields
|
/// from which the intermediate checkpoints are derived by even division and
|
||||||
/// `[8, 11, 14, 17, 20]`.
|
/// rounded to the 15-minute grid. `MealSchedule(firstMinute: 480,
|
||||||
|
/// lastMinute: 1200, count: 5)` yields `[480, 660, 840, 1020, 1200]`.
|
||||||
|
///
|
||||||
|
/// Every time here is a *minute of day*, an int in `0..1439`. The fields are
|
||||||
|
/// deliberately named `firstMinute`/`lastMinute` rather than reusing the old
|
||||||
|
/// hour-valued `first`/`last`, so `flutter analyze` enumerates every call site
|
||||||
|
/// that still thinks in hours.
|
||||||
///
|
///
|
||||||
/// This file is pure: no clock, no storage, no settings lookup. Persistence
|
/// This file is pure: no clock, no storage, no settings lookup. Persistence
|
||||||
/// lives in `services/meal_schedule_service.dart`, and the slot arithmetic
|
/// lives in `services/meal_schedule_service.dart`, and the slot arithmetic
|
||||||
@ -12,13 +18,17 @@
|
|||||||
/// KEEP IN SYNC WITH `diet_guard/_meal_schedule.py`. The two must agree on
|
/// KEEP IN SYNC WITH `diet_guard/_meal_schedule.py`. The two must agree on
|
||||||
/// every input, because a device that derives different slots than its peer
|
/// every input, because a device that derives different slots than its peer
|
||||||
/// nags for checkpoints the other never offers -- and a slot that can never be
|
/// nags for checkpoints the other never offers -- and a slot that can never be
|
||||||
/// satisfied is a permanent lock. Two rules make that agreement checkable:
|
/// satisfied is a permanent lock. `tests/fixtures/meal_schedule_vectors.json`
|
||||||
|
/// is read by both test suites; three rules make that agreement checkable:
|
||||||
///
|
///
|
||||||
/// * **Integer arithmetic only.** No doubles and no `round()` anywhere in the
|
/// * **Integer arithmetic only.** No doubles and no `round()` anywhere in the
|
||||||
/// derivation. Dart's `round()` is half-away-from-zero (`2.5.round() == 3`)
|
/// derivation. Dart's `round()` is half-away-from-zero (`2.5.round() == 3`)
|
||||||
/// while Python's is banker's rounding (`round(2.5) == 2`), so any
|
/// while Python's is banker's rounding (`round(2.5) == 2`), so any
|
||||||
/// floating-point path is a latent cross-language split brain. `~/` here,
|
/// floating-point path is a latent cross-language split brain. `~/` here,
|
||||||
/// `//` there.
|
/// `//` there.
|
||||||
|
/// * **Non-negative operands to every division.** `~/` truncates while
|
||||||
|
/// Python's `//` floors (`-7 ~/ 15 == 0`, `-7 // 15 == -1`). Every division
|
||||||
|
/// below runs on a value [MealSchedule.normalized] has pulled into the day.
|
||||||
/// * **Clamp, don't reject.** Every out-of-range input is normalised to the
|
/// * **Clamp, don't reject.** Every out-of-range input is normalised to the
|
||||||
/// nearest legal schedule rather than throwing, so the two languages cannot
|
/// nearest legal schedule rather than throwing, so the two languages cannot
|
||||||
/// disagree about which inputs are errors.
|
/// disagree about which inputs are errors.
|
||||||
@ -36,11 +46,16 @@ const int kMinMealCount = 2;
|
|||||||
/// `test/widgets/slot_selector_row_test.dart`.
|
/// `test/widgets/slot_selector_row_test.dart`.
|
||||||
const int kMaxMealCount = 6;
|
const int kMaxMealCount = 6;
|
||||||
|
|
||||||
/// Earliest hour a meal may be scheduled at.
|
/// Minutes in a day; a minute of day is `0..kMinutesPerDay - 1`.
|
||||||
const int kFirstHour = 0;
|
const int kMinutesPerDay = 1440;
|
||||||
|
|
||||||
/// Latest hour a meal may be scheduled at.
|
/// Minimum spacing between two checkpoints, and the grid interior checkpoints
|
||||||
const int kLastHour = 23;
|
/// are rounded onto.
|
||||||
|
///
|
||||||
|
/// One constant for both is what makes the strict-ascent proof in
|
||||||
|
/// [MealSchedule.slots] work: points at least one grid step apart cannot round
|
||||||
|
/// onto the same grid mark.
|
||||||
|
const int kSlotGridMinutes = 15;
|
||||||
|
|
||||||
/// Grace period after the final checkpoint, before the gate stops firing.
|
/// Grace period after the final checkpoint, before the gate stops firing.
|
||||||
///
|
///
|
||||||
@ -48,9 +63,9 @@ const int kLastHour = 23;
|
|||||||
/// have to log a late dinner, which has nothing to do with how many meals you
|
/// have to log a late dinner, which has nothing to do with how many meals you
|
||||||
/// eat. Tying it to the spacing would stretch the lockout window to midnight
|
/// eat. Tying it to the spacing would stretch the lockout window to midnight
|
||||||
/// at four meals, contradicting the "don't trap me overnight" intent.
|
/// at four meals, contradicting the "don't trap me overnight" intent.
|
||||||
const int kEnforcementTailHours = 2;
|
const int kEnforcementTailMinutes = 120;
|
||||||
|
|
||||||
const int _hoursPerDay = 24;
|
const int _lastMinute = kMinutesPerDay - 1;
|
||||||
|
|
||||||
int _clamp(int value, int low, int high) =>
|
int _clamp(int value, int low, int high) =>
|
||||||
value < low ? low : (value > high ? high : value);
|
value < low ? low : (value > high ? high : value);
|
||||||
@ -60,95 +75,142 @@ int _clamp(int value, int low, int high) =>
|
|||||||
class MealSchedule {
|
class MealSchedule {
|
||||||
/// Creates a [MealSchedule].
|
/// Creates a [MealSchedule].
|
||||||
const MealSchedule({
|
const MealSchedule({
|
||||||
required this.first,
|
required this.firstMinute,
|
||||||
required this.last,
|
required this.lastMinute,
|
||||||
required this.count,
|
required this.count,
|
||||||
});
|
});
|
||||||
|
|
||||||
/// Hour of the first meal, 0-23.
|
/// Minute of day of the first meal, 0-1424.
|
||||||
final int first;
|
final int firstMinute;
|
||||||
|
|
||||||
/// Hour of the last meal, strictly after [first].
|
/// Minute of day of the last meal, at least one grid step (15 minutes) after
|
||||||
final int last;
|
/// [firstMinute] and at most 1439.
|
||||||
|
final int lastMinute;
|
||||||
|
|
||||||
/// Total meals including both endpoints.
|
/// Total meals including both endpoints.
|
||||||
final int count;
|
final int count;
|
||||||
|
|
||||||
/// Returns an equivalent schedule guaranteed to satisfy the invariants.
|
/// Returns an equivalent schedule guaranteed to satisfy the invariants.
|
||||||
///
|
///
|
||||||
/// Ordering matters: [first] is clamped into the day, then [last] is clamped
|
/// Ordering matters: [firstMinute] is clamped into the day leaving room for
|
||||||
/// to leave at least one hour of window, then [count] is clamped to the
|
/// one grid step, then [lastMinute] is clamped to at least one grid step
|
||||||
/// window's width. That last clamp is the load-bearing one -- see [slots].
|
/// after it, then [count] is clamped to how many grid-spaced checkpoints the
|
||||||
|
/// window holds. That last clamp is the load-bearing one -- see [slots].
|
||||||
MealSchedule normalized() {
|
MealSchedule normalized() {
|
||||||
final normFirst = _clamp(first, kFirstHour, kLastHour - 1);
|
final first = _clamp(firstMinute, 0, _lastMinute - kSlotGridMinutes);
|
||||||
final normLast = _clamp(last, normFirst + 1, kLastHour);
|
final last = _clamp(lastMinute, first + kSlotGridMinutes, _lastMinute);
|
||||||
// A window of N hours holds at most N+1 whole-hour checkpoints; asking for
|
// A window of W minutes holds at most W ~/ 15 + 1 checkpoints spaced a
|
||||||
// more would repeat an hour (see slots()).
|
// grid step apart; asking for more would round two onto one mark.
|
||||||
|
final capacity = (last - first) ~/ kSlotGridMinutes + 1;
|
||||||
final normCount = _clamp(
|
final normCount = _clamp(
|
||||||
count,
|
count,
|
||||||
kMinMealCount,
|
kMinMealCount,
|
||||||
kMaxMealCount < normLast - normFirst + 1
|
kMaxMealCount < capacity ? kMaxMealCount : capacity,
|
||||||
? kMaxMealCount
|
|
||||||
: normLast - normFirst + 1,
|
|
||||||
);
|
);
|
||||||
return MealSchedule(first: normFirst, last: normLast, count: normCount);
|
return MealSchedule(firstMinute: first, lastMinute: last, count: normCount);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the meal-slot hours, ascending, with both endpoints exact.
|
/// Returns the meal-slot minutes, ascending, with both endpoints exact.
|
||||||
///
|
///
|
||||||
/// Meals are spread evenly across the window and rounded to whole hours by
|
/// With `span = last - first` and `d = count - 1`, interior slot *i* is
|
||||||
/// integer arithmetic: slot *i* is `first + (i*span + d ~/ 2) ~/ d` where
|
/// `raw = first + (i*span + d ~/ 2) ~/ d` (even division, the `d ~/ 2` term
|
||||||
/// `span = last - first` and `d = count - 1`. The `d ~/ 2` term is a
|
/// a round-half-up bias that keeps it free of floating point), then snapped
|
||||||
/// round-half-up bias applied before the division, which is what keeps this
|
/// to the nearest absolute quarter hour by `(raw + 7) ~/ 15 * 15`. The
|
||||||
/// free of floating point.
|
/// endpoints are [firstMinute] and [lastMinute] exactly -- never snapped.
|
||||||
///
|
///
|
||||||
/// Both endpoints land exactly on [first] and [last] by construction, so the
|
/// Strictly ascending, provably: [normalized] caps [count] so that
|
||||||
/// eating window is always honoured even when interior spacing must round.
|
/// `span / d >= 15`, hence consecutive `raw` values differ by at least 15,
|
||||||
///
|
/// and two integers at least 15 apart never snap onto the same grid mark.
|
||||||
/// The result is strictly ascending because [normalized] caps [count] at
|
/// Snapping moves a value by at most 7, so no interior slot can reach an
|
||||||
/// `last - first + 1`. Without that cap a narrow window repeats an hour
|
/// endpoint. That matters because slot minutes are set members, map keys
|
||||||
/// (`08-12` with 6 meals would give `8, 9, 10, 10, 11, 12`), and since slot
|
/// *and* notification ids: a repeat silently drops a checkpoint.
|
||||||
/// hours are used as set members, map keys *and* notification ids, a repeat
|
|
||||||
/// silently drops a checkpoint.
|
|
||||||
List<int> slots() {
|
List<int> slots() {
|
||||||
final schedule = normalized();
|
final schedule = normalized();
|
||||||
final span = schedule.last - schedule.first;
|
final first = schedule.firstMinute;
|
||||||
|
final last = schedule.lastMinute;
|
||||||
|
final span = last - first;
|
||||||
final divisions = schedule.count - 1;
|
final divisions = schedule.count - 1;
|
||||||
return [
|
return [
|
||||||
for (var index = 0; index < schedule.count; index++)
|
first,
|
||||||
schedule.first + (index * span + divisions ~/ 2) ~/ divisions,
|
for (var index = 1; index < divisions; index++)
|
||||||
|
(first + (index * span + divisions ~/ 2) ~/ divisions + 7) ~/
|
||||||
|
kSlotGridMinutes *
|
||||||
|
kSlotGridMinutes,
|
||||||
|
last,
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The hour at which slot enforcement stops for the day.
|
/// The minute at which slot enforcement stops for the day.
|
||||||
///
|
///
|
||||||
/// Clamped to the end of the day: a 23:00 last meal would otherwise put the
|
/// Derived from the *normalised* last meal, so it always agrees with the
|
||||||
/// cutoff at 25, making `hour < cutoff` vacuously true so the enforcement
|
/// last entry of [slots]. Clamped to the end of the day: a 23:00 last meal
|
||||||
/// window never closes and the reminder can never stop firing.
|
/// would otherwise put the cutoff at 1500, making `minute < cutoff`
|
||||||
int get enforcementEndHour {
|
/// vacuously true so the enforcement window never closes.
|
||||||
final end = last + kEnforcementTailHours;
|
int get enforcementEndMinute {
|
||||||
return end < _hoursPerDay ? end : _hoursPerDay;
|
final end = normalized().lastMinute + kEnforcementTailMinutes;
|
||||||
|
return end < kMinutesPerDay ? end : kMinutesPerDay;
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
bool operator ==(Object other) =>
|
bool operator ==(Object other) =>
|
||||||
other is MealSchedule &&
|
other is MealSchedule &&
|
||||||
other.first == first &&
|
other.firstMinute == firstMinute &&
|
||||||
other.last == last &&
|
other.lastMinute == lastMinute &&
|
||||||
other.count == count;
|
other.count == count;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
int get hashCode => Object.hash(first, last, count);
|
int get hashCode => Object.hash(firstMinute, lastMinute, count);
|
||||||
|
|
||||||
@override
|
@override
|
||||||
String toString() => 'MealSchedule($first-$last x$count)';
|
String toString() => 'MealSchedule($firstMinute-$lastMinute x$count)';
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The historical hardcoded schedule: 08:00, 12:00, 16:00, 20:00, enforcement
|
/// The historical hardcoded schedule: 08:00, 12:00, 16:00, 20:00, enforcement
|
||||||
/// closing at 22:00. Still what a device uses before the user has chosen
|
/// closing at 22:00. Still what a device uses before the user has chosen
|
||||||
/// anything, so upgrading changes no behaviour.
|
/// anything, so upgrading changes no behaviour.
|
||||||
const MealSchedule kDefaultSchedule = MealSchedule(
|
const MealSchedule kDefaultSchedule = MealSchedule(
|
||||||
first: 8,
|
firstMinute: 8 * 60,
|
||||||
last: 20,
|
lastMinute: 20 * 60,
|
||||||
count: 4,
|
count: 4,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/// Returns the synced `sched:<date>` value for [schedule].
|
||||||
|
///
|
||||||
|
/// Mirrors `_meal_schedule.schedule_to_wire`. Backward compatible by
|
||||||
|
/// construction: `f`/`l` carry whole hours exactly as before the move to
|
||||||
|
/// minutes, and `fm`/`lm` appear only when an endpoint is off the hour, so a
|
||||||
|
/// whole-hour schedule encodes byte-identically to the old `{f, l, n}` form.
|
||||||
|
/// Normalised first, so every `~/` runs on a non-negative value.
|
||||||
|
Map<String, int> scheduleToWire(MealSchedule schedule) {
|
||||||
|
final norm = schedule.normalized();
|
||||||
|
final first = norm.firstMinute;
|
||||||
|
final last = norm.lastMinute;
|
||||||
|
return {
|
||||||
|
'f': first ~/ 60,
|
||||||
|
'l': last ~/ 60,
|
||||||
|
'n': norm.count,
|
||||||
|
if (first % 60 != 0) 'fm': first,
|
||||||
|
if (last % 60 != 0) 'lm': last,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the normalised schedule a `sched:<date>` value describes, or null.
|
||||||
|
///
|
||||||
|
/// Mirrors `_meal_schedule.schedule_from_wire`. `fm`/`lm` win when they are
|
||||||
|
/// ints; otherwise `f`/`l` are hours. Never throws: anything without int `f`,
|
||||||
|
/// `l` and `n` yields null, so one bad field from a peer cannot take out the
|
||||||
|
/// whole history.
|
||||||
|
MealSchedule? scheduleFromWire(Object? raw) {
|
||||||
|
if (raw is! Map) return null;
|
||||||
|
final first = raw['f'];
|
||||||
|
final last = raw['l'];
|
||||||
|
final count = raw['n'];
|
||||||
|
if (first is! int || last is! int || count is! int) return null;
|
||||||
|
final firstMinute = raw['fm'];
|
||||||
|
final lastMinute = raw['lm'];
|
||||||
|
return MealSchedule(
|
||||||
|
firstMinute: firstMinute is int ? firstMinute : first * 60,
|
||||||
|
lastMinute: lastMinute is int ? lastMinute : last * 60,
|
||||||
|
count: count,
|
||||||
|
).normalized();
|
||||||
|
}
|
||||||
|
|||||||
@ -1,4 +1,5 @@
|
|||||||
/// Pure meal-slot arithmetic, mirroring diet_guard's `_slots.py`.
|
/// Pure meal-slot arithmetic, mirroring diet_guard's `_slots.py` and
|
||||||
|
/// `_slot_wire.py`.
|
||||||
///
|
///
|
||||||
/// Deliberately I/O-free and clock-free: every function is a total function of
|
/// Deliberately I/O-free and clock-free: every function is a total function of
|
||||||
/// its `now` and `schedule` arguments, so the time-of-day edges are
|
/// its `now` and `schedule` arguments, so the time-of-day edges are
|
||||||
@ -7,6 +8,11 @@
|
|||||||
/// the Python original is shared between the gate dashboard and the lock
|
/// the Python original is shared between the gate dashboard and the lock
|
||||||
/// decision.
|
/// decision.
|
||||||
///
|
///
|
||||||
|
/// A slot is a *minute of day* (`0..1439`): 480, 720, 960, 1200 by default.
|
||||||
|
/// A logged meal satisfies the slot nearest its recorded slot minute
|
||||||
|
/// ([satisfiedSlots]), so an entry written under an older schedule still
|
||||||
|
/// counts after the schedule moves -- nothing stored is ever rewritten.
|
||||||
|
///
|
||||||
/// `schedule` is a required argument on every function here, deliberately: it
|
/// `schedule` is a required argument on every function here, deliberately: it
|
||||||
/// used to be read from module constants, and a default would let a call site
|
/// used to be read from module constants, and a default would let a call site
|
||||||
/// that was missed during a refactor keep deriving the old fixed hours on one
|
/// that was missed during a refactor keep deriving the old fixed hours on one
|
||||||
@ -14,11 +20,24 @@
|
|||||||
/// slot one device offers and the other does not is a checkpoint that can
|
/// slot one device offers and the other does not is a checkpoint that can
|
||||||
/// never be satisfied. Callers resolve the value at the impure edge, through
|
/// never be satisfied. Callers resolve the value at the impure edge, through
|
||||||
/// `MealScheduleService.current`.
|
/// `MealScheduleService.current`.
|
||||||
|
///
|
||||||
|
/// **Entry wire rule** (mirrors `_slot_wire.py`): writers always write
|
||||||
|
/// `slot = minute ~/ 60` and add `slot_min = minute` only when the minute is
|
||||||
|
/// off the hour, so whole-hour entries stay byte-identical to the pre-minute
|
||||||
|
/// format and an older peer still reads an hour. Readers prefer an int
|
||||||
|
/// `slot_min`, then `slot * 60`, else no slot. See [slotFields] and
|
||||||
|
/// [entrySlotMinute]; `tests/fixtures/meal_schedule_vectors.json` gates both
|
||||||
|
/// languages.
|
||||||
library;
|
library;
|
||||||
|
|
||||||
import 'package:diet_guard_app/models/meal_schedule.dart';
|
import 'package:diet_guard_app/models/meal_schedule.dart';
|
||||||
|
|
||||||
/// Returns the meal-slot hours for a day, e.g. `[8, 12, 16, 20]`.
|
/// Returns [now]'s minute of day, `0..1439` (seconds are ignored).
|
||||||
|
///
|
||||||
|
/// Mirrors `_slots.minute_of_day`.
|
||||||
|
int minuteOfDay(DateTime now) => now.hour * 60 + now.minute;
|
||||||
|
|
||||||
|
/// Returns the meal-slot minutes for a day, e.g. `[480, 720, 960, 1200]`.
|
||||||
///
|
///
|
||||||
/// Mirrors `_slots.day_slots`.
|
/// Mirrors `_slots.day_slots`.
|
||||||
List<int> daySlots(MealSchedule schedule) => schedule.slots();
|
List<int> daySlots(MealSchedule schedule) => schedule.slots();
|
||||||
@ -26,29 +45,30 @@ List<int> daySlots(MealSchedule schedule) => schedule.slots();
|
|||||||
/// Returns true if [now] is inside the daily slot-enforcement window.
|
/// Returns true if [now] is inside the daily slot-enforcement window.
|
||||||
///
|
///
|
||||||
/// Mirrors `_slots.within_enforcement_window`.
|
/// Mirrors `_slots.within_enforcement_window`.
|
||||||
bool withinEnforcementWindow(DateTime now, MealSchedule schedule) =>
|
bool withinEnforcementWindow(DateTime now, MealSchedule schedule) {
|
||||||
now.hour >= schedule.slots().first &&
|
final minute = minuteOfDay(now);
|
||||||
now.hour < schedule.enforcementEndHour;
|
return schedule.slots().first <= minute &&
|
||||||
|
minute < schedule.enforcementEndMinute;
|
||||||
|
}
|
||||||
|
|
||||||
/// Returns today's slots whose hour has arrived as of [now].
|
/// Returns today's slots whose minute has arrived as of [now].
|
||||||
///
|
///
|
||||||
/// Empty outside the enforcement window. Mirrors `_slots.elapsed_slots`.
|
/// Empty outside the enforcement window. Mirrors `_slots.elapsed_slots`.
|
||||||
List<int> elapsedSlots(DateTime now, MealSchedule schedule) {
|
List<int> elapsedSlots(DateTime now, MealSchedule schedule) {
|
||||||
if (!withinEnforcementWindow(now, schedule)) return const [];
|
if (!withinEnforcementWindow(now, schedule)) return const [];
|
||||||
return daySlots(schedule).where((slot) => slot <= now.hour).toList();
|
final minute = minuteOfDay(now);
|
||||||
|
return daySlots(schedule).where((slot) => slot <= minute).toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns elapsed slots not yet covered by [logged].
|
/// Returns elapsed slots not yet covered by [logged] (normally
|
||||||
|
/// [satisfiedSlots] of the entries' slot minutes).
|
||||||
///
|
///
|
||||||
/// Mirrors `_slots.missing_slots`.
|
/// Mirrors `_slots.missing_slots`.
|
||||||
List<int> missingSlots(
|
List<int> missingSlots(DateTime now, Set<int> logged, MealSchedule schedule) =>
|
||||||
DateTime now,
|
elapsedSlots(
|
||||||
Set<int> logged,
|
|
||||||
MealSchedule schedule,
|
|
||||||
) => elapsedSlots(
|
|
||||||
now,
|
now,
|
||||||
schedule,
|
schedule,
|
||||||
).where((slot) => !logged.contains(slot)).toList();
|
).where((slot) => !logged.contains(slot)).toList();
|
||||||
|
|
||||||
/// Returns the most recent elapsed slot as of [now], or null.
|
/// Returns the most recent elapsed slot as of [now], or null.
|
||||||
///
|
///
|
||||||
@ -64,8 +84,7 @@ int? currentSlot(DateTime now, MealSchedule schedule) {
|
|||||||
/// first slot, clamp to the first slot; after the enforcement window ends,
|
/// first slot, clamp to the first slot; after the enforcement window ends,
|
||||||
/// clamp to the last slot; behaviour inside a window is unchanged. The two
|
/// clamp to the last slot; behaviour inside a window is unchanged. The two
|
||||||
/// languages must reach each answer by the *same* branch, not merely agree on
|
/// languages must reach each answer by the *same* branch, not merely agree on
|
||||||
/// the value -- `test/models/slot_test.dart` sweeps every hour of the day
|
/// the value -- the shared fixture pins every minute edge for that reason.
|
||||||
/// against several schedules for exactly that reason.
|
|
||||||
///
|
///
|
||||||
/// Unlike [currentSlot] this never returns null, which is the point: an
|
/// Unlike [currentSlot] this never returns null, which is the point: an
|
||||||
/// off-hours meal used to satisfy no slot at all, so eating at 07:30 or 22:30
|
/// off-hours meal used to satisfy no slot at all, so eating at 07:30 or 22:30
|
||||||
@ -74,11 +93,65 @@ int? currentSlot(DateTime now, MealSchedule schedule) {
|
|||||||
/// *those* would instead make every slot fall due at the end of the day.
|
/// *those* would instead make every slot fall due at the end of the day.
|
||||||
int slotForLog(DateTime now, MealSchedule schedule) {
|
int slotForLog(DateTime now, MealSchedule schedule) {
|
||||||
final slots = daySlots(schedule);
|
final slots = daySlots(schedule);
|
||||||
if (now.hour < slots.first) return slots.first;
|
if (minuteOfDay(now) < slots.first) return slots.first;
|
||||||
return currentSlot(now, schedule) ?? slots.last;
|
return currentSlot(now, schedule) ?? slots.last;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns a human `HH:00` label for [slot], e.g. `"08:00"`.
|
/// Returns the slot closest to [minute]; an exact tie goes to the earlier.
|
||||||
|
///
|
||||||
|
/// Mirrors `_slots.nearest_slot`, whose `min` keeps the first minimal element
|
||||||
|
/// of the ascending slots -- hence replacing the best only on a strictly
|
||||||
|
/// smaller distance here.
|
||||||
|
int nearestSlot(int minute, MealSchedule schedule) {
|
||||||
|
final slots = daySlots(schedule);
|
||||||
|
var best = slots.first;
|
||||||
|
for (final slot in slots) {
|
||||||
|
if ((slot - minute).abs() < (best - minute).abs()) best = slot;
|
||||||
|
}
|
||||||
|
return best;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the slots covered by meals recorded at [entryMinutes].
|
||||||
|
///
|
||||||
|
/// Mirrors `_slots.satisfied_slots`. Many-to-one is intended: two meals
|
||||||
|
/// snapping onto one slot satisfy only that slot.
|
||||||
|
Set<int> satisfiedSlots(Iterable<int> entryMinutes, MealSchedule schedule) => {
|
||||||
|
for (final minute in entryMinutes) nearestSlot(minute, schedule),
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Returns the entry fields that record [minute] as its slot.
|
||||||
|
///
|
||||||
|
/// Mirrors `_slot_wire.slot_fields`; throws [ArgumentError] for a minute
|
||||||
|
/// outside the day, as Python raises `ValueError`.
|
||||||
|
Map<String, int> slotFields(int minute) {
|
||||||
|
if (minute < 0 || minute >= kMinutesPerDay) {
|
||||||
|
throw ArgumentError.value(
|
||||||
|
minute,
|
||||||
|
'minute',
|
||||||
|
'slot minute is outside 0..${kMinutesPerDay - 1}',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return {'slot': minute ~/ 60, if (minute % 60 != 0) 'slot_min': minute};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the slot minute a raw log entry records, or null when it has none.
|
||||||
|
///
|
||||||
|
/// Mirrors `_slot_wire.entry_slot_minute`: an int `slot_min` wins, else an int
|
||||||
|
/// `slot` is an hour, else null. Values are not range-checked.
|
||||||
|
int? entrySlotMinute(Map<String, Object?> entry) {
|
||||||
|
final slotMin = entry['slot_min'];
|
||||||
|
if (slotMin is int) return slotMin;
|
||||||
|
final slot = entry['slot'];
|
||||||
|
if (slot is int) return slot * 60;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns a human `HH:MM` label for a slot minute, e.g. `"07:15"`.
|
||||||
///
|
///
|
||||||
/// Mirrors `_slots.slot_label`.
|
/// Mirrors `_slots.slot_label`.
|
||||||
String slotLabel(int slot) => '${(slot % 24).toString().padLeft(2, '0')}:00';
|
String slotLabel(int minute) {
|
||||||
|
final wrapped = minute % kMinutesPerDay;
|
||||||
|
final hours = (wrapped ~/ 60).toString().padLeft(2, '0');
|
||||||
|
final minutes = (wrapped % 60).toString().padLeft(2, '0');
|
||||||
|
return '$hours:$minutes';
|
||||||
|
}
|
||||||
|
|||||||
72
app/lib/models/workout_session.dart
Normal file
@ -0,0 +1,72 @@
|
|||||||
|
/// One published workout, as the PC syncs it in the Body document.
|
||||||
|
///
|
||||||
|
/// Split out of `services/activity_kcal.dart` for the 250-line cap; that
|
||||||
|
/// file re-exports it, so importers see no change. Parsing is tolerant: a
|
||||||
|
/// malformed session is dropped, an unparsable time reads as null.
|
||||||
|
library;
|
||||||
|
|
||||||
|
/// One workout, reduced to what the energy formulas need.
|
||||||
|
class Session {
|
||||||
|
/// Creates a session.
|
||||||
|
const Session({
|
||||||
|
required this.day,
|
||||||
|
required this.kind,
|
||||||
|
required this.minutes,
|
||||||
|
required this.km,
|
||||||
|
required this.label,
|
||||||
|
required this.source,
|
||||||
|
this.start,
|
||||||
|
this.end,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Parses the synced wire object (`day, kind, min, km, label, src`), or
|
||||||
|
/// null when it is malformed.
|
||||||
|
static Session? fromWire(Object? raw) {
|
||||||
|
if (raw is! Map) return null;
|
||||||
|
final day = raw['day'];
|
||||||
|
final kind = raw['kind'];
|
||||||
|
final minutes = raw['min'];
|
||||||
|
final km = raw['km'];
|
||||||
|
if (day is! String || kind is! String || minutes is! num) return null;
|
||||||
|
if (km != null && km is! num) return null;
|
||||||
|
return Session(
|
||||||
|
day: day,
|
||||||
|
kind: kind,
|
||||||
|
minutes: minutes.toDouble(),
|
||||||
|
km: (km as num?)?.toDouble(),
|
||||||
|
label: raw['label'] is String ? raw['label'] as String : kind,
|
||||||
|
source: raw['src'] is String ? raw['src'] as String : '',
|
||||||
|
start: _stampOrNull(raw['start']),
|
||||||
|
end: _stampOrNull(raw['end']),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Local `YYYY-MM-DD` the workout happened on.
|
||||||
|
final String day;
|
||||||
|
|
||||||
|
/// `strength`, `run`, `walk`, `cycle` or `other`.
|
||||||
|
final String kind;
|
||||||
|
|
||||||
|
/// Duration in minutes.
|
||||||
|
final double minutes;
|
||||||
|
|
||||||
|
/// Distance, or null when the source has none.
|
||||||
|
final double? km;
|
||||||
|
|
||||||
|
/// Human description.
|
||||||
|
final String label;
|
||||||
|
|
||||||
|
/// Where it came from (`runnerup`, `screen-locker`).
|
||||||
|
final String source;
|
||||||
|
|
||||||
|
/// ISO start time, when the source knows it.
|
||||||
|
final String? start;
|
||||||
|
|
||||||
|
/// ISO end time, when the source knows it. The phone drops Health
|
||||||
|
/// Connect steps inside `start..end`, so a walk is not counted twice.
|
||||||
|
final String? end;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An ISO time string, or null when absent or unparsable.
|
||||||
|
String? _stampOrNull(Object? value) =>
|
||||||
|
value is String && DateTime.tryParse(value) != null ? value : null;
|
||||||
247
app/lib/screens/body_screen.dart
Normal file
@ -0,0 +1,247 @@
|
|||||||
|
/// The Body screen: the goal sentence first, then weight (+ graph), BMI,
|
||||||
|
/// ideal weight, BMR, measured activity and steps, the week planner, the
|
||||||
|
/// profile (at the top instead while incomplete), and body fat last.
|
||||||
|
///
|
||||||
|
/// The phone half of the PC gate's Body tab (`_gatelock_body*.py`), reading
|
||||||
|
/// the same synced `body.json` (see `docs/DOCS-body.md`). **Informational
|
||||||
|
/// only**: nothing here writes the daily budget -- there is deliberately no
|
||||||
|
/// "apply" button.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/screens/body_screen_data.dart';
|
||||||
|
import 'package:diet_guard_app/services/app_settings_service.dart';
|
||||||
|
import 'package:diet_guard_app/services/body_calc.dart';
|
||||||
|
import 'package:diet_guard_app/services/body_energy.dart';
|
||||||
|
import 'package:diet_guard_app/services/body_prefs.dart';
|
||||||
|
import 'package:diet_guard_app/services/body_service.dart';
|
||||||
|
import 'package:diet_guard_app/services/health_steps.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
|
import 'package:diet_guard_app/ui/cues.dart';
|
||||||
|
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||||
|
import 'package:diet_guard_app/ui/theme.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/body/activity_card.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/body/body_section.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/body/body_stats_cards.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/body/body_tile_grid.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/body/goal_card.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/body/profile_card.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/body/week_plan_card.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/body/weight_card.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
export 'package:diet_guard_app/screens/body_screen_data.dart';
|
||||||
|
|
||||||
|
/// The Body screen.
|
||||||
|
class BodyScreen extends StatefulWidget {
|
||||||
|
/// Creates the screen.
|
||||||
|
const BodyScreen({super.key});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<BodyScreen> createState() => _BodyScreenState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _BodyScreenState extends State<BodyScreen> {
|
||||||
|
Map<String, double> _logged = const {};
|
||||||
|
|
||||||
|
/// Decided once, when the screen opens: a complete profile sits at the
|
||||||
|
/// bottom, an incomplete one at the top. Re-deciding on every build would
|
||||||
|
/// yank the card away mid-edit the moment the last field is saved; it
|
||||||
|
/// moves the next time the screen is entered.
|
||||||
|
late final bool _profileAtTop = !BodyService.instance.profileComplete;
|
||||||
|
|
||||||
|
/// Whether the Health Connect button shows: supported and not yet granted.
|
||||||
|
///
|
||||||
|
/// A notifier, not a bool: the Activity sheet stays open while the
|
||||||
|
/// permission is granted, and its button must disappear and its numbers
|
||||||
|
/// refresh without reopening the sheet.
|
||||||
|
final ValueNotifier<bool> _canConnectSteps = ValueNotifier(false);
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_canConnectSteps.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
unawaited(_loadLog());
|
||||||
|
unawaited(_loadSteps());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Refreshes steps (only when already permitted -- never prompts) and
|
||||||
|
/// decides whether to offer the connect button.
|
||||||
|
Future<void> _loadSteps() async {
|
||||||
|
final source = stepsSource;
|
||||||
|
if (!source.supported) return;
|
||||||
|
final granted = await source.hasPermission().catchError((_) => false);
|
||||||
|
if (granted) await refreshSteps();
|
||||||
|
if (!mounted) return;
|
||||||
|
_canConnectSteps.value = !granted;
|
||||||
|
setState(() {});
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _connectSteps() async {
|
||||||
|
final granted = await stepsSource.requestPermission().catchError(
|
||||||
|
(_) => false,
|
||||||
|
);
|
||||||
|
if (granted) await refreshSteps();
|
||||||
|
if (!mounted) return;
|
||||||
|
_canConnectSteps.value = !granted;
|
||||||
|
setState(() {});
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _loadLog() async {
|
||||||
|
final log = await LogStorageService.instance.readLog();
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() => _logged = kcalByDay(log));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Any profile/weight write changes every derived card; the cards read
|
||||||
|
/// [BodyService] in `build`, so a rebuild is all they need.
|
||||||
|
void _onChanged() => setState(() {});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final body = BodyService.instance;
|
||||||
|
final today = DateTime.now();
|
||||||
|
final bio = currentBiometrics(body, today);
|
||||||
|
final (exercise, _, _) = bodyExercise(body, bio, today);
|
||||||
|
final tiles = _tiles(body, bio, exercise);
|
||||||
|
return Scaffold(
|
||||||
|
appBar: AppBar(),
|
||||||
|
body: Padding(
|
||||||
|
padding: const EdgeInsets.all(AppSpacing.md),
|
||||||
|
child: Center(
|
||||||
|
child: ConstrainedBox(
|
||||||
|
constraints: const BoxConstraints(maxWidth: AppWidth.prose),
|
||||||
|
child: BodyTileGrid(tiles: tiles),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The Activity card from the live service state.
|
||||||
|
Widget _activityCard({required bool canConnect}) {
|
||||||
|
final body = BodyService.instance;
|
||||||
|
final (exercise, stepsKcal, window) = bodyExercise(
|
||||||
|
body,
|
||||||
|
currentBiometrics(body, DateTime.now()),
|
||||||
|
DateTime.now(),
|
||||||
|
);
|
||||||
|
return ActivityCard(
|
||||||
|
sessions: body.sessions,
|
||||||
|
weightKg: body.latestWeight?.$2,
|
||||||
|
exercise: exercise,
|
||||||
|
steps: stepsByDay(body),
|
||||||
|
stepsKcal: stepsKcal,
|
||||||
|
window: window,
|
||||||
|
onConnectSteps: canConnect ? _connectSteps : null,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every section as a tile: the profile first while it is incomplete, last
|
||||||
|
/// otherwise (decided once, see [_profileAtTop]).
|
||||||
|
List<BodyTileSpec> _tiles(
|
||||||
|
BodyService body,
|
||||||
|
Biometrics? bio,
|
||||||
|
Map<String, double>? exercise,
|
||||||
|
) {
|
||||||
|
final weight = body.latestWeight?.$2;
|
||||||
|
final bodyFat = body.latestBodyFat?.$2;
|
||||||
|
final age = bodyAgeText(body, DateTime.now());
|
||||||
|
final profile = BodyTileSpec(
|
||||||
|
semanticLabel: 'Profile',
|
||||||
|
icon: Icons.person,
|
||||||
|
value: age,
|
||||||
|
valueIcon: age == null ? null : Icons.cake,
|
||||||
|
builder: (_) => ProfileCard(onSaved: _onChanged),
|
||||||
|
);
|
||||||
|
final goal = bio == null
|
||||||
|
? null
|
||||||
|
: goalTarget(
|
||||||
|
savedGoal(body),
|
||||||
|
tableBmr(bio, bodyFat).value!,
|
||||||
|
tableBmr(bio, bodyFat).name,
|
||||||
|
exercise,
|
||||||
|
).kcal;
|
||||||
|
return [
|
||||||
|
if (_profileAtTop) profile,
|
||||||
|
BodyTileSpec(
|
||||||
|
semanticLabel: 'Daily calorie target',
|
||||||
|
icon: Icons.flag,
|
||||||
|
value: goal == null ? null : '$goal',
|
||||||
|
valueIcon: goal == null ? null : MacroKind.kcal.icon,
|
||||||
|
builder: (_) => bio == null
|
||||||
|
? BodySection(
|
||||||
|
semanticLabel: 'Daily calorie target',
|
||||||
|
children: [
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
for (final icon in bodyMissingIcons(body))
|
||||||
|
StatusCue(
|
||||||
|
kind: CueKind.warn,
|
||||||
|
icon: icon,
|
||||||
|
semanticLabel: bodyMissingNote(body),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
: GoalCard(bio: bio, exercise: exercise, bodyFatPct: bodyFat),
|
||||||
|
),
|
||||||
|
BodyTileSpec(
|
||||||
|
semanticLabel: 'Weight',
|
||||||
|
icon: Icons.monitor_weight,
|
||||||
|
value: weight == null ? null : formatKg(weight),
|
||||||
|
builder: (_) => WeightCard(onChanged: _onChanged),
|
||||||
|
),
|
||||||
|
if (bio != null) ...[
|
||||||
|
BodyTileSpec(
|
||||||
|
semanticLabel: 'BMI',
|
||||||
|
icon: Icons.accessibility_new,
|
||||||
|
value: oneDecimal(bmiReport(bio).bmi),
|
||||||
|
builder: (_) => BmiCard(bio: bio),
|
||||||
|
),
|
||||||
|
BodyTileSpec(
|
||||||
|
semanticLabel: 'Ideal weight',
|
||||||
|
icon: Icons.balance,
|
||||||
|
builder: (_) => IdealWeightCard(bio: bio),
|
||||||
|
),
|
||||||
|
BodyTileSpec(
|
||||||
|
semanticLabel: 'Resting metabolism (BMR)',
|
||||||
|
icon: Icons.bedtime,
|
||||||
|
value: whole(tableBmr(bio, bodyFat).value!),
|
||||||
|
valueIcon: MacroKind.kcal.icon,
|
||||||
|
builder: (_) => BmrCard(bio: bio, bodyFatPct: bodyFat),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
BodyTileSpec(
|
||||||
|
semanticLabel: 'Activity',
|
||||||
|
icon: Icons.directions_run,
|
||||||
|
builder: (_) => ValueListenableBuilder<bool>(
|
||||||
|
valueListenable: _canConnectSteps,
|
||||||
|
builder: (_, canConnect, _) => _activityCard(canConnect: canConnect),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
BodyTileSpec(
|
||||||
|
semanticLabel: 'Week planner',
|
||||||
|
icon: Icons.calendar_view_week,
|
||||||
|
builder: (_) => WeekPlanCard(
|
||||||
|
defaultTarget: AppSettingsService.dailyKcalGoal,
|
||||||
|
logged: _logged,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (!_profileAtTop) profile,
|
||||||
|
BodyTileSpec(
|
||||||
|
semanticLabel: 'Body fat',
|
||||||
|
icon: Icons.percent,
|
||||||
|
value: bodyFat == null ? null : '${oneDecimal(bodyFat)} %',
|
||||||
|
builder: (_) => BodyFatCard(onChanged: _onChanged),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
88
app/lib/screens/body_screen_data.dart
Normal file
@ -0,0 +1,88 @@
|
|||||||
|
/// Pure data helpers behind the Body screen (split out for the 250-line cap).
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/services/activity_kcal.dart';
|
||||||
|
import 'package:diet_guard_app/services/body_calc.dart';
|
||||||
|
import 'package:diet_guard_app/services/body_service.dart';
|
||||||
|
import 'package:diet_guard_app/services/body_steps.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart' show IconData, Icons;
|
||||||
|
|
||||||
|
/// Builds the person from the stored profile and newest weight, or null
|
||||||
|
/// when anything the formulas need is missing.
|
||||||
|
Biometrics? currentBiometrics(BodyService body, DateTime today) {
|
||||||
|
final birth = DateTime.tryParse(body.birth ?? '');
|
||||||
|
final height = body.heightCm;
|
||||||
|
final sex = body.sex;
|
||||||
|
final weight = body.latestWeight;
|
||||||
|
if (birth == null || height == null || sex == null || weight == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return Biometrics(
|
||||||
|
weightKg: weight.$2,
|
||||||
|
heightCm: height,
|
||||||
|
ageYears: ageOn(birth, today).toDouble(),
|
||||||
|
isMale: sex == 'm',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Steps outside workouts by day, as stored.
|
||||||
|
Map<String, int> stepsByDay(BodyService body) =>
|
||||||
|
body.document.steps.map((day, entry) => MapEntry(day, entry.n));
|
||||||
|
|
||||||
|
/// Mean daily exercise per formula (steps included), the steps' own share,
|
||||||
|
/// and the number of full days averaged -- like the PC's `_body_view`: the
|
||||||
|
/// two means are null without a person, or without any published workout
|
||||||
|
/// or step count.
|
||||||
|
(Map<String, double>?, double?, int) bodyExercise(
|
||||||
|
BodyService body,
|
||||||
|
Biometrics? bio,
|
||||||
|
DateTime today,
|
||||||
|
) {
|
||||||
|
final sessions = body.sessions;
|
||||||
|
final steps = stepsByDay(body);
|
||||||
|
if (bio == null || (sessions == null && steps.isEmpty)) {
|
||||||
|
return (null, null, 0);
|
||||||
|
}
|
||||||
|
final byDay = steps.map((day, n) => MapEntry(day, stepKcal(n, bio)));
|
||||||
|
final weight = bio.weightKg;
|
||||||
|
final all = sessions ?? const <Session>[];
|
||||||
|
return (
|
||||||
|
dailyExercise(all, weight, today, byDay),
|
||||||
|
extraShare(all, today, byDay),
|
||||||
|
windowDays(all, today, byDay),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sums each day's non-deleted kcal.
|
||||||
|
Map<String, double> kcalByDay(DayLog log) => {
|
||||||
|
for (final entry in log.entries)
|
||||||
|
entry.key: entry.value
|
||||||
|
.where((food) => !food.deleted)
|
||||||
|
.fold<double>(0, (sum, food) => sum + food.kcal),
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Glyphs of the inputs still missing (profile, weight), in the order the
|
||||||
|
/// user should supply them; the visible counterpart of [bodyMissingNote].
|
||||||
|
List<IconData> bodyMissingIcons(BodyService body) => [
|
||||||
|
if (body.birth == null || body.heightCm == null || body.sex == null)
|
||||||
|
Icons.person,
|
||||||
|
if (body.latestWeight == null) Icons.monitor_weight,
|
||||||
|
];
|
||||||
|
|
||||||
|
/// Spoken reason the numbers are missing (screen readers, tests; never
|
||||||
|
/// painted).
|
||||||
|
String bodyMissingNote(BodyService body) {
|
||||||
|
if (body.latestWeight == null && body.birth == null) {
|
||||||
|
return 'Set your profile and enter your weight to see BMI, ideal '
|
||||||
|
'weight and calorie targets.';
|
||||||
|
}
|
||||||
|
if (body.latestWeight == null) return 'Enter your weight to see the numbers.';
|
||||||
|
return 'Set your profile (birth date, height, sex) to see the numbers.';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The age in whole years, or null while no birth date is stored.
|
||||||
|
String? bodyAgeText(BodyService body, DateTime today) {
|
||||||
|
final birth = DateTime.tryParse(body.birth ?? '');
|
||||||
|
return birth == null ? null : '${ageOn(birth, today)}';
|
||||||
|
}
|
||||||
@ -9,6 +9,7 @@ library;
|
|||||||
|
|
||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart' show WaitWatch;
|
||||||
import 'package:diet_guard_app/models/day_status.dart';
|
import 'package:diet_guard_app/models/day_status.dart';
|
||||||
import 'package:diet_guard_app/models/period_average.dart';
|
import 'package:diet_guard_app/models/period_average.dart';
|
||||||
import 'package:diet_guard_app/screens/history_screen.dart';
|
import 'package:diet_guard_app/screens/history_screen.dart';
|
||||||
@ -17,11 +18,13 @@ import 'package:diet_guard_app/services/average_service.dart';
|
|||||||
import 'package:diet_guard_app/services/budget_history_service.dart';
|
import 'package:diet_guard_app/services/budget_history_service.dart';
|
||||||
import 'package:diet_guard_app/services/day_status_service.dart';
|
import 'package:diet_guard_app/services/day_status_service.dart';
|
||||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
|
import 'package:diet_guard_app/ui/cues.dart';
|
||||||
|
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||||
import 'package:diet_guard_app/widgets/average_summary_row.dart';
|
import 'package:diet_guard_app/widgets/average_summary_row.dart';
|
||||||
import 'package:diet_guard_app/widgets/day_status_calendar.dart';
|
import 'package:diet_guard_app/widgets/day_status_calendar.dart';
|
||||||
import 'package:diet_guard_app/widgets/streak_summary_row.dart';
|
import 'package:diet_guard_app/widgets/streak_summary_row.dart';
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:flutter/services.dart';
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// Screen showing the budget-adherence calendar, streaks, and budget entry.
|
/// Screen showing the budget-adherence calendar, streaks, and budget entry.
|
||||||
class CalendarScreen extends StatefulWidget {
|
class CalendarScreen extends StatefulWidget {
|
||||||
@ -151,11 +154,10 @@ class _CalendarScreenState extends State<CalendarScreen> {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
if (_loading) {
|
if (_loading) {
|
||||||
return const Scaffold(body: Center(child: CircularProgressIndicator()));
|
return const Scaffold(body: WaitWatch.centered('calendar.load'));
|
||||||
}
|
}
|
||||||
final theme = Theme.of(context);
|
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(title: const Text('Calendar')),
|
appBar: AppBar(),
|
||||||
body: SingleChildScrollView(
|
body: SingleChildScrollView(
|
||||||
padding: const EdgeInsets.all(16),
|
padding: const EdgeInsets.all(16),
|
||||||
child: Column(
|
child: Column(
|
||||||
@ -168,11 +170,10 @@ class _CalendarScreenState extends State<CalendarScreen> {
|
|||||||
if (_budgetStatus != null)
|
if (_budgetStatus != null)
|
||||||
Padding(
|
Padding(
|
||||||
padding: const EdgeInsets.only(top: 4),
|
padding: const EdgeInsets.only(top: 4),
|
||||||
child: Text(
|
child: StatusCue(
|
||||||
_budgetStatus!,
|
key: ValueKey(_budgetStatus),
|
||||||
style: TextStyle(
|
kind: _budgetError ? CueKind.error : CueKind.ok,
|
||||||
color: _budgetError ? theme.colorScheme.error : null,
|
semanticLabel: _budgetStatus!,
|
||||||
),
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
@ -215,7 +216,11 @@ class _BudgetRow extends StatelessWidget {
|
|||||||
return Row(
|
return Row(
|
||||||
mainAxisAlignment: MainAxisAlignment.center,
|
mainAxisAlignment: MainAxisAlignment.center,
|
||||||
children: [
|
children: [
|
||||||
const Text('Daily budget (kcal):'),
|
Icon(
|
||||||
|
MacroKind.kcal.icon,
|
||||||
|
color: MacroKind.kcal.color,
|
||||||
|
semanticLabel: 'Daily budget (kcal)',
|
||||||
|
),
|
||||||
const SizedBox(width: 8),
|
const SizedBox(width: 8),
|
||||||
SizedBox(
|
SizedBox(
|
||||||
width: 90,
|
width: 90,
|
||||||
@ -230,7 +235,10 @@ class _BudgetRow extends StatelessWidget {
|
|||||||
const SizedBox(width: 8),
|
const SizedBox(width: 8),
|
||||||
FilledButton(
|
FilledButton(
|
||||||
onPressed: onEditOrSave,
|
onPressed: onEditOrSave,
|
||||||
child: Text(editing ? 'Save' : 'Edit'),
|
child: Icon(
|
||||||
|
editing ? Icons.check : Icons.edit,
|
||||||
|
semanticLabel: editing ? 'Save' : 'Edit',
|
||||||
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|||||||
@ -8,14 +8,15 @@ import 'package:diet_guard_app/models/food_suggestion.dart';
|
|||||||
import 'package:diet_guard_app/models/nutrition.dart';
|
import 'package:diet_guard_app/models/nutrition.dart';
|
||||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
|
import 'package:diet_guard_app/ui/cues.dart';
|
||||||
import 'package:diet_guard_app/widgets/autocomplete_suggestion_list.dart';
|
import 'package:diet_guard_app/widgets/autocomplete_suggestion_list.dart';
|
||||||
import 'package:diet_guard_app/widgets/macro_input_row.dart';
|
import 'package:diet_guard_app/widgets/macro_input_row.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:uuid/uuid.dart';
|
import 'package:uuid/uuid.dart';
|
||||||
|
|
||||||
/// Edit screen for an existing [FoodEntry].
|
/// Edit screen for an existing [FoodEntry].
|
||||||
///
|
///
|
||||||
/// Preserves [FoodEntry.id], [FoodEntry.time], [FoodEntry.slot],
|
/// Preserves [FoodEntry.id], [FoodEntry.time], [FoodEntry.slotMinute],
|
||||||
/// and [FoodEntry.deleted]. All nutritional fields and
|
/// and [FoodEntry.deleted]. All nutritional fields and
|
||||||
/// the description are editable.
|
/// the description are editable.
|
||||||
class EditEntryScreen extends StatefulWidget {
|
class EditEntryScreen extends StatefulWidget {
|
||||||
@ -35,6 +36,7 @@ class _EditEntryScreenState extends State<EditEntryScreen> {
|
|||||||
List<FoodSuggestion> _suggestions = const [];
|
List<FoodSuggestion> _suggestions = const [];
|
||||||
String _source = 'manual';
|
String _source = 'manual';
|
||||||
String? _status;
|
String? _status;
|
||||||
|
int _rejections = 0;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
@ -80,9 +82,7 @@ class _EditEntryScreenState extends State<EditEntryScreen> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _onDescChanged() async {
|
Future<void> _onDescChanged() async {
|
||||||
final matches = await FoodBankService.instance.search(
|
final matches = await FoodBankService.instance.search(_descController.text);
|
||||||
_descController.text,
|
|
||||||
);
|
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
setState(() => _suggestions = matches);
|
setState(() => _suggestions = matches);
|
||||||
}
|
}
|
||||||
@ -104,7 +104,10 @@ class _EditEntryScreenState extends State<EditEntryScreen> {
|
|||||||
Future<void> _onSave() async {
|
Future<void> _onSave() async {
|
||||||
final desc = _descController.text.trim();
|
final desc = _descController.text.trim();
|
||||||
if (desc.isEmpty) {
|
if (desc.isEmpty) {
|
||||||
setState(() => _status = 'Description cannot be empty.');
|
setState(() {
|
||||||
|
_status = 'Description cannot be empty.';
|
||||||
|
_rejections++;
|
||||||
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
final nutrition = nutritionForPortion(
|
final nutrition = nutritionForPortion(
|
||||||
@ -130,7 +133,7 @@ class _EditEntryScreenState extends State<EditEntryScreen> {
|
|||||||
carbsG: nutrition.carbsG,
|
carbsG: nutrition.carbsG,
|
||||||
fatG: nutrition.fatG,
|
fatG: nutrition.fatG,
|
||||||
source: _source,
|
source: _source,
|
||||||
slot: e.slot,
|
slotMinute: e.slotMinute,
|
||||||
);
|
);
|
||||||
await LogStorageService.instance.updateEntry(e, updated);
|
await LogStorageService.instance.updateEntry(e, updated);
|
||||||
final log = await LogStorageService.instance.readLog();
|
final log = await LogStorageService.instance.readLog();
|
||||||
@ -142,17 +145,16 @@ class _EditEntryScreenState extends State<EditEntryScreen> {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(title: const Text('Edit meal')),
|
appBar: AppBar(),
|
||||||
body: SingleChildScrollView(
|
body: SingleChildScrollView(
|
||||||
padding: const EdgeInsets.all(16),
|
padding: const EdgeInsets.all(16),
|
||||||
child: Column(
|
child: Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
TextField(
|
IconField(
|
||||||
|
icon: Icons.restaurant,
|
||||||
|
semanticLabel: 'What did you eat?',
|
||||||
controller: _descController,
|
controller: _descController,
|
||||||
decoration: const InputDecoration(
|
|
||||||
labelText: 'What did you eat?',
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
ConstrainedBox(
|
ConstrainedBox(
|
||||||
constraints: const BoxConstraints(maxHeight: 240),
|
constraints: const BoxConstraints(maxHeight: 240),
|
||||||
@ -168,12 +170,20 @@ class _EditEntryScreenState extends State<EditEntryScreen> {
|
|||||||
width: double.infinity,
|
width: double.infinity,
|
||||||
child: ElevatedButton(
|
child: ElevatedButton(
|
||||||
onPressed: _onSave,
|
onPressed: _onSave,
|
||||||
child: const Text('Save'),
|
child: const Icon(Icons.check, semanticLabel: 'Save'),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
if (_status != null) ...[
|
if (_status != null) ...[
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
Text(_status!),
|
// New key per rejection so a repeat error shakes again.
|
||||||
|
Align(
|
||||||
|
alignment: Alignment.centerLeft,
|
||||||
|
child: StatusCue(
|
||||||
|
key: ValueKey(_rejections),
|
||||||
|
kind: CueKind.error,
|
||||||
|
semanticLabel: _status!,
|
||||||
|
),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
|
|||||||
@ -8,12 +8,15 @@ library;
|
|||||||
|
|
||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart' show WaitWatch;
|
||||||
import 'package:diet_guard_app/models/food_bank_record.dart';
|
import 'package:diet_guard_app/models/food_bank_record.dart';
|
||||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||||
import 'package:diet_guard_app/widgets/food_bank/fb_add_entry_dialog.dart';
|
import 'package:diet_guard_app/widgets/food_bank/fb_add_entry_dialog.dart';
|
||||||
import 'package:diet_guard_app/widgets/food_bank/fb_filter.dart';
|
import 'package:diet_guard_app/widgets/food_bank/fb_filter.dart';
|
||||||
import 'package:diet_guard_app/widgets/food_bank/fb_filter_sheet.dart';
|
import 'package:diet_guard_app/widgets/food_bank/fb_filter_sheet.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:diet_guard_app/widgets/food_bank/fb_record_tile.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/food_bank/fb_tile_grid.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// Browses every banked food -- log-derived and manually curated -- with
|
/// Browses every banked food -- log-derived and manually curated -- with
|
||||||
/// filtering, sorting, and an add-entry dialog.
|
/// filtering, sorting, and an add-entry dialog.
|
||||||
@ -129,6 +132,13 @@ class _FoodBankScreenState extends State<FoodBankScreen> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Shows the full macro line for a tapped tile.
|
||||||
|
Future<void> _openDetail(FoodBankRecord record) => showModalBottomSheet<void>(
|
||||||
|
context: context,
|
||||||
|
useSafeArea: true,
|
||||||
|
builder: (_) => SafeArea(child: RecordTile(record)),
|
||||||
|
);
|
||||||
|
|
||||||
Future<void> _openAddDialog() async {
|
Future<void> _openAddDialog() async {
|
||||||
final result = await showDialog<FoodBankRecord>(
|
final result = await showDialog<FoodBankRecord>(
|
||||||
context: context,
|
context: context,
|
||||||
@ -144,15 +154,16 @@ class _FoodBankScreenState extends State<FoodBankScreen> {
|
|||||||
final all = _allEntries;
|
final all = _allEntries;
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(
|
appBar: AppBar(
|
||||||
title: const Text('Food Bank'),
|
|
||||||
actions: [
|
actions: [
|
||||||
if (all != null)
|
if (all != null)
|
||||||
Stack(
|
Stack(
|
||||||
alignment: Alignment.center,
|
alignment: Alignment.center,
|
||||||
children: [
|
children: [
|
||||||
IconButton(
|
IconButton(
|
||||||
icon: const Icon(Icons.filter_list),
|
icon: const Icon(
|
||||||
tooltip: 'Filter & sort',
|
Icons.filter_list,
|
||||||
|
semanticLabel: 'Filter & sort',
|
||||||
|
),
|
||||||
onPressed: _openFilterSheet,
|
onPressed: _openFilterSheet,
|
||||||
),
|
),
|
||||||
if (_filter.isActive)
|
if (_filter.isActive)
|
||||||
@ -173,66 +184,23 @@ class _FoodBankScreenState extends State<FoodBankScreen> {
|
|||||||
],
|
],
|
||||||
),
|
),
|
||||||
body: all == null
|
body: all == null
|
||||||
? const Center(child: CircularProgressIndicator())
|
? const WaitWatch.centered('food_bank.load')
|
||||||
: _displayed.isEmpty
|
: _displayed.isEmpty
|
||||||
? Center(
|
? Center(
|
||||||
child: Text(
|
child: Icon(
|
||||||
all.isEmpty
|
all.isEmpty ? Icons.restaurant_menu : Icons.filter_list_off,
|
||||||
? 'Food bank is empty.\n'
|
size: 64,
|
||||||
'Log meals to populate it, or add entries manually.'
|
color: Theme.of(context).colorScheme.outline,
|
||||||
|
semanticLabel: all.isEmpty
|
||||||
|
? 'Food bank is empty.'
|
||||||
: 'No entries match the current filter.',
|
: 'No entries match the current filter.',
|
||||||
textAlign: TextAlign.center,
|
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
: ListView.builder(
|
: FbTileGrid(records: _displayed, onOpen: _openDetail),
|
||||||
itemCount: _displayed.length,
|
|
||||||
itemBuilder: (context, i) => RecordTile(_displayed[i]),
|
|
||||||
),
|
|
||||||
floatingActionButton: FloatingActionButton(
|
floatingActionButton: FloatingActionButton(
|
||||||
onPressed: _openAddDialog,
|
onPressed: _openAddDialog,
|
||||||
tooltip: 'Add manual entry',
|
child: const Icon(Icons.add, semanticLabel: 'Add manual entry'),
|
||||||
child: const Icon(Icons.add),
|
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// Record tile
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
/// One banked food: its name, macros, and how often it has been logged.
|
|
||||||
class RecordTile extends StatelessWidget {
|
|
||||||
/// Creates a [RecordTile] for [record].
|
|
||||||
const RecordTile(this.record, {super.key});
|
|
||||||
|
|
||||||
/// The banked record this tile renders.
|
|
||||||
final FoodBankRecord record;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final macros =
|
|
||||||
'P ${record.proteinG.toStringAsFixed(0)} g '
|
|
||||||
'C ${record.carbsG.toStringAsFixed(0)} g '
|
|
||||||
'F ${record.fatG.toStringAsFixed(0)} g';
|
|
||||||
final per = record.grams > 0
|
|
||||||
? ' per ${record.grams.toStringAsFixed(0)} g'
|
|
||||||
: '';
|
|
||||||
return ListTile(
|
|
||||||
title: Text(record.desc),
|
|
||||||
subtitle: Text(
|
|
||||||
'${record.kcal.toStringAsFixed(0)} kcal$per · $macros',
|
|
||||||
),
|
|
||||||
trailing: record.count > 0
|
|
||||||
? Text(
|
|
||||||
'×${record.count.toStringAsFixed(0)}',
|
|
||||||
style: Theme.of(context).textTheme.bodySmall,
|
|
||||||
)
|
|
||||||
: null,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// Filter sheet
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|||||||
@ -28,54 +28,27 @@ class _ClientIdSetupDialogState extends State<_ClientIdSetupDialog> {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
|
// Icon-only: the setup steps (open github.com/settings/developers, make
|
||||||
|
// an OAuth App with Device Flow, paste its client id) live in the repo
|
||||||
|
// docs, not on screen.
|
||||||
return AlertDialog(
|
return AlertDialog(
|
||||||
title: const Text('One-time GitHub setup needed'),
|
content: IconField(
|
||||||
content: SingleChildScrollView(
|
icon: Icons.apps,
|
||||||
child: Column(
|
semanticLabel: 'Client ID',
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
const Text(
|
|
||||||
'Diet Guard signs in via a GitHub OAuth App (no password '
|
|
||||||
'typed into this app). You only have to set this up once:',
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
const Text(
|
|
||||||
'1. On any device, open '
|
|
||||||
'github.com/settings/developers → "New OAuth App".\n'
|
|
||||||
'2. Name/Homepage/Callback URL can be anything (device flow '
|
|
||||||
"doesn't use the callback) — e.g. "
|
|
||||||
'"Diet Guard" and your GitHub profile URL.\n'
|
|
||||||
'3. Check "Enable Device Flow", then click "Register '
|
|
||||||
'application".\n'
|
|
||||||
"4. Copy the Client ID shown on the app's page and paste it "
|
|
||||||
'below.',
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
const Text(
|
|
||||||
'When you connect below, log in with the GitHub account that '
|
|
||||||
'has write access to kuhyx/syncs.',
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
TextField(
|
|
||||||
controller: _controller,
|
controller: _controller,
|
||||||
autofocus: true,
|
autofocus: true,
|
||||||
decoration: const InputDecoration(labelText: 'Client ID'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
actions: [
|
actions: [
|
||||||
TextButton(
|
IconButton(
|
||||||
onPressed: () => Navigator.of(context).pop(),
|
onPressed: () => Navigator.of(context).pop(),
|
||||||
child: const Text('Cancel'),
|
icon: const Icon(Icons.close, semanticLabel: 'Cancel'),
|
||||||
),
|
),
|
||||||
FilledButton(
|
IconButton.filled(
|
||||||
onPressed: () {
|
onPressed: () {
|
||||||
final id = _controller.text.trim();
|
final id = _controller.text.trim();
|
||||||
if (id.isNotEmpty) Navigator.of(context).pop(id);
|
if (id.isNotEmpty) Navigator.of(context).pop(id);
|
||||||
},
|
},
|
||||||
child: const Text('Continue'),
|
icon: const Icon(Icons.arrow_forward, semanticLabel: 'Continue'),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|||||||
@ -21,7 +21,7 @@ mixin _GitHubMirrorActions on State<GitHubMirrorScreen> {
|
|||||||
TextEditingController get _clientIdController;
|
TextEditingController get _clientIdController;
|
||||||
|
|
||||||
bool _busy = false;
|
bool _busy = false;
|
||||||
String? _status;
|
Widget? _status;
|
||||||
String _storedToken = '';
|
String _storedToken = '';
|
||||||
SyncSettings _currentSettings() {
|
SyncSettings _currentSettings() {
|
||||||
final typed = _tokenController.text.trim();
|
final typed = _tokenController.text.trim();
|
||||||
@ -37,9 +37,18 @@ mixin _GitHubMirrorActions on State<GitHubMirrorScreen> {
|
|||||||
clientId: _clientIdController.text.trim(),
|
clientId: _clientIdController.text.trim(),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
void _showMessage(String message) {
|
|
||||||
|
/// Shows the outcome as an icon cue; [semanticLabel] is spoken, never
|
||||||
|
/// painted.
|
||||||
|
void _showCue(CueKind kind, String semanticLabel) {
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
setState(() => _status = message);
|
setState(
|
||||||
|
() => _status = StatusCue(
|
||||||
|
key: UniqueKey(),
|
||||||
|
kind: kind,
|
||||||
|
semanticLabel: semanticLabel,
|
||||||
|
),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _connectGitHub() async {
|
Future<void> _connectGitHub() async {
|
||||||
@ -69,12 +78,12 @@ mixin _GitHubMirrorActions on State<GitHubMirrorScreen> {
|
|||||||
_storedToken = token;
|
_storedToken = token;
|
||||||
if (SyncSettings.exposesTokenValue) _tokenController.text = token;
|
if (SyncSettings.exposesTokenValue) _tokenController.text = token;
|
||||||
});
|
});
|
||||||
_showMessage('Connected — syncing…');
|
_showCue(CueKind.info, 'Connected — syncing…');
|
||||||
await _currentSettings().save();
|
await _currentSettings().save();
|
||||||
await _syncAfterConnect();
|
await _syncAfterConnect();
|
||||||
}
|
}
|
||||||
} on Exception catch (e) {
|
} on Exception catch (e) {
|
||||||
_showMessage('Could not start device flow: $e');
|
_showCue(CueKind.error, 'Could not start device flow: $e');
|
||||||
} finally {
|
} finally {
|
||||||
auth.close();
|
auth.close();
|
||||||
}
|
}
|
||||||
@ -88,10 +97,10 @@ mixin _GitHubMirrorActions on State<GitHubMirrorScreen> {
|
|||||||
try {
|
try {
|
||||||
await runSync(await syncBackend(client));
|
await runSync(await syncBackend(client));
|
||||||
await SyncHealth.recordSuccess();
|
await SyncHealth.recordSuccess();
|
||||||
_showMessage('Connected and synced.');
|
_showCue(CueKind.ok, 'Connected and synced.');
|
||||||
} on Exception catch (e) {
|
} on Exception catch (e) {
|
||||||
await SyncHealth.recordFailure();
|
await SyncHealth.recordFailure();
|
||||||
_showMessage('Connected, but sync failed: $e');
|
_showCue(CueKind.error, 'Connected, but sync failed: $e');
|
||||||
} finally {
|
} finally {
|
||||||
client.close();
|
client.close();
|
||||||
}
|
}
|
||||||
@ -102,7 +111,7 @@ mixin _GitHubMirrorActions on State<GitHubMirrorScreen> {
|
|||||||
await _currentSettings().save();
|
await _currentSettings().save();
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
setState(() => _busy = false);
|
setState(() => _busy = false);
|
||||||
_showMessage('Saved.');
|
_showCue(CueKind.ok, 'Saved.');
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _testConnection() async {
|
Future<void> _testConnection() async {
|
||||||
@ -111,11 +120,13 @@ mixin _GitHubMirrorActions on State<GitHubMirrorScreen> {
|
|||||||
final client = createGitHubClient(settings, httpClient: widget.httpClient);
|
final client = createGitHubClient(settings, httpClient: widget.httpClient);
|
||||||
try {
|
try {
|
||||||
final ok = await client.canAccessRepo();
|
final ok = await client.canAccessRepo();
|
||||||
_showMessage(
|
if (ok) {
|
||||||
ok ? 'GitHub connection OK.' : 'GitHub connection failed.',
|
_showCue(CueKind.ok, 'GitHub connection OK.');
|
||||||
);
|
} else {
|
||||||
|
_showCue(CueKind.error, 'GitHub connection failed.');
|
||||||
|
}
|
||||||
} on Exception catch (e) {
|
} on Exception catch (e) {
|
||||||
_showMessage('GitHub connection failed: $e');
|
_showCue(CueKind.error, 'GitHub connection failed: $e');
|
||||||
} finally {
|
} finally {
|
||||||
client.close();
|
client.close();
|
||||||
if (mounted) setState(() => _busy = false);
|
if (mounted) setState(() => _busy = false);
|
||||||
@ -133,10 +144,10 @@ mixin _GitHubMirrorActions on State<GitHubMirrorScreen> {
|
|||||||
// *because* the banner told them syncing had stopped, so a successful
|
// *because* the banner told them syncing had stopped, so a successful
|
||||||
// run here must dismiss the warning it caused.
|
// run here must dismiss the warning it caused.
|
||||||
await SyncHealth.recordSuccess();
|
await SyncHealth.recordSuccess();
|
||||||
_showMessage('Synced.');
|
_showCue(CueKind.ok, 'Synced.');
|
||||||
} on Exception catch (e) {
|
} on Exception catch (e) {
|
||||||
await SyncHealth.recordFailure();
|
await SyncHealth.recordFailure();
|
||||||
_showMessage('Sync failed: $e');
|
_showCue(CueKind.error, 'Sync failed: $e');
|
||||||
} finally {
|
} finally {
|
||||||
client.close();
|
client.close();
|
||||||
if (mounted) setState(() => _busy = false);
|
if (mounted) setState(() => _busy = false);
|
||||||
|
|||||||
@ -8,15 +8,17 @@ library;
|
|||||||
|
|
||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart' show WaitWatch;
|
||||||
import 'package:diet_guard_app/services/firebase_client.dart';
|
import 'package:diet_guard_app/services/firebase_client.dart';
|
||||||
import 'package:diet_guard_app/services/github_client_factory.dart';
|
import 'package:diet_guard_app/services/github_client_factory.dart';
|
||||||
import 'package:diet_guard_app/services/sync_health.dart';
|
import 'package:diet_guard_app/services/sync_health.dart';
|
||||||
import 'package:diet_guard_app/services/sync_service.dart';
|
import 'package:diet_guard_app/services/sync_service.dart';
|
||||||
import 'package:diet_guard_app/services/sync_settings.dart';
|
import 'package:diet_guard_app/services/sync_settings.dart';
|
||||||
|
import 'package:diet_guard_app/ui/cues.dart';
|
||||||
import 'package:diet_guard_app/ui/theme.dart';
|
import 'package:diet_guard_app/ui/theme.dart';
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:github_device_auth/github_device_auth.dart';
|
import 'package:github_device_auth/github_device_auth.dart';
|
||||||
import 'package:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
part 'github_client_id_dialog.dart';
|
part 'github_client_id_dialog.dart';
|
||||||
part 'github_mirror_actions.dart';
|
part 'github_mirror_actions.dart';
|
||||||
@ -94,107 +96,87 @@ class _GitHubMirrorScreenState extends State<GitHubMirrorScreen>
|
|||||||
/// The token as loaded, so a platform that cannot display it (web) still
|
/// The token as loaded, so a platform that cannot display it (web) still
|
||||||
/// round-trips it instead of blanking it on the next save.
|
/// round-trips it instead of blanking it on the next save.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/// Runs the OAuth device flow and, on success, fills in the token field.
|
/// Runs the OAuth device flow and, on success, fills in the token field.
|
||||||
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
if (_loading) {
|
if (_loading) {
|
||||||
return const Scaffold(body: Center(child: CircularProgressIndicator()));
|
return const Scaffold(body: WaitWatch.centered('github_mirror.load'));
|
||||||
}
|
}
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(title: const Text('Advanced sync (GitHub)')),
|
// No title and no explanatory paragraph: the code glyph that opened this
|
||||||
// Centred and capped at the prose width -- see settings_screen.dart's
|
// screen names it, and the connect button is self-evident.
|
||||||
// note on why: on the desktop surface an uncapped ListView spanned the
|
appBar: AppBar(),
|
||||||
// full window, so explanatory paragraphs ran far past the readable
|
// Centred and capped at the prose width so fields do not span the
|
||||||
// line-length limit.
|
// whole window on the desktop surface.
|
||||||
body: Center(
|
body: Center(
|
||||||
child: ConstrainedBox(
|
child: ConstrainedBox(
|
||||||
constraints: const BoxConstraints(maxWidth: AppWidth.prose),
|
constraints: const BoxConstraints(maxWidth: AppWidth.prose),
|
||||||
child: ListView(
|
child: ListView(
|
||||||
padding: const EdgeInsets.all(16),
|
padding: const EdgeInsets.all(16),
|
||||||
children: [
|
children: [
|
||||||
Text(
|
|
||||||
'Syncs still mirror to GitHub until every device has moved '
|
|
||||||
'to Firebase. Authorize in your browser — no token to '
|
|
||||||
'paste.',
|
|
||||||
style: Theme.of(context).textTheme.bodySmall,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
Align(
|
Align(
|
||||||
alignment: Alignment.centerLeft,
|
alignment: Alignment.centerLeft,
|
||||||
child: FilledButton.icon(
|
child: IconButton.filled(
|
||||||
onPressed: _connectGitHub,
|
onPressed: _connectGitHub,
|
||||||
icon: const Icon(Icons.login),
|
icon: const Icon(
|
||||||
label: const Text('Connect GitHub'),
|
Icons.login,
|
||||||
|
semanticLabel: 'Connect GitHub',
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
TextField(
|
IconField(
|
||||||
|
icon: Icons.person_outline,
|
||||||
|
semanticLabel: 'GitHub owner',
|
||||||
controller: _ownerController,
|
controller: _ownerController,
|
||||||
decoration: const InputDecoration(labelText: 'GitHub owner'),
|
|
||||||
),
|
),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
TextField(
|
IconField(
|
||||||
|
icon: Icons.folder_outlined,
|
||||||
|
semanticLabel: 'Repo',
|
||||||
controller: _repoController,
|
controller: _repoController,
|
||||||
decoration: const InputDecoration(labelText: 'Repo'),
|
|
||||||
),
|
),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
TextField(
|
IconField(
|
||||||
|
icon: Icons.apps,
|
||||||
|
semanticLabel: 'OAuth App client id',
|
||||||
controller: _clientIdController,
|
controller: _clientIdController,
|
||||||
decoration: const InputDecoration(
|
|
||||||
labelText: 'OAuth App client id',
|
|
||||||
helperText: 'Needed for the Connect GitHub button',
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
TextField(
|
IconField(
|
||||||
|
icon: Icons.key,
|
||||||
|
semanticLabel: 'Personal access token (fallback)',
|
||||||
controller: _tokenController,
|
controller: _tokenController,
|
||||||
obscureText: true,
|
obscure: true,
|
||||||
decoration: InputDecoration(
|
|
||||||
labelText: 'Personal access token (fallback)',
|
|
||||||
// Both wrapper hints are web-only; a VM test always takes
|
|
||||||
// the null branch.
|
|
||||||
// coverage:ignore-start
|
|
||||||
helperText: SyncSettings.exposesTokenValue
|
|
||||||
? null
|
|
||||||
: _storedToken.isEmpty
|
|
||||||
? 'Stored by the desktop wrapper, never by the browser'
|
|
||||||
: 'A token is stored by the desktop wrapper; type '
|
|
||||||
'here only to replace it',
|
|
||||||
// coverage:ignore-end
|
|
||||||
helperMaxLines: 2,
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
Wrap(
|
Wrap(
|
||||||
spacing: 8,
|
spacing: 8,
|
||||||
children: [
|
children: [
|
||||||
ElevatedButton(
|
IconButton.filled(
|
||||||
onPressed: _busy ? null : _save,
|
onPressed: _busy ? null : _save,
|
||||||
child: const Text('Save'),
|
icon: const Icon(Icons.check, semanticLabel: 'Save'),
|
||||||
),
|
),
|
||||||
OutlinedButton(
|
// Tests the GitHub connection only (a canAccessRepo call);
|
||||||
|
// it says nothing about Firebase.
|
||||||
|
IconButton.outlined(
|
||||||
onPressed: _busy ? null : _testConnection,
|
onPressed: _busy ? null : _testConnection,
|
||||||
// Named for what it actually does: _testConnection builds
|
tooltip: 'Test',
|
||||||
// a GitHub client and calls canAccessRepo(). It says
|
icon: const Icon(
|
||||||
// nothing about Firebase, and the bare label implied
|
Icons.network_check,
|
||||||
// otherwise.
|
semanticLabel: 'Test GitHub connection',
|
||||||
child: const Text('Test GitHub connection'),
|
|
||||||
),
|
),
|
||||||
ElevatedButton(
|
),
|
||||||
|
IconButton.filled(
|
||||||
onPressed: _busy ? null : _syncNow,
|
onPressed: _busy ? null : _syncNow,
|
||||||
child: const Text('Sync now'),
|
icon: const Icon(Icons.sync, semanticLabel: 'Sync now'),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
if (_status != null) ...[
|
if (_status != null) ...[
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
Text(_status!, style: Theme.of(context).textTheme.bodyMedium),
|
Align(alignment: Alignment.centerLeft, child: _status),
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
|
|||||||
@ -7,6 +7,7 @@ library;
|
|||||||
|
|
||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart' show WaitWatch;
|
||||||
import 'package:diet_guard_app/models/food_entry.dart';
|
import 'package:diet_guard_app/models/food_entry.dart';
|
||||||
import 'package:diet_guard_app/screens/edit_entry_screen.dart';
|
import 'package:diet_guard_app/screens/edit_entry_screen.dart';
|
||||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
@ -14,7 +15,7 @@ import 'package:diet_guard_app/widgets/history/history_filter.dart';
|
|||||||
import 'package:diet_guard_app/widgets/history/history_filter_sheet.dart';
|
import 'package:diet_guard_app/widgets/history/history_filter_sheet.dart';
|
||||||
import 'package:diet_guard_app/widgets/history/history_grouping.dart';
|
import 'package:diet_guard_app/widgets/history/history_grouping.dart';
|
||||||
import 'package:diet_guard_app/widgets/history/history_list.dart';
|
import 'package:diet_guard_app/widgets/history/history_list.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// Logged meal history: every entry, grouped by day, filterable and sortable.
|
/// Logged meal history: every entry, grouped by day, filterable and sortable.
|
||||||
///
|
///
|
||||||
@ -159,15 +160,16 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
|||||||
final allEntries = _allEntries;
|
final allEntries = _allEntries;
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(
|
appBar: AppBar(
|
||||||
title: const Text('History'),
|
|
||||||
actions: [
|
actions: [
|
||||||
if (allEntries != null)
|
if (allEntries != null)
|
||||||
Stack(
|
Stack(
|
||||||
alignment: Alignment.center,
|
alignment: Alignment.center,
|
||||||
children: [
|
children: [
|
||||||
IconButton(
|
IconButton(
|
||||||
icon: const Icon(Icons.filter_list),
|
icon: const Icon(
|
||||||
tooltip: 'Filter & sort',
|
Icons.filter_list,
|
||||||
|
semanticLabel: 'Filter & sort',
|
||||||
|
),
|
||||||
onPressed: _openFilterSheet,
|
onPressed: _openFilterSheet,
|
||||||
),
|
),
|
||||||
if (_filter.isActive)
|
if (_filter.isActive)
|
||||||
@ -188,11 +190,14 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
|||||||
],
|
],
|
||||||
),
|
),
|
||||||
body: allEntries == null
|
body: allEntries == null
|
||||||
? const Center(child: CircularProgressIndicator())
|
? const WaitWatch.centered('history.load')
|
||||||
: _displayed.isEmpty
|
: _displayed.isEmpty
|
||||||
? Center(
|
? Center(
|
||||||
child: Text(
|
child: Icon(
|
||||||
allEntries.isEmpty
|
allEntries.isEmpty ? Icons.restaurant : Icons.filter_list_off,
|
||||||
|
size: 64,
|
||||||
|
color: Theme.of(context).colorScheme.outline,
|
||||||
|
semanticLabel: allEntries.isEmpty
|
||||||
? 'Nothing logged yet.'
|
? 'Nothing logged yet.'
|
||||||
: 'No entries match the current filter.',
|
: 'No entries match the current filter.',
|
||||||
),
|
),
|
||||||
|
|||||||
@ -1,7 +1,20 @@
|
|||||||
|
import 'package:diet_guard_app/models/food_suggestion.dart';
|
||||||
import 'package:diet_guard_app/models/nutrition.dart';
|
import 'package:diet_guard_app/models/nutrition.dart';
|
||||||
import 'package:diet_guard_app/screens/log_meal_progress.dart';
|
import 'package:diet_guard_app/screens/log_meal_progress.dart';
|
||||||
import 'package:diet_guard_app/widgets/macro_input_row.dart';
|
import 'package:diet_guard_app/widgets/macro_input_row.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
/// Writes [suggestion]'s name and macros into the log form's controllers.
|
||||||
|
///
|
||||||
|
/// Split out of `log_meal_screen.dart` for the repo's 250-line cap.
|
||||||
|
void fillControllersFromSuggestion(
|
||||||
|
FoodSuggestion suggestion,
|
||||||
|
TextEditingController desc,
|
||||||
|
MacroControllers macros,
|
||||||
|
) {
|
||||||
|
desc.text = suggestion.name;
|
||||||
|
macros.fillFrom(suggestion.nutrition);
|
||||||
|
}
|
||||||
|
|
||||||
/// Builds the [Nutrition] for a submit from the form's macro controllers.
|
/// Builds the [Nutrition] for a submit from the form's macro controllers.
|
||||||
///
|
///
|
||||||
@ -18,7 +31,8 @@ Nutrition nutritionFromControllers(MacroControllers macros, String source) =>
|
|||||||
source: source,
|
source: source,
|
||||||
);
|
);
|
||||||
|
|
||||||
/// The four destination buttons in [LogMealScreen]'s app bar.
|
/// The destination buttons in [LogMealScreen]'s app bar, after [leading]
|
||||||
|
/// (the date picker).
|
||||||
///
|
///
|
||||||
/// Split out of `log_meal_screen.dart` for the repo's 250-line cap. Returned
|
/// Split out of `log_meal_screen.dart` for the repo's 250-line cap. Returned
|
||||||
/// as a list to be spread into `AppBar.actions`, so the bar's structure and
|
/// as a list to be spread into `AppBar.actions`, so the bar's structure and
|
||||||
@ -28,25 +42,33 @@ List<Widget> logMealAppBarActions({
|
|||||||
required VoidCallback onHistory,
|
required VoidCallback onHistory,
|
||||||
required VoidCallback onCalendar,
|
required VoidCallback onCalendar,
|
||||||
required VoidCallback onSettings,
|
required VoidCallback onSettings,
|
||||||
|
required VoidCallback onBody,
|
||||||
|
List<Widget> leading = const [],
|
||||||
}) => [
|
}) => [
|
||||||
|
...leading,
|
||||||
IconButton(
|
IconButton(
|
||||||
icon: const Icon(Icons.restaurant_menu),
|
tooltip: 'Body',
|
||||||
tooltip: 'Food bank',
|
icon: const Icon(Icons.monitor_weight, semanticLabel: 'Body'),
|
||||||
|
onPressed: onBody,
|
||||||
|
),
|
||||||
|
IconButton(
|
||||||
|
tooltip: 'Foods',
|
||||||
|
icon: const Icon(Icons.restaurant_menu, semanticLabel: 'Food bank'),
|
||||||
onPressed: onFoodBank,
|
onPressed: onFoodBank,
|
||||||
),
|
),
|
||||||
IconButton(
|
IconButton(
|
||||||
icon: const Icon(Icons.history),
|
|
||||||
tooltip: 'History',
|
tooltip: 'History',
|
||||||
|
icon: const Icon(Icons.history, semanticLabel: 'History'),
|
||||||
onPressed: onHistory,
|
onPressed: onHistory,
|
||||||
),
|
),
|
||||||
IconButton(
|
IconButton(
|
||||||
icon: const Icon(Icons.calendar_month),
|
|
||||||
tooltip: 'Calendar',
|
tooltip: 'Calendar',
|
||||||
|
icon: const Icon(Icons.calendar_month, semanticLabel: 'Calendar'),
|
||||||
onPressed: onCalendar,
|
onPressed: onCalendar,
|
||||||
),
|
),
|
||||||
IconButton(
|
IconButton(
|
||||||
icon: const Icon(Icons.settings),
|
tooltip: 'Sync',
|
||||||
tooltip: 'Sync settings',
|
icon: const Icon(Icons.settings, semanticLabel: 'Sync settings'),
|
||||||
onPressed: onSettings,
|
onPressed: onSettings,
|
||||||
),
|
),
|
||||||
];
|
];
|
||||||
|
|||||||
137
app/lib/screens/log_meal_claude_mixin.dart
Normal file
@ -0,0 +1,137 @@
|
|||||||
|
/// The sparkle button: send the typed text and/or photo to Claude.
|
||||||
|
///
|
||||||
|
/// Its own file because `log_meal_screen.dart` is at the repo's 250-line
|
||||||
|
/// ceiling. The transport is behind [ClaudeRelayClient]; this only drives the
|
||||||
|
/// button's states and shows the meal Claude logged.
|
||||||
|
///
|
||||||
|
/// The photo lives in [photo] for one send and nowhere else.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_due_mixin.dart';
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_future_mixin.dart';
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_logged_mixin.dart';
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_sync_mixin.dart';
|
||||||
|
import 'package:diet_guard_app/services/claude_relay_client.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_entry_lookup.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
|
import 'package:diet_guard_app/services/meal_photo_source.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/logged_meal_row.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/macro_input_row.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/meal_action_row.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
/// Photo attach and the Claude send, for the log screen's state.
|
||||||
|
mixin LogMealClaudeMixin<T extends StatefulWidget>
|
||||||
|
on
|
||||||
|
LogMealSyncMixin<T>,
|
||||||
|
LogMealDueMixin<T>,
|
||||||
|
LogMealLoggedMixin<T>,
|
||||||
|
LogMealFutureMixin<T> {
|
||||||
|
/// The relay this screen sends through. Supplied by the screen.
|
||||||
|
ClaudeRelayClient get relay;
|
||||||
|
|
||||||
|
/// Where photos come from. Supplied by the screen.
|
||||||
|
MealPhotoSource get photoSource;
|
||||||
|
|
||||||
|
/// The food field. Supplied by the screen.
|
||||||
|
TextEditingController get claudeDesc;
|
||||||
|
|
||||||
|
/// The macro fields. Supplied by the screen.
|
||||||
|
MacroControllers get claudeMacros;
|
||||||
|
|
||||||
|
/// The sparkle button's state.
|
||||||
|
ClaudeButtonState claudeState = ClaudeButtonState.idle;
|
||||||
|
|
||||||
|
/// The attached photo's JPEG bytes, or null. Never stored or synced.
|
||||||
|
Uint8List? photo;
|
||||||
|
|
||||||
|
StreamSubscription<ClaudeRelayEvent>? _relaySub;
|
||||||
|
String? _pendingRid;
|
||||||
|
|
||||||
|
/// Whether there is something to send (a description or a photo).
|
||||||
|
bool get canSend =>
|
||||||
|
futureDate == null &&
|
||||||
|
(claudeDesc.text.trim().isNotEmpty || photo != null);
|
||||||
|
|
||||||
|
/// Attaches a photo from [origin]; backing out keeps the current one.
|
||||||
|
Future<void> attachPhoto(PhotoOrigin origin) async {
|
||||||
|
final bytes = await photoSource.pick(origin);
|
||||||
|
if (!mounted || bytes == null) return;
|
||||||
|
setState(() => photo = bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drops the attached photo.
|
||||||
|
void removePhoto() => setState(() => photo = null);
|
||||||
|
|
||||||
|
/// Sends the form to Claude and follows the request's events.
|
||||||
|
void sendToClaude() {
|
||||||
|
if (!canSend) return;
|
||||||
|
final request = ClaudeRelayRequest(
|
||||||
|
requestId: newRequestId(),
|
||||||
|
slotMinute: targetSlot,
|
||||||
|
mode: dueMode ? ClaudeRelayMode.due : ClaudeRelayMode.normal,
|
||||||
|
text: claudeDesc.text.trim(),
|
||||||
|
photoJpeg: photo,
|
||||||
|
);
|
||||||
|
unawaited(_relaySub?.cancel());
|
||||||
|
_pendingRid = request.requestId;
|
||||||
|
setState(() => claudeState = ClaudeButtonState.sending);
|
||||||
|
_relaySub = relay.send(request).listen((e) => unawaited(_onEvent(e)));
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _onEvent(ClaudeRelayEvent event) async {
|
||||||
|
if (!mounted) return;
|
||||||
|
switch (event) {
|
||||||
|
case ClaudeRelayQueued():
|
||||||
|
setState(() => claudeState = ClaudeButtonState.queued);
|
||||||
|
case ClaudeRelayLocked():
|
||||||
|
_pendingRid = null;
|
||||||
|
setState(() => claudeState = ClaudeButtonState.locked);
|
||||||
|
case ClaudeRelayFailed():
|
||||||
|
_pendingRid = null;
|
||||||
|
setState(() => claudeState = ClaudeButtonState.error);
|
||||||
|
case ClaudeRelayLogged(:final entry):
|
||||||
|
_pendingRid = null;
|
||||||
|
// The worker logged it under the request id; the sync would deliver
|
||||||
|
// the same record, so this only shows it now and never doubles it.
|
||||||
|
final stored = await LogStorageService.instance.addIfAbsent(entry);
|
||||||
|
if (!mounted) return;
|
||||||
|
claudeDesc.clear();
|
||||||
|
claudeMacros.clear();
|
||||||
|
setState(() {
|
||||||
|
claudeState = ClaudeButtonState.idle;
|
||||||
|
photo = null;
|
||||||
|
});
|
||||||
|
showLogged([LoggedMeal(stored, LoggedOrigin.claude)]);
|
||||||
|
await publishAfterLog();
|
||||||
|
await refreshSlots();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Withdraws a request that is still in flight or queued, because the user
|
||||||
|
/// just logged the meal here instead.
|
||||||
|
///
|
||||||
|
/// Unclaimed: the node is deleted and the stream dropped. Already claimed
|
||||||
|
/// (the PC is mid-estimate): the meal will be logged, so the stream stays
|
||||||
|
/// open and its row shows with an undo rather than the entry turning up
|
||||||
|
/// unseen after the next sync. That race is accepted, see
|
||||||
|
/// `docs/DOCS-claude-relay.md`.
|
||||||
|
Future<void> withdrawClaude() async {
|
||||||
|
final rid = _pendingRid;
|
||||||
|
final waiting =
|
||||||
|
claudeState == ClaudeButtonState.sending ||
|
||||||
|
claudeState == ClaudeButtonState.queued;
|
||||||
|
if (rid == null || !waiting) return;
|
||||||
|
if (await relay.cancel(rid)) {
|
||||||
|
_pendingRid = null;
|
||||||
|
await _relaySub?.cancel();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cancels the event subscription; call from `dispose`. A request still
|
||||||
|
/// queued on the PC reaches this phone through sync instead.
|
||||||
|
void disposeClaude() => unawaited(_relaySub?.cancel());
|
||||||
|
}
|
||||||
89
app/lib/screens/log_meal_due_mixin.dart
Normal file
@ -0,0 +1,89 @@
|
|||||||
|
/// Due mode: some slot has elapsed with nothing logged.
|
||||||
|
///
|
||||||
|
/// The log screen then strips everything that is not "log this meal now" (the
|
||||||
|
/// app bar, sync banner, date row), hides the Android status bar, and targets
|
||||||
|
/// the oldest due slot with both the check and the sparkle. Its own file
|
||||||
|
/// because `log_meal_screen.dart` is at the repo's 250-line ceiling.
|
||||||
|
///
|
||||||
|
/// Slot arithmetic is not touched here: due slots come from `missingSlots`
|
||||||
|
/// and the nearest-slot rule from `slotForLog`, both in `models/slot.dart`.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/models/slot.dart';
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_sync_mixin.dart';
|
||||||
|
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
/// The clock the log screen reads for "which slots are due".
|
||||||
|
///
|
||||||
|
/// A hook rather than a constructor argument so the whole screen suite can pin
|
||||||
|
/// it once (`flutter_test_config.dart` pins 07:00, before the first slot);
|
||||||
|
/// otherwise every nav and slot test would pass at night and fail by day, once
|
||||||
|
/// due mode hides the app bar.
|
||||||
|
@visibleForTesting
|
||||||
|
DateTime Function() logMealClock = DateTime.now;
|
||||||
|
|
||||||
|
/// Shows or hides the Android status bar.
|
||||||
|
///
|
||||||
|
/// `main.dart` sets no system-UI mode, so "visible" is the platform default:
|
||||||
|
/// both bars shown. [hidden] true is sticky-immersive; false puts both back.
|
||||||
|
@visibleForTesting
|
||||||
|
Future<void> Function({required bool hidden}) setStatusBarHidden = _setBars;
|
||||||
|
|
||||||
|
Future<void> _setBars({required bool hidden}) => hidden
|
||||||
|
? SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky)
|
||||||
|
: SystemChrome.setEnabledSystemUIMode(
|
||||||
|
SystemUiMode.manual,
|
||||||
|
overlays: SystemUiOverlay.values,
|
||||||
|
);
|
||||||
|
|
||||||
|
/// Due-mode state and slot targeting for the log screen's state.
|
||||||
|
mixin LogMealDueMixin<T extends StatefulWidget> on LogMealSyncMixin<T> {
|
||||||
|
/// Whether the first read of today's log has finished. Until then the
|
||||||
|
/// screen draws neither mode, so it never flashes the app bar and drops it.
|
||||||
|
bool slotsLoaded = false;
|
||||||
|
|
||||||
|
bool _statusBarHidden = false;
|
||||||
|
|
||||||
|
/// What the screen reads as "now" (see [logMealClock]).
|
||||||
|
DateTime get screenNow => logMealClock();
|
||||||
|
|
||||||
|
/// Elapsed slots with nothing logged, oldest first.
|
||||||
|
List<int> get dueSlots =>
|
||||||
|
missingSlots(screenNow, loggedSlots, MealScheduleService.current);
|
||||||
|
|
||||||
|
/// Whether the screen is in due mode.
|
||||||
|
bool get dueMode => slotsLoaded && dueSlots.isNotEmpty;
|
||||||
|
|
||||||
|
/// The slot a log or a send lands in: the oldest due slot, else the slot
|
||||||
|
/// nearest [screenNow] (`slotForLog`).
|
||||||
|
int get targetSlot => dueSlots.isNotEmpty
|
||||||
|
? dueSlots.first
|
||||||
|
: slotForLog(screenNow, MealScheduleService.current);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> refreshSlots() async {
|
||||||
|
await super.refreshSlots();
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() => slotsLoaded = true);
|
||||||
|
await syncStatusBar();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hides the status bar while in due mode and restores it on exit.
|
||||||
|
Future<void> syncStatusBar() async {
|
||||||
|
final hide = dueMode;
|
||||||
|
if (hide == _statusBarHidden) return;
|
||||||
|
_statusBarHidden = hide;
|
||||||
|
await setStatusBarHidden(hidden: hide);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Puts the status bar back; call from `dispose`.
|
||||||
|
void restoreStatusBar() {
|
||||||
|
if (!_statusBarHidden) return;
|
||||||
|
_statusBarHidden = false;
|
||||||
|
unawaited(setStatusBarHidden(hidden: false));
|
||||||
|
}
|
||||||
|
}
|
||||||
169
app/lib/screens/log_meal_future_mixin.dart
Normal file
@ -0,0 +1,169 @@
|
|||||||
|
/// Lets the user pre-log a meal against a future date + slot instead of now.
|
||||||
|
///
|
||||||
|
/// Its own file because `log_meal_screen.dart` is at the repo's 250-line cap.
|
||||||
|
///
|
||||||
|
/// Scoped to dates strictly after today: the date picker's `firstDate` is
|
||||||
|
/// tomorrow.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/models/food_entry.dart';
|
||||||
|
import 'package:diet_guard_app/models/local_time.dart';
|
||||||
|
import 'package:diet_guard_app/models/meal_schedule.dart';
|
||||||
|
import 'package:diet_guard_app/models/slot.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
|
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/pickers/pickers.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/slot_selector_row.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
/// Adds a future-date meal-log picker to [LogMealScreen]'s state.
|
||||||
|
mixin LogMealFutureMixin<T extends StatefulWidget> on State<T> {
|
||||||
|
DateTime? _futureDate;
|
||||||
|
int? _futureSlot;
|
||||||
|
Set<int> _futureLoggedSlots = {};
|
||||||
|
MealSchedule? _futureSchedule;
|
||||||
|
|
||||||
|
/// The date currently chosen for a future log, or null when logging for
|
||||||
|
/// today through the screen's normal flow.
|
||||||
|
DateTime? get futureDate => _futureDate;
|
||||||
|
|
||||||
|
/// The slot chosen for [futureDate], or null until one is picked.
|
||||||
|
int? get futureSlot => _futureSlot;
|
||||||
|
|
||||||
|
/// Called after the picked date changes (including back to today), for
|
||||||
|
/// state keyed to the old date to drop itself. No-op unless overridden.
|
||||||
|
void onLogDateChanged() {}
|
||||||
|
|
||||||
|
/// Clears back to "log for today", dropping the picked date and slot.
|
||||||
|
void resetFutureLog() {
|
||||||
|
setState(() {
|
||||||
|
_futureDate = null;
|
||||||
|
_futureSlot = null;
|
||||||
|
_futureLoggedSlots = {};
|
||||||
|
_futureSchedule = null;
|
||||||
|
});
|
||||||
|
onLogDateChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _pickFutureDate() async {
|
||||||
|
final today = DateTime.now();
|
||||||
|
final tomorrow = DateTime(today.year, today.month, today.day + 1);
|
||||||
|
final picked = await pickDate(
|
||||||
|
context: context,
|
||||||
|
firstDate: tomorrow,
|
||||||
|
lastDate: tomorrow.add(const Duration(days: 365)),
|
||||||
|
initialDate: _futureDate ?? tomorrow,
|
||||||
|
);
|
||||||
|
if (picked == null || !mounted) return;
|
||||||
|
await selectLogDate(picked);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Switches the form to log against [picked] (strictly after today): what
|
||||||
|
/// the date picker does once a date is chosen.
|
||||||
|
Future<void> selectLogDate(DateTime picked) async {
|
||||||
|
final log = await LogStorageService.instance.readLog();
|
||||||
|
if (!mounted) return;
|
||||||
|
final day = localDateKey(picked);
|
||||||
|
final schedule = MealScheduleService.history.forDay(day);
|
||||||
|
// Snapped against the schedule for *that* day, the same rule as
|
||||||
|
// `loggedSlotsToday`: an exact match would show a pre-logged meal's slot
|
||||||
|
// as open again after a schedule edit, inviting a duplicate.
|
||||||
|
final logged = satisfiedSlots([
|
||||||
|
for (final entry in log[day] ?? const <FoodEntry>[])
|
||||||
|
if (!entry.deleted) ?entry.slotMinute,
|
||||||
|
], schedule);
|
||||||
|
setState(() {
|
||||||
|
_futureDate = picked;
|
||||||
|
_futureSchedule = schedule;
|
||||||
|
_futureLoggedSlots = logged;
|
||||||
|
_futureSlot = null;
|
||||||
|
});
|
||||||
|
onLogDateChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The app bar's date actions: the picker (leftmost icon) and, once a date
|
||||||
|
/// is picked, a way back to today. A picked date tints the picker gold with
|
||||||
|
/// a small dot; no text is painted.
|
||||||
|
List<Widget> buildDateActions(BuildContext context) {
|
||||||
|
final date = _futureDate;
|
||||||
|
final gold = Theme.of(context).colorScheme.primary;
|
||||||
|
return [
|
||||||
|
IconButton(
|
||||||
|
// Not Icons.calendar_month: the bar's own "Calendar" nav button uses
|
||||||
|
// that, and two on screen make `find.byIcon` ambiguous.
|
||||||
|
icon: Stack(
|
||||||
|
clipBehavior: Clip.none,
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
Icons.edit_calendar,
|
||||||
|
color: date == null ? null : gold,
|
||||||
|
semanticLabel: date == null ? 'Log for later' : 'Change date',
|
||||||
|
),
|
||||||
|
if (date != null)
|
||||||
|
Positioned(
|
||||||
|
top: -1,
|
||||||
|
right: -1,
|
||||||
|
child: Container(
|
||||||
|
key: const ValueKey('log-date-badge'),
|
||||||
|
width: 8,
|
||||||
|
height: 8,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: gold,
|
||||||
|
shape: BoxShape.circle,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
onPressed: _pickFutureDate,
|
||||||
|
),
|
||||||
|
if (date != null)
|
||||||
|
IconButton(
|
||||||
|
icon: const Icon(Icons.close, semanticLabel: 'Back to today'),
|
||||||
|
onPressed: resetFutureLog,
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The slot row for a picked future date, else nothing.
|
||||||
|
///
|
||||||
|
/// Today has no slot row any more: the screen derives today's slot (the
|
||||||
|
/// oldest due one, else the nearest). A *future* date has no due slots to
|
||||||
|
/// derive from, so the row survives for exactly that case.
|
||||||
|
Widget buildSlotRow() {
|
||||||
|
final date = _futureDate;
|
||||||
|
if (date == null) return const SizedBox.shrink();
|
||||||
|
return SlotSelectorRow(
|
||||||
|
now: DateTime(date.year, date.month, date.day),
|
||||||
|
schedule: _futureSchedule,
|
||||||
|
loggedSlots: _futureLoggedSlots,
|
||||||
|
selectedSlot: _futureSlot,
|
||||||
|
onSlotSelected: (slot) => setState(() => _futureSlot = slot),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolves the slot/time to log against: the future pick when one is
|
||||||
|
/// active, otherwise [todaySlot] for now. `error` is set instead when a
|
||||||
|
/// future date is chosen but no slot on it has been picked yet.
|
||||||
|
({String? error, int? slot, DateTime? when}) resolveLogTarget(
|
||||||
|
int? todaySlot,
|
||||||
|
) {
|
||||||
|
final date = _futureDate;
|
||||||
|
if (date == null) return (error: null, slot: todaySlot, when: null);
|
||||||
|
final slot = _futureSlot;
|
||||||
|
if (slot == null) {
|
||||||
|
return (
|
||||||
|
error: 'Pick a slot for that date first.',
|
||||||
|
slot: null,
|
||||||
|
when: null,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
error: null,
|
||||||
|
slot: slot,
|
||||||
|
// The slot is a minute of day, not an hour: passing it as the hour
|
||||||
|
// argument would roll 720 (12:00) forward a whole month.
|
||||||
|
when: DateTime(date.year, date.month, date.day, slot ~/ 60, slot % 60),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1,235 +0,0 @@
|
|||||||
/// Offers the day's delivered catering dishes to the log form.
|
|
||||||
///
|
|
||||||
/// Its own file because `log_meal_screen.dart` is at the repo's 250-line
|
|
||||||
/// ceiling.
|
|
||||||
///
|
|
||||||
/// **A delivered meal is not an eaten meal.** This only ever *prefills* the
|
|
||||||
/// form -- the user still taps "Log" for each dish. Nothing here writes a log
|
|
||||||
/// entry, and nothing here may start doing so: the gate would then satisfy its
|
|
||||||
/// own checkpoint from a delivery note, and the log would record what the
|
|
||||||
/// courier dropped off rather than what was eaten.
|
|
||||||
///
|
|
||||||
/// [prefillNextDish] is called from **two** places: once when the delivery
|
|
||||||
/// first arrives, and again after every successful submit. That second caller
|
|
||||||
/// is the load-bearing one. On the PC it briefly did not exist, which made the
|
|
||||||
/// "(N more to go)" promise a dead letter -- every dish after the first stayed
|
|
||||||
/// queued behind another click. `kuchnia_queue_test.dart` asserts the state
|
|
||||||
/// transition rather than "a dish was offered", because the latter passes
|
|
||||||
/// while this misbehaves.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:diet_guard_app/models/kuchnia_dish.dart';
|
|
||||||
import 'package:diet_guard_app/models/slot.dart';
|
|
||||||
import 'package:diet_guard_app/services/kuchnia_import.dart';
|
|
||||||
import 'package:diet_guard_app/services/kuchnia_queue.dart';
|
|
||||||
import 'package:diet_guard_app/services/kuchnia_spread.dart';
|
|
||||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
|
||||||
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
|
||||||
import 'package:diet_guard_app/widgets/macro_input_row.dart';
|
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
|
|
||||||
/// Writes [dish]'s name and macros into the log form's controllers.
|
|
||||||
///
|
|
||||||
/// Free function rather than a mixin method so the numeric formatting is
|
|
||||||
/// testable without pumping a widget.
|
|
||||||
///
|
|
||||||
/// Clears every macro field first, mirroring `_gatelock_delivery.py`'s
|
|
||||||
/// `self._clear_inputs()`. Dropping that step is what corrupted a real log
|
|
||||||
/// entry on 2026-08-23: a dish carries *per-portion* macros and leaves
|
|
||||||
/// [MacroControllers.perGrams] untouched, so a `100` left behind by an
|
|
||||||
/// earlier food-bank pick made `nutritionForPortion` read them as *per-100g*
|
|
||||||
/// and scale them by `grams / 100` -- 472 kcal logged as 1217.8.
|
|
||||||
///
|
|
||||||
/// The clear is a single call covering all six controllers rather than a
|
|
||||||
/// `perGrams.clear()` line here, so a seventh field added later cannot be
|
|
||||||
/// forgotten at this call site; `MacroControllers.clear()` is enumerated by
|
|
||||||
/// its own test.
|
|
||||||
void fillControllersFromDish(
|
|
||||||
KuchniaDish dish,
|
|
||||||
TextEditingController desc,
|
|
||||||
MacroControllers macros,
|
|
||||||
) {
|
|
||||||
macros.clear();
|
|
||||||
desc.text = dish.name;
|
|
||||||
final (grams, values) = dishFieldValues(dish);
|
|
||||||
macros.kcal.text = values.$1;
|
|
||||||
macros.protein.text = values.$2;
|
|
||||||
macros.carbs.text = values.$3;
|
|
||||||
macros.fat.text = values.$4;
|
|
||||||
macros.grams.text = grams;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Wires the catering queue into a log form.
|
|
||||||
mixin LogMealKuchniaMixin<T extends StatefulWidget> on State<T> {
|
|
||||||
/// The dish currently prefilled from the delivery, if any.
|
|
||||||
KuchniaDish? offeredDish;
|
|
||||||
|
|
||||||
/// How many delivered dishes still need logging, including the offered one.
|
|
||||||
///
|
|
||||||
/// The offered dish counts: it is prefilled, not logged, and the user has
|
|
||||||
/// still to tap for it. Excluding it made the line read "0 more" while a
|
|
||||||
/// real dish sat in the form.
|
|
||||||
int get dishesStillQueued => KuchniaQueueService.remaining;
|
|
||||||
|
|
||||||
/// The form's description field. Supplied by the screen.
|
|
||||||
TextEditingController get descController;
|
|
||||||
|
|
||||||
/// The form's macro fields. Supplied by the screen.
|
|
||||||
MacroControllers get macroControllers;
|
|
||||||
|
|
||||||
/// Called after the form is filled, so the screen can mark the source.
|
|
||||||
void onDishPrefilled() {}
|
|
||||||
|
|
||||||
/// Fills the form's fields from [dish].
|
|
||||||
///
|
|
||||||
/// Concrete here rather than an abstract hook: every implementation would be
|
|
||||||
/// the same three lines, and the screen file has no budget to spare.
|
|
||||||
void fillFormFromDish(KuchniaDish dish) {
|
|
||||||
fillControllersFromDish(dish, descController, macroControllers);
|
|
||||||
onDishPrefilled();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Loads today's delivery, guarded so it costs at most one walk per day.
|
|
||||||
///
|
|
||||||
/// Goes through [KuchniaQueueService.refreshOnce] rather than
|
|
||||||
/// `refreshDelivery`: this is an *automatic* trigger and can fire after
|
|
||||||
/// every meal, and each unguarded refresh is a login plus three requests
|
|
||||||
/// against a third party. The settings button is the explicit ask that
|
|
||||||
/// always goes and looks.
|
|
||||||
Future<void> loadDeliveryOnce({Set<String> alreadyLogged = const {}}) async {
|
|
||||||
if (!KuchniaQueueService.isInitialized) return;
|
|
||||||
final result = await KuchniaQueueService.refreshOnce(DateTime.now());
|
|
||||||
if (!mounted || result.dishes.isEmpty) return;
|
|
||||||
// Ordered by the caterer's own meal priority, against the *user's*
|
|
||||||
// schedule -- not a hardcoded four slots. A dish offered for a slot the
|
|
||||||
// user's schedule does not have is a checkpoint that can never be met.
|
|
||||||
final ordered = dishesInSlotOrder(
|
|
||||||
result.dishes,
|
|
||||||
daySlots(MealScheduleService.current),
|
|
||||||
);
|
|
||||||
KuchniaQueueService.instance.offer(ordered, alreadyLogged: alreadyLogged);
|
|
||||||
prefillNextDish();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Loads today's delivery, skipping dishes already logged today.
|
|
||||||
///
|
|
||||||
/// The skip matters across devices: a dish logged on the PC must not be
|
|
||||||
/// offered again here, and the food log is the only record of that.
|
|
||||||
Future<void> loadTodaysDelivery() async {
|
|
||||||
final logged = await LogStorageService.instance.todayEntries();
|
|
||||||
if (!mounted) return;
|
|
||||||
await loadDeliveryOnce(
|
|
||||||
alreadyLogged: {
|
|
||||||
for (final entry in logged) entry.desc.trim().toLowerCase(),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Loads today's delivery on an **explicit** user tap, unguarded.
|
|
||||||
///
|
|
||||||
/// Deliberately [refreshDelivery], not [KuchniaQueueService.refreshOnce]:
|
|
||||||
/// per `docs/kuchnia-wikinga.md`'s Triggers table, a user who asks gets a
|
|
||||||
/// look, the same as the CLI and the settings button. The guard exists to
|
|
||||||
/// rate-limit *automatic* triggers, and applying it here would make the
|
|
||||||
/// button silently do nothing for the rest of the day after the startup
|
|
||||||
/// load — the failure that has nothing to tap in the kitchen.
|
|
||||||
///
|
|
||||||
/// Still skips dishes already logged today (a dish logged on the PC must
|
|
||||||
/// not be re-offered) and still records the fetch, so a successful tap
|
|
||||||
/// also spares the automatic path a second walk.
|
|
||||||
///
|
|
||||||
/// Returns a line to show the user, or null when a dish was prefilled and
|
|
||||||
/// the form speaks for itself.
|
|
||||||
Future<String?> loadDeliveryOnTap() async {
|
|
||||||
if (!KuchniaQueueService.isInitialized) return 'Catering is not ready yet.';
|
|
||||||
final logged = await LogStorageService.instance.todayEntries();
|
|
||||||
if (!mounted) return null;
|
|
||||||
final result = await refreshDelivery(DateTime.now());
|
|
||||||
if (!mounted) return null;
|
|
||||||
if (!result.ok) return result.reason;
|
|
||||||
if (result.dishes.isEmpty) return 'No delivery today.';
|
|
||||||
await KuchniaQueueService.instance.recordFetched(DateTime.now());
|
|
||||||
if (!mounted) return null;
|
|
||||||
final ordered = dishesInSlotOrder(
|
|
||||||
result.dishes,
|
|
||||||
daySlots(MealScheduleService.current),
|
|
||||||
);
|
|
||||||
KuchniaQueueService.instance.offer(
|
|
||||||
ordered,
|
|
||||||
alreadyLogged: {
|
|
||||||
for (final entry in logged) entry.desc.trim().toLowerCase(),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
if (KuchniaQueueService.next == null) {
|
|
||||||
return 'All delivered dishes are already logged.';
|
|
||||||
}
|
|
||||||
prefillNextDish();
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether an explicit delivery fetch is in flight.
|
|
||||||
///
|
|
||||||
/// Only guards against a double tap opening two logins at once -- it is not
|
|
||||||
/// the daily guard, which an explicit tap deliberately bypasses.
|
|
||||||
bool deliveryBusy = false;
|
|
||||||
|
|
||||||
/// Runs [loadDeliveryOnTap] and shows its outcome as a SnackBar.
|
|
||||||
///
|
|
||||||
/// Lives here rather than on the screen because `log_meal_screen.dart` is at
|
|
||||||
/// the 250-line cap, and this is the mixin's own behaviour anyway.
|
|
||||||
Future<void> loadDeliveryAndReport() async {
|
|
||||||
setState(() => deliveryBusy = true);
|
|
||||||
String? message;
|
|
||||||
try {
|
|
||||||
message = await loadDeliveryOnTap();
|
|
||||||
} finally {
|
|
||||||
if (mounted) setState(() => deliveryBusy = false);
|
|
||||||
}
|
|
||||||
if (!mounted || message == null) return;
|
|
||||||
ScaffoldMessenger.of(
|
|
||||||
context,
|
|
||||||
).showSnackBar(SnackBar(content: Text(message)));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Prefills the form with the next queued dish, if there is one.
|
|
||||||
///
|
|
||||||
/// Safe to call when the queue is empty: it simply clears the offer.
|
|
||||||
void prefillNextDish() {
|
|
||||||
final dish = KuchniaQueueService.next;
|
|
||||||
if (dish == null) {
|
|
||||||
if (offeredDish != null) setState(() => offeredDish = null);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setState(() => offeredDish = dish);
|
|
||||||
fillFormFromDish(dish);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Drops the just-logged dish and immediately offers the next one.
|
|
||||||
///
|
|
||||||
/// Call this from the submit handler *after* the entry is written. This is
|
|
||||||
/// the second caller that keeps the queue alive across a submit.
|
|
||||||
void advanceQueueAfterLog(String loggedDesc) {
|
|
||||||
final dish = offeredDish;
|
|
||||||
if (dish == null) return;
|
|
||||||
if (dish.name.trim().toLowerCase() != loggedDesc.trim().toLowerCase()) {
|
|
||||||
// The user edited the description into something else, so the offered
|
|
||||||
// dish was not what they logged. Leave it queued rather than silently
|
|
||||||
// marking a dish eaten that never was.
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
KuchniaQueueService.instance.markLogged(dish);
|
|
||||||
offeredDish = null;
|
|
||||||
prefillNextDish();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A short line naming what is still queued, or null when nothing is.
|
|
||||||
///
|
|
||||||
/// The leftover matters: the caterer's five meals against four default slots
|
|
||||||
/// means at least one dish is still queued when the last slot is logged. It
|
|
||||||
/// is already banked, so it is named rather than dropped silently.
|
|
||||||
String? get queueStatusLine {
|
|
||||||
final left = dishesStillQueued;
|
|
||||||
if (left <= 0) return null;
|
|
||||||
return '$left more delivered ${left == 1 ? 'dish' : 'dishes'} to log.';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
82
app/lib/screens/log_meal_logged_mixin.dart
Normal file
@ -0,0 +1,82 @@
|
|||||||
|
/// The meals the screen logged for the user, shown below the action row with
|
||||||
|
/// an undo, plus the catering auto-log that fills the first of them.
|
||||||
|
///
|
||||||
|
/// The rows stay until the next meal is logged. Undo tombstones that one entry
|
||||||
|
/// by id (`deleteEntry`, never `undoLastToday`: several rows can be on screen,
|
||||||
|
/// and an auto-logged dish is not necessarily the newest entry), so the
|
||||||
|
/// deterministic catering id keeps blocking a re-log on the next open.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_due_mixin.dart';
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_sync_mixin.dart';
|
||||||
|
import 'package:diet_guard_app/services/kuchnia_autolog.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/logged_meal_row.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
/// Logged-meal rows, undo and the catering auto-log.
|
||||||
|
mixin LogMealLoggedMixin<T extends StatefulWidget>
|
||||||
|
on LogMealSyncMixin<T>, LogMealDueMixin<T> {
|
||||||
|
/// The rows under the action row, oldest first.
|
||||||
|
List<LoggedMeal> loggedRows = const [];
|
||||||
|
|
||||||
|
/// The latest open-or-resume chain. Tests await it instead of guessing how
|
||||||
|
/// long real file I/O takes (a fixed sleep flaked under load).
|
||||||
|
@visibleForTesting
|
||||||
|
Future<void> openChain = Future<void>.value();
|
||||||
|
|
||||||
|
/// Replaces the rows with [meals]: a new log retires the previous ones.
|
||||||
|
void showLogged(List<LoggedMeal> meals) {
|
||||||
|
if (mounted) setState(() => loggedRows = meals);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tombstones [meal]'s entry, drops its row and republishes.
|
||||||
|
Future<void> undoLogged(LoggedMeal meal) async {
|
||||||
|
final id = meal.entry.id;
|
||||||
|
if (id == null) return;
|
||||||
|
setState(() => loggedRows = [...loggedRows]..remove(meal));
|
||||||
|
await LogStorageService.instance.deleteEntry(id);
|
||||||
|
await publishAfterLog();
|
||||||
|
await refreshSlots();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Logs the delivered dishes of the due slots, no tap needed.
|
||||||
|
///
|
||||||
|
/// The old rule "a delivered meal is not an eaten meal" was overridden by
|
||||||
|
/// kuhy on 2026-11-17 ("LOG EVEN WITHOUT TAP"). Safe to call repeatedly: the
|
||||||
|
/// ids are deterministic (see `kuchnia_autolog.dart`).
|
||||||
|
Future<void> autoLogCatering() async {
|
||||||
|
if (!dueMode) return;
|
||||||
|
final entries = await KuchniaAutoLog.instance.logDue(dueSlots);
|
||||||
|
if (!mounted || entries.isEmpty) return;
|
||||||
|
showLogged([for (final e in entries) LoggedMeal(e, LoggedOrigin.catering)]);
|
||||||
|
await publishAfterLog();
|
||||||
|
await refreshSlots();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||||
|
// A resume does what an open does, with one sync (autoSync is
|
||||||
|
// single-flight, so calling super too would let the auto-log run before
|
||||||
|
// the pull finished). Pause still pushes through the sync mixin.
|
||||||
|
if (state == AppLifecycleState.resumed) {
|
||||||
|
startOpenChain();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
super.didChangeAppLifecycleState(state);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Starts [onOpenedOrResumed] and keeps its future in [openChain].
|
||||||
|
void startOpenChain() => openChain = onOpenedOrResumed();
|
||||||
|
|
||||||
|
/// What a fresh open or a resume does: show the screen from the local log,
|
||||||
|
/// pull what other devices logged, then auto-log what is still due.
|
||||||
|
Future<void> onOpenedOrResumed() async {
|
||||||
|
unawaited(refreshSlots());
|
||||||
|
await autoSync();
|
||||||
|
await refreshSlots();
|
||||||
|
await autoLogCatering();
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1,11 +1,12 @@
|
|||||||
|
import 'package:diet_guard_app/screens/body_screen.dart';
|
||||||
import 'package:diet_guard_app/screens/calendar_screen.dart';
|
import 'package:diet_guard_app/screens/calendar_screen.dart';
|
||||||
import 'package:diet_guard_app/screens/food_bank_screen.dart';
|
import 'package:diet_guard_app/screens/food_bank_screen.dart';
|
||||||
import 'package:diet_guard_app/screens/history_screen.dart';
|
import 'package:diet_guard_app/screens/history_screen.dart';
|
||||||
import 'package:diet_guard_app/screens/settings_screen.dart';
|
import 'package:diet_guard_app/screens/settings_screen.dart';
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// The four app-bar destinations reachable from [LogMealScreen].
|
/// The five app-bar destinations reachable from [LogMealScreen].
|
||||||
///
|
///
|
||||||
/// Split out of `log_meal_screen.dart` for the repo's 250-line cap. The routes
|
/// Split out of `log_meal_screen.dart` for the repo's 250-line cap. The routes
|
||||||
/// are unchanged -- each pushes exactly the [MaterialPageRoute] it did before.
|
/// are unchanged -- each pushes exactly the [MaterialPageRoute] it did before.
|
||||||
@ -25,23 +26,30 @@ mixin LogMealNavMixin<T extends StatefulWidget> on State<T> {
|
|||||||
|
|
||||||
/// Pushes the entry history screen.
|
/// Pushes the entry history screen.
|
||||||
void onOpenHistory() {
|
void onOpenHistory() {
|
||||||
Navigator.of(context).push<void>(
|
Navigator.of(
|
||||||
MaterialPageRoute(builder: (_) => const HistoryScreen()),
|
context,
|
||||||
);
|
).push<void>(MaterialPageRoute(builder: (_) => const HistoryScreen()));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Pushes the adherence calendar screen.
|
/// Pushes the adherence calendar screen.
|
||||||
void onOpenCalendar() {
|
void onOpenCalendar() {
|
||||||
Navigator.of(context).push<void>(
|
Navigator.of(
|
||||||
MaterialPageRoute(builder: (_) => const CalendarScreen()),
|
context,
|
||||||
);
|
).push<void>(MaterialPageRoute(builder: (_) => const CalendarScreen()));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pushes the Body screen (weight, BMI, calorie targets, week planner).
|
||||||
|
void onOpenBody() {
|
||||||
|
Navigator.of(
|
||||||
|
context,
|
||||||
|
).push<void>(MaterialPageRoute(builder: (_) => const BodyScreen()));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Pushes the food bank screen.
|
/// Pushes the food bank screen.
|
||||||
void onOpenFoodBank() {
|
void onOpenFoodBank() {
|
||||||
Navigator.of(context).push<void>(
|
Navigator.of(
|
||||||
MaterialPageRoute(builder: (_) => const FoodBankScreen()),
|
context,
|
||||||
);
|
).push<void>(MaterialPageRoute(builder: (_) => const FoodBankScreen()));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Pushes the settings screen, forwarding the HTTP client.
|
/// Pushes the settings screen, forwarding the HTTP client.
|
||||||
|
|||||||
@ -1,9 +1,11 @@
|
|||||||
import 'package:diet_guard_app/models/food_entry.dart';
|
import 'package:diet_guard_app/models/food_entry.dart';
|
||||||
import 'package:diet_guard_app/models/local_time.dart';
|
import 'package:diet_guard_app/models/local_time.dart';
|
||||||
|
import 'package:diet_guard_app/models/slot.dart';
|
||||||
import 'package:diet_guard_app/services/app_settings_service.dart';
|
import 'package:diet_guard_app/services/app_settings_service.dart';
|
||||||
import 'package:diet_guard_app/services/budget_history_service.dart';
|
import 'package:diet_guard_app/services/budget_history_service.dart';
|
||||||
import 'package:diet_guard_app/services/day_status_service.dart';
|
import 'package:diet_guard_app/services/day_status_service.dart';
|
||||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
|
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
||||||
import 'package:diet_guard_app/widgets/today_progress_card.dart';
|
import 'package:diet_guard_app/widgets/today_progress_card.dart';
|
||||||
import 'package:flutter/widgets.dart';
|
import 'package:flutter/widgets.dart';
|
||||||
|
|
||||||
@ -14,13 +16,13 @@ double parseMacroField(TextEditingController controller) =>
|
|||||||
/// Summarises today from the log just written.
|
/// Summarises today from the log just written.
|
||||||
///
|
///
|
||||||
/// Takes the already-read [log] rather than re-reading, so the card can
|
/// Takes the already-read [log] rather than re-reading, so the card can
|
||||||
/// never disagree with the write that produced it.
|
/// never disagree with the write that produced it. [logged] is that write:
|
||||||
TodayProgress buildTodayProgress(DayLog log) {
|
/// the card counts up from the totals without it.
|
||||||
|
TodayProgress buildTodayProgress(DayLog log, {FoodEntry? logged}) {
|
||||||
final budget = AppSettingsService.dailyKcalGoal;
|
final budget = AppSettingsService.dailyKcalGoal;
|
||||||
final today = localDateKey(DateTime.now());
|
final today = localDateKey(DateTime.now());
|
||||||
final entries = (log[today] ?? const <FoodEntry>[])
|
final entries = _live(log[today]);
|
||||||
.where((entry) => !entry.deleted)
|
final before = logged == null ? log : _without(log, logged.id);
|
||||||
.toList();
|
|
||||||
final macros = sumMacros(entries);
|
final macros = sumMacros(entries);
|
||||||
return TodayProgress(
|
return TodayProgress(
|
||||||
consumedKcal: sumKcal(entries),
|
consumedKcal: sumKcal(entries),
|
||||||
@ -28,8 +30,28 @@ TodayProgress buildTodayProgress(DayLog log) {
|
|||||||
proteinG: macros.proteinG,
|
proteinG: macros.proteinG,
|
||||||
carbsG: macros.carbsG,
|
carbsG: macros.carbsG,
|
||||||
fatG: macros.fatG,
|
fatG: macros.fatG,
|
||||||
adherenceStreak: adherenceStreak(
|
adherenceStreak: _streak(log),
|
||||||
statusMap(log, schedule: BudgetHistoryService.schedule),
|
loggedSlotMinute: logged == null ? null : _slotOf(logged),
|
||||||
),
|
loggedKcal: logged?.kcal,
|
||||||
|
previousKcal: logged == null ? null : sumKcal(_live(before[today])),
|
||||||
|
previousAdherenceStreak: logged == null ? null : _streak(before),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
int _slotOf(FoodEntry entry) =>
|
||||||
|
entry.slotMinute ??
|
||||||
|
slotForLog(DateTime.parse(entry.time), MealScheduleService.current);
|
||||||
|
|
||||||
|
List<FoodEntry> _live(List<FoodEntry>? entries) =>
|
||||||
|
(entries ?? const <FoodEntry>[]).where((entry) => !entry.deleted).toList();
|
||||||
|
|
||||||
|
int _streak(DayLog log) =>
|
||||||
|
adherenceStreak(statusMap(log, schedule: BudgetHistoryService.schedule));
|
||||||
|
|
||||||
|
DayLog _without(DayLog log, String? id) => {
|
||||||
|
for (final MapEntry(:key, :value) in log.entries)
|
||||||
|
key: [
|
||||||
|
for (final entry in value)
|
||||||
|
if (entry.id != id) entry,
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|||||||
@ -1,41 +1,54 @@
|
|||||||
/// Single-food meal logging screen -- the app's primary, done-criterion
|
/// Single-food meal logging screen -- the app's primary, done-criterion
|
||||||
/// screen: "I can open the diet app on my phone and fill meal I ate."
|
/// screen: "I can open the diet app on my phone and fill meal I ate."
|
||||||
|
///
|
||||||
|
/// Two modes. **Due mode** (a slot elapsed with nothing logged) shows only
|
||||||
|
/// what logging needs: the food field, suggestions, macros and the action row,
|
||||||
|
/// with the status bar hidden. **Normal mode** adds the app bar, the sync
|
||||||
|
/// banner and the date row. Either way the action row is photo / Claude /
|
||||||
|
/// log, and the field never moves between states.
|
||||||
library;
|
library;
|
||||||
|
|
||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
|
||||||
import 'package:diet_guard_app/models/food_suggestion.dart';
|
import 'package:diet_guard_app/models/food_suggestion.dart';
|
||||||
import 'package:diet_guard_app/models/slot.dart';
|
|
||||||
import 'package:diet_guard_app/screens/log_meal_actions.dart';
|
import 'package:diet_guard_app/screens/log_meal_actions.dart';
|
||||||
import 'package:diet_guard_app/screens/log_meal_kuchnia_mixin.dart';
|
import 'package:diet_guard_app/screens/log_meal_claude_mixin.dart';
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_due_mixin.dart';
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_future_mixin.dart';
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_logged_mixin.dart';
|
||||||
import 'package:diet_guard_app/screens/log_meal_nav_mixin.dart';
|
import 'package:diet_guard_app/screens/log_meal_nav_mixin.dart';
|
||||||
import 'package:diet_guard_app/screens/log_meal_progress.dart';
|
import 'package:diet_guard_app/screens/log_meal_progress.dart';
|
||||||
import 'package:diet_guard_app/screens/log_meal_sync_mixin.dart';
|
import 'package:diet_guard_app/screens/log_meal_sync_mixin.dart';
|
||||||
import 'package:diet_guard_app/services/due_slot_check.dart';
|
import 'package:diet_guard_app/services/claude_relay_client.dart';
|
||||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_feedback.dart';
|
||||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
import 'package:diet_guard_app/services/meal_photo_source.dart';
|
||||||
|
import 'package:diet_guard_app/ui/cues.dart';
|
||||||
import 'package:diet_guard_app/ui/theme.dart';
|
import 'package:diet_guard_app/ui/theme.dart';
|
||||||
import 'package:diet_guard_app/widgets/autocomplete_suggestion_list.dart';
|
import 'package:diet_guard_app/widgets/autocomplete_suggestion_list.dart';
|
||||||
import 'package:diet_guard_app/widgets/log_meal_actions_row.dart';
|
import 'package:diet_guard_app/widgets/logged_meal_row.dart';
|
||||||
import 'package:diet_guard_app/widgets/macro_input_row.dart';
|
import 'package:diet_guard_app/widgets/macro_input_row.dart';
|
||||||
import 'package:diet_guard_app/widgets/slot_selector_row.dart';
|
import 'package:diet_guard_app/widgets/meal_action_row.dart';
|
||||||
import 'package:diet_guard_app/widgets/sync_health_banner.dart';
|
import 'package:diet_guard_app/widgets/sync_health_banner.dart';
|
||||||
import 'package:diet_guard_app/widgets/today_progress_card.dart';
|
import 'package:diet_guard_app/widgets/today_progress_card.dart';
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// Lets the user log one food item, with food-bank autocomplete and
|
/// Lets the user log one food item, with food-bank autocomplete.
|
||||||
/// today's slot status.
|
|
||||||
class LogMealScreen extends StatefulWidget {
|
class LogMealScreen extends StatefulWidget {
|
||||||
/// Creates a [LogMealScreen].
|
/// Creates a [LogMealScreen].
|
||||||
const LogMealScreen({super.key, this.httpClient});
|
const LogMealScreen({super.key, this.httpClient, this.relay, this.photos});
|
||||||
|
|
||||||
/// Injectable HTTP client for auto-sync; tests pass a [MockClient].
|
/// Injectable HTTP client for auto-sync; tests pass a [MockClient].
|
||||||
/// Production leaves this null so [GitHubClient] builds a real one.
|
|
||||||
final http.Client? httpClient;
|
final http.Client? httpClient;
|
||||||
|
|
||||||
|
/// Where the sparkle button sends; the app-wide [claudeRelay] when null.
|
||||||
|
final ClaudeRelayClient? relay;
|
||||||
|
|
||||||
|
/// Where photos come from; the camera/gallery picker when null.
|
||||||
|
final MealPhotoSource? photos;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
State<LogMealScreen> createState() => _LogMealScreenState();
|
State<LogMealScreen> createState() => _LogMealScreenState();
|
||||||
}
|
}
|
||||||
@ -44,18 +57,28 @@ class _LogMealScreenState extends State<LogMealScreen>
|
|||||||
with
|
with
|
||||||
WidgetsBindingObserver,
|
WidgetsBindingObserver,
|
||||||
LogMealSyncMixin<LogMealScreen>,
|
LogMealSyncMixin<LogMealScreen>,
|
||||||
|
LogMealDueMixin<LogMealScreen>,
|
||||||
|
LogMealLoggedMixin<LogMealScreen>,
|
||||||
LogMealNavMixin<LogMealScreen>,
|
LogMealNavMixin<LogMealScreen>,
|
||||||
LogMealKuchniaMixin<LogMealScreen> {
|
LogMealFutureMixin<LogMealScreen>,
|
||||||
|
LogMealClaudeMixin<LogMealScreen> {
|
||||||
@override
|
@override
|
||||||
http.Client? get syncHttpClient => widget.httpClient;
|
http.Client? get syncHttpClient => widget.httpClient;
|
||||||
|
@override
|
||||||
|
ClaudeRelayClient get relay => widget.relay ?? claudeRelay;
|
||||||
|
@override
|
||||||
|
late final MealPhotoSource photoSource =
|
||||||
|
widget.photos ?? ImagePickerPhotoSource();
|
||||||
|
|
||||||
final TextEditingController _descController = TextEditingController();
|
final TextEditingController _descController = TextEditingController();
|
||||||
final MacroControllers _macros = MacroControllers();
|
final MacroControllers _macros = MacroControllers();
|
||||||
List<FoodSuggestion> _suggestions = const [];
|
|
||||||
@override
|
@override
|
||||||
int? selectedSlot;
|
TextEditingController get claudeDesc => _descController;
|
||||||
|
@override
|
||||||
|
MacroControllers get claudeMacros => _macros;
|
||||||
|
List<FoodSuggestion> _suggestions = const [];
|
||||||
String _source = 'manual';
|
String _source = 'manual';
|
||||||
String? _status;
|
CueState? _cue; // painted as a tinted icon, never as text
|
||||||
TodayProgress? _progress;
|
TodayProgress? _progress;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@ -63,49 +86,30 @@ class _LogMealScreenState extends State<LogMealScreen>
|
|||||||
super.initState();
|
super.initState();
|
||||||
WidgetsBinding.instance.addObserver(this);
|
WidgetsBinding.instance.addObserver(this);
|
||||||
_descController.addListener(_onDescChanged);
|
_descController.addListener(_onDescChanged);
|
||||||
for (final controller in [
|
_macros.addListenerToAll(_onMacroEdited);
|
||||||
_macros.kcal,
|
|
||||||
_macros.protein,
|
|
||||||
_macros.carbs,
|
|
||||||
_macros.fat,
|
|
||||||
_macros.perGrams,
|
|
||||||
_macros.grams,
|
|
||||||
]) {
|
|
||||||
controller.addListener(_onMacroEdited);
|
|
||||||
}
|
|
||||||
selectedSlot = slotForLog(DateTime.now(), MealScheduleService.current);
|
|
||||||
unawaited(refreshSlots());
|
|
||||||
unawaited(_onDescChanged());
|
unawaited(_onDescChanged());
|
||||||
// Read health before the first sync finishes, so a device that stalled in
|
// Health first, so a device that stalled earlier says so before a tick.
|
||||||
// a previous session says so immediately rather than only after a tick.
|
|
||||||
unawaited(refreshSyncHealth());
|
unawaited(refreshSyncHealth());
|
||||||
unawaited(autoSync());
|
startOpenChain();
|
||||||
// After autoSync so a dish already logged on the PC is known before the
|
|
||||||
// queue is built, and guarded so this costs at most one walk per day.
|
|
||||||
unawaited(loadTodaysDelivery());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
WidgetsBinding.instance.removeObserver(this);
|
WidgetsBinding.instance.removeObserver(this);
|
||||||
|
disposeClaude();
|
||||||
|
restoreStatusBar();
|
||||||
_descController.dispose();
|
_descController.dispose();
|
||||||
_macros.dispose();
|
_macros.dispose();
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
void _onMacroEdited() {
|
void _onMacroEdited() {
|
||||||
if (_source == 'food bank') {
|
if (_source == 'food bank') setState(() => _source = 'manual');
|
||||||
setState(() => _source = 'manual');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Re-runs the food-bank search and dismisses the previous progress card.
|
/// Re-runs the food-bank search and dismisses the previous progress card,
|
||||||
///
|
/// only while the field is non-empty: [_onLogMeal]'s own `clear()` fires
|
||||||
/// The card is cleared only when the field is non-empty because
|
/// this listener too, and would otherwise race it and null the new card.
|
||||||
/// [_onLogMeal]'s own `clear()` fires this listener too: without the guard
|
|
||||||
/// the two async chains race and the clear can null the card right after
|
|
||||||
/// [_onLogMeal] set it, so it never appears on device (in-memory test
|
|
||||||
/// stores resolve fast enough to hide this).
|
|
||||||
Future<void> _onDescChanged() async {
|
Future<void> _onDescChanged() async {
|
||||||
final matches = await FoodBankService.instance.search(_descController.text);
|
final matches = await FoodBankService.instance.search(_descController.text);
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
@ -115,16 +119,8 @@ class _LogMealScreenState extends State<LogMealScreen>
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
|
||||||
TextEditingController get descController => _descController;
|
|
||||||
@override
|
|
||||||
MacroControllers get macroControllers => _macros;
|
|
||||||
@override
|
|
||||||
void onDishPrefilled() => setState(() => _source = 'catering');
|
|
||||||
|
|
||||||
void _onSuggestionSelected(FoodSuggestion suggestion) {
|
void _onSuggestionSelected(FoodSuggestion suggestion) {
|
||||||
_descController.text = suggestion.name;
|
fillControllersFromSuggestion(suggestion, _descController, _macros);
|
||||||
_macros.fillFrom(suggestion.nutrition);
|
|
||||||
setState(() {
|
setState(() {
|
||||||
_source = 'food bank';
|
_source = 'food bank';
|
||||||
_suggestions = const [];
|
_suggestions = const [];
|
||||||
@ -133,111 +129,122 @@ class _LogMealScreenState extends State<LogMealScreen>
|
|||||||
|
|
||||||
Future<void> _onLogMeal() async {
|
Future<void> _onLogMeal() async {
|
||||||
final desc = _descController.text.trim();
|
final desc = _descController.text.trim();
|
||||||
if (desc.isEmpty) {
|
if (desc.isEmpty) return;
|
||||||
setState(() {
|
final target = resolveLogTarget(targetSlot);
|
||||||
_status = 'Type what you ate first.';
|
if (target.error != null) {
|
||||||
_progress = null;
|
setState(() => _cue = CueState.next(_cue, CueKind.error, target.error!));
|
||||||
});
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
final nutrition = nutritionFromControllers(_macros, _source);
|
LogFeedback.mealLogged(); // on the tap, before the write
|
||||||
await LogStorageService.instance.logMeal(
|
unawaited(withdrawClaude()); // else Claude would log it a second time
|
||||||
|
final entry = await LogStorageService.instance.logMeal(
|
||||||
desc,
|
desc,
|
||||||
nutrition,
|
nutritionFromControllers(_macros, _source),
|
||||||
slot: selectedSlot,
|
slotMinute: target.slot,
|
||||||
|
when: target.when,
|
||||||
);
|
);
|
||||||
final log = await LogStorageService.instance.readLog();
|
resetFutureLog();
|
||||||
await FoodBankService.instance.rebuildAndPersist(log);
|
final log = await publishAfterLog();
|
||||||
// Push the new meal now instead of waiting for the next lifecycle event,
|
|
||||||
// so the PC gate can see it in seconds. Fire-and-forget and best-effort:
|
|
||||||
// autoSync is single-flight and swallows offline/transient failures.
|
|
||||||
unawaited(autoSync());
|
|
||||||
// Offline backstop: if the push above fails (no connectivity), a
|
|
||||||
// connectivity-gated WorkManager task uploads the meal on reconnect.
|
|
||||||
unawaited(enqueueSyncBackstopTask());
|
|
||||||
// Clears a reminder the meal just logged has now satisfied; without it a
|
|
||||||
// notification already on screen survives up to 15 min and reads as a
|
|
||||||
// false alarm. `pullWhenDue: false` because `autoSync` above already owns
|
|
||||||
// the network for this submit.
|
|
||||||
await checkAndNotify(pullWhenDue: false);
|
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
_descController.clear();
|
_descController.clear();
|
||||||
_macros.clear();
|
_macros.clear();
|
||||||
setState(() {
|
setState(() {
|
||||||
_source = 'manual';
|
_source = 'manual';
|
||||||
selectedSlot = slotForLog(DateTime.now(), MealScheduleService.current);
|
photo = null; // else a stale photo keeps the sparkle lit
|
||||||
|
claudeState = ClaudeButtonState.idle;
|
||||||
});
|
});
|
||||||
await refreshSlots();
|
await refreshSlots();
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
// The second `prefillNextDish` caller. Without it every dish after the
|
showLogged([LoggedMeal(entry, LoggedOrigin.local)]);
|
||||||
// first stays queued behind another tap and the "N more to log" line
|
|
||||||
// becomes a dead letter -- the exact regression the PC gate once shipped.
|
|
||||||
advanceQueueAfterLog(desc);
|
|
||||||
setState(() {
|
setState(() {
|
||||||
_status = queueStatusLine;
|
_cue = null;
|
||||||
_progress = buildTodayProgress(log);
|
_progress = buildTodayProgress(log, logged: entry);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
|
if (!slotsLoaded) return const Scaffold();
|
||||||
|
final due = dueMode;
|
||||||
|
// Dimmed while Claude works, but never moved: nothing is added around it.
|
||||||
|
final busy = claudeState == ClaudeButtonState.sending;
|
||||||
|
// Hard rule: nothing sits under the keyboard, so the extras collapse.
|
||||||
|
final typing = MediaQuery.viewInsetsOf(context).bottom > 0;
|
||||||
|
final dim = busy || claudeState == ClaudeButtonState.queued;
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(
|
appBar: due
|
||||||
title: const Text('Diet Guard'),
|
? null
|
||||||
actions: [
|
: AppBar(
|
||||||
...logMealAppBarActions(
|
actions: logMealAppBarActions(
|
||||||
onFoodBank: onOpenFoodBank,
|
onFoodBank: onOpenFoodBank,
|
||||||
onHistory: onOpenHistory,
|
onHistory: onOpenHistory,
|
||||||
onCalendar: onOpenCalendar,
|
onCalendar: onOpenCalendar,
|
||||||
onSettings: onOpenSettings,
|
onSettings: onOpenSettings,
|
||||||
|
onBody: onOpenBody,
|
||||||
|
leading: buildDateActions(context),
|
||||||
),
|
),
|
||||||
],
|
|
||||||
),
|
),
|
||||||
body: SingleChildScrollView(
|
body: SafeArea(
|
||||||
|
child: SingleChildScrollView(
|
||||||
padding: const EdgeInsets.all(AppSpacing.md),
|
padding: const EdgeInsets.all(AppSpacing.md),
|
||||||
child: Column(
|
child: Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
SyncHealthBanner(status: syncHealth),
|
if (!due) SyncHealthBanner(status: syncHealth),
|
||||||
SlotSelectorRow(
|
buildSlotRow(),
|
||||||
now: DateTime.now(),
|
Opacity(
|
||||||
loggedSlots: loggedSlots,
|
opacity: dim ? 0.5 : 1,
|
||||||
selectedSlot: selectedSlot,
|
child: IgnorePointer(
|
||||||
onSlotSelected: (slot) => setState(() => selectedSlot = slot),
|
ignoring: busy,
|
||||||
),
|
child: Column(
|
||||||
const SizedBox(height: 8),
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
TextField(
|
children: [
|
||||||
|
IconField(
|
||||||
controller: _descController,
|
controller: _descController,
|
||||||
decoration: const InputDecoration(labelText: 'What did you eat?'),
|
icon: Icons.fastfood,
|
||||||
|
semanticLabel: 'What did you eat?',
|
||||||
|
onChanged: (_) => setState(() {}),
|
||||||
),
|
),
|
||||||
AutocompleteSuggestionList(
|
AutocompleteSuggestionList(
|
||||||
suggestions: _suggestions,
|
suggestions: _suggestions,
|
||||||
onSelected: _onSuggestionSelected,
|
onSelected: _onSuggestionSelected,
|
||||||
compact: true,
|
compact: true,
|
||||||
|
compactLimit: due ? 2 : 3,
|
||||||
|
reserveHeight: due,
|
||||||
),
|
),
|
||||||
const SizedBox(height: 8),
|
|
||||||
MacroInputRow(controllers: _macros, compact: true),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
LogMealActionsRow(
|
|
||||||
onLoadDelivery: loadDeliveryAndReport,
|
|
||||||
onLog: _onLogMeal,
|
|
||||||
deliveryBusy: deliveryBusy,
|
|
||||||
dishesQueued: dishesStillQueued,
|
|
||||||
),
|
|
||||||
// Mutually exclusive: _status carries a validation complaint,
|
|
||||||
// _progress the post-log summary. A successful log clears one
|
|
||||||
// and sets the other, so the two never stack.
|
|
||||||
if (_status != null) ...[
|
|
||||||
const SizedBox(height: AppSpacing.sm),
|
const SizedBox(height: AppSpacing.sm),
|
||||||
Text(_status!),
|
MacroInputRow(controllers: _macros, compact: true),
|
||||||
],
|
],
|
||||||
if (_progress != null) ...[
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: AppSpacing.sm),
|
||||||
|
MealActionRow(
|
||||||
|
claude: claudeState,
|
||||||
|
photoAttached: photo != null,
|
||||||
|
canSend: canSend,
|
||||||
|
canLog: _descController.text.trim().isNotEmpty,
|
||||||
|
onPhoto: () => unawaited(attachPhoto(PhotoOrigin.camera)),
|
||||||
|
onGallery: () => unawaited(attachPhoto(PhotoOrigin.gallery)),
|
||||||
|
onRemovePhoto: removePhoto,
|
||||||
|
onSend: sendToClaude,
|
||||||
|
onLog: _onLogMeal,
|
||||||
|
),
|
||||||
|
if (!typing)
|
||||||
|
for (final meal in loggedRows)
|
||||||
|
LoggedMealRow(meal: meal, onUndo: () => undoLogged(meal)),
|
||||||
|
if (_cue != null) ...[
|
||||||
|
const SizedBox(height: AppSpacing.sm),
|
||||||
|
_cue!.widget,
|
||||||
|
],
|
||||||
|
if (_progress != null && !due && !typing) ...[
|
||||||
const SizedBox(height: AppSpacing.sm),
|
const SizedBox(height: AppSpacing.sm),
|
||||||
TodayProgressCard(progress: _progress!),
|
TodayProgressCard(progress: _progress!),
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,17 +1,19 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
import 'dart:developer';
|
import 'dart:developer';
|
||||||
|
|
||||||
import 'package:diet_guard_app/models/slot.dart';
|
|
||||||
import 'package:diet_guard_app/services/background_tasks.dart';
|
import 'package:diet_guard_app/services/background_tasks.dart';
|
||||||
|
import 'package:diet_guard_app/services/due_slot_check.dart';
|
||||||
import 'package:diet_guard_app/services/firebase_client.dart';
|
import 'package:diet_guard_app/services/firebase_client.dart';
|
||||||
|
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||||
import 'package:diet_guard_app/services/github_client_factory.dart';
|
import 'package:diet_guard_app/services/github_client_factory.dart';
|
||||||
|
import 'package:diet_guard_app/services/health_steps.dart';
|
||||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
import 'package:diet_guard_app/services/sync_attempt.dart';
|
||||||
import 'package:diet_guard_app/services/sync_health.dart';
|
import 'package:diet_guard_app/services/sync_health.dart';
|
||||||
import 'package:diet_guard_app/services/sync_service.dart';
|
import 'package:diet_guard_app/services/sync_service.dart';
|
||||||
import 'package:diet_guard_app/services/sync_settings.dart';
|
import 'package:diet_guard_app/services/sync_settings.dart';
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// Background-sync and lifecycle behaviour for [LogMealScreen]'s state.
|
/// Background-sync and lifecycle behaviour for [LogMealScreen]'s state.
|
||||||
///
|
///
|
||||||
@ -32,12 +34,6 @@ mixin LogMealSyncMixin<T extends StatefulWidget> on State<T>
|
|||||||
/// The slots that already carry a logged meal today.
|
/// The slots that already carry a logged meal today.
|
||||||
Set<int> loggedSlots = {};
|
Set<int> loggedSlots = {};
|
||||||
|
|
||||||
/// The slot the screen is currently logging for.
|
|
||||||
///
|
|
||||||
/// Owned by the screen's own state; declared here so
|
|
||||||
/// [onScheduleMayHaveChanged] can re-derive it when the schedule changes.
|
|
||||||
abstract int? selectedSlot;
|
|
||||||
|
|
||||||
/// The screen's injected HTTP client, or null to use the default.
|
/// The screen's injected HTTP client, or null to use the default.
|
||||||
///
|
///
|
||||||
/// Declared abstract so the mixin stays independent of the widget's own
|
/// Declared abstract so the mixin stays independent of the widget's own
|
||||||
@ -73,6 +69,7 @@ mixin LogMealSyncMixin<T extends StatefulWidget> on State<T>
|
|||||||
Future<void> autoSync() async {
|
Future<void> autoSync() async {
|
||||||
if (autoSyncing) return;
|
if (autoSyncing) return;
|
||||||
autoSyncing = true;
|
autoSyncing = true;
|
||||||
|
bool? landed; // null until the sync itself ran
|
||||||
try {
|
try {
|
||||||
final settings = await SyncSettings.load();
|
final settings = await SyncSettings.load();
|
||||||
// Either backend counts. `isConfigured` means "has a GitHub token", so
|
// Either backend counts. `isConfigured` means "has a GitHub token", so
|
||||||
@ -91,18 +88,20 @@ mixin LogMealSyncMixin<T extends StatefulWidget> on State<T>
|
|||||||
if (mounted) await refreshSyncHealth();
|
if (mounted) await refreshSyncHealth();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
final client = createGitHubClient(
|
final client = createGitHubClient(settings, httpClient: syncHttpClient);
|
||||||
settings,
|
landed = await attemptSync(() async {
|
||||||
httpClient: syncHttpClient,
|
|
||||||
);
|
|
||||||
try {
|
try {
|
||||||
|
// Foreground only (this mixin is UI), and never prompts: fresh
|
||||||
|
// Health Connect steps ride along in this tick's body.json.
|
||||||
|
await refreshSteps();
|
||||||
await runSync(await syncBackend(client));
|
await runSync(await syncBackend(client));
|
||||||
await SyncHealth.recordSuccess();
|
|
||||||
} finally {
|
} finally {
|
||||||
client.close();
|
client.close();
|
||||||
}
|
}
|
||||||
|
});
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
await refreshSlots();
|
// Outside attemptSync: a refresh error is no sync failure.
|
||||||
|
if (landed) await refreshSlots();
|
||||||
await refreshSyncHealth();
|
await refreshSyncHealth();
|
||||||
} on Object catch (error, stackTrace) {
|
} on Object catch (error, stackTrace) {
|
||||||
// Best-effort, but never silent: this swallowed the reason a desktop
|
// Best-effort, but never silent: this swallowed the reason a desktop
|
||||||
@ -115,7 +114,9 @@ mixin LogMealSyncMixin<T extends StatefulWidget> on State<T>
|
|||||||
error: error,
|
error: error,
|
||||||
stackTrace: stackTrace,
|
stackTrace: stackTrace,
|
||||||
);
|
);
|
||||||
await SyncHealth.recordFailure();
|
// attemptSync already recorded the sync's own outcome; only a failure
|
||||||
|
// before it (loading settings) is one here.
|
||||||
|
if (landed == null) await SyncHealth.recordFailure();
|
||||||
if (mounted) await refreshSyncHealth();
|
if (mounted) await refreshSyncHealth();
|
||||||
} finally {
|
} finally {
|
||||||
autoSyncing = false;
|
autoSyncing = false;
|
||||||
@ -139,6 +140,31 @@ mixin LogMealSyncMixin<T extends StatefulWidget> on State<T>
|
|||||||
|
|
||||||
// coverage:ignore-end
|
// coverage:ignore-end
|
||||||
|
|
||||||
|
/// Everything that must follow a write to the food log, shared by the
|
||||||
|
/// manual submit and "Fill all" so a batch fill publishes exactly like a
|
||||||
|
/// typed meal. Call it once per batch, not per entry: [autoSync] is
|
||||||
|
/// single-flight, so a second call while the first is in flight is dropped
|
||||||
|
/// and the later entries would wait for the next tick.
|
||||||
|
///
|
||||||
|
/// Returns the log as read after the write.
|
||||||
|
Future<DayLog> publishAfterLog() async {
|
||||||
|
final log = await LogStorageService.instance.readLog();
|
||||||
|
await FoodBankService.instance.rebuildAndPersist(log);
|
||||||
|
// Push the new meal now instead of waiting for the next lifecycle event,
|
||||||
|
// so the PC gate can see it in seconds. Fire-and-forget and best-effort:
|
||||||
|
// autoSync is single-flight and swallows offline/transient failures.
|
||||||
|
unawaited(autoSync());
|
||||||
|
// Offline backstop: if the push above fails (no connectivity), a
|
||||||
|
// connectivity-gated WorkManager task uploads the meal on reconnect.
|
||||||
|
unawaited(enqueueSyncBackstopTask());
|
||||||
|
// Clears a reminder the meal just logged has now satisfied; without it a
|
||||||
|
// notification already on screen survives up to 15 min and reads as a
|
||||||
|
// false alarm. `pullWhenDue: false` because `autoSync` above already owns
|
||||||
|
// the network for this submit.
|
||||||
|
await checkAndNotify(pullWhenDue: false);
|
||||||
|
return log;
|
||||||
|
}
|
||||||
|
|
||||||
/// Re-reads which meal slots are already logged today.
|
/// Re-reads which meal slots are already logged today.
|
||||||
Future<void> refreshSlots() async {
|
Future<void> refreshSlots() async {
|
||||||
final logged = await LogStorageService.instance.loggedSlotsToday();
|
final logged = await LogStorageService.instance.loggedSlotsToday();
|
||||||
@ -146,21 +172,12 @@ mixin LogMealSyncMixin<T extends StatefulWidget> on State<T>
|
|||||||
setState(() => loggedSlots = logged);
|
setState(() => loggedSlots = logged);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Rebuilds the slot row after the settings screen pops.
|
/// Re-derives the due slots after the settings screen pops.
|
||||||
///
|
///
|
||||||
/// The meal-schedule editor lives in settings, and [SlotSelectorRow] reads
|
/// The meal-schedule editor lives in settings, and which slots are due (and
|
||||||
/// `MealScheduleService.current` at build time, so refreshing is enough to
|
/// so whether the screen is in due mode) reads `MealScheduleService.current`
|
||||||
/// re-derive the row -- but the selected slot also has to be recomputed,
|
/// at refresh time. Found on the phone: without this the settings preview
|
||||||
/// since the hour it referred to may no longer be a checkpoint at all.
|
/// and the overdue reminder both updated while the screen behind them kept
|
||||||
///
|
/// the old checkpoints until the app was restarted.
|
||||||
/// Found on the phone: without this the settings preview and the overdue
|
Future<void> onScheduleMayHaveChanged() => refreshSlots();
|
||||||
/// reminder both updated while the row behind them kept the old four
|
|
||||||
/// checkpoints until the app was restarted.
|
|
||||||
Future<void> onScheduleMayHaveChanged() async {
|
|
||||||
await refreshSlots();
|
|
||||||
if (!mounted) return;
|
|
||||||
setState(() {
|
|
||||||
selectedSlot = slotForLog(DateTime.now(), MealScheduleService.current);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -7,11 +7,18 @@
|
|||||||
part of 'settings_screen.dart';
|
part of 'settings_screen.dart';
|
||||||
|
|
||||||
mixin _SettingsKcalGoal on State<SettingsScreen> {
|
mixin _SettingsKcalGoal on State<SettingsScreen> {
|
||||||
String? _status;
|
/// The latest outcome as an icon cue; null until something happened.
|
||||||
|
Widget? _status;
|
||||||
|
|
||||||
void _showMessage(String message) {
|
void _showCue(CueKind kind, String semanticLabel) {
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
setState(() => _status = message);
|
setState(
|
||||||
|
() => _status = StatusCue(
|
||||||
|
key: UniqueKey(),
|
||||||
|
kind: kind,
|
||||||
|
semanticLabel: semanticLabel,
|
||||||
|
),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Timer? _kcalGoalDebounce;
|
Timer? _kcalGoalDebounce;
|
||||||
@ -50,13 +57,13 @@ mixin _SettingsKcalGoal on State<SettingsScreen> {
|
|||||||
() => Permission.ignoreBatteryOptimizations.request();
|
() => Permission.ignoreBatteryOptimizations.request();
|
||||||
try {
|
try {
|
||||||
final status = await request();
|
final status = await request();
|
||||||
_showMessage(
|
if (status.isGranted) {
|
||||||
status.isGranted
|
_showCue(CueKind.ok, 'Battery optimization exemption granted.');
|
||||||
? 'Battery optimization exemption granted.'
|
} else {
|
||||||
: 'Exemption not granted -- notifications may be delayed.',
|
_showCue(CueKind.warn, 'Exemption not granted.');
|
||||||
);
|
}
|
||||||
} on Exception catch (e) {
|
} on Exception catch (e) {
|
||||||
_showMessage('Could not request exemption: $e');
|
_showCue(CueKind.error, 'Could not request exemption: $e');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -15,24 +15,43 @@
|
|||||||
/// encrypted either.
|
/// encrypted either.
|
||||||
library;
|
library;
|
||||||
|
|
||||||
|
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart' show WaitWatch;
|
||||||
import 'package:diet_guard_app/services/kuchnia_client.dart';
|
import 'package:diet_guard_app/services/kuchnia_client.dart';
|
||||||
import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
|
import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
|
||||||
import 'package:diet_guard_app/services/kuchnia_import.dart';
|
import 'package:diet_guard_app/services/kuchnia_import.dart';
|
||||||
|
import 'package:diet_guard_app/ui/cues.dart';
|
||||||
import 'package:diet_guard_app/ui/theme.dart';
|
import 'package:diet_guard_app/ui/theme.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
/// What a delivery fetch reports: a cue [kind], a spoken [label] (never
|
||||||
|
/// painted) and, when dishes were banked, their [count] (painted as a number).
|
||||||
|
class FetchOutcome {
|
||||||
|
/// Creates an outcome.
|
||||||
|
const FetchOutcome(this.kind, this.label, {this.count});
|
||||||
|
|
||||||
|
/// Icon/colour of the cue.
|
||||||
|
final CueKind kind;
|
||||||
|
|
||||||
|
/// Spoken description; never painted.
|
||||||
|
final String label;
|
||||||
|
|
||||||
|
/// Dishes banked, shown as a bare number next to the cue.
|
||||||
|
final int? count;
|
||||||
|
}
|
||||||
|
|
||||||
/// Fetches today's delivery and reports what was banked.
|
/// Fetches today's delivery and reports what was banked.
|
||||||
///
|
///
|
||||||
/// Deliberately says "banked", not "logged": a delivered meal is not an eaten
|
/// Deliberately "banked", not "logged": the explicit fetch only fills the
|
||||||
/// meal, so the dishes land in the food bank and the user still taps to log
|
/// food bank; logging is the log screen's auto-log (`kuchnia_autolog.dart`).
|
||||||
/// each one. Top-level so the settings screen can pass it without growing.
|
/// Top-level so the settings screen can pass it without growing.
|
||||||
Future<String> fetchTodaysDelivery() async {
|
Future<FetchOutcome> fetchTodaysDelivery() async {
|
||||||
final result = await refreshDelivery(DateTime.now());
|
final result = await refreshDelivery(DateTime.now());
|
||||||
if (!result.ok) return result.reason!;
|
if (!result.ok) return FetchOutcome(CueKind.error, result.reason!);
|
||||||
if (result.dishes.isEmpty) return 'No delivery found for today.';
|
if (result.dishes.isEmpty) {
|
||||||
|
return const FetchOutcome(CueKind.warn, 'No delivery found for today.');
|
||||||
|
}
|
||||||
final count = result.dishes.length;
|
final count = result.dishes.length;
|
||||||
return '$count ${count == 1 ? 'dish' : 'dishes'} added to your food bank. '
|
return FetchOutcome(CueKind.ok, '$count dishes added', count: count);
|
||||||
'Log them from the meal screen when you eat them.';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Credential fields plus, on Android, a "fetch today's delivery" action.
|
/// Credential fields plus, on Android, a "fetch today's delivery" action.
|
||||||
@ -43,18 +62,14 @@ class KuchniaSettingsSection extends StatefulWidget {
|
|||||||
/// button is replaced by a one-line explanation rather than silently
|
/// button is replaced by a one-line explanation rather than silently
|
||||||
/// vanishing. [onFetch] defaults to the real fetch. Both are injectable so a
|
/// vanishing. [onFetch] defaults to the real fetch. Both are injectable so a
|
||||||
/// widget test can drive the section without a network or a platform check.
|
/// widget test can drive the section without a network or a platform check.
|
||||||
const KuchniaSettingsSection({
|
const KuchniaSettingsSection({this.canFetch, this.onFetch, super.key});
|
||||||
this.canFetch,
|
|
||||||
this.onFetch,
|
|
||||||
super.key,
|
|
||||||
});
|
|
||||||
|
|
||||||
/// Whether this platform can reach the catering panel; null means ask.
|
/// Whether this platform can reach the catering panel; null means ask.
|
||||||
final bool? canFetch;
|
final bool? canFetch;
|
||||||
|
|
||||||
/// Fetches today's delivery and returns a status line; null means the real
|
/// Fetches today's delivery and returns a status line; null means the real
|
||||||
/// one.
|
/// one.
|
||||||
final Future<String> Function()? onFetch;
|
final Future<FetchOutcome> Function()? onFetch;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
State<KuchniaSettingsSection> createState() => _KuchniaSettingsSectionState();
|
State<KuchniaSettingsSection> createState() => _KuchniaSettingsSectionState();
|
||||||
@ -69,7 +84,7 @@ class _KuchniaSettingsSectionState extends State<KuchniaSettingsSection> {
|
|||||||
);
|
);
|
||||||
bool _obscured = true;
|
bool _obscured = true;
|
||||||
bool _busy = false;
|
bool _busy = false;
|
||||||
String? _status;
|
Widget? _status;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
@ -85,7 +100,13 @@ class _KuchniaSettingsSectionState extends State<KuchniaSettingsSection> {
|
|||||||
_password.text,
|
_password.text,
|
||||||
);
|
);
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
setState(() => _status = 'Saved. It will sync to your other devices.');
|
setState(
|
||||||
|
() => _status = StatusCue(
|
||||||
|
key: UniqueKey(),
|
||||||
|
kind: CueKind.ok,
|
||||||
|
semanticLabel: 'Saved. It will sync to your other devices.',
|
||||||
|
),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _fetch() async {
|
Future<void> _fetch() async {
|
||||||
@ -93,92 +114,96 @@ class _KuchniaSettingsSectionState extends State<KuchniaSettingsSection> {
|
|||||||
_busy = true;
|
_busy = true;
|
||||||
_status = null;
|
_status = null;
|
||||||
});
|
});
|
||||||
final message = await (widget.onFetch ?? fetchTodaysDelivery)();
|
final outcome = await (widget.onFetch ?? fetchTodaysDelivery)();
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
setState(() {
|
setState(() {
|
||||||
_busy = false;
|
_busy = false;
|
||||||
_status = message;
|
_status = Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
spacing: AppSpacing.sm,
|
||||||
|
children: [
|
||||||
|
StatusCue(
|
||||||
|
key: UniqueKey(),
|
||||||
|
kind: outcome.kind,
|
||||||
|
semanticLabel: outcome.label,
|
||||||
|
),
|
||||||
|
if (outcome.count != null) Text('${outcome.count}'),
|
||||||
|
],
|
||||||
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final theme = Theme.of(context);
|
|
||||||
final canFetch = widget.canFetch ?? kuchniaFetchSupported;
|
final canFetch = widget.canFetch ?? kuchniaFetchSupported;
|
||||||
// The section owns its own leading divider so the settings screen needs a
|
// The section owns its own leading divider so the settings screen needs a
|
||||||
// single line for it -- that file sits on the repo's 250-line ceiling.
|
// single line for it -- that file sits on the repo's 250-line ceiling.
|
||||||
|
// No heading or blurb: the delivery truck on the fetch button names it.
|
||||||
return Column(
|
return Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
const SizedBox(height: 24),
|
const SizedBox(height: 24),
|
||||||
const Divider(),
|
const Divider(),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
Text('Kuchnia Wikinga', style: theme.textTheme.titleMedium),
|
|
||||||
const SizedBox(height: 4),
|
|
||||||
Text(
|
|
||||||
"Your catering panel login, so this device can look up the day's "
|
|
||||||
'delivered dishes and their macros. Stored and synced in plain '
|
|
||||||
'text, like the rest of your synced data.',
|
|
||||||
style: theme.textTheme.bodySmall,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
ConstrainedBox(
|
ConstrainedBox(
|
||||||
constraints: const BoxConstraints(maxWidth: AppWidth.field),
|
constraints: const BoxConstraints(maxWidth: AppWidth.field),
|
||||||
child: TextField(
|
child: IconField(
|
||||||
|
icon: Icons.alternate_email,
|
||||||
|
semanticLabel: 'Panel e-mail',
|
||||||
controller: _username,
|
controller: _username,
|
||||||
keyboardType: TextInputType.emailAddress,
|
keyboardType: TextInputType.emailAddress,
|
||||||
autocorrect: false,
|
autocorrect: false,
|
||||||
decoration: const InputDecoration(labelText: 'Panel e-mail'),
|
|
||||||
onSubmitted: (_) => _save(),
|
onSubmitted: (_) => _save(),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
ConstrainedBox(
|
ConstrainedBox(
|
||||||
constraints: const BoxConstraints(maxWidth: AppWidth.field),
|
constraints: const BoxConstraints(maxWidth: AppWidth.field),
|
||||||
child: TextField(
|
child: IconField(
|
||||||
|
icon: Icons.key,
|
||||||
|
semanticLabel: 'Panel password',
|
||||||
controller: _password,
|
controller: _password,
|
||||||
obscureText: _obscured,
|
obscure: _obscured,
|
||||||
autocorrect: false,
|
autocorrect: false,
|
||||||
enableSuggestions: false,
|
onSubmitted: (_) => _save(),
|
||||||
decoration: InputDecoration(
|
suffix: IconButton(
|
||||||
labelText: 'Panel password',
|
icon: Icon(
|
||||||
suffixIcon: IconButton(
|
_obscured ? Icons.visibility : Icons.visibility_off,
|
||||||
icon: Icon(_obscured ? Icons.visibility : Icons.visibility_off),
|
semanticLabel: _obscured ? 'Show password' : 'Hide password',
|
||||||
tooltip: _obscured ? 'Show password' : 'Hide password',
|
),
|
||||||
onPressed: () => setState(() => _obscured = !_obscured),
|
onPressed: () => setState(() => _obscured = !_obscured),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
onSubmitted: (_) => _save(),
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
Wrap(
|
Wrap(
|
||||||
spacing: 8,
|
spacing: 8,
|
||||||
runSpacing: 8,
|
runSpacing: 8,
|
||||||
children: [
|
children: [
|
||||||
FilledButton(onPressed: _save, child: const Text('Save login')),
|
IconButton.filled(
|
||||||
if (canFetch)
|
onPressed: _save,
|
||||||
OutlinedButton.icon(
|
icon: const Icon(Icons.check, semanticLabel: 'Save login'),
|
||||||
onPressed: _busy ? null : _fetch,
|
),
|
||||||
icon: const Icon(Icons.restaurant),
|
// Browser builds show the button greyed out: the panel blocks
|
||||||
label: Text(
|
// browser requests, and the disabled state is the cue.
|
||||||
_busy ? 'Fetching…' : "Fetch today's delivery",
|
IconButton.outlined(
|
||||||
|
onPressed: canFetch && !_busy ? _fetch : null,
|
||||||
|
icon: _busy
|
||||||
|
? const WaitWatch(
|
||||||
|
operation: 'kuchnia.sync',
|
||||||
|
child: SizedBox.square(
|
||||||
|
dimension: 20,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
: const Icon(
|
||||||
|
Icons.local_shipping_outlined,
|
||||||
|
semanticLabel: "Fetch today's delivery",
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
if (!canFetch) ...[
|
if (_status != null) ...[const SizedBox(height: 8), _status!],
|
||||||
const SizedBox(height: 8),
|
|
||||||
Text(
|
|
||||||
'Android only — the catering panel blocks browser requests. Your '
|
|
||||||
'login still syncs to your phone from here.',
|
|
||||||
style: theme.textTheme.bodySmall,
|
|
||||||
),
|
|
||||||
],
|
|
||||||
if (_status != null) ...[
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
Text(_status!, style: theme.textTheme.bodyMedium),
|
|
||||||
],
|
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,5 +1,5 @@
|
|||||||
// The meal-schedule editor: first meal, last meal, how many meals, and a
|
// The meal-schedule section: owns the schedule state and its persistence;
|
||||||
// live preview of the checkpoint times they derive.
|
// the widgets themselves live in `widgets/meal_schedule_editor.dart`.
|
||||||
//
|
//
|
||||||
// Split out of `settings_screen.dart` for the repo's 250-line cap. A `part`
|
// Split out of `settings_screen.dart` for the repo's 250-line cap. A `part`
|
||||||
// mixin for the same reason as `_SettingsKcalGoal`: it drives the screen's
|
// mixin for the same reason as `_SettingsKcalGoal`: it drives the screen's
|
||||||
@ -14,134 +14,22 @@ mixin _SettingsMealSchedule on State<SettingsScreen> {
|
|||||||
_schedule = MealScheduleService.current;
|
_schedule = MealScheduleService.current;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The meal counts selectable for the current window.
|
|
||||||
///
|
|
||||||
/// Capped at the number of whole hours the window holds, so the count
|
|
||||||
/// dropdown can never offer a value that would round two meals onto the
|
|
||||||
/// same hour. Invalid states are made unrepresentable here rather than
|
|
||||||
/// validated after the fact -- `MealSchedule.normalized` still clamps, but
|
|
||||||
/// that is the defence against corrupt synced data, not the input contract.
|
|
||||||
List<int> get _selectableCounts {
|
|
||||||
final span = _schedule.last - _schedule.first;
|
|
||||||
final maxCount = span + 1 < kMaxMealCount ? span + 1 : kMaxMealCount;
|
|
||||||
return [for (var n = kMinMealCount; n <= maxCount; n++) n];
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _applySchedule(MealSchedule next) async {
|
Future<void> _applySchedule(MealSchedule next) async {
|
||||||
final normalized = next.normalized();
|
final normalized = next.normalized();
|
||||||
setState(() => _schedule = normalized);
|
setState(() => _schedule = normalized);
|
||||||
if (!MealScheduleService.isInitialized) return;
|
if (!MealScheduleService.isInitialized) return;
|
||||||
await MealScheduleService.instance.recordChange(normalized);
|
await MealScheduleService.instance.recordChange(normalized);
|
||||||
// The reminder ids are slot hours, so a schedule change orphans the ones
|
// The reminder ids are slot minutes, so a schedule change leaves posted
|
||||||
// it no longer contains. Re-running the check cancels them immediately
|
// reminders for checkpoints that no longer exist. Re-running the check
|
||||||
// rather than leaving a stale nag until the next background tick.
|
// cancels them immediately rather than leaving a stale nag until the
|
||||||
|
// next background tick.
|
||||||
await checkAndNotify(pullWhenDue: false);
|
await checkAndNotify(pullWhenDue: false);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Dropdowns rather than a time picker: `showTimePicker` returns minutes,
|
List<Widget> _mealScheduleSection(BuildContext context) => [
|
||||||
/// and slots are whole hours on both devices by design.
|
MealScheduleEditor(
|
||||||
Widget _hourDropdown({
|
schedule: _schedule,
|
||||||
required String label,
|
onChanged: (next) => unawaited(_applySchedule(next)),
|
||||||
required int value,
|
|
||||||
required List<int> hours,
|
|
||||||
required ValueChanged<int> onChanged,
|
|
||||||
}) => ConstrainedBox(
|
|
||||||
constraints: const BoxConstraints(maxWidth: AppWidth.field),
|
|
||||||
child: InputDecorator(
|
|
||||||
decoration: InputDecoration(labelText: label),
|
|
||||||
child: DropdownButtonHideUnderline(
|
|
||||||
child: DropdownButton<int>(
|
|
||||||
value: value,
|
|
||||||
isDense: true,
|
|
||||||
isExpanded: true,
|
|
||||||
items: [
|
|
||||||
for (final hour in hours)
|
|
||||||
DropdownMenuItem(value: hour, child: Text(slotLabel(hour))),
|
|
||||||
],
|
|
||||||
onChanged: (hour) => hour == null ? null : onChanged(hour),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
List<Widget> _mealScheduleSection(BuildContext context) {
|
|
||||||
final theme = Theme.of(context);
|
|
||||||
final counts = _selectableCounts;
|
|
||||||
return [
|
|
||||||
Text('Meal times', style: theme.textTheme.titleMedium),
|
|
||||||
const SizedBox(height: 4),
|
|
||||||
Text(
|
|
||||||
'Checkpoints are spread evenly between your first and last meal.',
|
|
||||||
style: theme.textTheme.bodySmall,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
_hourDropdown(
|
|
||||||
label: 'First meal',
|
|
||||||
value: _schedule.first,
|
|
||||||
// Leaves at least one hour of window, so `last` always has a value
|
|
||||||
// strictly after `first` to offer.
|
|
||||||
hours: [for (var h = kFirstHour; h < kLastHour; h++) h],
|
|
||||||
onChanged: (hour) => unawaited(
|
|
||||||
_applySchedule(
|
|
||||||
MealSchedule(
|
|
||||||
first: hour,
|
|
||||||
last: _schedule.last,
|
|
||||||
count: _schedule.count,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
_hourDropdown(
|
|
||||||
label: 'Last meal',
|
|
||||||
value: _schedule.last,
|
|
||||||
hours: [for (var h = _schedule.first + 1; h <= kLastHour; h++) h],
|
|
||||||
onChanged: (hour) => unawaited(
|
|
||||||
_applySchedule(
|
|
||||||
MealSchedule(
|
|
||||||
first: _schedule.first,
|
|
||||||
last: hour,
|
|
||||||
count: _schedule.count,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
ConstrainedBox(
|
|
||||||
constraints: const BoxConstraints(maxWidth: AppWidth.field),
|
|
||||||
child: InputDecorator(
|
|
||||||
decoration: const InputDecoration(labelText: 'Meals per day'),
|
|
||||||
child: DropdownButtonHideUnderline(
|
|
||||||
child: DropdownButton<int>(
|
|
||||||
value: counts.contains(_schedule.count)
|
|
||||||
? _schedule.count
|
|
||||||
: counts.last,
|
|
||||||
isDense: true,
|
|
||||||
isExpanded: true,
|
|
||||||
items: [
|
|
||||||
for (final count in counts)
|
|
||||||
DropdownMenuItem(value: count, child: Text('$count')),
|
|
||||||
],
|
|
||||||
onChanged: (count) => count == null
|
|
||||||
? null
|
|
||||||
: unawaited(
|
|
||||||
_applySchedule(
|
|
||||||
MealSchedule(
|
|
||||||
first: _schedule.first,
|
|
||||||
last: _schedule.last,
|
|
||||||
count: count,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
Text(
|
|
||||||
_schedule.slots().map(slotLabel).join(' · '),
|
|
||||||
style: theme.textTheme.bodyMedium,
|
|
||||||
),
|
),
|
||||||
];
|
];
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,18 +1,14 @@
|
|||||||
/// App settings: kcal goal, notifications, and links to the two sync
|
/// App settings: kcal goal, notifications, data export/import, and links to
|
||||||
/// surfaces.
|
/// the shared Firebase "Sync settings" and the app-local GitHub mirror (its
|
||||||
///
|
/// connect also runs a real `runSync`, which the shared screen does not).
|
||||||
/// "Sync settings" is the shared `sync_settings_ui` package (Firebase
|
|
||||||
/// only -- diet_guard has no local backup format, so `BackupSlot` is null).
|
|
||||||
/// "Advanced sync (GitHub)" stays app-local ([GitHubMirrorScreen]) because
|
|
||||||
/// connecting it also triggers a real log sync via `runSync`, which the
|
|
||||||
/// shared package's Firebase section does not do -- it only saves settings.
|
|
||||||
library;
|
library;
|
||||||
|
|
||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart'
|
||||||
|
show E2ePassphraseButton;
|
||||||
import 'package:diet_guard_app/models/meal_schedule.dart';
|
import 'package:diet_guard_app/models/meal_schedule.dart';
|
||||||
import 'package:diet_guard_app/models/slot.dart';
|
|
||||||
import 'package:diet_guard_app/screens/github_mirror_screen.dart';
|
import 'package:diet_guard_app/screens/github_mirror_screen.dart';
|
||||||
import 'package:diet_guard_app/screens/settings_kuchnia.dart';
|
import 'package:diet_guard_app/screens/settings_kuchnia.dart';
|
||||||
import 'package:diet_guard_app/services/app_settings_service.dart';
|
import 'package:diet_guard_app/services/app_settings_service.dart';
|
||||||
@ -21,11 +17,18 @@ import 'package:diet_guard_app/services/firebase_backend.dart';
|
|||||||
import 'package:diet_guard_app/services/firebase_client.dart';
|
import 'package:diet_guard_app/services/firebase_client.dart';
|
||||||
import 'package:diet_guard_app/services/google_sign_in_backend.dart';
|
import 'package:diet_guard_app/services/google_sign_in_backend.dart';
|
||||||
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
||||||
|
import 'package:diet_guard_app/services/sync_e2e.dart';
|
||||||
|
import 'package:diet_guard_app/ui/cues.dart';
|
||||||
|
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||||
import 'package:diet_guard_app/ui/theme.dart';
|
import 'package:diet_guard_app/ui/theme.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/data_backup_row.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/log_sound_tile.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/meal_schedule_editor.dart';
|
||||||
import 'package:flutter/foundation.dart';
|
import 'package:flutter/foundation.dart';
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:flutter/services.dart';
|
import 'package:flutter/services.dart';
|
||||||
import 'package:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:kuhy_credit/kuhy_credit.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:permission_handler/permission_handler.dart';
|
import 'package:permission_handler/permission_handler.dart';
|
||||||
import 'package:sync_settings_ui/sync_settings_ui.dart';
|
import 'package:sync_settings_ui/sync_settings_ui.dart';
|
||||||
|
|
||||||
@ -48,8 +51,7 @@ class SettingsScreen extends StatefulWidget {
|
|||||||
this.firebaseFactory,
|
this.firebaseFactory,
|
||||||
});
|
});
|
||||||
|
|
||||||
/// Injectable HTTP client for the linked [GitHubMirrorScreen]; tests pass
|
/// HTTP client for the linked [GitHubMirrorScreen]; tests pass [MockClient].
|
||||||
/// a [MockClient].
|
|
||||||
final http.Client? httpClient;
|
final http.Client? httpClient;
|
||||||
|
|
||||||
/// Injectable battery-optimization-exemption request; tests pass a fake.
|
/// Injectable battery-optimization-exemption request; tests pass a fake.
|
||||||
@ -69,14 +71,10 @@ class SettingsScreen extends StatefulWidget {
|
|||||||
/// Reads the stored Firebase account. Injected for the same reason as
|
/// Reads the stored Firebase account. Injected for the same reason as
|
||||||
/// [googleFirebaseFactory]: the keystore is a platform channel.
|
/// [googleFirebaseFactory]: the keystore is a platform channel.
|
||||||
///
|
///
|
||||||
/// Deliberately backed by [storedAccount], not [loadAccount]: the shared
|
/// Backed by [storedAccount], not [loadAccount]: the shared screen reads
|
||||||
/// `SyncSettingsScreen` uses this single closure both to display the
|
/// the account back right after a Google sign-in, and [loadAccount]'s
|
||||||
/// status and to read back the account right after a Google sign-in.
|
/// desktop fallback throws on Android (seen on the phone as "Google sign-in
|
||||||
/// [loadAccount]'s desktop-wrapper fallback resolves to `file:///` on
|
/// failed"). See the keystore-only read in [firebase_backend.dart].
|
||||||
/// Android and throws -- verified on the phone, where it turned a
|
|
||||||
/// successful sign-in into "Google sign-in failed". `storedAccount` is the
|
|
||||||
/// keystore-only read [firebase_backend.dart] documents for exactly this
|
|
||||||
/// read-back case.
|
|
||||||
final Future<FirebaseAccount?> Function()? accountLoader;
|
final Future<FirebaseAccount?> Function()? accountLoader;
|
||||||
|
|
||||||
/// Persists the account. See [accountLoader].
|
/// Persists the account. See [accountLoader].
|
||||||
@ -152,37 +150,31 @@ class _SettingsScreenState extends State<SettingsScreen>
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(title: const Text('Settings')),
|
// No title: the gear that opened this screen already names it.
|
||||||
// Centred and capped at the prose width. On the desktop surface this
|
appBar: AppBar(),
|
||||||
// ListView spanned the full ~1366px window, so the explanatory
|
// Capped at the prose width so fields do not span a ~1366px window.
|
||||||
// paragraphs below ran ~180 characters per line -- roughly twice the
|
|
||||||
// readable limit (tokens.md rule 21) -- and every field stretched with
|
|
||||||
// them. Invisible on the phone, where the window is already narrow.
|
|
||||||
body: Center(
|
body: Center(
|
||||||
child: ConstrainedBox(
|
child: ConstrainedBox(
|
||||||
constraints: const BoxConstraints(maxWidth: AppWidth.prose),
|
constraints: const BoxConstraints(maxWidth: AppWidth.prose),
|
||||||
child: ListView(
|
child: ListView(
|
||||||
padding: const EdgeInsets.all(16),
|
padding: const EdgeInsets.all(16),
|
||||||
children: [
|
children: [
|
||||||
Text('Nutrition', style: Theme.of(context).textTheme.titleMedium),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
// A four-digit number: capped so the field does not read as a
|
// A four-digit number: capped so the field does not read as a
|
||||||
// layout error by spanning the whole column.
|
// layout error by spanning the whole column.
|
||||||
ConstrainedBox(
|
ConstrainedBox(
|
||||||
constraints: const BoxConstraints(maxWidth: AppWidth.field),
|
constraints: const BoxConstraints(maxWidth: AppWidth.field),
|
||||||
child: TextField(
|
child: IconField(
|
||||||
|
icon: MacroKind.kcal.icon,
|
||||||
|
iconColor: MacroKind.kcal.color,
|
||||||
|
semanticLabel: 'Daily kcal goal',
|
||||||
controller: _kcalGoalController,
|
controller: _kcalGoalController,
|
||||||
keyboardType: TextInputType.number,
|
keyboardType: TextInputType.number,
|
||||||
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
|
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
|
||||||
decoration: const InputDecoration(
|
|
||||||
labelText: 'Daily kcal goal',
|
|
||||||
helperText: 'Shown in the history day summary',
|
|
||||||
suffixText: 'kcal',
|
|
||||||
),
|
|
||||||
onChanged: _onKcalGoalChanged,
|
onChanged: _onKcalGoalChanged,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 24),
|
const LogSoundTile(),
|
||||||
|
const SizedBox(height: 16),
|
||||||
const Divider(),
|
const Divider(),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
..._mealScheduleSection(context),
|
..._mealScheduleSection(context),
|
||||||
@ -191,55 +183,64 @@ class _SettingsScreenState extends State<SettingsScreen>
|
|||||||
const Divider(),
|
const Divider(),
|
||||||
ListTile(
|
ListTile(
|
||||||
contentPadding: EdgeInsets.zero,
|
contentPadding: EdgeInsets.zero,
|
||||||
title: const Text('Sync settings'),
|
leading: const Icon(
|
||||||
subtitle: const Text('Firebase sync'),
|
Icons.cloud_sync_outlined,
|
||||||
|
semanticLabel: 'Sync settings',
|
||||||
|
),
|
||||||
trailing: const Icon(Icons.chevron_right),
|
trailing: const Icon(Icons.chevron_right),
|
||||||
onTap: () => unawaited(_openSyncSettings()),
|
onTap: () => unawaited(_openSyncSettings()),
|
||||||
),
|
),
|
||||||
|
// End-to-end encryption passphrase: closed lock while the last
|
||||||
|
// sync found no usable key, so nothing syncs until it is set.
|
||||||
|
ValueListenableBuilder<bool>(
|
||||||
|
valueListenable: syncLocked,
|
||||||
|
builder: (_, locked, _) => ListTile(
|
||||||
|
contentPadding: EdgeInsets.zero,
|
||||||
|
leading: E2ePassphraseButton(locked: locked),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
// Legacy mirror: muted tint marks it as the secondary path.
|
||||||
ListTile(
|
ListTile(
|
||||||
contentPadding: EdgeInsets.zero,
|
contentPadding: EdgeInsets.zero,
|
||||||
title: const Text('Advanced sync (GitHub)'),
|
leading: Icon(
|
||||||
subtitle: const Text('Cutover mirror — not recommended'),
|
Icons.code,
|
||||||
|
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||||
|
semanticLabel: 'Advanced sync (GitHub)',
|
||||||
|
),
|
||||||
trailing: const Icon(Icons.chevron_right),
|
trailing: const Icon(Icons.chevron_right),
|
||||||
onTap: () => unawaited(_openGitHubMirror()),
|
onTap: () => unawaited(_openGitHubMirror()),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 24),
|
DataBackupRow(
|
||||||
const Divider(),
|
onImported: () => _kcalGoalController.text = AppSettingsService
|
||||||
const SizedBox(height: 8),
|
.dailyKcalGoal
|
||||||
Text(
|
.toString(),
|
||||||
'Notifications',
|
|
||||||
style: Theme.of(context).textTheme.titleMedium,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 4),
|
|
||||||
Text(
|
|
||||||
_isAndroid
|
|
||||||
? 'A background check nags you every ~15 min if a '
|
|
||||||
'meal slot is overdue. Aggressive OEM battery '
|
|
||||||
'optimization (MIUI, some Samsung configs) can '
|
|
||||||
'delay this well past 15 min -- request an '
|
|
||||||
'exemption for reliable nagging.'
|
|
||||||
: 'A check runs every 5 min while this window is open and '
|
|
||||||
'notifies you about an overdue meal slot. A browser '
|
|
||||||
'cannot run anything once the window is closed -- on '
|
|
||||||
'the PC the real backstop is the diet_guard gate, '
|
|
||||||
'which locks the screen instead.',
|
|
||||||
style: Theme.of(context).textTheme.bodySmall,
|
|
||||||
),
|
),
|
||||||
// Battery-optimization exemption is Android-only, and
|
// Battery-optimization exemption is Android-only, and
|
||||||
// `permission_handler` has no web implementation at all;
|
// `permission_handler` has no web implementation at all;
|
||||||
// the row would throw rather than degrade in the browser.
|
// the row would throw rather than degrade in the browser.
|
||||||
if (_isAndroid) ...[
|
if (_isAndroid) ...[
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 24),
|
||||||
OutlinedButton.icon(
|
const Divider(),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
Align(
|
||||||
|
alignment: Alignment.centerLeft,
|
||||||
|
child: IconButton.outlined(
|
||||||
onPressed: _requestBatteryExemption,
|
onPressed: _requestBatteryExemption,
|
||||||
icon: const Icon(Icons.battery_alert),
|
icon: const Icon(
|
||||||
label: const Text('Disable battery optimization'),
|
Icons.battery_alert,
|
||||||
|
semanticLabel: 'Disable battery optimization',
|
||||||
|
),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
if (_status != null) ...[
|
if (_status != null) ...[
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
Text(_status!, style: Theme.of(context).textTheme.bodyMedium),
|
Align(alignment: Alignment.centerLeft, child: _status),
|
||||||
],
|
],
|
||||||
|
const SizedBox(height: 24),
|
||||||
|
const Divider(),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
const Align(alignment: Alignment.centerLeft, child: KuhyCredit()),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|||||||
220
app/lib/services/activity_kcal.dart
Normal file
@ -0,0 +1,220 @@
|
|||||||
|
/// Exercise energy per workout, by every formula the workout data supports.
|
||||||
|
///
|
||||||
|
/// Port of `diet_guard/_activity_kcal.py`, gated by the shared
|
||||||
|
/// `tests/fixtures/body_calc.json`. Every formula returns **net** kcal --
|
||||||
|
/// energy above resting -- because the measured TDEE adds exercise on top of
|
||||||
|
/// `BMR x 1.2`, which already pays for the resting hour.
|
||||||
|
///
|
||||||
|
/// * **MET** (Compendium 2011): `(MET - 1) x kg x hours`, speed-interpolated
|
||||||
|
/// for runs and walks; lifting is code 02052 (resistance training) = 5.0.
|
||||||
|
/// * **ACSM** level-ground equations: net VO2 = 0.2 v (run) / 0.1 v (walk),
|
||||||
|
/// v in m/min; kcal = VO2 x kg x min x 5 / 1000.
|
||||||
|
/// * **Per-km**: 0.9 (run) / 0.5 (walk) kcal/kg/km net.
|
||||||
|
///
|
||||||
|
/// ACSM and per-km need a distance, so every other session falls back to
|
||||||
|
/// its MET figure (listed in [SessionKcal.fallback]).
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/models/workout_session.dart';
|
||||||
|
|
||||||
|
export 'package:diet_guard_app/models/workout_session.dart';
|
||||||
|
|
||||||
|
/// Formula names, in display order.
|
||||||
|
const List<String> activityFormulas = ['MET', 'ACSM', 'Per-km'];
|
||||||
|
|
||||||
|
/// Measured activity averages at most the last two full weeks.
|
||||||
|
const int maxWindowDays = 14;
|
||||||
|
|
||||||
|
const List<(double, double)> _runMetByKmh = [
|
||||||
|
(6.4, 6),
|
||||||
|
(8, 8.3),
|
||||||
|
(8.4, 9),
|
||||||
|
(9.7, 9.8),
|
||||||
|
(10.8, 10.5),
|
||||||
|
(11.3, 11),
|
||||||
|
(12.1, 11.5),
|
||||||
|
(12.9, 11.8),
|
||||||
|
(13.8, 12.3),
|
||||||
|
(14.5, 12.8),
|
||||||
|
(16.1, 14.5),
|
||||||
|
(17.7, 16),
|
||||||
|
(19.3, 19),
|
||||||
|
(20.9, 19.8),
|
||||||
|
(22.5, 23),
|
||||||
|
];
|
||||||
|
const List<(double, double)> _walkMetByKmh = [
|
||||||
|
(3.2, 2.8),
|
||||||
|
(4, 3),
|
||||||
|
(4.8, 3.5),
|
||||||
|
(5.6, 4.3),
|
||||||
|
(6.4, 5),
|
||||||
|
(7.2, 7),
|
||||||
|
(8, 8.3),
|
||||||
|
];
|
||||||
|
const Map<String, double> _fixedMet = {
|
||||||
|
'strength': 5,
|
||||||
|
'run': 8,
|
||||||
|
'walk': 3.5,
|
||||||
|
'cycle': 7.5,
|
||||||
|
'other': 4,
|
||||||
|
};
|
||||||
|
const Map<String, double> _acsmSlope = {'run': 0.2, 'walk': 0.1};
|
||||||
|
const Map<String, double> _netKcalPerKgKm = {'run': 0.9, 'walk': 0.5};
|
||||||
|
const double _kcalPerLitreO2 = 5;
|
||||||
|
|
||||||
|
/// Net kcal of one session per formula; [fallback] names MET stand-ins.
|
||||||
|
class SessionKcal {
|
||||||
|
/// Creates a result.
|
||||||
|
const SessionKcal(this.session, this.kcal, this.fallback);
|
||||||
|
|
||||||
|
/// The session measured.
|
||||||
|
final Session session;
|
||||||
|
|
||||||
|
/// Formula name -> net kcal.
|
||||||
|
final Map<String, double> kcal;
|
||||||
|
|
||||||
|
/// Formulas that could not apply and reuse the MET figure.
|
||||||
|
final Set<String> fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
double _interpolate(List<(double, double)> table, double kmh) {
|
||||||
|
if (kmh <= table.first.$1) return table.first.$2;
|
||||||
|
for (var i = 0; i + 1 < table.length; i++) {
|
||||||
|
final (x0, y0) = table[i];
|
||||||
|
final (x1, y1) = table[i + 1];
|
||||||
|
if (kmh <= x1) return y0 + (y1 - y0) * (kmh - x0) / (x1 - x0);
|
||||||
|
}
|
||||||
|
return table.last.$2;
|
||||||
|
}
|
||||||
|
|
||||||
|
double? _speedKmh(Session session) {
|
||||||
|
final km = session.km;
|
||||||
|
if (km == null || km <= 0 || session.minutes <= 0) return null;
|
||||||
|
return km / (session.minutes / 60.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The MET value for [session]: speed-based when possible, else fixed.
|
||||||
|
double metFor(Session session) {
|
||||||
|
final kmh = _speedKmh(session);
|
||||||
|
if (kmh != null && session.kind == 'run') {
|
||||||
|
return _interpolate(_runMetByKmh, kmh);
|
||||||
|
}
|
||||||
|
if (kmh != null && session.kind == 'walk') {
|
||||||
|
return _interpolate(_walkMetByKmh, kmh);
|
||||||
|
}
|
||||||
|
return _fixedMet[session.kind] ?? _fixedMet['other']!;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Net kcal of [session] for a [weightKg] person, by every formula.
|
||||||
|
SessionKcal sessionKcal(Session session, double weightKg) {
|
||||||
|
final hours = session.minutes / 60.0;
|
||||||
|
final met = (metFor(session) - 1.0) * weightKg * hours;
|
||||||
|
final kcal = {'MET': met, 'ACSM': met, 'Per-km': met};
|
||||||
|
final fallback = {'ACSM', 'Per-km'};
|
||||||
|
final kmh = _speedKmh(session);
|
||||||
|
final km = session.km;
|
||||||
|
final slope = _acsmSlope[session.kind];
|
||||||
|
if (kmh != null && km != null && slope != null) {
|
||||||
|
final metresPerMin = kmh * 1000.0 / 60.0;
|
||||||
|
final netVo2 = slope * metresPerMin;
|
||||||
|
kcal['ACSM'] = netVo2 * weightKg * session.minutes * _kcalPerLitreO2 / 1000;
|
||||||
|
kcal['Per-km'] = _netKcalPerKgKm[session.kind]! * weightKg * km;
|
||||||
|
fallback.clear();
|
||||||
|
}
|
||||||
|
return SessionKcal(session, kcal, fallback);
|
||||||
|
}
|
||||||
|
|
||||||
|
String _dateKey(DateTime day) {
|
||||||
|
String two(int v) => v.toString().padLeft(2, '0');
|
||||||
|
return '${day.year.toString().padLeft(4, '0')}-${two(day.month)}'
|
||||||
|
'-${two(day.day)}';
|
||||||
|
}
|
||||||
|
|
||||||
|
DateTime _utcDay(DateTime day) => DateTime.utc(day.year, day.month, day.day);
|
||||||
|
|
||||||
|
/// How many full past days [dailyExercise] averages over.
|
||||||
|
///
|
||||||
|
/// [maxWindowDays], or fewer while the earliest past data (a session or an
|
||||||
|
/// [extraByDay] key before [today]) is younger than that; 0 when there is no
|
||||||
|
/// past data at all.
|
||||||
|
int windowDays(
|
||||||
|
List<Session> sessions,
|
||||||
|
DateTime today, [
|
||||||
|
Map<String, double>? extraByDay,
|
||||||
|
]) {
|
||||||
|
final last = _dateKey(today);
|
||||||
|
final days = [
|
||||||
|
for (final session in sessions)
|
||||||
|
if (session.day.compareTo(last) < 0) session.day,
|
||||||
|
for (final day in (extraByDay ?? const <String, double>{}).keys)
|
||||||
|
if (day.compareTo(last) < 0) day,
|
||||||
|
];
|
||||||
|
if (days.isEmpty) return 0;
|
||||||
|
final earliest = days.reduce((a, b) => a.compareTo(b) <= 0 ? a : b);
|
||||||
|
// Whole UTC days, so a DST change cannot shave an hour off the count.
|
||||||
|
final span = _utcDay(
|
||||||
|
today,
|
||||||
|
).difference(DateTime.parse('${earliest}T00:00:00Z')).inDays;
|
||||||
|
return span < maxWindowDays ? span : maxWindowDays;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mean net exercise kcal per day over the full past days before [today].
|
||||||
|
///
|
||||||
|
/// The window ends yesterday (today is still in progress) and starts
|
||||||
|
/// [maxWindowDays] back -- or, while the data is younger than that, on the
|
||||||
|
/// first day that has any, so a week of history is averaged over that week
|
||||||
|
/// rather than diluted over 14 days ([windowDays]). The denominator is
|
||||||
|
/// calendar days within that span: a rest day burns no exercise kcal. With
|
||||||
|
/// no past data at all, every formula reads 0.
|
||||||
|
///
|
||||||
|
/// [extraByDay] (day -> net kcal, e.g. steps outside workouts) is added to
|
||||||
|
/// every formula alike: it is not a workout any formula could measure.
|
||||||
|
Map<String, double> dailyExercise(
|
||||||
|
List<Session> sessions,
|
||||||
|
double weightKg,
|
||||||
|
DateTime today, [
|
||||||
|
Map<String, double>? extraByDay,
|
||||||
|
]) {
|
||||||
|
final totals = {for (final name in activityFormulas) name: 0.0};
|
||||||
|
final span = windowDays(sessions, today, extraByDay);
|
||||||
|
if (span == 0) return totals;
|
||||||
|
// Calendar arithmetic via the constructor, not Duration: subtracting N x
|
||||||
|
// 24 h across a DST change lands on 23:00 of the wrong day.
|
||||||
|
final first = _dateKey(DateTime(today.year, today.month, today.day - span));
|
||||||
|
final last = _dateKey(today);
|
||||||
|
bool inWindow(String day) =>
|
||||||
|
day.compareTo(first) >= 0 && day.compareTo(last) < 0;
|
||||||
|
for (final session in sessions) {
|
||||||
|
if (!inWindow(session.day)) continue;
|
||||||
|
sessionKcal(session, weightKg).kcal.forEach((name, value) {
|
||||||
|
totals[name] = totals[name]! + value;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
extraByDay?.forEach((day, kcal) {
|
||||||
|
if (!inWindow(day)) return;
|
||||||
|
for (final name in activityFormulas) {
|
||||||
|
totals[name] = totals[name]! + kcal;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return totals.map((name, total) => MapEntry(name, total / span));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The part of every [dailyExercise] mean that [extraByDay] contributes,
|
||||||
|
/// over the very same window -- so a "steps add N kcal/day (included above)"
|
||||||
|
/// line always adds up to the total it claims to be part of. Mirrors the
|
||||||
|
/// steps share computed in `diet_guard/_body_view.py`.
|
||||||
|
double extraShare(
|
||||||
|
List<Session> sessions,
|
||||||
|
DateTime today,
|
||||||
|
Map<String, double> extraByDay,
|
||||||
|
) {
|
||||||
|
final span = windowDays(sessions, today, extraByDay);
|
||||||
|
if (span == 0) return 0;
|
||||||
|
final first = _dateKey(DateTime(today.year, today.month, today.day - span));
|
||||||
|
final last = _dateKey(today);
|
||||||
|
var sum = 0.0;
|
||||||
|
extraByDay.forEach((day, kcal) {
|
||||||
|
if (day.compareTo(first) >= 0 && day.compareTo(last) < 0) sum += kcal;
|
||||||
|
});
|
||||||
|
return sum / span;
|
||||||
|
}
|
||||||
@ -33,6 +33,7 @@ class AppSettingsService {
|
|||||||
final DocumentStore _store;
|
final DocumentStore _store;
|
||||||
int _dailyKcalGoal = kDefaultDailyKcalGoal;
|
int _dailyKcalGoal = kDefaultDailyKcalGoal;
|
||||||
DateTime? _dailyKcalGoalUpdatedAt;
|
DateTime? _dailyKcalGoalUpdatedAt;
|
||||||
|
bool _soundOnLog = true;
|
||||||
|
|
||||||
/// Returns the configured daily kcal goal, or the default when
|
/// Returns the configured daily kcal goal, or the default when
|
||||||
/// uninitialised. This is the budget in force *today*; asking what applied
|
/// uninitialised. This is the budget in force *today*; asking what applied
|
||||||
@ -44,6 +45,19 @@ class AppSettingsService {
|
|||||||
static DateTime? get dailyKcalGoalUpdatedAt =>
|
static DateTime? get dailyKcalGoalUpdatedAt =>
|
||||||
_instance?._dailyKcalGoalUpdatedAt;
|
_instance?._dailyKcalGoalUpdatedAt;
|
||||||
|
|
||||||
|
/// Whether a logged meal plays the confirm cue; on unless turned off.
|
||||||
|
///
|
||||||
|
/// Device-local, deliberately not synced: a phone in a meeting and a PC
|
||||||
|
/// with speakers want different answers.
|
||||||
|
static bool get soundOnLog => _instance?._soundOnLog ?? true;
|
||||||
|
|
||||||
|
/// Persists [on] without touching the budget's edit stamp, which would
|
||||||
|
/// otherwise make this device win the next budget merge.
|
||||||
|
Future<void> setSoundOnLog({required bool on}) async {
|
||||||
|
_soundOnLog = on;
|
||||||
|
await _writeToDisk();
|
||||||
|
}
|
||||||
|
|
||||||
/// Initialises the singleton against the platform document store (files on
|
/// Initialises the singleton against the platform document store (files on
|
||||||
/// Android, IndexedDB in the browser-hosted desktop app).
|
/// Android, IndexedDB in the browser-hosted desktop app).
|
||||||
static Future<AppSettingsService> init() async {
|
static Future<AppSettingsService> init() async {
|
||||||
@ -105,6 +119,9 @@ class AppSettingsService {
|
|||||||
data['daily_kcal_goal_updated_at'] as String,
|
data['daily_kcal_goal_updated_at'] as String,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
if (data is Map && data['sound_on_log'] is bool) {
|
||||||
|
_soundOnLog = data['sound_on_log'] as bool;
|
||||||
|
}
|
||||||
} on Exception {
|
} on Exception {
|
||||||
// Ignore parse errors and keep defaults.
|
// Ignore parse errors and keep defaults.
|
||||||
}
|
}
|
||||||
@ -160,6 +177,7 @@ class AppSettingsService {
|
|||||||
'daily_kcal_goal': _dailyKcalGoal,
|
'daily_kcal_goal': _dailyKcalGoal,
|
||||||
'daily_kcal_goal_updated_at': _dailyKcalGoalUpdatedAt
|
'daily_kcal_goal_updated_at': _dailyKcalGoalUpdatedAt
|
||||||
?.toIso8601String(),
|
?.toIso8601String(),
|
||||||
|
'sound_on_log': _soundOnLog,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -7,6 +7,7 @@ library;
|
|||||||
|
|
||||||
import 'dart:developer';
|
import 'dart:developer';
|
||||||
import 'package:diet_guard_app/services/app_settings_service.dart';
|
import 'package:diet_guard_app/services/app_settings_service.dart';
|
||||||
|
import 'package:diet_guard_app/services/body_service.dart';
|
||||||
import 'package:diet_guard_app/services/budget_history_service.dart';
|
import 'package:diet_guard_app/services/budget_history_service.dart';
|
||||||
import 'package:diet_guard_app/services/firebase_client.dart';
|
import 'package:diet_guard_app/services/firebase_client.dart';
|
||||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||||
@ -14,6 +15,7 @@ import 'package:diet_guard_app/services/github_client_factory.dart';
|
|||||||
import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
|
import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
|
||||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
||||||
|
import 'package:diet_guard_app/services/sync_attempt.dart';
|
||||||
import 'package:diet_guard_app/services/sync_device_id.dart';
|
import 'package:diet_guard_app/services/sync_device_id.dart';
|
||||||
import 'package:diet_guard_app/services/sync_health.dart';
|
import 'package:diet_guard_app/services/sync_health.dart';
|
||||||
import 'package:diet_guard_app/services/sync_service.dart';
|
import 'package:diet_guard_app/services/sync_service.dart';
|
||||||
@ -62,6 +64,9 @@ Future<bool> backgroundSyncPush({http.Client? httpClient}) async {
|
|||||||
// neither publish this device's catering credential nor receive a peer's --
|
// neither publish this device's catering credential nor receive a peer's --
|
||||||
// and on the phone the background tick is most of the syncing there is.
|
// and on the phone the background tick is most of the syncing there is.
|
||||||
await KuchniaCredentialService.init();
|
await KuchniaCredentialService.init();
|
||||||
|
// `syncBody` no-ops without it, and the background tick is when the
|
||||||
|
// phone ingests the morning weigh-in.
|
||||||
|
await BodyService.init();
|
||||||
final SyncSettings settings;
|
final SyncSettings settings;
|
||||||
try {
|
try {
|
||||||
settings = await SyncSettings.load();
|
settings = await SyncSettings.load();
|
||||||
@ -86,21 +91,14 @@ Future<bool> backgroundSyncPush({http.Client? httpClient}) async {
|
|||||||
return true; // nothing to push; don't retry
|
return true; // nothing to push; don't retry
|
||||||
}
|
}
|
||||||
final client = createGitHubClient(settings, httpClient: httpClient);
|
final client = createGitHubClient(settings, httpClient: httpClient);
|
||||||
|
// Never silent: attemptSync records the outcome, the only signal that a
|
||||||
|
// background push failed. False -> WorkManager retries with backoff.
|
||||||
|
final landed = await attemptSync(() async {
|
||||||
try {
|
try {
|
||||||
await runSync(await syncBackend(client));
|
await runSync(await syncBackend(client));
|
||||||
await SyncHealth.recordSuccess();
|
|
||||||
return true;
|
|
||||||
} on Exception catch (error, stackTrace) {
|
|
||||||
// Never silent: this is the only signal that a background push failed.
|
|
||||||
log(
|
|
||||||
'diet_guard background sync failed',
|
|
||||||
level: 1000,
|
|
||||||
error: error,
|
|
||||||
stackTrace: stackTrace,
|
|
||||||
);
|
|
||||||
await SyncHealth.recordFailure();
|
|
||||||
return false; // offline / transient error -> retry with backoff
|
|
||||||
} finally {
|
} finally {
|
||||||
client.close();
|
client.close();
|
||||||
}
|
}
|
||||||
|
});
|
||||||
|
return landed;
|
||||||
}
|
}
|
||||||
|
|||||||
216
app/lib/services/body_calc.dart
Normal file
@ -0,0 +1,216 @@
|
|||||||
|
/// BMI, ideal-weight and resting-metabolism formulas -- pure arithmetic.
|
||||||
|
///
|
||||||
|
/// Byte-for-byte port of `diet_guard/_body_calc.py`, gated by the shared
|
||||||
|
/// `tests/fixtures/body_calc.json` (`test/services/body_parity_test.dart`).
|
||||||
|
/// Rounding goes through [halfUp], never `.round()`: Dart rounds half away
|
||||||
|
/// from zero and Python's `round` is banker's, so the bare builtins would
|
||||||
|
/// print different numbers on the two devices for the same person.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:math' as math;
|
||||||
|
|
||||||
|
const double _cmPerInch = 2.54;
|
||||||
|
const double _fiveFeetIn = 60;
|
||||||
|
|
||||||
|
/// Adult BMI categories are WHO's and do not apply to anyone still growing.
|
||||||
|
const int adultAge = 20;
|
||||||
|
const double _bmiPrimeDivisor = 25;
|
||||||
|
const double _healthyBmiLow = 18.5;
|
||||||
|
const double _healthyBmiHigh = 24.9;
|
||||||
|
const double _targetBmi = 22;
|
||||||
|
|
||||||
|
// (upper bound exclusive, label), WHO adult classification.
|
||||||
|
const List<(double, String)> _bmiBands = [
|
||||||
|
(16, 'severe thinness'),
|
||||||
|
(17, 'moderate thinness'),
|
||||||
|
(18.5, 'mild thinness'),
|
||||||
|
(25, 'normal'),
|
||||||
|
(30, 'overweight'),
|
||||||
|
(35, 'obese class I'),
|
||||||
|
(40, 'obese class II'),
|
||||||
|
];
|
||||||
|
const String _topBand = 'obese class III';
|
||||||
|
|
||||||
|
/// The lean-mass formula the calorie table switches to with a body fat %.
|
||||||
|
const String katchMcArdle = 'Katch-McArdle';
|
||||||
|
|
||||||
|
/// Rounds [value] half-up at [digits] decimals, identically to Python.
|
||||||
|
double halfUp(double value, [int digits = 0]) {
|
||||||
|
final scale = math.pow(10, digits).toDouble();
|
||||||
|
return (value * scale + 0.5).floorToDouble() / scale;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Body metrics that feed every formula.
|
||||||
|
///
|
||||||
|
/// Mirrors Python's `_budget_biometrics.Biometrics`.
|
||||||
|
class Biometrics {
|
||||||
|
/// Creates a set of body metrics.
|
||||||
|
const Biometrics({
|
||||||
|
required this.weightKg,
|
||||||
|
required this.heightCm,
|
||||||
|
required this.ageYears,
|
||||||
|
required this.isMale,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Body mass in kilograms.
|
||||||
|
final double weightKg;
|
||||||
|
|
||||||
|
/// Height in centimetres.
|
||||||
|
final double heightCm;
|
||||||
|
|
||||||
|
/// Age in completed years.
|
||||||
|
final double ageYears;
|
||||||
|
|
||||||
|
/// True for the male constants.
|
||||||
|
final bool isMale;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One named formula's result; [value] is null when it does not apply.
|
||||||
|
class Formula {
|
||||||
|
/// Creates a formula result.
|
||||||
|
const Formula(this.name, this.value);
|
||||||
|
|
||||||
|
/// Display name.
|
||||||
|
final String name;
|
||||||
|
|
||||||
|
/// The result, or null when undefined for this person.
|
||||||
|
final double? value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Body-mass index and its readings.
|
||||||
|
class BmiReport {
|
||||||
|
/// Creates a report.
|
||||||
|
const BmiReport({
|
||||||
|
required this.bmi,
|
||||||
|
required this.prime,
|
||||||
|
required this.trefethen,
|
||||||
|
required this.category,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Classic BMI, kg / m^2.
|
||||||
|
final double bmi;
|
||||||
|
|
||||||
|
/// BMI divided by 25.
|
||||||
|
final double prime;
|
||||||
|
|
||||||
|
/// Trefethen's "new BMI", 1.3 * kg / m^2.5.
|
||||||
|
final double trefethen;
|
||||||
|
|
||||||
|
/// WHO adult band, or a note that it does not apply (< 20 y).
|
||||||
|
final String category;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mifflin-St Jeor resting metabolic rate, kcal/day.
|
||||||
|
double mifflinStJeorBmr(Biometrics bio) {
|
||||||
|
final base = 10.0 * bio.weightKg + 6.25 * bio.heightCm - 5.0 * bio.ageYears;
|
||||||
|
return bio.isMale ? base + 5.0 : base - 161.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
String _category(double bmi, double ageYears) {
|
||||||
|
if (ageYears < adultAge) return 'adult categories do not apply under 20';
|
||||||
|
for (final (upper, label) in _bmiBands) {
|
||||||
|
if (bmi < upper) return label;
|
||||||
|
}
|
||||||
|
return _topBand;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns BMI, BMI Prime, Trefethen's BMI and the WHO category.
|
||||||
|
BmiReport bmiReport(Biometrics bio) {
|
||||||
|
final metres = bio.heightCm / 100.0;
|
||||||
|
final bmi = bio.weightKg / (metres * metres);
|
||||||
|
return BmiReport(
|
||||||
|
bmi: bmi,
|
||||||
|
prime: bmi / _bmiPrimeDivisor,
|
||||||
|
trefethen: 1.3 * bio.weightKg / math.pow(metres, 2.5),
|
||||||
|
category: _category(bmi, bio.ageYears),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
double? _perInch(
|
||||||
|
double inches,
|
||||||
|
double base,
|
||||||
|
double perInch, {
|
||||||
|
required bool defined,
|
||||||
|
}) => defined ? base + perInch * inches : null;
|
||||||
|
|
||||||
|
/// Every ideal-body-weight formula we can evaluate, in kg.
|
||||||
|
///
|
||||||
|
/// Only data-backed ones (Devine, its MetLife refits, Peterson); Broca, its
|
||||||
|
/// derivatives and Hamwi were dropped. The BMI healthy range is
|
||||||
|
/// [healthyRange], shown with BMI; [idealSummary] averages these.
|
||||||
|
List<Formula> idealWeights(Biometrics bio) {
|
||||||
|
final h = bio.heightCm;
|
||||||
|
final inches = h / _cmPerInch - _fiveFeetIn;
|
||||||
|
final ok = inches >= 0;
|
||||||
|
final male = bio.isMale;
|
||||||
|
final metres = h / 100.0;
|
||||||
|
return [
|
||||||
|
Formula('Devine', _perInch(inches, male ? 50 : 45.5, 2.3, defined: ok)),
|
||||||
|
Formula(
|
||||||
|
'Robinson',
|
||||||
|
_perInch(inches, male ? 52 : 49, male ? 1.9 : 1.7, defined: ok),
|
||||||
|
),
|
||||||
|
Formula(
|
||||||
|
'Miller',
|
||||||
|
_perInch(inches, male ? 56.2 : 53.1, male ? 1.41 : 1.36, defined: ok),
|
||||||
|
),
|
||||||
|
Formula(
|
||||||
|
'Peterson (BMI 22)',
|
||||||
|
2.2 * _targetBmi + 3.5 * _targetBmi * (metres - 1.5),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The weights (kg) at BMI 18.5 and 24.9 for this height.
|
||||||
|
(double, double) healthyRange(Biometrics bio) {
|
||||||
|
final metres = bio.heightCm / 100.0;
|
||||||
|
return (_healthyBmiLow * metres * metres, _healthyBmiHigh * metres * metres);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `(average, lowest, highest)` of the formulas that apply, or null.
|
||||||
|
(double, double, double)? idealSummary(List<Formula> formulas) {
|
||||||
|
final values = [for (final f in formulas) ?f.value];
|
||||||
|
if (values.isEmpty) return null;
|
||||||
|
final sum = values.fold<double>(0, (a, b) => a + b);
|
||||||
|
return (
|
||||||
|
sum / values.length,
|
||||||
|
values.reduce(math.min),
|
||||||
|
values.reduce(math.max),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resting metabolic rate by every formula, kcal/day.
|
||||||
|
///
|
||||||
|
/// Katch-McArdle and Cunningham work from lean mass, so they are null until
|
||||||
|
/// a body-fat % is logged.
|
||||||
|
List<Formula> bmrFormulas(Biometrics bio, [double? bodyFatPct]) {
|
||||||
|
final w = bio.weightKg;
|
||||||
|
final h = bio.heightCm;
|
||||||
|
final a = bio.ageYears;
|
||||||
|
final revised = bio.isMale
|
||||||
|
? 88.362 + 13.397 * w + 4.799 * h - 5.677 * a
|
||||||
|
: 447.593 + 9.247 * w + 3.098 * h - 4.330 * a;
|
||||||
|
final lean = bodyFatPct == null ? null : w * (1.0 - bodyFatPct / 100.0);
|
||||||
|
return [
|
||||||
|
Formula('Mifflin-St Jeor', mifflinStJeorBmr(bio)),
|
||||||
|
Formula('Harris-Benedict (revised 1984)', revised),
|
||||||
|
Formula(katchMcArdle, lean == null ? null : 370.0 + 21.6 * lean),
|
||||||
|
Formula('Cunningham', lean == null ? null : 500.0 + 22.0 * lean),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The BMR the calorie table uses: Katch-McArdle with body fat, else Mifflin.
|
||||||
|
Formula tableBmr(Biometrics bio, double? bodyFatPct) {
|
||||||
|
final formulas = bmrFormulas(bio, bodyFatPct);
|
||||||
|
return bodyFatPct != null ? formulas[2] : formulas[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Completed years between [birth] and [today].
|
||||||
|
int ageOn(DateTime birth, DateTime today) {
|
||||||
|
var years = today.year - birth.year;
|
||||||
|
if (today.month < birth.month ||
|
||||||
|
(today.month == birth.month && today.day < birth.day)) {
|
||||||
|
years -= 1;
|
||||||
|
}
|
||||||
|
return years;
|
||||||
|
}
|
||||||
206
app/lib/services/body_energy.dart
Normal file
@ -0,0 +1,206 @@
|
|||||||
|
/// The daily calorie target for one chosen goal -- the Body screen's top
|
||||||
|
/// line: "To **lose** **0.5** **kg** / **week** on **Moderate** eat
|
||||||
|
/// **2019** kcal". Every bold word is a [Goal] choice, remembered and synced
|
||||||
|
/// (`body_prefs.dart`). **Informational only**: nothing here writes the
|
||||||
|
/// budget.
|
||||||
|
///
|
||||||
|
/// Port of `diet_guard/_body_energy.py`, gated by the shared
|
||||||
|
/// `tests/fixtures/body_calc.json`. TDEE is the table BMR x an activity
|
||||||
|
/// factor, or for a "Measured" choice `BMR x 1.2` plus the real mean daily
|
||||||
|
/// exercise by that formula. Target = `TDEE -/+ kg per day x 7700`; below
|
||||||
|
/// the 1200 kcal floor it is flagged, never clamped.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/services/activity_kcal.dart';
|
||||||
|
import 'package:diet_guard_app/services/body_calc.dart';
|
||||||
|
|
||||||
|
/// kcal per kg of body fat.
|
||||||
|
const double kcalPerKg = 7700;
|
||||||
|
|
||||||
|
/// The floor below which a target is flagged.
|
||||||
|
const int minTargetKcal = 1200;
|
||||||
|
|
||||||
|
const double _sedentary = 1.2;
|
||||||
|
|
||||||
|
/// A "Measured" choice is `measured:<formula>` (MET, ACSM, Per-km).
|
||||||
|
const String measuredPrefix = 'measured:';
|
||||||
|
|
||||||
|
/// Goal directions, in menu order.
|
||||||
|
const List<String> directions = ['lose', 'maintain', 'gain'];
|
||||||
|
|
||||||
|
/// Offered in the amount picker; any other typed number is accepted too.
|
||||||
|
const List<double> presetAmounts = [0.25, 0.5, 0.75, 1];
|
||||||
|
|
||||||
|
/// Kilograms per weight unit.
|
||||||
|
const Map<String, double> weightUnits = {
|
||||||
|
'kg': 1,
|
||||||
|
'lb': 0.45359237,
|
||||||
|
'g': 0.001,
|
||||||
|
'st': 6.35029318,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Days per time unit; a month is the mean Gregorian month.
|
||||||
|
const Map<String, double> timeUnits = {
|
||||||
|
'day': 1,
|
||||||
|
'week': 7,
|
||||||
|
'month': 30.436875,
|
||||||
|
'year': 365.2425,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// One selectable activity level and its TDEE multiplier.
|
||||||
|
class ActivityLevel {
|
||||||
|
/// Creates a level.
|
||||||
|
const ActivityLevel(this.key, this.label, this.factor, this.meaning);
|
||||||
|
|
||||||
|
/// Stable key.
|
||||||
|
final String key;
|
||||||
|
|
||||||
|
/// Display label.
|
||||||
|
final String label;
|
||||||
|
|
||||||
|
/// BMR multiplier.
|
||||||
|
final double factor;
|
||||||
|
|
||||||
|
/// What the level means, shown in the picker.
|
||||||
|
final String meaning;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every activity level, in display order.
|
||||||
|
const List<ActivityLevel> activityLevels = [
|
||||||
|
ActivityLevel('sedentary', 'Sedentary', 1.2, 'little or no exercise'),
|
||||||
|
ActivityLevel('light', 'Light', 1.375, 'exercise 1-3x a week'),
|
||||||
|
ActivityLevel('moderate', 'Moderate', 1.55, 'exercise 3-5x a week'),
|
||||||
|
ActivityLevel('very', 'Very active', 1.725, 'exercise 6-7x a week'),
|
||||||
|
ActivityLevel('extra', 'Extra active', 1.9, 'training twice a day'),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// Every activity choice, in menu order: the five levels, then measured.
|
||||||
|
final List<String> activityChoices = [
|
||||||
|
for (final level in activityLevels) level.key,
|
||||||
|
for (final name in activityFormulas) '$measuredPrefix$name',
|
||||||
|
];
|
||||||
|
|
||||||
|
/// What the user wants: direction, amount per time, at an activity.
|
||||||
|
class Goal {
|
||||||
|
/// Creates a goal.
|
||||||
|
const Goal(
|
||||||
|
this.direction,
|
||||||
|
this.amount,
|
||||||
|
this.weightUnit,
|
||||||
|
this.timeUnit,
|
||||||
|
this.activity,
|
||||||
|
);
|
||||||
|
|
||||||
|
/// `lose`, `maintain` or `gain`.
|
||||||
|
final String direction;
|
||||||
|
|
||||||
|
/// How much, in [weightUnit] per [timeUnit].
|
||||||
|
final double amount;
|
||||||
|
|
||||||
|
/// A [weightUnits] key.
|
||||||
|
final String weightUnit;
|
||||||
|
|
||||||
|
/// A [timeUnits] key.
|
||||||
|
final String timeUnit;
|
||||||
|
|
||||||
|
/// An [activityChoices] entry.
|
||||||
|
final String activity;
|
||||||
|
|
||||||
|
/// Returns a copy with the given parts replaced.
|
||||||
|
Goal copyWith({
|
||||||
|
String? direction,
|
||||||
|
double? amount,
|
||||||
|
String? weightUnit,
|
||||||
|
String? timeUnit,
|
||||||
|
String? activity,
|
||||||
|
}) => Goal(
|
||||||
|
direction ?? this.direction,
|
||||||
|
amount ?? this.amount,
|
||||||
|
weightUnit ?? this.weightUnit,
|
||||||
|
timeUnit ?? this.timeUnit,
|
||||||
|
activity ?? this.activity,
|
||||||
|
);
|
||||||
|
|
||||||
|
/// Signed change in kg/day: positive loses, negative gains.
|
||||||
|
double kgPerDay() {
|
||||||
|
if (direction == 'maintain') return 0;
|
||||||
|
final rate = amount * weightUnits[weightUnit]! / timeUnits[timeUnit]!;
|
||||||
|
return direction == 'lose' ? rate : -rate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The goal until the user picks one.
|
||||||
|
const Goal defaultGoal = Goal('lose', 0.5, 'kg', 'week', 'moderate');
|
||||||
|
|
||||||
|
/// The answer to a [Goal], or why there is none.
|
||||||
|
class Target {
|
||||||
|
/// Creates a target.
|
||||||
|
const Target({required this.kcal, required this.tdee, required this.bmrName});
|
||||||
|
|
||||||
|
/// Daily target, or null when the goal needs unpublished measured data.
|
||||||
|
final int? kcal;
|
||||||
|
|
||||||
|
/// The maintenance figure it was derived from, when known.
|
||||||
|
final double? tdee;
|
||||||
|
|
||||||
|
/// The resting-burn formula the TDEE scales.
|
||||||
|
final String bmrName;
|
||||||
|
|
||||||
|
/// Whether the target is under the 1200 kcal floor.
|
||||||
|
bool get belowFloor {
|
||||||
|
final value = kcal;
|
||||||
|
return value != null && value < minTargetKcal;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Python's `f"{x:g}"`: six significant digits, trailing zeros dropped.
|
||||||
|
String formatG(double value) {
|
||||||
|
if (value == value.truncateToDouble() && value.abs() < 1e15) {
|
||||||
|
return value.toInt().toString();
|
||||||
|
}
|
||||||
|
var text = value.toStringAsPrecision(6);
|
||||||
|
if (text.contains('.') && !text.contains('e')) {
|
||||||
|
text = text
|
||||||
|
.replaceFirst(RegExp(r'0+$'), '')
|
||||||
|
.replaceFirst(RegExp(r'\.$'), '');
|
||||||
|
}
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Menu text for an activity choice, e.g. `Measured (ACSM)`.
|
||||||
|
String activityLabel(String key) {
|
||||||
|
if (key.startsWith(measuredPrefix)) {
|
||||||
|
return 'Measured (${key.substring(measuredPrefix.length)})';
|
||||||
|
}
|
||||||
|
for (final level in activityLevels) {
|
||||||
|
if (level.key == key) return level.label;
|
||||||
|
}
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
|
||||||
|
double? _tdee(double bmr, String activity, Map<String, double>? exercise) {
|
||||||
|
if (activity.startsWith(measuredPrefix)) {
|
||||||
|
final kcal = exercise?[activity.substring(measuredPrefix.length)];
|
||||||
|
return kcal == null ? null : bmr * _sedentary + kcal;
|
||||||
|
}
|
||||||
|
for (final level in activityLevels) {
|
||||||
|
if (level.key == activity) return bmr * level.factor;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The daily kcal that meets [goal] from a [bmr] (kcal/day).
|
||||||
|
Target goalTarget(
|
||||||
|
Goal goal,
|
||||||
|
double bmr,
|
||||||
|
String bmrName,
|
||||||
|
Map<String, double>? exercise,
|
||||||
|
) {
|
||||||
|
final tdee = _tdee(bmr, goal.activity, exercise);
|
||||||
|
if (tdee == null) return Target(kcal: null, tdee: null, bmrName: bmrName);
|
||||||
|
return Target(
|
||||||
|
kcal: halfUp(tdee - goal.kgPerDay() * kcalPerKg).toInt(),
|
||||||
|
tdee: tdee,
|
||||||
|
bmrName: bmrName,
|
||||||
|
);
|
||||||
|
}
|
||||||
49
app/lib/services/body_prefs.dart
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
/// The calorie goal the user last picked -- remembered and synced.
|
||||||
|
///
|
||||||
|
/// Stored as one extra field, `goal`, on the synced `profile` record (its
|
||||||
|
/// own stamp: saving it never counts as editing birth, height or sex), so the
|
||||||
|
/// sentence "To lose 0.5 kg / week on Moderate eat ..." reads the same on
|
||||||
|
/// the PC gate and the phone. Each part is validated on read: an unknown
|
||||||
|
/// direction, unit or activity falls back to that part of [defaultGoal].
|
||||||
|
///
|
||||||
|
/// Port of `diet_guard/_body_prefs.py`.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/services/body_energy.dart';
|
||||||
|
import 'package:diet_guard_app/services/body_service.dart';
|
||||||
|
|
||||||
|
/// The profile field the goal is stored under.
|
||||||
|
const String goalField = 'goal';
|
||||||
|
|
||||||
|
/// The wire/disk form (short keys).
|
||||||
|
Map<String, Object> goalToJson(Goal goal) => {
|
||||||
|
'dir': goal.direction,
|
||||||
|
'amt': goal.amount,
|
||||||
|
'wu': goal.weightUnit,
|
||||||
|
'tu': goal.timeUnit,
|
||||||
|
'act': goal.activity,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Parses a stored goal part by part, defaulting whatever is unusable.
|
||||||
|
Goal goalFromJson(Object? raw) {
|
||||||
|
if (raw is! Map) return defaultGoal;
|
||||||
|
final dir = raw['dir'];
|
||||||
|
final amt = raw['amt'];
|
||||||
|
final wu = raw['wu'];
|
||||||
|
final tu = raw['tu'];
|
||||||
|
final act = raw['act'];
|
||||||
|
return defaultGoal.copyWith(
|
||||||
|
direction: dir is String && directions.contains(dir) ? dir : null,
|
||||||
|
amount: amt is num && amt >= 0 ? amt.toDouble() : null,
|
||||||
|
weightUnit: wu is String && weightUnits.containsKey(wu) ? wu : null,
|
||||||
|
timeUnit: tu is String && timeUnits.containsKey(tu) ? tu : null,
|
||||||
|
activity: act is String && activityChoices.contains(act) ? act : null,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The remembered goal (the default until one is saved).
|
||||||
|
Goal savedGoal(BodyService body) => goalFromJson(body.profileValue(goalField));
|
||||||
|
|
||||||
|
/// Remembers (and syncs) [goal].
|
||||||
|
Future<void> setGoal(BodyService body, Goal goal) =>
|
||||||
|
body.setProfileFields({goalField: goalToJson(goal)});
|
||||||
225
app/lib/services/body_service.dart
Normal file
@ -0,0 +1,225 @@
|
|||||||
|
/// Persistence for the Body document: profile, weight log, PC workouts.
|
||||||
|
///
|
||||||
|
/// A singleton over the platform [DocumentStore], shaped like
|
||||||
|
/// `MealScheduleService`. Every setter stamps the edited part with "now", so
|
||||||
|
/// a manual edit outranks an ingested phone weigh-in of the same day in the
|
||||||
|
/// last-writer-wins merge (`sync_merge_body.dart`). Nothing here touches the
|
||||||
|
/// budget -- the Body screen is informational only.
|
||||||
|
///
|
||||||
|
/// Mirrors the storage half of `diet_guard/_body_store.py`.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/models/body_document.dart';
|
||||||
|
import 'package:diet_guard_app/models/local_time.dart';
|
||||||
|
import 'package:diet_guard_app/services/activity_kcal.dart';
|
||||||
|
import 'package:diet_guard_app/services/body_calc.dart';
|
||||||
|
import 'package:diet_guard_app/services/document_store.dart';
|
||||||
|
import 'package:diet_guard_app/services/document_store_factory.dart';
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
|
||||||
|
/// Singleton owning the `body.json` document.
|
||||||
|
class BodyService {
|
||||||
|
BodyService._(this._store);
|
||||||
|
|
||||||
|
/// Document name this service owns.
|
||||||
|
static const documentName = 'body.json';
|
||||||
|
|
||||||
|
static BodyService? _instance;
|
||||||
|
|
||||||
|
/// Returns the initialized singleton; throws if [init] was not called.
|
||||||
|
static BodyService get instance => _instance!;
|
||||||
|
|
||||||
|
/// True once [init] (or a test initialiser) has run.
|
||||||
|
static bool get isInitialized => _instance != null;
|
||||||
|
|
||||||
|
final DocumentStore _store;
|
||||||
|
BodyDocument _doc = const BodyDocument();
|
||||||
|
|
||||||
|
/// The whole document, for the sync layer.
|
||||||
|
BodyDocument get document => _doc;
|
||||||
|
|
||||||
|
/// Initialises the singleton against the platform document store.
|
||||||
|
static Future<BodyService> init() async {
|
||||||
|
if (_instance != null) return _instance!;
|
||||||
|
// coverage:ignore-start
|
||||||
|
final svc = BodyService._(await openDocumentStore());
|
||||||
|
// coverage:ignore-end
|
||||||
|
await svc._load();
|
||||||
|
_instance = svc;
|
||||||
|
return svc;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Initialises from [store], for tests.
|
||||||
|
@visibleForTesting
|
||||||
|
static Future<BodyService> initForTesting(DocumentStore store) async {
|
||||||
|
final svc = BodyService._(store);
|
||||||
|
await svc._load();
|
||||||
|
_instance = svc;
|
||||||
|
return svc;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drops the singleton, or -- given a [store] -- seeds an empty one over
|
||||||
|
/// it so a later [init] reuses it instead of reaching the platform store.
|
||||||
|
@visibleForTesting
|
||||||
|
static void resetForTesting({DocumentStore? store}) {
|
||||||
|
_instance = store == null ? null : BodyService._(store);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _load() async {
|
||||||
|
final raw = await _store.read(documentName);
|
||||||
|
if (raw == null) return;
|
||||||
|
try {
|
||||||
|
_doc = BodyDocument.fromJson(jsonDecode(raw));
|
||||||
|
} on FormatException {
|
||||||
|
// A corrupt document reads as empty, like the other services.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _write(BodyDocument doc) async {
|
||||||
|
_doc = doc;
|
||||||
|
await _store.write(documentName, jsonEncode(doc.toJson()));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Birth date as `YYYY-MM-DD`, or null.
|
||||||
|
String? get birth => _string(profileBirth);
|
||||||
|
|
||||||
|
/// Height in cm, or null.
|
||||||
|
double? get heightCm {
|
||||||
|
final value = _doc.profile[profileHeight]?.value;
|
||||||
|
return value is num ? value.toDouble() : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `m` / `f`, or null.
|
||||||
|
String? get sex {
|
||||||
|
final value = _string(profileSex);
|
||||||
|
return value == 'm' || value == 'f' ? value : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether birth date, height and sex are all set -- the Body screen then
|
||||||
|
/// moves the profile card to the bottom.
|
||||||
|
bool get profileComplete =>
|
||||||
|
DateTime.tryParse(birth ?? '') != null && heightCm != null && sex != null;
|
||||||
|
|
||||||
|
String? _string(String name) {
|
||||||
|
final value = _doc.profile[name]?.value;
|
||||||
|
return value is String && value.isNotEmpty ? value : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets the given profile fields, each stamped now; others are untouched.
|
||||||
|
Future<void> setProfile({
|
||||||
|
String? birth,
|
||||||
|
double? heightCm,
|
||||||
|
String? sex,
|
||||||
|
DateTime? now,
|
||||||
|
}) => setProfileFields({
|
||||||
|
profileBirth: ?birth,
|
||||||
|
profileHeight: ?heightCm,
|
||||||
|
profileSex: ?sex,
|
||||||
|
}, now: now);
|
||||||
|
|
||||||
|
/// Sets raw profile [fields], each stamped now; others keep their stamps.
|
||||||
|
Future<void> setProfileFields(
|
||||||
|
Map<String, Object?> fields, {
|
||||||
|
DateTime? now,
|
||||||
|
}) async {
|
||||||
|
if (fields.isEmpty) return;
|
||||||
|
final t = isoLocalSeconds(now ?? DateTime.now());
|
||||||
|
final profile = Map<String, Stamped>.from(_doc.profile);
|
||||||
|
fields.forEach((name, value) => profile[name] = Stamped(value, t));
|
||||||
|
await _write(_doc.copyWith(profile: profile));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A raw profile value, or null.
|
||||||
|
Object? profileValue(String name) => _doc.profile[name]?.value;
|
||||||
|
|
||||||
|
/// Records [kg] for [day] (`YYYY-MM-DD`), stamped now.
|
||||||
|
Future<void> setWeight(String day, double kg, {DateTime? now}) =>
|
||||||
|
_putWeight(day, kg, now);
|
||||||
|
|
||||||
|
/// Deletes [day]'s weight (a tombstone, so the delete syncs).
|
||||||
|
Future<void> deleteWeight(String day, {DateTime? now}) =>
|
||||||
|
_putWeight(day, null, now);
|
||||||
|
|
||||||
|
Future<void> _putWeight(String day, double? kg, DateTime? now) async {
|
||||||
|
final weights = Map<String, WeightEntry>.from(_doc.weights);
|
||||||
|
weights[day] = WeightEntry(
|
||||||
|
kg: kg,
|
||||||
|
src: 'manual',
|
||||||
|
t: isoLocalSeconds(now ?? DateTime.now()),
|
||||||
|
);
|
||||||
|
await _write(_doc.copyWith(weights: weights));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Records [pct] body fat for [day], stamped now (one decimal, half-up).
|
||||||
|
Future<void> setBodyFat(String day, double pct, {DateTime? now}) =>
|
||||||
|
_putBodyFat(day, halfUp(pct, 1), now);
|
||||||
|
|
||||||
|
/// Deletes [day]'s body fat (a tombstone, so the delete syncs).
|
||||||
|
Future<void> deleteBodyFat(String day, {DateTime? now}) =>
|
||||||
|
_putBodyFat(day, null, now);
|
||||||
|
|
||||||
|
Future<void> _putBodyFat(String day, double? pct, DateTime? now) async {
|
||||||
|
final bodyFat = Map<String, BodyFatEntry>.from(_doc.bodyFat);
|
||||||
|
bodyFat[day] = BodyFatEntry(
|
||||||
|
pct: pct,
|
||||||
|
t: isoLocalSeconds(now ?? DateTime.now()),
|
||||||
|
);
|
||||||
|
await _write(_doc.copyWith(bodyFat: bodyFat));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Non-deleted body fat readings, oldest first, as `(YYYY-MM-DD, %)`.
|
||||||
|
List<(String, double)> get bodyFatSeries =>
|
||||||
|
_series(_doc.bodyFat.map((day, entry) => MapEntry(day, entry.pct)));
|
||||||
|
|
||||||
|
/// The newest non-deleted body fat %, or null.
|
||||||
|
(String, double)? get latestBodyFat {
|
||||||
|
final series = bodyFatSeries;
|
||||||
|
return series.isEmpty ? null : series.last;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Applies ingested weigh-ins: each replaces its day only when the local
|
||||||
|
/// entry is missing or stamped **older**. Returns whether anything changed.
|
||||||
|
Future<bool> applyCandidates(Map<String, WeightEntry> candidates) async {
|
||||||
|
final weights = Map<String, WeightEntry>.from(_doc.weights);
|
||||||
|
var changed = false;
|
||||||
|
candidates.forEach((day, candidate) {
|
||||||
|
final local = weights[day];
|
||||||
|
if (local == null || stampMillis(local.t) < stampMillis(candidate.t)) {
|
||||||
|
weights[day] = candidate;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if (changed) await _write(_doc.copyWith(weights: weights));
|
||||||
|
return changed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Replaces the document with a sync merge result.
|
||||||
|
Future<void> applyMerged(BodyDocument merged) => _write(merged);
|
||||||
|
|
||||||
|
/// Non-deleted weights, oldest first, as `(YYYY-MM-DD, kg)`.
|
||||||
|
List<(String, double)> get weightSeries =>
|
||||||
|
_series(_doc.weights.map((day, entry) => MapEntry(day, entry.kg)));
|
||||||
|
|
||||||
|
static List<(String, double)> _series(Map<String, double?> byDay) {
|
||||||
|
final days = byDay.keys.toList()..sort();
|
||||||
|
return [
|
||||||
|
for (final day in days)
|
||||||
|
if (byDay[day] case final value?) (day, value),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The newest non-deleted weight, or null.
|
||||||
|
(String, double)? get latestWeight {
|
||||||
|
final series = weightSeries;
|
||||||
|
return series.isEmpty ? null : series.last;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Workouts the PC published, parsed; null when it never published any.
|
||||||
|
List<Session>? get sessions {
|
||||||
|
final activity = _doc.activity;
|
||||||
|
if (activity == null) return null;
|
||||||
|
return [for (final raw in activity.sessions) ?Session.fromWire(raw)];
|
||||||
|
}
|
||||||
|
}
|
||||||
30
app/lib/services/body_steps.dart
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
/// Daily steps (from Health Connect, phone-written) as exercise kcal.
|
||||||
|
///
|
||||||
|
/// Only steps above [stepBaseline] count: the `BMR x 1.2` sedentary
|
||||||
|
/// baseline the measured TDEE starts from already assumes a few thousand
|
||||||
|
/// steps of ordinary movement. The rest are walking at the per-km rate
|
||||||
|
/// (0.5 kcal per kg per km, net of resting) over a stride estimated from
|
||||||
|
/// height. Port of `diet_guard/_body_steps.py`.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/services/body_calc.dart';
|
||||||
|
|
||||||
|
/// Steps a day the sedentary baseline already covers.
|
||||||
|
const int stepBaseline = 4000;
|
||||||
|
|
||||||
|
// Stride as a fraction of height (the common pedometer estimate).
|
||||||
|
const double _strideMale = 0.415;
|
||||||
|
const double _strideFemale = 0.413;
|
||||||
|
const double _walkKcalPerKgKm = 0.5;
|
||||||
|
const double _mPerKm = 1000;
|
||||||
|
|
||||||
|
/// Estimated walking stride in metres.
|
||||||
|
double strideM(Biometrics bio) =>
|
||||||
|
bio.heightCm / 100.0 * (bio.isMale ? _strideMale : _strideFemale);
|
||||||
|
|
||||||
|
/// Net kcal of the steps above the baseline, as walking.
|
||||||
|
double stepKcal(int steps, Biometrics bio) {
|
||||||
|
final extra = steps > stepBaseline ? steps - stepBaseline : 0;
|
||||||
|
final km = extra * strideM(bio) / _mPerKm;
|
||||||
|
return km * _walkKcalPerKgKm * bio.weightKg;
|
||||||
|
}
|
||||||
156
app/lib/services/claude_relay_client.dart
Normal file
@ -0,0 +1,156 @@
|
|||||||
|
/// The phone's side of the Claude relay: what the sparkle button sends and
|
||||||
|
/// what comes back.
|
||||||
|
///
|
||||||
|
/// The screen only talks to this interface; `claude_relay_firebase.dart` is the
|
||||||
|
/// real transport (Firebase RTDB, end-to-end encrypted) and
|
||||||
|
/// `claude_relay_fake.dart` the test double. The wire is
|
||||||
|
/// `docs/DOCS-claude-relay.md` plus `tests/fixtures/claude_relay_contract.json`.
|
||||||
|
///
|
||||||
|
/// A `Stream`, not a `Future`: the PC may be off, so a request can sit
|
||||||
|
/// [ClaudeRelayQueued] for hours before the same stream delivers
|
||||||
|
/// [ClaudeRelayLogged]. Terminal events end the stream; [ClaudeRelayQueued]
|
||||||
|
/// does not.
|
||||||
|
///
|
||||||
|
/// **The request id is a ULID** (`rtdb_relay` never serves another key shape)
|
||||||
|
/// and **the entry id is derived from it**: `uuid5(namespace, rid)`, computed
|
||||||
|
/// here by [claudeEntryId] exactly as the PC does. So the phone knows the id
|
||||||
|
/// of the entry before Claude has answered, a logged result is checked against
|
||||||
|
/// it, and undo is a tombstone on that id.
|
||||||
|
///
|
||||||
|
/// **Photos are transient input.** `photoJpeg` lives in memory for one send:
|
||||||
|
/// it is never stored on the phone, never put on a `FoodEntry`, and never part
|
||||||
|
/// of a synced meal record (`repo_invariants_photo_test.dart` enforces it).
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:math';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/models/food_entry.dart';
|
||||||
|
import 'package:uuid/uuid.dart';
|
||||||
|
|
||||||
|
/// The UUID namespace the PC derives entry ids in (`entry_id_namespace` in the
|
||||||
|
/// contract fixture).
|
||||||
|
const claudeEntryNamespace = '5d9c1a40-6f0e-5c3e-9b57-d1e7a3c0b2f4';
|
||||||
|
|
||||||
|
/// The id of the entry the PC logs for request [requestId].
|
||||||
|
String claudeEntryId(String requestId) =>
|
||||||
|
const Uuid().v5(claudeEntryNamespace, requestId);
|
||||||
|
|
||||||
|
const _crockford = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
|
||||||
|
|
||||||
|
/// A fresh ULID: 48 bits of [now] in ms, then 80 random bits, 26 characters of
|
||||||
|
/// Crockford base32. [random] is injectable for tests.
|
||||||
|
String newRequestId({DateTime? now, Random? random}) {
|
||||||
|
final rng = random ?? Random.secure();
|
||||||
|
var ms = (now ?? DateTime.now()).millisecondsSinceEpoch;
|
||||||
|
final out = List<String>.filled(26, '0');
|
||||||
|
for (var i = 9; i >= 0; i--) {
|
||||||
|
out[i] = _crockford[ms % 32];
|
||||||
|
ms ~/= 32;
|
||||||
|
}
|
||||||
|
for (var i = 10; i < 26; i++) {
|
||||||
|
out[i] = _crockford[rng.nextInt(32)];
|
||||||
|
}
|
||||||
|
return out.join();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How the PC picks the slot: the oldest due slot, or the nearest to
|
||||||
|
/// [ClaudeRelayRequest.slotMinute].
|
||||||
|
enum ClaudeRelayMode {
|
||||||
|
/// The phone is in due mode.
|
||||||
|
due,
|
||||||
|
|
||||||
|
/// Nothing is due.
|
||||||
|
normal,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One send: the text and/or photo, and the slot the meal belongs to.
|
||||||
|
class ClaudeRelayRequest {
|
||||||
|
/// Creates a request; at least one of [text] and [photoJpeg] is non-empty.
|
||||||
|
const ClaudeRelayRequest({
|
||||||
|
required this.requestId,
|
||||||
|
required this.slotMinute,
|
||||||
|
this.mode = ClaudeRelayMode.normal,
|
||||||
|
this.text = '',
|
||||||
|
this.photoJpeg,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// A ULID (see [newRequestId]); the entry id is [claudeEntryId] of it.
|
||||||
|
final String requestId;
|
||||||
|
|
||||||
|
/// The slot minute the phone would log against now (`client_slot_min`).
|
||||||
|
final int slotMinute;
|
||||||
|
|
||||||
|
/// Whether the phone is in due mode.
|
||||||
|
final ClaudeRelayMode mode;
|
||||||
|
|
||||||
|
/// What the user typed, trimmed; may be empty when a photo is attached.
|
||||||
|
final String text;
|
||||||
|
|
||||||
|
/// The photo as a JPEG of at most 1024 px, or null.
|
||||||
|
final Uint8List? photoJpeg;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the relay reports about one [ClaudeRelayRequest].
|
||||||
|
sealed class ClaudeRelayEvent {
|
||||||
|
const ClaudeRelayEvent();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The PC is offline; the request is stored and will run later (not terminal).
|
||||||
|
final class ClaudeRelayQueued extends ClaudeRelayEvent {
|
||||||
|
/// Creates the event.
|
||||||
|
const ClaudeRelayQueued();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Claude logged the meal (terminal). `entry.id == claudeEntryId(rid)`.
|
||||||
|
final class ClaudeRelayLogged extends ClaudeRelayEvent {
|
||||||
|
/// Creates the event for [entry].
|
||||||
|
const ClaudeRelayLogged(this.entry);
|
||||||
|
|
||||||
|
/// The entry the worker wrote.
|
||||||
|
final FoodEntry entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sync is locked (no passphrase), so nothing can be sent (terminal).
|
||||||
|
final class ClaudeRelayLocked extends ClaudeRelayEvent {
|
||||||
|
/// Creates the event.
|
||||||
|
const ClaudeRelayLocked();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The send failed (terminal); [reason] is for logs, never painted.
|
||||||
|
final class ClaudeRelayFailed extends ClaudeRelayEvent {
|
||||||
|
/// Creates the event.
|
||||||
|
const ClaudeRelayFailed(this.reason);
|
||||||
|
|
||||||
|
/// Why it failed.
|
||||||
|
final String reason;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sends a meal to Claude through the relay.
|
||||||
|
abstract interface class ClaudeRelayClient {
|
||||||
|
/// Sends [request]; the stream carries zero or more [ClaudeRelayQueued]
|
||||||
|
/// then one terminal event, and never throws (failures are events).
|
||||||
|
Stream<ClaudeRelayEvent> send(ClaudeRelayRequest request);
|
||||||
|
|
||||||
|
/// Withdraws [requestId] if no worker has claimed it yet; true when it is
|
||||||
|
/// gone. False means it was already claimed (or the call failed), and the
|
||||||
|
/// meal will be logged: the stream keeps listening so the row still shows.
|
||||||
|
Future<bool> cancel(String requestId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The stand-in until a transport is wired: every send fails closed.
|
||||||
|
class UnconfiguredClaudeRelayClient implements ClaudeRelayClient {
|
||||||
|
/// Creates the stand-in.
|
||||||
|
const UnconfiguredClaudeRelayClient();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Stream<ClaudeRelayEvent> send(ClaudeRelayRequest request) =>
|
||||||
|
Stream.value(const ClaudeRelayFailed('relay not configured'));
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> cancel(String requestId) async => true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The client the screen uses unless it is handed one; `main.dart` assigns the
|
||||||
|
/// real transport.
|
||||||
|
ClaudeRelayClient claudeRelay = const UnconfiguredClaudeRelayClient();
|
||||||
49
app/lib/services/claude_relay_fake.dart
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
/// A controllable [ClaudeRelayClient] for tests and the unwired app.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/services/claude_relay_client.dart';
|
||||||
|
|
||||||
|
/// Records every request and lets the test emit the events by hand.
|
||||||
|
///
|
||||||
|
/// [emit] pushes to the most recent send's stream; a terminal event closes it,
|
||||||
|
/// as a real client's would.
|
||||||
|
class FakeClaudeRelayClient implements ClaudeRelayClient {
|
||||||
|
/// Every request sent, oldest first.
|
||||||
|
final List<ClaudeRelayRequest> sent = [];
|
||||||
|
|
||||||
|
/// Events replayed on each send before the stream waits for [emit].
|
||||||
|
final List<ClaudeRelayEvent> script = [];
|
||||||
|
|
||||||
|
/// Request ids passed to [cancel], oldest first.
|
||||||
|
final List<String> cancelled = [];
|
||||||
|
|
||||||
|
/// What [cancel] answers: true = withdrawn before any claim.
|
||||||
|
bool cancelResult = true;
|
||||||
|
|
||||||
|
StreamController<ClaudeRelayEvent>? _open;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Stream<ClaudeRelayEvent> send(ClaudeRelayRequest request) {
|
||||||
|
sent.add(request);
|
||||||
|
final controller = StreamController<ClaudeRelayEvent>();
|
||||||
|
_open = controller;
|
||||||
|
script.forEach(emit);
|
||||||
|
return controller.stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Delivers [event] to the open stream; a terminal one closes it.
|
||||||
|
void emit(ClaudeRelayEvent event) {
|
||||||
|
final controller = _open;
|
||||||
|
if (controller == null || controller.isClosed) return;
|
||||||
|
controller.add(event);
|
||||||
|
if (event is! ClaudeRelayQueued) unawaited(controller.close());
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> cancel(String requestId) async {
|
||||||
|
cancelled.add(requestId);
|
||||||
|
return cancelResult;
|
||||||
|
}
|
||||||
|
}
|
||||||
201
app/lib/services/claude_relay_firebase.dart
Normal file
@ -0,0 +1,201 @@
|
|||||||
|
/// The real [ClaudeRelayClient]: requests and answers through Firebase RTDB,
|
||||||
|
/// end-to-end encrypted, served by the PC's `claude-worker`.
|
||||||
|
///
|
||||||
|
/// One send: seal the request with the existing E2E key (header
|
||||||
|
/// `diet-guard-sync/e2e`, the key the log sync already uses), PUT it under
|
||||||
|
/// `requests/<ULID>/req`, then watch the node. No claim after
|
||||||
|
/// [claimWindow] means the PC is offline: [ClaudeRelayQueued], and the same
|
||||||
|
/// stream keeps waiting. The worker's sealed `result` becomes
|
||||||
|
/// [ClaudeRelayLogged] or [ClaudeRelayFailed], and the phone then deletes the
|
||||||
|
/// request node as `docs/DOCS-claude-relay.md` asks.
|
||||||
|
///
|
||||||
|
/// **Fail closed, visibly.** A locked key is [ClaudeRelayLocked]; a request
|
||||||
|
/// that breaks the contract, a transport that keeps failing, a result that
|
||||||
|
/// does not open or carries an entry id the phone did not derive, and a wait
|
||||||
|
/// past [maxWait] are all [ClaudeRelayFailed]. Nothing is ever shown as
|
||||||
|
/// logged unless a valid sealed result says so.
|
||||||
|
///
|
||||||
|
/// Polling, not a stream: the node's child keys (no values, so the photo is
|
||||||
|
/// never re-read) are listed every second, then every 5 s once the wait is
|
||||||
|
/// long. The phone is a foreground client here; a queued request that outlives
|
||||||
|
/// the screen reaches the log through the normal sync instead.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
import 'dart:developer';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:diet_guard_app/services/claude_relay_client.dart';
|
||||||
|
import 'package:diet_guard_app/services/claude_relay_rtdb.dart';
|
||||||
|
import 'package:diet_guard_app/services/claude_relay_wire.dart';
|
||||||
|
import 'package:diet_guard_app/services/firebase_backend.dart';
|
||||||
|
import 'package:diet_guard_app/services/firebase_client.dart';
|
||||||
|
import 'package:diet_guard_app/services/sync_device_id.dart';
|
||||||
|
import 'package:diet_guard_app/services/sync_e2e.dart';
|
||||||
|
|
||||||
|
const _fastPoll = Duration(seconds: 1);
|
||||||
|
const _slowPoll = Duration(seconds: 5);
|
||||||
|
const _slowAfter = Duration(seconds: 30);
|
||||||
|
const _maxPollFailures = 3;
|
||||||
|
|
||||||
|
/// [ClaudeRelayClient] over RTDB.
|
||||||
|
class RtdbClaudeRelay implements ClaudeRelayClient {
|
||||||
|
/// Creates the client; every dependency is injectable for tests.
|
||||||
|
RtdbClaudeRelay({
|
||||||
|
required this.openNodes,
|
||||||
|
required this.openCipher,
|
||||||
|
required this.deviceId,
|
||||||
|
DateTime Function()? now,
|
||||||
|
Future<void> Function(Duration)? delay,
|
||||||
|
this.claimWindow = const Duration(seconds: 3),
|
||||||
|
this.maxWait = const Duration(minutes: 15),
|
||||||
|
}) : _now = now ?? DateTime.now,
|
||||||
|
_delay = delay ?? Future<void>.delayed;
|
||||||
|
|
||||||
|
/// The app's real transport: Firebase session, E2E key from the keystore.
|
||||||
|
///
|
||||||
|
/// Everything resolves at send time, so building it in `main` costs nothing
|
||||||
|
/// and a device that signs in later just works.
|
||||||
|
factory RtdbClaudeRelay.firebase() {
|
||||||
|
FirebaseRestClient? client;
|
||||||
|
Future<FirebaseRestClient> session() async => client ??=
|
||||||
|
await openFirebase() ??
|
||||||
|
(throw const RelayTransportError('not signed in to Firebase'));
|
||||||
|
return RtdbClaudeRelay(
|
||||||
|
openNodes: () async {
|
||||||
|
final auth = (await session()).auth;
|
||||||
|
return RtdbNodes(
|
||||||
|
databaseUrl: kProject.databaseUrl,
|
||||||
|
idToken: auth.idToken,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
openCipher: () => session().then(openDietGuardCipher),
|
||||||
|
deviceId: () => currentSyncDeviceId,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Opens the node access, throwing [RelayTransportError] when unavailable.
|
||||||
|
final Future<RelayNodes> Function() openNodes;
|
||||||
|
|
||||||
|
/// Opens the E2E cipher, throwing [SyncLockedException] when locked.
|
||||||
|
final Future<E2eCipher> Function() openCipher;
|
||||||
|
|
||||||
|
/// This phone's sync device id, sent as `dev`.
|
||||||
|
final String Function() deviceId;
|
||||||
|
|
||||||
|
/// How long an unclaimed request waits before it reads as queued.
|
||||||
|
final Duration claimWindow;
|
||||||
|
|
||||||
|
/// How long one send waits for an answer before it fails.
|
||||||
|
final Duration maxWait;
|
||||||
|
|
||||||
|
final DateTime Function() _now;
|
||||||
|
final Future<void> Function(Duration) _delay;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Stream<ClaudeRelayEvent> send(ClaudeRelayRequest request) async* {
|
||||||
|
final problem = relayBodyProblem(relayBody(request));
|
||||||
|
if (problem != null) {
|
||||||
|
yield ClaudeRelayFailed('bad request: $problem');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final RelayNodes nodes;
|
||||||
|
final E2eCipher cipher;
|
||||||
|
try {
|
||||||
|
cipher = await openCipher();
|
||||||
|
nodes = await openNodes();
|
||||||
|
final unit = await sealRequest(
|
||||||
|
cipher,
|
||||||
|
request,
|
||||||
|
device: deviceId(),
|
||||||
|
nowMs: _now().millisecondsSinceEpoch,
|
||||||
|
);
|
||||||
|
await nodes.put('${requestNode(request.requestId)}/req', unit);
|
||||||
|
} on SyncLockedException {
|
||||||
|
yield const ClaudeRelayLocked();
|
||||||
|
return;
|
||||||
|
} on Object catch (error, stackTrace) {
|
||||||
|
log(
|
||||||
|
'claude relay send failed',
|
||||||
|
level: 1000,
|
||||||
|
error: error,
|
||||||
|
stackTrace: stackTrace,
|
||||||
|
);
|
||||||
|
yield const ClaudeRelayFailed('could not send');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
yield* _await(nodes, cipher, request.requestId);
|
||||||
|
}
|
||||||
|
|
||||||
|
Stream<ClaudeRelayEvent> _await(
|
||||||
|
RelayNodes nodes,
|
||||||
|
E2eCipher cipher,
|
||||||
|
String rid,
|
||||||
|
) async* {
|
||||||
|
final node = requestNode(rid);
|
||||||
|
final started = _now();
|
||||||
|
var queued = false;
|
||||||
|
var failures = 0;
|
||||||
|
while (true) {
|
||||||
|
final waited = _now().difference(started);
|
||||||
|
if (waited > maxWait) {
|
||||||
|
yield const ClaudeRelayFailed('no answer in time');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
final keys = await nodes.keys(node);
|
||||||
|
failures = 0;
|
||||||
|
if (keys.contains('result')) {
|
||||||
|
final result = await openResult(
|
||||||
|
cipher,
|
||||||
|
rid,
|
||||||
|
await nodes.get('$node/result'),
|
||||||
|
);
|
||||||
|
await _tidy(nodes, node);
|
||||||
|
yield result;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (keys.isEmpty) {
|
||||||
|
yield const ClaudeRelayFailed('request vanished');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!queued && !keys.contains('claim') && waited >= claimWindow) {
|
||||||
|
queued = true;
|
||||||
|
yield const ClaudeRelayQueued();
|
||||||
|
}
|
||||||
|
} on Object catch (error, stackTrace) {
|
||||||
|
log(
|
||||||
|
'claude relay poll failed',
|
||||||
|
level: 900,
|
||||||
|
error: error,
|
||||||
|
stackTrace: stackTrace,
|
||||||
|
);
|
||||||
|
if (++failures >= _maxPollFailures) {
|
||||||
|
yield const ClaudeRelayFailed('connection lost');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await _delay(waited < _slowAfter ? _fastPoll : _slowPoll);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Deletes the answered request node. Best effort: the worker also sweeps
|
||||||
|
/// answered nodes after 24 h, so a failure costs nothing but a few bytes.
|
||||||
|
Future<void> _tidy(RelayNodes nodes, String node) async {
|
||||||
|
try {
|
||||||
|
await nodes.delete(node);
|
||||||
|
} on Object catch (error) {
|
||||||
|
log('claude relay cleanup failed', level: 900, error: error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> cancel(String requestId) async {
|
||||||
|
try {
|
||||||
|
return await (await openNodes()).deleteUnclaimed(requestNode(requestId));
|
||||||
|
} on Object catch (error) {
|
||||||
|
log('claude relay cancel failed', level: 900, error: error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
150
app/lib/services/claude_relay_rtdb.dart
Normal file
@ -0,0 +1,150 @@
|
|||||||
|
/// Raw Realtime Database nodes for the relay, over REST.
|
||||||
|
///
|
||||||
|
/// The sync client (`FirebaseRestClient`) stores text blobs as string leaves;
|
||||||
|
/// the relay's units are JSON objects with a server-time sibling, so it needs
|
||||||
|
/// the node itself. Plain HTTPS like the sync client, so it works on Android
|
||||||
|
/// and in the browser-hosted desktop app alike.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
|
||||||
|
/// A relay call failed on the network or was refused. The message never holds
|
||||||
|
/// a URL: its query carries the ID token.
|
||||||
|
class RelayTransportError implements Exception {
|
||||||
|
/// Creates the error.
|
||||||
|
const RelayTransportError(this.message);
|
||||||
|
|
||||||
|
/// What went wrong, safe to log.
|
||||||
|
final String message;
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() => 'RelayTransportError: $message';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The four node operations the relay needs.
|
||||||
|
abstract interface class RelayNodes {
|
||||||
|
/// The JSON value at [path], or null when absent.
|
||||||
|
Future<Object?> get(String path);
|
||||||
|
|
||||||
|
/// The child keys of [path] (no values), empty when absent.
|
||||||
|
Future<Set<String>> keys(String path);
|
||||||
|
|
||||||
|
/// Replaces the node at [path] with [value].
|
||||||
|
Future<void> put(String path, Object value);
|
||||||
|
|
||||||
|
/// Deletes the node at [path].
|
||||||
|
Future<void> delete(String path);
|
||||||
|
|
||||||
|
/// Deletes [path] only while it holds neither a `claim` nor a `result`,
|
||||||
|
/// atomically: the delete carries the node's ETag, so a worker claiming it
|
||||||
|
/// in between turns the delete into a refusal. True when it is gone.
|
||||||
|
Future<bool> deleteUnclaimed(String path);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [RelayNodes] over the Realtime Database REST API.
|
||||||
|
class RtdbNodes implements RelayNodes {
|
||||||
|
/// Creates the client; [idToken] mints the token each request carries.
|
||||||
|
RtdbNodes({
|
||||||
|
required String databaseUrl,
|
||||||
|
required this.idToken,
|
||||||
|
http.Client? client,
|
||||||
|
String namespace = '',
|
||||||
|
}) : _base = databaseUrl.endsWith('/')
|
||||||
|
? databaseUrl.substring(0, databaseUrl.length - 1)
|
||||||
|
: databaseUrl,
|
||||||
|
_prefix = namespace.isEmpty ? '' : '$namespace/',
|
||||||
|
_http = client ?? http.Client();
|
||||||
|
|
||||||
|
/// Supplies a fresh Firebase ID token.
|
||||||
|
final Future<String> Function() idToken;
|
||||||
|
|
||||||
|
final String _base;
|
||||||
|
final String _prefix;
|
||||||
|
final http.Client _http;
|
||||||
|
|
||||||
|
Future<Uri> _uri(String path, [Map<String, String> query = const {}]) async =>
|
||||||
|
Uri.parse(
|
||||||
|
'$_base/$_prefix$path.json',
|
||||||
|
).replace(queryParameters: {'auth': await idToken(), ...query});
|
||||||
|
|
||||||
|
Future<http.Response> _send(
|
||||||
|
String what,
|
||||||
|
Future<http.Response> Function(Uri uri) call,
|
||||||
|
String path, [
|
||||||
|
Map<String, String> query = const {},
|
||||||
|
]) async {
|
||||||
|
try {
|
||||||
|
return await call(await _uri(path, query));
|
||||||
|
} on http.ClientException catch (error) {
|
||||||
|
throw RelayTransportError('network error $what: ${error.message}');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Never _refuse(String what, http.Response res) =>
|
||||||
|
throw RelayTransportError('$what refused: HTTP ${res.statusCode}');
|
||||||
|
|
||||||
|
bool _ok(http.Response res) => res.statusCode >= 200 && res.statusCode < 300;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<Object?> get(String path) async {
|
||||||
|
final res = await _send('reading', _http.get, path);
|
||||||
|
if (!_ok(res)) _refuse('reading', res);
|
||||||
|
return jsonDecode(res.body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<Set<String>> keys(String path) async {
|
||||||
|
final res = await _send('listing', _http.get, path, {'shallow': 'true'});
|
||||||
|
if (!_ok(res)) _refuse('listing', res);
|
||||||
|
final decoded = jsonDecode(res.body);
|
||||||
|
return decoded is Map ? decoded.keys.cast<String>().toSet() : {};
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> put(String path, Object value) async {
|
||||||
|
final res = await _send(
|
||||||
|
'writing',
|
||||||
|
(uri) => _http.put(uri, body: jsonEncode(value)),
|
||||||
|
path,
|
||||||
|
);
|
||||||
|
if (!_ok(res)) _refuse('writing', res);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> delete(String path) async {
|
||||||
|
final res = await _send('deleting', _http.delete, path);
|
||||||
|
if (!_ok(res)) _refuse('deleting', res);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> deleteUnclaimed(String path) async {
|
||||||
|
// `X-Firebase-ETag` makes the read return the node's ETag; a claim or a
|
||||||
|
// result written afterwards changes it, and `if-match` then answers 412.
|
||||||
|
// A full read, not a shallow one: the ETag of a shallow answer is not
|
||||||
|
// guaranteed to cover the children, and this path is rare.
|
||||||
|
final read = await _send(
|
||||||
|
'reading',
|
||||||
|
(uri) => _http.get(uri, headers: {'X-Firebase-ETag': 'true'}),
|
||||||
|
path,
|
||||||
|
);
|
||||||
|
if (!_ok(read)) _refuse('reading', read);
|
||||||
|
final node = jsonDecode(read.body);
|
||||||
|
if (node == null) return true;
|
||||||
|
if (node is Map &&
|
||||||
|
(node.containsKey('claim') || node.containsKey('result'))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
final etag = read.headers['etag'];
|
||||||
|
if (etag == null) return false;
|
||||||
|
final res = await _send(
|
||||||
|
'deleting',
|
||||||
|
(uri) => _http.delete(uri, headers: {'if-match': etag}),
|
||||||
|
path,
|
||||||
|
);
|
||||||
|
if (res.statusCode == 412) return false;
|
||||||
|
if (!_ok(res)) _refuse('deleting', res);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
144
app/lib/services/claude_relay_wire.dart
Normal file
@ -0,0 +1,144 @@
|
|||||||
|
/// The relay's wire format: sealing a request, opening a result.
|
||||||
|
///
|
||||||
|
/// Mirrors `docs/DOCS-claude-relay.md` sections 1 to 3 and is gated by
|
||||||
|
/// `tests/fixtures/claude_relay_contract.json`. A unit is
|
||||||
|
/// `{"_e2e": <blob>, <clear siblings>}`; the blob is crdt_sync's [E2eCipher]
|
||||||
|
/// over compact JSON with the unit's full path as AAD, so a blob copied to
|
||||||
|
/// another path does not open. Both the request (photo included) and the
|
||||||
|
/// result are sealed: no food text or image is ever in clear.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:diet_guard_app/models/food_entry.dart';
|
||||||
|
import 'package:diet_guard_app/services/claude_relay_client.dart';
|
||||||
|
|
||||||
|
/// The relay's root `R`; its header is the existing `diet-guard-sync/e2e`.
|
||||||
|
const relayRoot = 'diet-guard-sync/claude-e2e';
|
||||||
|
|
||||||
|
/// Largest base64 photo the worker accepts, in characters.
|
||||||
|
const relayPhotoB64Max = 600000;
|
||||||
|
|
||||||
|
/// Longest description the worker accepts, in characters after trimming.
|
||||||
|
const relayTextMax = 2000;
|
||||||
|
|
||||||
|
/// The node of request [rid].
|
||||||
|
String requestNode(String rid) => '$relayRoot/requests/$rid';
|
||||||
|
|
||||||
|
/// Returns why [body] breaks the contract, or null when it is valid.
|
||||||
|
///
|
||||||
|
/// The same rules the worker enforces (`bad_request`), checked here first so a
|
||||||
|
/// request that can only fail never leaves the phone.
|
||||||
|
String? relayBodyProblem(Map<String, Object?> body) {
|
||||||
|
final text = body['text'];
|
||||||
|
final photo = body['photo_jpeg_b64'];
|
||||||
|
if (text == null && photo == null) return 'nothing to estimate';
|
||||||
|
if (text != null) {
|
||||||
|
if (text is! String) return 'text is not a string';
|
||||||
|
final length = text.trim().runes.length;
|
||||||
|
if (length < 1 || length > relayTextMax) return 'text length';
|
||||||
|
}
|
||||||
|
if (photo != null) {
|
||||||
|
if (photo is! String || photo.length > relayPhotoB64Max) {
|
||||||
|
return 'photo size';
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
final bytes = base64.decode(photo);
|
||||||
|
if (bytes.length < 2 || bytes[0] != 0xFF || bytes[1] != 0xD8) {
|
||||||
|
return 'photo is not a jpeg';
|
||||||
|
}
|
||||||
|
} on FormatException {
|
||||||
|
return 'photo is not base64';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
final slot = body['client_slot_min'];
|
||||||
|
if (slot is! int || slot < 0 || slot > 1439) return 'slot';
|
||||||
|
if (body['mode'] != 'due' && body['mode'] != 'normal') return 'mode';
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The request's `body` object.
|
||||||
|
Map<String, Object?> relayBody(ClaudeRelayRequest request) => {
|
||||||
|
if (request.text.trim().isNotEmpty) 'text': request.text.trim(),
|
||||||
|
if (request.photoJpeg != null)
|
||||||
|
'photo_jpeg_b64': base64.encode(request.photoJpeg!),
|
||||||
|
'client_slot_min': request.slotMinute,
|
||||||
|
'mode': request.mode.name,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The sealed `req` unit for [request], ready to PUT.
|
||||||
|
///
|
||||||
|
/// `created` is the server's clock, not the phone's: it drives the worker's
|
||||||
|
/// 24 h expiry, and a phone clock can be wrong.
|
||||||
|
Future<Map<String, Object?>> sealRequest(
|
||||||
|
E2eCipher cipher,
|
||||||
|
ClaudeRelayRequest request, {
|
||||||
|
required String device,
|
||||||
|
required int nowMs,
|
||||||
|
}) async {
|
||||||
|
final plain = {
|
||||||
|
'kind': 'meal',
|
||||||
|
'dev': device,
|
||||||
|
'sent_at': nowMs,
|
||||||
|
'body': relayBody(request),
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
'_e2e': await cipher.seal(
|
||||||
|
jsonEncode(plain),
|
||||||
|
path: '${requestNode(request.requestId)}/req',
|
||||||
|
),
|
||||||
|
'created': {'.sv': 'timestamp'},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Opens the `result` unit of [rid] into the event the screen shows.
|
||||||
|
///
|
||||||
|
/// Fail closed: anything that is not exactly a logged meal for this request,
|
||||||
|
/// with the entry id the phone derived itself, is a [ClaudeRelayFailed].
|
||||||
|
Future<ClaudeRelayEvent> openResult(
|
||||||
|
E2eCipher cipher,
|
||||||
|
String rid,
|
||||||
|
Object? node,
|
||||||
|
) async {
|
||||||
|
try {
|
||||||
|
if (node is! Map || node['_e2e'] is! String) {
|
||||||
|
return const ClaudeRelayFailed('result is not a sealed unit');
|
||||||
|
}
|
||||||
|
final plain =
|
||||||
|
jsonDecode(
|
||||||
|
await cipher.open(
|
||||||
|
node['_e2e'] as String,
|
||||||
|
path: '${requestNode(rid)}/result',
|
||||||
|
),
|
||||||
|
)
|
||||||
|
as Map<String, dynamic>;
|
||||||
|
if (plain['id'] != rid) return const ClaudeRelayFailed('result id');
|
||||||
|
if (plain['ok'] != true || plain['status'] != 'logged') {
|
||||||
|
return ClaudeRelayFailed('${plain['error_code'] ?? 'error'}');
|
||||||
|
}
|
||||||
|
if (plain['entry_id'] != claudeEntryId(rid)) {
|
||||||
|
return const ClaudeRelayFailed('entry id mismatch');
|
||||||
|
}
|
||||||
|
return ClaudeRelayLogged(
|
||||||
|
FoodEntry(
|
||||||
|
id: plain['entry_id'] as String,
|
||||||
|
time: plain['time'] as String,
|
||||||
|
desc: plain['desc'] as String,
|
||||||
|
grams: (plain['grams'] as num).toDouble(),
|
||||||
|
kcal: (plain['kcal'] as num).toDouble(),
|
||||||
|
proteinG: (plain['protein_g'] as num).toDouble(),
|
||||||
|
carbsG: (plain['carbs_g'] as num).toDouble(),
|
||||||
|
fatG: (plain['fat_g'] as num).toDouble(),
|
||||||
|
source: 'claude',
|
||||||
|
slotMinute: plain['slot_min'] as int?,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} on E2eDecryptError {
|
||||||
|
return const ClaudeRelayFailed('result did not open');
|
||||||
|
} on Object {
|
||||||
|
// A wrong type or a missing field in a result is a bad answer, not a
|
||||||
|
// crash; the meal is not shown as logged.
|
||||||
|
return const ClaudeRelayFailed('result is malformed');
|
||||||
|
}
|
||||||
|
}
|
||||||
22
app/lib/services/confirm_cue_player.dart
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
// coverage:ignore-file
|
||||||
|
import 'package:audioplayers/audioplayers.dart';
|
||||||
|
|
||||||
|
AudioPlayer? _player;
|
||||||
|
|
||||||
|
final _mixOverMusicWithoutFocus = AudioContext(
|
||||||
|
android: const AudioContextAndroid(
|
||||||
|
contentType: AndroidContentType.sonification,
|
||||||
|
usageType: AndroidUsageType.assistanceSonification,
|
||||||
|
audioFocus: AndroidAudioFocus.none,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
/// Plays the bundled `confirm` cue through the audioplayers plugin.
|
||||||
|
Future<void> playConfirmCueAsset() async {
|
||||||
|
final player = _player ??= AudioPlayer();
|
||||||
|
await player.play(
|
||||||
|
AssetSource('sounds/log_confirm.ogg'),
|
||||||
|
ctx: _mixOverMusicWithoutFocus,
|
||||||
|
mode: PlayerMode.lowLatency,
|
||||||
|
);
|
||||||
|
}
|
||||||
144
app/lib/services/data_export.dart
Normal file
@ -0,0 +1,144 @@
|
|||||||
|
/// User-owned export and merge-only import of every synced document.
|
||||||
|
///
|
||||||
|
/// Import is `mergeLogs` plus the sync tick's own write-back, so it never
|
||||||
|
/// deletes and a repeat is a no-op. The catering login (a password) travels
|
||||||
|
/// only as an AEAD-sealed `kuchnia` section; see `data_export_kuchnia.dart`.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:diet_guard_app/services/body_service.dart';
|
||||||
|
import 'package:diet_guard_app/services/data_export_kuchnia.dart';
|
||||||
|
import 'package:diet_guard_app/services/export_keyring.dart';
|
||||||
|
import 'package:diet_guard_app/services/export_keyring_default.dart';
|
||||||
|
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
|
import 'package:diet_guard_app/services/sync_budget_local.dart';
|
||||||
|
import 'package:diet_guard_app/services/sync_merge.dart';
|
||||||
|
import 'package:diet_guard_app/services/sync_merge_body.dart';
|
||||||
|
|
||||||
|
/// The `format` marker an export carries.
|
||||||
|
const exportFormat = 'diet_guard_export';
|
||||||
|
|
||||||
|
/// The newest export layout this build reads and writes.
|
||||||
|
const exportVersion = 1;
|
||||||
|
|
||||||
|
class _Document {
|
||||||
|
const _Document(this.key, this.readLocal, this.apply);
|
||||||
|
|
||||||
|
final String key;
|
||||||
|
final Future<Log> Function() readLocal;
|
||||||
|
final Future<void> Function(Log merged) apply;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _applyFoodLog(Log merged) async {
|
||||||
|
final log = logToDayLog(merged);
|
||||||
|
await LogStorageService.instance.writeLog(log);
|
||||||
|
await FoodBankService.instance.rebuildAndPersist(log);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Log> _readBody() async =>
|
||||||
|
BodyService.isInitialized ? bodyToLog(BodyService.instance.document) : {};
|
||||||
|
|
||||||
|
Future<void> _applyBody(Log merged) async {
|
||||||
|
if (merged.isEmpty || !BodyService.isInitialized) return;
|
||||||
|
await BodyService.instance.applyMerged(logToBody(merged));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Food log first: applying it rebuilds the derived bank merged next.
|
||||||
|
final List<_Document> _documents = [
|
||||||
|
_Document(
|
||||||
|
'food_log',
|
||||||
|
() async => dayLogToLog(await LogStorageService.instance.readLog()),
|
||||||
|
_applyFoodLog,
|
||||||
|
),
|
||||||
|
_Document(
|
||||||
|
'food_bank',
|
||||||
|
() async => foodBankToLog(await FoodBankService.instance.readBank()),
|
||||||
|
(merged) => FoodBankService.instance.writeBank(logToFoodBank(merged)),
|
||||||
|
),
|
||||||
|
_Document(
|
||||||
|
'food_bank_manual',
|
||||||
|
() async =>
|
||||||
|
manualBankToLog(await FoodBankService.instance.readManualBank()),
|
||||||
|
(merged) =>
|
||||||
|
FoodBankService.instance.applyMergedManualBank(logToManualBank(merged)),
|
||||||
|
),
|
||||||
|
_Document('budget', () async => localBudgetLog(), applyBudgetLog),
|
||||||
|
const _Document('body', _readBody, _applyBody),
|
||||||
|
];
|
||||||
|
|
||||||
|
Map<String, Object?> _encodeLog(Log log) => {
|
||||||
|
for (final entry in log.entries) entry.key: entry.value.toJson(),
|
||||||
|
};
|
||||||
|
|
||||||
|
Log _decodeLog(String key, Object? payload) {
|
||||||
|
if (payload is! Map) throw FormatException('"$key" is not an object');
|
||||||
|
try {
|
||||||
|
return {
|
||||||
|
for (final entry in payload.entries)
|
||||||
|
entry.key as String: Record.fromJson(
|
||||||
|
(entry.value as Map).cast<String, dynamic>(),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
} on Object catch (error) {
|
||||||
|
throw FormatException('"$key" has a malformed record: $error');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns every synced document as one pretty-printed JSON export.
|
||||||
|
///
|
||||||
|
/// The encrypted login section uses the newest key of [keyring] (default: the
|
||||||
|
/// OS-keystore ring).
|
||||||
|
Future<String> exportAllData({DateTime? now, ExportKeyring? keyring}) async {
|
||||||
|
final documents = <String, Object?>{
|
||||||
|
for (final doc in _documents) doc.key: _encodeLog(await doc.readLocal()),
|
||||||
|
};
|
||||||
|
return const JsonEncoder.withIndent(' ').convert({
|
||||||
|
'format': exportFormat,
|
||||||
|
'version': exportVersion,
|
||||||
|
'exportedAt': (now ?? DateTime.now()).toIso8601String(),
|
||||||
|
'documents': documents,
|
||||||
|
...await kuchniaExportEntries(keyring ?? defaultKeyring()),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Merges an [exportAllData] payload into the local store.
|
||||||
|
///
|
||||||
|
/// Parses every document before writing any, so a bad file changes nothing.
|
||||||
|
/// Throws [FormatException] when [text] is not a diet_guard export. A sealed
|
||||||
|
/// login that cannot be opened (unknown key id even after [pullKeys], or
|
||||||
|
/// tampered data) is skipped after the rest merged, then reported as
|
||||||
|
/// [KuchniaImportException]. An existing local login is kept.
|
||||||
|
Future<void> importAllData(
|
||||||
|
String text, {
|
||||||
|
ExportKeyring? keyring,
|
||||||
|
Future<void> Function() pullKeys = pullExportKeys,
|
||||||
|
}) async {
|
||||||
|
final Object? raw;
|
||||||
|
try {
|
||||||
|
raw = jsonDecode(text);
|
||||||
|
} on FormatException {
|
||||||
|
throw const FormatException('not valid JSON');
|
||||||
|
}
|
||||||
|
if (raw is! Map || raw['format'] != exportFormat) {
|
||||||
|
throw const FormatException('not a diet_guard export');
|
||||||
|
}
|
||||||
|
final version = raw['version'];
|
||||||
|
final documents = raw['documents'];
|
||||||
|
if (version is! int || version > exportVersion || documents is! Map) {
|
||||||
|
throw const FormatException('unsupported diet_guard export');
|
||||||
|
}
|
||||||
|
final incoming = <_Document, Log>{
|
||||||
|
for (final doc in _documents)
|
||||||
|
if (documents[doc.key] != null)
|
||||||
|
doc: _decodeLog(doc.key, documents[doc.key]),
|
||||||
|
};
|
||||||
|
final before = {for (final doc in incoming.keys) doc: await doc.readLocal()};
|
||||||
|
for (final MapEntry(key: doc, value: log) in incoming.entries) {
|
||||||
|
final local = mergeLogs(before[doc]!, await doc.readLocal());
|
||||||
|
await doc.apply(mergeLogs(local, log));
|
||||||
|
}
|
||||||
|
await importKuchnia(raw, keyring ?? defaultKeyring(), pullKeys);
|
||||||
|
}
|
||||||
107
app/lib/services/data_export_kuchnia.dart
Normal file
@ -0,0 +1,107 @@
|
|||||||
|
/// The catering login inside the data export, as an encrypted section.
|
||||||
|
///
|
||||||
|
/// The password is never written in clear: the whole credential document is
|
||||||
|
/// sealed with AES-256-GCM under the newest key of the export keyring (see
|
||||||
|
/// `export_keyring.dart`), and the section names that key by `kid`. If the
|
||||||
|
/// keystore is unavailable the section is omitted and `kuchnia_skipped` says
|
||||||
|
/// so; there is no plaintext fallback.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/services/export_crypto.dart';
|
||||||
|
import 'package:diet_guard_app/services/export_keyring.dart';
|
||||||
|
import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
|
||||||
|
|
||||||
|
/// Export key holding the sealed login.
|
||||||
|
const kuchniaKey = 'kuchnia';
|
||||||
|
|
||||||
|
/// Export key explaining why [kuchniaKey] is absent.
|
||||||
|
const kuchniaSkippedKey = 'kuchnia_skipped';
|
||||||
|
|
||||||
|
/// A login in the file could not be restored; the rest of the import did run.
|
||||||
|
class KuchniaImportException implements Exception {
|
||||||
|
/// Creates the exception; [reason] is `unknown_key` or `unreadable`.
|
||||||
|
const KuchniaImportException(this.reason);
|
||||||
|
|
||||||
|
/// Why the section was skipped.
|
||||||
|
final String reason;
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() => 'KuchniaImportException: $reason';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Top-level export entries for the login: the sealed box, or the skip flag.
|
||||||
|
Future<Map<String, Object?>> kuchniaExportEntries(ExportKeyring keyring) async {
|
||||||
|
if (!KuchniaCredentialService.isInitialized ||
|
||||||
|
!KuchniaCredentialService.isConfigured) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
final ExportKey key;
|
||||||
|
try {
|
||||||
|
key = await keyring.ensureNewest();
|
||||||
|
} on Object {
|
||||||
|
return {kuchniaSkippedKey: 'keystore_unavailable'};
|
||||||
|
}
|
||||||
|
final clear = jsonEncode({
|
||||||
|
'username': KuchniaCredentialService.username,
|
||||||
|
'password': KuchniaCredentialService.password,
|
||||||
|
't': KuchniaCredentialService.editedAt,
|
||||||
|
});
|
||||||
|
return {kuchniaKey: await encryptWithKey(clear, key)};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The key for [kid]; pulls the synced keyring once if it is not held yet.
|
||||||
|
Future<ExportKey?> _findKey(
|
||||||
|
ExportKeyring keyring,
|
||||||
|
String kid,
|
||||||
|
Future<void> Function() pullKeys,
|
||||||
|
) async {
|
||||||
|
final held = await keyring.byId(kid);
|
||||||
|
if (held != null) return held;
|
||||||
|
try {
|
||||||
|
await pullKeys();
|
||||||
|
} on Object {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
final pulled = await keyring.byId(kid);
|
||||||
|
return pulled;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Opens the section from [root] and writes it only into an empty login.
|
||||||
|
///
|
||||||
|
/// Throws [KuchniaImportException] when it is present but cannot be opened.
|
||||||
|
/// A configured local login is never overwritten.
|
||||||
|
Future<void> importKuchnia(
|
||||||
|
Map<dynamic, dynamic> root,
|
||||||
|
ExportKeyring keyring,
|
||||||
|
Future<void> Function() pullKeys,
|
||||||
|
) async {
|
||||||
|
final box = root[kuchniaKey];
|
||||||
|
if (box == null) return;
|
||||||
|
final kid = envelopeKeyId(box);
|
||||||
|
final Map<dynamic, dynamic> doc;
|
||||||
|
try {
|
||||||
|
final key = kid == null ? null : await _findKey(keyring, kid, pullKeys);
|
||||||
|
if (key == null) throw const KuchniaImportException('unknown_key');
|
||||||
|
doc = jsonDecode(await decryptWithKey(box, key)) as Map;
|
||||||
|
} on KuchniaImportException {
|
||||||
|
rethrow;
|
||||||
|
} on Object {
|
||||||
|
throw const KuchniaImportException('unreadable');
|
||||||
|
}
|
||||||
|
final username = doc['username'];
|
||||||
|
final password = doc['password'];
|
||||||
|
if (username is! String || password is! String) {
|
||||||
|
throw const KuchniaImportException('unreadable');
|
||||||
|
}
|
||||||
|
if (!KuchniaCredentialService.isInitialized ||
|
||||||
|
KuchniaCredentialService.isConfigured) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await KuchniaCredentialService.instance.applySynced(
|
||||||
|
username,
|
||||||
|
password,
|
||||||
|
doc['t'] is String ? doc['t'] as String : '',
|
||||||
|
);
|
||||||
|
}
|
||||||
100
app/lib/services/export_crypto.dart
Normal file
@ -0,0 +1,100 @@
|
|||||||
|
/// AES-256-GCM sealing for the data export, keyed by an [ExportKey].
|
||||||
|
///
|
||||||
|
/// Pure Dart (`package:cryptography`), no `dart:io`, so it runs on Android and
|
||||||
|
/// in the web build alike. Nothing here falls back to plaintext: any failure
|
||||||
|
/// is an [ExportCryptoException].
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:math';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:cryptography/cryptography.dart';
|
||||||
|
import 'package:diet_guard_app/services/export_keyring.dart';
|
||||||
|
|
||||||
|
/// The `enc` marker of the only envelope layout this build reads and writes.
|
||||||
|
const encryptionVersion = 'v2';
|
||||||
|
|
||||||
|
const _nonceBytes = 12;
|
||||||
|
const _macBytes = 16;
|
||||||
|
|
||||||
|
/// Binds a ciphertext to its role and key id, so it cannot be replayed.
|
||||||
|
List<int> _aad(String kid) =>
|
||||||
|
utf8.encode('diet_guard_export:kuchnia:$encryptionVersion:$kid');
|
||||||
|
|
||||||
|
/// Wrong key, tampered or malformed envelope.
|
||||||
|
class ExportCryptoException implements Exception {
|
||||||
|
/// Creates the exception.
|
||||||
|
const ExportCryptoException(this.message);
|
||||||
|
|
||||||
|
/// What was wrong; never contains key material.
|
||||||
|
final String message;
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() => 'ExportCryptoException: $message';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Seals [plaintext] under [key] with a fresh random nonce.
|
||||||
|
///
|
||||||
|
/// `ciphertext` is the encrypted bytes followed by the 16-byte GCM tag.
|
||||||
|
Future<Map<String, Object?>> encryptWithKey(
|
||||||
|
String plaintext,
|
||||||
|
ExportKey key,
|
||||||
|
) async {
|
||||||
|
final rng = Random.secure();
|
||||||
|
final nonce = Uint8List.fromList([
|
||||||
|
for (var i = 0; i < _nonceBytes; i++) rng.nextInt(256),
|
||||||
|
]);
|
||||||
|
final box = await AesGcm.with256bits().encrypt(
|
||||||
|
utf8.encode(plaintext),
|
||||||
|
secretKey: SecretKey(key.bytes),
|
||||||
|
nonce: nonce,
|
||||||
|
aad: _aad(key.kid),
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
'enc': encryptionVersion,
|
||||||
|
'alg': 'AES-256-GCM',
|
||||||
|
'kid': key.kid,
|
||||||
|
'nonce': base64Encode(nonce),
|
||||||
|
'ciphertext': base64Encode([...box.cipherText, ...box.mac.bytes]),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The key id an envelope was sealed with, or null when it has none.
|
||||||
|
String? envelopeKeyId(Object? envelope) {
|
||||||
|
if (envelope is! Map || envelope['enc'] != encryptionVersion) return null;
|
||||||
|
final kid = envelope['kid'];
|
||||||
|
return kid is String ? kid : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Opens an [encryptWithKey] envelope; throws [ExportCryptoException].
|
||||||
|
Future<String> decryptWithKey(Object? envelope, ExportKey key) async {
|
||||||
|
final Uint8List nonce;
|
||||||
|
final Uint8List sealed;
|
||||||
|
try {
|
||||||
|
final map = envelope! as Map;
|
||||||
|
if (envelopeKeyId(map) != key.kid) throw const FormatException('kid');
|
||||||
|
nonce = base64Decode(map['nonce']! as String);
|
||||||
|
sealed = base64Decode(map['ciphertext']! as String);
|
||||||
|
} on Object {
|
||||||
|
throw const ExportCryptoException('malformed envelope');
|
||||||
|
}
|
||||||
|
if (nonce.length != _nonceBytes || sealed.length < _macBytes) {
|
||||||
|
throw const ExportCryptoException('malformed envelope');
|
||||||
|
}
|
||||||
|
final cut = sealed.length - _macBytes;
|
||||||
|
try {
|
||||||
|
final clear = await AesGcm.with256bits().decrypt(
|
||||||
|
SecretBox(
|
||||||
|
sealed.sublist(0, cut),
|
||||||
|
nonce: nonce,
|
||||||
|
mac: Mac(sealed.sublist(cut)),
|
||||||
|
),
|
||||||
|
secretKey: SecretKey(key.bytes),
|
||||||
|
aad: _aad(key.kid),
|
||||||
|
);
|
||||||
|
return utf8.decode(clear);
|
||||||
|
} on Object {
|
||||||
|
throw const ExportCryptoException('wrong key or tampered data');
|
||||||
|
}
|
||||||
|
}
|
||||||
126
app/lib/services/export_keyring.dart
Normal file
@ -0,0 +1,126 @@
|
|||||||
|
/// The export keyring: random 256-bit AES keys that unlock data exports.
|
||||||
|
///
|
||||||
|
/// Keys live in the OS keystore and also sync between devices as the
|
||||||
|
/// `export_keys` document (see `export_keyring_sync.dart`), so an export made
|
||||||
|
/// on one device opens on another. It is a keyring, not a single key: a key
|
||||||
|
/// is never deleted or overwritten, each id is its own record, and two
|
||||||
|
/// devices that mint a key at the same moment both keep both.
|
||||||
|
///
|
||||||
|
/// The synced copy is end-to-end encrypted under the shared crdt-sync
|
||||||
|
/// passphrase (`sync_e2e.dart`), on `diet-guard-sync/devices-e2e`. The old
|
||||||
|
/// plaintext `diet-guard-sync/devices/<id>/export_keys.json` nodes are
|
||||||
|
/// copied over once and then neither read nor written by this app.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:math';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
|
||||||
|
/// Keystore entry holding the whole ring as JSON.
|
||||||
|
const keyringStorageKey = 'diet_guard.export_keyring';
|
||||||
|
|
||||||
|
final _kidShape = RegExp(r'^[0-9a-f]{16}$');
|
||||||
|
const _keyBytes = 32;
|
||||||
|
|
||||||
|
/// One export key.
|
||||||
|
class ExportKey {
|
||||||
|
/// Creates a key; [kid] is 16 hex chars, [bytes] 32 bytes.
|
||||||
|
const ExportKey(this.kid, this.bytes, this.createdAt);
|
||||||
|
|
||||||
|
/// Random id written into every export sealed with this key.
|
||||||
|
final String kid;
|
||||||
|
|
||||||
|
/// The AES-256 key.
|
||||||
|
final List<int> bytes;
|
||||||
|
|
||||||
|
/// When it was minted (UTC); the newest key signs new exports.
|
||||||
|
final DateTime createdAt;
|
||||||
|
|
||||||
|
/// True when [kid] and [bytes] have the shape a real key has.
|
||||||
|
bool get isWellFormed => _kidShape.hasMatch(kid) && bytes.length == _keyBytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A keyring over an injected keystore.
|
||||||
|
///
|
||||||
|
/// Reads and writes throw when the keystore is unavailable or holds garbage;
|
||||||
|
/// callers treat that as "no keyring" and never fall back to plaintext. A
|
||||||
|
/// garbled ring is not replaced, since that would destroy the keys in it.
|
||||||
|
class ExportKeyring {
|
||||||
|
/// Creates a ring over [read]/[write] (the OS keystore in the app).
|
||||||
|
ExportKeyring({required this.read, required this.write});
|
||||||
|
|
||||||
|
/// Reads a keystore entry, or null when absent.
|
||||||
|
final SecretReader read;
|
||||||
|
|
||||||
|
/// Writes a keystore entry.
|
||||||
|
final SecretWriter write;
|
||||||
|
|
||||||
|
/// Every key held, in no particular order.
|
||||||
|
Future<List<ExportKey>> all() async {
|
||||||
|
final raw = await read(keyringStorageKey);
|
||||||
|
if (raw == null || raw.isEmpty) return [];
|
||||||
|
final decoded = jsonDecode(raw);
|
||||||
|
if (decoded is! Map) throw StateError('export keyring is corrupt');
|
||||||
|
return [
|
||||||
|
for (final MapEntry(key: kid, value: entry) in decoded.entries)
|
||||||
|
ExportKey(
|
||||||
|
kid as String,
|
||||||
|
base64Decode((entry as Map)['k'] as String),
|
||||||
|
DateTime.parse(entry['t'] as String).toUtc(),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The key with id [kid], or null when this device does not hold it.
|
||||||
|
Future<ExportKey?> byId(String kid) async {
|
||||||
|
for (final key in await all()) {
|
||||||
|
if (key.kid == kid) return key;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The newest key, minting and storing one if the ring is empty.
|
||||||
|
Future<ExportKey> ensureNewest() async {
|
||||||
|
var keys = await all();
|
||||||
|
if (keys.isEmpty) {
|
||||||
|
final rng = Random.secure();
|
||||||
|
final fresh = ExportKey(
|
||||||
|
[
|
||||||
|
for (var i = 0; i < 8; i++) rng.nextInt(256),
|
||||||
|
].map((b) => b.toRadixString(16).padLeft(2, '0')).join(),
|
||||||
|
[for (var i = 0; i < _keyBytes; i++) rng.nextInt(256)],
|
||||||
|
DateTime.now().toUtc(),
|
||||||
|
);
|
||||||
|
await mergeKeys([fresh]);
|
||||||
|
keys = [fresh];
|
||||||
|
}
|
||||||
|
return keys.reduce(
|
||||||
|
(a, b) =>
|
||||||
|
a.createdAt.isAfter(b.createdAt) ||
|
||||||
|
(a.createdAt == b.createdAt && a.kid.compareTo(b.kid) > 0)
|
||||||
|
? a
|
||||||
|
: b,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds the well-formed keys whose id is not held yet; never overwrites.
|
||||||
|
Future<void> mergeKeys(Iterable<ExportKey> incoming) async {
|
||||||
|
final held = {for (final key in await all()) key.kid: key};
|
||||||
|
final before = held.length;
|
||||||
|
for (final key in incoming) {
|
||||||
|
if (key.isWellFormed) held.putIfAbsent(key.kid, () => key);
|
||||||
|
}
|
||||||
|
if (held.length == before) return;
|
||||||
|
await write(
|
||||||
|
keyringStorageKey,
|
||||||
|
jsonEncode({
|
||||||
|
for (final key in held.values)
|
||||||
|
key.kid: {
|
||||||
|
'k': base64Encode(key.bytes),
|
||||||
|
't': key.createdAt.toIso8601String(),
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||