# nfce-app — Phase 1 Scoped-down scaffold: supplier/canonical-product/info-record model, invoice header/item storage, and NFC-e parsing for SEFAZ-RJ (built and tested against a real receipt — see `app/services/sefaz/rj.py`). Deliberately **not** included yet: households, shopping lists, digital pantry, crowd price feed, PostGIS, other states' SEFAZ adapters, auth endpoints (there's a `users` table but no register/login routes — a single default user is used for everything, see `nfce.py`). ## 0. Start the shared browser server first This app doesn't bundle its own Chromium — it connects to a separate, shared Playwright server. Go set that up first: see `../playwright-server/README.md`. It needs to be reachable on the same `homelab` Docker network before this app's fetch endpoint will work. ## 1. One-time: create the database on your existing `postgres16` This reuses your existing pgvector Postgres 16 instance instead of running a second Postgres container. See the earlier conversation for creating a dedicated `nfce_app` role scoped to just this database, rather than reusing `llmproxy` directly. ```bash docker exec -it postgres16 psql -U llmproxy -c "CREATE DATABASE nfce_app;" ``` ## 2. Configure ```bash cp .env.example .env # fill in: real DATABASE_URL credentials, a random JWT_SECRET, # and PLAYWRIGHT_WS_ENDPOINT pointing at playwright-server ``` ## 3. Find your homelab's Docker network name ```bash docker network ls docker inspect postgres16 --format '{{json .NetworkSettings.Networks}}' ``` Put that name in `.env` as `HOMELAB_NETWORK=` (no need to edit `docker-compose.yml` any more — the compose file reads it from there). ## 4. Build and run ```bash docker compose up -d --build ``` Migrations now run automatically on container startup (see `docker-entrypoint.sh`) — no separate manual step. This exists because we hit the same "forgot to run alembic upgrade head after a rebuild" bug twice in a row; baking it into startup removes the whole failure class rather than relying on remembering it every time. ### Two deployment shapes: `external` (default) and `bundled` One `docker-compose.yml`, selected by a compose profile: | | Command | PostgreSQL | Gotify / ntfy / Firefly / Tandoor | | --- | --- | --- | --- | | **external** (default) | `docker compose up -d --build` | your existing homelab `postgres16`, via `DATABASE_URL` | the ones you already run, via `.env` or Configurações | | **bundled** | `docker compose --profile bundled up -d --build` | a self-contained `postgres:16-alpine` with its own volume | same — all optional | For **bundled**, use the "Mode B" block in `.env.example`: point `DATABASE_URL` at the `postgres` service, set `HOMELAB_NETWORK_EXTERNAL=false` (compose then creates the network itself) and add `COMPOSE_PROFILES=bundled` so plain `docker compose up -d` and `scripts/safe-update.sh` include the database without the flag. Needs Docker Compose v2.20 or newer. Integration URLs/tokens in `.env` (`GOTIFY_URL`, `NTFY_URL`, `FIREFLY_URL`, `TANDOOR_URL`, …) are **fallbacks**: whatever is saved in the app under Configurações wins; the `.env` value is used only while that field is empty. > **Deploying on your own server for the first time from git** (coming from > an unzipped older version, existing database): follow > `docs/DEPLOY_SERVER.md` — it covers the deploy key, `.env`, the first > migration and how to go back. To install elsewhere, `scripts/make-bundle.sh` > packages it (git bundle + tarball) — same guide, section 9. ### Updating safely ```bash scripts/safe-update.sh ``` Takes a `pg_dump` into `./backups/` first, fast-forwards the checkout, rebuilds, runs `alembic upgrade head` in a one-off container, restarts and polls `/health/ready`. If anything after the backup fails it downgrades the schema to the previous revision, resets git to the previous commit, restores the previous image and restarts — and exits non-zero. Running it when there is nothing new is a no-op. Options: `--force`, `--no-pull`, `--skip-backup`, `--profile bundled`, `--dry-run`; see the header of the script. Restore a dump by hand with `pg_restore --clean --if-exists --no-owner`. ## 5. Check it's alive ```bash curl http://localhost:8010/health # process is up curl http://localhost:8010/health/ready # ...and the database answers ``` ## 6. Open the web UI ``` http://localhost:8010/ ``` Register an account (this is real auth now — bcrypt-hashed passwords, JWT tokens, stored in the browser's localStorage). Create a household from there if you want to share receipts with your wife — she registers her own account and joins with the invite code shown after you create it. The "Adicionar nota" box lets you paste a QR URL and parse it right from the browser — same `/parse` endpoint Swagger was hitting before, just with a UI around it. Attribute it to "Pessoal" or a household from the dropdown. ## Two ways to submit an NFC-e (API level) Both endpoints now require auth — send `Authorization: Bearer ` from `/auth/login` or `/auth/register`. Both also accept an optional `household_id` to share the invoice into a household instead of keeping it personal (must be a household you're actually a member of). **`POST /api/v1/nfce/parse`** — give it `qr_url`, the backend fetches it itself via the shared Chromium and parses the result. ```bash curl -X POST http://localhost:8010/api/v1/nfce/parse \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"qr_url": "https://www4.fazenda.rj.gov.br/consultaNFCe/QRCode?p=..."}' ``` **`POST /api/v1/nfce/parse-html`** — give it `html` you already fetched some other way (e.g. a phone's WebView via Tasker/AutoWeb) plus `qr_url` (used only to pick the right state adapter by hostname, not re-fetched). This is the PRIMARY path for RJ (see the Akamai finding above), not a fallback. Both return `status`: `"parsed"` (stored, `invoice` populated), `"retry"` (blocked/challenged — try again), or `"manual_entry_required"` (genuinely couldn't parse it — `raw_html_snippet` shows what came back, useful for debugging a portal structure change). ## LLM auto-assign setup (optional) The "Atribuir com IA" button on Produtos calls your LiteLLM proxy. Two things to get right in `.env`: 1. **`LLM_MODEL`** must be a model alias YOUR LiteLLM instance actually exposes (check its own config — I don't know what you've named yours), not a generic name like `gpt-4o`. 2. **`LLM_BASE_URL`** needs nfce-app to actually be able to reach your LiteLLM container. I don't know whether it's on the same Docker network as `postgres16` — if it is, a container-name URL like `http://litellm:4000` (adjust to your container's actual name) should work once both are on the `homelab` network from step 3. If it's on a different host/network entirely (like `playwright-server` is), use that server's real LAN IP and published port instead, same pattern as `PLAYWRIGHT_WS_ENDPOINT`. Leave `LLM_BASE_URL` blank to disable the feature — the endpoint returns a clear 400 error rather than failing confusingly. ## Gotify due-date reminders setup (optional) Configure the Gotify server URL and app token in Configurações → Gotify. That's only half the job — the app never checks due dates on its own, by design (no in-app scheduler). You need to trigger the check yourself, periodically, from something you already have running — a cron job or an n8n workflow are the natural fit given the rest of this homelab: ```bash # Example crontab entry, once a day 0 8 * * * curl -s -X POST https://your-nfce-app-host/api/v1/notifications/check-due-dates \ -H "Authorization: Bearer " ``` The token needs to be a real user session token (same as any other authenticated API call) — there's no separate service-account concept here. Only `parcelado` notas with a `payment_due_date` set are ever checked; `à vista` notas are never queried at all, since they're considered paid as of their issue date. ### Gotify vs ntfy — which one, or both Both are supported and independent — configure either, or both at once, and `check-due-dates` sends to every channel that's configured (one channel failing, or being left unconfigured, never blocks the other). The deciding factor is almost always **which phones need the alert**: - **Gotify** has no official iOS app (only third-party/unofficial clients with real gaps — background delivery in particular is unreliable on iOS). It's a great fit for an Android-only household. - **ntfy** ships an official app for both Android and iOS, with proper background push on both — the safer default whenever even one person in the household is on iOS. Given you're on Android and your wife is on iOS: configure **ntfy** for anything she needs to see (or for both of you, to keep it simple — one topic, both phones subscribed to it), and keep **Gotify** running too if you're already using it for other homelab alerts, since there's no cost to leaving both on. Practically: set up ntfy in Configurações → ntfy, add a topic name (treat it like a shared secret — anyone who knows it and your server URL can read/post to it unless you set access control on the ntfy server itself), and install the ntfy app on both phones subscribing to that topic. If you're using the public `ntfy.sh` instead of self-hosting, pick a topic name unlikely to be guessed — auth token is optional and only matters if you've locked the topic down. ## Firefly III export setup (optional) Configure the Firefly URL, a personal access token (create one from your Firefly profile page), and a default source account name in Configurações → Firefly III. The source account needs to already exist in Firefly (or be a name you're happy having Firefly create) — this app doesn't create asset accounts, only expense-side ones (the merchant), which Firefly does automatically from the name you send. Each nota exports as one Firefly transaction group with one split per item, each carrying its own category — see `app/services/firefly.py` for exactly how categories are chosen (linked master product's category, falling back to the supplier's own category, falling back to "Outros"). Firefly matches an existing category by that name or creates a new one. ### Configurar roteamento de conta no Firefly Every export uses one source account — the default one set in Configurações → Firefly III, or an override you pass explicitly. But a real household pays with more than one instrument (a couple of credit cards, a debit account, cash), and each nota already knows which one it used (`payment_type`, and `card_label` when it's a specific card). Rather than building a payment-type→account mapping table and UI here — which would just be reimplementing a small slice of what Firefly's own **Rules** engine already does — every exported split now carries tags that Rules can match on: - `"Nota"` — always present, on every split this app ever exports. Handy as a catch-all trigger if you ever want a Rule that applies to everything from this app (e.g. always add to a "Compras" budget). - the nota's `payment_type` (e.g. `"credito"`, `"debito"`, `"pix"`, `"dinheiro"`) — present whenever it's set. - the nota's `card_label` (e.g. `"Nubank"`, `"Inter"`) — present only when it's set, and more specific than `payment_type` since it distinguishes two cards of the same type. Set this up once, in Firefly itself (no code or config here): 1. In Firefly, go to **Automation → Rules** and create a new **rule group** if you don't have one yet (e.g. "Roteamento de conta — Nota"). 2. For each **card or payment method** you want routed to a specific account, create one rule: - **Trigger:** "Tag is" → the card's `card_label` (or the `payment_type` if you're not distinguishing individual cards). - **Action:** "Set source account" → the Firefly asset account for that card/method. - Check **"stop processing other rules"** on any rule that triggers on `card_label` — this is the ordering trick: put the specific (`card_label`) rules *above* the generic (`payment_type`) ones in the rule group, each with "stop processing" checked, so a Nubank credit-card nota matches the Nubank rule and never falls through to a generic "credito → some other account" rule. - Leave the generic `payment_type` rules (no "stop processing", or last in the group) as the fallback for anything that only has a payment type and no specific card. 3. Rules only run when `apply_rules: true` is sent with the transaction — this app always sends that, so no toggle needed on this side. 4. Test with one real export, then check the transaction in Firefly landed on the account you expected before trusting it for a batch. This also means adding a new card later is a two-minute Firefly-side change (one new rule) — nothing here needs to change or redeploy. ## Previsão e cenários `Previsão` (menu) projects next month and the next quarter per category from the trailing average of the last N complete months, and lets you nudge categories ("mercado +15%", "cortar internet", "novo gasto de R$ 90/mês") to see the difference per month, quarter and year. Scenarios can be saved; a saved scenario stores only its inputs and is recomputed against today's history when reopened. - `GET /api/v1/reports/forecast?months_back=6&method=mean|weighted&household_id=` - `POST /api/v1/reports/forecast-scenario` — body `{"adjustments":[{"category":"Mercado","kind":"percent","value":15},{"category":"Internet","kind":"remove"}]}`; kinds: `percent`, `fixed` (R$/month delta), `set` (R$/month total), `remove`. Add `"save_as":"name"` to persist. - `GET /api/v1/reports/forecast-scenarios`, `DELETE …/{id}` The response also carries `totals.committed_next_month` / `committed_next_quarter` and `committed_installments`: card installments of purchases **already made** that fall due in the coming months. That is cash already owed, shown beside the estimate and never added to it — those purchases were counted in the month they happened. The model is documented at the top of `app/services/forecast.py`. A category is "recorrente" when most of its spend is on replenishable items (the Pass 9 rules) **and** it shows up in at least half of the months considered. ## Níveis de detalhe: Essencial / Simples / Avançado The switch in the top bar applies everywhere and is remembered per user. **Essencial** shows plain-language summaries only, **Simples** the main numbers and charts, **Avançado** everything (filters by category/supplier, flow charts, heatmap, calculation settings). It also drives the older Simples/Pro table mode on the list pages (Avançado ⇒ Pro). ## Tandoor Recipes (optional) Configurações → Tandoor, or `TANDOOR_URL` / `TANDOOR_TOKEN` in `.env`. Replenishable products become Tandoor foods (by family name when there is one), and anything bought within its usual restock interval is marked "on hand", so Tandoor can tell which recipes are cookable now. - `GET /api/v1/integrations/tandoor/pantry-preview` — dry run, never writes - `POST /api/v1/integrations/tandoor/pantry-sync` — idempotent; cron it daily - `POST /api/v1/integrations/tandoor/shopping-lists/{list_id}/push` - `GET /api/v1/integrations/tandoor/recipes-makeable` The API shape targeted is Tandoor's REST API with a Bearer token; it has not been exercised against a live Tandoor instance yet — check `/docs/api/` if a call is rejected. ## Capturar no celular (script de captura) Configurações → **Capturar no celular** (`/static/capturar.html`). Install the userscript once — iPhone: Safari + the free *Userscripts* app; Android: Firefox or Edge + Violentmonkey/Tampermonkey — then connect the browser with one tap (if logged in there) or an 8-character code generated on another device. From then on: camera → QR → pass the SEFAZ check → the note is saved and a toast confirms it. No tap after the page loads. Offline captures are queued in the browser and sent later. Needs Nota reachable over **HTTPS** from the phone (reverse proxy or `tailscale serve`); set `PUBLIC_BASE_URL` in `.env` so the script and pairing links carry the address phones actually use. Behind **Authelia**, follow `docs/DEPLOY_AUTHELIA.md` — a few paths must bypass it for capture, extension and cron calls to work. Pairing shows a QR (rendered server-side with `segno`) and/or an 8-character code; Configurações → *Capturar no celular* chooses: QR + código, só QR (24-character secret that only travels in the QR; typed codes refused), or só código. - `GET /capture/nota-capture.user.js` — the script, with this instance baked in - `POST /api/v1/auth/pairing-code` → `{method, code, expires_at, pair_url, qr_svg}` (10 min, single use) - `GET /api/v1/auth/pairing-config` (public) · `PATCH /api/v1/app-settings/pairing` - `POST /api/v1/auth/pair` `{code}` → automation token (1 year; revoke all with `/auth/automation-token/revoke`) - `POST /api/v1/nfce/capture` `{html, url, html2?, household_id?}` — one endpoint for every capture client; detects NFC-e vs NF-e 55 **Escanear** (`/static/escanear.html`) is the optional in-app scanner: reads the cupom's QR *and* the NF-e (DANFE) barcode where the browser supports it, refuses non-fiscal QR codes, fills the NF-e key on the national portal, and keeps a "para abrir depois" list for checkouts without signal. A cupom that is already in Nota is recognised before opening SEFAZ ("Já está no Nota"), using Nota's own records only. "Add to Home Screen" gives it an icon; it opens in the normal browser on purpose, so the capture script keeps working. Options and the remaining phases: `docs/CAPTURE_PLAN.md`. ## Não repor (compras pontuais) `/static/repor.html` (linked from Produtos and Sugestões) suggests products that are one-off purchases — meals out, electronics, furniture, clothing, expensive items bought once — each with the reason, and confirms them in bulk ("Não repor" / "Repor (manter)"). Optional AI pass uses the LLM from Configurações. Categories that keep coming up can become a standing rule in one click. "Não repor" items never appear in restock reminders or suggested shopping lists. - `GET /api/v1/replenishable-suggestions?include_low=` · `POST /api/v1/replenishable-suggestions/ai` ## Receitas com IA `/static/receitas.html` (from Sugestões): recipe ideas from what is probably at home (recent replenishable purchases) and what the family buys most, in the style of the best-rated Tandoor recipes when Tandoor is configured. Each idea can be saved to Tandoor (tag `nota-ia`) or turn its missing ingredients into a shopping list. Only food and recipe names go to the model. - `POST /api/v1/integrations/recipes/suggest` · `POST /api/v1/integrations/tandoor/recipes` ## Dispositivos e tokens Configurações → *Dispositivos e tokens de automação* lists every paired phone and manual token (name, last use), flags forgotten ones (unused ≥ 90 days or never used) and revokes one at a time. - `GET /api/v1/auth/automation-tokens` · `DELETE /api/v1/auth/automation-tokens/{id}` ## Tests ```bash pip install -r requirements-dev.txt pytest # DB-free: forecast, dedup, reconciliation, rules, Tandoor mapping scripts/check-inline-js.sh # node --check on every inline