diff --git a/.cursor/rules/billing.mdc b/.cursor/rules/billing.mdc index c0f6bec..656ef9a 100644 --- a/.cursor/rules/billing.mdc +++ b/.cursor/rules/billing.mdc @@ -11,6 +11,11 @@ alwaysApply: false - **Sheet kinds:** clinic `CLINIC_PRICE` / `CLINIC_COMMISSION`; lab `LAB_PRICE` (outsourcing tab first) / `LAB_COMMISSION`. Commission lines are **fixed amounts**. - **Partner ledger is shared:** Accept/Decline for the other org; typed `externalPartyName` is local (no ack). - **Transactions:** Clinic RECEIPT → patient or linked org; PAYMENT → linked org or staff (`StaffPayment`, outbound only). Lab RECEIPT/PAYMENT → linked org; PAYMENT may also be staff. Grouped `GET /billing/party-search`. Merged list: `GET /billing/transactions` (+ optional party filter + signed **net**: RECEIPT +, PAYMENT −). +- **Inline party ledger:** default table is cash only. Selecting a patient/staff/org swaps that same table to `GET /billing/party-report` obligations + cash, one neutral Amount column with a Debit/Credit marker, and an aligned balance footer. Only the final balance uses green/red (green = they owe us, red = we owe them). Case rows show Received/Generated/From lab origin. Staff selection shows persisted commission, fixed salary, and gross from closed months. +- **Cash edits:** amount, note, and valid allocations only; identity/type/currency/date/creator stay immutable. Patient/staff cash is org-editable; shared partner cash is editable only by `recorderOrganizationId`. Every shared edit resets acknowledgement to pending, uses `expectedUpdatedAt`, and appends a `BillingCashTransactionEvent`. +- **Obligations are automatic:** approved treatment → patient; sent/started/outsource case → mirrored org rows; monthly commission and fixed salary → staff. Cash creation remains separate and manual. Party reports union obligations with cash; on a party account, RECEIPT is credit and PAYMENT is debit. Shared partner cash counts for the recorder while pending; accepted cash counts for both; rejected cash stays visible to both but counts only for the recorder. +- **Fixed salary:** one sheet on Commissions/Salary (`GET`/`PUT /billing/staff-salaries`) for the owner and active members. Amounts stay on `Membership.fixedMonthlySalary`. Saving does not write a ledger row. After a month ends, the hourly job snapshots that rate once and sums that month's commissions; both are separate staff payables dated on the last day. A later edit does not change a closed month. A missed month is closed on the next run with the rate then on the sheet. Toman uses Jalali months; Dollar/Euro use Gregorian months. V1 has no attendance or proration. +- **Unpriced types:** price sheets can set `hideUnpricedTypes`. Commission sheets always store it false, and migration `20261111233000_sheet_flag_and_subscription_courtesy` sets every existing commission sheet unchecked. Existing fee sheets received false when `20261111130000_billing_obligations` added the column; their lines, targets, and dates are not rewritten. Clinic and lab chart pickers hide zero/missing-price types but keep already-selected jobs visible. An active lab sheet with the flag blocks clinic dispatch for unsupported jobs. If the flag is off and any case job is unpriced, dispatch creates mirrored pending obligations with no amount; only the destination lab's Billing editor sets the fee, which updates both sides. - 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`). diff --git a/.cursor/rules/dyolink-overview.mdc b/.cursor/rules/dyolink-overview.mdc index 00d2635..ab5cdda 100644 --- a/.cursor/rules/dyolink-overview.mdc +++ b/.cursor/rules/dyolink-overview.mdc @@ -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 (org currency lock, staff PAYMENT, party net) — `.cursor/rules/billing.mdc`, skill `.cursor/skills/billing/SKILL.md`. +- **Billing** (clinic + lab): fee/commission sheets, automatic obligations, and a cash ledger. The Commissions/Salary tab holds one current salary sheet; month-end rows are posted after the month ends. `hideUnpricedTypes` defaults off and commission sheets cannot turn it on. See `.cursor/rules/billing.mdc` and `.cursor/skills/billing/SKILL.md`. ## Agent behavior diff --git a/.cursor/skills/billing/SKILL.md b/.cursor/skills/billing/SKILL.md index 54ccf2b..4f11f2b 100644 --- a/.cursor/skills/billing/SKILL.md +++ b/.cursor/skills/billing/SKILL.md @@ -39,14 +39,23 @@ Keep chrome identical: `BillingListToolbar`, outline labels, `AppMoneyInput`, eq - Shared ledger; Accept/Decline for the counterparty. Typed external name is local. - Allocations to lab cases only for clinic↔lab pairs. +- `PartnerPayment.recorderOrganizationId` is the edit-ownership source of truth; never infer it from CLINIC/LAB because same-type links are valid. Ambiguous legacy rows are read-only. +- Recorder edits may change amount, note, and valid allocations only. They reset shared acknowledgement to `PENDING`; counterparty Accept/Decline uses `expectedUpdatedAt`. Edits and decisions append `BillingCashTransactionEvent` snapshots. ## Ledger list + net - Prefer `GET /billing/transactions` (merged rows). Optional `partyKind` + `partyId` filters server-side and returns signed `net` (RECEIPT +, PAYMENT −) for the footer. +- `BillingLedgerEntry` stores **system obligations only**. `GET /billing/party-report` unions those rows with patient/partner/staff cash for one party and date range. In this party-account view, RECEIPT is credit (reduces receivable) and PAYMENT is debit (reduces payable). Pending partner cash counts only for its recorder; accepted cash counts for both; rejected cash stays visible to both but counts only for its recorder. +- The Transactions table is cash-only until a party is selected. Selection swaps the same table to party-report rows (Time, Source, Reference, Amount, Actions) and puts the net directly below Amount; do not restore a report dialog/button. Row amounts are neutral with a compact Debit/Credit marker; only net is green/red. Case rows use origin-specific sources—Received case, Generated case, or Outsourced case—plus the matching origin badge. Received means a clinic dispatch (`CLINIC_DISPATCH`), the same origin Cases labels “From clinic.” +- Cash rows expose edit metadata/allocations. Patient and staff cash is editable by the org; partner cash only by its exact recorder. Party, direction, currency, posting date, and creator are immutable. +- Automatic sources are idempotent by `(organizationId, sourceType, sourceId)`: treatment Approve, case Send/Start, outsource, monthly commission, and monthly salary. +- Case obligations are mirrored: sender/payer books show the destination as creditor; destination books show the sender as debtor. Stop/recall/replan voids obsolete case rows. ## Fee / commission editor - Start date required. Empty Apply-to = everyone. Lines store money `amount`. +- `CLINIC_PRICE` / `LAB_PRICE` may set `hideUnpricedTypes`. Commission kinds always save it false. Existing production sheets become unchecked when the column is added; a later one-time migration forces commission sheets false again. Missing or zero prosthesis lines are hidden from the applicable chart. A destination lab's active flagged sheet also blocks clinic Send. +- With a destination `LAB_PRICE` flag off, missing/zero case prices do not become zero or partial obligations: Send creates mirrored pending obligations (`amount = null`). The destination lab's Billing editor sets the manual case fee; the service updates `LabCase.billedAmount` and both ledger rows atomically. - Treatment dispatch / outsource quote previews are not stored. - A save replaces the lines the editor shows and keeps every stored line the editor does not send (`stain`, `glaze`, `build_up`, inactive prosthesis types). Those hidden lines still price existing tasks. - Deploy migration `20261020170000_retire_billing_step_lines` copies collapsed-step prices before it deletes `design` and `design_customized_abutment`. It does not delete prosthesis-type rows or `commission_earnings`. @@ -58,6 +67,15 @@ Keep chrome identical: `BillingListToolbar`, outline labels, `AppMoneyInput`, eq ## Treatment amount approve - Approve billed amount; stamps `CommissionEarning` from `CLINIC_COMMISSION`. Set `planBilledManual` from `billedAmountManual` only. +- Approve also upserts the patient obligation; re-approve updates the same source row. + +## Fixed salary + +- One sheet on the Commissions/Salary tab, beside **New commission schedule**. It lists the owner and every active member. `PUT /billing/staff-salaries` updates `Membership.fixedMonthlySalary` and does not create a ledger row or a new sheet. +- After the first save, a Staff salary section with one Edit row sits above Commission history. `Organization.staffSalaryUpdatedAt` is that marker. +- The hourly job writes a finished month only. Commission is that month's earnings. Salary is snapshotted once from the sheet; a later edit does not change it. A month the server missed is closed on the next run with the rate on the sheet then. Rows are dated on the last day. The open month stays out of the ledger. Toman uses Jalali months; Dollar/Euro use Gregorian months. +- Staff summary subtotals come from those closed rows in the active date range: commission + fixed salary = gross. Cash affects net only. Staff cash remains `StaffPayment`. +- V1 deliberately has no attendance, proration, bonus, or payroll-tax model. ## Deep links diff --git a/AGENTS.md b/AGENTS.md index e0f2280..3fdc83c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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`. -**Subscriptions (quick ref):** One **Base** plan includes 3 seats (the owner holds one). Extra seats are separate rows with their own end dates. Each owner gets one free month (`User.trialUsedAt`), stamped only after `grantForNewOwner` starts it. Do not set `trialUsedAt` before that call. A later organization gets Base seats that end immediately. Another organization with the same owner that already has `trialEndsAt` or any seat counts as later, even when `trialUsedAt` is still null. Migration `20261018120000_subscription_seats` runs once on deploy: every real organization gets Base for 30 days from that instant, 3 included seats, and an extra seat for each staff member past those 3. It does not set `trialUsedAt` and does not insert charge rows. Disabled members who are not the owner and have no open invite do not take a seat. Migration `20261023140000_drop_unreferenced_legacy_plans` deletes unused `trial`, `Small`, `Medium`, `Large`, and `Enterprise` plans and does not change any end date. Signup ensures the `base` plan. The free month is labeled Trial in the UI; the stored plan name stays `base`. Invitation placeholders (no members, and an invite that is still unaccepted) are left unchanged. During the free month an added seat costs $0 and ends with the base seats. After it, Add seat and Extend selected show the quote and then stop (`SUBSCRIPTION_PAYMENT_UNAVAILABLE`, contact Nudenticco@gmail.com). An overdue occupied seat is read-only. An overdue empty seat cannot be reserved. Owners and `TAB_BILLING_READ` manage Subscriptions. Cards show the assigned user. Other members get a `SEAT_EXPIRING` inbox notice 5 days before their seat ends. +**Subscriptions (quick ref):** One **Base** plan includes 3 seats (the owner holds one). Extra seats are separate rows with their own end dates. Each owner gets one free month (`User.trialUsedAt`), stamped only after `grantForNewOwner` starts it. Do not set `trialUsedAt` before that call. A later organization gets Base seats that end immediately. Another organization with the same owner that already has `trialEndsAt` or any seat counts as later, even when `trialUsedAt` is still null. Migration `20261018120000_subscription_seats` runs once on deploy: every real organization gets Base for 30 days from that instant, 3 included seats, and an extra seat for each staff member past those 3. It does not set `trialUsedAt` and does not insert charge rows. Disabled members who are not the owner and have no open invite do not take a seat. Migration `20261023140000_drop_unreferenced_legacy_plans` deletes unused `trial`, `Small`, `Medium`, `Large`, and `Enterprise` plans and does not change any end date. Migration `20261111233000_sheet_flag_and_subscription_courtesy` runs once: every existing seat and every non-null `trialEndsAt` gains 60 days (two 30-day subscription months). A date still in the future grows from itself; a date already past grows from that deploy. It does not insert seats or charge rows, and later deploys must not repeat it. Signup ensures the `base` plan. The free month is labeled Trial in the UI; the stored plan name stays `base`. Invitation placeholders (no members, and an invite that is still unaccepted) are left unchanged. During the free month an added seat costs $0 and ends with the base seats. After it, Add seat and Extend selected show the quote and then stop (`SUBSCRIPTION_PAYMENT_UNAVAILABLE`, contact Nudenticco@gmail.com). An overdue occupied seat is read-only. An overdue empty seat cannot be reserved. Owners and `TAB_BILLING_READ` manage Subscriptions. Cards show the assigned user. Other members get a `SEAT_EXPIRING` inbox notice 5 days before their seat ends. -**Billing (quick ref):** Same three-tab hub for CLINIC + LAB (`/billing?view=`). Clinic: `CLINIC_PRICE` / `CLINIC_COMMISSION` + patient receipts + partner payments. Lab: `LAB_PRICE` (prosthesis fees plus an outsourcing tab) / `LAB_COMMISSION` + partner ledger only. Commissions are **fixed amounts** (not percents). Dispatch and outsource prices are previews and are not stored. Collapsed workflow prices are copied onto the combined steps at deploy; `stain`, `glaze`, and `build_up` lines stay so existing tasks still resolve, and a sheet save keeps lines the editor does not show. Prosthesis fee rows, recorded commission earnings, and existing case tasks stay as they are. Partner list is a **shared** ledger: the sender’s row counts immediately, and the other org Accepts or Declines it. A typed party name stays local. Money inputs: `AppMoneyInput`. Billing is visible for both org types. See `.cursor/rules/billing.mdc`, `.cursor/skills/billing/SKILL.md`. +**Billing (quick ref):** Same three-tab hub for CLINIC + LAB (`/billing?view=`). Clinic: `CLINIC_PRICE` / `CLINIC_COMMISSION` + patient receipts + partner payments. Lab: `LAB_PRICE` (prosthesis fees plus an outsourcing tab) / `LAB_COMMISSION` + partner ledger only. Commissions are **fixed amounts**. Automatic `BillingLedgerEntry` obligations come from treatment Approve, case Send/Start/outsource, and staff commission plus fixed salary after each month ends; Toman uses Jalali months, Dollar/Euro Gregorian. Selecting a party swaps the cash table to an inline obligation+cash ledger with signed amount/net; selected staff also show commission, fixed salary, and gross from closed months. Partner cash remains shared Accept/Decline; rejected rows stay visible to both but count only for the recorder. Only the exact recorder can edit shared cash, and edits reset acknowledgement. Salary is one editable sheet on Commissions/Salary for the owner and active members; editing it does not change a closed month. Salary and commission may both apply; v1 has no proration/attendance. Price sheets may hide unpriced prosthesis types; existing fee and commission sheets deploy with that box unchecked, and commission sheets cannot turn it on. An active flagged lab sheet blocks clinic dispatch for unsupported jobs. If the flag is off, an unpriced case creates mirrored amount-pending obligations; only the destination lab sets the fee and it updates both orgs. Collapsed workflow prices and hidden legacy lines remain preserved. Money inputs: `AppMoneyInput`. See `.cursor/rules/billing.mdc`, `.cursor/skills/billing/SKILL.md`. **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`. diff --git a/backend/prisma/migrations/20261111130000_billing_obligations/migration.sql b/backend/prisma/migrations/20261111130000_billing_obligations/migration.sql new file mode 100644 index 0000000..0443f79 --- /dev/null +++ b/backend/prisma/migrations/20261111130000_billing_obligations/migration.sql @@ -0,0 +1,56 @@ +-- CreateEnum +CREATE TYPE "BillingLedgerPartyKind" AS ENUM ('PATIENT', 'STAFF', 'ORGANIZATION'); + +-- CreateEnum +CREATE TYPE "BillingLedgerEntryKind" AS ENUM ('OBLIGATION'); + +-- CreateEnum +CREATE TYPE "BillingObligationSourceType" AS ENUM ( + 'TREATMENT_APPROVE', + 'LAB_CASE', + 'OUTSOURCE_CASE', + 'STAFF_COMMISSION_MONTH', + 'STAFF_SALARY_MONTH' +); + +-- AlterTable +ALTER TABLE "billing_sheets" +ADD COLUMN "hideUnpricedTypes" BOOLEAN NOT NULL DEFAULT false; + +-- AlterTable +ALTER TABLE "memberships" +ADD COLUMN "fixedMonthlySalary" DECIMAL(14,2); + +-- CreateTable +CREATE TABLE "billing_ledger_entries" ( + "id" TEXT NOT NULL, + "organizationId" TEXT NOT NULL, + "partyKind" "BillingLedgerPartyKind" NOT NULL, + "partyId" TEXT NOT NULL, + "entryKind" "BillingLedgerEntryKind" NOT NULL DEFAULT 'OBLIGATION', + "sourceType" "BillingObligationSourceType" NOT NULL, + "sourceId" TEXT NOT NULL, + "amount" DECIMAL(14,2) NOT NULL, + "signedAmount" DECIMAL(14,2) NOT NULL, + "occurredAt" TIMESTAMP(3) NOT NULL, + "note" TEXT, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "billing_ledger_entries_pkey" PRIMARY KEY ("id"), + CONSTRAINT "billing_ledger_entries_amount_positive" CHECK ("amount" > 0), + CONSTRAINT "billing_ledger_entries_signed_nonzero" CHECK ("signedAmount" <> 0) +); + +-- CreateIndex +CREATE UNIQUE INDEX "billing_ledger_entries_organizationId_sourceType_sourceId_key" +ON "billing_ledger_entries"("organizationId", "sourceType", "sourceId"); + +-- CreateIndex +CREATE INDEX "billing_ledger_entries_organizationId_partyKind_partyId_occurredAt_idx" +ON "billing_ledger_entries"("organizationId", "partyKind", "partyId", "occurredAt"); + +-- AddForeignKey +ALTER TABLE "billing_ledger_entries" +ADD CONSTRAINT "billing_ledger_entries_organizationId_fkey" +FOREIGN KEY ("organizationId") REFERENCES "organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/backend/prisma/migrations/20261111163000_staff_billing_periods/migration.sql b/backend/prisma/migrations/20261111163000_staff_billing_periods/migration.sql new file mode 100644 index 0000000..42efde9 --- /dev/null +++ b/backend/prisma/migrations/20261111163000_staff_billing_periods/migration.sql @@ -0,0 +1,5 @@ +-- Staff month boundaries now follow the organization's billing currency: +-- Toman uses Jalali months; Dollar and Euro use Gregorian months. +-- These rows are derived and are recreated lazily or by the scheduled rollup. +DELETE FROM "billing_ledger_entries" +WHERE "sourceType" IN ('STAFF_COMMISSION_MONTH', 'STAFF_SALARY_MONTH'); diff --git a/backend/prisma/migrations/20261111170000_pending_case_obligations/migration.sql b/backend/prisma/migrations/20261111170000_pending_case_obligations/migration.sql new file mode 100644 index 0000000..4c1c193 --- /dev/null +++ b/backend/prisma/migrations/20261111170000_pending_case_obligations/migration.sql @@ -0,0 +1,27 @@ +ALTER TABLE "billing_ledger_entries" +ADD COLUMN "balanceSign" INTEGER NOT NULL DEFAULT 1; + +UPDATE "billing_ledger_entries" +SET "balanceSign" = CASE WHEN "signedAmount" < 0 THEN -1 ELSE 1 END; + +ALTER TABLE "billing_ledger_entries" +ALTER COLUMN "balanceSign" DROP DEFAULT, +ALTER COLUMN "amount" DROP NOT NULL, +ALTER COLUMN "signedAmount" DROP NOT NULL; + +ALTER TABLE "billing_ledger_entries" +DROP CONSTRAINT "billing_ledger_entries_amount_positive", +DROP CONSTRAINT "billing_ledger_entries_signed_nonzero"; + +ALTER TABLE "billing_ledger_entries" +ADD CONSTRAINT "billing_ledger_entries_balance_sign" +CHECK ("balanceSign" IN (-1, 1)), +ADD CONSTRAINT "billing_ledger_entries_amount_state" +CHECK ( + ("amount" IS NULL AND "signedAmount" IS NULL) + OR + ( + "amount" > 0 + AND "signedAmount" = "amount" * "balanceSign" + ) +); diff --git a/backend/prisma/migrations/20261111190000_billing_cash_edit_contract/migration.sql b/backend/prisma/migrations/20261111190000_billing_cash_edit_contract/migration.sql new file mode 100644 index 0000000..abccfb0 --- /dev/null +++ b/backend/prisma/migrations/20261111190000_billing_cash_edit_contract/migration.sql @@ -0,0 +1,88 @@ +-- CreateEnum +CREATE TYPE "BillingCashPaymentKind" AS ENUM ('PATIENT', 'PARTNER', 'STAFF'); + +-- CreateEnum +CREATE TYPE "BillingCashEventType" AS ENUM ('EDITED', 'ACCEPTED', 'REJECTED'); + +-- AlterTable +ALTER TABLE "partner_payments" ADD COLUMN "recorderOrganizationId" TEXT; + +-- Backfill the exact recorder when the row has one local side, or when org types +-- make the legacy CLINIC/LAB marker unambiguous. Same-type legacy rows remain null. +UPDATE "partner_payments" AS pp +SET "recorderOrganizationId" = CASE + WHEN pp."fromOrganizationId" IS NULL THEN pp."toOrganizationId" + WHEN pp."toOrganizationId" IS NULL THEN pp."fromOrganizationId" + WHEN pp."recordedBy"::text = from_type."name" + AND pp."recordedBy"::text <> to_type."name" THEN pp."fromOrganizationId" + WHEN pp."recordedBy"::text = to_type."name" + AND pp."recordedBy"::text <> from_type."name" THEN pp."toOrganizationId" + ELSE NULL +END +FROM "organizations" AS from_org +JOIN "organization_types" AS from_type ON from_type."id" = from_org."typeId", + "organizations" AS to_org +JOIN "organization_types" AS to_type ON to_type."id" = to_org."typeId" +WHERE from_org."id" = pp."fromOrganizationId" + AND to_org."id" = pp."toOrganizationId"; + +UPDATE "partner_payments" +SET "recorderOrganizationId" = COALESCE("fromOrganizationId", "toOrganizationId") +WHERE "recorderOrganizationId" IS NULL + AND ("fromOrganizationId" IS NULL OR "toOrganizationId" IS NULL); + +-- Normalize existing acknowledgement states. Local external payments are final; +-- shared rows without a decision are pending. +UPDATE "partner_payments" +SET "status" = CASE + WHEN "receiptRejectedAt" IS NOT NULL THEN 'REJECTED'::"PartnerPaymentStatus" + WHEN "receiptConfirmedAt" IS NOT NULL THEN 'CONFIRMED'::"PartnerPaymentStatus" + WHEN "fromOrganizationId" IS NULL OR "toOrganizationId" IS NULL + THEN 'CONFIRMED'::"PartnerPaymentStatus" + ELSE 'PENDING'::"PartnerPaymentStatus" +END; + +-- CreateTable +CREATE TABLE "billing_cash_transaction_events" ( + "id" TEXT NOT NULL, + "paymentKind" "BillingCashPaymentKind" NOT NULL, + "paymentId" TEXT NOT NULL, + "eventType" "BillingCashEventType" NOT NULL, + "organizationId" TEXT NOT NULL, + "actorUserId" TEXT NOT NULL, + "beforeSnapshot" JSONB NOT NULL, + "afterSnapshot" JSONB NOT NULL, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "billing_cash_transaction_events_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE INDEX "partner_payments_recorderOrganizationId_paidAt_idx" +ON "partner_payments"("recorderOrganizationId", "paidAt"); + +-- CreateIndex +CREATE INDEX "billing_cash_transaction_events_paymentKind_paymentId_createdAt_idx" +ON "billing_cash_transaction_events"("paymentKind", "paymentId", "createdAt"); + +-- CreateIndex +CREATE INDEX "billing_cash_transaction_events_organizationId_createdAt_idx" +ON "billing_cash_transaction_events"("organizationId", "createdAt"); + +-- AddForeignKey +ALTER TABLE "partner_payments" +ADD CONSTRAINT "partner_payments_recorderOrganizationId_fkey" +FOREIGN KEY ("recorderOrganizationId") REFERENCES "organizations"("id") +ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "billing_cash_transaction_events" +ADD CONSTRAINT "billing_cash_transaction_events_organizationId_fkey" +FOREIGN KEY ("organizationId") REFERENCES "organizations"("id") +ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "billing_cash_transaction_events" +ADD CONSTRAINT "billing_cash_transaction_events_actorUserId_fkey" +FOREIGN KEY ("actorUserId") REFERENCES "users"("id") +ON DELETE RESTRICT ON UPDATE CASCADE; diff --git a/backend/prisma/migrations/20261111210000_staff_salary_sheet/migration.sql b/backend/prisma/migrations/20261111210000_staff_salary_sheet/migration.sql new file mode 100644 index 0000000..9a99d94 --- /dev/null +++ b/backend/prisma/migrations/20261111210000_staff_salary_sheet/migration.sql @@ -0,0 +1,4 @@ +-- One current staff salary sheet per organization. Month-end snapshots stay on ledger rows. +ALTER TABLE "organizations" + ADD COLUMN "staffSalaryUpdatedAt" TIMESTAMP(3), + ADD COLUMN "staffBillingClosedThrough" TEXT; diff --git a/backend/prisma/migrations/20261111233000_sheet_flag_and_subscription_courtesy/migration.sql b/backend/prisma/migrations/20261111233000_sheet_flag_and_subscription_courtesy/migration.sql new file mode 100644 index 0000000..98b8817 --- /dev/null +++ b/backend/prisma/migrations/20261111233000_sheet_flag_and_subscription_courtesy/migration.sql @@ -0,0 +1,25 @@ +-- Existing commission sheets never use the price-sheet checkbox. +-- Fee sheets added this column as false and are left as saved. +UPDATE "billing_sheets" +SET "hideUnpricedTypes" = false +WHERE "kind" IN ('CLINIC_COMMISSION', 'LAB_COMMISSION'); + +-- One courtesy only. Prisma records this migration and does not run it again. +-- A subscription month is 30 days, so two months is 60 days. +-- A due date still in the future grows from that date. +-- A due date already past grows from this deploy, so the extra time is usable. +-- Charge history is not changed. +UPDATE "organization_seats" +SET + "endsAt" = CASE + WHEN "endsAt" > CURRENT_TIMESTAMP THEN "endsAt" + INTERVAL '60 days' + ELSE CURRENT_TIMESTAMP + INTERVAL '60 days' + END, + "updatedAt" = CURRENT_TIMESTAMP; + +UPDATE "organizations" +SET "trialEndsAt" = CASE + WHEN "trialEndsAt" > CURRENT_TIMESTAMP THEN "trialEndsAt" + INTERVAL '60 days' + ELSE CURRENT_TIMESTAMP + INTERVAL '60 days' +END +WHERE "trialEndsAt" IS NOT NULL; diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 83797f1..a59e068 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -40,6 +40,7 @@ model User { createdStaffPayments StaffPayment[] @relation("StaffPaymentCreatedBy") staffPayments StaffPayment[] @relation("StaffPaymentUser") commissionEarnings CommissionEarning[] + billingCashTransactionEvents BillingCashTransactionEvent[] subscriptionCharges SubscriptionCharge[] createdAt DateTime @default(now()) @@ -125,12 +126,19 @@ model Organization { billingSheetClinicTargets BillingSheetTarget[] @relation("BillingSheetTargetClinic") /// Locked after the first cash transaction (or inferred as TOMAN when legacy cash exists). billingCurrency BillingCurrency? + /// First save of the single staff salary sheet. Null means that sheet does not exist yet. + staffSalaryUpdatedAt DateTime? + /// Last finished staff period whose salary snapshot is settled. Set on the first sheet save. + staffBillingClosedThrough String? patientPayments PatientPayment[] partnerPaymentsFrom PartnerPayment[] @relation("PartnerPaymentFrom") partnerPaymentsTo PartnerPayment[] @relation("PartnerPaymentTo") + recordedPartnerPayments PartnerPayment[] @relation("PartnerPaymentRecorder") staffPayments StaffPayment[] commissionEarnings CommissionEarning[] + billingLedgerEntries BillingLedgerEntry[] + billingCashTransactionEvents BillingCashTransactionEvent[] createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@ -747,6 +755,8 @@ model Membership { isOwner Boolean @default(false) isActive Boolean @default(true) + /// Current fixed monthly salary. A closed month keeps the amount it snapshotted. + fixedMonthlySalary Decimal? @db.Decimal(14, 2) user User @relation(fields: [userId], references: [id]) organization Organization @relation(fields: [organizationId], references: [id]) @@ -961,18 +971,50 @@ enum PartnerPaymentRecordedBy { LAB } +enum BillingCashPaymentKind { + PATIENT + PARTNER + STAFF +} + +enum BillingCashEventType { + EDITED + ACCEPTED + REJECTED +} + enum BillingCurrency { TOMAN DOLLAR EURO } +enum BillingLedgerPartyKind { + PATIENT + STAFF + ORGANIZATION +} + +enum BillingLedgerEntryKind { + OBLIGATION +} + +enum BillingObligationSourceType { + TREATMENT_APPROVE + LAB_CASE + OUTSOURCE_CASE + STAFF_COMMISSION_MONTH + STAFF_SALARY_MONTH +} + model BillingSheet { id String @id @default(uuid()) organizationId String kind BillingSheetKind name String? effectiveOn DateTime @db.Date + /// On price sheets, hide unpriced prosthesis types and block unsupported dispatches. + hideUnpricedTypes Boolean @default(false) organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade) targets BillingSheetTarget[] @@ -1065,6 +1107,8 @@ model PartnerPayment { note String? status PartnerPaymentStatus recordedBy PartnerPaymentRecordedBy + /// Exact recorder for edit ownership. Null only for ambiguous legacy same-type rows. + recorderOrganizationId String? /// 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. @@ -1073,6 +1117,7 @@ model PartnerPayment { fromOrganization Organization? @relation("PartnerPaymentFrom", fields: [fromOrganizationId], references: [id], onDelete: Cascade) toOrganization Organization? @relation("PartnerPaymentTo", fields: [toOrganizationId], references: [id], onDelete: Cascade) + recorderOrganization Organization? @relation("PartnerPaymentRecorder", fields: [recorderOrganizationId], references: [id], onDelete: Restrict) createdBy User @relation("PartnerPaymentCreatedBy", fields: [createdByUserId], references: [id], onDelete: Restrict) allocations PartnerPaymentAllocation[] @@ -1081,6 +1126,7 @@ model PartnerPayment { @@index([fromOrganizationId, paidAt]) @@index([toOrganizationId, paidAt]) + @@index([recorderOrganizationId, paidAt]) @@map("partner_payments") } @@ -1151,3 +1197,51 @@ model CommissionEarning { @@index([labCaseId, catalogCode]) @@map("commission_earnings") } + +/// System-generated debit/credit obligation on one organization's books. +/// Cash stays in the existing payment tables and is merged at report time. +model BillingLedgerEntry { + id String @id @default(uuid()) + organizationId String + partyKind BillingLedgerPartyKind + partyId String + entryKind BillingLedgerEntryKind @default(OBLIGATION) + sourceType BillingObligationSourceType + sourceId String + /// Null means the obligation exists but its fee still needs to be set. + amount Decimal? @db.Decimal(14, 2) + signedAmount Decimal? @db.Decimal(14, 2) + /// Party-account sign: +1 party owes this org; -1 this org owes the party. + balanceSign Int + occurredAt DateTime + note String? + + organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade) + + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@unique([organizationId, sourceType, sourceId]) + @@index([organizationId, partyKind, partyId, occurredAt]) + @@map("billing_ledger_entries") +} + +/// Append-only audit of cash edits and shared acknowledgement decisions. +model BillingCashTransactionEvent { + id String @id @default(uuid()) + paymentKind BillingCashPaymentKind + paymentId String + eventType BillingCashEventType + organizationId String + actorUserId String + beforeSnapshot Json + afterSnapshot Json + createdAt DateTime @default(now()) + + organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict) + actor User @relation(fields: [actorUserId], references: [id], onDelete: Restrict) + + @@index([paymentKind, paymentId, createdAt]) + @@index([organizationId, createdAt]) + @@map("billing_cash_transaction_events") +} diff --git a/backend/prisma/wipe-app-data.ts b/backend/prisma/wipe-app-data.ts index 1680566..d11809d 100644 --- a/backend/prisma/wipe-app-data.ts +++ b/backend/prisma/wipe-app-data.ts @@ -37,10 +37,12 @@ const CATALOG_TABLES = new Set([ const TABLES_IN_ORDER = [ 'email_verification_codes', 'phone_verification_codes', + 'billing_ledger_entries', 'patient_payment_allocations', 'patient_payments', 'partner_payment_allocations', 'partner_payments', + 'staff_payments', 'commission_earnings', 'billing_sheet_lines', 'billing_sheet_targets', diff --git a/backend/src/admin/resources.ts b/backend/src/admin/resources.ts index 99d5672..5e865b9 100644 --- a/backend/src/admin/resources.ts +++ b/backend/src/admin/resources.ts @@ -42,6 +42,13 @@ const catalogActions: ResourceOptions['actions'] = { bulkDelete: { isAccessible: false }, }; +const readOnlyActions: ResourceOptions['actions'] = { + new: { isAccessible: false }, + edit: { isAccessible: false }, + delete: { isAccessible: false }, + bulkDelete: { isAccessible: false }, +}; + /** listedAt is trigger-maintained; never send it on AdminJS writes. */ const omitListedAt = (request: AdminActionRequest): AdminActionRequest => { if (request.payload && 'listedAt' in request.payload) { @@ -237,21 +244,35 @@ export function buildAdminResources(prisma: PrismaService): AdminResource[] { }), resource(prisma, 'PatientPayment', { navigation: { name: 'Billing', icon: 'CreditCard' }, + actions: readOnlyActions, }), resource(prisma, 'PatientPaymentAllocation', { navigation: { name: 'Billing', icon: 'CreditCard' }, + actions: readOnlyActions, }), resource(prisma, 'PartnerPayment', { navigation: { name: 'Billing', icon: 'CreditCard' }, + actions: readOnlyActions, }), resource(prisma, 'PartnerPaymentAllocation', { navigation: { name: 'Billing', icon: 'CreditCard' }, + actions: readOnlyActions, }), resource(prisma, 'StaffPayment', { navigation: { name: 'Billing', icon: 'CreditCard' }, + actions: readOnlyActions, }), resource(prisma, 'CommissionEarning', { navigation: { name: 'Billing', icon: 'CreditCard' }, + actions: readOnlyActions, + }), + resource(prisma, 'BillingLedgerEntry', { + navigation: { name: 'Billing', icon: 'CreditCard' }, + actions: readOnlyActions, + }), + resource(prisma, 'BillingCashTransactionEvent', { + navigation: { name: 'Billing', icon: 'CreditCard' }, + actions: readOnlyActions, }), ]; } diff --git a/backend/src/common/errors/error-codes.ts b/backend/src/common/errors/error-codes.ts index 26404b7..891ae1b 100644 --- a/backend/src/common/errors/error-codes.ts +++ b/backend/src/common/errors/error-codes.ts @@ -226,10 +226,14 @@ 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_PAYMENT_NOT_EDITABLE: 'BILLING_PAYMENT_NOT_EDITABLE', + BILLING_TRANSACTION_CHANGED: 'BILLING_TRANSACTION_CHANGED', BILLING_CURRENCY_REQUIRED: 'BILLING_CURRENCY_REQUIRED', BILLING_CURRENCY_INVALID: 'BILLING_CURRENCY_INVALID', BILLING_STAFF_INVALID: 'BILLING_STAFF_INVALID', BILLING_PARTY_INVALID: 'BILLING_PARTY_INVALID', + BILLING_PROSTHESIS_NOT_PROVIDED: 'BILLING_PROSTHESIS_NOT_PROVIDED', + BILLING_OBLIGATION_NOT_EDITABLE: 'BILLING_OBLIGATION_NOT_EDITABLE', SUBSCRIPTION_READ_ONLY: 'SUBSCRIPTION_READ_ONLY', SUBSCRIPTION_MANAGE_DENIED: 'SUBSCRIPTION_MANAGE_DENIED', diff --git a/backend/src/modules/auth/auth.service.ts b/backend/src/modules/auth/auth.service.ts index 9a492c3..a3aa482 100644 --- a/backend/src/modules/auth/auth.service.ts +++ b/backend/src/modules/auth/auth.service.ts @@ -55,22 +55,24 @@ import { import { SubscriptionService } from '../subscription/subscription.service'; import * as crypto from 'crypto'; +const membershipClientInclude = { + organization: { + include: { + type: true, + plan: true, + }, + }, + permissions: { + include: { + permission: true, + }, + }, + seat: { select: { endsAt: true } }, +} satisfies Prisma.MembershipInclude; + const loginUserInclude = { memberships: { - include: { - organization: { - include: { - type: true, - plan: true, - }, - }, - permissions: { - include: { - permission: true, - }, - }, - seat: { select: { endsAt: true } }, - }, + include: membershipClientInclude, }, } satisfies Prisma.UserInclude; @@ -192,23 +194,7 @@ export class AuthService { const normalizedEmail = email.trim().toLowerCase(); const user = await this.prisma.user.findUnique({ where: { email: normalizedEmail }, - include: { - memberships: { - include: { - organization: { - include: { - type: true, // Include organization type (CLINIC/LAB) - plan: true, - } - }, - permissions: { - include: { - permission: true, // Include permission details - }, - }, - }, - }, - }, + include: loginUserInclude, }); if (!user) { @@ -510,24 +496,7 @@ export class AuthService { try { const user = await this.prisma.user.findUnique({ where: { id: userId }, - include: { - memberships: { - include: { - organization: { - include: { - type: true, - plan: true, - }, - }, - permissions: { - include: { - permission: true, - }, - }, - seat: { select: { endsAt: true } }, - }, - }, - }, + include: loginUserInclude, }); if (!user) { @@ -599,24 +568,7 @@ export class AuthService { }, include: { user: { - include: { - memberships: { - include: { - organization: { - include: { - type: true, - plan: true, - }, - }, - permissions: { - include: { - permission: true, - }, - }, - seat: { select: { endsAt: true } }, - }, - }, - }, + include: loginUserInclude, }, }, }); @@ -824,23 +776,7 @@ export class AuthService { const user = await this.prisma.user.findUnique({ where: { mobile }, - include: { - memberships: { - include: { - organization: { - include: { - type: true, - plan: true, - }, - }, - permissions: { - include: { - permission: true, - }, - }, - }, - }, - }, + include: loginUserInclude, }); if (!user) { @@ -1064,24 +1000,7 @@ export class AuthService { }, include: { user: { - include: { - memberships: { - include: { - organization: { - include: { - type: true, - plan: true, - }, - }, - permissions: { - include: { - permission: true, - }, - }, - seat: { select: { endsAt: true } }, - }, - }, - }, + include: loginUserInclude, }, }, }); @@ -1117,18 +1036,7 @@ export class AuthService { }, include: { user: true, - organization: { - include: { - type: true, - plan: true, - }, - }, - permissions: { - include: { - permission: true, - }, - }, - seat: { select: { endsAt: true } }, + ...membershipClientInclude, }, }); diff --git a/backend/src/modules/billing/billing-case-obligation.spec.ts b/backend/src/modules/billing/billing-case-obligation.spec.ts new file mode 100644 index 0000000..7c6008d --- /dev/null +++ b/backend/src/modules/billing/billing-case-obligation.spec.ts @@ -0,0 +1,64 @@ +import { BillingObligationSourceType, LabCaseOrigin } from '@prisma/client'; +import { resolvePartnerCaseObligation } from './billing-case-obligation'; + +describe('resolvePartnerCaseObligation', () => { + it('creates a clinic-to-lab obligation for a received case', () => { + expect( + resolvePartnerCaseObligation({ + origin: LabCaseOrigin.CLINIC_DISPATCH, + destinationOrganizationId: 'lab', + treatmentOrganizationId: 'clinic', + partnerClinicOrganizationId: null, + parentDestinationOrganizationId: null, + }), + ).toEqual({ + sourceType: BillingObligationSourceType.LAB_CASE, + payerOrganizationId: 'clinic', + payeeOrganizationId: 'lab', + }); + }); + + it('creates the same mirrored obligation parties for a generated linked-clinic case', () => { + expect( + resolvePartnerCaseObligation({ + origin: LabCaseOrigin.LAB_INTERNAL, + destinationOrganizationId: 'lab', + treatmentOrganizationId: null, + partnerClinicOrganizationId: 'clinic', + parentDestinationOrganizationId: null, + }), + ).toEqual({ + sourceType: BillingObligationSourceType.LAB_CASE, + payerOrganizationId: 'clinic', + payeeOrganizationId: 'lab', + }); + }); + + it('uses the sending lab as payer for an outsourced case', () => { + expect( + resolvePartnerCaseObligation({ + origin: LabCaseOrigin.LAB_OUTSOURCE, + destinationOrganizationId: 'destination-lab', + treatmentOrganizationId: null, + partnerClinicOrganizationId: null, + parentDestinationOrganizationId: 'sending-lab', + }), + ).toEqual({ + sourceType: BillingObligationSourceType.OUTSOURCE_CASE, + payerOrganizationId: 'sending-lab', + payeeOrganizationId: 'destination-lab', + }); + }); + + it('does not create an inter-organization obligation without a linked payer', () => { + expect( + resolvePartnerCaseObligation({ + origin: LabCaseOrigin.LAB_INTERNAL, + destinationOrganizationId: 'lab', + treatmentOrganizationId: null, + partnerClinicOrganizationId: null, + parentDestinationOrganizationId: null, + }), + ).toBeNull(); + }); +}); diff --git a/backend/src/modules/billing/billing-case-obligation.ts b/backend/src/modules/billing/billing-case-obligation.ts new file mode 100644 index 0000000..f41cd5e --- /dev/null +++ b/backend/src/modules/billing/billing-case-obligation.ts @@ -0,0 +1,36 @@ +import { BillingObligationSourceType, LabCaseOrigin } from '@prisma/client'; + +export function resolvePartnerCaseObligation(input: { + origin: LabCaseOrigin; + destinationOrganizationId: string | null; + treatmentOrganizationId: string | null; + partnerClinicOrganizationId: string | null; + parentDestinationOrganizationId: string | null; +}): { + sourceType: BillingObligationSourceType; + payerOrganizationId: string; + payeeOrganizationId: string; +} | null { + const sourceType = + input.origin === LabCaseOrigin.LAB_OUTSOURCE + ? BillingObligationSourceType.OUTSOURCE_CASE + : BillingObligationSourceType.LAB_CASE; + const payerOrganizationId = + input.origin === LabCaseOrigin.LAB_OUTSOURCE + ? input.parentDestinationOrganizationId + : (input.treatmentOrganizationId ?? input.partnerClinicOrganizationId); + const payeeOrganizationId = input.destinationOrganizationId; + + if ( + !payerOrganizationId || + !payeeOrganizationId || + payerOrganizationId === payeeOrganizationId + ) { + return null; + } + return { + sourceType, + payerOrganizationId, + payeeOrganizationId, + }; +} diff --git a/backend/src/modules/billing/billing-cash-edit.spec.ts b/backend/src/modules/billing/billing-cash-edit.spec.ts new file mode 100644 index 0000000..e9859c1 --- /dev/null +++ b/backend/src/modules/billing/billing-cash-edit.spec.ts @@ -0,0 +1,36 @@ +import { resolvePartnerCashSides } from './billing-cash-edit'; + +describe('resolvePartnerCashSides', () => { + it('uses the exact recorder for same-type linked organizations', () => { + expect( + resolvePartnerCashSides({ + from: { id: 'lab-a', typeName: 'LAB' }, + to: { id: 'lab-b', typeName: 'LAB' }, + recorderOrganizationId: 'lab-b', + recordedBy: 'LAB', + }), + ).toEqual({ senderId: 'lab-b', counterpartyId: 'lab-a' }); + }); + + it('keeps ambiguous same-type legacy rows read-only', () => { + expect( + resolvePartnerCashSides({ + from: { id: 'lab-a', typeName: 'LAB' }, + to: { id: 'lab-b', typeName: 'LAB' }, + recorderOrganizationId: null, + recordedBy: 'LAB', + }), + ).toEqual({ senderId: null, counterpartyId: null }); + }); + + it('supports unambiguous clinic/lab legacy rows', () => { + expect( + resolvePartnerCashSides({ + from: { id: 'clinic', typeName: 'CLINIC' }, + to: { id: 'lab', typeName: 'LAB' }, + recorderOrganizationId: null, + recordedBy: 'CLINIC', + }), + ).toEqual({ senderId: 'clinic', counterpartyId: 'lab' }); + }); +}); diff --git a/backend/src/modules/billing/billing-cash-edit.ts b/backend/src/modules/billing/billing-cash-edit.ts new file mode 100644 index 0000000..51a53c0 --- /dev/null +++ b/backend/src/modules/billing/billing-cash-edit.ts @@ -0,0 +1,42 @@ +export type PartnerCashSide = { + id: string; + typeName: string; +}; + +export function resolvePartnerCashSides(input: { + from: PartnerCashSide | null; + to: PartnerCashSide | null; + recorderOrganizationId: string | null; + recordedBy: 'CLINIC' | 'LAB'; +}): { senderId: string | null; counterpartyId: string | null } { + const { from, to } = input; + if (!from || !to) { + return { + senderId: input.recorderOrganizationId ?? (from ?? to)?.id ?? null, + counterpartyId: null, + }; + } + if (input.recorderOrganizationId) { + if ( + input.recorderOrganizationId !== from.id && + input.recorderOrganizationId !== to.id + ) { + return { senderId: null, counterpartyId: null }; + } + return { + senderId: input.recorderOrganizationId, + counterpartyId: + input.recorderOrganizationId === from.id ? to.id : from.id, + }; + } + + const fromMatches = input.recordedBy === from.typeName; + const toMatches = input.recordedBy === to.typeName; + if (fromMatches === toMatches) { + return { senderId: null, counterpartyId: null }; + } + return { + senderId: fromMatches ? from.id : to.id, + counterpartyId: fromMatches ? to.id : from.id, + }; +} diff --git a/backend/src/modules/billing/billing.controller.ts b/backend/src/modules/billing/billing.controller.ts index dee5ca9..4e88f14 100644 --- a/backend/src/modules/billing/billing.controller.ts +++ b/backend/src/modules/billing/billing.controller.ts @@ -24,7 +24,11 @@ import { AllocationSearchQueryDto, CreatePaymentDto, ListPaymentsQueryDto, + PartyReportQueryDto, PartySearchQueryDto, + SaveStaffSalarySheetDto, + UpdateObligationAmountDto, + UpdatePaymentDto, } from './dto/billing-payment.dto'; import { UpsertBillingSheetDto } from './dto/upsert-billing-sheet.dto'; import { LabPriceQuoteDto, OutsourceQuoteDto } from './dto/billing-quote.dto'; @@ -146,6 +150,49 @@ export class BillingController { return this.billingService.listTransactions(req.user.id, organizationId, query); } + @Get('party-report') + @ApiOperation({ summary: 'Unified debit/credit report for one patient, staff member, or org' }) + partyReport( + @Query() query: PartyReportQueryDto, + @Req() req: { user: { id: string; organizationId?: string } }, + ) { + const organizationId = this.billingService.getOrganizationIdFromUser(req.user); + return this.billingService.partyReport(req.user.id, organizationId, query); + } + + @Put('obligations/:entryId/amount') + @ApiOperation({ summary: 'Set a destination lab case obligation amount' }) + updateObligationAmount( + @Param('entryId', ParseUUIDPipe) entryId: string, + @Body() dto: UpdateObligationAmountDto, + @Req() req: { user: { id: string; organizationId?: string } }, + ) { + const organizationId = this.billingService.getOrganizationIdFromUser(req.user); + return this.billingService.updateCaseObligationAmount( + req.user.id, + organizationId, + entryId, + dto.amount, + ); + } + + @Get('staff-salaries') + @ApiOperation({ summary: 'Read the single staff salary sheet' }) + getStaffSalarySheet(@Req() req: { user: { id: string; organizationId?: string } }) { + const organizationId = this.billingService.getOrganizationIdFromUser(req.user); + return this.billingService.getStaffSalarySheet(req.user.id, organizationId); + } + + @Put('staff-salaries') + @ApiOperation({ summary: 'Save the single staff salary sheet (TAB_BILLING_EDIT)' }) + saveStaffSalarySheet( + @Body() dto: SaveStaffSalarySheetDto, + @Req() req: { user: { id: string; organizationId?: string } }, + ) { + const organizationId = this.billingService.getOrganizationIdFromUser(req.user); + return this.billingService.saveStaffSalarySheet(req.user.id, organizationId, dto.lines); + } + @Get('staff-payments') @ApiOperation({ summary: 'List staff payments' }) listStaffPayments( @@ -166,6 +213,17 @@ export class BillingController { return this.billingService.createStaffPayment(req.user.id, organizationId, dto); } + @Put('staff-payments/:id') + @ApiOperation({ summary: 'Edit a recorded staff cash payment (TAB_BILLING_EDIT)' }) + updateStaffPayment( + @Param('id', ParseUUIDPipe) id: string, + @Body() dto: UpdatePaymentDto, + @Req() req: { user: { id: string; organizationId?: string } }, + ) { + const organizationId = this.billingService.getOrganizationIdFromUser(req.user); + return this.billingService.updateStaffPayment(req.user.id, organizationId, id, dto); + } + @Get('resolved-lines') @ApiOperation({ summary: 'Resolved fee-schedule lines for a date (billing or treatment read)' }) getResolvedLines( @@ -216,6 +274,17 @@ export class BillingController { return this.billingService.createPatientPayment(req.user.id, organizationId, dto); } + @Put('patient-payments/:id') + @ApiOperation({ summary: 'Edit a recorded patient cash receipt (TAB_BILLING_EDIT)' }) + updatePatientPayment( + @Param('id', ParseUUIDPipe) id: string, + @Body() dto: UpdatePaymentDto, + @Req() req: { user: { id: string; organizationId?: string } }, + ) { + const organizationId = this.billingService.getOrganizationIdFromUser(req.user); + return this.billingService.updatePatientPayment(req.user.id, organizationId, id, dto); + } + @Get('partner-payments') @ApiOperation({ summary: 'List clinic-lab partner payments' }) listPartnerPayments( @@ -256,6 +325,17 @@ export class BillingController { return this.billingService.createPartnerPayment(req.user.id, organizationId, dto); } + @Put('partner-payments/:id') + @ApiOperation({ summary: 'Edit a recorder-owned partner cash payment (TAB_BILLING_EDIT)' }) + updatePartnerPayment( + @Param('id', ParseUUIDPipe) id: string, + @Body() dto: UpdatePaymentDto, + @Req() req: { user: { id: string; organizationId?: string } }, + ) { + const organizationId = this.billingService.getOrganizationIdFromUser(req.user); + return this.billingService.updatePartnerPayment(req.user.id, organizationId, id, dto); + } + @Post('partner-payments/:id/acknowledge') @ApiOperation({ summary: 'Accept or decline a partner payment as the other organization' }) acknowledgePartnerPayment( @@ -269,6 +349,7 @@ export class BillingController { organizationId, id, dto.decision, + dto.expectedUpdatedAt, ); } } diff --git a/backend/src/modules/billing/billing.service.ts b/backend/src/modules/billing/billing.service.ts index e8c8ee8..503ceb5 100644 --- a/backend/src/modules/billing/billing.service.ts +++ b/backend/src/modules/billing/billing.service.ts @@ -1,6 +1,15 @@ -import { HttpStatus, Injectable } from '@nestjs/common'; +import { + HttpStatus, + Injectable, + OnModuleDestroy, + OnModuleInit, +} from '@nestjs/common'; import { BillingCatalogKind, + BillingCashEventType, + BillingCashPaymentKind, + BillingLedgerPartyKind, + BillingObligationSourceType, BillingSheetKind, CatalogEntityKind, LinkStatus, @@ -39,12 +48,13 @@ import { calculateClinicDetailAmount, calculateCommissionEarned, calculateLabCaseAmount, - calculateOutsourceStepsAmount, commissionQtyForTask, INTRAORAL_SCAN_STEP, + outsourceChargeAmount, outsourceQuoteBasis, preferNonEmptyJobs, roundBillingAmount, + unpricedProsthesisCodes, type BillingPriceLine, type ProsthesisQtyMeta, } from './calculate-amounts'; @@ -55,7 +65,11 @@ import { } 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 { + CreatePaymentDto, + PartyReportQueryDto, + UpdatePaymentDto, +} from './dto/billing-payment.dto'; import { isBillingCurrencyCode, lockBillingCurrencyOnWrite, @@ -68,6 +82,23 @@ import { type BillingSheetKindValue, type BillingSheetRecord, } from './resolve-billing-sheet'; +import { + sharedCashCountsInPartyReport, + signedPartyCashAmount, +} from './party-ledger'; +import { SaveStaffSalarySheetDto } from './dto/billing-payment.dto'; +import { + finishedStaffBillingPeriods, + previousStaffBillingPeriod, + staffBillingPeriodForDate, + staffBillingPeriodFromKey, + staffPeriodKeyMatchesCurrency, + staffPeriodLastDay, + staffPeriodsAfter, + type StaffBillingPeriod, +} from './staff-billing-period'; +import { resolvePartnerCashSides } from './billing-cash-edit'; +import { resolvePartnerCaseObligation } from './billing-case-obligation'; type PaymentListQuery = { q?: string; @@ -75,6 +106,7 @@ type PaymentListQuery = { to?: string; partyKind?: 'patient' | 'staff' | 'org'; partyId?: string; + unlimited?: boolean; }; const sheetInclude = { @@ -88,7 +120,10 @@ const sheetInclude = { } satisfies Prisma.BillingSheetInclude; @Injectable() -export class BillingService { +export class BillingService implements OnModuleInit, OnModuleDestroy { + private staffRollupTimer: ReturnType | null = null; + private staffRollupRunning = false; + constructor( private readonly prisma: PrismaService, private readonly catalogLabels: CatalogLabelService, @@ -101,6 +136,184 @@ export class BillingService { return user.organizationId; } + onModuleInit() { + void this.runScheduledStaffRollupIfDue().catch(() => undefined); + this.staffRollupTimer = setInterval( + () => void this.runScheduledStaffRollupIfDue().catch(() => undefined), + 60 * 60 * 1000, + ); + this.staffRollupTimer.unref?.(); + } + + onModuleDestroy() { + if (this.staffRollupTimer) clearInterval(this.staffRollupTimer); + } + + private async runScheduledStaffRollupIfDue() { + if (this.staffRollupRunning) return; + this.staffRollupRunning = true; + try { + await this.closeFinishedStaffPeriods(); + } finally { + this.staffRollupRunning = false; + } + } + + /** Close every finished staff month. The month still in progress is left unwritten. */ + async closeFinishedStaffPeriods() { + const now = new Date(); + const organizations = await this.prisma.organization.findMany({ + select: { + id: true, + staffSalaryUpdatedAt: true, + staffBillingClosedThrough: true, + }, + }); + for (const organization of organizations) { + const currency = await this.staffBillingCurrency(organization.id); + await this.clearOpenStaffObligations(organization.id, currency, now); + await this.refreshFinishedCommissionPeriods(organization.id, currency, now); + await this.closeFinishedSalaryPeriods(organization, currency, now); + } + } + + private async clearOpenStaffObligations( + organizationId: string, + currency: BillingCurrencyCode, + now: Date, + ) { + const current = staffBillingPeriodForDate(now, currency); + await this.prisma.billingLedgerEntry.deleteMany({ + where: { + organizationId, + sourceType: { + in: [ + BillingObligationSourceType.STAFF_COMMISSION_MONTH, + BillingObligationSourceType.STAFF_SALARY_MONTH, + ], + }, + OR: [ + { sourceId: { endsWith: `:${current.key}:commission` } }, + { sourceId: { endsWith: `:${current.key}:salary` } }, + ], + }, + }); + } + + private async refreshFinishedCommissionPeriods( + organizationId: string, + currency: BillingCurrencyCode, + now: Date, + ) { + const earliest = await this.prisma.commissionEarning.findFirst({ + where: { organizationId }, + orderBy: { earnedAt: 'asc' }, + select: { earnedAt: true }, + }); + if (!earliest) return; + const periods = finishedStaffBillingPeriods(earliest.earnedAt, now, currency); + for (const period of periods) { + const sums = await this.prisma.commissionEarning.groupBy({ + by: ['userId'], + where: { + organizationId, + earnedAt: { gte: period.start, lt: period.end }, + }, + _sum: { earnedAmount: true }, + }); + const occurredAt = staffPeriodLastDay(period); + await this.prisma.$transaction(async (tx) => { + const ids = sums.map((row) => `${row.userId}:${period.key}:commission`); + await tx.billingLedgerEntry.deleteMany({ + where: { + organizationId, + sourceType: BillingObligationSourceType.STAFF_COMMISSION_MONTH, + sourceId: stalePeriodSourceFilter(`:${period.key}:commission`, ids), + }, + }); + for (const row of sums) { + await this.upsertObligation(tx, { + organizationId, + partyKind: BillingLedgerPartyKind.STAFF, + partyId: row.userId, + sourceType: BillingObligationSourceType.STAFF_COMMISSION_MONTH, + sourceId: `${row.userId}:${period.key}:commission`, + amount: Number(row._sum.earnedAmount ?? 0), + sign: -1, + occurredAt, + refreshOccurredAt: true, + }); + } + }); + } + } + + private async closeFinishedSalaryPeriods( + organization: { + id: string; + staffSalaryUpdatedAt: Date | null; + staffBillingClosedThrough: string | null; + }, + currency: BillingCurrencyCode, + now: Date, + ) { + if (!organization.staffSalaryUpdatedAt || !organization.staffBillingClosedThrough) return; + const previous = previousStaffBillingPeriod(now, currency); + if (previous.end > now) return; + const closedKey = organization.staffBillingClosedThrough; + if (!staffPeriodKeyMatchesCurrency(closedKey, currency)) { + await this.prisma.organization.update({ + where: { id: organization.id }, + data: { staffBillingClosedThrough: previous.key }, + }); + return; + } + const closed = staffBillingPeriodFromKey(closedKey); + if (!closed || closed.start >= previous.start) return; + for (const period of staffPeriodsAfter(closedKey, now, currency)) { + await this.snapshotStaffSalaryPeriod(organization.id, period); + } + await this.prisma.organization.update({ + where: { id: organization.id }, + data: { staffBillingClosedThrough: previous.key }, + }); + } + + /** Insert the salary owed for a finished month. An existing row stays as it was. */ + private async snapshotStaffSalaryPeriod( + organizationId: string, + period: StaffBillingPeriod, + ) { + const memberships = await this.prisma.membership.findMany({ + where: { + organizationId, + OR: [{ isOwner: true }, { isActive: true }], + fixedMonthlySalary: { gt: 0 }, + }, + select: { userId: true, fixedMonthlySalary: true }, + }); + const occurredAt = staffPeriodLastDay(period); + const data = memberships.flatMap((membership) => { + const amount = roundBillingAmount(Number(membership.fixedMonthlySalary ?? 0)); + if (amount <= 0) return []; + return [ + { + organizationId, + partyKind: BillingLedgerPartyKind.STAFF, + partyId: membership.userId, + sourceType: BillingObligationSourceType.STAFF_SALARY_MONTH, + sourceId: `${membership.userId}:${period.key}:salary`, + amount: new Prisma.Decimal(amount.toFixed(2)), + signedAmount: new Prisma.Decimal((-amount).toFixed(2)), + balanceSign: -1, + occurredAt, + }, + ]; + }); + if (data.length === 0) return; + await this.prisma.billingLedgerEntry.createMany({ data, skipDuplicates: true }); + } + async listSheets( actorUserId: string, organizationId: string, @@ -293,6 +506,7 @@ export class BillingService { kind: dto.kind, name: dto.name?.trim() || null, effectiveOn: dateOnlyUtc(dto.effectiveOn), + hideUnpricedTypes: isPriceKind(dto.kind) && Boolean(dto.hideUnpricedTypes), targets: { create: this.targetCreates(dto) }, lines: { create: this.lineCreates(dto) }, }, @@ -324,6 +538,7 @@ export class BillingService { data: { name: dto.name?.trim() || null, effectiveOn: dateOnlyUtc(dto.effectiveOn), + hideUnpricedTypes: isPriceKind(dto.kind) && Boolean(dto.hideUnpricedTypes), targets: { create: this.targetCreates(dto) }, lines: { create: [ @@ -373,7 +588,7 @@ export class BillingService { }, include: patientPaymentInclude, orderBy: [{ paidAt: 'desc' }, { createdAt: 'desc' }], - take: party ? 2000 : 200, + take: query.unlimited ? undefined : party ? 2000 : 200, }) : Promise.resolve([]), !party || party.kind === 'org' @@ -401,7 +616,7 @@ export class BillingService { }, include: partnerPaymentInclude, orderBy: [{ paidAt: 'desc' }, { createdAt: 'desc' }], - take: party ? 2000 : 200, + take: query.unlimited ? undefined : party ? 2000 : 200, }) : Promise.resolve([]), !party || party.kind === 'staff' @@ -413,7 +628,7 @@ export class BillingService { }, include: staffPaymentInclude, orderBy: [{ paidAt: 'desc' }, { createdAt: 'desc' }], - take: party ? 2000 : 200, + take: query.unlimited ? undefined : party ? 2000 : 200, }) : Promise.resolve([]), ]); @@ -434,7 +649,6 @@ export class BillingService { 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; @@ -461,15 +675,24 @@ export class BillingService { id: row.id, kind: 'patient' as const, type: 'RECEIPT' as const, + partyId: row.patientId, 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), + allocations: row.allocations.map((a) => ({ + targetId: a.treatmentId, + amount: a.amount, + label: a.treatmentTitle, + })), acknowledgement: 'none' as const, canAcknowledge: false, recordedByViewer: true, + canEdit: row.canEdit, + canAllocate: Boolean(row.patientId), + updatedAt: row.updatedAt, })), ...partners.map((row) => { const type = row.fromOrganizationId === organizationId ? ('PAYMENT' as const) : ('RECEIPT' as const); @@ -477,30 +700,47 @@ export class BillingService { id: row.id, kind: 'partner' as const, type, + partyId: + type === 'RECEIPT' + ? row.fromOrganizationId + : row.toOrganizationId, 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), + allocations: row.allocations.map((a) => ({ + targetId: a.labCaseId, + amount: a.amount, + label: a.caseLabel, + })), acknowledgement: row.acknowledgement, canAcknowledge: row.canAcknowledge, recordedByViewer: row.recordedByViewer, + canEdit: row.canEdit, + canAllocate: row.canAllocate, + updatedAt: row.updatedAt, }; }), ...staff.map((row) => ({ id: row.id, kind: 'staff' as const, type: 'PAYMENT' as const, + partyId: row.userId, partyName: row.partyName, partyIsWalkIn: false, amount: row.amount, paidAt: row.paidAt, note: row.note, attachments: [] as string[], + allocations: [] as Array<{ targetId: string; amount: string; label: string }>, acknowledgement: 'none' as const, canAcknowledge: false, recordedByViewer: true, + canEdit: row.canEdit, + canAllocate: false, + updatedAt: row.updatedAt, })), ].sort((a, b) => b.paidAt.localeCompare(a.paidAt)); @@ -508,15 +748,358 @@ export class BillingService { if (party) { let signed = 0; for (const row of ledger) { + if (!sharedCashCountsInPartyReport(row)) continue; const amount = Number(row.amount); signed += row.type === 'RECEIPT' ? amount : -amount; } - net = roundBillingAmount(signed).toFixed(2); + net = roundSignedBillingAmount(signed).toFixed(2); } return { success: true as const, data: ledger, net }; } + async partyReport( + actorUserId: string, + organizationId: string, + query: PartyReportQueryDto, + ) { + await this.assertCanRead(actorUserId, organizationId); + if (query.partyKind === 'patient') { + await this.assertPatientInOrg(organizationId, query.partyId); + } else if (query.partyKind === 'staff') { + await this.assertStaffInOrg(organizationId, query.partyId); + } else { + await this.assertActiveLink(organizationId, query.partyId); + } + + const partyKind = + query.partyKind === 'patient' + ? BillingLedgerPartyKind.PATIENT + : query.partyKind === 'staff' + ? BillingLedgerPartyKind.STAFF + : BillingLedgerPartyKind.ORGANIZATION; + const occurredAt = occurredAtWhere(query); + const [obligations, cash] = await Promise.all([ + this.prisma.billingLedgerEntry.findMany({ + where: { + organizationId, + partyKind, + partyId: query.partyId, + ...occurredAt, + }, + orderBy: [{ occurredAt: 'desc' }, { createdAt: 'desc' }], + }), + this.listTransactions(actorUserId, organizationId, { + from: query.from, + to: query.to, + partyKind: query.partyKind, + partyId: query.partyId, + unlimited: true, + }), + ]); + + const treatmentIds = obligations + .filter((row) => row.sourceType === BillingObligationSourceType.TREATMENT_APPROVE) + .map((row) => row.sourceId); + const caseIds = obligations + .filter( + (row) => + row.sourceType === BillingObligationSourceType.LAB_CASE || + row.sourceType === BillingObligationSourceType.OUTSOURCE_CASE, + ) + .map((row) => row.sourceId); + const [treatments, cases] = await Promise.all([ + treatmentIds.length + ? this.prisma.treatment.findMany({ + where: { id: { in: treatmentIds } }, + select: { id: true, title: true }, + }) + : Promise.resolve([]), + caseIds.length + ? this.prisma.labCase.findMany({ + where: { id: { in: caseIds } }, + select: { + id: true, + origin: true, + externalCode: true, + patientDisplayName: true, + }, + }) + : Promise.resolve([]), + ]); + const treatmentLabels = new Map( + treatments.map((row) => [row.id, row.title] as const), + ); + const caseLabels = new Map( + cases.map((row) => [ + row.id, + [row.externalCode || row.id.slice(0, 8), row.patientDisplayName].filter(Boolean).join(' · '), + ] as const), + ); + const caseOrigins = new Map( + cases.map((row) => [row.id, row.origin] as const), + ); + + const rows = [ + ...obligations.map((row) => { + const amount = row.amount?.toFixed(2) ?? null; + const signedAmount = row.signedAmount?.toFixed(2) ?? null; + const caseObligation = + row.sourceType === BillingObligationSourceType.LAB_CASE || + row.sourceType === BillingObligationSourceType.OUTSOURCE_CASE; + return { + id: row.id, + lineKind: 'OBLIGATION' as const, + direction: row.balanceSign > 0 ? ('DEBIT' as const) : ('CREDIT' as const), + amount, + signedAmount, + amountPending: amount == null, + canEditAmount: caseObligation && row.balanceSign > 0, + occurredAt: row.occurredAt.toISOString(), + sourceType: row.sourceType, + sourceId: row.sourceId, + caseOrigin: caseObligation + ? (caseOrigins.get(row.sourceId) ?? null) + : null, + reference: + treatmentLabels.get(row.sourceId) ?? + caseLabels.get(row.sourceId) ?? + staffPeriodReference(row.sourceId), + note: row.note, + acknowledgement: 'none' as const, + canAllocate: false, + countsInTotals: amount != null, + }; + }), + ...cash.data.map((row) => { + // Cash direction is the inverse on the selected party account: + // a receipt credits what they owe; a payment debits what we owe them. + const signed = signedPartyCashAmount(row.type, Number(row.amount)); + return { + id: `cash:${row.kind}:${row.id}`, + lineKind: 'CASH' as const, + direction: signed >= 0 ? ('DEBIT' as const) : ('CREDIT' as const), + amount: Number(row.amount).toFixed(2), + signedAmount: signed.toFixed(2), + amountPending: false, + canEditAmount: false, + occurredAt: row.paidAt, + sourceType: row.type === 'RECEIPT' ? ('CASH_RECEIPT' as const) : ('CASH_PAYMENT' as const), + sourceId: row.id, + reference: row.attachments.join(' · '), + note: row.note, + acknowledgement: row.acknowledgement, + canAcknowledge: row.canAcknowledge, + recordedByViewer: row.recordedByViewer, + canEditCash: row.canEdit, + canAllocate: row.canAllocate, + paymentKind: row.kind, + updatedAt: row.updatedAt, + allocations: row.allocations, + countsInTotals: sharedCashCountsInPartyReport(row), + }; + }), + ].sort((a, b) => b.occurredAt.localeCompare(a.occurredAt)); + + const debit = rows + .filter( + (row) => + row.countsInTotals && + row.signedAmount != null && + Number(row.signedAmount) > 0, + ) + .reduce((sum, row) => sum + Number(row.amount ?? 0), 0); + const credit = rows + .filter( + (row) => + row.countsInTotals && + row.signedAmount != null && + Number(row.signedAmount) < 0, + ) + .reduce((sum, row) => sum + Number(row.amount ?? 0), 0); + const net = rows + .filter((row) => row.countsInTotals && row.signedAmount != null) + .reduce((sum, row) => sum + Number(row.signedAmount ?? 0), 0); + const commissionSubtotal = + query.partyKind === 'staff' + ? obligations + .filter( + (row) => + row.sourceType === + BillingObligationSourceType.STAFF_COMMISSION_MONTH, + ) + .reduce((sum, row) => sum + Number(row.amount ?? 0), 0) + : 0; + const fixedSalarySubtotal = + query.partyKind === 'staff' + ? obligations + .filter( + (row) => + row.sourceType === BillingObligationSourceType.STAFF_SALARY_MONTH, + ) + .reduce((sum, row) => sum + Number(row.amount ?? 0), 0) + : 0; + return { + success: true as const, + data: rows, + totals: { + debit: roundBillingAmount(debit).toFixed(2), + credit: roundBillingAmount(credit).toFixed(2), + net: roundSignedBillingAmount(net).toFixed(2), + }, + staffCompensation: + query.partyKind === 'staff' + ? { + commission: roundBillingAmount(commissionSubtotal).toFixed(2), + fixedSalary: roundBillingAmount(fixedSalarySubtotal).toFixed(2), + gross: roundBillingAmount( + commissionSubtotal + fixedSalarySubtotal, + ).toFixed(2), + } + : null, + }; + } + + async updateCaseObligationAmount( + actorUserId: string, + organizationId: string, + entryId: string, + value: string, + ) { + await this.assertCanEdit(actorUserId, organizationId); + const amount = parseMoney(value); + if (amount <= 0) { + throw new AppException(ErrorCode.BILLING_AMOUNT_INVALID, HttpStatus.BAD_REQUEST); + } + + const entry = await this.prisma.billingLedgerEntry.findFirst({ + where: { id: entryId, organizationId }, + select: { sourceType: true, sourceId: true, balanceSign: true }, + }); + if ( + !entry || + entry.balanceSign !== 1 || + (entry.sourceType !== BillingObligationSourceType.LAB_CASE && + entry.sourceType !== BillingObligationSourceType.OUTSOURCE_CASE) + ) { + throw new AppException( + ErrorCode.BILLING_OBLIGATION_NOT_EDITABLE, + HttpStatus.BAD_REQUEST, + ); + } + + const labCase = await this.prisma.labCase.findUnique({ + where: { id: entry.sourceId }, + select: { destinationOrganizationId: true }, + }); + if (labCase?.destinationOrganizationId !== organizationId) { + throw new AppException( + ErrorCode.BILLING_OBLIGATION_NOT_EDITABLE, + HttpStatus.BAD_REQUEST, + ); + } + + await this.prisma.$transaction(async (tx) => { + await tx.labCase.update({ + where: { id: entry.sourceId }, + data: { + billedAmount: new Prisma.Decimal(amount.toFixed(2)), + billedAmountManual: true, + }, + }); + await this.syncPartnerCaseObligations(tx, entry.sourceId); + }); + + return { success: true as const, data: { amount: amount.toFixed(2) } }; + } + + async getStaffSalarySheet(actorUserId: string, organizationId: string) { + await this.assertCanRead(actorUserId, organizationId); + return { success: true as const, data: await this.loadStaffSalarySheet(organizationId) }; + } + + async saveStaffSalarySheet( + actorUserId: string, + organizationId: string, + lines: SaveStaffSalarySheetDto['lines'], + ) { + await this.assertCanEdit(actorUserId, organizationId); + const seen = new Set(); + for (const line of lines) { + if (seen.has(line.userId)) { + throw new AppException(ErrorCode.BILLING_LINE_INVALID, HttpStatus.BAD_REQUEST); + } + seen.add(line.userId); + parseMoney(line.fixedMonthlySalary); + } + const roster = await this.salarySheetMemberships(organizationId); + const rosterIds = new Set(roster.map((membership) => membership.userId)); + for (const userId of seen) { + if (!rosterIds.has(userId)) { + throw new AppException(ErrorCode.BILLING_TARGET_INVALID, HttpStatus.BAD_REQUEST); + } + } + + const currency = await this.staffBillingCurrency(organizationId); + const previous = previousStaffBillingPeriod(new Date(), currency); + await this.prisma.$transaction(async (tx) => { + for (const line of lines) { + const amount = parseMoney(line.fixedMonthlySalary); + await tx.membership.update({ + where: { userId_organizationId: { userId: line.userId, organizationId } }, + data: { fixedMonthlySalary: new Prisma.Decimal(amount.toFixed(2)) }, + }); + } + const organization = await tx.organization.findUniqueOrThrow({ + where: { id: organizationId }, + select: { staffBillingClosedThrough: true }, + }); + await tx.organization.update({ + where: { id: organizationId }, + data: { + staffSalaryUpdatedAt: new Date(), + ...(organization.staffBillingClosedThrough + ? {} + : { staffBillingClosedThrough: previous.key }), + }, + }); + }); + return { success: true as const, data: await this.loadStaffSalarySheet(organizationId) }; + } + + private async loadStaffSalarySheet(organizationId: string) { + const [organization, memberships] = await Promise.all([ + this.prisma.organization.findUniqueOrThrow({ + where: { id: organizationId }, + select: { staffSalaryUpdatedAt: true }, + }), + this.salarySheetMemberships(organizationId), + ]); + return { + updatedAt: organization.staffSalaryUpdatedAt?.toISOString() ?? null, + lines: memberships.map((membership) => ({ + userId: membership.userId, + name: membership.user.name, + fixedMonthlySalary: membership.fixedMonthlySalary?.toFixed(2) ?? '0.00', + })), + }; + } + + private salarySheetMemberships(organizationId: string) { + return this.prisma.membership.findMany({ + where: { + organizationId, + OR: [{ isOwner: true }, { isActive: true }], + }, + select: { + userId: true, + fixedMonthlySalary: true, + user: { select: { name: true } }, + }, + orderBy: { user: { name: 'asc' } }, + }); + } + async searchParties( actorUserId: string, organizationId: string, @@ -680,7 +1263,7 @@ export class BillingService { if (dto.patientId) { await this.assertPatientInOrg(organizationId, dto.patientId); } - const amount = parseMoney(dto.amount); + const amount = parsePositiveMoney(dto.amount); const allocations = dto.patientId ? normalizeAllocations(dto.allocations) : []; assertAllocationTotal(amount, allocations); @@ -752,9 +1335,7 @@ export class BillingService { orderBy: [{ paidAt: 'desc' }, { createdAt: 'desc' }], take: party ? 2000 : 200, }); - const mapped = rows - .map((row) => mapPartnerPayment(row, organizationId)) - .filter((row) => row.acknowledgement !== 'rejected' || row.recordedByViewer); + const mapped = rows.map((row) => mapPartnerPayment(row, organizationId)); const q = query.q?.trim().toLowerCase(); return { success: true as const, @@ -790,7 +1371,7 @@ export class BillingService { throw new AppException(ErrorCode.BILLING_TRANSACTION_TYPE_INVALID, HttpStatus.BAD_REQUEST); } - const amount = parseMoney(dto.amount); + const amount = parsePositiveMoney(dto.amount); const allocations = dto.counterpartOrganizationId ? normalizeAllocations(dto.allocations) : []; assertAllocationTotal(amount, allocations); const currencyToLock = await this.resolveCurrencyForCreate(organizationId, dto.currency); @@ -811,6 +1392,7 @@ export class BillingService { status: PartnerPaymentStatus.CONFIRMED, recordedBy: recordedBy === 'LAB' ? PartnerPaymentRecordedBy.LAB : PartnerPaymentRecordedBy.CLINIC, + recorderOrganizationId: organizationId, createdByUserId: actorUserId, }, include: partnerPaymentInclude, @@ -842,9 +1424,10 @@ export class BillingService { amount: new Prisma.Decimal(amount.toFixed(2)), paidAt: new Date(), note: dto.note?.trim() || null, - status: PartnerPaymentStatus.CONFIRMED, + status: PartnerPaymentStatus.PENDING, recordedBy: recordedBy === 'LAB' ? PartnerPaymentRecordedBy.LAB : PartnerPaymentRecordedBy.CLINIC, + recorderOrganizationId: organizationId, createdByUserId: actorUserId, allocations: { create: allocations.map((row) => ({ @@ -909,7 +1492,7 @@ export class BillingService { if (dto.userId) { await this.assertStaffInOrg(organizationId, dto.userId); } - const amount = parseMoney(dto.amount); + const amount = parsePositiveMoney(dto.amount); const currencyToLock = await this.resolveCurrencyForCreate(organizationId, dto.currency); const payment = await this.prisma.$transaction(async (tx) => { @@ -930,11 +1513,236 @@ export class BillingService { return { success: true as const, data: mapStaffPayment(payment) }; } + async updatePatientPayment( + actorUserId: string, + organizationId: string, + id: string, + dto: UpdatePaymentDto, + ) { + await this.assertCanEdit(actorUserId, organizationId); + const existing = await this.prisma.patientPayment.findUnique({ + where: { id }, + include: patientPaymentInclude, + }); + if (!existing || existing.organizationId !== organizationId) { + throw new AppException(ErrorCode.BILLING_PAYMENT_NOT_FOUND, HttpStatus.NOT_FOUND); + } + this.assertExpectedUpdatedAt(existing.updatedAt, dto.expectedUpdatedAt); + + const amount = parsePositiveMoney(dto.amount); + const allocations = existing.patientId ? normalizeAllocations(dto.allocations) : []; + if (!existing.patientId && (dto.allocations?.length ?? 0) > 0) { + throw new AppException(ErrorCode.BILLING_ALLOCATION_INVALID, HttpStatus.BAD_REQUEST); + } + assertAllocationTotal(amount, allocations); + if (existing.patientId && allocations.length > 0) { + const treatmentIds = allocations.map((row) => row.targetId); + const treatments = await this.prisma.treatment.findMany({ + where: { + id: { in: treatmentIds }, + organizationId, + patientId: existing.patientId, + }, + select: { id: true }, + }); + if (treatments.length !== new Set(treatmentIds).size) { + throw new AppException(ErrorCode.BILLING_ALLOCATION_INVALID, HttpStatus.BAD_REQUEST); + } + } + + const updated = await this.prisma.$transaction(async (tx) => { + const matched = await tx.patientPayment.updateMany({ + where: { + id, + organizationId, + updatedAt: existing.updatedAt, + }, + data: { + amount: new Prisma.Decimal(amount.toFixed(2)), + note: dto.note?.trim() || null, + }, + }); + if (matched.count !== 1) this.throwTransactionChanged(); + await tx.patientPaymentAllocation.deleteMany({ where: { paymentId: id } }); + if (allocations.length > 0) { + await tx.patientPaymentAllocation.createMany({ + data: allocations.map((row) => ({ + paymentId: id, + treatmentId: row.targetId, + amount: new Prisma.Decimal(row.amount.toFixed(2)), + })), + }); + } + const payment = await tx.patientPayment.findUniqueOrThrow({ + where: { id }, + include: patientPaymentInclude, + }); + await this.writeCashEvent(tx, { + paymentKind: BillingCashPaymentKind.PATIENT, + paymentId: id, + eventType: BillingCashEventType.EDITED, + organizationId, + actorUserId, + before: mapPatientPayment(existing), + after: mapPatientPayment(payment), + }); + return payment; + }); + return { success: true as const, data: mapPatientPayment(updated) }; + } + + async updateStaffPayment( + actorUserId: string, + organizationId: string, + id: string, + dto: UpdatePaymentDto, + ) { + await this.assertCanEdit(actorUserId, organizationId); + if ((dto.allocations?.length ?? 0) > 0) { + throw new AppException(ErrorCode.BILLING_ALLOCATION_INVALID, HttpStatus.BAD_REQUEST); + } + const existing = await this.prisma.staffPayment.findUnique({ + where: { id }, + include: staffPaymentInclude, + }); + if (!existing || existing.organizationId !== organizationId) { + throw new AppException(ErrorCode.BILLING_PAYMENT_NOT_FOUND, HttpStatus.NOT_FOUND); + } + this.assertExpectedUpdatedAt(existing.updatedAt, dto.expectedUpdatedAt); + const amount = parsePositiveMoney(dto.amount); + + const updated = await this.prisma.$transaction(async (tx) => { + const matched = await tx.staffPayment.updateMany({ + where: { + id, + organizationId, + updatedAt: existing.updatedAt, + }, + data: { + amount: new Prisma.Decimal(amount.toFixed(2)), + note: dto.note?.trim() || null, + }, + }); + if (matched.count !== 1) this.throwTransactionChanged(); + const payment = await tx.staffPayment.findUniqueOrThrow({ + where: { id }, + include: staffPaymentInclude, + }); + await this.writeCashEvent(tx, { + paymentKind: BillingCashPaymentKind.STAFF, + paymentId: id, + eventType: BillingCashEventType.EDITED, + organizationId, + actorUserId, + before: mapStaffPayment(existing), + after: mapStaffPayment(payment), + }); + return payment; + }); + return { success: true as const, data: mapStaffPayment(updated) }; + } + + async updatePartnerPayment( + actorUserId: string, + organizationId: string, + id: string, + dto: UpdatePaymentDto, + ) { + await this.assertCanEdit(actorUserId, organizationId); + const existing = await this.prisma.partnerPayment.findUnique({ + where: { id }, + include: partnerPaymentInclude, + }); + if (!existing) { + throw new AppException(ErrorCode.BILLING_PAYMENT_NOT_FOUND, HttpStatus.NOT_FOUND); + } + const sides = partnerSides(existing); + if ( + sides.senderId !== organizationId || + existing.recorderOrganizationId !== organizationId + ) { + throw new AppException(ErrorCode.BILLING_PAYMENT_NOT_EDITABLE, HttpStatus.FORBIDDEN); + } + this.assertExpectedUpdatedAt(existing.updatedAt, dto.expectedUpdatedAt); + + const amount = parsePositiveMoney(dto.amount); + const shared = Boolean(existing.fromOrganizationId && existing.toOrganizationId); + const allocations = shared ? normalizeAllocations(dto.allocations) : []; + if (!shared && (dto.allocations?.length ?? 0) > 0) { + throw new AppException(ErrorCode.BILLING_ALLOCATION_INVALID, HttpStatus.BAD_REQUEST); + } + assertAllocationTotal(amount, allocations); + if (allocations.length > 0) { + const fromType = existing.fromOrganization?.type.name; + const toType = existing.toOrganization?.type.name; + const clinicId = + fromType === 'CLINIC' + ? existing.fromOrganizationId + : toType === 'CLINIC' + ? existing.toOrganizationId + : null; + const labId = + fromType === 'LAB' + ? existing.fromOrganizationId + : toType === 'LAB' + ? existing.toOrganizationId + : null; + if (!clinicId || !labId) { + throw new AppException(ErrorCode.BILLING_ALLOCATION_INVALID, HttpStatus.BAD_REQUEST); + } + await this.assertCaseAllocations(labId, clinicId, allocations); + } + + const updated = await this.prisma.$transaction(async (tx) => { + const matched = await tx.partnerPayment.updateMany({ + where: { + id, + recorderOrganizationId: organizationId, + updatedAt: existing.updatedAt, + }, + data: { + amount: new Prisma.Decimal(amount.toFixed(2)), + note: dto.note?.trim() || null, + status: shared ? PartnerPaymentStatus.PENDING : PartnerPaymentStatus.CONFIRMED, + receiptConfirmedAt: null, + receiptRejectedAt: null, + }, + }); + if (matched.count !== 1) this.throwTransactionChanged(); + await tx.partnerPaymentAllocation.deleteMany({ where: { paymentId: id } }); + if (allocations.length > 0) { + await tx.partnerPaymentAllocation.createMany({ + data: allocations.map((row) => ({ + paymentId: id, + labCaseId: row.targetId, + amount: new Prisma.Decimal(row.amount.toFixed(2)), + })), + }); + } + const payment = await tx.partnerPayment.findUniqueOrThrow({ + where: { id }, + include: partnerPaymentInclude, + }); + await this.writeCashEvent(tx, { + paymentKind: BillingCashPaymentKind.PARTNER, + paymentId: id, + eventType: BillingCashEventType.EDITED, + organizationId, + actorUserId, + before: mapPartnerPayment(existing, organizationId), + after: mapPartnerPayment(payment, organizationId), + }); + return payment; + }); + return { success: true as const, data: mapPartnerPayment(updated, organizationId) }; + } + async acknowledgePartnerPayment( actorUserId: string, organizationId: string, id: string, decision: 'ACCEPT' | 'DECLINE', + expectedUpdatedAt: string, ) { await this.assertCanEdit(actorUserId, organizationId); const payment = await this.prisma.partnerPayment.findUnique({ @@ -947,18 +1755,54 @@ export class BillingService { const sides = partnerSides(payment); if ( sides.counterpartyId !== organizationId || + payment.status !== PartnerPaymentStatus.PENDING || 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, + this.assertExpectedUpdatedAt(payment.updatedAt, expectedUpdatedAt); + const updated = await this.prisma.$transaction(async (tx) => { + const now = new Date(); + const matched = await tx.partnerPayment.updateMany({ + where: { + id, + updatedAt: payment.updatedAt, + status: PartnerPaymentStatus.PENDING, + receiptConfirmedAt: null, + receiptRejectedAt: null, + }, + data: + decision === 'ACCEPT' + ? { + status: PartnerPaymentStatus.CONFIRMED, + receiptConfirmedAt: now, + receiptRejectedAt: null, + } + : { + status: PartnerPaymentStatus.REJECTED, + receiptConfirmedAt: null, + receiptRejectedAt: now, + }, + }); + if (matched.count !== 1) this.throwTransactionChanged(); + const row = await tx.partnerPayment.findUniqueOrThrow({ + where: { id }, + include: partnerPaymentInclude, + }); + await this.writeCashEvent(tx, { + paymentKind: BillingCashPaymentKind.PARTNER, + paymentId: id, + eventType: + decision === 'ACCEPT' + ? BillingCashEventType.ACCEPTED + : BillingCashEventType.REJECTED, + organizationId, + actorUserId, + before: mapPartnerPayment(payment, organizationId), + after: mapPartnerPayment(row, organizationId), + }); + return row; }); return { success: true as const, data: mapPartnerPayment(updated, organizationId) }; } @@ -985,12 +1829,15 @@ export class BillingService { } await this.assertLinkedClinicLab(organizationId, dto.labOrganizationId); const asOf = toBillingDateOnly(new Date()); - const lines = await this.resolvedPriceLines(this.prisma as unknown as Prisma.TransactionClient, { + const resolvedSheet = await this.resolvedPriceSheet( + 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, ); @@ -999,10 +1846,43 @@ export class BillingService { tooth: job.tooth.trim(), prosthesisTypeCode: job.prosthesisTypeCode.trim(), })), - lines, + lines: resolvedSheet.lines, metaByCode, }); - return { success: true as const, data: { amount: amount.toFixed(2) } }; + const unpricedCodes = unpricedProsthesisCodes(dto.jobs, resolvedSheet.lines); + return { + success: true as const, + data: { + amount: unpricedCodes.length > 0 ? null : amount.toFixed(2), + unpricedCodes, + blocksSend: resolvedSheet.hideUnpricedTypes && unpricedCodes.length > 0, + }, + }; + } + + async assertLabProvidesProsthesis( + db: Prisma.TransactionClient, + args: { + labOrganizationId: string; + clinicOrganizationId: string; + jobs: Array<{ prosthesisTypeCode: string }>; + asOf?: Date; + }, + ) { + const resolvedSheet = await this.resolvedPriceSheet(db, { + organizationId: args.labOrganizationId, + kind: 'LAB_PRICE', + asOf: toBillingDateOnly(args.asOf ?? new Date()), + clinicOrganizationId: args.clinicOrganizationId, + }); + const unpricedCodes = unpricedProsthesisCodes(args.jobs, resolvedSheet.lines); + if (resolvedSheet.hideUnpricedTypes && unpricedCodes.length > 0) { + throw new AppException( + ErrorCode.BILLING_PROSTHESIS_NOT_PROVIDED, + HttpStatus.CONFLICT, + { prosthesisTypeCodes: unpricedCodes }, + ); + } } async quoteOutsource(actorUserId: string, organizationId: string, dto: OutsourceQuoteDto) { @@ -1076,30 +1956,26 @@ export class BillingService { 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) } }; + const charge = outsourceChargeAmount({ + basis, + jobs: labCase.toothProsthesis.map((job) => ({ + tooth: job.tooth, + prosthesisTypeCode: job.prosthesisTypeCode, + })), + steps: selectable + .filter((task) => selected.has(task.id)) + .map((task) => ({ + workflowStepCode: task.workflowStepCode, + prosthesisTypeCode: task.prosthesisTypeCode, + teeth: task.teeth, + })), + lines, + metaByCode, + }); + return { + success: true as const, + data: { amount: charge.amount == null ? null : charge.amount.toFixed(2) }, + }; } async getResolvedLines( @@ -1123,7 +1999,7 @@ export class BillingService { }); if (!member) userId = null; } - const lines = await this.resolvedPriceLines(this.prisma as unknown as Prisma.TransactionClient, { + const resolvedSheet = await this.resolvedPriceSheet(this.prisma as unknown as Prisma.TransactionClient, { organizationId, kind: query.kind, asOf: query.asOf, @@ -1134,7 +2010,8 @@ export class BillingService { return { success: true as const, data: { - lines: lines.map((line) => ({ + hideUnpricedTypes: resolvedSheet.hideUnpricedTypes, + lines: resolvedSheet.lines.map((line) => ({ catalogKind: line.catalogKind, catalogCode: line.catalogCode, amount: line.amount, @@ -1201,41 +2078,41 @@ export class BillingService { const orgType = await getOrganizationTypeName(this.prisma, organizationId); const counterpartId = query.counterpartOrganizationId; const text = query.q?.trim(); - const rows = await this.prisma.labCase.findMany({ - where: { - ...(orgType === 'CLINIC' - ? { - treatment: { organizationId }, - destinationOrganizationId: counterpartId, - sentAt: { not: null }, - } - : { - destinationOrganizationId: organizationId, - OR: [ - { treatment: { organizationId: counterpartId } }, - { partnerClinicOrganizationId: counterpartId }, - ], - }), - ...(text - ? { - OR: [ - { externalCode: { contains: text, mode: 'insensitive' } }, - { patientDisplayName: { contains: text, mode: 'insensitive' } }, - { referringClinicName: { contains: text, mode: 'insensitive' } }, - { - treatment: { - patient: { - OR: [ - { firstName: { contains: text, mode: 'insensitive' } }, - { lastName: { contains: text, mode: 'insensitive' } }, - ], - }, - }, + const scope = + orgType === 'CLINIC' + ? { + treatment: { organizationId }, + destinationOrganizationId: counterpartId, + sentAt: { not: null }, + } + : { + destinationOrganizationId: organizationId, + OR: [ + { treatment: { organizationId: counterpartId } }, + { partnerClinicOrganizationId: counterpartId }, + ], + }; + const textFilter = text + ? { + OR: [ + { externalCode: { contains: text, mode: 'insensitive' as const } }, + { patientDisplayName: { contains: text, mode: 'insensitive' as const } }, + { referringClinicName: { contains: text, mode: 'insensitive' as const } }, + { + treatment: { + patient: { + OR: [ + { firstName: { contains: text, mode: 'insensitive' as const } }, + { lastName: { contains: text, mode: 'insensitive' as const } }, + ], }, - ], - } - : {}), - }, + }, + }, + ], + } + : null; + const rows = await this.prisma.labCase.findMany({ + where: textFilter ? { AND: [scope, textFilter] } : scope, select: { id: true, sentAt: true, @@ -1497,6 +2374,222 @@ export class BillingService { } } + async syncTreatmentObligation( + db: Prisma.TransactionClient, + treatmentId: string, + occurredAt = new Date(), + ) { + const treatment = await db.treatment.findUnique({ + where: { id: treatmentId }, + select: { + id: true, + organizationId: true, + patientId: true, + billedAmount: true, + }, + }); + if (!treatment) return; + + await this.upsertObligation(db, { + organizationId: treatment.organizationId, + partyKind: BillingLedgerPartyKind.PATIENT, + partyId: treatment.patientId, + sourceType: BillingObligationSourceType.TREATMENT_APPROVE, + sourceId: treatment.id, + amount: Number(treatment.billedAmount ?? 0), + sign: 1, + occurredAt, + }); + } + + async voidTreatmentObligation(db: Prisma.TransactionClient, treatmentId: string) { + await db.billingLedgerEntry.deleteMany({ + where: { + sourceType: BillingObligationSourceType.TREATMENT_APPROVE, + sourceId: treatmentId, + }, + }); + } + + async syncPartnerCaseObligations(db: Prisma.TransactionClient, labCaseId: string) { + const labCase = await db.labCase.findUnique({ + where: { id: labCaseId }, + select: { + id: true, + origin: true, + destinationOrganizationId: true, + partnerClinicOrganizationId: true, + sentAt: true, + startedAt: true, + billedAmount: true, + treatment: { select: { organizationId: true } }, + parentLabCase: { select: { destinationOrganizationId: true } }, + }, + }); + if (!labCase) return; + + const obligation = resolvePartnerCaseObligation({ + origin: labCase.origin, + destinationOrganizationId: labCase.destinationOrganizationId, + treatmentOrganizationId: labCase.treatment?.organizationId ?? null, + partnerClinicOrganizationId: labCase.partnerClinicOrganizationId, + parentDestinationOrganizationId: + labCase.parentLabCase?.destinationOrganizationId ?? null, + }); + const amount = + labCase.billedAmount == null ? null : Number(labCase.billedAmount); + + if (!obligation) { + const sourceType = + labCase.origin === 'LAB_OUTSOURCE' + ? BillingObligationSourceType.OUTSOURCE_CASE + : BillingObligationSourceType.LAB_CASE; + await this.voidObligationSource(db, sourceType, labCase.id); + return; + } + + const occurredAt = labCase.sentAt ?? labCase.startedAt ?? new Date(); + await this.upsertObligation(db, { + organizationId: obligation.payerOrganizationId, + partyKind: BillingLedgerPartyKind.ORGANIZATION, + partyId: obligation.payeeOrganizationId, + sourceType: obligation.sourceType, + sourceId: labCase.id, + amount, + keepPending: true, + sign: -1, + occurredAt, + }); + await this.upsertObligation(db, { + organizationId: obligation.payeeOrganizationId, + partyKind: BillingLedgerPartyKind.ORGANIZATION, + partyId: obligation.payerOrganizationId, + sourceType: obligation.sourceType, + sourceId: labCase.id, + amount, + keepPending: true, + sign: 1, + occurredAt, + }); + } + + async voidCaseObligations(db: Prisma.TransactionClient, labCaseIds: string | string[]) { + const ids = Array.isArray(labCaseIds) ? labCaseIds : [labCaseIds]; + if (ids.length === 0) return; + await db.billingLedgerEntry.deleteMany({ + where: { + sourceType: { + in: [ + BillingObligationSourceType.LAB_CASE, + BillingObligationSourceType.OUTSOURCE_CASE, + ], + }, + sourceId: { in: ids }, + }, + }); + } + + private async upsertObligation( + db: Prisma.TransactionClient, + args: { + organizationId: string; + partyKind: BillingLedgerPartyKind; + partyId: string; + sourceType: BillingObligationSourceType; + sourceId: string; + amount: number | null; + keepPending?: boolean; + sign: 1 | -1; + occurredAt: Date; + note?: string | null; + refreshOccurredAt?: boolean; + }, + ) { + if (args.amount == null && args.keepPending) { + await db.billingLedgerEntry.upsert({ + where: { + organizationId_sourceType_sourceId: { + organizationId: args.organizationId, + sourceType: args.sourceType, + sourceId: args.sourceId, + }, + }, + create: { + organizationId: args.organizationId, + partyKind: args.partyKind, + partyId: args.partyId, + sourceType: args.sourceType, + sourceId: args.sourceId, + amount: null, + signedAmount: null, + balanceSign: args.sign, + occurredAt: args.occurredAt, + note: args.note ?? null, + }, + update: { + partyKind: args.partyKind, + partyId: args.partyId, + amount: null, + signedAmount: null, + balanceSign: args.sign, + note: args.note ?? null, + }, + }); + return; + } + const amount = roundBillingAmount(args.amount ?? 0); + if (!Number.isFinite(amount) || amount <= 0) { + await db.billingLedgerEntry.deleteMany({ + where: { + organizationId: args.organizationId, + sourceType: args.sourceType, + sourceId: args.sourceId, + }, + }); + return; + } + const decimalAmount = new Prisma.Decimal(amount.toFixed(2)); + const signedAmount = new Prisma.Decimal((amount * args.sign).toFixed(2)); + await db.billingLedgerEntry.upsert({ + where: { + organizationId_sourceType_sourceId: { + organizationId: args.organizationId, + sourceType: args.sourceType, + sourceId: args.sourceId, + }, + }, + create: { + organizationId: args.organizationId, + partyKind: args.partyKind, + partyId: args.partyId, + sourceType: args.sourceType, + sourceId: args.sourceId, + amount: decimalAmount, + signedAmount, + balanceSign: args.sign, + occurredAt: args.occurredAt, + note: args.note ?? null, + }, + update: { + partyKind: args.partyKind, + partyId: args.partyId, + amount: decimalAmount, + signedAmount, + balanceSign: args.sign, + note: args.note ?? null, + ...(args.refreshOccurredAt ? { occurredAt: args.occurredAt } : {}), + }, + }); + } + + private async voidObligationSource( + db: Prisma.TransactionClient, + sourceType: BillingObligationSourceType, + sourceId: string, + ) { + await db.billingLedgerEntry.deleteMany({ where: { sourceType, sourceId } }); + } + /** Fee-schedule amount per treatment detail — shared by price stamping and commissions. */ private async clinicDetailAmounts(db: Prisma.TransactionClient, treatmentId: string) { const treatment = await db.treatment.findUnique({ @@ -1549,12 +2642,34 @@ export class BillingService { include: { toothProsthesis: true, treatment: { select: { organizationId: true } }, + parentLabCase: { + select: { + 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?.destinationOrganizationId) return; let clinicOrganizationId = labCase.treatment?.organizationId ?? null; - if (!clinicOrganizationId && labCase.partnerClinicOrganizationId) { + if (labCase.origin === 'LAB_OUTSOURCE') { + clinicOrganizationId = null; + } else if (!clinicOrganizationId && labCase.partnerClinicOrganizationId) { const partner = await db.organization.findUnique({ where: { id: labCase.partnerClinicOrganizationId }, select: { type: { select: { name: true } } }, @@ -1564,32 +2679,82 @@ export class BillingService { } } const asOf = toBillingDateOnly(labCase.sentAt ?? labCase.startedAt ?? new Date()); - const lines = await this.resolvedPriceLines(db, { + const resolvedSheet = await this.resolvedPriceSheet(db, { organizationId: labCase.destinationOrganizationId, kind: 'LAB_PRICE', asOf, clinicOrganizationId, }); const metaByCode = await this.prosthesisMetaByCode(db); - const calculated = calculateLabCaseAmount({ - jobs: labCase.toothProsthesis.map((job) => ({ - tooth: job.tooth, - prosthesisTypeCode: job.prosthesisTypeCode, - })), - lines, + const childJobs = labCase.toothProsthesis.map((job) => ({ + tooth: job.tooth, + prosthesisTypeCode: job.prosthesisTypeCode, + })); + let calculated = calculateLabCaseAmount({ + jobs: childJobs, + lines: resolvedSheet.lines, metaByCode, }); - const billed = labCase.billedAmountManual - ? Number(labCase.billedAmount ?? calculated) - : calculated; + let unpriced = unpricedProsthesisCodes(childJobs, resolvedSheet.lines).length > 0; + if (labCase.origin === 'LAB_OUTSOURCE' && labCase.parentLabCase) { + const parentTasks = labCase.parentLabCase.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 beforeSend = parentTasks.map((task) => + task.outsourcedToLabCaseId === labCase.id + ? { ...task, outsourcedToLabCaseId: null } + : task, + ); + const selectedIds = parentTasks + .filter((task) => task.outsourcedToLabCaseId === labCase.id) + .map((task) => task.id); + const selectable = beforeSend.filter( + (task) => outsourceTaskProblem(beforeSend, [task.id]) === null, + ); + const charge = outsourceChargeAmount({ + basis: outsourceQuoteBasis( + selectedIds, + selectable.map((task) => task.id), + ), + jobs: labCase.parentLabCase.toothProsthesis, + steps: selectable + .filter((task) => selectedIds.includes(task.id)) + .map((task) => ({ + workflowStepCode: task.workflowStepCode, + prosthesisTypeCode: task.prosthesisTypeCode, + teeth: task.teeth, + })), + lines: resolvedSheet.lines, + metaByCode, + }); + calculated = charge.calculated; + unpriced = charge.amount == null; + } + const hasManualAmount = + labCase.billedAmountManual && labCase.billedAmount != null; + const billed = hasManualAmount + ? Number(labCase.billedAmount) + : unpriced + ? null + : calculated; await db.labCase.update({ where: { id: labCase.id }, data: { calculatedAmount: new Prisma.Decimal(calculated.toFixed(2)), - billedAmount: new Prisma.Decimal(billed.toFixed(2)), + billedAmount: + billed == null ? null : new Prisma.Decimal(billed.toFixed(2)), }, }); + await this.syncPartnerCaseObligations(db, labCase.id); } private async resolvedPriceLines( @@ -1602,6 +2767,19 @@ export class BillingService { clinicOrganizationId?: string | null; }, ): Promise { + return (await this.resolvedPriceSheet(db, args)).lines; + } + + private async resolvedPriceSheet( + db: Prisma.TransactionClient, + args: { + organizationId: string; + kind: BillingSheetKindValue; + asOf: string; + userId?: string | null; + clinicOrganizationId?: string | null; + }, + ): Promise<{ id: string | null; hideUnpricedTypes: boolean; lines: BillingPriceLine[] }> { const sheets = await db.billingSheet.findMany({ where: { organizationId: args.organizationId, kind: args.kind }, include: { targets: true, lines: true }, @@ -1622,14 +2800,18 @@ export class BillingService { userId: args.userId, clinicOrganizationId: args.clinicOrganizationId, }); - if (!resolved) return []; + if (!resolved) return { id: null, hideUnpricedTypes: false, lines: [] }; const sheet = sheets.find((row) => row.id === resolved.id); - return (sheet?.lines ?? []).map((line) => ({ - catalogKind: line.catalogKind, - catalogCode: line.catalogCode, - amount: Number(line.amount), - percent: line.percent != null ? Number(line.percent) : null, - })); + return { + id: sheet?.id ?? null, + hideUnpricedTypes: Boolean(sheet?.hideUnpricedTypes), + lines: (sheet?.lines ?? []).map((line) => ({ + catalogKind: line.catalogKind, + catalogCode: line.catalogCode, + amount: Number(line.amount), + percent: line.percent != null ? Number(line.percent) : null, + })), + }; } private async prosthesisMetaByCode( @@ -1961,6 +3143,9 @@ export class BillingService { if (kind === 'CLINIC_PRICE' && hasEffectivePermission(membership, 'TAB_TREATMENT_READ')) { return; } + if (kind === 'LAB_PRICE' && hasEffectivePermission(membership, 'TAB_CASES_READ')) { + return; + } throw new AppException(ErrorCode.PERMISSION_ACCESS_BILLING, HttpStatus.FORBIDDEN); } @@ -1980,6 +3165,49 @@ export class BillingService { } } + private async staffBillingCurrency( + organizationId: string, + ): Promise { + const settings = await resolveBillingCurrency(this.prisma, organizationId); + return settings.currency ?? 'TOMAN'; + } + + private assertExpectedUpdatedAt(current: Date, expected: string) { + const parsed = new Date(expected); + if (!Number.isFinite(parsed.getTime()) || current.getTime() !== parsed.getTime()) { + this.throwTransactionChanged(); + } + } + + private throwTransactionChanged(): never { + throw new AppException(ErrorCode.BILLING_TRANSACTION_CHANGED, HttpStatus.CONFLICT); + } + + private async writeCashEvent( + db: Prisma.TransactionClient, + args: { + paymentKind: BillingCashPaymentKind; + paymentId: string; + eventType: BillingCashEventType; + organizationId: string; + actorUserId: string; + before: unknown; + after: unknown; + }, + ) { + await db.billingCashTransactionEvent.create({ + data: { + paymentKind: args.paymentKind, + paymentId: args.paymentId, + eventType: args.eventType, + organizationId: args.organizationId, + actorUserId: args.actorUserId, + beforeSnapshot: toAuditJson(args.before), + afterSnapshot: toAuditJson(args.after), + }, + }); + } + private async assertCanEdit(userId: string, organizationId: string) { const membership = await this.getMembership(userId, organizationId); if (!membership) { @@ -2015,6 +3243,10 @@ function isCommissionKind(kind: UpsertBillingSheetDto['kind']): boolean { return kind === 'CLINIC_COMMISSION' || kind === 'LAB_COMMISSION'; } +function isPriceKind(kind: UpsertBillingSheetDto['kind']): boolean { + return kind === 'CLINIC_PRICE' || kind === 'LAB_PRICE'; +} + function allowedCatalogKinds( kind: UpsertBillingSheetDto['kind'], ): UpsertBillingSheetDto['lines'][number]['catalogKind'][] { @@ -2051,6 +3283,12 @@ function stringList(value: unknown): string[] { return value.filter((item): item is string => typeof item === 'string'); } +function stalePeriodSourceFilter(suffix: string, keepIds: readonly string[]) { + return keepIds.length > 0 + ? { endsWith: suffix, notIn: [...keepIds] } + : { endsWith: suffix }; +} + function dateOnlyUtc(value: string): Date { return new Date(`${value}T00:00:00.000Z`); } @@ -2061,6 +3299,18 @@ function addUtcDays(dateOnly: string, days: number): string { return date.toISOString().slice(0, 10); } +function roundSignedBillingAmount(value: number): number { + if (!Number.isFinite(value)) return 0; + return Math.round(value * 100) / 100; +} + +function staffPeriodReference(sourceId: string): string { + const parts = sourceId.split(':'); + if (parts.length >= 4) return `${parts[1]}:${parts[2]}`; + if (parts.length === 3) return parts[1]; + return ''; +} + function parseMoney(value: string): number { const amount = Number(value.trim().replace(/,/g, '')); if (!Number.isFinite(amount) || amount < 0) { @@ -2069,6 +3319,18 @@ function parseMoney(value: string): number { return roundBillingAmount(amount); } +function parsePositiveMoney(value: string): number { + const amount = parseMoney(value); + if (amount <= 0) { + throw new AppException(ErrorCode.BILLING_AMOUNT_INVALID, HttpStatus.BAD_REQUEST); + } + return amount; +} + +function toAuditJson(value: unknown): Prisma.InputJsonValue { + return JSON.parse(JSON.stringify(value)) as Prisma.InputJsonValue; +} + function normalizeAllocations( allocations: Array<{ targetId: string; amount: string }> | undefined, ): Array<{ targetId: string; amount: number }> { @@ -2158,6 +3420,18 @@ function paidAtWhere(query: { from?: string; to?: string }): { }; } +function occurredAtWhere(query: { from?: string; to?: string }): { + occurredAt?: { gte?: Date; lt?: Date }; +} { + if (!query.from && !query.to) return {}; + return { + occurredAt: { + ...(query.from ? { gte: dateOnlyUtc(query.from) } : {}), + ...(query.to ? { lt: dateOnlyUtc(addUtcDays(query.to, 1)) } : {}), + }, + }; +} + function normalizePartyFilter(query: PaymentListQuery): { kind: 'patient' | 'staff' | 'org'; id: string; @@ -2171,13 +3445,17 @@ function mapStaffPayment( ) { return { id: payment.id, + organizationId: payment.organizationId, userId: payment.userId, externalPartyName: payment.externalPartyName, partyName: payment.user?.name ?? payment.externalPartyName ?? '', amount: payment.amount.toString(), paidAt: payment.paidAt.toISOString(), note: payment.note, + canEdit: true, + createdByUserId: payment.createdByUserId, createdAt: payment.createdAt.toISOString(), + updatedAt: payment.updatedAt.toISOString(), }; } @@ -2186,6 +3464,7 @@ function mapPatientPayment( ) { return { id: payment.id, + organizationId: payment.organizationId, patientId: payment.patientId, externalPartyName: payment.externalPartyName, patientName: payment.patient @@ -2195,6 +3474,7 @@ function mapPatientPayment( amount: payment.amount.toString(), paidAt: payment.paidAt.toISOString(), note: payment.note, + canEdit: true, remainder: remainderOf(payment.amount, payment.allocations), allocations: payment.allocations.map((row) => ({ treatmentId: row.treatmentId, @@ -2203,28 +3483,43 @@ function mapPatientPayment( treatmentTitle: row.treatment.title, patientName: `${row.treatment.patient.firstName} ${row.treatment.patient.lastName}`.trim(), })), + createdByUserId: payment.createdByUserId, createdAt: payment.createdAt.toISOString(), + updatedAt: payment.updatedAt.toISOString(), }; } +function partnerCashCanAllocate( + payment: Prisma.PartnerPaymentGetPayload<{ include: typeof partnerPaymentInclude }>, +): boolean { + const fromType = payment.fromOrganization?.type.name; + const toType = payment.toOrganization?.type.name; + if (!fromType || !toType) return false; + return ( + (fromType === 'CLINIC' && toType === 'LAB') || + (fromType === 'LAB' && toType === 'CLINIC') + ); +} + 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 }; + return resolvePartnerCashSides({ + from: payment.fromOrganization + ? { + id: payment.fromOrganization.id, + typeName: payment.fromOrganization.type.name, + } + : null, + to: payment.toOrganization + ? { + id: payment.toOrganization.id, + typeName: payment.toOrganization.type.name, + } + : null, + recorderOrganizationId: payment.recorderOrganizationId, + recordedBy: payment.recordedBy, + }); } function mapPartnerPayment( @@ -2246,7 +3541,12 @@ function mapPartnerPayment( note: payment.note, status: payment.status, recordedBy: payment.recordedBy, + recorderOrganizationId: payment.recorderOrganizationId, recordedByViewer: sides.senderId === viewerOrganizationId, + canEdit: + sides.senderId === viewerOrganizationId && + payment.recorderOrganizationId === viewerOrganizationId, + canAllocate: partnerCashCanAllocate(payment), acknowledgement, canAcknowledge: sides.counterpartyId === viewerOrganizationId && acknowledgement === 'pending', externalPartyName: payment.externalPartyName, @@ -2268,7 +3568,9 @@ function mapPartnerPayment( caseLabel: row.labCase.externalCode?.trim() || patient || row.labCaseId.slice(0, 8), }; }), + createdByUserId: payment.createdByUserId, createdAt: payment.createdAt.toISOString(), + updatedAt: payment.updatedAt.toISOString(), }; } @@ -2294,6 +3596,7 @@ function mapSheet( kind: sheet.kind, name: sheet.name, effectiveOn: toBillingDateOnly(sheet.effectiveOn), + hideUnpricedTypes: sheet.hideUnpricedTypes, targetUserIds: targetUsers.map((user) => user.id), targetClinicIds: targetClinics.map((clinic) => clinic.id), targetUsers, diff --git a/backend/src/modules/billing/calculate-amounts.spec.ts b/backend/src/modules/billing/calculate-amounts.spec.ts index 00649b8..34176a4 100644 --- a/backend/src/modules/billing/calculate-amounts.spec.ts +++ b/backend/src/modules/billing/calculate-amounts.spec.ts @@ -7,6 +7,7 @@ import { calculateOutsourceStepsAmount, commissionQtyForTask, isPerTypeProsthesisUnit, + outsourceChargeAmount, outsourceQuoteBasis, preferNonEmptyJobs, priceFor, @@ -234,4 +235,66 @@ describe('outsource price quote', () => { ), ).toBe(20 * 2 + 40 + 8); }); + + it('stores a step total only when every selected step has a price', () => { + const priced = outsourceChargeAmount({ + basis: 'steps', + jobs: [], + steps: [ + { + workflowStepCode: 'milling_dry_sinter', + prosthesisTypeCode: 'pfz_crown', + teeth: ['14'], + }, + ], + lines: stepLines, + metaByCode: meta, + }); + expect(priced.amount).toBe(15); + + const missing = outsourceChargeAmount({ + basis: 'steps', + jobs: [], + steps: [ + { + workflowStepCode: 'milling_dry_sinter', + prosthesisTypeCode: 'pfz_crown', + teeth: ['14'], + }, + { + workflowStepCode: 'polish_prep', + prosthesisTypeCode: 'pfz_crown', + teeth: ['14'], + }, + ], + lines: stepLines, + metaByCode: meta, + }); + expect(missing.calculated).toBe(15); + expect(missing.amount).toBeNull(); + }); + + it('stores a prosthesis total only when every job has a price', () => { + expect( + outsourceChargeAmount({ + basis: 'prosthesis', + jobs: [{ tooth: '14', prosthesisTypeCode: 'pfz_crown' }], + steps: [], + lines, + metaByCode: meta, + }).amount, + ).toBe(100); + expect( + outsourceChargeAmount({ + basis: 'prosthesis', + jobs: [ + { tooth: '14', prosthesisTypeCode: 'pfz_crown' }, + { tooth: '14', prosthesisTypeCode: 'unknown_type' }, + ], + steps: [], + lines, + metaByCode: meta, + }).amount, + ).toBeNull(); + }); }); diff --git a/backend/src/modules/billing/calculate-amounts.ts b/backend/src/modules/billing/calculate-amounts.ts index ae1b2d6..7b8155e 100644 --- a/backend/src/modules/billing/calculate-amounts.ts +++ b/backend/src/modules/billing/calculate-amounts.ts @@ -184,3 +184,64 @@ export function outsourceQuoteBasis( if (selectableIds.every((id) => selected.has(id))) return 'prosthesis'; return 'steps'; } + +/** Prosthesis types with no positive price. A zero line counts as missing. */ +export function unpricedProsthesisCodes( + jobs: readonly { prosthesisTypeCode: string }[], + lines: readonly BillingPriceLine[], +): string[] { + const priced = new Set( + lines + .filter((line) => line.catalogKind === 'PROSTHESIS_TYPE' && line.amount > 0) + .map((line) => line.catalogCode), + ); + return [ + ...new Set( + jobs + .map((job) => job.prosthesisTypeCode.trim()) + .filter((code) => Boolean(code) && !priced.has(code)), + ), + ].sort(); +} + +/** + * Amount stored for an outsource. A missing or zero price stays unset so the + * obligation is pending instead of a partial total. `calculated` is the raw + * sheet math, with missing lines counted as zero. + */ +export function outsourceChargeAmount(args: { + basis: 'empty' | 'prosthesis' | 'steps'; + jobs: readonly ToothProsthesisJob[]; + steps: readonly OutsourceQuoteTask[]; + lines: readonly BillingPriceLine[]; + metaByCode: ReadonlyMap; +}): { calculated: number; amount: number | null } { + if (args.basis === 'steps') { + const calculated = calculateOutsourceStepsAmount( + args.steps, + args.lines, + args.metaByCode, + ); + const missing = + args.steps.length === 0 || + args.steps.some((step) => { + const code = outsourcingPriceCodeForStep( + step.workflowStepCode, + step.prosthesisTypeCode, + ); + return priceFor(args.lines, 'LAB_WORKFLOW_STEP', code) <= 0; + }); + return { calculated, amount: missing ? null : calculated }; + } + if (args.basis === 'prosthesis') { + const calculated = calculateLabCaseAmount({ + jobs: args.jobs, + lines: args.lines, + metaByCode: args.metaByCode, + }); + const missing = + unpricedProsthesisCodes(args.jobs, args.lines).length > 0 || calculated <= 0; + return { calculated, amount: missing ? null : calculated }; + } + return { calculated: 0, amount: null }; +} diff --git a/backend/src/modules/billing/dto/billing-payment.dto.ts b/backend/src/modules/billing/dto/billing-payment.dto.ts index ce2b04f..bcdeab6 100644 --- a/backend/src/modules/billing/dto/billing-payment.dto.ts +++ b/backend/src/modules/billing/dto/billing-payment.dto.ts @@ -2,6 +2,7 @@ import { Type } from 'class-transformer'; import { ArrayMaxSize, IsArray, + IsDateString, IsIn, IsNumberString, IsOptional, @@ -18,7 +19,9 @@ export class PaymentAllocationDto { targetId: string; @IsNumberString({}, { message: ErrorCode.BILLING_AMOUNT_INVALID }) - @Matches(/^\d+(\.\d{1,2})?$/, { message: ErrorCode.BILLING_AMOUNT_INVALID }) + @Matches(/^(?=.*[1-9])\d+(\.\d{1,2})?$/, { + message: ErrorCode.BILLING_AMOUNT_INVALID, + }) amount: string; } @@ -27,7 +30,9 @@ export class CreatePaymentDto { type: 'RECEIPT' | 'PAYMENT'; @IsNumberString({}, { message: ErrorCode.BILLING_AMOUNT_INVALID }) - @Matches(/^\d+(\.\d{1,2})?$/, { message: ErrorCode.BILLING_AMOUNT_INVALID }) + @Matches(/^(?=.*[1-9])\d+(\.\d{1,2})?$/, { + message: ErrorCode.BILLING_AMOUNT_INVALID, + }) amount: string; @IsOptional() @@ -72,6 +77,32 @@ export class CreatePaymentDto { export class AcknowledgePaymentDto { @IsIn(['ACCEPT', 'DECLINE'], { message: ErrorCode.BILLING_PAYMENT_ACK_INVALID }) decision: 'ACCEPT' | 'DECLINE'; + + @IsDateString({}, { message: ErrorCode.BILLING_TRANSACTION_CHANGED }) + expectedUpdatedAt: string; +} + +export class UpdatePaymentDto { + @IsNumberString({}, { message: ErrorCode.BILLING_AMOUNT_INVALID }) + @Matches(/^(?=.*[1-9])\d+(\.\d{1,2})?$/, { + message: ErrorCode.BILLING_AMOUNT_INVALID, + }) + amount: string; + + @IsOptional() + @IsString() + @MaxLength(500) + note?: string; + + @IsOptional() + @IsArray() + @ValidateNested({ each: true }) + @Type(() => PaymentAllocationDto) + @ArrayMaxSize(50) + allocations?: PaymentAllocationDto[]; + + @IsDateString({}, { message: ErrorCode.BILLING_TRANSACTION_CHANGED }) + expectedUpdatedAt: string; } export class ListPaymentsQueryDto { @@ -99,6 +130,47 @@ export class ListPaymentsQueryDto { partyId?: string; } +export class PartyReportQueryDto { + @IsIn(['patient', 'staff', 'org'], { message: ErrorCode.BILLING_PARTY_INVALID }) + partyKind: 'patient' | 'staff' | 'org'; + + @IsUUID() + partyId: string; + + @IsOptional() + @IsString() + @Matches(/^\d{4}-\d{2}-\d{2}$/) + from?: string; + + @IsOptional() + @IsString() + @Matches(/^\d{4}-\d{2}-\d{2}$/) + to?: string; +} + +export class StaffSalaryLineDto { + @IsUUID('all', { message: ErrorCode.BILLING_TARGET_INVALID }) + userId: string; + + @IsNumberString({}, { message: ErrorCode.BILLING_AMOUNT_INVALID }) + @Matches(/^\d+(\.\d{1,2})?$/, { message: ErrorCode.BILLING_AMOUNT_INVALID }) + fixedMonthlySalary: string; +} + +export class SaveStaffSalarySheetDto { + @IsArray() + @ArrayMaxSize(500) + @ValidateNested({ each: true }) + @Type(() => StaffSalaryLineDto) + lines: StaffSalaryLineDto[]; +} + +export class UpdateObligationAmountDto { + @IsNumberString({}, { message: ErrorCode.BILLING_AMOUNT_INVALID }) + @Matches(/^\d+(\.\d{1,2})?$/, { message: ErrorCode.BILLING_AMOUNT_INVALID }) + amount: string; +} + export class PartySearchQueryDto { @IsOptional() @IsString() diff --git a/backend/src/modules/billing/dto/upsert-billing-sheet.dto.ts b/backend/src/modules/billing/dto/upsert-billing-sheet.dto.ts index 00bf93e..8928a01 100644 --- a/backend/src/modules/billing/dto/upsert-billing-sheet.dto.ts +++ b/backend/src/modules/billing/dto/upsert-billing-sheet.dto.ts @@ -2,6 +2,7 @@ import { Type } from 'class-transformer'; import { ArrayMaxSize, IsArray, + IsBoolean, IsIn, IsNumberString, IsOptional, @@ -67,6 +68,10 @@ export class UpsertBillingSheetDto { @ArrayMaxSize(200) targetClinicIds?: string[]; + @IsOptional() + @IsBoolean() + hideUnpricedTypes?: boolean; + @IsArray() @ValidateNested({ each: true }) @Type(() => BillingSheetLineDto) diff --git a/backend/src/modules/billing/party-ledger.spec.ts b/backend/src/modules/billing/party-ledger.spec.ts new file mode 100644 index 0000000..b87e2b4 --- /dev/null +++ b/backend/src/modules/billing/party-ledger.spec.ts @@ -0,0 +1,58 @@ +import { + sharedCashCountsInPartyReport, + signedPartyCashAmount, +} from './party-ledger'; + +describe('signedPartyCashAmount', () => { + it('credits a party when the organization receives cash from it', () => { + expect(signedPartyCashAmount('RECEIPT', 125)).toBe(-125); + }); + + it('debits a party when the organization pays it', () => { + expect(signedPartyCashAmount('PAYMENT', 125)).toBe(125); + }); + + it('counts a pending shared payment only for the organization that recorded it', () => { + expect( + sharedCashCountsInPartyReport({ + kind: 'partner', + acknowledgement: 'pending', + recordedByViewer: true, + }), + ).toBe(true); + expect( + sharedCashCountsInPartyReport({ + kind: 'partner', + acknowledgement: 'pending', + recordedByViewer: false, + }), + ).toBe(false); + }); + + it('counts accepted shared payments for both parties', () => { + expect( + sharedCashCountsInPartyReport({ + kind: 'partner', + acknowledgement: 'accepted', + recordedByViewer: false, + }), + ).toBe(true); + }); + + it('counts a rejected shared payment only for its recorder', () => { + expect( + sharedCashCountsInPartyReport({ + kind: 'partner', + acknowledgement: 'rejected', + recordedByViewer: true, + }), + ).toBe(true); + expect( + sharedCashCountsInPartyReport({ + kind: 'partner', + acknowledgement: 'rejected', + recordedByViewer: false, + }), + ).toBe(false); + }); +}); diff --git a/backend/src/modules/billing/party-ledger.ts b/backend/src/modules/billing/party-ledger.ts new file mode 100644 index 0000000..fe9729e --- /dev/null +++ b/backend/src/modules/billing/party-ledger.ts @@ -0,0 +1,19 @@ +export function signedPartyCashAmount( + type: 'RECEIPT' | 'PAYMENT', + amount: number, +): number { + if (!Number.isFinite(amount) || amount < 0) return 0; + return type === 'RECEIPT' ? -amount : amount; +} + +export function sharedCashCountsInPartyReport(row: { + kind: 'patient' | 'partner' | 'staff'; + acknowledgement: string; + recordedByViewer: boolean; +}): boolean { + if (row.kind !== 'partner' || row.acknowledgement === 'none') return true; + if (row.acknowledgement === 'accepted') return true; + if (row.acknowledgement === 'pending') return row.recordedByViewer; + if (row.acknowledgement === 'rejected') return row.recordedByViewer; + return false; +} diff --git a/backend/src/modules/billing/staff-billing-period.spec.ts b/backend/src/modules/billing/staff-billing-period.spec.ts new file mode 100644 index 0000000..16cd4f3 --- /dev/null +++ b/backend/src/modules/billing/staff-billing-period.spec.ts @@ -0,0 +1,68 @@ +import { + finishedStaffBillingPeriods, + previousStaffBillingPeriod, + staffBillingPeriodForDate, + staffBillingPeriodFromKey, + staffBillingPeriodsBetween, + staffPeriodLastDay, + staffPeriodsAfter, +} from './staff-billing-period'; + +describe('staff billing periods', () => { + const duringAban1405 = new Date('2026-11-11T12:00:00.000Z'); + + it('uses Jalali month boundaries for Toman', () => { + const period = staffBillingPeriodForDate(duringAban1405, 'TOMAN'); + + expect(period.key).toBe('J:1405-08'); + expect(period.start.toISOString()).toBe('2026-10-23T00:00:00.000Z'); + expect(period.end.toISOString()).toBe('2026-11-22T00:00:00.000Z'); + }); + + it.each(['DOLLAR', 'EURO'] as const)( + 'uses Gregorian month boundaries for %s', + (currency) => { + const period = staffBillingPeriodForDate(duringAban1405, currency); + + expect(period.key).toBe('G:2026-11'); + expect(period.start.toISOString()).toBe('2026-11-01T00:00:00.000Z'); + expect(period.end.toISOString()).toBe('2026-12-01T00:00:00.000Z'); + }, + ); + + it('round-trips keys and finds the preceding Jalali period', () => { + expect(staffBillingPeriodFromKey('J:1405-08')?.start.toISOString()).toBe( + '2026-10-23T00:00:00.000Z', + ); + expect(previousStaffBillingPeriod(duringAban1405, 'TOMAN').key).toBe( + 'J:1405-07', + ); + }); + + it('dates a closed month on its last day and skips the month still in progress', () => { + const current = staffBillingPeriodForDate(duringAban1405, 'TOMAN'); + expect(staffPeriodLastDay(current).toISOString()).toBe('2026-11-21T00:00:00.000Z'); + + const finished = finishedStaffBillingPeriods( + new Date('2026-08-01T00:00:00.000Z'), + duringAban1405, + 'TOMAN', + ).map((period) => period.key); + expect(finished.at(-1)).toBe('J:1405-07'); + expect(finished).not.toContain('J:1405-08'); + expect(staffPeriodsAfter('J:1405-07', duringAban1405, 'TOMAN')).toEqual([]); + expect( + staffPeriodsAfter('J:1405-06', duringAban1405, 'TOMAN').map((period) => period.key), + ).toEqual(['J:1405-07']); + }); + + it('enumerates every period touched by a date range', () => { + expect( + staffBillingPeriodsBetween( + new Date('2026-10-20T00:00:00.000Z'), + new Date('2026-11-25T00:00:00.000Z'), + 'TOMAN', + ).map((period) => period.key), + ).toEqual(['J:1405-07', 'J:1405-08', 'J:1405-09']); + }); +}); diff --git a/backend/src/modules/billing/staff-billing-period.ts b/backend/src/modules/billing/staff-billing-period.ts new file mode 100644 index 0000000..1cdf3d7 --- /dev/null +++ b/backend/src/modules/billing/staff-billing-period.ts @@ -0,0 +1,160 @@ +import { + gregorianToJalali, + jalaliToGregorian, +} from '../../common/jalali'; +import type { BillingCurrencyCode } from './billing-currency'; + +export type StaffBillingPeriod = { + key: string; + calendar: 'JALALI' | 'GREGORIAN'; + label: string; + start: Date; + end: Date; +}; + +function utcDate(year: number, month: number, day: number): Date { + return new Date(Date.UTC(year, month - 1, day)); +} + +function twoDigits(value: number): string { + return String(value).padStart(2, '0'); +} + +export function staffBillingPeriodForDate( + date: Date, + currency: BillingCurrencyCode, +): StaffBillingPeriod { + if (currency === 'TOMAN') { + const [jy, jm] = gregorianToJalali( + date.getUTCFullYear(), + date.getUTCMonth() + 1, + date.getUTCDate(), + ); + const [startYear, startMonth, startDay] = jalaliToGregorian(jy, jm, 1); + const nextJy = jm === 12 ? jy + 1 : jy; + const nextJm = jm === 12 ? 1 : jm + 1; + const [endYear, endMonth, endDay] = jalaliToGregorian(nextJy, nextJm, 1); + const label = `${jy}-${twoDigits(jm)}`; + return { + key: `J:${label}`, + calendar: 'JALALI', + label, + start: utcDate(startYear, startMonth, startDay), + end: utcDate(endYear, endMonth, endDay), + }; + } + + const year = date.getUTCFullYear(); + const month = date.getUTCMonth() + 1; + const label = `${year}-${twoDigits(month)}`; + return { + key: `G:${label}`, + calendar: 'GREGORIAN', + label, + start: utcDate(year, month, 1), + end: utcDate(year, month + 1, 1), + }; +} + +export function staffBillingPeriodFromKey(key: string): StaffBillingPeriod | null { + const match = /^(J|G):(-?\d{1,4})-(\d{2})$/.exec(key); + if (!match) return null; + const year = Number(match[2]); + const month = Number(match[3]); + if (!Number.isInteger(year) || !Number.isInteger(month) || month < 1 || month > 12) { + return null; + } + + if (match[1] === 'J') { + try { + const [startYear, startMonth, startDay] = jalaliToGregorian(year, month, 1); + const nextYear = month === 12 ? year + 1 : year; + const nextMonth = month === 12 ? 1 : month + 1; + const [endYear, endMonth, endDay] = jalaliToGregorian(nextYear, nextMonth, 1); + const label = `${year}-${twoDigits(month)}`; + return { + key: `J:${label}`, + calendar: 'JALALI', + label, + start: utcDate(startYear, startMonth, startDay), + end: utcDate(endYear, endMonth, endDay), + }; + } catch { + return null; + } + } + + if (year < 1 || year > 9999) return null; + const start = utcDate(year, month, 1); + const end = utcDate(year, month + 1, 1); + const label = `${year}-${twoDigits(month)}`; + return { + key: `G:${label}`, + calendar: 'GREGORIAN', + label, + start, + end, + }; +} + +export function previousStaffBillingPeriod( + date: Date, + currency: BillingCurrencyCode, +): StaffBillingPeriod { + const current = staffBillingPeriodForDate(date, currency); + return staffBillingPeriodForDate( + new Date(current.start.getTime() - 1), + currency, + ); +} + +/** UTC midnight on the period's last calendar day. */ +export function staffPeriodLastDay(period: StaffBillingPeriod): Date { + return new Date(period.end.getTime() - 24 * 60 * 60 * 1000); +} + +export function staffPeriodKeyMatchesCurrency( + key: string, + currency: BillingCurrencyCode, +): boolean { + return currency === 'TOMAN' ? key.startsWith('J:') : key.startsWith('G:'); +} + +/** Periods that have fully ended by `now`, starting from the period that contains `from`. */ +export function finishedStaffBillingPeriods( + from: Date, + now: Date, + currency: BillingCurrencyCode, +): StaffBillingPeriod[] { + const previous = previousStaffBillingPeriod(now, currency); + if (previous.end > now) return []; + const through = new Date(previous.end.getTime() - 1); + return staffBillingPeriodsBetween(from, through, currency); +} + +/** Finished periods strictly after a closed period key. */ +export function staffPeriodsAfter( + closedThroughKey: string, + now: Date, + currency: BillingCurrencyCode, +): StaffBillingPeriod[] { + const closed = staffBillingPeriodFromKey(closedThroughKey); + if (!closed || !staffPeriodKeyMatchesCurrency(closedThroughKey, currency)) return []; + return finishedStaffBillingPeriods(closed.end, now, currency); +} + +export function staffBillingPeriodsBetween( + from: Date, + to: Date, + currency: BillingCurrencyCode, + limit = 120, +): StaffBillingPeriod[] { + if (from > to || limit <= 0) return []; + const periods: StaffBillingPeriod[] = []; + let period = staffBillingPeriodForDate(from, currency); + while (period.start <= to && periods.length < limit) { + periods.push(period); + period = staffBillingPeriodForDate(period.end, currency); + } + return periods; +} diff --git a/backend/src/modules/cases/cases.service.ts b/backend/src/modules/cases/cases.service.ts index af6a497..68eb152 100644 --- a/backend/src/modules/cases/cases.service.ts +++ b/backend/src/modules/cases/cases.service.ts @@ -728,6 +728,7 @@ export class CasesService { if (outsourceBlocksStop(stillOpen)) { throw new AppException(ErrorCode.LAB_CASE_OUTSOURCE_OPEN, HttpStatus.CONFLICT); } + await this.billing.voidCaseObligations(tx, [labCaseId, ...openIds]); await deleteOutsourceDescendants(tx, labCaseId); const round = await tx.labCaseRound.create({ data: { @@ -919,6 +920,7 @@ export class CasesService { tx, ); + await this.billing.stampLabCasePrice(tx, child.id); return child.id; }); @@ -968,7 +970,10 @@ export class CasesService { throw new AppException(ErrorCode.LAB_CASE_OUTSOURCE_RECALL_NOT_ALLOWED, HttpStatus.CONFLICT); } - await this.prisma.labCase.delete({ where: { id: child.id } }); + await this.prisma.$transaction(async (tx) => { + await this.billing.voidCaseObligations(tx, child.id); + await tx.labCase.delete({ where: { id: child.id } }); + }); const refreshed = await this.prisma.labCase.findFirstOrThrow({ where: { id: labCaseId }, diff --git a/backend/src/modules/treatments/treatments.service.ts b/backend/src/modules/treatments/treatments.service.ts index 908b400..dd6f63f 100644 --- a/backend/src/modules/treatments/treatments.service.ts +++ b/backend/src/modules/treatments/treatments.service.ts @@ -14,6 +14,7 @@ import { PrismaService } from '../../../prisma/prisma.service'; import { generateLabCaseTasks } from '../cases/lab-case-task.generator'; import { deleteOutsourceDescendants, + listOutsourceDescendantIds, outsourceTreeHasCompletedTask, } from '../cases/lab-case-outsource.tree'; import { ProsthesisCatalogService } from '../prosthesis-catalog/prosthesis-catalog.service'; @@ -273,7 +274,10 @@ export class TreatmentsService { throw new AppException(ErrorCode.TREATMENT_HAS_DETAILS, HttpStatus.CONFLICT); } - await this.prisma.treatment.delete({ where: { id: treatmentId } }); + await this.prisma.$transaction(async (tx) => { + await this.billing.voidTreatmentObligation(tx, treatmentId); + await tx.treatment.delete({ where: { id: treatmentId } }); + }); return { success: true }; } @@ -624,6 +628,7 @@ export class TreatmentsService { }, }); await this.billing.stampClinicCommissions(tx, treatmentId); + await this.billing.syncTreatmentObligation(tx, treatmentId); }); const treatment = await this.prisma.treatment.findUniqueOrThrow({ where: { id: treatmentId }, @@ -878,6 +883,7 @@ export class TreatmentsService { select: { id: true, sentAt: true, + destinationOrganizationId: true, toothProsthesis: { select: { tooth: true, prosthesisTypeCode: true, selectionGroupId: true }, }, @@ -909,6 +915,23 @@ export class TreatmentsService { if (await outsourceTreeHasCompletedTask(tx, lc.id)) { throw new AppException(ErrorCode.TREATMENT_DETAIL_SENT, HttpStatus.CONFLICT); } + const storedJobs = new Set( + (stored?.toothProsthesis ?? []).map( + (row) => `${row.tooth}\t${row.prosthesisTypeCode}`, + ), + ); + const introducedJobs = (lc.toothProsthesis ?? []).filter( + (row) => !storedJobs.has(`${row.tooth}\t${row.prosthesisTypeCode}`), + ); + if (stored?.destinationOrganizationId && introducedJobs.length > 0) { + await this.billing.assertLabProvidesProsthesis(tx, { + labOrganizationId: stored.destinationOrganizationId, + clinicOrganizationId: organizationId, + jobs: introducedJobs, + }); + } + const outsourceIds = await listOutsourceDescendantIds(tx, lc.id); + await this.billing.voidCaseObligations(tx, outsourceIds); await deleteOutsourceDescendants(tx, lc.id); await tx.labCaseToothProsthesis.deleteMany({ where: { labCaseId: lc.id } }); const prosthesisRows = new Map< @@ -1149,6 +1172,15 @@ export class TreatmentsService { throw new AppException(ErrorCode.TREATMENT_CASE_ALREADY_SENT, HttpStatus.BAD_REQUEST); } + await this.billing.assertLabProvidesProsthesis( + this.prisma as unknown as Prisma.TransactionClient, + { + labOrganizationId: labCase.destinationOrganizationId, + clinicOrganizationId: organizationId, + jobs: labCase.toothProsthesis, + }, + ); + const now = new Date(); const isFirstSend = !labCase.sentAt; diff --git a/frontend/messages/en.json b/frontend/messages/en.json index 456c831..51a07c4 100644 --- a/frontend/messages/en.json +++ b/frontend/messages/en.json @@ -558,6 +558,7 @@ "sendToExocadCloseHint": "Close Exocad before sending. Open it again afterwards to see the case.", "sendCaseTitle": "Outsource steps", "outsourcePrice": "Outsource price", + "outsourcePricePending": "This outsource includes work without a fee. You can send it, but the destination lab must set the final amount in Billing.", "sendCaseSelectAll": "Select all", "sendCaseLab": "Lab", "sendCaseLabsLoading": "Loading labs...", @@ -889,6 +890,8 @@ "selectLabPlaceholder": "Choose a linked lab…", "sendToLab": "Send to lab", "labFeePreview": "Lab fee", + "labFeeNeedsBillingAmount": "This case contains services without a lab fee. You can send it, but the destination lab must set the final amount in Billing.", + "labDoesNotProvideTypes": "This lab does not provide the following prosthesis services: {types}. Choose another lab or change the case.", "dueDateLabel": "Due date", "dueDateOptional": "optional", "dueDateLockedCompleted": "Due date cannot be changed after all tasks are completed.", @@ -1285,7 +1288,7 @@ "billing": { "title": "Billing", "feeSchedules": "Fee schedules", - "staffCommissions": "Staff commissions", + "staffCommissions": "Commissions/Salary", "transactions": "Transactions", "addTransaction": "Add transaction", "newFeeSchedule": "New fee schedule", @@ -1295,6 +1298,10 @@ "transactionHistory": "Transaction history", "feeScheduleHistory": "Fee schedule history", "commissionHistory": "Commission history", + "updateStaffSalary": "Update staff salary", + "staffSalarySection": "Staff salary", + "salaryUpdated": "Updated", + "noSalaryStaff": "No staff to pay.", "startDate": "Start date", "startDateRequired": "Choose the date this schedule takes effect.", "sheetName": "Name", @@ -1332,6 +1339,7 @@ "noPayments": "No transactions yet.", "searchPayments": "Search transactions", "filterByParty": "Filter by party", + "clearPartyFilter": "Clear selected party", "typeFilterAll": "All types", "dateFrom": "From", "dateTo": "To", @@ -1373,7 +1381,52 @@ "time": "Time", "attachments": "Attachments", "cancel": "Cancel", - "walkInPatient": "Walk-in" + "walkInPatient": "Walk-in", + "hideUnpricedTypes": "Hide prosthesis types without a price", + "hideUnpricedTypesClinicInfo": "Unpriced prosthesis types will be hidden from the clinic treatment chart while this fee schedule is active.", + "hideUnpricedTypesLabInfo": "Unpriced prosthesis types will be hidden from this lab's case chart. Linked clinics will also be prevented from sending cases that contain those services while this schedule is active.", + "debitCreditReport": "Debit/credit report", + "debit": "Debit", + "credit": "Credit", + "reportSource": "Source", + "reference": "Reference", + "reportEmpty": "No debit or credit rows match this period.", + "reportSourceTreatment": "Approved treatment", + "reportSourceLabCase": "Case fee", + "reportSourceReceivedCase": "Received case", + "reportSourceGeneratedCase": "Generated case", + "reportSourceOutsource": "Outsourced case", + "caseOriginReceived": "Received", + "caseOriginGenerated": "Generated", + "caseOriginOutsourced": "From lab", + "reportSourceCommission": "Monthly commissions", + "reportSourceSalary": "Monthly salary", + "reportSourceCashReceipt": "Cash receipt", + "reportSourceCashPayment": "Cash payment", + "reportDebitTotal": "Debit total: {amount}", + "reportCreditTotal": "Credit total: {amount}", + "reportNet": "Net: {amount}", + "errorLoadReport": "Could not load the debit/credit report.", + "fixedMonthlySalary": "Fixed monthly salary", + "saveSalary": "Save salary", + "salarySaved": "Monthly salary saved.", + "errorLoadSalary": "Could not load the monthly salary.", + "errorSaveSalary": "Could not save the monthly salary.", + "obligationAmountRequired": "Amount required", + "caseObligationAmount": "Case fee", + "setObligationAmount": "Set amount", + "saveObligationAmount": "Save amount", + "obligationAmountSaved": "The case fee was saved for both organizations.", + "errorSaveObligationAmount": "Could not save the case fee.", + "actions": "Actions", + "balanceTotal": "Balance", + "paymentAccepted": "Accepted", + "editTransaction": "Edit transaction", + "transactionUpdated": "Transaction updated.", + "errorUpdateTransaction": "Could not update the transaction.", + "commissionSubtotal": "Commission", + "fixedSalarySubtotal": "Fixed salary", + "grossCompensation": "Gross compensation" }, "localDb": { "browse": "Browse", @@ -1602,9 +1655,13 @@ "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_NOT_EDITABLE": "Only the organization that recorded this payment can edit it.", + "BILLING_TRANSACTION_CHANGED": "This transaction changed since you opened it. Refresh and try again.", "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." + "BILLING_PARTY_INVALID": "Choose a valid party for this filter.", + "BILLING_PROSTHESIS_NOT_PROVIDED": "The selected lab does not provide one or more prosthesis types in this case.", + "BILLING_OBLIGATION_NOT_EDITABLE": "Only the destination lab can set this case fee." } } diff --git a/frontend/messages/fa.json b/frontend/messages/fa.json index 89b143f..830c707 100644 --- a/frontend/messages/fa.json +++ b/frontend/messages/fa.json @@ -558,6 +558,7 @@ "sendToExocadCloseHint": "پیش از ارسال Exocad را ببندید. بعد از ارسال آن را دوباره باز کنید تا پرونده را ببینید.", "sendCaseTitle": "مراحل برون سپاری", "outsourcePrice": "قیمت برون‌سپاری", + "outsourcePricePending": "این برون‌سپاری شامل کار بدون تعرفه است. ارسال مجاز است، اما لابراتوار مقصد باید مبلغ نهایی را در بخش مالی ثبت کند.", "sendCaseSelectAll": "انتخاب همه", "sendCaseLab": "لابراتوار", "sendCaseLabsLoading": "در حال بارگذاری لابراتوارها...", @@ -890,6 +891,8 @@ "selectLabPlaceholder": "یک لابراتوار متصل انتخاب کنید…", "sendToLab": "ارسال به لابراتوار", "labFeePreview": "تعرفه لابراتوار", + "labFeeNeedsBillingAmount": "این پرونده شامل خدماتی بدون تعرفه لابراتوار است. ارسال مجاز است، اما لابراتوار مقصد باید مبلغ نهایی را در بخش مالی ثبت کند.", + "labDoesNotProvideTypes": "این لابراتوار خدمات پروتز زیر را ارائه نمی‌دهد: {types}. لابراتوار دیگری انتخاب کنید یا پرونده را تغییر دهید.", "dueDateLabel": "موعد تحویل", "dueDateOptional": "اختیاری", "dueDateLockedCompleted": "پس از تکمیل همه وظایف، موعد قابل تغییر نیست.", @@ -1286,7 +1289,7 @@ "billing": { "title": "صورتحساب", "feeSchedules": "جدول‌های تعرفه", - "staffCommissions": "کمیسیون کارکنان", + "staffCommissions": "کمیسیون/حقوق", "transactions": "تراکنش‌ها", "addTransaction": "افزودن تراکنش", "newFeeSchedule": "جدول تعرفه جدید", @@ -1296,6 +1299,10 @@ "transactionHistory": "تاریخچه تراکنش‌ها", "feeScheduleHistory": "تاریخچه جدول‌های تعرفه", "commissionHistory": "تاریخچه کمیسیون‌ها", + "updateStaffSalary": "به‌روزرسانی حقوق کارکنان", + "staffSalarySection": "حقوق کارکنان", + "salaryUpdated": "به‌روزرسانی", + "noSalaryStaff": "کارکنانی برای حقوق وجود ندارد.", "startDate": "تاریخ شروع", "startDateRequired": "تاریخ شروع این جدول را انتخاب کنید.", "sheetName": "نام", @@ -1333,6 +1340,7 @@ "noPayments": "هنوز تراکنشی نیست.", "searchPayments": "جستجوی تراکنش‌ها", "filterByParty": "فیلتر بر اساس طرف", + "clearPartyFilter": "پاک کردن طرف انتخاب‌شده", "typeFilterAll": "همه انواع", "dateFrom": "از", "dateTo": "تا", @@ -1374,7 +1382,52 @@ "time": "زمان", "attachments": "پیوست‌ها", "cancel": "انصراف", - "walkInPatient": "بدون نوبت" + "walkInPatient": "بدون نوبت", + "hideUnpricedTypes": "پنهان کردن انواع پروتز بدون قیمت", + "hideUnpricedTypesClinicInfo": "تا زمانی که این جدول تعرفه فعال است، انواع پروتز بدون قیمت در چارت درمان کلینیک نمایش داده نمی‌شوند.", + "hideUnpricedTypesLabInfo": "انواع پروتز بدون قیمت در چارت پرونده این لابراتوار پنهان می‌شوند. همچنین تا زمانی که این جدول فعال است، کلینیک‌های متصل نمی‌توانند پرونده‌ای شامل این خدمات ارسال کنند.", + "debitCreditReport": "گزارش بدهکار/بستانکار", + "debit": "بدهکار", + "credit": "بستانکار", + "reportSource": "منبع", + "reference": "مرجع", + "reportEmpty": "در این بازه هیچ ردیف بدهکار یا بستانکاری وجود ندارد.", + "reportSourceTreatment": "درمان تأییدشده", + "reportSourceLabCase": "هزینه پرونده", + "reportSourceReceivedCase": "پرونده دریافتی", + "reportSourceGeneratedCase": "پرونده ایجادشده", + "reportSourceOutsource": "پرونده برون‌سپاری", + "caseOriginReceived": "دریافتی", + "caseOriginGenerated": "ایجادشده", + "caseOriginOutsourced": "از لابراتوار", + "reportSourceCommission": "کمیسیون ماهانه", + "reportSourceSalary": "حقوق ماهانه", + "reportSourceCashReceipt": "دریافت نقدی", + "reportSourceCashPayment": "پرداخت نقدی", + "reportDebitTotal": "جمع بدهکار: {amount}", + "reportCreditTotal": "جمع بستانکار: {amount}", + "reportNet": "خالص: {amount}", + "errorLoadReport": "بارگذاری گزارش بدهکار/بستانکار ناموفق بود.", + "fixedMonthlySalary": "حقوق ثابت ماهانه", + "saveSalary": "ذخیره حقوق", + "salarySaved": "حقوق ماهانه ذخیره شد.", + "errorLoadSalary": "بارگذاری حقوق ماهانه ناموفق بود.", + "errorSaveSalary": "ذخیره حقوق ماهانه ناموفق بود.", + "obligationAmountRequired": "نیازمند مبلغ", + "caseObligationAmount": "هزینه پرونده", + "setObligationAmount": "تعیین مبلغ", + "saveObligationAmount": "ذخیره مبلغ", + "obligationAmountSaved": "هزینه پرونده برای هر دو سازمان ذخیره شد.", + "errorSaveObligationAmount": "ذخیره هزینه پرونده ناموفق بود.", + "actions": "عملیات", + "balanceTotal": "مانده", + "paymentAccepted": "تأییدشده", + "editTransaction": "ویرایش تراکنش", + "transactionUpdated": "تراکنش به‌روزرسانی شد.", + "errorUpdateTransaction": "به‌روزرسانی تراکنش ناموفق بود.", + "commissionSubtotal": "کمیسیون", + "fixedSalarySubtotal": "حقوق ثابت", + "grossCompensation": "جمع ناخالص دریافتی" }, "localDb": { "browse": "مرور", @@ -1603,9 +1656,13 @@ "BILLING_TRANSACTION_TYPE_INVALID": "دریافت یا پرداخت را انتخاب کنید.", "BILLING_PAYMENT_NOT_FOUND": "این پرداخت پیدا نشد.", "BILLING_PAYMENT_ACK_INVALID": "این پرداخت دیگر قابل تأیید نیست.", + "BILLING_PAYMENT_NOT_EDITABLE": "فقط سازمان ثبت‌کننده این پرداخت می‌تواند آن را ویرایش کند.", + "BILLING_TRANSACTION_CHANGED": "این تراکنش پس از باز شدن تغییر کرده است. صفحه را تازه‌سازی و دوباره تلاش کنید.", "BILLING_CURRENCY_REQUIRED": "ارز این سازمان را انتخاب کنید.", "BILLING_CURRENCY_INVALID": "تومان، دلار یا یورو را انتخاب کنید.", "BILLING_STAFF_INVALID": "یک عضو کارکنان برای این پرداخت انتخاب کنید.", - "BILLING_PARTY_INVALID": "طرف معتبری برای این فیلتر انتخاب کنید." + "BILLING_PARTY_INVALID": "طرف معتبری برای این فیلتر انتخاب کنید.", + "BILLING_PROSTHESIS_NOT_PROVIDED": "لابراتوار انتخاب‌شده یک یا چند نوع پروتز این پرونده را ارائه نمی‌دهد.", + "BILLING_OBLIGATION_NOT_EDITABLE": "فقط لابراتوار مقصد می‌تواند هزینه این پرونده را تعیین کند." } } diff --git a/frontend/messages/nl.json b/frontend/messages/nl.json index 519c39f..eaabe97 100644 --- a/frontend/messages/nl.json +++ b/frontend/messages/nl.json @@ -558,6 +558,7 @@ "sendToExocadCloseHint": "Sluit Exocad voordat u verstuurt. Open het daarna opnieuw om de casus te zien.", "sendCaseTitle": "Stappen uitbesteden", "outsourcePrice": "Uitbestedingsprijs", + "outsourcePricePending": "Deze uitbesteding bevat werk zonder tarief. Verzenden is toegestaan, maar het bestemmingslab moet het definitieve bedrag in Facturatie instellen.", "sendCaseSelectAll": "Alles selecteren", "sendCaseLab": "Lab", "sendCaseLabsLoading": "Labs laden...", @@ -889,6 +890,8 @@ "selectLabPlaceholder": "Kies een gekoppeld lab…", "sendToLab": "Versturen naar lab", "labFeePreview": "Labtarief", + "labFeeNeedsBillingAmount": "Deze case bevat diensten zonder labtarief. Verzenden is toegestaan, maar het bestemmingslab moet het definitieve bedrag in Facturatie instellen.", + "labDoesNotProvideTypes": "Dit lab levert de volgende prothesediensten niet: {types}. Kies een ander lab of wijzig de case.", "dueDateLabel": "Vervaldatum", "dueDateOptional": "optioneel", "dueDateLockedCompleted": "Vervaldatum kan niet worden gewijzigd nadat alle taken zijn voltooid.", @@ -1285,7 +1288,7 @@ "billing": { "title": "Facturatie", "feeSchedules": "Tariefschema's", - "staffCommissions": "Personeelscommissies", + "staffCommissions": "Commissies/Salaris", "transactions": "Transacties", "addTransaction": "Transactie toevoegen", "newFeeSchedule": "Nieuw tariefschema", @@ -1295,6 +1298,10 @@ "transactionHistory": "Transactiegeschiedenis", "feeScheduleHistory": "Tariefschemageschiedenis", "commissionHistory": "Commissiegeschiedenis", + "updateStaffSalary": "Personeelssalaris bijwerken", + "staffSalarySection": "Personeelssalaris", + "salaryUpdated": "Bijgewerkt", + "noSalaryStaff": "Er is geen personeel om te betalen.", "startDate": "Startdatum", "startDateRequired": "Kies de datum waarop dit schema ingaat.", "sheetName": "Naam", @@ -1332,6 +1339,7 @@ "noPayments": "Nog geen transacties.", "searchPayments": "Transacties zoeken", "filterByParty": "Filter op partij", + "clearPartyFilter": "Geselecteerde partij wissen", "typeFilterAll": "Alle types", "dateFrom": "Van", "dateTo": "Tot", @@ -1373,7 +1381,52 @@ "time": "Tijd", "attachments": "Koppelingen", "cancel": "Annuleren", - "walkInPatient": "Walk-in" + "walkInPatient": "Walk-in", + "hideUnpricedTypes": "Prothesetypen zonder prijs verbergen", + "hideUnpricedTypesClinicInfo": "Prothesetypen zonder prijs worden in de behandelkaart van de kliniek verborgen zolang dit tariefschema actief is.", + "hideUnpricedTypesLabInfo": "Prothesetypen zonder prijs worden in de casekaart van dit lab verborgen. Gekoppelde klinieken kunnen ook geen cases met deze diensten versturen zolang dit schema actief is.", + "debitCreditReport": "Debet-/creditrapport", + "debit": "Debet", + "credit": "Credit", + "reportSource": "Bron", + "reference": "Referentie", + "reportEmpty": "Geen debet- of creditregels in deze periode.", + "reportSourceTreatment": "Goedgekeurde behandeling", + "reportSourceLabCase": "Casetarief", + "reportSourceReceivedCase": "Ontvangen case", + "reportSourceGeneratedCase": "Gegenereerde case", + "reportSourceOutsource": "Uitbestede case", + "caseOriginReceived": "Ontvangen", + "caseOriginGenerated": "Gegenereerd", + "caseOriginOutsourced": "Van lab", + "reportSourceCommission": "Maandelijkse commissies", + "reportSourceSalary": "Maandsalaris", + "reportSourceCashReceipt": "Contante ontvangst", + "reportSourceCashPayment": "Contante betaling", + "reportDebitTotal": "Totaal debet: {amount}", + "reportCreditTotal": "Totaal credit: {amount}", + "reportNet": "Netto: {amount}", + "errorLoadReport": "Het debet-/creditrapport kon niet worden geladen.", + "fixedMonthlySalary": "Vast maandsalaris", + "saveSalary": "Salaris opslaan", + "salarySaved": "Maandsalaris opgeslagen.", + "errorLoadSalary": "Het maandsalaris kon niet worden geladen.", + "errorSaveSalary": "Het maandsalaris kon niet worden opgeslagen.", + "obligationAmountRequired": "Bedrag vereist", + "caseObligationAmount": "Casetarief", + "setObligationAmount": "Bedrag instellen", + "saveObligationAmount": "Bedrag opslaan", + "obligationAmountSaved": "Het casetarief is voor beide organisaties opgeslagen.", + "errorSaveObligationAmount": "Het casetarief kon niet worden opgeslagen.", + "actions": "Acties", + "balanceTotal": "Saldo", + "paymentAccepted": "Geaccepteerd", + "editTransaction": "Transactie bewerken", + "transactionUpdated": "Transactie bijgewerkt.", + "errorUpdateTransaction": "De transactie kon niet worden bijgewerkt.", + "commissionSubtotal": "Commissie", + "fixedSalarySubtotal": "Vast salaris", + "grossCompensation": "Brutovergoeding" }, "localDb": { "browse": "Bladeren", @@ -1602,9 +1655,13 @@ "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_NOT_EDITABLE": "Alleen de organisatie die deze betaling heeft geregistreerd kan deze bewerken.", + "BILLING_TRANSACTION_CHANGED": "Deze transactie is gewijzigd sinds u deze opende. Vernieuw en probeer opnieuw.", "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." + "BILLING_PARTY_INVALID": "Kies een geldige partij voor dit filter.", + "BILLING_PROSTHESIS_NOT_PROVIDED": "Het geselecteerde lab levert een of meer prothesetypen in deze case niet.", + "BILLING_OBLIGATION_NOT_EDITABLE": "Alleen het bestemmingslab kan dit casetarief instellen." } } diff --git a/frontend/src/components/billing/staffCompensation.spec.ts b/frontend/src/components/billing/staffCompensation.spec.ts new file mode 100644 index 0000000..7b97c5c --- /dev/null +++ b/frontend/src/components/billing/staffCompensation.spec.ts @@ -0,0 +1,48 @@ +import { describe, expect, it } from 'vitest'; +import type { BillingPartyReportRow } from '@/types/billing'; +import { staffCompensationTotals } from './staffCompensation'; + +function row( + sourceType: BillingPartyReportRow['sourceType'], + amount: string | null, + lineKind: BillingPartyReportRow['lineKind'] = 'OBLIGATION', +): BillingPartyReportRow { + return { + id: `${sourceType}:${amount}`, + lineKind, + direction: 'CREDIT', + amount, + signedAmount: amount == null ? null : `-${amount}`, + amountPending: amount == null, + canEditAmount: false, + occurredAt: '2026-11-01T00:00:00.000Z', + sourceType, + sourceId: 'source', + reference: '', + note: null, + acknowledgement: 'none', + countsInTotals: amount != null, + }; +} + +describe('staffCompensationTotals', () => { + it('adds persisted commission and fixed salary obligations into gross compensation', () => { + expect( + staffCompensationTotals([ + row('STAFF_COMMISSION_MONTH', '125.50'), + row('STAFF_COMMISSION_MONTH', '74.50'), + row('STAFF_SALARY_MONTH', '1000.00'), + ]), + ).toEqual({ commission: 200, fixedSalary: 1000, gross: 1200 }); + }); + + it('excludes cash, pending amounts, and unrelated obligations', () => { + expect( + staffCompensationTotals([ + row('CASH_PAYMENT', '300.00', 'CASH'), + row('STAFF_SALARY_MONTH', null), + row('LAB_CASE', '900.00'), + ]), + ).toEqual({ commission: 0, fixedSalary: 0, gross: 0 }); + }); +}); diff --git a/frontend/src/components/billing/staffCompensation.ts b/frontend/src/components/billing/staffCompensation.ts new file mode 100644 index 0000000..a283718 --- /dev/null +++ b/frontend/src/components/billing/staffCompensation.ts @@ -0,0 +1,34 @@ +import type { BillingPartyReportRow } from '@/types/billing'; + +export type StaffCompensationTotals = { + commission: number; + fixedSalary: number; + gross: number; +}; + +/** Gross compensation is derived only from persisted obligation rows, never cash. */ +export function staffCompensationTotals( + rows: readonly BillingPartyReportRow[], +): StaffCompensationTotals { + const commission = sumSource(rows, 'STAFF_COMMISSION_MONTH'); + const fixedSalary = sumSource(rows, 'STAFF_SALARY_MONTH'); + return { + commission, + fixedSalary, + gross: commission + fixedSalary, + }; +} + +function sumSource( + rows: readonly BillingPartyReportRow[], + sourceType: 'STAFF_COMMISSION_MONTH' | 'STAFF_SALARY_MONTH', +): number { + return rows + .filter( + (row) => + row.lineKind === 'OBLIGATION' && + row.sourceType === sourceType && + row.amount != null, + ) + .reduce((sum, row) => sum + Number(row.amount), 0); +} diff --git a/frontend/src/components/ui/billing/BillingListToolbar.tsx b/frontend/src/components/ui/billing/BillingListToolbar.tsx index 9c88275..a31eb7e 100644 --- a/frontend/src/components/ui/billing/BillingListToolbar.tsx +++ b/frontend/src/components/ui/billing/BillingListToolbar.tsx @@ -19,6 +19,8 @@ type Props = { addLabel: string; onAdd: () => void; canEdit: boolean; + secondaryAddLabel?: string; + onSecondaryAdd?: () => void; /** Optional control between search and dates (e.g. transaction type filter). */ middle?: ReactNode; /** Replaces the default search input (same flex-1 slot). */ @@ -37,6 +39,8 @@ export function BillingListToolbar({ addLabel, onAdd, canEdit, + secondaryAddLabel, + onSecondaryAdd, middle, searchSlot, }: Props) { @@ -64,6 +68,16 @@ export function BillingListToolbar({ + {canEdit && secondaryAddLabel && onSecondaryAdd ? ( + + ) : null} {canEdit ? ( + ) : null} {open && sections.some((section) => section.items.length > 0) ? (
    {sections.map((section) => diff --git a/frontend/src/components/ui/billing/BillingPaymentsPanel.tsx b/frontend/src/components/ui/billing/BillingPaymentsPanel.tsx index 473ea0d..6f0c132 100644 --- a/frontend/src/components/ui/billing/BillingPaymentsPanel.tsx +++ b/frontend/src/components/ui/billing/BillingPaymentsPanel.tsx @@ -2,7 +2,7 @@ import { useCallback, useEffect, useMemo, useState } from 'react'; import { useTranslations } from 'next-intl'; -import { Check, Paperclip, Search, X } from 'lucide-react'; +import { Check, Paperclip, Pencil, 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'; @@ -20,6 +20,10 @@ import { partySectionsFromSearch, type BillingPartySectionKey, } from '@/components/ui/billing/BillingPartyCombobox'; +import { + BillingTransactionEditor, + type EditableCashTransaction, +} from '@/components/ui/billing/BillingTransactionEditor'; import { TableIconButton } from '@/components/ui/shared/TableIconButton'; import { FORM_SELECT_TALL_CLASS } from '@/components/shared/formSelectStyles'; import { moneyFieldLabel } from '@/components/billing/moneyFieldLabel'; @@ -30,12 +34,15 @@ import { useAppFormatters } from '@/lib/hooks/useAppFormatters'; import { useBillingCurrency } from '@/lib/hooks/useBillingCurrency'; import { parseAppMoney } from '@/lib/i18n/format'; import { stripTrailingDecimalZeros } from '@/lib/i18n/moneyInputFormat'; +import { staffCompensationTotals } from '@/components/billing/staffCompensation'; import type { AllocationCaseHit, AllocationTreatmentHit, BillingCurrency, BillingLedgerRow, BillingPartyKind, + BillingPartyReport, + BillingPartyReportRow, CashTransactionType, } from '@/types/billing'; @@ -56,6 +63,38 @@ type Props = { initialTo?: string; }; +const SOURCE_LABEL_KEY: Record = { + TREATMENT_APPROVE: 'reportSourceTreatment', + LAB_CASE: 'reportSourceLabCase', + OUTSOURCE_CASE: 'reportSourceOutsource', + STAFF_COMMISSION_MONTH: 'reportSourceCommission', + STAFF_SALARY_MONTH: 'reportSourceSalary', + CASH_RECEIPT: 'reportSourceCashReceipt', + CASH_PAYMENT: 'reportSourceCashPayment', +}; + +function reportSourceKey(row: BillingPartyReportRow): string { + if (row.caseOrigin === 'CLINIC_DISPATCH') return 'reportSourceReceivedCase'; + if (row.caseOrigin === 'LAB_INTERNAL') return 'reportSourceGeneratedCase'; + if (row.caseOrigin === 'LAB_OUTSOURCE' || row.sourceType === 'OUTSOURCE_CASE') { + return 'reportSourceOutsource'; + } + return SOURCE_LABEL_KEY[row.sourceType]; +} + +function caseOriginLabelKey( + origin: BillingPartyReportRow['caseOrigin'], +): + | 'caseOriginReceived' + | 'caseOriginGenerated' + | 'caseOriginOutsourced' + | null { + if (origin === 'CLINIC_DISPATCH') return 'caseOriginReceived'; + if (origin === 'LAB_INTERNAL') return 'caseOriginGenerated'; + if (origin === 'LAB_OUTSOURCE') return 'caseOriginOutsourced'; + return null; +} + function sectionToPartyKind(section: BillingPartySectionKey): BillingPartyKind { if (section === 'patients') return 'patient'; if (section === 'staff') return 'staff'; @@ -89,8 +128,19 @@ export function BillingPaymentsPanel({ const [from, setFrom] = useState(initialFrom ?? ''); const [to, setTo] = useState(initialTo ?? ''); const [rows, setRows] = useState([]); - const [net, setNet] = useState(null); + const [report, setReport] = useState(null); const [formOpen, setFormOpen] = useState(false); + const [editingCash, setEditingCash] = useState( + null, + ); + const [editingCashParty, setEditingCashParty] = useState<{ + kind: BillingPartyKind; + id: string; + } | null>(null); + const [editingObligation, setEditingObligation] = + useState(null); + const [obligationAmount, setObligationAmount] = useState(''); + const [obligationSaving, setObligationSaving] = useState(false); const [txnType, setTxnType] = useState('RECEIPT'); const [amount, setAmount] = useState(''); @@ -121,7 +171,10 @@ export function BillingPaymentsPanel({ const staffSelected = selectedParty?.section === 'staff'; const orgSelected = selectedParty?.section === 'clinics' || selectedParty?.section === 'labs'; - const canAttach = patientSelected || orgSelected; + const clinicLabPair = + (isClinic && selectedParty?.section === 'labs') || + (!isClinic && selectedParty?.section === 'clinics'); + const canAttach = patientSelected || clinicLabPair; const showCurrencyPicker = !currencySettings.currencyLocked; const filters = useMemo( @@ -137,10 +190,21 @@ export function BillingPaymentsPanel({ const load = useCallback(async () => { setLoading(true); + setReport(null); try { - const res = await billingApi.listTransactions(filters); + const [res, report] = await Promise.all([ + billingApi.listTransactions(filters), + filters.partyKind && filters.partyId + ? billingApi.getPartyReport({ + partyKind: filters.partyKind, + partyId: filters.partyId, + from: filters.from, + to: filters.to, + }) + : Promise.resolve(null), + ]); setRows(res.data); - setNet(res.net); + setReport(report); } catch (error: unknown) { toast.showError(getUserFacingError(error, tErrors, t('errorLoadPayments'))); } finally { @@ -148,6 +212,13 @@ export function BillingPaymentsPanel({ } }, [filters, t, tErrors, toast]); + useEffect(() => { + setEditingCash(null); + setEditingCashParty(null); + setEditingObligation(null); + setObligationAmount(''); + }, [filterParty]); + useEffect(() => { const handle = window.setTimeout(() => { void load(); @@ -157,6 +228,7 @@ export function BillingPaymentsPanel({ useEffect(() => { if (!formOpen) return; + let active = true; const handle = window.setTimeout(() => { void (async () => { try { @@ -164,24 +236,30 @@ export function BillingPaymentsPanel({ q: partyName.trim() || undefined, txnType, }); - setPartySections( - partySectionsFromSearch(res.data, { - patients: t('partySectionPatients'), - staff: t('partySectionStaff'), - clinics: t('partySectionClinics'), - labs: t('partySectionLabs'), - walkIn: t('walkInPatient'), - }), - ); + if (active) { + setPartySections( + partySectionsFromSearch(res.data, { + patients: t('partySectionPatients'), + staff: t('partySectionStaff'), + clinics: t('partySectionClinics'), + labs: t('partySectionLabs'), + walkIn: t('walkInPatient'), + }), + ); + } } catch { - setPartySections([]); + if (active) setPartySections([]); } })(); }, 250); - return () => window.clearTimeout(handle); + return () => { + active = false; + window.clearTimeout(handle); + }; }, [formOpen, partyName, t, txnType]); useEffect(() => { + let active = true; const handle = window.setTimeout(() => { void (async () => { try { @@ -219,13 +297,16 @@ export function BillingPaymentsPanel({ if (!ids.has(item.id)) existing.items.push(item); } } - setFilterSections([...merged.values()]); + if (active) setFilterSections([...merged.values()]); } catch { - setFilterSections([]); + if (active) setFilterSections([]); } })(); }, 250); - return () => window.clearTimeout(handle); + return () => { + active = false; + window.clearTimeout(handle); + }; }, [query, t]); useEffect(() => { @@ -303,10 +384,14 @@ export function BillingPaymentsPanel({ return t('selectPartyPayment'); } - async function acknowledge(id: string, decision: 'ACCEPT' | 'DECLINE') { + async function acknowledge( + id: string, + updatedAt: string, + decision: 'ACCEPT' | 'DECLINE', + ) { setAckBusyId(id); try { - await billingApi.acknowledgePartnerPayment(id, decision); + await billingApi.acknowledgePartnerPayment(id, decision, updatedAt); await load(); } catch (error: unknown) { toast.showError(getUserFacingError(error, tErrors, t('errorSavePayment'))); @@ -315,22 +400,67 @@ export function BillingPaymentsPanel({ } } + function startCashEdit( + row: { + id: string; + kind: 'patient' | 'partner' | 'staff'; + amount: string; + note: string | null; + updatedAt: string; + canAllocate: boolean; + allocations: Array<{ targetId: string; amount: string; label: string }>; + }, + party: { kind: BillingPartyKind; id: string } | null, + ) { + setEditingObligation(null); + setEditingCash(row); + setEditingCashParty(party); + } + + async function saveObligationAmount() { + if (!editingObligation) return; + const parsed = parseAppMoney(obligationAmount); + if (!parsed || Number(parsed) <= 0) { + toast.showError(t('invalidAmount')); + return; + } + setObligationSaving(true); + try { + await billingApi.updateObligationAmount(editingObligation.id, parsed); + setEditingObligation(null); + setObligationAmount(''); + toast.showSuccess(t('obligationAmountSaved')); + await load(); + } catch (error: unknown) { + toast.showError( + getUserFacingError(error, tErrors, t('errorSaveObligationAmount')), + ); + } finally { + setObligationSaving(false); + } + } + 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 = visibleRows.length === 0; - const netNumber = net == null ? null : Number(net); + const selectedMode = Boolean(filterParty); + const empty = selectedMode + ? (report?.data.length ?? 0) === 0 + : visibleRows.length === 0; + const netNumber = report ? Number(report.totals.net) : null; const netTone = netNumber == null ? '' - : netNumber > 0 + : netNumber >= 0 ? 'text-emerald-700 dark:text-emerald-400' - : netNumber < 0 - ? 'text-amber-800 dark:text-amber-300' - : 'text-text-secondary'; + : 'text-red-700 dark:text-red-400'; + const compensation = useMemo( + () => staffCompensationTotals(report?.data ?? []), + [report?.data], + ); async function submitCreate() { const parsedAmount = parseAppMoney(amount); @@ -359,7 +489,7 @@ export function BillingPaymentsPanel({ userId: staffSelected ? selectedParty!.id : undefined, externalPartyName: localParty ? typedParty : undefined, allocations: - localParty || staffSelected + localParty || staffSelected || !canAttach ? [] : allocations .map((row) => { @@ -418,6 +548,11 @@ export function BillingPaymentsPanel({ sections={filterSections} placeholder={t('searchPayments')} icon={} + clearLabel={t('clearPartyFilter')} + onClear={() => { + setQuery(''); + setFilterParty(null); + }} onChange={({ name, id, section }) => { setQuery(name); if (id && section) { @@ -429,16 +564,18 @@ export function BillingPaymentsPanel({ /> } middle={ - + !filterParty ? ( + + ) : null } /> @@ -617,120 +754,420 @@ export function BillingPaymentsPanel({ ) : null} + {filterParty && sectionToPartyKind(filterParty.section) === 'staff' ? ( + +
    +
    +

    {t('commissionSubtotal')}

    +

    + {formatMoney(compensation.commission)} +

    +
    +
    +

    {t('fixedSalarySubtotal')}

    +

    + {formatMoney(compensation.fixedSalary)} +

    +
    +
    +

    {t('grossCompensation')}

    +

    + {formatMoney(compensation.gross)} +

    +
    +
    +
    + ) : null} + + {editingCash ? ( + { + setEditingCash(null); + setEditingCashParty(null); + }} + onSaved={async () => { + setEditingCash(null); + setEditingCashParty(null); + await load(); + }} + /> + ) : null} + + {editingObligation ? ( + +
    + +
    + + +
    + ) : null} +

    {t('transactionHistory')}

    {loading ? (

    {tCommon('loading')}

    + ) : selectedMode && report && filterParty ? ( + + + + + + + + } + body={ + report.data.length > 0 ? ( + report.data.map((row) => ( + + + + + + + + )) + ) : ( + + + + ) + } + footer={ + + + + + } + /> ) : empty ? (

    {t('noPayments')}

    ) : ( - <> -
    {t('time')} + {t('reportSource')} + + {t('reference')} + {amountLabel} + {t('actions')} +
    + {formatDateTime(row.occurredAt)} + +
    + + {t(reportSourceKey(row) as 'reportSourceTreatment')} + + {caseOriginLabelKey(row.caseOrigin) ? ( + + {t(caseOriginLabelKey(row.caseOrigin)!)} + + ) : null} + {row.acknowledgement === 'pending' ? ( + + {t('paymentPending')} + + ) : null} + {row.acknowledgement === 'accepted' ? ( + + {t('paymentAccepted')} + + ) : null} + {row.acknowledgement === 'rejected' ? ( + + {t('paymentDeclined')} + + ) : null} + {row.amountPending ? ( + + {t('obligationAmountRequired')} + + ) : null} +
    +
    +
    +

    + {row.reference || '—'} +

    + {row.note ? ( +

    + {row.note} +

    + ) : null} +
    +
    +
    + + {row.amount == null ? '—' : formatMoney(row.amount)} + + + {row.direction === 'DEBIT' + ? t('debit') + : t('credit')} + +
    +
    +
    + {canEdit && row.canEditCash && row.paymentKind && row.updatedAt ? ( + + startCashEdit( + { + id: row.sourceId, + kind: row.paymentKind!, + amount: row.amount ?? '0', + note: row.note, + updatedAt: row.updatedAt!, + canAllocate: Boolean(row.canAllocate), + allocations: row.allocations ?? [], + }, + { + kind: sectionToPartyKind(filterParty.section), + id: filterParty.id, + }, + ) + } + > + + + ) : null} + {canEdit && row.canEditAmount ? ( + { + setEditingCash(null); + setEditingCashParty(null); + setEditingObligation(row); + setObligationAmount(row.amount ?? ''); + }} + > + + + ) : null} + {canEdit && row.canAcknowledge && row.updatedAt ? ( + <> + + void acknowledge( + row.sourceId, + row.updatedAt!, + 'ACCEPT', + ) + } + > + + + + void acknowledge( + row.sourceId, + row.updatedAt!, + 'DECLINE', + ) + } + > + + + + ) : null} +
    +
    + {t('reportEmpty')} +
    + {t('balanceTotal')} + + {formatMoney(report.totals.net)} + +
    - - - - - - - } - body={visibleRows.map((row) => ( - + + + + + + + + } + body={visibleRows.map((row) => ( + + - - - - + + + + - ))} - /> - {filterParty && net != null ? ( -

    - {t('ledgerNet', { - amount: formatMoney(net), - currency: currencySettings.currency - ? currencyName(currencySettings.currency) - : '', - })} - {netNumber != null && netNumber > 0 - ? ` · ${t('ledgerNetCredit')}` - : netNumber != null && netNumber < 0 - ? ` · ${t('ledgerNetDebt')}` - : ''} -

    - ) : null} - + : row.attachments.join(', ') + } + > + {row.attachments.length === 0 + ? t('unallocated') + : row.attachments.join(', ')} + + + + ))} + /> )} diff --git a/frontend/src/components/ui/billing/BillingSheetEditor.tsx b/frontend/src/components/ui/billing/BillingSheetEditor.tsx index c5b8199..1ba8a9a 100644 --- a/frontend/src/components/ui/billing/BillingSheetEditor.tsx +++ b/frontend/src/components/ui/billing/BillingSheetEditor.tsx @@ -8,6 +8,7 @@ import { Card } from '@/components/ui/shared/Card'; import { Input } from '@/components/ui/shared/Input'; import { AppDateInput } from '@/components/ui/shared/AppDateInput'; import { AppMoneyInput } from '@/components/ui/shared/AppMoneyInput'; +import { Checkbox } from '@/components/ui/shared/Checkbox'; import { OutlineFieldLabel } from '@/components/ui/shared/OutlineFieldLabel'; import { TreatmentTypeBadge } from '@/components/ui/treatment/TreatmentTypeBadge'; import { startOfLocalDay, toDateInputValue } from '@/components/appointments/appointmentTime'; @@ -73,6 +74,7 @@ export function BillingSheetEditor({ (code: BillingCurrency) => tCommon(`currencyName.${code}` as 'currencyName.TOMAN'), ); const commission = isCommissionSheetKind(kind); + const priceSheet = kind === 'CLINIC_PRICE' || kind === 'LAB_PRICE'; const toClinics = sheetTargetsClinics(kind); const groups = useMemo( @@ -96,6 +98,9 @@ export function BillingSheetEditor({ const [values, setValues] = useState(seeded); const [formError, setFormError] = useState(''); const [targetsOpen, setTargetsOpen] = useState(false); + const [hideUnpricedTypes, setHideUnpricedTypes] = useState( + sheet?.hideUnpricedTypes ?? false, + ); const [targetQuery, setTargetQuery] = useState(''); const [activeGroupKey, setActiveGroupKey] = useState(groups[0]?.key ?? ''); @@ -156,6 +161,7 @@ export function BillingSheetEditor({ name: name.trim() || undefined, effectiveOn, lines, + hideUnpricedTypes: priceSheet ? hideUnpricedTypes : false, ...(toClinics ? { targetClinicIds: selectedIds } : { targetUserIds: selectedIds }), }); } @@ -213,6 +219,24 @@ export function BillingSheetEditor({ + {priceSheet ? ( +
    + + {hideUnpricedTypes ? ( +

    + {kind === 'LAB_PRICE' + ? t('hideUnpricedTypesLabInfo') + : t('hideUnpricedTypesClinicInfo')} +

    + ) : null} +
    + ) : null} + {targetsOpen ? (

    {applyToLabel}

    diff --git a/frontend/src/components/ui/billing/BillingSheetsPanel.tsx b/frontend/src/components/ui/billing/BillingSheetsPanel.tsx index 3ffd326..a1e62f4 100644 --- a/frontend/src/components/ui/billing/BillingSheetsPanel.tsx +++ b/frontend/src/components/ui/billing/BillingSheetsPanel.tsx @@ -9,6 +9,7 @@ import { Table, TABLE_HEADER_CELL_CLASS } from '@/components/ui/shared/Table'; import { TableIconButton } from '@/components/ui/shared/TableIconButton'; import { BillingListToolbar } from '@/components/ui/billing/BillingListToolbar'; import { BillingSheetEditor } from '@/components/ui/billing/BillingSheetEditor'; +import { BillingStaffSalaryEditor } from '@/components/ui/billing/BillingStaffSalaryEditor'; import { isCommissionSheetKind } from '@/components/billing/billingSheetKind'; import { billingApi } from '@/lib/api/billing'; import { getUserFacingError } from '@/components/shared/formatApiError'; @@ -21,6 +22,7 @@ import type { BillingSheetCatalog, BillingSheetKind, BillingSheetTargets, + StaffSalarySheet, } from '@/types/billing'; type Props = { @@ -60,25 +62,30 @@ export function BillingSheetsPanel({ const [from, setFrom] = useState(initialFrom); const [to, setTo] = useState(initialTo); const [editorSheet, setEditorSheet] = useState(undefined); + const [salarySheet, setSalarySheet] = useState(null); + const [salaryEditorOpen, setSalaryEditorOpen] = useState(false); const [saving, setSaving] = useState(false); useEffect(() => { let cancelled = false; setEditorSheet(undefined); + setSalaryEditorOpen(false); setQuery(''); setLoading(true); void (async () => { try { - const [sheetRes, catalogRes, targetRes] = await Promise.all([ + const [sheetRes, catalogRes, targetRes, salaryRes] = await Promise.all([ billingApi.listSheets(kind), billingApi.listCatalog(kind), billingApi.listTargets(kind), + commission ? billingApi.getStaffSalarySheet() : Promise.resolve(null), ]); if (cancelled) return; setSheets(sheetRes.data); setCatalog(catalogRes.data); setTargets(targetRes.data); + setSalarySheet(salaryRes?.data ?? null); } catch (error: unknown) { if (cancelled) return; toast.showError(getUserFacingError(error, tErrors, t('errorLoadSheets'))); @@ -90,25 +97,27 @@ export function BillingSheetsPanel({ return () => { cancelled = true; }; - }, [kind, t, tErrors, toast]); + }, [commission, kind, t, tErrors, toast]); const reload = useCallback(async () => { setLoading(true); try { - const [sheetRes, catalogRes, targetRes] = await Promise.all([ + const [sheetRes, catalogRes, targetRes, salaryRes] = await Promise.all([ billingApi.listSheets(kind), billingApi.listCatalog(kind), billingApi.listTargets(kind), + commission ? billingApi.getStaffSalarySheet() : Promise.resolve(null), ]); setSheets(sheetRes.data); setCatalog(catalogRes.data); setTargets(targetRes.data); + setSalarySheet(salaryRes?.data ?? null); } catch (error: unknown) { toast.showError(getUserFacingError(error, tErrors, t('errorLoadSheets'))); } finally { setLoading(false); } - }, [kind, t, tErrors, toast]); + }, [commission, kind, t, tErrors, toast]); const filtered = useMemo(() => { const q = query.trim().toLowerCase(); @@ -127,7 +136,13 @@ export function BillingSheetsPanel({ }); }, [from, query, sheets, to]); + function openSalary() { + setEditorSheet(undefined); + setSalaryEditorOpen(true); + } + function openNew() { + setSalaryEditorOpen(false); setEditorSheet({ id: '', organizationId: '', @@ -138,6 +153,7 @@ export function BillingSheetsPanel({ targetClinicIds: [], targetUsers: [], targetClinics: [], + hideUnpricedTypes: false, lines: [], createdAt: '', updatedAt: '', @@ -164,6 +180,22 @@ export function BillingSheetsPanel({ } } + async function handleSaveSalary( + lines: Array<{ userId: string; fixedMonthlySalary: string }>, + ) { + setSaving(true); + try { + const response = await billingApi.saveStaffSalarySheet(lines); + setSalarySheet(response.data); + toast.showSuccess(t('salarySaved')); + setSalaryEditorOpen(false); + } catch (error: unknown) { + toast.showError(getUserFacingError(error, tErrors, t('errorSaveSalary'))); + } finally { + setSaving(false); + } + } + async function handleDelete(sheet: BillingSheet) { if ( !(await confirm({ @@ -198,8 +230,53 @@ export function BillingSheetsPanel({ addLabel={commission ? t('newCommissionSchedule') : t('newFeeSchedule')} onAdd={openNew} canEdit={canEdit} + secondaryAddLabel={commission ? t('updateStaffSalary') : undefined} + onSecondaryAdd={commission ? openSalary : undefined} /> + {salaryEditorOpen && salarySheet ? ( + setSalaryEditorOpen(false)} + onSave={handleSaveSalary} + /> + ) : null} + + {commission && salarySheet?.updatedAt && !salaryEditorOpen ? ( +
    +

    {t('staffSalarySection')}

    +
    {t('party')}{t('type')}{amountLabel}{t('time')}{t('attachments')}
    {t('party')}{t('type')}{amountLabel}{t('time')}{t('attachments')} + {t('actions')} +
    - - {row.partyIsWalkIn - ? `${row.partyName} · ${t('walkInPatient')}` - : row.partyName} - -
    - - {row.type === 'RECEIPT' ? t('receipt') : t('payment')} - - {row.acknowledgement === 'pending' && row.recordedByViewer ? ( - {t('paymentPending')} - ) : null} - {row.acknowledgement === 'rejected' && row.recordedByViewer ? ( - {t('paymentDeclined')} - ) : null} - {canEdit && row.canAcknowledge ? ( - <> - void acknowledge(row.id, 'ACCEPT')} - > - - - void acknowledge(row.id, 'DECLINE')} - > - - - - ) : null} -
    -
    - {formatMoney(row.amount)} - - {formatDateTime(row.paidAt)} - - {row.attachments.length === 0 + {row.partyIsWalkIn + ? `${row.partyName} · ${t('walkInPatient')}` + : row.partyName} + +
    + + {row.type === 'RECEIPT' ? t('receipt') : t('payment')} + + {row.acknowledgement === 'pending' ? ( + {t('paymentPending')} + ) : null} + {row.acknowledgement === 'rejected' ? ( + {t('paymentDeclined')} + ) : null} +
    +
    + {formatMoney(row.amount)} + + {formatDateTime(row.paidAt)} + -
    +
    + {canEdit && row.canEdit ? ( + + startCashEdit( + { + id: row.id, + kind: row.kind, + amount: row.amount, + note: row.note, + updatedAt: row.updatedAt, + canAllocate: row.canAllocate, + allocations: row.allocations, + }, + row.partyId + ? { + kind: + row.kind === 'partner' + ? 'org' + : row.kind, + id: row.partyId, + } + : null, + ) + } + > + + + ) : null} + {canEdit && row.canAcknowledge ? ( + <> + + void acknowledge(row.id, row.updatedAt, 'ACCEPT') + } + > + + + + void acknowledge(row.id, row.updatedAt, 'DECLINE') + } + > + + + + ) : null} +
    +
    + + + + + } + body={ + + + + + + } + /> + + ) : null} + {editorSheet !== undefined ? ( void; + onSave: (lines: Array>) => Promise; +}; + +export function BillingStaffSalaryEditor({ + lines, + canEdit, + saving, + onCancel, + onSave, +}: 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 seeded = useMemo(() => { + const values: Record = {}; + for (const line of lines) { + values[line.userId] = stripTrailingDecimalZeros(line.fixedMonthlySalary); + } + return values; + }, [lines]); + const [values, setValues] = useState>(seeded); + const [formError, setFormError] = useState(''); + + async function handleSave() { + setFormError(''); + const next: Array> = []; + for (const line of lines) { + const raw = values[line.userId] ?? '0'; + if (!isBillingAmountInput(raw)) { + setFormError(t('invalidPrice')); + return; + } + next.push({ + userId: line.userId, + fixedMonthlySalary: toBillingAmountString(raw), + }); + } + await onSave(next); + } + + return ( +
    +
    +

    {t('updateStaffSalary')}

    + +
    + + + {lines.length === 0 ? ( +

    {t('noSalaryStaff')}

    + ) : ( +
    + {lines.map((line) => ( +
    + + {line.name} + +
    + + {amountLabel} + +
    + + setValues((prev) => ({ ...prev, [line.userId]: next })) + } + /> +
    +
    +
    + ))} +
    + )} +
    + + {formError ?

    {formError}

    : null} + + {canEdit ? ( +
    + + +
    + ) : null} +
    + ); +} diff --git a/frontend/src/components/ui/billing/BillingTransactionEditor.tsx b/frontend/src/components/ui/billing/BillingTransactionEditor.tsx new file mode 100644 index 0000000..4d88d53 --- /dev/null +++ b/frontend/src/components/ui/billing/BillingTransactionEditor.tsx @@ -0,0 +1,262 @@ +'use client'; + +import { useEffect, useState } from 'react'; +import { useTranslations } from 'next-intl'; +import { AppMoneyInput } from '@/components/ui/shared/AppMoneyInput'; +import { Button } from '@/components/ui/shared/Button'; +import { Card } from '@/components/ui/shared/Card'; +import { Input } from '@/components/ui/shared/Input'; +import { moneyFieldLabel } from '@/components/billing/moneyFieldLabel'; +import { stripTrailingDecimalZeros } from '@/lib/i18n/moneyInputFormat'; +import { parseAppMoney } from '@/lib/i18n/format'; +import { billingApi } from '@/lib/api/billing'; +import { getUserFacingError } from '@/components/shared/formatApiError'; +import { useBillingCurrency } from '@/lib/hooks/useBillingCurrency'; +import { useAppFormatters } from '@/lib/hooks/useAppFormatters'; +import { useToast } from '@/lib/hooks/useToast'; +import type { BillingPartyKind } from '@/types/billing'; + +export type EditableCashTransaction = { + id: string; + kind: 'patient' | 'partner' | 'staff'; + amount: string; + note: string | null; + updatedAt: string; + canAllocate: boolean; + allocations: Array<{ targetId: string; amount: string; label: string }>; +}; + +type Props = { + row: EditableCashTransaction; + party: { kind: BillingPartyKind; id: string } | null; + onCancel: () => void; + onSaved: () => Promise | void; +}; + +type AllocationHit = { id: string; label: string; billed: string | null }; + +export function BillingTransactionEditor({ + row, + party, + onCancel, + onSaved, +}: Props) { + const t = useTranslations('billing'); + const tCommon = useTranslations('common'); + const tErrors = useTranslations('errors'); + const toast = useToast(); + const { formatMoney } = useAppFormatters(); + const { settings } = useBillingCurrency(true); + const [amount, setAmount] = useState(stripTrailingDecimalZeros(row.amount)); + const [note, setNote] = useState(row.note ?? ''); + const [allocations, setAllocations] = useState(row.allocations); + const [allocationQuery, setAllocationQuery] = useState(''); + const [hits, setHits] = useState([]); + const [saving, setSaving] = useState(false); + const canAllocate = + row.canAllocate && + Boolean(party?.id) && + ((row.kind === 'patient' && party?.kind === 'patient') || + (row.kind === 'partner' && party?.kind === 'org')); + const amountLabel = moneyFieldLabel( + t('amount'), + settings.currency, + (code) => tCommon(`currencyName.${code}` as 'currencyName.TOMAN'), + ); + + useEffect(() => { + if (!canAllocate || !party) { + setHits([]); + return; + } + let active = true; + const handle = window.setTimeout(() => { + void (row.kind === 'patient' + ? billingApi.searchTreatments({ + q: allocationQuery.trim() || undefined, + patientId: party.id, + }) + : billingApi.searchCases({ + q: allocationQuery.trim() || undefined, + counterpartOrganizationId: party.id, + }) + ) + .then((response) => { + if (!active) return; + if (row.kind === 'patient') { + setHits( + response.data.map((item) => ({ + id: item.id, + label: 'title' in item ? item.title : item.id, + billed: item.billedAmount, + })), + ); + } else { + setHits( + response.data.map((item) => ({ + id: item.id, + label: + 'caseLabel' in item + ? [item.caseLabel, item.patientName].filter(Boolean).join(' · ') + : item.id, + billed: item.billedAmount, + })), + ); + } + }) + .catch(() => { + if (active) setHits([]); + }); + }, 250); + return () => { + active = false; + window.clearTimeout(handle); + }; + }, [allocationQuery, canAllocate, party, row.kind]); + + function addAllocation(hit: AllocationHit) { + if (allocations.some((item) => item.targetId === hit.id)) return; + setAllocations((current) => [ + ...current, + { + targetId: hit.id, + label: hit.label, + amount: hit.billed ? stripTrailingDecimalZeros(hit.billed) : '', + }, + ]); + } + + async function save() { + const parsedAmount = parseAppMoney(amount); + if (!parsedAmount || Number(parsedAmount) <= 0) { + toast.showError(t('invalidAmount')); + return; + } + const parsedAllocations = allocations.map((allocation) => ({ + targetId: allocation.targetId, + amount: parseAppMoney(allocation.amount), + })); + if (parsedAllocations.some((allocation) => !allocation.amount)) { + toast.showError(t('invalidAmount')); + return; + } + const body = { + amount: parsedAmount, + note: note.trim() || undefined, + expectedUpdatedAt: row.updatedAt, + allocations: parsedAllocations.map((allocation) => ({ + targetId: allocation.targetId, + amount: allocation.amount as string, + })), + }; + + setSaving(true); + try { + if (row.kind === 'patient') { + await billingApi.updatePatientPayment(row.id, body); + } else if (row.kind === 'partner') { + await billingApi.updatePartnerPayment(row.id, body); + } else { + await billingApi.updateStaffPayment(row.id, body); + } + toast.showSuccess(t('transactionUpdated')); + await onSaved(); + } catch (error: unknown) { + toast.showError(getUserFacingError(error, tErrors, t('errorUpdateTransaction'))); + } finally { + setSaving(false); + } + } + + return ( + +

    {t('editTransaction')}

    +
    + + setNote(event.target.value)} + maxLength={500} + /> +
    + + {canAllocate ? ( +
    + setAllocationQuery(event.target.value)} + placeholder={t('searchAllocations')} + /> + {hits.length > 0 ? ( +
      + {hits.map((hit) => ( +
    • + +
    • + ))} +
    + ) : null} + {allocations.map((allocation) => ( +
    + {allocation.label} +
    + + setAllocations((current) => + current.map((item) => + item.targetId === allocation.targetId + ? { ...item, amount: value } + : item, + ), + ) + } + /> +
    + +
    + ))} +
    + ) : null} + +
    + + +
    +
    + ); +} diff --git a/frontend/src/components/ui/lab/CaseCreatePanel.tsx b/frontend/src/components/ui/lab/CaseCreatePanel.tsx index b058dca..b3670ee 100644 --- a/frontend/src/components/ui/lab/CaseCreatePanel.tsx +++ b/frontend/src/components/ui/lab/CaseCreatePanel.tsx @@ -1,6 +1,6 @@ 'use client'; -import { useCallback, useEffect, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useLocale, useTranslations } from 'next-intl'; import { getUserFacingError } from '@/components/shared/formatApiError'; import { @@ -35,6 +35,7 @@ import { toDateInputValue } from '@/components/lab/labCaseDueDateDisplay'; import { buildLabLineFromVoice } from '@/components/lab/voiceLine'; import { caseCommentsApi } from '@/lib/api/case-comments'; import { casesApi } from '@/lib/api/cases'; +import { billingApi } from '@/lib/api/billing'; import { prosthesisCatalogApi } from '@/lib/api/prosthesis-catalog'; import { useCaseSectionCounts } from '@/lib/hooks/useCaseSectionCounts'; import { tabBadgesChangedEventName } from '@/lib/tabBadgeUtils'; @@ -188,6 +189,10 @@ export function CaseCreatePanel({ const [prosthesisOptions, setProsthesisOptions] = useState( prosthesisCatalog ?? [], ); + const [hideUnpricedTypes, setHideUnpricedTypes] = useState(false); + const [pricedProsthesisCodes, setPricedProsthesisCodes] = useState>( + () => new Set(), + ); const [saving, setSaving] = useState(false); const [starting, setStarting] = useState(false); const [deleting, setDeleting] = useState(false); @@ -235,6 +240,41 @@ export function CaseCreatePanel({ void prosthesisCatalogApi.list().then((r) => setProsthesisOptions(r.data)).catch(() => undefined); }, [prosthesisCatalog]); + useEffect(() => { + let cancelled = false; + void billingApi + .getResolvedLines({ + kind: 'LAB_PRICE', + asOf: new Date().toISOString().slice(0, 10), + clinicOrganizationId: partnerClinicOrganizationId || undefined, + }) + .then((response) => { + if (cancelled) return; + setHideUnpricedTypes(response.data.hideUnpricedTypes); + setPricedProsthesisCodes( + new Set( + response.data.lines + .filter((line) => line.catalogKind === 'PROSTHESIS_TYPE' && line.amount > 0) + .map((line) => line.catalogCode), + ), + ); + }) + .catch(() => { + if (!cancelled) { + setHideUnpricedTypes(false); + setPricedProsthesisCodes(new Set()); + } + }); + return () => { + cancelled = true; + }; + }, [partnerClinicOrganizationId]); + + const assignableProsthesisOptions = useMemo(() => { + if (!hideUnpricedTypes) return prosthesisOptions; + return prosthesisOptions.filter((entry) => pricedProsthesisCodes.has(entry.code)); + }, [hideUnpricedTypes, pricedProsthesisCodes, prosthesisOptions]); + const groups = plan.toothSelectionGroups.length > 0 ? plan.toothSelectionGroups @@ -642,6 +682,7 @@ export function CaseCreatePanel({ toothProsthesis={plan.toothProsthesis} detailClientId={plan.clientId} catalog={prosthesisOptions} + pickerCatalog={assignableProsthesisOptions} disabled={disabled} className="w-full min-w-0" onToggleLink={(a, b) => { @@ -735,7 +776,7 @@ export function CaseCreatePanel({ applyVoice(selection, applied)} onDiscard={() => onVoiceResultHandled?.()} /> diff --git a/frontend/src/components/ui/lab/CaseDetailPanel.tsx b/frontend/src/components/ui/lab/CaseDetailPanel.tsx index 072459f..76efd3a 100644 --- a/frontend/src/components/ui/lab/CaseDetailPanel.tsx +++ b/frontend/src/components/ui/lab/CaseDetailPanel.tsx @@ -583,11 +583,11 @@ export function CaseDetailPanel({ {t('importantLabel')} ) : null} - {labCase.billedAmount != null || labCase.calculatedAmount != null ? ( + {labCase.billedAmount != null ? (

    {billedLeadLabel} {' : '} - {formatAppMoney(labCase.billedAmount ?? labCase.calculatedAmount, intlLocale)} + {formatAppMoney(labCase.billedAmount, intlLocale)}

    ) : null} diff --git a/frontend/src/components/ui/lab/CaseSendDialog.tsx b/frontend/src/components/ui/lab/CaseSendDialog.tsx index 61c2763..7af51de 100644 --- a/frontend/src/components/ui/lab/CaseSendDialog.tsx +++ b/frontend/src/components/ui/lab/CaseSendDialog.tsx @@ -10,6 +10,7 @@ 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 { labBlockedBannerClass } from '@/components/treatment/treatmentStatusStyles'; import { billingApi } from '@/lib/api/billing'; import { useAppFormatters } from '@/lib/hooks/useAppFormatters'; import { ProsthesisJobLineLabel } from '@/components/ui/lab/ProsthesisJobLineLabel'; @@ -75,6 +76,7 @@ export function CaseSendDialog({ const tCommon = useTranslations('common'); const { formatMoney } = useAppFormatters(); const [quote, setQuote] = useState(null); + const [quotePending, setQuotePending] = useState(false); const [destinationId, setDestinationId] = useState(''); const [selected, setSelected] = useState>(new Set()); @@ -133,6 +135,7 @@ export function CaseSendDialog({ useEffect(() => { if (!open || !destinationId || !labCase.id || selected.size === 0) { setQuote(null); + setQuotePending(false); return; } let cancelled = false; @@ -143,10 +146,16 @@ export function CaseSendDialog({ taskIds: [...selected], }) .then((res) => { - if (!cancelled) setQuote(res.data.amount); + if (!cancelled) { + setQuote(res.data.amount); + setQuotePending(res.data.amount == null); + } }) .catch(() => { - if (!cancelled) setQuote(null); + if (!cancelled) { + setQuote(null); + setQuotePending(false); + } }); return () => { cancelled = true; @@ -290,6 +299,9 @@ export function CaseSendDialog({ {formatMoney(quote)}

    ) : null} + {destinationId && selected.size > 0 && quotePending ? ( +

    {t('outsourcePricePending')}

    + ) : null}
    {body} + {footer ? ( + + {footer} + + ) : null}
    {t('salaryUpdated')}{tCommon('name')}{tCommon('action')}
    + {formatTableDate(salarySheet.updatedAt)} + {t('staffSalarySection')} +
    + {canEdit ? ( + + + + ) : null} +
    +
    - {footer && ( -
    - {footer} -
    - )} ); } diff --git a/frontend/src/components/ui/treatment/LabCasesDispatchPanel.tsx b/frontend/src/components/ui/treatment/LabCasesDispatchPanel.tsx index d16ce8d..407e4aa 100644 --- a/frontend/src/components/ui/treatment/LabCasesDispatchPanel.tsx +++ b/frontend/src/components/ui/treatment/LabCasesDispatchPanel.tsx @@ -28,6 +28,7 @@ import { } from '@/components/treatment/prosthesisTree'; import { LabCaseToothJobsList } from '@/components/ui/lab/LabCaseProsthesisGroupsList'; import { LabCaseShareQr } from '@/components/ui/lab/LabCaseShareQrDialog'; +import { labBlockedBannerClass } from '@/components/treatment/treatmentStatusStyles'; interface LabCasesDispatchPanelProps { details: TreatmentDetailDraft[]; @@ -109,6 +110,8 @@ export function LabCasesDispatchPanel({ const tErrors = useTranslations('errors'); const { formatMoney } = useAppFormatters(); const [labFee, setLabFee] = useState(null); + const [unsupportedCodes, setUnsupportedCodes] = useState([]); + const [sendBlockedByPriceSheet, setSendBlockedByPriceSheet] = useState(false); const [fetchedCatalog, setFetchedCatalog] = useState([]); const [pendingComment, setPendingComment] = useState(''); const hasTrackerSummary = Boolean(labCaseSummary && labCaseSummary.labCaseId); @@ -150,6 +153,8 @@ export function LabCasesDispatchPanel({ useEffect(() => { if (!quoteLabId) { setLabFee(null); + setUnsupportedCodes([]); + setSendBlockedByPriceSheet(false); return; } const jobs = (activeLabCase?.toothProsthesis ?? []) @@ -159,10 +164,18 @@ export function LabCasesDispatchPanel({ void billingApi .quoteLabPrice({ labOrganizationId: quoteLabId, jobs }) .then((res) => { - if (!cancelled) setLabFee(res.data.amount); + if (!cancelled) { + setLabFee(res.data.amount); + setUnsupportedCodes(res.data.unpricedCodes); + setSendBlockedByPriceSheet(res.data.blocksSend); + } }) .catch(() => { - if (!cancelled) setLabFee(null); + if (!cancelled) { + setLabFee(null); + setUnsupportedCodes([]); + setSendBlockedByPriceSheet(false); + } }); return () => { cancelled = true; @@ -477,6 +490,22 @@ export function LabCasesDispatchPanel({

    ) : null} + {quoteLabId && + unsupportedCodes.length > 0 && + !sendBlockedByPriceSheet ? ( +

    + {t('labFeeNeedsBillingAmount')} +

    + ) : null} + {sendBlockedByPriceSheet ? ( +

    + {t('labDoesNotProvideTypes', { + types: unsupportedCodes + .map((code) => catalog.find((entry) => entry.code === code)?.label ?? code) + .join(', '), + })} +

    + ) : null}