Compare commits

...

5 Commits

45 changed files with 3684 additions and 675 deletions

View File

@@ -35,6 +35,7 @@ throw new AppException(ErrorCode.PERMISSION_DENIED, HttpStatus.FORBIDDEN);
- Schema: `backend/prisma/schema.prisma`
- Always add a migration for schema changes (`npm run prisma:migrate` in backend).
- Seed permissions stay in sync with `ALL_TAB_PERMISSIONS` in `common/permissions.ts`.
- Signup connects the `trial` plan and `CLINIC` / `LAB` organization types by name. `ensureTrialPlan` and `ensureOrganizationType` create a missing row and do not change an existing trial plan's price. Migration `20261021193000_ensure_reference_plans` inserts those rows only when they are absent.
- **Schema change ⇒ AdminJS:** update `backend/src/admin/resources.ts` in the same change (add/rename/remove resources, hide new secrets). Trigger-maintained fields such as `LabCase.listedAt` must not be `GENERATED ALWAYS`. See `.cursor/rules/adminjs.mdc`.
## API responses

View File

@@ -1,5 +1,5 @@
---
description: Billing hub — sheets, commissions, partner/patient ledger
description: Billing hub — sheets, commissions, partner/patient/staff ledger
globs: backend/src/modules/billing/**,frontend/src/components/ui/billing/**,frontend/src/components/billing/**,frontend/src/lib/api/billing.ts,frontend/src/types/billing.ts
alwaysApply: false
---
@@ -7,11 +7,10 @@ alwaysApply: false
# Billing
- Permissions: `TAB_BILLING_READ` / `TAB_BILLING_EDIT`. Hub: `/billing` with `?view=transactions|schedules|commissions` (+ optional `from`/`to`).
- **Sheet kinds:** clinic `CLINIC_PRICE` / `CLINIC_COMMISSION`; lab `LAB_PRICE` / `LAB_COMMISSION`. Commission lines are **fixed amounts** (same money input as fees).
- **Clinic stamp:** approving a treatment price stamps `CommissionEarning` from `CLINIC_COMMISSION` unit amounts as of the visit day.
- **Partner ledger is shared:** list by org on either side. The sender’s row counts immediately. The other org Accepts or Declines (`receiptConfirmedAt` / `receiptRejectedAt`); Decline hides it from that org only. A typed name is local (`externalPartyName`) and is not confirmed.
- **Lab fee sheets** include an outsourcing tab (`LAB_WORKFLOW_STEP`, plus billing-only `design_implant` / `design_frame` / `design_full`). Quotes are previews and are not stored.
- **Clinic transactions:** RECEIPT → patient or a typed name; PAYMENT → linked lab or a typed name. **Lab:** RECEIPT/PAYMENT → linked clinic or a typed name (no patient ledger).
- Money UI: `AppMoneyInput`; party field: `BillingPartyCombobox`; list chrome: `BillingListToolbar` + shared `Table` (`table-fixed`). Labels: **Price**, not Amount.
- **Org currency:** `Organization.billingCurrency` (`TOMAN` | `DOLLAR` | `EURO`). Locked after first cash write; orgs with legacy cash and null column resolve as **TOMAN**. Labels use org currency via `moneyFieldLabel` + `common.currencyName.*` (not UI locale).
- **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 −).
- 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 + cash ledger — `.cursor/rules/billing.mdc`, skill `.cursor/skills/billing/SKILL.md`.
- **Billing** (clinic + lab): fee/commission sheets + cash ledger (org currency lock, staff PAYMENT, party net) — `.cursor/rules/billing.mdc`, skill `.cursor/skills/billing/SKILL.md`.
## Agent behavior

View File

@@ -14,7 +14,7 @@ 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. The next send reopens that file when it still exists and skips Browse. A missing file shows Browse again. 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. A tooth is written only when that work type and material already exist; parameters, dependents, and color come from the fullest saved tooth of the same pair. Unmatched lines go to `t_Notes` as `tooth code`. 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}”.

View File

@@ -6,46 +6,57 @@ description: Billing hub — fee/commission sheets, patient and partner transact
# Billing
**UI:** [`frontend/src/components/ui/billing/`](frontend/src/components/ui/billing/) (`BillingPage`, `BillingPaymentsPanel`, `BillingSheetsPanel`, `BillingSheetEditor`, `BillingListToolbar`)
**Helpers:** [`frontend/src/components/billing/`](frontend/src/components/billing/) (`billingSheetKind`, `sheetLineGroups`, `sheetAmount`, `calculateDetailAmount`)
**Helpers:** [`frontend/src/components/billing/`](frontend/src/components/billing/) (`billingSheetKind`, `sheetLineGroups`, `sheetAmount`, `calculateDetailAmount`, `moneyFieldLabel`)
**API:** [`frontend/src/lib/api/billing.ts`](frontend/src/lib/api/billing.ts) · [`backend/src/modules/billing/`](backend/src/modules/billing/)
**Types:** [`frontend/src/types/billing.ts`](frontend/src/types/billing.ts)
## Org currency
- Column: `Organization.billingCurrency` (`TOMAN` | `DOLLAR` | `EURO`), nullable.
- Resolve (`GET /billing/settings`): set → use it; else if any patient/partner/staff cash → effective `TOMAN` (`legacy_toman`); else unlocked.
- First create with unlocked currency requires `currency` in the DTO and locks the org column. Legacy orgs silently set `TOMAN` on write.
- All money field labels (transactions, fee/commission sheets, treatment approve, case billed) use `moneyFieldLabel` + `common.currencyName.*`.
## Hub layout (clinic + lab)
Same three tabs; sheet kind differs by org type (`sheetKindForView`):
| Tab (`?view=`) | Clinic | Lab |
|----------------|--------|-----|
| `transactions` (default) | Patient receipts + partner payments | Partner payments only |
| `schedules` | `CLINIC_PRICE` (treatment types → dentists) | `LAB_PRICE` (prosthesis → clinics, then outsourcing steps) |
| `commissions` | `CLINIC_COMMISSION` fixed amount | `LAB_COMMISSION` fixed amount |
| `transactions` (default) | Patient + partner + staff cash | Partner + staff cash |
| `schedules` | `CLINIC_PRICE` | `LAB_PRICE` (outsourcing tab first, then prosthesis categories) |
| `commissions` | `CLINIC_COMMISSION` | `LAB_COMMISSION` |
Keep chrome identical: `BillingListToolbar`, outline labels, `AppMoneyInput`, equal-column `Table`.
Keep chrome identical: `BillingListToolbar`, outline labels, `AppMoneyInput`, equal-column `Table`. Label cash/sheet money as **Amount**.
## Party search and create
- `GET /billing/party-search?q=&txnType=RECEIPT|PAYMENT` → grouped `{ patients?, staff?, clinics?, labs? }`.
- Clinic RECEIPT → patient **or** linked org (or typed name → patient external). Clinic/Lab PAYMENT → linked org **or** staff (`POST /billing/staff-payments`). Lab RECEIPT → linked org only.
- Staff payments are outbound only; no allocations; no partner ack.
## Partner payments
- List: `OR` from/to current org — **shared ledger**.
- Create: clinic may only record partner **PAYMENT**; lab may record **RECEIPT** or **PAYMENT**. `status` stays `CONFIRMED` for the sender.
- The other org sees a highlighted row and can Accept or Decline with billing edit. The highlighted row stays on their ledger until then. Accept sets `receiptConfirmedAt`. Decline sets `receiptRejectedAt` and drops the row from their list; the sender keeps it.
- A typed name that matches no linked org (or, for a clinic receipt, no patient) is stored as `externalPartyName`. It has no allocations and no acknowledgement.
- Allocations attach to lab cases (partner) or treatments (clinic patient receipt) only when a real org or patient is selected. Allocation total ≤ payment amount; remainder allowed.
- Shared ledger; Accept/Decline for the counterparty. Typed external name is local.
- Allocations to lab cases only for clinic↔lab pairs.
## Ledger list + net
- Prefer `GET /billing/transactions` (merged rows). Optional `partyKind` + `partyId` filters server-side and returns signed `net` (RECEIPT +, PAYMENT −) for the footer.
## Fee / commission editor
- Start date required (`effectiveOn`). Empty Apply-to = everyone (users or clinics depending on kind).
- Price and commission lines both store **money** `amount` (`percent` null). Lab/clinic commission stamp uses unit amount × qty.
- Category tabs + catalog colors for prosthesis groups. Lab price sheets add an **Outsourcing prices** tab after the categories: model design, model creation, Implant/Frame/Full Design, then each emitted outsourceable step.
- The three design prices are billing-only codes. They are not workflow steps and do not generate tasks.
- Treatment dispatch and the outsource dialog show a live `{ amount }` preview. Do not store that quote on the treatment or the case.
- Start date required. Empty Apply-to = everyone. Lines store money `amount`.
- Treatment dispatch / outsource quote previews are not stored.
## Clinic visibility
- Billing is visible for clinics and labs. `HIDDEN_TAB_FEATURE_FLAGS.billingOrgTypes` in `hidden-tabs.ts` is empty.
- Billing is visible for clinics and labs. `HIDDEN_TAB_FEATURE_FLAGS.billingOrgTypes` is empty.
## Treatment price approve
## Treatment amount approve
- Clinic Treatment workspace: approve billed amount; backend stamps commission earnings from the active `CLINIC_COMMISSION` sheet. Set `planBilledManual` from `billedAmountManual` only (no `|| true`).
- Approve billed amount; stamps `CommissionEarning` from `CLINIC_COMMISSION`. Set `planBilledManual` from `billedAmountManual` only.
## Deep links
- `/billing?view=schedules|commissions` and optional `from`/`to` (YYYY-MM-DD). Tab clicks must `router.replace` so the query stays in sync.
- `/billing?view=schedules|commissions` and optional `from`/`to`. Tab clicks `router.replace` so the query stays in sync.

View File

@@ -60,9 +60,9 @@ List item shape: `prosthesisGroups: { prosthesisTypeCode, teeth[], ponticTeeth?
Writes the open case into a DentalDB SQLite file on this computer. Nothing is uploaded to the Dyolink server. Close Exocad before writing, then open it again.
- 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). The next send reopens the saved file when it still exists and skips Browse. A missing file shows Browse again.
- Mapper: `frontend/src/components/local-db/exocadTransfer.ts`. Lab id `0`. Match or create the client from `referringClinicName`, otherwise the case clinic name. Never use practice id `2147483647`. Match or create the patient by first and last name. `Treatment.importedOrderId` is the Dyolink case id, so a second send updates that treatment and replaces its `ToothWork` rows.
- FDI restorations become `ToothWork` (`WorkTypeSN` / `MaterialSN`). A pontic uses the connected crown’s material. Implant, post and core, denture, and `UA`/`LA` are skipped and listed after the send.
- `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.
- Mapper: `frontend/src/components/local-db/exocadTransfer.ts`. Lab id `0`. Match or create the client from `referringClinicName`, otherwise the case clinic name. Never use practice id `2147483647`. Match or create the patient by first and last name. `Treatment.importedOrderId` is the Dyolink case id, so a second send updates that treatment and replaces its `ToothWork` rows. 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.
- 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 parameters, dependent rows, and `ValuedMaterialParameters` color from the fullest saved tooth of that same pair. 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 = `AnatomicCrown`/`ZI`; PFM = `Coping`/`NP`; Full Metal = `AnatomicCrown`/`NP`; PMMA = `AnatomicCrown`/`PMMA`; Glass Ceramic Crown = `AnatomicCrown`/`GCER`; pontic = `AnatomicPontic` 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. Temporary resin, veneer/inlay/onlay/overlay full-contour or layered with no material in the name, abutments, cast post, and fiber post get no tooth row. The case header is still created. Unmatched lines are appended to `t_Notes` as `tooth code`, and the skipped toast still lists them.
- 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

@@ -68,12 +68,12 @@ frontend/src/
**Staff (quick ref):** Owner / `TAB_STAFF_EDIT` can **remove** a password (`POST /staff/members/:id/clear-password`) and copy a setup link — never set one for someone else. Login page unchanged (`passwordHash: null` cannot sign in). `/accept-invite` `password_setup` is password-only. See `.cursor/rules/staff.mdc`.
**Billing (quick ref):** Same three-tab hub for CLINIC + LAB (`/billing?view=`). Clinic: `CLINIC_PRICE` / `CLINIC_COMMISSION` + patient receipts + partner payments. Lab: `LAB_PRICE` (prosthesis fees plus an outsourcing tab) / `LAB_COMMISSION` + partner ledger only. Commissions are **fixed amounts** (not percents). Dispatch and outsource prices are previews and are not stored. Partner list is a **shared** ledger: the sender’s row counts immediately, and the other org Accepts or Declines it. A typed party name stays local. Money inputs: `AppMoneyInput`. Billing is visible for both org types. See `.cursor/rules/billing.mdc`, `.cursor/skills/billing/SKILL.md`.
**Billing (quick ref):** Same three-tab hub for CLINIC + LAB (`/billing?view=`). Clinic: `CLINIC_PRICE` / `CLINIC_COMMISSION` + patient/partner/staff cash. Lab: `LAB_PRICE` (outsourcing tab first, then prosthesis) / `LAB_COMMISSION` + partner/staff cash. Org currency (`TOMAN`|`DOLLAR`|`EURO`) locks after first cash write; legacy cash ⇒ تومان. Labels use org currency (`moneyFieldLabel`), not UI locale. Commissions are **fixed amounts**. Partner ledger is **shared** (Accept/Decline); staff PAYMENT and typed names stay local. List supports party filter + signed net. 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 order number. The page stays LTR; on Persian sheets the org name is shrink-wrapped (RTL only when the name itself is Arabic script) and labels use `0px` letter-spacing. Lab-origin Start has no clinic send and notifies the linked org once (`PARTNER_CASE_CREATED`, share link); generated-case comments have no visibility toggle. A lab-to-lab case uses the eye button so the sending lab can see that comment. Comments use Cases **or** Tasks permission. Unstarted generated drafts can be deleted (`DELETE /cases/:id`). **Edit** (`POST /cases/:id/stop`) returns a started generated case to that drafts rail: completed steps and the previous prosthesis plan stay as history, in-progress steps are dropped, and the case can be edited and started again. Open outsources with no finished step are cancelled; a finished outsourced step blocks Edit. **Outsource** gives selected in-progress prosthesis steps, plus model design and model create, to one linked lab as a child case. Child `sourceKey` stays the child case id unless two selected steps share tooth, type, and workflow (`childId:parentSourceKey`). The child shows only that sending lab (no original clinic or dentist). Those steps leave Tasks until that lab completes them, and only the sending lab sees that direct handoff. The sender chart stays the full plan; the receiver chart is the selected jobs plus pontics on that bridge, or that line’s teeth for a model step. Scan, packing, and shipping stay on the owning lab. **Live:** inbox Socket.IO → `notifyTabBadgesChanged()` soft-refreshes list + selected detail (no remount). A file upload emits `case-section.changed` on that socket (no inbox card) so Files and Messages unread counts refresh the same way. **Add case** is a full-width split button with the lab mic. One file can be removed from its card menu. An upload keeps running after leaving Files or Cases; the open case adds the file from the upload response without another fetch. Attachments have no size cap; production must recreate nginx from the SSL template or `/api` stays at 50MB. See `.cursor/skills/lab-cases/SKILL.md` and `.cursor/skills/lab-case-share-link/SKILL.md`.
**Lab Cases tab:** Filter by **prosthesis type** (not treatment type); auto-select newest case on open; list **10 per page**; left rail list fills column height (`flex-1 overflow-y-auto`). Unstarted lab-origin **drafts** sit in a collapsed expandable rail section (opens on click or **Add case**); received + started cases list below, newest first by send or start time (`listedAt`, same key as Tasks). List cards use `LabCaseProsthesisGroupsList` (colored type + teeth, shared with Treatment rail) plus **From clinic** / **Generated** / **From lab** origin badges. Job titles use `ProsthesisJobLineLabel` the same as Treatment/Tasks (`13 · Pontic - 14 · PFZ Crown`; no category; indirect keeps Inlay · Layered ceramic). Deep link: `?caseId=`, `?clinicOrganizationId=`. **Share link:** QR + URL on sent cases **and** started lab-origin cases (attachment left, QR right); opens `/lab-case/[token]` focus page. **Case Sheet PDF:** same portrait/landscape layout, one A4 page (`jspdf`/`html2canvas`, scaled to fit); realistic FDI chart; hex-only print layout; share QR stays in the flex header; optional `externalCode` replaces the printed order number and the `case-sheet-{orderNumber}.pdf` filename. The page stays LTR; on Persian sheets the org name is shrink-wrapped (RTL only when the name itself is Arabic script) and labels use `0px` letter-spacing. Lab-origin Start has no clinic send and notifies the linked org once (`PARTNER_CASE_CREATED`, share link); generated-case comments have no visibility toggle. A lab-to-lab case uses the eye button so the sending lab can see that comment. Comments use Cases **or** Tasks permission. Unstarted generated drafts can be deleted (`DELETE /cases/:id`). **Edit** (`POST /cases/:id/stop`) returns a started generated case to that drafts rail: completed steps and the previous prosthesis plan stay as history, in-progress steps are dropped, and the case can be edited and started again. Open outsources with no finished step are cancelled; a finished outsourced step blocks Edit. **Outsource** gives selected in-progress prosthesis steps to one linked lab as a child case. Child `sourceKey` stays the child case id unless two selected steps share tooth, type, and workflow (`childId:parentSourceKey`). The child shows only that sending lab (no original clinic or dentist). Those steps leave Tasks until that lab completes them, and only the sending lab sees that direct handoff. The sender chart stays the full plan; the receiver chart is the selected jobs plus pontics on that bridge. **Live:** inbox Socket.IO → `notifyTabBadgesChanged()` soft-refreshes list + selected detail (no remount). A file upload emits `case-section.changed` on that socket (no inbox card) so Files and Messages unread counts refresh the same way. **Add case** is a full-width split button with the lab mic. One file can be removed from its card menu. An upload keeps running after leaving Files or Cases; the open case adds the file from the upload response without another fetch. Attachments have no size cap; production must recreate nginx from the SSL template or `/api` stays at 50MB. **Send to Exocad** (Chrome and Edge only, any screen size; no helper program or download) writes the open case into a DentalDB SQLite file on that computer. There is no Local database tab. Send to Exocad keeps `LocalDbSessionProvider` and reopens the last database file while that file still exists. See `.cursor/skills/lab-cases/SKILL.md` and `.cursor/skills/lab-case-share-link/SKILL.md`.
**Lab Cases tab:** Filter by **prosthesis type** (not treatment type); auto-select newest case on open; list **10 per page**; left rail list fills column height (`flex-1 overflow-y-auto`). Unstarted lab-origin **drafts** sit in a collapsed expandable rail section (opens on click or **Add case**); received + started cases list below, newest first by send or start time (`listedAt`, same key as Tasks). List cards use `LabCaseProsthesisGroupsList` (colored type + teeth, shared with Treatment rail) plus **From clinic** / **Generated** / **From lab** origin badges. Job titles use `ProsthesisJobLineLabel` the same as Treatment/Tasks (`13 · Pontic - 14 · PFZ Crown`; no category; indirect keeps Inlay · Layered ceramic). Deep link: `?caseId=`, `?clinicOrganizationId=`. **Share link:** QR + URL on sent cases **and** started lab-origin cases (attachment left, QR right); opens `/lab-case/[token]` focus page. **Case Sheet PDF:** same portrait/landscape layout, one A4 page (`jspdf`/`html2canvas`, scaled to fit); realistic FDI chart; hex-only print layout; share QR stays in the flex header; optional `externalCode` replaces the printed order number and the `case-sheet-{orderNumber}.pdf` filename. The page stays LTR; on Persian sheets the org name is shrink-wrapped (RTL only when the name itself is Arabic script) and labels use `0px` letter-spacing. Lab-origin Start has no clinic send and notifies the linked org once (`PARTNER_CASE_CREATED`, share link); generated-case comments have no visibility toggle. A lab-to-lab case uses the eye button so the sending lab can see that comment. Comments use Cases **or** Tasks permission. Unstarted generated drafts can be deleted (`DELETE /cases/:id`). **Edit** (`POST /cases/:id/stop`) returns a started generated case to that drafts rail: completed steps and the previous prosthesis plan stay as history, in-progress steps are dropped, and the case can be edited and started again. Open outsources with no finished step are cancelled; a finished outsourced step blocks Edit. **Outsource** gives selected in-progress prosthesis steps to one linked lab as a child case. Child `sourceKey` stays the child case id unless two selected steps share tooth, type, and workflow (`childId:parentSourceKey`). The child shows only that sending lab (no original clinic or dentist). Those steps leave Tasks until that lab completes them, and only the sending lab sees that direct handoff. The sender chart stays the full plan; the receiver chart is the selected jobs plus pontics on that bridge. **Live:** inbox Socket.IO → `notifyTabBadgesChanged()` soft-refreshes list + selected detail (no remount). A file upload emits `case-section.changed` on that socket (no inbox card) so Files and Messages unread counts refresh the same way. **Add case** is a full-width split button with the lab mic. One file can be removed from its card menu. An upload keeps running after leaving Files or Cases; the open case adds the file from the upload response without another fetch. Attachments have no size cap; production must recreate nginx from the SSL template or `/api` stays at 50MB. **Send to Exocad** (Chrome and Edge only, any screen size; no helper program or download) writes the open case into a DentalDB SQLite file on that computer. The browser remembers the file only after the DentalDB check and reopens it while it still exists; an invalid file is not remembered, so Browse stays available. A tooth is written only when that work type and material already exist in the file. There is no Local database tab. See `.cursor/skills/lab-cases/SKILL.md` and `.cursor/skills/lab-case-share-link/SKILL.md`.
**Lab 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.

View File

@@ -0,0 +1,10 @@
-- Editors no longer offer these codes. Stored tasks keep their own step labels.
DELETE FROM "billing_sheet_lines"
WHERE "catalogKind" = 'LAB_WORKFLOW_STEP'
AND "catalogCode" IN (
'stain',
'glaze',
'build_up',
'design',
'design_customized_abutment'
);

View File

@@ -0,0 +1,30 @@
-- Reference rows that signup connects by name. Seed also upserts them.
-- A migrated database that never ran seed must still be able to register.
INSERT INTO "organization_types" ("id", "name")
SELECT gen_random_uuid()::text, 'CLINIC'
WHERE NOT EXISTS (SELECT 1 FROM "organization_types" WHERE "name" = 'CLINIC');
INSERT INTO "organization_types" ("id", "name")
SELECT gen_random_uuid()::text, 'LAB'
WHERE NOT EXISTS (SELECT 1 FROM "organization_types" WHERE "name" = 'LAB');
INSERT INTO "plans" ("id", "name", "maxUsers", "price", "features")
SELECT gen_random_uuid()::text, 'trial', 5, 0, '{}'::jsonb
WHERE NOT EXISTS (SELECT 1 FROM "plans" WHERE "name" = 'trial');
INSERT INTO "plans" ("id", "name", "maxUsers", "price", "features")
SELECT gen_random_uuid()::text, 'Small', 5, 150, '{}'::jsonb
WHERE NOT EXISTS (SELECT 1 FROM "plans" WHERE "name" = 'Small');
INSERT INTO "plans" ("id", "name", "maxUsers", "price", "features")
SELECT gen_random_uuid()::text, 'Medium', 10, 250, '{}'::jsonb
WHERE NOT EXISTS (SELECT 1 FROM "plans" WHERE "name" = 'Medium');
INSERT INTO "plans" ("id", "name", "maxUsers", "price", "features")
SELECT gen_random_uuid()::text, 'Large', 15, 400, '{}'::jsonb
WHERE NOT EXISTS (SELECT 1 FROM "plans" WHERE "name" = 'Large');
INSERT INTO "plans" ("id", "name", "maxUsers", "price", "features")
SELECT gen_random_uuid()::text, 'Enterprise', 999999, 1000, '{}'::jsonb
WHERE NOT EXISTS (SELECT 1 FROM "plans" WHERE "name" = 'Enterprise');

View File

@@ -0,0 +1,36 @@
-- CreateEnum
CREATE TYPE "BillingCurrency" AS ENUM ('TOMAN', 'DOLLAR', 'EURO');
-- AlterTable
ALTER TABLE "organizations" ADD COLUMN "billingCurrency" "BillingCurrency";
-- CreateTable
CREATE TABLE "staff_payments" (
"id" TEXT NOT NULL,
"organizationId" TEXT NOT NULL,
"userId" TEXT,
"externalPartyName" TEXT,
"amount" DECIMAL(14,2) NOT NULL,
"paidAt" TIMESTAMP(3) NOT NULL,
"note" TEXT,
"createdByUserId" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "staff_payments_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "staff_payments_organizationId_paidAt_idx" ON "staff_payments"("organizationId", "paidAt");
-- CreateIndex
CREATE INDEX "staff_payments_organizationId_userId_idx" ON "staff_payments"("organizationId", "userId");
-- AddForeignKey
ALTER TABLE "staff_payments" ADD CONSTRAINT "staff_payments_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "staff_payments" ADD CONSTRAINT "staff_payments_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "staff_payments" ADD CONSTRAINT "staff_payments_createdByUserId_fkey" FOREIGN KEY ("createdByUserId") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

View File

@@ -37,6 +37,8 @@ model User {
billingSheetTargets BillingSheetTarget[]
createdPatientPayments PatientPayment[] @relation("PatientPaymentCreatedBy")
createdPartnerPayments PartnerPayment[] @relation("PartnerPaymentCreatedBy")
createdStaffPayments StaffPayment[] @relation("StaffPaymentCreatedBy")
staffPayments StaffPayment[] @relation("StaffPaymentUser")
commissionEarnings CommissionEarning[]
createdAt DateTime @default(now())
@@ -115,9 +117,13 @@ model Organization {
partnerLabCases LabCase[] @relation("LabCasePartnerClinic")
billingSheets BillingSheet[]
billingSheetClinicTargets BillingSheetTarget[] @relation("BillingSheetTargetClinic")
/// Locked after the first cash transaction (or inferred as TOMAN when legacy cash exists).
billingCurrency BillingCurrency?
patientPayments PatientPayment[]
partnerPaymentsFrom PartnerPayment[] @relation("PartnerPaymentFrom")
partnerPaymentsTo PartnerPayment[] @relation("PartnerPaymentTo")
staffPayments StaffPayment[]
commissionEarnings CommissionEarning[]
createdAt DateTime @default(now())
@@ -908,6 +914,12 @@ enum PartnerPaymentRecordedBy {
LAB
}
enum BillingCurrency {
TOMAN
DOLLAR
EURO
}
model BillingSheet {
id String @id @default(uuid())
organizationId String
@@ -1039,6 +1051,30 @@ model PartnerPaymentAllocation {
@@map("partner_payment_allocations")
}
/// Cash paid by this organization to a staff member (or a typed external name).
/// Always an outbound payment; not linked to CommissionEarning.
model StaffPayment {
id String @id @default(uuid())
organizationId String
userId String?
externalPartyName String?
amount Decimal @db.Decimal(14, 2)
paidAt DateTime
note String?
createdByUserId String
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
user User? @relation("StaffPaymentUser", fields: [userId], references: [id], onDelete: Restrict)
createdBy User @relation("StaffPaymentCreatedBy", fields: [createdByUserId], references: [id], onDelete: Restrict)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([organizationId, paidAt])
@@index([organizationId, userId])
@@map("staff_payments")
}
/// Lab earning: one row per completed task step. Clinic earning: one row per
/// approved treatment and treatment type. `catalogCode` is the workflow step or
/// the treatment type accordingly.

View File

@@ -241,6 +241,9 @@ export function buildAdminResources(prisma: PrismaService): AdminResource[] {
resource(prisma, 'PartnerPaymentAllocation', {
navigation: { name: 'Billing', icon: 'CreditCard' },
}),
resource(prisma, 'StaffPayment', {
navigation: { name: 'Billing', icon: 'CreditCard' },
}),
resource(prisma, 'CommissionEarning', {
navigation: { name: 'Billing', icon: 'CreditCard' },
}),

View File

@@ -226,6 +226,10 @@ export const ErrorCode = {
BILLING_TRANSACTION_TYPE_INVALID: 'BILLING_TRANSACTION_TYPE_INVALID',
BILLING_PAYMENT_NOT_FOUND: 'BILLING_PAYMENT_NOT_FOUND',
BILLING_PAYMENT_ACK_INVALID: 'BILLING_PAYMENT_ACK_INVALID',
BILLING_CURRENCY_REQUIRED: 'BILLING_CURRENCY_REQUIRED',
BILLING_CURRENCY_INVALID: 'BILLING_CURRENCY_INVALID',
BILLING_STAFF_INVALID: 'BILLING_STAFF_INVALID',
BILLING_PARTY_INVALID: 'BILLING_PARTY_INVALID',
// Generic HTTP
NOT_FOUND: 'NOT_FOUND',

View File

@@ -0,0 +1,29 @@
import { Prisma } from '@prisma/client';
type CatalogDb = Prisma.TransactionClient;
const TRIAL_PLAN = {
name: 'trial',
maxUsers: 5,
price: 0,
features: {},
} as const;
/** Signup connects this row by name. Create it when a database was migrated without seed. */
export async function ensureTrialPlan(db: CatalogDb): Promise<void> {
await db.plan.upsert({
where: { name: TRIAL_PLAN.name },
update: {},
create: { ...TRIAL_PLAN },
});
}
/** CLINIC and LAB are required before an organization can connect its type. */
export async function ensureOrganizationType(db: CatalogDb, name: string): Promise<void> {
if (name !== 'CLINIC' && name !== 'LAB') return;
await db.organizationType.upsert({
where: { name },
update: {},
create: { name },
});
}

