improvements: milling and sintering unified. Price calculation added to billing both for clinic sent and outsourced cases. pament confirmation added to billing flows.

This commit is contained in:
2026-10-16 16:16:42 +03:30
parent 1e4fcfd27f
commit 6972b9eaff
33 changed files with 1156 additions and 127 deletions

View File

@@ -9,8 +9,9 @@ alwaysApply: false
- 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 of the payment — do **not** filter by `recordedBy`. New rows are always `CONFIRMED` (no confirm/reject API).
- **Clinic transactions:** RECEIPT → patient cash; PAYMENT → linked lab. **Lab:** RECEIPT/PAYMENT → linked clinic only (no patient ledger).
- Money UI: `AppMoneyInput`; list chrome: `BillingListToolbar` + shared `Table` (`table-fixed`). Labels: **Price**, not Amount.
- **This publish:** hide Billing for CLINIC orgs via `HIDDEN_TAB_FEATURE_FLAGS.billingOrgTypes` (`hidden-tabs.ts`); lab keeps it.
- **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.
- 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

@@ -7,7 +7,7 @@ alwaysApply: false
# Lab Tasks
- **Default sort:** same as Cases — `labCaseTaskListedAtOrder` / `listedAt` desc (`COALESCE(startedAt, sentAt)`), then `sourceKey`, tooth, prosthesis type, step order, id. Do not sort `startedAt` then `sentAt`. `GET /tasks/locate-page` must use the exact same tuple. `sortBy=dueDate` tiebreaker is `listedAt` desc.
- **Grouping:** only when `sortBy=date`; flat list + hint for other sorts. One live plan renders scan → prosthesis sections → optional model pair → packing/shipping. `lineCount` stays 1 so “Line N” stays hidden. A type with both dry milling and sintering generates `milling_dry_sinter`; both stain and glaze generate `stain_glaze`. A type with only one half keeps that half, and existing task rows are not rewritten. Same-type exclusive steps coalesce across matching teeth; duplicate non-model steps for stacked types use a combined `typeA+typeB` section. Connected badge only for a real bridge.
- **Grouping:** only when `sortBy=date`; flat list + hint for other sorts. One live plan renders scan → prosthesis sections → optional model pair → packing/shipping. `lineCount` stays 1 so “Line N” stays hidden. 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. Same-type exclusive steps coalesce across matching teeth; duplicate non-model steps for stacked types use a combined `typeA+typeB` section. Connected badge only for a real bridge.
- **Prosthesis colors:** family pastels via `prosthesisTypeColorFromCatalog`. Job/task lines are `ProsthesisJobLineLabel` (same as Treatment/Cases): `13 · Pontic - 14 · PFZ Crown`, no category, colored Pontic + leaf, inherit font size, print hex. Indirect keeps subcategory + leaf. Joins use `PROSTHESIS_JOB_PATH_SEP`. No type pills, never row index.
- **Important first:** `pinImportant=true` (sort pin, not filter).
- **Task assignment:** assign in Cases (`TAB_CASES_EDIT`), but never assign a step while it is outsourced. Status edit on Tasks only for an in-progress task that is unassigned or assigned to you; a completed step is a badge. Reopening that step is Cases edit only. Others see “Assigned to {name}”.

View File

@@ -17,27 +17,30 @@ 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) |
| `schedules` | `CLINIC_PRICE` (treatment types → dentists) | `LAB_PRICE` (prosthesis → clinics, then outsourcing steps) |
| `commissions` | `CLINIC_COMMISSION` fixed amount | `LAB_COMMISSION` fixed amount |
Keep chrome identical: `BillingListToolbar`, outline labels, `AppMoneyInput`, equal-column `Table`.
## Partner payments
- List: `OR` from/to current org — **shared ledger** (both sides see each other’s entries).
- Create: clinic may only record partner **PAYMENT**; lab may record **RECEIPT** or **PAYMENT**. Always `status: CONFIRMED`.
- Allocations attach to lab cases (partner) or treatments (clinic patient receipt). Allocation total ≤ payment amount; remainder allowed.
- Do not reintroduce confirm/reject or `leftover` list filters unless product asks.
- 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.
## 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 / both commission catalogs as implemented).
- 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.
## Clinic visibility (this publish)
## Clinic visibility
- Hide Billing for **CLINIC** via `HIDDEN_TAB_FEATURE_FLAGS.billingOrgTypes` in `hidden-tabs.ts` (lab still sees it). Flip that array empty when product signs off.
- Billing is visible for clinics and labs. `HIDDEN_TAB_FEATURE_FLAGS.billingOrgTypes` in `hidden-tabs.ts` is empty.
## Treatment price approve

View File

@@ -73,7 +73,7 @@ Components: `TaskCaseGroupHeader`, `TaskProsthesisGroupHeader`, `TaskRow`.
## APIs
- `GET /tasks` — paginated flat task list (grouping is client-side when `sortBy=date`). Items include canonical `lineNumber` / `lineCount` and whole-current-case `taskProgress`; keep these when only a filtered or paginated subset of a case is visible so line labels and progress never shrink to the visible page.
- `PATCH /tasks/:taskId` — update status (only assignee or unassigned task, and only while `IN_PROGRESS`). Completed steps cannot be reopened here. **New cases** store independent `__line__` tasks under each real source key: one scan, optional model pair from `requiresModelSteps`, and applicable packing/shipping. A type with both dry milling and sintering generates `milling_dry_sinter`; both stain and glaze generate `stain_glaze`. A type with only one half keeps that half, and existing task rows are not rewritten. Scan, packing, and shipping cannot be outsourced. Model design and model create can; the child chart copies that line’s teeth, or the whole plan for a historical `__case__` model step. Scan completion does not fan out to other lines. Historical `__case__` scan completion keeps its whole-case fan-out. Lists ignore tasks with `roundId` set.
- `PATCH /tasks/:taskId` — update status (only assignee or unassigned task, and only while `IN_PROGRESS`). Completed steps cannot be reopened here. **New cases** store independent `__line__` tasks under each real source key: one scan, optional model pair from `requiresModelSteps`, and applicable packing/shipping. 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. Scan, packing, and shipping cannot be outsourced. Model design and model create can; the child chart copies that line’s teeth, or the whole plan for a historical `__case__` model step. Scan completion does not fan out to other lines. Historical `__case__` scan completion keeps its whole-case fan-out. Lists ignore tasks with `roundId` set.
- `GET /tasks/filter-options` — clinics + workflow steps (localized)
- `GET /tasks/locate-page` — page number for a task in the sorted filtered list (date sort position is `listedAt`, not separate `sentAt`/`startedAt` compares)
- `GET /cases/assignable-staff` — staff eligible for task assignment

View File

@@ -68,9 +68,9 @@ 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` / `LAB_COMMISSION` + partner ledger only. Commissions are **fixed amounts** (not percents). Partner list is a **shared** ledger (both orgs see both sides’ rows; always `CONFIRMED`). Money inputs: `AppMoneyInput`. **This publish:** Billing is hidden for CLINIC via `hidden-tabs.ts` (`billingOrgTypes: ['CLINIC']`). See `.cursor/rules/billing.mdc`, `.cursor/skills/billing/SKILL.md`.
**Billing (quick ref):** Same three-tab hub for CLINIC + LAB (`/billing?view=`). Clinic: `CLINIC_PRICE` / `CLINIC_COMMISSION` + patient receipts + partner payments. Lab: `LAB_PRICE` (prosthesis fees plus an outsourcing tab) / `LAB_COMMISSION` + partner ledger only. Commissions are **fixed amounts** (not percents). Dispatch and outsource prices are previews and are not stored. Partner list is a **shared** ledger: the sender’s row counts immediately, and the other org Accepts or Declines it. A typed party name stays local. Money inputs: `AppMoneyInput`. Billing is visible for both org types. See `.cursor/rules/billing.mdc`, `.cursor/skills/billing/SKILL.md`.
**Lab Tasks tab:** Newest case first (`listedAt`); grouping only for date sort; filters include completed step, origin, due date, assignment, and prosthesis. New tasks are plan-scoped: one scan → prosthesis sections → optional Model design/creation (when any type has `requiresModelSteps`) → packing/shipping. `lineCount` stays 1. `__line__` tasks are independently completable. A type with both dry milling and sintering generates `milling_dry_sinter`; both 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 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`.

View File

