Compare commits

...

6 Commits

Author SHA1 Message Date
50fc9bbba7 Merge pull request 'improvements/pre-release-v2' (#129) from improvements/pre-release-v2 into master
All checks were successful
Registry — build, push, deploy / build-and-push (push) Successful in 21m31s
Registry — build, push, deploy / deploy (push) Successful in 1m31s
Reviewed-on: #129
Reviewed-by: aminmsvi <amn.mousavi@gmail.com>
2026-11-16 03:19:09 +03:30
4ca22aab8f improvements: branch reviewed. issues fixed.
All checks were successful
Production — tag build, push, deploy / build-and-push (push) Successful in 4m33s
Production — tag build, push, deploy / deploy (push) Successful in 15m19s
2026-11-16 03:10:54 +03:30
b78a4d88cb improvements: treatment's mobile UI fixed. 2026-11-16 02:39:01 +03:30
7586e88589 improvements: voice feature 502 bad gateway issue addressed. websocket connection issue fixed. 2026-11-16 01:56:20 +03:30
11c524d768 improvements: some unnecessary interuptions fixed when exporting a case to exocad. 2026-11-16 01:40:23 +03:30
135dc2bf3a improvements: billing improved!!! so did it's dashboard gadgets! 2026-11-16 01:08:13 +03:30
54 changed files with 1761 additions and 272 deletions

View File

@@ -11,11 +11,11 @@ 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 persisted commission, fixed salary, and gross from closed months.
- **Cash edits:** amount, note, and valid allocations only; 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; sent/started/outsource case → mirrored org rows; monthly commission and fixed salary → staff. 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 that rate once and sums that month's commissions; both are separate staff payables dated on the last day. 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 or proration.
- **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, dispatch creates mirrored pending obligations with no amount; only the destination lab's Billing editor sets the fee, which updates both sides.
- **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.
- **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.
- **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).
- Lab case pickers sort by `listedAt` desc (same COALESCE as Cases — never `sentAt` then `startedAt`).

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. The Commissions/Salary tab holds one current salary sheet; month-end rows are posted after the month ends. `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. `hideUnpricedTypes` defaults off and commission sheets cannot turn it on. See `.cursor/rules/billing.mdc` and `.cursor/skills/billing/SKILL.md`.
## Agent behavior
@@ -35,7 +35,7 @@ Treatment-type colors and labels: `components/shared/treatmentTypeDisplay.ts` +
## Today dashboard
CLINIC + LAB KPIs/charts in `modules/today/today.service.ts`. Lab gadgets count the same cases as Cases and Tasks (started own cases included; outsourced steps excluded). Deep links: `components/today/today-deep-links.ts`. Task KPIs need `TAB_TASKS_READ` (no owner bypass). Skill: `.cursor/skills/today-dashboard/SKILL.md`.
CLINIC + LAB KPIs/charts in `modules/today/today.service.ts`. Lab gadgets count the same cases as Cases and Tasks (started own cases included; outsourced steps excluded). A treatment editor and a task user each get a personal work-and-income chart for the open billing month. Deep links: `components/today/today-deep-links.ts`. Task KPIs need `TAB_TASKS_READ` (no owner bypass). Skill: `.cursor/skills/today-dashboard/SKILL.md`.
## Lab case share link
@@ -47,4 +47,4 @@ Logical failures: `AppException(ErrorCode.X)` → `errors.X` in en/fa/nl. UI: `g
## Notifications (inbox + live tabs)
Header bell: `UserNotification` + Socket.IO. Same `notification.created` also drives sidebar tab badges and soft list refresh on **currently open** Cases/Tasks/Treatment/Orgs pages. A case file upload emits `case-section.changed` on that socket (no inbox row) for the case Files/Messages counts. Inbox + Tasks/Treatment badges use **`CASE_COMPLETED`** (every task in the case done); per-step `TASK_COMPLETED` is timeline-only. Skills: `.cursor/skills/notifications-inbox/SKILL.md`, `.cursor/skills/tab-badges/SKILL.md`.
Header bell: `UserNotification` + Socket.IO. Nginx proxies `/socket.io/` to the API in `nginx.conf`, `http-only.conf`, `http-only.dev.conf`, and `nginx.ssl.conf.template`. Same `notification.created` also drives sidebar tab badges and soft list refresh on **currently open** Cases/Tasks/Treatment/Orgs pages. A case file upload emits `case-section.changed` on that socket (no inbox row) for the case Files/Messages counts. Inbox + Tasks/Treatment badges use **`CASE_COMPLETED`** (every task in the case done); per-step `TASK_COMPLETED` is timeline-only. Skills: `.cursor/skills/notifications-inbox/SKILL.md`, `.cursor/skills/tab-badges/SKILL.md`.

View File

@@ -14,10 +14,10 @@ alwaysApply: false
- **Comments:** a generated case hides the eye until a linked clinic is selected; that eye publishes the comment to the clinic. A linked lab reads the thread on the share page and does not use the eye. A received case uses the eye for the clinic. A lab-to-lab case uses it for the sending lab; the sender's handoff lists only comments with that control on.
- **Outsource** (`POST /cases/:id/outsource`, label `cases.sendCase`): one linked lab, checked in-progress prosthesis-job steps plus `model_design` / `model_create`, one `LAB_OUTSOURCE` child case. The child stores the sending lab as `referringClinicName` and clears dentist and partner clinic. Those parent steps leave Tasks until the child completes them (written back with no actor). Sender detail shows only that direct lab. The sender chart stays the full plan; the child chart is the selected jobs plus pontics on that bridge, or that line’s teeth for a model step (the whole plan for a historical `__case__` model step). Recall before any of those steps is completed. Received child cases have Outsource, not Start, Delete, or Edit. Scan, packing, and shipping stay on the owning lab. Child `sourceKey` is the child case id. When two selected steps share tooth, prosthesis type, and workflow step, `outsourceChildSourceKey` uses `childId:parentSourceKey` so the current-round unique index accepts both. `dedupeToothJobs` includes `sourceKey`.
- **Share link:** QR + URL when the case is sent **or** a lab-origin case is started; token API + focus page — see `.cursor/skills/lab-case-share-link/SKILL.md`.
- **Send to Exocad:** local DentalDB SQLite write from the case header, every origin, at every screen size, only in Chrome and Edge (`showOpenFilePicker`). Other browsers do not show the button. There is no local helper and no download fallback. A second send updates the same treatment (`importedOrderId`). An empty `externalCode` becomes that Exocad id when the file is written. The browser remembers the file handle only after the DentalDB check. The next send reopens that file when it still exists and skips Browse. A missing file shows Browse again. A file that is not a DentalDB database is not remembered, and Browse stays available. An empty `workParamsSHA` is copied from the newest saved case whose file name ends with `WorkParamsDB.xml` (not `WorkParamsDB-EndoCrown.xml`) onto a new `WorkParamsInfo` and `WorkParamsInfoLocal`. Do not set treatment `flags` to 16. The connect dialog says the feature is experimental and asks for a manual backup; Nudentic is not responsible. A tooth is written only when that work type and material already exist. Monolithic zirconia and PFZ are `Coping`, a pontic is `ReducedPontic`, and the FDI opposite is `Antagonist`/`Healthy` when that pair exists. Parameters come from the fullest saved tooth of the same pair, without shade. A Coping donor is the fullest tooth whose `ImplantType` already matches. `customized_abutment` on that Coping copies `CustomAbutment` only when a saved tooth of the same pair already has it; otherwise that value is not invented. A plain Coping copies `None` when a saved coping has it. Other abutment codes are not mapped. More than one technician is left unset. Client and Name reuse one existing match, or a complete first and last name; otherwise the case is not written and the toast says why. Notes are the comment body. There is no Local database tab. Keep `LocalDbSessionProvider`, the connect dialog, and the file open/write path.
- **Send to Exocad:** local DentalDB SQLite write from the case header, every origin, at every screen size, only in Chrome and Edge (`showOpenFilePicker`). Other browsers do not show the button. There is no local helper and no download fallback. A second send updates the same treatment (`importedOrderId`). An empty `externalCode` becomes that Exocad id when the file is written. The browser remembers the file handle only after the DentalDB check. The next send reopens that file when it still exists and skips Browse. A missing file shows Browse again. A file that is not a DentalDB database is not remembered, and Browse stays available. An empty `workParamsSHA` is copied from the newest saved case whose file name ends with `WorkParamsDB.xml` (not `WorkParamsDB-EndoCrown.xml`) onto a new `WorkParamsInfo` and `WorkParamsInfoLocal`. Do not set treatment `flags` to 16. The connect dialog says the feature is experimental and asks for a manual backup; Nudentic is not responsible. A tooth is written only when that work type and material already exist. Monolithic zirconia and PFZ are `Coping`, a pontic is `ReducedPontic`, and the FDI opposite is `Antagonist`/`Healthy` when that pair exists. Parameters come from the fullest saved tooth of the same pair, without shade. A Coping donor is the fullest tooth whose `ImplantType` already matches. `customized_abutment` on that Coping copies `CustomAbutment` only when a saved tooth of the same pair already has it; otherwise that value is not invented. A plain Coping copies `None` when a saved coping has it. Other abutment codes are not mapped. More than one technician is left unset. Client is an exact name, one unique token match, or a new client with the given name, including one word. An empty clinic name still writes the case. A patient name that cannot be split is not written and the toast says why. A new case gets the next `t_schaleId` for that client. After the write, the user can grant the CAD-Data folder so the empty `{date}_{practice}-{tray}` directory is created; cancelling that grant leaves the case in the database. Notes are the comment body. There is no Local database tab. Keep `LocalDbSessionProvider`, the connect dialog, and the file open/write path.
- **One plan:** a live case has one prosthesis plan. Clinic send still uses `treatmentDetailId` as `sourceKey`. Lab-origin cases use the case id. Outsource children use the child case id, or `childId:parentSourceKey` when two selected steps would collide (see Outsource). `LabCaseLine` is gone. Detail and New case use `UnderlineTabs`: Details, Files, Messages. Files and Messages show unread counts (`LabCaseSectionReadState`); opening Details does not clear them. `ATTACHMENT_ADDED` is not a sidebar badge. Origin is one combobox of linked clinics and labs, or a typed name. Dentist/Technician stays optional. Arch jobs (`UA`/`LA`) highlight the read-only FDI chart.
- **Case Sheet PDF:** same layout for portrait and landscape (Download PDF menu). One A4 page, scaled to fit — the chart is never split. Header is a flex row: current organization name (one line, 56px line box so html2canvas does not clip the 28px glyphs), Nudentic lockup aligned with that text, share QR at 88px inside a 96px frame with `fill` off (a stretched SVG is dropped by html2canvas; not a table cell). Print root top padding is 16px portrait / 24px landscape so the QR is not clipped; `html2canvas` `scrollY` is 0. The page stays LTR in every locale. On `fa`, the org name is a shrink-wrapped `inline-block` (`direction: ltr` unless the name itself contains Arabic script) with `letter-spacing` and `word-spacing` `0px` — a full-width RTL box gaps Latin words. Party and meta values use `printRtlValueStyle` (Arabic script stays RTL; Latin stays LTR and right-aligned). Section rules keep a 12px gap and 8px padding so the line clears the values; `FA_RULE_DROP` (6px) clears Persian descenders. `onclone` must not overwrite the name span’s direction. Print ink is `prosthesisTypePrintColorFromCatalog` (heaviest family swatch). Prosthesis rows are SVG boxes. Chart is 85% of the page width with capped glyph height, shared upper column widths, outline-only unselected teeth, root vs crown fills, a larger gap under the upper caption, and matching tooth/number/midline gaps on both arches. Bridge marks match the FDI chart: 10px `#009cae` dots on the column boundary in the tooth-to-number gap. `onclone` sizes the lockup SVGs and the organization-name line box. Hex inline styles only. Optional `externalCode` replaces the printed order number and the `case-sheet-{orderNumber}.pdf` filename.
- **Detail chrome:** The header follows the detail panel width (`@container`, not the viewport): two columns (info start, actions end) from `@2xl`, otherwise one stack with the buttons under the info: name and the same QR thumb (`w-24 sm:w-32`) on the first row, mobile/from/date on one wrapping line, then progress bar, external code, **Mark as important**, and billed, stacked and left aligned. Edit / Outsource / Send to Exocad / Get PDF are one equal-width grid (`responsiveFill`, truncating caption): 2 columns when narrow, one column per button from `@xl`, 2 columns in the `@2xl` end column with the QR below. Get PDF is a primary `CaseLifecycleButton` with no icon. Add files uses that button at the treatment action width. **Add case** is a full-width `px-6 py-3 text-base` split (label + mic) matching New treatment and Add detail voice. There is no Comments button, and opening Messages does not scroll the page. File cards: name at the start and checkbox at the end, then a clipped preview, then size over date at the start with the View/Download menu centered at the end. Remove is on that menu (`DELETE /cases/:id/attachments/:attachmentId`, confirm first). An in-progress upload is its own card with a progress bar. The sent-date line reads “Outsource {date}”.
- **Detail chrome:** The header follows the detail panel width (`@container`, not the viewport): two columns (info start, actions end) from `@2xl`, otherwise one stack with the buttons under the info: name and the same QR thumb (`w-24 sm:w-32`) on the first row, mobile/from/date on one wrapping line, then progress bar, external code, **Mark as important**, and billed, stacked and left aligned. The destination lab with `TAB_BILLING_EDIT` edits that fee (`PUT /billing/cases/:id/amount`) and the open case updates immediately; anyone else sees the stored fee, or the calculated quote when no fee is stored. Edit / Outsource / Send to Exocad / Get PDF are one equal-width grid (`responsiveFill`, truncating caption): 2 columns when narrow, one column per button from `@xl`, 2 columns in the `@2xl` end column with the QR below. Get PDF is a primary `CaseLifecycleButton` with no icon. Add files uses that button at the treatment action width. **Add case** is a full-width `px-6 py-3 text-base` split (label + mic) matching New treatment and Add detail voice. There is no Comments button, and opening Messages does not scroll the page. File cards: name at the start and checkbox at the end, then a clipped preview, then size over date at the start with the View/Download menu centered at the end. Remove is on that menu (`DELETE /cases/:id/attachments/:attachmentId`, confirm first). An in-progress upload is its own card with a progress bar. The sent-date line reads “Outsource {date}”.
- **Attachments:** no size cap. One file per request, streamed with `orgDiskStorage` (not memory). The client has no axios timeout. The upload queue sits with the toast, so leaving Files or Cases does not cancel it and does not refetch the case; the open case patches from the response. A draft flushes once, then keeps the new file id so autosave does not unlink it. Nginx `/api` uses `client_max_body_size 0`, `send_timeout 3600s`, and `proxy_request_buffering off`. JSON bodies stay on the Express limit; only multipart is unlimited. Production must recreate nginx from the SSL template. Staging also needs the Windows host nginx reloaded. Do not set `Content-Type: multipart/form-data` by hand.
- **Drafts rail:** unstarted lab-origin cases sit in a collapsed `TreatmentRailSection`; expands on click or **Add case**. Main list is received + started cases (`drafts=exclude` / `drafts=only`), newest first by `listedAt` (`LAB_CASE_LIST_ORDER_BY`; trigger `lab_cases_listed_at_sync` = `COALESCE(startedAt, sentAt)`). Never `orderBy startedAt, sentAt` and never a `GENERATED ALWAYS` `listedAt`.
- **Add case / Start / Delete draft:** `TAB_CASES_EDIT`. The rail button is full width. Its mic uses the existing lab voice apply on that case’s one plan (blank plan replaced, existing jobs merged). No draft yet → create the draft, then record. Delete only unstarted lab-origin drafts (`origin === LAB_INTERNAL && !startedAt`). Comments on Cases accept `TAB_CASES_*` (owners are not blocked by Tasks opt-in).

View File

@@ -12,10 +12,10 @@ alwaysApply: false
- **Tooth hits:** unrotated full cell, `pointerdown` only (not `click` too — double-toggles). Glyph `pointer-events-none`; nest scale/hover inside the rotate wrapper. Groups: `toothSelectionGroups.ts` (never 1-tooth connected); prune lab `toothProsthesis` on change. Done stores a jobs copy brush; **Clear this tooth** stores a clear brush. Ctrl/Cmd+click, drag, and Shift+range replay either action. Reset brush/range state whenever `detailClientId` changes so actions never cross details/lines.
- **Pontic picker:** Pontic remains selectable for pontic-first entry, but its empty suggestion slot appears only beside an immediate crown/indirect neighbor (filled stays visible). A tooth immediately beside Pontic initially enables Crown, Indirect, and Pontic (Pontic chains are allowed); assigning a Crown immediately enables Implant on that tooth, while Indirect does not. Changing one connected abutment restoration changes every restoration abutment in that Pontic span while preserving each tooth’s root/implant jobs. Removable on an FDI tooth shows the full-arch notice; only partial denture is tooth-selected.
- **Day strip:** `ScheduleDayPicker` `compact` centered in the header. Timed cards use purpose banners. Unscheduled cards use the same banner from the **first detail’s type only** (live draft for the open card); empty first line keeps chip theming. Trash inherits banner ink. Strip-delete only when `areUnscheduledDetailsStripDeletable` (blank lines or `[]`); persist `[]` then `DELETE /treatments/:id`.
- **Lab dispatch UI:** due date end-aligned beside title (`sm:flex-row` + `justify-between`; stacks on mobile). Job list is `LabCaseToothJobsList` → `ProsthesisJobLineLabel` (`13 · Pontic - 14 · PFZ Crown`; inherit `text-xs`; no category). Same-type teeth in one detail share a row; Connected badge only for a real bridge. Content clinical field = **Notes** (not case comments). Sent cases: dest/jobs share a row with the Cases QR thumb; tracker + comments are **full width below** the QR.
- **Lab dispatch UI:** due date end-aligned beside title (`sm:flex-row` + `justify-between`; stacks on mobile). Job list is `LabCaseToothJobsList` → `ProsthesisJobLineLabel` (`13 · Pontic - 14 · PFZ Crown`; inherit `text-xs`; no category). Same-type teeth in one detail share a row; Connected badge only for a real bridge. Content clinical field = **Notes** (not case comments). Sent cases: dest/jobs share a row with the Cases QR thumb; tracker + comments are **full width below** the QR. The fee line uses the draft’s `billedAmount` (mapped from the API and the send response). A sent case with no fee shows `labFeeSentNeedsAmount`.
- **Lab comments:** shared `LabCaseCommentsPanel` (newest-first; sent=`justify-start`, received=`justify-end`; `viewerSide`) across Treatment / Cases / Tasks / share. Use logical `text-start`/`text-end`, not left/right.
- **Detail chrome:** chips (type + teeth) + Add at top; **Remove** = trash on chip (unsent, including last line; disabled when day-locked / no edit / uploading). Last-line confirm: plan will be empty until Add. Empty `[]` shows `noDetails` (not the type-first overlay). New treatment seeds one blank detail. No delete in type/notes fields.
- **Patient search:** `PatientSearchCombobox` in the **page header** (workspace-wide). Opens today’s strip visit if any, else latest history. No visit/history → inline editor empty state pointing to **New treatment** in the rail (never a dialog, never auto-create). **New treatment** stays at the top of the left rail; selected-patient card sits under it. Picker: Walk-in first, then a matching full-width card for the current named patient (name + mobile/email, else hint), then search. Never auto-create from the appointment card.
- **Patient search:** `PatientSearchCombobox` in the **page header** (workspace-wide). Opens today’s strip visit if any, else latest history. No visit/history → inline editor empty state pointing to **New treatment** (never a dialog, never auto-create). **New treatment** stays at the top of the left rail; selected-patient card sits under it. Below `xl`, that card stays on the editor screen; history is the pane behind **History**. Picker: Walk-in first, then a matching full-width card for the current named patient (name + mobile/email, else hint), then search. Never auto-create from the appointment card.
- **Lab dispatch attention:** `LabDispatchAttentionPanel` — unsent lab-dependent details; quick jump to dispatch.
- **History API:** patient-scoped; filtered by provider on treatment or appointment — owners are not exempt.
- **History filters (client-side):** `PastTreatmentsPanel` — “Not shipped to lab” + single date; helpers in `treatmentHistoryFilters.ts`.

View File

