Compare commits

..

6 Commits

Author SHA1 Message Date
63481fdd35 improvements: statements pdf layout added. staff salary report improved.
All checks were successful
Production — tag build, push, deploy / build-and-push (push) Successful in 4m12s
Production — tag build, push, deploy / deploy (push) Successful in 14m16s
2026-11-23 02:13:59 +03:30
dde3eb5d00 Merge pull request 'feature: teeth color shades added. UI and UX updated in all flows accordingly. voice feature updated. pdf layouts matched and etc' (#132) from feature/teeth-color-shades into master
All checks were successful
Registry — build, push, deploy / build-and-push (push) Successful in 37m43s
Registry — build, push, deploy / deploy (push) Successful in 2m13s
Reviewed-on: #132
Reviewed-by: Babak <babak.safarnezhad@gmail.com>
2026-11-21 17:34:40 +03:30
28e68f8c0b Merge pull request 'Remove the unauthorized ci-check workflow that reads Actions secrets.' (#131) from remove-unauthorized-ci-check into master
All checks were successful
Registry — build, push, deploy / build-and-push (push) Successful in 1m24s
Registry — build, push, deploy / deploy (push) Successful in 1m32s
Reviewed-on: #131
Reviewed-by: aminmsvi <amn.mousavi@gmail.com>
2026-11-19 20:28:53 +03:30
feaf548f98 Remove the unauthorized ci-check workflow that reads Actions secrets.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 20:18:02 +03:30
8e92c13f7a Merge pull request 'deploy-wixur-com & resolve ssl certification expire date issue its now automated with arvancloud api just on nudentic.ir.' (#130) from deploy-wixur-com into master
All checks were successful
Registry — build, push, deploy / build-and-push (push) Successful in 1m8s
Registry — build, push, deploy / deploy (push) Successful in 1m19s
Reviewed-on: #130
Reviewed-by: aminmsvi <amn.mousavi@gmail.com>
2026-11-19 20:10:25 +03:30
9a8c492d15 feature: teeth color shades added. UI and UX updated in all flows accordingly. voice feature updated. pdf layouts matched and etc 2026-11-18 18:41:51 +03:30
77 changed files with 2734 additions and 133 deletions

View File

@@ -11,10 +11,10 @@ alwaysApply: false
- **Sheet kinds:** clinic `CLINIC_PRICE` / `CLINIC_COMMISSION`; lab `LAB_PRICE` (outsourcing tab first) / `LAB_COMMISSION`. Commission lines are **fixed amounts**.
- **Partner ledger is shared:** Accept/Decline for the other org; typed `externalPartyName` is local (no ack).
- **Transactions:** Clinic RECEIPT → patient or linked org; PAYMENT → linked org or staff (`StaffPayment`, outbound only). Lab RECEIPT/PAYMENT → linked org; PAYMENT may also be staff. Grouped `GET /billing/party-search`. Merged list: `GET /billing/transactions` (+ optional party filter + signed **net**: RECEIPT +, PAYMENT −).
- **Inline party ledger:** default table is cash only. Selecting a patient/staff/org swaps that same table to `GET /billing/party-report` obligations + cash, one neutral Amount column with a Debit/Credit marker, and an aligned balance footer. Only the final balance uses green/red (green = they owe us, red = we owe them). Case rows show Received/Generated/From lab origin. Staff selection shows closed-month commission and salary, plus an unsaved preview of the open month through the report day. A notification link selects the sender the same way, with no date range.
- **Inline party ledger:** default table is cash only. Selecting a patient/staff/org swaps that same table to `GET /billing/party-report` obligations + cash, one neutral Amount column with a Debit/Credit marker, and an aligned balance footer. Only the final balance uses green/red (green = they owe us, red = we owe them). Case rows show Received/Generated/From lab origin. An organization selection can **Print statement**: the same rows and `totals.net`, oldest first, one page when the rows fit, bordered columns for number, date, reference, and amount. The Persian table is RTL; its cell text stays left-to-right and is shifted up so the glyphs sit in the row. The Case Sheet header stays LTR. No payment-note block. The staff card is the open month only, summed from the preview rows. **Show details** on that card, or on a commission row, loads `GET /billing/staff-income` (job, unit price, quantity, amount, and earning lines). A clinic line’s reference is the patient; a lab line’s reference is the referring clinic and dentist. Salary rows have no details, and that response does not repeat the salary. A notification link selects the sender the same way, with no date range.
- **Cash edits:** amount, note, and valid allocations edit inside the selected table row. Allocations open under that row. Identity/type/currency/date/creator stay immutable. Patient/staff cash is org-editable; shared partner cash is editable only by `recorderOrganizationId`. Every shared edit resets acknowledgement to pending, uses `expectedUpdatedAt`, and appends a `BillingCashTransactionEvent`.
- **Obligations are automatic:** approved treatment → patient; a case fee is mirrored only when every current-round task is done (received, outsourced, and generated-with-partner); monthly commission and fixed salary → staff. Send/Start stores the case price and does not post the debt. Reopening a step removes that case’s debt. Cash creation remains separate and manual. Party reports union obligations with cash; on a party account, RECEIPT is credit and PAYMENT is debit. Shared partner cash counts for the recorder while pending; accepted cash counts for both; rejected cash stays visible to both but counts only for the recorder.
- **Fixed salary:** one sheet on Commissions/Salary (`GET`/`PUT /billing/staff-salaries`) for the owner and active members. Amounts stay on `Membership.fixedMonthlySalary`. Saving does not write a ledger row. After a month ends, the hourly job snapshots the full month once and sums that month's commissions; both are separate staff payables dated on the last day. The open month shows the same two rows unsaved: commissions earned so far, and the sheet amount times days elapsed over days in the month. A later edit does not change a closed month. A missed month is closed on the next run with the rate then on the sheet. Toman uses Jalali months; Dollar/Euro use Gregorian months. V1 has no attendance model. The stored month-end salary is the full month.
- **Fixed salary:** one sheet on Commissions/Salary (`GET`/`PUT /billing/staff-salaries`) for the owner and active members. Amounts stay on `Membership.fixedMonthlySalary`. Saving does not write a ledger row. After a month ends, the hourly job snapshots the full month once and sums that month's commissions; both are separate staff payables dated on the last day. A null or zero rate creates no salary row. The open month shows the same two rows unsaved when each amount is above zero: commissions earned so far, and the sheet amount times days elapsed over days in the month. **Show details** is commission only. A later edit does not change a closed month. A missed month is closed on the next run with the rate then on the sheet. Toman uses Jalali months; Dollar/Euro use Gregorian months. V1 has no attendance model. The stored month-end salary is the full month.
- **Unpriced types:** price sheets can set `hideUnpricedTypes`. Commission sheets always store it false, and migration `20261111233000_sheet_flag_and_subscription_courtesy` sets every existing commission sheet unchecked. Existing fee sheets received false when `20261111130000_billing_obligations` added the column; their lines, targets, and dates are not rewritten. Clinic and lab chart pickers hide zero/missing-price types but keep already-selected jobs visible. An active lab sheet with the flag blocks clinic dispatch for unsupported jobs. If the flag is off and any case job is unpriced, the price stays empty until the destination lab sets it. The pending obligation appears when every step is done; the lab can type the fee on the case before that, and that amount is what the debt uses.
- 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).

View File

@@ -13,7 +13,7 @@ Monorepo: `backend/` (NestJS + Prisma), `frontend/` (Next.js + next-intl), `infr
- **LAB** orgs: cases, tasks, lab workflows.
- Named **patients** are scoped to `createdByOrganizationId`. `identification` stays globally unique — other-org / walk-in hit `PATIENT_IDENTIFICATION_UNAVAILABLE` (no shared row). `mobile` is not unique.
- Tab access: `TAB_*_READ` / `TAB_*_EDIT` in `backend/src/common/permissions.ts`. EDIT implies READ.
- **Billing** (clinic + lab): fee/commission sheets, automatic obligations, and a cash ledger. A case fee becomes a debt when every current-round task is done. The Commissions/Salary tab holds one current salary sheet; month-end rows are posted after the month ends, and the open month is only a calculated preview. `hideUnpricedTypes` defaults off and commission sheets cannot turn it on. See `.cursor/rules/billing.mdc` and `.cursor/skills/billing/SKILL.md`.
- **Billing** (clinic + lab): fee/commission sheets, automatic obligations, and a cash ledger. A case fee becomes a debt when every current-round task is done. The Commissions/Salary tab holds one current salary sheet; month-end rows are posted after the month ends, and the open month is only a calculated preview. The staff card shows that preview only. An organization can print the party ledger as a statement. `hideUnpricedTypes` defaults off and commission sheets cannot turn it on. See `.cursor/rules/billing.mdc` and `.cursor/skills/billing/SKILL.md`.
## Agent behavior

View File

@@ -0,0 +1,18 @@
---
description: Case-level tooth shade (VITA codes) — storage, edit gates, surfaces, voice
globs: backend/src/modules/tooth-shade-catalog/**,backend/src/modules/cases/cases.service.ts,backend/src/modules/treatments/treatments.service.ts,backend/src/modules/voice/**,frontend/src/components/ui/shared/ToothShadeGuide.tsx,frontend/src/components/ui/treatment/TreatmentDetailsEditor.tsx,frontend/src/components/ui/treatment/TreatmentWorkspace.tsx,frontend/src/components/ui/lab/Case*.tsx,frontend/src/components/treatment/voice*.ts,frontend/src/components/lab/voiceLine.ts
alwaysApply: false
---
# Tooth shade
- **One optional shade per lab case**, not per tooth: `LabCase.toothShadeCode` → `ToothShade.code` (nullable FK). Codes: `0M1–0M3, A1–A4 (+A3.5), B1–B4, C1–C4, D2–D4`. Lab-dependent work only.
- **Null is normal.** Historical shades stay in comments/notes; never backfill. Every surface must tolerate `null`.
- **Validate** with `ToothShadeCatalogService.normalize` (canonicalizes `a 3,5` → `A3.5`, `OM1` → `0M1`; unknown → `TOOTH_SHADE_INVALID`). Inactive codes stay valid on existing cases; the picker lists active ones.
- **Edit gates** (`TOOTH_SHADE_LOCKED` on a real change only — autosave resends unchanged values, which must stay a no-op):
- Clinic (Treatment provider): unsent, or sent until any step in the outsource tree is completed.
- Lab: `LAB_INTERNAL` drafts via draft autosave; started via `PATCH /cases/:id/tooth-shade` until a current-round step in the tree is completed. Needs `TAB_CASES_EDIT`.
- Received `CLINIC_DISPATCH` and `LAB_OUTSOURCE` cases are read-only for the lab. Outsource copies the parent shade, and later parent edits update the children.
- **Full guide** (`ToothShadeGuide`, LTR tab order in every locale): Treatment editor under the type row for lab-dependent details, Cases create panel, and the case detail header (hidden there when read-only and empty). **Text only** elsewhere: Tasks grouped header (also the share page), Case Sheet PDF (`—` when empty).
- **Voice:** `toothShadeCode` field — never in `comment`. Lands only on a lab-dependent detail (or a lab case line).
- Exocad export does not map shade yet.

View File

@@ -47,10 +47,11 @@ Keep chrome identical: `BillingListToolbar`, outline labels, `AppMoneyInput`, eq
- Prefer `GET /billing/transactions` (merged rows). Optional `partyKind` + `partyId` filters server-side and returns signed `net` (RECEIPT +, PAYMENT −) for the footer.
- `BillingLedgerEntry` stores **system obligations only**. `GET /billing/party-report` unions those rows with patient/partner/staff cash for one party and date range. In this party-account view, RECEIPT is credit (reduces receivable) and PAYMENT is debit (reduces payable). Pending partner cash counts only for its recorder; accepted cash counts for both; rejected cash stays visible to both but counts only for its recorder.
- The Transactions table is cash-only until a party is selected. Selection swaps the same table to party-report rows (Time, Source, Reference, Amount, Actions) and puts the net directly below Amount; do not restore a report dialog/button. Row amounts are neutral with a compact Debit/Credit marker; only net is green/red. Case rows use origin-specific sources—Received case, Generated case, or Outsourced case—plus the matching origin badge. Received means a clinic dispatch (`CLINIC_DISPATCH`), the same origin Cases labels “From clinic.”
- An organization selection can print that same ledger. **Print statement** downloads an A4 PDF (oldest first, header and columns repeated, debit/credit/balance on the last page). A report that fits on one page stays on one page. The table is a bordered grid with row number, date, reference, and amount; debit/credit sits on that amount line. Source and note are not printed. The Persian table is RTL; the page header stays LTR. Persian cell text stays `direction: ltr` — the capture paints `rtl` backwards — and each cell’s text is shifted up 10px so Vazirmatn sits in the 27px row (table font 14px). The printed balance is `totals.net`. Pending and declined cash stay on the page and stay out of the totals, without a status note. The header matches the Case Sheet: organization name, the Nudentic lockup, and the phone (`issuer` on the party report), addressed to the selected org. There is no payment-note or bank block. Patients and staff do not get this button. The party report does not return a separate staff-compensation total; the card sums the preview rows.
- Cash rows expose edit metadata/allocations. Editing happens on the row: amount and note in the cells, allocations on the lines under that row. Patient and staff cash is editable by the org; partner cash only by its exact recorder. Party, direction, currency, posting date, and creator are immutable.
- Automatic sources are idempotent by `(organizationId, sourceType, sourceId)`: treatment Approve, case completion, monthly commission, and monthly salary.
- Case obligations are mirrored when every current-round task is `COMPLETED`: payer books show the destination as creditor; destination books show the payer as debtor. Send, Start, and outsource store `calculatedAmount` / `billedAmount` only. Reopening a step deletes that case’s rows. Stop/recall already do. A received case and an outsourced case notify the destination lab’s billing users in the same write that inserts the obligation. The link selects that payer on Transactions with no date filter.
- The open staff month is not stored. The party report appends commission earned from the month start through the report day, and fixed salary times the elapsed fraction of that month. Both count in the balance and the staff totals, and they disappear once the stored rows exist.
- The open staff month is not stored. The party report appends commission earned from the month start through the report day, and fixed salary times the elapsed fraction of that month. Both count in the balance, and they disappear once the stored rows exist. A null or zero `fixedMonthlySalary` creates no salary preview and no closed salary row. The staff card shows only that open month. **Show details** on the card, or on a commission row, calls `GET /billing/staff-income`. Salary rows have no details action. The response is commission only: jobs grouped by unit price (quantity × unit price, with a sum) plus one line per earning. A clinic line’s reference is the patient name; a lab line’s reference is the referring clinic and dentist. If the listed commission sum differs from the posted month, the panel says the hourly job has not caught up.
## Fee / commission editor
@@ -75,7 +76,7 @@ Keep chrome identical: `BillingListToolbar`, outline labels, `AppMoneyInput`, eq
- One sheet on the Commissions/Salary tab, beside **New commission schedule**. It lists the owner and every active member. `PUT /billing/staff-salaries` updates `Membership.fixedMonthlySalary` and does not create a ledger row or a new sheet.
- After the first save, a Staff salary section with one Edit row sits above Commission history. `Organization.staffSalaryUpdatedAt` is that marker.
- The hourly job writes a finished month only. Commission is that month's earnings. Salary is the full sheet amount, snapshotted once; a later edit does not change it. A month the server missed is closed on the next run with the rate on the sheet then. Rows are dated on the last day. The open month is a calculated preview only. Toman uses Jalali months; Dollar/Euro use Gregorian months.
- Staff summary subtotals include the closed rows in the date range and, while the month is open, the unsaved preview. Commission + fixed salary = gross. Cash affects net only. Staff cash remains `StaffPayment`.
- The staff card shows the unsaved open month only. Commission + fixed salary = gross. **Show details** lists the commission jobs and earning rows for that month, not the salary. Cash affects net only. Staff cash remains `StaffPayment`.
- The stored month-end salary is the full sheet amount. The open-month preview is that amount times days elapsed over days in the month. V1 has no attendance, bonus, or payroll-tax model.
## Deep links

View File

@@ -70,12 +70,14 @@ frontend/src/
**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. Migration `20261111233000_sheet_flag_and_subscription_courtesy` runs once: every existing seat and every non-null `trialEndsAt` gains 60 days (two 30-day subscription months). A date still in the future grows from itself; a date already past grows from that deploy. It does not insert seats or charge rows, and later deploys must not repeat it. 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**. Automatic `BillingLedgerEntry` obligations come from treatment Approve, a case whose every current-round task is done, and staff commission plus fixed salary after each month ends; Toman uses Jalali months, Dollar/Euro Gregorian. Send stores the case price and does not post the debt. Selecting a party swaps the cash table to an inline obligation+cash ledger with signed amount/net; selected staff also show commission, fixed salary, and gross, including an unsaved preview of the open month through the report day. Partner cash remains shared Accept/Decline; rejected rows stay visible to both but count only for the recorder. Only the exact recorder can edit shared cash, and edits reset acknowledgement. Salary is one editable sheet on Commissions/Salary for the owner and active members; editing it does not change a closed month. Salary and commission may both apply. The stored month-end salary is the full amount; the open-month preview is that amount times the days elapsed. There is no attendance model. Price sheets may hide unpriced prosthesis types; existing fee and commission sheets deploy with that box unchecked, and commission sheets cannot turn it on. An active flagged lab sheet blocks clinic dispatch for unsupported jobs. If the flag is off, an unpriced case keeps an empty fee until the destination lab sets it. The pending obligation is created when every step is done. A received or outsourced case notifies that lab’s billing users then, and the link selects the payer on Transactions. Collapsed workflow prices and hidden legacy lines remain preserved. Money inputs: `AppMoneyInput`. 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**. Automatic `BillingLedgerEntry` obligations come from treatment Approve, a case whose every current-round task is done, and staff commission plus fixed salary after each month ends; Toman uses Jalali months, Dollar/Euro Gregorian. Send stores the case price and does not post the debt. Selecting a party swaps the cash table to an inline obligation+cash ledger with signed amount/net. Selected staff show one open-month card (commission, fixed salary, and gross through the report day). Show details is that month’s commission by job and unit price; salary stays a ledger row. An organization can print the same ledger as a bordered statement (number, date, reference, amount). The Persian table is RTL; its cell text stays LTR and is shifted up so the glyphs sit in the row. Partner cash remains shared Accept/Decline; rejected rows stay visible to both but count only for the recorder. Only the exact recorder can edit shared cash, and edits reset acknowledgement. Salary is one editable sheet on Commissions/Salary for the owner and active members; editing it does not change a closed month. Salary and commission may both apply. The stored month-end salary is the full amount; the open-month preview is that amount times the days elapsed. There is no attendance model. Price sheets may hide unpriced prosthesis types; existing fee and commission sheets deploy with that box unchecked, and commission sheets cannot turn it on. An active flagged lab sheet blocks clinic dispatch for unsupported jobs. If the flag is off, an unpriced case keeps an empty fee until the destination lab sets it. The pending obligation is created when every step is done. A received or outsourced case notifies that lab’s billing users then, and the link selects the payer on Transactions. Collapsed workflow prices and hidden legacy lines remain preserved. Money inputs: `AppMoneyInput`. 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 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. Monolithic zirconia and PFZ are Coping, a pontic is a reduced pontic, and the opposite tooth is an antagonist, only when that pair already exists in the file. A titanium custom abutment on that Coping copies ImplantType CustomAbutment from a saved tooth of the same pair when the file already has it. The connect dialog says the feature is experimental, asks for a manual backup, says Nudentic is not responsible, and says the user uses it on their own. A one-word clinic name still fills Client, and an empty clinic name still writes the case. A patient name that cannot fill Name is not written, and the toast says so. Each new case gets the next tray for that client. After the write, the user can grant the CAD-Data folder so the empty project directory is created. A failed case rolls back. There is no Local database tab. See `.cursor/skills/lab-cases/SKILL.md` and `.cursor/skills/lab-case-share-link/SKILL.md`.
**Tooth shade (quick ref):** One optional VITA shade per lab case (`LabCase.toothShadeCode`, nullable; historical shades stay in notes). Full guide in Treatment (lab-dependent) and Cases create/detail; text only on Tasks, share page, and Case Sheet. Locks once any step in the outsource tree is completed; an unchanged resend is a no-op. See `.cursor/rules/tooth-shade.mdc`.
**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.
- **Lab:** view with Cases or Tasks access; edit task status only with Tasks edit + assignee rules; comments if Cases or Tasks edit.

View File

@@ -17,6 +17,41 @@ export type TreatmentTypeSeed = {
availableInTreatment?: boolean;
};
export type ToothShadeSeed = {
code: string;
family: '0M' | 'A' | 'B' | 'C' | 'D';
sortOrder: number;
hex: string;
};
/**
* VITA Classical A1–D4 + Bleached 0M1–0M3 (exact codes).
* No universal official hex/RGB exists for these shades (VITA does not publish one;
* spectrophotometric Lab→sRGB conversions look muddy on screen). Swatches are
* approximate warm enamel tones for UI only — not clinical color matching.
*/
export const TOOTH_SHADES: readonly ToothShadeSeed[] = [
{ code: '0M1', family: '0M', sortOrder: 1, hex: '#F7F4EF' },
{ code: '0M2', family: '0M', sortOrder: 2, hex: '#F4EFE6' },
{ code: '0M3', family: '0M', sortOrder: 3, hex: '#F0E9DA' },
{ code: 'A1', family: 'A', sortOrder: 4, hex: '#F1E6D3' },
{ code: 'A2', family: 'A', sortOrder: 5, hex: '#E8D5B7' },
{ code: 'A3', family: 'A', sortOrder: 6, hex: '#DCC19A' },
{ code: 'A3.5', family: 'A', sortOrder: 7, hex: '#D0B08A' },
{ code: 'A4', family: 'A', sortOrder: 8, hex: '#C49A72' },
{ code: 'B1', family: 'B', sortOrder: 9, hex: '#F0E8D4' },
{ code: 'B2', family: 'B', sortOrder: 10, hex: '#E5D6B5' },
{ code: 'B3', family: 'B', sortOrder: 11, hex: '#D9C49A' },
{ code: 'B4', family: 'B', sortOrder: 12, hex: '#CDB07E' },
{ code: 'C1', family: 'C', sortOrder: 13, hex: '#E4DDD0' },
{ code: 'C2', family: 'C', sortOrder: 14, hex: '#D5CBBC' },
{ code: 'C3', family: 'C', sortOrder: 15, hex: '#C4B8A6' },
{ code: 'C4', family: 'C', sortOrder: 16, hex: '#B0A28F' },
{ code: 'D2', family: 'D', sortOrder: 17, hex: '#E2D6C4' },
{ code: 'D3', family: 'D', sortOrder: 18, hex: '#D4C4AD' },
{ code: 'D4', family: 'D', sortOrder: 19, hex: '#C5B094' },
] as const;
export const TREATMENT_TYPES: readonly TreatmentTypeSeed[] = [
{ code: 'restoration', labDependent: false, sortOrder: 1 },
{ code: 'specialized_restoration', labDependent: false, sortOrder: 2 },

View File

@@ -0,0 +1,38 @@
-- Tooth shade catalog + optional case-level shade on lab_cases
CREATE TABLE "tooth_shades" (
"code" TEXT NOT NULL,
"family" TEXT NOT NULL,
"sortOrder" INTEGER NOT NULL DEFAULT 0,
"hex" TEXT NOT NULL,
"isActive" BOOLEAN NOT NULL DEFAULT true,
CONSTRAINT "tooth_shades_pkey" PRIMARY KEY ("code")
);
INSERT INTO "tooth_shades" ("code", "family", "sortOrder", "hex", "isActive") VALUES
('0M1', '0M', 1, '#F7F4EF', true),
('0M2', '0M', 2, '#F4EFE6', true),
('0M3', '0M', 3, '#F0E9DA', true),
('A1', 'A', 4, '#F1E6D3', true),
('A2', 'A', 5, '#E8D5B7', true),
('A3', 'A', 6, '#DCC19A', true),
('A3.5', 'A', 7, '#D0B08A', true),
('A4', 'A', 8, '#C49A72', true),
('B1', 'B', 9, '#F0E8D4', true),
('B2', 'B', 10, '#E5D6B5', true),
('B3', 'B', 11, '#D9C49A', true),
('B4', 'B', 12, '#CDB07E', true),
('C1', 'C', 13, '#E4DDD0', true),
('C2', 'C', 14, '#D5CBBC', true),
('C3', 'C', 15, '#C4B8A6', true),
('C4', 'C', 16, '#B0A28F', true),
('D2', 'D', 17, '#E2D6C4', true),
('D3', 'D', 18, '#D4C4AD', true),
('D4', 'D', 19, '#C5B094', true);
ALTER TABLE "lab_cases" ADD COLUMN "toothShadeCode" TEXT;
ALTER TABLE "lab_cases" ADD CONSTRAINT "lab_cases_toothShadeCode_fkey" FOREIGN KEY ("toothShadeCode") REFERENCES "tooth_shades"("code") ON DELETE SET NULL ON UPDATE CASCADE;
CREATE INDEX "lab_cases_toothShadeCode_idx" ON "lab_cases"("toothShadeCode");

View File

@@ -301,6 +301,8 @@ model LabCase {
origin LabCaseOrigin @default(CLINIC_DISPATCH)
/// Optional code from an external lab app (e.g. exocad) for print/matching.
externalCode String?
/// Optional VITA-style tooth shade code (ToothShade.code). Case-level, not per tooth.
toothShadeCode String?
accessToken String? @unique
referringClinicName String?
referringDentistName String?
@@ -309,6 +311,7 @@ model LabCase {
partnerClinicOrganizationId String?
treatment Treatment? @relation(fields: [treatmentId], references: [id], onDelete: Cascade)
toothShade ToothShade? @relation(fields: [toothShadeCode], references: [code], onDelete: SetNull)
partnerClinic Organization? @relation("LabCasePartnerClinic", fields: [partnerClinicOrganizationId], references: [id], onDelete: SetNull)
parentLabCase LabCase? @relation("LabCaseOutsourceParent", fields: [parentLabCaseId], references: [id], onDelete: SetNull)
childLabCases LabCase[] @relation("LabCaseOutsourceParent")
@@ -334,6 +337,7 @@ model LabCase {
@@index([partnerClinicOrganizationId])
@@index([parentLabCaseId])
@@index([listedAt])
@@index([toothShadeCode])
@@map("lab_cases")
}
@@ -412,6 +416,21 @@ model TreatmentType {
@@map("treatment_types")
}
/// Static VITA Classical + bleach shade guide. Labels are the codes themselves.
model ToothShade {
code String @id
/// Guide family: 0M | A | B | C | D
family String
sortOrder Int @default(0)
/// Approximate tab fill for the shade guide UI.
hex String
isActive Boolean @default(true)
labCases LabCase[]
@@map("tooth_shades")
}
enum CatalogEntityKind {
TREATMENT_TYPE
PROSTHESIS_TYPE

View File

@@ -8,6 +8,7 @@ import {
LEGACY_TREATMENT_TYPES,
LAB_WORKFLOW_STEPS,
PROSTHESIS_TYPES,
TOOTH_SHADES,
CATALOG_TRANSLATIONS,
buildProsthesisStepCodes,
} from './catalog-seed-data';
@@ -159,6 +160,26 @@ async function main() {
}
console.log('✅ Seeded treatment type catalog');
for (const shade of TOOTH_SHADES) {
await prisma.toothShade.upsert({
where: { code: shade.code },
update: {
family: shade.family,
sortOrder: shade.sortOrder,
hex: shade.hex,
isActive: true,
},
create: {
code: shade.code,
family: shade.family,
sortOrder: shade.sortOrder,
hex: shade.hex,
isActive: true,
},
});
}
console.log('✅ Seeded tooth shade catalog');
for (const step of LAB_WORKFLOW_STEPS) {
await prisma.labWorkflowStep.upsert({
where: { code: step.code },

View File

@@ -232,6 +232,12 @@ export function buildAdminResources(prisma: PrismaService): AdminResource[] {
navigation: { name: 'Catalog', icon: 'Catalog' },
actions: catalogActions,
}),
resource(prisma, 'ToothShade', {
navigation: { name: 'Catalog', icon: 'Catalog' },
// Codes are stored on lab cases; edit hex/order/active only.
properties: { code: { isDisabled: true } },
actions: catalogActions,
}),
resource(prisma, 'BillingSheet', {
navigation: { name: 'Billing', icon: 'CreditCard' },

View File

@@ -19,6 +19,7 @@ import { TasksModule } from './modules/tasks/tasks.module';
import { TreatmentCatalogModule } from './modules/treatment-catalog/treatment-catalog.module';
import { CatalogModule } from './modules/catalog/catalog.module';
import { ProsthesisCatalogModule } from './modules/prosthesis-catalog/prosthesis-catalog.module';
import { ToothShadeCatalogModule } from './modules/tooth-shade-catalog/tooth-shade-catalog.module';
import { LabCaseCommentsModule } from './modules/lab-case-comments/lab-case-comments.module';
import { TodayModule } from './modules/today/today.module';
import { NotificationsModule } from './modules/notifications/notifications.module';
@@ -55,6 +56,7 @@ import { SubscriptionWriteInterceptor } from './modules/subscription/subscriptio
CatalogModule,
TreatmentCatalogModule,
ProsthesisCatalogModule,
ToothShadeCatalogModule,
AuthModule,
PatientsModule,
AppointmentsModule,

View File

@@ -159,6 +159,8 @@ export const ErrorCode = {
TREATMENT_CASE_ALREADY_SENT: 'TREATMENT_CASE_ALREADY_SENT',
TREATMENT_DUE_DATE_LOCKED: 'TREATMENT_DUE_DATE_LOCKED',
TREATMENT_INVALID_DUE_DATE: 'TREATMENT_INVALID_DUE_DATE',
TOOTH_SHADE_INVALID: 'TOOTH_SHADE_INVALID',
TOOTH_SHADE_LOCKED: 'TOOTH_SHADE_LOCKED',
TREATMENT_DETAIL_KEY_REQUIRED: 'TREATMENT_DETAIL_KEY_REQUIRED',
TREATMENT_FILE_REQUIRED: 'TREATMENT_FILE_REQUIRED',
TREATMENT_ATTACHMENT_NOT_FOUND: 'TREATMENT_ATTACHMENT_NOT_FOUND',

View File

@@ -26,6 +26,7 @@ import {
ListPaymentsQueryDto,
PartyReportQueryDto,
PartySearchQueryDto,
StaffIncomeQueryDto,
SaveStaffSalarySheetDto,
UpdateObligationAmountDto,
UpdatePaymentDto,
@@ -150,6 +151,21 @@ export class BillingController {
return this.billingService.listTransactions(req.user.id, organizationId, query);
}
@Get('staff-income')
@ApiOperation({ summary: 'Commission jobs and earning lines for one staff month' })
staffIncome(
@Query() query: StaffIncomeQueryDto,
@Req() req: { user: { id: string; organizationId?: string; language?: string } },
) {
const organizationId = this.billingService.getOrganizationIdFromUser(req.user);
return this.billingService.staffIncome(
req.user.id,
organizationId,
query,
req.user.language,
);
}
@Get('party-report')
@ApiOperation({ summary: 'Unified debit/credit report for one patient, staff member, or org' })
partyReport(

View File

@@ -88,7 +88,14 @@ import {
sharedCashCountsInPartyReport,
signedPartyCashAmount,
} from './party-ledger';
import { SaveStaffSalarySheetDto } from './dto/billing-payment.dto';
import { SaveStaffSalarySheetDto, StaffIncomeQueryDto } from './dto/billing-payment.dto';
import {
explainStaffSalary,
groupCommissionEarnings,
staffIncomeEarningWindow,
staffIncomeReportDay,
sumCommissionEarnings,
} from './staff-income';
import {
finishedStaffBillingPeriods,
previousStaffBillingPeriod,
@@ -793,7 +800,7 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
? BillingLedgerPartyKind.STAFF
: BillingLedgerPartyKind.ORGANIZATION;
const occurredAt = occurredAtWhere(query);
const [obligations, cash] = await Promise.all([
const [obligations, cash, issuerOrg] = await Promise.all([
this.prisma.billingLedgerEntry.findMany({
where: {
organizationId,
@@ -810,6 +817,10 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
partyId: query.partyId,
unlimited: true,
}),
this.prisma.organization.findUnique({
where: { id: organizationId },
select: { name: true, phone: true },
}),
]);
const treatmentIds = obligations
@@ -942,26 +953,6 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
const net = rows
.filter((row) => row.countsInTotals && row.signedAmount != null)
.reduce((sum, row) => sum + Number(row.signedAmount ?? 0), 0);
const commissionSubtotal =
query.partyKind === 'staff'
? rows
.filter(
(row) =>
row.lineKind === 'OBLIGATION' &&
row.sourceType === BillingObligationSourceType.STAFF_COMMISSION_MONTH,
)
.reduce((sum, row) => sum + Number(row.amount ?? 0), 0)
: 0;
const fixedSalarySubtotal =
query.partyKind === 'staff'
? rows
.filter(
(row) =>
row.lineKind === 'OBLIGATION' &&
row.sourceType === BillingObligationSourceType.STAFF_SALARY_MONTH,
)
.reduce((sum, row) => sum + Number(row.amount ?? 0), 0)
: 0;
return {
success: true as const,
data: rows,
@@ -970,16 +961,137 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
credit: roundBillingAmount(credit).toFixed(2),
net: roundSignedBillingAmount(net).toFixed(2),
},
staffCompensation:
query.partyKind === 'staff'
? {
commission: roundBillingAmount(commissionSubtotal).toFixed(2),
fixedSalary: roundBillingAmount(fixedSalarySubtotal).toFixed(2),
gross: roundBillingAmount(
commissionSubtotal + fixedSalarySubtotal,
).toFixed(2),
}
: null,
issuer: {
name: issuerOrg?.name ?? '',
phone: issuerOrg?.phone ?? null,
},
};
}
/** Commission jobs and earning lines behind one staff month. */
async staffIncome(
actorUserId: string,
organizationId: string,
query: StaffIncomeQueryDto,
localeInput?: string | null,
) {
await this.assertCanRead(actorUserId, organizationId);
await this.assertStaffInOrg(organizationId, query.userId);
const currency = await this.staffBillingCurrency(organizationId);
const period = staffBillingPeriodFromKey(query.periodKey);
if (!period || !staffPeriodKeyMatchesCurrency(period.key, currency)) {
throw new AppException(ErrorCode.BILLING_CURRENCY_INVALID, HttpStatus.BAD_REQUEST);
}
const now = new Date();
const reportDay = staffIncomeReportDay(now, query.to);
const current = staffBillingPeriodForDate(now, currency);
const open = period.key === current.key;
const window = staffIncomeEarningWindow({ period, open, reportDay });
const commissionId = `${query.userId}:${period.key}:commission`;
const [earnings, ledger, orgType] = await Promise.all([
window
? this.prisma.commissionEarning.findMany({
where: {
organizationId,
userId: query.userId,
earnedAt: { gte: window.from, lt: window.until },
},
orderBy: [{ earnedAt: 'asc' }, { id: 'asc' }],
select: {
id: true,
catalogCode: true,
qty: true,
baseAmount: true,
earnedAmount: true,
earnedAt: true,
labCase: {
select: { referringClinicName: true, referringDentistName: true },
},
treatment: {
select: { patient: { select: { firstName: true, lastName: true } } },
},
},
})
: Promise.resolve([]),
this.prisma.billingLedgerEntry.findMany({
where: {
organizationId,
partyKind: BillingLedgerPartyKind.STAFF,
partyId: query.userId,
sourceType: BillingObligationSourceType.STAFF_COMMISSION_MONTH,
sourceId: commissionId,
},
select: { amount: true },
}),
getOrganizationTypeName(this.prisma, organizationId),
]);
const amounts = earnings.map((row) => ({
catalogCode: row.catalogCode,
qty: Number(row.qty),
unitAmount: Number(row.baseAmount),
earnedAmount: Number(row.earnedAmount),
}));
const locale = normalizeCatalogLocale(localeInput);
const labelKind =
orgType === 'CLINIC'
? CatalogEntityKind.TREATMENT_TYPE
: CatalogEntityKind.LAB_WORKFLOW_STEP;
const labels = await this.catalogLabels.resolveLabels(
labelKind,
amounts.map((row) => row.catalogCode),
locale,
);
const labelFor = (code: string) => labels.get(code) ?? formatCodeAsLabel(code);
const postedCommission = ledger[0];
const listed = sumCommissionEarnings(amounts);
return {
success: true as const,
data: {
period: {
key: period.key,
label: period.label,
calendar: period.calendar,
start: period.start.toISOString().slice(0, 10),
end: staffPeriodLastDay(period).toISOString().slice(0, 10),
},
open,
reportDay: open ? reportDay.toISOString().slice(0, 10) : null,
commission: {
postedAmount:
postedCommission?.amount == null
? null
: roundBillingAmount(Number(postedCommission.amount)).toFixed(2),
listedAmount: listed.toFixed(2),
groups: groupCommissionEarnings(amounts)
.map((group) => ({
catalogCode: group.code,
label: labelFor(group.code),
unitAmount: group.unitAmount.toFixed(2),
qty: group.qty.toFixed(2),
amount: group.amount.toFixed(2),
}))
.sort(
(a, b) =>
a.label.localeCompare(b.label) ||
a.unitAmount.localeCompare(b.unitAmount) ||
a.catalogCode.localeCompare(b.catalogCode),
),
lines: earnings.map((row) => ({
id: row.id,
earnedAt: row.earnedAt.toISOString(),
catalogCode: row.catalogCode,
label: labelFor(row.catalogCode),
qty: Number(row.qty).toFixed(2),
unitAmount: roundBillingAmount(Number(row.baseAmount)).toFixed(2),
earnedAmount: roundBillingAmount(Number(row.earnedAmount)).toFixed(2),
reference: staffIncomeReference(orgType, row),
})),
},
},
};
}
@@ -992,17 +1104,12 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
) {
const currency = await this.staffBillingCurrency(organizationId);
const now = new Date();
const today = dateOnlyUtc(now.toISOString().slice(0, 10));
let reportDay = today;
if (query.to) {
const to = dateOnlyUtc(query.to);
if (to.getTime() < reportDay.getTime()) reportDay = to;
}
const reportDay = staffIncomeReportDay(now, query.to);
if (query.from && dateOnlyUtc(query.from).getTime() > reportDay.getTime()) return [];
const period = staffBillingPeriodForDate(now, currency);
const window = staffIncomeEarningWindow({ period, open: true, reportDay });
const span = staffPeriodElapsedDays(period, reportDay);
if (!span) return [];
const through = new Date(reportDay.getTime() + 24 * 60 * 60 * 1000);
if (!window || !span) return [];
const occurredAt = reportDay.toISOString();
const rows: Array<{
@@ -1035,7 +1142,7 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
where: {
organizationId,
userId,
earnedAt: { gte: period.start, lt: through },
earnedAt: { gte: window.from, lt: window.until },
},
_sum: { earnedAmount: true },
});
@@ -1058,20 +1165,22 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
where: { userId_organizationId: { userId, organizationId } },
select: { fixedMonthlySalary: true },
});
const salary = roundBillingAmount(Number(membership?.fixedMonthlySalary ?? 0));
if (salary > 0) {
const amount = roundBillingAmount((salary * span.elapsed) / span.days);
if (amount > 0) {
rows.push(
this.staffPreviewRow(
BillingObligationSourceType.STAFF_SALARY_MONTH,
salaryId,
amount,
period.key,
occurredAt,
),
);
}
const salary = explainStaffSalary({
open: true,
postedAmount: null,
monthlyRate: roundBillingAmount(Number(membership?.fixedMonthlySalary ?? 0)),
elapsed: span,
});
if (salary.amount) {
rows.push(
this.staffPreviewRow(
BillingObligationSourceType.STAFF_SALARY_MONTH,
salaryId,
Number(salary.amount),
period.key,
occurredAt,
),
);
}
}
return rows;
@@ -3639,6 +3748,27 @@ function staffPeriodReference(sourceId: string): string {
return '';
}
function staffIncomeReference(
orgType: string,
row: {
labCase: {
referringClinicName: string | null;
referringDentistName: string | null;
} | null;
treatment: { patient: { firstName: string; lastName: string } } | null;
},
): string {
if (orgType === 'LAB') {
return [row.labCase?.referringClinicName, row.labCase?.referringDentistName]
.map((part) => part?.trim() ?? '')
.filter((part) => part.length > 0)
.join(' · ');
}
const patient = row.treatment?.patient;
if (!patient) return '';
return `${patient.firstName} ${patient.lastName}`.trim();
}
function parseMoney(value: string): number {
const amount = Number(value.trim().replace(/,/g, ''));
if (!Number.isFinite(amount) || amount < 0) {

View File

@@ -130,6 +130,19 @@ export class ListPaymentsQueryDto {
partyId?: string;
}
export class StaffIncomeQueryDto {
@IsUUID('all', { message: ErrorCode.BILLING_STAFF_INVALID })
userId: string;
@Matches(/^(J|G):-?\d{1,4}-\d{2}$/, { message: ErrorCode.BILLING_CURRENCY_INVALID })
periodKey: string;
@IsOptional()
@IsString()
@Matches(/^\d{4}-\d{2}-\d{2}$/)
to?: string;
}
export class PartyReportQueryDto {
@IsIn(['patient', 'staff', 'org'], { message: ErrorCode.BILLING_PARTY_INVALID })
partyKind: 'patient' | 'staff' | 'org';

View File

@@ -0,0 +1,84 @@
import { staffBillingPeriodForDate } from './staff-billing-period';
import {
explainStaffSalary,
groupCommissionEarnings,
staffIncomeEarningWindow,
staffIncomeReportDay,
} from './staff-income';
describe('staff income detail', () => {
const period = staffBillingPeriodForDate(new Date('2026-11-15T00:00:00.000Z'), 'DOLLAR');
it('stops the open month on the report day', () => {
const reportDay = staffIncomeReportDay(new Date('2026-11-22T15:00:00.000Z'), '2026-11-10');
expect(reportDay.toISOString()).toBe('2026-11-10T00:00:00.000Z');
const window = staffIncomeEarningWindow({ period, open: true, reportDay });
expect(window).toEqual({
from: period.start,
until: new Date('2026-11-11T00:00:00.000Z'),
});
});
it('uses the whole period once the month is closed', () => {
const reportDay = staffIncomeReportDay(new Date('2026-12-02T00:00:00.000Z'));
expect(
staffIncomeEarningWindow({ period, open: false, reportDay }),
).toEqual({ from: period.start, until: period.end });
});
it('returns no open-month rows when the report day is outside that month', () => {
const reportDay = staffIncomeReportDay(new Date('2026-11-22T00:00:00.000Z'), '2026-10-01');
expect(staffIncomeEarningWindow({ period, open: true, reportDay })).toBeNull();
});
it('groups commission rows by job and unit price', () => {
expect(
groupCommissionEarnings([
{ catalogCode: 'milling_dry_sinter', qty: 2, unitAmount: 15, earnedAmount: 30 },
{ catalogCode: 'milling_dry_sinter', qty: 1, unitAmount: 15, earnedAmount: 15 },
{ catalogCode: 'milling_dry_sinter', qty: 1, unitAmount: 20, earnedAmount: 20 },
{ catalogCode: 'stain_glaze', qty: 1, unitAmount: 8, earnedAmount: 8 },
]),
).toEqual([
{ code: 'milling_dry_sinter', unitAmount: 15, qty: 3, amount: 45 },
{ code: 'milling_dry_sinter', unitAmount: 20, qty: 1, amount: 20 },
{ code: 'stain_glaze', unitAmount: 8, qty: 1, amount: 8 },
]);
});
it('keeps a closed salary at the posted amount when the sheet rate later changes', () => {
expect(
explainStaffSalary({
open: false,
postedAmount: 3000,
monthlyRate: 9000,
elapsed: { elapsed: 10, days: 30 },
}),
).toEqual({
kind: 'closed',
monthlyRate: null,
elapsedDays: null,
daysInMonth: null,
amount: '3000.00',
postedAmount: '3000.00',
});
});
it('prorates the open month from the current rate and the days elapsed', () => {
expect(
explainStaffSalary({
open: true,
postedAmount: null,
monthlyRate: 3000,
elapsed: { elapsed: 10, days: 30 },
}),
).toEqual({
kind: 'preview',
monthlyRate: '3000.00',
elapsedDays: 10,
daysInMonth: 30,
amount: '1000.00',
postedAmount: null,
});
});
});

View File

@@ -0,0 +1,163 @@
import { roundBillingAmount } from './calculate-amounts';
import {
staffPeriodElapsedDays,
type StaffBillingPeriod,
} from './staff-billing-period';
export type StaffIncomeWindow = {
from: Date;
/** Exclusive upper bound, matching `earnedAt < until`. */
until: Date;
};
function utcDay(date: Date): Date {
return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
}
/** Today, or `to` when the report ends earlier. Same cutoff as the open-month preview. */
export function staffIncomeReportDay(now: Date, to?: string): Date {
const today = utcDay(now);
if (!to) return today;
const end = new Date(`${to}T00:00:00.000Z`);
if (Number.isNaN(end.getTime())) return today;
return end.getTime() < today.getTime() ? end : today;
}
/**
* Open month: earnings from the period start through the report day.
* Closed month: the whole period. A report day outside the open period yields no rows.
*/
export function staffIncomeEarningWindow(args: {
period: StaffBillingPeriod;
open: boolean;
reportDay: Date;
}): StaffIncomeWindow | null {
if (!args.open) {
return { from: args.period.start, until: args.period.end };
}
if (!staffPeriodElapsedDays(args.period, args.reportDay)) return null;
return {
from: args.period.start,
until: new Date(args.reportDay.getTime() + 24 * 60 * 60 * 1000),
};
}
export type StaffSalaryExplanation = {
kind: 'preview' | 'closed' | 'none';
monthlyRate: string | null;
elapsedDays: number | null;
daysInMonth: number | null;
amount: string | null;
postedAmount: string | null;
};
function money(value: number): string {
return roundBillingAmount(value).toFixed(2);
}
/**
* A closed month keeps the posted amount. The rate on the sheet today is not
* the rate that was saved, so the day math stays empty.
* An open month with a stored row uses that row, matching the ledger.
*/
export function explainStaffSalary(args: {
open: boolean;
postedAmount: number | null;
monthlyRate: number;
elapsed: { elapsed: number; days: number } | null;
}): StaffSalaryExplanation {
const posted =
args.postedAmount != null && args.postedAmount > 0
? money(args.postedAmount)
: null;
if (!args.open || posted) {
if (!posted) {
return {
kind: 'none',
monthlyRate: null,
elapsedDays: null,
daysInMonth: null,
amount: null,
postedAmount: null,
};
}
return {
kind: 'closed',
monthlyRate: null,
elapsedDays: null,
daysInMonth: null,
amount: posted,
postedAmount: posted,
};
}
if (!args.elapsed || args.monthlyRate <= 0) {
return {
kind: 'none',
monthlyRate: args.monthlyRate > 0 ? money(args.monthlyRate) : null,
elapsedDays: args.elapsed?.elapsed ?? null,
daysInMonth: args.elapsed?.days ?? null,
amount: null,
postedAmount: null,
};
}
const amount = roundBillingAmount(
(args.monthlyRate * args.elapsed.elapsed) / args.elapsed.days,
);
if (amount <= 0) {
return {
kind: 'none',
monthlyRate: money(args.monthlyRate),
elapsedDays: args.elapsed.elapsed,
daysInMonth: args.elapsed.days,
amount: null,
postedAmount: null,
};
}
return {
kind: 'preview',
monthlyRate: money(args.monthlyRate),
elapsedDays: args.elapsed.elapsed,
daysInMonth: args.elapsed.days,
amount: money(amount),
postedAmount: null,
};
}
export type CommissionEarningAmount = {
catalogCode: string;
qty: number;
unitAmount: number;
earnedAmount: number;
};
export function sumCommissionEarnings(lines: readonly CommissionEarningAmount[]): number {
return roundBillingAmount(lines.reduce((sum, line) => sum + line.earnedAmount, 0));
}
/** One row per job and unit price. Amount is quantity times that price. */
export function groupCommissionEarnings(lines: readonly CommissionEarningAmount[]): Array<{
code: string;
unitAmount: number;
qty: number;
amount: number;
}> {
const groups = new Map<string, { code: string; unitAmount: number; qty: number }>();
for (const line of lines) {
const unitAmount = roundBillingAmount(line.unitAmount);
const key = `${line.catalogCode}\0${unitAmount.toFixed(2)}`;
const current = groups.get(key) ?? { code: line.catalogCode, unitAmount, qty: 0 };
current.qty += line.qty;
groups.set(key, current);
}
return [...groups.values()].map((group) => {
const qty = roundBillingAmount(group.qty);
return {
code: group.code,
unitAmount: group.unitAmount,
qty,
amount: roundBillingAmount(qty * group.unitAmount),
};
});
}

View File

@@ -25,6 +25,7 @@ import {
ListLabCasesDto,
UpdateLabCaseImportantDto,
UpdateLabCaseExternalCodeDto,
UpdateLabCaseToothShadeDto,
AssignLabCaseTaskDto,
CreateLabInternalCaseDto,
UpdateLabInternalCaseDto,
@@ -252,6 +253,17 @@ export class CasesController {
return this.casesService.setCaseExternalCode(id, dto, organizationId, req.user.id, req.user.language);
}
@Patch(':id/tooth-shade')
@ApiOperation({ summary: 'Set or clear the optional tooth shade for a lab-origin case' })
setCaseToothShade(
@Param('id') id: string,
@Body() dto: UpdateLabCaseToothShadeDto,
@Req() req,
) {
const organizationId = this.casesService.getOrganizationIdFromUser(req.user);
return this.casesService.setCaseToothShade(id, dto, organizationId, req.user.id, req.user.language);
}
@Patch(':caseId/tasks/:taskId/assign')
@ApiOperation({ summary: 'Assign or unassign a task to lab staff' })
assignTask(

View File

@@ -3,6 +3,7 @@ import { PrismaService } from '../../../prisma/prisma.service';
import { LabOrgGuard } from '../../common/guards/lab-org.guard';
import { NotificationsModule } from '../notifications/notifications.module';
import { ProsthesisCatalogModule } from '../prosthesis-catalog/prosthesis-catalog.module';
import { ToothShadeCatalogModule } from '../tooth-shade-catalog/tooth-shade-catalog.module';
import { TasksModule } from '../tasks/tasks.module';
import { CatalogModule } from '../catalog/catalog.module';
import { LabCaseCommentsModule } from '../lab-case-comments/lab-case-comments.module';
@@ -14,7 +15,16 @@ import { LabCaseAccessController } from './lab-case-access.controller';
import { LabCaseAccessService } from './lab-case-access.service';
@Module({
imports: [ProsthesisCatalogModule, NotificationsModule, TasksModule, CatalogModule, LabCaseCommentsModule, BillingModule, SubscriptionModule],
imports: [
ProsthesisCatalogModule,
ToothShadeCatalogModule,
NotificationsModule,
TasksModule,
CatalogModule,
LabCaseCommentsModule,
BillingModule,
SubscriptionModule,
],
controllers: [LabCaseAccessController, CasesController],
providers: [CasesService, LabCaseAccessService, PrismaService, LabOrgGuard],
exports: [CasesService, LabCaseAccessService],

View File

@@ -19,8 +19,18 @@ import {
normalizeCatalogLocale,
} from '../catalog/catalog-label.service';
import { ProsthesisCatalogService } from '../prosthesis-catalog/prosthesis-catalog.service';
import { ToothShadeCatalogService } from '../tooth-shade-catalog/tooth-shade-catalog.service';
import { normalizeTeeth } from '../treatments/treatment.utils';
import { ListLabCasesDto, UpdateLabCaseImportantDto, UpdateLabCaseExternalCodeDto, AssignLabCaseTaskDto, CreateLabInternalCaseDto, UpdateLabInternalCaseDto, OutsourceLabCaseDto } from './dto/cases.dto';
import {
ListLabCasesDto,
UpdateLabCaseImportantDto,
UpdateLabCaseExternalCodeDto,
UpdateLabCaseToothShadeDto,
AssignLabCaseTaskDto,
CreateLabInternalCaseDto,
UpdateLabInternalCaseDto,
OutsourceLabCaseDto,
} from './dto/cases.dto';
import { generateLabCaseTasks } from './lab-case-task.generator';
import {
isLabCaseOverdue,
@@ -65,6 +75,7 @@ import {
import {
deleteOutsourceDescendants,
listOutsourceDescendantIds,
outsourceTreeHasCompletedTask,
} from './lab-case-outsource.tree';
function dedupeToothJobs<
@@ -159,6 +170,7 @@ export class CasesService {
constructor(
private readonly prisma: PrismaService,
private readonly prosthesisCatalog: ProsthesisCatalogService,
private readonly toothShadeCatalog: ToothShadeCatalogService,
private readonly catalogLabels: CatalogLabelService,
private readonly labCaseActivity: LabCaseActivityService,
private readonly userNotifications: UserNotificationService,
@@ -469,6 +481,8 @@ export class CasesService {
await this.assertCanEditCases(actorUserId, labOrganizationId);
await this.assertPartnerClinic(dto.partnerClinicOrganizationId, labOrganizationId);
const toothShadeCode = await this.toothShadeCatalog.normalize(dto.toothShadeCode);
const created = await this.prisma.labCase.create({
data: {
origin: LabCaseOrigin.LAB_INTERNAL,
@@ -479,6 +493,7 @@ export class CasesService {
patientDisplayMobile: dto.patientDisplayMobile?.trim() || null,
partnerClinicOrganizationId: dto.partnerClinicOrganizationId || null,
dueDate: dto.dueDate ? new Date(dto.dueDate) : null,
toothShadeCode,
sortOrder: 0,
},
include: labCaseListInclude,
@@ -512,6 +527,8 @@ export class CasesService {
await this.assertPartnerClinic(dto.partnerClinicOrganizationId, labOrganizationId);
const toothShadeCode = await this.toothShadeCatalog.normalizeOptional(dto.toothShadeCode);
const removedFiles: string[] = [];
const saved = await this.prisma.$transaction(async (tx) => {
await tx.labCase.update({
@@ -524,6 +541,7 @@ export class CasesService {
partnerClinicOrganizationId: dto.partnerClinicOrganizationId || null,
dueDate:
dto.dueDate === undefined ? undefined : dto.dueDate ? new Date(dto.dueDate) : null,
...(toothShadeCode !== undefined ? { toothShadeCode } : {}),
},
});
@@ -835,6 +853,7 @@ export class CasesService {
sentAt: new Date(),
accessToken: generateLabCaseAccessToken(),
dueDate: existing.dueDate,
toothShadeCode: existing.toothShadeCode,
referringClinicName: sender?.name.trim() || null,
referringDentistName: null,
patientDisplayName:
@@ -1442,6 +1461,56 @@ export class CasesService {
return { success: true, data: await this.mapLabCaseDetail(labCase, localeInput, labOrganizationId) };
}
/**
* Lab-origin shade edit: draft always, or started with no completed current-round step
* anywhere in its outsource tree. Outsource children take the new shade too.
* Clinic-dispatch and outsource receivers cannot change shade here.
*/
async setCaseToothShade(
labCaseId: string,
dto: UpdateLabCaseToothShadeDto,
labOrganizationId: string,
actorUserId: string,
localeInput?: string | null,
) {
await this.assertCanEditCases(actorUserId, labOrganizationId);
const existing = await this.prisma.labCase.findFirst({
where: {
id: labCaseId,
origin: LabCaseOrigin.LAB_INTERNAL,
destinationOrganizationId: labOrganizationId,
},
select: { id: true, startedAt: true, toothShadeCode: true },
});
if (!existing) {
throw new AppException(ErrorCode.CASE_NOT_FOUND, HttpStatus.NOT_FOUND);
}
const toothShadeCode = await this.toothShadeCatalog.normalize(dto.toothShadeCode);
if (toothShadeCode !== existing.toothShadeCode) {
await this.prisma.$transaction(async (tx) => {
if (existing.startedAt && (await outsourceTreeHasCompletedTask(tx, labCaseId))) {
throw new AppException(ErrorCode.TOOTH_SHADE_LOCKED, HttpStatus.CONFLICT);
}
const ids = [labCaseId, ...(await listOutsourceDescendantIds(tx, labCaseId))];
await tx.labCase.updateMany({
where: { id: { in: ids } },
data: { toothShadeCode },
});
});
}
const labCase = await this.prisma.labCase.findFirstOrThrow({
where: { id: labCaseId },
include: labCaseListInclude,
});
return { success: true, data: await this.mapLabCaseDetail(labCase, localeInput, labOrganizationId) };
}
async listAssignableStaff(labOrganizationId: string, actorUserId: string) {
await this.assertCanEditCases(actorUserId, labOrganizationId);
@@ -1779,6 +1848,7 @@ export class CasesService {
isOverdue: isLabCaseOverdue(lc.dueDate, currentTasks),
isImportant: lc.isImportant,
externalCode: lc.externalCode ?? null,
toothShadeCode: lc.toothShadeCode ?? null,
origin: lc.origin,
startedAt: lc.startedAt?.toISOString() ?? null,
referringClinicName: lc.referringClinicName,

View File

@@ -27,6 +27,13 @@ export class UpdateLabCaseExternalCodeDto {
externalCode?: string | null;
}
export class UpdateLabCaseToothShadeDto {
@IsOptional()
@IsString()
@MaxLength(16)
toothShadeCode?: string | null;
}
export class OutsourceLabCaseDto {
@IsUUID()
destinationOrganizationId!: string;
@@ -126,6 +133,11 @@ export class CreateLabInternalCaseDto {
@IsOptional()
@IsDateString()
dueDate?: string | null;
@IsOptional()
@IsString()
@MaxLength(16)
toothShadeCode?: string | null;
}
export class UpdateLabInternalCaseDto extends CreateLabInternalCaseDto {

View File

@@ -964,6 +964,7 @@ export class TasksService {
isImportant: task.labCase.isImportant,
caseDueDate: task.labCase.dueDate?.toISOString() ?? null,
isCaseOverdue: isLabCaseOverdue(task.labCase.dueDate, task.labCase.tasks),
toothShadeCode: task.labCase.toothShadeCode ?? null,
assignee: task.assignee
? { id: task.assignee.id, name: task.assignee.name }
: null,

View File

@@ -0,0 +1,21 @@
import { Controller, Get, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { ToothShadeCatalogService } from './tooth-shade-catalog.service';
@ApiTags('tooth-shade-catalog')
@ApiBearerAuth('JWT-auth')
@UseGuards(JwtAuthGuard)
@Controller('tooth-shade-catalog')
export class ToothShadeCatalogController {
constructor(private readonly toothShadeCatalog: ToothShadeCatalogService) {}
@Get()
@ApiOperation({ summary: 'List tooth shade guide codes (VITA Classical + bleach)' })
list() {
return this.toothShadeCatalog.list().then((data) => ({
success: true,
data,
}));
}
}

View File

@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { PrismaService } from '../../../prisma/prisma.service';
import { ToothShadeCatalogController } from './tooth-shade-catalog.controller';
import { ToothShadeCatalogService } from './tooth-shade-catalog.service';
@Module({
controllers: [ToothShadeCatalogController],
providers: [ToothShadeCatalogService, PrismaService],
exports: [ToothShadeCatalogService],
})
export class ToothShadeCatalogModule {}

View File

@@ -0,0 +1,61 @@
import { HttpStatus, Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { AppException, ErrorCode } from '../../common/errors';
import { PrismaService } from '../../../prisma/prisma.service';
import { canonicalToothShadeCode } from './tooth-shade-code';
export type ToothShadeCatalogEntry = {
code: string;
family: string;
sortOrder: number;
hex: string;
};
@Injectable()
export class ToothShadeCatalogService implements OnModuleInit {
private readonly logger = new Logger(ToothShadeCatalogService.name);
/** Every stored code, active or not — a deactivated shade stays valid on existing cases. */
private knownCodes: Set<string> | null = null;
constructor(private readonly prisma: PrismaService) {}
async onModuleInit() {
try {
await this.loadKnownCodes();
} catch (error) {
this.logger.warn(`Tooth shade catalog not loaded at boot: ${String(error)}`);
}
}
private async loadKnownCodes(): Promise<Set<string>> {
const rows = await this.prisma.toothShade.findMany({ select: { code: true } });
this.knownCodes = new Set(rows.map((row) => row.code));
return this.knownCodes;
}
/** Active shades for the picker and voice prompt, read fresh so AdminJS edits show at once. */
async list(): Promise<ToothShadeCatalogEntry[]> {
return this.prisma.toothShade.findMany({
where: { isActive: true },
orderBy: [{ sortOrder: 'asc' }, { code: 'asc' }],
select: { code: true, family: true, sortOrder: true, hex: true },
});
}
/** Null/empty clears. Unknown codes throw TOOTH_SHADE_INVALID. */
async normalize(input: string | null | undefined): Promise<string | null> {
const code = canonicalToothShadeCode(input);
if (code === null) return null;
const known =
this.knownCodes?.has(code) ? this.knownCodes : await this.loadKnownCodes();
if (!known.has(code)) {
throw new AppException(ErrorCode.TOOTH_SHADE_INVALID, HttpStatus.BAD_REQUEST);
}
return code;
}
/** `undefined` means "leave unchanged" (field omitted from the request). */
async normalizeOptional(input: string | null | undefined): Promise<string | null | undefined> {
if (input === undefined) return undefined;
return this.normalize(input);
}
}

View File

@@ -0,0 +1,29 @@
import { canonicalToothShadeCode } from './tooth-shade-code';
describe('canonicalToothShadeCode', () => {
it('keeps exact catalog codes', () => {
for (const code of ['0M1', 'A1', 'A3.5', 'B4', 'C1', 'D2']) {
expect(canonicalToothShadeCode(code)).toBe(code);
}
});
it('fixes case, spacing, decimal separators and digits', () => {
expect(canonicalToothShadeCode(' a2 ')).toBe('A2');
expect(canonicalToothShadeCode('A 3,5')).toBe('A3.5');
expect(canonicalToothShadeCode('a3/5')).toBe('A3.5');
expect(canonicalToothShadeCode('A۳٫۵')).toBe('A3.5');
expect(canonicalToothShadeCode('B٢')).toBe('B2');
});
it('reads a letter O as the bleach zero', () => {
expect(canonicalToothShadeCode('OM1')).toBe('0M1');
expect(canonicalToothShadeCode('om 3')).toBe('0M3');
});
it('returns null for empty or non-string input', () => {
expect(canonicalToothShadeCode('')).toBeNull();
expect(canonicalToothShadeCode(' ')).toBeNull();
expect(canonicalToothShadeCode(null)).toBeNull();
expect(canonicalToothShadeCode(2)).toBeNull();
});
});

View File

@@ -0,0 +1,20 @@
const PERSIAN_DIGITS = '۰۱۲۳۴۵۶۷۸۹';
const ARABIC_DIGITS = '٠١٢٣٤٥٦٧٨٩';
/**
* Canonical spelling of a typed or dictated shade ("a 3,5" → "A3.5", "OM1" → "0M1").
* Returns null for empty input. It does not check the catalog.
*/
export function canonicalToothShadeCode(input: unknown): string | null {
if (typeof input !== 'string') return null;
let value = input.normalize('NFKC').trim();
if (!value) return null;
value = value.replace(/[۰-۹]/g, (d) => String(PERSIAN_DIGITS.indexOf(d)));
value = value.replace(/[٠-٩]/g, (d) => String(ARABIC_DIGITS.indexOf(d)));
value = value
.replace(/[\s\-_]+/g, '')
.replace(/[,/٫]/g, '.')
.toUpperCase();
if (/^OM\d/.test(value)) value = `0M${value.slice(2)}`;
return value || null;
}

View File

@@ -121,6 +121,11 @@ export class SaveLabCaseDto {
@IsOptional()
@IsDateString()
dueDate?: string | null;
@IsOptional()
@IsString()
@MaxLength(16)
toothShadeCode?: string | null;
}
export class UpdateLabCaseDueDateDto {

View File

@@ -2,6 +2,7 @@ import { Module } from '@nestjs/common';
import { PrismaService } from '../../../prisma/prisma.service';
import { ClinicOrgGuard } from '../../common/guards/clinic-org.guard';
import { ProsthesisCatalogModule } from '../prosthesis-catalog/prosthesis-catalog.module';
import { ToothShadeCatalogModule } from '../tooth-shade-catalog/tooth-shade-catalog.module';
import { LabCaseCommentsModule } from '../lab-case-comments/lab-case-comments.module';
import { NotificationsModule } from '../notifications/notifications.module';
import { TreatmentsController } from './treatments.controller';
@@ -10,7 +11,14 @@ import { BillingModule } from '../billing/billing.module';
import { SubscriptionModule } from '../subscription/subscription.module';
@Module({
imports: [ProsthesisCatalogModule, LabCaseCommentsModule, NotificationsModule, BillingModule, SubscriptionModule],
imports: [
ProsthesisCatalogModule,
ToothShadeCatalogModule,
LabCaseCommentsModule,
NotificationsModule,
BillingModule,
SubscriptionModule,
],
controllers: [TreatmentsController],
providers: [TreatmentsService, PrismaService, ClinicOrgGuard],
})

View File

@@ -18,6 +18,7 @@ import {
outsourceTreeHasCompletedTask,
} from '../cases/lab-case-outsource.tree';
import { ProsthesisCatalogService } from '../prosthesis-catalog/prosthesis-catalog.service';
import { ToothShadeCatalogService } from '../tooth-shade-catalog/tooth-shade-catalog.service';
import { TreatmentCatalogService } from '../treatment-catalog/treatment-catalog.service';
import {
SaveTreatmentDraftDto,
@@ -145,6 +146,7 @@ export class TreatmentsService {
private readonly prisma: PrismaService,
private readonly treatmentCatalog: TreatmentCatalogService,
private readonly prosthesisCatalog: ProsthesisCatalogService,
private readonly toothShadeCatalog: ToothShadeCatalogService,
private readonly labCaseActivity: LabCaseActivityService,
private readonly userNotifications: UserNotificationService,
private readonly billing: BillingService,
@@ -999,6 +1001,15 @@ export class TreatmentsService {
lc.dueDate,
);
}
if (lc.toothShadeCode !== undefined) {
await this.updateLabCaseToothShadeInTx(
tx,
lc.id,
organizationId,
actorUserId,
lc.toothShadeCode,
);
}
continue;
}
@@ -1010,6 +1021,7 @@ export class TreatmentsService {
throw new AppException(ErrorCode.TREATMENT_INVALID_DUE_DATE, HttpStatus.BAD_REQUEST);
}
}
const toothShadeCode = await this.toothShadeCatalog.normalizeOptional(lc.toothShadeCode);
const row = lc.id
? await tx.labCase.update({
@@ -1019,6 +1031,7 @@ export class TreatmentsService {
sortOrder: index,
destinationOrganizationId: lc.destinationOrganizationId ?? null,
...(dueDate !== undefined ? { dueDate } : {}),
...(toothShadeCode !== undefined ? { toothShadeCode } : {}),
},
})
: await tx.labCase.create({
@@ -1029,6 +1042,7 @@ export class TreatmentsService {
sortOrder: index,
destinationOrganizationId: lc.destinationOrganizationId ?? null,
...(dueDate !== undefined ? { dueDate } : {}),
...(toothShadeCode !== undefined ? { toothShadeCode } : {}),
},
});
@@ -1342,6 +1356,47 @@ export class TreatmentsService {
});
}
/**
* Sent case: autosave resends every lab case, so an unchanged shade is a no-op even after
* the plan locks. A real change is refused once any step in the outsource tree is done,
* and otherwise also lands on the outsource children.
*/
private async updateLabCaseToothShadeInTx(
tx: Prisma.TransactionClient,
labCaseId: string,
organizationId: string,
actorUserId: string,
toothShadeInput: string | null,
) {
const labCase = await tx.labCase.findFirst({
where: {
id: labCaseId,
treatment: {
organizationId,
...treatmentProviderScopeWhere(actorUserId),
},
},
select: { id: true, toothShadeCode: true },
});
if (!labCase) {
throw new AppException(ErrorCode.LAB_CASE_NOT_FOUND, HttpStatus.NOT_FOUND);
}
const toothShadeCode = await this.toothShadeCatalog.normalize(toothShadeInput);
if (toothShadeCode === labCase.toothShadeCode) return;
if (await outsourceTreeHasCompletedTask(tx, labCaseId)) {
throw new AppException(ErrorCode.TOOTH_SHADE_LOCKED, HttpStatus.CONFLICT);
}
const ids = [labCaseId, ...(await listOutsourceDescendantIds(tx, labCaseId))];
await tx.labCase.updateMany({
where: { id: { in: ids } },
data: { toothShadeCode },
});
}
async uploadDetailAttachments(
appointmentId: string,
detailClientKey: string,
@@ -1717,6 +1772,7 @@ export class TreatmentsService {
destinationOrganizationId?: string | null;
sentAt?: Date | null;
dueDate?: Date | null;
toothShadeCode?: string | null;
accessToken?: string | null;
details?: Array<{
treatmentDetailId: string;
@@ -1763,6 +1819,7 @@ export class TreatmentsService {
destinationOrganizationId: lc.destinationOrganizationId ?? null,
sentAt: lc.sentAt?.toISOString() ?? null,
dueDate: lc.dueDate?.toISOString() ?? null,
toothShadeCode: lc.toothShadeCode ?? null,
taskProgress,
treatmentDetailId: lc.details?.[0]?.treatmentDetailId ?? null,
detail: lc.details?.[0]

View File

@@ -106,8 +106,8 @@ export function buildExtractionPrompt(
'You are a parser, not an assistant: report only what was said.',
'',
'HARD RULES',
'1. Never invent a code. treatmentType and prosthesis[].types[] must be codes from the',
' lists below. labId must be an id from the lab list. If what you heard is not in a',
'1. Never invent a code. treatmentType, prosthesis[].types[] and toothShadeCode must be',
' codes from the lists below. labId must be an id from the lab list. If what you heard is not in a',
' list, use null (or omit it from prosthesis[].types[]).',
'2. "side" is always the PATIENT\'s side. The patient\'s upper right is quadrant 1. Never',
" flip to the viewer's point of view.",
@@ -121,7 +121,7 @@ export function buildExtractionPrompt(
' as a prosthesis[].targets entry with "arch" set and "position" null.',
'7. "comment" holds the meaningful speech that fits no other field — observations,',
' patient context, anything worth keeping that is not a treatmentType, tooth,',
' prosthesis, lab or deadline. Filler and small talk (greetings, thanks, "ok") are',
' prosthesis, lab, deadline or tooth shade. Filler and small talk (greetings, thanks, "ok") are',
' dropped entirely, never noted. When the clinician asked for a note, keep the asking',
' words out of its text.',
'8. pontic is a per-tooth role, never a material and never a jaw. Never stack pontic with',
@@ -189,11 +189,20 @@ export function buildExtractionPrompt(
' for a note, the asking words stay out of its text: for "بنویس که بیمار حساسیت به',
' سرما دارد", comment is "بیمار حساسیت به سرما دارد".',
' WHERE THE NOTE ENDS: a clause you also reported in another field — a lab, a tooth,',
' a prosthesis, a deadline — is that instruction, so it never belongs in "comment" as',
' well. Nothing may appear in two fields. Example: "توی توضیحات بنویس رنگ دندون A2',
' هست و بفرست برای لابراتوآر سانشاین" -> comment "رنگ دندون A2 هست", and the lab',
' goes to labId. "و بفرست برای لابراتوآر سانشاین" is an instruction, not the note.',
' a prosthesis, a deadline, a tooth shade — is that instruction, so it never belongs',
' in "comment" as well. Nothing may appear in two fields. Example: "توی توضیحات بنویس',
' بیمار حساسیت به سرما دارد و رنگ دندون A2 هست و بفرست برای لابراتوآر سانشاین" ->',
' comment "بیمار حساسیت به سرما دارد", toothShadeCode "A2", and the lab goes to labId.',
'- toothShadeCode: a CODE from the TOOTH SHADES list when a shade (رنگ / shade / kleur)',
' was spoken, e.g. "آ دو" or "A two" -> "A2", "آ سه و نیم" -> "A3.5", "او ام یک" or',
' "bleach one" -> "0M1". One shade for the whole case. Null when none. Never invent a',
' code. Never also put that shade in comment. The digit in a shade is never a tooth.',
'- labMatchExact: true only when the spoken name matched a lab name exactly.',
'',
'TOOTH SHADES (codes only — use exactly):',
catalog.toothShades.length > 0
? catalog.toothShades.map((s) => `- ${s.code}`).join('\n')
: '(none)',
].join('\n');
return [

View File

@@ -101,6 +101,7 @@ const CTX: ResolveContext = {
]),
prosthesisSubcategoryCodes: new Set(['night_guard']),
linkedLabIds: new Set(['lab-sina', 'lab-mehr']),
toothShadeCodes: new Set(['0M1', 'A1', 'A2', 'A3.5', 'B1']),
};
describe('resolveConnectedSpans', () => {
@@ -530,6 +531,7 @@ describe('resolveVoiceIntent', () => {
labId: null,
labMatchExact: false,
due: null,
toothShadeCode: null,
};
it('composes a plain restoration', () => {
@@ -553,6 +555,21 @@ describe('resolveVoiceIntent', () => {
});
});
it('keeps a catalog tooth shade, canonicalizing the spelling', () => {
expect(resolveVoiceIntent({ ...base, toothShadeCode: 'A2' }, CTX).toothShadeCode).toBe('A2');
expect(resolveVoiceIntent({ ...base, toothShadeCode: 'a 3,5' }, CTX).toothShadeCode).toBe(
'A3.5',
);
expect(resolveVoiceIntent({ ...base, toothShadeCode: 'OM1' }, CTX).toothShadeCode).toBe('0M1');
expect(resolveVoiceIntent(base, CTX).toothShadeCode).toBeNull();
});
it('drops a tooth shade outside the catalog and reports it', () => {
const result = resolveVoiceIntent({ ...base, toothShadeCode: 'Z9' }, CTX);
expect(result.toothShadeCode).toBeNull();
expect(result.unresolved).toContainEqual({ spoken: 'Z9', reason: 'unknown_catalog_code' });
});
it('drops a lab id the clinic is not linked to', () => {
// Shipping to a lab the clinic never named is worse than shipping nowhere.
const result = resolveVoiceIntent(

View File

@@ -10,6 +10,7 @@ import {
type Arch,
type PatientSide,
} from '../../common/fdi';
import { canonicalToothShadeCode } from '../tooth-shade-catalog/tooth-shade-code';
import { resolveDueDate } from './due-date.resolver';
import {
resolveToothIntent,
@@ -51,6 +52,7 @@ export type ResolvedExtraction = {
labId: string | null;
labMatchExact: boolean;
dueDate: string | null;
toothShadeCode: string | null;
unresolved: UnresolvedItem[];
};
@@ -71,6 +73,7 @@ export type ResolveContext = {
prosthesisCategoryCodes: ReadonlySet<string>;
prosthesisSubcategoryCodes: ReadonlySet<string>;
linkedLabIds: ReadonlySet<string>;
toothShadeCodes: ReadonlySet<string>;
};
function spokenOf(intent: unknown): string {
@@ -562,6 +565,17 @@ export function resolveVoiceIntent(
unresolved.push({ spoken: '', reason: 'unknown_catalog_code' });
}
const toothShadeCode = resolveCatalogCode(
canonicalToothShadeCode(intent?.toothShadeCode),
ctx.toothShadeCodes,
);
if (intent?.toothShadeCode != null && !toothShadeCode) {
unresolved.push({
spoken: String(intent.toothShadeCode),
reason: 'unknown_catalog_code',
});
}
return {
treatmentType: hasResolvedAssignment ? 'prosthesis' : treatmentType,
teeth: spanResult.teeth,
@@ -571,6 +585,7 @@ export function resolveVoiceIntent(
labId,
labMatchExact: labId ? intent?.labMatchExact === true : false,
dueDate: due.dueDate,
toothShadeCode,
unresolved,
};
}

View File

@@ -27,6 +27,7 @@ const wire = (overrides: Partial<WireVoiceIntent> = {}): WireVoiceIntent => ({
labId: null,
labMatchExact: false,
due: emptyDue,
toothShadeCode: null,
...overrides,
});

View File

@@ -54,6 +54,7 @@ export type WireVoiceIntent = {
labId: string | null;
labMatchExact: boolean;
due: WireDue;
toothShadeCode: string | null;
};
const TOOTH_SCHEMA = {
@@ -129,6 +130,7 @@ export const VOICE_INTENT_JSON_SCHEMA = {
'labId',
'labMatchExact',
'due',
'toothShadeCode',
],
properties: {
treatmentType: {
@@ -177,6 +179,12 @@ export const VOICE_INTENT_JSON_SCHEMA = {
type: 'boolean',
description: 'True only when the spoken name matched a lab name exactly.',
},
toothShadeCode: {
type: ['string', 'null'],
description:
'A tooth shade CODE from the supplied shade list (e.g. "A2", "0M1", "A3.5"), or null. ' +
'Never invent a code. Never put a shade into comment when it belongs here.',
},
due: {
type: 'object',
additionalProperties: false,
@@ -308,5 +316,9 @@ export function toVoiceIntent(wire: WireVoiceIntent): VoiceIntent {
labId: wire?.labId ?? null,
labMatchExact: wire?.labMatchExact === true,
due: toDueIntent(wire?.due),
toothShadeCode:
typeof wire?.toothShadeCode === 'string' && wire.toothShadeCode.trim()
? wire.toothShadeCode.trim()
: null,
};
}

View File

@@ -30,6 +30,7 @@ const catalog = (): ExtractionCatalog => ({
],
prosthesisSubcategories: [{ code: 'veneer', label: 'Veneer' }],
labs: [{ id: 'org-lab-1', name: 'Some Lab' }],
toothShades: [{ code: 'A2' }, { code: '0M1' }],
});
describe('narrowCatalogForOrgType', () => {

View File

@@ -25,6 +25,7 @@ const CATALOG = {
prosthesisCategories: [{ code: 'crown', label: 'روکش‌ها' }],
prosthesisSubcategories: [],
labs: [{ id: 'lab-1', name: 'لابراتوار سینا' }],
toothShades: [{ code: 'A2' }, { code: '0M1' }],
};
type ChatBody = {

View File

@@ -1,11 +1,12 @@
import { Module } from '@nestjs/common';
import { PrismaService } from '../../../prisma/prisma.service';
import { ProsthesisCatalogModule } from '../prosthesis-catalog/prosthesis-catalog.module';
import { ToothShadeCatalogModule } from '../tooth-shade-catalog/tooth-shade-catalog.module';
import { VoiceController } from './voice.controller';
import { VoiceService } from './voice.service';
@Module({
imports: [ProsthesisCatalogModule],
imports: [ProsthesisCatalogModule, ToothShadeCatalogModule],
controllers: [VoiceController],
providers: [VoiceService, PrismaService],
})

View File

@@ -52,6 +52,8 @@ export type ExtractionCatalog = {
prosthesisSubcategories: { code: string; label: string }[];
/** The clinic's linked labs — a closed choice list. */
labs: { id: string; name: string }[];
/** VITA Classical + bleach shade codes (labels are the codes). */
toothShades: { code: string }[];
};
export type ExtractionResult = {

View File

@@ -31,6 +31,7 @@ const EMPTY_INTENT = {
labId: null,
labMatchExact: false,
due: null,
toothShadeCode: null,
};
const DTO: ExtractVoiceDto = {
@@ -114,11 +115,18 @@ function buildService(opts: {
.mockResolvedValue([{ code: 'veneer', label: 'Veneer' }]),
};
const toothShadeCatalog = {
list: jest.fn().mockResolvedValue([
{ code: 'A2', family: 'A', sortOrder: 5, hex: '#E8D5B7' },
]),
};
return new VoiceService(
prisma as never,
config as never,
treatmentCatalog as never,
prosthesisCatalog as never,
toothShadeCatalog as never,
);
}

View File

@@ -17,6 +17,7 @@ import {
import { narrowCatalogForOrgType } from './narrowCatalogForOrgType';
import { normalizeCatalogLocale } from '../catalog/catalog-label.service';
import { ProsthesisCatalogService } from '../prosthesis-catalog/prosthesis-catalog.service';
import { ToothShadeCatalogService } from '../tooth-shade-catalog/tooth-shade-catalog.service';
import { TreatmentCatalogService } from '../treatment-catalog/treatment-catalog.service';
import { weekStartForLocale } from './due-date.resolver';
import {
@@ -57,6 +58,7 @@ export class VoiceService {
private readonly config: ConfigService,
private readonly treatmentCatalog: TreatmentCatalogService,
private readonly prosthesisCatalog: ProsthesisCatalogService,
private readonly toothShadeCatalog: ToothShadeCatalogService,
) {}
private get voiceConfig(): VoiceConfig {
@@ -165,6 +167,7 @@ export class VoiceService {
catalog.prosthesisSubcategories.map((c) => c.code),
),
linkedLabIds: new Set(catalog.labs.map((l) => l.id)),
toothShadeCodes: new Set(catalog.toothShades.map((s) => s.code)),
});
} catch (error) {
throw this.toAppException(error, 'extraction');
@@ -291,12 +294,14 @@ export class VoiceService {
prosthesisCategories,
prosthesisSubcategories,
labs,
toothShades,
] = await Promise.all([
this.treatmentCatalog.list(locale, null),
this.prosthesisCatalog.list(locale),
this.prosthesisCatalog.listCategories(locale),
this.prosthesisCatalog.listSubcategories(locale),
this.listLinkedLabs(organizationId),
this.toothShadeCatalog.list(),
]);
return {
@@ -309,6 +314,7 @@ export class VoiceService {
prosthesisCategories,
prosthesisSubcategories,
labs,
toothShades: toothShades.map((s) => ({ code: s.code })),
};
}
@@ -381,6 +387,7 @@ export class VoiceService {
prosthesisAssignments: resolved.prosthesisAssignments.length,
lab: resolved.labId != null,
dueDate: resolved.dueDate != null,
toothShade: resolved.toothShadeCode != null,
},
unresolvedCount: resolved.unresolved.length,
}),

View File

@@ -77,6 +77,8 @@ export type VoiceIntent = {
/** False when the spoken name only approximately matched — the UI then requires an explicit tick. */
labMatchExact: boolean;
due: DueIntent | null;
/** Optional VITA-style tooth shade code from the shade guide, or null. */
toothShadeCode: string | null;
};
/** Why a spoken item could not be turned into a domain value. Shown to the user. */

View File

@@ -615,7 +615,9 @@
"errorDeleteCase": "Could not delete the case.",
"draftsTitle": "Drafts",
"draftsSubtitle": "Unstarted cases you created. Start a draft to add it to the case list.",
"draftsEmpty": "No drafts."
"draftsEmpty": "No drafts.",
"caseSheetToothShade": "Shade",
"errorUpdateToothShade": "Could not save the tooth shade."
},
"labCaseAccess": {
"pageTitle": "Case tasks",
@@ -1058,7 +1060,8 @@
"unknown_catalog_code": "not in this clinic’s list",
"invalid_date": "not a usable date"
},
"voiceFailed": "Voice entry failed. Please try again."
"voiceFailed": "Voice entry failed. Please try again.",
"toothShadeLabel": "Tooth shade"
},
"organizations": {
"loadingOrganization": "Loading organization...",
@@ -1442,7 +1445,33 @@
"commissionSubtotal": "Commission",
"fixedSalarySubtotal": "Fixed salary",
"grossCompensation": "Gross compensation",
"projectedSoFar": "So far"
"projectedSoFar": "So far",
"printStatement": "Print statement",
"statementTitle": "Account statement",
"statementAddressedTo": "To",
"statementPhone": "Phone",
"statementPrintedOn": "Printed {date}",
"statementRowNumber": "#",
"statementPage": "Page {page} of {pages}",
"statementRange": "{from} – {to}",
"statementRangeFrom": "From {from}",
"statementRangeTo": "Through {to}",
"statementRangeAll": "All dates",
"errorPrintStatement": "Could not print the statement.",
"openMonthCompensation": "This month through {date}",
"showIncomeDetails": "Show details",
"incomeDetailsTitle": "Income for {period}",
"incomeThrough": "Through {date}",
"commissionByStep": "Commission by job",
"earningRecords": "Earning records",
"incomeStep": "Job",
"incomeQuantity": "Quantity",
"incomeUnitAmount": "Unit price",
"incomeAmount": "Amount",
"incomeSum": "Sum",
"incomePostedMismatch": "The saved month total is {posted}. These records add up to {listed}. A reopened step updates the saved total on the next run.",
"incomeEmptyCommission": "No commission records in this month.",
"errorLoadIncome": "Could not load the income details."
},
"localDb": {
"browse": "Browse",
@@ -1680,6 +1709,11 @@
"BILLING_STAFF_INVALID": "Choose a staff member for this payment.",
"BILLING_PARTY_INVALID": "Choose a valid party for this filter.",
"BILLING_PROSTHESIS_NOT_PROVIDED": "The selected lab does not provide one or more prosthesis types in this case.",
"BILLING_OBLIGATION_NOT_EDITABLE": "Only the destination lab can set this case fee."
"BILLING_OBLIGATION_NOT_EDITABLE": "Only the destination lab can set this case fee.",
"TOOTH_SHADE_INVALID": "That tooth shade is not valid.",
"TOOTH_SHADE_LOCKED": "The tooth shade cannot be changed after a lab step is completed."
},
"toothShade": {
"label": "Tooth shade"
}
}

View File

@@ -616,7 +616,9 @@
"errorDeleteCase": "حذف پرونده ممکن نشد.",
"draftsTitle": "پیش‌نویس‌ها",
"draftsSubtitle": "پرونده‌های شروع‌نشده‌ای که ساخته‌اید. با شروع پیش‌نویس، به فهرست پرونده‌ها اضافه می‌شود.",
"draftsEmpty": "پیش‌نویسی نیست."
"draftsEmpty": "پیش‌نویسی نیست.",
"caseSheetToothShade": "رنگ",
"errorUpdateToothShade": "ذخیره رنگ دندان ممکن نشد."
},
"labCaseAccess": {
"pageTitle": "وظایف پرونده",
@@ -1059,7 +1061,8 @@
"unknown_catalog_code": "در فهرست این مطب نیست",
"invalid_date": "تاریخ قابل استفاده نیست"
},
"voiceFailed": "ثبت گفتاری انجام نشد. لطفاً دوباره تلاش کنید."
"voiceFailed": "ثبت گفتاری انجام نشد. لطفاً دوباره تلاش کنید.",
"toothShadeLabel": "رنگ دندان"
},
"organizations": {
"loadingOrganization": "در حال بارگذاری سازمان...",
@@ -1443,7 +1446,33 @@
"commissionSubtotal": "کمیسیون",
"fixedSalarySubtotal": "حقوق ثابت",
"grossCompensation": "جمع ناخالص دریافتی",
"projectedSoFar": "تا این روز"
"projectedSoFar": "تا این روز",
"printStatement": "چاپ صورتحساب",
"statementTitle": "صورتحساب",
"statementAddressedTo": "به",
"statementPhone": "تلفن",
"statementPrintedOn": "تاریخ چاپ {date}",
"statementRowNumber": "ردیف",
"statementPage": "صفحه {page} از {pages}",
"statementRange": "از {from} تا {to}",
"statementRangeFrom": "از {from}",
"statementRangeTo": "تا {to}",
"statementRangeAll": "همه تاریخ‌ها",
"errorPrintStatement": "چاپ صورتحساب ناموفق بود.",
"openMonthCompensation": "این ماه تا {date}",
"showIncomeDetails": "نمایش جزئیات",
"incomeDetailsTitle": "درآمد {period}",
"incomeThrough": "تا {date}",
"commissionByStep": "کمیسیون به تفکیک کار",
"earningRecords": "رکوردهای درآمد",
"incomeStep": "کار",
"incomeQuantity": "تعداد",
"incomeUnitAmount": "قیمت واحد",
"incomeAmount": "مبلغ",
"incomeSum": "جمع",
"incomePostedMismatch": "جمع ذخیره‌شده این ماه {posted} است. این رکوردها روی هم {listed} می‌شوند. اگر مرحله‌ای دوباره باز شود، جمع ذخیره‌شده در اجرای بعدی به‌روز می‌شود.",
"incomeEmptyCommission": "در این ماه رکورد کمیسیونی نیست.",
"errorLoadIncome": "بارگذاری جزئیات درآمد ناموفق بود."
},
"localDb": {
"browse": "مرور",
@@ -1681,6 +1710,11 @@
"BILLING_STAFF_INVALID": "یک عضو کارکنان برای این پرداخت انتخاب کنید.",
"BILLING_PARTY_INVALID": "طرف معتبری برای این فیلتر انتخاب کنید.",
"BILLING_PROSTHESIS_NOT_PROVIDED": "لابراتوار انتخاب‌شده یک یا چند نوع پروتز این پرونده را ارائه نمی‌دهد.",
"BILLING_OBLIGATION_NOT_EDITABLE": "فقط لابراتوار مقصد می‌تواند هزینه این پرونده را تعیین کند."
"BILLING_OBLIGATION_NOT_EDITABLE": "فقط لابراتوار مقصد می‌تواند هزینه این پرونده را تعیین کند.",
"TOOTH_SHADE_INVALID": "این رنگ دندان معتبر نیست.",
"TOOTH_SHADE_LOCKED": "پس از تکمیل یک مرحله لابراتوار نمی‌توان رنگ دندان را تغییر داد."
},
"toothShade": {
"label": "رنگ دندان"
}
}

View File

@@ -616,7 +616,9 @@
"errorDeleteCase": "Case kon niet worden verwijderd.",
"draftsTitle": "Concepten",
"draftsSubtitle": "Niet-gestarte cases die u hebt gemaakt. Start een concept om het in de caselijst te zetten.",
"draftsEmpty": "Geen concepten."
"draftsEmpty": "Geen concepten.",
"caseSheetToothShade": "Kleur",
"errorUpdateToothShade": "De tandkleur kon niet worden opgeslagen."
},
"labCaseAccess": {
"pageTitle": "Dossiertaken",
@@ -1058,7 +1060,8 @@
"unknown_catalog_code": "staat niet in de lijst van deze praktijk",
"invalid_date": "geen bruikbare datum"
},
"voiceFailed": "Spraakinvoer is mislukt. Probeer het opnieuw."
"voiceFailed": "Spraakinvoer is mislukt. Probeer het opnieuw.",
"toothShadeLabel": "Tandkleur"
},
"organizations": {
"loadingOrganization": "Organisatie laden...",
@@ -1442,7 +1445,33 @@
"commissionSubtotal": "Commissie",
"fixedSalarySubtotal": "Vast salaris",
"grossCompensation": "Brutovergoeding",
"projectedSoFar": "Tot nu toe"
"projectedSoFar": "Tot nu toe",
"printStatement": "Overzicht afdrukken",
"statementTitle": "Rekeningoverzicht",
"statementAddressedTo": "Aan",
"statementPhone": "Telefoon",
"statementPrintedOn": "Afgedrukt {date}",
"statementRowNumber": "#",
"statementPage": "Pagina {page} van {pages}",
"statementRange": "{from} – {to}",
"statementRangeFrom": "Vanaf {from}",
"statementRangeTo": "Tot en met {to}",
"statementRangeAll": "Alle datums",
"errorPrintStatement": "Het overzicht kon niet worden afgedrukt.",
"openMonthCompensation": "Deze maand tot en met {date}",
"showIncomeDetails": "Details tonen",
"incomeDetailsTitle": "Inkomen voor {period}",
"incomeThrough": "Tot en met {date}",
"commissionByStep": "Commissie per werk",
"earningRecords": "Inkomstenregels",
"incomeStep": "Werk",
"incomeQuantity": "Aantal",
"incomeUnitAmount": "Eenheidsprijs",
"incomeAmount": "Bedrag",
"incomeSum": "Som",
"incomePostedMismatch": "Het opgeslagen maandtotaal is {posted}. Deze regels tellen op tot {listed}. Een heropende stap werkt het opgeslagen totaal bij bij de volgende run.",
"incomeEmptyCommission": "Geen commissieregels in deze maand.",
"errorLoadIncome": "De inkomstendetails konden niet worden geladen."
},
"localDb": {
"browse": "Bladeren",
@@ -1680,6 +1709,11 @@
"BILLING_STAFF_INVALID": "Kies een medewerker voor deze betaling.",
"BILLING_PARTY_INVALID": "Kies een geldige partij voor dit filter.",
"BILLING_PROSTHESIS_NOT_PROVIDED": "Het geselecteerde lab levert een of meer prothesetypen in deze case niet.",
"BILLING_OBLIGATION_NOT_EDITABLE": "Alleen het bestemmingslab kan dit casetarief instellen."
"BILLING_OBLIGATION_NOT_EDITABLE": "Alleen het bestemmingslab kan dit casetarief instellen.",
"TOOTH_SHADE_INVALID": "Die tandkleur is ongeldig.",
"TOOTH_SHADE_LOCKED": "De tandkleur kan niet worden gewijzigd nadat een labstap is voltooid."
},
"toothShade": {
"label": "Tandkleur"
}
}

View File

@@ -1,11 +1,12 @@
import { describe, expect, it } from 'vitest';
import type { BillingPartyReportRow } from '@/types/billing';
import { staffCompensationTotals } from './staffCompensation';
import { splitStaffCompensation, staffCompensationTotals } from './staffCompensation';
function row(
sourceType: BillingPartyReportRow['sourceType'],
amount: string | null,
lineKind: BillingPartyReportRow['lineKind'] = 'OBLIGATION',
extras: Partial<BillingPartyReportRow> = {},
): BillingPartyReportRow {
return {
id: `${sourceType}:${amount}`,
@@ -22,6 +23,7 @@ function row(
note: null,
acknowledgement: 'none',
countsInTotals: amount != null,
...extras,
};
}
@@ -46,3 +48,34 @@ describe('staffCompensationTotals', () => {
).toEqual({ commission: 0, fixedSalary: 0, gross: 0 });
});
});
describe('splitStaffCompensation', () => {
it('keeps the open-month preview out of the closed totals', () => {
expect(
splitStaffCompensation([
row('STAFF_COMMISSION_MONTH', '40.00', 'OBLIGATION', {
projected: true,
reference: 'J:1404-08',
}),
row('STAFF_SALARY_MONTH', '100.00', 'OBLIGATION', {
projected: true,
reference: 'J:1404-08',
}),
row('STAFF_COMMISSION_MONTH', '200.00'),
row('STAFF_SALARY_MONTH', '1000.00'),
]),
).toEqual({
open: { commission: 40, fixedSalary: 100, gross: 140 },
closed: { commission: 200, fixedSalary: 1000, gross: 1200 },
openPeriodKey: 'J:1404-08',
});
});
it('hides the open month when the preview is outside the range', () => {
expect(splitStaffCompensation([row('STAFF_SALARY_MONTH', '1000.00')])).toEqual({
open: null,
closed: { commission: 0, fixedSalary: 1000, gross: 1000 },
openPeriodKey: null,
});
});
});

View File

@@ -6,7 +6,7 @@ export type StaffCompensationTotals = {
gross: number;
};
/** Gross compensation includes closed months and the unsaved current-month preview. */
/** Sum commission and fixed salary on the rows passed in. */
export function staffCompensationTotals(
rows: readonly BillingPartyReportRow[],
): StaffCompensationTotals {
@@ -19,6 +19,42 @@ export function staffCompensationTotals(
};
}
export type SplitStaffCompensation = {
/** Null when this date range has no open-month preview. */
open: StaffCompensationTotals | null;
closed: StaffCompensationTotals;
/** Period key on the open-month preview, when one is present. */
openPeriodKey: string | null;
};
/** Separate the unsaved current month from closed months already in the ledger. */
export function splitStaffCompensation(
rows: readonly BillingPartyReportRow[],
): SplitStaffCompensation {
const projected = rows.filter((row) => row.projected);
const stored = rows.filter((row) => !row.projected);
const open = staffCompensationTotals(projected);
const hasOpen = projected.some(
(row) =>
row.lineKind === 'OBLIGATION' &&
(row.sourceType === 'STAFF_COMMISSION_MONTH' ||
row.sourceType === 'STAFF_SALARY_MONTH') &&
row.amount != null,
);
const openRow = projected.find(
(row) =>
row.lineKind === 'OBLIGATION' &&
(row.sourceType === 'STAFF_COMMISSION_MONTH' ||
row.sourceType === 'STAFF_SALARY_MONTH') &&
row.reference,
);
return {
open: hasOpen ? open : null,
closed: staffCompensationTotals(stored),
openPeriodKey: hasOpen ? (openRow?.reference ?? null) : null,
};
}
function sumSource(
rows: readonly BillingPartyReportRow[],
sourceType: 'STAFF_COMMISSION_MONTH' | 'STAFF_SALARY_MONTH',

View File

@@ -0,0 +1,52 @@
import { describe, expect, it } from 'vitest';
import { statementPages } from './statementPages';
function row(id: string, occurredAt: string) {
return { id, occurredAt };
}
describe('statementPages', () => {
it('prints an empty statement as one page', () => {
expect(statementPages([])).toEqual([[]]);
});
it('orders rows oldest first', () => {
const pages = statementPages(
[
row('b', '2026-11-02T00:00:00.000Z'),
row('a', '2026-11-03T00:00:00.000Z'),
row('c', '2026-11-01T00:00:00.000Z'),
],
14,
9,
);
expect(pages).toHaveLength(1);
expect(pages[0].map((item) => item.id)).toEqual(['c', 'b', 'a']);
});
it('keeps a short overflow on the same page instead of a one-row sheet', () => {
const rows = Array.from({ length: 10 }, (_, index) =>
row(String(index).padStart(2, '0'), `2026-11-${String(index + 1).padStart(2, '0')}T00:00:00.000Z`),
);
expect(statementPages(rows, 14, 9)).toHaveLength(1);
});
it('keeps the last page short enough for the totals', () => {
const rows = Array.from({ length: 23 }, (_, index) =>
row(String(index).padStart(2, '0'), `2026-11-${String(index + 1).padStart(2, '0')}T00:00:00.000Z`),
);
const pages = statementPages(rows, 14, 9);
expect(pages.map((page) => page.length)).toEqual([14, 9]);
expect(pages[0][0].id).toBe('00');
expect(pages[1][8].id).toBe('22');
});
it('breaks the tie on id when two rows share a time', () => {
const pages = statementPages(
[row('b', '2026-11-01T00:00:00.000Z'), row('a', '2026-11-01T00:00:00.000Z')],
14,
9,
);
expect(pages[0].map((item) => item.id)).toEqual(['a', 'b']);
});
});

View File

@@ -0,0 +1,33 @@
export const STATEMENT_ROWS_PER_PAGE = 20;
export const STATEMENT_ROWS_ON_LAST_PAGE = 15;
type StatementRow = {
id: string;
occurredAt: string;
};
/** Oldest first, with the totals reserved on the last page. */
export function statementPages<T extends StatementRow>(
rows: readonly T[],
rowsPerPage = STATEMENT_ROWS_PER_PAGE,
rowsOnLastPage = STATEMENT_ROWS_ON_LAST_PAGE,
): T[][] {
const ordered = [...rows].sort((a, b) => {
const byTime = a.occurredAt.localeCompare(b.occurredAt);
if (byTime !== 0) return byTime;
return a.id.localeCompare(b.id);
});
if (ordered.length === 0) return [[]];
if (ordered.length <= rowsPerPage) return [ordered];
const pages: T[][] = [];
let offset = 0;
while (ordered.length - offset > rowsOnLastPage) {
const leftover = ordered.length - offset - rowsOnLastPage;
if (leftover < rowsPerPage && leftover + rowsOnLastPage <= rowsPerPage) break;
const take = Math.min(rowsPerPage, leftover);
pages.push(ordered.slice(offset, offset + take));
offset += take;
}
pages.push(ordered.slice(offset));
return pages;
}

View File

@@ -0,0 +1,212 @@
import { createRoot } from 'react-dom/client';
import { createElement } from 'react';
import { jsPDF } from 'jspdf';
import html2canvas from 'html2canvas';
import {
BillingStatementPrintLayout,
STATEMENT_TABLE_ROW_HEIGHT,
type BillingStatementPrintLabels,
type BillingStatementPrintRow,
} from '@/components/ui/billing/BillingStatementPrintLayout';
export type StatementPdfPage = {
rows: readonly BillingStatementPrintRow[];
showTotals: boolean;
pageLabel: string;
};
type DownloadStatementPdfArgs = {
locale: string;
fontFamily: string;
issuerName: string;
issuerPhone: string | null;
partyName: string;
labels: Omit<BillingStatementPrintLabels, 'page'>;
pages: readonly StatementPdfPage[];
debit: string;
credit: string;
balance: string;
fileName: string;
};
export function statementPrintFontFamily(locale: string): string {
if (locale !== 'fa' || typeof document === 'undefined') {
return 'system-ui, -apple-system, "Segoe UI", sans-serif';
}
const style = getComputedStyle(document.documentElement);
const vazir = style.getPropertyValue('--font-vazirmatn').trim();
const noto = style.getPropertyValue('--font-noto-sans-arabic').trim();
return [vazir, noto, 'Tahoma', '"Segoe UI"', 'sans-serif'].filter(Boolean).join(', ');
}
function waitForPaint(): Promise<void> {
return new Promise((resolve) => {
requestAnimationFrame(() => {
requestAnimationFrame(() => resolve());
});
});
}
function stripClonedStyles(clonedDoc: Document) {
clonedDoc.querySelectorAll('style, link[rel="stylesheet"]').forEach((node) => {
const css = node instanceof HTMLStyleElement ? (node.textContent ?? '') : '';
if (css.includes('@font-face') && !/oklch\(|\blab\(/i.test(css)) return;
node.remove();
});
clonedDoc.querySelectorAll('[data-statement-org]').forEach((node) => {
if (!(node instanceof HTMLElement)) return;
node.style.display = 'flex';
node.style.alignItems = 'center';
node.style.justifyContent = 'flex-start';
node.style.height = '56px';
node.style.lineHeight = '56px';
node.style.overflow = 'hidden';
node.style.direction = 'ltr';
node.style.letterSpacing = '0px';
node.style.wordSpacing = '0px';
const text = node.querySelector('[data-statement-org-text]');
if (!(text instanceof HTMLElement)) return;
text.style.display = 'inline-block';
text.style.maxWidth = '100%';
text.style.overflow = 'visible';
text.style.lineHeight = '56px';
text.style.paddingTop = '0';
text.style.paddingBottom = '0';
text.style.letterSpacing = '0px';
text.style.wordSpacing = '0px';
text.style.whiteSpace = 'nowrap';
text.style.unicodeBidi = 'isolate';
});
clonedDoc.querySelectorAll('[data-statement-lockup]').forEach((node) => {
if (!(node instanceof HTMLElement)) return;
node.style.height = '32px';
node.style.lineHeight = '32px';
node.style.overflow = 'hidden';
});
clonedDoc.querySelectorAll('[data-statement-cell]').forEach((node) => {
if (!(node instanceof HTMLElement)) return;
node.style.display = 'flex';
node.style.alignItems = 'center';
node.style.height = `${STATEMENT_TABLE_ROW_HEIGHT}px`;
node.style.boxSizing = 'border-box';
node.style.direction = 'ltr';
});
clonedDoc.querySelectorAll('[data-statement-lockup] svg').forEach((node) => {
if (!(node instanceof SVGSVGElement)) return;
const parts = (node.getAttribute('viewBox') ?? '').trim().split(/[\s,]+/).map(Number);
const vbW = parts[2];
const vbH = parts[3];
if (!vbW || !vbH) return;
const height = 26;
const width = Math.max(1, Math.round(height * (vbW / vbH)));
node.setAttribute('width', String(width));
node.setAttribute('height', String(height));
node.style.width = `${width}px`;
node.style.height = `${height}px`;
node.style.verticalAlign = 'middle';
node.style.overflow = 'hidden';
});
}
/**
* One A4 page per slice. Each page is captured at its own size so a long
* ledger is not shrunk onto a single sheet.
*/
export async function downloadStatementPdf({
locale,
fontFamily,
issuerName,
issuerPhone,
partyName,
labels,
pages,
debit,
credit,
balance,
fileName,
}: DownloadStatementPdfArgs): Promise<void> {
const host = document.createElement('div');
host.setAttribute('aria-hidden', 'true');
host.style.cssText =
'position:fixed;left:-12000px;top:0;z-index:-1;pointer-events:none;background:#fff;';
document.body.appendChild(host);
const root = createRoot(host);
try {
root.render(
createElement(
'div',
null,
pages.map((page, index) =>
createElement(BillingStatementPrintLayout, {
key: index,
locale,
fontFamily,
issuerName,
issuerPhone,
partyName,
labels: { ...labels, page: page.pageLabel },
rows: page.rows,
showTotals: page.showTotals,
debit,
credit,
balance,
}),
),
),
);
await waitForPaint();
await new Promise((resolve) => setTimeout(resolve, 80));
const sheets = [...host.querySelectorAll('[data-statement-root]')];
if (sheets.length === 0) {
throw new Error('Statement root not found');
}
const pdf = new jsPDF({ orientation: 'portrait', unit: 'mm', format: 'a4' });
const pageWidth = pdf.internal.pageSize.getWidth();
const pageHeight = pdf.internal.pageSize.getHeight();
const margin = 4;
const usableWidth = pageWidth - margin * 2;
const usableHeight = pageHeight - margin * 2;
for (let index = 0; index < sheets.length; index += 1) {
const sheet = sheets[index];
if (!(sheet instanceof HTMLElement)) continue;
const canvas = await html2canvas(sheet, {
scale: 2,
backgroundColor: '#ffffff',
useCORS: true,
logging: false,
scrollX: 0,
scrollY: 0,
onclone: stripClonedStyles,
});
if (index > 0) pdf.addPage();
const imgData = canvas.toDataURL('image/png');
let drawWidth = usableWidth;
let drawHeight = (canvas.height * drawWidth) / canvas.width;
if (drawHeight > usableHeight) {
drawHeight = usableHeight;
drawWidth = (canvas.width * drawHeight) / canvas.height;
}
const x = margin + (usableWidth - drawWidth) / 2;
pdf.addImage(imgData, 'PNG', x, margin, drawWidth, drawHeight);
}
pdf.save(fileName);
} finally {
root.unmount();
host.remove();
}
}
export function statementPdfFileName(partyName: string, from?: string, to?: string): string {
const slug =
partyName
.trim()
.toLowerCase()
.replace(/[^\p{L}\p{N}]+/gu, '-')
.replace(/^-+|-+$/g, '') || 'party';
const range = [from, to].filter(Boolean).join('_') || 'all';
return `statement-${slug}-${range}.pdf`;
}

View File

@@ -56,6 +56,7 @@ export type CaseTaskGroup = {
caseDueDate: string | null;
isCaseOverdue: boolean;
isImportant: boolean;
toothShadeCode?: string | null;
taskProgress: LabTaskListItem['taskProgress'];
origin?: 'CLINIC_DISPATCH' | 'LAB_INTERNAL' | 'LAB_OUTSOURCE';
partnerOrganizationType?: 'CLINIC' | 'LAB' | string | null;
@@ -96,6 +97,7 @@ export function groupTasksForDisplay(
caseDueDate: task.caseDueDate ?? null,
isCaseOverdue: task.isCaseOverdue,
isImportant: task.isImportant,
toothShadeCode: task.toothShadeCode ?? null,
taskProgress: task.taskProgress,
origin: task.origin,
partnerOrganizationType: task.partnerOrganizationType,

View File

@@ -46,6 +46,7 @@ const result = (overrides: Partial<VoiceExtractionResult> = {}): VoiceExtraction
labId: null,
labMatchExact: false,
dueDate: null,
toothShadeCode: null,
unresolved: [],
...overrides,
});
@@ -57,6 +58,7 @@ const allTicked: VoiceApplySelection = {
prosthesis: true,
lab: true,
dueDate: true,
toothShade: true,
};
const tick = (overrides: Partial<VoiceApplySelection> = {}): VoiceApplySelection => ({
...allTicked,

View File

@@ -26,7 +26,7 @@ export function buildLabLineFromVoice(
result: VoiceExtractionResult,
selection: VoiceApplySelection,
ctx: VoiceLineContext,
): { line: LineDraft | null; dueDate: string | null } {
): { line: LineDraft | null; dueDate: string | null; toothShadeCode: string | null } {
const line = newLine();
if (selection.comment && result.comment) {
@@ -70,5 +70,7 @@ export function buildLabLineFromVoice(
return {
line: isBlankLine(line) ? null : line,
dueDate: selection.dueDate && result.dueDate ? result.dueDate : null,
toothShadeCode:
selection.toothShade && result.toothShadeCode ? result.toothShadeCode : null,
};
}

View File

@@ -77,6 +77,7 @@ const result = (overrides: Partial<VoiceExtractionResult> = {}): VoiceExtraction
labId: null,
labMatchExact: false,
dueDate: null,
toothShadeCode: null,
unresolved: [],
...overrides,
});
@@ -88,6 +89,7 @@ const allTicked: VoiceApplySelection = {
prosthesis: true,
lab: true,
dueDate: true,
toothShade: true,
};
const tick = (overrides: Partial<VoiceApplySelection> = {}): VoiceApplySelection => ({
...allTicked,
@@ -385,6 +387,33 @@ describe('buildVoiceApplyPlan — the comment', () => {
});
});
describe('buildVoiceApplyPlan — the tooth shade', () => {
it('lands on the lab draft of a lab-dependent detail, even with nothing else', () => {
const plan = buildVoiceApplyPlan(result({ toothShadeCode: 'A2' }), tick(), ctx());
expect(plan.labCaseDraft?.toothShadeCode).toBe('A2');
expect(plan.detail.comment).toBe('');
});
it('is skipped when its row is unticked', () => {
const plan = buildVoiceApplyPlan(
result({ toothShadeCode: 'A2' }),
tick({ toothShade: false }),
ctx(),
);
expect(plan.labCaseDraft).toBeNull();
});
it('never creates a lab draft on a detail that is not lab-dependent', () => {
const plan = buildVoiceApplyPlan(
result({ treatmentType: 'restoration', toothShadeCode: 'A2' }),
tick(),
ctx({ defaultTreatmentType: 'restoration' }),
);
expect(plan.detail.treatmentType).toBe('restoration');
expect(plan.labCaseDraft).toBeNull();
});
});
describe('buildVoiceApplyPlan — it does not mutate what it was given', () => {
it('copies the dictated teeth rather than aliasing them', () => {
const dictated = result({ treatmentType: 'restoration', teeth: ['21'] });

View File

@@ -81,10 +81,12 @@ export function buildVoiceApplyPlan(
detail.toothSelectionGroups = landed.groups;
}
const landsShade = labDependent && selection.toothShade && Boolean(result.toothShadeCode);
const wantsLabDraft =
lines.some((line) => line.applied.length > 0) ||
Boolean(selection.lab && result.labId) ||
Boolean(selection.dueDate && result.dueDate);
Boolean(selection.dueDate && result.dueDate) ||
landsShade;
if (!wantsLabDraft) return { detail, labCaseDraft: null };
@@ -97,6 +99,9 @@ export function buildVoiceApplyPlan(
if (selection.dueDate && result.dueDate) {
labCaseDraft.dueDate = result.dueDate;
}
if (landsShade) {
labCaseDraft.toothShadeCode = result.toothShadeCode;
}
labCaseDraft.toothProsthesis = lines.flatMap((line) => {
// A jaw appliance belongs to no selection group; a tooth takes the group it landed in.
const selectionGroupId = line.isJaw

View File

@@ -95,6 +95,7 @@ function baseResult(overrides: Partial<VoiceExtractionResult> = {}): VoiceExtrac
labId: null,
labMatchExact: false,
dueDate: null,
toothShadeCode: null,
unresolved: [],
...overrides,
};
@@ -112,6 +113,21 @@ describe('isLabDependentResult', () => {
});
describe('voiceRowAvailability', () => {
it('shows a tooth shade row only for lab-dependent work', () => {
expect(
voiceRowAvailability(
baseResult({ treatmentType: 'prosthesis', toothShadeCode: 'A2' }),
LAB_DEPENDENT,
).toothShade,
).toBe(true);
expect(
voiceRowAvailability(baseResult({ toothShadeCode: 'A2' }), LAB_DEPENDENT).toothShade,
).toBe(false);
expect(
voiceRowAvailability(baseResult({ toothShadeCode: 'A2' }), LAB_DEPENDENT, 'lab').toothShade,
).toBe(true);
});
it('shows a plain teeth row for a non-lab-dependent type', () => {
const result = baseResult({ teeth: ['14'] });
const available = voiceRowAvailability(result, LAB_DEPENDENT);
@@ -158,8 +174,24 @@ describe('initialVoiceSelection', () => {
describe('countSelected', () => {
it('intersects the selection with availability rather than counting raw ticks', () => {
const selection = { treatmentType: true, teeth: true, comment: true, prosthesis: true, lab: true, dueDate: true };
const available = { treatmentType: true, teeth: false, comment: true, prosthesis: false, lab: true, dueDate: false };
const selection = {
treatmentType: true,
teeth: true,
comment: true,
prosthesis: true,
lab: true,
dueDate: true,
toothShade: true,
};
const available = {
treatmentType: true,
teeth: false,
comment: true,
prosthesis: false,
lab: true,
dueDate: false,
toothShade: false,
};
expect(countSelected(selection, available)).toBe(3);
});
});

View File

@@ -67,6 +67,8 @@ export function voiceRowAvailability(
comment: Boolean(result.comment?.trim()),
lab: !isLab && result.labId != null,
dueDate: result.dueDate != null,
// A shade belongs to the lab case, so only lab-dependent work carries one.
toothShade: labDependent && result.toothShadeCode != null,
};
}
@@ -88,6 +90,7 @@ export function initialVoiceSelection(
prosthesis: available.prosthesis,
lab: available.lab && result.labMatchExact,
dueDate: available.dueDate,
toothShade: available.toothShade,
};
}

View File

@@ -1,7 +1,7 @@
'use client';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslations } from 'next-intl';
import { useLocale, useTranslations } from 'next-intl';
import { Check, Paperclip, Pencil, Search, X } from 'lucide-react';
import { labBlockedBannerClass } from '@/components/treatment/treatmentStatusStyles';
import { Button } from '@/components/ui/shared/Button';
@@ -34,7 +34,15 @@ import { useAppFormatters } from '@/lib/hooks/useAppFormatters';
import { useBillingCurrency } from '@/lib/hooks/useBillingCurrency';
import { parseAppMoney } from '@/lib/i18n/format';
import { stripTrailingDecimalZeros } from '@/lib/i18n/moneyInputFormat';
import { staffCompensationTotals } from '@/components/billing/staffCompensation';
import { splitStaffCompensation } from '@/components/billing/staffCompensation';
import type { StaffCompensationTotals } from '@/components/billing/staffCompensation';
import { statementPages } from '@/components/billing/statementPages';
import {
downloadStatementPdf,
statementPdfFileName,
statementPrintFontFamily,
} from '@/components/billing/statementPdf';
import { BillingStaffIncomeDialog } from '@/components/ui/billing/BillingStaffIncomeDialog';
import type {
AllocationCaseHit,
AllocationTreatmentHit,
@@ -96,6 +104,11 @@ function caseOriginLabelKey(
return null;
}
function staffMonthPeriodKey(row: BillingPartyReportRow): string | null {
if (row.sourceType !== 'STAFF_COMMISSION_MONTH') return null;
return row.reference || null;
}
function sectionToPartyKind(section: BillingPartySectionKey): BillingPartyKind {
if (section === 'patients') return 'patient';
if (section === 'staff') return 'staff';
@@ -112,8 +125,9 @@ export function BillingPaymentsPanel({
const t = useTranslations('billing');
const tCommon = useTranslations('common');
const tErrors = useTranslations('errors');
const locale = useLocale();
const toast = useToast();
const { formatDateTime, formatMoney } = useAppFormatters();
const { formatDate, formatDateTime, formatMoney } = useAppFormatters();
const { settings: currencySettings, reload: reloadCurrency } = useBillingCurrency(true);
const isClinic = orgType === 'CLINIC';
@@ -178,6 +192,7 @@ export function BillingPaymentsPanel({
);
const [allocations, setAllocations] = useState<DraftAlloc[]>([]);
const [saving, setSaving] = useState(false);
const [incomePeriodKey, setIncomePeriodKey] = useState<string | null>(null);
const patientSelected = selectedParty?.section === 'patients';
const staffSelected = selectedParty?.section === 'staff';
@@ -469,10 +484,73 @@ export function BillingPaymentsPanel({
: netNumber >= 0
? 'text-emerald-700 dark:text-emerald-400'
: 'text-red-700 dark:text-red-400';
const compensation = useMemo(
() => staffCompensationTotals(report?.data ?? []),
const compensationSplit = useMemo(
() => splitStaffCompensation(report?.data ?? []),
[report?.data],
);
const openThrough = report?.data.find((row) => row.projected)?.occurredAt ?? null;
const reportOrgSelected =
filterParty?.section === 'clinics' || filterParty?.section === 'labs';
async function printStatement() {
if (!report || !filterParty || !reportOrgSelected) return;
const pages = statementPages(report.data);
let number = 0;
const fromLabel = from ? formatDate(`${from}T12:00:00`) : '';
const toLabel = to ? formatDate(`${to}T12:00:00`) : '';
const rangeLabel =
from && to
? t('statementRange', { from: fromLabel, to: toLabel })
: from
? t('statementRangeFrom', { from: fromLabel })
: to
? t('statementRangeTo', { to: toLabel })
: t('statementRangeAll');
try {
await downloadStatementPdf({
locale,
fontFamily: statementPrintFontFamily(locale),
issuerName: report.issuer.name,
issuerPhone: report.issuer.phone,
partyName: filterParty.name,
debit: formatMoney(report.totals.debit),
credit: formatMoney(report.totals.credit),
balance: formatMoney(report.totals.net),
fileName: statementPdfFileName(filterParty.name, from || undefined, to || undefined),
labels: {
title: t('statementTitle'),
addressedTo: t('statementAddressedTo'),
phone: t('statementPhone'),
printedOn: t('statementPrintedOn', { date: formatDate(new Date()) }),
rowNumber: t('statementRowNumber'),
date: t('time'),
reference: t('reference'),
amount: amountLabel,
debit: t('debit'),
credit: t('credit'),
balance: t('balanceTotal'),
range: rangeLabel,
empty: t('reportEmpty'),
},
pages: pages.map((page, index) => ({
showTotals: index === pages.length - 1,
pageLabel: t('statementPage', { page: index + 1, pages: pages.length }),
rows: page.map((row) => {
number += 1;
return {
number,
date: formatDateTime(row.occurredAt),
reference: row.reference,
amount: row.amount == null ? '' : formatMoney(row.amount),
direction: row.direction === 'DEBIT' ? t('debit') : t('credit'),
};
}),
})),
});
} catch (error: unknown) {
toast.showError(getUserFacingError(error, tErrors, t('errorPrintStatement')));
}
}
async function submitCreate() {
const parsedAmount = parseAppMoney(amount);
@@ -766,33 +844,47 @@ export function BillingPaymentsPanel({
</Card>
) : null}
{filterParty && sectionToPartyKind(filterParty.section) === 'staff' ? (
{filterParty &&
sectionToPartyKind(filterParty.section) === 'staff' &&
compensationSplit.open ? (
<Card className="space-y-3">
<div className="grid grid-cols-1 gap-2 text-sm sm:grid-cols-3">
<div className="rounded-[var(--radius-sm)] bg-background-secondary/70 p-3">
<p className="text-text-muted">{t('commissionSubtotal')}</p>
<p className="font-medium tabular-nums text-text-primary">
{formatMoney(compensation.commission)}
</p>
</div>
<div className="rounded-[var(--radius-sm)] bg-background-secondary/70 p-3">
<p className="text-text-muted">{t('fixedSalarySubtotal')}</p>
<p className="font-medium tabular-nums text-text-primary">
{formatMoney(compensation.fixedSalary)}
</p>
</div>
<div className="rounded-[var(--radius-sm)] bg-background-secondary/70 p-3">
<p className="text-text-muted">{t('grossCompensation')}</p>
<p className="font-semibold tabular-nums text-text-primary">
{formatMoney(compensation.gross)}
</p>
</div>
<div className="flex flex-wrap items-center justify-between gap-2">
<h3 className="text-sm font-semibold text-text-primary">
{t('openMonthCompensation', {
date: openThrough ? formatDate(`${openThrough.slice(0, 10)}T12:00:00`) : '',
})}
</h3>
{compensationSplit.openPeriodKey ? (
<Button
size="sm"
variant="outline"
onClick={() => setIncomePeriodKey(compensationSplit.openPeriodKey)}
>
{t('showIncomeDetails')}
</Button>
) : null}
</div>
<CompensationFigures
totals={compensationSplit.open}
formatMoney={formatMoney}
labels={{
commission: t('commissionSubtotal'),
salary: t('fixedSalarySubtotal'),
gross: t('grossCompensation'),
}}
/>
</Card>
) : null}
<div className="space-y-2">
<h2 className="text-sm font-semibold text-text-primary">{t('transactionHistory')}</h2>
<div className="flex flex-wrap items-center justify-between gap-2">
<h2 className="text-sm font-semibold text-text-primary">{t('transactionHistory')}</h2>
{reportOrgSelected && report && !loading ? (
<Button size="sm" variant="outline" onClick={() => printStatement()}>
{t('printStatement')}
</Button>
) : null}
</div>
{loading ? (
<p className="text-sm text-text-muted">{tCommon('loading')}</p>
) : selectedMode && report && filterParty ? (
@@ -945,6 +1037,15 @@ export function BillingPaymentsPanel({
</td>
<td>
<div className="flex items-center gap-1">
{!editingAmount && staffMonthPeriodKey(row) ? (
<Button
size="sm"
variant="ghost"
onClick={() => setIncomePeriodKey(staffMonthPeriodKey(row))}
>
{t('showIncomeDetails')}
</Button>
) : null}
{editingAmount ? (
<>
<Button
@@ -1229,6 +1330,42 @@ export function BillingPaymentsPanel({
/>
)}
</div>
{incomePeriodKey && filterParty && sectionToPartyKind(filterParty.section) === 'staff' ? (
<BillingStaffIncomeDialog
userId={filterParty.id}
periodKey={incomePeriodKey}
to={to || undefined}
staffName={filterParty.name}
onClose={() => setIncomePeriodKey(null)}
/>
) : null}
</div>
);
}
function CompensationFigures({
totals,
formatMoney,
labels,
}: {
totals: StaffCompensationTotals;
formatMoney: (value: number) => string;
labels: { commission: string; salary: string; gross: string };
}) {
return (
<div className="grid grid-cols-1 gap-2 text-sm sm:grid-cols-3">
<div className="rounded-[var(--radius-sm)] bg-background-secondary/70 p-3">
<p className="text-text-muted">{labels.commission}</p>
<p className="font-medium tabular-nums text-text-primary">{formatMoney(totals.commission)}</p>
</div>
<div className="rounded-[var(--radius-sm)] bg-background-secondary/70 p-3">
<p className="text-text-muted">{labels.salary}</p>
<p className="font-medium tabular-nums text-text-primary">{formatMoney(totals.fixedSalary)}</p>
</div>
<div className="rounded-[var(--radius-sm)] bg-background-secondary/70 p-3">
<p className="text-text-muted">{labels.gross}</p>
<p className="font-semibold tabular-nums text-text-primary">{formatMoney(totals.gross)}</p>
</div>
</div>
);
}

View File

@@ -0,0 +1,190 @@
'use client';
import { useEffect, useState } from 'react';
import { useTranslations } from 'next-intl';
import { Button } from '@/components/ui/shared/Button';
import { DialogCloseButton } from '@/components/ui/shared/DialogCloseButton';
import {
ResponsiveDialogOverlay,
ResponsiveDialogPanel,
} from '@/components/ui/shared/ResponsiveDialog';
import { Table, TABLE_HEADER_CELL_CLASS } from '@/components/ui/shared/Table';
import { billingApi } from '@/lib/api/billing';
import { getUserFacingError } from '@/components/shared/formatApiError';
import { useAppFormatters } from '@/lib/hooks/useAppFormatters';
import type { StaffIncomeDetail } from '@/types/billing';
type BillingStaffIncomeDialogProps = {
userId: string;
periodKey: string;
to?: string;
staffName: string;
onClose: () => void;
};
export function BillingStaffIncomeDialog({
userId,
periodKey,
to,
staffName,
onClose,
}: BillingStaffIncomeDialogProps) {
const t = useTranslations('billing');
const tCommon = useTranslations('common');
const tErrors = useTranslations('errors');
const { formatDate, formatDateTime, formatMoney, formatNumber } = useAppFormatters();
const [detail, setDetail] = useState<StaffIncomeDetail['data'] | null>(null);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
let cancelled = false;
setLoading(true);
setError(null);
void billingApi
.getStaffIncome({ userId, periodKey, to })
.then((response) => {
if (!cancelled) setDetail(response.data);
})
.catch((err: unknown) => {
if (!cancelled) setError(getUserFacingError(err, tErrors, t('errorLoadIncome')));
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [periodKey, t, tErrors, to, userId]);
const commission = detail?.commission;
const mismatch =
commission?.postedAmount != null && commission.postedAmount !== commission.listedAmount;
const groupSum = (commission?.groups ?? []).reduce(
(sum, group) => sum + Number(group.amount),
0,
);
return (
<ResponsiveDialogOverlay onBackdropClick={onClose}>
<ResponsiveDialogPanel
maxWidthClass="sm:max-w-3xl"
role="dialog"
aria-modal="true"
aria-labelledby="staff-income-title"
>
<div className="mb-4 flex items-start justify-between gap-3">
<div className="min-w-0">
<h2 id="staff-income-title" className="text-base font-semibold text-text-primary">
{t('incomeDetailsTitle', { period: detail?.period.label ?? periodKey })}
</h2>
<p className="mt-1 text-sm text-text-muted">{staffName}</p>
{detail?.open && detail.reportDay ? (
<p className="mt-1 text-sm text-text-secondary">
{t('incomeThrough', { date: formatDate(`${detail.reportDay}T12:00:00`) })}
</p>
) : null}
</div>
<DialogCloseButton onClick={onClose} />
</div>
{loading ? <p className="text-sm text-text-muted">{tCommon('loading')}</p> : null}
{error ? <p className="text-sm text-red-700 dark:text-red-400">{error}</p> : null}
{detail && commission ? (
<div className="space-y-5">
<section className="space-y-2">
<h3 className="text-sm font-semibold text-text-primary">{t('commissionByStep')}</h3>
{mismatch ? (
<p className="text-sm text-text-secondary">
{t('incomePostedMismatch', {
posted: formatMoney(commission.postedAmount),
listed: formatMoney(commission.listedAmount),
})}
</p>
) : null}
{commission.groups.length > 0 ? (
<Table
headers={
<tr>
<th className={TABLE_HEADER_CELL_CLASS}>{t('incomeStep')}</th>
<th className={TABLE_HEADER_CELL_CLASS}>{t('incomeUnitAmount')}</th>
<th className={TABLE_HEADER_CELL_CLASS}>{t('incomeQuantity')}</th>
<th className={TABLE_HEADER_CELL_CLASS}>{t('incomeAmount')}</th>
</tr>
}
body={[
...commission.groups.map((group) => (
<tr key={`${group.catalogCode}:${group.unitAmount}`}>
<td className="text-sm text-text-primary">{group.label}</td>
<td className="text-sm tabular-nums text-text-secondary">
{formatMoney(group.unitAmount)}
</td>
<td className="text-sm tabular-nums text-text-secondary">
{formatNumber(Number(group.qty))}
</td>
<td className="text-sm tabular-nums text-text-primary">
{formatMoney(group.amount)}
</td>
</tr>
)),
<tr key="sum">
<td className="text-sm font-semibold text-text-primary">{t('incomeSum')}</td>
<td />
<td />
<td className="text-sm font-semibold tabular-nums text-text-primary">
{formatMoney(groupSum.toFixed(2))}
</td>
</tr>,
]}
/>
) : (
<p className="text-sm text-text-secondary">{t('incomeEmptyCommission')}</p>
)}
</section>
{commission.lines.length > 0 ? (
<section className="space-y-2">
<h3 className="text-sm font-semibold text-text-primary">{t('earningRecords')}</h3>
<Table
headers={
<tr>
<th className={TABLE_HEADER_CELL_CLASS}>{t('time')}</th>
<th className={TABLE_HEADER_CELL_CLASS}>{t('incomeStep')}</th>
<th className={TABLE_HEADER_CELL_CLASS}>{t('reference')}</th>
<th className={TABLE_HEADER_CELL_CLASS}>{t('incomeQuantity')}</th>
<th className={TABLE_HEADER_CELL_CLASS}>{t('incomeUnitAmount')}</th>
<th className={TABLE_HEADER_CELL_CLASS}>{t('incomeAmount')}</th>
</tr>
}
body={commission.lines.map((line) => (
<tr key={line.id}>
<td className="text-sm text-text-secondary">{formatDateTime(line.earnedAt)}</td>
<td className="text-sm text-text-primary">{line.label}</td>
<td className="text-sm text-text-secondary">{line.reference || '—'}</td>
<td className="text-sm tabular-nums text-text-secondary">
{formatNumber(Number(line.qty))}
</td>
<td className="text-sm tabular-nums text-text-secondary">
{formatMoney(line.unitAmount)}
</td>
<td className="text-sm tabular-nums text-text-primary">
{formatMoney(line.earnedAmount)}
</td>
</tr>
))}
/>
</section>
) : null}
<div className="flex justify-end">
<Button variant="ghost" onClick={onClose}>
{t('cancel')}
</Button>
</div>
</div>
) : null}
</ResponsiveDialogPanel>
</ResponsiveDialogOverlay>
);
}

View File

@@ -0,0 +1,438 @@
import type { CSSProperties } from 'react';
import { BrandLockup } from '@/components/ui/shared/BrandLockup';
export type BillingStatementPrintRow = {
number: number;
date: string;
reference: string;
amount: string;
direction: string;
};
export type BillingStatementPrintLabels = {
title: string;
addressedTo: string;
phone: string;
printedOn: string;
rowNumber: string;
date: string;
reference: string;
amount: string;
debit: string;
credit: string;
balance: string;
page: string;
range: string;
empty: string;
};
type BillingStatementPrintLayoutProps = {
locale: string;
fontFamily: string;
issuerName: string;
issuerPhone: string | null;
partyName: string;
labels: BillingStatementPrintLabels;
rows: readonly BillingStatementPrintRow[];
showTotals: boolean;
debit: string;
credit: string;
balance: string;
};
const PAGE = { width: 794, height: 1123 };
const INK = '#0f172a';
const MUTED = '#64748b';
const LINE = '#cbd5e1';
const RULE_GAP = 12;
const FA_RULE_DROP = 6;
const ARABIC_SCRIPT = /[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF]/;
const body = { color: INK, fontSize: 17, lineHeight: '22px' };
function printLabelStyle(rtl: boolean): CSSProperties {
return {
color: MUTED,
fontSize: 14,
fontWeight: 600,
lineHeight: '18px',
margin: 0,
...(rtl
? {
direction: 'rtl',
textAlign: 'right',
letterSpacing: '0px',
wordSpacing: '0px',
textTransform: 'none',
}
: { letterSpacing: '0.04em', textTransform: 'uppercase' }),
};
}
function printHeadingStyle(rtl: boolean): CSSProperties {
return {
margin: 0,
fontSize: 20,
fontWeight: 600,
lineHeight: '26px',
...(rtl
? {
direction: 'rtl',
textAlign: 'right',
letterSpacing: '0px',
wordSpacing: '0px',
textTransform: 'none',
}
: {}),
};
}
function printRtlValueStyle(value: string): CSSProperties {
const arabic = ARABIC_SCRIPT.test(value);
return {
direction: arabic ? 'rtl' : 'ltr',
unicodeBidi: 'isolate',
textAlign: 'right',
letterSpacing: '0px',
wordSpacing: '0px',
};
}
function valueStyle(value: string, rtl: boolean): CSSProperties {
return rtl ? printRtlValueStyle(value) : {};
}
function printRule(rtl: boolean): CSSProperties {
return {
borderTop: `1px solid ${LINE}`,
marginTop: rtl ? RULE_GAP + FA_RULE_DROP : RULE_GAP,
paddingTop: 8,
};
}
/** Previous rows were an 18px line box. 1.5× keeps the text clear of the grid. */
export const STATEMENT_TABLE_ROW_HEIGHT = 27;
const TABLE_FONT = 14;
/**
* Vazirmatn is painted on the bottom rule. 10px is about 2.5mm on the A4 page,
* enough to sit the glyphs in the middle of the row.
*/
const FA_CELL_LIFT = '-10px';
function faTextLift(rtl: boolean): CSSProperties {
return rtl ? { position: 'relative', top: FA_CELL_LIFT } : {};
}
function cellStyle(rtl: boolean): CSSProperties {
return {
boxSizing: 'content-box',
height: STATEMENT_TABLE_ROW_HEIGHT,
border: `1px solid ${LINE}`,
padding: 0,
color: INK,
fontSize: TABLE_FONT,
lineHeight: `${TABLE_FONT}px`,
fontWeight: 400,
verticalAlign: 'middle',
textAlign: rtl ? 'right' : 'left',
letterSpacing: '0px',
wordSpacing: '0px',
textTransform: 'none',
};
}
function cellContent(rtl: boolean): CSSProperties {
return {
boxSizing: 'border-box',
display: 'flex',
alignItems: 'center',
justifyContent: rtl ? 'flex-end' : 'flex-start',
height: STATEMENT_TABLE_ROW_HEIGHT,
margin: 0,
padding: '0 8px',
overflow: rtl ? 'visible' : 'hidden',
whiteSpace: 'nowrap',
// The capture paints `direction: rtl` backwards. Keep LTR here; the table
// direction still places the columns from the right.
direction: 'ltr',
unicodeBidi: 'isolate',
textAlign: rtl ? 'right' : 'left',
letterSpacing: '0px',
wordSpacing: '0px',
};
}
export function BillingStatementPrintLayout({
locale,
fontFamily,
issuerName,
issuerPhone,
partyName,
labels,
rows,
showTotals,
debit,
credit,
balance,
}: BillingStatementPrintLayoutProps) {
const rtl = locale === 'fa';
const head: CSSProperties = {
...cellStyle(rtl),
color: MUTED,
fontWeight: 600,
};
const columns = [labels.rowNumber, labels.date, labels.reference, labels.amount];
return (
<div
data-statement-root
dir="ltr"
style={{
boxSizing: 'border-box',
width: PAGE.width,
height: PAGE.height,
paddingTop: 16,
paddingRight: 24,
paddingBottom: rtl ? 20 : 8,
paddingLeft: 24,
backgroundColor: '#ffffff',
color: INK,
fontFamily,
fontSize: 17,
lineHeight: '22px',
direction: 'ltr',
display: 'flex',
flexDirection: 'column',
...(rtl ? { letterSpacing: '0px', wordSpacing: '0px' } : {}),
}}
>
<header
style={{
display: 'flex',
alignItems: 'center',
gap: 12,
borderBottom: `1px solid ${LINE}`,
paddingBottom: rtl ? RULE_GAP + FA_RULE_DROP : RULE_GAP,
}}
>
<div
data-statement-org
style={{
margin: 0,
minWidth: 0,
flex: 1,
alignSelf: 'center',
display: 'flex',
alignItems: 'center',
justifyContent: 'flex-start',
height: 56,
overflow: 'hidden',
fontSize: 28,
fontWeight: 600,
lineHeight: '56px',
direction: 'ltr',
letterSpacing: '0px',
wordSpacing: '0px',
}}
>
<span
data-statement-org-text
style={{
display: 'inline-block',
maxWidth: '100%',
overflow: 'visible',
lineHeight: '56px',
whiteSpace: 'nowrap',
verticalAlign: 'middle',
letterSpacing: '0px',
wordSpacing: '0px',
unicodeBidi: 'isolate',
direction: ARABIC_SCRIPT.test(issuerName) ? 'rtl' : 'ltr',
textAlign: ARABIC_SCRIPT.test(issuerName) ? 'right' : 'left',
}}
>
{issuerName}
</span>
</div>
<div
data-statement-lockup
style={{
flexShrink: 0,
alignSelf: 'center',
height: 32,
color: INK,
fontSize: 26,
lineHeight: '32px',
}}
>
<BrandLockup
style={{ display: 'inline-flex', alignItems: 'center', height: 32, verticalAlign: 'middle' }}
/>
</div>
<div style={{ flex: 1, minWidth: 0, textAlign: 'right' }}>
<p style={{ ...printLabelStyle(rtl), textAlign: 'right' }}>{labels.printedOn}</p>
{issuerPhone ? (
<p
style={{
...body,
margin: '2px 0 0',
fontWeight: 500,
textAlign: 'right',
direction: 'ltr',
unicodeBidi: 'isolate',
letterSpacing: '0px',
}}
>
{issuerPhone}
</p>
) : null}
</div>
</header>
<section
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'flex-start',
gap: 12,
marginTop: RULE_GAP,
}}
>
<div style={{ minWidth: 0 }}>
<p style={printLabelStyle(rtl)}>{labels.addressedTo}</p>
<p
style={{
margin: '2px 0 0',
fontSize: 20,
fontWeight: 600,
lineHeight: '26px',
...valueStyle(partyName, rtl),
}}
>
{partyName}
</p>
</div>
<div style={{ flexShrink: 0, textAlign: rtl ? 'right' : 'left' }}>
<p style={{ ...body, margin: 0, fontWeight: 500, ...valueStyle(labels.range, rtl) }}>{labels.range}</p>
</div>
</section>
<h1 style={{ ...printHeadingStyle(rtl), marginTop: RULE_GAP }}>{labels.title}</h1>
<table
dir={rtl ? 'rtl' : 'ltr'}
style={{
width: '100%',
borderCollapse: 'collapse',
tableLayout: 'fixed',
marginTop: RULE_GAP,
}}
>
<colgroup>
<col style={{ width: '8%' }} />
<col style={{ width: '24%' }} />
<col style={{ width: '38%' }} />
<col style={{ width: '30%' }} />
</colgroup>
<thead>
<tr>
{columns.map((column) => (
<th key={column} style={head}>
<div data-statement-cell style={cellContent(rtl)}>
<span style={faTextLift(rtl)}>{column}</span>
</div>
</th>
))}
</tr>
</thead>
<tbody>
{rows.length === 0 ? (
<tr>
<td colSpan={4} style={{ ...cellStyle(rtl), color: MUTED }}>
<div data-statement-cell style={{ ...cellContent(false), justifyContent: 'center' }}>
{labels.empty}
</div>
</td>
</tr>
) : (
rows.map((row) => (
<tr key={row.number}>
<td style={cellStyle(rtl)}>
<div data-statement-cell style={cellContent(rtl)}>
<span style={faTextLift(rtl)}>{row.number}</span>
</div>
</td>
<td style={cellStyle(rtl)}>
<div data-statement-cell style={cellContent(rtl)}>
<span style={faTextLift(rtl)}>{row.date}</span>
</div>
</td>
<td style={cellStyle(rtl)}>
<div data-statement-cell style={cellContent(rtl)}>
<span style={faTextLift(rtl)}>{row.reference}</span>
</div>
</td>
<td style={cellStyle(rtl)}>
<div data-statement-cell style={cellContent(rtl)}>
<span style={faTextLift(rtl)}>
{rtl && row.direction ? (
<span style={{ marginRight: 8, color: MUTED }}>{row.direction}</span>
) : null}
{row.amount}
{!rtl && row.direction ? (
<span style={{ marginLeft: 8, color: MUTED }}>{row.direction}</span>
) : null}
</span>
</div>
</td>
</tr>
))
)}
</tbody>
</table>
<div style={{ flex: 1 }} />
{showTotals ? (
<div
style={{
display: 'flex',
justifyContent: 'flex-end',
gap: 24,
...printRule(rtl),
}}
>
{[
[labels.debit, debit],
[labels.credit, credit],
[labels.balance, balance],
].map(([label, value]) => (
<div key={label} style={{ minWidth: 120 }}>
<p style={{ ...printLabelStyle(rtl), textAlign: rtl ? 'right' : 'left' }}>{label}</p>
<p
style={{
...body,
margin: '2px 0 0',
fontWeight: 600,
...valueStyle(value, rtl),
}}
>
{value}
</p>
</div>
))}
</div>
) : null}
<footer
style={{
display: 'flex',
justifyContent: 'space-between',
...printRule(rtl),
}}
>
<span style={printLabelStyle(rtl)}>{labels.page}</span>
</footer>
</div>
);
}

View File

@@ -50,8 +50,9 @@ import type { LabCaseDetail } from '@/types/cases';
import type { FdiToothId } from '@/types/treatment';
import type { LinkedOrganizationOption } from '@/types/treatment';
import type { ToothSelectionGroup } from '@/components/treatment/toothSelectionGroups';
import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog';
import type { ProsthesisCatalogEntry, ToothShadeCatalogEntry } from '@/types/treatment-catalog';
import type { VoiceApplySelection, VoiceExtractionResult } from '@/types/voice';
import { ToothShadeGuide } from '@/components/ui/shared/ToothShadeGuide';
const INPUT_CLASS =
'mt-1 w-full rounded-[var(--radius-md)] border border-border bg-background-secondary/90 text-text-primary text-sm px-3 py-2 placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-primary/35';
@@ -139,6 +140,7 @@ interface CaseCreatePanelProps {
labCase: LabCaseDetail;
canEdit: boolean;
prosthesisCatalog?: ProsthesisCatalogEntry[];
toothShadeCatalog?: ToothShadeCatalogEntry[];
/** Dictation owned by the Add case control. Applied onto this case's single plan. */
voiceResult?: VoiceExtractionResult | null;
onVoiceResultHandled?: () => void;
@@ -152,6 +154,7 @@ export function CaseCreatePanel({
labCase,
canEdit,
prosthesisCatalog,
toothShadeCatalog = [],
voiceResult = null,
onVoiceResultHandled,
onSaved,
@@ -182,6 +185,9 @@ export function CaseCreatePanel({
labCase.partnerClinicOrganizationId ?? '',
);
const [dueDate, setDueDate] = useState(toDateInputValue(labCase.dueDate));
const [toothShadeCode, setToothShadeCode] = useState<string | null>(
labCase.toothShadeCode ?? null,
);
const [plan, setPlan] = useState<LineDraft>(() => planFromDetail(labCase));
const [section, setSection] = useState<'details' | 'files' | 'messages'>('details');
const sectionCounts = useCaseSectionCounts(labCase.id, section);
@@ -222,6 +228,7 @@ export function CaseCreatePanel({
setPatientDisplayMobile(labCase.patientDisplayMobile ?? '');
setPartnerClinicOrganizationId(labCase.partnerClinicOrganizationId ?? '');
setDueDate(toDateInputValue(labCase.dueDate));
setToothShadeCode(labCase.toothShadeCode ?? null);
setPlan(planFromDetail(labCase));
setSection('details');
// Hydrate only when switching drafts — never re-apply the same id after autosave.
@@ -293,6 +300,7 @@ export function CaseCreatePanel({
patientDisplayMobile: patientDisplayMobile.trim() || null,
partnerClinicOrganizationId: partnerClinicOrganizationId || null,
dueDate: dueDate || null,
toothShadeCode,
toothProsthesis: plan.toothProsthesis.map((tp) => ({
tooth: tp.tooth,
prosthesisTypeCode: tp.prosthesisTypeCode,
@@ -307,6 +315,7 @@ export function CaseCreatePanel({
patientDisplayMobile,
partnerClinicOrganizationId,
dueDate,
toothShadeCode,
plan,
],
);
@@ -475,15 +484,20 @@ export function CaseCreatePanel({
* already has jobs is merged. A dictated due date and comment still land.
*/
function applyVoice(selection: VoiceApplySelection, applied: VoiceExtractionResult) {
const { line, dueDate: dictatedDueDate } = buildLabLineFromVoice(applied, selection, {
const {
line,
dueDate: dictatedDueDate,
toothShadeCode: dictatedShade,
} = buildLabLineFromVoice(applied, selection, {
prosthesisCatalog: prosthesisOptions,
});
onVoiceResultHandled?.();
if (dictatedDueDate) setDueDate(dictatedDueDate);
if (dictatedShade) setToothShadeCode(dictatedShade);
// Null when the dictation carried no line content — a due date on its own still lands.
// Without the notice, Apply on a row that lands no job closes the sheet and changes nothing.
if (!line) {
if (!dictatedDueDate) onError(tTreatment('voiceNothingExtracted'));
if (!dictatedDueDate && !dictatedShade) onError(tTreatment('voiceNothingExtracted'));
return;
}
@@ -662,6 +676,17 @@ export function CaseCreatePanel({
defaultToToday={false}
/>
</label>
{toothShadeCatalog.length > 0 ? (
<div className="sm:col-span-2">
<ToothShadeGuide
shades={toothShadeCatalog}
value={toothShadeCode}
onChange={setToothShadeCode}
disabled={disabled}
readOnly={disabled}
/>
</div>
) : null}
</div>
<UnderlineTabs

View File

@@ -60,7 +60,9 @@ import type {
LabCaseTaskGroup,
LabTaskStatus,
} from '@/types/cases';
import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog';
import type { ProsthesisCatalogEntry, ToothShadeCatalogEntry } from '@/types/treatment-catalog';
import { ToothShadeGuide } from '@/components/ui/shared/ToothShadeGuide';
import { isLabGeneratedCase } from '@/components/lab/labCaseOrigin';
function caseSheetLineNotes(labCase: LabCaseDetail): string[] {
const raw = [labCase.detail?.comment];
@@ -233,6 +235,9 @@ export interface CaseDetailPanelProps {
onImportantChange?: (checked: boolean) => void;
updatingExternalCode?: boolean;
onExternalCodeChange?: (externalCode: string | null) => void;
toothShadeCatalog?: ToothShadeCatalogEntry[];
updatingToothShade?: boolean;
onToothShadeChange?: (toothShadeCode: string | null) => void;
commentsSection?: ReactNode;
assignableStaff?: AssignableTaskStaff[];
canAssignTasks?: boolean;
@@ -274,6 +279,9 @@ export function CaseDetailPanel({
onImportantChange,
updatingExternalCode = false,
onExternalCodeChange,
toothShadeCatalog = [],
updatingToothShade = false,
onToothShadeChange,
commentsSection,
assignableStaff = [],
canAssignTasks = false,
@@ -436,6 +444,7 @@ export function CaseDetailPanel({
orderNumber: t('caseSheetOrderNumber'),
orderDate: t('caseSheetOrderDate'),
dateDue: t('caseSheetDateDue'),
toothShade: t('caseSheetToothShade'),
sender: t('caseSheetSender'),
recipient: t('caseSheetRecipient'),
patient: t('caseSheetPatient'),
@@ -543,6 +552,15 @@ export function CaseDetailPanel({
),
);
const canEditToothShade =
canEditImportant &&
isLabGeneratedCase(labCase.origin) &&
(!labCase.startedAt || (labCase.taskProgress?.completed ?? 0) === 0) &&
Boolean(onToothShadeChange);
// Read-only cases without a shade (all historical ones) skip the empty guide.
const showToothShadeGuide =
toothShadeCatalog.length > 0 && (canEditToothShade || Boolean(labCase.toothShadeCode));
return (
<div className="@container space-y-4 min-w-0">
<header className="grid grid-cols-1 items-start gap-3 border-b border-border pb-3 @2xl:grid-cols-[minmax(0,1fr)_auto] @2xl:gap-4">
@@ -577,6 +595,16 @@ export function CaseDetailPanel({
</>
) : null}
</div>
{showToothShadeGuide ? (
<ToothShadeGuide
className="mt-2"
shades={toothShadeCatalog}
value={labCase.toothShadeCode ?? null}
onChange={canEditToothShade ? onToothShadeChange : undefined}
disabled={updatingToothShade}
readOnly={!canEditToothShade}
/>
) : null}
</div>
{labCase.shareUrl ? (
<div className="shrink-0 @2xl:hidden">

View File

@@ -31,6 +31,7 @@ export type CaseSheetLabels = {
orderNumber: string;
orderDate: string;
dateDue: string;
toothShade: string;
sender: string;
recipient: string;
patient: string;
@@ -291,7 +292,7 @@ export function CaseSheetPrintLayout({
<section
style={{
display: 'grid',
gridTemplateColumns: '1fr 1fr 1fr',
gridTemplateColumns: '1fr 1fr 1fr 1fr',
alignItems: 'start',
gap: 12,
marginTop: RULE_GAP,
@@ -300,6 +301,11 @@ export function CaseSheetPrintLayout({
<MetaBlock label={labels.orderNumber} value={orderNumber} rtl={rtl} />
<MetaBlock label={labels.orderDate} value={formatCaseDateTime(orderDate, locale)} rtl={rtl} />
<MetaBlock label={labels.dateDue} value={formatCaseDateTime(labCase.dueDate, locale)} rtl={rtl} />
<MetaBlock
label={labels.toothShade}
value={labCase.toothShadeCode?.trim() || '—'}
rtl={rtl}
/>
</section>
<section

View File

@@ -30,6 +30,7 @@ import {
} from '@/lib/uploads/caseUploadQueue';
import { caseCommentsApi } from '@/lib/api/case-comments';
import { prosthesisCatalogApi } from '@/lib/api/prosthesis-catalog';
import { toothShadeCatalogApi } from '@/lib/api/tooth-shade-catalog';
import { treatmentCatalogApi } from '@/lib/api/treatment-catalog';
import { prosthesisJobPathLabel } from '@/components/treatment/prosthesisJobPath';
import { treatmentTypeLabelFromCatalog } from '@/components/shared/treatmentTypeDisplay';
@@ -44,7 +45,11 @@ import { MobileDetailBackButton } from '@/components/ui/shared/MobileDetailBackB
import { FORM_SELECT_CLASS } from '@/components/shared/formSelectStyles';
import { SearchBar } from '@/components/ui/shared/SearchBar';
import { AppDateInput } from '@/components/ui/shared/AppDateInput';
import type { ProsthesisCatalogEntry, TreatmentCatalogEntry } from '@/types/treatment-catalog';
import type {
ProsthesisCatalogEntry,
ToothShadeCatalogEntry,
TreatmentCatalogEntry,
} from '@/types/treatment-catalog';
import type {
AssignableTaskStaff,
CasesFilterOptions,
@@ -104,7 +109,9 @@ export function CasesPage() {
prosthesisTypes: [],
});
const [prosthesisCatalog, setProsthesisCatalog] = useState<ProsthesisCatalogEntry[]>([]);
const [toothShadeCatalog, setToothShadeCatalog] = useState<ToothShadeCatalogEntry[]>([]);
const [treatmentCatalog, setTreatmentCatalog] = useState<TreatmentCatalogEntry[]>([]);
const [updatingToothShade, setUpdatingToothShade] = useState(false);
const [selectedCaseId, setSelectedCaseId] = useState<string | null>(null);
const [mobileDetailOpen, setMobileDetailOpen] = useState(false);
@@ -301,6 +308,7 @@ export function CasesPage() {
useEffect(() => {
void casesApi.listFilterOptions().then((r) => setFilterOptions(r.data)).catch(() => {});
void prosthesisCatalogApi.list().then((r) => setProsthesisCatalog(r.data)).catch(() => {});
void toothShadeCatalogApi.list().then((r) => setToothShadeCatalog(r.data)).catch(() => {});
void treatmentCatalogApi.list().then((r) => setTreatmentCatalog(r.data)).catch(() => {});
if (canEdit) {
void casesApi.listAssignableStaff().then((r) => setAssignableStaff(r.data)).catch(() => {});
@@ -658,6 +666,28 @@ export function CasesPage() {
}
}
async function handleCaseToothShadeChange(toothShadeCode: string | null) {
if (!selectedCaseId || !canEdit || !selectedCase) return;
const caseId = selectedCaseId;
const previousCase = selectedCase;
setSelectedCase({ ...selectedCase, toothShadeCode });
setUpdatingToothShade(true);
toast.setError('');
try {
const response = await casesApi.setCaseToothShade(caseId, toothShadeCode);
if (selectedCaseIdRef.current === caseId) {
setSelectedCase(withKnownCaseFiles(response.data));
}
} catch (error: unknown) {
if (selectedCaseIdRef.current === caseId) setSelectedCase(previousCase);
toast.showError(getUserFacingError(error, tErrors, t('errorUpdateToothShade')));
} finally {
setUpdatingToothShade(false);
}
}
const filterSelectClass = `${FORM_SELECT_CLASS} w-full min-w-0 rounded-md py-1.5 text-xs sm:py-2 sm:text-sm`;
function renderCaseCard(item: LabCaseListItem) {
@@ -910,6 +940,7 @@ export function CasesPage() {
labCase={selectedCase}
canEdit={canEdit}
prosthesisCatalog={prosthesisCatalog}
toothShadeCatalog={toothShadeCatalog}
voiceResult={
voiceResult && voiceCaseIdRef.current === selectedCase.id ? voiceResult : null
}
@@ -1008,6 +1039,9 @@ export function CasesPage() {
onImportantChange={(checked) => void handleCaseImportantToggle(checked)}
updatingExternalCode={updatingExternalCode}
onExternalCodeChange={(code) => void handleCaseExternalCodeChange(code)}
toothShadeCatalog={toothShadeCatalog}
updatingToothShade={updatingToothShade}
onToothShadeChange={(code) => void handleCaseToothShadeChange(code)}
assignableStaff={assignableStaff}
canAssignTasks={canEdit}
assigningTaskId={assigningTaskId}

View File

@@ -8,6 +8,7 @@ import { LabCaseOriginBadge } from '@/components/ui/lab/LabCaseOriginBadge';
import { CaseTaskProgressBar } from '@/components/ui/lab/CaseDetailPanel';
import type { CaseTaskGroup } from '@/components/lab/taskListGrouping';
import { formatPatientName } from '@/components/lab/caseDetailUtils';
import { ToothShadeReadonlyText } from '@/components/ui/shared/ToothShadeGuide';
import { formatAppDate, APP_DATE } from '@/lib/i18n/format';
interface TaskCaseGroupHeaderProps {
@@ -57,6 +58,12 @@ export function TaskCaseGroupHeader({
</Badge>
) : null}
<LabCaseOriginBadge origin={caseGroup.origin} className="text-[10px]" />
{caseGroup.toothShadeCode ? (
<ToothShadeReadonlyText
code={caseGroup.toothShadeCode}
className="text-[10px] text-text-secondary"
/>
) : null}
</>
);

View File

@@ -0,0 +1,111 @@
'use client';
import { useTranslations } from 'next-intl';
import type { ToothShadeCatalogEntry } from '@/types/treatment-catalog';
type ToothShadeGuideProps = {
shades: readonly ToothShadeCatalogEntry[];
value: string | null;
onChange?: (code: string | null) => void;
disabled?: boolean;
/** When true, tabs are not interactive (still shows selected lift). */
readOnly?: boolean;
className?: string;
};
/**
* Physical shade-guide look: tooth tab + stem + label.
* Selected tab lifts via margin (not transform) so `overflow-x-auto` cannot clip the top.
*/
export function ToothShadeGuide({
shades,
value,
onChange,
disabled = false,
readOnly = false,
className = '',
}: ToothShadeGuideProps) {
const t = useTranslations('toothShade');
const interactive = !disabled && !readOnly && Boolean(onChange);
return (
<div className={`w-full min-w-0 border-y border-border/70 py-2 ${className}`}>
<p className="mb-1.5 text-center text-xs font-medium text-text-muted">{t('label')}</p>
{/* LTR in every locale so the tabs keep the physical guide order (0M → D). */}
<div className="flex w-full justify-center">
<div
dir="ltr"
className="inline-flex max-w-full gap-0.5 overflow-x-auto px-0.5 pb-0.5 [-ms-overflow-style:none] [scrollbar-width:none] sm:gap-1 [&::-webkit-scrollbar]:hidden"
role="radiogroup"
aria-label={t('label')}
aria-disabled={disabled || readOnly || undefined}
>
{shades.map((shade) => {
const selected = value === shade.code;
return (
<button
key={shade.code}
type="button"
role="radio"
aria-checked={selected}
disabled={!interactive}
title={shade.code}
onClick={() => {
if (!interactive || !onChange) return;
onChange(selected ? null : shade.code);
}}
className={`group relative flex shrink-0 flex-col items-center transition-[margin] duration-150 ease-out focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40 focus-visible:ring-offset-1 ${
selected ? 'mt-0 z-[1]' : 'mt-1'
} ${interactive ? 'cursor-pointer' : 'cursor-default'}`}
>
<span
className={`relative flex h-9 w-5 items-end justify-center overflow-hidden rounded-t-[0.65rem] border sm:h-10 sm:w-6 ${
selected
? 'border-primary border-[1.5px] shadow-[0_5px_8px_-3px_rgba(15,23,42,0.4)]'
: 'border-border/70 shadow-sm'
}`}
style={{ backgroundColor: shade.hex }}
aria-hidden
>
<span
className="mb-0.5 h-2 w-2.5 rounded-t-full bg-black/5 sm:h-2.5 sm:w-3"
style={{ boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.35)' }}
/>
</span>
<span
className={`h-2.5 w-[2px] sm:h-3 ${selected ? 'bg-primary/70' : 'bg-slate-400/80'}`}
aria-hidden
/>
<span
className={`mt-0.5 max-w-[2.1rem] truncate text-[9px] font-semibold leading-none sm:max-w-[2.4rem] sm:text-[10px] ${
selected ? 'text-primary' : 'text-text-secondary'
}`}
>
{shade.code}
</span>
</button>
);
})}
</div>
</div>
</div>
);
}
/** Compact labeled value for Tasks / PDF / share headers. */
export function ToothShadeReadonlyText({
code,
className = '',
}: {
code: string | null | undefined;
className?: string;
}) {
const t = useTranslations('toothShade');
if (!code) return null;
return (
<span className={className}>
<span className="text-text-muted">{t('label')}: </span>
<span className="font-medium text-text-primary tabular-nums">{code}</span>
</span>
);
}

View File

@@ -12,7 +12,11 @@ import { TreatmentDetailAttachmentsStrip } from '@/components/ui/treatment/Treat
import { VoiceRecordingBar } from '@/components/ui/treatment/VoiceRecordingBar';
import type { VoiceCaptureState } from '@/lib/voice/useVoiceCapture';
import type { LabCaseToothProsthesisDraft, TreatmentDetailDraft } from '@/types/treatment';
import type { ProsthesisCatalogEntry, TreatmentCatalogEntry } from '@/types/treatment-catalog';
import type {
ProsthesisCatalogEntry,
ToothShadeCatalogEntry,
TreatmentCatalogEntry,
} from '@/types/treatment-catalog';
import { treatmentTypeColor, treatmentTypeOptionStyle } from '@/components/shared/treatmentTypeDisplay';
import {
isDetailTypeSelected,
@@ -28,6 +32,7 @@ import {
WORKSPACE_ACTION_BTN_HEIGHT,
WorkspaceActionLabel,
} from '@/components/ui/shared/WorkspaceActionLabel';
import { ToothShadeGuide } from '@/components/ui/shared/ToothShadeGuide';
interface TreatmentDetailsEditorProps {
details: TreatmentDetailDraft[];
@@ -79,6 +84,9 @@ interface TreatmentDetailsEditorProps {
prosthesisCatalog?: ProsthesisCatalogEntry[];
/** Jobs live on the lab-case draft, not on TreatmentDetailDraft. */
toothProsthesis?: LabCaseToothProsthesisDraft[];
toothShadeCatalog?: ToothShadeCatalogEntry[];
toothShadeCode?: string | null;
onToothShadeChange?: (code: string | null) => void;
}
export function TreatmentDetailsEditor({
@@ -117,6 +125,9 @@ export function TreatmentDetailsEditor({
liveDetailCalculated,
prosthesisCatalog = [],
toothProsthesis = [],
toothShadeCatalog = [],
toothShadeCode = null,
onToothShadeChange,
}: TreatmentDetailsEditorProps) {
const t = useTranslations('treatment');
const tCommon = useTranslations('common');
@@ -388,6 +399,18 @@ export function TreatmentDetailsEditor({
) : null}
</div>
{activeDetail &&
labDependentCodes.has(activeDetail.treatmentType) &&
toothShadeCatalog.length > 0 ? (
<ToothShadeGuide
shades={toothShadeCatalog}
value={toothShadeCode}
onChange={onToothShadeChange}
disabled={readOnly}
readOnly={readOnly || !onToothShadeChange}
/>
) : null}
{chart ? (
<div className="relative min-w-0 w-full">
{chartLocked ? (

View File

@@ -31,6 +31,7 @@ import {
import { appointmentsApi } from '@/lib/api/appointments';
import { treatmentCatalogApi } from '@/lib/api/treatment-catalog';
import { prosthesisCatalogApi } from '@/lib/api/prosthesis-catalog';
import { toothShadeCatalogApi } from '@/lib/api/tooth-shade-catalog';
import { voiceApi } from '@/lib/api/voice';
import { useVoiceCapture } from '@/lib/voice/useVoiceCapture';
import { isMediaRecorderSupported } from '@/lib/voice/audioFormat';
@@ -94,7 +95,11 @@ import {
import type { Organization } from '@/types/organization';
import type { Patient } from '@/types/patient';
import type { AppointmentRecord } from '@/types/appointment';
import type { ProsthesisCatalogEntry, TreatmentCatalogEntry } from '@/types/treatment-catalog';
import type {
ProsthesisCatalogEntry,
ToothShadeCatalogEntry,
TreatmentCatalogEntry,
} from '@/types/treatment-catalog';
import type {
FdiToothId,
LabCaseDraft,
@@ -282,6 +287,7 @@ function mapLabCaseDraftFromApi(lc: PastLabCase): LabCaseDraft {
sentAt: lc.sentAt ?? null,
sends: lc.sends ?? [],
dueDate: lc.dueDate ?? null,
toothShadeCode: lc.toothShadeCode ?? null,
taskProgress: lc.taskProgress ?? null,
shareUrl: lc.shareUrl ?? null,
calculatedAmount: lc.calculatedAmount ?? null,
@@ -351,6 +357,7 @@ function serializeLabCases(drafts: LabCaseDraft[]): string {
destinationOrganizationId: lc.destinationOrganizationId ?? null,
detailClientId: lc.detailClientId,
dueDate: lc.dueDate ?? null,
toothShadeCode: lc.toothShadeCode ?? null,
attachmentIds: [...lc.attachmentIds].sort(),
toothProsthesis: [...lc.toothProsthesis]
.map((tp) => ({
@@ -375,6 +382,7 @@ function isLabCasesDirty(drafts: LabCaseDraft[], savedSnapshot: string | null):
lc.toothProsthesis.length > 0 ||
Boolean(lc.destinationOrganizationId) ||
Boolean(lc.dueDate) ||
Boolean(lc.toothShadeCode) ||
lc.attachmentIds.length > 0,
);
}
@@ -525,6 +533,7 @@ export function TreatmentWorkspace({
const [labDependentCodes, setLabDependentCodes] = useState<Set<string>>(new Set());
const [treatmentCatalog, setTreatmentCatalog] = useState<TreatmentCatalogEntry[]>([]);
const [prosthesisCatalog, setProsthesisCatalog] = useState<ProsthesisCatalogEntry[]>([]);
const [toothShadeCatalog, setToothShadeCatalog] = useState<ToothShadeCatalogEntry[]>([]);
const treatmentDropdownCatalog = useMemo(
() => treatmentCatalog.filter((entry) => entry.availableInTreatment),
[treatmentCatalog],
@@ -1208,11 +1217,12 @@ export function TreatmentWorkspace({
let cancelled = false;
void (async () => {
try {
const [orgsResponse, catalogResponse, prosthesisResponse, voiceResponse] =
const [orgsResponse, catalogResponse, prosthesisResponse, shadeResponse, voiceResponse] =
await Promise.all([
treatmentsApi.listLinkedOrganizations(),
treatmentCatalogApi.list(),
prosthesisCatalogApi.list(),
toothShadeCatalogApi.list(),
// Voice availability comes from the API, not a NEXT_PUBLIC_* var: those are
// baked in at build time, so enabling a locale would need a frontend rebuild.
// A failure here must not take the whole treatment tab down with it.
@@ -1223,6 +1233,7 @@ export function TreatmentWorkspace({
setOrgs(orgsResponse.data);
setTreatmentCatalog(catalogResponse.data);
setProsthesisCatalog(prosthesisResponse.data);
setToothShadeCatalog(shadeResponse.data);
setLabDependentCodes(
new Set(catalogResponse.data.filter((entry) => entry.labDependent).map((entry) => entry.code)),
);
@@ -1674,6 +1685,7 @@ export function TreatmentWorkspace({
),
attachmentIds: lc.attachmentIds,
dueDate: lc.dueDate ?? null,
toothShadeCode: lc.toothShadeCode ?? null,
};
})
.filter((row): row is NonNullable<typeof row> => row !== null);
@@ -2680,9 +2692,8 @@ export function TreatmentWorkspace({
tErrors,
]);
// Auto-create an unsent draft when the active detail is prosthesis (no wizard step).
// Auto-create an unsent draft when the active detail is prosthesis (shade + dispatch need a case).
useEffect(() => {
if (!showLabDispatch) return;
if (!canEditTreatmentForDay || !hasLiveContext) return;
const activeDetail = details.find((d) => d.clientId === activeDetailId);
if (!activeDetail || !labDependentCodes.has(activeDetail.treatmentType)) return;
@@ -2701,7 +2712,6 @@ export function TreatmentWorkspace({
isDetailLocked,
labCaseDrafts,
labDependentCodes,
showLabDispatch,
]);
const handleSendLabCase = useCallback(
@@ -3194,6 +3204,24 @@ export function TreatmentWorkspace({
toothProsthesis={
labCaseDraftForDetail(labCaseDrafts, activeDetailId)?.toothProsthesis ?? []
}
toothShadeCatalog={toothShadeCatalog}
toothShadeCode={
labCaseDraftForDetail(labCaseDrafts, activeDetailId)?.toothShadeCode ?? null
}
onToothShadeChange={(code) => {
const prev = labCaseDraftsRef.current;
const target = labCaseDraftForDetail(prev, activeDetailId);
const next = target
? prev.map((lc) =>
lc.clientId === target.clientId ? { ...lc, toothShadeCode: code } : lc,
)
: [
...prev,
{ ...newLabCaseDraft(), detailClientId: activeDetailId, toothShadeCode: code },
];
labCaseDraftsRef.current = next;
setLabCaseDrafts(next);
}}
chart={
<div ref={labPanelRef} className="min-w-0 w-full">
{showLabDispatch && labWorkspaceView === 'dispatch' ? (

View File

@@ -389,6 +389,18 @@ export function VoiceReviewSheet({
</span>
</Row>
) : null}
{available.toothShade && effective.toothShadeCode ? (
<Row
label={t('toothShadeLabel')}
checked={selection.toothShade}
onChange={toggle('toothShade')}
>
<span className="text-sm font-medium tabular-nums text-text-primary">
{effective.toothShadeCode}
</span>
</Row>
) : null}
</div>
)}

View File

@@ -6,6 +6,7 @@ import type {
BillingLedgerRow,
BillingNamedOrg,
BillingPartyReport,
StaffIncomeDetail,
BillingPartySearchResult,
BillingSheet,
BillingSheetCatalog,
@@ -116,6 +117,15 @@ export const billingApi = {
return response.data;
},
getStaffIncome: async (params: {
userId: string;
periodKey: string;
to?: string;
}): Promise<StaffIncomeDetail> => {
const response = await apiClient.get('/billing/staff-income', { params });
return response.data;
},
getPartyReport: async (params: {
partyKind: 'patient' | 'staff' | 'org';
partyId: string;

View File

@@ -16,6 +16,7 @@ export interface LabInternalCasePayload {
patientDisplayMobile?: string | null;
partnerClinicOrganizationId?: string | null;
dueDate?: string | null;
toothShadeCode?: string | null;
toothProsthesis?: Array<{
tooth: string;
prosthesisTypeCode: string;
@@ -195,6 +196,14 @@ export const casesApi = {
return response.data;
},
setCaseToothShade: async (
caseId: string,
toothShadeCode: string | null,
): Promise<{ success: boolean; data: LabCaseDetail }> => {
const response = await apiClient.patch(`/cases/${caseId}/tooth-shade`, { toothShadeCode });
return response.data;
},
listAttachments: async (
caseId: string,
): Promise<{ success: boolean; data: LabCaseAttachmentMeta[] }> => {

View File

@@ -0,0 +1,9 @@
import { apiClient } from './client';
import type { ToothShadeCatalogEntry } from '@/types/treatment-catalog';
export const toothShadeCatalogApi = {
list: async (): Promise<{ success: boolean; data: ToothShadeCatalogEntry[] }> => {
const response = await apiClient.get('/tooth-shade-catalog');
return response.data;
},
};

View File

@@ -215,11 +215,43 @@ export type BillingPartyReport = {
success: boolean;
data: BillingPartyReportRow[];
totals: { debit: string; credit: string; net: string };
staffCompensation: {
commission: string;
fixedSalary: string;
gross: string;
} | null;
issuer: { name: string; phone: string | null };
};
export type StaffIncomeDetail = {
success: boolean;
data: {
period: {
key: string;
label: string;
calendar: 'JALALI' | 'GREGORIAN';
start: string;
end: string;
};
open: boolean;
reportDay: string | null;
commission: {
postedAmount: string | null;
listedAmount: string;
groups: Array<{
catalogCode: string;
label: string;
unitAmount: string;
qty: string;
amount: string;
}>;
lines: Array<{
id: string;
earnedAt: string;
catalogCode: string;
label: string;
qty: string;
unitAmount: string;
earnedAmount: string;
reference: string;
}>;
};
};
};
export type PartnerPayment = {

View File

@@ -154,6 +154,8 @@ export interface LabCaseDetail {
isImportant: boolean;
/** Optional external lab-app code (e.g. exocad); used as PDF order number when set. */
externalCode?: string | null;
/** Optional VITA-style tooth shade for the whole case. */
toothShadeCode?: string | null;
referringClinicName?: string | null;
referringDentistName?: string | null;
patientDisplayName?: string | null;
@@ -309,6 +311,7 @@ export interface LabTaskListItem {
isImportant: boolean;
caseDueDate: string | null;
isCaseOverdue: boolean;
toothShadeCode?: string | null;
assignee: LabTaskUser | null;
assignedAt: string | null;
lastStatusChangedAt: string | null;

View File

@@ -17,3 +17,10 @@ export interface ProsthesisCatalogEntry {
chartRegion: 'crown' | 'root' | 'arch' | string;
stackGroup: 'restoration' | 'implant' | 'post_core' | 'arch' | string;
}
export interface ToothShadeCatalogEntry {
code: string;
family: string;
sortOrder: number;
hex: string;
}

View File

@@ -127,6 +127,7 @@ export interface PastLabCase {
}>;
sends?: LabCaseSendInfo[];
dueDate?: string | null;
toothShadeCode?: string | null;
taskProgress?: LabCaseTaskProgress | null;
attachments?: TreatmentAttachmentMeta[];
/** Present on sent cases — same share URL the lab Cases QR encodes. */
@@ -197,6 +198,7 @@ export interface LabCaseDraft {
sentAt?: string | null;
sends?: LabCaseSendInfo[];
dueDate?: string | null;
toothShadeCode?: string | null;
taskProgress?: LabCaseTaskProgress | null;
shareUrl?: string | null;
calculatedAmount?: string | null;
@@ -230,6 +232,7 @@ export interface SaveLabCasePayload {
}>;
attachmentIds?: string[];
dueDate?: string | null;
toothShadeCode?: string | null;
}
export interface SaveTreatmentPayload {
@@ -253,6 +256,7 @@ export interface LabCaseResponse {
} | null;
sends: LabCaseSendInfo[];
dueDate: string | null;
toothShadeCode?: string | null;
taskProgress?: LabCaseTaskProgress | null;
toothProsthesis?: LabCaseToothProsthesisDraft[];
attachments?: TreatmentAttachmentMeta[];

View File

@@ -59,6 +59,7 @@ export interface VoiceExtractionResult {
/** When false, the lab row must not tick itself — the name only approximately matched. */
labMatchExact: boolean;
dueDate: string | null;
toothShadeCode: string | null;
unresolved: VoiceUnresolvedItem[];
}
@@ -77,6 +78,7 @@ export interface VoiceApplySelection {
prosthesis: boolean;
lab: boolean;
dueDate: boolean;
toothShade: boolean;
}
export type VoicePhase = 'idle' | 'recording' | 'processing';