Check/salary bankid api (#892)
* fix(bankid): harden login/signup flow — polling, signup rollback, metadata merge, enrichment lookup - middleware: read BankID enrichment from the bankid_enrichment table (the extension_data path has been dead since the multi-tenant refactor), so company-less BankID users land on /select-company instead of the manual wizard - BankIdAuth: hard 6-min poll deadline; every failed poll counts toward the give-up limit; guard overlapping ticks so completion runs exactly once (a double /complete regenerated the magic link and invalidated the first, failing logins intermittently); retry clicks wait out the start cooldown instead of silently no-oping; Swedish messages for 429/unknown start errors - bankid/complete: all-or-nothing signup — delete the created user when the identity insert, app_metadata update, or magic-link generation fails, so a retry starts clean instead of hitting account_exists with an unusable account - bankid/unlink: read-merge-write app_metadata so has_password survives unlink (BankID-only users could otherwise strand themselves with no login method) - login: BankID "create account" CTA now links to /register instead of dismissing the notice; sv.json: fix missing å/ä/ö in settings_bankid strings Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: move secondary guides into docs/, delete dead root files Move DOCKER.md, SELF-HOSTING.md, WHITELABEL.md and extensions.md (renamed EXTENSIONS.md) into a new docs/ folder and update all path references (README, setup.sh, .dockerignore image rules, docker-publish workflow comment, _example-branding, lib/branding/service.ts). Delete two dead root files: customer.json (stray API-test payload) and findings.md (point-in-time swarm audit export, criticals already filed). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Signed-off-by: Emil <emilmattsson14@gmail.com> * fix(api): security & correctness hardening + withRouteContext MFA migration across API routes Audit of ~100 app/api routes. Highlights: Security - agent/conversations: list leaked colleagues' titles + message previews (company-scoped RLS, no user filter) -> user-scoped - calendar/feed PUT: raw body into .update() allowed feed_token fixation on a public unauthenticated URL -> strict schema, content toggles only - bokslutsdispositioner: unbounded schablonintaktRate could inflate the IL 30 kap 25% periodiseringsfond cap base -> bounded - agent profile/composer/onboarding: viewers could rewrite the agent profile while sibling /verify blocked them -> role-gated Correctness - account-totals / listAssets: unbounded queries silently truncated at 1000 rows (under-counted money; skipped assets at year-end depreciation) -> fetchAllRows with stable order (+3 more pagination fixes) - voucher-gaps: swallowed detect_voucher_gaps RPC errors (BFNAR gap view could show "no gaps" when the check never ran) -> surfaced - 5 phantom-success writes (OK on zero matched rows) fixed - assets K3 component-sum validated against stale acquisition_cost -> fixed - invite silent email-send failure -> response carries email_sent; deadlines/calendar cast-then-check JSON crashes -> Zod Convention - ~44 legacy routes converted to withRouteContext (MFA); added Zod validation, corrected status codes, console.* -> lib/logger Response shapes preserved for existing callers. ~110 new tests. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(bookkeeping): save a booking as a reusable template from Bokför direkt Add a "Spara som mall" action to the manual booking dialog so users can capture a kontering they just worked out as a booking template — right where they figured out how something should be booked. - derive amount-parameterised template lines from the concrete booking (settlement = the non-VAT leg nearest the total, 26xx = a VAT line with its rate snapped to the nearest standard rate, the rest = business ratios; line labels come from the loaded BAS chart) - extract the shared TemplateForm out of BookingTemplatesPanel so the booking dialog reuses the same editor, live preview and convertibility hints instead of duplicating them - save via the existing POST /api/settings/booking-templates endpoint Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(bokslut): render arsredovisning RR/BR at ÅRL post level — no kontonummer Bolagsverket rejected a user's filed årsredovisning with "Balansräkning och resultaträkning ska inte innehålla kontonummer": the PDF built every statement row as per-account "1930 Företagskonto" lines while the iXBRL filing path already aggregated to statutory posts, so the two artifacts diverged. The PDF statements now derive from the same K2 risbs mapping the iXBRL document uses (mapTrialBalancesToK2), via a new statement-rows.ts that emits post-level rows in uppställningsform order for both the K2 and K3 templates. Also fixed along the way: - Jämförelseår column (ÅRL 3:5 §) — previous-year trial balances now load and render; the old PDF had no comparatives at all. - mapping.warnings (unmapped accounts, RR ≠ 2099, obalans, reclass nudges) flow into ArsredovisningData.warnings so the wizard flags a non-fileable document before download. - Flerårsöversikt current/previous year overridden with the mapper's strict-3000–3799 Nettoomsattning, mirroring build-input's duplicate-fact rule, so the FB table ties to the RR. - FB eget kapital-table is post-level and drops obeskattade reserver (never eget kapital); K3 equity-changes statement uses real prior-year opening balances with derived utdelning/nyemission residuals that tie the roll-forward exactly to booked UB. - build-input dedupes warnings now that the PDF path runs the same mapping. Regression test asserts no RR/BR label ever contains a four-digit account number again. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(reports): diagnose untransferred prior-year results behind balance-sheet differens Prod incident (97 kr): a multi-year SIE migration lacked one year's omforing av arets resultat; the residual corrupted every later derived opening balance and Balansrakningen showed a bare "Differens: 97 kr" with no explanation. Continuity checking cannot catch this failure mode (prior-year UB and derived IB match per-account by construction) - the invariant that actually breaks is per-year P&L = 0 for all non-latest years. - lib/reports/imbalance-diagnosis.ts: shared detector (findUntransferredResults + buildImbalanceDiagnosis) - Balansrakning/Balansrapport attach imbalance_diagnosis when unbalanced, naming the exact culprit years; rendered in web views + PDF; MCP gnubok_get_balance_sheet inherits the field via spread - SIE import: parse-time warning when a completed year's vouchers leave a P&L residual, plus a post-import DB walk surfacing culprits as warnings and structured details.untransferredResults; the Arcim migration workspace previously dropped result.warnings entirely and now renders them - opening-balance/correct: pre-flight the company lock date and return 409 OB_COMPANY_LOCK_DATE (retryable: false, lock date interpolated in the client message) instead of the retryable 500 that invited blind retries; catch-path maps a raced trigger rejection to the same code Diagnosis runs only on unbalanced paths (zero cost when healthy) and never fails the report or the import. No migration, nothing persisted. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix: production error remediation — FX rates, deadlines, log levels, correction relink Batch of fixes for recurring Vercel runtime errors: - Riksbanken FX rates: persistent read-through cache (exchange_rates table), one retry honoring Retry-After on 429/5xx, bounded ingest concurrency, and an honest fallback — most recent cached observation or null, never a hardcoded rate silently booked into amount_sek. Unrated transactions stay repairable via refresh-exchange-rate. - Tax deadline regeneration inserts replacement rows before deleting the superseded set, so a failed insert no longer wipes a company's deadlines (the 23502 user_id regression did exactly that). Migration makes deadlines.user_id nullable for system-generated rows. - Route wrappers + errorResponse log 4xx outcomes at warn so only genuine 5xx reach Vercel's runtime-error clustering; client-supplied /api/log telemetry demoted to warn as well. - application/json documents (raw PSD2 responses archived per BFL) validate as parseable JSON with object/array root instead of always failing the magic-byte check. - correctEntry surfaces document-relink failures to callers, and the BFL document-immutability trigger now allows relinking underlag from a reversed entry to its correction (migration + pg test). - Middleware clears stale session cookies on /api requests too, using scope 'local' so cleanup doesn't re-trigger the failed token refresh. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(skatteverket): persist token health and stop retrying dead consents Terminal auth errors (SESSION_EXPIRED, REFRESH_EXHAUSTED, MISSING_SCOPE, TOKEN_CORRUPTED) mark the token row needs_reconsent with the error code and timestamp — SKV per-flow refresh tokens live 65 minutes, so once expired nothing recovers without a fresh BankID consent. The AGI kvittens and skattekonto sync crons skip flagged connections instead of failing every night, and the settings panel prompts for re-consent proactively. A successful reconnect resets the row to active. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(banking): allocate distinct BAS ledger slots for PSD2 mirror accounts A bank returning N same-currency accounts used to map them all onto the currency default (1930/1932/1933/1934), tripping the UNIQUE (company_id, ledger_account) constraint per-account — swallowed errors left accounts silently unmirrored. allocatePsd2LedgerAccount now hands out the currency default first, then free 1931–1959 sub-account slots, skipping slots held by any existing row. - Callback persists allocations to accounts_data so the picker pre-fills reality; reconnect reuses previously mirrored ledgers instead of re-deriving (a user remap to 1935 survives). - Selection save resolves effective ledgers up front and rejects duplicates or cross-connection conflicts with a 400 instead of silently skipping the mirror. - Bank error codes + psu_type are forwarded to the settings page for every OAuth error, keying the Handelsbanken corporate fullmakt guidance. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(agent): stage exact journal lines on categorization previews Categorization previews only carried debit/credit accounts, the GROSS amount, and separate VAT rows — read together that looks like an unbalanced 'gross on cost account + VAT debit' entry, and it misled both users and agents into rejecting correct proposals. The MCP preview and the pending-operation PATCH now materialize the exact lines the commit executor will post (net cost line, VAT line, gross bank line, SEK) via buildTransactionEntryLines, and PATCH re-derives them from the new mapping instead of spreading stale staged lines. ApprovalCard and /pending render the verifikat lines, falling back to the legacy summary only for operations staged before this fix. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(bookkeeping): prune unused imported accounts from the chart SIE imports routinely bring in hundreds of accounts that were never used and clutter the kontoplan. New account_usage_counts RPC (one grouped query instead of a count per account) backs GET /api/bookkeeping/accounts/usage, and POST /api/bookkeeping/accounts/prune deletes zero-usage accounts — dry-run first, then an explicit account list capped at 2000. Accounts with journal lines are skipped, never deleted. The chart manager shows a usage column and a prune dialog grouping custom accounts vs unused BAS-seeded ones. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(api): carry dimensions through v1 invoice and supplier-invoice surfaces Credit-note creation now copies default_dimensions and per-line dimensions from the original, so the reversing journal entry nets against the same dimension cells instead of dropping them. List/detail responses expose the dimension fields, and the OpenAPI spec snapshot follows. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * perf: batch serial Supabase round-trips on hot dashboard paths Every dashboard render pays the layout's query chain, so serialized awaits are direct wall-clock: the layout, chat conversation, invoice detail, supplier detail, select-company, and agent-onboarding pages now run their independent lookups in parallel batches, and getCompanyCapabilities folds its disabled-config read into the same round-trip. JournalEntryList hydrates the saved fiscal-year scope optimistically instead of serializing the first entries fetch behind the fiscal-periods request. The supplier detail page filters invoices server-side via a new supplier_id query param instead of fetching the whole company ledger, and the invoice editor (with its framer-motion dependency) lazy-loads so it stops shipping with the invoice list bundle. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(salary): one-click runs, payslip delivery, payments settings, run cockpit Salary P1 batch, driving the 20-click flow toward 3 clicks: - One-click 'Starta lönekörning': POST /api/salary/runs accepts an empty body and resolves defaults server-side — period follows the latest non-corrected run, payment date from the new salary_pay_day setting, series from the per-source-type map. The separate /salary/runs/new page is gone. - Run detail page rebuilt as a step-railed cockpit (progress rail, KPI cards, employee ledger, journal preview) on a deliberately wider canvas; components extracted to components/salary/run/. - Payslip delivery: tokenized public payslip pages (/payslip/[token], backed by salary_payslip_links) plus per-employee email send with PDF — employees need no account, and the middleware exempts the route from auth redirects. - Payments settings: salary pay day, default bank, and pain.001 vs Bankgirot Lön format with per-bank upload instructions and an LB sunset warning (banks retire LB during 2026). - AGI panel: full submission status flows (stale drafts, signing links, kvittens polling, error reports); tax payment panel with skattekonto shortcut and mark-as-paid. - Salary calendar bulk editing, employee benefits/tax-card polish, municipality tax-table lookup improvements. messages/sv+en also carry the strings for the account-prune, skatteverket-reconsent, and banking surfaces committed just before this. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * chore: adopt Next 16 proxy.ts convention + repo housekeeping - Rename middleware.ts to proxy.ts with the proxy() export (Next 16 renamed the middleware convention; behavior unchanged). - Exclude dev_docs/ from tsconfig so stray snippets in planning docs don't break the build type-check. - Ratchet antipatterns-baseline down (raw-route-auth 165 → 119) to lock in the withRouteContext migration from 5cfd2b76. - template-library uses roundOre() instead of inline rounding. - database.md: drop account_balances from the key-tables list. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(bookkeeping): robust service-role detection in correction document relink relink_documents_to_correction() keyed its service-role branch on auth.role(), which reads the singular request.jwt.claim.role GUC that PostgREST v10+ and the pg-real harness no longer populate. Genuine service-role callers (pending-ops executor / MCP approve) landed in the auth gate and could not relink underlag. Read the role from the request.jwt.claims JSON directly, mirroring the canonical link_voucher_rpcs_tenant_guard convention. Validated on staging. Also: harden the salary run page's error paths (res.json().catch) against non-JSON error bodies, and roll back the pg-real service-role case in finally so an aborted transaction cannot poison a pooled connection for the next test. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(documents): restore journal_entry_line_id link durability (BFL 7 kap) Migration 20260704103000 rewrote enforce_document_journal_entry_immutability to guard journal_entry_id but left journal_entry_line_id to the metadata trigger, which exempts draft-linked docs -- and the entry-level trigger only fired on UPDATE OF journal_entry_id, so a line-id-only UPDATE never invoked it at all. That let a set journal_entry_line_id be cleared to NULL, breaking the "link durable from first set" invariant (document-immutability.pg regression). Widen the trigger to fire on journal_entry_line_id too and guard it with the same uuid-durability rule as journal_entry_id (setting NULL -> uuid stays allowed; clearing/re-pointing a set value is blocked, status-independent). The correction-relink GUC path, which legitimately clears line_id when moving underlag to the posted correction, stays exempt. Validated on staging. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Signed-off-by: Emil <emilmattsson14@gmail.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
ec27228a8e
commit
2c2743eb79
+258
@@ -0,0 +1,258 @@
|
||||
# Self-Hosting Accounted with Docker
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Docker and Docker Compose (v2)
|
||||
- A [Supabase](https://supabase.com) project (free tier works)
|
||||
|
||||
You do **not** need Node.js, npm, or anything else installed locally. The pre-built image has everything.
|
||||
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
|
||||
### 1. Download the required files
|
||||
|
||||
```bash
|
||||
mkdir Accounted && cd Accounted
|
||||
|
||||
# Compose file + env template
|
||||
curl -fsSLO https://raw.githubusercontent.com/gnubok/gnubok/main/docker-compose.yml
|
||||
curl -fsSLO https://raw.githubusercontent.com/gnubok/gnubok/main/.env.docker.example
|
||||
|
||||
# Cron sidecar (Dockerfile + schedule)
|
||||
mkdir -p docker
|
||||
curl -fsSL -o docker/cron.Dockerfile \
|
||||
https://raw.githubusercontent.com/gnubok/gnubok/main/docker/cron.Dockerfile
|
||||
curl -fsSL -o docker/crontab.self-hosted \
|
||||
https://raw.githubusercontent.com/gnubok/gnubok/main/docker/crontab.self-hosted
|
||||
```
|
||||
|
||||
### 2. Configure your environment
|
||||
|
||||
```bash
|
||||
cp .env.docker.example .env
|
||||
```
|
||||
|
||||
Open `.env` and fill in the **required** values:
|
||||
|
||||
| Variable | Where to find it |
|
||||
|----------|-----------------|
|
||||
| `NEXT_PUBLIC_SUPABASE_URL` | Supabase dashboard → Settings → API → Project URL |
|
||||
| `NEXT_PUBLIC_SUPABASE_ANON_KEY` | Supabase dashboard → Settings → API → `anon` `public` key |
|
||||
| `SUPABASE_SERVICE_ROLE_KEY` | Supabase dashboard → Settings → API → `service_role` key |
|
||||
| `NEXT_PUBLIC_APP_URL` | The URL where you'll access Accounted (e.g. `https://gnubok.example.com`) |
|
||||
| `CRON_SECRET` | Any random string: `openssl rand -hex 32` works |
|
||||
|
||||
Once `.env` is filled in, **restrict its permissions** so other users on the host can't read your service-role key or cron secret:
|
||||
|
||||
```bash
|
||||
chmod 600 .env
|
||||
```
|
||||
|
||||
### 3. Start
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
The app is now reachable on **loopback only** at `http://127.0.0.1:3000`. This is intentional: direct internet exposure over HTTP is not safe for an accounting app. The next section enables HTTPS.
|
||||
|
||||
### 4. Verify
|
||||
|
||||
```bash
|
||||
# Should return {"status":"healthy",...}
|
||||
curl http://localhost:3000/api/health
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Enable HTTPS (recommended)
|
||||
|
||||
Ship a Caddy reverse proxy alongside the app: it auto-provisions Let's Encrypt certificates and renews them forever.
|
||||
|
||||
### 1. Point a domain at the host
|
||||
|
||||
`gnubok.example.com → <your-public-ip>` (A record). Ports 80 and 443 must be reachable from the internet (Let's Encrypt's HTTP-01 challenge uses port 80).
|
||||
|
||||
### 2. Set `DOMAIN` in `.env`
|
||||
|
||||
```env
|
||||
DOMAIN=gnubok.example.com
|
||||
NEXT_PUBLIC_APP_URL=https://gnubok.example.com
|
||||
```
|
||||
|
||||
### 3. Download the overlay + Caddyfile
|
||||
|
||||
```bash
|
||||
curl -fsSLO https://raw.githubusercontent.com/gnubok/gnubok/main/docker-compose.caddy.yml
|
||||
mkdir -p docker
|
||||
curl -fsSL -o docker/Caddyfile \
|
||||
https://raw.githubusercontent.com/gnubok/gnubok/main/docker/Caddyfile
|
||||
```
|
||||
|
||||
### 4. Start with the overlay
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.yml -f docker-compose.caddy.yml up -d
|
||||
```
|
||||
|
||||
Caddy obtains a cert on first boot (takes ~10 s). Visit `https://gnubok.example.com`.
|
||||
|
||||
If you already have nginx / a managed load balancer / Cloudflare in front, skip Caddy and point your existing proxy at `127.0.0.1:3000`: set `NEXT_PUBLIC_APP_URL` to match the public URL.
|
||||
|
||||
---
|
||||
|
||||
## Optional Extensions
|
||||
|
||||
The self-hosted image ships with all extensions enabled (except Enable Banking, which requires private PSD2 credentials). Each extension activates when you provide its env vars: without them, the app works normally and the feature is simply unavailable.
|
||||
|
||||
### AI Features (ai-categorization, ai-chat, receipt-ocr, invoice-inbox)
|
||||
|
||||
```env
|
||||
ANTHROPIC_API_KEY=sk-ant-...
|
||||
OPENAI_API_KEY=sk-...
|
||||
```
|
||||
|
||||
### Email (invoice sending, reminders)
|
||||
|
||||
```env
|
||||
RESEND_API_KEY=re_...
|
||||
RESEND_FROM_EMAIL=faktura@your-domain.com
|
||||
RESEND_WEBHOOK_SECRET=whsec_...
|
||||
```
|
||||
|
||||
### Push Notifications
|
||||
|
||||
```env
|
||||
NEXT_PUBLIC_VAPID_PUBLIC_KEY=...
|
||||
VAPID_PRIVATE_KEY=...
|
||||
VAPID_SUBJECT=mailto:you@example.com
|
||||
```
|
||||
|
||||
Generate VAPID keys with: `npx web-push generate-vapid-keys`
|
||||
|
||||
### Calendar
|
||||
|
||||
No env vars needed: always available.
|
||||
|
||||
---
|
||||
|
||||
## Updating
|
||||
|
||||
The default `IMAGE_TAG=latest` follows `main` and updates on every `docker compose pull`. For production, **pin to a specific release** so updates are deliberate:
|
||||
|
||||
```env
|
||||
# .env
|
||||
IMAGE_TAG=1.2.3
|
||||
```
|
||||
|
||||
Browse available tags at https://github.com/erp-mafia/gnubok/pkgs/container/gnubok. For maximum integrity, pin by digest:
|
||||
|
||||
```env
|
||||
IMAGE_TAG=1.2.3@sha256:abcdef...
|
||||
```
|
||||
|
||||
Apply updates:
|
||||
|
||||
```bash
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
The cron sidecar is a small Alpine image built locally: it rebuilds automatically on `up --build` if you re-download `docker/cron.Dockerfile`. Base-image digests (node, alpine, caddy) are pinned in source; [Dependabot](.github/dependabot.yml) opens PRs weekly when upstream ships security updates.
|
||||
|
||||
---
|
||||
|
||||
## Building from Source
|
||||
|
||||
If you prefer to build locally instead of pulling the pre-built image:
|
||||
|
||||
```bash
|
||||
# Clone the repo
|
||||
git clone https://github.com/gnubok/gnubok.git
|
||||
cd Accounted
|
||||
cp .env.docker.example .env
|
||||
# Fill in .env
|
||||
|
||||
# Build and start
|
||||
docker compose -f docker-compose.yml -f docker-compose.build.yml up --build -d
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
The compose setup runs two containers:
|
||||
|
||||
| Container | What it does |
|
||||
|-----------|-------------|
|
||||
| `app` | Next.js application server |
|
||||
| `cron` | Lightweight Alpine sidecar that runs scheduled jobs (deadline checks, invoice reminders, tax deadline sync, document verification) via [supercronic](https://github.com/aptible/supercronic) |
|
||||
|
||||
The cron container waits for the app's healthcheck to pass before starting. It calls the app's cron API endpoints over the internal Docker network.
|
||||
|
||||
### How NEXT_PUBLIC_* injection works
|
||||
|
||||
The image is built with placeholder values (e.g. `__NEXT_PUBLIC_SUPABASE_URL__`) baked into the JavaScript bundles. At container start, `docker-entrypoint.sh` runs as `root`, `sed`-substitutes the placeholders with your runtime env vars, then runs `chmod -R a-w /app/.next/static` and drops privileges with `su-exec nextjs:nodejs` before exec'ing Node. The served JS bundle is owned by `root` and read-only by the time the application starts: a runtime RCE in the Node process cannot rewrite what other users will receive.
|
||||
|
||||
---
|
||||
|
||||
## Ports
|
||||
|
||||
The app listens on port 3000 inside the container. The base compose binds it to `127.0.0.1:3000` on the host: change `PORT` in `.env` to remap. To expose on all interfaces (only do this if you're putting your own reverse proxy in front), override the port binding in a local `docker-compose.override.yml`:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
app:
|
||||
ports: !override
|
||||
- "${PORT:-3000}:3000"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Reverse Proxy
|
||||
|
||||
The preferred path is the bundled Caddy overlay: see [Enable HTTPS](#enable-https-recommended). If you already run nginx, Traefik, or sit behind Cloudflare, leave the app on `127.0.0.1:3000` and point your existing proxy at it. Set `NEXT_PUBLIC_APP_URL` to the public URL.
|
||||
|
||||
Example nginx upstream:
|
||||
|
||||
```nginx
|
||||
server {
|
||||
server_name gnubok.example.com;
|
||||
listen 443 ssl http2;
|
||||
# ssl_certificate / ssl_certificate_key / etc.
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:3000;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**Container exits immediately**
|
||||
```bash
|
||||
docker compose logs app
|
||||
```
|
||||
Most common cause: missing required env vars. Check that all 5 required values in `.env` are set.
|
||||
|
||||
**Health check fails**
|
||||
```bash
|
||||
curl -v http://localhost:3000/api/health
|
||||
```
|
||||
The health endpoint tests database connectivity. If it returns `unhealthy`, verify your Supabase URL and service role key are correct.
|
||||
|
||||
**Cron container keeps restarting**
|
||||
```bash
|
||||
docker compose logs cron
|
||||
```
|
||||
The cron container depends on the app being healthy first. If the app never becomes healthy, the cron container will wait indefinitely.
|
||||
|
||||
**Port already in use**
|
||||
Set a different port: `PORT=8080 docker compose up -d`
|
||||
@@ -0,0 +1,870 @@
|
||||
# Extension System: Design Document
|
||||
|
||||
## The App
|
||||
|
||||
Accounted is a Swedish accounting platform for sole traders (enskild firma) and limited companies (aktiebolag). It handles the legally required bookkeeping and financial management that every Swedish business needs.
|
||||
|
||||
## Core Functionality
|
||||
|
||||
The core is the standard accounting system. It's what every user gets out of the box: the features that exist in any accounting platform like Fortnox, Visma, or Björn Lundén. Nothing more, nothing less:
|
||||
|
||||
- Double-entry bookkeeping (journal entries, BAS chart of accounts, voucher numbering)
|
||||
- Invoicing (create, send, track, payment matching)
|
||||
- Supplier invoice management
|
||||
- Bank transaction reconciliation
|
||||
- Financial reports (income statement, balance sheet, trial balance, VAT declaration, general ledger)
|
||||
- Tax compliance (SRU export, NE-bilaga, tax deadline tracking)
|
||||
- Document archive with 7-year legal retention
|
||||
- Customer and supplier management
|
||||
|
||||
That's the core. It doesn't include receipt scanning, AI categorization, AI chat, push notifications, or PSD2 bank connection. Those are not standard accounting features: they're value-adds.
|
||||
|
||||
## Extensions
|
||||
|
||||
Extensions are **everything beyond the core accounting system**. They are self-contained tools that a user adds to their dashboard. All compiled extensions are active for all users: the operator decides which extensions to include via `extensions.config.json` at build time.
|
||||
|
||||
There are two kinds of extensions:
|
||||
|
||||
### General Extensions
|
||||
|
||||
General extensions are not tied to any specific business sector. They're useful for any business but they go beyond what a standard accounting system offers.
|
||||
|
||||
Examples:
|
||||
- **Receipt OCR**: Scan receipts and extract data automatically
|
||||
- **AI Categorization**: AI-powered transaction categorization suggestions
|
||||
- **AI Chat**: AI assistant for tax and bookkeeping questions
|
||||
- **Push Notifications**: Event notifications for accounting activities
|
||||
- **Enable Banking**: PSD2 automatic bank transaction sync
|
||||
|
||||
These are configured via `extensions.config.json` and only loaded when explicitly enabled by the operator.
|
||||
|
||||
### Sector Extensions
|
||||
|
||||
Sector extensions are tied to a specific market sector. They're only relevant to businesses operating in that sector. A restaurant owner wants "Food Cost %" but an IT consultant does not.
|
||||
|
||||
Examples:
|
||||
- **Restaurant:** Food Cost %, Earnings Per Alcohol Liter, POS Z-Report Import, Tip Tracking
|
||||
- **Construction:** ROT Calculator, Project Cost Tracking
|
||||
- **Hotel:** RevPAR, Occupancy Tracking
|
||||
- **IT/Consulting:** Billable Hours Ratio, Project Billing Metrics
|
||||
- **E-commerce:** Shopify Order Import, Multi-channel Revenue Analytics
|
||||
|
||||
### The Unified Model
|
||||
|
||||
Both general and sector extensions live in the same system:
|
||||
|
||||
```
|
||||
extensions/
|
||||
general/ ← General extensions (any business)
|
||||
receipt-ocr/
|
||||
ai-categorization/
|
||||
ai-chat/
|
||||
push-notifications/
|
||||
enable-banking/
|
||||
invoice-inbox/
|
||||
calendar/
|
||||
email/
|
||||
restaurant/ ← Restaurant sector extensions
|
||||
food-cost/
|
||||
earnings-per-liter/
|
||||
pos-import/
|
||||
tip-tracking/
|
||||
construction/ ← Construction sector extensions
|
||||
rot-calculator/
|
||||
project-cost/
|
||||
hotel/ ← Hotel sector extensions
|
||||
revpar/
|
||||
occupancy/
|
||||
tech/ ← IT/Consulting sector extensions
|
||||
billable-hours/
|
||||
project-billing/
|
||||
ecommerce/ ← E-commerce sector extensions
|
||||
shopify-import/
|
||||
multichannel-revenue/
|
||||
export/ ← Export & international trade extensions
|
||||
eu-sales-list/
|
||||
intrastat/
|
||||
vat-monitor/
|
||||
currency-receivables/
|
||||
```
|
||||
|
||||
Each extension directory contains a `manifest.json` declaring metadata, entry point, workspace component path, required env vars, and npm dependencies.
|
||||
|
||||
In the marketplace:
|
||||
- General extensions are shown to everyone, always visible
|
||||
- Sector extensions are suggested based on the user's primary sector
|
||||
- But all extensions are browsable by everyone regardless of sector
|
||||
|
||||
In the sidebar under "Your Extensions":
|
||||
- Both general and sector extensions appear together
|
||||
- Whatever the user has enabled shows up here
|
||||
|
||||
---
|
||||
|
||||
## Design Decisions (Confirmed)
|
||||
|
||||
### 1. Extensions are self-contained: they do NOT write to the core accounting system
|
||||
|
||||
Extensions are **independent tools that live on the dashboard**. They are NOT part of the core accounting system. They have their own world, their own data, their own purpose. They never create journal entries, invoices, or modify any accounting records.
|
||||
|
||||
There are two one-way data flows into an extension. Data never flows back:
|
||||
|
||||
```
|
||||
Core Accounting Data ──→ Extension (reads it, displays it, uses it in calculations)
|
||||
User Manual Input ──→ Extension (stores it in extension's own data, processes it)
|
||||
Extension ──✗──→ Core Accounting (never writes back)
|
||||
```
|
||||
|
||||
An extension may:
|
||||
- **Be fed core data**: the platform feeds accounting data (journal entries, transactions, invoices) into the extension for it to read and use in calculations
|
||||
- **Accept user input**: the user submits data directly into the extension for data that doesn't exist in any accounting system (e.g. liters of alcohol sold per day, POS Z-report files, Shopify order exports)
|
||||
- **Store its own data**: extension-specific data lives in the extension's own storage, separate from core accounting
|
||||
- **Calculate and display**: combine core data + extension data to produce metrics, reports, insights
|
||||
|
||||
An extension may NOT:
|
||||
- Create journal entries
|
||||
- Create or modify invoices
|
||||
- Modify transactions or any core accounting table
|
||||
- Write back to the core accounting system in any way
|
||||
|
||||
This is a critical architectural constraint. Extensions are safe: enabling or disabling one can never corrupt or affect the accounting data. The core bookkeeping is a walled garden that extensions can look into but never modify.
|
||||
|
||||
**Important:** Features like POS Z-Report Import and Shopify Order Import are EXTENSIONS. They import data into the extension's own storage and provide analytics on that data. They do not create journal entries from imported data. The bookkeeping of POS data or Shopify orders is a separate activity the user does in the core platform.
|
||||
|
||||
### 2. Data source depends on the extension: three patterns
|
||||
|
||||
**Pattern A: Fed from core accounting data**
|
||||
Some extensions are fed existing bookkeeping data. For example, a "Food Cost %" extension reads journal entries for food purchase accounts (4000-series) and food revenue accounts (3000-series), then calculates and displays the metric. The user doesn't enter anything: the data already exists in the bookkeeping. These are extensions for data that Fortnox, Visma, and other accounting systems already have.
|
||||
|
||||
**Pattern B: User submits data manually**
|
||||
Some extensions need data that doesn't exist in any accounting system. No system tracks liters of alcohol sold, or daily staff tips, or room occupancy counts. For these extensions, the user manually submits data into the extension's workspace. The extension stores, processes, and displays this data. This has nothing to do with the core accounting functionality.
|
||||
|
||||
**Pattern C: Both**
|
||||
Some extensions combine core accounting data with user-submitted data. "Earnings Per Alcohol Liter" reads alcohol revenue from the bookkeeping (Pattern A) and takes user-entered liter counts (Pattern B) to calculate revenue per liter.
|
||||
|
||||
### 3. Extension marketplace for browsing
|
||||
|
||||
Users have a dedicated "Extensions" marketplace page where they can:
|
||||
- Browse all compiled extensions (general + all sectors)
|
||||
- Read descriptions and details
|
||||
- Open extension workspaces
|
||||
|
||||
### 4. Primary sector with cross-sector browsing
|
||||
|
||||
During onboarding, the user selects a **primary sector** (e.g. "Restaurant & Cafe"). The app then suggests extensions for that sector, plus general extensions. But the user is NOT locked in: they can browse and enable extensions from any sector at any time via the marketplace.
|
||||
|
||||
The primary sector serves as a **recommendation filter**, not a restriction.
|
||||
|
||||
### 5. First-party now, third-party later
|
||||
|
||||
We build all extensions ourselves initially. But the architecture should be clean and well-defined enough that external developers could eventually build extensions too. This means:
|
||||
- Clear extension interface/contract
|
||||
- Well-documented data access patterns
|
||||
- Self-contained extension structure (each extension is a standalone module)
|
||||
|
||||
---
|
||||
|
||||
## The User Experience
|
||||
|
||||
1. User signs up, goes through onboarding
|
||||
2. On the dashboard, the sidebar shows links to compiled extensions that have a workspace + quickAction
|
||||
3. Clicking an extension opens its workspace: a dedicated page with the extension's own UI
|
||||
4. The user interacts with the extension: views data, enters inputs, sees calculations/reports
|
||||
5. User can browse the marketplace to see all compiled extensions
|
||||
|
||||
---
|
||||
|
||||
## Extension Definition
|
||||
|
||||
### What an Extension Contains
|
||||
|
||||
| Part | Required? | Description |
|
||||
|------|-----------|-------------|
|
||||
| **Metadata** | Yes | Name, description, sector (or 'general'), category, icon: for marketplace and sidebar |
|
||||
| **Workspace UI** | Yes | A React component: the main page the user sees when they click the extension |
|
||||
| **Extension data** | Depends | Storage for user-submitted data and extension state |
|
||||
| **Configuration** | Optional | Settings panel for customizing the extension's behavior |
|
||||
| **Core data queries** | Optional | Queries that read from journal entries, transactions, invoices, etc. |
|
||||
|
||||
### Marketplace Definition (ExtensionDefinition)
|
||||
|
||||
This is the metadata used for the marketplace UI and sector browsing. It comes from each extension's `manifest.json` file and is code-generated into `lib/extensions/_generated/sector-definitions.ts`.
|
||||
|
||||
```typescript
|
||||
interface ExtensionDefinition {
|
||||
// Identity
|
||||
slug: string // URL-safe ID, unique within sector (e.g. 'earnings-per-liter')
|
||||
name: string // Display name (e.g. 'Earnings Per Alcohol Liter')
|
||||
sector: SectorSlug // 'general' | 'restaurant' | 'construction' | 'hotel' | 'tech' | 'ecommerce' | 'export'
|
||||
category: ExtensionCategory // 'accounting' | 'reports' | 'import' | 'operations'
|
||||
|
||||
// Display (for marketplace and sidebar)
|
||||
description: string // One-line description
|
||||
longDescription: string // Detailed description with features
|
||||
icon: string // Lucide icon name
|
||||
entityTypes?: EntityType[] // Supported entity types (default: both EF and AB)
|
||||
|
||||
// Data patterns
|
||||
dataPattern: 'core' | 'manual' | 'both' // How the extension gets its data
|
||||
readsCoreTables?: string[] // Which core tables this extension reads (for pattern A/C)
|
||||
hasOwnData?: boolean // Whether users submit data into this extension (for pattern B/C)
|
||||
|
||||
// Optional
|
||||
quickAction?: QuickActionDefinition // Dashboard quick action
|
||||
subscriptionNotice?: string // Notice shown when enabling (e.g. external subscription)
|
||||
}
|
||||
```
|
||||
|
||||
### Runtime Extension Interface
|
||||
|
||||
This is the contract for extension logic at runtime. Extensions are imported and registered by the loader.
|
||||
|
||||
```typescript
|
||||
interface Extension {
|
||||
id: string
|
||||
name: string
|
||||
version: string
|
||||
sector?: SectorSlug
|
||||
|
||||
// Surfaces
|
||||
routes?: RouteDefinition[]
|
||||
apiRoutes?: ApiRouteDefinition[] // Dispatched by catch-all at /api/extensions/ext/
|
||||
sidebarItems?: SidebarItem[]
|
||||
eventHandlers?: ExtensionEventHandler[]
|
||||
mappingRuleTypes?: MappingRuleTypeDefinition[]
|
||||
reportTypes?: ReportDefinition[]
|
||||
settingsPanel?: SettingsPanelDefinition
|
||||
taxCodes?: TaxCodeDefinition[]
|
||||
dimensionTypes?: DimensionDefinition[]
|
||||
|
||||
/** Named services this extension provides to core via registry lookup */
|
||||
services?: Record<string, (...args: any[]) => Promise<any>>
|
||||
|
||||
// Lifecycle hooks
|
||||
onInstall?(ctx: ExtensionContext): Promise<void>
|
||||
onUninstall?(ctx: ExtensionContext): Promise<void>
|
||||
}
|
||||
```
|
||||
|
||||
### Sector Definition
|
||||
|
||||
```typescript
|
||||
interface Sector {
|
||||
slug: SectorSlug // 'general' | 'restaurant' | 'construction' | 'hotel' | 'tech' | 'ecommerce' | 'export'
|
||||
name: string // 'General' | 'Restaurant & Cafe' | etc.
|
||||
icon: string // Lucide icon name
|
||||
description: string // Short tagline
|
||||
extensions: ExtensionDefinition[]
|
||||
}
|
||||
```
|
||||
|
||||
### Extension Categories
|
||||
|
||||
```typescript
|
||||
type ExtensionCategory = 'accounting' | 'reports' | 'import' | 'operations'
|
||||
```
|
||||
|
||||
| Category | Color | Purpose |
|
||||
|----------|-------|---------|
|
||||
| Accounting & Tax | Red | Calculations related to bookkeeping, VAT, deductions |
|
||||
| Industry Reports | Blue | KPIs, analytics, metrics |
|
||||
| Smart Import | Green | Parse and import data from external tools |
|
||||
| Operational Tools | Gray | Day-to-day business tools |
|
||||
|
||||
---
|
||||
|
||||
## Concrete Examples
|
||||
|
||||
| Extension | Sector | Data Pattern | User Input | Reads Core Data | What it Does |
|
||||
|-----------|--------|--------------|------------|-----------------|--------------|
|
||||
| Receipt OCR | General | B (manual) | Uploads receipt images | None | Scans receipts, extracts merchant/amount/VAT data |
|
||||
| AI Categorization | General | A (core) | None | Uncategorized transactions | Suggests BAS account categories using AI |
|
||||
| Enable Banking | General | B (manual) | Bank connection setup | None | Syncs bank transactions via PSD2 |
|
||||
| Earnings Per Alcohol Liter | Restaurant | A + B (both) | Liters sold per day/week | Alcohol revenue from BAS 3001 | Calculates revenue/liter, trends over time |
|
||||
| Food Cost % | Restaurant | A (core) | None | Food purchases (4000-series), food revenue (3000-series) | Calculates food_cost/food_revenue %, trends |
|
||||
| Tip Tracking | Restaurant | B (manual) | Tip amounts per shift | Optionally reads staff cost accounts | Total tips, tips/employee, tip % of revenue |
|
||||
| POS Z-Report Import | Restaurant | B (manual) | Uploads Z-report CSV/Excel | None | Parses POS data, stores in extension, shows daily sales analytics |
|
||||
| Shopify Order Import | E-commerce | B (manual) | Uploads order export | None | Imports orders into extension, shows revenue by product, trends |
|
||||
| ROT Calculator | Construction | A + B (both) | Labor hours, material costs per job | Invoice data for customer billing | ROT deduction amounts (30% of labor, max 50k/year per customer) |
|
||||
| RevPAR | Hotel | A + B (both) | Room count and occupancy | Room revenue accounts | Revenue Per Available Room, occupancy rate |
|
||||
| Billable Hours Ratio | IT/Consulting | A + B (both) | Hours worked per project | Invoice data for billed amounts | Billable/total hours, effective hourly rate |
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
### Where Things Live
|
||||
|
||||
```
|
||||
extensions/ ← Extension source code (opt-in via config)
|
||||
general/ ← General extensions
|
||||
receipt-ocr/
|
||||
manifest.json ← Metadata, entry point, env vars, workspace path
|
||||
index.ts ← Extension definition + logic (exports Extension)
|
||||
lib/
|
||||
__tests__/
|
||||
ai-categorization/
|
||||
manifest.json
|
||||
index.ts
|
||||
lib/
|
||||
ai-chat/
|
||||
manifest.json
|
||||
index.ts
|
||||
lib/
|
||||
push-notifications/
|
||||
manifest.json
|
||||
index.ts
|
||||
lib/
|
||||
enable-banking/
|
||||
manifest.json
|
||||
index.ts
|
||||
lib/
|
||||
email/ ← Email service extension (registers Resend impl)
|
||||
manifest.json
|
||||
index.ts
|
||||
lib/
|
||||
invoice-inbox/
|
||||
manifest.json
|
||||
index.ts
|
||||
calendar/
|
||||
manifest.json
|
||||
index.ts
|
||||
restaurant/ ← Restaurant sector
|
||||
food-cost/
|
||||
manifest.json
|
||||
earnings-per-liter/
|
||||
manifest.json
|
||||
pos-import/
|
||||
manifest.json
|
||||
tip-tracking/
|
||||
manifest.json
|
||||
construction/ ← Construction sector
|
||||
rot-calculator/
|
||||
manifest.json
|
||||
project-cost/
|
||||
manifest.json
|
||||
hotel/ ← Hotel sector
|
||||
revpar/
|
||||
manifest.json
|
||||
occupancy/
|
||||
manifest.json
|
||||
tech/ ← IT/Consulting sector
|
||||
billable-hours/
|
||||
manifest.json
|
||||
project-billing/
|
||||
manifest.json
|
||||
ecommerce/ ← E-commerce sector
|
||||
shopify-import/
|
||||
manifest.json
|
||||
multichannel-revenue/
|
||||
manifest.json
|
||||
export/ ← Export & international trade sector
|
||||
eu-sales-list/
|
||||
manifest.json
|
||||
index.ts
|
||||
intrastat/
|
||||
manifest.json
|
||||
vat-monitor/
|
||||
manifest.json
|
||||
currency-receivables/
|
||||
manifest.json
|
||||
|
||||
extensions.config.json ← Which extensions are enabled (empty = core-only)
|
||||
extensions.schema.json ← JSON Schema for extensions.config.json
|
||||
|
||||
lib/
|
||||
extensions/
|
||||
types.ts ← Extension, ExtensionDefinition, Sector types
|
||||
sectors.ts ← Sector shells + generated extension definitions
|
||||
workspace-registry.tsx ← Maps sector/slug → lazy-loaded React component
|
||||
loader.ts ← Imports from _generated, registers extensions
|
||||
registry.ts ← Runtime extension registry (get, register)
|
||||
context-factory.ts ← Builds ExtensionContext for handlers
|
||||
_generated/ ← AUTO-GENERATED by npm run setup:extensions
|
||||
extension-list.ts ← FIRST_PARTY_EXTENSIONS array (static imports)
|
||||
workspace-map.tsx ← Lazy-loaded workspace components
|
||||
sector-definitions.ts ← ExtensionDefinition[] per sector
|
||||
enabled-extensions.ts ← ENABLED_EXTENSION_IDS set for build-time checks
|
||||
email/
|
||||
service.ts ← EmailService interface + no-op default + getEmailService()
|
||||
reports/
|
||||
sru-export/ ← SRU file export (core, not an extension)
|
||||
ne-bilaga/ ← NE tax form attachment (core, not an extension)
|
||||
|
||||
scripts/
|
||||
generate-extension-registry.ts ← Reads config + manifests, writes _generated/ files
|
||||
|
||||
app/api/extensions/
|
||||
ext/[...path]/
|
||||
route.ts ← Catch-all API dispatcher for extension routes
|
||||
|
||||
components/
|
||||
extensions/
|
||||
ExtensionWorkspaceShell.tsx ← Shared layout wrapper
|
||||
shared/ ← Shared UI primitives
|
||||
KPICard.tsx
|
||||
DataEntryForm.tsx
|
||||
DateRangeFilter.tsx
|
||||
EmptyExtensionState.tsx
|
||||
ExtensionLoadingSkeleton.tsx
|
||||
general/ ← General extension workspaces
|
||||
ReceiptOcrWorkspace.tsx
|
||||
AiCategorizationWorkspace.tsx
|
||||
AiChatWorkspace.tsx
|
||||
restaurant/ ← Restaurant extension workspaces
|
||||
EarningsPerLiterWorkspace.tsx
|
||||
FoodCostWorkspace.tsx
|
||||
PosImportWorkspace.tsx
|
||||
construction/
|
||||
RotCalculatorWorkspace.tsx
|
||||
hotel/
|
||||
RevparWorkspace.tsx
|
||||
tech/
|
||||
BillableHoursWorkspace.tsx
|
||||
ecommerce/
|
||||
ShopifyImportWorkspace.tsx
|
||||
|
||||
app/(dashboard)/
|
||||
extensions/ ← Marketplace
|
||||
page.tsx ← Extension hub (browse sectors + general)
|
||||
[sector]/
|
||||
page.tsx ← Extensions for a specific sector
|
||||
[extension]/
|
||||
page.tsx ← Extension detail + workspace link
|
||||
e/ ← Extension workspaces
|
||||
[sector]/
|
||||
[slug]/
|
||||
page.tsx ← Renders the workspace component
|
||||
```
|
||||
|
||||
### Data Storage
|
||||
|
||||
Extensions store their data in the existing `extension_data` table:
|
||||
|
||||
```
|
||||
extension_data:
|
||||
user_id: auth user
|
||||
extension_id: 'restaurant/earnings-per-liter' (sector/slug format)
|
||||
key: 'settings' | 'entries' | 'config' | custom keys
|
||||
value: JSONB (flexible)
|
||||
```
|
||||
|
||||
For the "Earnings Per Liter" extension, data might look like:
|
||||
```
|
||||
key: 'settings' → { "defaultUnit": "liter", "currency": "SEK" }
|
||||
key: 'entries' → [{ "date": "2025-01-15", "liters": 42.5, "type": "spirits" }, ...]
|
||||
key: 'config' → { "revenueAccounts": ["3001"], "trackByType": true }
|
||||
```
|
||||
|
||||
### Extension Enablement
|
||||
|
||||
Extensions are enabled at **build time** via `extensions.config.json`. All compiled extensions are active for all users: there is no per-user toggle system. The operator (hosted or self-hosted) decides which extensions to include.
|
||||
|
||||
To check if an extension is compiled in at runtime (e.g. for conditional UI), use the build-time constant:
|
||||
|
||||
```typescript
|
||||
import { ENABLED_EXTENSION_IDS } from '@/lib/extensions/_generated/enabled-extensions'
|
||||
|
||||
if (ENABLED_EXTENSION_IDS.has('receipt-ocr')) {
|
||||
// Show OCR UI
|
||||
}
|
||||
```
|
||||
|
||||
AI extensions (`receipt-ocr`, `ai-categorization`, `ai-chat`) additionally require per-user AI consent before making API calls. This is a separate system using the `extension_data` table, managed by `lib/extensions/ai-consent.ts`.
|
||||
|
||||
> **Note:** The `extension_toggles` database table still exists but is no longer queried by any code. It can be dropped in a future migration.
|
||||
|
||||
### API Routes for Extensions
|
||||
|
||||
Extensions declare their API routes via the `apiRoutes` array on the `Extension` object:
|
||||
|
||||
```typescript
|
||||
export const myExtension: Extension = {
|
||||
id: 'my-extension',
|
||||
// ...
|
||||
apiRoutes: [
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/',
|
||||
handler: async (request: Request, ctx?: ExtensionContext) => {
|
||||
// Handle POST /api/extensions/ext/my-extension/
|
||||
return new Response(JSON.stringify({ ok: true }))
|
||||
},
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/:id',
|
||||
handler: async (request: Request, ctx?: ExtensionContext) => {
|
||||
// :id is extracted and available as ?_id=... search param
|
||||
const url = new URL(request.url)
|
||||
const id = url.searchParams.get('_id')
|
||||
return new Response(JSON.stringify({ id }))
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
All extension API routes are served by a single **catch-all dispatcher** at:
|
||||
|
||||
```
|
||||
app/api/extensions/ext/[...path]/route.ts
|
||||
```
|
||||
|
||||
URL scheme: `/api/extensions/ext/{extensionId}/{...routePath}`
|
||||
|
||||
The dispatcher handles:
|
||||
1. **Auth check**: 401 if not logged in
|
||||
2. **Extension lookup**: 404 if extension not registered or has no apiRoutes
|
||||
3. **Path matching**: Matches method + path pattern (supports `:param` wildcards)
|
||||
4. **AI consent check**: 403 if AI extension and user hasn't consented
|
||||
5. **Param extraction**: Path params like `:id` are added as `_id` search params
|
||||
6. **Context building**: Creates `ExtensionContext` with supabase, userId, settings, storage, logger
|
||||
7. **Dispatch**: Calls the matched handler with the request and context
|
||||
|
||||
The generic data CRUD routes for `extension_data` still exist alongside:
|
||||
|
||||
```
|
||||
app/api/extensions/[sector]/[slug]/
|
||||
data/route.ts : GET (read entries), POST (submit new entry), DELETE (remove entry)
|
||||
settings/route.ts : GET (read settings), PATCH (update settings)
|
||||
```
|
||||
|
||||
### Sidebar Integration
|
||||
|
||||
The sidebar (`DashboardNav.tsx`) has a section for extensions. It shows all compiled extensions that have a workspace and a `quickAction` with an `href`:
|
||||
|
||||
```
|
||||
── Your Extensions ──────────
|
||||
📷 Receipt OCR → /e/general/receipt-ocr
|
||||
🤖 AI Categorization → /e/general/ai-categorization
|
||||
📊 Food Cost % → /e/restaurant/food-cost
|
||||
🍷 Earnings Per Liter → /e/restaurant/earnings-per-liter
|
||||
```
|
||||
|
||||
Each link goes to `/e/{sector}/{slug}` which renders the extension's workspace component.
|
||||
|
||||
---
|
||||
|
||||
## The Extension Workspace Pattern
|
||||
|
||||
Every extension workspace follows the same pattern:
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ Extension Workspace Shell │
|
||||
│ ┌─────────────────────────────────────────────┐ │
|
||||
│ │ Header: Extension name + settings link │ │
|
||||
│ ├─────────────────────────────────────────────┤ │
|
||||
│ │ │ │
|
||||
│ │ Extension-specific UI │ │
|
||||
│ │ │ │
|
||||
│ │ This is where the extension does its thing │ │
|
||||
│ │ - Data entry forms │ │
|
||||
│ │ - KPI cards and charts │ │
|
||||
│ │ - Tables of submitted data │ │
|
||||
│ │ - Calculation results │ │
|
||||
│ │ - Date range filters │ │
|
||||
│ │ │ │
|
||||
│ └─────────────────────────────────────────────┘ │
|
||||
└─────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
The `ExtensionWorkspaceShell` provides consistent chrome (header, breadcrumbs, settings link). The extension fills in the content area with whatever UI it needs.
|
||||
|
||||
### Example: Earnings Per Alcohol Liter
|
||||
|
||||
When the user clicks this extension, they see:
|
||||
|
||||
1. **KPI cards at top**: Current earnings/liter, trend vs last month, total liters this month
|
||||
2. **Data entry section**: Form to log daily sales (date, liters sold, alcohol type)
|
||||
3. **History table**: Past entries with edit/delete
|
||||
4. **Chart**: Earnings per liter over time (line chart)
|
||||
5. **Revenue breakdown**: Reads from core journal entries: alcohol revenue by account
|
||||
|
||||
The extension reads revenue data from journal_entry_lines (BAS 3001 for 25% alcohol revenue) and combines it with user-submitted liter data to calculate the metric.
|
||||
|
||||
---
|
||||
|
||||
## Migration from Previous Architecture (Completed)
|
||||
|
||||
The previous architecture had extensions "always loaded" via hardcoded static imports in `loader.ts`, with SRU export and NE-bilaga treated as extensions. The system was fully decoupled in "Plan B: Full Decoupling":
|
||||
|
||||
### What Changed
|
||||
|
||||
1. **Extension opt-in system** -- Extensions are configured via `extensions.config.json`. A generator script (`npm run setup:extensions`) reads manifest files and produces `lib/extensions/_generated/` files. Core compiles and runs with an empty config (zero extensions).
|
||||
|
||||
2. **Services pattern** -- Extensions can expose named services via `services?: Record<string, (...args: any[]) => Promise<any>>` on the Extension interface. Core code uses `extensionRegistry.get('ext-id')?.services?.methodName` for runtime lookup instead of direct imports. This is how `ai-categorization` provides template embedding functions to core booking logic.
|
||||
|
||||
3. **Catch-all API dispatcher** -- Extension API routes are registered via `apiRoutes: ApiRouteDefinition[]` on the Extension object. The catch-all at `/api/extensions/ext/[...path]/route.ts` handles auth, AI consent checks, path param extraction, and dispatches to the handler. URL pattern: `/api/extensions/ext/{extensionId}/{path}`.
|
||||
|
||||
4. **SRU/NE-bilaga are core** -- These tax compliance features were moved from `extensions/` into `lib/reports/sru-export/` and `lib/reports/ne-bilaga/`. They are always available regardless of extension configuration.
|
||||
|
||||
5. **Email is optional** -- Core defines an `EmailService` interface in `lib/email/service.ts` with a no-op default. The `email` extension registers a Resend implementation at load time. Core callers use `getEmailService()` -- when the email extension is not enabled, email calls silently return `{ success: false }`.
|
||||
|
||||
6. **Export sector** -- EU Sales List, Intrastat, VAT Monitor, and Currency Receivables are extensions under `extensions/export/`.
|
||||
|
||||
7. **Manifest files** -- Every extension has a `manifest.json` that declares metadata, entry point, workspace component path, required env vars, optional env vars, and npm dependencies.
|
||||
|
||||
8. **Generated files** -- Three files in `lib/extensions/_generated/` are produced by the generator:
|
||||
- `extension-list.ts` -- Static imports and `FIRST_PARTY_EXTENSIONS` array
|
||||
- `workspace-map.tsx` -- `next/dynamic` lazy-loaded workspace components
|
||||
- `sector-definitions.ts` -- `ExtensionDefinition[]` per sector for the marketplace UI
|
||||
|
||||
---
|
||||
|
||||
## Implementation Status
|
||||
|
||||
| Item | Status | Notes |
|
||||
|------|--------|-------|
|
||||
| Extension types (ExtensionDefinition, Sector, etc.) | Done | `lib/extensions/types.ts` |
|
||||
| Sector data registry | Done | `lib/extensions/sectors.ts` + generated definitions |
|
||||
| Database migration (extension_toggles) | Done | Migration 037 (table exists but no longer queried) |
|
||||
| Build-time extension check | Done | `ENABLED_EXTENSION_IDS` in `_generated/enabled-extensions.ts` |
|
||||
| Workspace component registry | Done | `lib/extensions/workspace-registry.tsx` + generated map |
|
||||
| Workspace routing (`/e/[sector]/[slug]`) | Done | `app/(dashboard)/e/[sector]/[slug]/page.tsx` |
|
||||
| Workspace shell | Done | `components/extensions/ExtensionWorkspaceShell.tsx` |
|
||||
| Marketplace pages | Done | `app/(dashboard)/extensions/` |
|
||||
| Sidebar "Your Extensions" | Done | Wired into DashboardNav |
|
||||
| Onboarding with build-time extension checks | Done | Uses `ENABLED_EXTENSION_IDS` |
|
||||
| Shared UI components | Done | KPICard, DataEntryForm, DateRangeFilter, etc. |
|
||||
| Extension API routes (generic CRUD) | Done | `app/api/extensions/[sector]/[slug]/` |
|
||||
| Catch-all API dispatcher | Done | `app/api/extensions/ext/[...path]/route.ts` |
|
||||
| Services pattern | Done | Used by ai-categorization for template embeddings |
|
||||
| Email service interface | Done | `lib/email/service.ts` + email extension |
|
||||
| SRU/NE-bilaga moved to core | Done | `lib/reports/sru-export/` + `lib/reports/ne-bilaga/` |
|
||||
| Manifest files for all extensions | Done | 25 manifest.json files |
|
||||
| Code generator | Done | `scripts/generate-extension-registry.ts` |
|
||||
| extensions.config.json opt-in | Done | Core runs with empty config |
|
||||
| General extensions with manifests | Done | All general extensions have manifests |
|
||||
| Export sector extensions | Done | EU Sales List, Intrastat, VAT Monitor, Currency Receivables |
|
||||
| Restaurant sector extensions | Done | Food Cost, Earnings Per Liter, POS Import, Tip Tracking |
|
||||
| Construction sector extensions | Done | ROT Calculator, Project Cost |
|
||||
| Hotel sector extensions | Done | RevPAR, Occupancy |
|
||||
| Tech sector extensions | Done | Billable Hours, Project Billing |
|
||||
| E-commerce sector extensions | Done | Shopify Import, Multichannel Revenue |
|
||||
|
||||
---
|
||||
|
||||
## Self-Hosting Guide
|
||||
|
||||
### Core Setup (No Extensions)
|
||||
|
||||
Core runs with zero extensions. This gives you the standard accounting system: bookkeeping, invoicing, bank reconciliation, reports, tax compliance (SRU, NE-bilaga, VAT declaration).
|
||||
|
||||
```bash
|
||||
# 1. Clone and install
|
||||
git clone <repo-url> && cd Accounted
|
||||
npm install
|
||||
|
||||
# 2. Set environment variables (minimum 4)
|
||||
export NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
|
||||
export NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key
|
||||
export SUPABASE_SERVICE_ROLE_KEY=your-service-role-key
|
||||
export NEXT_PUBLIC_APP_URL=https://your-domain.com
|
||||
|
||||
# 3. Run database migrations
|
||||
# Apply all migrations in supabase/migrations/ to your Supabase project
|
||||
|
||||
# 4. Build and run
|
||||
npm run build # setup:extensions runs automatically (empty config = no extensions)
|
||||
npm start
|
||||
```
|
||||
|
||||
### Enabling Extensions
|
||||
|
||||
```bash
|
||||
# 1. See available extensions
|
||||
npx tsx scripts/generate-extension-registry.ts --list
|
||||
|
||||
# 2. Edit extensions.config.json: add extension IDs
|
||||
{
|
||||
"extensions": ["receipt-ocr", "ai-categorization", "email"]
|
||||
}
|
||||
|
||||
# 3. Regenerate (also runs automatically on build/dev)
|
||||
npm run setup:extensions
|
||||
|
||||
# 4. Set extension-specific env vars (check each manifest.json for requiredEnvVars)
|
||||
export ANTHROPIC_API_KEY=...
|
||||
export OPENAI_API_KEY=...
|
||||
export RESEND_API_KEY=...
|
||||
export RESEND_FROM_EMAIL=...
|
||||
|
||||
# 5. Rebuild
|
||||
npm run build
|
||||
```
|
||||
|
||||
The `extensions.config.json` file is validated against `extensions.schema.json`. The generator will error if you reference an unknown extension ID.
|
||||
|
||||
---
|
||||
|
||||
## Extension Developer Guide
|
||||
|
||||
### Creating a New Extension
|
||||
|
||||
**Option 1: Manual creation**
|
||||
|
||||
1. Create the extension directory: `extensions/<sector>/<name>/`
|
||||
2. Create `manifest.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "my-extension",
|
||||
"sector": "general",
|
||||
"exportName": "myExtension",
|
||||
"entryPoint": "@/extensions/general/my-extension",
|
||||
"workspace": "@/components/extensions/general/MyExtensionWorkspace",
|
||||
"requiredEnvVars": [],
|
||||
"optionalEnvVars": [],
|
||||
"npmDependencies": [],
|
||||
"definition": {
|
||||
"name": "My Extension",
|
||||
"category": "reports",
|
||||
"icon": "BarChart",
|
||||
"dataPattern": "core",
|
||||
"readsCoreTables": ["journal_entry_lines"],
|
||||
"description": "Short description",
|
||||
"longDescription": "Detailed description with features and use cases."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
3. Create `index.ts` exporting the Extension object:
|
||||
|
||||
```typescript
|
||||
import type { Extension } from '@/lib/extensions/types'
|
||||
|
||||
export const myExtension: Extension = {
|
||||
id: 'my-extension',
|
||||
name: 'My Extension',
|
||||
version: '1.0.0',
|
||||
sector: 'general',
|
||||
// ... surfaces, services, event handlers
|
||||
}
|
||||
```
|
||||
|
||||
4. Create the workspace component at the path specified in `manifest.workspace`
|
||||
5. Add the extension ID to `extensions.config.json`
|
||||
6. Run `npm run setup:extensions`
|
||||
|
||||
**Manifest fields:**
|
||||
|
||||
| Field | Required | Description |
|
||||
|-------|----------|-------------|
|
||||
| `id` | Yes | Unique extension ID (matches config and Extension.id) |
|
||||
| `sector` | Yes | Sector slug |
|
||||
| `exportName` | No | Named export from entryPoint (null = metadata-only extension) |
|
||||
| `entryPoint` | No | Import path for the Extension object (null = no runtime logic) |
|
||||
| `workspace` | No | Import path for the workspace React component (null = no UI) |
|
||||
| `requiredEnvVars` | Yes | Env vars that must be set for the extension to work |
|
||||
| `optionalEnvVars` | Yes | Env vars that enhance but are not required |
|
||||
| `npmDependencies` | Yes | npm packages the extension depends on |
|
||||
| `definition` | Yes | Marketplace metadata (name, category, icon, description, etc.) |
|
||||
|
||||
Extensions with `exportName: null` and `entryPoint: null` are metadata-only -- they appear in the marketplace and have a workspace UI but no server-side runtime logic (e.g. pure frontend calculators like Food Cost %).
|
||||
|
||||
### Services Pattern
|
||||
|
||||
Extensions can expose named services for cross-boundary calls. This avoids direct imports from extension code into core:
|
||||
|
||||
```typescript
|
||||
// Extension: ai-categorization/index.ts
|
||||
export const aiCategorizationExtension: Extension = {
|
||||
id: 'ai-categorization',
|
||||
name: 'AI Categorization',
|
||||
version: '1.0.0',
|
||||
services: {
|
||||
findSimilarTemplates: async (description: string, limit?: number) => {
|
||||
// ... embedding search logic
|
||||
return matches
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Core code calls the service via registry lookup:
|
||||
|
||||
```typescript
|
||||
// Core code: no direct import from extensions/
|
||||
const ext = extensionRegistry.get('ai-categorization')
|
||||
const results = await ext?.services?.findSimilarTemplates(description, 5)
|
||||
if (results) {
|
||||
// Use results
|
||||
}
|
||||
// Gracefully degrades if extension is not loaded
|
||||
```
|
||||
|
||||
This pattern is used for:
|
||||
- `ai-categorization` providing template embedding search to core booking suggestions
|
||||
- Any extension that needs to provide functionality callable by core without a direct dependency
|
||||
|
||||
### Event Bus Usage
|
||||
|
||||
Extensions subscribe to events emitted by core. Handlers run concurrently via `Promise.allSettled` -- a failing handler never crashes the emitter.
|
||||
|
||||
```typescript
|
||||
export const myExtension: Extension = {
|
||||
id: 'my-extension',
|
||||
// ...
|
||||
eventHandlers: [
|
||||
{
|
||||
eventType: 'transaction.categorized',
|
||||
handler: async (payload, ctx) => {
|
||||
// React to categorized transactions
|
||||
// ctx provides supabase, userId, settings, storage, log
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
Events are one-way: core services emit, extensions subscribe. Extensions should never emit events back to core. If an extension is not compiled in (not in `extensions.config.json`), its handlers are never registered.
|
||||
|
||||
### Workspace Components
|
||||
|
||||
Workspace components are React components rendered at `/e/{sector}/{slug}`. They receive `{ userId: string }` as props and are lazy-loaded via `next/dynamic`.
|
||||
|
||||
The workspace path is declared in `manifest.json` under the `workspace` field. The generator creates a dynamic import map in `_generated/workspace-map.tsx`.
|
||||
|
||||
All workspace components should use the `ExtensionWorkspaceShell` wrapper for consistent layout (header, breadcrumbs, settings link).
|
||||
|
||||
### Email Service Interface Pattern
|
||||
|
||||
The email extension demonstrates how to make a core capability optional:
|
||||
|
||||
1. **Core defines the interface** (`lib/email/service.ts`):
|
||||
- `EmailService` interface with `sendEmail()` and `isConfigured()`
|
||||
- `NoopEmailService` as default (returns `{ success: false }`)
|
||||
- `getEmailService()` getter and `registerEmailService()` setter
|
||||
|
||||
2. **Extension registers the implementation** (`extensions/general/email/index.ts`):
|
||||
- Imports `registerEmailService` from core
|
||||
- Creates `ResendEmailService` and registers it at load time
|
||||
|
||||
3. **Core callers use the getter** -- never import from the extension:
|
||||
```typescript
|
||||
const emailService = getEmailService()
|
||||
if (emailService.isConfigured()) {
|
||||
await emailService.sendEmail({ to, subject, html })
|
||||
}
|
||||
```
|
||||
|
||||
This pattern can be reused for any capability that should degrade gracefully when its extension is not loaded.
|
||||
|
||||
---
|
||||
|
||||
## Summary
|
||||
|
||||
**The app** is a Swedish accounting platform.
|
||||
|
||||
**Core functionality** is the standard accounting system: bookkeeping, invoicing, reports, tax (SRU, NE-bilaga), bank reconciliation. Every user gets this. Core compiles and runs with zero extensions.
|
||||
|
||||
**Extensions** are everything beyond core accounting. They come in three kinds:
|
||||
- **General extensions** (receipt-ocr, ai-categorization, email, etc.) -- useful for any business, not sector-specific
|
||||
- **Sector extensions** (food cost %, earnings per liter, etc.) -- tied to a specific market sector
|
||||
- **Export extensions** (EU Sales List, Intrastat, etc.) -- for businesses with international trade
|
||||
|
||||
All extensions live in the same system, appear in the same marketplace, and show up in the sidebar when they have a workspace + quickAction. All compiled extensions are active for all users -- the operator chooses which to include in `extensions.config.json` at build time. AI extensions additionally require per-user consent before making API calls.
|
||||
|
||||
Extensions are read-only with respect to the core accounting system. They can be fed accounting data, they can accept manual user input, but they never write back to the bookkeeping. They can expose services to core via the registry lookup pattern, and they can register API routes that are dispatched by the catch-all handler.
|
||||
@@ -0,0 +1,386 @@
|
||||
# Self-Hosting Accounted
|
||||
|
||||
This guide walks you through deploying Accounted on your own infrastructure using Docker.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Docker and Docker Compose v2+
|
||||
- A Supabase project (free tier works: create one at [supabase.com](https://supabase.com))
|
||||
|
||||
## 1. Create a Supabase Project
|
||||
|
||||
1. Go to [supabase.com](https://supabase.com) and create a new project.
|
||||
2. Note these values from **Settings > API**:
|
||||
- `Project URL` (e.g., `https://abcdefgh.supabase.co`)
|
||||
- `anon` public key
|
||||
- `service_role` secret key
|
||||
|
||||
## 2. Configure Supabase Auth
|
||||
|
||||
In the Supabase dashboard under **Authentication > URL Configuration**:
|
||||
|
||||
1. Set **Site URL** to your deployment URL (e.g., `https://gnubok.example.com`).
|
||||
2. Add `https://gnubok.example.com/auth/callback` to the **Redirect URLs** allowlist.
|
||||
|
||||
Accounted uses email + password authentication with magic link as a fallback. The default Supabase email auth settings work out of the box. For production, configure a custom SMTP provider under **Authentication > SMTP Settings** to avoid Supabase's built-in rate limits.
|
||||
|
||||
MFA (two-factor authentication via TOTP) is **not enforced** for self-hosted deployments: the Docker image sets `NEXT_PUBLIC_SELF_HOSTED=true` by default, which disables MFA enforcement. Users can still optionally enable 2FA in Settings > Säkerhet if they wish.
|
||||
|
||||
## 3. Apply Database Migrations
|
||||
|
||||
The `supabase/migrations/` directory contains the ordered SQL files that set up the full schema, including tables, RLS policies, triggers, and functions.
|
||||
|
||||
**Option A: Supabase CLI (recommended):**
|
||||
|
||||
```bash
|
||||
# Install the Supabase CLI
|
||||
npm install -g supabase
|
||||
|
||||
# Link to your project
|
||||
supabase link --project-ref <your-project-ref>
|
||||
|
||||
# Push all migrations
|
||||
supabase db push
|
||||
```
|
||||
|
||||
**Option B: SQL Editor:**
|
||||
|
||||
Run each file in `supabase/migrations/` in order in the Supabase SQL Editor. They must be applied sequentially: later migrations depend on earlier ones.
|
||||
|
||||
### PostgreSQL Extensions
|
||||
|
||||
The migrations automatically enable these extensions:
|
||||
|
||||
| Extension | Migration | Purpose |
|
||||
|-----------|-----------|---------|
|
||||
| `uuid-ossp` | 001 | UUID generation |
|
||||
| `vector` (pgvector) | 033 | AI embedding storage (for AI extensions) |
|
||||
| `btree_gist` | 042 | Fiscal period overlap prevention |
|
||||
| `pg_cron` | 048 | In-database scheduled jobs |
|
||||
|
||||
These are all available on Supabase hosted. `pg_cron` requires a paid plan: if you are on the free tier, migration 048 will fail. You can safely skip it; the cron sidecar container handles the equivalent job via HTTP instead.
|
||||
|
||||
## 4. Configure Environment
|
||||
|
||||
**Option A: Setup script (recommended):**
|
||||
|
||||
```bash
|
||||
git clone https://github.com/erp-mafia/gnubok.git
|
||||
cd Accounted
|
||||
./setup.sh
|
||||
```
|
||||
|
||||
The script checks prerequisites, prompts for your Supabase credentials, auto-generates `CRON_SECRET`, and writes everything to `.env`.
|
||||
|
||||
**Option B: Manual:**
|
||||
|
||||
```bash
|
||||
git clone https://github.com/erp-mafia/gnubok.git
|
||||
cd Accounted
|
||||
cp .env.docker.example .env
|
||||
```
|
||||
|
||||
Edit `.env` with your values:
|
||||
|
||||
```bash
|
||||
# ─── Required ───
|
||||
NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key
|
||||
SUPABASE_SERVICE_ROLE_KEY=your-service-role-key
|
||||
NEXT_PUBLIC_APP_URL=https://your-domain.com
|
||||
CRON_SECRET=<generate with: openssl rand -hex 32>
|
||||
```
|
||||
|
||||
`NEXT_PUBLIC_APP_URL` must match your public-facing URL. It is used in invoice reminder emails, calendar feed links, and PSD2 callbacks. If left as a placeholder, links will be broken.
|
||||
|
||||
## 5. Start the Application
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
This starts two containers:
|
||||
|
||||
| Container | Purpose |
|
||||
|-----------|---------|
|
||||
| `app` | Next.js application (`ghcr.io/erp-mafia/gnubok:latest`) |
|
||||
| `cron` | Scheduled jobs via [supercronic](https://github.com/aptible/supercronic) |
|
||||
|
||||
The cron container waits for the app health check to pass before starting.
|
||||
|
||||
Verify the deployment:
|
||||
|
||||
```bash
|
||||
curl http://localhost:3000/api/health
|
||||
# {"status":"healthy","timestamp":"...","version":"1.0.0"}
|
||||
```
|
||||
|
||||
> **Note:** The health check queries the database, so migrations must be applied before it returns healthy.
|
||||
|
||||
### Building from Source
|
||||
|
||||
To build the Docker image locally instead of pulling from GHCR:
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.yml -f docker-compose.build.yml up --build
|
||||
```
|
||||
|
||||
The locally-built image runs **unprivileged** (`USER nextjs`): the entrypoint
|
||||
populates the `.next`/`public` tmpfs mounts and substitutes the `NEXT_PUBLIC_*`
|
||||
placeholders as the `nextjs` user, so the container needs no Linux capabilities
|
||||
and runs as-is under the hardened compose defaults (`cap_drop: ALL`,
|
||||
`read_only: true`).
|
||||
|
||||
### Custom Port
|
||||
|
||||
Set `PORT` in your `.env` or environment to change the host port (the container always listens on 3000 internally):
|
||||
|
||||
```bash
|
||||
PORT=8080 docker compose up -d
|
||||
```
|
||||
|
||||
## 6. First Login
|
||||
|
||||
1. Open your deployment URL in a browser.
|
||||
2. Click "Skapa konto" (Create account) and register with email + password.
|
||||
3. Check your email and click the confirmation link.
|
||||
4. Complete the 5-step onboarding wizard:
|
||||
- **Step 1**: Choose entity type (enskild firma or aktiebolag)
|
||||
- **Step 2**: Company name and org number
|
||||
- **Step 3**: Fiscal year, VAT registration, accounting method
|
||||
- **Step 4**: Preliminary tax amount (optional, skip if unsure)
|
||||
- **Step 5**: Bank details for invoices (optional)
|
||||
|
||||
There is no admin account or invite system: any email address can sign up. You can also use the magic link option on the login page if preferred.
|
||||
|
||||
## Scheduled Jobs
|
||||
|
||||
The cron sidecar runs these jobs automatically:
|
||||
|
||||
| Schedule (UTC) | Endpoint | Purpose |
|
||||
|----------------|----------|---------|
|
||||
| Daily 06:00 | `/api/deadlines/status/cron` | Update deadline statuses |
|
||||
| Daily 08:00 | `/api/invoices/reminders/cron` | Send overdue invoice reminders |
|
||||
| Yearly Jan 2 | `/api/tax-deadlines/cron` | Generate tax deadlines for the new year |
|
||||
| Sundays 03:00 | `/api/documents/verify/cron` | SHA-256 integrity check on document archive |
|
||||
|
||||
All cron endpoints are authenticated with `Authorization: Bearer <CRON_SECRET>`. The cron container calls the app over the internal Docker network (`http://app:3000`), so these endpoints are not exposed publicly.
|
||||
|
||||
Additionally, migration 048 schedules a `pg_cron` job inside the database that marks overdue supplier invoices daily at 06:00 UTC.
|
||||
|
||||
## Optional Features
|
||||
|
||||
### AI Features
|
||||
|
||||
The self-hosted Docker image includes these AI-powered extensions: receipt OCR, AI categorization, AI chat, and invoice inbox. To enable them, add API keys to your `.env`:
|
||||
|
||||
```bash
|
||||
ANTHROPIC_API_KEY=sk-ant-... # Required for all AI features
|
||||
OPENAI_API_KEY=sk-... # Required for embedding-based features (categorization, chat)
|
||||
```
|
||||
|
||||
Each user must individually grant AI consent in the UI before AI features activate (per GDPR requirements).
|
||||
|
||||
**AI chat knowledge base** (optional): The AI chat can answer Swedish tax and accounting questions using a RAG knowledge base. To populate it, create `dev_docs/ai_knowledge_base/` with markdown files and run:
|
||||
|
||||
```bash
|
||||
npx tsx extensions/general/ai-chat/ingestion/ingest.ts
|
||||
```
|
||||
|
||||
**Booking template embeddings** (optional): For AI-powered transaction categorization suggestions, seed the template embeddings by calling:
|
||||
|
||||
```bash
|
||||
curl -X POST -H "Authorization: Bearer $CRON_SECRET" \
|
||||
https://your-domain.com/api/admin/seed-template-embeddings
|
||||
```
|
||||
|
||||
### Email (Invoice Sending and Reminders)
|
||||
|
||||
```bash
|
||||
RESEND_API_KEY=re_...
|
||||
RESEND_FROM_EMAIL=noreply@your-domain.com
|
||||
```
|
||||
|
||||
Requires a [Resend](https://resend.com) account with a verified sender domain. Without this, invoices can still be generated as PDFs but cannot be emailed.
|
||||
|
||||
### Push Notifications
|
||||
|
||||
```bash
|
||||
NEXT_PUBLIC_VAPID_PUBLIC_KEY=...
|
||||
VAPID_PRIVATE_KEY=...
|
||||
VAPID_SUBJECT=mailto:you@example.com
|
||||
```
|
||||
|
||||
Generate VAPID keys with `npx web-push generate-vapid-keys`. Push notifications require HTTPS.
|
||||
|
||||
### Error Tracking (Sentry)
|
||||
|
||||
```bash
|
||||
SENTRY_DSN=https://...@sentry.io/...
|
||||
NEXT_PUBLIC_SENTRY_DSN=https://...@sentry.io/...
|
||||
```
|
||||
|
||||
Sentry is disabled if these are not set. No errors are thrown.
|
||||
|
||||
## Storage Buckets
|
||||
|
||||
Migration 024 automatically creates the `documents` storage bucket (private, 50 MB limit, WORM, no update/delete).
|
||||
|
||||
If you enable the **receipt-ocr** extension, you must manually create a `receipts` storage bucket in the Supabase dashboard:
|
||||
|
||||
1. Go to **Storage** in the Supabase dashboard.
|
||||
2. Create a new bucket named `receipts`.
|
||||
3. Set it as **public** (receipt images are referenced by public URL).
|
||||
4. Set an appropriate file size limit (e.g., 10 MB).
|
||||
|
||||
## Updating
|
||||
|
||||
Pull the latest image and restart:
|
||||
|
||||
```bash
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
If a new release includes database migrations, apply them before restarting:
|
||||
|
||||
```bash
|
||||
supabase db push
|
||||
```
|
||||
|
||||
Check the [release notes](https://github.com/erp-mafia/gnubok/releases) for migration instructions.
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
```
|
||||
┌─────────────────────┐ ┌──────────────────┐
|
||||
│ Docker: app │ │ Docker: cron │
|
||||
│ (Next.js) │◄────│ (supercronic) │
|
||||
│ Port 3000 │ │ Bearer auth │
|
||||
└────────┬────────────┘ └──────────────────┘
|
||||
│
|
||||
│ HTTPS
|
||||
▼
|
||||
┌─────────────────────┐
|
||||
│ Supabase │
|
||||
│ - PostgreSQL + RLS │
|
||||
│ - Auth (email+pw) │
|
||||
│ - Storage (docs) │
|
||||
└─────────────────────┘
|
||||
```
|
||||
|
||||
The Next.js app is stateless: all data lives in Supabase. The Docker entrypoint injects your `NEXT_PUBLIC_*` environment variables into the pre-built JS bundles at container startup, so a single image works with any Supabase project.
|
||||
|
||||
## Fully Self-Hosted (No Supabase Cloud)
|
||||
|
||||
The setup above relies on a Supabase project at supabase.com. If you also want to host the database, auth, and storage yourself (to keep all data on-premises, avoid the SaaS dependency, or run air-gapped) you can pair Accounted with [Supabase's official Docker self-hosting stack](https://supabase.com/docs/guides/self-hosting/docker) instead.
|
||||
|
||||
This is a more involved path. You take responsibility for backups, TLS certificates, image upgrades, and Postgres operations. It is intended for operators already running Docker services who are comfortable with PostgreSQL.
|
||||
|
||||
### Architecture
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
user((User))
|
||||
proxy["Reverse proxy + TLS<br/>(Caddy / Traefik / nginx)"]
|
||||
user -- HTTPS --> proxy
|
||||
|
||||
subgraph dnet["shared Docker network"]
|
||||
subgraph app_stack["Accounted stack (this repo)"]
|
||||
app["app<br/>Next.js · :3000"]
|
||||
cron["cron<br/>supercronic"]
|
||||
cron -. Bearer CRON_SECRET .-> app
|
||||
end
|
||||
|
||||
subgraph supabase_stack["Supabase self-host stack"]
|
||||
kong["kong<br/>API gateway · :8000"]
|
||||
studio["studio<br/>dashboard"]
|
||||
db[("postgres<br/>+ pg_cron")]
|
||||
auth["gotrue"]
|
||||
rest["postgrest"]
|
||||
rt["realtime"]
|
||||
storage["storage-api<br/>(+ imgproxy)"]
|
||||
kong --- auth & rest & rt & storage & studio
|
||||
auth & rest & rt & storage --- db
|
||||
end
|
||||
|
||||
app -- "@supabase/supabase-js" --> kong
|
||||
end
|
||||
|
||||
proxy -- app.example.com --> app
|
||||
proxy -- supabase.example.com --> kong
|
||||
proxy -- studio.example.com --> studio
|
||||
```
|
||||
|
||||
### Setup outline
|
||||
|
||||
1. **Bring up Supabase** following [supabase.com/docs/guides/self-hosting/docker](https://supabase.com/docs/guides/self-hosting/docker). Generate your own `JWT_SECRET`, `ANON_KEY`, and `SERVICE_ROLE_KEY` (Supabase ships `sh utils/generate-keys.sh`). Pick a hostname for the API gateway (e.g. `supabase.example.com`) and point `SUPABASE_PUBLIC_URL` / `API_EXTERNAL_URL` at it.
|
||||
|
||||
2. **Apply the Accounted migrations** directly via `psql`: the Supabase CLI (`db push`) assumes a cloud project, so run the SQL files against the self-hosted database container:
|
||||
|
||||
```bash
|
||||
# From the repo root, stream each migration straight into the supabase-db
|
||||
# container: glob order is already sorted, and nothing is left behind on the
|
||||
# host or in the container.
|
||||
for f in supabase/migrations/*.sql; do
|
||||
echo "Applying $f..."
|
||||
docker exec -i supabase-db psql -v ON_ERROR_STOP=1 -U postgres -d postgres < "$f" || exit 1
|
||||
done
|
||||
```
|
||||
|
||||
3. **Configure `.env`** with your self-hosted endpoints (extract the keys from your Supabase `.env`):
|
||||
|
||||
```bash
|
||||
NEXT_PUBLIC_SUPABASE_URL=https://supabase.example.com
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY=<ANON_KEY from supabase .env>
|
||||
SUPABASE_SERVICE_ROLE_KEY=<SERVICE_ROLE_KEY from supabase .env>
|
||||
NEXT_PUBLIC_APP_URL=https://app.example.com
|
||||
CRON_SECRET=<openssl rand -hex 32>
|
||||
NEXT_PUBLIC_SELF_HOSTED=true
|
||||
```
|
||||
|
||||
4. **Allowlist the callback URLs** in GoTrue's redirect list (the Supabase stack's `.env`), then recreate the auth container so it picks up the change:
|
||||
|
||||
```bash
|
||||
ADDITIONAL_REDIRECT_URLS=https://app.example.com/auth/callback,https://app.example.com/api/auth/callback
|
||||
```
|
||||
```bash
|
||||
cd <your-supabase-dir> && docker compose up -d auth
|
||||
```
|
||||
|
||||
5. **Reverse proxy** in front of both hosts. The app container and the Supabase `kong` container must share an external Docker network so the proxy can route to them by name.
|
||||
|
||||
### What you give up vs. cloud Supabase
|
||||
|
||||
- **Backups** are entirely your responsibility: set up `pg_dump` (or a tool like restic) to off-host storage. As a portable, vendor-neutral *logical* backup on top of the raw dump, you can also export each fiscal period as a standard **SIE4** file via the API and archive it: any Swedish bookkeeping system can re-import it:
|
||||
|
||||
```bash
|
||||
curl -fsS -H "Authorization: Bearer <reports:read API key>" \
|
||||
"$NEXT_PUBLIC_APP_URL/api/v1/companies/<companyId>/reports/sie-export?period_id=<periodId>" \
|
||||
-o "export_<periodId>.se"
|
||||
```
|
||||
- **Storage**: the included `storage-api` defaults to the local-filesystem backend. For production durability, use the `docker-compose.s3.yml` overlay and point it at S3 / MinIO.
|
||||
- **SMTP**: no built-in mailer. Either set `ENABLE_EMAIL_AUTOCONFIRM=true` for dev/staging, or wire `SMTP_*` env vars in the Supabase stack to a provider (Resend, Postmark, etc.).
|
||||
- **Upgrades**: you sync the `supabase/postgres` image yourself; your data lives in the DB volume, so a Postgres image bump needs no migration re-run. When you pull a newer Accounted release, apply only the **new** migration files added since your last deploy (the SQL is not idempotent, so re-running already-applied migrations will error). Track which migrations you've applied, e.g. with a checksum/version table.
|
||||
|
||||
### Notes
|
||||
|
||||
- **`pg_cron`** is included in the `supabase/postgres` image, so the `pg_cron` migration succeeds (unlike on the Supabase free tier, see the standard self-hosting flow above).
|
||||
- **MFA**: as on the standard path, `NEXT_PUBLIC_SELF_HOSTED=true` disables enforcement; users may still enable TOTP voluntarily.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**Health check fails with "unhealthy":**
|
||||
Migrations have not been applied, or the Supabase credentials are wrong. Check that `NEXT_PUBLIC_SUPABASE_URL` and `SUPABASE_SERVICE_ROLE_KEY` are correct and that migrations have been pushed.
|
||||
|
||||
**Confirmation email not arriving:**
|
||||
Check the Supabase dashboard under **Authentication > Users** to verify the signup attempt was received. On the free tier, Supabase rate-limits emails to 4/hour. Configure custom SMTP under **Authentication > SMTP Settings** for production use.
|
||||
|
||||
**Auth callback redirects to error:**
|
||||
Ensure `https://your-domain.com/auth/callback` is in the Supabase **Redirect URLs** allowlist and that **Site URL** matches your `NEXT_PUBLIC_APP_URL`.
|
||||
|
||||
**`pg_cron` migration fails:**
|
||||
`pg_cron` requires a paid Supabase plan. On the free tier, you can safely comment out migration 048 or let it fail: the overdue supplier invoice check is non-critical and can be triggered manually.
|
||||
|
||||
**Container restarts in a loop:**
|
||||
Check logs with `docker compose logs app`. The app requires all five core env vars (`NEXT_PUBLIC_SUPABASE_URL`, `NEXT_PUBLIC_SUPABASE_ANON_KEY`, `SUPABASE_SERVICE_ROLE_KEY`, `NEXT_PUBLIC_APP_URL`, `CRON_SECRET`) and will crash on startup if any are missing.
|
||||
@@ -0,0 +1,186 @@
|
||||
# Whitelabel fork checklist
|
||||
|
||||
Accounted is whitelabel-friendly: every user-visible brand reference reads from a single `BrandingService` (`lib/branding/service.ts`). If you don't override anything, the app behaves exactly like upstream gnubok. To run your own brand on top of Accounted, fork the repo and override the values you care about.
|
||||
|
||||
## Quick start
|
||||
|
||||
```bash
|
||||
# 1. Fork erp-mafia/gnubok on GitHub → you/your-brand
|
||||
# 2. Clone and add upstream remote (one-time)
|
||||
git clone https://github.com/you/your-brand
|
||||
cd your-brand
|
||||
git remote add upstream https://github.com/erp-mafia/gnubok
|
||||
|
||||
# 3. Copy the example branding extension
|
||||
cp -r extensions/general/_example-branding extensions/general/your-brand
|
||||
# Edit extensions/general/your-brand/index.ts with your brand values
|
||||
|
||||
# 4. (Optional) Set env vars instead of / in addition to the extension. See "Env vars" below.
|
||||
|
||||
# 5. Enable the extension
|
||||
# Edit extensions.config.json and add "your-brand" to the array.
|
||||
|
||||
# 6. Run locally
|
||||
npm run setup:extensions
|
||||
npm run dev
|
||||
|
||||
# 7. Deploy to your hosting (Vercel, Docker, etc.)
|
||||
```
|
||||
|
||||
## Env vars
|
||||
|
||||
All branding can be set via env vars. Public ones use `NEXT_PUBLIC_BRANDING_*` (build-time inlined, available in client components). Server-only ones use `BRANDING_*`.
|
||||
|
||||
| Env var | Field | Default |
|
||||
|---|---|---|
|
||||
| `NEXT_PUBLIC_BRANDING_APP_NAME` | `appName` | `Accounted` |
|
||||
| `NEXT_PUBLIC_BRANDING_APP_DESCRIPTION` | `appDescription` | `Ekonomihantering` |
|
||||
| `BRANDING_LEGAL_ENTITY` | `legalEntity` | `Arcim` |
|
||||
| `BRANDING_SUPPORT_EMAIL` | `supportEmail` | `support@gnubok.se` |
|
||||
| `BRANDING_PRIVACY_EMAIL` | `privacyEmail` | `privacy@gnubok.se` |
|
||||
| `BRANDING_SECURITY_EMAIL` | `securityEmail` | `security@arcim.io` |
|
||||
| `NEXT_PUBLIC_BRANDING_AUTH_EMAIL_FROM` | `authEmailFrom`: From address Supabase Auth sends verification / reset emails from. Used to pre-populate the `from:` query on the "open in Gmail" button after signup. Set to whatever you configured in your Supabase Auth SMTP. | `noreply@gnubok.se` |
|
||||
| `NEXT_PUBLIC_APP_URL` | `appUrl` | `https://app.gnubok.se` |
|
||||
| `NEXT_PUBLIC_BRANDING_LOGO_PATH` | `logoPath` | `/gnubokiceon-removebg-preview.png` |
|
||||
| `NEXT_PUBLIC_BRANDING_FAVICON_PATH` | `faviconPath` | `/favicon.ico` |
|
||||
| `NEXT_PUBLIC_BRANDING_APPLE_ICON_PATH` | `appleTouchIconPath` | `/icons/icon-192.png` |
|
||||
| `NEXT_PUBLIC_BRANDING_PWA_ICON_BASE` | `pwaIconBasePath` | `/icons` |
|
||||
| `NEXT_PUBLIC_BRANDING_THEME_COLOR` | `themeColor` | `#304D83` |
|
||||
| `NEXT_PUBLIC_BRANDING_MANIFEST_THEME_COLOR` | `manifestThemeColor` | `#1a1a1a` |
|
||||
| `NEXT_PUBLIC_BRANDING_MANIFEST_BG_COLOR` | `manifestBackgroundColor` | `#ffffff` |
|
||||
| `NEXT_PUBLIC_BRANDING_HIDDEN_NAV` | `hiddenNavHrefs` (comma-separated, e.g. `/salary,/customers`) | `` (none hidden) |
|
||||
|
||||
Resolution order (last wins): **defaults → env vars → extension override**.
|
||||
|
||||
`NEXT_PUBLIC_*` env vars are inlined at build time. Changing them requires a fresh `npm run build` to propagate.
|
||||
|
||||
`NEXT_PUBLIC_BRANDING_APP_NAME` also stamps the service worker push-notification fallback title in `public/sw.js`. This happens at build time for Vercel/local builds (via `scripts/inject-public-branding.mjs`, run from `prebuild`) and at container start for Docker (via `docker-entrypoint.sh`).
|
||||
|
||||
### Email / Resend (when `email` or `invoice-inbox` extensions are enabled)
|
||||
|
||||
| Env var | Purpose |
|
||||
|---|---|
|
||||
| `RESEND_API_KEY` | Resend API key: required for both outbound mail and the inbox webhook |
|
||||
| `RESEND_FROM_EMAIL` | Default `From` address (e.g. `noreply@your-brand.se`); also used as the address you From-spoof through Resend |
|
||||
| `RESEND_INBOUND_DOMAIN` | Domain used to compose per-company invoice-inbox addresses: `{local-part}@{RESEND_INBOUND_DOMAIN}` |
|
||||
| `RESEND_INBOUND_WEBHOOK_SECRET` | Verifies the `/inbound` webhook signature from Resend |
|
||||
|
||||
## Things you MUST NOT change
|
||||
|
||||
These are stable contracts. Renaming them breaks existing data, sessions, or external clients (npm package consumers, MCP connectors, browser sessions, invite links). Leave them alone in your fork:
|
||||
|
||||
| Identifier | Where | Why |
|
||||
|---|---|---|
|
||||
| `gnubok-company-id` | cookie | Active company context: renaming breaks logged-in sessions |
|
||||
| `gnubok-invite-token` | cookie | Pre-auth invite token holding: renaming drops in-flight invites |
|
||||
| `gnubok_sk_` | API key prefix | All issued API keys; existing clients fail validation |
|
||||
| `gnubok_inv_` | invite token prefix | All sent invite links break |
|
||||
| `gnubok_*` | MCP tool names (`gnubok_list_invoices`, etc.) | Published MCP API: Claude clients have these cached |
|
||||
| `gnubok-mcp` | npm package name | Whitelabel users still install `npx gnubok-mcp`. Document `GNUBOK_URL=https://app.your-brand.se/api/extensions/ext/mcp-server/mcp` so they hit your endpoint |
|
||||
| `GNUBOK_API_KEY` | env var read by `gnubok-mcp` package | Same reason: npm consumer expects this name |
|
||||
|
||||
## What's outside this branding service
|
||||
|
||||
A few things that look brand-related but are configured elsewhere:
|
||||
|
||||
- **Supabase auth emails** (password reset, magic link): set in the Supabase dashboard for your project, not in code.
|
||||
- **Resend sending domain**: verify `noreply@your-brand.se` (or wherever) in Resend, set `RESEND_FROM_EMAIL`.
|
||||
- **DNS / domain**: point `app.your-brand.se` at your Vercel deployment.
|
||||
- **OAuth redirect allowlist for MCP**: `app/api/mcp-oauth/authorize/route.ts` lists `claude.ai/api/*`, `claude.com/api/*`, and localhost. Your domain is the OAuth issuer, not a redirect target: no change needed unless you're integrating with new MCP clients.
|
||||
- **iCal feed PRODID** (`lib/calendar/ics-generator.ts`): defaults to `erp-base.se`, callers may pass their domain.
|
||||
- **`NEXT_PUBLIC_APP_URL`**: used as the OAuth issuer. Set this to your domain (e.g. `https://app.your-brand.se`).
|
||||
- **Skatteverket submission identity**: `extensions/general/skatteverket/lib/api-client.ts` does not set a custom `User-Agent`; submissions go out with the Node/Vercel runtime default. If your deployment needs to identify itself to Skatteverket under a different brand, that's a future enhancement (env var + header), not something the current branding service covers.
|
||||
|
||||
## Staying in sync with upstream
|
||||
|
||||
Add this workflow at `.github/workflows/sync-upstream.yml` to your fork. It runs weekly and opens a PR with upstream changes:
|
||||
|
||||
```yaml
|
||||
name: Sync from upstream
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 3 * * 1' # Mondays 03:00 UTC
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
sync:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
issues: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Configure git
|
||||
run: |
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
|
||||
- name: Add upstream and fetch
|
||||
run: |
|
||||
git remote add upstream https://github.com/erp-mafia/gnubok
|
||||
git fetch upstream main
|
||||
|
||||
- name: Create sync branch and merge
|
||||
id: merge
|
||||
run: |
|
||||
BRANCH="sync/upstream-$(date +%Y-%m-%d)"
|
||||
git checkout -b "$BRANCH"
|
||||
if git merge --no-edit upstream/main; then
|
||||
echo "status=clean" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "status=conflict" >> "$GITHUB_OUTPUT"
|
||||
git merge --abort || true
|
||||
fi
|
||||
echo "branch=$BRANCH" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Push and open PR (clean merge)
|
||||
if: steps.merge.outputs.status == 'clean'
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
if git diff --quiet origin/main..HEAD; then
|
||||
echo "Up to date with upstream: nothing to do."
|
||||
exit 0
|
||||
fi
|
||||
git push origin "${{ steps.merge.outputs.branch }}"
|
||||
gh pr create \
|
||||
--base main \
|
||||
--head "${{ steps.merge.outputs.branch }}" \
|
||||
--title "Sync from upstream Accounted" \
|
||||
--body "Automated weekly sync from \`erp-mafia/gnubok@main\`."
|
||||
|
||||
- name: Report conflict
|
||||
if: steps.merge.outputs.status == 'conflict'
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
gh issue create \
|
||||
--title "Upstream sync conflict ($(date +%Y-%m-%d))" \
|
||||
--label sync-conflict \
|
||||
--body "Automated upstream merge hit a conflict. Resolve manually: \`git fetch upstream && git merge upstream/main\`."
|
||||
```
|
||||
|
||||
## Conflict avoidance
|
||||
|
||||
The fork-friendliness of this design depends on you keeping changes confined to your branding extension folder. Every file you edit in `lib/`, `app/`, or `components/` becomes a potential conflict on the next upstream merge. If you find yourself wanting to override something the branding service doesn't expose, prefer:
|
||||
|
||||
1. **Open an upstream issue**: the branding service is intentionally minimal; missing fields can be added.
|
||||
2. **PR a hook upstream**: extending the service or adding a registry pattern keeps your fork clean.
|
||||
|
||||
## Verifying your whitelabel
|
||||
|
||||
After deploying:
|
||||
|
||||
- [ ] Visit `/`: browser tab title shows your brand.
|
||||
- [ ] Visit `/login` and `/register`: your logo renders.
|
||||
- [ ] View source of `/manifest.webmanifest`: `name`, `short_name`, `theme_color` reflect your overrides.
|
||||
- [ ] Trigger an invite email: From line says `<your-brand> <noreply@...>`, body uses your name.
|
||||
- [ ] Visit `/dpa` and `/privacy`: legal entity and contact email are yours.
|
||||
- [ ] Open OAuth flow (`/api/mcp-oauth/authorize?...`) from a test MCP client: consent page references your brand.
|
||||
- [ ] Submit support form (Settings → Support): internal subject prefix is `[<your-brand> support]`.
|
||||
Reference in New Issue
Block a user