@@ -47,15 +47,16 @@ 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.”
- Cash rows expose edit metadata/allocations. 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 Send/Start, outsource, monthly commission, and monthly salary.
- Case obligations are mirrored: sender/payer books show the destination as creditor; destination books show the sender as debtor. Stop/recall/replan voids obsolete case 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.
## Fee / commission editor
- Start date required. Empty Apply-to = everyone. Lines store money `amount`.
- `CLINIC_PRICE` / `LAB_PRICE` may set `hideUnpricedTypes`. Commission kinds always save it false. Existing production sheets become unchecked when the column is added; a later one-time migration forces commission sheets false again. Missing or zero prosthesis lines are hidden from the applicable chart. A destination lab's active flagged sheet also blocks clinic Send.
- With a destination `LAB_PRICE` flag off, missing/zero case prices do not become zero or partial obligations: Send creates mirrored pending obligations (`amount = null`). The destination lab's Billing editor sets the manual case fee; the service updates `LabCase.billedAmount` and both ledger rows atomically.
- With a destination `LAB_PRICE` flag off, missing or zero prices stay off the ledger. Send stores the quote. The destination lab can set the fee on the case before the work is finished. When every current-round task is done, the mirrored rows are created; an empty fee is a pending amount the lab can still set, and that save updates both rows.
- Treatment dispatch / outsource quote previews are not stored.
- A save replaces the lines the editor shows and keeps every stored line the editor does not send (`stain`, `glaze`, `build_up`, inactive prosthesis types). Those hidden lines still price existing tasks.
- Deploy migration `20261020170000_retire_billing_step_lines` copies collapsed-step prices before it deletes `design` and `design_customized_abutment`. It does not delete prosthesis-type rows or `commission_earnings`.
@@ -73,9 +74,9 @@ 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 snapshotted once from the sheet; 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 stays out of the ledger. Toman uses Jalali months; Dollar/Euro use Gregorian months.
- Staff summary subtotals come from those closed rows in the active date range: commission + fixed salary = gross. Cash affects net only. Staff cash remains `StaffPayment`.
- V1 deliberately has no attendance, proration, bonus, or payroll-tax model.
- 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 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

@@ -50,6 +50,7 @@ List item shape: `prosthesisGroups: { prosthesisTypeCode, teeth[], ponticTeeth?
- **Important + external code** (`TAB_CASES_EDIT`): **Mark as important** is centered in the header on `lg`. Below `lg` the header is one compact stack: name and the desktop QR thumb (`w-24 sm:w-32`) on the first row, mobile / from / date on one wrapping line, the progress bar (no separate “tasks completed” sentence), important and billed on one row, and Edit / Outsource / Get PDF sharing one row (`CaseLifecycleButton` `responsiveFill`). External code is under the progress bar in the start column, same width as the bar (no title; placeholder only); billed price is under important on `lg`. Save code on blur → `PATCH /cases/:id/external-code`. Edit, Outsource, Get PDF, and Add files use `CaseLifecycleButton` (primary, no icon; Treatment Lab dispatch / Chart / Add detail width from `lg` up). **Add case** is full width at New treatment size (`px-6 py-3 text-base`) and, when voice is available, splits like Add detail: label starts a blank draft, the mic records against the open draft (or creates one first). Apply still fills that case’s single plan. There is no second mic on the Details tab. There is no Comments button. Opening Messages does not scroll the page. Start and Delete on a draft use the lifecycle width. The sent-date line is `cases.sentAt` (“Outsource {date}”). File cards (`CaseFilesPanel`): name at the start and checkbox at the end, a clipped preview between them and the footer, then size over date at the start with the View/Download menu centered at the end. Each file being uploaded is its own card with a progress bar (one request per file). The job lives above the page, so leaving Files or Cases does not cancel it; coming back shows the same card. Finishing patches the open case from the upload response. It does not fetch the case again. A draft flushes once before the batch, then keeps the new file id locally so a later autosave does not unlink it. Remove one file from that menu after confirm (`DELETE /cases/:id/attachments/:attachmentId`): a clinic file still on a treatment is unlinked only; a lab upload with `detailId` null and no other case link is deleted from the database and disk. Tasks stays view-only.
- FDI chart (`CaseToothChartPanel`): prosthesis colors + **connected bridge dots** from `selectionGroupId` (`buildCaseConnectedTeeth` / `buildCaseProsthesisRows` in `caseDetailUtils.ts`).
- **Important + external code** (`TAB_CASES_EDIT`): **Mark as important** and the billed price sit under the external code field. The header layout follows the detail panel width (Tailwind container query `@container`, not the viewport). From `@2xl` (42rem) it is two columns (info start, actions end). Narrower, including the split list/detail view on a small laptop and phones, it is one stack with the buttons under the info: name and the desktop QR thumb (`w-24 sm:w-32`) on the first row, mobile / from / date on one wrapping line, then the progress bar (no separate “tasks completed” sentence), external code, important, and billed, stacked. The action buttons (Edit, Outsource, Send to Exocad, Get PDF) are one equal-width grid (`CaseLifecycleButton` `responsiveFill`, truncating caption): 2 columns when the panel is narrow, one equal column per button from `@xl`, 2 columns again in the `@2xl` end column (`@2xl:w-72`), with the QR below. A lone last button spans both columns. Send to Exocad shows at every screen size, but only when the browser can overwrite the picked file (Chrome and Edge). External code is the same width as the progress bar (no title; placeholder only). Save code on blur → `PATCH /cases/:id/external-code`. Add files uses that button at the treatment action width. **Add case** is full width at New treatment size (`px-6 py-3 text-base`) and, when voice is available, splits like Add detail: label starts a blank draft, the mic records against the open draft (or creates one first). Apply still fills that case’s single plan. There is no second mic on the Details tab. There is no Comments button. Opening Messages does not scroll the page. Start and Delete on a draft use the lifecycle width. The sent-date line is `cases.sentAt` (“Outsource {date}”). File cards (`CaseFilesPanel`): name at the start and checkbox at the end, a clipped preview between them and the footer, then size over date at the start with the View/Download menu centered at the end. Each file being uploaded is its own card with a progress bar (one request per file). The job lives above the page, so leaving Files or Cases does not cancel it; coming back shows the same card. Finishing patches the open case from the upload response. It does not fetch the case again. A draft flushes once before the batch, then keeps the new file id locally so a later autosave does not unlink it. Remove one file from that menu after confirm (`DELETE /cases/:id/attachments/:attachmentId`): a clinic file still on a treatment is unlinked only; a lab upload with `detailId` null and no other case link is deleted from the database and disk. Tasks stays view-only.
- **Case fee:** only the destination lab (`destinationOrganizationId` on the case detail) with `TAB_BILLING_EDIT` edits the billed amount. Save calls `PUT /billing/cases/:id/amount` and updates the open case through `onCaseUpdated`. Other viewers see the stored fee, or the calculated quote when none is stored.
- **Section badges:** Files counts `ATTACHMENT_ADDED` and Messages counts `LAB_COMMENT` / `CLINIC_COMMENT`, after `LabCaseSectionReadState`, excluding the actor. `GET /cases/:id/section-counts`. `POST /cases/:id/sections/:section/read` only when that tab is open and its count is greater than 0. Opening Details does not clear them. Uploads emit `case-section.changed` to other lab members who can read Cases or Tasks (no inbox card). The existing socket turns that into `tab-badges-changed`. `ATTACHMENT_ADDED` is not a sidebar Cases/Tasks/Treatment count. `LabCaseSectionReadState` has a composite id and stays off the AdminJS allowlist.
- **Attachment uploads:** no size limit in multer, axios, or nginx `/api` (`client_max_body_size 0`, `client_body_timeout 3600s`, `send_timeout 3600s`, `proxy_request_buffering off`, proxy read/send 3600s). The server-level `send_timeout 10` would cut a paused download, so `/api` overrides it. JSON and urlencoded bodies stay on the Express limits; only multipart is unlimited. Files stream to disk via `orgDiskStorage` under `uploads/lab-cases/{orgId}` (treatment uploads use `uploads/treatments`). The attachment row and the case link are one transaction; the disk file is removed only after that transaction commits on delete, and only for a lab-owned upload. A failed activity row does not fail the upload. Do not buffer the file in memory and do not set `Content-Type: multipart/form-data` yourself — that drops the boundary. Releasing this needs `prisma migrate deploy` (the backend container runs it on start; Postgres 15) and a nginx recreate from `nginx.ssl.conf.template`. Staging’s Windows host nginx is a separate paste-and-reload of `windows-edge-http.conf`; Docker alone leaves the 50MB edge. Uploaded bytes live on the backend container disk (`/app/uploads`, no volume) and can fill that disk.
- **Case Sheet PDF** — see below.
@@ -62,7 +63,7 @@ Writes the open case into a DentalDB SQLite file on this computer. Nothing is up
- Button `cases.sendToExocad` on the case header at every screen size, every origin, for anyone who can open the case, only when the browser can overwrite the picked file (`showOpenFilePicker`: Chrome and Edge). It is separate from Outsource. Safari and other browsers do not show it. There is no local helper program and no download fallback.
- `LocalDbSessionProvider` holds the open file. The browser overwrites the picked file and remembers that file handle (IndexedDB) only after the file passes the DentalDB check. The next send reopens the saved file when it still exists and skips Browse. A missing file shows Browse again. A file that is not a usable DentalDB database is not remembered, and the connect dialog stays open so Browse can be used again.
- The connect dialog warns that Send to Exocad is experimental, that the user must make a manual backup of the DentalDB file first, that Nudentic is not responsible for any issues, and that the user uses the feature on their own.
- Mapper: `frontend/src/components/local-db/exocadTransfer.ts`. Lab id `0`. The client is the case clinic name (the sheet sender). Reuse an existing client only when exactly one client name contains every token. A new client is created only when that name has a first and last name; a single token that is not unique is not written, and the toast says Client could not be filled. Never use practice id `2147483647`. Match a patient of that client by the same tokens, ignoring order. DentalDB stores the family name in `fname` and the given name in `lname`. A new patient is created only when both parts exist. Otherwise nothing is written and the toast says Name could not be filled. `t_Notes` is the case comment bodies, or the detail comment when the thread is empty. `Treatment.importedOrderId` is the Dyolink case id, so a second send updates that treatment and replaces its `ToothWork` rows. One case is one transaction: a failed insert rolls the case back and the database is unchanged. When `workParamsSHA` is empty, copy that hash onto a new `WorkParamsInfo` and `WorkParamsInfoLocal` from the newest saved case whose file name ends with `WorkParamsDB.xml` (not `WorkParamsDB-EndoCrown.xml`), then set `workParamsSHA` and `workParamInfoId`. Do not set treatment `flags` to 16. The CAD-Data project folder is still created by Exocad's own Save.
- Mapper: `frontend/src/components/local-db/exocadTransfer.ts`. Lab id `0`. The client is the case clinic name (the sheet sender). Reuse a client when the trimmed name matches one client, ignoring case, or when exactly one client name contains every token. Otherwise create a client with the name as given, including one word. Several partial matches do not pick a client. An empty clinic name still writes the case on one empty-named client. Never use practice id `2147483647`. Match a patient of that client by the same tokens, ignoring order. DentalDB stores the family name in `fname` and the given name in `lname`. A new patient is created only when both parts exist. Otherwise nothing is written and the toast says Name could not be filled. `t_Notes` is the case comment bodies, or the detail comment when the thread is empty. `Treatment.importedOrderId` is the Dyolink case id, so a second send updates that treatment and replaces its `ToothWork` rows. A new case sets `t_schaleId` to one more than that client's highest tray, or 1. An update keeps a tray that is already set. The project directory is `{date}_{practice}-{tray}` from the stored treatment date. After the database write, the user grants the `CAD-Data` folder once; that handle is remembered and only the empty project directory is created. If that grant is cancelled, the case stays in the database and the toast says Save can still fail. One case is one transaction: a failed insert rolls the case back and the database is unchanged. When `workParamsSHA` is empty, copy that hash onto a new `WorkParamsInfo` and `WorkParamsInfoLocal` from the newest saved case whose file name ends with `WorkParamsDB.xml` (not `WorkParamsDB-EndoCrown.xml`), then set `workParamsSHA` and `workParamInfoId`. Do not set treatment `flags` to 16.
- A tooth is written only when the catalog name has an obvious Exocad material and that exact `WorkTypeSN` + `MaterialSN` already exists on a saved tooth. Copy numeric and textual parameters and their dependents from the fullest saved tooth of that same pair. For a Coping, that donor is the fullest tooth whose `ImplantType` already matches. Do not copy shade. Do not copy a donor with no parameters, and do not copy one material's numbers onto another. Obvious pairs: Monolithic Zirconia and PFZ Crown = `Coping`/`ZI`; PFM = `Coping`/`NP`; Full Metal = `AnatomicCrown`/`NP`; PMMA = `AnatomicCrown`/`PMMA`; Glass Ceramic Crown = `AnatomicCrown`/`GCER`; pontic = `ReducedPontic` plus the connected crown material when that pontic pair exists; IPS Overlay = `OverlayCrown`/`LS2`. Pressed Ceramic / IPS e.max (`AnatomicCrown`/`LS2`), PEEK (`AnatomicCrown`/`PEEK`), Veneer Zirconia (`Veneer`/`ZI`), IPS veneers (`Veneer`/`LS2`), and Zirconia Overlay (`AnatomicInlay`/`ZI`) are the same rule: written only when the opened file already has that pair. Each written tooth also gets its FDI opposite as `Antagonist`/`Healthy` when that pair exists and the opposite is not itself a restoration. When the file already stores them, the case scan mode is `AntagonistType` `RegisteredJaws` and the tooth shade is `---`. A file with exactly one technician assigns that technician. More than one technician is left unset. Temporary resin, veneer/inlay/onlay/overlay full-contour or layered with no material in the name, cast post, fiber post, and an abutment with no crown get no tooth row. The case header is still created. `customized_abutment` (Custom Abutment (Titanium)) on a Coping copies `ImplantType` `CustomAbutment` from a saved tooth of that same pair when the file already has it. If it does not, that value is not invented and the crown is copied from a `None` coping when one exists. A plain Coping copies `ImplantType` `None` when a saved coping has it, and does not take `CustomAbutment` from another tooth. Other abutment codes are not mapped. An abutment on a tooth that was written is not listed again. The skipped toast still lists teeth that were not written.
- When the file is written and `externalCode` is empty, save the Exocad `treatment_id` through `PATCH /cases/:id/external-code` (`TAB_CASES_EDIT`).
- There is no Local database tab. Send to Exocad keeps `LocalDbSessionProvider`, `LocalDbConnectDialog`, and the file open/write path.

View File

@@ -47,11 +47,13 @@ Full tab-badge map: `.cursor/skills/tab-badges/SKILL.md`.
CASE_SENT, CLINIC_COMMENT, LAB_COMMENT (+ LAB_COMMENT_CLINIC), CASE_IMPORTANT, CASE_COMPLETED (all tasks in the case done — not each step), PARTNER_CASE_CREATED (lab-origin Start, once, to the linked clinic `TAB_TREATMENT_EDIT` or lab `TAB_CASES_READ`, share-link href), TASK_ASSIGNED (assignee only), CONNECTION_REQUEST, STAFF_INVITE — see service call sites. When that generated case is fully done, the same partner also gets `CASE_COMPLETED` on the share link.
Billing notices go to `TAB_BILLING_READ`, including the actor: `BILLING_CASE_FEE` / `BILLING_CASE_FEE_PENDING` when a received or outsourced case obligation is inserted (every current-round task done), `BILLING_PAYMENT_PENDING` when a shared payment is created or edited back to waiting, and `BILLING_PAYMENT_DECLINED` to the recorder. The href is `/billing?partyId=&partyName=&partySection=clinics|labs` with no date range, so Transactions opens with that organization selected and shows obligations and payments.
**Inbox card context** is denormalized inside `UserNotificationService.notify()` (`enrichInboxPayload`) from ids already on the payload (`labCaseId`, `taskId`, `fromOrganizationId`). Emit sites stay thin (`{ labCaseId }`, etc.). Inbox list/read does **not** join related tables. Older rows may lack these fields until new events are emitted.
**Realtime auth:** after access-token refresh (proactive, axios 401 retry, or `checkAuth`), frontend dispatches `dyolink:access-token-refreshed` so `RealtimeProvider` reconnects with the new cookie.
**Realtime auth:** after access-token refresh (proactive, axios 401 retry, or `checkAuth`), frontend dispatches `dyolink:access-token-refreshed` so `RealtimeProvider` reconnects with the new cookie. Nginx must proxy `/socket.io/` to the API. That block is in `nginx.conf`, `http-only.conf`, `http-only.dev.conf`, and `nginx.ssl.conf.template`. A `location /` that only reaches Next.js drops the socket.
## Frontend UI
- `NotificationBell` + `NotificationsPage` + `NotificationCard` (full-width page list; same card height; extra context truncated on one line)
- Deep links: `/cases?caseId=`, `/tasks?taskId=`, `/treatment?labCaseId=`, `/organizations`, `/staff`
- Deep links: `/cases?caseId=`, `/tasks?taskId=`, `/treatment?labCaseId=`, `/organizations`, `/staff`, `/billing?partyId=`

View File

@@ -53,14 +53,17 @@ Day axis tick is month + day (`APP_DATE.chartAxisDay` via `mapWeekChartBuckets`)
## Chart period dropdowns
Seven time-window charts support a compact header `<select>` via `ChartCard` `headerAction` (no taller widgets). Periods persist in `localStorage` (`chart-periods.ts`) and are sent on `GET /today/summary`.
Time-window charts support a compact header `<select>` via `ChartCard` `headerAction` (no taller widgets). Periods persist in `localStorage` (`chart-periods.ts`) and are sent on `GET /today/summary`.
| Chart | Periods | Direction |
|-------|---------|-----------|
| Appointments (all / mine), lab task activity, cases due | week, month | lookback (cases due = **forward**) |
| My work and income | week, month | open billing month by default; week is the last 7 days |
| Treatment mix, case partners, efficiency | week, month, year | lookback |
Do **not** put year on day-series charts. Backend: `daysForChartPeriod` + `buildLocalDayBuckets` in `today.service.ts`.
Do **not** put year on day-series charts. Backend: `daysForChartPeriod` + `buildLocalDayBuckets` in `today.service.ts`. The three money donuts keep week as the last 7 days. Their month is the org’s open billing month through today (Jalali for Toman, Gregorian for Dollar/Euro), not a rolling 30 days.
**My work and income** (`chart-my-treatment-work` / `chart-my-task-work`) is a composed chart for `TAB_TREATMENT_EDIT` and for task users. Bars are that person’s treatment details, or tasks they completed. The line is their commission that day plus an even share of the open-month salary preview. Period totals sit in the same bottom legend as the other day charts, and the card header stays a title plus the week/month select. Recorded staff payments appear in the tooltip. An all-zero period uses the same empty state as the other charts. Default period is the open billing month; week is the last 7 days. My billed mix, billed by dentist, and commission by staff stay as they are.
## Layout and rings

View File

@@ -22,7 +22,7 @@ Thin route: `app/[locale]/(dashboard)/treatment/page.tsx` (supports `?appointmen
1. **Day strip** — `AppointmentsStrip.tsx` renders `DayStripItem[]` (`appointment` | `unscheduled`) via `DayStripCard`. Header uses **`ScheduleDayPicker` `compact`**: date is centered in a 3-col grid; no “Schedule date” label; **Today** sits on the navigator (`CalendarDaySelect` when the label row is hidden). Timed appointments keep treatment-type pastel banners. Unscheduled cards use the same banner from the **first detail’s type only** (`unscheduledStripColorCode`; live draft for the open card; `draftHydratingRef` must be set **before** strip/appointment pick so overlay does not paint the previous card’s type). Empty first line → chip theming even if later lines are typed. Trash inherits banner ink on typed cards. Strip trash only when `areUnscheduledDetailsStripDeletable` (no type/teeth/notes/attachments, including `[]`). Workspace fetches `GET /appointments` **and** `GET /treatments/day`. Patient search (`PatientSearchCombobox`) sits in the **page header** (workspace-wide). **New treatment** is one shared `Button` at the **top of the left rail**, with the selected-patient card under it: it opens `NewTreatmentPatientPicker` (Walk-in always first, then a matching full-width card for the current named patient with name + mobile/email or hint, then search). Creating happens only after an explicit patient choice — never from the selected appointment card. New treatment seeds one blank detail so the type field is ready; a persisted empty plan hydrates as `[]` until Add (`noDetails` copy — not the type-first overlay). Last-line chip delete confirms the plan will be empty until Add.
1. **Day strip** — `AppointmentsStrip.tsx` renders `DayStripItem[]` (`appointment` | `unscheduled`) via `DayStripCard`. Header uses **`ScheduleDayPicker` `compact`**: date is centered in a 3-col grid; no “Schedule date” label; **Today** sits on the navigator (`CalendarDaySelect` when the label row is hidden). Timed appointments keep treatment-type pastel banners. Unscheduled cards use the same banner from the **first detail’s type only** (`unscheduledStripColorCode`; live draft for the open card; `draftHydratingRef` must be set **before** strip/appointment pick so overlay does not paint the previous card’s type). Empty first line → chip theming even if later lines are typed. Trash inherits banner ink on typed cards. Strip trash only when `areUnscheduledDetailsStripDeletable` (no type/teeth/notes/attachments, including `[]`). Workspace fetches `GET /appointments` **and** `GET /treatments/day`. Patient search (`PatientSearchCombobox`) sits in the **page header** (workspace-wide). **New treatment** is one shared `Button` at the **top of the left rail**, with the selected-patient card under it: it opens `NewTreatmentPatientPicker` (Walk-in always first, then a matching full-width card for the current named patient with name + mobile/email or hint, then search). Creating happens only after an explicit patient choice — never from the selected appointment card. Below `xl`, that card stays on the editor screen; history is the pane behind **History**. New treatment seeds one blank detail so the type field is ready; a persisted empty plan hydrates as `[]` until Add (`noDetails` copy — not the type-first overlay). Last-line chip delete confirms the plan will be empty until Add.
2. **Treatment preview** — `TreatmentPreviewCard.tsx` (history browse only; omitted for the live draft)
@@ -41,7 +41,7 @@ Right-column entry is **not** a three-step wizard. Type dropdown + `TreatmentDet
| Stage | UI | When |
|-------|-----|------|
| **Treatment** | Type dropdown + `TreatmentDetailAttachmentsStrip`, `FdiToothChart` / `ProsthesisAssignChart`, full-width Notes | Default |
| **Lab** | `LabCasesDispatchPanel` in the chart slot | Lab-dependent type + user clicks **Lab dispatch** (or rail / Go to dispatch). Auto-ensures a shipment draft (teeth/arch not required to create the draft). **No default lab or prosthesis type** on a new detail (including siblings in the same plan). Last **3 sent** labs appear as chips under search — pick is explicit. Comments stay on the dispatch panel. After send, the same case QR as lab Cases is shown (`shareUrl`): dest/jobs share a row with the thumb; tracker + comments are full width below. |
| **Lab** | `LabCasesDispatchPanel` in the chart slot | Lab-dependent type + user clicks **Lab dispatch** (or rail / Go to dispatch). Auto-ensures a shipment draft (teeth/arch not required to create the draft). **No default lab or prosthesis type** on a new detail (including siblings in the same plan). Last **3 sent** labs appear as chips under search — pick is explicit. Comments stay on the dispatch panel. After send, the same case QR as lab Cases is shown (`shareUrl`): dest/jobs share a row with the thumb; tracker + comments are full width below. The stored lab fee (`billedAmount` on the lab-case draft, kept from the send response) is shown under that; a sent case with no fee uses `labFeeSentNeedsAmount`, not the pre-send unpriced copy. |
- Prosthesis types are assigned on the chart (`ProsthesisAssignChart` + `ProsthesisJobPopover`; stacking / disable / suggestion slots in `pickerPolicy()` in `prosthesisTree.ts`). The picker is two columns (`4fr` wrapping category grid / `1fr` add-ons) with a vertical `border-e` divider. Category and subcategory tiles (and matching leaves) show SVGs from `src/assets/prosthesis-catalog` (served from `public/prosthesis-catalog`) via `ProsthesisCatalogIcon` + `prosthesisCatalogIcons.ts`. Production Docker must copy `public/` into the standalone image (see `.cursor/rules/frontend-assets.mdc`). **Category / filled addon** tiles use `md` icons on a shared `items-end` stage and a reserved two-line label (`/` wraps with `<wbr>`). **Subcategory / leaf** tiles use `sm` icons, one-line ellipsis labels, and vertically center icon+label (`min-h-[4.25rem]`); implant/post-core use a taller box so they stay inside the card. Family pastels: `PROSTHESIS_CATEGORY_COLORS` (indirect/veneer sky, implant green, pontic orange, removable pink, appliance aqua). Screen type names: `prosthesisTypeLabelStyleFromCatalog`; Case Sheet print hex: `prosthesisTypeLabelColorFromCatalog`. Category tiles keep the wrapping `minmax(8rem, 1fr)` grid and stretch to fill the overlay; expanded children use `minmax(10.2rem, 1fr)` with a parent-colored **L** rail sized to the first child card (not a per-card tree). Parent-bar back arrow is black. Child labels stay one line and ellipsize (`…`) when they overflow. **Add detail**, Lab dispatch, and Chart share one control width (`WorkspaceActionLabel` in `TreatmentDetailsEditor`). Indirect children are **Veneer → Inlay → Onlay → Overlay** (same order as the category title). Crown leaves without a dedicated SVG use the monolithic zirconia drawing, not the Crown parent icon. Empty crown suggestion: plus + dashed chip (`addonCrownCanBeAdded`) inside a full-height slot; after a crown is picked the slot stays as the filled type chip. **Pontic** uses that same column whenever `pickerPolicy()` enables the Pontic tile (`addonPonticCanBeAdded`; filled chip after apply; click applies immediately). Arch Upper/Lower/Both is a compact `h-8` segmented control at half the tree column width — it **is** the assignment (`retargetArchJobs`): Both→Upper/Lower drops the other jaw; Upper/Lower→Both copies the type onto the empty jaw; Upper↔Lower moves the job. Chart Upper/Lower arch labels are dashed outline buttons with plus (open the picker; control shows current jobs, or the clicked jaw if none). Category parents use the heaviest family pastel; children only lighten. One **restoration** per tooth (crown / veneer-inlay-onlay-overlay). **Screw-retained** is implant (`stackGroup: implant`, paints the crown) and is itself the restoration — no crown suggestion slot, and Crown / Indirect are disabled. Implant or post & core (without a non-crown restoration) shows a **crown** suggestion slot. A veneer/inlay/onlay/overlay hides the suggestion slot. **Post & core** category is visible but disabled when a restoration or implant is on the tooth. **Implant** category is disabled when post & core is on the tooth. Complete denture / overdenture / appliances / digital use **Upper arch / Lower arch** (`UA`/`LA`). **Partial denture** is tooth-level (select FDI teeth, Removable in the tooth picker); after send it is **one lab job** for all those teeth. Picker leaves are filtered by `chartRegion` so Removable appears in both tooth and arch pickers. Prosthesis FDI teeth **must** have jobs — never persist selected teeth without `toothProsthesis` (`pruneDetailTeethToJobs`). Catalog has no `addonKind` — stacking uses `stackGroup` plus `pickerPolicy()` suggestion slots.
- Detail chips show **type + teeth**, not “Detail N”. Lab-dependent chips use colored sent/unsent text (same size as the label). **Sent** means the linked lab case has `sentAt`. The edit lock is separate: the line stays editable until a lab step is completed. Sent date stays on Lab dispatch.
@@ -205,7 +205,7 @@ Use shared `Checkbox` (not native `<input type="checkbox">`) to avoid focus-driv
Walk-in uses one sentinel `Patient` per clinic (`isWalkIn`, hidden from Patients/search/booking). Display via i18n, never the stored name. Named patients are this-org only (`createdByOrganizationId`); another clinic’s identification is `PATIENT_IDENTIFICATION_UNAVAILABLE`, not a shared row. Patient search: same workspace patient with a live visit → no-op; else open today’s strip visit if any; else load latest history into the editor; **no history and no strip visit → do not auto-create**. Detach the previous visit, keep the searched patient, and show an inline editor empty state (`noTreatmentFoundTitle` / `noTreatmentFoundBody`) that points to **New treatment** in the rail (Walk-in, current named patient card, or search).
Walk-in uses one sentinel `Patient` per clinic (`isWalkIn`, hidden from Patients/search/booking). Display via i18n, never the stored name. Named patients are this-org only (`createdByOrganizationId`); another clinic’s identification is `PATIENT_IDENTIFICATION_UNAVAILABLE`, not a shared row. Patient search: same workspace patient with a live visit → no-op; else open today’s strip visit if any; else load latest history into the editor; **no history and no strip visit → do not auto-create**. Detach the previous visit, keep the searched patient, and show an inline editor empty state (`noTreatmentFoundTitle` / `noTreatmentFoundBody`) that points to **New treatment** on the same screen (Walk-in, current named patient card, or search).
Draft writes for appointments require provider match (`ensureAppointmentProvider`). Standalone requires `treatment.providerUserId === actor`.

View File

@@ -44,7 +44,7 @@ frontend/src/
**Treatment tab:** Preview and editable form are **separate** until the user clicks **Load into workspace** on a history item. See `.cursor/skills/treatment-workspace/SKILL.md` before changing that flow.
**Treatment edit / details (quick ref):**
- Day/mode gate: editable only for live draft on today/future (`canEditTreatmentForDay`). Past day / historical load → read-only form. Patient search sits in the **page header** (workspace-wide). If the patient has a visit on the day strip, that visit opens; else the latest history plan loads. Day arrows that land on a day with no visit reset the workspace to one blank detail and no patient, the same as opening Treatment with nothing selected. A day that has a visit still opens it. If neither exists, the editor shows an inline empty state (no dialog) pointing to **New treatment** in the rail — do not auto-create. **New treatment** is at the top of the left rail (selected-patient card below it) and opens a picker: Walk-in first, then a matching card for the current named patient (name + mobile/email), then search. It does not auto-copy the appointment card’s patient. New treatment seeds one blank detail; a persisted empty plan loads as `[]` until Add.
- Day/mode gate: editable only for live draft on today/future (`canEditTreatmentForDay`). Past day / historical load → read-only form. Patient search sits in the **page header** (workspace-wide). If the patient has a visit on the day strip, that visit opens; else the latest history plan loads. Day arrows that land on a day with no visit reset the workspace to one blank detail and no patient, the same as opening Treatment with nothing selected. A day that has a visit still opens it. If neither exists, the editor shows an inline empty state (no dialog) pointing to **New treatment** — do not auto-create. **New treatment** is at the top of the left rail (selected-patient card below it). Below `xl`, that card stays on the editor screen; history is the pane behind **History**. and opens a picker: Walk-in first, then a matching card for the current named patient (name + mobile/email), then search. It does not auto-copy the appointment card’s patient. New treatment seeds one blank detail; a persisted empty plan loads as `[]` until Add.
- **Unscheduled strip cards** use the same treatment-type banner as appointments from the **first detail’s type only** (`unscheduledStripColorCode`; live draft for the open card). Empty first line → chip theming even if later lines are typed. Strip trash only when every line is blank (no type/teeth/notes/attachments, including `[]`); typed cards need chip-delete first. Backend `DELETE /treatments/:id` is empty-only (`TREATMENT_HAS_DETAILS`).
- A sent line stays editable until any lab task is completed, including a step finished by a further lab. Then the line locks (`TREATMENT_DETAIL_SENT`). **Add detail** still OK same day; **Remove detail** = trash on chip (unsent, including last line; day/edit gates apply). A sent line cannot be removed. Empty details persist as `[]`.
- **Entry:** Type dropdown + compact attachments strip (`TreatmentDetailAttachmentsStrip`) on one row (plus **Lab dispatch** / **Chart** toggle when the type is lab-dependent; dispatch is primary, Chart is outline; **Add detail** uses the same width), then bordered FDI chart (Cases chrome/scale) **or** the lab dispatch panel in that same slot, then full-width auto-growing **Notes**. Prosthesis types are assigned on the chart (teeth, or Upper/Lower arch labels for jaw products — dashed outline + plus). Arch Upper/Lower/Both remaps existing `UA`/`LA` jobs (Both→Upper clears lower). Picker: `4fr` wrapping category grid / `1fr` add-ons with a vertical divider; tiles use `ProsthesisCatalogIcon` (`md` + two-line labels on category/addon; `sm` + centered icon/label on child cards); expanded children use a parent-colored **L** rail sized to the first child card; parent-bar back arrow is black; empty crown slot is plus + dashed “Crown can be added”; filled crown slot stays visible so it can be changed. Screen type names use `prosthesisTypeLabelStyleFromCatalog`. Implant/post & core show a **crown** suggestion slot; a veneer/inlay/onlay/overlay hides it. The empty **Pontic** suggestion appears only beside an immediate crown/indirect neighbor; a filled Pontic stays visible and the category remains available for pontic-first entry. Post & core is disabled after crown or implant; Implant is disabled after post & core; screw-retained does not suggest another crown. Removable on a tooth shows the full-arch notice (partial is tooth-selected; complete/overdenture use arch controls). Prosthesis teeth always have jobs (hydrate/save prune). Lab-rail / Go to dispatch **opens the dispatch view** (`pendingScrollToLabRef`). Detail chips show type + teeth; lab-dependent chips use colored sent/unsent text. Sent follows the linked lab case `sentAt` (or the detail’s own `sentAt`); editing stays open until a lab step is completed. The sent date stays on dispatch. Lab dispatch keeps comments.
@@ -70,11 +70,11 @@ 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, case Send/Start/outsource, and staff commission plus fixed salary after each month ends; Toman uses Jalali months, Dollar/Euro Gregorian. 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 from closed months. 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; v1 has no proration/attendance. 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 creates mirrored amount-pending obligations; only the destination lab sets the fee and it updates both orgs. 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 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`.
**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 clinic or patient name that cannot fill Client or Name is not written, and the toast says which name failed. 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`.
**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`.
**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.
@@ -82,7 +82,7 @@ frontend/src/
- **Clinic:** treatment **provider** with `TAB_TREATMENT_EDIT` — read-only tasks, can comment. Same QR as lab Cases appears on Treatment **Lab dispatch** after send (dest/jobs beside the thumb; tracker + comments full width below).
- Logged out → login with `?from=` → `storeAuthRedirectFromPath` then `useEnterAppWhenAuthenticated` (`consumeAuthRedirect` once after org ready — not inside `useAuth.login()` / `registerTrial`). Trial register uses the same hook; staff/org invite (including `password_setup`) then `login()` + `navigateIntoAppIfOrgSelected`. See `.cursor/rules/post-auth-navigation.mdc`.
**Today dashboard:** KPIs + charts per org type/permissions; deep links via `today-deep-links.ts` (Tasks KPIs/charts, case partners). See `.cursor/skills/today-dashboard/SKILL.md`.
**Today dashboard:** KPIs + charts per org type/permissions; deep links via `today-deep-links.ts` (Tasks KPIs/charts, case partners). A treatment editor and a task user each get a personal work-and-income chart (bars for their work, a line for commission plus the open-month salary preview). See `.cursor/skills/today-dashboard/SKILL.md`.
## Backend layout