@@ -63,18 +63,19 @@ export const LAB_WORKFLOW_STEPS = [
{ code: 'milling_dry', sortOrder: 9 },
{ code: 'milling_dry_sinter', sortOrder: 10 },
{ code: 'milling_wet', sortOrder: 11 },
{ code: 'printer_resin', sortOrder: 12 },
{ code: 'pressing', sortOrder: 13 },
{ code: 'sinter', sortOrder: 14 },
{ code: 'build_up', sortOrder: 15 },
{ code: 'build_up_crown', sortOrder: 16 },
{ code: 'build_up_laminate', sortOrder: 17 },
{ code: 'stain', sortOrder: 18 },
{ code: 'stain_glaze', sortOrder: 19 },
{ code: 'glaze', sortOrder: 20 },
{ code: 'polish_prep', sortOrder: 21 },
{ code: 'packing', sortOrder: 22 },
{ code: 'shipping', sortOrder: 23 },
{ code: 'milling_wet_sinter', sortOrder: 12 },
{ code: 'printer_resin', sortOrder: 13 },
{ code: 'pressing', sortOrder: 14 },
{ code: 'sinter', sortOrder: 15 },
{ code: 'build_up', sortOrder: 16 },
{ code: 'build_up_crown', sortOrder: 17 },
{ code: 'build_up_laminate', sortOrder: 18 },
{ code: 'stain', sortOrder: 19 },
{ code: 'stain_glaze', sortOrder: 20 },
{ code: 'glaze', sortOrder: 21 },
{ code: 'polish_prep', sortOrder: 22 },
{ code: 'packing', sortOrder: 23 },
{ code: 'shipping', sortOrder: 24 },
] as const;
export type ProsthesisChartRegion = 'crown' | 'root' | 'arch';
@@ -505,7 +506,7 @@ export const PROSTHESIS_TYPES: ProsthesisTypeSeed[] = [
const PACK_SHIP = ['packing', 'shipping'] as const;
/** Dry milling then sintering, or stain then glaze, become one step when both are present. */
/** A milling step plus sintering, or stain plus glaze, become one step when both are present. */
function collapseStepPair(
steps: readonly string[],
pair: readonly [string, string],
@@ -533,6 +534,7 @@ export function buildProsthesisStepCodes(type: ProsthesisTypeSeed): string[] {
['milling_dry', 'sinter'],
'milling_dry_sinter',
);
steps = collapseStepPair(steps, ['milling_wet', 'sinter'], 'milling_wet_sinter');
steps = collapseStepPair(steps, ['stain', 'glaze'], 'stain_glaze');
if (!type.skipPackingShipping) {
steps.push(...PACK_SHIP);
@@ -764,6 +766,13 @@ export const WORKFLOW_STEP_LABELS: Record<string, Record<string, string>> = {
nl: 'Abutment kiezen',
},
design: { en: 'Design', fa: 'طراحی', nl: 'Ontwerp' },
design_implant: {
en: 'Implant Design',
fa: 'طراحی ایمپلنت',
nl: 'Implantaatontwerp',
},
design_frame: { en: 'Frame Design', fa: 'طراحی فریم', nl: 'Frame-ontwerp' },
design_full: { en: 'Full Design', fa: 'طراحی کامل', nl: 'Volledig ontwerp' },
design_customized_abutment: {
en: 'Design (custom abutment)',
fa: 'طراحی (اباتمنت سفارشی)',
@@ -778,6 +787,11 @@ export const WORKFLOW_STEP_LABELS: Record<string, Record<string, string>> = {
nl: 'Droogfrezen/Sinteren',
},
milling_wet: { en: 'Wet milling', fa: 'میلینگ تر', nl: 'Natfrezen' },
milling_wet_sinter: {
en: 'Wet milling/Sintering',
fa: 'میلینگ تر/سینترینگ',
nl: 'Natfrezen/Sinteren',
},
sla_print: { en: 'SLA Print', fa: 'پرینت SLA', nl: 'SLA-print' },
printer_resin: { en: 'Resin printing', fa: 'پرینت رزین', nl: 'Harsprinten' },
printer_metal: { en: 'Metal Print', fa: 'پرینت فلز', nl: 'Metaalprint' },

View File

@@ -158,7 +158,7 @@ const TASK_GENERATION_RULES = [
[
'Line-shared outsourcing',
'__line__ tasks',
'Scan, model, packing, and shipping tasks are independently completable per line and cannot be outsourced.',
'Scan, packing, and shipping cannot be outsourced. Model design and model creation can.',
],
[
'Same type on multiple teeth',

View File

@@ -0,0 +1,18 @@
-- AlterTable
ALTER TABLE "patient_payments" ALTER COLUMN "patientId" DROP NOT NULL;
ALTER TABLE "patient_payments" ADD COLUMN "externalPartyName" TEXT;
-- AlterTable
ALTER TABLE "partner_payments" ALTER COLUMN "fromOrganizationId" DROP NOT NULL;
ALTER TABLE "partner_payments" ALTER COLUMN "toOrganizationId" DROP NOT NULL;
ALTER TABLE "partner_payments" ADD COLUMN "externalPartyName" TEXT;
ALTER TABLE "partner_payments" ADD COLUMN "receiptConfirmedAt" TIMESTAMP(3);
ALTER TABLE "partner_payments" ADD COLUMN "receiptRejectedAt" TIMESTAMP(3);
-- Existing shared rows already counted for both organizations.
UPDATE "partner_payments"
SET "receiptConfirmedAt" = "createdAt"
WHERE "fromOrganizationId" IS NOT NULL
AND "toOrganizationId" IS NOT NULL
AND "receiptConfirmedAt" IS NULL
AND "receiptRejectedAt" IS NULL;

View File

@@ -958,16 +958,18 @@ model BillingSheetLine {
}
model PatientPayment {
id String @id @default(uuid())
organizationId String
patientId String
amount Decimal @db.Decimal(14, 2)
paidAt DateTime
note String?
createdByUserId String
id String @id @default(uuid())
organizationId String
patientId String?
/// Typed party when the receipt is not a patient in this clinic.
externalPartyName String?
amount Decimal @db.Decimal(14, 2)
paidAt DateTime
note String?
createdByUserId String
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
patient Patient @relation(fields: [patientId], references: [id], onDelete: Restrict)
patient Patient? @relation(fields: [patientId], references: [id], onDelete: Restrict)
createdBy User @relation("PatientPaymentCreatedBy", fields: [createdByUserId], references: [id], onDelete: Restrict)
allocations PatientPaymentAllocation[]
@@ -995,17 +997,23 @@ model PatientPaymentAllocation {
model PartnerPayment {
id String @id @default(uuid())
fromOrganizationId String
toOrganizationId String
fromOrganizationId String?
toOrganizationId String?
/// Typed party when the other side is not a linked organization.
externalPartyName String?
amount Decimal @db.Decimal(14, 2)
paidAt DateTime
note String?
status PartnerPaymentStatus
recordedBy PartnerPaymentRecordedBy
/// Set when the other organization accepts this row as their own receipt or payment.
receiptConfirmedAt DateTime?
/// Set when the other organization declines. Their ledger drops the row; the sender keeps it.
receiptRejectedAt DateTime?
createdByUserId String
fromOrganization Organization @relation("PartnerPaymentFrom", fields: [fromOrganizationId], references: [id], onDelete: Cascade)
toOrganization Organization @relation("PartnerPaymentTo", fields: [toOrganizationId], references: [id], onDelete: Cascade)
fromOrganization Organization? @relation("PartnerPaymentFrom", fields: [fromOrganizationId], references: [id], onDelete: Cascade)
toOrganization Organization? @relation("PartnerPaymentTo", fields: [toOrganizationId], references: [id], onDelete: Cascade)
createdBy User @relation("PartnerPaymentCreatedBy", fields: [createdByUserId], references: [id], onDelete: Restrict)
allocations PartnerPaymentAllocation[]

View File

@@ -224,6 +224,8 @@ export const ErrorCode = {
BILLING_PARTNER_INVALID: 'BILLING_PARTNER_INVALID',
BILLING_PATIENT_INVALID: 'BILLING_PATIENT_INVALID',
BILLING_TRANSACTION_TYPE_INVALID: 'BILLING_TRANSACTION_TYPE_INVALID',
BILLING_PAYMENT_NOT_FOUND: 'BILLING_PAYMENT_NOT_FOUND',
BILLING_PAYMENT_ACK_INVALID: 'BILLING_PAYMENT_ACK_INVALID',
// Generic HTTP
NOT_FOUND: 'NOT_FOUND',

View File

@@ -65,6 +65,7 @@ const UNION_MIDDLE_ORDER: Record<string, number> = {
milling_dry: 3,
milling_dry_sinter: 3,
milling_wet: 4,
milling_wet_sinter: 4,
printer_resin: 5,
pressing: 6,
sinter: 7,

View File

@@ -20,11 +20,13 @@ import {
ResolvedLinesQueryDto,
} from './dto/billing-sheet-query.dto';
import {
AcknowledgePaymentDto,
AllocationSearchQueryDto,
CreatePaymentDto,
ListPaymentsQueryDto,
} from './dto/billing-payment.dto';
import { UpsertBillingSheetDto } from './dto/upsert-billing-sheet.dto';
import { LabPriceQuoteDto, OutsourceQuoteDto } from './dto/billing-quote.dto';
@ApiTags('billing')
@ApiBearerAuth('JWT-auth')
@@ -176,6 +178,26 @@ export class BillingController {
return this.billingService.listPartnerPayments(req.user.id, organizationId, query);
}
@Post('lab-price-quote')
@ApiOperation({ summary: 'Preview a linked lab fee for the current prosthesis plan' })
quoteLabPrice(
@Body() dto: LabPriceQuoteDto,
@Req() req: { user: { id: string; organizationId?: string } },
) {
const organizationId = this.billingService.getOrganizationIdFromUser(req.user);
return this.billingService.quoteLabPrice(req.user.id, organizationId, dto);
}
@Post('outsource-price-quote')
@ApiOperation({ summary: 'Preview the destination lab fee for an outsource' })
quoteOutsource(
@Body() dto: OutsourceQuoteDto,
@Req() req: { user: { id: string; organizationId?: string } },
) {
const organizationId = this.billingService.getOrganizationIdFromUser(req.user);
return this.billingService.quoteOutsource(req.user.id, organizationId, dto);
}
@Post('partner-payments')
@ApiOperation({ summary: 'Record a clinic-lab payment (TAB_BILLING_EDIT)' })
createPartnerPayment(
@@ -185,4 +207,20 @@ export class BillingController {
const organizationId = this.billingService.getOrganizationIdFromUser(req.user);
return this.billingService.createPartnerPayment(req.user.id, organizationId, dto);
}
@Post('partner-payments/:id/acknowledge')
@ApiOperation({ summary: 'Accept or decline a partner payment as the other organization' })
acknowledgePartnerPayment(
@Param('id', ParseUUIDPipe) id: string,
@Body() dto: AcknowledgePaymentDto,
@Req() req: { user: { id: string; organizationId?: string } },
) {
const organizationId = this.billingService.getOrganizationIdFromUser(req.user);
return this.billingService.acknowledgePartnerPayment(
req.user.id,
organizationId,
id,
dto.decision,
);
}
}

View File

@@ -9,7 +9,7 @@ import {
Prisma,
} from '@prisma/client';
import { PrismaService } from '../../../prisma/prisma.service';
import { AppException, ErrorCode } from '../../common/errors';
import { AppException, ErrorCode, type ErrorCodeValue } from '../../common/errors';
import {
hasEffectivePermission,
participatesInTasks,
@@ -22,20 +22,35 @@ import {
} from '../../common/organization-type';
import {
CatalogLabelService,
formatCodeAsLabel,
normalizeCatalogLocale,
type CatalogLocale,
} from '../catalog/catalog-label.service';
import { WORKFLOW_STEP_LABELS } from '../../../prisma/catalog-seed-data';
import {
isBillingDesignPriceCode,
outsourcingPriceStepCodes,
} from './outsourcing-price-steps';
import { UpsertBillingSheetDto } from './dto/upsert-billing-sheet.dto';
import {
calculateClinicDetailAmount,
calculateCommissionEarned,
calculateLabCaseAmount,
calculateOutsourceStepsAmount,
commissionQtyForTask,
INTRAORAL_SCAN_STEP,
outsourceQuoteBasis,
preferNonEmptyJobs,
roundBillingAmount,
type BillingPriceLine,
type ProsthesisQtyMeta,
} from './calculate-amounts';
import { normalizeTaskTeeth } from '../cases/lab-case-task.util';
import {
outsourceTaskProblem,
type OutsourceTaskRow,
} from '../cases/lab-case-outsource.rules';
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 {
@@ -187,6 +202,22 @@ export class BillingService {
);
}
if (kind === 'LAB_PRICE') {
const codes = outsourcingPriceStepCodes();
const labels = await this.catalogLabels.resolveLabels(
CatalogEntityKind.LAB_WORKFLOW_STEP,
codes,
locale,
);
workflowSteps.push(
...codes.map((code, index) => ({
code,
sortOrder: index + 1,
label: workflowPriceLabel(code, labels, locale),
})),
);
}
return {
success: true as const,
data: { treatmentTypes, prosthesisTypes, prosthesisCategories, workflowSteps },
@@ -346,16 +377,19 @@ export class BillingService {
if (dto.type !== 'RECEIPT') {
throw new AppException(ErrorCode.BILLING_TRANSACTION_TYPE_INVALID, HttpStatus.BAD_REQUEST);
}
if (!dto.patientId) {
const externalPartyName = dto.externalPartyName?.trim() || '';
if (!dto.patientId && !externalPartyName) {
throw new AppException(ErrorCode.BILLING_PATIENT_INVALID, HttpStatus.BAD_REQUEST);
}
await this.assertPatientInOrg(organizationId, dto.patientId);
if (dto.patientId) {
await this.assertPatientInOrg(organizationId, dto.patientId);
}
const amount = parseMoney(dto.amount);
const allocations = normalizeAllocations(dto.allocations);
const allocations = dto.patientId ? normalizeAllocations(dto.allocations) : [];
assertAllocationTotal(amount, allocations);
const treatmentIds = allocations.map((row) => row.targetId);
if (treatmentIds.length > 0) {
if (treatmentIds.length > 0 && dto.patientId) {
const treatments = await this.prisma.treatment.findMany({
where: { id: { in: treatmentIds }, organizationId, patientId: dto.patientId },
select: { id: true },
@@ -368,7 +402,8 @@ export class BillingService {
const payment = await this.prisma.patientPayment.create({
data: {
organizationId,
patientId: dto.patientId,
patientId: dto.patientId ?? null,
externalPartyName: dto.patientId ? null : externalPartyName,
amount: new Prisma.Decimal(amount.toFixed(2)),
paidAt: new Date(),
note: dto.note?.trim() || null,
@@ -411,7 +446,9 @@ export class BillingService {
orderBy: [{ paidAt: 'desc' }, { createdAt: 'desc' }],
take: 200,
});
const mapped = rows.map(mapPartnerPayment);
const mapped = rows
.map((row) => mapPartnerPayment(row, organizationId))
.filter((row) => row.acknowledgement !== 'rejected' || row.recordedByViewer);
const q = query.q?.trim().toLowerCase();
return {
success: true as const,
@@ -438,7 +475,8 @@ export class BillingService {
await this.assertCanEdit(actorUserId, organizationId);
const orgType = await getOrganizationTypeName(this.prisma, organizationId);
const recordedBy = orgType === 'LAB' ? 'LAB' : 'CLINIC';
if (!dto.counterpartOrganizationId) {
const externalPartyName = dto.externalPartyName?.trim() || '';
if (!dto.counterpartOrganizationId && !externalPartyName) {
throw new AppException(ErrorCode.BILLING_PARTNER_INVALID, HttpStatus.BAD_REQUEST);
}
if (recordedBy === 'CLINIC' && dto.type !== 'PAYMENT') {
@@ -449,9 +487,30 @@ export class BillingService {
}
const amount = parseMoney(dto.amount);
const allocations = normalizeAllocations(dto.allocations);
const allocations = dto.counterpartOrganizationId ? normalizeAllocations(dto.allocations) : [];
assertAllocationTotal(amount, allocations);
if (!dto.counterpartOrganizationId) {
const fromId = dto.type === 'RECEIPT' ? null : organizationId;
const toId = dto.type === 'RECEIPT' ? organizationId : null;
const payment = await this.prisma.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;
const fromId =
recordedBy === 'CLINIC' || dto.type === 'PAYMENT' ? organizationId : counterpartId;
@@ -487,7 +546,40 @@ export class BillingService {
},
include: partnerPaymentInclude,
});
return { success: true as const, data: mapPartnerPayment(payment) };
return { success: true as const, data: mapPartnerPayment(payment, organizationId) };
}
async acknowledgePartnerPayment(
actorUserId: string,
organizationId: string,
id: string,
decision: 'ACCEPT' | 'DECLINE',
) {
await this.assertCanEdit(actorUserId, organizationId);
const payment = await this.prisma.partnerPayment.findUnique({
where: { id },
include: partnerPaymentInclude,
});
if (!payment) {
throw new AppException(ErrorCode.BILLING_PAYMENT_NOT_FOUND, HttpStatus.NOT_FOUND);
}
const sides = partnerSides(payment);
if (
sides.counterpartyId !== organizationId ||
payment.receiptConfirmedAt ||
payment.receiptRejectedAt
) {
throw new AppException(ErrorCode.BILLING_PAYMENT_ACK_INVALID, HttpStatus.BAD_REQUEST);
}
const updated = await this.prisma.partnerPayment.update({
where: { id },
data:
decision === 'ACCEPT'
? { receiptConfirmedAt: new Date() }
: { receiptRejectedAt: new Date() },
include: partnerPaymentInclude,
});
return { success: true as const, data: mapPartnerPayment(updated, organizationId) };
}
async listPartners(actorUserId: string, organizationId: string) {
@@ -500,6 +592,136 @@ export class BillingService {
};
}
async quoteLabPrice(actorUserId: string, organizationId: string, dto: LabPriceQuoteDto) {
await this.assertPermission(
actorUserId,
organizationId,
'TAB_TREATMENT_READ',
ErrorCode.PERMISSION_ACCESS_TREATMENTS,
);
const orgType = await getOrganizationTypeName(this.prisma, organizationId);
if (orgType !== 'CLINIC') {
throw new AppException(ErrorCode.PERMISSION_CLINIC_ONLY, HttpStatus.FORBIDDEN);
}
await this.assertLinkedClinicLab(organizationId, dto.labOrganizationId);
const asOf = toBillingDateOnly(new Date());
const lines = await this.resolvedPriceLines(this.prisma as unknown as Prisma.TransactionClient, {
organizationId: dto.labOrganizationId,
kind: 'LAB_PRICE',
asOf,
clinicOrganizationId: organizationId,
});
const metaByCode = await this.prosthesisMetaByCode(
this.prisma as unknown as Prisma.TransactionClient,
);
const amount = calculateLabCaseAmount({
jobs: dto.jobs.map((job) => ({
tooth: job.tooth.trim(),
prosthesisTypeCode: job.prosthesisTypeCode.trim(),
})),
lines,
metaByCode,
});
return { success: true as const, data: { amount: amount.toFixed(2) } };
}
async quoteOutsource(actorUserId: string, organizationId: string, dto: OutsourceQuoteDto) {
await this.assertPermission(
actorUserId,
organizationId,
'TAB_CASES_EDIT',
ErrorCode.PERMISSION_EDIT_CASES,
);
const orgType = await getOrganizationTypeName(this.prisma, organizationId);
if (orgType !== 'LAB') {
throw new AppException(ErrorCode.PERMISSION_DENIED, HttpStatus.FORBIDDEN);
}
const destinationType = await getOrganizationTypeName(this.prisma, dto.destinationOrganizationId);
if (destinationType !== 'LAB') {
throw new AppException(ErrorCode.BILLING_PARTNER_INVALID, HttpStatus.BAD_REQUEST);
}
await this.assertActiveLink(organizationId, dto.destinationOrganizationId);
const labCase = await this.prisma.labCase.findFirst({
where: { id: dto.caseId, destinationOrganizationId: organizationId },
include: {
toothProsthesis: {
select: { tooth: true, prosthesisTypeCode: true },
},
tasks: {
where: { roundId: null },
select: {
id: true,
sourceKey: true,
treatmentDetailId: true,
teeth: true,
prosthesisTypeCode: true,
selectionGroupId: true,
status: true,
roundId: true,
outsourcedToLabCaseId: true,
workflowStepCode: true,
},
},
},
});
if (!labCase) {
throw new AppException(ErrorCode.LAB_CASE_NOT_FOUND, HttpStatus.NOT_FOUND);
}
const taskRows: OutsourceTaskRow[] = labCase.tasks.map((task) => ({
id: task.id,
sourceKey: task.sourceKey || task.treatmentDetailId || '',
teeth: normalizeTaskTeeth(task.teeth),
prosthesisTypeCode: task.prosthesisTypeCode,
selectionGroupId: task.selectionGroupId ?? '',
status: task.status,
roundId: task.roundId,
outsourcedToLabCaseId: task.outsourcedToLabCaseId,
workflowStepCode: task.workflowStepCode,
}));
const selectable = taskRows.filter(
(task) => outsourceTaskProblem(taskRows, [task.id]) === null,
);
const basis = outsourceQuoteBasis(
dto.taskIds,
selectable.map((task) => task.id),
);
const lines = await this.resolvedPriceLines(this.prisma as unknown as Prisma.TransactionClient, {
organizationId: dto.destinationOrganizationId,
kind: 'LAB_PRICE',
asOf: toBillingDateOnly(new Date()),
});
const metaByCode = await this.prosthesisMetaByCode(
this.prisma as unknown as Prisma.TransactionClient,
);
const selected = new Set(dto.taskIds);
const amount =
basis === 'prosthesis'
? calculateLabCaseAmount({
jobs: labCase.toothProsthesis.map((job) => ({
tooth: job.tooth,
prosthesisTypeCode: job.prosthesisTypeCode,
})),
lines,
metaByCode,
})
: basis === 'steps'
? calculateOutsourceStepsAmount(
selectable
.filter((task) => selected.has(task.id))
.map((task) => ({
workflowStepCode: task.workflowStepCode,
prosthesisTypeCode: task.prosthesisTypeCode,
teeth: task.teeth,
})),
lines,
metaByCode,
)
: 0;
return { success: true as const, data: { amount: roundBillingAmount(amount).toFixed(2) } };
}
async getResolvedLines(
actorUserId: string,
organizationId: string,
@@ -1078,6 +1300,37 @@ export class BillingService {
.sort((a, b) => a.name.localeCompare(b.name));
}
private async assertActiveLink(organizationId: string, otherOrganizationId: string) {
const link = await this.prisma.organizationLink.findFirst({
where: {
status: LinkStatus.ACTIVE,
OR: [
{ organizationAId: organizationId, organizationBId: otherOrganizationId },
{ organizationAId: otherOrganizationId, organizationBId: organizationId },
],
},
select: { id: true },
});
if (!link) {
throw new AppException(ErrorCode.BILLING_PARTNER_INVALID, HttpStatus.BAD_REQUEST);
}
}
private async assertPermission(
userId: string,
organizationId: string,
permission: string,
denied: ErrorCodeValue,
) {
const membership = await this.getMembership(userId, organizationId);
if (!membership) {
throw new AppException(ErrorCode.PERMISSION_NOT_MEMBER, HttpStatus.FORBIDDEN);
}
if (!hasEffectivePermission(membership, permission)) {
throw new AppException(denied, HttpStatus.FORBIDDEN);
}
}
private async assertLinkedClinicLab(clinicOrganizationId: string, labOrganizationId: string) {
const clinicType = await getOrganizationTypeName(this.prisma, clinicOrganizationId);
const labType = await getOrganizationTypeName(this.prisma, labOrganizationId);
@@ -1232,11 +1485,12 @@ export class BillingService {
throw new AppException(ErrorCode.BILLING_LINE_INVALID, HttpStatus.BAD_REQUEST);
}
}
if (stepCodes.length > 0) {
const realStepCodes = stepCodes.filter((code) => !isBillingDesignPriceCode(code));
if (realStepCodes.length > 0) {
const found = await this.prisma.labWorkflowStep.count({
where: { code: { in: stepCodes } },
where: { code: { in: realStepCodes } },
});
if (found !== new Set(stepCodes).size) {
if (found !== new Set(realStepCodes).size) {
throw new AppException(ErrorCode.BILLING_LINE_INVALID, HttpStatus.BAD_REQUEST);
}
}
@@ -1347,12 +1601,24 @@ function allowedCatalogKinds(
case 'CLINIC_COMMISSION':
return ['TREATMENT_TYPE'];
case 'LAB_PRICE':
return ['PROSTHESIS_TYPE'];
return ['PROSTHESIS_TYPE', 'LAB_WORKFLOW_STEP'];
default:
return ['LAB_WORKFLOW_STEP'];
}
}
function workflowPriceLabel(
code: string,
labels: Map<string, string>,
locale: CatalogLocale,
): string {
const fromDb = labels.get(code);
const human = formatCodeAsLabel(code);
if (fromDb && fromDb !== human) return fromDb;
const seed = WORKFLOW_STEP_LABELS[code];
return seed?.[locale] ?? seed?.en ?? fromDb ?? human;
}
function uniqueIds(ids: string[] | undefined): string[] {
return [...new Set((ids ?? []).map((id) => id.trim()).filter(Boolean))];
}
@@ -1432,8 +1698,8 @@ const patientPaymentInclude = {
} satisfies Prisma.PatientPaymentInclude;
const partnerPaymentInclude = {
fromOrganization: { select: { id: true, name: true } },
toOrganization: { select: { id: true, name: true } },
fromOrganization: { select: { id: true, name: true, type: { select: { name: true } } } },
toOrganization: { select: { id: true, name: true, type: { select: { name: true } } } },
allocations: {
include: {
labCase: {
@@ -1459,8 +1725,11 @@ function mapPatientPayment(
return {
id: payment.id,
patientId: payment.patientId,
patientName: `${payment.patient.firstName} ${payment.patient.lastName}`.trim(),
patientIsWalkIn: payment.patient.isWalkIn,
externalPartyName: payment.externalPartyName,
patientName: payment.patient
? `${payment.patient.firstName} ${payment.patient.lastName}`.trim()
: payment.externalPartyName ?? '',
patientIsWalkIn: payment.patient?.isWalkIn ?? false,
amount: payment.amount.toString(),
paidAt: payment.paidAt.toISOString(),
note: payment.note,
@@ -1476,9 +1745,38 @@ function mapPatientPayment(
};
}
function mapPartnerPayment(
function partnerSides(
payment: Prisma.PartnerPaymentGetPayload<{ include: typeof partnerPaymentInclude }>,
) {
const from = payment.fromOrganization;
const to = payment.toOrganization;
if (!from || !to) {
return { senderId: (from ?? to)?.id ?? null, counterpartyId: null as string | null };
}
const sender =
payment.recordedBy === 'CLINIC'
? from.type.name === 'CLINIC'
? from
: to
: from.type.name === 'LAB'
? from
: to;
const counterparty = sender.id === from.id ? to : from;
return { senderId: sender.id, counterpartyId: counterparty.id };
}
function mapPartnerPayment(
payment: Prisma.PartnerPaymentGetPayload<{ include: typeof partnerPaymentInclude }>,
viewerOrganizationId: string,
) {
const sides = partnerSides(payment);
const acknowledgement = payment.receiptRejectedAt
? 'rejected'
: payment.receiptConfirmedAt
? 'accepted'
: sides.counterpartyId
? 'pending'
: 'none';
return {
id: payment.id,
amount: payment.amount.toString(),
@@ -1486,10 +1784,14 @@ function mapPartnerPayment(
note: payment.note,
status: payment.status,
recordedBy: payment.recordedBy,
recordedByViewer: sides.senderId === viewerOrganizationId,
acknowledgement,
canAcknowledge: sides.counterpartyId === viewerOrganizationId && acknowledgement === 'pending',
externalPartyName: payment.externalPartyName,
fromOrganizationId: payment.fromOrganizationId,
fromOrganizationName: payment.fromOrganization.name,
fromOrganizationName: payment.fromOrganization?.name ?? payment.externalPartyName ?? '',
toOrganizationId: payment.toOrganizationId,
toOrganizationName: payment.toOrganization.name,
toOrganizationName: payment.toOrganization?.name ?? payment.externalPartyName ?? '',
remainder: remainderOf(payment.amount, payment.allocations),
allocations: payment.allocations.map((row) => {
const patient =

View File

@@ -4,8 +4,10 @@ import {
calculateClinicDetailAmount,
calculateCommissionEarned,
calculateLabCaseAmount,
calculateOutsourceStepsAmount,
commissionQtyForTask,
isPerTypeProsthesisUnit,
outsourceQuoteBasis,
preferNonEmptyJobs,
priceFor,
} from './calculate-amounts';
@@ -198,3 +200,38 @@ describe('calculateCommissionEarned', () => {
expect(calculateCommissionEarned(0, 3)).toBe(0);
});
});
describe('outsource price quote', () => {
const stepLines = [
{ catalogKind: 'LAB_WORKFLOW_STEP' as const, catalogCode: 'design_frame', amount: 20 },
{ catalogKind: 'LAB_WORKFLOW_STEP' as const, catalogCode: 'design_full', amount: 30 },
{ catalogKind: 'LAB_WORKFLOW_STEP' as const, catalogCode: 'design_implant', amount: 40 },
{ catalogKind: 'LAB_WORKFLOW_STEP' as const, catalogCode: 'milling_dry_sinter', amount: 15 },
{ catalogKind: 'LAB_WORKFLOW_STEP' as const, catalogCode: 'model_design', amount: 8 },
];
it('uses the prosthesis fee only when every outsourceable step is selected', () => {
expect(outsourceQuoteBasis(['a', 'b'], ['a', 'b'])).toBe('prosthesis');
expect(outsourceQuoteBasis(['a'], ['a', 'b'])).toBe('steps');
expect(outsourceQuoteBasis([], ['a'])).toBe('empty');
});
it('prices design buckets and model steps, and treats a missing price as zero', () => {
expect(
calculateOutsourceStepsAmount(
[
{ workflowStepCode: 'design', prosthesisTypeCode: 'pfm_crown', teeth: ['14', '15'] },
{
workflowStepCode: 'design_customized_abutment',
prosthesisTypeCode: 'screw_retained',
teeth: ['21'],
},
{ workflowStepCode: 'model_design', prosthesisTypeCode: '__line__', teeth: [] },
{ workflowStepCode: 'polish_prep', prosthesisTypeCode: 'pfz_crown', teeth: ['14'] },
],
stepLines,
meta,
),
).toBe(20 * 2 + 40 + 8);
});
});

View File

@@ -1,3 +1,5 @@
import { outsourcingPriceCodeForStep } from './outsourcing-price-steps';
export type BillingCatalogKindValue = 'TREATMENT_TYPE' | 'PROSTHESIS_TYPE' | 'LAB_WORKFLOW_STEP';
export type BillingPriceLine = {
@@ -131,3 +133,54 @@ export function commissionQtyForTask(args: {
export function calculateCommissionEarned(unitAmount: number, qty: number): number {
return roundBillingAmount(unitAmount * qty);
}
export type OutsourceQuoteTask = {
workflowStepCode: string;
prosthesisTypeCode: string;
teeth: readonly string[];
};
export function metaForProsthesisCode(
prosthesisTypeCode: string,
metaByCode: ReadonlyMap<string, ProsthesisQtyMeta>,
): ProsthesisQtyMeta | undefined {
const parts = prosthesisTypeCode
.split('+')
.map((part) => part.trim())
.filter(Boolean);
const metas = parts
.map((code) => metaByCode.get(code))
.filter((row): row is ProsthesisQtyMeta => Boolean(row));
return metas.find((row) => isPerTypeProsthesisUnit(row)) ?? metas[0];
}
/** Step prices for a partial outsource. A missing line counts as zero. */
export function calculateOutsourceStepsAmount(
tasks: readonly OutsourceQuoteTask[],
lines: readonly BillingPriceLine[],
metaByCode: ReadonlyMap<string, ProsthesisQtyMeta>,
): number {
let total = 0;
for (const task of tasks) {
const code = outsourcingPriceCodeForStep(task.workflowStepCode, task.prosthesisTypeCode);
const qty = commissionQtyForTask({
workflowStepCode: task.workflowStepCode,
teeth: task.teeth,
prosthesisTypeCode: task.prosthesisTypeCode,
meta: metaForProsthesisCode(task.prosthesisTypeCode, metaByCode),
});
total += qty * priceFor(lines, 'LAB_WORKFLOW_STEP', code);
}
return roundBillingAmount(total);
}
/** Whole case when every outsourceable in-progress step is selected. */
export function outsourceQuoteBasis(
selectedIds: readonly string[],
selectableIds: readonly string[],
): 'empty' | 'prosthesis' | 'steps' {
const selected = new Set(selectedIds);
if (selected.size === 0 || selectableIds.length === 0) return 'empty';
if (selectableIds.every((id) => selected.has(id))) return 'prosthesis';
return 'steps';
}

View File

@@ -51,6 +51,17 @@ export class CreatePaymentDto {
@IsOptional()
@IsUUID()
counterpartOrganizationId?: string;
/** Typed party when no linked organization or patient was selected. */
@IsOptional()
@IsString()
@MaxLength(200)
externalPartyName?: string;
}
export class AcknowledgePaymentDto {
@IsIn(['ACCEPT', 'DECLINE'], { message: ErrorCode.BILLING_PAYMENT_ACK_INVALID })
decision: 'ACCEPT' | 'DECLINE';
}
export class ListPaymentsQueryDto {

View File

@@ -0,0 +1,44 @@
import { Type } from 'class-transformer';
import {
ArrayMaxSize,
IsArray,
IsString,
IsUUID,
MaxLength,
ValidateNested,
} from 'class-validator';
import { ErrorCode } from '../../../common/errors';
export class LabPriceQuoteJobDto {
@IsString()
@MaxLength(8)
tooth: string;
@IsString()
@MaxLength(160)
prosthesisTypeCode: string;
}
export class LabPriceQuoteDto {
@IsUUID()
labOrganizationId: string;
@IsArray()
@ArrayMaxSize(400)
@ValidateNested({ each: true })
@Type(() => LabPriceQuoteJobDto)
jobs: LabPriceQuoteJobDto[];
}
export class OutsourceQuoteDto {
@IsUUID()
destinationOrganizationId: string;
@IsUUID()
caseId: string;
@IsArray()
@ArrayMaxSize(400)
@IsUUID(undefined, { each: true, message: ErrorCode.LAB_CASE_OUTSOURCE_TASKS_INVALID })
taskIds: string[];
}

View File

@@ -0,0 +1,60 @@
import {
DESIGN_FRAME_PRICE,
DESIGN_FULL_PRICE,
DESIGN_IMPLANT_PRICE,
designPriceCodeForTypes,
outsourcingPriceCodeForStep,
outsourcingPriceStepCodes,
} from './outsourcing-price-steps';
describe('outsourcing price steps', () => {
const codes = outsourcingPriceStepCodes();
it('pins model steps and the three design prices, then real pipeline steps', () => {
expect(codes.slice(0, 5)).toEqual([
'model_design',
'model_create',
DESIGN_IMPLANT_PRICE,
DESIGN_FRAME_PRICE,
DESIGN_FULL_PRICE,
]);
expect(codes).toContain('milling_dry');
expect(codes).toContain('milling_dry_sinter');
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).toContain('choosing_abutment');
expect(new Set(codes).size).toBe(codes.length);
});
it('leaves scan, packing, shipping, and the raw design steps off the sheet', () => {
expect(codes).not.toContain('intraoral_scan');
expect(codes).not.toContain('packing');
expect(codes).not.toContain('shipping');
expect(codes).not.toContain('design');
expect(codes).not.toContain('design_customized_abutment');
});
it('prices implant design, frame design, and full design from the prosthesis type', () => {
expect(designPriceCodeForTypes(['pfm_crown'])).toBe(DESIGN_FRAME_PRICE);
expect(designPriceCodeForTypes(['press_ceramic'])).toBe(DESIGN_FRAME_PRICE);
expect(designPriceCodeForTypes(['veneer_layered'])).toBe(DESIGN_FRAME_PRICE);
expect(designPriceCodeForTypes(['monolithic_zirconia'])).toBe(DESIGN_FULL_PRICE);
expect(designPriceCodeForTypes(['veneer_full_contour'])).toBe(DESIGN_FULL_PRICE);
expect(designPriceCodeForTypes(['smile_design'])).toBe(DESIGN_FULL_PRICE);
expect(designPriceCodeForTypes(['complete_denture'])).toBe(DESIGN_FULL_PRICE);
expect(designPriceCodeForTypes(['pfz_crown+pmma'])).toBe(DESIGN_FRAME_PRICE);
expect(designPriceCodeForTypes(['pmma+customized_abutment'])).toBe(DESIGN_IMPLANT_PRICE);
expect(outsourcingPriceCodeForStep('design', 'glass_ceramic_crown')).toBe(DESIGN_FULL_PRICE);
expect(outsourcingPriceCodeForStep('design_customized_abutment', 'screw_retained')).toBe(
DESIGN_IMPLANT_PRICE,
);
expect(outsourcingPriceCodeForStep('milling_dry_sinter', 'monolithic_zirconia')).toBe(
'milling_dry_sinter',
);
});
});

View File

@@ -0,0 +1,101 @@
import {
LAB_WORKFLOW_STEPS,
PROSTHESIS_TYPES,
buildProsthesisStepCodes,
} from '../../../prisma/catalog-seed-data';
/** Billing-only prices. They are not workflow steps and do not generate tasks. */
export const DESIGN_IMPLANT_PRICE = 'design_implant';
export const DESIGN_FRAME_PRICE = 'design_frame';
export const DESIGN_FULL_PRICE = 'design_full';
export const BILLING_DESIGN_PRICE_CODES = [
DESIGN_IMPLANT_PRICE,
DESIGN_FRAME_PRICE,
DESIGN_FULL_PRICE,
] as const;
const EXCLUDED_PIPELINE_CODES = new Set([
'intraoral_scan',
'packing',
'shipping',
'design',
'design_customized_abutment',
'model_design',
'model_create',
]);
const IMPLANT_DESIGN_TYPES = new Set([
'customized_abutment',
'zirconia_abutment',
'screw_retained',
]);
const FRAME_DESIGN_TYPES = new Set(['pfm_crown', 'pfz_crown', 'press_ceramic']);
const PINNED_PRICE_CODES = [
'model_design',
'model_create',
DESIGN_IMPLANT_PRICE,
DESIGN_FRAME_PRICE,
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);
}
/** One row per step that an active prosthesis pipeline emits, plus model and design prices. */
export function outsourcingPriceStepCodes(): string[] {
const emitted = new Set<string>();
for (const type of PROSTHESIS_TYPES) {
if (type.isActive === false) continue;
for (const code of buildProsthesisStepCodes(type)) {
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]),
);
const rest = [...emitted].sort((a, b) => {
const diff = (order.get(a) ?? 1000) - (order.get(b) ?? 1000);
if (diff !== 0) return diff;
return a.localeCompare(b);
});
return [...PINNED_PRICE_CODES, ...rest];
}
export function prosthesisTypeParts(code: string): string[] {
return code
.split('+')
.map((part) => part.trim())
.filter(Boolean);
}
export function designPriceCodeForTypes(codes: readonly string[]): string {
const parts = codes.flatMap((code) => prosthesisTypeParts(code));
if (parts.some((code) => IMPLANT_DESIGN_TYPES.has(code))) return DESIGN_IMPLANT_PRICE;
if (
parts.some((code) => FRAME_DESIGN_TYPES.has(code) || code.endsWith('_layered'))
) {
return DESIGN_FRAME_PRICE;
}
return DESIGN_FULL_PRICE;
}
/** Map a task step onto an outsourcing price code. */
export function outsourcingPriceCodeForStep(
workflowStepCode: string,
prosthesisTypeCode: string,
): string {
if (workflowStepCode === 'design_customized_abutment') return DESIGN_IMPLANT_PRICE;
if (workflowStepCode === 'design') return designPriceCodeForTypes([prosthesisTypeCode]);
return workflowStepCode;
}

View File

@@ -261,10 +261,13 @@ describe('generateLabCaseTasks', () => {
]);
});
it('collapses dry milling with sintering, and stain with glaze, only when both are present', () => {
it('collapses a milling step with sintering, and stain with glaze, only when both are present', () => {
const zirconia = stepsFromSeed('monolithic_zirconia').map((step) => step.workflowStepCode);
const pmma = stepsFromSeed('pmma').map((step) => step.workflowStepCode);
const glass = stepsFromSeed('glass_ceramic_crown').map((step) => step.workflowStepCode);
const layered = stepsFromSeed('veneer_layered').map((step) => step.workflowStepCode);
const fullMetal = stepsFromSeed('full_metal_crown').map((step) => step.workflowStepCode);
const postCore = stepsFromSeed('cast_post_core').map((step) => step.workflowStepCode);
const pfm = stepsFromSeed('pfm_crown').map((step) => step.workflowStepCode);
expect(zirconia).toContain('milling_dry_sinter');
@@ -278,10 +281,32 @@ describe('generateLabCaseTasks', () => {
expect(pmma).toContain('milling_dry');
expect(pmma).not.toContain('milling_dry_sinter');
expect(glass).toContain('sinter');
expect(pmma).not.toContain('sinter');
expect(glass).toContain('milling_wet_sinter');
expect(glass).not.toContain('milling_wet');
expect(glass).not.toContain('sinter');
expect(glass).not.toContain('milling_dry_sinter');
expect(glass).toContain('stain_glaze');
expect(glass.indexOf('design')).toBeLessThan(glass.indexOf('milling_wet_sinter'));
expect(glass.indexOf('milling_wet_sinter')).toBeLessThan(glass.indexOf('stain_glaze'));
expect(layered).toContain('milling_wet_sinter');
expect(layered).toContain('build_up_laminate');
expect(layered).not.toContain('milling_wet');
expect(layered).not.toContain('sinter');
expect(layered.indexOf('milling_wet_sinter')).toBeLessThan(layered.indexOf('build_up_laminate'));
expect(fullMetal).toContain('milling_wet');
expect(fullMetal).not.toContain('milling_wet_sinter');
expect(fullMetal).not.toContain('sinter');
expect(postCore).toContain('milling_wet');
expect(postCore).not.toContain('milling_wet_sinter');
expect(postCore).not.toContain('sinter');
expect(pfm).toContain('sinter');
expect(pfm).not.toContain('milling_wet');
expect(pfm).not.toContain('milling_wet_sinter');
expect(pfm).not.toContain('milling_dry_sinter');
expect(pfm.indexOf('printer_metal')).toBeLessThan(pfm.indexOf('sinter'));
});

Binary file not shown.

View File

@@ -547,6 +547,7 @@
"generatedBadge": "Generated",
"sendCase": "Outsource",
"sendCaseTitle": "Outsource steps",
"outsourcePrice": "Outsource price",
"sendCaseSelectAll": "Select all",
"sendCaseLab": "Lab",
"sendCaseLabsLoading": "Loading labs...",
@@ -877,6 +878,7 @@
"selectLab": "Destination lab",
"selectLabPlaceholder": "Choose a linked lab…",
"sendToLab": "Send to lab",
"labFeePreview": "Lab fee",
"dueDateLabel": "Due date",
"dueDateOptional": "optional",
"dueDateLockedCompleted": "Due date cannot be changed after all tasks are completed.",
@@ -1286,6 +1288,7 @@
"noTargetsAvailable": "No people or clinics are available to attach.",
"treatmentTypes": "Treatment types",
"workflowSteps": "Workflow steps",
"outsourcingPrices": "Outsourcing prices",
"price": "Price (dollar)",
"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.",
@@ -1320,6 +1323,11 @@
"selectLab": "Select lab",
"selectClinic": "Select clinic",
"searchPatient": "Search patient",
"partySearch": "Search or type a name",
"paymentPending": "Waiting",
"paymentDeclined": "Declined",
"acceptPayment": "Accept",
"declinePayment": "Decline",
"note": "Note",
"notePlaceholder": "Optional note",
"party": "Party",
@@ -1536,6 +1544,8 @@
"BILLING_ALLOCATION_INVALID": "One or more attached treatments or cases are not valid.",
"BILLING_PARTNER_INVALID": "Choose a linked clinic or lab for this transaction.",
"BILLING_PATIENT_INVALID": "Choose a patient for this receipt.",
"BILLING_TRANSACTION_TYPE_INVALID": "Choose receipt or payment."
"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."
}
}

View File

@@ -547,6 +547,7 @@
"fromLabBadge": "از لابراتوار",
"sendCase": "برون سپاری",
"sendCaseTitle": "مراحل برون سپاری",
"outsourcePrice": "قیمت برون‌سپاری",
"sendCaseSelectAll": "انتخاب همه",
"sendCaseLab": "لابراتوار",
"sendCaseLabsLoading": "در حال بارگذاری لابراتوارها...",
@@ -878,6 +879,7 @@
"selectLab": "لابراتوار مقصد",
"selectLabPlaceholder": "یک لابراتوار متصل انتخاب کنید…",
"sendToLab": "ارسال به لابراتوار",
"labFeePreview": "تعرفه لابراتوار",
"dueDateLabel": "موعد تحویل",
"dueDateOptional": "اختیاری",
"dueDateLockedCompleted": "پس از تکمیل همه وظایف، موعد قابل تغییر نیست.",
@@ -1287,6 +1289,7 @@
"noTargetsAvailable": "فرد یا کلینیکی برای اتصال در دسترس نیست.",
"treatmentTypes": "انواع درمان",
"workflowSteps": "مراحل گردش‌کار",
"outsourcingPrices": "قیمت‌های برون‌سپاری",
"price": "مبلغ (تومان)",
"commissionBaseHint": "کمیسیون سهمی از قیمت جدول تعرفه‌ای است که برای همان دندان‌پزشک در تاریخ درمان اعمال می‌شود.",
"commissionBaseHintLab": "کمیسیون سهمی از تعرفه لابراتوار برای کلینیک ارسال‌کننده است.",
@@ -1321,6 +1324,11 @@
"selectLab": "لابراتوار را انتخاب کنید",
"selectClinic": "کلینیک را انتخاب کنید",
"searchPatient": "جستجوی بیمار",
"partySearch": "جستجو یا نوشتن نام",
"paymentPending": "در انتظار",
"paymentDeclined": "رد شده",
"acceptPayment": "پذیرش",
"declinePayment": "رد",
"note": "یادداشت",
"notePlaceholder": "یادداشت اختیاری",
"party": "طرف",
@@ -1537,6 +1545,8 @@
"BILLING_ALLOCATION_INVALID": "یک یا چند طرح یا پرونده متصل معتبر نیست.",
"BILLING_PARTNER_INVALID": "برای این تراکنش یک کلینیک یا لابراتوار متصل انتخاب کنید.",
"BILLING_PATIENT_INVALID": "برای این دریافت یک بیمار انتخاب کنید.",
"BILLING_TRANSACTION_TYPE_INVALID": "دریافت یا پرداخت را انتخاب کنید."
"BILLING_TRANSACTION_TYPE_INVALID": "دریافت یا پرداخت را انتخاب کنید.",
"BILLING_PAYMENT_NOT_FOUND": "این پرداخت پیدا نشد.",
"BILLING_PAYMENT_ACK_INVALID": "این پرداخت دیگر قابل تأیید نیست."
}
}

View File

@@ -547,6 +547,7 @@
"fromLabBadge": "Van lab",
"sendCase": "Uitbesteden",
"sendCaseTitle": "Stappen uitbesteden",
"outsourcePrice": "Uitbestedingsprijs",
"sendCaseSelectAll": "Alles selecteren",
"sendCaseLab": "Lab",
"sendCaseLabsLoading": "Labs laden...",
@@ -877,6 +878,7 @@
"selectLab": "Bestemmingslab",
"selectLabPlaceholder": "Kies een gekoppeld lab…",
"sendToLab": "Versturen naar lab",
"labFeePreview": "Labtarief",
"dueDateLabel": "Vervaldatum",
"dueDateOptional": "optioneel",
"dueDateLockedCompleted": "Vervaldatum kan niet worden gewijzigd nadat alle taken zijn voltooid.",
@@ -1286,6 +1288,7 @@
"noTargetsAvailable": "Er zijn geen personen of klinieken om te koppelen.",
"treatmentTypes": "Behandeltypes",
"workflowSteps": "Werkstappen",
"outsourcingPrices": "Uitbestedingsprijzen",
"price": "Prijs (euro)",
"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.",
@@ -1320,6 +1323,11 @@
"selectLab": "Selecteer lab",
"selectClinic": "Selecteer kliniek",
"searchPatient": "Patiënt zoeken",
"partySearch": "Zoek of typ een naam",
"paymentPending": "Wachtend",
"paymentDeclined": "Geweigerd",
"acceptPayment": "Accepteren",
"declinePayment": "Weigeren",
"note": "Notitie",
"notePlaceholder": "Optionele notitie",
"party": "Partij",
@@ -1536,6 +1544,8 @@
"BILLING_ALLOCATION_INVALID": "Een of meer gekoppelde behandelingen of cases zijn ongeldig.",
"BILLING_PARTNER_INVALID": "Kies een gekoppelde kliniek of lab voor deze transactie.",
"BILLING_PATIENT_INVALID": "Kies een patiënt voor deze ontvangst.",
"BILLING_TRANSACTION_TYPE_INVALID": "Kies ontvangst of betaling."
"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."
}
}

View File

@@ -20,13 +20,13 @@ export type SheetLineGroup = {
/**
* One tab per catalog group so a schedule never becomes a long scroll:
* treatment types, then a tab per prosthesis category (or workflow steps for
* lab commissions).
* treatment types, then a tab per prosthesis category. Lab prices add an
* outsourcing tab. Lab commissions are one workflow-step tab.
*/
export function buildSheetLineGroups(
catalog: BillingSheetCatalog,
kind: BillingSheetKind,
labels: { treatmentTypes: string; workflowSteps: string },
labels: { treatmentTypes: string; workflowSteps: string; outsourcingPrices: string },
): SheetLineGroup[] {
if (kind === 'LAB_COMMISSION') {
return withRows([
@@ -79,6 +79,19 @@ export function buildSheetLineGroups(
}
}
if (kind === 'LAB_PRICE') {
groups.push({
key: 'outsourcing-prices',
label: labels.outsourcingPrices,
categoryCode: null,
rows: catalog.workflowSteps.map((row) => ({
catalogKind: 'LAB_WORKFLOW_STEP' as const,
code: row.code,
label: row.label,
})),
});
}
return withRows(groups);
}

View File

@@ -6,10 +6,9 @@ export type HiddenTabOrgType = 'CLINIC' | 'LAB';
export const HIDDEN_TAB_FEATURE_FLAGS = {
/**
* Billing hub stays in the codebase. Hide for listed org types this publish
* (clinic pontic pricing discussion). Empty = visible for all.
* Billing is visible for clinics and labs. Empty = visible for all.
*/
billingOrgTypes: ['CLINIC'] as readonly HiddenTabOrgType[],
billingOrgTypes: [] as readonly HiddenTabOrgType[],
reports: true,
} as const;

View File

@@ -0,0 +1,67 @@
'use client';
import { useState } from 'react';
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 function BillingPartyCombobox({
name,
selectedId,
options,
placeholder,
onChange,
}: {
name: string;
selectedId: string;
options: Array<{ id: string; label: string; hint?: string }>;
placeholder: string;
onChange: (next: { name: string; id: string }) => void;
}) {
const [open, setOpen] = useState(false);
const query = name.trim().toLowerCase();
const matches = options.filter((option) => !query || option.label.toLowerCase().includes(query));
return (
<div className="relative">
<input
className={INPUT_CLASS}
value={name}
placeholder={placeholder}
onFocus={() => setOpen(true)}
onBlur={() => window.setTimeout(() => setOpen(false), 150)}
onChange={(event) => {
const next = event.target.value;
const trimmed = next.trim();
const exact = trimmed
? options.filter((option) => option.label.trim() === trimmed)
: [];
const kept = exact.find((option) => option.id === selectedId);
onChange({ name: next, id: (kept ?? exact[0])?.id ?? '' });
}}
/>
{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>
))}
</ul>
) : null}
</div>
);
}

View File

@@ -2,7 +2,7 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslations } from 'next-intl';
import { Paperclip } from 'lucide-react';
import { Check, Paperclip, X } from 'lucide-react';
import { Button } from '@/components/ui/shared/Button';
import { Card } from '@/components/ui/shared/Card';
import { Input } from '@/components/ui/shared/Input';
@@ -14,7 +14,8 @@ import {
BILLING_FILTER_SELECT_CLASS,
BillingListToolbar,
} from '@/components/ui/billing/BillingListToolbar';
import { PatientSearchCombobox } from '@/components/ui/patient/PatientSearchCombobox';
import { BillingPartyCombobox } from '@/components/ui/billing/BillingPartyCombobox';
import { TableIconButton } from '@/components/ui/shared/TableIconButton';
import { FORM_SELECT_TALL_CLASS } from '@/components/shared/formSelectStyles';
import { billingApi } from '@/lib/api/billing';
import { getUserFacingError } from '@/components/shared/formatApiError';
@@ -30,18 +31,34 @@ import type {
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;
@@ -82,7 +99,9 @@ export function BillingPaymentsPanel({
const [amount, setAmount] = useState('');
const [note, setNote] = useState('');
const [selectedPatient, setSelectedPatient] = useState<Patient | null>(null);
const [partyName, setPartyName] = useState('');
const [counterpartId, setCounterpartId] = useState('');
const [ackBusyId, setAckBusyId] = useState<string | null>(null);
const [attachOpen, setAttachOpen] = useState(false);
const [allocSearch, setAllocSearch] = useState('');
const [allocHits, setAllocHits] = useState<Array<{ id: string; label: string; billed: string | null }>>(
@@ -93,12 +112,16 @@ export function BillingPaymentsPanel({
const clinicReceipt = isClinic && txnType === 'RECEIPT';
const partyReady = clinicReceipt ? Boolean(selectedPatient) : Boolean(counterpartId);
const {
search: patientSearch,
setSearch: setPatientSearch,
patients: patientHits,
loading: patientSearchLoading,
} = usePatientSearchQuery(formOpen && clinicReceipt, { includeWalkIn: true });
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 filters = useMemo(
() => ({
@@ -197,6 +220,7 @@ export function BillingPaymentsPanel({
setNote('');
setSelectedPatient(null);
setPatientSearch('');
setPartyName('');
setCounterpartId('');
setAttachOpen(false);
setAllocSearch('');
@@ -222,21 +246,32 @@ export function BillingPaymentsPanel({
toast.showError(t('invalidPrice'));
return;
}
if (clinicReceipt && !selectedPatient) {
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 && !counterpartId) {
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 ? selectedPatient?.id : undefined,
counterpartOrganizationId: clinicReceipt ? undefined : counterpartId,
allocations: allocations
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;
@@ -262,9 +297,30 @@ export function BillingPaymentsPanel({
}
}
async function acknowledge(id: string, decision: 'ACCEPT' | 'DECLINE') {
setAckBusyId(id);
try {
await billingApi.acknowledgePartnerPayment(id, decision);
await load();
} catch (error: unknown) {
toast.showError(getUserFacingError(error, tErrors, t('errorSavePayment')));
} finally {
setAckBusyId(null);
}
}
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,
@@ -273,12 +329,16 @@ export function BillingPaymentsPanel({
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,
@@ -287,6 +347,9 @@ export function BillingPaymentsPanel({
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));
@@ -337,6 +400,8 @@ export function BillingPaymentsPanel({
onChange={(e) => {
setTxnType(e.target.value as CashTransactionType);
setSelectedPatient(null);
setPartyName('');
setPatientSearch('');
setCounterpartId('');
setAllocations([]);
setAttachOpen(false);
@@ -356,40 +421,30 @@ export function BillingPaymentsPanel({
<div className="flex items-center gap-2">
<div className="min-w-0 flex-1">
{clinicReceipt ? (
<PatientSearchCombobox
search={patientSearch}
onSearchChange={setPatientSearch}
patients={patientHits}
loading={patientSearchLoading}
selectedPatient={selectedPatient}
onSelectPatient={setSelectedPatient}
showInlineSummary
placeholder={t('searchPatient')}
<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 className="relative">
<OutlineFieldLabel>
{isClinic ? t('selectLab') : t('selectClinic')}
</OutlineFieldLabel>
<select
className={filterSelectClass}
value={counterpartId}
onChange={(e) => {
setCounterpartId(e.target.value);
setAllocations([]);
}}
aria-label={isClinic ? t('selectLab') : t('selectClinic')}
>
<option value="">{t('selectPartner')}</option>
{partners.map((org) => (
<option key={org.id} value={org.id}>
{org.name}
</option>
))}
</select>
</div>
)}
</div>
</div>
<button
type="button"
@@ -519,14 +574,48 @@ export function BillingPaymentsPanel({
</tr>
}
body={rows.map((row) => (
<tr key={`${row.type}-${row.id}`}>
<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">
<Badge variant={row.type === 'RECEIPT' ? 'success' : 'warning'}>
{row.type === 'RECEIPT' ? t('receipt') : t('payment')}
</Badge>
<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)}

View File

@@ -70,6 +70,7 @@ export function BillingSheetEditor({
buildSheetLineGroups(catalog, kind, {
treatmentTypes: t('treatmentTypes'),
workflowSteps: t('workflowSteps'),
outsourcingPrices: t('outsourcingPrices'),
}),
[catalog, kind, t],
);

View File

@@ -10,6 +10,8 @@ import {
import { Button } from '@/components/ui/shared/Button';
import { Checkbox } from '@/components/ui/shared/Checkbox';
import { FORM_SELECT_TALL_CLASS } from '@/components/shared/formSelectStyles';
import { billingApi } from '@/lib/api/billing';
import { useAppFormatters } from '@/lib/hooks/useAppFormatters';
import { ProsthesisJobLineLabel } from '@/components/ui/lab/ProsthesisJobLineLabel';
import {
CASE_TASK_SCOPE,
@@ -71,6 +73,8 @@ export function CaseSendDialog({
}: CaseSendDialogProps) {
const t = useTranslations('cases');
const tCommon = useTranslations('common');
const { formatMoney } = useAppFormatters();
const [quote, setQuote] = useState<string | null>(null);
const [destinationId, setDestinationId] = useState('');
const [selected, setSelected] = useState<Set<string>>(new Set());
@@ -124,6 +128,31 @@ export function CaseSendDialog({
return steps;
}, [labCase.tasksByTooth]);
const selectedKey = [...selected].sort().join(',');
useEffect(() => {
if (!open || !destinationId || !labCase.id || selected.size === 0) {
setQuote(null);
return;
}
let cancelled = false;
void billingApi
.quoteOutsource({
destinationOrganizationId: destinationId,
caseId: labCase.id,
taskIds: [...selected],
})
.then((res) => {
if (!cancelled) setQuote(res.data.amount);
})
.catch(() => {
if (!cancelled) setQuote(null);
});
return () => {
cancelled = true;
};
}, [destinationId, labCase.id, open, selected, selectedKey]);
if (!open) return null;
const readyIds = [
@@ -255,6 +284,12 @@ export function CaseSendDialog({
</div>
)}
</div>
{destinationId && selected.size > 0 && quote != null ? (
<p className="text-sm text-text-secondary">
{t('outsourcePrice')}{' '}
<span className="font-medium text-text-primary tabular-nums">{formatMoney(quote)}</span>
</p>
) : null}
<div className="flex justify-end gap-2">
<Button type="button" variant="outline" onClick={onClose}>
{tCommon('cancel')}

View File

@@ -13,6 +13,8 @@ import { DetailLabCaseCommentsSection } from '@/components/ui/treatment/DetailLa
import { LabCaseTrackerCard } from '@/components/ui/treatment/LabCaseTrackerCard';
import { treatmentTypeLabelFromCatalog } from '@/components/shared/treatmentTypeDisplay';
import { treatmentsApi } from '@/lib/api/treatments';
import { billingApi } from '@/lib/api/billing';
import { useAppFormatters } from '@/lib/hooks/useAppFormatters';
import { prosthesisCatalogApi } from '@/lib/api/prosthesis-catalog';
import type { ProsthesisCatalogEntry, TreatmentCatalogEntry } from '@/types/treatment-catalog';
import type { LabCaseDraft, LinkedOrganizationOption, TreatmentDetailDraft } from '@/types/treatment';
@@ -105,6 +107,8 @@ export function LabCasesDispatchPanel({
}: LabCasesDispatchPanelProps) {
const t = useTranslations('treatment');
const tErrors = useTranslations('errors');
const { formatMoney } = useAppFormatters();
const [labFee, setLabFee] = useState<string | null>(null);
const [fetchedCatalog, setFetchedCatalog] = useState<ProsthesisCatalogEntry[]>([]);
const [pendingComment, setPendingComment] = useState('');
const hasTrackerSummary = Boolean(labCaseSummary && labCaseSummary.labCaseId);
@@ -135,6 +139,35 @@ export function LabCasesDispatchPanel({
const sent = Boolean(activeLabCase?.sentAt);
const sentPlanLocked = activeLabCase ? isSentPlanLocked(activeLabCase) : false;
const quoteLabId = !sent ? activeLabCase?.destinationOrganizationId ?? '' : '';
const quoteJobsKey = !sent
? (activeLabCase?.toothProsthesis ?? [])
.filter((row) => row.detailClientId === activeDetailId && row.prosthesisTypeCode)
.map((row) => `${row.tooth}:${row.prosthesisTypeCode}`)
.join('|')
: '';
useEffect(() => {
if (!quoteLabId) {
setLabFee(null);
return;
}
const jobs = (activeLabCase?.toothProsthesis ?? [])
.filter((row) => row.detailClientId === activeDetailId && row.prosthesisTypeCode)
.map((row) => ({ tooth: row.tooth, prosthesisTypeCode: row.prosthesisTypeCode }));
let cancelled = false;
void billingApi
.quoteLabPrice({ labOrganizationId: quoteLabId, jobs })
.then((res) => {
if (!cancelled) setLabFee(res.data.amount);
})
.catch(() => {
if (!cancelled) setLabFee(null);
});
return () => {
cancelled = true;
};
}, [activeDetailId, activeLabCase, quoteJobsKey, quoteLabId]);
const activeLabOrgName = activeLabCase?.destinationOrganizationId
? orgs.find((o) => o.id === activeLabCase.destinationOrganizationId)?.name
@@ -436,6 +469,15 @@ export function LabCasesDispatchPanel({
/>
) : null}
{quoteLabId && labFee != null ? (
<p className="text-sm text-text-secondary">
{t('labFeePreview')}{' '}
<span className="font-medium text-text-primary tabular-nums">
{formatMoney(labFee)}
</span>
</p>
) : null}
<div className="flex flex-wrap items-center gap-3 pt-1">
<Button
type="button"

View File

@@ -145,4 +145,31 @@ export const billingApi = {
const response = await apiClient.post('/billing/partner-payments', body);
return response.data;
},
acknowledgePartnerPayment: async (
id: string,
decision: 'ACCEPT' | 'DECLINE',
): Promise<{ success: boolean; data: PartnerPayment }> => {
const response = await apiClient.post(`/billing/partner-payments/${id}/acknowledge`, {
decision,
});
return response.data;
},
quoteLabPrice: async (body: {
labOrganizationId: string;
jobs: Array<{ tooth: string; prosthesisTypeCode: string }>;
}): Promise<{ success: boolean; data: { amount: string } }> => {
const response = await apiClient.post('/billing/lab-price-quote', body);
return response.data;
},
quoteOutsource: async (body: {
destinationOrganizationId: string;
caseId: string;
taskIds: string[];
}): Promise<{ success: boolean; data: { amount: string } }> => {
const response = await apiClient.post('/billing/outsource-price-quote', body);
return response.data;
},
};

View File

@@ -81,7 +81,8 @@ export type PatientPaymentAllocation = {
export type PatientPayment = {
id: string;
patientId: string;
patientId: string | null;
externalPartyName?: string | null;
patientName: string;
patientIsWalkIn: boolean;
amount: string;
@@ -99,6 +100,8 @@ export type PartnerPaymentAllocation = {
caseLabel: string;
};
export type PaymentAcknowledgement = 'pending' | 'accepted' | 'rejected' | 'none';
export type PartnerPayment = {
id: string;
amount: string;
@@ -106,9 +109,13 @@ export type PartnerPayment = {
note: string | null;
status: PartnerPaymentStatus;
recordedBy: 'CLINIC' | 'LAB';
fromOrganizationId: string;
recordedByViewer: boolean;
acknowledgement: PaymentAcknowledgement;
canAcknowledge: boolean;
externalPartyName?: string | null;
fromOrganizationId: string | null;
fromOrganizationName: string;
toOrganizationId: string;
toOrganizationId: string | null;
toOrganizationName: string;
remainder: string;
allocations: PartnerPaymentAllocation[];
@@ -144,6 +151,7 @@ export type CreatePaymentInput = {
note?: string;
patientId?: string;
counterpartOrganizationId?: string;
externalPartyName?: string;
allocations?: Array<{ targetId: string; amount: string }>;
};