Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix(auth): route enterprise first-run users to onboarding instead of logout (#1471)
Brad Barbind61126f426d0
diff --git a/.ai/plans/2026-08-24-enterprise-first-run-onboarding-lockout.md b/.ai/plans/2026-08-24-enterprise-first-run-onboarding-lockout.mdnew file mode 100644index 0000000000..e59c922080--- /dev/null+++ b/.ai/plans/2026-08-24-enterprise-first-run-onboarding-lockout.md@@ -0,0 +1,202 @@+# Enterprise first-run onboarding lockout — implementation plan++**Spec:** .ai/specs/2026-08-24-enterprise-first-run-onboarding-lockout.md+**Research:** N/A (internal auth-flow bug, not an ERP-domain feature)+**Branch:** fix/enterprise-first-run-onboarding++## Progress+- [x] Task 1: Migration — `groups_for_user` returns an empty array, never NULL+ (`20260824205409_groups-for-user-empty-array.sql`; COALESCE over the aggregate,+ same signature/attributes. `generate:types` NOT needed — return type stays+ `TEXT[]`. Live psql assertion NOT run: no Carbon crbn dev DB is up in this+ worktree — port 54322 is an unrelated `byoc-console` Supabase, which lacks the+ `membership` table. Re-run the plan's psql check once `crbn up` provisions the+ Carbon dev DB.)+- [x] Task 2: ERP `/x` loader — guard now keys on `groups.error` (not `!groups.data`);+ returned `groups: groups.data ?? []`; `getUserGroups` normalizes `data ?? []`.+ Verified: `grep '!groups.data'` empty; `turbo typecheck --filter=erp` passes.+- [x] Task 3: MES — `throw` added to `destroyAuthSession`; no-company redirect →+ `path.to.setupRequired` (`/setup-required`, new `_public+/setup-required.tsx`+ linking to ERP onboarding). Verified: greps present; `turbo typecheck --filter=mes`+ passes.+- [ ] Task 4: Browser verification (`/test`) — enterprise first-run + regressions+ (BLOCKED: needs a running Carbon dev stack + a company-less confirmed user driven+ through the login door. The crbn stack is not up in this worktree.)++## Dependencies+- Tasks 1, 2, 3 are **independent** of each other (the RPC's TS type is `string[]`+ before and after — `RETURNS TEXT[]` is unchanged — so Task 2/3 don't need Task 1's+ `generate:types`).+- Task 4 depends on Tasks 1–3.++## Follow-ups (not in this plan)+- Spec AC "automated regression test" at the route-loader level needs an e2e /+ DB-integration harness that this repo does not have today (no Playwright config, no+ DB-hitting `*.test.ts`). Task 1 covers the RPC behavior with a SQL assertion and+ Task 4 covers the flow in the browser; a proper loader e2e is a separate infra task.++---++## Task 1: Migration — `groups_for_user` returns an empty array, never NULL++**Depends on:** none+**Files:**+- Create: `packages/database/supabase/migrations/{generated}_groups-for-user-empty-array.sql`+- Modify: `apps/erp/src/database.d.ts` / generated DB types — via `generate:types` (do not hand-edit)+- Copy from (precedent): `packages/database/supabase/migrations/20230123004632_groups.sql:293` (the current function body)++**Steps:**+1. Generate the migration file (never hand-pick a timestamp):+ ```bash+ pnpm db:migrate:new groups-for-user-empty-array+ ```+2. Put exactly this in the new file (same name / signature / `SECURITY DEFINER` /+ `search_path`; only the aggregate is wrapped in `COALESCE`):+ ```sql+ CREATE OR REPLACE FUNCTION groups_for_user(uid text) RETURNS TEXT[]+ LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = public AS $$+ DECLARE retval TEXT[];+ BEGIN+ WITH RECURSIVE "groupsForUser" AS (+ SELECT "groupId", "memberGroupId", "memberUserId" FROM "membership"+ WHERE "memberUserId" = uid::text+ UNION+ SELECT g1."groupId", g1."memberGroupId", g1."memberUserId" FROM "membership" g1+ INNER JOIN "groupsForUser" g2 ON g2."groupId" = g1."memberGroupId"+ )+ SELECT COALESCE(array_agg("groupId"), '{}') INTO retval FROM "groupsForUser";+ RETURN retval;+ END;+ $$;+ ```+3. Regenerate DB types (the always-after-migration step):+ ```bash+ pnpm run generate:types+ ```+4. Before finalizing, confirm no caller depends on the NULL return:+ ```bash+ grep -rn "groups_for_user" packages apps | grep -i "is null"+ # Expected: no matches (callers use `= ANY(groups_for_user(...))`, unaffected by NULL vs '{}')+ ```++**Verify:**+```bash+# Apply just this function to the local Supabase DB and check the empty case.+DBURL="$(grep -m1 '^SUPABASE_DB_URL' .env.local | cut -d= -f2- | tr -d '"')"; DBURL="${DBURL:-postgresql://postgres:[email protected]:54322/postgres}"+psql "$DBURL" -f "$(ls -t packages/database/supabase/migrations/*groups-for-user-empty-array.sql | head -1)"+psql "$DBURL" -At -c "SELECT groups_for_user('00000000-0000-0000-0000-000000000000') = '{}'::text[] AS ok"+# Expected: t+```+If the local DB isn't reachable at that URL, STOP and report — do not skip the check.++**Out of scope:** the `users_for_groups` function directly below it; any other RPC.++---++## Task 2: ERP `/x` loader — stop logging out no-company users; normalize groups++**Depends on:** none+**Files:**+- Modify: `apps/erp/app/routes/x+/_layout.tsx` — the line-200 guard + the returned `groups`+- Modify: `apps/erp/app/modules/users/users.server.ts` (`getUserGroups`, ~line 728) — normalize to `[]`+- Copy from (precedent): the existing `requiresOnboarding` branch already in `x+/_layout.tsx:~252` (no change to it — it becomes reachable)++**Steps:**+1. In `apps/erp/app/routes/x+/_layout.tsx`, change the guard (currently line 200):+ ```ts+ // before+ if (!claims || user.error || !user.data || !groups.data) {+ throw await destroyAuthSession(request);+ }+ // after — empty groups is a valid pre-onboarding state; only a real RPC error logs out+ if (!claims || user.error || !user.data || groups.error) {+ throw await destroyAuthSession(request);+ }+ ```+2. Wherever `groups.data` is read afterward (the returned `data({ session: { groups: ... } })`),+ use `groups.data ?? []` so downstream always gets an array.+3. In `apps/erp/app/modules/users/users.server.ts` `getUserGroups`, normalize the RPC result+ so `data` is `[]` (not `null`) on an empty set — belt-and-suspenders with Task 1+ (e.g. return `{ data: data ?? [], error }`). Do not change the function signature.+4. Leave the `requiresOnboarding` branch (`!company?.name || (CarbonEdition === Edition.Cloud && !stripeCustomer)`) exactly as-is — it now handles company-less users.++**Verify:**+```bash+grep -n "!groups.data" apps/erp/app/routes/x+/_layout.tsx+# Expected: no matches+pnpm exec turbo run typecheck --filter=erp+# Expected: erp typecheck passes (no errors)+```++**Out of scope:** reordering the loader / moving the onboarding redirect before the+company-scoped `Promise.all` (deferred per spec Q2(a)); the multi-company picker and+single-company auto-enter branches (unchanged).++---++## Task 3: MES — fix missing `throw`; "complete setup in ERP" screen for no-company++**Depends on:** none+**Files:**+- Modify: `apps/mes/app/utils/path.ts` — add `setupRequired`+- Create: `apps/mes/app/routes/setup-required.tsx` — the message screen+- Modify: `apps/mes/app/routes/x+/_layout.tsx` — add `throw` (line ~122); redirect no-company to setup screen (line ~127)+- Copy from (precedent): `apps/mes/app/routes/_public+/login.tsx` (full-page VStack/Heading/Button layout with the logo block)++**Steps:**+1. `apps/mes/app/utils/path.ts`: add a `setupRequired: "/setup-required"` entry next to+ the existing `onboarding: \`${ERP_URL}/onboarding\`` (line 167). Keep `onboarding` as-is.+2. Create `apps/mes/app/routes/setup-required.tsx`: a full-page screen copied from the+ layout shape of `_public+/login.tsx` (the centered logo + `VStack` + `Heading` + `Button`).+ Copy: a `Heading` "Finish setting up your account", body text "Your account isn't part+ of a company yet. Complete onboarding in the Carbon ERP to continue.", and a `Button`+ whose `onClick` does `window.location.href = path.to.onboarding` (= `${ERP_URL}/onboarding`).+ No loader company/group requirement — this route must render for an authenticated+ user with no company. If MES's route conventions force this under an authed layout that+ itself requires a company, STOP and report (place it where a company-less authed user+ can see it).+3. `apps/mes/app/routes/x+/_layout.tsx`:+ - Line ~122: `await destroyAuthSession(request);` → `throw await destroyAuthSession(request);`+ - Line ~127: `throw redirect(path.to.accountSettings);` → `throw redirect(path.to.setupRequired);`+ - Leave line ~208 (`if (!companyPlan && CarbonEdition === Edition.Cloud) throw redirect(path.to.onboarding)`) unchanged.++**Verify:**+```bash+grep -n "throw await destroyAuthSession" apps/mes/app/routes/x+/_layout.tsx+# Expected: 1 match (the fixed line)+grep -n "setupRequired" apps/mes/app/utils/path.ts apps/mes/app/routes/x+/_layout.tsx+# Expected: matches in both files+pnpm exec turbo run typecheck --filter=mes+# Expected: mes typecheck passes (no errors)+```++**Out of scope:** hosting the onboarding wizard in MES; any change to ERP onboarding.++---++## Task 4: Browser verification (`/test`) — enterprise first-run + regressions++**Depends on:** Tasks 1, 2, 3+**Files:** none (verification)++**Steps:**+1. Run `/test` with a DB that has **no company** (mimics enterprise first-run — do NOT use a+ `crbn up` DB that ran the dev bootstrap, since it seeds a company and hides the bug).+ Create a confirmed auth user with a `public."user"` row (`active = true`) and no company+ (admin `createUser` + confirm), then drive it through the **login door** — magic-link or+ OAuth `/callback` → `/x` — NOT signup: an unknown-email signup routes to `/verify →+ /onboarding` and would mask the guard entirely (see spec "signup vs login"). Then:+ - Log in as that user → **assert redirect to `/onboarding`**, not `/login`.+ - Complete the onboarding wizard → assert a `company` + `userToCompany` + `employee` ++ `membership` row now exist for the user; assert `/x` loads.+2. Regression checks in the same run:+ - Existing single-company user → `/x` loads directly.+ - Existing multi-company user → company picker.+ - Force a `claims`/`user` failure (or a `groups_for_user` RPC error) → still logged out.+ - Company-less user on **MES** → sees the "complete setup in ERP" screen with a working+ link to `${ERP_URL}/onboarding` (no redirect loop into account settings).++**Verify:** all assertions in Step 1–2 pass (spec Acceptance Criteria #1–#6). AC #1+(`groups_for_user` returns `'{}'`) is already proven by Task 1's SQL check.++**Out of scope:** building a Playwright/e2e harness (see Follow-ups).diff --git a/.ai/research/cross-currency-payment-settlement.md b/.ai/research/cross-currency-payment-settlement.mdnew file mode 100644index 0000000000..98ad7f156c--- /dev/null+++ b/.ai/research/cross-currency-payment-settlement.md@@ -0,0 +1,277 @@+# Cross-Currency Payment Settlement & Realized FX Gain/Loss++Research into how best-in-class ERP/accounting systems settle a payment whose currency+differs from the invoice's currency, and how realized foreign-exchange gain/loss is+recognized. Context: Carbon needs a domain-correct model for payments synced back from+external accounting systems (Rillet / Xero / QuickBooks) that may be denominated in a+currency different from the invoice they settle.++Date: 2026-08-24++---++## TL;DR — the canonical model++Name the three currencies precisely:++- **A = invoice (transaction/document) currency** — what the invoice's open balance is denominated in.+- **B = base (accounting/functional/home/reporting) currency** — what the ledger and AR/AP control account are valued in.+- **C = payment (cash/tender) currency** — what actually hit the bank.++The correct behavior, on which every mature system agrees:++1. **The open balance lives in currency A.** An invoice's remaining balance is tracked and+ reduced in the *invoice's own currency*. A payment reduces that balance by an amount+ **expressed in A**, never by the payment's face amount in C. This is the single most+ important invariant, and the exact place the Carbon bug lives (see §5).++2. **Realized FX gain/loss = the change in the *base-currency* value of the settled A-amount+ between invoice date and payment date.** It is `(applied_A × rate_A→B@payment) −+ (applied_A × rate_A→B@invoice)`. It has nothing to do with currency C directly; C only+ determines *how much A* the cash bought.++3. **AR/AP is relieved at the invoice-date base value**; the cash lands at the payment-date+ base value; the difference is the realized gain/loss, so debits = credits and the+ subledger stays tied to the GL.++4. **Third-currency (C ≠ A and C ≠ B) is the hard case.** Only heavyweight ERPs (SAP,+ Dynamics 365 F&O) support it directly, via an explicit **cross-rate** (A↔C) so the system+ never has to guess a double conversion. NetSuite, QuickBooks Online, and Xero **disallow**+ payment-currency ≠ invoice-currency and force a workaround.++---++## 1. The standard model for settling a foreign-currency invoice++### Determining the amount applied (in which currency)++The applied amount is resolved **in the invoice currency A**. The receivable is a monetary+item denominated in A; the payment application reduces the A-denominated open balance.++- If the payment is received in **A** (C = A), the applied A-amount is just the cash amount.+- If the payment is received in **B or a third currency C**, the cash must be **converted into+ A** (using the A↔C rate at settlement) to know how much of the A-denominated balance it+ clears. Systems that support this (Dynamics, SAP) call the A↔C rate the **cross rate** and+ require the user (or the sync) to supply it. Microsoft is explicit: "the settlement of+ remaining invoice amounts will be done using the currency and exchange rates of the original+ invoice to ensure that no gain or loss is incurred" on the *A-side* of the split+ (Microsoft Learn, currency revaluation for AP/AR).++Only after the cash is expressed in A do you know whether the invoice is fully or partially+settled. The FX movement is a *separate* line, not part of the applied amount.++### Computing realized FX gain/loss++Realized FX is the difference between the invoice's booked base value and the cash's base+value, **for the portion settled**:++```+booked_base = applied_A × rate(A→B)@invoiceDate // what AR was carried at+settled_base = applied_A × rate(A→B)@paymentDate // what that A is worth now+realizedFX = settled_base − booked_base // >0 gain (AR), sign flips for AP+```++- CorporateFinanceInstitute / SoftLedger: the gain/loss is "the difference between the+ exchange rate on the invoice date (transaction date) and the payment date (settlement+ date)." SoftLedger's worked example: a 100 EUR invoice booked at 1.142173 → 114.22 USD;+ paid when the rate is 1.15494 → the extra USD needed produces a **$1.28 realized loss**+ (AP direction) purely from the rate move.+- Xero: "calculate[s] the realized foreign currency gain and loss by comparing the rate when+ the invoice was issued with the one when it was paid," shown at the bottom of the paid+ invoice.+- Dynamics 365 F&O: "Realized gains or losses … are calculated by converting to the+ accounting currency … using the exchange rates … as of the payment date."++### Relieving the AR/AP control account (staying tied out)++The subledger and GL stay tied because the settlement journal always relieves AR/AP at its+**carried (invoice-date) base value**, routes the FX delta to a P&L account, and lands cash+at its own base value. Canonical AR settlement (customer receipt), values in base B:++```+Dr Cash/Bank settled_base (cash's B value at payment date)+Cr Accounts Receivable booked_base (relieves AR at invoice-date value)+Dr/Cr Realized FX Gain/Loss (P&L) realizedFX (balancing plug)+```++For a gain, `Cr Realized FX Gain`; for a loss, `Dr Realized FX Loss`. SoftLedger describes+exactly this: "an additional journal entry between the … Realized Gain/Loss Account and the+AR Account … to adjust the balance to the settlement amount given the exchange rate at the+time of settlement." SAP S/4HANA posts the realized difference **only when the open item is+cleared**, automatically to the configured realized-gain / realized-loss GL accounts+(assignable per Sales/Purchasing/General).++Key consequence: AR is relieved by exactly the amount it was booked at, so the AR subledger's+open-item detail and the GL control-account balance never drift — the FX movement is+absorbed by the P&L account, not smeared into AR.++---++## 2. Same-currency-as-invoice vs third-currency payments++**Do systems even allow C ≠ A?** Mostly no.++- **NetSuite:** Does **not** support applying a payment in one currency to an invoice in+ another currency — "the system's inability to perform double currency conversion on a+ single transaction. Each transaction supports only one exchange rate field." The documented+ workaround is a two-step *cash receipt → bank deposit* through **Undeposited Funds**, where+ the currency boundary is crossed at the deposit step, not the application step (Prolecto,+ jCurve, Concentrus).+- **QuickBooks Online:** A customer payment must be in the **invoice's currency**. When cash+ arrives in a different currency (e.g., home currency against a foreign invoice), the+ documented pattern is a "dummy"/clearing bank account and a manual home-currency adjustment+ — QBO applies in A and you reconcile the C-side separately (Intuit community threads).+- **Xero:** Payment is recorded against the invoice **in the invoice's currency**; if the+ actual bank account is a different currency, you route through a clearing/transfer and the+ realized FX crystallizes on the conversion leg. Xero does not let you type a foreign face+ amount directly onto a differently-denominated invoice.+- **SAP S/4HANA and Dynamics 365 F&O:** **Do** support true third-currency settlement.+ Dynamics exposes a **Cross rate** field used precisely "when the payment line and the+ invoice line use different currencies **and neither currency is the accounting currency**."+ Their example: accounting = USD, invoice = CAD, payment = EUR; the cross rate translates+ **directly between CAD and EUR** rather than triangulating through USD. This is the+ reference design for third-currency settlement.++**How common is third-currency settlement?** Rare in practice and generally discouraged. The+standard advice (echoed across NetSuite/Xero/QBO guidance) is to **have the customer pay in+the invoice currency**, or treat an off-currency remittance as a prepayment/credit and+re-apply. Real third-currency settlement is a heavy-ERP feature, not a small-business one.++**How disallowing systems behave:** they don't silently auto-convert onto the invoice.+They either (a) **reject** the mismatch, (b) require the payment to be **re-denominated into+A first** (record in A, reconcile the bank in C separately via a clearing account), or (c)+force a **manual FX/clearing entry**. None of them apply the C face amount to the A balance.++---++## 3. Realized vs unrealized FX at settlement++- **At settlement, it is always REALIZED.** IAS 21 (¶28): "exchange differences arising on+ the **settlement** of monetary items … shall be recognised in profit or loss in the period+ in which they arise." ASC 830 is materially identical for transaction gains/losses on+ monetary items. Settling an invoice is the textbook realization event.+- **Unrealized** FX only applies to *open* (unsettled) monetary balances re-translated at a+ period-end/closing rate — a balance-sheet revaluation that reverses next period. It is the+ month-end revaluation job, **not** the payment path.+- **Where it posts:** a dedicated **Realized FX Gain/Loss** P&L account (income-statement).+ SAP lets you configure separate realized-gain and realized-loss accounts and split them by+ process; Dynamics posts to the legal entity's configured gain/loss account; SoftLedger/Xero+ post to a "Realized Currency Gain/Loss" account. Keep realized (P&L, on settlement) and+ unrealized (revaluation, reverses) as **distinct accounts**.++Note on already-revalued items (SAP behavior, worth mirroring conceptually): if the open item+was revalued at a prior period end, clearing first **reverses the unrealized revaluation**+correction, then books the **realized** difference against the original invoice-date rate — so+you never double-count. For a v1 without period-end revaluation, this reduces to the simple+invoice-date-vs-payment-date computation.++---++## 4. Rounding / residual handling++Two distinct rounding concerns:++1. **Round realized FX to the base currency's precision.** The gain/loss amount is a+ base-currency (B) money value → round to B's decimal places at the point it's booked+ (SoftLedger: "rounds to the reporting currency's precision"). Carbon already has the right+ primitives for this (settlement values rounded at `currency.decimalPlaces`, internal GL+ lines at scale 5 — see `numeric-precision.md`). The realized-FX line is a settlement+ value.++2. **Don't strand an invoice as "partially paid" over FX dust.** The failure mode: convert+ C→A, get an A-amount a cent or two short of the open balance, and leave the invoice open by+ $0.01–0.02 that is *purely* a conversion-rounding artifact. Mature systems avoid this by:+ - **Tracking the open balance in A and settling the A-side exactly**, letting the entire+ rate movement fall into the FX gain/loss line rather than into a residual A balance+ (Microsoft: remaining amounts settled "using the currency and exchange rates of the+ original invoice … [so] no gain or loss is incurred" on the A remainder).+ - A **residual write-off threshold** / "auto-write-off small differences" so a sub-threshold+ remainder is cleared to a small-difference (or the FX) account and the invoice flips to+ fully paid (Oracle "Residual Balance Threshold"; SAP tolerance groups; QBO minor-charge+ write-off). Carbon already ships this idea as `INVOICE_DUST_THRESHOLD = 0.01` and+ post-payment's `0.0001` unapplied-dust band (`invoicing.models.ts`, per+ `numeric-precision.md`).+ - **Snap-to-zero:** if the intended settlement is "pay in full," clear the *entire*+ remaining A balance and let FX absorb the delta, rather than deriving the A-amount from+ the C cash and discovering a residual.++The rule of thumb: **rounding lives on the FX/write-off line, never on the AR open balance.**++---++## 5. Common pitfalls / what NOT to do++1. **Applying the payment's face amount (in C) directly against an A-denominated balance.**+ THE bug being fixed. Paying "500 USD" against a "500 EUR" invoice and calling it settled+ treats 1 USD = 1 EUR, corrupting the open balance and *silently swallowing the entire FX+ movement* into a wrong applied amount. The C amount must be converted to A (via the A↔C+ settlement rate / cross rate) **before** it touches the open balance.++2. **Skipping the realized FX line entirely.** If you relieve AR at the payment-date value+ instead of the invoice-date value (or land cash at the invoice-date value), the journal+ still "balances" but the FX gain/loss is buried in AR or cash and the subledger drifts from+ the GL. AR must be relieved at its **carried** value; the plug is realized FX.++3. **Triangulating through base without a cross-rate when C ≠ A ≠ B.** Converting C→B→A using+ two independently-sourced rates introduces a phantom gain/loss from rate inconsistency.+ Dynamics' cross-rate exists precisely to translate A↔C **directly**. If Carbon must support+ third-currency, carry an explicit A↔C rate from the source system rather than deriving it.++4. **Treating settlement FX as unrealized (or revaluing instead of realizing).** Settlement is+ a realization event → P&L now, not a reversing balance-sheet entry.++5. **Deriving the applied A-amount from the cash and then discovering a residual** — instead of+ settling the intended A balance and letting FX/dust absorb the remainder — leaves invoices+ perpetually "almost paid" (see §4).++6. **Reusing the unrealized-FX (revaluation) account for realized settlement gains/losses.**+ They must be separable for reporting; mixing them makes the revaluation reversal double-count.++---++## Practical recommendation for Carbon v1 vs defer++Given the sync context (payments arriving from Rillet/Xero/QuickBooks), and that those three+sources **already restrict** payment currency to the invoice currency:++**v1 (support):**+- **C = A (payment in invoice currency), base = B.** The overwhelmingly common case and the+ only one QBO/Xero even emit. Convert nothing on the A-side; compute realized FX from+ `rate(A→B)@invoice` vs `rate(A→B)@payment`; relieve AR at invoice-date base; post the delta+ to a dedicated **Realized FX Gain/Loss** P&L account; round FX to B's decimals; clear+ sub-threshold A residual via the existing dust threshold.+- **C = B (payment in base currency against a foreign invoice).** Also common. Requires the+ A↔B settlement rate to convert the base cash into an A-applied amount; same FX computation.+ This is what QBO's "invoice foreign, pay home" flow produces.+- **The invariant:** always reduce the open balance in **A**, always book realized FX as a+ separate P&L line, never apply a C face amount to an A balance.++**Defer (or reject with a clear error) unless a source actually emits it:**+- **True third-currency settlement (C ≠ A and C ≠ B).** Needs an explicit cross-rate (A↔C)+ carried on the synced payment, à la Dynamics/SAP. NetSuite/QBO/Xero don't produce this, so+ the sync is unlikely to see it. If a source ever sends C ∉ {A, B} without an A↔C rate,+ **reject/flag rather than guess a double conversion** — that's the pitfall in §5.3. Add it+ later behind an explicit cross-rate field if a source (e.g. a bank feed) demands it.++This keeps v1 correct for 100% of what the current integrations emit while structurally+refusing the corrupting shortcut.++---++## Sources++- [IAS 21 — The Effects of Changes in Foreign Exchange Rates (IFRS Community)](https://ifrscommunity.com/knowledge-base/ias-21-effects-of-changes-in-foreign-exchange-rates/) — settlement of monetary items → exchange differences in P&L.+- [How foreign currency translation is applied under IAS 21 and ASC 830 (Data Studios)](https://www.datastudios.org/post/how-foreign-currency-translation-is-applied-under-ias-21-and-asc-830)+- [Foreign Currency Transactions: Accounting Guide (Vintti)](https://www.vintti.com/blog/foreign-currency-transactions-accounting-and-reporting-practices) — realized vs unrealized at settlement date.+- [Foreign Exchange Gain/Loss — Overview, Recording, Example (Corporate Finance Institute)](https://corporatefinanceinstitute.com/resources/accounting/foreign-exchange-gain-loss/)+- [Realized Foreign Currency Gain/Loss from AP Bills and AR Invoices (SoftLedger)](https://softledger.com/support/en/articles/11940078-realized-foreign-currency-gain-loss-from-foreign-currency-ap-bills-and-ar-invoices) — exact journal entry + worked example (100 EUR, $1.28 loss).+- [Specify the cross rate — Dynamics 365 Finance (Microsoft Learn)](https://learn.microsoft.com/en-us/dynamics365/finance/accounts-payable/specify-cross-rate) — third-currency settlement via explicit A↔C cross rate; USD/CAD/EUR example.+- [Currency revaluation for AP and AR — Dynamics 365 Finance (Microsoft Learn)](https://learn.microsoft.com/en-us/dynamics365/finance/cash-bank-management/foreign-currency-revaluation-accounts-payable-accounts-receivable) — remaining amounts settled in original invoice currency/rate; realized posts on clearing.+- [Managing Exchange Rate Differences — SAP S/4HANA (SAP Learning)](https://learning.sap.com/courses/customizing-core-settings-in-financial-accounting-in-sap-s4hana/managing-exchange-rate-differences) — realized posted only when open item cleared; configured GL accounts per process.+- [How does SAP Business One handle Exchange Rate Differences (SAP Community)](https://community.sap.com/t5/enterprise-resource-planning-blog-posts-by-sap/how-does-sap-business-one-handle-exchange-rate-differences/ba-p/13461871)+- [Learn How To Accept Different Foreign Currency in NetSuite Cash Receipt Operations (Prolecto)](https://blog.prolecto.com/2017/12/09/learn-how-to-accept-different-foreign-currency-in-netsuite-cash-receipt-operations/) — NetSuite one-rate-per-transaction limitation + Undeposited Funds workaround.+- [Accept Customer Payment for Invoice in Different Currency (Concentrus)](https://blog.concentrus.com/accept-customer-payment-for-invoice-in-different-currency)+- [Record payments for foreign invoices/bills in different currencies (QuickBooks)](https://quickbooks.intuit.com/learn-support/en-za/help-article/multicurrency/receiving-making-payment-foreign-invoice-bill/L1weZLBmC_ZA_en_ZA)+- [Invoice foreign / pay home currency — how to receive payment (QuickBooks community)](https://quickbooks.intuit.com/learn-support/en-us/banking/invoice-in-foreign-currency-and-receive-payment-in-home-currency/00/599684)+- [Foreign currency gains and losses in Xero explained (Hedgeflows)](https://blog.hedgeflows.com/foreign-currency-gains-and-losses-in-xero-explained) — Xero realized FX = issue rate vs pay rate; partial-payment handling.+- [Residual Balance Write-Off Process — Oracle Fusion Financials](https://docs.oracle.com/en/cloud/saas/financials/25b/fafrm/residual-account-balance-write-off-process.html) — residual threshold auto-write-off.diff --git a/.ai/specs/2026-08-24-enterprise-first-run-onboarding-lockout.md b/.ai/specs/2026-08-24-enterprise-first-run-onboarding-lockout.mdnew file mode 100644index 0000000000..cfd07f5b8a--- /dev/null+++ b/.ai/specs/2026-08-24-enterprise-first-run-onboarding-lockout.md@@ -0,0 +1,227 @@+# Enterprise first-run onboarding lockout++> Status: draft+> Author: Brad Barbin+> Date: 2026-08-24++## TLDR++On a fresh **enterprise / self-hosted** deployment the first user authenticates+successfully but is immediately bounced back to `/login` instead of reaching+onboarding, so they can never create the first company through the UI. The cause+is the `/x` shell loader: `groups_for_user()` returns `NULL` (not an empty array)+for a user with zero `membership` rows, and the loader treats `!groups.data` as an+auth failure and destroys the session — before the onboarding redirect a few lines+later can run. Fix: make `groups_for_user` return `'{}'`, drop `!groups.data` from+the ERP logout guard so the existing `requiresOnboarding` redirect fires, and give+MES a "finish setup in ERP" screen (plus a missing `throw`).++## Problem Statement++**Symptom.** Enterprise/self-hosted first user (a confirmed `auth.users` row + a+`public."user"` row, e.g. seeded or invited, with **no** `company` / `employee` /+`userToCompany` / `membership` rows) logs in via magic link, lands briefly, then is+redirected to `/login?redirectTo=/x`. Onboarding is never reached; the deployment is+unusable.++Observed chain: `/magic-link → /callback → POST /callback.data 202 (session set) →+GET /x.data 202 → /login.data?redirectTo=/x`.++**Root cause.** `apps/erp/app/routes/x+/_layout.tsx:200`:++```ts+if (!claims || user.error || !user.data || !groups.data) {+ throw await destroyAuthSession(request);+}+```++`groups.data` comes from `getUserGroups` → the `groups_for_user(uid)` RPC+(`packages/database/supabase/migrations/20230123004632_groups.sql:293`), which does+`SELECT array_agg("groupId") INTO retval FROM "groupsForUser"`. `array_agg` over an+**empty** set returns **`NULL`**, so a user with no memberships gets+`groups.data === null` → `!groups.data` is true → the loader destroys the session.+This guard runs **before** the onboarding branch (`x+/_layout.tsx:~252`):++```ts+const requiresOnboarding = !company?.name || (CarbonEdition === Edition.Cloud && !stripeCustomer);+if (requiresOnboarding) { throw redirect(path.to.onboarding.root); }+```++`membership` rows are only created by the trigger on `employee` insert, which only+runs during company provisioning (`seed-company`). No company ⇒ no membership ⇒+`groups_for_user` = NULL ⇒ logout, and onboarding is unreachable.++**Why onboarding is reachable at all — signup vs login.** The wizard lives at+`/onboarding` (`onboarding+/_layout.tsx`), a route whose loader calls+`requirePermissions(request, {})`. With an empty permission set that helper+**early-exits with no role/groups check** (`auth.server.ts:351`), so a+company-less authenticated user *can* load `/onboarding` — but only by landing+there directly. Nothing sends them there from `/x`: the sole `/x → /onboarding`+redirect is the `requiresOnboarding` branch above, which sits **after** the+line-200 logout guard and is therefore dead code for a zero-company user.+Onboarding is reached exactly once, through the **signup** path — `login.tsx`+routes an unknown email (non-Enterprise) to `sendVerificationCode` → `/verify`,+and `verify.tsx` redirects the freshly-created user to `path.to.onboarding.root`+(`verify.tsx:127`). **Login** — magic-link or OAuth `/callback` — always lands on+`/x` (`authenticatedRoot`) instead. So whether a new user sees the wizard or a+logout depends entirely on which door they came through, and the guard makes the+login door a dead end.++**Why it never reproduces in local dev.** Two reasons compound. First, `crbn up`+runs the dev bootstrap `packages/database/src/datasets/bootstrap.ts` ("Creates the+auth user, the company, and every piece of reference data…"), which calls+`seedCompanyReferenceData` to insert a company + `userToCompany` + `employee` (→+`membership` rows), so the *bootstrapped* dev user always has a company and passes+the guard. Second — and this is what makes a genuinely *fresh* local user reach+onboarding — local runs the **community** edition, where an unknown email is+allowed to sign up: it flows `login → /verify → /onboarding`, never touching `/x`.+So locally onboarding is reached through the signup door, which has no groups+guard.++Enterprise closes both doors. Signups are disabled — `login.tsx` rejects an+unknown email with "User record not found" (the `else if (Edition.Enterprise)`+arm), so the signup → onboarding path does not exist. The first user must be+**DB-seeded**, which makes them a *known, active* account, so login takes the+magic-link branch → `/callback` → `/x` → the groups guard → logout. There is no+login-side path to onboarding for an enterprise first user.++**Confirmed reproduction.** A seeded user with `auth.users.confirmed_at` set,+`public."user".active = true`, and **zero** `company` / `userToCompany` /+`employee` / `membership` rows. Being confirmed + active is a *necessary*+condition for the symptom: it is what lets the session mint and reach `/x`, where+the guard then bounces it. The sole failing clause is `!groups.data` — `!claims`+passes because `get_claims(userId, null)` returns a truthy `{"role": null}` merged+with the `{}` `userPermission` row the `create_public_user` trigger wrote.++Consequence: **the fix is app-side** on the `/x` guard (make the existing+`requiresOnboarding` redirect reachable), not "run the dev bootstrap in prod"+(which would skip the onboarding UX a real customer should see). The **regression+test must create a company-less user and drive it through the login path** — a+signup would route to `/verify` and mask the bug — never via the dev bootstrap.++## Proposed Solution++Two-part, defense-in-depth: correct the RPC (root cause) and stop the ERP loader+from treating "authenticated, no company/groups yet" as an auth failure. MES gets a+clear terminal screen rather than a loop.++### Design Decisions++| Decision | Choice | Rationale |+|----------|--------|-----------|+| Where to fix the NULL groups (Q1) | **Fix the `groups_for_user` RPC** to `COALESCE(..., '{}')`, plus normalize `getUserGroups` to `data ?? []` as defense | A valid authenticated user with no memberships should yield `[]`, not NULL — the NULL is a genuine bug affecting every caller. RLS `= ANY(groups_for_user(...))` behaves identically for NULL vs `'{}'` (no match), so no policy changes. |+| ERP loader change shape (Q2) | **Minimal patch**: drop `\|\| !groups.data` from the line-200 logout guard (keep `!claims \|\| user.error \|\| !user.data`); the existing `requiresOnboarding` branch then redirects to `/onboarding` | `x+/_layout.tsx` is a hot, security-sensitive loader; smallest, lowest-risk diff. The extra company-scoped queries that run once with `companyId === undefined` are tolerated for v1 (they already run today; they return `{error}` rather than throw). A larger "resolve companies first, redirect early" restructure is deferred. |+| MES scope (Q3) | **Terminal "complete setup in ERP" screen** for a company-less MES user + fix the missing `throw` on its `destroyAuthSession`; onboarding stays ERP-only | MES doesn't host the onboarding wizard and gets its config from ERP; a company-less MES-first user is an unsupported edge, so a clear message beats a redirect loop into `accountSettings`. |+| Guard semantics for a real RPC failure | Log out on `groups.error` (genuine failure), not on empty `groups.data` | Preserves the "auth is broken → log out" signal without conflating it with the legitimate no-groups state. |+| Backward compatibility (heuristic 7) | `groups_for_user` is a shared `SECURITY DEFINER` RPC (STABLE surface) — change return value NULL→`'{}'` only | Semantically compatible; audited all callers (RLS `ANY`, the auth guard). No signature/behavior change beyond eliminating NULL. |++Heuristics 1–6 (new-table multi-tenancy, service shape, RLS coverage, permission+scoping, form pattern, module layout): **N/A** — this change adds no new tables,+services, forms, or routes.++## Data Model Changes++No schema/tables. One migration that `CREATE OR REPLACE`s the existing RPC so it+never returns NULL (new file — do not edit the historical migration):++```sql+-- packages/database/supabase/migrations/20260824000000_groups-for-user-empty-array.sql+CREATE OR REPLACE FUNCTION groups_for_user(uid text) RETURNS TEXT[]+ LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = public AS $$+ DECLARE retval TEXT[];+ BEGIN+ WITH RECURSIVE "groupsForUser" AS (+ SELECT "groupId", "memberGroupId", "memberUserId" FROM "membership"+ WHERE "memberUserId" = uid::text+ UNION+ SELECT g1."groupId", g1."memberGroupId", g1."memberUserId" FROM "membership" g1+ INNER JOIN "groupsForUser" g2 ON g2."groupId" = g1."memberGroupId"+ )+ SELECT COALESCE(array_agg("groupId"), '{}') INTO retval FROM "groupsForUser";+ RETURN retval;+ END;+$$;+```++Compatibility: keep the same name, signature, `SECURITY DEFINER`, and+`search_path`. Grep confirms callers use `= ANY(groups_for_user(...))` (NULL and+`'{}'` both yield no match) — no explicit `IS NULL` checks to migrate.++## API / Service Changes++**ERP — `apps/erp/app/routes/x+/_layout.tsx`**+- Line ~200 guard: change+ `if (!claims || user.error || !user.data || !groups.data)` →+ `if (!claims || user.error || !user.data || groups.error)`.+ (Drops the `!groups.data` clause per Q2(a); switches to `groups.error` so a real+ RPC failure still logs out.)+- Downstream usage of `groups.data` (the returned `data({ session: { groups } })`):+ read `groups.data ?? []` so an empty result is a well-formed array.+- No other reordering; the existing `requiresOnboarding` branch (`!company?.name`)+ now redirects company-less users to `path.to.onboarding.root`.++**Shared — `getUserGroups` (`apps/erp/app/modules/users/users.server.ts`)**+- Normalize the RPC result so `data` is `[]` (not `null`) on an empty set —+ belt-and-suspenders with the migration.++**MES — `apps/mes/app/routes/x+/_layout.tsx`**+- Line ~122: `await destroyAuthSession(request)` → `throw await destroyAuthSession(request)`+ (the destroy is currently computed but never acted on).+- Line ~125: replace the company-less `throw redirect(path.to.accountSettings)` with a+ render of the new "complete setup in ERP" screen (below), so a company-less MES+ user gets a clear terminal state instead of a potential loop.++## UI Changes++- **MES**: a small terminal screen shown to an authenticated user with no company —+ "Your account isn't set up yet. Finish onboarding in the ERP app," with a link to+ the ERP onboarding URL (derived the same way MES derives the ERP URL today). No+ onboarding wizard in MES.+- **ERP**: none — the existing onboarding wizard is simply now reachable.++## Acceptance Criteria++- [ ] Calling `groups_for_user('<user-with-no-memberships>')` returns `'{}'`, not `NULL`.+- [ ] Enterprise deploy, first user (confirmed, `public."user"` row, **no** company):+ magic-link login lands on `/onboarding` (not `/login`), and completing the wizard+ provisions a `company` + `userToCompany` + `employee` + `membership` rows.+- [ ] After onboarding, that user's next login goes straight to `/x` with no logout.+- [ ] A user whose auth genuinely fails (no `claims`, `user` lookup error, or a+ `groups_for_user` RPC error) is still logged out.+- [ ] Existing single-company user still loads `/x`; existing multi-company user still+ hits the company picker.+- [ ] A company-less user on **MES** sees the "complete setup in ERP" screen (with a+ working link to ERP onboarding), never a redirect loop.+- [ ] Automated regression test creates a company-less confirmed user (not via the dev+ bootstrap) and asserts the `/x` loader redirects to `/onboarding`, not `/login`.++## Risks++| Risk | Severity | Mitigation |+|------|----------|------------|+| Changing a shared `SECURITY DEFINER` RPC used in RLS | Med | Return value only (NULL→`'{}'`), semantically identical for `ANY(...)`; audit all callers; covered by acceptance test #1 |+| Loosening the `/x` logout guard could let a broken-auth user through | Med | Keep `!claims / user.error / !user.data / groups.error`; only the "empty groups" (valid pre-onboarding) case is allowed to proceed |+| Company-scoped queries run once with `companyId === undefined` (minimal-patch path) | Low | They already run today and return `{error}` (don't throw); onboarding redirect fires immediately after. Restructure deferred as follow-up |+| MES ERP-URL derivation wrong in some topologies | Low | Reuse the existing MES→ERP URL helper already used elsewhere in MES |++## Open Questions++> Resolved with the user before this spec was written (audit trail of the interview).++- [x] **Where to fix the NULL groups — shared RPC vs app-only?** — **Answer (a):** fix+ the `groups_for_user` RPC (`COALESCE(..., '{}')`), plus normalize `getUserGroups`+ as defense. The NULL is a real bug and RLS is unaffected.+- [x] **ERP loader: minimal patch or restructure?** — **Answer (a):** minimal patch —+ drop `!groups.data` from the guard (use `groups.error`); the existing+ `requiresOnboarding` branch handles the redirect. Restructure deferred.+- [x] **MES scope for a company-less user?** — **Answer (b):** terminal "complete setup+ in ERP" screen + fix the missing `throw`; onboarding stays ERP-only.++## Changelog++- 2026-08-24: Created (open questions resolved via interview before writing).+- 2026-08-24: Root cause validated against a live enterprise-shaped seed (confirmed ++ active user, zero company/membership rows; sole failing clause `!groups.data`).+ Expanded the reproduction analysis with the signup-vs-login routing distinction:+ onboarding is only ever reached via the signup door (`/verify → /onboarding`), which+ Enterprise disables, so a DB-seeded first user can only log in → `/x` → logout.diff --git a/apps/erp/app/modules/users/users.server.ts b/apps/erp/app/modules/users/users.server.tsindex 5adcf07c14..653da2d7ea 100644--- a/apps/erp/app/modules/users/users.server.ts+++ b/apps/erp/app/modules/users/users.server.ts@@ -729,7 +729,12 @@ export async function getUserGroups(client: SupabaseClient<Database>,userId: string) {- return client.rpc("groups_for_user", { uid: userId });+ // Normalize an empty result to [] (not null) — belt-and-suspenders with the+ // groups_for_user COALESCE migration, so a user with no memberships is a+ // well-formed empty array rather than a null the /x guard could mistake for+ // an auth failure.+ const result = await client.rpc("groups_for_user", { uid: userId });+ return { ...result, data: result.data ?? [] };}export async function getUserDefaults(diff --git a/apps/erp/app/routes/x+/_layout.tsx b/apps/erp/app/routes/x+/_layout.tsxindex 646e259800..becace6d3e 100644--- a/apps/erp/app/routes/x+/_layout.tsx+++ b/apps/erp/app/routes/x+/_layout.tsx@@ -198,7 +198,11 @@ export async function loader({ request }: LoaderFunctionArgs) {itarCertificationPromise]);- if (!claims || user.error || !user.data || !groups.data) {+ // Empty groups is a valid pre-onboarding state (a first-run user with no+ // company yet has zero memberships → groups is []), NOT an auth failure —+ // logging out here made the `requiresOnboarding` redirect below unreachable.+ // Only a genuine RPC error (groups.error) logs out.+ if (!claims || user.error || !user.data || groups.error) {throw await destroyAuthSession(request);}@@ -274,7 +278,7 @@ export async function loader({ request }: LoaderFunctionArgs) {customFields: customFields.data ?? [],defaults: defaults.data,integrations: integrations.data ?? [],- groups: groups.data,+ groups: groups.data ?? [],permissions: claims?.permissions,plan,role: claims?.role,diff --git a/apps/mes/app/routes/_public+/setup-required.tsx b/apps/mes/app/routes/_public+/setup-required.tsxnew file mode 100644index 0000000000..2438a5bf1c--- /dev/null+++ b/apps/mes/app/routes/_public+/setup-required.tsx@@ -0,0 +1,63 @@+import { CONTROLLED_ENVIRONMENT } from "@carbon/auth";+import { getAuthSession } from "@carbon/auth/session.server";+import { Button, Heading, VStack } from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import type { LoaderFunctionArgs, MetaFunction } from "react-router";+import { redirect } from "react-router";+import { path } from "~/utils/path";++export const meta: MetaFunction = () => {+ return [{ title: "Carbon | Finish setup" }];+};++// A terminal screen for an authenticated user who has no company yet — MES does+// not host the onboarding wizard, so it points them at ERP onboarding rather+// than looping them through an ERP `/x` route that also requires a company.+// Unauthenticated visitors go to login; company-less authed users see the+// message (this route is NOT under the `x+` company guard).+export async function loader({ request }: LoaderFunctionArgs) {+ const authSession = await getAuthSession(request);+ if (!authSession) {+ throw redirect(path.to.login);+ }+ return {};+}++export default function SetupRequiredRoute() {+ const { t } = useLingui();++ return (+ <>+ <div className="flex justify-center mb-8">+ <img+ src={CONTROLLED_ENVIRONMENT ? "/flag.png" : "/carbon-mark-light.svg"}+ alt={t`Carbon Logo`}+ className="w-24 dark:hidden"+ />+ <img+ src={CONTROLLED_ENVIRONMENT ? "/flag.png" : "/carbon-mark-dark.svg"}+ alt={t`Carbon Logo`}+ className="w-24 hidden dark:block"+ />+ </div>+ <div className="rounded-lg md:bg-card md:border md:border-border md:shadow-lg p-8 w-[380px]">+ <VStack spacing={4} className="items-center justify-center text-center">+ <Heading size="h3">+ <Trans>Finish setting up your account</Trans>+ </Heading>+ <p className="text-muted-foreground tracking-tight text-sm">+ <Trans>+ Your account isn't part of a company yet. Complete onboarding in+ the Carbon ERP to continue.+ </Trans>+ </p>+ <Button size="lg" className="w-full" asChild>+ <a href={path.to.onboarding}>+ <Trans>Go to onboarding</Trans>+ </a>+ </Button>+ </VStack>+ </div>+ </>+ );+}diff --git a/apps/mes/app/routes/x+/_layout.tsx b/apps/mes/app/routes/x+/_layout.tsxindex 96153f5c96..a728b3f3c1 100644--- a/apps/mes/app/routes/x+/_layout.tsx+++ b/apps/mes/app/routes/x+/_layout.tsx@@ -119,12 +119,17 @@ export async function loader({ request, context }: LoaderFunctionArgs) {]);if (user.error || !user.data) {- await destroyAuthSession(request);+ throw await destroyAuthSession(request);}const company = companies.data?.find((c) => c.companyId === companyId);if (!company) {- throw redirect(path.to.accountSettings);+ // A company-less authenticated user (e.g. an enterprise first-run user who+ // hasn't onboarded) has no MES to enter — MES doesn't host onboarding.+ // Send them to a terminal screen that links to ERP onboarding, not into+ // accountSettings (an ERP /x route that would itself bounce a no-company+ // user, i.e. a redirect loop).+ throw redirect(path.to.setupRequired);}// Get the location and console state from middleware contextdiff --git a/apps/mes/app/utils/path.ts b/apps/mes/app/utils/path.tsindex 6a590b1454..afb2d36211 100644--- a/apps/mes/app/utils/path.ts+++ b/apps/mes/app/utils/path.ts@@ -192,6 +192,7 @@ export const path = {return parentId ? `${basePath}?parentId=${parentId}` : basePath;},scrapReasons: `${api}/scrap-reasons`,+ setupRequired: "/setup-required",startOperation: (id: string) => generatePath(`${x}/start/${id}`),suggestion: `${x}/suggestion`,switchCompany: (companyId: string) =>diff --git a/packages/database/supabase/migrations/20260824205409_groups-for-user-empty-array.sql b/packages/database/supabase/migrations/20260824205409_groups-for-user-empty-array.sqlnew file mode 100644index 0000000000..f9ae89fda9--- /dev/null+++ b/packages/database/supabase/migrations/20260824205409_groups-for-user-empty-array.sql@@ -0,0 +1,24 @@+-- groups_for_user must never return NULL. `array_agg` over an empty set returns+-- NULL, so a valid authenticated user with zero memberships (an enterprise/+-- self-hosted first-run user, before onboarding creates their company) yielded+-- NULL, which the /x shell loader treated as an auth failure and logged out —+-- making onboarding unreachable. COALESCE to an empty array so "no groups" is a+-- well-formed result, not NULL. Same name / signature / SECURITY DEFINER /+-- search_path as 20230123004632_groups.sql; RLS `= ANY(groups_for_user(...))`+-- treats NULL and '{}' identically, so no policy is affected.+CREATE OR REPLACE FUNCTION groups_for_user(uid text) RETURNS TEXT[]+ LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = public+ AS $$+ DECLARE retval TEXT[];+ BEGIN+ WITH RECURSIVE "groupsForUser" AS (+ SELECT "groupId", "memberGroupId", "memberUserId" FROM "membership"+ WHERE "memberUserId" = uid::text+ UNION+ SELECT g1."groupId", g1."memberGroupId", g1."memberUserId" FROM "membership" g1+ INNER JOIN "groupsForUser" g2 ON g2."groupId" = g1."memberGroupId"+ ) SELECT COALESCE(array_agg("groupId"), '{}') INTO retval FROM "groupsForUser";++ RETURN retval;+ END;+$$;diff --git a/packages/locale/locales/de/mes.po b/packages/locale/locales/de/mes.poindex d36eec0e80..89e5bc624b 100644--- a/packages/locale/locales/de/mes.po+++ b/packages/locale/locales/de/mes.po@@ -515,6 +515,9 @@ msgstr "Beenden {0}"msgid "Finish Anyways"msgstr "Trotzdem beenden"+msgid "Finish setting up your account"+msgstr ""+msgid "Finish with material unpicked?"msgstr "Mit nicht gepicktem Material abschließen?"@@ -524,6 +527,9 @@ msgstr "Vergessen auszustempeln?"msgid "Go back to operation"msgstr "Zurück zur Operation"+msgid "Go to onboarding"+msgstr ""+msgid "How many were actually picked?"msgstr "Wie viele wurden tatsächlich gepickt?"@@ -1497,6 +1503,9 @@ msgstr "Sie haben sich um <0/> angemeldet. Sie können Ihre Abmeldungszeit untenmsgid "You've been clocked in for {hoursElapsed} hours. Did you forget to clock out?"msgstr "Sie sind seit {hoursElapsed} Stunden eingestempelt. Haben Sie vergessen auszustempeln?"+msgid "Your account isn't part of a company yet. Complete onboarding in the Carbon ERP to continue."+msgstr ""+msgid "Your organization requires an authenticator app. Set it up in Carbon, then come back here."msgstr "Ihre Organisation erfordert eine Authentifizierungs-App. Richten Sie sie in Carbon ein und kommen Sie dann hierher zurück."diff --git a/packages/locale/locales/en/mes.po b/packages/locale/locales/en/mes.poindex 135e0e31b1..2f51dcc6e2 100644--- a/packages/locale/locales/en/mes.po+++ b/packages/locale/locales/en/mes.po@@ -515,6 +515,9 @@ msgstr "Finish {0}"msgid "Finish Anyways"msgstr "Finish Anyways"+msgid "Finish setting up your account"+msgstr "Finish setting up your account"+msgid "Finish with material unpicked?"msgstr "Finish with material unpicked?"@@ -524,6 +527,9 @@ msgstr "Forgot to Clock Out?"msgid "Go back to operation"msgstr "Go back to operation"+msgid "Go to onboarding"+msgstr "Go to onboarding"+msgid "How many were actually picked?"msgstr "How many were actually picked?"@@ -1497,6 +1503,9 @@ msgstr "You clocked in at <0/>. You can edit your clock-out time below or acknowmsgid "You've been clocked in for {hoursElapsed} hours. Did you forget to clock out?"msgstr "You've been clocked in for {hoursElapsed} hours. Did you forget to clock out?"+msgid "Your account isn't part of a company yet. Complete onboarding in the Carbon ERP to continue."+msgstr "Your account isn't part of a company yet. Complete onboarding in the Carbon ERP to continue."+msgid "Your organization requires an authenticator app. Set it up in Carbon, then come back here."msgstr "Your organization requires an authenticator app. Set it up in Carbon, then come back here."diff --git a/packages/locale/locales/es/mes.po b/packages/locale/locales/es/mes.poindex 13b7cc0f99..a88b1e4563 100644--- a/packages/locale/locales/es/mes.po+++ b/packages/locale/locales/es/mes.po@@ -515,6 +515,9 @@ msgstr "Finalizar {0}"msgid "Finish Anyways"msgstr "Finalizar de todas formas"+msgid "Finish setting up your account"+msgstr ""+msgid "Finish with material unpicked?"msgstr "¿Finalizar con material sin recoger?"@@ -524,6 +527,9 @@ msgstr "¿Olvidó registrar la salida?"msgid "Go back to operation"msgstr "Volver a la operación"+msgid "Go to onboarding"+msgstr ""+msgid "How many were actually picked?"msgstr "¿Cuántos se recogieron realmente?"@@ -1497,6 +1503,9 @@ msgstr "Marcaste entrada a las <0/>. Puedes editar tu hora de salida a continuacmsgid "You've been clocked in for {hoursElapsed} hours. Did you forget to clock out?"msgstr "Ha estado registrado durante {hoursElapsed} horas. ¿Olvidó registrar la salida?"+msgid "Your account isn't part of a company yet. Complete onboarding in the Carbon ERP to continue."+msgstr ""+msgid "Your organization requires an authenticator app. Set it up in Carbon, then come back here."msgstr "Tu organización requiere una aplicación de autenticación. Configúrala en Carbon y luego vuelve aquí."diff --git a/packages/locale/locales/fr/mes.po b/packages/locale/locales/fr/mes.poindex 8bd4588524..ccc89d2130 100644--- a/packages/locale/locales/fr/mes.po+++ b/packages/locale/locales/fr/mes.po@@ -515,6 +515,9 @@ msgstr "Terminer {0}"msgid "Finish Anyways"msgstr "Terminer quand même"+msgid "Finish setting up your account"+msgstr ""+msgid "Finish with material unpicked?"msgstr "Terminer avec du matériel non prélevé?"@@ -524,6 +527,9 @@ msgstr "Oubli de pointer la sortie ?"msgid "Go back to operation"msgstr "Revenir à l'opération"+msgid "Go to onboarding"+msgstr ""+msgid "How many were actually picked?"msgstr "Combien ont réellement été prélevés ?"@@ -1497,6 +1503,9 @@ msgstr "Vous avez pointé à <0/>. Vous pouvez modifier votre heure de départ cmsgid "You've been clocked in for {hoursElapsed} hours. Did you forget to clock out?"msgstr "Vous êtes pointé depuis {hoursElapsed} heures. Avez-vous oublié de pointer la sortie ?"+msgid "Your account isn't part of a company yet. Complete onboarding in the Carbon ERP to continue."+msgstr ""+msgid "Your organization requires an authenticator app. Set it up in Carbon, then come back here."msgstr "Votre organisation nécessite une application d'authentification. Configurez-la dans Carbon, puis revenez ici."diff --git a/packages/locale/locales/hi/mes.po b/packages/locale/locales/hi/mes.poindex 5c0aaf8e53..df070e0b02 100644--- a/packages/locale/locales/hi/mes.po+++ b/packages/locale/locales/hi/mes.po@@ -515,6 +515,9 @@ msgstr "{0} को समाप्त करें"msgid "Finish Anyways"msgstr "वैसे भी समाप्त करें"+msgid "Finish setting up your account"+msgstr ""+msgid "Finish with material unpicked?"msgstr "सामग्री बिना चुने समाप्त करें?"@@ -524,6 +527,9 @@ msgstr "घड़ी से बाहर निकलना भूल गए?"msgid "Go back to operation"msgstr "ऑपरेशन पर वापस जाएं"+msgid "Go to onboarding"+msgstr ""+msgid "How many were actually picked?"msgstr "वास्तव में कितने चुने गए?"@@ -1497,6 +1503,9 @@ msgstr "आपने <0/> पर घड़ी शुरू की है। आmsgid "You've been clocked in for {hoursElapsed} hours. Did you forget to clock out?"msgstr "आप {hoursElapsed} घंटे के लिए क्लॉक इन हैं। क्या आप क्लॉक आउट करना भूल गए?"+msgid "Your account isn't part of a company yet. Complete onboarding in the Carbon ERP to continue."+msgstr ""+msgid "Your organization requires an authenticator app. Set it up in Carbon, then come back here."msgstr "आपके संगठन को एक ऑथेंटिकेटर ऐप की आवश्यकता है। इसे Carbon में सेट अप करें, फिर यहाँ वापस आएं।"diff --git a/packages/locale/locales/it/mes.po b/packages/locale/locales/it/mes.poindex 579a81f427..84e6d950f3 100644--- a/packages/locale/locales/it/mes.po+++ b/packages/locale/locales/it/mes.po@@ -515,6 +515,9 @@ msgstr "Termina {0}"msgid "Finish Anyways"msgstr "Termina comunque"+msgid "Finish setting up your account"+msgstr ""+msgid "Finish with material unpicked?"msgstr "Terminare con il materiale non prelevato?"@@ -524,6 +527,9 @@ msgstr "Hai dimenticato di timbrare l'uscita?"msgid "Go back to operation"msgstr "Torna all'operazione"+msgid "Go to onboarding"+msgstr ""+msgid "How many were actually picked?"msgstr "Quanti sono stati effettivamente prelevati?"@@ -1497,6 +1503,9 @@ msgstr "Ti sei connesso a <0/>. Puoi modificare l'orario di disconnessione di semsgid "You've been clocked in for {hoursElapsed} hours. Did you forget to clock out?"msgstr "Sei timbrato in ingresso da {hoursElapsed} ore. Hai dimenticato di timbrare l'uscita?"+msgid "Your account isn't part of a company yet. Complete onboarding in the Carbon ERP to continue."+msgstr ""+msgid "Your organization requires an authenticator app. Set it up in Carbon, then come back here."msgstr "La tua organizzazione richiede un'app di autenticazione. Configurala in Carbon, quindi torna qui."diff --git a/packages/locale/locales/ja/mes.po b/packages/locale/locales/ja/mes.poindex 5055d26efb..6271714bfc 100644--- a/packages/locale/locales/ja/mes.po+++ b/packages/locale/locales/ja/mes.po@@ -515,6 +515,9 @@ msgstr "完了 {0}"msgid "Finish Anyways"msgstr "とにかく完了"+msgid "Finish setting up your account"+msgstr ""+msgid "Finish with material unpicked?"msgstr "材料がピッキングされていない状態で終了しますか?"@@ -524,6 +527,9 @@ msgstr "退勤打刻を忘れましたか?"msgid "Go back to operation"msgstr "操作に戻る"+msgid "Go to onboarding"+msgstr ""+msgid "How many were actually picked?"msgstr "実際にはいくつ選ばれましたか?"@@ -1497,6 +1503,9 @@ msgstr "あなたは<0/>にクロックインしました。下記でクロッmsgid "You've been clocked in for {hoursElapsed} hours. Did you forget to clock out?"msgstr "{hoursElapsed} 時間出勤中です。退勤打刻を忘れていませんか?"+msgid "Your account isn't part of a company yet. Complete onboarding in the Carbon ERP to continue."+msgstr ""+msgid "Your organization requires an authenticator app. Set it up in Carbon, then come back here."msgstr "あなたの組織は認証器アプリが必要です。Carbonで設定してから、ここに戻ってください。"diff --git a/packages/locale/locales/ko/mes.po b/packages/locale/locales/ko/mes.poindex 3f7e0e2800..e5bd749060 100644--- a/packages/locale/locales/ko/mes.po+++ b/packages/locale/locales/ko/mes.po@@ -515,6 +515,9 @@ msgstr "{0} 완료"msgid "Finish Anyways"msgstr "그래도 완료"+msgid "Finish setting up your account"+msgstr ""+msgid "Finish with material unpicked?"msgstr "미선택 재료가 있는 상태로 완료하시겠습니까?"@@ -524,6 +527,9 @@ msgstr "퇴근 체크를 잊으셨나요?"msgid "Go back to operation"msgstr "공정작업으로 돌아가기"+msgid "Go to onboarding"+msgstr ""+msgid "How many were actually picked?"msgstr "실제로 몇 개를 피킹했습니까?"@@ -1497,6 +1503,9 @@ msgstr "<0/>에 근무를 시작했습니다. 아래에서 퇴근 시간을 편msgid "You've been clocked in for {hoursElapsed} hours. Did you forget to clock out?"msgstr "{hoursElapsed}시간 동안 출근 상태입니다. 퇴근 처리를 잊으셨나요?"+msgid "Your account isn't part of a company yet. Complete onboarding in the Carbon ERP to continue."+msgstr ""+msgid "Your organization requires an authenticator app. Set it up in Carbon, then come back here."msgstr "조직에서 인증 앱을 요구하고 있습니다. Carbon에서 설정한 후 여기로 돌아오세요."diff --git a/packages/locale/locales/pl/mes.po b/packages/locale/locales/pl/mes.poindex e3a3201ee5..4bb062aa4b 100644--- a/packages/locale/locales/pl/mes.po+++ b/packages/locale/locales/pl/mes.po@@ -515,6 +515,9 @@ msgstr "Zakończ {0}"msgid "Finish Anyways"msgstr "Zakończ mimo wszystko"+msgid "Finish setting up your account"+msgstr ""+msgid "Finish with material unpicked?"msgstr "Zakończyć bez wybranego materiału?"@@ -524,6 +527,9 @@ msgstr "Zapomniałeś zakończyć zmianę?"msgid "Go back to operation"msgstr "Wróć do operacji"+msgid "Go to onboarding"+msgstr ""+msgid "How many were actually picked?"msgstr "Ile faktycznie zostało zebrane?"@@ -1497,6 +1503,9 @@ msgstr "Zalogowałeś się o <0/>. Możesz edytować czas wylogowania poniżej lmsgid "You've been clocked in for {hoursElapsed} hours. Did you forget to clock out?"msgstr "Jesteś zalogowany od {hoursElapsed} godzin. Czy zapomniałeś zakończyć zmianę?"+msgid "Your account isn't part of a company yet. Complete onboarding in the Carbon ERP to continue."+msgstr ""+msgid "Your organization requires an authenticator app. Set it up in Carbon, then come back here."msgstr "Twoja organizacja wymaga aplikacji uwierzytelniającej. Skonfiguruj ją w aplikacji Carbon, a następnie wróć tutaj."diff --git a/packages/locale/locales/pt/mes.po b/packages/locale/locales/pt/mes.poindex 536e06bc54..1e39fe2308 100644--- a/packages/locale/locales/pt/mes.po+++ b/packages/locale/locales/pt/mes.po@@ -515,6 +515,9 @@ msgstr "Terminar {0}"msgid "Finish Anyways"msgstr "Terminar Mesmo Assim"+msgid "Finish setting up your account"+msgstr ""+msgid "Finish with material unpicked?"msgstr "Finalizar com material não selecionado?"@@ -524,6 +527,9 @@ msgstr "Esqueceu de Registrar Saída?"msgid "Go back to operation"msgstr "Voltar para operação"+msgid "Go to onboarding"+msgstr ""+msgid "How many were actually picked?"msgstr "Quantos foram realmente apanhados?"@@ -1497,6 +1503,9 @@ msgstr "Você marcou entrada às <0/>. Você pode editar a hora de saída abaixomsgid "You've been clocked in for {hoursElapsed} hours. Did you forget to clock out?"msgstr "Você está registrado há {hoursElapsed} horas. Esqueceu de registrar a saída?"+msgid "Your account isn't part of a company yet. Complete onboarding in the Carbon ERP to continue."+msgstr ""+msgid "Your organization requires an authenticator app. Set it up in Carbon, then come back here."msgstr "Sua organização requer um aplicativo autenticador. Configure-o no Carbon e retorne aqui."diff --git a/packages/locale/locales/ru/mes.po b/packages/locale/locales/ru/mes.poindex 789a10e6bb..4b2f3ebf01 100644--- a/packages/locale/locales/ru/mes.po+++ b/packages/locale/locales/ru/mes.po@@ -515,6 +515,9 @@ msgstr "Завершить {0}"msgid "Finish Anyways"msgstr "Завершить в любом случае"+msgid "Finish setting up your account"+msgstr ""+msgid "Finish with material unpicked?"msgstr "Завершить с неподобранным материалом?"@@ -524,6 +527,9 @@ msgstr "Забыли отметить уход?"msgid "Go back to operation"msgstr "Вернуться к операции"+msgid "Go to onboarding"+msgstr ""+msgid "How many were actually picked?"msgstr "Сколько было фактически собрано?"@@ -1497,6 +1503,9 @@ msgstr "Вы отметились в системе в <0/>. Вы можетеmsgid "You've been clocked in for {hoursElapsed} hours. Did you forget to clock out?"msgstr "Вы на смене уже {hoursElapsed} часов. Вы забыли отметить уход?"+msgid "Your account isn't part of a company yet. Complete onboarding in the Carbon ERP to continue."+msgstr ""+msgid "Your organization requires an authenticator app. Set it up in Carbon, then come back here."msgstr "Ваша организация требует приложения аутентификатора. Настройте его в Carbon, а затем вернитесь сюда."diff --git a/packages/locale/locales/tr/mes.po b/packages/locale/locales/tr/mes.poindex 107e11003f..5173da4fba 100644--- a/packages/locale/locales/tr/mes.po+++ b/packages/locale/locales/tr/mes.po@@ -515,6 +515,9 @@ msgstr "Bitir {0}"msgid "Finish Anyways"msgstr "Yine de Bitir"+msgid "Finish setting up your account"+msgstr ""+msgid "Finish with material unpicked?"msgstr "Malzeme seçilmeden bitir?"@@ -524,6 +527,9 @@ msgstr "Çıkış yapmayı unuttunuz mu?"msgid "Go back to operation"msgstr "İşleme geri dön"+msgid "Go to onboarding"+msgstr ""+msgid "How many were actually picked?"msgstr "Gerçekte kaç tane alındı?"@@ -1497,6 +1503,9 @@ msgstr "Saat <0/>'te kaydedildiniz. Aşağıda çıkış saatinizi düzenleyebilmsgid "You've been clocked in for {hoursElapsed} hours. Did you forget to clock out?"msgstr "Ne kadar süredir giriş yaptınız? Çıkış yapmayı unuttunuz mu?"+msgid "Your account isn't part of a company yet. Complete onboarding in the Carbon ERP to continue."+msgstr ""+msgid "Your organization requires an authenticator app. Set it up in Carbon, then come back here."msgstr "Kuruluşunuz bir kimlik doğrulama uygulaması gerektirir. Bunu Carbon'da ayarlayın, ardından buraya geri dönün."diff --git a/packages/locale/locales/zh/mes.po b/packages/locale/locales/zh/mes.poindex 666d9a8b3f..3f1ba80349 100644--- a/packages/locale/locales/zh/mes.po+++ b/packages/locale/locales/zh/mes.po@@ -515,6 +515,9 @@ msgstr "完成 {0}"msgid "Finish Anyways"msgstr "仍然完成"+msgid "Finish setting up your account"+msgstr ""+msgid "Finish with material unpicked?"msgstr "物料未拣选完毕,是否完成?"@@ -524,6 +527,9 @@ msgstr "忘记打卡下班了?"msgid "Go back to operation"msgstr "返回操作"+msgid "Go to onboarding"+msgstr ""+msgid "How many were actually picked?"msgstr "实际上捡了多少个?"@@ -1497,6 +1503,9 @@ msgstr "您在 <0/> 打卡。您可以编辑下方的下班时间,或确认您msgid "You've been clocked in for {hoursElapsed} hours. Did you forget to clock out?"msgstr "您已打卡上班 {hoursElapsed} 小时。您是否忘记打卡下班了?"+msgid "Your account isn't part of a company yet. Complete onboarding in the Carbon ERP to continue."+msgstr ""+msgid "Your organization requires an authenticator app. Set it up in Carbon, then come back here."msgstr "您的组织需要身份验证器应用。在 Carbon 中设置,然后返回此处。"