View File

@@ -0,0 +1,15 @@
ALTER TYPE "UserNotificationType" ADD VALUE IF NOT EXISTS 'BILLING_CASE_FEE';
ALTER TYPE "UserNotificationType" ADD VALUE IF NOT EXISTS 'BILLING_CASE_FEE_PENDING';
ALTER TYPE "UserNotificationType" ADD VALUE IF NOT EXISTS 'BILLING_PAYMENT_PENDING';
ALTER TYPE "UserNotificationType" ADD VALUE IF NOT EXISTS 'BILLING_PAYMENT_DECLINED';
-- A case fee is a debt only after every current-round step is done.
DELETE FROM "billing_ledger_entries" AS entry
WHERE entry."sourceType" IN ('LAB_CASE', 'OUTSOURCE_CASE')
AND EXISTS (
SELECT 1
FROM "lab_case_tasks" AS task
WHERE task."labCaseId" = entry."sourceId"
AND task."roundId" IS NULL
AND task."status" <> 'COMPLETED'
);

View File

@@ -620,6 +620,10 @@ enum UserNotificationType {
CONNECTION_REQUEST
STAFF_INVITE
SEAT_EXPIRING
BILLING_CASE_FEE
BILLING_CASE_FEE_PENDING
BILLING_PAYMENT_PENDING
BILLING_PAYMENT_DECLINED
}
/// Fan-out inbox row per recipient. Independent of LabCaseActivity tab badges.

View File