View File

@@ -28,6 +28,7 @@ import { JwtPayload } from './interfaces/jwt-payload.interface';
import { ownerPermissionsForOrgType, type OrganizationTypeName } from '../../common/organization-type';
import { getEffectivePermissionNames, getOrgTypeFromMembership, hasActivePlan, participatesInTasks, participatesInTreatments, participationPermissionsForOrgType } from '../../common/membership-permissions';
import { assertClinicOrganization, assertLabOrganization } from '../../common/organization-type';
import { ensureOrganizationType, ensureTrialPlan } from '../../common/reference-catalog';
import { StaffWorkingHoursService } from '../staff/staff-working-hours.service';
import { UpsertWorkingHoursDto } from '../staff/dto/upsert-working-hours.dto';
import { UpdateParticipationDto } from './dto/update-participation.dto';
@@ -340,6 +341,8 @@ export class AuthService {
}
await this.assertRegistrationAvailable(tx, email, payload.mobile);
await ensureOrganizationType(tx, payload.organizationType);
await ensureTrialPlan(tx);
const user = await tx.user.create({
data: {
@@ -463,6 +466,7 @@ export class AuthService {
try {
const organization = await this.prisma.$transaction(async (tx) => {
await assertOwnerOrganizationNameAvailable(tx, userId, organizationName);
await ensureOrganizationType(tx, dto.organizationType);
const createdOrganization = await tx.organization.create({
data: {

View File

@@ -0,0 +1,95 @@
import { BillingCurrency, Prisma } from '@prisma/client';
export type BillingCurrencyCode = 'TOMAN' | 'DOLLAR' | 'EURO';
export type BillingCurrencySource = 'set' | 'legacy_toman' | 'unset';
export type BillingCurrencySettings = {
currency: BillingCurrencyCode | null;
currencyLocked: boolean;
currencySource: BillingCurrencySource;
};
type PrismaLike = {
organization: {
findUnique: (args: {
where: { id: string };
select: { billingCurrency: true };
}) => Promise<{ billingCurrency: BillingCurrency | null } | null>;
};
patientPayment: {
findFirst: (args: { where: { organizationId: string }; select: { id: true } }) => Promise<{ id: string } | null>;
};
partnerPayment: {
findFirst: (args: {
where: {
OR: Array<{ fromOrganizationId: string } | { toOrganizationId: string }>;
};
select: { id: true };
}) => Promise<{ id: string } | null>;
};
staffPayment: {
findFirst: (args: { where: { organizationId: string }; select: { id: true } }) => Promise<{ id: string } | null>;
};
};
export function isBillingCurrencyCode(value: unknown): value is BillingCurrencyCode {
return value === 'TOMAN' || value === 'DOLLAR' || value === 'EURO';
}
export async function orgHasCashHistory(
prisma: PrismaLike,
organizationId: string,
): Promise<boolean> {
const [patient, partner, staff] = await Promise.all([
prisma.patientPayment.findFirst({ where: { organizationId }, select: { id: true } }),
prisma.partnerPayment.findFirst({
where: {
OR: [{ fromOrganizationId: organizationId }, { toOrganizationId: organizationId }],
},
select: { id: true },
}),
prisma.staffPayment.findFirst({ where: { organizationId }, select: { id: true } }),
]);
return Boolean(patient || partner || staff);
}
export async function resolveBillingCurrency(
prisma: PrismaLike,
organizationId: string,
): Promise<BillingCurrencySettings> {
const org = await prisma.organization.findUnique({
where: { id: organizationId },
select: { billingCurrency: true },
});
if (org?.billingCurrency) {
return {
currency: org.billingCurrency,
currencyLocked: true,
currencySource: 'set',
};
}
if (await orgHasCashHistory(prisma, organizationId)) {
return {
currency: 'TOMAN',
currencyLocked: true,
currencySource: 'legacy_toman',
};
}
return {
currency: null,
currencyLocked: false,
currencySource: 'unset',
};
}
/** Persist billingCurrency when creating the first (or legacy) cash row. */
export async function lockBillingCurrencyOnWrite(
tx: Prisma.TransactionClient,
organizationId: string,
currencyToSet: BillingCurrencyCode,
): Promise<void> {
await tx.organization.updateMany({
where: { id: organizationId, billingCurrency: null },
data: { billingCurrency: currencyToSet },
});
}

View File

@@ -24,6 +24,7 @@ import {
AllocationSearchQueryDto,
CreatePaymentDto,
ListPaymentsQueryDto,
PartySearchQueryDto,
} from './dto/billing-payment.dto';
import { UpsertBillingSheetDto } from './dto/upsert-billing-sheet.dto';
import { LabPriceQuoteDto, OutsourceQuoteDto } from './dto/billing-quote.dto';
@@ -118,6 +119,53 @@ export class BillingController {
return this.billingService.listPartners(req.user.id, organizationId);
}
@Get('settings')
@ApiOperation({ summary: 'Org billing currency settings' })
getSettings(@Req() req: { user: { id: string; organizationId?: string } }) {
const organizationId = this.billingService.getOrganizationIdFromUser(req.user);
return this.billingService.getSettings(req.user.id, organizationId);
}
@Get('party-search')
@ApiOperation({ summary: 'Grouped party search for cash transactions' })
searchParties(
@Query() query: PartySearchQueryDto,
@Req() req: { user: { id: string; organizationId?: string } },
) {
const organizationId = this.billingService.getOrganizationIdFromUser(req.user);
return this.billingService.searchParties(req.user.id, organizationId, query);
}
@Get('transactions')
@ApiOperation({ summary: 'Merged cash ledger (patient, partner, staff) with optional net' })
listTransactions(
@Query() query: ListPaymentsQueryDto,
@Req() req: { user: { id: string; organizationId?: string } },
) {
const organizationId = this.billingService.getOrganizationIdFromUser(req.user);
return this.billingService.listTransactions(req.user.id, organizationId, query);
}
@Get('staff-payments')
@ApiOperation({ summary: 'List staff payments' })
listStaffPayments(
@Query() query: ListPaymentsQueryDto,
@Req() req: { user: { id: string; organizationId?: string } },
) {
const organizationId = this.billingService.getOrganizationIdFromUser(req.user);
return this.billingService.listStaffPayments(req.user.id, organizationId, query);
}
@Post('staff-payments')
@ApiOperation({ summary: 'Record a staff payment (TAB_BILLING_EDIT)' })
createStaffPayment(
@Body() dto: CreatePaymentDto,
@Req() req: { user: { id: string; organizationId?: string } },
) {
const organizationId = this.billingService.getOrganizationIdFromUser(req.user);
return this.billingService.createStaffPayment(req.user.id, organizationId, dto);
}
@Get('resolved-lines')
@ApiOperation({ summary: 'Resolved fee-schedule lines for a date (billing or treatment read)' })
getResolvedLines(

View File

@@ -28,7 +28,9 @@ import {
} from '../catalog/catalog-label.service';
import { WORKFLOW_STEP_LABELS } from '../../../prisma/catalog-seed-data';
import {
commissionWorkflowStepCodes,
isBillingDesignPriceCode,
outsourcingPriceCodeForStep,
outsourcingPriceStepCodes,
} from './outsourcing-price-steps';
import { UpsertBillingSheetDto } from './dto/upsert-billing-sheet.dto';
@@ -53,6 +55,12 @@ import {
import type { LabPriceQuoteDto, OutsourceQuoteDto } from './dto/billing-quote.dto';
import { LAB_CASE_LIST_ORDER_BY } from '../../common/lab-case-listed-at';
import { CreatePaymentDto } from './dto/billing-payment.dto';
import {
isBillingCurrencyCode,
lockBillingCurrencyOnWrite,
resolveBillingCurrency,
type BillingCurrencyCode,
} from './billing-currency';
import {
resolveBillingSheet,
toBillingDateOnly,
@@ -60,6 +68,14 @@ import {
type BillingSheetRecord,
} from './resolve-billing-sheet';
type PaymentListQuery = {
q?: string;
from?: string;
to?: string;
partyKind?: 'patient' | 'staff' | 'org';
partyId?: string;
};
const sheetInclude = {
targets: {
include: {
@@ -184,20 +200,17 @@ export class BillingService {
}
if (kind === 'LAB_COMMISSION') {
const steps = await this.prisma.labWorkflowStep.findMany({
orderBy: { sortOrder: 'asc' },
select: { code: true, sortOrder: true },
});
const codes = commissionWorkflowStepCodes();
const labels = await this.catalogLabels.resolveLabels(
CatalogEntityKind.LAB_WORKFLOW_STEP,
steps.map((row) => row.code),
codes,
locale,
);
workflowSteps.push(
...steps.map((row) => ({
code: row.code,
sortOrder: row.sortOrder,
label: labels.get(row.code) ?? row.code,
...codes.map((code, index) => ({
code,
sortOrder: index + 1,
label: workflowPriceLabel(code, labels, locale),
})),
);
}
@@ -325,34 +338,305 @@ export class BillingService {
return { success: true as const };
}
async getSettings(actorUserId: string, organizationId: string) {
await this.assertCanRead(actorUserId, organizationId);
const settings = await resolveBillingCurrency(this.prisma, organizationId);
return { success: true as const, data: settings };
}
async listTransactions(actorUserId: string, organizationId: string, query: PaymentListQuery) {
await this.assertCanRead(actorUserId, organizationId);
const orgType = await getOrganizationTypeName(this.prisma, organizationId);
const paidAtFilter = paidAtWhere(query);
const party = normalizePartyFilter(query);
const q = query.q?.trim().toLowerCase();
const [patientRows, partnerRows, staffRows] = await Promise.all([
orgType === 'CLINIC' && (!party || party.kind === 'patient')
? this.prisma.patientPayment.findMany({
where: {
organizationId,
...paidAtFilter,
...(party?.kind === 'patient' ? { patientId: party.id } : {}),
},
include: patientPaymentInclude,
orderBy: [{ paidAt: 'desc' }, { createdAt: 'desc' }],
take: party ? 2000 : 200,
})
: Promise.resolve([]),
!party || party.kind === 'org'
? this.prisma.partnerPayment.findMany({
where: {
AND: [
{
OR: [
{ fromOrganizationId: organizationId },
{ toOrganizationId: organizationId },
],
},
...(party?.kind === 'org'
? [
{
OR: [
{ fromOrganizationId: party.id, toOrganizationId: organizationId },
{ toOrganizationId: party.id, fromOrganizationId: organizationId },
],
},
]
: []),
paidAtFilter,
],
},
include: partnerPaymentInclude,
orderBy: [{ paidAt: 'desc' }, { createdAt: 'desc' }],
take: party ? 2000 : 200,
})
: Promise.resolve([]),
!party || party.kind === 'staff'
? this.prisma.staffPayment.findMany({
where: {
organizationId,
...paidAtFilter,
...(party?.kind === 'staff' ? { userId: party.id } : {}),
},
include: staffPaymentInclude,
orderBy: [{ paidAt: 'desc' }, { createdAt: 'desc' }],
take: party ? 2000 : 200,
})
: Promise.resolve([]),
]);
const patients = patientRows.map(mapPatientPayment).filter((row) => {
if (party?.kind === 'patient') return true;
if (!q) return true;
const hay = [
row.note ?? '',
row.patientName,
...row.allocations.map((a) => a.patientName),
...row.allocations.map((a) => a.treatmentTitle),
]
.join(' ')
.toLowerCase();
return hay.includes(q);
});
const partners = partnerRows
.map((row) => mapPartnerPayment(row, organizationId))
.filter((row) => row.acknowledgement !== 'rejected' || row.recordedByViewer)
.filter((row) => {
if (party?.kind === 'org') return true;
if (!q) return true;
const hay = [
row.note ?? '',
row.fromOrganizationName,
row.toOrganizationName,
...row.allocations.map((a) => a.caseLabel),
]
.join(' ')
.toLowerCase();
return hay.includes(q);
});
const staff = staffRows.map(mapStaffPayment).filter((row) => {
if (party?.kind === 'staff') return true;
if (!q) return true;
const hay = [row.note ?? '', row.partyName].join(' ').toLowerCase();
return hay.includes(q);
});
const ledger = [
...patients.map((row) => ({
id: row.id,
kind: 'patient' as const,
type: 'RECEIPT' as const,
partyName: row.patientIsWalkIn ? `${row.patientName}` : row.patientName,
partyIsWalkIn: row.patientIsWalkIn,
amount: row.amount,
paidAt: row.paidAt,
note: row.note,
attachments: row.allocations.map((a) => a.treatmentTitle),
acknowledgement: 'none' as const,
canAcknowledge: false,
recordedByViewer: true,
})),
...partners.map((row) => {
const type = row.fromOrganizationId === organizationId ? ('PAYMENT' as const) : ('RECEIPT' as const);
return {
id: row.id,
kind: 'partner' as const,
type,
partyName: type === 'RECEIPT' ? row.fromOrganizationName : row.toOrganizationName,
partyIsWalkIn: false,
amount: row.amount,
paidAt: row.paidAt,
note: row.note,
attachments: row.allocations.map((a) => a.caseLabel),
acknowledgement: row.acknowledgement,
canAcknowledge: row.canAcknowledge,
recordedByViewer: row.recordedByViewer,
};
}),
...staff.map((row) => ({
id: row.id,
kind: 'staff' as const,
type: 'PAYMENT' as const,
partyName: row.partyName,
partyIsWalkIn: false,
amount: row.amount,
paidAt: row.paidAt,
note: row.note,
attachments: [] as string[],
acknowledgement: 'none' as const,
canAcknowledge: false,
recordedByViewer: true,
})),
].sort((a, b) => b.paidAt.localeCompare(a.paidAt));
let net: string | null = null;
if (party) {
let signed = 0;
for (const row of ledger) {
const amount = Number(row.amount);
signed += row.type === 'RECEIPT' ? amount : -amount;
}
net = roundBillingAmount(signed).toFixed(2);
}
return { success: true as const, data: ledger, net };
}
async searchParties(
actorUserId: string,
organizationId: string,
query: { q?: string; txnType: 'RECEIPT' | 'PAYMENT' },
) {
await this.assertCanRead(actorUserId, organizationId);
const orgType = await getOrganizationTypeName(this.prisma, organizationId);
const q = query.q?.trim().toLowerCase() ?? '';
const linked = await this.listAllLinkedOrgs(organizationId);
const clinics = linked
.filter((org) => org.type === 'CLINIC')
.filter((org) => !q || org.name.toLowerCase().includes(q))
.map(({ id, name }) => ({ id, name }));
const labs = linked
.filter((org) => org.type === 'LAB')
.filter((org) => !q || org.name.toLowerCase().includes(q))
.map(({ id, name }) => ({ id, name }));
let patients: Array<{ id: string; name: string; isWalkIn: boolean }> = [];
if (orgType === 'CLINIC' && query.txnType === 'RECEIPT') {
const rows = await this.prisma.patient.findMany({
where: {
OR: [
{ createdByOrganizationId: organizationId },
{ treatments: { some: { organizationId } } },
],
...(q
? {
AND: [
{
OR: [
{ firstName: { contains: q, mode: 'insensitive' } },
{ lastName: { contains: q, mode: 'insensitive' } },
{ mobile: { contains: q } },
],
},
],
}
: {}),
},
select: { id: true, firstName: true, lastName: true, isWalkIn: true },
orderBy: [{ lastName: 'asc' }, { firstName: 'asc' }],
take: 30,
});
patients = rows.map((row) => ({
id: row.id,
name: `${row.firstName} ${row.lastName}`.trim(),
isWalkIn: row.isWalkIn,
}));
}
let staff: Array<{ id: string; name: string }> = [];
if (query.txnType === 'PAYMENT') {
const memberships = await this.prisma.membership.findMany({
where: {
organizationId,
OR: [{ isOwner: true }, { isActive: true }],
user: q
? {
OR: [
{ name: { contains: q, mode: 'insensitive' } },
{ email: { contains: q, mode: 'insensitive' } },
],
}
: undefined,
},
include: { user: { select: { id: true, name: true } } },
take: 30,
});
const byUser = new Map<string, string>();
for (const row of memberships) {
byUser.set(row.user.id, row.user.name);
}
staff = [...byUser.entries()]
.map(([id, name]) => ({ id, name }))
.sort((a, b) => a.name.localeCompare(b.name));
}
const includeOrgs = query.txnType === 'RECEIPT' || query.txnType === 'PAYMENT';
const data: {
patients?: typeof patients;
staff?: typeof staff;
clinics?: typeof clinics;
labs?: typeof labs;
} = {};
if (patients.length > 0) data.patients = patients;
if (staff.length > 0) data.staff = staff;
if (includeOrgs && clinics.length > 0) data.clinics = clinics;
if (includeOrgs && labs.length > 0) data.labs = labs;
// Lab RECEIPT: partner orgs only (already filtered — no patients/staff).
// Clinic RECEIPT: patients + orgs. PAYMENT: orgs + staff.
if (orgType === 'LAB' && query.txnType === 'RECEIPT') {
delete data.patients;
delete data.staff;
}
if (query.txnType === 'PAYMENT') {
delete data.patients;
}
if (orgType === 'CLINIC' && query.txnType === 'RECEIPT') {
delete data.staff;
}
return { success: true as const, data };
}
async listPatientPayments(
actorUserId: string,
organizationId: string,
query: { q?: string; from?: string; to?: string },
query: PaymentListQuery,
) {
await this.assertCanRead(actorUserId, organizationId);
await assertClinicOrganization(this.prisma, organizationId);
const rows = await this.prisma.patientPayment.findMany({
const paidAtFilter = paidAtWhere(query);
const party = normalizePartyFilter(query);
const detailed = await this.prisma.patientPayment.findMany({
where: {
organizationId,
...(query.from || query.to
? {
paidAt: {
...(query.from ? { gte: dateOnlyUtc(query.from) } : {}),
...(query.to ? { lt: dateOnlyUtc(addUtcDays(query.to, 1)) } : {}),
},
}
: {}),
...paidAtFilter,
...(party?.kind === 'patient' ? { patientId: party.id } : {}),
},
include: patientPaymentInclude,
orderBy: [{ paidAt: 'desc' }, { createdAt: 'desc' }],
take: 200,
take: party ? 2000 : 200,
});
const mapped = rows.map(mapPatientPayment);
const mapped = detailed.map(mapPatientPayment);
const q = query.q?.trim().toLowerCase();
return {
success: true as const,
data: mapped.filter((row) => {
if (party?.kind === 'patient') return true;
if (!q) return true;
const hay = [
row.note ?? '',
@@ -399,23 +683,28 @@ export class BillingService {
}
}
const payment = await this.prisma.patientPayment.create({
data: {
organizationId,
patientId: dto.patientId ?? null,
externalPartyName: dto.patientId ? null : externalPartyName,
amount: new Prisma.Decimal(amount.toFixed(2)),
paidAt: new Date(),
note: dto.note?.trim() || null,
createdByUserId: actorUserId,
allocations: {
create: allocations.map((row) => ({
treatmentId: row.targetId,
amount: new Prisma.Decimal(row.amount.toFixed(2)),
})),
const currencyToLock = await this.resolveCurrencyForCreate(organizationId, dto.currency);
const payment = await this.prisma.$transaction(async (tx) => {
await lockBillingCurrencyOnWrite(tx, organizationId, currencyToLock);
return tx.patientPayment.create({
data: {
organizationId,
patientId: dto.patientId ?? null,
externalPartyName: dto.patientId ? null : externalPartyName,
amount: new Prisma.Decimal(amount.toFixed(2)),
paidAt: new Date(),
note: dto.note?.trim() || null,
createdByUserId: actorUserId,
allocations: {
create: allocations.map((row) => ({
treatmentId: row.targetId,
amount: new Prisma.Decimal(row.amount.toFixed(2)),
})),
},
},
},
include: patientPaymentInclude,
include: patientPaymentInclude,
});
});
return { success: true as const, data: mapPatientPayment(payment) };
}
@@ -423,28 +712,33 @@ export class BillingService {
async listPartnerPayments(
actorUserId: string,
organizationId: string,
query: {
q?: string;
from?: string;
to?: string;
},
query: PaymentListQuery,
) {
await this.assertCanRead(actorUserId, organizationId);
const paidAtFilter = paidAtWhere(query);
const party = normalizePartyFilter(query);
const rows = await this.prisma.partnerPayment.findMany({
where: {
OR: [{ fromOrganizationId: organizationId }, { toOrganizationId: organizationId }],
...(query.from || query.to
? {
paidAt: {
...(query.from ? { gte: dateOnlyUtc(query.from) } : {}),
...(query.to ? { lt: dateOnlyUtc(addUtcDays(query.to, 1)) } : {}),
},
}
: {}),
AND: [
{
OR: [{ fromOrganizationId: organizationId }, { toOrganizationId: organizationId }],
},
...(party?.kind === 'org'
? [
{
OR: [
{ fromOrganizationId: party.id, toOrganizationId: organizationId },
{ toOrganizationId: party.id, fromOrganizationId: organizationId },
],
},
]
: []),
paidAtFilter,
],
},
include: partnerPaymentInclude,
orderBy: [{ paidAt: 'desc' }, { createdAt: 'desc' }],
take: 200,
take: party ? 2000 : 200,
});
const mapped = rows
.map((row) => mapPartnerPayment(row, organizationId))
@@ -453,6 +747,7 @@ export class BillingService {
return {
success: true as const,
data: mapped.filter((row) => {
if (party?.kind === 'org') return true;
if (!q) return true;
const hay = [
row.note ?? '',
@@ -479,25 +774,59 @@ export class BillingService {
if (!dto.counterpartOrganizationId && !externalPartyName) {
throw new AppException(ErrorCode.BILLING_PARTNER_INVALID, HttpStatus.BAD_REQUEST);
}
if (recordedBy === 'CLINIC' && dto.type !== 'PAYMENT') {
throw new AppException(ErrorCode.BILLING_TRANSACTION_TYPE_INVALID, HttpStatus.BAD_REQUEST);
}
if (recordedBy === 'LAB' && dto.type !== 'RECEIPT' && dto.type !== 'PAYMENT') {
if (dto.type !== 'RECEIPT' && dto.type !== 'PAYMENT') {
throw new AppException(ErrorCode.BILLING_TRANSACTION_TYPE_INVALID, HttpStatus.BAD_REQUEST);
}
const amount = parseMoney(dto.amount);
const allocations = dto.counterpartOrganizationId ? normalizeAllocations(dto.allocations) : [];
assertAllocationTotal(amount, allocations);
const currencyToLock = await this.resolveCurrencyForCreate(organizationId, dto.currency);
if (!dto.counterpartOrganizationId) {
const fromId = dto.type === 'RECEIPT' ? null : organizationId;
const toId = dto.type === 'RECEIPT' ? organizationId : null;
const payment = await this.prisma.partnerPayment.create({
const payment = await this.prisma.$transaction(async (tx) => {
await lockBillingCurrencyOnWrite(tx, organizationId, currencyToLock);
return tx.partnerPayment.create({
data: {
fromOrganizationId: fromId,
toOrganizationId: toId,
externalPartyName,
amount: new Prisma.Decimal(amount.toFixed(2)),
paidAt: new Date(),
note: dto.note?.trim() || null,
status: PartnerPaymentStatus.CONFIRMED,
recordedBy:
recordedBy === 'LAB' ? PartnerPaymentRecordedBy.LAB : PartnerPaymentRecordedBy.CLINIC,
createdByUserId: actorUserId,
},
include: partnerPaymentInclude,
});
});
return { success: true as const, data: mapPartnerPayment(payment, organizationId) };
}
const counterpartId = dto.counterpartOrganizationId;
await this.assertActiveLink(organizationId, counterpartId);
const fromId = dto.type === 'PAYMENT' ? organizationId : counterpartId;
const toId = dto.type === 'PAYMENT' ? counterpartId : organizationId;
const fromType = await getOrganizationTypeName(this.prisma, fromId);
const toType = await getOrganizationTypeName(this.prisma, toId);
const clinicId = fromType === 'CLINIC' ? fromId : toType === 'CLINIC' ? toId : null;
const labId = fromType === 'LAB' ? fromId : toType === 'LAB' ? toId : null;
if (clinicId && labId) {
await this.assertCaseAllocations(labId, clinicId, allocations);
} else if (allocations.length > 0) {
throw new AppException(ErrorCode.BILLING_ALLOCATION_INVALID, HttpStatus.BAD_REQUEST);
}
const payment = await this.prisma.$transaction(async (tx) => {
await lockBillingCurrencyOnWrite(tx, organizationId, currencyToLock);
return tx.partnerPayment.create({
data: {
fromOrganizationId: fromId,
toOrganizationId: toId,
externalPartyName,
amount: new Prisma.Decimal(amount.toFixed(2)),
paidAt: new Date(),
note: dto.note?.trim() || null,
@@ -505,50 +834,90 @@ export class BillingService {
recordedBy:
recordedBy === 'LAB' ? PartnerPaymentRecordedBy.LAB : PartnerPaymentRecordedBy.CLINIC,
createdByUserId: actorUserId,
allocations: {
create: allocations.map((row) => ({
labCaseId: row.targetId,
amount: new Prisma.Decimal(row.amount.toFixed(2)),
})),
},
},
include: partnerPaymentInclude,
});
return { success: true as const, data: mapPartnerPayment(payment, organizationId) };
}
const counterpartId = dto.counterpartOrganizationId;
const fromId =
recordedBy === 'CLINIC' || dto.type === 'PAYMENT' ? organizationId : counterpartId;
const toId =
recordedBy === 'CLINIC' || dto.type === 'PAYMENT' ? counterpartId : organizationId;
const fromType = await getOrganizationTypeName(this.prisma, fromId);
const toType = await getOrganizationTypeName(this.prisma, toId);
const clinicId = fromType === 'CLINIC' ? fromId : toType === 'CLINIC' ? toId : null;
const labId = fromType === 'LAB' ? fromId : toType === 'LAB' ? toId : null;
if (!clinicId || !labId) {
throw new AppException(ErrorCode.BILLING_PARTNER_INVALID, HttpStatus.BAD_REQUEST);
}
await this.assertLinkedClinicLab(clinicId, labId);
await this.assertCaseAllocations(labId, clinicId, allocations);
const payment = await this.prisma.partnerPayment.create({
data: {
fromOrganizationId: fromId,
toOrganizationId: toId,
amount: new Prisma.Decimal(amount.toFixed(2)),
paidAt: new Date(),
note: dto.note?.trim() || null,
status: PartnerPaymentStatus.CONFIRMED,
recordedBy:
recordedBy === 'LAB' ? PartnerPaymentRecordedBy.LAB : PartnerPaymentRecordedBy.CLINIC,
createdByUserId: actorUserId,
allocations: {
create: allocations.map((row) => ({
labCaseId: row.targetId,
amount: new Prisma.Decimal(row.amount.toFixed(2)),
})),
},
},
include: partnerPaymentInclude,
});
return { success: true as const, data: mapPartnerPayment(payment, organizationId) };
}
async listStaffPayments(
actorUserId: string,
organizationId: string,
query: PaymentListQuery,
) {
await this.assertCanRead(actorUserId, organizationId);
const paidAtFilter = paidAtWhere(query);
const party = normalizePartyFilter(query);
const rows = await this.prisma.staffPayment.findMany({
where: {
organizationId,
...paidAtFilter,
...(party?.kind === 'staff' ? { userId: party.id } : {}),
},
include: staffPaymentInclude,
orderBy: [{ paidAt: 'desc' }, { createdAt: 'desc' }],
take: party ? 2000 : 200,
});
const mapped = rows.map(mapStaffPayment);
const q = query.q?.trim().toLowerCase();
return {
success: true as const,
data: mapped.filter((row) => {
if (party?.kind === 'staff') return true;
if (!q) return true;
const hay = [row.note ?? '', row.partyName].join(' ').toLowerCase();
return hay.includes(q);
}),
};
}
async createStaffPayment(
actorUserId: string,
organizationId: string,
dto: CreatePaymentDto,
) {
await this.assertCanEdit(actorUserId, organizationId);
if (dto.type !== 'PAYMENT') {
throw new AppException(ErrorCode.BILLING_TRANSACTION_TYPE_INVALID, HttpStatus.BAD_REQUEST);
}
const externalPartyName = dto.externalPartyName?.trim() || '';
if (!dto.userId && !externalPartyName) {
throw new AppException(ErrorCode.BILLING_STAFF_INVALID, HttpStatus.BAD_REQUEST);
}
if (dto.userId && externalPartyName) {
throw new AppException(ErrorCode.BILLING_STAFF_INVALID, HttpStatus.BAD_REQUEST);
}
if (dto.userId) {
await this.assertStaffInOrg(organizationId, dto.userId);
}
const amount = parseMoney(dto.amount);
const currencyToLock = await this.resolveCurrencyForCreate(organizationId, dto.currency);
const payment = await this.prisma.$transaction(async (tx) => {
await lockBillingCurrencyOnWrite(tx, organizationId, currencyToLock);
return tx.staffPayment.create({
data: {
organizationId,
userId: dto.userId ?? null,
externalPartyName: dto.userId ? null : externalPartyName,
amount: new Prisma.Decimal(amount.toFixed(2)),
paidAt: new Date(),
note: dto.note?.trim() || null,
createdByUserId: actorUserId,
},
include: staffPaymentInclude,
});
});
return { success: true as const, data: mapStaffPayment(payment) };
}
async acknowledgePartnerPayment(
actorUserId: string,
organizationId: string,
@@ -584,11 +953,10 @@ export class BillingService {
async listPartners(actorUserId: string, organizationId: string) {
await this.assertCanRead(actorUserId, organizationId);
const orgType = await getOrganizationTypeName(this.prisma, organizationId);
const counterpartType = orgType === 'CLINIC' ? 'LAB' : 'CLINIC';
const linked = await this.listAllLinkedOrgs(organizationId);
return {
success: true as const,
data: await this.listLinkedOrgs(organizationId, counterpartType),
data: linked.map(({ id, name, type }) => ({ id, name, type })),
};
}
@@ -925,6 +1293,11 @@ export class BillingService {
});
if (!task) return;
const catalogCode = outsourcingPriceCodeForStep(
task.workflowStepCode,
task.prosthesisTypeCode,
);
if (task.workflowStepCode === INTRAORAL_SCAN_STEP) {
const existingScan = await db.commissionEarning.findFirst({
where: { labCaseId: task.labCaseId, catalogCode: INTRAORAL_SCAN_STEP },
@@ -933,7 +1306,7 @@ export class BillingService {
if (existingScan) return;
} else {
const existing = await db.commissionEarning.findFirst({
where: { labCaseTaskId: task.id, catalogCode: task.workflowStepCode },
where: { labCaseTaskId: task.id },
select: { id: true },
});
if (existing) return;
@@ -950,7 +1323,7 @@ export class BillingService {
commissionLines.find(
(row) =>
row.catalogKind === 'LAB_WORKFLOW_STEP' &&
row.catalogCode === task.workflowStepCode,
row.catalogCode === catalogCode,
)?.amount ?? 0;
if (unitAmount <= 0) return;
@@ -969,7 +1342,7 @@ export class BillingService {
userId,
labCaseId: task.labCaseId,
labCaseTaskId: task.id,
catalogCode: task.workflowStepCode,
catalogCode,
baseAmount: new Prisma.Decimal(unitAmount.toFixed(2)),
percent: new Prisma.Decimal('0'),
qty: new Prisma.Decimal(qty.toFixed(2)),
@@ -1267,7 +1640,7 @@ export class BillingService {
return sheet;
}
private async listLinkedOrgs(organizationId: string, type: OrganizationTypeName) {
private async listAllLinkedOrgs(organizationId: string) {
const [linksA, linksB] = await Promise.all([
this.prisma.organizationLink.findMany({
where: { organizationAId: organizationId, status: LinkStatus.ACTIVE },
@@ -1283,21 +1656,59 @@ export class BillingService {
}),
]);
return [
...linksA.map((link) => ({
const byId = new Map<string, { id: string; name: string; type: OrganizationTypeName }>();
for (const link of linksA) {
byId.set(link.organizationB.id, {
id: link.organizationB.id,
name: link.organizationB.name,
type: link.organizationB.type.name,
})),
...linksB.map((link) => ({
type: link.organizationB.type.name as OrganizationTypeName,
});
}
for (const link of linksB) {
byId.set(link.organizationA.id, {
id: link.organizationA.id,
name: link.organizationA.name,
type: link.organizationA.type.name,
})),
]
type: link.organizationA.type.name as OrganizationTypeName,
});
}
return [...byId.values()].sort((a, b) => a.name.localeCompare(b.name));
}
private async listLinkedOrgs(organizationId: string, type: OrganizationTypeName) {
return (await this.listAllLinkedOrgs(organizationId))
.filter((org) => org.type === type)
.map(({ id, name }) => ({ id, name }))
.sort((a, b) => a.name.localeCompare(b.name));
.map(({ id, name }) => ({ id, name }));
}
private async resolveCurrencyForCreate(
organizationId: string,
requested: string | undefined,
): Promise<BillingCurrencyCode> {
const settings = await resolveBillingCurrency(this.prisma, organizationId);
if (settings.currencySource === 'unset') {
if (!isBillingCurrencyCode(requested)) {
throw new AppException(ErrorCode.BILLING_CURRENCY_REQUIRED, HttpStatus.BAD_REQUEST);
}
return requested;
}
if (settings.currencySource === 'legacy_toman') {
return 'TOMAN';
}
return settings.currency ?? 'TOMAN';
}
private async assertStaffInOrg(organizationId: string, userId: string) {
const membership = await this.prisma.membership.findFirst({
where: {
organizationId,
userId,
OR: [{ isOwner: true }, { isActive: true }],
},
select: { id: true },
});
if (!membership) {
throw new AppException(ErrorCode.BILLING_STAFF_INVALID, HttpStatus.BAD_REQUEST);
}
}
private async assertActiveLink(organizationId: string, otherOrganizationId: string) {
@@ -1719,6 +2130,45 @@ const partnerPaymentInclude = {
},
} satisfies Prisma.PartnerPaymentInclude;
const staffPaymentInclude = {
user: { select: { id: true, name: true } },
} satisfies Prisma.StaffPaymentInclude;
function paidAtWhere(query: { from?: string; to?: string }): {
paidAt?: { gte?: Date; lt?: Date };
} {
if (!query.from && !query.to) return {};
return {
paidAt: {
...(query.from ? { gte: dateOnlyUtc(query.from) } : {}),
...(query.to ? { lt: dateOnlyUtc(addUtcDays(query.to, 1)) } : {}),
},
};
}
function normalizePartyFilter(query: PaymentListQuery): {
kind: 'patient' | 'staff' | 'org';
id: string;
} | null {
if (!query.partyKind || !query.partyId) return null;
return { kind: query.partyKind, id: query.partyId };
}
function mapStaffPayment(
payment: Prisma.StaffPaymentGetPayload<{ include: typeof staffPaymentInclude }>,
) {
return {
id: payment.id,
userId: payment.userId,
externalPartyName: payment.externalPartyName,
partyName: payment.user?.name ?? payment.externalPartyName ?? '',
amount: payment.amount.toString(),
paidAt: payment.paidAt.toISOString(),
note: payment.note,
createdAt: payment.createdAt.toISOString(),
};
}
function mapPatientPayment(
payment: Prisma.PatientPaymentGetPayload<{ include: typeof patientPaymentInclude }>,
) {

View File

@@ -47,16 +47,26 @@ export class CreatePaymentDto {
@IsUUID()
patientId?: string;
/** Lab id (clinic paying a lab) or clinic id (lab receipt/payment). */
/** Linked org id (clinic↔lab or same-type linked orgs). */
@IsOptional()
@IsUUID()
counterpartOrganizationId?: string;
/** Typed party when no linked organization or patient was selected. */
/** Staff member for outbound staff payments. */
@IsOptional()
@IsUUID()
userId?: string;
/** Typed party when no linked organization, patient, or staff was selected. */
@IsOptional()
@IsString()
@MaxLength(200)
externalPartyName?: string;
/** Required only when org currency is still unlocked (no cash history). */
@IsOptional()
@IsIn(['TOMAN', 'DOLLAR', 'EURO'], { message: ErrorCode.BILLING_CURRENCY_INVALID })
currency?: 'TOMAN' | 'DOLLAR' | 'EURO';
}
export class AcknowledgePaymentDto {
@@ -79,6 +89,24 @@ export class ListPaymentsQueryDto {
@IsString()
@Matches(/^\d{4}-\d{2}-\d{2}$/)
to?: string;
@IsOptional()
@IsIn(['patient', 'staff', 'org'], { message: ErrorCode.BILLING_PARTY_INVALID })
partyKind?: 'patient' | 'staff' | 'org';
@IsOptional()
@IsUUID()
partyId?: string;
}
export class PartySearchQueryDto {
@IsOptional()
@IsString()
@MaxLength(120)
q?: string;
@IsIn(['RECEIPT', 'PAYMENT'], { message: ErrorCode.BILLING_TRANSACTION_TYPE_INVALID })
txnType: 'RECEIPT' | 'PAYMENT';
}
export class AllocationSearchQueryDto {

View File

@@ -2,6 +2,7 @@ import {
DESIGN_FRAME_PRICE,
DESIGN_FULL_PRICE,
DESIGN_IMPLANT_PRICE,
commissionWorkflowStepCodes,
designPriceCodeForTypes,
outsourcingPriceCodeForStep,
outsourcingPriceStepCodes,
@@ -23,10 +24,10 @@ describe('outsourcing price steps', () => {
expect(codes).toContain('milling_wet');
expect(codes).toContain('milling_wet_sinter');
expect(codes).toContain('sinter');
expect(codes).toContain('stain');
expect(codes).toContain('glaze');
expect(codes).toContain('stain_glaze');
expect(codes).toContain('build_up');
expect(codes).not.toContain('stain');
expect(codes).not.toContain('glaze');
expect(codes).not.toContain('build_up');
expect(codes).toContain('choosing_abutment');
expect(new Set(codes).size).toBe(codes.length);
});
@@ -56,5 +57,27 @@ describe('outsourcing price steps', () => {
expect(outsourcingPriceCodeForStep('milling_dry_sinter', 'monolithic_zirconia')).toBe(
'milling_dry_sinter',
);
expect(outsourcingPriceCodeForStep('design', 'pfm_crown')).toBe(DESIGN_FRAME_PRICE);
expect(outsourcingPriceCodeForStep('design_customized_abutment', 'customized_abutment')).toBe(
DESIGN_IMPLANT_PRICE,
);
});
it('shares the fee steps with commissions and adds scan, packing, and shipping', () => {
const commission = commissionWorkflowStepCodes();
expect(commission[0]).toBe('intraoral_scan');
expect(commission.slice(1, 1 + codes.length)).toEqual(codes);
expect(commission.slice(-2)).toEqual(['packing', 'shipping']);
for (const code of [
DESIGN_IMPLANT_PRICE,
DESIGN_FRAME_PRICE,
DESIGN_FULL_PRICE,
]) {
expect(commission).toContain(code);
}
for (const code of ['design', 'design_customized_abutment', 'stain', 'glaze', 'build_up']) {
expect(commission).not.toContain(code);
}
expect(new Set(commission).size).toBe(commission.length);
});
});

View File

@@ -41,12 +41,6 @@ const PINNED_PRICE_CODES = [
DESIGN_FULL_PRICE,
] as const;
/**
* Stored tasks can still use these codes after pipelines collapsed or retired them.
* They stay priceable so an older case does not quote those steps as zero.
*/
const HISTORICAL_OUTSOURCE_CODES = ['build_up', 'stain', 'glaze'] as const;
export function isBillingDesignPriceCode(code: string): boolean {
return (BILLING_DESIGN_PRICE_CODES as readonly string[]).includes(code);
}
@@ -60,7 +54,6 @@ export function outsourcingPriceStepCodes(): string[] {
if (!EXCLUDED_PIPELINE_CODES.has(code)) emitted.add(code);
}
}
for (const code of HISTORICAL_OUTSOURCE_CODES) emitted.add(code);
const order = new Map<string, number>(
LAB_WORKFLOW_STEPS.map((step) => [step.code, step.sortOrder]),
);
@@ -72,6 +65,11 @@ export function outsourcingPriceStepCodes(): string[] {
return [...PINNED_PRICE_CODES, ...rest];
}
/** Fee-sheet steps, including the three design prices, plus scan, packing, and shipping. */
export function commissionWorkflowStepCodes(): string[] {
return ['intraoral_scan', ...outsourcingPriceStepCodes(), 'packing', 'shipping'];
}
export function prosthesisTypeParts(code: string): string[] {
return code
.split('+')

View File

@@ -19,6 +19,7 @@ import {
EmailVerificationService,
} from '../email-verification/email-verification.service';
import { canConnectOrganizationTypes } from '../../common/linked-organizations';
import { ensureOrganizationType, ensureTrialPlan } from '../../common/reference-catalog';
import { AcceptOrganizationInviteDto } from './dto/accept-organization-invite.dto';
import { CreateConnectionRequestDto } from './dto/create-connection-request.dto';
import { InviteOrganizationDto } from './dto/invite-organization.dto';
@@ -627,6 +628,7 @@ export class OrganizationService {
await assertOwnerOrganizationNameAvailable(tx, owner.id, organizationName, {
conflictCode: ErrorCode.ORG_INVITE_NAME_TAKEN,
});
await ensureOrganizationType(tx, invitedType);
// Placeholder org until acceptInvite; plan stays null until acceptance.
invitedOrg = await tx.organization.create({
@@ -813,6 +815,8 @@ export class OrganizationService {
});
let targetOrganizationId = invitation.invitedOrganizationId;
await ensureOrganizationType(tx, dto.organizationType);
await ensureTrialPlan(tx);
if (targetOrganizationId) {
await tx.organization.update({
where: { id: targetOrganizationId },

1153
docs/exocad error.txt Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -37,7 +37,12 @@
"none": "None",
"preview": "Preview",
"openMenu": "Open menu",
"closeMenu": "Close menu"
"closeMenu": "Close menu",
"currencyName": {
"TOMAN": "toman",
"DOLLAR": "dollar",
"EURO": "euro"
}
},
"language": {
"label": "Language",
@@ -469,11 +474,11 @@
"importantLabel": "Important",
"unreadCase": "Unread updates",
"markCaseImportant": "Mark as important",
"calculatedAmount": "Calculated (dollar)",
"billedAmount": "Billed (dollar)",
"calculatedAmount": "Calculated",
"billedAmount": "Billed",
"billedLead": "Billed",
"billedCurrencyNote": "(dollar)",
"billedCurrencySuffix": "$",
"billedCurrencyNote": "",
"billedCurrencySuffix": "",
"markImportant": "Mark as important",
"lastUpdatedBy": "Updated by {name}",
"lastUpdatedUnknown": "Not started yet",
@@ -817,15 +822,15 @@
"casesTitle": "Treatment cases",
"casesSubtitle": "Each case has its own teeth, notes, attachments, and destinations for send.",
"detailsTitle": "Treatment details",
"planTotal": "Plan total (dollar)",
"calculatedAmount": "Calculated (dollar)",
"billedAmount": "Billed (dollar)",
"approvedPrice": "Approved price (dollar)",
"approvePrice": "Approve price",
"priceApproved": "Plan price approved.",
"invalidApprovedPrice": "Enter a valid price (zero or more, up to two decimals).",
"approvePriceNeedsPlan": "Save the plan before approving the price.",
"approvePriceError": "Could not approve this price.",
"planTotal": "Plan total",
"calculatedAmount": "Calculated",
"billedAmount": "Billed",
"approvedPrice": "Approved amount",
"approvePrice": "Approve amount",
"priceApproved": "Plan amount approved.",
"invalidApprovedPrice": "Enter a valid amount (zero or more, up to two decimals).",
"approvePriceNeedsPlan": "Save the plan before approving the amount.",
"approvePriceError": "Could not approve this amount.",
"addDetail": "Add detail",
"confirmRemoveDetail": "Remove this treatment detail?",
"confirmRemoveLastDetail": "This is the last detail. Removing it leaves the plan empty until you add another. Continue?",
@@ -1147,7 +1152,7 @@
"subscriptionsSubtitle": "Your Nudentic workspace plan and seats for {orgName}. Clinic and lab income tracking stays under the sidebar Billing tab.",
"noSubscriptionNotice": "This organization has no active subscription. Select a plan below to start the purchase process.",
"currentPlan": "Current plan",
"planPrice": "Plan price (dollar)",
"planPrice": "Plan price",
"seatsUsed": "Seats used",
"seatsRemaining": "Seats remaining",
"daysRemaining": "Days remaining",
@@ -1295,7 +1300,8 @@
"treatmentTypes": "Treatment types",
"workflowSteps": "Workflow steps",
"outsourcingPrices": "Outsourcing prices",
"price": "Price (dollar)",
"price": "Amount",
"amount": "Amount",
"commissionBaseHint": "Commission is a share of the fee schedule price that applies to the same dentist on the treatment date.",
"commissionBaseHintLab": "Commission is a share of the lab fee charged to the sending clinic.",
"confirmDeleteSheet": "Delete this schedule? Existing plans and cases keep their stamped prices.",
@@ -1304,7 +1310,8 @@
"noSheets": "No schedules yet.",
"searchSheets": "Search schedules",
"unnamedSheet": "Untitled",
"invalidPrice": "Enter a valid price (zero or more, up to two decimals).",
"invalidPrice": "Enter a valid amount (zero or more, up to two decimals).",
"invalidAmount": "Enter a valid amount (zero or more, up to two decimals).",
"invalidPercent": "Enter a percentage between 0 and 100.",
"errorLoadSheets": "Could not load schedules.",
"errorSaveSheet": "Could not save this schedule.",
@@ -1316,6 +1323,7 @@
"errorSavePayment": "Could not save this transaction.",
"noPayments": "No transactions yet.",
"searchPayments": "Search transactions",
"filterByParty": "Filter by party",
"typeFilterAll": "All types",
"dateFrom": "From",
"dateTo": "To",
@@ -1328,8 +1336,22 @@
"selectPatient": "Select patient",
"selectLab": "Select lab",
"selectClinic": "Select clinic",
"selectParty": "Select or type a party",
"selectPartyReceiptClinic": "Patient or organization",
"selectPartyPayment": "Organization or staff",
"partySectionPatients": "Patients",
"partySectionStaff": "Staff",
"partySectionClinics": "Clinics",
"partySectionLabs": "Labs",
"searchPatient": "Search patient",
"partySearch": "Search or type a name",
"currency": "Currency",
"currencyPlaceholder": "Choose currency",
"currencyRequired": "Choose a currency for this organization.",
"currencyLockWarning": "This choice is permanent for the organization after you save.",
"ledgerNet": "Net {amount}",
"ledgerNetCredit": "They owe you",
"ledgerNetDebt": "You owe them",
"paymentPending": "Waiting",
"paymentDeclined": "Declined",
"acceptPayment": "Accept",
@@ -1560,6 +1582,10 @@
"BILLING_PATIENT_INVALID": "Choose a patient for this receipt.",
"BILLING_TRANSACTION_TYPE_INVALID": "Choose receipt or payment.",
"BILLING_PAYMENT_NOT_FOUND": "That payment was not found.",
"BILLING_PAYMENT_ACK_INVALID": "This payment can no longer be confirmed."
"BILLING_PAYMENT_ACK_INVALID": "This payment can no longer be confirmed.",
"BILLING_CURRENCY_REQUIRED": "Choose a currency for this organization.",
"BILLING_CURRENCY_INVALID": "Choose toman, dollar, or euro.",
"BILLING_STAFF_INVALID": "Choose a staff member for this payment.",
"BILLING_PARTY_INVALID": "Choose a valid party for this filter."
}
}

View File

@@ -37,7 +37,12 @@
"none": "هیچکدام",
"preview": "پیش‌نمایش",
"openMenu": "باز کردن منو",
"closeMenu": "بستن منو"
"closeMenu": "بستن منو",
"currencyName": {
"TOMAN": "تومان",
"DOLLAR": "دلار",
"EURO": "یورو"
}
},
"language": {
"label": "زبان",
@@ -469,11 +474,11 @@
"importantLabel": "مهم",
"unreadCase": "به‌روزرسانی‌های خوانده‌نشده",
"markCaseImportant": "علامت‌گذاری به‌عنوان مهم",
"calculatedAmount": "محاسبه‌شده (تومان)",
"billedAmount": "صورتحساب (تومان)",
"calculatedAmount": "محاسبه‌شده",
"billedAmount": "صورتحساب",
"billedLead": "صورتحساب",
"billedCurrencyNote": "(تومان)",
"billedCurrencySuffix": "تومان",
"billedCurrencyNote": "",
"billedCurrencySuffix": "",
"markImportant": "علامت‌گذاری به عنوان مهم",
"lastUpdatedBy": "به‌روزرسانی توسط {name}",
"lastUpdatedUnknown": "هنوز شروع نشده",
@@ -818,15 +823,15 @@
"casesTitle": "پرونده‌های درمانی",
"casesSubtitle": "هر پرونده دارای دندان‌ها، یادداشت‌ها، پیوست‌ها و مقصدهای ارسال خود است.",
"detailsTitle": "جزئیات درمان",
"planTotal": "جمع طرح (تومان)",
"calculatedAmount": "محاسبه‌شده (تومان)",
"billedAmount": "صورتحساب (تومان)",
"approvedPrice": "مبلغ تأییدشده (تومان)",
"approvePrice": "تأیید قیمت",
"priceApproved": "قیمت طرح تأیید شد.",
"invalidApprovedPrice": "قیمت معتبر وارد کنید (صفر یا بیشتر، تا دو رقم اعشار).",
"approvePriceNeedsPlan": "قبل از تأیید قیمت، طرح را ذخیره کنید.",
"approvePriceError": "تأیید این قیمت ممکن نشد.",
"planTotal": "جمع طرح",
"calculatedAmount": "محاسبه‌شده",
"billedAmount": "صورتحساب",
"approvedPrice": "مبلغ تأییدشده",
"approvePrice": "تأیید مبلغ",
"priceApproved": "مبلغ طرح تأیید شد.",
"invalidApprovedPrice": "مبلغ معتبر وارد کنید (صفر یا بیشتر، تا دو رقم اعشار).",
"approvePriceNeedsPlan": "قبل از تأیید مبلغ، طرح را ذخیره کنید.",
"approvePriceError": "تأیید این مبلغ ممکن نشد.",
"addDetail": "افزودن جزئیات",
"confirmRemoveDetail": "این جزئیات درمان حذف شود؟",
"confirmRemoveLastDetail": "این آخرین جزئیات است. با حذف آن برنامه خالی می‌ماند تا جزئیات جدیدی اضافه کنید. ادامه می‌دهید؟",
@@ -1148,7 +1153,7 @@
"subscriptionsSubtitle": "طرح و مجوزهای فضای کاری Nudentic شما برای {orgName}. پیگیری درآمد کلینیک و لابراتوار در برگه صورتحساب در نوار کناری قرار دارد.",
"noSubscriptionNotice": "این سازمان اشتراک فعالی ندارد. برای شروع فرآیند خرید، یک طرح زیر را انتخاب کنید.",
"currentPlan": "طرح فعلی",
"planPrice": "قیمت طرح (تومان)",
"planPrice": "قیمت طرح",
"seatsUsed": "مجوزهای استفاده شده",
"seatsRemaining": "مجوزهای باقی‌مانده",
"daysRemaining": "روزهای باقی‌مانده",
@@ -1296,7 +1301,8 @@
"treatmentTypes": "انواع درمان",
"workflowSteps": "مراحل گردش‌کار",
"outsourcingPrices": "قیمت‌های برون‌سپاری",
"price": "مبلغ (تومان)",
"price": "مبلغ",
"amount": "مبلغ",
"commissionBaseHint": "کمیسیون سهمی از قیمت جدول تعرفه‌ای است که برای همان دندان‌پزشک در تاریخ درمان اعمال می‌شود.",
"commissionBaseHintLab": "کمیسیون سهمی از تعرفه لابراتوار برای کلینیک ارسال‌کننده است.",
"confirmDeleteSheet": "این جدول حذف شود؟ قیمت‌های ثبت‌شده روی طرح‌ها و کیس‌ها باقی می‌مانند.",
@@ -1305,7 +1311,8 @@
"noSheets": "هنوز جدولی نیست.",
"searchSheets": "جستجوی جدول‌ها",
"unnamedSheet": "بدون عنوان",
"invalidPrice": "قیمت معتبر وارد کنید (صفر یا بیشتر، تا دو رقم اعشار).",
"invalidPrice": "مبلغ معتبر وارد کنید (صفر یا بیشتر، تا دو رقم اعشار).",
"invalidAmount": "مبلغ معتبر وارد کنید (صفر یا بیشتر، تا دو رقم اعشار).",
"invalidPercent": "درصدی بین ۰ تا ۱۰۰ وارد کنید.",
"errorLoadSheets": "بارگذاری جدول‌ها ممکن نشد.",
"errorSaveSheet": "ذخیره این جدول ممکن نشد.",
@@ -1317,6 +1324,7 @@
"errorSavePayment": "ذخیره این تراکنش ممکن نشد.",
"noPayments": "هنوز تراکنشی نیست.",
"searchPayments": "جستجوی تراکنش‌ها",
"filterByParty": "فیلتر بر اساس طرف",
"typeFilterAll": "همه انواع",
"dateFrom": "از",
"dateTo": "تا",
@@ -1329,8 +1337,22 @@
"selectPatient": "بیمار را انتخاب کنید",
"selectLab": "لابراتوار را انتخاب کنید",
"selectClinic": "کلینیک را انتخاب کنید",
"selectParty": "طرف را انتخاب یا تایپ کنید",
"selectPartyReceiptClinic": "بیمار یا سازمان",
"selectPartyPayment": "سازمان یا کارکنان",
"partySectionPatients": "بیماران",
"partySectionStaff": "کارکنان",
"partySectionClinics": "کلینیک‌ها",
"partySectionLabs": "لابراتوارها",
"searchPatient": "جستجوی بیمار",
"partySearch": "جستجو یا نوشتن نام",
"currency": "ارز",
"currencyPlaceholder": "انتخاب ارز",
"currencyRequired": "ارز این سازمان را انتخاب کنید.",
"currencyLockWarning": "پس از ذخیره، این انتخاب برای سازمان دائمی است.",
"ledgerNet": "خالص {amount}",
"ledgerNetCredit": "بستانکار",
"ledgerNetDebt": "بدهکار",
"paymentPending": "در انتظار",
"paymentDeclined": "رد شده",
"acceptPayment": "پذیرش",
@@ -1561,6 +1583,10 @@
"BILLING_PATIENT_INVALID": "برای این دریافت یک بیمار انتخاب کنید.",
"BILLING_TRANSACTION_TYPE_INVALID": "دریافت یا پرداخت را انتخاب کنید.",
"BILLING_PAYMENT_NOT_FOUND": "این پرداخت پیدا نشد.",
"BILLING_PAYMENT_ACK_INVALID": "این پرداخت دیگر قابل تأیید نیست."
"BILLING_PAYMENT_ACK_INVALID": "این پرداخت دیگر قابل تأیید نیست.",
"BILLING_CURRENCY_REQUIRED": "ارز این سازمان را انتخاب کنید.",
"BILLING_CURRENCY_INVALID": "تومان، دلار یا یورو را انتخاب کنید.",
"BILLING_STAFF_INVALID": "یک عضو کارکنان برای این پرداخت انتخاب کنید.",
"BILLING_PARTY_INVALID": "طرف معتبری برای این فیلتر انتخاب کنید."
}
}

View File

@@ -37,7 +37,12 @@
"none": "Geen",
"preview": "Voorbeeld",
"openMenu": "Menu openen",
"closeMenu": "Menu sluiten"
"closeMenu": "Menu sluiten",
"currencyName": {
"TOMAN": "toman",
"DOLLAR": "dollar",
"EURO": "euro"
}
},
"language": {
"label": "Taal",
@@ -469,11 +474,11 @@
"importantLabel": "Belangrijk",
"unreadCase": "Ongelezen updates",
"markCaseImportant": "Markeer als belangrijk",
"calculatedAmount": "Berekend (euro)",
"billedAmount": "Gefactureerd (euro)",
"calculatedAmount": "Berekend",
"billedAmount": "Gefactureerd",
"billedLead": "Gefactureerd",
"billedCurrencyNote": "(euro)",
"billedCurrencySuffix": "€",
"billedCurrencyNote": "",
"billedCurrencySuffix": "",
"markImportant": "Markeren als belangrijk",
"lastUpdatedBy": "Bijgewerkt door {name}",
"lastUpdatedUnknown": "Nog niet gestart",
@@ -817,15 +822,15 @@
"casesTitle": "Behandelcasussen",
"casesSubtitle": "Elke case heeft zijn eigen tanden, notities, bijlagen en verzendbestemmingen.",
"detailsTitle": "Behandeldetails",
"planTotal": "Plantotaal (euro)",
"calculatedAmount": "Berekend (euro)",
"billedAmount": "Gefactureerd (euro)",
"approvedPrice": "Goedgekeurde prijs (euro)",
"approvePrice": "Prijs goedkeuren",
"priceApproved": "Planprijs goedgekeurd.",
"invalidApprovedPrice": "Voer een geldige prijs in (nul of meer, tot twee decimalen).",
"approvePriceNeedsPlan": "Sla het plan op voordat u de prijs goedkeurt.",
"approvePriceError": "Kan deze prijs niet goedkeuren.",
"planTotal": "Plantotaal",
"calculatedAmount": "Berekend",
"billedAmount": "Gefactureerd",
"approvedPrice": "Goedgekeurd bedrag",
"approvePrice": "Bedrag goedkeuren",
"priceApproved": "Planbedrag goedgekeurd.",
"invalidApprovedPrice": "Voer een geldig bedrag in (nul of meer, tot twee decimalen).",
"approvePriceNeedsPlan": "Sla het plan op voordat u het bedrag goedkeurt.",
"approvePriceError": "Kan dit bedrag niet goedkeuren.",
"addDetail": "Detail toevoegen",
"confirmRemoveDetail": "Dit behandelingsdetail verwijderen?",
"confirmRemoveLastDetail": "Dit is het laatste detail. Als u het verwijdert, blijft het plan leeg tot u een nieuw detail toevoegt. Doorgaan?",
@@ -1147,7 +1152,7 @@
"subscriptionsSubtitle": "Uw Nudentic-werkruimteplan en plaatsen voor {orgName}. Kliniek- en laboratoriuminkomsten blijven onder het tabblad Facturatie in de zijbalk.",
"noSubscriptionNotice": "Deze organisatie heeft geen actief abonnement. Selecteer hieronder een abonnement om het aankoopproces te starten.",
"currentPlan": "Huidig abonnement",
"planPrice": "Abonnementsprijs (euro)",
"planPrice": "Abonnementsprijs",
"seatsUsed": "Plaatsen gebruikt",
"seatsRemaining": "Plaatsen over",
"daysRemaining": "Dagen over",
@@ -1295,7 +1300,8 @@
"treatmentTypes": "Behandeltypes",
"workflowSteps": "Werkstappen",
"outsourcingPrices": "Uitbestedingsprijzen",
"price": "Prijs (euro)",
"price": "Bedrag",
"amount": "Bedrag",
"commissionBaseHint": "Commissie is een deel van de tariefschemaprijs die op de behandeldatum voor dezelfde tandarts geldt.",
"commissionBaseHintLab": "Commissie is een deel van het labtarief dat de verzendende kliniek betaalt.",
"confirmDeleteSheet": "Dit schema verwijderen? Bestaande plannen en cases behouden hun vastgelegde prijzen.",
@@ -1304,7 +1310,8 @@
"noSheets": "Nog geen schema's.",
"searchSheets": "Schema's zoeken",
"unnamedSheet": "Naamloos",
"invalidPrice": "Voer een geldige prijs in (nul of meer, tot twee decimalen).",
"invalidPrice": "Voer een geldig bedrag in (nul of meer, tot twee decimalen).",
"invalidAmount": "Voer een geldig bedrag in (nul of meer, tot twee decimalen).",
"invalidPercent": "Voer een percentage tussen 0 en 100 in.",
"errorLoadSheets": "Kan schema's niet laden.",
"errorSaveSheet": "Kan dit schema niet opslaan.",
@@ -1316,6 +1323,7 @@
"errorSavePayment": "Kan deze transactie niet opslaan.",
"noPayments": "Nog geen transacties.",
"searchPayments": "Transacties zoeken",
"filterByParty": "Filter op partij",
"typeFilterAll": "Alle types",
"dateFrom": "Van",
"dateTo": "Tot",
@@ -1328,8 +1336,22 @@
"selectPatient": "Selecteer patiënt",
"selectLab": "Selecteer lab",
"selectClinic": "Selecteer kliniek",
"selectParty": "Selecteer of typ een partij",
"selectPartyReceiptClinic": "Patiënt of organisatie",
"selectPartyPayment": "Organisatie of medewerker",
"partySectionPatients": "Patiënten",
"partySectionStaff": "Medewerkers",
"partySectionClinics": "Klinieken",
"partySectionLabs": "Labs",
"searchPatient": "Patiënt zoeken",
"partySearch": "Zoek of typ een naam",
"currency": "Valuta",
"currencyPlaceholder": "Kies valuta",
"currencyRequired": "Kies een valuta voor deze organisatie.",
"currencyLockWarning": "Deze keuze is permanent voor de organisatie nadat u opslaat.",
"ledgerNet": "Netto {amount}",
"ledgerNetCredit": "Zij zijn u schuldig",
"ledgerNetDebt": "U bent hun schuldig",
"paymentPending": "Wachtend",
"paymentDeclined": "Geweigerd",
"acceptPayment": "Accepteren",
@@ -1560,6 +1582,10 @@
"BILLING_PATIENT_INVALID": "Kies een patiënt voor deze ontvangst.",
"BILLING_TRANSACTION_TYPE_INVALID": "Kies ontvangst of betaling.",
"BILLING_PAYMENT_NOT_FOUND": "Die betaling is niet gevonden.",
"BILLING_PAYMENT_ACK_INVALID": "Deze betaling kan niet meer worden bevestigd."
"BILLING_PAYMENT_ACK_INVALID": "Deze betaling kan niet meer worden bevestigd.",
"BILLING_CURRENCY_REQUIRED": "Kies een valuta voor deze organisatie.",
"BILLING_CURRENCY_INVALID": "Kies toman, dollar of euro.",
"BILLING_STAFF_INVALID": "Kies een medewerker voor deze betaling.",
"BILLING_PARTY_INVALID": "Kies een geldige partij voor dit filter."
}
}

View File

@@ -81,6 +81,7 @@
"resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.0.tgz",
"integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==",
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/code-frame": "^7.29.0",
"@babel/generator": "^7.29.0",
@@ -1499,7 +1500,6 @@
"resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.11.tgz",
"integrity": "sha512-ZMp1V8ZFcPG5dIWnQLr3NSI1MiCU7UETdS/A0G8V/XWHvJv3ZsFqutJn1Y5RPmAPX6F3BiE397OqveU/9NCuIA==",
"license": "MIT",
"peer": true,
"dependencies": {
"@jridgewell/gen-mapping": "^0.3.5",
"@jridgewell/trace-mapping": "^0.3.25"
@@ -1747,6 +1747,7 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.1.tgz",
"integrity": "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==",
"license": "Apache-2.0",
"peer": true,
"engines": {
"node": ">=8.0.0"
}
@@ -1768,6 +1769,7 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.10.0.tgz",
"integrity": "sha512-/wNZ8twnEQQA4HoHu22+vcsdru6pWPWxW+7w+FlxT6Id7PE/WIbZmVKkte+PF72e0F2dnImFeHD2syyE1Mw6MQ==",
"license": "Apache-2.0",
"peer": true,
"dependencies": {
"@opentelemetry/semantic-conventions": "^1.29.0"
},
@@ -1783,6 +1785,7 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation/-/instrumentation-0.220.0.tgz",
"integrity": "sha512-xQx3E2WxP1mDvKzxLxX+CTCtNLa560YJZ3087qYHerl2YmiKpv7AH+dAy7vmx+eVrZ5BwhfWUAVoKOoxCNHcpw==",
"license": "Apache-2.0",
"peer": true,
"dependencies": {
"@opentelemetry/api-logs": "0.220.0",
"import-in-the-middle": "^3.0.0",
@@ -1833,6 +1836,7 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-2.10.0.tgz",
"integrity": "sha512-GuYQQT7QD2EeO8lcZLRQzcbOyhqAzL+6WWTKTU9mSUBYBazkEDl+VrQcXQhbB08OWM9anD1aHleVadzulpOaUQ==",
"license": "Apache-2.0",
"peer": true,
"dependencies": {
"@opentelemetry/core": "2.10.0",
"@opentelemetry/resources": "2.10.0",
@@ -2236,6 +2240,7 @@
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",
"integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -3778,6 +3783,7 @@
"integrity": "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==",
"devOptional": true,
"license": "MIT",
"peer": true,
"dependencies": {
"csstype": "^3.2.2"
}
@@ -3850,6 +3856,7 @@
"integrity": "sha512-XZzOmihLIr8AD1b9hL9ccNMzEMWt/dE2u7NyTY9jJG6YNiNthaD5XtUHVF2uCXZ15ng+z2hT3MVuxnUYhq6k1g==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@typescript-eslint/scope-manager": "8.57.0",
"@typescript-eslint/types": "8.57.0",
@@ -4499,7 +4506,6 @@
"resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.14.1.tgz",
"integrity": "sha512-nuBEDgQfm1ccRp/8bCQrx1frohyufl4JlbMMZ4P1wpeOfDhF6FQkxZJ1b/e+PLwr6X1Nhw6OLme5usuBWYBvuQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"@webassemblyjs/helper-numbers": "1.13.2",
"@webassemblyjs/helper-wasm-bytecode": "1.13.2"
@@ -4509,29 +4515,25 @@
"version": "1.13.2",
"resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.13.2.tgz",
"integrity": "sha512-6oXyTOzbKxGH4steLbLNOu71Oj+C8Lg34n6CqRvqfS2O71BxY6ByfMDRhBytzknj9yGUPVJ1qIKhRlAwO1AovA==",
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/@webassemblyjs/helper-api-error": {
"version": "1.13.2",
"resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.13.2.tgz",
"integrity": "sha512-U56GMYxy4ZQCbDZd6JuvvNV/WFildOjsaWD3Tzzvmw/mas3cXzRJPMjP83JqEsgSbyrmaGjBfDtV7KDXV9UzFQ==",
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/@webassemblyjs/helper-buffer": {
"version": "1.14.1",
"resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.14.1.tgz",
"integrity": "sha512-jyH7wtcHiKssDtFPRB+iQdxlDf96m0E39yb0k5uJVhFGleZFoNw1c4aeIcVUPPbXUVJ94wwnMOAqUHyzoEPVMA==",
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/@webassemblyjs/helper-numbers": {
"version": "1.13.2",
"resolved": "https://registry.npmjs.org/@webassemblyjs/helper-numbers/-/helper-numbers-1.13.2.tgz",
"integrity": "sha512-FE8aCmS5Q6eQYcV3gI35O4J789wlQA+7JrqTTpJqn5emA4U2hvwJmvFRC0HODS+3Ye6WioDklgd6scJ3+PLnEA==",
"license": "MIT",
"peer": true,
"dependencies": {
"@webassemblyjs/floating-point-hex-parser": "1.13.2",
"@webassemblyjs/helper-api-error": "1.13.2",
@@ -4542,15 +4544,13 @@
"version": "1.13.2",
"resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.13.2.tgz",
"integrity": "sha512-3QbLKy93F0EAIXLh0ogEVR6rOubA9AoZ+WRYhNbFyuB70j3dRdwH9g+qXhLAO0kiYGlg3TxDV+I4rQTr/YNXkA==",
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/@webassemblyjs/helper-wasm-section": {
"version": "1.14.1",
"resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.14.1.tgz",
"integrity": "sha512-ds5mXEqTJ6oxRoqjhWDU83OgzAYjwsCV8Lo/N+oRsNDmx/ZDpqalmrtgOMkHwxsG0iI//3BwWAErYRHtgn0dZw==",
"license": "MIT",
"peer": true,
"dependencies": {
"@webassemblyjs/ast": "1.14.1",
"@webassemblyjs/helper-buffer": "1.14.1",
@@ -4563,7 +4563,6 @@
"resolved": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.13.2.tgz",
"integrity": "sha512-4LtOzh58S/5lX4ITKxnAK2USuNEvpdVV9AlgGQb8rJDHaLeHciwG4zlGr0j/SNWlr7x3vO1lDEsuePvtcDNCkw==",
"license": "MIT",
"peer": true,
"dependencies": {
"@xtuc/ieee754": "^1.2.0"
}
@@ -4573,7 +4572,6 @@
"resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.13.2.tgz",
"integrity": "sha512-Lde1oNoIdzVzdkNEAWZ1dZ5orIbff80YPdHx20mrHwHrVNNTjNr8E3xz9BdpcGqRQbAEa+fkrCb+fRFTl/6sQw==",
"license": "Apache-2.0",
"peer": true,
"dependencies": {
"@xtuc/long": "4.2.2"
}
@@ -4582,15 +4580,13 @@
"version": "1.13.2",
"resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.13.2.tgz",
"integrity": "sha512-3NQWGjKTASY1xV5m7Hr0iPeXD9+RDobLll3T9d2AO+g3my8xy5peVyjSag4I50mR1bBSN/Ct12lo+R9tJk0NZQ==",
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/@webassemblyjs/wasm-edit": {
"version": "1.14.1",
"resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.14.1.tgz",
"integrity": "sha512-RNJUIQH/J8iA/1NzlE4N7KtyZNHi3w7at7hDjvRNm5rcUXa00z1vRz3glZoULfJ5mpvYhLybmVcwcjGrC1pRrQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"@webassemblyjs/ast": "1.14.1",
"@webassemblyjs/helper-buffer": "1.14.1",
@@ -4607,7 +4603,6 @@
"resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.14.1.tgz",
"integrity": "sha512-AmomSIjP8ZbfGQhumkNvgC33AY7qtMCXnN6bL2u2Js4gVCg8fp735aEiMSBbDR7UQIj90n4wKAFUSEd0QN2Ukg==",
"license": "MIT",
"peer": true,
"dependencies": {
"@webassemblyjs/ast": "1.14.1",
"@webassemblyjs/helper-wasm-bytecode": "1.13.2",
@@ -4621,7 +4616,6 @@
"resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.14.1.tgz",
"integrity": "sha512-PTcKLUNvBqnY2U6E5bdOQcSM+oVP/PmrDY9NzowJjislEjwP/C4an2303MCVS2Mg9d3AJpIGdUFIQQWbPds0Sw==",
"license": "MIT",
"peer": true,
"dependencies": {
"@webassemblyjs/ast": "1.14.1",
"@webassemblyjs/helper-buffer": "1.14.1",
@@ -4634,7 +4628,6 @@
"resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.14.1.tgz",
"integrity": "sha512-JLBl+KZ0R5qB7mCnud/yyX08jWFw5MsoalJ1pQ4EdFlgj9VdXKGuENGsiCIjegI1W7p91rUlcB/LB5yRJKNTcQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"@webassemblyjs/ast": "1.14.1",
"@webassemblyjs/helper-api-error": "1.13.2",
@@ -4649,7 +4642,6 @@
"resolved": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.14.1.tgz",
"integrity": "sha512-kPSSXE6De1XOR820C90RIo2ogvZG+c3KiHzqUoO/F34Y2shGzesfqv7o57xrxovZJH/MetF5UjroJ/R/3isoiw==",
"license": "MIT",
"peer": true,
"dependencies": {
"@webassemblyjs/ast": "1.14.1",
"@xtuc/long": "4.2.2"
@@ -4659,21 +4651,20 @@
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz",
"integrity": "sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==",
"license": "BSD-3-Clause",
"peer": true
"license": "BSD-3-Clause"
},
"node_modules/@xtuc/long": {
"version": "4.2.2",
"resolved": "https://registry.npmjs.org/@xtuc/long/-/long-4.2.2.tgz",
"integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==",
"license": "Apache-2.0",
"peer": true
"license": "Apache-2.0"
},
"node_modules/acorn": {
"version": "8.16.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz",
"integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==",
"license": "MIT",
"peer": true,
"bin": {
"acorn": "bin/acorn"
},
@@ -4725,7 +4716,6 @@
"resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-2.1.1.tgz",
"integrity": "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==",
"license": "MIT",
"peer": true,
"dependencies": {
"ajv": "^8.0.0"
},
@@ -4743,7 +4733,6 @@
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",
"integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",
"license": "MIT",
"peer": true,
"dependencies": {
"fast-deep-equal": "^3.1.3",
"fast-uri": "^3.0.1",
@@ -4759,8 +4748,7 @@
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
"integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/ansi-styles": {
"version": "4.3.0",
@@ -5041,6 +5029,7 @@
"integrity": "sha512-Ixm8tFfoKKIPYdCCKYTsqv+Fd4IJ0DQqMyEimo+pxUOMUR9cVPlwTrFt9Avu+3cb6Zp3mAzl+t1MrG2fxxKsxw==",
"devOptional": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/types": "^7.26.0"
}
@@ -5117,6 +5106,7 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"baseline-browser-mapping": "^2.9.0",
"caniuse-lite": "^1.0.30001759",
@@ -5135,8 +5125,7 @@
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/cac": {
"version": "6.7.14",
@@ -5296,7 +5285,6 @@
"resolved": "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-1.0.4.tgz",
"integrity": "sha512-rNjApaLzuwaOTjCiT8lSDdGN1APCiqkChLMJxJPWLunPAt5fy8xgU9/jNOchV84wfIxrA0lRQB7oCT8jrn/wrQ==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=6.0"
}
@@ -5358,8 +5346,7 @@
"version": "2.20.3",
"resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz",
"integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==",
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/commondir": {
"version": "1.0.1",
@@ -6057,6 +6044,7 @@
"integrity": "sha512-XoMjdBOwe/esVgEvLmNsD3IRHkm7fbKIUGvrleloJXUZgDHig2IPWNniv+GwjyJXzuNqVjlr5+4yVUZjycJwfQ==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@eslint-community/eslint-utils": "^4.8.0",
"@eslint-community/regexpp": "^4.12.1",
@@ -6242,6 +6230,7 @@
"integrity": "sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@rtsao/scc": "^1.1.0",
"array-includes": "^3.1.9",
@@ -6498,7 +6487,6 @@
"resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz",
"integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=0.8.x"
}
@@ -6588,8 +6576,7 @@
"url": "https://opencollective.com/fastify"
}
],
"license": "BSD-3-Clause",
"peer": true
"license": "BSD-3-Clause"
},
"node_modules/fastq": {
"version": "1.20.1",
@@ -7685,7 +7672,6 @@
"resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-27.5.1.tgz",
"integrity": "sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==",
"license": "MIT",
"peer": true,
"dependencies": {
"@types/node": "*",
"merge-stream": "^2.0.0",
@@ -7700,7 +7686,6 @@
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz",
"integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==",
"license": "MIT",
"peer": true,
"dependencies": {
"has-flag": "^4.0.0"
},
@@ -8213,8 +8198,7 @@
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz",
"integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==",
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/merge2": {
"version": "1.4.1",
@@ -8289,7 +8273,6 @@
"resolved": "https://registry.npmjs.org/minimizer-webpack-plugin/-/minimizer-webpack-plugin-5.8.0.tgz",
"integrity": "sha512-2cT9+goJfBhtMz+gJqejSf09ClgmYhPhccRb/fb0ztVbixt0BkO8mRuI26FoPPuUNkRk6iEDryWAIouc5W8eJA==",
"license": "MIT",
"peer": true,
"dependencies": {
"@jridgewell/trace-mapping": "^0.3.31",
"jest-worker": "^27.4.5",
@@ -8420,14 +8403,14 @@
"version": "2.6.2",
"resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz",
"integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==",
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/next": {
"version": "16.1.6",
"resolved": "https://registry.npmjs.org/next/-/next-16.1.6.tgz",
"integrity": "sha512-hkyRkcu5x/41KoqnROkfTm2pZVbKxvbZRuNvKXLRXxs3VfyO0WhY50TQS40EuKO9SW3rBj/sF3WbVwDACeMZyw==",
"license": "MIT",
"peer": true,
"dependencies": {
"@next/env": "16.1.6",
"@swc/helpers": "0.5.15",
@@ -8553,17 +8536,6 @@
}
}
},
"node_modules/next-intl/node_modules/@swc/helpers": {
"version": "0.5.23",
"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.23.tgz",
"integrity": "sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==",
"license": "Apache-2.0",
"optional": true,
"peer": true,
"dependencies": {
"tslib": "^2.8.0"
}
},
"node_modules/next/node_modules/postcss": {
"version": "8.4.31",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.31.tgz",
@@ -9087,6 +9059,7 @@
"resolved": "https://registry.npmjs.org/react/-/react-19.2.3.tgz",
"integrity": "sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=0.10.0"
}
@@ -9096,6 +9069,7 @@
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.3.tgz",
"integrity": "sha512-yELu4WmLPw5Mr/lmeEpox5rw3RETacE++JgHqQzd2dg+YbJuat3jH4ingc+WPZhxaoFzdv9y33G+F7Nl5O0GBg==",
"license": "MIT",
"peer": true,
"dependencies": {
"scheduler": "^0.27.0"
},
@@ -9108,6 +9082,7 @@
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.71.2.tgz",
"integrity": "sha512-1CHvcDYzuRUNOflt4MOq3ZM46AronNJtQ1S7tnX6YN4y72qhgiUItpacZUAQ0TyWYci3yz1X+rXaSxiuEm86PA==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=18.0.0"
},
@@ -9123,7 +9098,8 @@
"version": "16.13.1",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
"license": "MIT"
"license": "MIT",
"peer": true
},
"node_modules/react-qr-code": {
"version": "2.2.0",
@@ -9143,6 +9119,7 @@
"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.3.0.tgz",
"integrity": "sha512-KQopgqFo/p/fgmAs5qz6p5RWaNAzq40WAu7fJIXnQpYxFPbJYtsJPWvGeF2rOBaY/kEuV77AVsX8TsQzKm+A/g==",
"license": "MIT",
"peer": true,
"dependencies": {
"@types/use-sync-external-store": "^0.0.6",
"use-sync-external-store": "^1.4.0"
@@ -9195,7 +9172,8 @@
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz",
"integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==",
"license": "MIT"
"license": "MIT",
"peer": true
},
"node_modules/redux-thunk": {
"version": "3.1.0",
@@ -9262,7 +9240,6 @@
"resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
"integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=0.10.0"
}
@@ -9353,6 +9330,7 @@
"resolved": "https://registry.npmjs.org/rollup/-/rollup-4.63.1.tgz",
"integrity": "sha512-3Df9jsstwhccuEfmAMi9l8XUh/GOkVObmFTU7CCVBysEbcOZLl84jCtaAZMcPiMz2EGKsATzQcU+Xr3n/wU6cg==",
"license": "MIT",
"peer": true,
"dependencies": {
"@types/estree": "1.0.9"
},
@@ -9483,7 +9461,6 @@
"resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.3.3.tgz",
"integrity": "sha512-eflK8wEtyOE6+hsaRVPxvUKYCpRgzLqDTb8krvAsRIwOGlHoSgYLgBXoubGgLd2fT41/OUYdb48v4k4WWHQurA==",
"license": "MIT",
"peer": true,
"dependencies": {
"@types/json-schema": "^7.0.9",
"ajv": "^8.9.0",
@@ -9520,7 +9497,6 @@
"resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-5.1.0.tgz",
"integrity": "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw==",
"license": "MIT",
"peer": true,
"dependencies": {
"fast-deep-equal": "^3.1.3"
},
@@ -9532,8 +9508,7 @@
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
"integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/semver": {
"version": "6.3.1",
@@ -9790,7 +9765,6 @@
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
"integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
"license": "BSD-3-Clause",
"peer": true,
"engines": {
"node": ">=0.10.0"
}
@@ -9809,7 +9783,6 @@
"resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz",
"integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==",
"license": "MIT",
"peer": true,
"dependencies": {
"buffer-from": "^1.0.0",
"source-map": "^0.6.0"
@@ -10118,7 +10091,6 @@
"resolved": "https://registry.npmjs.org/terser/-/terser-5.51.2.tgz",
"integrity": "sha512-bWnjSNscmuI+GJze6ZupnHP8G/cTcsJF+bXCeQknk2SHQsgbNJnLrqiH9jZ2W4STPVXH2mDKKRX3iwPhc9Cn/Q==",
"license": "BSD-2-Clause",
"peer": true,
"dependencies": {
"@jridgewell/source-map": "^0.3.3",
"acorn": "^8.15.0",
@@ -10203,6 +10175,7 @@
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -10410,6 +10383,7 @@
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true,
"license": "Apache-2.0",
"peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@@ -10610,6 +10584,7 @@
"integrity": "sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"esbuild": "^0.27.0 || ^0.28.0",
"fdir": "^6.5.0",
@@ -10733,6 +10708,7 @@
"integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -10831,7 +10807,6 @@
"resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.5.2.tgz",
"integrity": "sha512-6i/00NBjP4yGPs+caKSyRfpTF/8Torsu0MOW3mMzIbhgISFder8i7xbqgHlLMwJrdiN8ndBV3UA1/AfzPSr+jg==",
"license": "MIT",
"peer": true,
"dependencies": {
"graceful-fs": "^4.1.2"
},
@@ -10850,7 +10825,6 @@
"resolved": "https://registry.npmjs.org/webpack/-/webpack-5.110.2.tgz",
"integrity": "sha512-TciLrfM7zgEjqGdY851HkirDsSPQgTFsWQpl9oHqMAMYsHhEC0bKjscvjpnz+pzx10hLC8qISApGrsnrCP4UtQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"@types/estree": "^1.0.8",
"@types/json-schema": "^7.0.15",
@@ -10893,7 +10867,6 @@
"resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-3.5.1.tgz",
"integrity": "sha512-jyuiGJdtvY434z5bUZrjz67v76/ePNvFZTp9Mdz29IlH4+GPsgyGjiv0fKI+M7BdkU6ADjulUcKAd3tUK3WlEw==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=10.13.0"
}
@@ -10903,7 +10876,6 @@
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",
"integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">= 0.6"
}
@@ -11101,6 +11073,7 @@
"resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz",
"integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",
"license": "MIT",
"peer": true,
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}

View File

@@ -0,0 +1,11 @@
import type { BillingCurrency } from '@/types/billing';
/** Append org currency name to a base label (e.g. "Amount" → "Amount (تومان)"). */
export function moneyFieldLabel(
baseLabel: string,
currency: BillingCurrency | null | undefined,
currencyName: (code: BillingCurrency) => string,
): string {
if (!currency) return baseLabel;
return `${baseLabel} (${currencyName(currency)})`;
}

View File

@@ -15,13 +15,19 @@ export type SheetLineGroup = {
label: string;
/** Prosthesis category code, used for the tab swatch; null for other groups. */
categoryCode: string | null;
/** Explicit tab swatch when there is no prosthesis category (e.g. outsourcing). */
swatchColor?: string | null;
rows: SheetLineRow[];
};
/** Matches the outsourcing tab label color in the fee schedule editor. */
export const OUTSOURCING_PRICES_SWATCH = '#0f766e';
/**
* One tab per catalog group so a schedule never becomes a long scroll:
* treatment types, then a tab per prosthesis category. Lab prices add an
* outsourcing tab. Lab commissions are one workflow-step tab.
* treatment types, then a tab per prosthesis category. Lab prices put
* outsourcing first, then prosthesis categories. Lab commissions are one
* workflow-step tab.
*/
export function buildSheetLineGroups(
catalog: BillingSheetCatalog,
@@ -80,16 +86,20 @@ export function buildSheetLineGroups(
}
if (kind === 'LAB_PRICE') {
const prosthesisGroups = [...groups];
groups.length = 0;
groups.push({
key: 'outsourcing-prices',
label: labels.outsourcingPrices,
categoryCode: null,
swatchColor: OUTSOURCING_PRICES_SWATCH,
rows: catalog.workflowSteps.map((row) => ({
catalogKind: 'LAB_WORKFLOW_STEP' as const,
code: row.code,
label: row.label,
})),
});
groups.push(...prosthesisGroups);
}
return withRows(groups);

View File

@@ -110,6 +110,11 @@ async function saveBrowserHandle(handle: FilePickerHandle): Promise<void> {
db.close();
}
/** Drop the remembered file so the next send asks for a database again. */
export async function forgetBrowserDatabase(): Promise<void> {
await clearBrowserHandle();
}
async function clearBrowserHandle(): Promise<void> {
cachedHandle = null;
if (typeof indexedDB === 'undefined') return;

View File

@@ -127,6 +127,67 @@ function seed(db: SqlDatabase): SqliteQuery {
return asQuery(db);
}
function seedSavedPair(
query: SqliteQuery,
workType: string,
material: string,
options: {
toothId?: string;
textual?: Array<{ name: string; value: string; dependent?: { name: string; value: string; kind: number } }>;
numeric?: Array<{ name: string; value: number; dependent?: { name: string; value: string; kind: number } }>;
color?: string;
} = {},
): void {
if (query.all('SELECT treatment_id FROM Treatment WHERE treatment_id = 900').length === 0) {
query.run(
`INSERT INTO Treatment (
treatment_id, practice_lab_id, practice_pr_id,
patient_lab_id, patient_practice_id, patient_patient_id,
t_date, flags, projectGUID, importedOrderId
) VALUES (900, 0, 1, 1, 1, 1, '2020-01-01', 16, 'donor-guid', 'donor-case')`,
);
}
query.run(
`INSERT INTO ToothWork (ToothId, flags, WorkTypeSN, MaterialSN, treatment_id) VALUES (?, 0, ?, ?, 900)`,
[options.toothId ?? '99', workType, material],
);
const toothWorkId = Number(query.all('SELECT last_insert_rowid()')[0]?.[0]);
for (const row of options.textual ?? []) {
query.run('INSERT INTO ToothWorkParameters (custom_wd_id, toothWork_id) VALUES (NULL, ?)', [toothWorkId]);
const id = Number(query.all('SELECT last_insert_rowid()')[0]?.[0]);
query.run('INSERT INTO TextualToothWorkParameter (id, ParameterSN, ValueSN) VALUES (?, ?, ?)', [id, row.name, row.value]);
if (row.dependent) {
query.run(
`INSERT INTO DependentToothWorkParameters
(parent_param_id, dep_param_string, dep_param_value_string, dep_param_kind)
VALUES (?, ?, ?, ?)`,
[id, row.dependent.name, row.dependent.value, row.dependent.kind],
);
}
}
for (const row of options.numeric ?? []) {
query.run('INSERT INTO ToothWorkParameters (custom_wd_id, toothWork_id) VALUES (NULL, ?)', [toothWorkId]);
const id = Number(query.all('SELECT last_insert_rowid()')[0]?.[0]);
query.run('INSERT INTO NumericToothWorkParameter (id, ParameterSN, value) VALUES (?, ?, ?)', [id, row.name, row.value]);
if (row.dependent) {
query.run(
`INSERT INTO DependentOnNumericToothWorkParameters
(parent_param_id, dep_param_string, dep_param_value_string, dep_param_kind)
VALUES (?, ?, ?, ?)`,
[id, row.dependent.name, row.dependent.value, row.dependent.kind],
);
}
}
if (options.color) {
query.run(
`INSERT INTO ValuedMaterialParameters
(PARAM_TYPE, ValueSN, MaterialSN, MaterialPropertySN, toothwork_id)
VALUES ('TEXTUAL', ?, ?, 'Color', ?)`,
[options.color, material, toothWorkId],
);
}
}
const options = { now: '2026-10-16T09:00:00.000Z', projectGuid: 'guid-1' };
function sampleCase(overrides: Partial<ExocadCaseInput> = {}): ExocadCaseInput {
@@ -147,9 +208,11 @@ describe('transferCaseToExocad', () => {
it('creates the clinic, patient, header, and tooth work', async () => {
const db = await openSql();
const query = seed(db);
seedSavedPair(query, 'AnatomicCrown', 'ZI');
const result = transferCaseToExocad(query, sampleCase(), options);
expect(result).toMatchObject({ treatmentId: 1, created: true, skipped: [] });
expect(result).toMatchObject({ created: true, skipped: [] });
expect(result.treatmentId).not.toBe(900);
expect(query.all('SELECT practice_id, name FROM clients WHERE name = ?', ['North Clinic'])).toEqual([
[2, 'North Clinic'],
]);
@@ -158,12 +221,21 @@ describe('transferCaseToExocad', () => {
).toEqual([[0, 2, 1, 'Ada', 'Lovelace', null]]);
expect(
query.all(
'SELECT practice_pr_id, patient_patient_id, t_Notes, t_duedate, projectGUID, importedOrderId, flags FROM Treatment',
'SELECT practice_pr_id, patient_patient_id, t_Notes, t_duedate, projectGUID, importedOrderId, flags FROM Treatment WHERE treatment_id = ?',
[result.treatmentId],
),
).toEqual([[2, 1, 'Dr Smith\nShade A2', '2026-10-20', 'guid-1', 'case-1', 0]]);
expect(query.all('SELECT ToothId, WorkTypeSN, MaterialSN FROM ToothWork')).toEqual([
['14', 'AnatomicCrown', 'ZI'],
]);
expect(
query.all('SELECT ToothId, WorkTypeSN, MaterialSN FROM ToothWork WHERE treatment_id = ?', [result.treatmentId]),
).toEqual([['14', 'AnatomicCrown', 'ZI']]);
expect(
query.all(
`SELECT COUNT(*) FROM ToothWorkParameters params
JOIN ToothWork work ON work.id = params.toothWork_id
WHERE work.treatment_id = ?`,
[result.treatmentId],
),
).toEqual([[0]]);
expect(query.all('SELECT name FROM clients WHERE practice_id = ?', [EXOCAD_MULTIDIE_PRACTICE_ID])).toEqual([
['MultiDiePractice'],
]);
@@ -173,6 +245,8 @@ describe('transferCaseToExocad', () => {
it('updates the same treatment and reuses the clinic and patient', async () => {
const db = await openSql();
const query = seed(db);
seedSavedPair(query, 'AnatomicCrown', 'ZI');
seedSavedPair(query, 'Coping', 'NP', { toothId: '98' });
transferCaseToExocad(query, sampleCase(), options);
const second = transferCaseToExocad(
query,
@@ -185,17 +259,32 @@ describe('transferCaseToExocad', () => {
{ now: '2026-10-17T09:00:00.000Z', projectGuid: 'guid-2' },
);
expect(second).toMatchObject({ treatmentId: 1, created: false, skipped: [] });
expect(second).toMatchObject({ created: false, skipped: [] });
expect(query.all('SELECT COUNT(*) FROM clients WHERE practice_id != ?', [EXOCAD_MULTIDIE_PRACTICE_ID])).toEqual([[2]]);
expect(query.all('SELECT COUNT(*) FROM patients WHERE lab_id = 0')).toEqual([[1]]);
expect(query.all('SELECT projectGUID, importedOrderId FROM Treatment')).toEqual([['guid-1', 'case-1']]);
expect(query.all('SELECT ToothId, WorkTypeSN, MaterialSN FROM ToothWork')).toEqual([['16', 'Coping', 'NP']]);
expect(
query.all('SELECT projectGUID, importedOrderId FROM Treatment WHERE treatment_id = ?', [second.treatmentId]),
).toEqual([['guid-1', 'case-1']]);
expect(
query.all('SELECT ToothId, WorkTypeSN, MaterialSN FROM ToothWork WHERE treatment_id = ?', [second.treatmentId]),
).toEqual([['16', 'Coping', 'NP']]);
db.close();
});
it('maps a pontic from the connected crown and skips the lines Exocad cannot take yet', async () => {
const db = await openSql();
const query = seed(db);
seedSavedPair(query, 'AnatomicCrown', 'GCER', {
toothId: '81',
numeric: [{ name: 'MinThickness', value: 0.2 }],
});
seedSavedPair(query, 'AnatomicCrown', 'GCER', {
toothId: '82',
textual: [{ name: 'PreparationType', value: 'Crown', dependent: { name: 'ScanAbutmentScan', value: 'false', kind: 0 } }],
numeric: [{ name: 'MinThickness', value: 0.5, dependent: { name: 'MinThicknessSpecial', value: '0', kind: 1 } }],
color: 'A1',
});
seedSavedPair(query, 'AnatomicPontic', 'GCER', { toothId: '83' });
const result = transferCaseToExocad(
query,
sampleCase({
@@ -205,6 +294,7 @@ describe('transferCaseToExocad', () => {
{ tooth: '14', prosthesisTypeCode: 'prefabricated_abutment' },
{ tooth: 'UA', prosthesisTypeCode: 'complete_denture' },
{ tooth: '21', prosthesisTypeCode: 'pontic' },
{ tooth: '15', prosthesisTypeCode: 'press_ceramic' },
],
}),
options,
@@ -214,15 +304,83 @@ describe('transferCaseToExocad', () => {
{ tooth: '14', prosthesisTypeCode: 'prefabricated_abutment', reason: 'unmapped' },
{ tooth: 'UA', prosthesisTypeCode: 'complete_denture', reason: 'arch' },
{ tooth: '21', prosthesisTypeCode: 'pontic', reason: 'pontic' },
{ tooth: '15', prosthesisTypeCode: 'press_ceramic', reason: 'unmapped' },
]);
expect(query.all('SELECT ToothId, WorkTypeSN, MaterialSN FROM ToothWork ORDER BY ToothId')).toEqual([
['13', 'AnatomicPontic', 'LS2'],
['14', 'AnatomicCrown', 'LS2'],
expect(
query.all(
'SELECT ToothId, WorkTypeSN, MaterialSN FROM ToothWork WHERE treatment_id = ? ORDER BY ToothId',
[result.treatmentId],
),
).toEqual([
['13', 'AnatomicPontic', 'GCER'],
['14', 'AnatomicCrown', 'GCER'],
]);
expect(query.all('SELECT t_Notes FROM Treatment WHERE treatment_id = ?', [result.treatmentId])).toEqual([
['Dr Smith\nShade A2\n14 prefabricated_abutment\nUA complete_denture\n21 pontic\n15 press_ceramic'],
]);
expect(
query.all(
`SELECT textual.ParameterSN, textual.ValueSN
FROM TextualToothWorkParameter textual
JOIN ToothWorkParameters params ON params.id = textual.id
JOIN ToothWork work ON work.id = params.toothWork_id
WHERE work.treatment_id = ? AND work.ToothId = '14'`,
[result.treatmentId],
),
).toEqual([['PreparationType', 'Crown']]);
expect(
query.all(
`SELECT numeric.ParameterSN, numeric.value
FROM NumericToothWorkParameter numeric
JOIN ToothWorkParameters params ON params.id = numeric.id
JOIN ToothWork work ON work.id = params.toothWork_id
WHERE work.treatment_id = ? AND work.ToothId = '14'`,
[result.treatmentId],
),
).toEqual([['MinThickness', 0.5]]);
expect(
query.all(
`SELECT dep.dep_param_string, dep.dep_param_value_string, dep.dep_param_kind
FROM DependentToothWorkParameters dep
JOIN TextualToothWorkParameter textual ON textual.id = dep.parent_param_id
JOIN ToothWorkParameters params ON params.id = textual.id
JOIN ToothWork work ON work.id = params.toothWork_id
WHERE work.treatment_id = ? AND work.ToothId = '14'`,
[result.treatmentId],
),
).toEqual([['ScanAbutmentScan', 'false', 0]]);
expect(
query.all(
`SELECT dep.dep_param_string, dep.dep_param_value_string, dep.dep_param_kind
FROM DependentOnNumericToothWorkParameters dep
JOIN NumericToothWorkParameter numeric ON numeric.id = dep.parent_param_id
JOIN ToothWorkParameters params ON params.id = numeric.id
JOIN ToothWork work ON work.id = params.toothWork_id
WHERE work.treatment_id = ? AND work.ToothId = '14'`,
[result.treatmentId],
),
).toEqual([['MinThicknessSpecial', '0', 1]]);
expect(
query.all(
`SELECT valued.ValueSN, valued.MaterialSN, valued.MaterialPropertySN
FROM ValuedMaterialParameters valued
JOIN ToothWork work ON work.id = valued.toothwork_id
WHERE work.treatment_id = ? AND work.ToothId = '14'`,
[result.treatmentId],
),
).toEqual([['A1', 'GCER', 'Color']]);
expect(
query.all(
`SELECT COUNT(*) FROM ToothWorkParameters params
JOIN ToothWork work ON work.id = params.toothWork_id
WHERE work.treatment_id = ? AND work.ToothId = '13'`,
[result.treatmentId],
),
).toEqual([[0]]);
db.close();
});
it('maps an older zirconia veneer', async () => {
it('leaves a material with no saved pair out of the tooth table', async () => {
const db = await openSql();
const query = seed(db);
const result = transferCaseToExocad(
@@ -231,9 +389,80 @@ describe('transferCaseToExocad', () => {
options,
);
expect(result.skipped).toEqual([]);
expect(query.all('SELECT ToothId, WorkTypeSN, MaterialSN FROM ToothWork')).toEqual([
['11', 'Veneer', 'ZI'],
expect(result.skipped).toEqual([{ tooth: '11', prosthesisTypeCode: 'veneer_zirconia', reason: 'unmapped' }]);
expect(query.all('SELECT ToothId FROM ToothWork WHERE treatment_id = ?', [result.treatmentId])).toEqual([]);
expect(query.all('SELECT t_Notes, projectGUID, importedOrderId FROM Treatment WHERE treatment_id = ?', [result.treatmentId])).toEqual([
['Dr Smith\nShade A2\n11 veneer_zirconia', 'guid-1', 'case-1'],
]);
db.close();
});
it('writes a saved veneer pair and keeps a PMMA color off a zirconia tooth', async () => {
const db = await openSql();
const query = seed(db);
seedSavedPair(query, 'Veneer', 'ZI', {
toothId: '71',
numeric: [{ name: 'MinThickness', value: 0.4 }],
color: 'A2',
});
seedSavedPair(query, 'AnatomicCrown', 'ZI', { toothId: '72', color: 'A1', numeric: [{ name: 'MinThickness', value: 0.5 }] });
seedSavedPair(query, 'AnatomicCrown', 'PMMA', { toothId: '73', color: 'A', numeric: [{ name: 'MinThickness', value: 0.3 }] });
const veneer = transferCaseToExocad(
query,
sampleCase({ caseId: 'veneer-case', teeth: [{ tooth: '11', prosthesisTypeCode: 'veneer_zirconia' }] }),
options,
);
expect(
query.all('SELECT WorkTypeSN, MaterialSN FROM ToothWork WHERE treatment_id = ?', [veneer.treatmentId]),
).toEqual([['Veneer', 'ZI']]);
expect(
query.all(
`SELECT ValueSN FROM ValuedMaterialParameters valued
JOIN ToothWork work ON work.id = valued.toothwork_id
WHERE work.treatment_id = ?`,
[veneer.treatmentId],
),
).toEqual([['A2']]);
const pmma = transferCaseToExocad(
query,
sampleCase({ caseId: 'pmma-case', teeth: [{ tooth: '12', prosthesisTypeCode: 'pmma' }] }),
{ ...options, projectGuid: 'guid-pmma' },
);
expect(
query.all(
`SELECT numeric.value, valued.ValueSN
FROM ToothWork work
JOIN ToothWorkParameters params ON params.toothWork_id = work.id
JOIN NumericToothWorkParameter numeric ON numeric.id = params.id
JOIN ValuedMaterialParameters valued ON valued.toothwork_id = work.id
WHERE work.treatment_id = ?`,
[pmma.treatmentId],
),
).toEqual([[0.3, 'A']]);
db.close();
});
it('does not invent a material for a name that does not name one', async () => {
const db = await openSql();
const query = seed(db);
seedSavedPair(query, 'AnatomicCrown', 'PMMA');
seedSavedPair(query, 'AnatomicCrown', 'LS2', { toothId: '97' });
const result = transferCaseToExocad(
query,
sampleCase({
teeth: [
{ tooth: '11', prosthesisTypeCode: 'temporary_resin_crown' },
{ tooth: '12', prosthesisTypeCode: 'veneer_layered' },
{ tooth: '13', prosthesisTypeCode: 'fiber_post_core' },
],
}),
options,
);
expect(query.all('SELECT ToothId FROM ToothWork WHERE treatment_id = ?', [result.treatmentId])).toEqual([]);
expect(query.all('SELECT t_Notes FROM Treatment WHERE treatment_id = ?', [result.treatmentId])).toEqual([
['Dr Smith\nShade A2\n11 temporary_resin_crown\n12 veneer_layered\n13 fiber_post_core'],
]);
db.close();
});
@@ -241,8 +470,9 @@ describe('transferCaseToExocad', () => {
it('uses the Default client when the case has no clinic name', async () => {
const db = await openSql();
const query = seed(db);
seedSavedPair(query, 'AnatomicCrown', 'ZI');
transferCaseToExocad(query, sampleCase({ clinicName: ' ' }), options);
expect(query.all('SELECT practice_pr_id FROM Treatment')).toEqual([[1]]);
expect(query.all("SELECT practice_pr_id FROM Treatment WHERE importedOrderId = 'case-1'")).toEqual([[1]]);
expect(query.all('SELECT COUNT(*) FROM clients')).toEqual([[2]]);
db.close();
});
@@ -253,4 +483,62 @@ describe('transferCaseToExocad', () => {
expect(() => transferCaseToExocad(query, sampleCase(), options)).toThrow(ExocadTransferError);
db.close();
});
it('copies the lab default material configuration onto a new treatment', async () => {
const db = await openSql();
const query = seed(db);
db.run('ALTER TABLE Treatment ADD COLUMN workParamsSHA TEXT');
db.run('ALTER TABLE Treatment ADD COLUMN workParamInfoId INT');
db.run('CREATE TABLE WorkParamsData (hash TEXT primary key, content BLOB)');
db.run(
`CREATE TABLE WorkParamsInfo (
id integer primary key autoincrement,
workParamsDataHash TEXT,
lastModificationDate DATETIME,
foreign key (workParamsDataHash) references WorkParamsData(hash)
)`,
);
db.run('CREATE TABLE WorkParamsInfoLocal (id INT primary key, fileName TEXT)');
db.run(`INSERT INTO WorkParamsData (hash, content) VALUES ('content-hash', x'00')`);
db.run(`INSERT INTO WorkParamsData (hash, content) VALUES ('endo-hash', x'01')`);
db.run(`INSERT INTO WorkParamsInfo (id, workParamsDataHash, lastModificationDate) VALUES (5, 'content-hash', '2024-09-27')`);
db.run(`INSERT INTO WorkParamsInfo (id, workParamsDataHash, lastModificationDate) VALUES (6, 'endo-hash', '2024-09-27')`);
db.run(`INSERT INTO WorkParamsInfoLocal (id, fileName) VALUES (5, 'D:\\config\\WorkParamsDB.xml')`);
db.run(`INSERT INTO WorkParamsInfoLocal (id, fileName) VALUES (6, 'D:\\config\\WorkParamsDB-EndoCrown.xml')`);
db.run(
`INSERT INTO Treatment (
treatment_id, practice_lab_id, practice_pr_id, patient_lab_id, patient_practice_id, patient_patient_id,
t_date, flags, projectGUID, importedOrderId, workParamsSHA, workParamInfoId
) VALUES (50, 0, 1, 1, 1, 1, '2026-01-01', 16, 'donor', 'donor-case', 'file-sha', 5)`,
);
db.run(
`INSERT INTO Treatment (
treatment_id, practice_lab_id, practice_pr_id, patient_lab_id, patient_practice_id, patient_patient_id,
t_date, flags, projectGUID, importedOrderId, workParamsSHA, workParamInfoId
) VALUES (60, 0, 1, 1, 1, 1, '2026-02-01', 16, 'endo', 'endo-case', 'endo-sha', 6)`,
);
transferCaseToExocad(query, sampleCase(), options);
const header = query.all(
'SELECT workParamsSHA, workParamInfoId, flags FROM Treatment WHERE importedOrderId = ?',
['case-1'],
);
const infoId = header[0]?.[1];
expect(header[0]?.[0]).toBe('file-sha');
expect(header[0]?.[2]).toBe(0);
expect(infoId).not.toBe(5);
expect(query.all('SELECT workParamsDataHash FROM WorkParamsInfo WHERE id = ?', [infoId as number])).toEqual([
['content-hash'],
]);
expect(query.all('SELECT fileName FROM WorkParamsInfoLocal WHERE id = ?', [infoId as number])).toEqual([
['D:\\config\\WorkParamsDB.xml'],
]);
transferCaseToExocad(query, sampleCase({ teeth: [{ tooth: '16', prosthesisTypeCode: 'pfm_crown' }] }), options);
expect(query.all('SELECT COUNT(*) FROM WorkParamsInfo')).toEqual([[3]]);
expect(
query.all('SELECT workParamInfoId FROM Treatment WHERE importedOrderId = ?', ['case-1']),
).toEqual([[infoId]]);
db.close();
});
});

View File

@@ -20,29 +20,24 @@ const REQUIRED_TABLES = [
'ValuedMaterialParameters',
] as const;
const RESTORATION: Record<string, { workType: string; material: string }> = {
/**
* Catalog codes with one obvious Exocad work type and material.
* A tooth is written only when the opened database already has that pair.
*/
const MATERIAL_MATCH: Record<string, { workType: string; material: string }> = {
monolithic_zirconia: { workType: 'AnatomicCrown', material: 'ZI' },
pfz_crown: { workType: 'AnatomicCrown', material: 'ZI' },
pfm_crown: { workType: 'Coping', material: 'NP' },
full_metal_crown: { workType: 'AnatomicCrown', material: 'NP' },
glass_ceramic_crown: { workType: 'AnatomicCrown', material: 'LS2' },
press_ceramic: { workType: 'AnatomicCrown', material: 'LS2' },
glass_ceramic_crown: { workType: 'AnatomicCrown', material: 'GCER' },
pmma: { workType: 'AnatomicCrown', material: 'PMMA' },
temporary_resin_crown: { workType: 'AnatomicCrown', material: 'PMMA' },
press_ceramic: { workType: 'AnatomicCrown', material: 'LS2' },
peek_crown: { workType: 'AnatomicCrown', material: 'PEEK' },
veneer_full_contour: { workType: 'Veneer', material: 'LS2' },
veneer_layered: { workType: 'Veneer', material: 'LS2' },
inlay_full_contour: { workType: 'AnatomicInlay', material: 'LS2' },
inlay_layered: { workType: 'AnatomicInlay', material: 'LS2' },
onlay_full_contour: { workType: 'AnatomicInlay', material: 'LS2' },
onlay_layered: { workType: 'AnatomicInlay', material: 'LS2' },
overlay_full_contour: { workType: 'AnatomicInlay', material: 'LS2' },
overlay_layered: { workType: 'AnatomicInlay', material: 'LS2' },
veneer_zirconia: { workType: 'Veneer', material: 'ZI' },
veneer_ips_press: { workType: 'Veneer', material: 'LS2' },
veneer_ips_cad: { workType: 'Veneer', material: 'LS2' },
zirconia_overlay: { workType: 'AnatomicInlay', material: 'ZI' },
ips_overlay: { workType: 'AnatomicInlay', material: 'LS2' },
ips_overlay: { workType: 'OverlayCrown', material: 'LS2' },
};
export class ExocadTransferError extends Error {
@@ -107,8 +102,9 @@ export function exocadDueDate(value: string | null | undefined): string | null {
return match ? match[1] : null;
}
function buildNotes(dentistName: string, comment: string): string | null {
function buildNotes(dentistName: string, comment: string, skipped: ExocadSkippedLine[]): string | null {
const parts = [dentistName.trim(), comment.trim()].filter((part) => part.length > 0);
for (const line of skipped) parts.push(`${line.tooth} ${line.prosthesisTypeCode}`);
return parts.length > 0 ? parts.join('\n') : null;
}
@@ -121,11 +117,15 @@ function isFdiTooth(tooth: string): boolean {
return /^\d{1,2}$/.test(tooth.trim());
}
function planTeeth(jobs: ExocadToothJob[]): { writes: ToothWrite[]; skipped: ExocadSkippedLine[] } {
function pairExists(db: SqliteQuery, workType: string, material: string): boolean {
return db.all('SELECT id FROM ToothWork WHERE WorkTypeSN = ? AND MaterialSN = ? LIMIT 1', [workType, material]).length > 0;
}
function planTeeth(db: SqliteQuery, jobs: ExocadToothJob[]): { writes: ToothWrite[]; skipped: ExocadSkippedLine[] } {
const groupMaterial = new Map<string, string>();
for (const job of jobs) {
const group = job.selectionGroupId?.trim() ?? '';
const mapped = RESTORATION[job.prosthesisTypeCode];
const mapped = MATERIAL_MATCH[job.prosthesisTypeCode];
if (!group || !mapped || groupMaterial.has(group)) continue;
groupMaterial.set(group, mapped.material);
}
@@ -154,10 +154,14 @@ function planTeeth(jobs: ExocadToothJob[]): { writes: ToothWrite[]; skipped: Exo
continue;
}
const restoration = group.find((job) => RESTORATION[job.prosthesisTypeCode]);
const restoration = group.find((job) => MATERIAL_MATCH[job.prosthesisTypeCode]);
if (restoration) {
const mapped = RESTORATION[restoration.prosthesisTypeCode];
writes.push({ toothId: tooth, workType: mapped.workType, material: mapped.material });
const mapped = MATERIAL_MATCH[restoration.prosthesisTypeCode];
if (pairExists(db, mapped.workType, mapped.material)) {
writes.push({ toothId: tooth, workType: mapped.workType, material: mapped.material });
} else {
skipped.push({ tooth, prosthesisTypeCode: restoration.prosthesisTypeCode, reason: 'unmapped' });
}
for (const job of group) {
if (job === restoration) continue;
skipped.push({ tooth, prosthesisTypeCode: job.prosthesisTypeCode, reason: 'unmapped' });
@@ -168,10 +172,10 @@ function planTeeth(jobs: ExocadToothJob[]): { writes: ToothWrite[]; skipped: Exo
const pontic = group.find((job) => job.prosthesisTypeCode === 'pontic');
if (pontic) {
const material = groupMaterial.get(pontic.selectionGroupId?.trim() ?? '') ?? '';
if (!material) {
skipped.push({ tooth, prosthesisTypeCode: pontic.prosthesisTypeCode, reason: 'pontic' });
} else {
if (material && pairExists(db, 'AnatomicPontic', material)) {
writes.push({ toothId: tooth, workType: 'AnatomicPontic', material });
} else {
skipped.push({ tooth, prosthesisTypeCode: pontic.prosthesisTypeCode, reason: material ? 'unmapped' : 'pontic' });
}
for (const job of group) {
if (job === pontic) continue;
@@ -198,6 +202,11 @@ function assertExocad(db: SqliteQuery): void {
if (lab.length === 0) throw new ExocadTransferError('NOT_EXOCAD');
}
/** Reject a SQLite file that is not a DentalDB database. Call this before remembering the file. */
export function assertExocadDatabase(db: SqliteQuery): void {
assertExocad(db);
}
function clientRows(db: SqliteQuery): Array<{ practiceId: number; name: string }> {
return db
.all(
@@ -310,23 +319,257 @@ function deleteToothWork(db: SqliteQuery, treatmentId: number): void {
db.run('DELETE FROM ToothWork WHERE treatment_id = ?', treatment);
}
function insertTeeth(db: SqliteQuery, treatmentId: number, writes: ToothWrite[]): void {
type DependentCopy = {
name: string | null;
value: string | null;
kind: number;
};
type ParameterCopy = {
customWdId: number | null;
name: string | null;
valueText: string | null;
valueNumber: number | null;
dependents: DependentCopy[];
};
type ColorCopy = {
paramType: string | null;
value: string | null;
material: string | null;
property: string | null;
};
type MaterialSnapshot = {
textual: ParameterCopy[];
numeric: ParameterCopy[];
colors: ColorCopy[];
};
function cellText(value: unknown): string | null {
if (value == null) return null;
return String(value);
}
function cellNumber(value: unknown): number | null {
if (value == null || value === '') return null;
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : null;
}
function pairKey(workType: string, material: string): string {
return `${workType}\0${material}`;
}
function readDependents(db: SqliteQuery, table: string, parentId: number): DependentCopy[] {
return db
.all(
`SELECT dep_param_string, dep_param_value_string, dep_param_kind FROM ${table} WHERE parent_param_id = ?`,
[parentId],
)
.map((row) => ({
name: cellText(row[0]),
value: cellText(row[1]),
kind: cellNumber(row[2]) ?? 0,
}));
}
/** Parameter and color rows from the fullest saved tooth of this work type and material. */
function readMaterialSnapshot(db: SqliteQuery, workType: string, material: string): MaterialSnapshot | null {
const donors = db.all(
`SELECT work.id
FROM ToothWork work
JOIN ToothWorkParameters params ON params.toothWork_id = work.id
WHERE work.WorkTypeSN = ? AND work.MaterialSN = ?
GROUP BY work.id
ORDER BY COUNT(params.id) DESC, work.id DESC
LIMIT 1`,
[workType, material],
);
const donorId = numberValue(donors[0]?.[0]);
if (!donorId) return null;
const textual = db
.all(
`SELECT params.custom_wd_id, textual.ParameterSN, textual.ValueSN, textual.id
FROM TextualToothWorkParameter textual
JOIN ToothWorkParameters params ON params.id = textual.id
WHERE params.toothWork_id = ?`,
[donorId],
)
.map((row) => ({
customWdId: cellNumber(row[0]),
name: cellText(row[1]),
valueText: cellText(row[2]),
valueNumber: null,
dependents: readDependents(db, 'DependentToothWorkParameters', numberValue(row[3])),
}));
const numeric = db
.all(
`SELECT params.custom_wd_id, numeric.ParameterSN, numeric.value, numeric.id
FROM NumericToothWorkParameter numeric
JOIN ToothWorkParameters params ON params.id = numeric.id
WHERE params.toothWork_id = ?`,
[donorId],
)
.map((row) => ({
customWdId: cellNumber(row[0]),
name: cellText(row[1]),
valueText: null,
valueNumber: cellNumber(row[2]),
dependents: readDependents(db, 'DependentOnNumericToothWorkParameters', numberValue(row[3])),
}));
const colors = db
.all(
`SELECT PARAM_TYPE, ValueSN, MaterialSN, MaterialPropertySN
FROM ValuedMaterialParameters WHERE toothwork_id = ?`,
[donorId],
)
.map((row) => ({
paramType: cellText(row[0]),
value: cellText(row[1]),
material: cellText(row[2]),
property: cellText(row[3]),
}));
return { textual, numeric, colors };
}
function materialSnapshots(db: SqliteQuery, writes: ToothWrite[]): Map<string, MaterialSnapshot | null> {
const snapshots = new Map<string, MaterialSnapshot | null>();
for (const write of writes) {
const key = pairKey(write.workType, write.material);
if (snapshots.has(key)) continue;
snapshots.set(key, readMaterialSnapshot(db, write.workType, write.material));
}
return snapshots;
}
function insertParameter(db: SqliteQuery, toothWorkId: number, row: ParameterCopy, kind: 'textual' | 'numeric'): void {
db.run('INSERT INTO ToothWorkParameters (custom_wd_id, toothWork_id) VALUES (?, ?)', [row.customWdId, toothWorkId]);
const id = numberValue(db.all('SELECT last_insert_rowid()')[0]?.[0]);
if (kind === 'textual') {
db.run('INSERT INTO TextualToothWorkParameter (id, ParameterSN, ValueSN) VALUES (?, ?, ?)', [
id,
row.name,
row.valueText,
]);
for (const dependent of row.dependents) {
db.run(
`INSERT INTO DependentToothWorkParameters
(parent_param_id, dep_param_string, dep_param_value_string, dep_param_kind)
VALUES (?, ?, ?, ?)`,
[id, dependent.name, dependent.value, dependent.kind],
);
}
return;
}
db.run('INSERT INTO NumericToothWorkParameter (id, ParameterSN, value) VALUES (?, ?, ?)', [
id,
row.name,
row.valueNumber,
]);
for (const dependent of row.dependents) {
db.run(
`INSERT INTO DependentOnNumericToothWorkParameters
(parent_param_id, dep_param_string, dep_param_value_string, dep_param_kind)
VALUES (?, ?, ?, ?)`,
[id, dependent.name, dependent.value, dependent.kind],
);
}
}
function applyMaterialSnapshot(db: SqliteQuery, toothWorkId: number, snapshot: MaterialSnapshot): void {
for (const row of snapshot.textual) insertParameter(db, toothWorkId, row, 'textual');
for (const row of snapshot.numeric) insertParameter(db, toothWorkId, row, 'numeric');
for (const color of snapshot.colors) {
db.run(
`INSERT INTO ValuedMaterialParameters
(PARAM_TYPE, ValueSN, MaterialSN, MaterialPropertySN, toothwork_id)
VALUES (?, ?, ?, ?, ?)`,
[color.paramType, color.value, color.material, color.property, toothWorkId],
);
}
}
function insertTeeth(
db: SqliteQuery,
treatmentId: number,
writes: ToothWrite[],
snapshots: Map<string, MaterialSnapshot | null>,
): void {
for (const row of writes) {
db.run(
`INSERT INTO ToothWork (ToothId, flags, WorkTypeSN, MaterialSN, treatment_id)
VALUES (?, 0, ?, ?, ?)`,
[row.toothId, row.workType, row.material, treatmentId],
);
const toothWorkId = numberValue(db.all('SELECT last_insert_rowid()')[0]?.[0]);
const snapshot = snapshots.get(pairKey(row.workType, row.material));
if (snapshot) applyMaterialSnapshot(db, toothWorkId, snapshot);
}
}
function treatmentHasColumn(db: SqliteQuery, column: string): boolean {
const rows = db.all('PRAGMA table_info(Treatment)');
return rows.some((row) => String(row[1] ?? '').toLowerCase() === column.toLowerCase());
}
/**
* Fill an empty workParamsSHA from the newest saved case whose file name ends
* with WorkParamsDB.xml, not WorkParamsDB-EndoCrown.xml. Exocad loads
* WorkParamsInfo by workParamInfoId. A null id is the read-only project warning
* and the tooth-click crash. Each saved case has its own info row.
*/
function embedMaterialConfiguration(db: SqliteQuery, treatmentId: number): void {
if (!treatmentHasColumn(db, 'workParamsSHA') || !treatmentHasColumn(db, 'workParamInfoId')) return;
const tables = db.all(`SELECT name FROM sqlite_master WHERE type = 'table'`);
const names = new Set(tables.map((row) => String(row[0] ?? '').toLowerCase()));
if (!names.has('workparamsinfo') || !names.has('workparamsinfolocal')) return;
const current = db.all(
'SELECT workParamsSHA, workParamInfoId FROM Treatment WHERE treatment_id = ?',
[treatmentId],
);
const currentSha = String(current[0]?.[0] ?? '').trim();
const currentInfo = numberValue(current[0]?.[1]);
if (currentSha && currentInfo > 0) return;
const donor = db.all(
`SELECT t.workParamsSHA, i.workParamsDataHash, i.lastModificationDate, l.fileName, t.workParamInfoId
FROM Treatment t
JOIN WorkParamsInfo i ON i.id = t.workParamInfoId
JOIN WorkParamsInfoLocal l ON l.id = i.id
WHERE t.treatment_id != ?
AND t.workParamsSHA IS NOT NULL
AND trim(t.workParamsSHA) != ''
AND l.fileName LIKE '%WorkParamsDB.xml'
ORDER BY t.treatment_id DESC
LIMIT 1`,
[treatmentId],
);
const source = donor[0];
if (!source || source[3] == null) return;
db.run(
`INSERT INTO WorkParamsInfo (workParamsDataHash, lastModificationDate) VALUES (?, ?)`,
[source[1] == null ? null : String(source[1]), source[2] == null ? null : String(source[2])],
);
const newId = numberValue(db.all('SELECT last_insert_rowid()')[0]?.[0]);
db.run('INSERT INTO WorkParamsInfoLocal (id, fileName) VALUES (?, ?)', [newId, String(source[3])]);
db.run(
'UPDATE Treatment SET workParamsSHA = ?, workParamInfoId = ? WHERE treatment_id = ?',
[String(source[0]), newId, treatmentId],
);
}
function writeCase(db: SqliteQuery, input: ExocadCaseInput, options: ExocadTransferOptions): ExocadTransferResult {
const practiceId = ensureClient(db, input.clinicName);
const patientId = ensurePatient(db, practiceId, input.patientFirstName, input.patientLastName);
const notes = buildNotes(input.dentistName, input.comment);
const due = exocadDueDate(input.dueDate);
const now = options.now ?? new Date().toISOString();
const { writes, skipped } = planTeeth(input.teeth);
const { writes, skipped } = planTeeth(db, input.teeth);
const notes = buildNotes(input.dentistName, input.comment, skipped);
const snapshots = materialSnapshots(db, writes);
const header = [
EXOCAD_LAB_ID,
practiceId,
@@ -355,7 +598,8 @@ function writeCase(db: SqliteQuery, input: ExocadCaseInput, options: ExocadTrans
[...header, treatmentId],
);
deleteToothWork(db, treatmentId);
insertTeeth(db, treatmentId, writes);
insertTeeth(db, treatmentId, writes, snapshots);
embedMaterialConfiguration(db, treatmentId);
return { treatmentId, created: false, skipped };
}
@@ -369,7 +613,8 @@ function writeCase(db: SqliteQuery, input: ExocadCaseInput, options: ExocadTrans
[...header, projectGuid, input.caseId],
);
const treatmentId = numberValue(db.all('SELECT last_insert_rowid()')[0]?.[0]);
insertTeeth(db, treatmentId, writes);
insertTeeth(db, treatmentId, writes, snapshots);
embedMaterialConfiguration(db, treatmentId);
return { treatmentId, created: true, skipped };
}

View File

@@ -7,7 +7,7 @@ type LocalDbTranslator = (key: string) => string;
export function localDbErrorText(
error: unknown,
t: LocalDbTranslator,
fallback: 'openFailed' | 'applyFailed',
fallback: 'openFailed' | 'applyFailed' | 'loadFailed',
): string {
if (error instanceof ExocadTransferError) return t('notExocad');
const message = error instanceof Error ? error.message : '';

View File

@@ -21,6 +21,8 @@ type Props = {
canEdit: boolean;
/** Optional control between search and dates (e.g. transaction type filter). */
middle?: ReactNode;
/** Replaces the default search input (same flex-1 slot). */
searchSlot?: ReactNode;
};
/** Shared Billing list chrome: search + optional middle + from/to + Add. */
@@ -36,6 +38,7 @@ export function BillingListToolbar({
onAdd,
canEdit,
middle,
searchSlot,
}: Props) {
const t = useTranslations('billing');
@@ -43,12 +46,14 @@ export function BillingListToolbar({
<div className="surface-card p-3 sm:p-4">
<div className="flex flex-col gap-3 sm:flex-row sm:items-center">
<div className="min-w-0 flex-1">
<Input
placeholder={searchPlaceholder}
value={search}
onChange={(e) => onSearchChange(e.target.value)}
icon={<Search className="h-4 w-4 icon-flat" />}
/>
{searchSlot ?? (
<Input
placeholder={searchPlaceholder}
value={search}
onChange={(e) => onSearchChange(e.target.value)}
icon={<Search className="h-4 w-4 icon-flat" />}
/>
)}
</div>
{middle}
<div className="flex w-full flex-wrap items-center gap-2 sm:w-auto">

View File

@@ -74,7 +74,6 @@ export function BillingPage() {
<BillingPaymentsPanel
canEdit={canEdit}
orgType={isLab ? 'LAB' : 'CLINIC'}
organizationId={currentOrganization?.id ?? ''}
initialFrom={initialFrom}
initialTo={initialTo}
/>

View File

@@ -1,31 +1,74 @@
'use client';
import { useState } from 'react';
import { useEffect, useId, useState, type ReactNode } from 'react';
import { OutlineFieldLabel } from '@/components/ui/shared/OutlineFieldLabel';
import type { BillingPartySearchResult } from '@/types/billing';
const INPUT_CLASS =
'mt-1 w-full rounded-[var(--radius-md)] border border-border bg-background-secondary/90 text-text-primary text-sm px-3 py-2 placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-primary/35';
export type BillingPartySectionKey = 'patients' | 'staff' | 'clinics' | 'labs';
export type BillingPartySelection = {
name: string;
id: string;
section: BillingPartySectionKey | null;
};
type Section = {
key: BillingPartySectionKey;
label: string;
items: Array<{ id: string; label: string; hint?: string }>;
};
export function BillingPartyCombobox({
name,
selectedId,
options,
sections,
placeholder,
onChange,
onQueryChange,
label,
labelPlacement = 'outline',
icon,
endIcon,
}: {
name: string;
selectedId: string;
options: Array<{ id: string; label: string; hint?: string }>;
sections: Section[];
placeholder: string;
onChange: (next: { name: string; id: string }) => void;
onChange: (next: BillingPartySelection) => void;
onQueryChange?: (query: string) => void;
/** When set with outline placement, sits on the top border like other billing fields. */
label?: string;
labelPlacement?: 'outline' | 'none';
icon?: ReactNode;
endIcon?: ReactNode;
}) {
const [open, setOpen] = useState(false);
const query = name.trim().toLowerCase();
const matches = options.filter((option) => !query || option.label.toLowerCase().includes(query));
const inputId = useId();
const outline = Boolean(label) && labelPlacement === 'outline';
useEffect(() => {
onQueryChange?.(name);
}, [name, onQueryChange]);
const flat = sections.flatMap((section) =>
section.items.map((item) => ({ ...item, section: section.key })),
);
return (
<div className="relative">
<div className="relative w-full">
{outline && label ? (
<OutlineFieldLabel htmlFor={inputId}>{label}</OutlineFieldLabel>
) : null}
{icon ? (
<div className="pointer-events-none absolute inset-y-0 start-0 z-[1] flex items-center ps-3 text-text-muted">
{icon}
</div>
) : null}
<input
className={INPUT_CLASS}
id={inputId}
className={`w-full rounded-[var(--radius-md)] border border-border text-text-primary text-base sm:text-sm py-2.5 sm:py-2 placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-primary/35 focus:border-border-strong ${
outline ? 'bg-background-card' : 'bg-background-secondary/90'
} ${icon ? 'ps-10' : 'ps-3'} ${endIcon ? 'pe-10' : 'pe-3'}`}
value={name}
placeholder={placeholder}
onFocus={() => setOpen(true)}
@@ -34,34 +77,105 @@ export function BillingPartyCombobox({
const next = event.target.value;
const trimmed = next.trim();
const exact = trimmed
? options.filter((option) => option.label.trim() === trimmed)
? flat.filter((option) => option.label.trim() === trimmed)
: [];
const kept = exact.find((option) => option.id === selectedId);
onChange({ name: next, id: (kept ?? exact[0])?.id ?? '' });
const hit = kept ?? exact[0];
onChange({
name: next,
id: hit?.id ?? '',
section: hit?.section ?? null,
});
}}
/>
{open && matches.length > 0 ? (
<ul className="absolute z-20 mt-1 max-h-52 w-full overflow-auto rounded-[var(--radius-md)] border border-border bg-background-card py-1 shadow-md">
{matches.map((option) => (
<li key={option.id}>
<button
type="button"
className="flex w-full items-center justify-between gap-2 px-3 py-2 text-start text-sm text-text-primary hover:bg-background-secondary"
onMouseDown={(event) => event.preventDefault()}
onClick={() => {
onChange({ name: option.label, id: option.id });
setOpen(false);
}}
>
<span className="min-w-0 truncate">{option.label}</span>
{option.hint ? (
<span className="shrink-0 text-xs text-text-muted">{option.hint}</span>
) : null}
</button>
</li>
))}
{endIcon ? (
<div className="pointer-events-none absolute inset-y-0 end-0 flex items-center pe-3 text-text-muted">
{endIcon}
</div>
) : null}
{open && sections.some((section) => section.items.length > 0) ? (
<ul className="absolute z-20 mt-1 max-h-64 w-full overflow-auto rounded-[var(--radius-md)] border border-border bg-background-card py-1 shadow-md">
{sections.map((section) =>
section.items.length === 0 ? null : (
<li key={section.key}>
<p className="px-3 py-1 text-[0.65rem] font-semibold uppercase tracking-wide text-text-muted">
{section.label}
</p>
<ul>
{section.items.map((option) => (
<li key={`${section.key}-${option.id}`}>
<button
type="button"
className="flex w-full items-center justify-between gap-2 px-3 py-2 text-start text-sm text-text-primary hover:bg-background-secondary"
onMouseDown={(event) => event.preventDefault()}
onClick={() => {
onChange({
name: option.label,
id: option.id,
section: section.key,
});
setOpen(false);
}}
>
<span className="min-w-0 truncate">{option.label}</span>
{option.hint ? (
<span className="shrink-0 text-xs text-text-muted">{option.hint}</span>
) : null}
</button>
</li>
))}
</ul>
</li>
),
)}
</ul>
) : null}
</div>
);
}
export function partySectionsFromSearch(
data: BillingPartySearchResult,
labels: {
patients: string;
staff: string;
clinics: string;
labs: string;
walkIn?: string;
},
): Section[] {
const sections: Section[] = [];
if (data.patients?.length) {
sections.push({
key: 'patients',
label: labels.patients,
items: data.patients.map((row) => ({
id: row.id,
label: row.name,
hint: row.isWalkIn ? labels.walkIn : undefined,
})),
});
}
if (data.staff?.length) {
sections.push({
key: 'staff',
label: labels.staff,
items: data.staff.map((row) => ({ id: row.id, label: row.name })),
});
}
if (data.clinics?.length) {
sections.push({
key: 'clinics',
label: labels.clinics,
items: data.clinics.map((row) => ({ id: row.id, label: row.name })),
});
}
if (data.labs?.length) {
sections.push({
key: 'labs',
label: labels.labs,
items: data.labs.map((row) => ({ id: row.id, label: row.name })),
});
}
return sections;
}

View File

@@ -2,7 +2,8 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslations } from 'next-intl';
import { Check, Paperclip, X } from 'lucide-react';
import { Check, Paperclip, Search, X } from 'lucide-react';
import { labBlockedBannerClass } from '@/components/treatment/treatmentStatusStyles';
import { Button } from '@/components/ui/shared/Button';
import { Card } from '@/components/ui/shared/Card';
import { Input } from '@/components/ui/shared/Input';
@@ -14,67 +15,56 @@ import {
BILLING_FILTER_SELECT_CLASS,
BillingListToolbar,
} from '@/components/ui/billing/BillingListToolbar';
import { BillingPartyCombobox } from '@/components/ui/billing/BillingPartyCombobox';
import {
BillingPartyCombobox,
partySectionsFromSearch,
type BillingPartySectionKey,
} from '@/components/ui/billing/BillingPartyCombobox';
import { TableIconButton } from '@/components/ui/shared/TableIconButton';
import { FORM_SELECT_TALL_CLASS } from '@/components/shared/formSelectStyles';
import { moneyFieldLabel } from '@/components/billing/moneyFieldLabel';
import { billingApi } from '@/lib/api/billing';
import { getUserFacingError } from '@/components/shared/formatApiError';
import { useToast } from '@/lib/hooks/useToast';
import { useAppFormatters } from '@/lib/hooks/useAppFormatters';
import { usePatientSearchQuery } from '@/lib/hooks/usePatientSearchQuery';
import { useBillingCurrency } from '@/lib/hooks/useBillingCurrency';
import { parseAppMoney } from '@/lib/i18n/format';
import { stripTrailingDecimalZeros } from '@/lib/i18n/moneyInputFormat';
import type {
AllocationCaseHit,
AllocationTreatmentHit,
BillingNamedOrg,
BillingCurrency,
BillingLedgerRow,
BillingPartyKind,
CashTransactionType,
PartnerPayment,
PatientPayment,
PaymentAcknowledgement,
} from '@/types/billing';
import type { Patient } from '@/types/patient';
type DraftAlloc = { targetId: string; label: string; amount: string };
function patientPartyLabel(patient: Patient): string {
return `${patient.firstName} ${patient.lastName}`.trim();
}
function solePartyMatch<T>(items: readonly T[], labelOf: (item: T) => string, typed: string): T | null {
const trimmed = typed.trim();
if (!trimmed) return null;
const matches = items.filter((item) => labelOf(item).trim() === trimmed);
return matches.length === 1 ? matches[0] : null;
}
type LedgerRow = {
id: string;
kind: 'patient' | 'partner';
type: CashTransactionType;
partyName: string;
amount: string;
paidAt: string;
attachments: string;
acknowledgement: PaymentAcknowledgement;
canAcknowledge: boolean;
recordedByViewer: boolean;
};
type TypeFilter = 'ALL' | CashTransactionType;
type SelectedParty = {
id: string;
name: string;
section: BillingPartySectionKey;
};
type Props = {
canEdit: boolean;
orgType: 'CLINIC' | 'LAB';
organizationId: string;
initialFrom?: string;
initialTo?: string;
};
function sectionToPartyKind(section: BillingPartySectionKey): BillingPartyKind {
if (section === 'patients') return 'patient';
if (section === 'staff') return 'staff';
return 'org';
}
export function BillingPaymentsPanel({
canEdit,
orgType,
organizationId,
initialFrom,
initialTo,
}: Props) {
@@ -83,24 +73,41 @@ export function BillingPaymentsPanel({
const tErrors = useTranslations('errors');
const toast = useToast();
const { formatDateTime, formatMoney } = useAppFormatters();
const { settings: currencySettings, reload: reloadCurrency } = useBillingCurrency(true);
const isClinic = orgType === 'CLINIC';
const currencyName = useCallback(
(code: BillingCurrency) => tCommon(`currencyName.${code}` as 'currencyName.TOMAN'),
[tCommon],
);
const amountLabel = moneyFieldLabel(t('amount'), currencySettings.currency, currencyName);
const [loading, setLoading] = useState(true);
const [query, setQuery] = useState('');
const [filterParty, setFilterParty] = useState<SelectedParty | null>(null);
const [typeFilter, setTypeFilter] = useState<TypeFilter>('ALL');
const [from, setFrom] = useState(initialFrom ?? '');
const [to, setTo] = useState(initialTo ?? '');
const [patientRows, setPatientRows] = useState<PatientPayment[]>([]);
const [partnerRows, setPartnerRows] = useState<PartnerPayment[]>([]);
const [partners, setPartners] = useState<BillingNamedOrg[]>([]);
const [rows, setRows] = useState<BillingLedgerRow[]>([]);
const [net, setNet] = useState<string | null>(null);
const [formOpen, setFormOpen] = useState(false);
const [txnType, setTxnType] = useState<CashTransactionType>('RECEIPT');
const [amount, setAmount] = useState('');
const [note, setNote] = useState('');
const [selectedPatient, setSelectedPatient] = useState<Patient | null>(null);
const [partyName, setPartyName] = useState('');
const [counterpartId, setCounterpartId] = useState('');
const [selectedParty, setSelectedParty] = useState<SelectedParty | null>(null);
const [partySections, setPartySections] = useState(
partySectionsFromSearch({}, {
patients: t('partySectionPatients'),
staff: t('partySectionStaff'),
clinics: t('partySectionClinics'),
labs: t('partySectionLabs'),
walkIn: t('walkInPatient'),
}),
);
const [filterSections, setFilterSections] = useState(partySections);
const [currencyPick, setCurrencyPick] = useState<BillingCurrency | ''>('');
const [ackBusyId, setAckBusyId] = useState<string | null>(null);
const [attachOpen, setAttachOpen] = useState(false);
const [allocSearch, setAllocSearch] = useState('');
@@ -110,55 +117,36 @@ export function BillingPaymentsPanel({
const [allocations, setAllocations] = useState<DraftAlloc[]>([]);
const [saving, setSaving] = useState(false);
const clinicReceipt = isClinic && txnType === 'RECEIPT';
const partyReady = clinicReceipt ? Boolean(selectedPatient) : Boolean(counterpartId);
const { setSearch: setPatientSearch, patients: patientHits } = usePatientSearchQuery(
formOpen && clinicReceipt,
{ includeWalkIn: true },
);
useEffect(() => {
if (!clinicReceipt) return;
const match = solePartyMatch(patientHits, patientPartyLabel, partyName);
if (match && match.id !== selectedPatient?.id) setSelectedPatient(match);
}, [clinicReceipt, partyName, patientHits, selectedPatient?.id]);
const patientSelected = selectedParty?.section === 'patients';
const staffSelected = selectedParty?.section === 'staff';
const orgSelected =
selectedParty?.section === 'clinics' || selectedParty?.section === 'labs';
const canAttach = patientSelected || orgSelected;
const showCurrencyPicker = !currencySettings.currencyLocked;
const filters = useMemo(
() => ({
q: query.trim() || undefined,
q: filterParty ? undefined : query.trim() || undefined,
from: from || undefined,
to: to || undefined,
partyKind: filterParty ? sectionToPartyKind(filterParty.section) : undefined,
partyId: filterParty?.id,
}),
[from, query, to],
[filterParty, from, query, to],
);
const load = useCallback(async () => {
setLoading(true);
try {
if (isClinic) {
const [payRes, partnerRes, orgsRes] = await Promise.all([
billingApi.listPatientPayments(filters),
billingApi.listPartnerPayments(filters),
billingApi.listPartners(),
]);
setPatientRows(payRes.data);
setPartnerRows(partnerRes.data);
setPartners(orgsRes.data);
} else {
const [payRes, orgsRes] = await Promise.all([
billingApi.listPartnerPayments(filters),
billingApi.listPartners(),
]);
setPartnerRows(payRes.data);
setPartners(orgsRes.data);
setPatientRows([]);
}
const res = await billingApi.listTransactions(filters);
setRows(res.data);
setNet(res.net);
} catch (error: unknown) {
toast.showError(getUserFacingError(error, tErrors, t('errorLoadPayments')));
} finally {
setLoading(false);
}
}, [filters, isClinic, t, tErrors, toast]);
}, [filters, t, tErrors, toast]);
useEffect(() => {
const handle = window.setTimeout(() => {
@@ -167,6 +155,79 @@ export function BillingPaymentsPanel({
return () => window.clearTimeout(handle);
}, [load]);
useEffect(() => {
if (!formOpen) return;
const handle = window.setTimeout(() => {
void (async () => {
try {
const res = await billingApi.searchParties({
q: partyName.trim() || undefined,
txnType,
});
setPartySections(
partySectionsFromSearch(res.data, {
patients: t('partySectionPatients'),
staff: t('partySectionStaff'),
clinics: t('partySectionClinics'),
labs: t('partySectionLabs'),
walkIn: t('walkInPatient'),
}),
);
} catch {
setPartySections([]);
}
})();
}, 250);
return () => window.clearTimeout(handle);
}, [formOpen, partyName, t, txnType]);
useEffect(() => {
const handle = window.setTimeout(() => {
void (async () => {
try {
const res = await billingApi.searchParties({
q: query.trim() || undefined,
txnType: 'RECEIPT',
});
const receipt = partySectionsFromSearch(res.data, {
patients: t('partySectionPatients'),
staff: t('partySectionStaff'),
clinics: t('partySectionClinics'),
labs: t('partySectionLabs'),
walkIn: t('walkInPatient'),
});
const payRes = await billingApi.searchParties({
q: query.trim() || undefined,
txnType: 'PAYMENT',
});
const payment = partySectionsFromSearch(payRes.data, {
patients: t('partySectionPatients'),
staff: t('partySectionStaff'),
clinics: t('partySectionClinics'),
labs: t('partySectionLabs'),
walkIn: t('walkInPatient'),
});
const merged = new Map<string, (typeof receipt)[number]>();
for (const section of [...receipt, ...payment]) {
const existing = merged.get(section.key);
if (!existing) {
merged.set(section.key, section);
continue;
}
const ids = new Set(existing.items.map((item) => item.id));
for (const item of section.items) {
if (!ids.has(item.id)) existing.items.push(item);
}
}
setFilterSections([...merged.values()]);
} catch {
setFilterSections([]);
}
})();
}, 250);
return () => window.clearTimeout(handle);
}, [query, t]);
useEffect(() => {
if (!formOpen || !attachOpen) {
setAllocHits([]);
@@ -175,14 +236,10 @@ export function BillingPaymentsPanel({
const handle = window.setTimeout(() => {
void (async () => {
try {
if (clinicReceipt) {
if (!selectedPatient) {
setAllocHits([]);
return;
}
if (patientSelected && selectedParty) {
const res = await billingApi.searchTreatments({
q: allocSearch.trim() || undefined,
patientId: selectedPatient.id,
patientId: selectedParty.id,
});
setAllocHits(
res.data.map((row: AllocationTreatmentHit) => ({
@@ -191,12 +248,10 @@ export function BillingPaymentsPanel({
billed: row.billedAmount,
})),
);
} else if (!counterpartId) {
setAllocHits([]);
} else {
} else if (orgSelected && selectedParty) {
const res = await billingApi.searchCases({
q: allocSearch.trim() || undefined,
counterpartOrganizationId: counterpartId,
counterpartOrganizationId: selectedParty.id,
});
setAllocHits(
res.data.map((row: AllocationCaseHit) => ({
@@ -205,6 +260,8 @@ export function BillingPaymentsPanel({
billed: row.billedAmount,
})),
);
} else {
setAllocHits([]);
}
} catch {
setAllocHits([]);
@@ -212,16 +269,15 @@ export function BillingPaymentsPanel({
})();
}, 250);
return () => window.clearTimeout(handle);
}, [allocSearch, attachOpen, clinicReceipt, counterpartId, formOpen, selectedPatient]);
}, [allocSearch, attachOpen, formOpen, orgSelected, patientSelected, selectedParty]);
function resetForm() {
setTxnType('RECEIPT');
setAmount('');
setNote('');
setSelectedPatient(null);
setPatientSearch('');
setPartyName('');
setCounterpartId('');
setSelectedParty(null);
setCurrencyPick('');
setAttachOpen(false);
setAllocSearch('');
setAllocHits([]);
@@ -240,61 +296,11 @@ export function BillingPaymentsPanel({
]);
}
async function handleCreate() {
const parsedAmount = parseAppMoney(amount);
if (!parsedAmount) {
toast.showError(t('invalidPrice'));
return;
}
const typedParty = partyName.trim();
const matchedPatient = clinicReceipt
? solePartyMatch(patientHits, patientPartyLabel, typedParty) ?? selectedPatient
: null;
const matchedOrgId = clinicReceipt
? ''
: solePartyMatch(partners, (org) => org.name, typedParty)?.id ?? counterpartId;
if (clinicReceipt && !matchedPatient && !typedParty) {
toast.showError(t('selectPatient'));
return;
}
if (!clinicReceipt && !matchedOrgId && !typedParty) {
toast.showError(isClinic ? t('selectLab') : t('selectClinic'));
return;
}
const localParty = clinicReceipt ? !matchedPatient : !matchedOrgId;
const body = {
type: txnType,
amount: parsedAmount,
note: note.trim() || undefined,
patientId: clinicReceipt ? matchedPatient?.id : undefined,
counterpartOrganizationId: clinicReceipt ? undefined : matchedOrgId || undefined,
externalPartyName: localParty ? typedParty : undefined,
allocations: localParty
? []
: allocations
.map((row) => {
const parsed = parseAppMoney(row.amount);
if (!parsed) return null;
return { targetId: row.targetId, amount: parsed };
})
.filter((row): row is { targetId: string; amount: string } => Boolean(row)),
};
setSaving(true);
try {
if (clinicReceipt) {
await billingApi.createPatientPayment(body);
} else {
await billingApi.createPartnerPayment(body);
}
toast.showSuccess(t('paymentSaved'));
resetForm();
setFormOpen(false);
await load();
} catch (error: unknown) {
toast.showError(getUserFacingError(error, tErrors, t('errorSavePayment')));
} finally {
setSaving(false);
function partyLabel(): string {
if (txnType === 'RECEIPT') {
return isClinic ? t('selectPartyReceiptClinic') : t('selectPartner');
}
return t('selectPartyPayment');
}
async function acknowledge(id: string, decision: 'ACCEPT' | 'DECLINE') {
@@ -309,62 +315,94 @@ export function BillingPaymentsPanel({
}
}
const partyOptions = clinicReceipt
? patientHits.map((patient) => ({
id: patient.id,
label: patientPartyLabel(patient),
hint: patient.isWalkIn ? t('walkInPatient') : undefined,
}))
: partners.map((org) => ({ id: org.id, label: org.name }));
const rows = useMemo(() => {
const receipts: LedgerRow[] = patientRows.map((row) => ({
id: row.id,
kind: 'patient',
type: 'RECEIPT',
partyName: row.patientIsWalkIn ? `${row.patientName} · ${t('walkInPatient')}` : row.patientName,
amount: row.amount,
paidAt: row.paidAt,
attachments:
row.allocations.length === 0
? t('unallocated')
: row.allocations.map((item) => item.treatmentTitle).join(', '),
acknowledgement: 'none',
canAcknowledge: false,
recordedByViewer: true,
}));
const partner: LedgerRow[] = partnerRows.map((row) => {
const type: CashTransactionType =
row.fromOrganizationId === organizationId ? 'PAYMENT' : 'RECEIPT';
return {
id: row.id,
kind: 'partner',
type,
partyName: type === 'RECEIPT' ? row.fromOrganizationName : row.toOrganizationName,
amount: row.amount,
paidAt: row.paidAt,
attachments:
row.allocations.length === 0
? t('unallocated')
: row.allocations.map((item) => item.caseLabel).join(', '),
acknowledgement: row.acknowledgement,
canAcknowledge: row.canAcknowledge,
recordedByViewer: row.recordedByViewer,
};
});
const merged = [...receipts, ...partner].sort((a, b) => b.paidAt.localeCompare(a.paidAt));
if (typeFilter === 'ALL') return merged;
return merged.filter((row) => row.type === typeFilter);
}, [organizationId, partnerRows, patientRows, t, typeFilter]);
const visibleRows = useMemo(() => {
if (typeFilter === 'ALL') return rows;
return rows.filter((row) => row.type === typeFilter);
}, [rows, typeFilter]);
const filterSelectClass = `${FORM_SELECT_TALL_CLASS} w-full min-w-0 rounded-md`;
const empty = rows.length === 0;
const empty = visibleRows.length === 0;
const netNumber = net == null ? null : Number(net);
const netTone =
netNumber == null
? ''
: netNumber > 0
? 'text-emerald-700 dark:text-emerald-400'
: netNumber < 0
? 'text-amber-800 dark:text-amber-300'
: 'text-text-secondary';
async function submitCreate() {
const parsedAmount = parseAppMoney(amount);
if (!parsedAmount) {
toast.showError(t('invalidAmount'));
return;
}
const typedParty = partyName.trim();
if (!selectedParty && !typedParty) {
toast.showError(t('selectParty'));
return;
}
if (showCurrencyPicker && !currencyPick) {
toast.showError(t('currencyRequired'));
return;
}
const localParty = !selectedParty;
const body = {
type: txnType,
amount: parsedAmount,
note: note.trim() || undefined,
currency: showCurrencyPicker && currencyPick ? currencyPick : undefined,
patientId: patientSelected ? selectedParty!.id : undefined,
counterpartOrganizationId: orgSelected ? selectedParty!.id : undefined,
userId: staffSelected ? selectedParty!.id : undefined,
externalPartyName: localParty ? typedParty : undefined,
allocations:
localParty || staffSelected
? []
: allocations
.map((row) => {
const parsed = parseAppMoney(row.amount);
if (!parsed) return null;
return { targetId: row.targetId, amount: parsed };
})
.filter((row): row is { targetId: string; amount: string } => Boolean(row)),
};
setSaving(true);
try {
if (staffSelected) {
await billingApi.createStaffPayment(body);
} else if (patientSelected || (isClinic && txnType === 'RECEIPT' && localParty)) {
await billingApi.createPatientPayment(body);
} else if (orgSelected || localParty) {
await billingApi.createPartnerPayment(body);
} else {
toast.showError(t('selectParty'));
setSaving(false);
return;
}
toast.showSuccess(t('paymentSaved'));
resetForm();
setFormOpen(false);
await reloadCurrency();
await load();
} catch (error: unknown) {
toast.showError(getUserFacingError(error, tErrors, t('errorSavePayment')));
} finally {
setSaving(false);
}
}
return (
<div className="space-y-4">
<BillingListToolbar
search={query}
onSearchChange={setQuery}
onSearchChange={(next) => {
setQuery(next);
if (filterParty && filterParty.name !== next) setFilterParty(null);
}}
searchPlaceholder={t('searchPayments')}
from={from}
to={to}
@@ -373,6 +411,23 @@ export function BillingPaymentsPanel({
addLabel={t('addTransaction')}
onAdd={() => setFormOpen(true)}
canEdit={canEdit}
searchSlot={
<BillingPartyCombobox
name={filterParty?.name ?? query}
selectedId={filterParty?.id ?? ''}
sections={filterSections}
placeholder={t('searchPayments')}
icon={<Search className="h-4 w-4 icon-flat" />}
onChange={({ name, id, section }) => {
setQuery(name);
if (id && section) {
setFilterParty({ id, name, section });
} else {
setFilterParty(null);
}
}}
/>
}
middle={
<select
className={BILLING_FILTER_SELECT_CLASS}
@@ -388,10 +443,29 @@ export function BillingPaymentsPanel({
/>
{formOpen && canEdit ? (
<Card className="space-y-3">
<Card className="space-y-5">
<p className="text-sm font-medium text-text-primary">{t('addTransaction')}</p>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
{showCurrencyPicker ? (
<div className="space-y-2 pb-1">
<p className={labBlockedBannerClass}>{t('currencyLockWarning')}</p>
<div className="relative">
<OutlineFieldLabel>{t('currency')}</OutlineFieldLabel>
<select
className={filterSelectClass}
value={currencyPick}
onChange={(e) => setCurrencyPick(e.target.value as BillingCurrency | '')}
>
<option value="">{t('currencyPlaceholder')}</option>
<option value="TOMAN">{tCommon('currencyName.TOMAN')}</option>
<option value="DOLLAR">{tCommon('currencyName.DOLLAR')}</option>
<option value="EURO">{tCommon('currencyName.EURO')}</option>
</select>
</div>
</div>
) : null}
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<div className="relative">
<OutlineFieldLabel>{t('type')}</OutlineFieldLabel>
<select
@@ -399,10 +473,8 @@ export function BillingPaymentsPanel({
value={txnType}
onChange={(e) => {
setTxnType(e.target.value as CashTransactionType);
setSelectedPatient(null);
setSelectedParty(null);
setPartyName('');
setPatientSearch('');
setCounterpartId('');
setAllocations([]);
setAttachOpen(false);
}}
@@ -412,7 +484,7 @@ export function BillingPaymentsPanel({
</select>
</div>
<AppMoneyInput
label={t('price')}
label={amountLabel}
labelPlacement="outline"
value={amount}
onChange={setAmount}
@@ -421,36 +493,28 @@ export function BillingPaymentsPanel({
<div className="flex items-center gap-2">
<div className="min-w-0 flex-1">
<div className="relative">
<OutlineFieldLabel>
{clinicReceipt ? t('selectPatient') : isClinic ? t('selectLab') : t('selectClinic')}
</OutlineFieldLabel>
<BillingPartyCombobox
name={partyName}
selectedId={clinicReceipt ? selectedPatient?.id ?? '' : counterpartId}
options={partyOptions}
placeholder={t('partySearch')}
onChange={({ name, id }) => {
setPartyName(name);
setAllocations([]);
if (clinicReceipt) {
setPatientSearch(name);
const hit = patientHits.find((patient) => patient.id === id) ?? null;
setSelectedPatient(
hit ?? (id && selectedPatient?.id === id ? selectedPatient : null),
);
return;
}
setCounterpartId(id);
}}
/>
</div>
<BillingPartyCombobox
name={partyName}
selectedId={selectedParty?.id ?? ''}
sections={partySections}
label={partyLabel()}
placeholder={t('partySearch')}
onChange={({ name, id, section }) => {
setPartyName(name);
setAllocations([]);
if (id && section) {
setSelectedParty({ id, name, section });
} else {
setSelectedParty(null);
}
}}
/>
</div>
<button
type="button"
aria-label={t('attach')}
title={t('attach')}
disabled={!partyReady}
disabled={!canAttach}
onClick={() => setAttachOpen((open) => !open)}
className={`inline-flex h-[2.625rem] w-[2.625rem] shrink-0 items-center justify-center rounded-md border sm:h-9 sm:w-9 ${
attachOpen
@@ -471,10 +535,10 @@ export function BillingPaymentsPanel({
maxLength={500}
/>
{attachOpen && partyReady ? (
{attachOpen && canAttach ? (
<div className="space-y-2 rounded-[var(--radius-md)] border border-border/60 p-3">
<Input
label={clinicReceipt ? t('attachTreatments') : t('attachCases')}
label={patientSelected ? t('attachTreatments') : t('attachCases')}
labelPlacement="outline"
value={allocSearch}
onChange={(e) => setAllocSearch(e.target.value)}
@@ -530,7 +594,7 @@ export function BillingPaymentsPanel({
<div className="flex flex-col-reverse gap-2 sm:flex-row sm:items-center">
<Button
variant="primary"
onClick={() => void handleCreate()}
onClick={() => void submitCreate()}
isLoading={saving}
fullWidth
className="sm:w-auto"
@@ -562,73 +626,111 @@ export function BillingPaymentsPanel({
<p className="text-sm text-text-muted">{t('noPayments')}</p>
</Card>
) : (
<Table
className="table-fixed"
headers={
<tr>
<th className={`w-1/5 ${TABLE_HEADER_CELL_CLASS}`}>{t('party')}</th>
<th className={`w-1/5 ${TABLE_HEADER_CELL_CLASS}`}>{t('type')}</th>
<th className={`w-1/5 ${TABLE_HEADER_CELL_CLASS}`}>{t('price')}</th>
<th className={`w-1/5 ${TABLE_HEADER_CELL_CLASS}`}>{t('time')}</th>
<th className={`w-1/5 ${TABLE_HEADER_CELL_CLASS}`}>{t('attachments')}</th>
</tr>
}
body={rows.map((row) => (
<tr
key={`${row.kind}-${row.id}`}
className={
row.acknowledgement === 'pending' && !row.recordedByViewer
? 'bg-primary-soft/40'
: undefined
}
>
<td className="truncate text-sm font-medium text-text-primary" title={row.partyName}>
{row.partyName}
</td>
<td className="align-middle">
<div className="flex items-center gap-1">
<Badge variant={row.type === 'RECEIPT' ? 'success' : 'warning'}>
{row.type === 'RECEIPT' ? t('receipt') : t('payment')}
</Badge>
{row.acknowledgement === 'pending' && row.recordedByViewer ? (
<span className="text-xs text-text-muted">{t('paymentPending')}</span>
) : null}
{row.acknowledgement === 'rejected' && row.recordedByViewer ? (
<span className="text-xs text-text-muted">{t('paymentDeclined')}</span>
) : null}
{canEdit && row.canAcknowledge ? (
<>
<TableIconButton
label={t('acceptPayment')}
disabled={ackBusyId !== null}
onClick={() => void acknowledge(row.id, 'ACCEPT')}
>
<Check className="h-4 w-4" />
</TableIconButton>
<TableIconButton
tone="danger"
label={t('declinePayment')}
disabled={ackBusyId !== null}
onClick={() => void acknowledge(row.id, 'DECLINE')}
>
<X className="h-4 w-4" />
</TableIconButton>
</>
) : null}
</div>
</td>
<td className="truncate text-sm tabular-nums text-text-primary">
{formatMoney(row.amount)}
</td>
<td className="truncate text-sm text-text-secondary" title={formatDateTime(row.paidAt)}>
{formatDateTime(row.paidAt)}
</td>
<td className="truncate text-sm text-text-secondary" title={row.attachments}>
{row.attachments}
</td>
</tr>
))}
/>
<>
<Table
className="table-fixed"
headers={
<tr>
<th className={`w-1/5 ${TABLE_HEADER_CELL_CLASS}`}>{t('party')}</th>
<th className={`w-1/5 ${TABLE_HEADER_CELL_CLASS}`}>{t('type')}</th>
<th className={`w-1/5 ${TABLE_HEADER_CELL_CLASS}`}>{amountLabel}</th>
<th className={`w-1/5 ${TABLE_HEADER_CELL_CLASS}`}>{t('time')}</th>
<th className={`w-1/5 ${TABLE_HEADER_CELL_CLASS}`}>{t('attachments')}</th>
</tr>
}
body={visibleRows.map((row) => (
<tr
key={`${row.kind}-${row.id}`}
className={
row.acknowledgement === 'pending' && !row.recordedByViewer
? 'bg-primary-soft/40'
: undefined
}
>
<td
className="truncate text-sm font-medium text-text-primary"
title={
row.partyIsWalkIn
? `${row.partyName} · ${t('walkInPatient')}`
: row.partyName
}
>
{row.partyIsWalkIn
? `${row.partyName} · ${t('walkInPatient')}`
: row.partyName}
</td>
<td className="align-middle">
<div className="flex items-center gap-1">
<Badge variant={row.type === 'RECEIPT' ? 'success' : 'warning'}>
{row.type === 'RECEIPT' ? t('receipt') : t('payment')}
</Badge>
{row.acknowledgement === 'pending' && row.recordedByViewer ? (
<span className="text-xs text-text-muted">{t('paymentPending')}</span>
) : null}
{row.acknowledgement === 'rejected' && row.recordedByViewer ? (
<span className="text-xs text-text-muted">{t('paymentDeclined')}</span>
) : null}
{canEdit && row.canAcknowledge ? (
<>
<TableIconButton
label={t('acceptPayment')}
disabled={ackBusyId !== null}
onClick={() => void acknowledge(row.id, 'ACCEPT')}
>
<Check className="h-4 w-4" />
</TableIconButton>
<TableIconButton
tone="danger"
label={t('declinePayment')}
disabled={ackBusyId !== null}
onClick={() => void acknowledge(row.id, 'DECLINE')}
>
<X className="h-4 w-4" />
</TableIconButton>
</>
) : null}
</div>
</td>
<td className="truncate text-sm tabular-nums text-text-primary">
{formatMoney(row.amount)}
</td>
<td
className="truncate text-sm text-text-secondary"
title={formatDateTime(row.paidAt)}
>
{formatDateTime(row.paidAt)}
</td>
<td
className="truncate text-sm text-text-secondary"
title={
row.attachments.length === 0
? t('unallocated')
: row.attachments.join(', ')
}
>
{row.attachments.length === 0
? t('unallocated')
: row.attachments.join(', ')}
</td>
</tr>
))}
/>
{filterParty && net != null ? (
<p className={`text-sm font-medium tabular-nums ${netTone}`}>
{t('ledgerNet', {
amount: formatMoney(net),
currency: currencySettings.currency
? currencyName(currencySettings.currency)
: '',
})}
{netNumber != null && netNumber > 0
? ` · ${t('ledgerNetCredit')}`
: netNumber != null && netNumber < 0
? ` · ${t('ledgerNetDebt')}`
: ''}
</p>
) : null}
</>
)}
</div>
</div>

View File

@@ -19,6 +19,7 @@ import {
} from '@/components/billing/billingSheetKind';
import {
buildSheetLineGroups,
OUTSOURCING_PRICES_SWATCH,
sheetLineRows,
type SheetLineGroup,
type SheetLineRow,
@@ -28,8 +29,11 @@ import {
isBillingAmountInput,
toBillingAmountString,
} from '@/components/billing/sheetAmount';
import { moneyFieldLabel } from '@/components/billing/moneyFieldLabel';
import { useBillingCurrency } from '@/lib/hooks/useBillingCurrency';
import { stripTrailingDecimalZeros } from '@/lib/i18n/moneyInputFormat';
import type {
BillingCurrency,
BillingSheet,
BillingSheetCatalog,
BillingSheetKind,
@@ -62,6 +66,12 @@ export function BillingSheetEditor({
}: Props) {
const t = useTranslations('billing');
const tCommon = useTranslations('common');
const { settings: currencySettings } = useBillingCurrency(true);
const amountLabel = moneyFieldLabel(
t('amount'),
currencySettings.currency,
(code: BillingCurrency) => tCommon(`currencyName.${code}` as 'currencyName.TOMAN'),
);
const commission = isCommissionSheetKind(kind);
const toClinics = sheetTargetsClinics(kind);
@@ -264,7 +274,7 @@ export function BillingSheetEditor({
>
<LineLabel row={row} catalog={catalog} />
<div className="flex shrink-0 items-center gap-1.5">
<span className="shrink-0 whitespace-nowrap text-xs text-text-muted">{t('price')}</span>
<span className="shrink-0 whitespace-nowrap text-xs text-text-muted">{amountLabel}</span>
<div className="w-28">
<AppMoneyInput
id={key}
@@ -306,9 +316,34 @@ function GroupTab({
active: boolean;
onSelect: () => void;
}) {
const swatch = group.categoryCode
const isOutsourcing = group.key === 'outsourcing-prices';
const categorySwatch = group.categoryCode
? prosthesisCategoryFamilyColor(group.categoryCode, 1)
: null;
if (isOutsourcing) {
const swatch = active ? (group.swatchColor ?? OUTSOURCING_PRICES_SWATCH) : 'currentColor';
return (
<button
type="button"
onClick={onSelect}
className={`inline-flex items-center gap-2 rounded-[var(--radius-sm)] border px-3 py-1.5 text-xs font-medium sm:text-sm ${
active
? 'bg-primary-soft border-primary/50'
: 'text-text-secondary border-border/40 hover:bg-background-card/70 hover:border-border'
}`}
style={active ? { color: group.swatchColor ?? OUTSOURCING_PRICES_SWATCH } : undefined}
>
<span
className="h-2.5 w-2.5 shrink-0 rounded-full border"
style={{ backgroundColor: swatch, borderColor: 'rgba(0, 0, 0, 0.18)' }}
aria-hidden
/>
{group.label}
</button>
);
}
return (
<button
type="button"
@@ -319,10 +354,10 @@ function GroupTab({
: 'text-text-secondary border-border/40 hover:bg-background-card/70 hover:border-border'
}`}
>
{swatch ? (
{categorySwatch ? (
<span
className="h-2.5 w-2.5 rounded-full border"
style={{ backgroundColor: swatch, borderColor: 'rgba(0, 0, 0, 0.18)' }}
style={{ backgroundColor: categorySwatch, borderColor: 'rgba(0, 0, 0, 0.18)' }}
aria-hidden
/>
) : null}

View File

@@ -27,7 +27,7 @@ import {
} from '@/components/lab/caseDetailUtils';
import { downloadCaseSheetPdf } from '@/components/lab/caseSheetPdf';
import { browserCanWriteLocalFile } from '@/components/local-db/browserFile';
import type { ExocadCaseInput } from '@/components/local-db/exocadTransfer';
import { ExocadTransferError, type ExocadCaseInput } from '@/components/local-db/exocadTransfer';
import { localDbErrorText } from '@/components/local-db/localDbErrors';
import { useLocalDbSession } from '@/components/ui/local-db/LocalDbSessionProvider';
import type { CaseSheetOrientation } from '@/components/ui/lab/CaseSheetPrintLayout';
@@ -40,6 +40,9 @@ import { forgetKnownCaseFile, withKnownCaseFiles } from '@/lib/uploads/caseUploa
import { ConnectedSelectionBadge } from '@/components/ui/treatment/ConnectedSelectionBadge';
import { useToast } from '@/lib/hooks/useToast';
import { formatAppMoney } from '@/lib/i18n/format';
import { moneyFieldLabel } from '@/components/billing/moneyFieldLabel';
import { useBillingCurrency } from '@/lib/hooks/useBillingCurrency';
import type { BillingCurrency } from '@/types/billing';
import {
CASE_TASK_SCOPE,
LINE_TASK_SCOPE,
@@ -293,6 +296,12 @@ export function CaseDetailPanel({
const tErrors = useTranslations('errors');
const tCommon = useTranslations('common');
const intlLocale = useLocale();
const { settings: currencySettings } = useBillingCurrency(true);
const billedLeadLabel = moneyFieldLabel(
t('billedLead'),
currencySettings.currency,
(code: BillingCurrency) => tCommon(`currencyName.${code}` as 'currencyName.TOMAN'),
);
const messages = useMessages();
const toast = useToast();
const localDb = useLocalDbSession();
@@ -434,6 +443,7 @@ export function CaseDetailPanel({
try {
result = localDb.transferCase(toExocadCase(labCase));
} catch (caught) {
if (caught instanceof ExocadTransferError) await localDb.abandon();
toast.showError(localDbErrorText(caught, tLocal, 'applyFailed'));
return;
}
@@ -575,13 +585,9 @@ export function CaseDetailPanel({
) : null}
{labCase.billedAmount != null || labCase.calculatedAmount != null ? (
<p className="text-xs text-text-secondary sm:text-sm">
<span className="font-bold text-text-primary">{t('billedLead')}</span>
{' '}
{t('billedCurrencyNote')}
<span className="font-bold text-text-primary">{billedLeadLabel}</span>
{' : '}
{formatAppMoney(labCase.billedAmount ?? labCase.calculatedAmount, intlLocale)}
{' '}
{t('billedCurrencySuffix')}
</p>
) : null}
</div>

View File

@@ -8,6 +8,7 @@ import {
openWithBrowserPicker,
type DatabaseSink,
} from '@/components/local-db/browserFile';
import { localDbErrorText } from '@/components/local-db/localDbErrors';
type LocalDbOpenControlsProps = {
onOpened: (sink: DatabaseSink) => Promise<void>;
@@ -30,8 +31,8 @@ export function LocalDbOpenControls({ onOpened }: LocalDbOpenControlsProps) {
}
try {
await onOpened(sink);
} catch {
setError(t('loadFailed'));
} catch (caught) {
setError(localDbErrorText(caught, t, 'loadFailed'));
}
}

View File

@@ -10,10 +10,16 @@ import {
useState,
type ReactNode,
} from 'react';
import { transferCaseToExocad, type ExocadCaseInput, type ExocadTransferResult } from '@/components/local-db/exocadTransfer';
import {
assertExocadDatabase,
transferCaseToExocad,
type ExocadCaseInput,
type ExocadTransferResult,
} from '@/components/local-db/exocadTransfer';
import {
browserCanWriteLocalFile,
browserDatabaseStillExists,
forgetBrowserDatabase,
preloadBrowserHandle,
reopenStoredBrowserFile,
type DatabaseSink,
@@ -23,12 +29,14 @@ import { LocalDbConnectDialog } from '@/components/ui/local-db/LocalDbConnectDia
/**
* Open Exocad database for Send to Exocad.
* Chrome and Edge only. The browser remembers the file handle.
* The next send reopens that file when it still exists. A missing file shows Browse again.
* Chrome and Edge only. The browser remembers the file handle after the DentalDB check.
* The next send reopens that file when it still exists. A missing or rejected file shows Browse again.
*/
export type LocalDbSessionValue = {
apply: () => Promise<void>;
/** Forget the open file after it is rejected, so the next send can browse again. */
abandon: () => Promise<void>;
requestConnection: () => Promise<boolean>;
transferCase: (input: ExocadCaseInput) => ExocadTransferResult;
};
@@ -66,6 +74,12 @@ export function LocalDbSessionProvider({ children }: { children: ReactNode }) {
const replaceWithSink = useCallback(async (sink: DatabaseSink) => {
const next = await LocalSqlite.open(sink.bytes);
try {
next.execute((query) => assertExocadDatabase(query));
} catch (error) {
next.close();
throw error;
}
try {
await sink.remember?.();
} catch {
@@ -76,6 +90,11 @@ export function LocalDbSessionProvider({ children }: { children: ReactNode }) {
sinkRef.current = sink;
}, []);
const abandon = useCallback(async () => {
dropSession();
await forgetBrowserDatabase();
}, [dropSession]);
const apply = useCallback(async () => {
const session = sessionRef.current;
const sink = sinkRef.current;
@@ -111,7 +130,8 @@ export function LocalDbSessionProvider({ children }: { children: ReactNode }) {
return true;
}
} catch {
// The file dialog is the fallback when the saved file cannot be read.
dropSession();
await forgetBrowserDatabase();
}
return await new Promise<boolean>((resolve) => {
connectResolveRef.current = resolve;
@@ -125,8 +145,8 @@ export function LocalDbSessionProvider({ children }: { children: ReactNode }) {
}, [dropSession, replaceWithSink]);
const value = useMemo<LocalDbSessionValue>(
() => ({ apply, requestConnection, transferCase }),
[apply, requestConnection, transferCase],
() => ({ apply, abandon, requestConnection, transferCase }),
[abandon, apply, requestConnection, transferCase],
);
return (

View File

@@ -20,6 +20,9 @@ import {
} from '@/components/treatment/treatmentDetailRules';
import { invalidPonticTeethOnDetail } from '@/components/treatment/prosthesisTree';
import { formatAppMoney } from '@/lib/i18n/format';
import { moneyFieldLabel } from '@/components/billing/moneyFieldLabel';
import { useBillingCurrency } from '@/lib/hooks/useBillingCurrency';
import type { BillingCurrency } from '@/types/billing';
import {
WORKSPACE_ACTION_BTN_CLASS,
WORKSPACE_ACTION_BTN_HEIGHT,
@@ -118,6 +121,15 @@ export function TreatmentDetailsEditor({
const t = useTranslations('treatment');
const tCommon = useTranslations('common');
const locale = useLocale();
const { settings: currencySettings } = useBillingCurrency(true);
const currencyName = (code: BillingCurrency) =>
tCommon(`currencyName.${code}` as 'currencyName.TOMAN');
const planTotalLabel = moneyFieldLabel(t('planTotal'), currencySettings.currency, currencyName);
const approvedAmountLabel = moneyFieldLabel(
t('approvedPrice'),
currencySettings.currency,
currencyName,
);
const notesRef = useRef<HTMLTextAreaElement>(null);
const activeDetail = details.find((d) => d.clientId === activeDetailId) ?? details[0];
@@ -177,14 +189,14 @@ export function TreatmentDetailsEditor({
<div>
<h3 className="text-sm font-semibold text-text-primary">{t('detailsTitle')}</h3>
<p className="text-xs text-text-muted mt-0.5">
{t('planTotal')}: {formatAppMoney(planTotal, locale)}
{planTotalLabel}: {formatAppMoney(planTotal, locale)}
</p>
</div>
<div className="flex flex-wrap items-center justify-end gap-2">
{showApprove ? (
<>
<div className="flex items-center gap-2 text-xs font-medium text-text-secondary">
<span className="whitespace-nowrap">{t('approvedPrice')}</span>
<span className="whitespace-nowrap">{approvedAmountLabel}</span>
<div className="w-28">
<AppMoneyInput
value={approvedAmount ?? ''}

View File

@@ -2,7 +2,10 @@ import { apiClient } from './client';
import type {
AllocationCaseHit,
AllocationTreatmentHit,
BillingCurrencySettings,
BillingLedgerRow,
BillingNamedOrg,
BillingPartySearchResult,
BillingSheet,
BillingSheetCatalog,
BillingSheetKind,
@@ -12,7 +15,9 @@ import type {
PatientPayment,
PaymentListQuery,
ResolvedBillingLines,
StaffPayment,
UpsertBillingSheetInput,
CashTransactionType,
} from '@/types/billing';
function paymentParams(query?: PaymentListQuery) {
@@ -21,6 +26,8 @@ function paymentParams(query?: PaymentListQuery) {
q: query.q || undefined,
from: query.from || undefined,
to: query.to || undefined,
partyKind: query.partyKind || undefined,
partyId: query.partyId || undefined,
};
}
@@ -78,6 +85,33 @@ export const billingApi = {
return response.data;
},
getSettings: async (): Promise<{ success: boolean; data: BillingCurrencySettings }> => {
const response = await apiClient.get('/billing/settings');
return response.data;
},
searchParties: async (params: {
q?: string;
txnType: CashTransactionType;
}): Promise<{ success: boolean; data: BillingPartySearchResult }> => {
const response = await apiClient.get('/billing/party-search', {
params: {
q: params.q || undefined,
txnType: params.txnType,
},
});
return response.data;
},
listTransactions: async (
query?: PaymentListQuery,
): Promise<{ success: boolean; data: BillingLedgerRow[]; net: string | null }> => {
const response = await apiClient.get('/billing/transactions', {
params: paymentParams(query),
});
return response.data;
},
getResolvedLines: async (params: {
kind: BillingSheetKind;
asOf: string;
@@ -146,6 +180,22 @@ export const billingApi = {
return response.data;
},
listStaffPayments: async (
query?: PaymentListQuery,
): Promise<{ success: boolean; data: StaffPayment[] }> => {
const response = await apiClient.get('/billing/staff-payments', {
params: paymentParams(query),
});
return response.data;
},
createStaffPayment: async (
body: CreatePaymentInput,
): Promise<{ success: boolean; data: StaffPayment }> => {
const response = await apiClient.post('/billing/staff-payments', body);
return response.data;
},
acknowledgePartnerPayment: async (
id: string,
decision: 'ACCEPT' | 'DECLINE',

View File

@@ -0,0 +1,39 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import { billingApi } from '@/lib/api/billing';
import type { BillingCurrencySettings } from '@/types/billing';
const DEFAULT: BillingCurrencySettings = {
currency: null,
currencyLocked: false,
currencySource: 'unset',
};
export function useBillingCurrency(enabled = true) {
const [settings, setSettings] = useState<BillingCurrencySettings>(DEFAULT);
const [loading, setLoading] = useState(enabled);
const reload = useCallback(async () => {
if (!enabled) {
setSettings(DEFAULT);
setLoading(false);
return;
}
setLoading(true);
try {
const res = await billingApi.getSettings();
setSettings(res.data);
} catch {
setSettings(DEFAULT);
} finally {
setLoading(false);
}
}, [enabled]);
useEffect(() => {
void reload();
}, [reload]);
return { settings, loading, reload };
}

View File

@@ -65,10 +65,45 @@ export type UpsertBillingSheetInput = {
export type PartnerPaymentStatus = 'PENDING' | 'CONFIRMED' | 'REJECTED';
export type CashTransactionType = 'RECEIPT' | 'PAYMENT';
export type BillingCurrency = 'TOMAN' | 'DOLLAR' | 'EURO';
export type BillingCurrencySource = 'set' | 'legacy_toman' | 'unset';
export type BillingCurrencySettings = {
currency: BillingCurrency | null;
currencyLocked: boolean;
currencySource: BillingCurrencySource;
};
export type BillingNamedOrg = {
id: string;
name: string;
type?: 'CLINIC' | 'LAB';
};
export type BillingPartyKind = 'patient' | 'staff' | 'org';
export type BillingPartyHit = {
id: string;
name: string;
isWalkIn?: boolean;
};
export type BillingPartySearchResult = {
patients?: BillingPartyHit[];
staff?: BillingPartyHit[];
clinics?: BillingPartyHit[];
labs?: BillingPartyHit[];
};
export type StaffPayment = {
id: string;
userId: string | null;
externalPartyName: string | null;
partyName: string;
amount: string;
paidAt: string;
note: string | null;
createdAt: string;
};
export type PatientPaymentAllocation = {
@@ -102,6 +137,21 @@ export type PartnerPaymentAllocation = {
export type PaymentAcknowledgement = 'pending' | 'accepted' | 'rejected' | 'none';
export type BillingLedgerRow = {
id: string;
kind: 'patient' | 'partner' | 'staff';
type: CashTransactionType;
partyName: string;
partyIsWalkIn: boolean;
amount: string;
paidAt: string;
note: string | null;
attachments: string[];
acknowledgement: PaymentAcknowledgement;
canAcknowledge: boolean;
recordedByViewer: boolean;
};
export type PartnerPayment = {
id: string;
amount: string;
@@ -126,6 +176,8 @@ export type PaymentListQuery = {
q?: string;
from?: string;
to?: string;
partyKind?: BillingPartyKind;
partyId?: string;
};
export type AllocationTreatmentHit = {
@@ -151,7 +203,9 @@ export type CreatePaymentInput = {
note?: string;
patientId?: string;
counterpartOrganizationId?: string;
userId?: string;
externalPartyName?: string;
currency?: BillingCurrency;
allocations?: Array<{ targetId: string; amount: string }>;
};