improvements: the whole branch reviewed. some tests added. some cleraning done.
This commit is contained in:
@@ -35,7 +35,7 @@ throw new AppException(ErrorCode.PERMISSION_DENIED, HttpStatus.FORBIDDEN);
|
||||
- Schema: `backend/prisma/schema.prisma`
|
||||
- Always add a migration for schema changes (`npm run prisma:migrate` in backend).
|
||||
- Seed permissions stay in sync with `ALL_TAB_PERMISSIONS` in `common/permissions.ts`.
|
||||
- Signup connects the `trial` plan and `CLINIC` / `LAB` organization types by name. `ensureTrialPlan` and `ensureOrganizationType` create a missing row and do not change an existing trial plan's price. Migration `20261021193000_ensure_reference_plans` inserts those rows only when they are absent.
|
||||
- Signup connects the `base` plan and `CLINIC` / `LAB` organization types by name. `ensureBasePlan` creates a missing base row and does not change an existing base plan's price. `ensureOrganizationType` does the same for org types. Migration `20261023140000_drop_unreferenced_legacy_plans` removes unused `trial` / `Small` / `Medium` / `Large` / `Enterprise` rows and does not move seat dates.
|
||||
- **Schema change ⇒ AdminJS:** update `backend/src/admin/resources.ts` in the same change (add/rename/remove resources, hide new secrets). Trigger-maintained fields such as `LabCase.listedAt` must not be `GENERATED ALWAYS`. See `.cursor/rules/adminjs.mdc`.
|
||||
|
||||
## API responses
|
||||
|
||||
@@ -14,3 +14,4 @@ alwaysApply: false
|
||||
- Money UI: `AppMoneyInput`; party field: `BillingPartyCombobox` (sections); list chrome: `BillingListToolbar` + `Table`. Cash/sheet labels: **Amount** (with org currency suffix).
|
||||
- Billing is visible for CLINIC and LAB (`billingOrgTypes` is empty).
|
||||
- Lab case pickers sort by `listedAt` desc (same COALESCE as Cases — never `sentAt` then `startedAt`).
|
||||
- **Collapsed steps:** deploy copies `design` onto the three design prices (custom-abutment design wins for implant design), sums `stain`+`glaze` into `stain_glaze`, and sums each milling step with `sinter` into its combined code. It does not overwrite a price already stored for the new code. `stain`, `glaze`, and `build_up` stay so existing tasks still resolve. Saving a sheet keeps lines the editor does not show. Prosthesis fee rows and recorded earnings stay. Existing case tasks are not rewritten.
|
||||
|
||||
@@ -48,6 +48,8 @@ Keep chrome identical: `BillingListToolbar`, outline labels, `AppMoneyInput`, eq
|
||||
|
||||
- Start date required. Empty Apply-to = everyone. Lines store money `amount`.
|
||||
- Treatment dispatch / outsource quote previews are not stored.
|
||||
- A save replaces the lines the editor shows and keeps every stored line the editor does not send (`stain`, `glaze`, `build_up`, inactive prosthesis types). Those hidden lines still price existing tasks.
|
||||
- Deploy migration `20261020170000_retire_billing_step_lines` copies collapsed-step prices before it deletes `design` and `design_customized_abutment`. It does not delete prosthesis-type rows or `commission_earnings`.
|
||||
|
||||
## Clinic visibility
|
||||
|
||||
|
||||
@@ -68,14 +68,13 @@ frontend/src/
|
||||
|
||||
**Staff (quick ref):** Owner / `TAB_STAFF_EDIT` can **remove** a password (`POST /staff/members/:id/clear-password`) and copy a setup link — never set one for someone else. Login page unchanged (`passwordHash: null` cannot sign in). `/accept-invite` `password_setup` is password-only. See `.cursor/rules/staff.mdc`.
|
||||
|
||||
**Subscriptions (quick ref):** One **Base** plan includes 3 seats (the owner holds one). Extra seats are separate rows with their own end dates. Each owner gets one free month (`User.trialUsedAt`), stamped only after `grantForNewOwner` starts it. Do not set `trialUsedAt` before that call. A later organization gets Base seats that end immediately. Another organization with the same owner that already has `trialEndsAt` or any seat counts as later, even when `trialUsedAt` is still null. Migration `20261018120000_subscription_seats` runs once on deploy: every real organization gets Base for 30 days from that instant, 3 included seats, and an extra seat for each staff member past those 3. It does not set `trialUsedAt` and does not insert charge rows. Invitation placeholders (no members, and an invite that is still unaccepted) are left unchanged. During the free month an added seat costs $0 and ends with the base seats. After it, Add seat and Extend selected show the quote and then stop (`SUBSCRIPTION_PAYMENT_UNAVAILABLE`, contact Nudenticco@gmail.com). An overdue occupied seat is read-only. An overdue empty seat cannot be reserved. Owners and `TAB_BILLING_READ` manage Subscriptions. Cards show the assigned user. Other members get a `SEAT_EXPIRING` inbox notice 5 days before their seat ends.
|
||||
**Subscriptions (quick ref):** One **Base** plan includes 3 seats (the owner holds one). Extra seats are separate rows with their own end dates. Each owner gets one free month (`User.trialUsedAt`), stamped only after `grantForNewOwner` starts it. Do not set `trialUsedAt` before that call. A later organization gets Base seats that end immediately. Another organization with the same owner that already has `trialEndsAt` or any seat counts as later, even when `trialUsedAt` is still null. Migration `20261018120000_subscription_seats` runs once on deploy: every real organization gets Base for 30 days from that instant, 3 included seats, and an extra seat for each staff member past those 3. It does not set `trialUsedAt` and does not insert charge rows. Disabled members who are not the owner and have no open invite do not take a seat. Migration `20261023140000_drop_unreferenced_legacy_plans` deletes unused `trial`, `Small`, `Medium`, `Large`, and `Enterprise` plans and does not change any end date. Signup ensures the `base` plan. The free month is labeled Trial in the UI; the stored plan name stays `base`. Invitation placeholders (no members, and an invite that is still unaccepted) are left unchanged. During the free month an added seat costs $0 and ends with the base seats. After it, Add seat and Extend selected show the quote and then stop (`SUBSCRIPTION_PAYMENT_UNAVAILABLE`, contact Nudenticco@gmail.com). An overdue occupied seat is read-only. An overdue empty seat cannot be reserved. Owners and `TAB_BILLING_READ` manage Subscriptions. Cards show the assigned user. Other members get a `SEAT_EXPIRING` inbox notice 5 days before their seat ends.
|
||||
|
||||
**Billing (quick ref):** Same three-tab hub for CLINIC + LAB (`/billing?view=`). Clinic: `CLINIC_PRICE` / `CLINIC_COMMISSION` + patient receipts + partner payments. Lab: `LAB_PRICE` (prosthesis fees plus an outsourcing tab) / `LAB_COMMISSION` + partner ledger only. Commissions are **fixed amounts** (not percents). Dispatch and outsource prices are previews and are not stored. Partner list is a **shared** ledger: the sender’s row counts immediately, and the other org Accepts or Declines it. A typed party name stays local. Money inputs: `AppMoneyInput`. Billing is visible for both org types. See `.cursor/rules/billing.mdc`, `.cursor/skills/billing/SKILL.md`.
|
||||
**Billing (quick ref):** Same three-tab hub for CLINIC + LAB (`/billing?view=`). Clinic: `CLINIC_PRICE` / `CLINIC_COMMISSION` + patient receipts + partner payments. Lab: `LAB_PRICE` (prosthesis fees plus an outsourcing tab) / `LAB_COMMISSION` + partner ledger only. Commissions are **fixed amounts** (not percents). Dispatch and outsource prices are previews and are not stored. Collapsed workflow prices are copied onto the combined steps at deploy; `stain`, `glaze`, and `build_up` lines stay so existing tasks still resolve, and a sheet save keeps lines the editor does not show. Prosthesis fee rows, recorded commission earnings, and existing case tasks stay as they are. Partner list is a **shared** ledger: the sender’s row counts immediately, and the other org Accepts or Declines it. A typed party name stays local. Money inputs: `AppMoneyInput`. Billing is visible for both org types. See `.cursor/rules/billing.mdc`, `.cursor/skills/billing/SKILL.md`.
|
||||
|
||||
**Lab Tasks tab:** Newest case first (`listedAt`); grouping only for date sort; filters include completed step, origin, due date, assignment, and prosthesis. New tasks are plan-scoped: one scan → prosthesis sections → optional Model design/creation (when any type has `requiresModelSteps`) → packing/shipping. `lineCount` stays 1. `__line__` tasks are independently completable. A type with both dry milling and sintering generates `milling_dry_sinter`; both wet milling and sintering generate `milling_wet_sinter`; both stain and glaze generate `stain_glaze`. A type with only one half keeps that half, and existing task rows are not rewritten. Model design and model create can be outsourced with that line’s teeth, or the whole plan for a historical `__case__` model step; scan, packing, and shipping cannot. Historical `__case__` scan keeps whole-case fan-out. Same-type exclusive steps coalesce across matching teeth; duplicate non-model steps for stacked types become `typeA+typeB` sections. Pontics fold into connected crown/indirect sections. Task identity includes source, first tooth, section type, and workflow code because one section may produce different tooth sets across steps. Job titles use `ProsthesisJobLineLabel`; task assignment is in Cases; only assignee/unassigned pool can update status in Tasks. `CASE_COMPLETED` drives inbox/tab badges only after all case tasks finish. See `.cursor/skills/lab-tasks/SKILL.md`.
|
||||
|
||||
**Lab Cases tab:** Filter by **prosthesis type** (not treatment type); auto-select newest case on open; list **10 per page**; left rail list fills column height (`flex-1 overflow-y-auto`). Unstarted lab-origin **drafts** sit in a collapsed expandable rail section (opens on click or **Add case**); received + started cases list below, newest first by send or start time (`listedAt`, same key as Tasks). List cards use `LabCaseProsthesisGroupsList` (colored type + teeth, shared with Treatment rail) plus **From clinic** / **Generated** / **From lab** origin badges. Job titles use `ProsthesisJobLineLabel` the same as Treatment/Tasks (`13 · Pontic - 14 · PFZ Crown`; no category; indirect keeps Inlay · Layered ceramic). Deep link: `?caseId=`, `?clinicOrganizationId=`. **Share link:** QR + URL on sent cases **and** started lab-origin cases (attachment left, QR right); opens `/lab-case/[token]` focus page. **Case Sheet PDF:** same portrait/landscape layout, one A4 page (`jspdf`/`html2canvas`, scaled to fit); realistic FDI chart; hex-only print layout; share QR stays in the flex header; optional `externalCode` replaces order number. The page stays LTR; on Persian sheets the org name is shrink-wrapped (RTL only when the name itself is Arabic script) and labels use `0px` letter-spacing. Lab-origin Start has no clinic send and notifies the linked org once (`PARTNER_CASE_CREATED`, share link); generated-case comments have no visibility toggle. A lab-to-lab case uses the eye button so the sending lab can see that comment. Comments use Cases **or** Tasks permission. Unstarted generated drafts can be deleted (`DELETE /cases/:id`). **Edit** (`POST /cases/:id/stop`) returns a started generated case to that drafts rail: completed steps and the previous prosthesis plan stay as history, in-progress steps are dropped, and the case can be edited and started again. Open outsources with no finished step are cancelled; a finished outsourced step blocks Edit. **Outsource** gives selected in-progress prosthesis steps, plus model design and model create, to one linked lab as a child case. Child `sourceKey` stays the child case id unless two selected steps share tooth, type, and workflow (`childId:parentSourceKey`). The child shows only that sending lab (no original clinic or dentist). Those steps leave Tasks until that lab completes them, and only the sending lab sees that direct handoff. The sender chart stays the full plan; the receiver chart is the selected jobs plus pontics on that bridge, or that line’s teeth for a model step. Scan, packing, and shipping stay on the owning lab. **Live:** inbox Socket.IO → `notifyTabBadgesChanged()` soft-refreshes list + selected detail (no remount). A file upload emits `case-section.changed` on that socket (no inbox card) so Files and Messages unread counts refresh the same way. **Add case** is a full-width split button with the lab mic. One file can be removed from its card menu. An upload keeps running after leaving Files or Cases; the open case adds the file from the upload response without another fetch. Attachments have no size cap; production must recreate nginx from the SSL template or `/api` stays at 50MB. See `.cursor/skills/lab-cases/SKILL.md` and `.cursor/skills/lab-case-share-link/SKILL.md`.
|
||||
**Lab Cases tab:** Filter by **prosthesis type** (not treatment type); auto-select newest case on open; list **10 per page**; left rail list fills column height (`flex-1 overflow-y-auto`). Unstarted lab-origin **drafts** sit in a collapsed expandable rail section (opens on click or **Add case**); received + started cases list below, newest first by send or start time (`listedAt`, same key as Tasks). List cards use `LabCaseProsthesisGroupsList` (colored type + teeth, shared with Treatment rail) plus **From clinic** / **Generated** / **From lab** origin badges. Job titles use `ProsthesisJobLineLabel` the same as Treatment/Tasks (`13 · Pontic - 14 · PFZ Crown`; no category; indirect keeps Inlay · Layered ceramic). Deep link: `?caseId=`, `?clinicOrganizationId=`. **Share link:** QR + URL on sent cases **and** started lab-origin cases (attachment left, QR right); opens `/lab-case/[token]` focus page. **Case Sheet PDF:** same portrait/landscape layout, one A4 page (`jspdf`/`html2canvas`, scaled to fit); realistic FDI chart; hex-only print layout; share QR stays in the flex header; optional `externalCode` replaces the printed order number and the `case-sheet-{orderNumber}.pdf` filename. The page stays LTR; on Persian sheets the org name is shrink-wrapped (RTL only when the name itself is Arabic script) and labels use `0px` letter-spacing. Lab-origin Start has no clinic send and notifies the linked org once (`PARTNER_CASE_CREATED`, share link); generated-case comments have no visibility toggle. A lab-to-lab case uses the eye button so the sending lab can see that comment. Comments use Cases **or** Tasks permission. Unstarted generated drafts can be deleted (`DELETE /cases/:id`). **Edit** (`POST /cases/:id/stop`) returns a started generated case to that drafts rail: completed steps and the previous prosthesis plan stay as history, in-progress steps are dropped, and the case can be edited and started again. Open outsources with no finished step are cancelled; a finished outsourced step blocks Edit. **Outsource** gives selected in-progress prosthesis steps to one linked lab as a child case. Child `sourceKey` stays the child case id unless two selected steps share tooth, type, and workflow (`childId:parentSourceKey`). The child shows only that sending lab (no original clinic or dentist). Those steps leave Tasks until that lab completes them, and only the sending lab sees that direct handoff. The sender chart stays the full plan; the receiver chart is the selected jobs plus pontics on that bridge. **Live:** inbox Socket.IO → `notifyTabBadgesChanged()` soft-refreshes list + selected detail (no remount). A file upload emits `case-section.changed` on that socket (no inbox card) so Files and Messages unread counts refresh the same way. **Add case** is a full-width split button with the lab mic. One file can be removed from its card menu. An upload keeps running after leaving Files or Cases; the open case adds the file from the upload response without another fetch. Attachments have no size cap; production must recreate nginx from the SSL template or `/api` stays at 50MB. **Send to Exocad** (Chrome and Edge only, any screen size; no helper program or download) writes the open case into a DentalDB SQLite file on that computer. The browser remembers the file only after the DentalDB check and reopens it while it still exists; an invalid file is not remembered, so Browse stays available. A tooth is written only when that work type and material already exist in the file. There is no Local database tab. See `.cursor/skills/lab-cases/SKILL.md` and `.cursor/skills/lab-case-share-link/SKILL.md`.
|
||||
**Lab Cases tab:** Filter by **prosthesis type** (not treatment type); auto-select newest case on open; list **10 per page**; left rail list fills column height (`flex-1 overflow-y-auto`). Unstarted lab-origin **drafts** sit in a collapsed expandable rail section (opens on click or **Add case**); received + started cases list below, newest first by send or start time (`listedAt`, same key as Tasks). List cards use `LabCaseProsthesisGroupsList` (colored type + teeth, shared with Treatment rail) plus **From clinic** / **Generated** / **From lab** origin badges. Job titles use `ProsthesisJobLineLabel` the same as Treatment/Tasks (`13 · Pontic - 14 · PFZ Crown`; no category; indirect keeps Inlay · Layered ceramic). Deep link: `?caseId=`, `?clinicOrganizationId=`. **Share link:** QR + URL on sent cases **and** started lab-origin cases (attachment left, QR right); opens `/lab-case/[token]` focus page. **Case Sheet PDF:** same portrait/landscape layout, one A4 page (`jspdf`/`html2canvas`, scaled to fit); realistic FDI chart; hex-only print layout; share QR stays in the flex header; optional `externalCode` replaces the printed order number and the `case-sheet-{orderNumber}.pdf` filename. The page stays LTR; on Persian sheets the org name is shrink-wrapped (RTL only when the name itself is Arabic script) and labels use `0px` letter-spacing. Lab-origin Start has no clinic send and notifies the linked org once (`PARTNER_CASE_CREATED`, share link); generated-case comments have no visibility toggle. A lab-to-lab case uses the eye button so the sending lab can see that comment. Comments use Cases **or** Tasks permission. Unstarted generated drafts can be deleted (`DELETE /cases/:id`). **Edit** (`POST /cases/:id/stop`) returns a started generated case to that drafts rail: completed steps and the previous prosthesis plan stay as history, in-progress steps are dropped, and the case can be edited and started again. Open outsources with no finished step are cancelled; a finished outsourced step blocks Edit. **Outsource** gives selected in-progress prosthesis steps, plus model design and model create, to one linked lab as a child case. Child `sourceKey` stays the child case id unless two selected steps share tooth, type, and workflow (`childId:parentSourceKey`). The child shows only that sending lab (no original clinic or dentist). Those steps leave Tasks until that lab completes them, and only the sending lab sees that direct handoff. The sender chart stays the full plan; the receiver chart is the selected jobs plus pontics on that bridge. **Live:** inbox Socket.IO → `notifyTabBadgesChanged()` soft-refreshes list + selected detail (no remount). A file upload emits `case-section.changed` on that socket (no inbox card) so Files and Messages unread counts refresh the same way. **Add case** is a full-width split button with the lab mic. One file can be removed from its card menu. An upload keeps running after leaving Files or Cases; the open case adds the file from the upload response without another fetch. Attachments have no size cap; production must recreate nginx from the SSL template or `/api` stays at 50MB. **Send to Exocad** (Chrome and Edge only, any screen size; no helper program or download) writes the open case into a DentalDB SQLite file on that computer. The browser remembers the file only after the DentalDB check and reopens it while it still exists; an invalid file is not remembered, so Browse stays available. A tooth is written only when that work type and material already exist in the file. There is no Local database tab. See `.cursor/skills/lab-cases/SKILL.md` and `.cursor/skills/lab-case-share-link/SKILL.md`.
|
||||
|
||||
**Lab case share link (quick ref):**
|
||||
- Token on first ship **or** lab-origin Start → `/{locale}/lab-case/{token}` after login. Editing a generated case keeps that token. The page reads the current round and the live patient/clinic snapshots. Cases, Treatment lab dispatch, and the Case Sheet QR all use this URL.
|
||||
|
||||
@@ -1,10 +1,116 @@
|
||||
-- Editors no longer offer these codes. Stored tasks keep their own step labels.
|
||||
-- Copy prices onto the codes the fee sheet shows after pipelines collapsed.
|
||||
-- Do not overwrite a price that is already stored for the new code.
|
||||
-- Existing case tasks are not rewritten. stain, glaze, and build_up stay so those
|
||||
-- tasks still resolve. design and design_customized_abutment are replaced by the
|
||||
-- three design prices, which quotes already map onto.
|
||||
|
||||
INSERT INTO "billing_sheet_lines" ("id", "sheetId", "catalogKind", "catalogCode", "amount", "percent")
|
||||
SELECT gen_random_uuid()::text, src."sheetId", 'LAB_WORKFLOW_STEP', 'design_implant', src.amount, NULL
|
||||
FROM "billing_sheet_lines" src
|
||||
WHERE src."catalogKind" = 'LAB_WORKFLOW_STEP'
|
||||
AND src."catalogCode" = 'design_customized_abutment'
|
||||
AND src.amount <> 0
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM "billing_sheet_lines" existing
|
||||
WHERE existing."sheetId" = src."sheetId"
|
||||
AND existing."catalogKind" = 'LAB_WORKFLOW_STEP'
|
||||
AND existing."catalogCode" = 'design_implant'
|
||||
);
|
||||
|
||||
INSERT INTO "billing_sheet_lines" ("id", "sheetId", "catalogKind", "catalogCode", "amount", "percent")
|
||||
SELECT gen_random_uuid()::text, src."sheetId", 'LAB_WORKFLOW_STEP', target.code, src.amount, NULL
|
||||
FROM "billing_sheet_lines" src
|
||||
CROSS JOIN (
|
||||
VALUES ('design_implant'::text), ('design_frame'::text), ('design_full'::text)
|
||||
) AS target(code)
|
||||
WHERE src."catalogKind" = 'LAB_WORKFLOW_STEP'
|
||||
AND src."catalogCode" = 'design'
|
||||
AND src.amount <> 0
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM "billing_sheet_lines" existing
|
||||
WHERE existing."sheetId" = src."sheetId"
|
||||
AND existing."catalogKind" = 'LAB_WORKFLOW_STEP'
|
||||
AND existing."catalogCode" = target.code
|
||||
);
|
||||
|
||||
INSERT INTO "billing_sheet_lines" ("id", "sheetId", "catalogKind", "catalogCode", "amount", "percent")
|
||||
SELECT gen_random_uuid()::text, src."sheetId", 'LAB_WORKFLOW_STEP', 'build_up_crown', src.amount, NULL
|
||||
FROM "billing_sheet_lines" src
|
||||
WHERE src."catalogKind" = 'LAB_WORKFLOW_STEP'
|
||||
AND src."catalogCode" = 'build_up'
|
||||
AND src.amount <> 0
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM "billing_sheet_lines" existing
|
||||
WHERE existing."sheetId" = src."sheetId"
|
||||
AND existing."catalogKind" = 'LAB_WORKFLOW_STEP'
|
||||
AND existing."catalogCode" = 'build_up_crown'
|
||||
);
|
||||
|
||||
INSERT INTO "billing_sheet_lines" ("id", "sheetId", "catalogKind", "catalogCode", "amount", "percent")
|
||||
SELECT gen_random_uuid()::text, src."sheetId", 'LAB_WORKFLOW_STEP', 'build_up_laminate', src.amount, NULL
|
||||
FROM "billing_sheet_lines" src
|
||||
WHERE src."catalogKind" = 'LAB_WORKFLOW_STEP'
|
||||
AND src."catalogCode" = 'build_up'
|
||||
AND src.amount <> 0
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM "billing_sheet_lines" existing
|
||||
WHERE existing."sheetId" = src."sheetId"
|
||||
AND existing."catalogKind" = 'LAB_WORKFLOW_STEP'
|
||||
AND existing."catalogCode" = 'build_up_laminate'
|
||||
);
|
||||
|
||||
INSERT INTO "billing_sheet_lines" ("id", "sheetId", "catalogKind", "catalogCode", "amount", "percent")
|
||||
SELECT gen_random_uuid()::text, grouped."sheetId", 'LAB_WORKFLOW_STEP', grouped.target_code, grouped.amount, NULL
|
||||
FROM (
|
||||
SELECT src."sheetId", 'stain_glaze' AS target_code, SUM(src.amount) AS amount
|
||||
FROM "billing_sheet_lines" src
|
||||
WHERE src."catalogKind" = 'LAB_WORKFLOW_STEP'
|
||||
AND src."catalogCode" IN ('stain', 'glaze')
|
||||
GROUP BY src."sheetId"
|
||||
HAVING SUM(src.amount) <> 0
|
||||
) grouped
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM "billing_sheet_lines" existing
|
||||
WHERE existing."sheetId" = grouped."sheetId"
|
||||
AND existing."catalogKind" = 'LAB_WORKFLOW_STEP'
|
||||
AND existing."catalogCode" = grouped.target_code
|
||||
);
|
||||
|
||||
INSERT INTO "billing_sheet_lines" ("id", "sheetId", "catalogKind", "catalogCode", "amount", "percent")
|
||||
SELECT gen_random_uuid()::text, grouped."sheetId", 'LAB_WORKFLOW_STEP', grouped.target_code, grouped.amount, NULL
|
||||
FROM (
|
||||
SELECT src."sheetId", 'milling_dry_sinter' AS target_code, SUM(src.amount) AS amount
|
||||
FROM "billing_sheet_lines" src
|
||||
WHERE src."catalogKind" = 'LAB_WORKFLOW_STEP'
|
||||
AND src."catalogCode" IN ('milling_dry', 'sinter')
|
||||
GROUP BY src."sheetId"
|
||||
HAVING SUM(src.amount) <> 0
|
||||
) grouped
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM "billing_sheet_lines" existing
|
||||
WHERE existing."sheetId" = grouped."sheetId"
|
||||
AND existing."catalogKind" = 'LAB_WORKFLOW_STEP'
|
||||
AND existing."catalogCode" = grouped.target_code
|
||||
);
|
||||
|
||||
INSERT INTO "billing_sheet_lines" ("id", "sheetId", "catalogKind", "catalogCode", "amount", "percent")
|
||||
SELECT gen_random_uuid()::text, grouped."sheetId", 'LAB_WORKFLOW_STEP', grouped.target_code, grouped.amount, NULL
|
||||
FROM (
|
||||
SELECT src."sheetId", 'milling_wet_sinter' AS target_code, SUM(src.amount) AS amount
|
||||
FROM "billing_sheet_lines" src
|
||||
WHERE src."catalogKind" = 'LAB_WORKFLOW_STEP'
|
||||
AND src."catalogCode" IN ('milling_wet', 'sinter')
|
||||
GROUP BY src."sheetId"
|
||||
HAVING SUM(src.amount) <> 0
|
||||
) grouped
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM "billing_sheet_lines" existing
|
||||
WHERE existing."sheetId" = grouped."sheetId"
|
||||
AND existing."catalogKind" = 'LAB_WORKFLOW_STEP'
|
||||
AND existing."catalogCode" = grouped.target_code
|
||||
);
|
||||
|
||||
-- These two codes are no longer stored. Quotes map them onto the design prices above.
|
||||
DELETE FROM "billing_sheet_lines"
|
||||
WHERE "catalogKind" = 'LAB_WORKFLOW_STEP'
|
||||
AND "catalogCode" IN (
|
||||
'stain',
|
||||
'glaze',
|
||||
'build_up',
|
||||
'design',
|
||||
'design_customized_abutment'
|
||||
);
|
||||
AND "catalogCode" IN ('design', 'design_customized_abutment');
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
-- Subscription v2 uses the base plan only.
|
||||
-- An earlier migration inserts the old plan names when they are missing.
|
||||
-- Remove them when no organization still points at them.
|
||||
-- Do not change trialEndsAt, seat end dates, or a plan that is still referenced.
|
||||
|
||||
DELETE FROM "plans" leftover
|
||||
WHERE leftover."name" IN ('trial', 'Small', 'Medium', 'Large', 'Enterprise')
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM "organizations" o WHERE o."planId" = leftover.id
|
||||
);
|
||||
@@ -2,19 +2,20 @@ import { Prisma } from '@prisma/client';
|
||||
|
||||
type CatalogDb = Prisma.TransactionClient;
|
||||
|
||||
const TRIAL_PLAN = {
|
||||
name: 'trial',
|
||||
maxUsers: 5,
|
||||
price: 0,
|
||||
const BASE_PLAN = {
|
||||
name: 'base',
|
||||
maxUsers: 3,
|
||||
price: 20,
|
||||
seatPrice: 7,
|
||||
features: {},
|
||||
} as const;
|
||||
|
||||
/** Signup connects this row by name. Create it when a database was migrated without seed. */
|
||||
export async function ensureTrialPlan(db: CatalogDb): Promise<void> {
|
||||
export async function ensureBasePlan(db: CatalogDb): Promise<void> {
|
||||
await db.plan.upsert({
|
||||
where: { name: TRIAL_PLAN.name },
|
||||
where: { name: BASE_PLAN.name },
|
||||
update: {},
|
||||
create: { ...TRIAL_PLAN },
|
||||
create: { ...BASE_PLAN },
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ import { JwtPayload } from './interfaces/jwt-payload.interface';
|
||||
import { ownerPermissionsForOrgType, type OrganizationTypeName } from '../../common/organization-type';
|
||||
import { getEffectivePermissionNames, getOrgTypeFromMembership, hasActivePlan, hasEffectivePermission, participatesInTasks, participatesInTreatments, participationPermissionsForOrgType } from '../../common/membership-permissions';
|
||||
import { assertClinicOrganization, assertLabOrganization } from '../../common/organization-type';
|
||||
import { ensureOrganizationType, ensureTrialPlan } from '../../common/reference-catalog';
|
||||
import { ensureBasePlan, ensureOrganizationType } from '../../common/reference-catalog';
|
||||
import { StaffWorkingHoursService } from '../staff/staff-working-hours.service';
|
||||
import { UpsertWorkingHoursDto } from '../staff/dto/upsert-working-hours.dto';
|
||||
import { UpdateParticipationDto } from './dto/update-participation.dto';
|
||||
@@ -340,7 +340,7 @@ export class AuthService {
|
||||
|
||||
await this.assertRegistrationAvailable(tx, email, payload.mobile);
|
||||
await ensureOrganizationType(tx, payload.organizationType);
|
||||
await ensureTrialPlan(tx);
|
||||
await ensureBasePlan(tx);
|
||||
|
||||
const user = await tx.user.create({
|
||||
data: {
|
||||
@@ -462,6 +462,7 @@ export class AuthService {
|
||||
const organization = await this.prisma.$transaction(async (tx) => {
|
||||
await assertOwnerOrganizationNameAvailable(tx, userId, organizationName);
|
||||
await ensureOrganizationType(tx, dto.organizationType);
|
||||
await ensureBasePlan(tx);
|
||||
|
||||
const createdOrganization = await tx.organization.create({
|
||||
data: {
|
||||
|
||||
@@ -34,6 +34,7 @@ import {
|
||||
outsourcingPriceStepCodes,
|
||||
} from './outsourcing-price-steps';
|
||||
import { UpsertBillingSheetDto } from './dto/upsert-billing-sheet.dto';
|
||||
import { omittedSheetLines } from './sheet-line-preserve';
|
||||
import {
|
||||
calculateClinicDetailAmount,
|
||||
calculateCommissionEarned,
|
||||
@@ -313,6 +314,7 @@ export class BillingService {
|
||||
throw new AppException(ErrorCode.BILLING_SHEET_KIND_INVALID, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
await this.assertSheetPayload(organizationId, orgType, dto);
|
||||
const keptLines = omittedSheetLines(existing.lines, dto.lines);
|
||||
|
||||
const sheet = await this.prisma.$transaction(async (tx) => {
|
||||
await tx.billingSheetTarget.deleteMany({ where: { sheetId: id } });
|
||||
@@ -323,7 +325,17 @@ export class BillingService {
|
||||
name: dto.name?.trim() || null,
|
||||
effectiveOn: dateOnlyUtc(dto.effectiveOn),
|
||||
targets: { create: this.targetCreates(dto) },
|
||||
lines: { create: this.lineCreates(dto) },
|
||||
lines: {
|
||||
create: [
|
||||
...this.lineCreates(dto),
|
||||
...keptLines.map((line) => ({
|
||||
catalogKind: line.catalogKind,
|
||||
catalogCode: line.catalogCode,
|
||||
amount: line.amount,
|
||||
percent: line.percent,
|
||||
})),
|
||||
],
|
||||
},
|
||||
},
|
||||
include: sheetInclude,
|
||||
});
|
||||
|
||||
27
backend/src/modules/billing/sheet-line-preserve.spec.ts
Normal file
27
backend/src/modules/billing/sheet-line-preserve.spec.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { omittedSheetLines } from './sheet-line-preserve';
|
||||
|
||||
describe('omittedSheetLines', () => {
|
||||
it('keeps stored lines the editor did not send', () => {
|
||||
const kept = omittedSheetLines(
|
||||
[
|
||||
{ catalogKind: 'LAB_WORKFLOW_STEP', catalogCode: 'stain', amount: 10 },
|
||||
{ catalogKind: 'LAB_WORKFLOW_STEP', catalogCode: 'stain_glaze', amount: 30 },
|
||||
{ catalogKind: 'PROSTHESIS_TYPE', catalogCode: 'veneer_zirconia', amount: 80 },
|
||||
],
|
||||
[
|
||||
{ catalogKind: 'LAB_WORKFLOW_STEP', catalogCode: 'stain_glaze' },
|
||||
{ catalogKind: 'PROSTHESIS_TYPE', catalogCode: 'pfm_crown' },
|
||||
],
|
||||
);
|
||||
expect(kept.map((line) => line.catalogCode)).toEqual(['stain', 'veneer_zirconia']);
|
||||
});
|
||||
|
||||
it('returns nothing when every stored line is in the save', () => {
|
||||
expect(
|
||||
omittedSheetLines(
|
||||
[{ catalogKind: 'LAB_WORKFLOW_STEP', catalogCode: 'polish_prep' }],
|
||||
[{ catalogKind: 'LAB_WORKFLOW_STEP', catalogCode: 'polish_prep' }],
|
||||
),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
13
backend/src/modules/billing/sheet-line-preserve.ts
Normal file
13
backend/src/modules/billing/sheet-line-preserve.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
type SheetLineKey = {
|
||||
catalogKind: string;
|
||||
catalogCode: string;
|
||||
};
|
||||
|
||||
/** Lines the editor no longer renders. A save must not drop them. */
|
||||
export function omittedSheetLines<T extends SheetLineKey>(
|
||||
existing: readonly T[],
|
||||
next: readonly SheetLineKey[],
|
||||
): T[] {
|
||||
const keys = new Set(next.map((line) => `${line.catalogKind}:${line.catalogCode}`));
|
||||
return existing.filter((line) => !keys.has(`${line.catalogKind}:${line.catalogCode}`));
|
||||
}
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
} from '../email-verification/email-verification.service';
|
||||
import { canConnectOrganizationTypes } from '../../common/linked-organizations';
|
||||
import { SubscriptionService } from '../subscription/subscription.service';
|
||||
import { ensureOrganizationType, ensureTrialPlan } from '../../common/reference-catalog';
|
||||
import { ensureBasePlan, ensureOrganizationType } from '../../common/reference-catalog';
|
||||
import { AcceptOrganizationInviteDto } from './dto/accept-organization-invite.dto';
|
||||
import { CreateConnectionRequestDto } from './dto/create-connection-request.dto';
|
||||
import { InviteOrganizationDto } from './dto/invite-organization.dto';
|
||||
@@ -816,7 +816,7 @@ export class OrganizationService {
|
||||
|
||||
let targetOrganizationId = invitation.invitedOrganizationId;
|
||||
await ensureOrganizationType(tx, dto.organizationType);
|
||||
await ensureTrialPlan(tx);
|
||||
await ensureBasePlan(tx);
|
||||
if (targetOrganizationId) {
|
||||
await tx.organization.update({
|
||||
where: { id: targetOrganizationId },
|
||||
|
||||
@@ -70,6 +70,7 @@ export function SubscriptionsPage() {
|
||||
const toast = useToast();
|
||||
const [current, setCurrent] = useState<SubscriptionCurrent | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadFailed, setLoadFailed] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [months, setMonths] = useState(1);
|
||||
const [baseSelected, setBaseSelected] = useState(true);
|
||||
@@ -85,14 +86,21 @@ export function SubscriptionsPage() {
|
||||
useEffect(() => {
|
||||
if (!currentOrganization || !canManage) return;
|
||||
let cancelled = false;
|
||||
setCurrent(null);
|
||||
setLoading(true);
|
||||
setLoadFailed(false);
|
||||
void subscriptionsApi
|
||||
.current()
|
||||
.then((response) => {
|
||||
if (!cancelled && response.success) setCurrent(response.data);
|
||||
if (cancelled) return;
|
||||
if (response.success) setCurrent(response.data);
|
||||
else setLoadFailed(true);
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (!cancelled) toast.showError(getUserFacingError(error, tErrors, t('subscriptionLoadFailed')));
|
||||
if (!cancelled) {
|
||||
setLoadFailed(true);
|
||||
toast.showError(getUserFacingError(error, tErrors, t('subscriptionLoadFailed')));
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false);
|
||||
@@ -130,6 +138,14 @@ export function SubscriptionsPage() {
|
||||
const seatPrice = current?.seatPrice ?? 7;
|
||||
const selectedExtraCount = selectedExtraIds.length;
|
||||
const quote = (baseSelected ? basePrice : 0) * months + seatPrice * selectedExtraCount * months;
|
||||
const priceLabel = (euros: number) =>
|
||||
extensionAmount(
|
||||
euros,
|
||||
locale,
|
||||
current?.secondaryCurrency,
|
||||
current?.unitsPerEuro,
|
||||
(code) => tCommon(`currencyName.${code}` as 'currencyName.TOMAN'),
|
||||
);
|
||||
const allSelected = baseSelected && selectedExtraCount === extras.length;
|
||||
const someSelected = baseSelected || selectedExtraCount > 0;
|
||||
|
||||
@@ -145,7 +161,7 @@ export function SubscriptionsPage() {
|
||||
title: t('addSeat'),
|
||||
message: t('trialAddBody', {
|
||||
date: endLabel,
|
||||
amount: moneyLabel(seatPrice, locale),
|
||||
amount: priceLabel(seatPrice),
|
||||
}),
|
||||
confirmLabel: t('addSeat'),
|
||||
cancelLabel: tCommon('cancel'),
|
||||
@@ -168,7 +184,7 @@ export function SubscriptionsPage() {
|
||||
title: t('addSeat'),
|
||||
message: t('paidAddBody', {
|
||||
date: formatAppDate(paidEnd.toISOString(), locale),
|
||||
amount: moneyLabel(seatPrice * months, locale),
|
||||
amount: priceLabel(seatPrice * months),
|
||||
}),
|
||||
confirmLabel: t('addSeat'),
|
||||
cancelLabel: tCommon('cancel'),
|
||||
@@ -196,13 +212,7 @@ export function SubscriptionsPage() {
|
||||
title: t('extendSelected'),
|
||||
message: t('extendBody', {
|
||||
months: formatAppInteger(months, locale),
|
||||
amount: extensionAmount(
|
||||
quote,
|
||||
locale,
|
||||
current?.secondaryCurrency,
|
||||
current?.unitsPerEuro,
|
||||
(code) => tCommon(`currencyName.${code}` as 'currencyName.TOMAN'),
|
||||
),
|
||||
amount: priceLabel(quote),
|
||||
}),
|
||||
confirmLabel: t('extendSelected'),
|
||||
cancelLabel: tCommon('cancel'),
|
||||
@@ -228,8 +238,10 @@ export function SubscriptionsPage() {
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{loading || !current ? (
|
||||
{loading ? (
|
||||
<p className="text-sm text-text-secondary">{tCommon('loadingEllipsis')}</p>
|
||||
) : loadFailed || !current ? (
|
||||
<p className="text-sm text-amber-700 dark:text-amber-400">{t('subscriptionLoadFailed')}</p>
|
||||
) : !current.hasPlan ? (
|
||||
<p className="text-sm text-amber-700 dark:text-amber-400">{t('subscriptionNoPlan')}</p>
|
||||
) : (
|
||||
@@ -349,7 +361,7 @@ export function SubscriptionsPage() {
|
||||
</>
|
||||
)}
|
||||
|
||||
{current?.hasPlan ? (
|
||||
{!loading && !loadFailed && current?.hasPlan ? (
|
||||
<div className="sticky bottom-0 z-10 mt-6 flex flex-wrap items-center justify-between gap-3 rounded-[var(--radius-md)] border border-border bg-background-secondary/95 px-4 py-3 backdrop-blur-sm">
|
||||
<label className="flex items-center gap-2 text-sm text-text-secondary">
|
||||
{t('subscriptionMonths')}
|
||||
@@ -366,14 +378,7 @@ export function SubscriptionsPage() {
|
||||
/>
|
||||
</label>
|
||||
<p className="text-base font-medium text-text-primary">
|
||||
{t('extendTotal')}:{' '}
|
||||
{extensionAmount(
|
||||
quote,
|
||||
locale,
|
||||
current.secondaryCurrency,
|
||||
current.unitsPerEuro,
|
||||
(code) => tCommon(`currencyName.${code}` as 'currencyName.TOMAN'),
|
||||
)}
|
||||
{t('extendTotal')}: {priceLabel(quote)}
|
||||
</p>
|
||||
<Button type="button" disabled={!someSelected} onClick={() => extendSelected()}>
|
||||
{t('extendSelected')}
|
||||
|
||||
Reference in New Issue
Block a user