@@ -160,6 +160,22 @@ export class BillingController {
return this.billingService.partyReport(req.user.id, organizationId, query);
}
@Put('cases/:labCaseId/amount')
@ApiOperation({ summary: 'Set the destination lab fee for a case' })
setCaseBilledAmount(
@Param('labCaseId', ParseUUIDPipe) labCaseId: string,
@Body() dto: UpdateObligationAmountDto,
@Req() req: { user: { id: string; organizationId?: string } },
) {
const organizationId = this.billingService.getOrganizationIdFromUser(req.user);
return this.billingService.setCaseBilledAmount(
req.user.id,
organizationId,
labCaseId,
dto.amount,
);
}
@Put('obligations/:entryId/amount')
@ApiOperation({ summary: 'Set a destination lab case obligation amount' })
updateObligationAmount(

View File

@@ -1,8 +1,10 @@
import { Module } from '@nestjs/common';
import { NotificationsModule } from '../notifications/notifications.module';
import { BillingController } from './billing.controller';
import { BillingService } from './billing.service';
@Module({
imports: [NotificationsModule],
controllers: [BillingController],
providers: [BillingService],
exports: [BillingService],

View File

@@ -12,10 +12,12 @@ import {
BillingObligationSourceType,
BillingSheetKind,
CatalogEntityKind,
LabTaskStatus,
LinkStatus,
PartnerPaymentRecordedBy,
PartnerPaymentStatus,
Prisma,
UserNotificationType,
} from '@prisma/client';
import { PrismaService } from '../../../prisma/prisma.service';
import { AppException, ErrorCode, type ErrorCodeValue } from '../../common/errors';
@@ -93,12 +95,23 @@ import {
staffBillingPeriodForDate,
staffBillingPeriodFromKey,
staffPeriodKeyMatchesCurrency,
staffPeriodElapsedDays,
staffPeriodLastDay,
staffPeriodsAfter,
type StaffBillingPeriod,
} from './staff-billing-period';
import { resolvePartnerCashSides } from './billing-cash-edit';
import { resolvePartnerCaseObligation } from './billing-case-obligation';
import { UserNotificationService } from '../notifications/user-notification.service';
type CaseFeeNotice = {
organizationId: string;
partyId: string;
partyName: string;
partySection: 'clinics' | 'labs';
amountPending: boolean;
labCaseId: string;
};
type PaymentListQuery = {
q?: string;
@@ -127,6 +140,7 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
constructor(
private readonly prisma: PrismaService,
private readonly catalogLabels: CatalogLabelService,
private readonly userNotifications: UserNotificationService,
) {}
getOrganizationIdFromUser(user: { organizationId?: string }) {
@@ -840,7 +854,13 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
cases.map((row) => [row.id, row.origin] as const),
);
const previews =
query.partyKind === 'staff'
? await this.openStaffPreviewRows(organizationId, query.partyId, query, obligations)
: [];
const rows = [
...previews,
...obligations.map((row) => {
const amount = row.amount?.toFixed(2) ?? null;
const signedAmount = row.signedAmount?.toFixed(2) ?? null;
@@ -869,6 +889,7 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
acknowledgement: 'none' as const,
canAllocate: false,
countsInTotals: amount != null,
projected: false,
};
}),
...cash.data.map((row) => {
@@ -897,6 +918,7 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
updatedAt: row.updatedAt,
allocations: row.allocations,
countsInTotals: sharedCashCountsInPartyReport(row),
projected: false,
};
}),
].sort((a, b) => b.occurredAt.localeCompare(a.occurredAt));
@@ -922,19 +944,20 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
.reduce((sum, row) => sum + Number(row.signedAmount ?? 0), 0);
const commissionSubtotal =
query.partyKind === 'staff'
? obligations
? rows
.filter(
(row) =>
row.sourceType ===
BillingObligationSourceType.STAFF_COMMISSION_MONTH,
row.lineKind === 'OBLIGATION' &&
row.sourceType === BillingObligationSourceType.STAFF_COMMISSION_MONTH,
)
.reduce((sum, row) => sum + Number(row.amount ?? 0), 0)
: 0;
const fixedSalarySubtotal =
query.partyKind === 'staff'
? obligations
? rows
.filter(
(row) =>
row.lineKind === 'OBLIGATION' &&
row.sourceType === BillingObligationSourceType.STAFF_SALARY_MONTH,
)
.reduce((sum, row) => sum + Number(row.amount ?? 0), 0)
@@ -960,6 +983,129 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
};
}
/** Unsaved commission and salary for the month still in progress. */
private async openStaffPreviewRows(
organizationId: string,
userId: string,
query: { from?: string; to?: string },
existing: Array<{ sourceType: BillingObligationSourceType; sourceId: string }>,
) {
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;
}
if (query.from && dateOnlyUtc(query.from).getTime() > reportDay.getTime()) return [];
const period = staffBillingPeriodForDate(now, currency);
const span = staffPeriodElapsedDays(period, reportDay);
if (!span) return [];
const through = new Date(reportDay.getTime() + 24 * 60 * 60 * 1000);
const occurredAt = reportDay.toISOString();
const rows: Array<{
id: string;
lineKind: 'OBLIGATION';
direction: 'CREDIT';
amount: string;
signedAmount: string;
amountPending: false;
canEditAmount: false;
occurredAt: string;
sourceType: BillingObligationSourceType;
sourceId: string;
caseOrigin: null;
reference: string;
note: null;
acknowledgement: 'none';
canAllocate: false;
countsInTotals: true;
projected: true;
}> = [];
const commissionId = `${userId}:${period.key}:commission`;
const salaryId = `${userId}:${period.key}:salary`;
const hasStored = (sourceType: BillingObligationSourceType, sourceId: string) =>
existing.some((row) => row.sourceType === sourceType && row.sourceId === sourceId);
if (!hasStored(BillingObligationSourceType.STAFF_COMMISSION_MONTH, commissionId)) {
const sum = await this.prisma.commissionEarning.aggregate({
where: {
organizationId,
userId,
earnedAt: { gte: period.start, lt: through },
},
_sum: { earnedAmount: true },
});
const amount = roundBillingAmount(Number(sum._sum.earnedAmount ?? 0));
if (amount > 0) {
rows.push(
this.staffPreviewRow(
BillingObligationSourceType.STAFF_COMMISSION_MONTH,
commissionId,
amount,
period.key,
occurredAt,
),
);
}
}
if (!hasStored(BillingObligationSourceType.STAFF_SALARY_MONTH, salaryId)) {
const membership = await this.prisma.membership.findUnique({
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,
),
);
}
}
}
return rows;
}
private staffPreviewRow(
sourceType: BillingObligationSourceType,
sourceId: string,
amount: number,
reference: string,
occurredAt: string,
) {
const money = amount.toFixed(2);
return {
id: `projected:${sourceId}`,
lineKind: 'OBLIGATION' as const,
direction: 'CREDIT' as const,
amount: money,
signedAmount: (-amount).toFixed(2),
amountPending: false as const,
canEditAmount: false as const,
occurredAt,
sourceType,
sourceId,
caseOrigin: null,
reference,
note: null,
acknowledgement: 'none' as const,
canAllocate: false as const,
countsInTotals: true as const,
projected: true as const,
};
}
async updateCaseObligationAmount(
actorUserId: string,
organizationId: string,
@@ -999,7 +1145,7 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
);
}
await this.prisma.$transaction(async (tx) => {
const notice = await this.prisma.$transaction(async (tx) => {
await tx.labCase.update({
where: { id: entry.sourceId },
data: {
@@ -1007,12 +1153,48 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
billedAmountManual: true,
},
});
await this.syncPartnerCaseObligations(tx, entry.sourceId);
return this.postCaseDebtIfComplete(tx, entry.sourceId, new Date());
});
if (notice) await this.notifyCaseFee(notice);
return { success: true as const, data: { amount: amount.toFixed(2) } };
}
async setCaseBilledAmount(
actorUserId: string,
organizationId: string,
labCaseId: string,
value: string,
) {
await this.assertCanEdit(actorUserId, organizationId);
const amount = parseMoney(value);
if (amount <= 0) {
throw new AppException(ErrorCode.BILLING_AMOUNT_INVALID, HttpStatus.BAD_REQUEST);
}
const labCase = await this.prisma.labCase.findFirst({
where: { id: labCaseId, destinationOrganizationId: organizationId },
select: { id: true },
});
if (!labCase) {
throw new AppException(
ErrorCode.BILLING_OBLIGATION_NOT_EDITABLE,
HttpStatus.BAD_REQUEST,
);
}
const notice = await this.prisma.$transaction(async (tx) => {
await tx.labCase.update({
where: { id: labCaseId },
data: {
billedAmount: new Prisma.Decimal(amount.toFixed(2)),
billedAmountManual: true,
},
});
return this.postCaseDebtIfComplete(tx, labCaseId, new Date());
});
if (notice) await this.notifyCaseFee(notice);
return { success: true as const, data: { amount: amount.toFixed(2) } };
}
async getStaffSalarySheet(actorUserId: string, organizationId: string) {
await this.assertCanRead(actorUserId, organizationId);
return { success: true as const, data: await this.loadStaffSalarySheet(organizationId) };
@@ -1439,6 +1621,16 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
include: partnerPaymentInclude,
});
});
const sender = await this.organizationParty(organizationId);
if (sender) {
await this.notifyBillingParty({
organizationId: counterpartId,
type: UserNotificationType.BILLING_PAYMENT_PENDING,
partyId: organizationId,
partyName: sender.name,
partySection: sender.section,
});
}
return { success: true as const, data: mapPartnerPayment(payment, organizationId) };
}
@@ -1734,6 +1926,18 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
});
return payment;
});
if (shared && sides.counterpartyId) {
const sender = await this.organizationParty(organizationId);
if (sender) {
await this.notifyBillingParty({
organizationId: sides.counterpartyId,
type: UserNotificationType.BILLING_PAYMENT_PENDING,
partyId: organizationId,
partyName: sender.name,
partySection: sender.section,
});
}
}
return { success: true as const, data: mapPartnerPayment(updated, organizationId) };
}
@@ -1804,6 +2008,18 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
});
return row;
});
if (decision === 'DECLINE' && payment.recorderOrganizationId) {
const decliner = await this.organizationParty(organizationId);
if (decliner) {
await this.notifyBillingParty({
organizationId: payment.recorderOrganizationId,
type: UserNotificationType.BILLING_PAYMENT_DECLINED,
partyId: organizationId,
partyName: decliner.name,
partySection: decliner.section,
});
}
}
return { success: true as const, data: mapPartnerPayment(updated, organizationId) };
}
@@ -2411,7 +2627,95 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
});
}
async syncPartnerCaseObligations(db: Prisma.TransactionClient, labCaseId: string) {
private async organizationParty(organizationId: string) {
const organization = await this.prisma.organization.findUnique({
where: { id: organizationId },
select: { name: true, type: { select: { name: true } } },
});
if (!organization) return null;
return {
name: organization.name,
section: organization.type.name === 'LAB' ? ('labs' as const) : ('clinics' as const),
};
}
private async notifyBillingParty(input: {
organizationId: string;
type: UserNotificationType;
partyId: string;
partyName: string;
partySection: 'clinics' | 'labs';
labCaseId?: string;
}) {
const members = await this.prisma.membership.findMany({
where: {
organizationId: input.organizationId,
OR: [{ isOwner: true }, { isActive: true }],
},
include: {
permissions: { include: { permission: true } },
organization: { select: { planId: true, type: { select: { name: true } } } },
},
});
const recipientUserIds = members
.filter((member) => hasEffectivePermission(member, 'TAB_BILLING_READ'))
.map((member) => member.userId);
if (recipientUserIds.length === 0) return;
const params = new URLSearchParams({
partyId: input.partyId,
partyName: input.partyName,
partySection: input.partySection,
});
await this.userNotifications.notify({
organizationId: input.organizationId,
type: input.type,
href: `/billing?${params.toString()}`,
recipientUserIds,
payload: {
fromOrganizationId: input.partyId,
...(input.labCaseId ? { labCaseId: input.labCaseId } : {}),
},
});
}
/** Writes the mirrored debt once every current-round step is done. */
async postCaseDebtIfComplete(
db: Prisma.TransactionClient,
labCaseId: string,
completedAt: Date,
): Promise<CaseFeeNotice | null> {
const [open, total] = await Promise.all([
db.labCaseTask.count({
where: {
labCaseId,
roundId: null,
status: { not: LabTaskStatus.COMPLETED },
},
}),
db.labCaseTask.count({ where: { labCaseId, roundId: null } }),
]);
if (total === 0 || open > 0) return null;
return this.syncPartnerCaseObligations(db, labCaseId, completedAt);
}
async notifyCaseFee(notice: CaseFeeNotice) {
await this.notifyBillingParty({
organizationId: notice.organizationId,
type: notice.amountPending
? UserNotificationType.BILLING_CASE_FEE_PENDING
: UserNotificationType.BILLING_CASE_FEE,
partyId: notice.partyId,
partyName: notice.partyName,
partySection: notice.partySection,
labCaseId: notice.labCaseId,
});
}
async syncPartnerCaseObligations(
db: Prisma.TransactionClient,
labCaseId: string,
occurredAt?: Date,
): Promise<CaseFeeNotice | null> {
const labCase = await db.labCase.findUnique({
where: { id: labCaseId },
select: {
@@ -2426,7 +2730,7 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
parentLabCase: { select: { destinationOrganizationId: true } },
},
});
if (!labCase) return;
if (!labCase) return null;
const obligation = resolvePartnerCaseObligation({
origin: labCase.origin,
@@ -2445,10 +2749,18 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
? BillingObligationSourceType.OUTSOURCE_CASE
: BillingObligationSourceType.LAB_CASE;
await this.voidObligationSource(db, sourceType, labCase.id);
return;
return null;
}
const occurredAt = labCase.sentAt ?? labCase.startedAt ?? new Date();
const when = occurredAt ?? labCase.sentAt ?? labCase.startedAt ?? new Date();
const existing = await db.billingLedgerEntry.findFirst({
where: {
organizationId: obligation.payeeOrganizationId,
sourceType: obligation.sourceType,
sourceId: labCase.id,
},
select: { id: true },
});
await this.upsertObligation(db, {
organizationId: obligation.payerOrganizationId,
partyKind: BillingLedgerPartyKind.ORGANIZATION,
@@ -2458,7 +2770,7 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
amount,
keepPending: true,
sign: -1,
occurredAt,
occurredAt: when,
});
await this.upsertObligation(db, {
organizationId: obligation.payeeOrganizationId,
@@ -2469,8 +2781,25 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
amount,
keepPending: true,
sign: 1,
occurredAt,
occurredAt: when,
});
if (existing || (amount != null && amount <= 0)) return null;
if (labCase.origin !== 'CLINIC_DISPATCH' && labCase.origin !== 'LAB_OUTSOURCE') {
return null;
}
const payer = await db.organization.findUnique({
where: { id: obligation.payerOrganizationId },
select: { name: true, type: { select: { name: true } } },
});
if (!payer) return null;
return {
organizationId: obligation.payeeOrganizationId,
partyId: obligation.payerOrganizationId,
partyName: payer.name,
partySection: payer.type.name === 'LAB' ? 'labs' : 'clinics',
amountPending: amount == null,
labCaseId: labCase.id,
};
}
async voidCaseObligations(db: Prisma.TransactionClient, labCaseIds: string | string[]) {
@@ -2754,7 +3083,6 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
billed == null ? null : new Prisma.Decimal(billed.toFixed(2)),
},
});
await this.syncPartnerCaseObligations(db, labCase.id);
}
private async resolvedPriceLines(

View File

@@ -4,6 +4,7 @@ import {
staffBillingPeriodForDate,
staffBillingPeriodFromKey,
staffBillingPeriodsBetween,
staffPeriodElapsedDays,
staffPeriodLastDay,
staffPeriodsAfter,
} from './staff-billing-period';
@@ -42,6 +43,14 @@ describe('staff billing periods', () => {
it('dates a closed month on its last day and skips the month still in progress', () => {
const current = staffBillingPeriodForDate(duringAban1405, 'TOMAN');
expect(staffPeriodLastDay(current).toISOString()).toBe('2026-11-21T00:00:00.000Z');
expect(staffPeriodElapsedDays(current, duringAban1405)).toEqual({
elapsed: 20,
days: 30,
});
expect(staffPeriodElapsedDays(current, staffPeriodLastDay(current))).toEqual({
elapsed: 30,
days: 30,
});
const finished = finishedStaffBillingPeriods(
new Date('2026-08-01T00:00:00.000Z'),

View File

@@ -113,6 +113,23 @@ export function staffPeriodLastDay(period: StaffBillingPeriod): Date {
return new Date(period.end.getTime() - 24 * 60 * 60 * 1000);
}
/** Days from the period start through `day`, and the length of the period. */
export function staffPeriodElapsedDays(
period: StaffBillingPeriod,
day: Date,
): { elapsed: number; days: number } | null {
const dayStart = new Date(
Date.UTC(day.getUTCFullYear(), day.getUTCMonth(), day.getUTCDate()),
);
if (dayStart < period.start || dayStart >= period.end) return null;
const days = Math.round((period.end.getTime() - period.start.getTime()) / 86400000);
const next = new Date(dayStart.getTime() + 86400000);
const cap = next < period.end ? next : period.end;
const elapsed = Math.round((cap.getTime() - period.start.getTime()) / 86400000);
if (days <= 0 || elapsed <= 0) return null;
return { elapsed, days };
}
export function staffPeriodKeyMatchesCurrency(
key: string,
currency: BillingCurrencyCode,

View File

@@ -1033,6 +1033,7 @@ export class CasesService {
},
});
await this.billing.revokeCommissionOnUncomplete(tx, taskId);
await this.billing.voidCaseObligations(tx, labCaseId);
});
const refreshed = await this.prisma.labCase.findFirstOrThrow({
@@ -1786,6 +1787,7 @@ export class CasesService {
patientDisplayMobile: lc.patientDisplayMobile,
partnerClinicOrganizationId: lc.partnerClinicOrganizationId,
partnerOrganizationType: lc.partnerClinic?.type.name ?? null,
destinationOrganizationId: lc.destinationOrganizationId,
calculatedAmount: lc.calculatedAmount?.toString() ?? null,
billedAmount: lc.billedAmount?.toString() ?? null,
billedAmountManual: lc.billedAmountManual,

View File

@@ -406,9 +406,25 @@ export class TasksService {
);
}
return { result, caseCompleted, ancestorCompletions };
const debtNotices: Array<
NonNullable<Awaited<ReturnType<BillingService['postCaseDebtIfComplete']>>>
> = [];
if (caseCompleted) {
const notice = await this.billing.postCaseDebtIfComplete(tx, task.labCaseId, now);
if (notice) debtNotices.push(notice);
}
for (const ancestor of ancestorCompletions) {
const notice = await this.billing.postCaseDebtIfComplete(tx, ancestor.labCaseId, now);
if (notice) debtNotices.push(notice);
}
return { result, caseCompleted, ancestorCompletions, debtNotices };
});
for (const notice of updated.debtNotices) {
void this.billing.notifyCaseFee(notice).catch(() => undefined);
}
if (updated.caseCompleted) {
void this.userNotifications.notify({
organizationId: labOrganizationId,

View File

@@ -73,4 +73,9 @@ export class TodaySummaryQueryDto {
@IsOptional()
@IsIn(WEEK_MONTH)
billingPeriod?: 'week' | 'month';
@ApiPropertyOptional({ enum: WEEK_MONTH })
@IsOptional()
@IsIn(WEEK_MONTH)
personalPeriod?: 'week' | 'month';
}

View File

@@ -21,6 +21,10 @@ import {
type CatalogLocale,
} from '../catalog/catalog-label.service';
import { startOfUtcDay } from '../../common/lab-case-due-date';
import {
staffBillingPeriodForDate,
staffPeriodElapsedDays,
} from '../billing/staff-billing-period';
import { CURRENT_VISIBLE_TASK_FILTER } from '../cases/lab-case-outsource.rules';
import { TodaySummaryQueryDto } from './dto/today-summary-query.dto';
@@ -46,6 +50,21 @@ type PartnerCasesBucket = {
pending: number;
};
type PersonalDay = {
code: string;
label: string;
work: number;
income: number;
paid: number;
};
type PersonalSeries = {
days: PersonalDay[];
workTotal: number;
incomeTotal: number;
paidTotal: number;
};
type TodayCharts = {
treatmentMixWeek?: ChartBucket[];
tasksByProsthesis?: ChartBucket[];
@@ -61,6 +80,8 @@ type TodayCharts = {
dentistBilledMix?: ChartBucket[];
clinicDentistsBilled?: ChartBucket[];
labStaffCommission?: ChartBucket[];
myTreatmentWork?: PersonalSeries;
myTaskWork?: PersonalSeries;
};
type TodayActions = {
@@ -335,6 +356,33 @@ export class TodayService {
);
}
}
const personalPeriod = resolveWeekMonthPeriod(query.personalPeriod, 'month');
if (this.canEditTreatment(membership.isOwner, permissionNames)) {
tasks.push(
this.loadPersonalWorkIncome({
organizationId,
userId,
rangeEnd: to,
period: personalPeriod,
utcOffsetMinutes: query.utcOffsetMinutes,
work: 'treatment',
charts,
}),
);
}
if (this.canViewTasks(membership.isOwner, permissionNames)) {
tasks.push(
this.loadPersonalWorkIncome({
organizationId,
userId,
rangeEnd: to,
period: personalPeriod,
utcOffsetMinutes: query.utcOffsetMinutes,
work: 'tasks',
charts,
}),
);
}
if (this.canViewBilling(membership.isOwner, permissionNames)) {
tasks.push(
this.buildSubscriptionWidget(organizationId).then((value) => {
@@ -1366,6 +1414,26 @@ export class TodayService {
return membership;
}
private async chartMoneyWindow(
organizationId: string,
rangeEnd: Date,
period: ChartPeriodWeekMonth,
) {
if (period === 'week') return moneyWindow(rangeEnd, 7);
const organization = await this.prisma.organization.findUnique({
where: { id: organizationId },
select: { billingCurrency: true },
});
const currency =
organization?.billingCurrency === 'DOLLAR' || organization?.billingCurrency === 'EURO'
? organization.billingCurrency
: 'TOMAN';
return {
gte: staffBillingPeriodForDate(rangeEnd, currency).start,
lt: rangeEnd,
};
}
private resolvePermissionNames(membership: {
isOwner: boolean;
organization: {
@@ -1393,7 +1461,7 @@ export class TodayService {
treatment: {
organizationId,
providerUserId: userId,
treatmentAt: moneyWindow(rangeEnd, daysForChartPeriod(period)),
treatmentAt: await this.chartMoneyWindow(organizationId, rangeEnd, period),
},
},
_sum: { billedAmount: true },
@@ -1430,7 +1498,7 @@ export class TodayService {
where: {
organizationId,
billedAmount: { not: null },
treatmentAt: moneyWindow(rangeEnd, daysForChartPeriod(period)),
treatmentAt: await this.chartMoneyWindow(organizationId, rangeEnd, period),
},
_sum: { billedAmount: true },
});
@@ -1464,7 +1532,7 @@ export class TodayService {
by: ['userId'],
where: {
organizationId,
earnedAt: moneyWindow(rangeEnd, daysForChartPeriod(period)),
earnedAt: await this.chartMoneyWindow(organizationId, rangeEnd, period),
},
_sum: { earnedAmount: true },
});
@@ -1488,6 +1556,144 @@ export class TodayService {
}));
}
/**
* Daily work and income for the signed-in user.
* Month uses the open billing month through today. Week uses the last 7 days.
* Income is commission on that day plus an even share of the open-month salary
* preview, so the month line adds up to that preview plus commission.
* Recorded staff payments stay on `paid` for the tooltip.
*/
private async loadPersonalWorkIncome(input: {
organizationId: string;
userId: string;
rangeEnd: Date;
period: ChartPeriodWeekMonth;
utcOffsetMinutes?: number;
work: 'treatment' | 'tasks';
charts: TodayCharts;
}) {
const { organizationId, userId, rangeEnd, period, work, charts } = input;
const reportDay = new Date(rangeEnd.getTime() - 1);
const organization = await this.prisma.organization.findUnique({
where: { id: organizationId },
select: { billingCurrency: true },
});
const currency =
organization?.billingCurrency === 'DOLLAR' || organization?.billingCurrency === 'EURO'
? organization.billingCurrency
: 'TOMAN';
const billingPeriod = staffBillingPeriodForDate(reportDay, currency);
const elapsed = staffPeriodElapsedDays(billingPeriod, reportDay);
const window =
period === 'month'
? {
gte: billingPeriod.start,
lt: rangeEnd < billingPeriod.end ? rangeEnd : billingPeriod.end,
}
: moneyWindow(rangeEnd, 7);
const [membership, workAt, earnings, payments] = await Promise.all([
this.prisma.membership.findUnique({
where: { userId_organizationId: { userId, organizationId } },
select: { fixedMonthlySalary: true },
}),
work === 'treatment'
? this.prisma.treatmentDetail.findMany({
where: {
treatment: {
organizationId,
providerUserId: userId,
treatmentAt: { gte: window.gte, lt: window.lt },
},
},
select: { treatment: { select: { treatmentAt: true } } },
})
: this.prisma.labCaseTask.findMany({
where: {
status: LabTaskStatus.COMPLETED,
lastStatusChangedByUserId: userId,
lastStatusChangedAt: { gte: window.gte, lt: window.lt },
...CURRENT_VISIBLE_TASK_FILTER,
labCase: this.visibleStartedToLabWhere(organizationId),
},
select: { lastStatusChangedAt: true },
}),
this.prisma.commissionEarning.findMany({
where: {
organizationId,
userId,
earnedAt: { gte: window.gte, lt: window.lt },
},
select: { earnedAt: true, earnedAmount: true },
}),
this.prisma.staffPayment.findMany({
where: {
organizationId,
userId,
paidAt: { gte: window.gte, lt: window.lt },
},
select: { paidAt: true, amount: true },
}),
]);
const offsetMs = (input.utcOffsetMinutes ?? 0) * 60_000;
const spans = daySpansCovering(window.gte, window.lt, offsetMs);
const salaryDays = spans.filter(
(span) => span.start < billingPeriod.end && span.end > billingPeriod.start,
);
const salary = moneyNumber(membership?.fixedMonthlySalary);
const salaryPreview =
elapsed && salary > 0
? roundMoney((salary * elapsed.elapsed) / elapsed.days)
: 0;
const share =
elapsed && elapsed.elapsed > 0
? Math.min(1, salaryDays.length / elapsed.elapsed)
: 0;
const slices = spreadMoney(roundMoney(salaryPreview * share), salaryDays.length);
const salaryByCode = new Map(
salaryDays.map((span, index) => [span.code, slices[index] ?? 0]),
);
const days = spans.map((span) => ({
code: span.code,
label: span.code,
work: 0,
income: salaryByCode.get(span.code) ?? 0,
paid: 0,
}));
const indexByCode = new Map(days.map((day, index) => [day.code, index]));
const add = (at: Date, field: 'work' | 'income' | 'paid', amount: number) => {
const index = indexByCode.get(localDayKeyFromDate(at, offsetMs));
if (index === undefined) return;
const day = days[index];
if (!day) return;
if (field === 'work') day.work += amount;
else day[field] = roundMoney(day[field] + amount);
};
if (work === 'treatment') {
for (const row of workAt as Array<{ treatment: { treatmentAt: Date } }>) {
add(row.treatment.treatmentAt, 'work', 1);
}
} else {
for (const row of workAt as Array<{ lastStatusChangedAt: Date | null }>) {
if (row.lastStatusChangedAt) add(row.lastStatusChangedAt, 'work', 1);
}
}
for (const row of earnings) add(row.earnedAt, 'income', moneyNumber(row.earnedAmount));
for (const row of payments) add(row.paidAt, 'paid', moneyNumber(row.amount));
const series: PersonalSeries = {
days,
workTotal: days.reduce((sum, day) => sum + day.work, 0),
incomeTotal: roundMoney(days.reduce((sum, day) => sum + day.income, 0)),
paidTotal: roundMoney(days.reduce((sum, day) => sum + day.paid, 0)),
};
if (work === 'treatment') charts.myTreatmentWork = series;
else charts.myTaskWork = series;
}
private assertCanViewToday(isOwner: boolean, permissionNames: string[]) {
if (isOwner) return;
if (!permissionNames.includes('TAB_TODAY_READ')) {
@@ -1600,6 +1806,42 @@ function moneyNumber(value: { toString(): string } | number | null | undefined):
return Number(value ?? 0);
}
function roundMoney(value: number): number {
return Math.round(value * 100) / 100;
}
/** Even daily shares that still add up to `total`. */
function spreadMoney(total: number, count: number): number[] {
if (count <= 0) return [];
const slice = Math.floor((total / count) * 100) / 100;
const amounts = Array.from({ length: count }, () => slice);
const last = count - 1;
amounts[last] = roundMoney((amounts[last] ?? 0) + (roundMoney(total) - roundMoney(slice * count)));
return amounts;
}
function daySpansCovering(
start: Date,
end: Date,
offsetMs: number,
): Array<{ code: string; start: Date; end: Date }> {
if (!(start < end)) return [];
const firstLocal = new Date(start.getTime() + offsetMs);
firstLocal.setUTCHours(0, 0, 0, 0);
let cursor = new Date(firstLocal.getTime() - offsetMs);
const spans: Array<{ code: string; start: Date; end: Date }> = [];
while (cursor < end && spans.length < 40) {
const next = new Date(cursor.getTime() + 86_400_000);
spans.push({
code: localDayKeyFromDate(cursor, offsetMs),
start: cursor,
end: next,
});
cursor = next;
}
return spans;
}
function buildLocalDayBuckets(
anchor: Date,
count: number,

View File

@@ -1749,6 +1749,9 @@ export class TreatmentsService {
};
}>;
tasks?: Array<{ id: string; status: LabTaskStatus }>;
calculatedAmount?: { toFixed(digits: number): string } | null;
billedAmount?: { toFixed(digits: number): string } | null;
billedAmountManual?: boolean;
}, locale?: string | null) {
const taskProgress = this.mapTaskProgress(lc.tasks ?? []);
const detailTeeth = lc.details?.[0]?.detail
@@ -1794,6 +1797,9 @@ export class TreatmentsService {
sentAt: s.sentAt.toISOString(),
})) ?? [],
shareUrl: this.labCaseShareUrl(lc, locale),
calculatedAmount: lc.calculatedAmount?.toFixed(2) ?? null,
billedAmount: lc.billedAmount?.toFixed(2) ?? null,
billedAmountManual: Boolean(lc.billedAmountManual),
};
}

View File

@@ -272,6 +272,13 @@
"chartDentistBilledMixTitle": "My billed mix",
"chartClinicDentistsBilledTitle": "Billed by dentist",
"chartLabStaffCommissionTitle": "Commission by staff",
"chartMyTreatmentTitle": "My work and income",
"chartMyTasksTitle": "My work and income",
"chartPersonalWorkLegend": "Work",
"chartPersonalIncomeLegend": "Income",
"chartPersonalPaid": "Paid",
"chartPersonalTreatmentTotal": "{count} treatments",
"chartPersonalTaskTotal": "{count} tasks",
"chartEmpty": "No data for this period yet.",
"periodWeek": "Week",
"periodMonth": "Month",
@@ -554,6 +561,7 @@
"sendToExocadSaved": "Sent to Exocad as case {id}. Open Exocad again to see the case.",
"sendToExocadUpdated": "Updated Exocad case {id}. Open Exocad again to see the case.",
"sendToExocadSkipped": "Not sent: {lines}.",
"sendToExocadFolderMissing": "The case was written. The Exocad project folder was not created, so Save in Exocad can still fail until you choose the CAD-Data folder.",
"sendToExocadConnectTitle": "Connect Exocad database",
"sendToExocadCloseHint": "Close Exocad before sending. Open it again afterwards to see the case.",
"sendToExocadExperimentalWarning": "This is an experimental feature. Make a manual backup of the Exocad database before using it. Nudentic is not responsible for any issues. You use this feature on your own.",
@@ -788,7 +796,7 @@
"loadingAppointments": "Loading appointments…",
"selectDayWithAppointment": "Search for a patient or select a visit from the day strip.",
"noTreatmentFoundTitle": "No treatment found",
"noTreatmentFoundBody": "There is no treatment or visit for {name} yet. You can add one with the {action} button in the rail.",
"noTreatmentFoundBody": "There is no treatment or visit for {name} yet. You can add one with the {action} button.",
"confirmDiscard": "You have unsaved changes. Discard them and continue?",
"errorChooseOrg": "Choose at least one active organization to send this case.",
"successCaseSent": "Case sent to selected organizations.",
@@ -811,7 +819,7 @@
"noAppointment": "No appointment",
"walkIn": "Walk-in",
"newTreatment": "New treatment",
"mobileOpenRail": "Patient / history",
"mobileOpenRail": "History",
"newTreatmentPatientPrompt": "Who is this visit for?",
"newTreatmentUseCurrent": "Use {name}",
"newTreatmentUseCurrentHint": "Start a new visit for the patient already open on this page.",
@@ -892,6 +900,7 @@
"sendToLab": "Send to lab",
"labFeePreview": "Lab fee",
"labFeeNeedsBillingAmount": "This case contains services without a lab fee. You can send it, but the destination lab must set the final amount in Billing.",
"labFeeSentNeedsAmount": "This case was sent without a lab fee. The destination lab sets the final amount in Billing.",
"labDoesNotProvideTypes": "This lab does not provide the following prosthesis services: {types}. Choose another lab or change the case.",
"dueDateLabel": "Due date",
"dueDateOptional": "optional",
@@ -1229,6 +1238,10 @@
"typeConnectionRequest": "New organization connection request",
"typeStaffInvite": "Staff invitation created",
"typeSeatExpiring": "A seat ends soon",
"typeBillingCaseFee": "A case fee is ready",
"typeBillingCaseFeePending": "A case fee needs a price",
"typeBillingPaymentPending": "A payment is waiting for a decision",
"typeBillingPaymentDeclined": "A payment was declined",
"typeUnknown": "Notification",
"destCases": "Open Cases",
"destTasks": "Open Tasks",
@@ -1237,6 +1250,7 @@
"destStaff": "Open Staff",
"destSubscriptions": "Open Subscriptions",
"destToday": "Open Today",
"destBilling": "Open Billing",
"destOpen": "Open"
},
"prosthesis": {
@@ -1427,7 +1441,8 @@
"errorUpdateTransaction": "Could not update the transaction.",
"commissionSubtotal": "Commission",
"fixedSalarySubtotal": "Fixed salary",
"grossCompensation": "Gross compensation"
"grossCompensation": "Gross compensation",
"projectedSoFar": "So far"
},
"localDb": {
"browse": "Browse",
@@ -1436,7 +1451,6 @@
"applyFailed": "Could not write the file.",
"conflict": "That record conflicts with a row already in the table.",
"notExocad": "That file is not an Exocad database.",
"clientNameIncomplete": "Not sent. The clinic name needs a last name so Exocad can fill Client. Edit the clinic name and try again. The Exocad database was not changed.",
"patientNameIncomplete": "Not sent. The patient name needs a last name so Exocad can fill Name. Edit the patient and try again. The Exocad database was not changed.",
"sendRolledBack": "Not sent. The Exocad database was not changed."
},

View File

@@ -272,6 +272,13 @@
"chartDentistBilledMixTitle": "ترکیب مبلغ من",
"chartClinicDentistsBilledTitle": "مبالغ بر اساس دندان‌پزشک",
"chartLabStaffCommissionTitle": "کمیسیون بر اساس کارکنان",
"chartMyTreatmentTitle": "کار و درآمد من",
"chartMyTasksTitle": "کار و درآمد من",
"chartPersonalWorkLegend": "کار",
"chartPersonalIncomeLegend": "درآمد",
"chartPersonalPaid": "پرداخت‌شده",
"chartPersonalTreatmentTotal": "{count} درمان",
"chartPersonalTaskTotal": "{count} کار",
"chartEmpty": "هنوز داده‌ای برای این بازه وجود ندارد.",
"periodWeek": "هفته",
"periodMonth": "ماه",
@@ -554,6 +561,7 @@
"sendToExocadSaved": "به Exocad به عنوان پرونده {id} فرستاده شد. Exocad را دوباره باز کنید تا پرونده را ببینید.",
"sendToExocadUpdated": "پرونده {id} در Exocad به‌روز شد. Exocad را دوباره باز کنید تا پرونده را ببینید.",
"sendToExocadSkipped": "فرستاده نشد: {lines}.",
"sendToExocadFolderMissing": "پرونده نوشته شد. پوشه پروژه Exocad ساخته نشد، بنابراین ذخیره در Exocad تا وقتی پوشه CAD-Data را انتخاب نکنید می‌تواند ناموفق بماند.",
"sendToExocadConnectTitle": "اتصال پایگاه داده Exocad",
"sendToExocadCloseHint": "پیش از ارسال Exocad را ببندید. بعد از ارسال آن را دوباره باز کنید تا پرونده را ببینید.",
"sendToExocadExperimentalWarning": "این قابلیت آزمایشی است. پیش از استفاده، یک نسخه پشتیبان دستی از پایگاه داده Exocad بگیرید. نودنتیک مسئول هیچ مشکلی نیست. استفاده از این قابلیت بر عهده خود شماست.",
@@ -789,7 +797,7 @@
"loadingAppointments": "در حال بارگذاری نوبت‌ها...",
"selectDayWithAppointment": "برای بیمار جستجو کنید یا یک ویزیت را از نوار روز انتخاب کنید.",
"noTreatmentFoundTitle": "درمانی یافت نشد",
"noTreatmentFoundBody": "هنوز درمان یا ویزیتی برای {name} ثبت نشده است. می‌توانید با دکمه {action} در نوار کناری یکی اضافه کنید.",
"noTreatmentFoundBody": "هنوز درمان یا ویزیتی برای {name} ثبت نشده است. می‌توانید با دکمه {action} یکی اضافه کنید.",
"confirmDiscard": "تغییرات ذخیره‌نشده دارید. آنها را کنار بگذارید و ادامه دهید؟",
"errorChooseOrg": "حداقل یک سازمان فعال را برای ارسال این پرونده انتخاب کنید.",
"successCaseSent": "پرونده به سازمان‌های انتخاب شده ارسال شد.",
@@ -812,7 +820,7 @@
"noAppointment": "بدون نوبت",
"walkIn": "بدون نوبت (مراجع)",
"newTreatment": "درمان جدید",
"mobileOpenRail": "بیمار / سابقه",
"mobileOpenRail": "سابقه",
"newTreatmentPatientPrompt": "این ویزیت برای چه کسی است؟",
"newTreatmentUseCurrent": "استفاده از {name}",
"newTreatmentUseCurrentHint": "ویزیت جدیدی برای بیماری که همین حالا در این صفحه باز است شروع کنید.",
@@ -893,6 +901,7 @@
"sendToLab": "ارسال به لابراتوار",
"labFeePreview": "تعرفه لابراتوار",
"labFeeNeedsBillingAmount": "این پرونده شامل خدماتی بدون تعرفه لابراتوار است. ارسال مجاز است، اما لابراتوار مقصد باید مبلغ نهایی را در بخش مالی ثبت کند.",
"labFeeSentNeedsAmount": "این پرونده بدون تعرفه لابراتوار ارسال شد. لابراتوار مقصد مبلغ نهایی را در بخش مالی ثبت می‌کند.",
"labDoesNotProvideTypes": "این لابراتوار خدمات پروتز زیر را ارائه نمی‌دهد: {types}. لابراتوار دیگری انتخاب کنید یا پرونده را تغییر دهید.",
"dueDateLabel": "موعد تحویل",
"dueDateOptional": "اختیاری",
@@ -1230,6 +1239,10 @@
"typeConnectionRequest": "درخواست اتصال سازمان جدید",
"typeStaffInvite": "دعوتنامه کارکنان ایجاد شد",
"typeSeatExpiring": "یک صندلی به‌زودی تمام می‌شود",
"typeBillingCaseFee": "هزینه پرونده آماده است",
"typeBillingCaseFeePending": "هزینه پرونده نیاز به قیمت دارد",
"typeBillingPaymentPending": "یک پرداخت منتظر تصمیم است",
"typeBillingPaymentDeclined": "یک پرداخت رد شد",
"typeUnknown": "اعلان",
"destCases": "باز کردن پرونده‌ها",
"destTasks": "باز کردن وظایف",
@@ -1238,6 +1251,7 @@
"destStaff": "باز کردن کارکنان",
"destSubscriptions": "باز کردن اشتراک‌ها",
"destToday": "باز کردن امروز",
"destBilling": "باز کردن صورتحساب",
"destOpen": "باز کردن"
},
"prosthesis": {
@@ -1428,7 +1442,8 @@
"errorUpdateTransaction": "به‌روزرسانی تراکنش ناموفق بود.",
"commissionSubtotal": "کمیسیون",
"fixedSalarySubtotal": "حقوق ثابت",
"grossCompensation": "جمع ناخالص دریافتی"
"grossCompensation": "جمع ناخالص دریافتی",
"projectedSoFar": "تا این روز"
},
"localDb": {
"browse": "مرور",
@@ -1437,7 +1452,6 @@
"applyFailed": "نوشتن فایل انجام نشد.",
"conflict": "این رکورد با ردیفی که از قبل در جدول است تداخل دارد.",
"notExocad": "این فایل پایگاه داده Exocad نیست.",
"clientNameIncomplete": "ارسال نشد. نام کلینیک نام خانوادگی ندارد، بنابراین Client در Exocad پر نمی‌شود. نام کلینیک را اصلاح کنید و دوباره بفرستید. پایگاه داده Exocad تغییر نکرد.",
"patientNameIncomplete": "ارسال نشد. نام بیمار نام خانوادگی ندارد، بنابراین Name در Exocad پر نمی‌شود. نام بیمار را اصلاح کنید و دوباره بفرستید. پایگاه داده Exocad تغییر نکرد.",
"sendRolledBack": "ارسال نشد. پایگاه داده Exocad تغییر نکرد."
},

View File

@@ -272,6 +272,13 @@
"chartDentistBilledMixTitle": "Mijn omzetmix",
"chartClinicDentistsBilledTitle": "Omzet per tandarts",
"chartLabStaffCommissionTitle": "Commissie per medewerker",
"chartMyTreatmentTitle": "Mijn werk en inkomen",
"chartMyTasksTitle": "Mijn werk en inkomen",
"chartPersonalWorkLegend": "Werk",
"chartPersonalIncomeLegend": "Inkomen",
"chartPersonalPaid": "Betaald",
"chartPersonalTreatmentTotal": "{count} behandelingen",
"chartPersonalTaskTotal": "{count} taken",
"chartEmpty": "Nog geen gegevens voor deze periode.",
"periodWeek": "Week",
"periodMonth": "Maand",
@@ -554,6 +561,7 @@
"sendToExocadSaved": "Naar Exocad gestuurd als casus {id}. Open Exocad opnieuw om de casus te zien.",
"sendToExocadUpdated": "Exocad-casus {id} bijgewerkt. Open Exocad opnieuw om de casus te zien.",
"sendToExocadSkipped": "Niet gestuurd: {lines}.",
"sendToExocadFolderMissing": "De casus is opgeslagen. De Exocad-projectmap is niet aangemaakt, dus Opslaan in Exocad kan nog mislukken totdat u de map CAD-Data kiest.",
"sendToExocadConnectTitle": "Exocad-database koppelen",
"sendToExocadCloseHint": "Sluit Exocad voordat u verstuurt. Open het daarna opnieuw om de casus te zien.",
"sendToExocadExperimentalWarning": "Dit is een experimentele functie. Maak een handmatige back-up van de Exocad-database voordat u deze gebruikt. Nudentic is niet aansprakelijk voor eventuele problemen. U gebruikt deze functie op eigen verantwoordelijkheid.",
@@ -788,7 +796,7 @@
"loadingAppointments": "Afspraken laden...",
"selectDayWithAppointment": "Zoek een patiënt of kies een bezoek uit de dagstrook.",
"noTreatmentFoundTitle": "Geen behandeling gevonden",
"noTreatmentFoundBody": "Er is nog geen behandeling of bezoek voor {name}. U kunt er een toevoegen met de knop {action} in de zijbalk.",
"noTreatmentFoundBody": "Er is nog geen behandeling of bezoek voor {name}. U kunt er een toevoegen met de knop {action}.",
"confirmDiscard": "U heeft niet-opgeslagen wijzigingen. Wilt u deze negeren en doorgaan?",
"errorChooseOrg": "Kies ten minste één actieve organisatie om deze case te verzenden.",
"successCaseSent": "Case verzonden naar geselecteerde organisaties.",
@@ -811,7 +819,7 @@
"noAppointment": "Geen afspraak",
"walkIn": "Inloop",
"newTreatment": "Nieuwe behandeling",
"mobileOpenRail": "Patiënt / geschiedenis",
"mobileOpenRail": "Geschiedenis",
"newTreatmentPatientPrompt": "Voor wie is dit bezoek?",
"newTreatmentUseCurrent": "{name} gebruiken",
"newTreatmentUseCurrentHint": "Start een nieuw bezoek voor de patiënt die al op deze pagina openstaat.",
@@ -892,6 +900,7 @@
"sendToLab": "Versturen naar lab",
"labFeePreview": "Labtarief",
"labFeeNeedsBillingAmount": "Deze case bevat diensten zonder labtarief. Verzenden is toegestaan, maar het bestemmingslab moet het definitieve bedrag in Facturatie instellen.",
"labFeeSentNeedsAmount": "Deze case is verzonden zonder labtarief. Het bestemmingslab stelt het definitieve bedrag in Facturatie in.",
"labDoesNotProvideTypes": "Dit lab levert de volgende prothesediensten niet: {types}. Kies een ander lab of wijzig de case.",
"dueDateLabel": "Vervaldatum",
"dueDateOptional": "optioneel",
@@ -1229,6 +1238,10 @@
"typeConnectionRequest": "Nieuw organisatieverzoek",
"typeStaffInvite": "Personeelsuitnodiging aangemaakt",
"typeSeatExpiring": "Een plaats eindigt binnenkort",
"typeBillingCaseFee": "Een dossierprijs staat klaar",
"typeBillingCaseFeePending": "Een dossierprijs heeft een bedrag nodig",
"typeBillingPaymentPending": "Een betaling wacht op een beslissing",
"typeBillingPaymentDeclined": "Een betaling is geweigerd",
"typeUnknown": "Melding",
"destCases": "Cases openen",
"destTasks": "Taken openen",
@@ -1237,6 +1250,7 @@
"destStaff": "Personeel openen",
"destSubscriptions": "Abonnementen openen",
"destToday": "Vandaag openen",
"destBilling": "Facturatie openen",
"destOpen": "Openen"
},
"prosthesis": {
@@ -1427,7 +1441,8 @@
"errorUpdateTransaction": "De transactie kon niet worden bijgewerkt.",
"commissionSubtotal": "Commissie",
"fixedSalarySubtotal": "Vast salaris",
"grossCompensation": "Brutovergoeding"
"grossCompensation": "Brutovergoeding",
"projectedSoFar": "Tot nu toe"
},
"localDb": {
"browse": "Bladeren",
@@ -1436,7 +1451,6 @@
"applyFailed": "Het bestand kon niet worden geschreven.",
"conflict": "Dat record botst met een rij die al in de tabel staat.",
"notExocad": "Dat bestand is geen Exocad-database.",
"clientNameIncomplete": "Niet verzonden. De klinieknaam heeft geen achternaam, dus Exocad kan Client niet invullen. Pas de klinieknaam aan en probeer het opnieuw. De Exocad-database is niet gewijzigd.",
"patientNameIncomplete": "Niet verzonden. De patiëntnaam heeft geen achternaam, dus Exocad kan Name niet invullen. Pas de patiënt aan en probeer het opnieuw. De Exocad-database is niet gewijzigd.",
"sendRolledBack": "Niet verzonden. De Exocad-database is niet gewijzigd."
},

View File

@@ -6,7 +6,7 @@ export type StaffCompensationTotals = {
gross: number;
};
/** Gross compensation is derived only from persisted obligation rows, never cash. */
/** Gross compensation includes closed months and the unsaved current-month preview. */
export function staffCompensationTotals(
rows: readonly BillingPartyReportRow[],
): StaffCompensationTotals {

View File

@@ -206,3 +206,110 @@ export async function openWithBrowserPicker(): Promise<DatabaseSink> {
});
return sinkFromBrowserHandle(handle);
}
type DirectoryHandle = {
queryPermission?: (descriptor: { mode: 'readwrite' }) => Promise<FilePermission>;
requestPermission?: (descriptor: { mode: 'readwrite' }) => Promise<FilePermission>;
getDirectoryHandle: (name: string, options?: { create?: boolean }) => Promise<unknown>;
};
type OpenDirectoryPicker = (options?: {
mode?: 'readwrite';
id?: string;
}) => Promise<DirectoryHandle>;
const CAD_DATA_KEY = 'cad-data';
let cachedDirectory: DirectoryHandle | null = null;
function directoryPicker(): OpenDirectoryPicker | null {
if (typeof window === 'undefined') return null;
const picker = (window as Window & { showDirectoryPicker?: OpenDirectoryPicker }).showDirectoryPicker;
return picker ?? null;
}
async function loadDirectoryHandle(): Promise<DirectoryHandle | null> {
if (cachedDirectory) return cachedDirectory;
if (typeof indexedDB === 'undefined') return null;
try {
const db = await handleDb();
const handle = await new Promise<DirectoryHandle | null>((resolve, reject) => {
const tx = db.transaction(HANDLE_STORE, 'readonly');
const request = tx.objectStore(HANDLE_STORE).get(CAD_DATA_KEY);
request.onsuccess = () => resolve((request.result as DirectoryHandle | undefined) ?? null);
request.onerror = () => reject(request.error);
});
db.close();
cachedDirectory = handle;
return handle;
} catch {
return null;
}
}
async function saveDirectoryHandle(handle: DirectoryHandle): Promise<void> {
cachedDirectory = handle;
if (typeof indexedDB === 'undefined') return;
const db = await handleDb();
await new Promise<void>((resolve, reject) => {
const tx = db.transaction(HANDLE_STORE, 'readwrite');
tx.objectStore(HANDLE_STORE).put(handle, CAD_DATA_KEY);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
db.close();
}
async function clearDirectoryHandle(): Promise<void> {
cachedDirectory = null;
if (typeof indexedDB === 'undefined') return;
try {
const db = await handleDb();
await new Promise<void>((resolve, reject) => {
const tx = db.transaction(HANDLE_STORE, 'readwrite');
tx.objectStore(HANDLE_STORE).delete(CAD_DATA_KEY);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
db.close();
} catch {
cachedDirectory = null;
}
}
async function grantedDirectory(handle: DirectoryHandle): Promise<DirectoryHandle | null> {
const permission = handle.queryPermission ? await handle.queryPermission(READ_WRITE) : 'prompt';
if (permission === 'granted') return handle;
if (!handle.requestPermission) return null;
return (await handle.requestPermission(READ_WRITE)) === 'granted' ? handle : null;
}
/**
* Create one empty project directory inside the CAD-Data folder the user grants.
* The database file permission cannot create that folder. Cancel leaves the case in the database.
*/
export async function ensureExocadProjectDirectory(folderName: string): Promise<boolean> {
const safe = folderName.trim();
if (!safe || /[\\/]/.test(safe)) return false;
try {
const remembered = await loadDirectoryHandle();
const ready = remembered ? await grantedDirectory(remembered) : null;
if (ready) {
await ready.getDirectoryHandle(safe, { create: true });
return true;
}
} catch (error) {
if (isMissingFileError(error)) await clearDirectoryHandle();
else return false;
}
const picker = directoryPicker();
if (!picker) return false;
try {
const handle = await picker({ mode: 'readwrite', id: 'dyolink-exocad-cad-data' });
await saveDirectoryHandle(handle);
await handle.getDirectoryHandle(safe, { create: true });
return true;
} catch {
return false;
}
}

View File

@@ -46,7 +46,7 @@ const SCHEMA = [
practice_lab_id INT, practice_pr_id INT,
patient_lab_id INT, patient_practice_id INT, patient_patient_id INT,
t_date DATETIME, t_Notes TEXT, flags BIGINT, projectGUID TEXT,
importedOrderId TEXT, t_duedate TEXT,
importedOrderId TEXT, t_duedate TEXT, t_schaleId INT,
foreign key (practice_lab_id, practice_pr_id) references clients(lab_id, practice_id),
foreign key (patient_lab_id, patient_practice_id, patient_patient_id)
references patients(lab_id, practice_id, patient_id)
@@ -494,18 +494,27 @@ describe('transferCaseToExocad', () => {
db.close();
});
it('does not write when the clinic name has no last name', async () => {
it('writes the case when the clinic name is one word or empty', async () => {
const db = await openSql();
const query = seed(db);
expect(() => transferCaseToExocad(query, sampleCase({ clinicName: ' ' }), options)).toThrow(ExocadTransferError);
try {
transferCaseToExocad(query, sampleCase({ clinicName: 'yavari' }), options);
} catch (error) {
expect(error).toBeInstanceOf(ExocadTransferError);
expect((error as ExocadTransferError).code).toBe('CLIENT_NAME_INCOMPLETE');
}
expect(query.all("SELECT treatment_id FROM Treatment WHERE importedOrderId = 'case-1'")).toEqual([]);
expect(query.all('SELECT COUNT(*) FROM clients')).toEqual([[2]]);
const blank = transferCaseToExocad(query, sampleCase({ clinicName: ' ' }), options);
const again = transferCaseToExocad(
query,
sampleCase({ caseId: 'case-blank-2', clinicName: ' ' }),
{ ...options, projectGuid: 'guid-blank' },
);
expect(query.all('SELECT name, practice_id FROM clients WHERE TRIM(name) = ?', [''])).toEqual([['', 2]]);
expect(query.all('SELECT practice_pr_id FROM Treatment WHERE treatment_id = ?', [blank.treatmentId])).toEqual([[2]]);
expect(query.all('SELECT practice_pr_id FROM Treatment WHERE treatment_id = ?', [again.treatmentId])).toEqual([[2]]);
const named = transferCaseToExocad(
query,
sampleCase({ caseId: 'case-yavari', clinicName: 'yavari' }),
{ ...options, projectGuid: 'guid-yavari' },
);
expect(query.all('SELECT name FROM clients WHERE practice_id = (SELECT practice_pr_id FROM Treatment WHERE treatment_id = ?)', [named.treatmentId])).toEqual([
['yavari'],
]);
db.close();
});
@@ -533,7 +542,7 @@ describe('transferCaseToExocad', () => {
db.close();
});
it('does not guess between clients that share one name token', async () => {
it('reuses an exact client name before a partial match', async () => {
const db = await openSql();
const query = seed(db);
for (const [id, name] of [
@@ -547,12 +556,36 @@ describe('transferCaseToExocad', () => {
[id, name],
);
}
expect(() => transferCaseToExocad(query, sampleCase({ clinicName: 'yavari' }), options)).toThrow(ExocadTransferError);
expect(query.all("SELECT treatment_id FROM Treatment WHERE importedOrderId = 'case-1'")).toEqual([]);
const exact = transferCaseToExocad(query, sampleCase({ clinicName: 'yavari' }), options);
expect(query.all('SELECT practice_pr_id FROM Treatment WHERE treatment_id = ?', [exact.treatmentId])).toEqual([[189]]);
expect(query.all('SELECT COUNT(*) FROM clients WHERE name = ?', ['yavari'])).toEqual([[1]]);
db.close();
});
it('creates a client instead of choosing among several partial matches', async () => {
const db = await openSql();
const query = seed(db);
for (const [id, name] of [
[120, 'Yavari Hoseinali'],
[178, 'Yavari,Tehran'],
] as const) {
query.run(
`INSERT INTO clients (lab_id, practice_id, name, language, country, city, zip, street, email, flags)
VALUES (0, ?, ?, '', '', '', '', '', '', 0)`,
[id, name],
);
}
const created = transferCaseToExocad(query, sampleCase({ clinicName: 'yavari' }), options);
const row = query.all(
'SELECT clients.name, clients.practice_id FROM clients JOIN Treatment ON Treatment.practice_pr_id = clients.practice_id WHERE Treatment.treatment_id = ?',
[created.treatmentId],
);
expect(row).toEqual([['yavari', 179]]);
expect(row[0][1]).not.toBe(120);
expect(row[0][1]).not.toBe(178);
db.close();
});
it('does not write when the patient name has no last name', async () => {
const db = await openSql();
const query = seed(db);
@@ -568,6 +601,29 @@ describe('transferCaseToExocad', () => {
db.close();
});
it('assigns the next tray and keeps it when the same case is sent again', async () => {
const db = await openSql();
const query = seed(db);
seedSavedPair(query, 'Coping', 'ZI');
const first = transferCaseToExocad(query, sampleCase(), options);
expect(query.all('SELECT t_schaleId FROM Treatment WHERE treatment_id = ?', [first.treatmentId])).toEqual([[1]]);
expect(first.projectFolder).toBe('2026-10-16_00002-001');
const second = transferCaseToExocad(
query,
sampleCase({ caseId: 'case-2' }),
{ ...options, projectGuid: 'guid-2', now: '2026-10-17T09:00:00.000Z' },
);
expect(query.all('SELECT t_schaleId FROM Treatment WHERE treatment_id = ?', [second.treatmentId])).toEqual([[2]]);
expect(second.projectFolder).toBe('2026-10-17_00002-002');
const updated = transferCaseToExocad(query, sampleCase(), { ...options, now: '2026-11-01T09:00:00.000Z' });
expect(updated.treatmentId).toBe(first.treatmentId);
expect(query.all('SELECT t_schaleId FROM Treatment WHERE treatment_id = ?', [updated.treatmentId])).toEqual([[1]]);
expect(updated.projectFolder).toBe('2026-11-01_00002-001');
db.close();
});
it('writes coping, reduced pontic, and the opposite antagonist without a shade', async () => {
const db = await openSql();
const query = seed(db);

View File

@@ -40,10 +40,7 @@ const MATERIAL_MATCH: Record<string, { workType: string; material: string }> = {
ips_overlay: { workType: 'OverlayCrown', material: 'LS2' },
};
export type ExocadTransferFailure =
| 'NOT_EXOCAD'
| 'CLIENT_NAME_INCOMPLETE'
| 'PATIENT_NAME_INCOMPLETE';
export type ExocadTransferFailure = 'NOT_EXOCAD' | 'PATIENT_NAME_INCOMPLETE';
export class ExocadTransferError extends Error {
constructor(readonly code: ExocadTransferFailure) {
@@ -88,6 +85,8 @@ export type ExocadTransferResult = {
treatmentId: number;
created: boolean;
skipped: ExocadSkippedLine[];
/** `{date}_{practice}-{tray}` under the Exocad CAD-Data directory. */
projectFolder: string;
};
export type ExocadTransferOptions = {
@@ -121,6 +120,14 @@ export function exocadDueDate(value: string | null | undefined): string | null {
return match ? match[1] : null;
}
/** Directory Exocad Save lists: `2026-11-12_00120-006`. */
export function exocadProjectFolder(dateValue: string, practiceId: number, schaleId: number): string {
const date = exocadDueDate(dateValue) ?? '0000-00-00';
const practice = String(practiceId).padStart(5, '0');
const tray = String(schaleId).padStart(3, '0');
return `${date}_${practice}-${tray}`;
}
function buildNotes(comment: string): string | null {
const text = comment.trim();
return text.length > 0 ? text : null;
@@ -305,19 +312,21 @@ function insertClient(db: SqliteQuery, name: string): number {
return practiceId;
}
type ClientChoice =
| { practiceId: number }
| { createName: string }
| { failure: 'CLIENT_NAME_INCOMPLETE' };
type ClientChoice = { practiceId: number } | { createName: string };
function decideClient(rows: Array<{ practiceId: number; name: string }>, clinicName: string): ClientChoice {
const wanted = clinicName.trim();
if (!wanted) {
const blank = rows.find((row) => row.name.trim() === '');
if (blank) return { practiceId: blank.practiceId };
return { createName: '' };
}
const exact = rows.filter((row) => row.name.trim().toLocaleLowerCase() === wanted.toLocaleLowerCase());
if (exact.length === 1) return { practiceId: exact[0].practiceId };
const tokens = nameTokens(wanted);
if (tokens.length === 0) return { failure: 'CLIENT_NAME_INCOMPLETE' };
const matches = rows.filter((row) => coversTokens(row.name, tokens));
if (matches.length === 1) return { practiceId: matches[0].practiceId };
if (tokens.length >= 2) return { createName: wanted };
return { failure: 'CLIENT_NAME_INCOMPLETE' };
return { createName: wanted };
}
function matchingPatientId(
@@ -354,13 +363,12 @@ function insertPatient(
return patientId;
}
/** Match an existing client and patient, or create both only when each name has two parts. */
/** Match or create a client, including a one-word or empty clinic name. The patient still needs two name parts. */
function resolveParties(
db: SqliteQuery,
input: ExocadCaseInput,
): { practiceId: number; patientId: number } {
const decision = decideClient(clientRows(db), input.clinicName);
if ('failure' in decision) throw new ExocadTransferError(decision.failure);
const parts = personParts(input.patientFirstName, input.patientLastName);
const tokens = nameTokens(`${input.patientFirstName} ${input.patientLastName}`);
@@ -714,6 +722,27 @@ function embedMaterialConfiguration(db: SqliteQuery, treatmentId: number): void
);
}
function nextSchaleId(db: SqliteQuery, practiceId: number): number {
if (!treatmentHasColumn(db, 't_schaleId')) return 1;
const rows = db.all(
'SELECT MAX(t_schaleId) FROM Treatment WHERE practice_lab_id = ? AND practice_pr_id = ?',
[EXOCAD_LAB_ID, practiceId],
);
return numberValue(rows[0]?.[0]) + 1;
}
function storedSchaleId(db: SqliteQuery, treatmentId: number): number | null {
if (!treatmentHasColumn(db, 't_schaleId')) return null;
const rows = db.all('SELECT t_schaleId FROM Treatment WHERE treatment_id = ?', [treatmentId]);
const value = numberValue(rows[0]?.[0]);
return value > 0 ? value : null;
}
function writeSchaleId(db: SqliteQuery, treatmentId: number, schaleId: number): void {
if (!treatmentHasColumn(db, 't_schaleId')) return;
db.run('UPDATE Treatment SET t_schaleId = ? WHERE treatment_id = ?', [schaleId, treatmentId]);
}
function writeCase(db: SqliteQuery, input: ExocadCaseInput, options: ExocadTransferOptions): ExocadTransferResult {
const { practiceId, patientId } = resolveParties(db, input);
const due = exocadDueDate(input.dueDate);
@@ -735,6 +764,8 @@ function writeCase(db: SqliteQuery, input: ExocadCaseInput, options: ExocadTrans
const existing = db.all('SELECT treatment_id FROM Treatment WHERE importedOrderId = ?', [input.caseId]);
if (existing.length > 0) {
const treatmentId = numberValue(existing[0][0]);
const keptSchale = storedSchaleId(db, treatmentId);
const schaleId = keptSchale ?? nextSchaleId(db, practiceId);
db.run(
`UPDATE Treatment SET
practice_lab_id = ?,
@@ -748,14 +779,16 @@ function writeCase(db: SqliteQuery, input: ExocadCaseInput, options: ExocadTrans
WHERE treatment_id = ?`,
[...header, treatmentId],
);
if (keptSchale == null) writeSchaleId(db, treatmentId, schaleId);
deleteToothWork(db, treatmentId);
insertTeeth(db, treatmentId, writes, snapshots);
copyConfirmedCaseParameters(db, treatmentId);
assignSoleTechnician(db, treatmentId);
embedMaterialConfiguration(db, treatmentId);
return { treatmentId, created: false, skipped };
return { treatmentId, created: false, skipped, projectFolder: exocadProjectFolder(now, practiceId, schaleId) };
}
const schaleId = nextSchaleId(db, practiceId);
const projectGuid = options.projectGuid ?? crypto.randomUUID();
db.run(
`INSERT INTO Treatment (
@@ -766,11 +799,12 @@ function writeCase(db: SqliteQuery, input: ExocadCaseInput, options: ExocadTrans
[...header, projectGuid, input.caseId],
);
const treatmentId = numberValue(db.all('SELECT last_insert_rowid()')[0]?.[0]);
writeSchaleId(db, treatmentId, schaleId);
insertTeeth(db, treatmentId, writes, snapshots);
copyConfirmedCaseParameters(db, treatmentId);
assignSoleTechnician(db, treatmentId);
embedMaterialConfiguration(db, treatmentId);
return { treatmentId, created: true, skipped };
return { treatmentId, created: true, skipped, projectFolder: exocadProjectFolder(now, practiceId, schaleId) };
}
/** Insert or update one DentalDB case. Disk stays unchanged until the caller exports the database. */

View File

@@ -10,7 +10,6 @@ export function localDbErrorText(
fallback: 'openFailed' | 'applyFailed' | 'loadFailed' | 'sendRolledBack',
): string {
if (error instanceof ExocadTransferError) {
if (error.code === 'CLIENT_NAME_INCOMPLETE') return t('clientNameIncomplete');
if (error.code === 'PATIENT_NAME_INCOMPLETE') return t('patientNameIncomplete');
return t('notExocad');
}

View File

@@ -10,7 +10,8 @@ export type TodayChartPeriodKey =
| 'treatmentMix'
| 'casePartners'
| 'efficiency'
| 'billing';
| 'billing'
| 'personal';
export type TodayChartPeriods = Record<TodayChartPeriodKey, TodayChartPeriod>;
@@ -23,6 +24,7 @@ export const TODAY_CHART_PERIOD_KEYS: TodayChartPeriodKey[] = [
'casePartners',
'efficiency',
'billing',
'personal',
];
export const TODAY_CHART_PERIOD_DEFAULTS: TodayChartPeriods = {
@@ -34,6 +36,7 @@ export const TODAY_CHART_PERIOD_DEFAULTS: TodayChartPeriods = {
casePartners: 'month',
efficiency: 'month',
billing: 'week',
personal: 'month',
};
/** Aggregate charts that support year; day-series charts are week/month only. */

View File

@@ -51,7 +51,9 @@ export const TODAY_GADGET_ID_FEATURE: Record<string, TodayGadgetFeature> = {
'chart-appointments-week-mine': 'treatment',
'chart-appointments-by-provider': 'appointments',
'chart-treatment-mix': 'treatment',
'chart-my-treatment-work': 'treatment',
'chart-lab-task-activity': 'cases',
'chart-my-task-work': 'tasks',
'chart-tasks-by-prosthesis': 'tasks',
'chart-cases-due-week': 'cases',
'chart-case-partners-month': 'treatment',

View File

@@ -16,6 +16,19 @@ function viewFromQuery(value: string | null): BillingHubView {
return 'transactions';
}
function partyFromQuery(searchParams: { get(name: string): string | null }): {
id: string;
name: string;
section: 'clinics' | 'labs';
} | null {
const id = searchParams.get('partyId');
const name = searchParams.get('partyName');
const section = searchParams.get('partySection');
if (!id || !name) return null;
if (section !== 'clinics' && section !== 'labs') return null;
return { id, name, section };
}
const TABS: BillingHubView[] = ['transactions', 'schedules', 'commissions'];
export function BillingPage() {
@@ -71,11 +84,12 @@ export function BillingPage() {
/>
{view === 'transactions' ? (
<BillingPaymentsPanel
<BillingPaymentsPanel
canEdit={canEdit}
orgType={isLab ? 'LAB' : 'CLINIC'}
initialFrom={initialFrom}
initialTo={initialTo}
initialParty={partyFromQuery(searchParams)}
/>
) : (
<BillingSheetsPanel

View File

@@ -61,6 +61,7 @@ type Props = {
orgType: 'CLINIC' | 'LAB';
initialFrom?: string;
initialTo?: string;
initialParty?: { id: string; name: string; section: 'clinics' | 'labs' } | null;
};
const SOURCE_LABEL_KEY: Record<BillingPartyReportRow['sourceType'], string> = {
@@ -106,6 +107,7 @@ export function BillingPaymentsPanel({
orgType,
initialFrom,
initialTo,
initialParty = null,
}: Props) {
const t = useTranslations('billing');
const tCommon = useTranslations('common');
@@ -123,8 +125,18 @@ export function BillingPaymentsPanel({
const [loading, setLoading] = useState(true);
const [query, setQuery] = useState('');
const [filterParty, setFilterParty] = useState<SelectedParty | null>(null);
const [filterParty, setFilterParty] = useState<SelectedParty | null>(initialParty);
const [typeFilter, setTypeFilter] = useState<TypeFilter>('ALL');
useEffect(() => {
if (!initialParty?.id || !initialParty.name) return;
setFilterParty({
id: initialParty.id,
name: initialParty.name,
section: initialParty.section,
});
setQuery('');
}, [initialParty?.id, initialParty?.name, initialParty?.section]);
const [from, setFrom] = useState(initialFrom ?? '');
const [to, setTo] = useState(initialTo ?? '');
const [rows, setRows] = useState<BillingLedgerRow[]>([]);
@@ -779,56 +791,6 @@ export function BillingPaymentsPanel({
</Card>
) : null}
{editingCash ? (
<BillingTransactionEditor
key={`${editingCash.kind}:${editingCash.id}:${editingCash.updatedAt}`}
row={editingCash}
party={editingCashParty}
onCancel={() => {
setEditingCash(null);
setEditingCashParty(null);
}}
onSaved={async () => {
setEditingCash(null);
setEditingCashParty(null);
await load();
}}
/>
) : null}
{editingObligation ? (
<Card className="flex flex-col gap-2 sm:flex-row sm:items-end">
<div className="min-w-0 flex-1">
<AppMoneyInput
label={moneyFieldLabel(
t('caseObligationAmount'),
currencySettings.currency,
currencyName,
)}
labelPlacement="outline"
value={obligationAmount}
onChange={setObligationAmount}
/>
</div>
<Button
variant="ghost"
onClick={() => {
setEditingObligation(null);
setObligationAmount('');
}}
disabled={obligationSaving}
>
{tCommon('cancel')}
</Button>
<Button
onClick={() => void saveObligationAmount()}
isLoading={obligationSaving}
>
{t('saveObligationAmount')}
</Button>
</Card>
) : null}
<div className="space-y-2">
<h2 className="text-sm font-semibold text-text-primary">{t('transactionHistory')}</h2>
{loading ? (
@@ -853,7 +815,37 @@ export function BillingPaymentsPanel({
}
body={
report.data.length > 0 ? (
report.data.map((row) => (
report.data.map((row) => {
if (
editingCash &&
row.lineKind === 'CASH' &&
row.paymentKind === editingCash.kind &&
row.sourceId === editingCash.id
) {
return (
<BillingTransactionEditor
key={`${editingCash.kind}:${editingCash.id}:${editingCash.updatedAt}`}
row={editingCash}
party={editingCashParty}
layout="party"
timeLabel={formatDateTime(row.occurredAt)}
source={
<span>{t(reportSourceKey(row) as 'reportSourceTreatment')}</span>
}
onCancel={() => {
setEditingCash(null);
setEditingCashParty(null);
}}
onSaved={async () => {
setEditingCash(null);
setEditingCashParty(null);
await load();
}}
/>
);
}
const editingAmount = editingObligation?.id === row.id;
return (
<tr
key={row.id}
className={
@@ -906,6 +898,11 @@ export function BillingPaymentsPanel({
{t('obligationAmountRequired')}
</Badge>
) : null}
{row.projected ? (
<Badge variant="default" fixedWidth={false}>
{t('projectedSoFar')}
</Badge>
) : null}
</div>
</td>
<td className="text-sm text-text-secondary">
@@ -927,20 +924,50 @@ export function BillingPaymentsPanel({
</div>
</td>
<td className="text-sm tabular-nums text-text-primary">
<div className="flex items-center gap-2">
<span>
{row.amount == null ? '—' : formatMoney(row.amount)}
</span>
<span className="rounded border border-border bg-background-secondary/70 px-1.5 py-0.5 text-[0.625rem] font-semibold uppercase tracking-wide text-text-muted">
{row.direction === 'DEBIT'
? t('debit')
: t('credit')}
</span>
</div>
{editingAmount ? (
<AppMoneyInput
value={obligationAmount}
onChange={setObligationAmount}
disabled={obligationSaving}
/>
) : (
<div className="flex items-center gap-2">
<span>
{row.amount == null ? '—' : formatMoney(row.amount)}
</span>
<span className="rounded border border-border bg-background-secondary/70 px-1.5 py-0.5 text-[0.625rem] font-semibold uppercase tracking-wide text-text-muted">
{row.direction === 'DEBIT'
? t('debit')
: t('credit')}
</span>
</div>
)}
</td>
<td>
<div className="flex items-center gap-1">
{canEdit && row.canEditCash && row.paymentKind && row.updatedAt ? (
{editingAmount ? (
<>
<Button
size="sm"
onClick={() => void saveObligationAmount()}
isLoading={obligationSaving}
>
{tCommon('save')}
</Button>
<Button
size="sm"
variant="ghost"
disabled={obligationSaving}
onClick={() => {
setEditingObligation(null);
setObligationAmount('');
}}
>
{tCommon('cancel')}
</Button>
</>
) : null}
{!editingAmount && canEdit && row.canEditCash && row.paymentKind && row.updatedAt ? (
<TableIconButton
label={t('editTransaction')}
onClick={() =>
@@ -964,7 +991,7 @@ export function BillingPaymentsPanel({
<Pencil className="h-4 w-4" />
</TableIconButton>
) : null}
{canEdit && row.canEditAmount ? (
{!editingAmount && canEdit && row.canEditAmount ? (
<TableIconButton
label={t('setObligationAmount')}
onClick={() => {
@@ -977,7 +1004,7 @@ export function BillingPaymentsPanel({
<Pencil className="h-4 w-4" />
</TableIconButton>
) : null}
{canEdit && row.canAcknowledge && row.updatedAt ? (
{!editingAmount && canEdit && row.canAcknowledge && row.updatedAt ? (
<>
<TableIconButton
label={t('acceptPayment')}
@@ -1011,7 +1038,8 @@ export function BillingPaymentsPanel({
</div>
</td>
</tr>
))
);
})
) : (
<tr>
<td colSpan={5} className="py-5 text-center text-sm text-text-muted">
@@ -1054,7 +1082,37 @@ export function BillingPaymentsPanel({
</th>
</tr>
}
body={visibleRows.map((row) => (
body={visibleRows.map((row) => {
if (editingCash && editingCash.id === row.id && editingCash.kind === row.kind) {
const partyName = row.partyIsWalkIn
? `${row.partyName} · ${t('walkInPatient')}`
: row.partyName;
return (
<BillingTransactionEditor
key={`${editingCash.kind}:${editingCash.id}:${editingCash.updatedAt}`}
row={editingCash}
party={editingCashParty}
layout="cash"
timeLabel={formatDateTime(row.paidAt)}
partyCell={<span className="truncate" title={partyName}>{partyName}</span>}
typeCell={
<Badge variant={row.type === 'RECEIPT' ? 'success' : 'warning'}>
{row.type === 'RECEIPT' ? t('receipt') : t('payment')}
</Badge>
}
onCancel={() => {
setEditingCash(null);
setEditingCashParty(null);
}}
onSaved={async () => {
setEditingCash(null);
setEditingCashParty(null);
await load();
}}
/>
);
}
return (
<tr
key={`${row.kind}-${row.id}`}
className={
@@ -1166,7 +1224,8 @@ export function BillingPaymentsPanel({
</div>
</td>
</tr>
))}
);
})}
/>
)}
</div>

View File

@@ -1,17 +1,14 @@
'use client';
import { useEffect, useState } from 'react';
import { useEffect, useState, type ReactNode } from 'react';
import { useTranslations } from 'next-intl';
import { AppMoneyInput } from '@/components/ui/shared/AppMoneyInput';
import { Button } from '@/components/ui/shared/Button';
import { Card } from '@/components/ui/shared/Card';
import { Input } from '@/components/ui/shared/Input';
import { moneyFieldLabel } from '@/components/billing/moneyFieldLabel';
import { stripTrailingDecimalZeros } from '@/lib/i18n/moneyInputFormat';
import { parseAppMoney } from '@/lib/i18n/format';
import { billingApi } from '@/lib/api/billing';
import { getUserFacingError } from '@/components/shared/formatApiError';
import { useBillingCurrency } from '@/lib/hooks/useBillingCurrency';
import { useAppFormatters } from '@/lib/hooks/useAppFormatters';
import { useToast } from '@/lib/hooks/useToast';
import type { BillingPartyKind } from '@/types/billing';
@@ -31,6 +28,11 @@ type Props = {
party: { kind: BillingPartyKind; id: string } | null;
onCancel: () => void;
onSaved: () => Promise<void> | void;
layout: 'party' | 'cash';
timeLabel: string;
source?: ReactNode;
partyCell?: ReactNode;
typeCell?: ReactNode;
};
type AllocationHit = { id: string; label: string; billed: string | null };
@@ -40,13 +42,17 @@ export function BillingTransactionEditor({
party,
onCancel,
onSaved,
layout,
timeLabel,
source,
partyCell,
typeCell,
}: Props) {
const t = useTranslations('billing');
const tCommon = useTranslations('common');
const tErrors = useTranslations('errors');
const toast = useToast();
const { formatMoney } = useAppFormatters();
const { settings } = useBillingCurrency(true);
const [amount, setAmount] = useState(stripTrailingDecimalZeros(row.amount));
const [note, setNote] = useState(row.note ?? '');
const [allocations, setAllocations] = useState(row.allocations);
@@ -58,11 +64,7 @@ export function BillingTransactionEditor({
Boolean(party?.id) &&
((row.kind === 'patient' && party?.kind === 'patient') ||
(row.kind === 'partner' && party?.kind === 'org'));
const amountLabel = moneyFieldLabel(
t('amount'),
settings.currency,
(code) => tCommon(`currencyName.${code}` as 'currencyName.TOMAN'),
);
const columnCount = layout === 'party' ? 5 : 6;
useEffect(() => {
if (!canAllocate || !party) {
@@ -168,95 +170,120 @@ export function BillingTransactionEditor({
}
}
return (
<Card className="space-y-3">
<p className="text-sm font-medium text-text-primary">{t('editTransaction')}</p>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
<AppMoneyInput
label={amountLabel}
labelPlacement="outline"
value={amount}
onChange={setAmount}
/>
<Input
label={t('note')}
labelPlacement="outline"
value={note}
onChange={(event) => setNote(event.target.value)}
maxLength={500}
/>
</div>
const amountField = (
<AppMoneyInput value={amount} onChange={setAmount} disabled={saving} />
);
const noteField = (
<Input
value={note}
onChange={(event) => setNote(event.target.value)}
maxLength={500}
placeholder={t('note')}
disabled={saving}
aria-label={t('note')}
/>
);
const actions = (
<div className="flex flex-wrap items-center gap-1">
<Button size="sm" onClick={() => void save()} isLoading={saving}>
{tCommon('save')}
</Button>
<Button size="sm" variant="ghost" onClick={onCancel} disabled={saving}>
{tCommon('cancel')}
</Button>
</div>
);
return (
<>
<tr className="bg-background-secondary/40">
{layout === 'party' ? (
<>
<td className="truncate text-sm text-text-secondary" title={timeLabel}>
{timeLabel}
</td>
<td className="text-sm text-text-primary">{source}</td>
<td>{noteField}</td>
<td>{amountField}</td>
<td>{actions}</td>
</>
) : (
<>
<td className="text-sm font-medium text-text-primary">{partyCell}</td>
<td>{typeCell}</td>
<td>{amountField}</td>
<td className="truncate text-sm text-text-secondary" title={timeLabel}>
{timeLabel}
</td>
<td>{noteField}</td>
<td>{actions}</td>
</>
)}
</tr>
{canAllocate ? (
<div className="space-y-2 rounded-[var(--radius-md)] border border-border/60 p-3">
<Input
label={row.kind === 'patient' ? t('attachTreatments') : t('attachCases')}
labelPlacement="outline"
value={allocationQuery}
onChange={(event) => setAllocationQuery(event.target.value)}
placeholder={t('searchAllocations')}
/>
{hits.length > 0 ? (
<ul className="max-h-32 divide-y divide-border/40 overflow-y-auto rounded-[var(--radius-sm)] border border-border/60">
{hits.map((hit) => (
<li key={hit.id}>
<button
type="button"
className="w-full px-3 py-2 text-start text-sm hover:bg-background-card/70"
onClick={() => addAllocation(hit)}
>
{hit.label}
{hit.billed ? (
<span className="ms-2 text-text-muted">
{formatMoney(hit.billed)}
</span>
) : null}
</button>
</li>
))}
</ul>
) : null}
{allocations.map((allocation) => (
<div key={allocation.targetId} className="flex flex-wrap items-center gap-2">
<span className="min-w-0 flex-1 text-sm">{allocation.label}</span>
<div className="w-28">
<AppMoneyInput
value={allocation.amount}
onChange={(value) =>
<tr className="bg-background-secondary/40">
<td colSpan={columnCount} className="space-y-2">
<Input
label={row.kind === 'patient' ? t('attachTreatments') : t('attachCases')}
labelPlacement="outline"
value={allocationQuery}
onChange={(event) => setAllocationQuery(event.target.value)}
placeholder={t('searchAllocations')}
disabled={saving}
/>
{hits.length > 0 ? (
<ul className="max-h-32 divide-y divide-border/40 overflow-y-auto rounded-[var(--radius-sm)] border border-border/60">
{hits.map((hit) => (
<li key={hit.id}>
<button
type="button"
className="w-full px-3 py-2 text-start text-sm hover:bg-background-card/70"
onClick={() => addAllocation(hit)}
>
{hit.label}
{hit.billed ? (
<span className="ms-2 text-text-muted">{formatMoney(hit.billed)}</span>
) : null}
</button>
</li>
))}
</ul>
) : null}
{allocations.map((allocation) => (
<div key={allocation.targetId} className="flex flex-wrap items-center gap-2">
<span className="min-w-0 flex-1 text-sm">{allocation.label}</span>
<div className="w-28">
<AppMoneyInput
value={allocation.amount}
disabled={saving}
onChange={(value) =>
setAllocations((current) =>
current.map((item) =>
item.targetId === allocation.targetId
? { ...item, amount: value }
: item,
),
)
}
/>
</div>
<Button
size="sm"
variant="ghost"
disabled={saving}
onClick={() =>
setAllocations((current) =>
current.map((item) =>
item.targetId === allocation.targetId
? { ...item, amount: value }
: item,
),
current.filter((item) => item.targetId !== allocation.targetId),
)
}
/>
>
{tCommon('delete')}
</Button>
</div>
<Button
size="sm"
variant="ghost"
onClick={() =>
setAllocations((current) =>
current.filter((item) => item.targetId !== allocation.targetId),
)
}
>
{tCommon('delete')}
</Button>
</div>
))}
</div>
))}
</td>
</tr>
) : null}
<div className="flex flex-col-reverse gap-2 sm:flex-row">
<Button variant="ghost" onClick={onCancel} disabled={saving}>
{tCommon('cancel')}
</Button>
<Button onClick={() => void save()} isLoading={saving}>
{t('saveTransaction')}
</Button>
</div>
</Card>
</>
);
}

View File

@@ -39,9 +39,14 @@ import { useCaseSectionCounts } from '@/lib/hooks/useCaseSectionCounts';
import { forgetKnownCaseFile, withKnownCaseFiles } from '@/lib/uploads/caseUploadQueue';
import { ConnectedSelectionBadge } from '@/components/ui/treatment/ConnectedSelectionBadge';
import { useToast } from '@/lib/hooks/useToast';
import { formatAppMoney } from '@/lib/i18n/format';
import { formatAppMoney, parseAppMoney } from '@/lib/i18n/format';
import { stripTrailingDecimalZeros } from '@/lib/i18n/moneyInputFormat';
import { moneyFieldLabel } from '@/components/billing/moneyFieldLabel';
import { useBillingCurrency } from '@/lib/hooks/useBillingCurrency';
import { useAuth } from '@/lib/hooks/useAuth';
import { hasPermission } from '@/components/shared/permissions';
import { billingApi } from '@/lib/api/billing';
import { AppMoneyInput } from '@/components/ui/shared/AppMoneyInput';
import type { BillingCurrency } from '@/types/billing';
import {
CASE_TASK_SCOPE,
@@ -290,6 +295,7 @@ export function CaseDetailPanel({
onCaseUpdated,
}: CaseDetailPanelProps) {
const t = useTranslations('cases');
const tBilling = useTranslations('billing');
const tLocal = useTranslations('localDb');
const tTreatment = useTranslations('treatment');
const tComments = useTranslations('caseComments');
@@ -297,6 +303,19 @@ export function CaseDetailPanel({
const tCommon = useTranslations('common');
const intlLocale = useLocale();
const { settings: currencySettings } = useBillingCurrency(true);
const { currentOrganization } = useAuth();
const canEditCaseFee =
hasPermission(currentOrganization, 'TAB_BILLING_EDIT') &&
currentOrganization?.id === labCase.destinationOrganizationId;
const [feeDraft, setFeeDraft] = useState(
stripTrailingDecimalZeros(labCase.billedAmount || labCase.calculatedAmount || ''),
);
const [feeSaving, setFeeSaving] = useState(false);
useEffect(() => {
setFeeDraft(
stripTrailingDecimalZeros(labCase.billedAmount || labCase.calculatedAmount || ''),
);
}, [labCase.id, labCase.billedAmount, labCase.calculatedAmount]);
const billedLeadLabel = moneyFieldLabel(
t('billedLead'),
currencySettings.currency,
@@ -474,6 +493,12 @@ export function CaseDetailPanel({
})
: '';
toast.showSuccess(saved);
try {
const folderReady = await localDb.ensureProjectFolder(result.projectFolder);
if (!folderReady) toast.showInfo(t('sendToExocadFolderMissing'));
} catch {
toast.showInfo(t('sendToExocadFolderMissing'));
}
if (skipped) toast.showInfo(skipped);
} catch (caught) {
toast.showError(localDbErrorText(caught, tLocal, 'applyFailed'));
@@ -594,12 +619,65 @@ export function CaseDetailPanel({
{t('importantLabel')}
</Badge>
) : null}
{labCase.billedAmount != null ? (
{canEditCaseFee ? (
<div className="flex flex-wrap items-center gap-2">
<span className="text-xs font-bold text-text-primary sm:text-sm">
{billedLeadLabel}
</span>
<div className="w-32">
<AppMoneyInput
value={feeDraft}
onChange={setFeeDraft}
disabled={feeSaving}
/>
</div>
<Button
size="sm"
isLoading={feeSaving}
onClick={() => {
const parsed = parseAppMoney(feeDraft);
if (!parsed || Number(parsed) <= 0) {
toast.showError(tErrors('BILLING_AMOUNT_INVALID'));
return;
}
setFeeSaving(true);
void billingApi
.setCaseBilledAmount(labCase.id, parsed)
.then((saved) => {
toast.showSuccess(tBilling('obligationAmountSaved'));
onCaseUpdated?.({
...labCase,
billedAmount: saved.data.amount,
billedAmountManual: true,
});
})
.catch((error: unknown) => {
toast.showError(
getUserFacingError(
error,
tErrors,
tBilling('errorSaveObligationAmount'),
),
);
})
.finally(() => setFeeSaving(false));
}}
>
{tCommon('save')}
</Button>
</div>
) : labCase.billedAmount != null ? (
<p className="text-xs text-text-secondary sm:text-sm">
<span className="font-bold text-text-primary">{billedLeadLabel}</span>
{' : '}
{formatAppMoney(labCase.billedAmount, intlLocale)}
</p>
) : labCase.calculatedAmount ? (
<p className="text-xs text-text-secondary sm:text-sm">
<span className="font-bold text-text-primary">{billedLeadLabel}</span>
{' : '}
{formatAppMoney(labCase.calculatedAmount, intlLocale)}
</p>
) : null}
</div>
</div>

View File

@@ -19,6 +19,7 @@ import {
import {
browserCanWriteLocalFile,
browserDatabaseStillExists,
ensureExocadProjectDirectory,
forgetBrowserDatabase,
preloadBrowserHandle,
reopenStoredBrowserFile,
@@ -39,6 +40,8 @@ export type LocalDbSessionValue = {
abandon: () => Promise<void>;
requestConnection: () => Promise<boolean>;
transferCase: (input: ExocadCaseInput) => ExocadTransferResult;
/** Create the empty CAD-Data project directory. False when the folder was not granted. */
ensureProjectFolder: (folderName: string) => Promise<boolean>;
};
const LocalDbSessionContext = createContext<LocalDbSessionValue | null>(null);
@@ -108,6 +111,11 @@ export function LocalDbSessionProvider({ children }: { children: ReactNode }) {
return session.execute((query) => transferCaseToExocad(query, input));
}, []);
const ensureProjectFolder = useCallback(
(folderName: string) => ensureExocadProjectDirectory(folderName),
[],
);
const finishConnect = useCallback((connected: boolean) => {
setConnectOpen(false);
connectResolveRef.current?.(connected);
@@ -145,8 +153,8 @@ export function LocalDbSessionProvider({ children }: { children: ReactNode }) {
}, [dropSession, replaceWithSink]);
const value = useMemo<LocalDbSessionValue>(
() => ({ apply, abandon, requestConnection, transferCase }),
[abandon, apply, requestConnection, transferCase],
() => ({ apply, abandon, requestConnection, transferCase, ensureProjectFolder }),
[abandon, apply, ensureProjectFolder, requestConnection, transferCase],
);
return (

View File

@@ -18,6 +18,10 @@ const TYPE_I18N: Record<UserNotificationType, string> = {
CONNECTION_REQUEST: 'typeConnectionRequest',
STAFF_INVITE: 'typeStaffInvite',
SEAT_EXPIRING: 'typeSeatExpiring',
BILLING_CASE_FEE: 'typeBillingCaseFee',
BILLING_CASE_FEE_PENDING: 'typeBillingCaseFeePending',
BILLING_PAYMENT_PENDING: 'typeBillingPaymentPending',
BILLING_PAYMENT_DECLINED: 'typeBillingPaymentDeclined',
};
function destKeyFromHref(href: string): string {
@@ -30,6 +34,7 @@ function destKeyFromHref(href: string): string {
return 'destSubscriptions';
}
if (href === '/today' || href.startsWith('/today/')) return 'destToday';
if (href === '/billing' || href.startsWith('/billing?')) return 'destBilling';
return 'destOpen';
}

View File

@@ -41,6 +41,7 @@ import {
mapLabTaskActivityChartData,
TodayLabTaskActivityChart,
} from '@/components/ui/today/TodayLabTaskActivityChart';
import { TodayPersonalWorkChart } from '@/components/ui/today/TodayPersonalWorkChart';
import { TodaySubscriptionKpiCard } from '@/components/ui/today/TodaySubscriptionKpiCard';
import { TodayUpcomingAppointments } from '@/components/ui/today/TodayUpcomingAppointments';
import {
@@ -549,6 +550,34 @@ function buildChartCells(options: {
});
}
const taskWork = charts.myTaskWork;
if (taskWork) {
cells.push({
id: 'chart-my-task-work',
layout: areaChart,
content: (
<ChartCard
title={t('chartMyTasksTitle')}
headerAction={periodSelect('personal')}
isEmpty={taskWork.days.every(
(day) => day.work === 0 && day.income === 0 && day.paid === 0,
)}
emptyMessage={t('chartEmpty')}
>
<TodayPersonalWorkChart
data={mapWeekChartBuckets(taskWork.days, options.dayLabelFormatter)}
workLabel={t('chartPersonalWorkLegend')}
incomeLabel={t('chartPersonalIncomeLegend')}
paidLabel={t('chartPersonalPaid')}
workTotalLabel={t('chartPersonalTaskTotal', { count: taskWork.workTotal })}
incomeTotalLabel={options.formatMoney(taskWork.incomeTotal)}
formatMoney={(value) => options.formatMoney(value)}
/>
</ChartCard>
),
});
}
if (orgType === 'LAB' && charts.labTaskActivityWeek !== undefined) {
cells.push({
id: 'chart-lab-task-activity',
@@ -732,6 +761,36 @@ function buildChartCells(options: {
});
}
const treatmentWork = charts.myTreatmentWork;
if (treatmentWork) {
cells.push({
id: 'chart-my-treatment-work',
layout: areaChart,
content: (
<ChartCard
title={t('chartMyTreatmentTitle')}
headerAction={periodSelect('personal')}
isEmpty={treatmentWork.days.every(
(day) => day.work === 0 && day.income === 0 && day.paid === 0,
)}
emptyMessage={t('chartEmpty')}
>
<TodayPersonalWorkChart
data={mapWeekChartBuckets(treatmentWork.days, options.dayLabelFormatter)}
workLabel={t('chartPersonalWorkLegend')}
incomeLabel={t('chartPersonalIncomeLegend')}
paidLabel={t('chartPersonalPaid')}
workTotalLabel={t('chartPersonalTreatmentTotal', {
count: treatmentWork.workTotal,
})}
incomeTotalLabel={options.formatMoney(treatmentWork.incomeTotal)}
formatMoney={(value) => options.formatMoney(value)}
/>
</ChartCard>
),
});
}
const dentistMixData = charts.dentistBilledMix ?? [];
if (options.showDentistMixChart && charts.dentistBilledMix !== undefined) {
cells.push({
@@ -852,10 +911,12 @@ function countVisibleCharts(
count += charts.treatmentMixWeek !== undefined ? 1 : 0;
count += showCasePartnersChart && charts.casePartnersMonth !== undefined ? 1 : 0;
count += charts.dentistBilledMix !== undefined ? 1 : 0;
count += charts.myTreatmentWork !== undefined ? 1 : 0;
count += charts.clinicDentistsBilled !== undefined ? 1 : 0;
}
if (orgType === 'LAB') {
count += charts.labTaskActivityWeek !== undefined ? 1 : 0;
count += charts.myTaskWork !== undefined ? 1 : 0;
count += charts.tasksByProsthesis !== undefined ? 1 : 0;
count += charts.casesDueWeek !== undefined ? 1 : 0;
count += showCasePartnersChart && charts.casePartnersMonth !== undefined ? 1 : 0;

View File

@@ -0,0 +1,174 @@
'use client';
import { useMemo } from 'react';
import { useLocale } from 'next-intl';
import {
Bar,
CartesianGrid,
ComposedChart,
Line,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from 'recharts';
import { TodayChartFrame } from '@/components/ui/today/TodayChartFrame';
import {
TODAY_CHART_AXIS_COLOR,
TODAY_CHART_COMPLETED_COLOR,
TODAY_CHART_GRID_COLOR,
TODAY_CHART_RECEIVED_COLOR,
TODAY_CHART_TOOLTIP_BG,
TODAY_CHART_TOOLTIP_BORDER,
} from '@/components/today/chart-theme';
import {
TODAY_CHART_PLOT_MARGIN,
TODAY_CHART_X_PADDING,
todayChartDenseXAxisProps,
} from '@/components/today/chart-day-labels';
import type { TodayPersonalDay } from '@/types/today';
export type PersonalWorkChartRow = TodayPersonalDay & { axisLabel: string };
interface TodayPersonalWorkChartProps {
data: PersonalWorkChartRow[];
workLabel: string;
incomeLabel: string;
paidLabel: string;
workTotalLabel: string;
incomeTotalLabel: string;
formatMoney: (value: number) => string;
}
export function TodayPersonalWorkChart({
data,
workLabel,
incomeLabel,
paidLabel,
workTotalLabel,
incomeTotalLabel,
formatMoney,
}: TodayPersonalWorkChartProps) {
const locale = useLocale();
const compact = useMemo(
() =>
new Intl.NumberFormat(locale === 'fa' ? 'fa-IR' : locale, {
notation: 'compact',
maximumFractionDigits: 1,
}),
[locale],
);
const xAxis = todayChartDenseXAxisProps(data.length);
const showDots = data.length <= 14;
return (
<TodayChartFrame>
<div className="flex h-full min-h-0 flex-col">
<div className="min-h-0 flex-1">
<ResponsiveContainer width="100%" height="100%">
<ComposedChart data={data} margin={TODAY_CHART_PLOT_MARGIN}>
<CartesianGrid stroke={TODAY_CHART_GRID_COLOR} vertical={false} />
<XAxis
dataKey="axisLabel"
padding={TODAY_CHART_X_PADDING}
tick={{ fill: TODAY_CHART_AXIS_COLOR, fontSize: xAxis.fontSize }}
axisLine={{ stroke: TODAY_CHART_GRID_COLOR }}
tickLine={false}
interval={xAxis.interval}
minTickGap={xAxis.minTickGap}
/>
<YAxis
yAxisId="work"
allowDecimals={false}
tick={{ fill: TODAY_CHART_AXIS_COLOR, fontSize: 11 }}
axisLine={false}
tickLine={false}
width={32}
/>
<YAxis
yAxisId="income"
orientation="right"
tick={{ fill: TODAY_CHART_AXIS_COLOR, fontSize: 11 }}
axisLine={false}
tickLine={false}
width={48}
tickFormatter={(value: number) => compact.format(value)}
/>
<Tooltip
cursor={{ fill: 'rgba(0, 188, 255, 0.08)' }}
content={({ active, payload }) => {
if (!active || !payload?.length) return null;
const row = payload[0]?.payload as PersonalWorkChartRow | undefined;
if (!row) return null;
return (
<div
className="rounded-md px-3 py-2 text-xs shadow-md"
style={{
backgroundColor: TODAY_CHART_TOOLTIP_BG,
border: `1px solid ${TODAY_CHART_TOOLTIP_BORDER}`,
color: '#f5f9ff',
}}
>
<p className="font-medium">{row.label}</p>
<p className="mt-0.5">
{workLabel}: {row.work}
</p>
<p>
{incomeLabel}: {formatMoney(row.income)}
</p>
<p>
{paidLabel}: {formatMoney(row.paid)}
</p>
</div>
);
}}
/>
<Bar
yAxisId="work"
dataKey="work"
name={workLabel}
fill={TODAY_CHART_COMPLETED_COLOR}
radius={[4, 4, 0, 0]}
maxBarSize={48}
/>
<Line
yAxisId="income"
type="monotone"
dataKey="income"
name={incomeLabel}
stroke={TODAY_CHART_RECEIVED_COLOR}
strokeWidth={2}
dot={
showDots
? { r: 3, fill: TODAY_CHART_RECEIVED_COLOR, strokeWidth: 0 }
: false
}
activeDot={{ r: 5, fill: TODAY_CHART_RECEIVED_COLOR }}
/>
</ComposedChart>
</ResponsiveContainer>
</div>
<div className="mt-0.5 flex shrink-0 flex-wrap items-center justify-center gap-x-4 gap-y-0.5 pb-0 text-[11px] text-text-muted">
<span className="inline-flex items-center gap-1.5 whitespace-nowrap">
<span
className="inline-block h-2.5 w-2.5 shrink-0 rounded-sm"
style={{ backgroundColor: TODAY_CHART_COMPLETED_COLOR }}
aria-hidden
/>
{workLabel}
{workTotalLabel}
</span>
<span className="inline-flex items-center gap-1.5 whitespace-nowrap">
<span
className="inline-block h-2.5 w-2.5 shrink-0 rounded-sm"
style={{ backgroundColor: TODAY_CHART_RECEIVED_COLOR }}
aria-hidden
/>
{incomeLabel}
{incomeTotalLabel}
</span>
</div>
</div>
</TodayChartFrame>
);
}

View File

@@ -490,6 +490,17 @@ export function LabCasesDispatchPanel({
</span>
</p>
) : null}
{sent && activeLabCase?.billedAmount ? (
<p className="text-sm text-text-secondary">
{t('labFeePreview')}{' '}
<span className="font-medium text-text-primary tabular-nums">
{formatMoney(activeLabCase.billedAmount)}
</span>
</p>
) : null}
{sent && !activeLabCase?.billedAmount ? (
<p className={labBlockedBannerClass}>{t('labFeeSentNeedsAmount')}</p>
) : null}
{quoteLabId &&
unsupportedCodes.length > 0 &&
!sendBlockedByPriceSheet ? (

View File

@@ -284,6 +284,9 @@ function mapLabCaseDraftFromApi(lc: PastLabCase): LabCaseDraft {
dueDate: lc.dueDate ?? null,
taskProgress: lc.taskProgress ?? null,
shareUrl: lc.shareUrl ?? null,
calculatedAmount: lc.calculatedAmount ?? null,
billedAmount: lc.billedAmount ?? null,
billedAmountManual: Boolean(lc.billedAmountManual),
};
}
@@ -386,7 +389,14 @@ function mergeServerIdsIntoLabCases(
return local.map((lc) => {
const s = byClientId.get(lc.clientId);
if (!s) return lc;
return { ...lc, id: s.id ?? lc.id, shareUrl: s.shareUrl ?? lc.shareUrl };
return {
...lc,
id: s.id ?? lc.id,
shareUrl: s.shareUrl ?? lc.shareUrl,
calculatedAmount: s.calculatedAmount ?? lc.calculatedAmount,
billedAmount: s.billedAmount ?? lc.billedAmount,
billedAmountManual: s.billedAmountManual ?? lc.billedAmountManual,
};
});
}
@@ -501,7 +511,7 @@ export function TreatmentWorkspace({
const [patientSearchBusy, setPatientSearchBusy] = useState(false);
const [newTreatmentPickerOpen, setNewTreatmentPickerOpen] = useState(false);
const [creatingStandalone, setCreatingStandalone] = useState(false);
/** Below xl: show left rail instead of editor (Cases-style pane swap). */
/** Below xl: history pane instead of the editor and patient card. */
const [mobileRailOpen, setMobileRailOpen] = useState(false);
const {
@@ -724,12 +734,6 @@ export function TreatmentWorkspace({
!historyLoading &&
history.length === 0;
useEffect(() => {
if (showNoTreatmentFound) {
setMobileRailOpen(true);
}
}, [showNoTreatmentFound]);
const unreadUpdatesCount = unreadLabCases.length;
const otherPatientsUnreadCount = useMemo(
() => unreadLabCases.filter((item) => item.patientId !== activePatientId).length,
@@ -2780,6 +2784,9 @@ export function TreatmentWorkspace({
sends: response.data.sends,
taskProgress: response.data.taskProgress ?? lc.taskProgress,
shareUrl: response.data.shareUrl ?? lc.shareUrl,
calculatedAmount: response.data.calculatedAmount ?? lc.calculatedAmount,
billedAmount: response.data.billedAmount ?? null,
billedAmountManual: Boolean(response.data.billedAmountManual),
}
: lc,
),
@@ -2909,11 +2916,10 @@ export function TreatmentWorkspace({
<div className="treatment-layout-grid grid grid-cols-1 xl:grid-cols-[minmax(300px,380px)_minmax(0,1fr)] gap-4 items-start">
<div
className={`space-y-3 min-w-0 xl:max-w-[380px] ${
mobileRailOpen ? 'block' : 'hidden'
className={`min-w-0 xl:col-start-1 xl:row-start-1 xl:max-w-[380px] ${
mobileRailOpen ? 'hidden' : 'block'
} xl:block`}
>
<MobileDetailBackButton hideFrom="xl" onClick={() => setMobileRailOpen(false)} />
<div className="surface-card p-3 space-y-3">
{canEdit && !isViewingPastDay ? (
<div className="space-y-2">
@@ -2974,6 +2980,14 @@ export function TreatmentWorkspace({
</p>
)}
</div>
</div>
<div
className={`space-y-3 min-w-0 xl:col-start-1 xl:row-start-2 xl:max-w-[380px] ${
mobileRailOpen ? 'block' : 'hidden'
} xl:block`}
>
<MobileDetailBackButton hideFrom="xl" onClick={() => setMobileRailOpen(false)} />
{isBrowsing && previewTreatment ? (
<>
@@ -3072,7 +3086,7 @@ export function TreatmentWorkspace({
</div>
<div
className={`space-y-3 min-w-0 w-full ${
className={`space-y-3 min-w-0 w-full xl:col-start-2 xl:row-start-1 xl:row-span-2 ${
mobileRailOpen ? 'hidden' : 'block'
} xl:block`}
>
@@ -3080,7 +3094,7 @@ export function TreatmentWorkspace({
<Button
type="button"
variant="outline"
size="sm"
fullWidth
onClick={() => setMobileRailOpen(true)}
>
{t('mobileOpenRail')}

View File

@@ -269,6 +269,17 @@ export const billingApi = {
return response.data;
},
setCaseBilledAmount: async (
labCaseId: string,
amount: string,
): Promise<{ success: boolean; data: { amount: string } }> => {
const response = await apiClient.put(
`/billing/cases/${encodeURIComponent(labCaseId)}/amount`,
{ amount },
);
return response.data;
},
updateObligationAmount: async (
entryId: string,
amount: string,

View File

@@ -20,6 +20,7 @@ function chartPeriodQuery(periods?: TodayChartPeriods) {
casePartnersPeriod: periods.casePartners,
efficiencyPeriod: periods.efficiency,
billingPeriod: periods.billing,
personalPeriod: periods.personal,
};
}

View File

@@ -208,6 +208,7 @@ export type BillingPartyReportRow = {
updatedAt?: string;
allocations?: Array<{ targetId: string; amount: string; label: string }>;
countsInTotals: boolean;
projected?: boolean;
};
export type BillingPartyReport = {

View File

@@ -196,6 +196,7 @@ export interface LabCaseDetail {
/** Present only for the lab that owns this case. Direct handoffs; no further lab is named. */
outsourcing?: LabCaseOutsourceHandoff[];
shareUrl?: string | null;
destinationOrganizationId?: string | null;
calculatedAmount?: string | null;
billedAmount?: string | null;
billedAmountManual?: boolean;

View File

@@ -10,7 +10,11 @@ export type UserNotificationType =
| 'PARTNER_CASE_CREATED'
| 'CONNECTION_REQUEST'
| 'STAFF_INVITE'
| 'SEAT_EXPIRING';
| 'SEAT_EXPIRING'
| 'BILLING_CASE_FEE'
| 'BILLING_CASE_FEE_PENDING'
| 'BILLING_PAYMENT_PENDING'
| 'BILLING_PAYMENT_DECLINED';
export type UserNotificationItem = {
id: string;

View File

@@ -40,6 +40,24 @@ export type TodayCompletionGauge = {
percent: number;
};
export type TodayPersonalDay = {
code: string;
label: string;
/** Short tick (`Oct 10`). Tooltip uses `label`. */
axisLabel?: string;
work: number;
income: number;
/** Staff payments recorded that day. Tooltip only. */
paid: number;
};
export type TodayPersonalSeries = {
days: TodayPersonalDay[];
workTotal: number;
incomeTotal: number;
paidTotal: number;
};
export type TodaySummaryCharts = {
treatmentMixWeek?: TodayChartBucket[];
tasksByProsthesis?: TodayChartBucket[];
@@ -55,6 +73,8 @@ export type TodaySummaryCharts = {
dentistBilledMix?: TodayChartBucket[];
clinicDentistsBilled?: TodayChartBucket[];
labStaffCommission?: TodayChartBucket[];
myTreatmentWork?: TodayPersonalSeries;
myTaskWork?: TodayPersonalSeries;
};
export type TodayWidgetKey =

View File

@@ -131,6 +131,9 @@ export interface PastLabCase {
attachments?: TreatmentAttachmentMeta[];
/** Present on sent cases — same share URL the lab Cases QR encodes. */
shareUrl?: string | null;
calculatedAmount?: string | null;
billedAmount?: string | null;
billedAmountManual?: boolean;
}
export interface PastTreatment {
@@ -196,6 +199,9 @@ export interface LabCaseDraft {
dueDate?: string | null;
taskProgress?: LabCaseTaskProgress | null;
shareUrl?: string | null;
calculatedAmount?: string | null;
billedAmount?: string | null;
billedAmountManual?: boolean;
}
export type SavedTreatmentDetailPayload = {
@@ -251,4 +257,7 @@ export interface LabCaseResponse {
toothProsthesis?: LabCaseToothProsthesisDraft[];
attachments?: TreatmentAttachmentMeta[];
shareUrl?: string | null;
calculatedAmount?: string | null;
billedAmount?: string | null;
billedAmountManual?: boolean;
}

View File

@@ -25,6 +25,15 @@ COOKIE_SECURE=true
SMS_IR_API_KEY=CHANGE_ME_SMS_IR_API_KEY
SMS_IR_TEMPLATE_ID=123456
# Voice dictation. Staging is in Iran, so OpenRouter is unreachable from this PC.
# Copy these four lines into C:\dyolink\secrets\backend.staging.env. Leave the key
# empty and the microphone does not render. Put the GapGPT key only in that
# secrets file — do not commit it.
OPENROUTER_API_KEY=
OPENROUTER_BASE_URL=https://api.gapgpt.app/v1
VOICE_ASR_MODEL=gapgpt/whisper-1
VOICE_LLM_MODEL=gemini-3.7-flash
# Account email codes (register, staff invite, organization invite, forgot-password).
# Required. SMTP_USER is the From address. The API refuses to send when these are missing.
SMTP_HOST=smtp.gmail.com

View File

@@ -28,6 +28,24 @@ server {
proxy_connect_timeout 300;
}
# Socket.IO (Nest namespace /realtime). Without this, /socket.io/ hits Next.js
# and the browser reports "websocket is closed before the connection is established".
location /socket.io/ {
set $backend_upstream http://backend:3000;
proxy_pass $backend_upstream;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
proxy_connect_timeout 300;
}
location /api {
set $backend_upstream http://backend:3000;
proxy_pass $backend_upstream;

View File

@@ -32,6 +32,23 @@ server {
proxy_connect_timeout 300;
}
# Socket.IO (Nest namespace /realtime). Without this, /socket.io/ hits Next.js
# and the browser reports "websocket is closed before the connection is established".
location /socket.io/ {
proxy_pass http://dyolink_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
proxy_connect_timeout 300;
}
location /api {
proxy_pass http://dyolink_backend;
proxy_http_version 1.1;

View File

@@ -72,6 +72,23 @@ server {
proxy_connect_timeout 300;
}
# Socket.IO (Nest namespace /realtime). Without this, /socket.io/ hits Next.js
# and the browser reports "websocket is closed before the connection is established".
location /socket.io/ {
proxy_pass http://dyolink_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
proxy_connect_timeout 300;
}
# Backend API
location /api {
proxy_pass http://dyolink_backend;

View File

@@ -66,6 +66,24 @@ server {
proxy_connect_timeout 300;
}
# Socket.IO (Nest namespace /realtime). Without this, /socket.io/ hits Next.js
# and the browser reports "websocket is closed before the connection is established".
location /socket.io/ {
set $backend_upstream http://backend:3000;
proxy_pass $backend_upstream;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
proxy_connect_timeout 300;
}
location /api {
set $backend_upstream http://backend:3000;
proxy_pass $backend_upstream;