From 1c7c96950edc5697bf33053ec9d6f70945b1ca72 Mon Sep 17 00:00:00 2001 From: Admin Date: Wed, 11 Nov 2026 15:10:18 +0330 Subject: [PATCH 1/7] bugfix: seat overdue warning fixed. --- backend/src/modules/auth/auth.service.ts | 136 ++++------------------- frontend/src/lib/hooks/useAuth.tsx | 8 +- 2 files changed, 26 insertions(+), 118 deletions(-) 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/frontend/src/lib/hooks/useAuth.tsx b/frontend/src/lib/hooks/useAuth.tsx index cdf10d6..1474c72 100644 --- a/frontend/src/lib/hooks/useAuth.tsx +++ b/frontend/src/lib/hooks/useAuth.tsx @@ -258,8 +258,8 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { if (orgs.length === 1) { const org = orgs[0]; - await authApi.selectOrganization(org.id); - setCurrentOrganization(organizationFromSelection(org)); + const selected = await authApi.selectOrganization(org.id); + setCurrentOrganization(organizationFromSelection(selected.data.organization)); localStorage.setItem('currentOrganizationId', org.id); } else { router.push('/select-organization'); @@ -300,8 +300,8 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { if (orgs.length === 1) { const org = orgs[0]; - await authApi.selectOrganization(org.id); - setCurrentOrganization(organizationFromSelection(org)); + const selected = await authApi.selectOrganization(org.id); + setCurrentOrganization(organizationFromSelection(selected.data.organization)); localStorage.setItem('currentOrganizationId', org.id); } else { router.push('/select-organization'); -- 2.53.0.windows.1 From e7e107dc517eda0cdf9b8d9545fe648be5ceafb4 Mon Sep 17 00:00:00 2001 From: Admin Date: Wed, 11 Nov 2026 18:15:33 +0330 Subject: [PATCH 2/7] improvements: obligations are now automatically generated. prosthesis catalog can be filtered iuf some items has no price on them. billing supports static salary amounts now. --- .cursor/rules/billing.mdc | 3 + .cursor/skills/billing/SKILL.md | 13 + AGENTS.md | 2 +- backend/package.json | 1 + .../migration.sql | 56 ++ .../migration.sql | 5 + .../migration.sql | 27 + backend/prisma/schema.prisma | 51 ++ backend/prisma/seed-billing-demo.ts | 445 ++++++++++ backend/prisma/wipe-app-data.ts | 2 + backend/src/admin/resources.ts | 3 + backend/src/common/errors/error-codes.ts | 2 + .../src/modules/billing/billing.controller.ts | 55 ++ .../src/modules/billing/billing.service.ts | 822 +++++++++++++++++- .../billing/dto/billing-payment.dto.ts | 30 + .../billing/dto/upsert-billing-sheet.dto.ts | 5 + .../src/modules/billing/party-ledger.spec.ts | 58 ++ backend/src/modules/billing/party-ledger.ts | 19 + .../billing/staff-billing-period.spec.ts | 48 + .../modules/billing/staff-billing-period.ts | 125 +++ backend/src/modules/cases/cases.service.ts | 7 +- .../modules/treatments/treatments.service.ts | 34 +- frontend/messages/en.json | 39 +- frontend/messages/fa.json | 39 +- frontend/messages/nl.json | 39 +- .../ui/billing/BillingPartyReportDialog.tsx | 330 +++++++ .../ui/billing/BillingPaymentsPanel.tsx | 62 +- .../ui/billing/BillingSheetEditor.tsx | 24 + .../ui/billing/BillingSheetsPanel.tsx | 1 + .../src/components/ui/lab/CaseCreatePanel.tsx | 45 +- .../ui/treatment/LabCasesDispatchPanel.tsx | 36 +- .../ui/treatment/ProsthesisAssignChart.tsx | 10 +- .../ui/treatment/TreatmentWorkspace.tsx | 16 +- frontend/src/lib/api/billing.ts | 44 +- frontend/src/types/billing.ts | 33 + 35 files changed, 2470 insertions(+), 61 deletions(-) create mode 100644 backend/prisma/migrations/20261111130000_billing_obligations/migration.sql create mode 100644 backend/prisma/migrations/20261111163000_staff_billing_periods/migration.sql create mode 100644 backend/prisma/migrations/20261111170000_pending_case_obligations/migration.sql create mode 100644 backend/prisma/seed-billing-demo.ts create mode 100644 backend/src/modules/billing/party-ledger.spec.ts create mode 100644 backend/src/modules/billing/party-ledger.ts create mode 100644 backend/src/modules/billing/staff-billing-period.spec.ts create mode 100644 backend/src/modules/billing/staff-billing-period.ts create mode 100644 frontend/src/components/ui/billing/BillingPartyReportDialog.tsx diff --git a/.cursor/rules/billing.mdc b/.cursor/rules/billing.mdc index c0f6bec..ef5bad7 100644 --- a/.cursor/rules/billing.mdc +++ b/.cursor/rules/billing.mdc @@ -11,6 +11,9 @@ 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 −). +- **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:** `Membership.fixedMonthlySalary`; salary and commission are separate rows whose combined staff payable is their sum. Toman rollups use Jalali months; Dollar/Euro use Gregorian months. V1 has no attendance/proration; changing salary can affect the current generated period. +- **Unpriced types:** price sheets can set `hideUnpricedTypes`. 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/skills/billing/SKILL.md b/.cursor/skills/billing/SKILL.md index 54ccf2b..0274962 100644 --- a/.cursor/skills/billing/SKILL.md +++ b/.cursor/skills/billing/SKILL.md @@ -43,10 +43,16 @@ Keep chrome identical: `BillingListToolbar`, outline labels, `AppMoneyInput`, eq ## 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. +- 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. +- Run `npm run prisma:seed-billing-demo` for idempotent local report data. ## Fee / commission editor - Start date required. Empty Apply-to = everyone. Lines store money `amount`. +- `CLINIC_PRICE` / `LAB_PRICE` may set `hideUnpricedTypes`. 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 +64,13 @@ 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 + +- `Membership.fixedMonthlySalary` is org-local. Manage it from the staff party report with Billing edit permission. +- Salary and commission are both allowed and produce separate period obligations whose combined payable is their sum. Toman periods follow Jalali months; Dollar/Euro periods follow Gregorian months. Staff cash remains `StaffPayment`. +- V1 deliberately has no attendance, proration, bonus, or payroll-tax model. Mid-month changes can alter the current lazily ensured month. ## Deep links diff --git a/AGENTS.md b/AGENTS.md index e0f2280..ba4068c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -70,7 +70,7 @@ frontend/src/ **Subscriptions (quick ref):** One **Base** plan includes 3 seats (the owner holds one). Extra seats are separate rows with their own end dates. Each owner gets one free month (`User.trialUsedAt`), stamped only after `grantForNewOwner` starts it. Do not set `trialUsedAt` before that call. A later organization gets Base seats that end immediately. Another organization with the same owner that already has `trialEndsAt` or any seat counts as later, even when `trialUsedAt` is still null. Migration `20261018120000_subscription_seats` runs once on deploy: every real organization gets Base for 30 days from that instant, 3 included seats, and an extra seat for each staff member past those 3. It does not set `trialUsedAt` and does not insert charge rows. Disabled members who are not the owner and have no open invite do not take a seat. Migration `20261023140000_drop_unreferenced_legacy_plans` deletes unused `trial`, `Small`, `Medium`, `Large`, and `Enterprise` plans and does not change any end date. 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/fixed salary periods; Toman uses Jalali months, Dollar/Euro Gregorian. Party reports union obligations with existing cash rows. Partner cash remains a shared Accept/Decline row; rejected rows stay visible to both but count only for the recorder. Salary and commission may both apply; v1 has no proration/attendance. Price sheets may hide unpriced prosthesis types; 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/package.json b/backend/package.json index c9fa7af..afab2af 100644 --- a/backend/package.json +++ b/backend/package.json @@ -22,6 +22,7 @@ "prisma:migrate": "prisma migrate dev", "prisma:deploy": "prisma migrate deploy", "prisma:seed": "prisma db seed", + "prisma:seed-billing-demo": "ts-node prisma/seed-billing-demo.ts", "prisma:reset-treatment": "ts-node prisma/reset-treatment-data.ts", "prisma:wipe-app-data": "ts-node prisma/wipe-app-data.ts", "prisma:regenerate-tasks": "ts-node prisma/regenerate-lab-tasks.ts", 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/schema.prisma b/backend/prisma/schema.prisma index 83797f1..fd033be 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -131,6 +131,7 @@ model Organization { partnerPaymentsTo PartnerPayment[] @relation("PartnerPaymentTo") staffPayments StaffPayment[] commissionEarnings CommissionEarning[] + billingLedgerEntries BillingLedgerEntry[] createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@ -747,6 +748,8 @@ model Membership { isOwner Boolean @default(false) isActive Boolean @default(true) + /// Optional fixed salary payable each full calendar month. Commissions remain independent. + fixedMonthlySalary Decimal? @db.Decimal(14, 2) user User @relation(fields: [userId], references: [id]) organization Organization @relation(fields: [organizationId], references: [id]) @@ -967,12 +970,32 @@ enum BillingCurrency { 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[] @@ -1151,3 +1174,31 @@ 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") +} diff --git a/backend/prisma/seed-billing-demo.ts b/backend/prisma/seed-billing-demo.ts new file mode 100644 index 0000000..4ca061f --- /dev/null +++ b/backend/prisma/seed-billing-demo.ts @@ -0,0 +1,445 @@ +import { + BillingLedgerPartyKind, + BillingObligationSourceType, + LinkStatus, + PartnerPaymentRecordedBy, + PartnerPaymentStatus, + Prisma, + PrismaClient, +} from '@prisma/client'; +import * as bcrypt from 'bcrypt'; +import { staffBillingPeriodForDate } from '../src/modules/billing/staff-billing-period'; + +const prisma = new PrismaClient(); + +const IDS = { + treatment: '10000000-0000-4000-8000-000000000001', + labCase: '10000000-0000-4000-8000-000000000002', + patientPayment: '10000000-0000-4000-8000-000000000003', + partnerPayment: '10000000-0000-4000-8000-000000000004', + staffPayment: '10000000-0000-4000-8000-000000000005', + pendingLabCase: '10000000-0000-4000-8000-000000000006', +}; + +function money(value: number) { + return new Prisma.Decimal(value.toFixed(2)); +} + +async function main() { + let link = await prisma.organizationLink.findFirst({ + where: { status: LinkStatus.ACTIVE }, + include: { + organizationA: { include: { type: true } }, + organizationB: { include: { type: true } }, + }, + }); + if (!link) { + const [clinicType, labType, plan] = await Promise.all([ + prisma.organizationType.findUnique({ where: { name: 'CLINIC' } }), + prisma.organizationType.findUnique({ where: { name: 'LAB' } }), + prisma.plan.findUnique({ where: { name: 'base' } }), + ]); + if (!clinicType || !labType) { + throw new Error('Run npm run prisma:seed before the billing demo seed.'); + } + const passwordHash = await bcrypt.hash('Demo123!', 10); + async function ensureOrganization(type: { id: string }, label: 'Clinic' | 'Lab') { + const existing = await prisma.organization.findFirst({ + where: { typeId: type.id }, + include: { type: true }, + orderBy: { createdAt: 'asc' }, + }); + if (existing) return existing; + const email = `billing.demo.${label.toLowerCase()}@dyolink.local`; + const owner = await prisma.user.upsert({ + where: { email }, + create: { email, name: `Billing Demo ${label} Owner`, passwordHash }, + update: { passwordHash }, + }); + const organization = await prisma.organization.upsert({ + where: { + ownerId_name: { ownerId: owner.id, name: `Billing Demo ${label}` }, + }, + create: { + name: `Billing Demo ${label}`, + typeId: type.id, + ownerId: owner.id, + planId: plan?.id ?? null, + billingCurrency: 'TOMAN', + }, + update: { planId: plan?.id ?? null, billingCurrency: 'TOMAN' }, + include: { type: true }, + }); + const membership = await prisma.membership.upsert({ + where: { + userId_organizationId: { + userId: owner.id, + organizationId: organization.id, + }, + }, + create: { + userId: owner.id, + organizationId: organization.id, + isOwner: true, + isActive: true, + }, + update: { isOwner: true, isActive: true }, + }); + await prisma.organizationSeat.upsert({ + where: { membershipId: membership.id }, + create: { + organizationId: organization.id, + membershipId: membership.id, + kind: 'BASE', + endsAt: new Date(Date.UTC(2035, 0, 1)), + }, + update: { endsAt: new Date(Date.UTC(2035, 0, 1)) }, + }); + return organization; + } + const clinic = await ensureOrganization(clinicType, 'Clinic'); + const lab = await ensureOrganization(labType, 'Lab'); + const existingLink = await prisma.organizationLink.findFirst({ + where: { + OR: [ + { organizationAId: clinic.id, organizationBId: lab.id }, + { organizationAId: lab.id, organizationBId: clinic.id }, + ], + }, + }); + if (existingLink) { + await prisma.organizationLink.update({ + where: { id: existingLink.id }, + data: { status: LinkStatus.ACTIVE }, + }); + } else { + await prisma.organizationLink.create({ + data: { + organizationAId: clinic.id, + organizationBId: lab.id, + status: LinkStatus.ACTIVE, + sharedDataTypes: [], + }, + }); + } + link = await prisma.organizationLink.findFirst({ + where: { + status: LinkStatus.ACTIVE, + OR: [ + { organizationAId: clinic.id, organizationBId: lab.id }, + { organizationAId: lab.id, organizationBId: clinic.id }, + ], + }, + include: { + organizationA: { include: { type: true } }, + organizationB: { include: { type: true } }, + }, + }); + } + if (!link) throw new Error('Could not create the billing demo organization link.'); + const organizations = [link.organizationA, link.organizationB]; + const clinic = organizations.find((org) => org.type.name === 'CLINIC'); + const lab = organizations.find((org) => org.type.name === 'LAB'); + if (!clinic || !lab) { + throw new Error('The first active organization link must connect a clinic and a lab.'); + } + + const clinicMemberships = await prisma.membership.findMany({ + where: { organizationId: clinic.id, OR: [{ isOwner: true }, { isActive: true }] }, + orderBy: [{ isOwner: 'asc' }, { createdAt: 'asc' }], + }); + const provider = clinicMemberships[0]; + if (!provider) throw new Error('The clinic needs at least one active member.'); + + let patient = await prisma.patient.findFirst({ + where: { createdByOrganizationId: clinic.id, isWalkIn: false }, + orderBy: { createdAt: 'asc' }, + }); + patient ??= await prisma.patient.create({ + data: { + firstName: 'Billing', + lastName: 'Demo Patient', + identification: `billing-demo-${clinic.id}`, + mobile: '0000000000', + createdByOrganizationId: clinic.id, + }, + }); + + const now = new Date(); + const staffPeriod = staffBillingPeriodForDate( + now, + clinic.billingCurrency ?? 'TOMAN', + ); + const treatment = await prisma.treatment.upsert({ + where: { id: IDS.treatment }, + create: { + id: IDS.treatment, + organizationId: clinic.id, + patientId: patient.id, + providerUserId: provider.userId, + title: 'Billing demo treatment', + treatmentAt: now, + calculatedAmount: money(1_500_000), + billedAmount: money(1_500_000), + billedAmountManual: true, + }, + update: { + organizationId: clinic.id, + patientId: patient.id, + providerUserId: provider.userId, + billedAmount: money(1_500_000), + billedAmountManual: true, + }, + }); + const labCase = await prisma.labCase.upsert({ + where: { id: IDS.labCase }, + create: { + id: IDS.labCase, + treatmentId: treatment.id, + destinationOrganizationId: lab.id, + sentAt: now, + externalCode: 'BILLING-DEMO', + patientDisplayName: `${patient.firstName} ${patient.lastName}`.trim(), + calculatedAmount: money(800_000), + billedAmount: money(800_000), + }, + update: { + treatmentId: treatment.id, + destinationOrganizationId: lab.id, + sentAt: now, + billedAmount: money(800_000), + }, + }); + const pendingLabCase = await prisma.labCase.upsert({ + where: { id: IDS.pendingLabCase }, + create: { + id: IDS.pendingLabCase, + treatmentId: treatment.id, + destinationOrganizationId: lab.id, + sentAt: now, + externalCode: 'BILLING-PENDING', + patientDisplayName: `${patient.firstName} ${patient.lastName}`.trim(), + calculatedAmount: money(0), + billedAmount: null, + billedAmountManual: false, + }, + update: { + treatmentId: treatment.id, + destinationOrganizationId: lab.id, + sentAt: now, + calculatedAmount: money(0), + billedAmount: null, + billedAmountManual: false, + }, + }); + + await prisma.organization.updateMany({ + where: { id: { in: [clinic.id, lab.id] }, billingCurrency: null }, + data: { billingCurrency: 'TOMAN' }, + }); + await prisma.membership.update({ + where: { id: provider.id }, + data: { fixedMonthlySalary: money(12_000_000) }, + }); + await prisma.commissionEarning.upsert({ + where: { + treatmentId_catalogCode: { + treatmentId: treatment.id, + catalogCode: 'billing_demo_commission', + }, + }, + create: { + organizationId: clinic.id, + userId: provider.userId, + treatmentId: treatment.id, + catalogCode: 'billing_demo_commission', + baseAmount: money(250_000), + percent: money(0), + qty: money(1), + earnedAmount: money(250_000), + earnedAt: now, + }, + update: { earnedAmount: money(250_000), earnedAt: now }, + }); + + const obligations = [ + { + organizationId: clinic.id, + partyKind: BillingLedgerPartyKind.PATIENT, + partyId: patient.id, + sourceType: BillingObligationSourceType.TREATMENT_APPROVE, + sourceId: treatment.id, + amount: 1_500_000, + sign: 1, + occurredAt: now, + }, + { + organizationId: clinic.id, + partyKind: BillingLedgerPartyKind.ORGANIZATION, + partyId: lab.id, + sourceType: BillingObligationSourceType.LAB_CASE, + sourceId: labCase.id, + amount: 800_000, + sign: -1, + occurredAt: now, + }, + { + organizationId: lab.id, + partyKind: BillingLedgerPartyKind.ORGANIZATION, + partyId: clinic.id, + sourceType: BillingObligationSourceType.LAB_CASE, + sourceId: labCase.id, + amount: 800_000, + sign: 1, + occurredAt: now, + }, + { + organizationId: clinic.id, + partyKind: BillingLedgerPartyKind.STAFF, + partyId: provider.userId, + sourceType: BillingObligationSourceType.STAFF_COMMISSION_MONTH, + sourceId: `${provider.userId}:${staffPeriod.key}:commission`, + amount: 250_000, + sign: -1, + occurredAt: staffPeriod.start, + }, + { + organizationId: clinic.id, + partyKind: BillingLedgerPartyKind.STAFF, + partyId: provider.userId, + sourceType: BillingObligationSourceType.STAFF_SALARY_MONTH, + sourceId: `${provider.userId}:${staffPeriod.key}:salary`, + amount: 12_000_000, + sign: -1, + occurredAt: staffPeriod.start, + }, + ]; + for (const row of obligations) { + const { sign, amount, ...entry } = row; + await prisma.billingLedgerEntry.upsert({ + where: { + organizationId_sourceType_sourceId: { + organizationId: entry.organizationId, + sourceType: entry.sourceType, + sourceId: entry.sourceId, + }, + }, + create: { + ...entry, + amount: money(amount), + signedAmount: money(amount * sign), + balanceSign: sign, + }, + update: { + partyKind: entry.partyKind, + partyId: entry.partyId, + amount: money(amount), + signedAmount: money(amount * sign), + balanceSign: sign, + occurredAt: entry.occurredAt, + }, + }); + } + for (const row of [ + { + organizationId: clinic.id, + partyId: lab.id, + sign: -1, + }, + { + organizationId: lab.id, + partyId: clinic.id, + sign: 1, + }, + ]) { + await prisma.billingLedgerEntry.upsert({ + where: { + organizationId_sourceType_sourceId: { + organizationId: row.organizationId, + sourceType: BillingObligationSourceType.LAB_CASE, + sourceId: pendingLabCase.id, + }, + }, + create: { + organizationId: row.organizationId, + partyKind: BillingLedgerPartyKind.ORGANIZATION, + partyId: row.partyId, + sourceType: BillingObligationSourceType.LAB_CASE, + sourceId: pendingLabCase.id, + amount: null, + signedAmount: null, + balanceSign: row.sign, + occurredAt: now, + }, + update: { + partyId: row.partyId, + amount: null, + signedAmount: null, + balanceSign: row.sign, + occurredAt: now, + }, + }); + } + + await prisma.patientPayment.upsert({ + where: { id: IDS.patientPayment }, + create: { + id: IDS.patientPayment, + organizationId: clinic.id, + patientId: patient.id, + amount: money(500_000), + paidAt: now, + note: 'Billing demo patient receipt', + createdByUserId: provider.userId, + }, + update: { patientId: patient.id, amount: money(500_000), paidAt: now }, + }); + await prisma.partnerPayment.upsert({ + where: { id: IDS.partnerPayment }, + create: { + id: IDS.partnerPayment, + fromOrganizationId: clinic.id, + toOrganizationId: lab.id, + amount: money(300_000), + paidAt: now, + note: 'Billing demo partner payment', + status: PartnerPaymentStatus.CONFIRMED, + recordedBy: PartnerPaymentRecordedBy.CLINIC, + receiptConfirmedAt: now, + createdByUserId: provider.userId, + }, + update: { + fromOrganizationId: clinic.id, + toOrganizationId: lab.id, + amount: money(300_000), + paidAt: now, + receiptConfirmedAt: now, + }, + }); + await prisma.staffPayment.upsert({ + where: { id: IDS.staffPayment }, + create: { + id: IDS.staffPayment, + organizationId: clinic.id, + userId: provider.userId, + amount: money(5_000_000), + paidAt: now, + note: 'Billing demo salary payment', + createdByUserId: provider.userId, + }, + update: { userId: provider.userId, amount: money(5_000_000), paidAt: now }, + }); + + console.log(`Billing demo ready for clinic "${clinic.name}" and lab "${lab.name}".`); + console.log(`Patient: ${patient.firstName} ${patient.lastName}; staff user: ${provider.userId}`); + console.log('Pending amount case: BILLING-PENDING'); +} + +main() + .catch((error) => { + console.error(error); + process.exitCode = 1; + }) + .finally(async () => { + await prisma.$disconnect(); + }); 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..9fce4d7 100644 --- a/backend/src/admin/resources.ts +++ b/backend/src/admin/resources.ts @@ -253,5 +253,8 @@ export function buildAdminResources(prisma: PrismaService): AdminResource[] { resource(prisma, 'CommissionEarning', { navigation: { name: 'Billing', icon: 'CreditCard' }, }), + resource(prisma, 'BillingLedgerEntry', { + navigation: { name: 'Billing', icon: 'CreditCard' }, + }), ]; } diff --git a/backend/src/common/errors/error-codes.ts b/backend/src/common/errors/error-codes.ts index 26404b7..95f2838 100644 --- a/backend/src/common/errors/error-codes.ts +++ b/backend/src/common/errors/error-codes.ts @@ -230,6 +230,8 @@ export const ErrorCode = { 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/billing/billing.controller.ts b/backend/src/modules/billing/billing.controller.ts index dee5ca9..c29f902 100644 --- a/backend/src/modules/billing/billing.controller.ts +++ b/backend/src/modules/billing/billing.controller.ts @@ -24,7 +24,10 @@ import { AllocationSearchQueryDto, CreatePaymentDto, ListPaymentsQueryDto, + PartyReportQueryDto, PartySearchQueryDto, + UpdateObligationAmountDto, + UpdateStaffSalaryDto, } from './dto/billing-payment.dto'; import { UpsertBillingSheetDto } from './dto/upsert-billing-sheet.dto'; import { LabPriceQuoteDto, OutsourceQuoteDto } from './dto/billing-quote.dto'; @@ -146,6 +149,58 @@ 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/:userId/salary') + @ApiOperation({ summary: 'Get a staff member fixed monthly salary' }) + getStaffSalary( + @Param('userId', ParseUUIDPipe) userId: string, + @Req() req: { user: { id: string; organizationId?: string } }, + ) { + const organizationId = this.billingService.getOrganizationIdFromUser(req.user); + return this.billingService.getStaffSalary(req.user.id, organizationId, userId); + } + + @Put('staff/:userId/salary') + @ApiOperation({ summary: 'Set a staff member fixed monthly salary (TAB_BILLING_EDIT)' }) + updateStaffSalary( + @Param('userId', ParseUUIDPipe) userId: string, + @Body() dto: UpdateStaffSalaryDto, + @Req() req: { user: { id: string; organizationId?: string } }, + ) { + const organizationId = this.billingService.getOrganizationIdFromUser(req.user); + return this.billingService.updateStaffSalary( + req.user.id, + organizationId, + userId, + dto.fixedMonthlySalary, + ); + } + @Get('staff-payments') @ApiOperation({ summary: 'List staff payments' }) listStaffPayments( diff --git a/backend/src/modules/billing/billing.service.ts b/backend/src/modules/billing/billing.service.ts index e8c8ee8..2d6f689 100644 --- a/backend/src/modules/billing/billing.service.ts +++ b/backend/src/modules/billing/billing.service.ts @@ -1,6 +1,13 @@ -import { HttpStatus, Injectable } from '@nestjs/common'; +import { + HttpStatus, + Injectable, + OnModuleDestroy, + OnModuleInit, +} from '@nestjs/common'; import { BillingCatalogKind, + BillingLedgerPartyKind, + BillingObligationSourceType, BillingSheetKind, CatalogEntityKind, LinkStatus, @@ -55,7 +62,7 @@ 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 } from './dto/billing-payment.dto'; import { isBillingCurrencyCode, lockBillingCurrencyOnWrite, @@ -68,6 +75,16 @@ import { type BillingSheetKindValue, type BillingSheetRecord, } from './resolve-billing-sheet'; +import { + sharedCashCountsInPartyReport, + signedPartyCashAmount, +} from './party-ledger'; +import { + previousStaffBillingPeriod, + staffBillingPeriodForDate, + staffBillingPeriodFromKey, + staffBillingPeriodsBetween, +} from './staff-billing-period'; type PaymentListQuery = { q?: string; @@ -75,6 +92,7 @@ type PaymentListQuery = { to?: string; partyKind?: 'patient' | 'staff' | 'org'; partyId?: string; + unlimited?: boolean; }; const sheetInclude = { @@ -88,7 +106,10 @@ const sheetInclude = { } satisfies Prisma.BillingSheetInclude; @Injectable() -export class BillingService { +export class BillingService implements OnModuleInit, OnModuleDestroy { + private staffRollupTimer: ReturnType | null = null; + private readonly scheduledStaffRollups = new Set(); + constructor( private readonly prisma: PrismaService, private readonly catalogLabels: CatalogLabelService, @@ -101,6 +122,132 @@ 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() { + await this.rollUpPreviousStaffPeriod(); + } + + async rollUpPreviousStaffPeriod() { + const now = new Date(); + const organizations = await this.prisma.organization.findMany({ select: { id: true } }); + for (const organization of organizations) { + const currency = await this.staffBillingCurrency(organization.id); + const current = staffBillingPeriodForDate(now, currency); + const previous = previousStaffBillingPeriod(now, currency); + for (const period of [current, previous]) { + const scheduledKey = `${organization.id}:${period.key}`; + if (this.scheduledStaffRollups.has(scheduledKey)) continue; + await this.ensureStaffPeriodObligations(organization.id, period.key); + this.scheduledStaffRollups.add(scheduledKey); + } + } + } + + async ensureStaffPeriodObligations(organizationId: string, periodKey: string) { + const period = staffBillingPeriodFromKey(periodKey); + if (!period) { + throw new AppException(ErrorCode.BILLING_LINE_INVALID, HttpStatus.BAD_REQUEST); + } + const { start, end } = period; + const currency = await this.staffBillingCurrency(organizationId); + const currentPeriod = staffBillingPeriodForDate(new Date(), currency); + const includeCurrentSalary = currentPeriod.key === period.key; + const [commissionSums, memberships] = await Promise.all([ + this.prisma.commissionEarning.groupBy({ + by: ['userId'], + where: { organizationId, earnedAt: { gte: start, lt: end } }, + _sum: { earnedAmount: true }, + }), + includeCurrentSalary + ? this.prisma.membership.findMany({ + where: { + organizationId, + OR: [{ isOwner: true }, { isActive: true }], + fixedMonthlySalary: { gt: 0 }, + }, + select: { userId: true, fixedMonthlySalary: true }, + }) + : Promise.resolve([]), + ]); + + await this.prisma.$transaction(async (tx) => { + const expected = new Map< + string, + { + partyId: string; + sourceType: BillingObligationSourceType; + amount: number; + } + >(); + for (const row of commissionSums) { + expected.set(`${row.userId}:${period.key}:commission`, { + partyId: row.userId, + sourceType: BillingObligationSourceType.STAFF_COMMISSION_MONTH, + amount: Number(row._sum.earnedAmount ?? 0), + }); + } + for (const membership of memberships) { + expected.set(`${membership.userId}:${period.key}:salary`, { + partyId: membership.userId, + sourceType: BillingObligationSourceType.STAFF_SALARY_MONTH, + amount: Number(membership.fixedMonthlySalary ?? 0), + }); + } + + const periodSourceIds = [ + ...commissionSums.map((row) => `${row.userId}:${period.key}:commission`), + ...memberships.map((row) => `${row.userId}:${period.key}:salary`), + ]; + await tx.billingLedgerEntry.deleteMany({ + where: { + organizationId, + sourceType: BillingObligationSourceType.STAFF_COMMISSION_MONTH, + sourceId: { + endsWith: `:${period.key}:commission`, + notIn: periodSourceIds, + }, + }, + }); + if (includeCurrentSalary) { + await tx.billingLedgerEntry.deleteMany({ + where: { + organizationId, + sourceType: BillingObligationSourceType.STAFF_SALARY_MONTH, + sourceId: { + endsWith: `:${period.key}:salary`, + notIn: periodSourceIds, + }, + }, + }); + } + + for (const [sourceId, row] of expected) { + await this.upsertObligation(tx, { + organizationId, + partyKind: BillingLedgerPartyKind.STAFF, + partyId: row.partyId, + sourceType: row.sourceType, + sourceId, + amount: row.amount, + sign: -1, + occurredAt: start, + }); + } + }); + } + async listSheets( actorUserId: string, organizationId: string, @@ -293,6 +440,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 +472,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 +522,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 +550,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 +562,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 +583,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; @@ -508,15 +656,265 @@ 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); + const periods = await this.staffReportPeriods(organizationId, query.partyId, query); + for (const periodKey of periods) { + await this.ensureStaffPeriodObligations(organizationId, periodKey); + } + } 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, 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 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, + reference: + treatmentLabels.get(row.sourceId) ?? + caseLabels.get(row.sourceId) ?? + staffPeriodReference(row.sourceId), + note: row.note, + acknowledgement: 'none' as const, + 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, + 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); + return { + success: true as const, + data: rows, + totals: { + debit: roundBillingAmount(debit).toFixed(2), + credit: roundBillingAmount(credit).toFixed(2), + net: roundSignedBillingAmount(net).toFixed(2), + }, + }; + } + + 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 getStaffSalary(actorUserId: string, organizationId: string, userId: string) { + await this.assertCanRead(actorUserId, organizationId); + await this.assertStaffInOrg(organizationId, userId); + const membership = await this.prisma.membership.findUniqueOrThrow({ + where: { userId_organizationId: { userId, organizationId } }, + select: { fixedMonthlySalary: true }, + }); + return { + success: true as const, + data: { fixedMonthlySalary: membership.fixedMonthlySalary?.toFixed(2) ?? '0.00' }, + }; + } + + async updateStaffSalary( + actorUserId: string, + organizationId: string, + userId: string, + value: string, + ) { + await this.assertCanEdit(actorUserId, organizationId); + await this.assertStaffInOrg(organizationId, userId); + const amount = parseMoney(value); + await this.prisma.membership.update({ + where: { userId_organizationId: { userId, organizationId } }, + data: { + fixedMonthlySalary: + amount > 0 ? new Prisma.Decimal(amount.toFixed(2)) : null, + }, + }); + const currency = await this.staffBillingCurrency(organizationId); + const period = staffBillingPeriodForDate(new Date(), currency); + await this.ensureStaffPeriodObligations(organizationId, period.key); + return { + success: true as const, + data: { fixedMonthlySalary: amount.toFixed(2) }, + }; + } + async searchParties( actorUserId: string, organizationId: string, @@ -752,9 +1150,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, @@ -985,12 +1381,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 +1398,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) { @@ -1123,7 +1555,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 +1566,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, @@ -1497,6 +1930,216 @@ 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?.destinationOrganizationId) return; + + const sourceType = + labCase.origin === 'LAB_OUTSOURCE' + ? BillingObligationSourceType.OUTSOURCE_CASE + : BillingObligationSourceType.LAB_CASE; + const payerOrganizationId = + labCase.origin === 'LAB_OUTSOURCE' + ? labCase.parentLabCase?.destinationOrganizationId + : (labCase.treatment?.organizationId ?? labCase.partnerClinicOrganizationId); + const amount = + labCase.billedAmount == null ? null : Number(labCase.billedAmount); + + if (!payerOrganizationId || payerOrganizationId === labCase.destinationOrganizationId) { + await this.voidObligationSource(db, sourceType, labCase.id); + return; + } + + const occurredAt = labCase.sentAt ?? labCase.startedAt ?? new Date(); + await this.upsertObligation(db, { + organizationId: payerOrganizationId, + partyKind: BillingLedgerPartyKind.ORGANIZATION, + partyId: labCase.destinationOrganizationId, + sourceType, + sourceId: labCase.id, + amount, + keepPending: true, + sign: -1, + occurredAt, + }); + await this.upsertObligation(db, { + organizationId: labCase.destinationOrganizationId, + partyKind: BillingLedgerPartyKind.ORGANIZATION, + partyId: payerOrganizationId, + 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; + }, + ) { + 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, + }, + }); + } + + 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({ @@ -1564,7 +2207,7 @@ 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, @@ -1576,20 +2219,30 @@ export class BillingService { tooth: job.tooth, prosthesisTypeCode: job.prosthesisTypeCode, })), - lines, + lines: resolvedSheet.lines, metaByCode, }); - const billed = labCase.billedAmountManual - ? Number(labCase.billedAmount ?? calculated) - : calculated; + const unpricedCodes = unpricedProsthesisCodes( + labCase.toothProsthesis, + resolvedSheet.lines, + ); + const hasManualAmount = + labCase.billedAmountManual && labCase.billedAmount != null; + const billed = hasManualAmount + ? Number(labCase.billedAmount) + : unpricedCodes.length > 0 + ? 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 +2255,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 +2288,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 +2631,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 +2653,48 @@ export class BillingService { } } + private async staffReportPeriods( + organizationId: string, + userId: string, + query: { from?: string; to?: string }, + ): Promise { + const currency = await this.staffBillingCurrency(organizationId); + const periods = new Set(); + const earnings = await this.prisma.commissionEarning.findMany({ + where: { + organizationId, + userId, + ...(query.from || query.to + ? { + earnedAt: { + ...(query.from ? { gte: dateOnlyUtc(query.from) } : {}), + ...(query.to ? { lt: dateOnlyUtc(addUtcDays(query.to, 1)) } : {}), + }, + } + : {}), + }, + select: { earnedAt: true }, + }); + for (const earning of earnings) { + periods.add(staffBillingPeriodForDate(earning.earnedAt, currency).key); + } + + const now = new Date(); + const from = query.from ? dateOnlyUtc(query.from) : now; + const to = query.to ? dateOnlyUtc(query.to) : now; + for (const period of staffBillingPeriodsBetween(from, to, currency)) { + periods.add(period.key); + } + return [...periods].sort(); + } + + private async staffBillingCurrency( + organizationId: string, + ): Promise { + const settings = await resolveBillingCurrency(this.prisma, organizationId); + return settings.currency ?? 'TOMAN'; + } + private async assertCanEdit(userId: string, organizationId: string) { const membership = await this.getMembership(userId, organizationId); if (!membership) { @@ -2015,6 +2730,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 +2770,24 @@ function stringList(value: unknown): string[] { return value.filter((item): item is string => typeof item === 'string'); } +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(); +} + function dateOnlyUtc(value: string): Date { return new Date(`${value}T00:00:00.000Z`); } @@ -2061,6 +2798,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) { @@ -2158,6 +2907,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; @@ -2294,6 +3055,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/dto/billing-payment.dto.ts b/backend/src/modules/billing/dto/billing-payment.dto.ts index ce2b04f..f2a1dbd 100644 --- a/backend/src/modules/billing/dto/billing-payment.dto.ts +++ b/backend/src/modules/billing/dto/billing-payment.dto.ts @@ -99,6 +99,36 @@ 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 UpdateStaffSalaryDto { + @IsNumberString({}, { message: ErrorCode.BILLING_AMOUNT_INVALID }) + @Matches(/^\d+(\.\d{1,2})?$/, { message: ErrorCode.BILLING_AMOUNT_INVALID }) + fixedMonthlySalary: string; +} + +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..bbb0ba1 --- /dev/null +++ b/backend/src/modules/billing/staff-billing-period.spec.ts @@ -0,0 +1,48 @@ +import { + previousStaffBillingPeriod, + staffBillingPeriodForDate, + staffBillingPeriodFromKey, + staffBillingPeriodsBetween, +} 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('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..3bd119f --- /dev/null +++ b/backend/src/modules/billing/staff-billing-period.ts @@ -0,0 +1,125 @@ +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, + ); +} + +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..45c045a 100644 --- a/frontend/messages/en.json +++ b/frontend/messages/en.json @@ -889,6 +889,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.", @@ -1373,7 +1375,38 @@ "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": "Lab case fee", + "reportSourceOutsource": "Outsourced case fee", + "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." }, "localDb": { "browse": "Browse", @@ -1605,6 +1638,8 @@ "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..5050a60 100644 --- a/frontend/messages/fa.json +++ b/frontend/messages/fa.json @@ -890,6 +890,8 @@ "selectLabPlaceholder": "یک لابراتوار متصل انتخاب کنید…", "sendToLab": "ارسال به لابراتوار", "labFeePreview": "تعرفه لابراتوار", + "labFeeNeedsBillingAmount": "این پرونده شامل خدماتی بدون تعرفه لابراتوار است. ارسال مجاز است، اما لابراتوار مقصد باید مبلغ نهایی را در بخش مالی ثبت کند.", + "labDoesNotProvideTypes": "این لابراتوار خدمات پروتز زیر را ارائه نمی‌دهد: {types}. لابراتوار دیگری انتخاب کنید یا پرونده را تغییر دهید.", "dueDateLabel": "موعد تحویل", "dueDateOptional": "اختیاری", "dueDateLockedCompleted": "پس از تکمیل همه وظایف، موعد قابل تغییر نیست.", @@ -1374,7 +1376,38 @@ "time": "زمان", "attachments": "پیوست‌ها", "cancel": "انصراف", - "walkInPatient": "بدون نوبت" + "walkInPatient": "بدون نوبت", + "hideUnpricedTypes": "پنهان کردن انواع پروتز بدون قیمت", + "hideUnpricedTypesClinicInfo": "تا زمانی که این جدول تعرفه فعال است، انواع پروتز بدون قیمت در چارت درمان کلینیک نمایش داده نمی‌شوند.", + "hideUnpricedTypesLabInfo": "انواع پروتز بدون قیمت در چارت پرونده این لابراتوار پنهان می‌شوند. همچنین تا زمانی که این جدول فعال است، کلینیک‌های متصل نمی‌توانند پرونده‌ای شامل این خدمات ارسال کنند.", + "debitCreditReport": "گزارش بدهکار/بستانکار", + "debit": "بدهکار", + "credit": "بستانکار", + "reportSource": "منبع", + "reference": "مرجع", + "reportEmpty": "در این بازه هیچ ردیف بدهکار یا بستانکاری وجود ندارد.", + "reportSourceTreatment": "درمان تأییدشده", + "reportSourceLabCase": "هزینه پرونده لابراتوار", + "reportSourceOutsource": "هزینه پرونده برون‌سپاری", + "reportSourceCommission": "کمیسیون ماهانه", + "reportSourceSalary": "حقوق ماهانه", + "reportSourceCashReceipt": "دریافت نقدی", + "reportSourceCashPayment": "پرداخت نقدی", + "reportDebitTotal": "جمع بدهکار: {amount}", + "reportCreditTotal": "جمع بستانکار: {amount}", + "reportNet": "خالص: {amount}", + "errorLoadReport": "بارگذاری گزارش بدهکار/بستانکار ناموفق بود.", + "fixedMonthlySalary": "حقوق ثابت ماهانه", + "saveSalary": "ذخیره حقوق", + "salarySaved": "حقوق ماهانه ذخیره شد.", + "errorLoadSalary": "بارگذاری حقوق ماهانه ناموفق بود.", + "errorSaveSalary": "ذخیره حقوق ماهانه ناموفق بود.", + "obligationAmountRequired": "نیازمند مبلغ", + "caseObligationAmount": "هزینه پرونده", + "setObligationAmount": "تعیین مبلغ", + "saveObligationAmount": "ذخیره مبلغ", + "obligationAmountSaved": "هزینه پرونده برای هر دو سازمان ذخیره شد.", + "errorSaveObligationAmount": "ذخیره هزینه پرونده ناموفق بود." }, "localDb": { "browse": "مرور", @@ -1606,6 +1639,8 @@ "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..7b84408 100644 --- a/frontend/messages/nl.json +++ b/frontend/messages/nl.json @@ -889,6 +889,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.", @@ -1373,7 +1375,38 @@ "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": "Labcase-tarief", + "reportSourceOutsource": "Uitbesteed case-tarief", + "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." }, "localDb": { "browse": "Bladeren", @@ -1605,6 +1638,8 @@ "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/ui/billing/BillingPartyReportDialog.tsx b/frontend/src/components/ui/billing/BillingPartyReportDialog.tsx new file mode 100644 index 0000000..e7871a2 --- /dev/null +++ b/frontend/src/components/ui/billing/BillingPartyReportDialog.tsx @@ -0,0 +1,330 @@ +'use client'; + +import { useEffect, useState } from 'react'; +import { useTranslations } from 'next-intl'; +import { billingApi } from '@/lib/api/billing'; +import { getUserFacingError } from '@/components/shared/formatApiError'; +import { useToast } from '@/lib/hooks/useToast'; +import { useAppFormatters } from '@/lib/hooks/useAppFormatters'; +import { AppDateInput } from '@/components/ui/shared/AppDateInput'; +import { AppMoneyInput } from '@/components/ui/shared/AppMoneyInput'; +import { Badge } from '@/components/ui/shared/Badge'; +import { Button } from '@/components/ui/shared/Button'; +import { DialogCloseButton } from '@/components/ui/shared/DialogCloseButton'; +import { + ResponsiveDialogOverlay, + ResponsiveDialogPanel, +} from '@/components/ui/shared/ResponsiveDialog'; +import { Table, TABLE_HEADER_CELL_CLASS } from '@/components/ui/shared/Table'; +import { moneyFieldLabel } from '@/components/billing/moneyFieldLabel'; +import { useBillingCurrency } from '@/lib/hooks/useBillingCurrency'; +import { parseAppMoney } from '@/lib/i18n/format'; +import type { + BillingPartyKind, + BillingPartyReport, + BillingPartyReportRow, +} from '@/types/billing'; + +type Props = { + party: { id: string; name: string; kind: BillingPartyKind }; + initialFrom: string; + initialTo: string; + canEdit: boolean; + onClose: () => void; +}; + +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', +}; + +export function BillingPartyReportDialog({ + party, + initialFrom, + initialTo, + canEdit, + onClose, +}: Props) { + const t = useTranslations('billing'); + const tCommon = useTranslations('common'); + const tErrors = useTranslations('errors'); + const toast = useToast(); + const { formatDateTime, formatMoney } = useAppFormatters(); + const { settings: currencySettings } = useBillingCurrency(true); + const [from, setFrom] = useState(initialFrom); + const [to, setTo] = useState(initialTo); + const [report, setReport] = useState(null); + const [loading, setLoading] = useState(true); + const [reportEpoch, setReportEpoch] = useState(0); + const [salary, setSalary] = useState(''); + const [salarySaving, setSalarySaving] = useState(false); + const [editingObligation, setEditingObligation] = + useState(null); + const [obligationAmount, setObligationAmount] = useState(''); + const [obligationSaving, setObligationSaving] = useState(false); + const salaryLabel = moneyFieldLabel( + t('fixedMonthlySalary'), + currencySettings.currency, + (code) => tCommon(`currencyName.${code}` as 'currencyName.TOMAN'), + ); + + useEffect(() => { + if (party.kind !== 'staff') return; + void billingApi + .getStaffSalary(party.id) + .then((response) => setSalary(response.data.fixedMonthlySalary)) + .catch((error: unknown) => + toast.showError(getUserFacingError(error, tErrors, t('errorLoadSalary'))), + ); + }, [party.id, party.kind, t, tErrors, toast]); + + useEffect(() => { + let active = true; + const handle = window.setTimeout(() => { + setLoading(true); + void billingApi + .getPartyReport({ + partyKind: party.kind, + partyId: party.id, + from: from || undefined, + to: to || undefined, + }) + .then((response) => { + if (active) setReport(response); + }) + .catch((error: unknown) => { + if (active) toast.showError(getUserFacingError(error, tErrors, t('errorLoadReport'))); + }) + .finally(() => { + if (active) setLoading(false); + }); + }, 200); + return () => { + active = false; + window.clearTimeout(handle); + }; + }, [from, party.id, party.kind, reportEpoch, t, tErrors, to, toast]); + + async function saveSalary() { + const parsed = parseAppMoney(salary); + if (parsed == null) { + toast.showError(t('invalidAmount')); + return; + } + setSalarySaving(true); + try { + const response = await billingApi.updateStaffSalary(party.id, parsed); + setSalary(response.data.fixedMonthlySalary); + setReportEpoch((value) => value + 1); + toast.showSuccess(t('salarySaved')); + } catch (error: unknown) { + toast.showError(getUserFacingError(error, tErrors, t('errorSaveSalary'))); + } finally { + setSalarySaving(false); + } + } + + async function saveObligationAmount() { + if (!editingObligation) return; + const parsed = parseAppMoney(obligationAmount); + if (parsed == null || Number(parsed) <= 0) { + toast.showError(t('invalidAmount')); + return; + } + setObligationSaving(true); + try { + await billingApi.updateObligationAmount(editingObligation.id, parsed); + setEditingObligation(null); + setObligationAmount(''); + setReportEpoch((value) => value + 1); + toast.showSuccess(t('obligationAmountSaved')); + } catch (error: unknown) { + toast.showError( + getUserFacingError(error, tErrors, t('errorSaveObligationAmount')), + ); + } finally { + setObligationSaving(false); + } + } + + return ( + + +
+
+

+ {t('debitCreditReport')} +

+

{party.name}

+
+ +
+ +
+ + +
+ + {party.kind === 'staff' ? ( +
+
+ +
+ {canEdit ? ( + + ) : null} +
+ ) : null} + + {editingObligation ? ( +
+
+ tCommon(`currencyName.${code}` as 'currencyName.TOMAN'), + )} + labelPlacement="outline" + value={obligationAmount} + onChange={setObligationAmount} + /> +
+
+ + +
+
+ ) : null} + +
+ {loading ? ( +

{tCommon('loading')}

+ ) : !report || report.data.length === 0 ? ( +

{t('reportEmpty')}

+ ) : ( + + + + + + + + } + body={report.data.map((row) => ( + + + + + + + + ))} + /> + )} + + + {report ? ( +
+ {t('reportDebitTotal', { amount: formatMoney(report.totals.debit) })} + {t('reportCreditTotal', { amount: formatMoney(report.totals.credit) })} + + {t('reportNet', { amount: formatMoney(report.totals.net) })} + +
+ ) : null} + +
+ +
+ + + ); +} diff --git a/frontend/src/components/ui/billing/BillingPaymentsPanel.tsx b/frontend/src/components/ui/billing/BillingPaymentsPanel.tsx index 473ea0d..1e70f89 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, FileText, Paperclip, Search, X } from 'lucide-react'; import { labBlockedBannerClass } from '@/components/treatment/treatmentStatusStyles'; import { Button } from '@/components/ui/shared/Button'; import { Card } from '@/components/ui/shared/Card'; @@ -20,6 +20,7 @@ import { partySectionsFromSearch, type BillingPartySectionKey, } from '@/components/ui/billing/BillingPartyCombobox'; +import { BillingPartyReportDialog } from '@/components/ui/billing/BillingPartyReportDialog'; import { TableIconButton } from '@/components/ui/shared/TableIconButton'; import { FORM_SELECT_TALL_CLASS } from '@/components/shared/formSelectStyles'; import { moneyFieldLabel } from '@/components/billing/moneyFieldLabel'; @@ -91,6 +92,7 @@ export function BillingPaymentsPanel({ const [rows, setRows] = useState([]); const [net, setNet] = useState(null); const [formOpen, setFormOpen] = useState(false); + const [reportOpen, setReportOpen] = useState(false); const [txnType, setTxnType] = useState('RECEIPT'); const [amount, setAmount] = useState(''); @@ -138,9 +140,19 @@ export function BillingPaymentsPanel({ const load = useCallback(async () => { setLoading(true); 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); + setNet(report?.totals.net ?? res.net); } catch (error: unknown) { toast.showError(getUserFacingError(error, tErrors, t('errorLoadPayments'))); } finally { @@ -429,19 +441,41 @@ export function BillingPaymentsPanel({ /> } middle={ - +
+ + {filterParty ? ( + + ) : null} +
} /> + {reportOpen && filterParty ? ( + setReportOpen(false)} + /> + ) : null} + {formOpen && canEdit ? (

{t('addTransaction')}

@@ -667,7 +701,7 @@ export function BillingPaymentsPanel({ {row.acknowledgement === 'pending' && row.recordedByViewer ? ( {t('paymentPending')} ) : null} - {row.acknowledgement === 'rejected' && row.recordedByViewer ? ( + {row.acknowledgement === 'rejected' ? ( {t('paymentDeclined')} ) : null} {canEdit && row.canAcknowledge ? ( 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..cc661ca 100644 --- a/frontend/src/components/ui/billing/BillingSheetsPanel.tsx +++ b/frontend/src/components/ui/billing/BillingSheetsPanel.tsx @@ -138,6 +138,7 @@ export function BillingSheetsPanel({ targetClinicIds: [], targetUsers: [], targetClinics: [], + hideUnpricedTypes: false, lines: [], createdAt: '', updatedAt: '', 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/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}
- ) : null} -
- ) : null} - - {editingObligation ? ( -
-
- tCommon(`currencyName.${code}` as 'currencyName.TOMAN'), - )} - labelPlacement="outline" - value={obligationAmount} - onChange={setObligationAmount} - /> -
-
- - -
-
- ) : null} - -
- {loading ? ( -

{tCommon('loading')}

- ) : !report || report.data.length === 0 ? ( -

{t('reportEmpty')}

- ) : ( -
{t('time')}{t('reportSource')}{t('reference')}{t('debit')}{t('credit')}
{formatDateTime(row.occurredAt)} +
+ {t(SOURCE_LABEL_KEY[row.sourceType] as 'reportSourceTreatment')} + {row.acknowledgement === 'rejected' ? ( + + {t('paymentDeclined')} + + ) : null} + {row.amountPending ? ( + + {t('obligationAmountRequired')} + + ) : null} +
+
+
+ {row.reference || row.note || '—'} + {canEdit && row.canEditAmount ? ( + + ) : null} +
+
+ {row.direction === 'DEBIT' && row.amount != null + ? formatMoney(row.amount) + : '—'} + + {row.direction === 'CREDIT' && row.amount != null + ? formatMoney(row.amount) + : '—'} +
- - - - - - - } - body={report.data.map((row) => ( - - - - - - - - ))} - /> - )} - - - {report ? ( -
- {t('reportDebitTotal', { amount: formatMoney(report.totals.debit) })} - {t('reportCreditTotal', { amount: formatMoney(report.totals.credit) })} - - {t('reportNet', { amount: formatMoney(report.totals.net) })} - -
- ) : null} - -
- -
- - - ); -} diff --git a/frontend/src/components/ui/billing/BillingPaymentsPanel.tsx b/frontend/src/components/ui/billing/BillingPaymentsPanel.tsx index 1e70f89..4bf89da 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, FileText, 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,7 +20,10 @@ import { partySectionsFromSearch, type BillingPartySectionKey, } from '@/components/ui/billing/BillingPartyCombobox'; -import { BillingPartyReportDialog } from '@/components/ui/billing/BillingPartyReportDialog'; +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'; @@ -31,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'; @@ -57,6 +63,16 @@ 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 sectionToPartyKind(section: BillingPartySectionKey): BillingPartyKind { if (section === 'patients') return 'patient'; if (section === 'staff') return 'staff'; @@ -82,6 +98,11 @@ export function BillingPaymentsPanel({ [tCommon], ); const amountLabel = moneyFieldLabel(t('amount'), currencySettings.currency, currencyName); + const salaryLabel = moneyFieldLabel( + t('fixedMonthlySalary'), + currencySettings.currency, + currencyName, + ); const [loading, setLoading] = useState(true); const [query, setQuery] = useState(''); @@ -90,9 +111,21 @@ 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 [reportOpen, setReportOpen] = 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 [salary, setSalary] = useState(''); + const [salarySaving, setSalarySaving] = useState(false); const [txnType, setTxnType] = useState('RECEIPT'); const [amount, setAmount] = useState(''); @@ -139,6 +172,7 @@ export function BillingPaymentsPanel({ const load = useCallback(async () => { setLoading(true); + setReport(null); try { const [res, report] = await Promise.all([ billingApi.listTransactions(filters), @@ -152,7 +186,7 @@ export function BillingPaymentsPanel({ : Promise.resolve(null), ]); setRows(res.data); - setNet(report?.totals.net ?? res.net); + setReport(report); } catch (error: unknown) { toast.showError(getUserFacingError(error, tErrors, t('errorLoadPayments'))); } finally { @@ -160,6 +194,31 @@ export function BillingPaymentsPanel({ } }, [filters, t, tErrors, toast]); + useEffect(() => { + setEditingCash(null); + setEditingCashParty(null); + setEditingObligation(null); + setObligationAmount(''); + if (!filterParty || sectionToPartyKind(filterParty.section) !== 'staff') { + setSalary(''); + return; + } + let active = true; + void billingApi + .getStaffSalary(filterParty.id) + .then((response) => { + if (active) setSalary(response.data.fixedMonthlySalary); + }) + .catch((error: unknown) => { + if (active) { + toast.showError(getUserFacingError(error, tErrors, t('errorLoadSalary'))); + } + }); + return () => { + active = false; + }; + }, [filterParty, t, tErrors, toast]); + useEffect(() => { const handle = window.setTimeout(() => { void load(); @@ -315,10 +374,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'))); @@ -327,22 +390,89 @@ export function BillingPaymentsPanel({ } } + function startCashEdit( + row: { + id: string; + kind: 'patient' | 'partner' | 'staff'; + amount: string; + note: string | null; + updatedAt: string; + 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); + } + } + + async function saveSalary() { + if (!filterParty) return; + const parsed = parseAppMoney(salary); + if (parsed == null) { + toast.showError(t('invalidAmount')); + return; + } + setSalarySaving(true); + try { + const response = await billingApi.updateStaffSalary( + filterParty.id, + parsed, + ); + setSalary(response.data.fixedMonthlySalary); + toast.showSuccess(t('salarySaved')); + await load(); + } catch (error: unknown) { + toast.showError(getUserFacingError(error, tErrors, t('errorSaveSalary'))); + } finally { + setSalarySaving(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); @@ -441,7 +571,7 @@ export function BillingPaymentsPanel({ /> } middle={ -
+ !filterParty ? ( - {filterParty ? ( - - ) : null} -
+ ) : null } /> - {reportOpen && filterParty ? ( - setReportOpen(false)} - /> - ) : null} - {formOpen && canEdit ? (

{t('addTransaction')}

@@ -651,120 +761,415 @@ export function BillingPaymentsPanel({
) : null} + {filterParty && sectionToPartyKind(filterParty.section) === 'staff' ? ( + +
+
+ +
+ {canEdit ? ( + + ) : null} +
+
+
+

{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 ? ( +
{t('time')}{t('reportSource')}{t('reference')}{t('debit')}{t('credit')}
{formatDateTime(row.occurredAt)} -
- {t(SOURCE_LABEL_KEY[row.sourceType] as 'reportSourceTreatment')} - {row.acknowledgement === 'rejected' ? ( - - {t('paymentDeclined')} - - ) : null} - {row.amountPending ? ( - - {t('obligationAmountRequired')} - - ) : null} -
-
-
- {row.reference || row.note || '—'} - {canEdit && row.canEditAmount ? ( - - ) : null} -
-
- {row.direction === 'DEBIT' && row.amount != null - ? formatMoney(row.amount) - : '—'} - - {row.direction === 'CREDIT' && row.amount != null - ? formatMoney(row.amount) - : '—'} -
+ + + + + + + } + 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( + SOURCE_LABEL_KEY[ + row.sourceType + ] as 'reportSourceTreatment', + )} + + {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.amount == null ? '—' : formatMoney(row.amount)} + +
+ {canEdit && row.canEditCash && row.paymentKind && row.updatedAt ? ( + + startCashEdit( + { + id: row.sourceId, + kind: row.paymentKind!, + amount: row.amount ?? '0', + note: row.note, + updatedAt: row.updatedAt!, + 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/BillingTransactionEditor.tsx b/frontend/src/components/ui/billing/BillingTransactionEditor.tsx new file mode 100644 index 0000000..469e9be --- /dev/null +++ b/frontend/src/components/ui/billing/BillingTransactionEditor.tsx @@ -0,0 +1,260 @@ +'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; + 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 = + 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/shared/Table.tsx b/frontend/src/components/ui/shared/Table.tsx index 86f328f..d7a5595 100644 --- a/frontend/src/components/ui/shared/Table.tsx +++ b/frontend/src/components/ui/shared/Table.tsx @@ -26,13 +26,13 @@ export function Table({ headers, body, footer, className = '' }: TableProps) {
{body} + {footer ? ( + + {footer} + + ) : null}
{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' ? ( - {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, + 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} +
+
- {footer && ( -
- {footer} -
- )} ); } diff --git a/frontend/src/lib/api/billing.ts b/frontend/src/lib/api/billing.ts index a4963b0..638be43 100644 --- a/frontend/src/lib/api/billing.ts +++ b/frontend/src/lib/api/billing.ts @@ -17,6 +17,7 @@ import type { PaymentListQuery, ResolvedBillingLines, StaffPayment, + UpdatePaymentInput, UpsertBillingSheetInput, CashTransactionType, } from '@/types/billing'; @@ -192,6 +193,14 @@ export const billingApi = { return response.data; }, + updatePatientPayment: async ( + id: string, + body: UpdatePaymentInput, + ): Promise<{ success: boolean; data: PatientPayment }> => { + const response = await apiClient.put(`/billing/patient-payments/${id}`, body); + return response.data; + }, + listPartnerPayments: async ( query?: PaymentListQuery, ): Promise<{ success: boolean; data: PartnerPayment[] }> => { @@ -208,6 +217,14 @@ export const billingApi = { return response.data; }, + updatePartnerPayment: async ( + id: string, + body: UpdatePaymentInput, + ): Promise<{ success: boolean; data: PartnerPayment }> => { + const response = await apiClient.put(`/billing/partner-payments/${id}`, body); + return response.data; + }, + listStaffPayments: async ( query?: PaymentListQuery, ): Promise<{ success: boolean; data: StaffPayment[] }> => { @@ -224,12 +241,22 @@ export const billingApi = { return response.data; }, + updateStaffPayment: async ( + id: string, + body: UpdatePaymentInput, + ): Promise<{ success: boolean; data: StaffPayment }> => { + const response = await apiClient.put(`/billing/staff-payments/${id}`, body); + return response.data; + }, + acknowledgePartnerPayment: async ( id: string, decision: 'ACCEPT' | 'DECLINE', + expectedUpdatedAt: string, ): Promise<{ success: boolean; data: PartnerPayment }> => { const response = await apiClient.post(`/billing/partner-payments/${id}/acknowledge`, { decision, + expectedUpdatedAt, }); return response.data; }, diff --git a/frontend/src/types/billing.ts b/frontend/src/types/billing.ts index d6e7e06..ff9d371 100644 --- a/frontend/src/types/billing.ts +++ b/frontend/src/types/billing.ts @@ -99,13 +99,17 @@ export type BillingPartySearchResult = { export type StaffPayment = { id: string; + organizationId: string; userId: string | null; externalPartyName: string | null; partyName: string; amount: string; paidAt: string; note: string | null; + canEdit: boolean; + createdByUserId: string; createdAt: string; + updatedAt: string; }; export type PatientPaymentAllocation = { @@ -118,6 +122,7 @@ export type PatientPaymentAllocation = { export type PatientPayment = { id: string; + organizationId: string; patientId: string | null; externalPartyName?: string | null; patientName: string; @@ -125,9 +130,12 @@ export type PatientPayment = { amount: string; paidAt: string; note: string | null; + canEdit: boolean; remainder: string; allocations: PatientPaymentAllocation[]; + createdByUserId: string; createdAt: string; + updatedAt: string; }; export type PartnerPaymentAllocation = { @@ -143,15 +151,19 @@ export type BillingLedgerRow = { id: string; kind: 'patient' | 'partner' | 'staff'; type: CashTransactionType; + partyId: string | null; partyName: string; partyIsWalkIn: boolean; amount: string; paidAt: string; note: string | null; attachments: string[]; + allocations: Array<{ targetId: string; amount: string; label: string }>; acknowledgement: PaymentAcknowledgement; canAcknowledge: boolean; recordedByViewer: boolean; + canEdit: boolean; + updatedAt: string; }; export type BillingPartyReportRow = { @@ -175,6 +187,12 @@ export type BillingPartyReportRow = { reference: string; note: string | null; acknowledgement: PaymentAcknowledgement; + canAcknowledge?: boolean; + recordedByViewer?: boolean; + canEditCash?: boolean; + paymentKind?: 'patient' | 'partner' | 'staff'; + updatedAt?: string; + allocations?: Array<{ targetId: string; amount: string; label: string }>; countsInTotals: boolean; }; @@ -182,6 +200,11 @@ export type BillingPartyReport = { success: boolean; data: BillingPartyReportRow[]; totals: { debit: string; credit: string; net: string }; + staffCompensation: { + commission: string; + fixedSalary: string; + gross: string; + } | null; }; export type PartnerPayment = { @@ -191,7 +214,9 @@ export type PartnerPayment = { note: string | null; status: PartnerPaymentStatus; recordedBy: 'CLINIC' | 'LAB'; + recorderOrganizationId: string | null; recordedByViewer: boolean; + canEdit: boolean; acknowledgement: PaymentAcknowledgement; canAcknowledge: boolean; externalPartyName?: string | null; @@ -201,7 +226,9 @@ export type PartnerPayment = { toOrganizationName: string; remainder: string; allocations: PartnerPaymentAllocation[]; + createdByUserId: string; createdAt: string; + updatedAt: string; }; export type PaymentListQuery = { @@ -241,6 +268,13 @@ export type CreatePaymentInput = { allocations?: Array<{ targetId: string; amount: string }>; }; +export type UpdatePaymentInput = { + amount: string; + note?: string; + allocations?: Array<{ targetId: string; amount: string }>; + expectedUpdatedAt: string; +}; + export type BillingPriceLine = { catalogKind: BillingCatalogKind; catalogCode: string; -- 2.53.0.windows.1 From 8210e4f76dd448234a107a77d597a8d62ed36172 Mon Sep 17 00:00:00 2001 From: Admin Date: Wed, 11 Nov 2026 19:45:18 +0330 Subject: [PATCH 4/7] bugfix: transactions search bug fixed. search value can now be removed manually. --- .cursor/rules/billing.mdc | 2 +- .cursor/skills/billing/SKILL.md | 3 +- backend/package.json | 1 - backend/prisma/seed-billing-demo.ts | 450 ------------------ .../billing/billing-case-obligation.spec.ts | 64 +++ .../billing/billing-case-obligation.ts | 36 ++ .../src/modules/billing/billing.service.ts | 50 +- frontend/messages/en.json | 10 +- frontend/messages/fa.json | 10 +- frontend/messages/nl.json | 10 +- .../ui/billing/BillingPartyCombobox.tsx | 36 +- .../ui/billing/BillingPaymentsPanel.tsx | 130 +++-- frontend/src/types/billing.ts | 1 + 13 files changed, 288 insertions(+), 515 deletions(-) delete mode 100644 backend/prisma/seed-billing-demo.ts create mode 100644 backend/src/modules/billing/billing-case-obligation.spec.ts create mode 100644 backend/src/modules/billing/billing-case-obligation.ts diff --git a/.cursor/rules/billing.mdc b/.cursor/rules/billing.mdc index 2aa532f..8aab2b0 100644 --- a/.cursor/rules/billing.mdc +++ b/.cursor/rules/billing.mdc @@ -11,7 +11,7 @@ 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 signed Amount column, and an aligned balance footer. Staff selection also shows current fixed salary plus persisted commission/salary/gross subtotals. +- **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 also shows current fixed salary plus persisted commission/salary/gross subtotals. - **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:** `Membership.fixedMonthlySalary`; salary and commission are separate rows whose combined staff payable is their sum. Toman rollups use Jalali months; Dollar/Euro use Gregorian months. V1 has no attendance/proration; changing salary can affect the current generated period. diff --git a/.cursor/skills/billing/SKILL.md b/.cursor/skills/billing/SKILL.md index 93a5f93..d62968f 100644 --- a/.cursor/skills/billing/SKILL.md +++ b/.cursor/skills/billing/SKILL.md @@ -46,11 +46,10 @@ Keep chrome identical: `BillingListToolbar`, outline labels, `AppMoneyInput`, eq - Prefer `GET /billing/transactions` (merged rows). Optional `partyKind` + `partyId` filters server-side and returns signed `net` (RECEIPT +, PAYMENT −) for the footer. - `BillingLedgerEntry` stores **system obligations only**. `GET /billing/party-report` unions those rows with patient/partner/staff cash for one party and date range. In this party-account view, RECEIPT is credit (reduces receivable) and PAYMENT is debit (reduces payable). Pending partner cash counts only for its recorder; accepted cash counts for both; rejected cash stays visible to both but counts only for its recorder. -- The Transactions table is cash-only until a party is selected. Selection swaps the same table to party-report rows (Time, Source, Reference, signed Amount, Actions) and puts the net directly below Amount; do not restore a report dialog/button. +- 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. -- Run `npm run prisma:seed-billing-demo` for idempotent local report data. ## Fee / commission editor diff --git a/backend/package.json b/backend/package.json index afab2af..c9fa7af 100644 --- a/backend/package.json +++ b/backend/package.json @@ -22,7 +22,6 @@ "prisma:migrate": "prisma migrate dev", "prisma:deploy": "prisma migrate deploy", "prisma:seed": "prisma db seed", - "prisma:seed-billing-demo": "ts-node prisma/seed-billing-demo.ts", "prisma:reset-treatment": "ts-node prisma/reset-treatment-data.ts", "prisma:wipe-app-data": "ts-node prisma/wipe-app-data.ts", "prisma:regenerate-tasks": "ts-node prisma/regenerate-lab-tasks.ts", diff --git a/backend/prisma/seed-billing-demo.ts b/backend/prisma/seed-billing-demo.ts deleted file mode 100644 index fbf4ebc..0000000 --- a/backend/prisma/seed-billing-demo.ts +++ /dev/null @@ -1,450 +0,0 @@ -import { - BillingLedgerPartyKind, - BillingObligationSourceType, - LinkStatus, - PartnerPaymentRecordedBy, - PartnerPaymentStatus, - Prisma, - PrismaClient, -} from '@prisma/client'; -import * as bcrypt from 'bcrypt'; -import { staffBillingPeriodForDate } from '../src/modules/billing/staff-billing-period'; - -const prisma = new PrismaClient(); - -const IDS = { - treatment: '10000000-0000-4000-8000-000000000001', - labCase: '10000000-0000-4000-8000-000000000002', - patientPayment: '10000000-0000-4000-8000-000000000003', - partnerPayment: '10000000-0000-4000-8000-000000000004', - staffPayment: '10000000-0000-4000-8000-000000000005', - pendingLabCase: '10000000-0000-4000-8000-000000000006', -}; - -function money(value: number) { - return new Prisma.Decimal(value.toFixed(2)); -} - -async function main() { - let link = await prisma.organizationLink.findFirst({ - where: { status: LinkStatus.ACTIVE }, - include: { - organizationA: { include: { type: true } }, - organizationB: { include: { type: true } }, - }, - }); - if (!link) { - const [clinicType, labType, plan] = await Promise.all([ - prisma.organizationType.findUnique({ where: { name: 'CLINIC' } }), - prisma.organizationType.findUnique({ where: { name: 'LAB' } }), - prisma.plan.findUnique({ where: { name: 'base' } }), - ]); - if (!clinicType || !labType) { - throw new Error('Run npm run prisma:seed before the billing demo seed.'); - } - const passwordHash = await bcrypt.hash('Demo123!', 10); - async function ensureOrganization(type: { id: string }, label: 'Clinic' | 'Lab') { - const existing = await prisma.organization.findFirst({ - where: { typeId: type.id }, - include: { type: true }, - orderBy: { createdAt: 'asc' }, - }); - if (existing) return existing; - const email = `billing.demo.${label.toLowerCase()}@dyolink.local`; - const owner = await prisma.user.upsert({ - where: { email }, - create: { email, name: `Billing Demo ${label} Owner`, passwordHash }, - update: { passwordHash }, - }); - const organization = await prisma.organization.upsert({ - where: { - ownerId_name: { ownerId: owner.id, name: `Billing Demo ${label}` }, - }, - create: { - name: `Billing Demo ${label}`, - typeId: type.id, - ownerId: owner.id, - planId: plan?.id ?? null, - billingCurrency: 'TOMAN', - }, - update: { planId: plan?.id ?? null, billingCurrency: 'TOMAN' }, - include: { type: true }, - }); - const membership = await prisma.membership.upsert({ - where: { - userId_organizationId: { - userId: owner.id, - organizationId: organization.id, - }, - }, - create: { - userId: owner.id, - organizationId: organization.id, - isOwner: true, - isActive: true, - }, - update: { isOwner: true, isActive: true }, - }); - await prisma.organizationSeat.upsert({ - where: { membershipId: membership.id }, - create: { - organizationId: organization.id, - membershipId: membership.id, - kind: 'BASE', - endsAt: new Date(Date.UTC(2035, 0, 1)), - }, - update: { endsAt: new Date(Date.UTC(2035, 0, 1)) }, - }); - return organization; - } - const clinic = await ensureOrganization(clinicType, 'Clinic'); - const lab = await ensureOrganization(labType, 'Lab'); - const existingLink = await prisma.organizationLink.findFirst({ - where: { - OR: [ - { organizationAId: clinic.id, organizationBId: lab.id }, - { organizationAId: lab.id, organizationBId: clinic.id }, - ], - }, - }); - if (existingLink) { - await prisma.organizationLink.update({ - where: { id: existingLink.id }, - data: { status: LinkStatus.ACTIVE }, - }); - } else { - await prisma.organizationLink.create({ - data: { - organizationAId: clinic.id, - organizationBId: lab.id, - status: LinkStatus.ACTIVE, - sharedDataTypes: [], - }, - }); - } - link = await prisma.organizationLink.findFirst({ - where: { - status: LinkStatus.ACTIVE, - OR: [ - { organizationAId: clinic.id, organizationBId: lab.id }, - { organizationAId: lab.id, organizationBId: clinic.id }, - ], - }, - include: { - organizationA: { include: { type: true } }, - organizationB: { include: { type: true } }, - }, - }); - } - if (!link) throw new Error('Could not create the billing demo organization link.'); - const organizations = [link.organizationA, link.organizationB]; - const clinic = organizations.find((org) => org.type.name === 'CLINIC'); - const lab = organizations.find((org) => org.type.name === 'LAB'); - if (!clinic || !lab) { - throw new Error('The first active organization link must connect a clinic and a lab.'); - } - - const clinicMemberships = await prisma.membership.findMany({ - where: { organizationId: clinic.id, OR: [{ isOwner: true }, { isActive: true }] }, - orderBy: [{ isOwner: 'asc' }, { createdAt: 'asc' }], - }); - const provider = clinicMemberships[0]; - if (!provider) throw new Error('The clinic needs at least one active member.'); - - let patient = await prisma.patient.findFirst({ - where: { createdByOrganizationId: clinic.id, isWalkIn: false }, - orderBy: { createdAt: 'asc' }, - }); - patient ??= await prisma.patient.create({ - data: { - firstName: 'Billing', - lastName: 'Demo Patient', - identification: `billing-demo-${clinic.id}`, - mobile: '0000000000', - createdByOrganizationId: clinic.id, - }, - }); - - const now = new Date(); - const staffPeriod = staffBillingPeriodForDate( - now, - clinic.billingCurrency ?? 'TOMAN', - ); - const treatment = await prisma.treatment.upsert({ - where: { id: IDS.treatment }, - create: { - id: IDS.treatment, - organizationId: clinic.id, - patientId: patient.id, - providerUserId: provider.userId, - title: 'Billing demo treatment', - treatmentAt: now, - calculatedAmount: money(1_500_000), - billedAmount: money(1_500_000), - billedAmountManual: true, - }, - update: { - organizationId: clinic.id, - patientId: patient.id, - providerUserId: provider.userId, - billedAmount: money(1_500_000), - billedAmountManual: true, - }, - }); - const labCase = await prisma.labCase.upsert({ - where: { id: IDS.labCase }, - create: { - id: IDS.labCase, - treatmentId: treatment.id, - destinationOrganizationId: lab.id, - sentAt: now, - externalCode: 'BILLING-DEMO', - patientDisplayName: `${patient.firstName} ${patient.lastName}`.trim(), - calculatedAmount: money(800_000), - billedAmount: money(800_000), - }, - update: { - treatmentId: treatment.id, - destinationOrganizationId: lab.id, - sentAt: now, - billedAmount: money(800_000), - }, - }); - const pendingLabCase = await prisma.labCase.upsert({ - where: { id: IDS.pendingLabCase }, - create: { - id: IDS.pendingLabCase, - treatmentId: treatment.id, - destinationOrganizationId: lab.id, - sentAt: now, - externalCode: 'BILLING-PENDING', - patientDisplayName: `${patient.firstName} ${patient.lastName}`.trim(), - calculatedAmount: money(0), - billedAmount: null, - billedAmountManual: false, - }, - update: { - treatmentId: treatment.id, - destinationOrganizationId: lab.id, - sentAt: now, - calculatedAmount: money(0), - billedAmount: null, - billedAmountManual: false, - }, - }); - - await prisma.organization.updateMany({ - where: { id: { in: [clinic.id, lab.id] }, billingCurrency: null }, - data: { billingCurrency: 'TOMAN' }, - }); - await prisma.membership.update({ - where: { id: provider.id }, - data: { fixedMonthlySalary: money(12_000_000) }, - }); - await prisma.commissionEarning.upsert({ - where: { - treatmentId_catalogCode: { - treatmentId: treatment.id, - catalogCode: 'billing_demo_commission', - }, - }, - create: { - organizationId: clinic.id, - userId: provider.userId, - treatmentId: treatment.id, - catalogCode: 'billing_demo_commission', - baseAmount: money(250_000), - percent: money(0), - qty: money(1), - earnedAmount: money(250_000), - earnedAt: now, - }, - update: { earnedAmount: money(250_000), earnedAt: now }, - }); - - const obligations = [ - { - organizationId: clinic.id, - partyKind: BillingLedgerPartyKind.PATIENT, - partyId: patient.id, - sourceType: BillingObligationSourceType.TREATMENT_APPROVE, - sourceId: treatment.id, - amount: 1_500_000, - sign: 1, - occurredAt: now, - }, - { - organizationId: clinic.id, - partyKind: BillingLedgerPartyKind.ORGANIZATION, - partyId: lab.id, - sourceType: BillingObligationSourceType.LAB_CASE, - sourceId: labCase.id, - amount: 800_000, - sign: -1, - occurredAt: now, - }, - { - organizationId: lab.id, - partyKind: BillingLedgerPartyKind.ORGANIZATION, - partyId: clinic.id, - sourceType: BillingObligationSourceType.LAB_CASE, - sourceId: labCase.id, - amount: 800_000, - sign: 1, - occurredAt: now, - }, - { - organizationId: clinic.id, - partyKind: BillingLedgerPartyKind.STAFF, - partyId: provider.userId, - sourceType: BillingObligationSourceType.STAFF_COMMISSION_MONTH, - sourceId: `${provider.userId}:${staffPeriod.key}:commission`, - amount: 250_000, - sign: -1, - occurredAt: staffPeriod.start, - }, - { - organizationId: clinic.id, - partyKind: BillingLedgerPartyKind.STAFF, - partyId: provider.userId, - sourceType: BillingObligationSourceType.STAFF_SALARY_MONTH, - sourceId: `${provider.userId}:${staffPeriod.key}:salary`, - amount: 12_000_000, - sign: -1, - occurredAt: staffPeriod.start, - }, - ]; - for (const row of obligations) { - const { sign, amount, ...entry } = row; - await prisma.billingLedgerEntry.upsert({ - where: { - organizationId_sourceType_sourceId: { - organizationId: entry.organizationId, - sourceType: entry.sourceType, - sourceId: entry.sourceId, - }, - }, - create: { - ...entry, - amount: money(amount), - signedAmount: money(amount * sign), - balanceSign: sign, - }, - update: { - partyKind: entry.partyKind, - partyId: entry.partyId, - amount: money(amount), - signedAmount: money(amount * sign), - balanceSign: sign, - occurredAt: entry.occurredAt, - }, - }); - } - for (const row of [ - { - organizationId: clinic.id, - partyId: lab.id, - sign: -1, - }, - { - organizationId: lab.id, - partyId: clinic.id, - sign: 1, - }, - ]) { - await prisma.billingLedgerEntry.upsert({ - where: { - organizationId_sourceType_sourceId: { - organizationId: row.organizationId, - sourceType: BillingObligationSourceType.LAB_CASE, - sourceId: pendingLabCase.id, - }, - }, - create: { - organizationId: row.organizationId, - partyKind: BillingLedgerPartyKind.ORGANIZATION, - partyId: row.partyId, - sourceType: BillingObligationSourceType.LAB_CASE, - sourceId: pendingLabCase.id, - amount: null, - signedAmount: null, - balanceSign: row.sign, - occurredAt: now, - }, - update: { - partyId: row.partyId, - amount: null, - signedAmount: null, - balanceSign: row.sign, - occurredAt: now, - }, - }); - } - - await prisma.patientPayment.upsert({ - where: { id: IDS.patientPayment }, - create: { - id: IDS.patientPayment, - organizationId: clinic.id, - patientId: patient.id, - amount: money(500_000), - paidAt: now, - note: 'Billing demo patient receipt', - createdByUserId: provider.userId, - }, - update: { patientId: patient.id, amount: money(500_000), paidAt: now }, - }); - await prisma.partnerPayment.upsert({ - where: { id: IDS.partnerPayment }, - create: { - id: IDS.partnerPayment, - fromOrganizationId: clinic.id, - toOrganizationId: lab.id, - amount: money(300_000), - paidAt: now, - note: 'Billing demo partner payment', - status: PartnerPaymentStatus.CONFIRMED, - recordedBy: PartnerPaymentRecordedBy.CLINIC, - recorderOrganizationId: clinic.id, - receiptConfirmedAt: now, - createdByUserId: provider.userId, - }, - update: { - fromOrganizationId: clinic.id, - toOrganizationId: lab.id, - amount: money(300_000), - paidAt: now, - status: PartnerPaymentStatus.CONFIRMED, - recordedBy: PartnerPaymentRecordedBy.CLINIC, - recorderOrganizationId: clinic.id, - receiptConfirmedAt: now, - receiptRejectedAt: null, - }, - }); - await prisma.staffPayment.upsert({ - where: { id: IDS.staffPayment }, - create: { - id: IDS.staffPayment, - organizationId: clinic.id, - userId: provider.userId, - amount: money(5_000_000), - paidAt: now, - note: 'Billing demo salary payment', - createdByUserId: provider.userId, - }, - update: { userId: provider.userId, amount: money(5_000_000), paidAt: now }, - }); - - console.log(`Billing demo ready for clinic "${clinic.name}" and lab "${lab.name}".`); - console.log(`Patient: ${patient.firstName} ${patient.lastName}; staff user: ${provider.userId}`); - console.log('Pending amount case: BILLING-PENDING'); -} - -main() - .catch((error) => { - console.error(error); - process.exitCode = 1; - }) - .finally(async () => { - await prisma.$disconnect(); - }); 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.service.ts b/backend/src/modules/billing/billing.service.ts index dc47414..37411ab 100644 --- a/backend/src/modules/billing/billing.service.ts +++ b/backend/src/modules/billing/billing.service.ts @@ -92,6 +92,7 @@ import { staffBillingPeriodsBetween, } from './staff-billing-period'; import { resolvePartnerCashSides } from './billing-cash-edit'; +import { resolvePartnerCaseObligation } from './billing-case-obligation'; type PaymentListQuery = { q?: string; @@ -760,7 +761,12 @@ export class BillingService implements OnModuleInit, OnModuleDestroy { caseIds.length ? this.prisma.labCase.findMany({ where: { id: { in: caseIds } }, - select: { id: true, externalCode: true, patientDisplayName: true }, + select: { + id: true, + origin: true, + externalCode: true, + patientDisplayName: true, + }, }) : Promise.resolve([]), ]); @@ -773,6 +779,9 @@ export class BillingService implements OnModuleInit, OnModuleDestroy { [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) => { @@ -792,6 +801,9 @@ export class BillingService implements OnModuleInit, OnModuleDestroy { 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) ?? @@ -2310,30 +2322,34 @@ export class BillingService implements OnModuleInit, OnModuleDestroy { parentLabCase: { select: { destinationOrganizationId: true } }, }, }); - if (!labCase?.destinationOrganizationId) return; + if (!labCase) return; - const sourceType = - labCase.origin === 'LAB_OUTSOURCE' - ? BillingObligationSourceType.OUTSOURCE_CASE - : BillingObligationSourceType.LAB_CASE; - const payerOrganizationId = - labCase.origin === 'LAB_OUTSOURCE' - ? labCase.parentLabCase?.destinationOrganizationId - : (labCase.treatment?.organizationId ?? labCase.partnerClinicOrganizationId); + 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 (!payerOrganizationId || payerOrganizationId === labCase.destinationOrganizationId) { + 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: payerOrganizationId, + organizationId: obligation.payerOrganizationId, partyKind: BillingLedgerPartyKind.ORGANIZATION, - partyId: labCase.destinationOrganizationId, - sourceType, + partyId: obligation.payeeOrganizationId, + sourceType: obligation.sourceType, sourceId: labCase.id, amount, keepPending: true, @@ -2341,10 +2357,10 @@ export class BillingService implements OnModuleInit, OnModuleDestroy { occurredAt, }); await this.upsertObligation(db, { - organizationId: labCase.destinationOrganizationId, + organizationId: obligation.payeeOrganizationId, partyKind: BillingLedgerPartyKind.ORGANIZATION, - partyId: payerOrganizationId, - sourceType, + partyId: obligation.payerOrganizationId, + sourceType: obligation.sourceType, sourceId: labCase.id, amount, keepPending: true, diff --git a/frontend/messages/en.json b/frontend/messages/en.json index f2fce69..ac099ad 100644 --- a/frontend/messages/en.json +++ b/frontend/messages/en.json @@ -1334,6 +1334,7 @@ "noPayments": "No transactions yet.", "searchPayments": "Search transactions", "filterByParty": "Filter by party", + "clearPartyFilter": "Clear selected party", "typeFilterAll": "All types", "dateFrom": "From", "dateTo": "To", @@ -1386,8 +1387,13 @@ "reference": "Reference", "reportEmpty": "No debit or credit rows match this period.", "reportSourceTreatment": "Approved treatment", - "reportSourceLabCase": "Lab case fee", - "reportSourceOutsource": "Outsourced case fee", + "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", diff --git a/frontend/messages/fa.json b/frontend/messages/fa.json index 8e93d73..625aa1c 100644 --- a/frontend/messages/fa.json +++ b/frontend/messages/fa.json @@ -1335,6 +1335,7 @@ "noPayments": "هنوز تراکنشی نیست.", "searchPayments": "جستجوی تراکنش‌ها", "filterByParty": "فیلتر بر اساس طرف", + "clearPartyFilter": "پاک کردن طرف انتخاب‌شده", "typeFilterAll": "همه انواع", "dateFrom": "از", "dateTo": "تا", @@ -1387,8 +1388,13 @@ "reference": "مرجع", "reportEmpty": "در این بازه هیچ ردیف بدهکار یا بستانکاری وجود ندارد.", "reportSourceTreatment": "درمان تأییدشده", - "reportSourceLabCase": "هزینه پرونده لابراتوار", - "reportSourceOutsource": "هزینه پرونده برون‌سپاری", + "reportSourceLabCase": "هزینه پرونده", + "reportSourceReceivedCase": "پرونده دریافتی", + "reportSourceGeneratedCase": "پرونده ایجادشده", + "reportSourceOutsource": "پرونده برون‌سپاری", + "caseOriginReceived": "دریافتی", + "caseOriginGenerated": "ایجادشده", + "caseOriginOutsourced": "از لابراتوار", "reportSourceCommission": "کمیسیون ماهانه", "reportSourceSalary": "حقوق ماهانه", "reportSourceCashReceipt": "دریافت نقدی", diff --git a/frontend/messages/nl.json b/frontend/messages/nl.json index 54ab2ed..224b8ad 100644 --- a/frontend/messages/nl.json +++ b/frontend/messages/nl.json @@ -1334,6 +1334,7 @@ "noPayments": "Nog geen transacties.", "searchPayments": "Transacties zoeken", "filterByParty": "Filter op partij", + "clearPartyFilter": "Geselecteerde partij wissen", "typeFilterAll": "Alle types", "dateFrom": "Van", "dateTo": "Tot", @@ -1386,8 +1387,13 @@ "reference": "Referentie", "reportEmpty": "Geen debet- of creditregels in deze periode.", "reportSourceTreatment": "Goedgekeurde behandeling", - "reportSourceLabCase": "Labcase-tarief", - "reportSourceOutsource": "Uitbesteed case-tarief", + "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", diff --git a/frontend/src/components/ui/billing/BillingPartyCombobox.tsx b/frontend/src/components/ui/billing/BillingPartyCombobox.tsx index e2e6f07..e672bb6 100644 --- a/frontend/src/components/ui/billing/BillingPartyCombobox.tsx +++ b/frontend/src/components/ui/billing/BillingPartyCombobox.tsx @@ -1,6 +1,13 @@ 'use client'; -import { useEffect, useId, useState, type ReactNode } from 'react'; +import { + useEffect, + useId, + useRef, + useState, + type ReactNode, +} from 'react'; +import { X } from 'lucide-react'; import { OutlineFieldLabel } from '@/components/ui/shared/OutlineFieldLabel'; import type { BillingPartySearchResult } from '@/types/billing'; @@ -29,6 +36,8 @@ export function BillingPartyCombobox({ labelPlacement = 'outline', icon, endIcon, + onClear, + clearLabel, }: { name: string; selectedId: string; @@ -41,10 +50,14 @@ export function BillingPartyCombobox({ labelPlacement?: 'outline' | 'none'; icon?: ReactNode; endIcon?: ReactNode; + onClear?: () => void; + clearLabel?: string; }) { const [open, setOpen] = useState(false); const inputId = useId(); + const inputRef = useRef(null); const outline = Boolean(label) && labelPlacement === 'outline'; + const showClear = Boolean(selectedId && onClear); useEffect(() => { onQueryChange?.(name); @@ -65,10 +78,11 @@ export function BillingPartyCombobox({ ) : null} setOpen(true)} @@ -88,11 +102,27 @@ export function BillingPartyCombobox({ }); }} /> - {endIcon ? ( + {endIcon && !showClear ? (
{endIcon}
) : null} + {showClear ? ( + + ) : 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 4bf89da..a048f4a 100644 --- a/frontend/src/components/ui/billing/BillingPaymentsPanel.tsx +++ b/frontend/src/components/ui/billing/BillingPaymentsPanel.tsx @@ -73,6 +73,28 @@ const SOURCE_LABEL_KEY: Record = { 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'; @@ -228,6 +250,7 @@ export function BillingPaymentsPanel({ useEffect(() => { if (!formOpen) return; + let active = true; const handle = window.setTimeout(() => { void (async () => { try { @@ -235,24 +258,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 { @@ -290,13 +319,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(() => { @@ -560,6 +592,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) { @@ -899,12 +936,20 @@ export function BillingPaymentsPanel({
    - {t( - SOURCE_LABEL_KEY[ - row.sourceType - ] as 'reportSourceTreatment', - )} + {t(reportSourceKey(row) as 'reportSourceTreatment')} + {caseOriginLabelKey(row.caseOrigin) ? ( + + {t(caseOriginLabelKey(row.caseOrigin)!)} + + ) : null} {row.acknowledgement === 'pending' ? ( {t('paymentPending')} @@ -927,20 +972,35 @@ export function BillingPaymentsPanel({ ) : null}
    - - {row.reference || row.note || '—'} + +
    +

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

    + {row.note ? ( +

    + {row.note} +

    + ) : null} +
    - - {row.amount == null ? '—' : formatMoney(row.amount)} + +
    + + {row.amount == null ? '—' : formatMoney(row.amount)} + + + {row.direction === 'DEBIT' + ? t('debit') + : t('credit')} + +
    @@ -1024,14 +1084,14 @@ export function BillingPaymentsPanel({ ) } footer={ - + {t('balanceTotal')} - + {formatMoney(report.totals.net)} diff --git a/frontend/src/types/billing.ts b/frontend/src/types/billing.ts index ff9d371..0e28987 100644 --- a/frontend/src/types/billing.ts +++ b/frontend/src/types/billing.ts @@ -184,6 +184,7 @@ export type BillingPartyReportRow = { | 'CASH_RECEIPT' | 'CASH_PAYMENT'; sourceId: string; + caseOrigin?: 'CLINIC_DISPATCH' | 'LAB_INTERNAL' | 'LAB_OUTSOURCE' | null; reference: string; note: string | null; acknowledgement: PaymentAcknowledgement; -- 2.53.0.windows.1 From 836fde45cfec782794b6c7f6f74a2fdc1cfc7a54 Mon Sep 17 00:00:00 2001 From: Admin Date: Wed, 11 Nov 2026 20:36:22 +0330 Subject: [PATCH 5/7] improvements: code reviewed, some issues fixed. --- .../src/modules/billing/billing.service.ts | 257 +++++++++++------- .../modules/billing/calculate-amounts.spec.ts | 63 +++++ .../src/modules/billing/calculate-amounts.ts | 61 +++++ frontend/messages/en.json | 1 + frontend/messages/fa.json | 1 + frontend/messages/nl.json | 1 + .../ui/billing/BillingPaymentsPanel.tsx | 10 +- .../ui/billing/BillingTransactionEditor.tsx | 2 + .../src/components/ui/lab/CaseDetailPanel.tsx | 4 +- .../src/components/ui/lab/CaseSendDialog.tsx | 16 +- frontend/src/lib/api/billing.ts | 2 +- frontend/src/types/billing.ts | 3 + 12 files changed, 316 insertions(+), 105 deletions(-) diff --git a/backend/src/modules/billing/billing.service.ts b/backend/src/modules/billing/billing.service.ts index 37411ab..6d1e2e0 100644 --- a/backend/src/modules/billing/billing.service.ts +++ b/backend/src/modules/billing/billing.service.ts @@ -48,12 +48,13 @@ import { calculateClinicDetailAmount, calculateCommissionEarned, calculateLabCaseAmount, - calculateOutsourceStepsAmount, commissionQtyForTask, INTRAORAL_SCAN_STEP, + outsourceChargeAmount, outsourceQuoteBasis, preferNonEmptyJobs, roundBillingAmount, + unpricedProsthesisCodes, type BillingPriceLine, type ProsthesisQtyMeta, } from './calculate-amounts'; @@ -214,18 +215,17 @@ export class BillingService implements OnModuleInit, OnModuleDestroy { }); } - const periodSourceIds = [ - ...commissionSums.map((row) => `${row.userId}:${period.key}:commission`), - ...memberships.map((row) => `${row.userId}:${period.key}:salary`), - ]; + const commissionIds = commissionSums.map( + (row) => `${row.userId}:${period.key}:commission`, + ); + const salaryIds = memberships.map( + (row) => `${row.userId}:${period.key}:salary`, + ); await tx.billingLedgerEntry.deleteMany({ where: { organizationId, sourceType: BillingObligationSourceType.STAFF_COMMISSION_MONTH, - sourceId: { - endsWith: `:${period.key}:commission`, - notIn: periodSourceIds, - }, + sourceId: stalePeriodSourceFilter(`:${period.key}:commission`, commissionIds), }, }); if (includeCurrentSalary) { @@ -233,10 +233,7 @@ export class BillingService implements OnModuleInit, OnModuleDestroy { where: { organizationId, sourceType: BillingObligationSourceType.STAFF_SALARY_MONTH, - sourceId: { - endsWith: `:${period.key}:salary`, - notIn: periodSourceIds, - }, + sourceId: stalePeriodSourceFilter(`:${period.key}:salary`, salaryIds), }, }); } @@ -633,6 +630,7 @@ export class BillingService implements OnModuleInit, OnModuleDestroy { canAcknowledge: false, recordedByViewer: true, canEdit: row.canEdit, + canAllocate: Boolean(row.patientId), updatedAt: row.updatedAt, })), ...partners.map((row) => { @@ -660,6 +658,7 @@ export class BillingService implements OnModuleInit, OnModuleDestroy { canAcknowledge: row.canAcknowledge, recordedByViewer: row.recordedByViewer, canEdit: row.canEdit, + canAllocate: row.canAllocate, updatedAt: row.updatedAt, }; }), @@ -679,6 +678,7 @@ export class BillingService implements OnModuleInit, OnModuleDestroy { canAcknowledge: false, recordedByViewer: true, canEdit: row.canEdit, + canAllocate: false, updatedAt: row.updatedAt, })), ].sort((a, b) => b.paidAt.localeCompare(a.paidAt)); @@ -810,6 +810,7 @@ export class BillingService implements OnModuleInit, OnModuleDestroy { staffPeriodReference(row.sourceId), note: row.note, acknowledgement: 'none' as const, + canAllocate: false, countsInTotals: amount != null, }; }), @@ -834,6 +835,7 @@ export class BillingService implements OnModuleInit, OnModuleDestroy { canAcknowledge: row.canAcknowledge, recordedByViewer: row.recordedByViewer, canEditCash: row.canEdit, + canAllocate: row.canAllocate, paymentKind: row.kind, updatedAt: row.updatedAt, allocations: row.allocations, @@ -1848,30 +1850,26 @@ export class BillingService implements OnModuleInit, OnModuleDestroy { 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( @@ -1974,41 +1972,41 @@ export class BillingService implements OnModuleInit, OnModuleDestroy { 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, @@ -2536,12 +2534,34 @@ export class BillingService implements OnModuleInit, OnModuleDestroy { 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 } } }, @@ -2558,23 +2578,63 @@ export class BillingService implements OnModuleInit, OnModuleDestroy { clinicOrganizationId, }); const metaByCode = await this.prosthesisMetaByCode(db); - const calculated = calculateLabCaseAmount({ - jobs: labCase.toothProsthesis.map((job) => ({ - tooth: job.tooth, - prosthesisTypeCode: job.prosthesisTypeCode, - })), + const childJobs = labCase.toothProsthesis.map((job) => ({ + tooth: job.tooth, + prosthesisTypeCode: job.prosthesisTypeCode, + })); + let calculated = calculateLabCaseAmount({ + jobs: childJobs, lines: resolvedSheet.lines, metaByCode, }); - const unpricedCodes = unpricedProsthesisCodes( - labCase.toothProsthesis, - resolvedSheet.lines, - ); + 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) - : unpricedCodes.length > 0 + : unpriced ? null : calculated; @@ -3150,22 +3210,10 @@ function stringList(value: unknown): string[] { return value.filter((item): item is string => typeof item === 'string'); } -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(); +function stalePeriodSourceFilter(suffix: string, keepIds: readonly string[]) { + return keepIds.length > 0 + ? { endsWith: suffix, notIn: [...keepIds] } + : { endsWith: suffix }; } function dateOnlyUtc(value: string): Date { @@ -3368,6 +3416,18 @@ function mapPatientPayment( }; } +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 }>, ) { @@ -3413,6 +3473,7 @@ function mapPartnerPayment( canEdit: sides.senderId === viewerOrganizationId && payment.recorderOrganizationId === viewerOrganizationId, + canAllocate: partnerCashCanAllocate(payment), acknowledgement, canAcknowledge: sides.counterpartyId === viewerOrganizationId && acknowledgement === 'pending', externalPartyName: payment.externalPartyName, 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/frontend/messages/en.json b/frontend/messages/en.json index ac099ad..db7d934 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...", diff --git a/frontend/messages/fa.json b/frontend/messages/fa.json index 625aa1c..9779c59 100644 --- a/frontend/messages/fa.json +++ b/frontend/messages/fa.json @@ -558,6 +558,7 @@ "sendToExocadCloseHint": "پیش از ارسال Exocad را ببندید. بعد از ارسال آن را دوباره باز کنید تا پرونده را ببینید.", "sendCaseTitle": "مراحل برون سپاری", "outsourcePrice": "قیمت برون‌سپاری", + "outsourcePricePending": "این برون‌سپاری شامل کار بدون تعرفه است. ارسال مجاز است، اما لابراتوار مقصد باید مبلغ نهایی را در بخش مالی ثبت کند.", "sendCaseSelectAll": "انتخاب همه", "sendCaseLab": "لابراتوار", "sendCaseLabsLoading": "در حال بارگذاری لابراتوارها...", diff --git a/frontend/messages/nl.json b/frontend/messages/nl.json index 224b8ad..6a01e21 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...", diff --git a/frontend/src/components/ui/billing/BillingPaymentsPanel.tsx b/frontend/src/components/ui/billing/BillingPaymentsPanel.tsx index a048f4a..3171181 100644 --- a/frontend/src/components/ui/billing/BillingPaymentsPanel.tsx +++ b/frontend/src/components/ui/billing/BillingPaymentsPanel.tsx @@ -178,7 +178,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( @@ -429,6 +432,7 @@ export function BillingPaymentsPanel({ amount: string; note: string | null; updatedAt: string; + canAllocate: boolean; allocations: Array<{ targetId: string; amount: string; label: string }>; }, party: { kind: BillingPartyKind; id: string } | null, @@ -533,7 +537,7 @@ export function BillingPaymentsPanel({ userId: staffSelected ? selectedParty!.id : undefined, externalPartyName: localParty ? typedParty : undefined, allocations: - localParty || staffSelected + localParty || staffSelected || !canAttach ? [] : allocations .map((row) => { @@ -1015,6 +1019,7 @@ export function BillingPaymentsPanel({ amount: row.amount ?? '0', note: row.note, updatedAt: row.updatedAt!, + canAllocate: Boolean(row.canAllocate), allocations: row.allocations ?? [], }, { @@ -1185,6 +1190,7 @@ export function BillingPaymentsPanel({ amount: row.amount, note: row.note, updatedAt: row.updatedAt, + canAllocate: row.canAllocate, allocations: row.allocations, }, row.partyId diff --git a/frontend/src/components/ui/billing/BillingTransactionEditor.tsx b/frontend/src/components/ui/billing/BillingTransactionEditor.tsx index 469e9be..4d88d53 100644 --- a/frontend/src/components/ui/billing/BillingTransactionEditor.tsx +++ b/frontend/src/components/ui/billing/BillingTransactionEditor.tsx @@ -22,6 +22,7 @@ export type EditableCashTransaction = { amount: string; note: string | null; updatedAt: string; + canAllocate: boolean; allocations: Array<{ targetId: string; amount: string; label: string }>; }; @@ -53,6 +54,7 @@ export function BillingTransactionEditor({ 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')); 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}
    + {canEdit && secondaryAddLabel && onSecondaryAdd ? ( + + ) : null} {canEdit ? ( - ) : null} -

    {t('commissionSubtotal')}

    diff --git a/frontend/src/components/ui/billing/BillingSheetsPanel.tsx b/frontend/src/components/ui/billing/BillingSheetsPanel.tsx index cc661ca..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: '', @@ -165,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({ @@ -199,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')}

    + + + + + + } + 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/lib/api/billing.ts b/frontend/src/lib/api/billing.ts index c8b8de2..1bd832b 100644 --- a/frontend/src/lib/api/billing.ts +++ b/frontend/src/lib/api/billing.ts @@ -12,6 +12,8 @@ import type { BillingSheetKind, BillingSheetTargets, CreatePaymentInput, + StaffSalaryLine, + StaffSalarySheet, PartnerPayment, PatientPayment, PaymentListQuery, @@ -124,20 +126,15 @@ export const billingApi = { return response.data; }, - getStaffSalary: async ( - userId: string, - ): Promise<{ success: boolean; data: { fixedMonthlySalary: string } }> => { - const response = await apiClient.get(`/billing/staff/${userId}/salary`); + getStaffSalarySheet: async (): Promise<{ success: boolean; data: StaffSalarySheet }> => { + const response = await apiClient.get('/billing/staff-salaries'); return response.data; }, - updateStaffSalary: async ( - userId: string, - fixedMonthlySalary: string, - ): Promise<{ success: boolean; data: { fixedMonthlySalary: string } }> => { - const response = await apiClient.put(`/billing/staff/${userId}/salary`, { - fixedMonthlySalary, - }); + saveStaffSalarySheet: async ( + lines: Array>, + ): Promise<{ success: boolean; data: StaffSalarySheet }> => { + const response = await apiClient.put('/billing/staff-salaries', { lines }); return response.data; }, diff --git a/frontend/src/types/billing.ts b/frontend/src/types/billing.ts index 14b9e77..f1110d8 100644 --- a/frontend/src/types/billing.ts +++ b/frontend/src/types/billing.ts @@ -50,6 +50,17 @@ export type BillingSheetTargets = { clinics: BillingNamedTarget[]; }; +export type StaffSalaryLine = { + userId: string; + name: string; + fixedMonthlySalary: string; +}; + +export type StaffSalarySheet = { + updatedAt: string | null; + lines: StaffSalaryLine[]; +}; + export type UpsertBillingSheetInput = { kind: BillingSheetKind; name?: string; -- 2.53.0.windows.1 From 3198eae47bac3793df060232b20eb2514f60bc02 Mon Sep 17 00:00:00 2001 From: Admin Date: Wed, 11 Nov 2026 23:12:07 +0330 Subject: [PATCH 7/7] improvements: a data migration added for prod deployment. --- .cursor/rules/billing.mdc | 2 +- .cursor/rules/dyolink-overview.mdc | 2 +- .cursor/skills/billing/SKILL.md | 2 +- AGENTS.md | 4 +- .../migration.sql | 25 ++++++++ .../src/modules/billing/billing.service.ts | 58 ++++++------------- 6 files changed, 48 insertions(+), 45 deletions(-) create mode 100644 backend/prisma/migrations/20261111233000_sheet_flag_and_subscription_courtesy/migration.sql diff --git a/.cursor/rules/billing.mdc b/.cursor/rules/billing.mdc index 5d7f95d..656ef9a 100644 --- a/.cursor/rules/billing.mdc +++ b/.cursor/rules/billing.mdc @@ -15,7 +15,7 @@ alwaysApply: false - **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`. 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. +- **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 c5de2c9..4f11f2b 100644 --- a/.cursor/skills/billing/SKILL.md +++ b/.cursor/skills/billing/SKILL.md @@ -54,7 +54,7 @@ Keep chrome identical: `BillingListToolbar`, outline labels, `AppMoneyInput`, eq ## Fee / commission editor - Start date required. Empty Apply-to = everyone. Lines store money `amount`. -- `CLINIC_PRICE` / `LAB_PRICE` may set `hideUnpricedTypes`. Missing or zero prosthesis lines are hidden from the applicable chart. A destination lab's active flagged sheet also blocks clinic Send. +- `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. diff --git a/AGENTS.md b/AGENTS.md index 69eb479..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**. 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; an active flagged lab sheet blocks clinic dispatch for unsupported jobs. If the flag is off, an unpriced case creates mirrored amount-pending obligations; only the destination lab sets the fee and it updates both orgs. Collapsed workflow prices and hidden legacy lines remain preserved. Money inputs: `AppMoneyInput`. See `.cursor/rules/billing.mdc`, `.cursor/skills/billing/SKILL.md`. +**Billing (quick ref):** Same three-tab hub for CLINIC + LAB (`/billing?view=`). Clinic: `CLINIC_PRICE` / `CLINIC_COMMISSION` + patient receipts + partner payments. Lab: `LAB_PRICE` (prosthesis fees plus an outsourcing tab) / `LAB_COMMISSION` + partner ledger only. Commissions are **fixed amounts**. Automatic `BillingLedgerEntry` obligations come from treatment Approve, 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/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/src/modules/billing/billing.service.ts b/backend/src/modules/billing/billing.service.ts index 668762a..503ceb5 100644 --- a/backend/src/modules/billing/billing.service.ts +++ b/backend/src/modules/billing/billing.service.ts @@ -293,47 +293,25 @@ export class BillingService implements OnModuleInit, OnModuleDestroy { select: { userId: true, fixedMonthlySalary: true }, }); const occurredAt = staffPeriodLastDay(period); - await this.prisma.$transaction(async (tx) => { - for (const membership of memberships) { - const amount = roundBillingAmount(Number(membership.fixedMonthlySalary ?? 0)); - if (amount <= 0) continue; - const sourceId = `${membership.userId}:${period.key}:salary`; - const existing = await tx.billingLedgerEntry.findUnique({ - where: { - organizationId_sourceType_sourceId: { - organizationId, - sourceType: BillingObligationSourceType.STAFF_SALARY_MONTH, - sourceId, - }, - }, - select: { id: true }, - }); - if (existing) continue; - try { - await tx.billingLedgerEntry.create({ - data: { - organizationId, - partyKind: BillingLedgerPartyKind.STAFF, - partyId: membership.userId, - sourceType: BillingObligationSourceType.STAFF_SALARY_MONTH, - sourceId, - amount: new Prisma.Decimal(amount.toFixed(2)), - signedAmount: new Prisma.Decimal((-amount).toFixed(2)), - balanceSign: -1, - occurredAt, - }, - }); - } catch (error) { - if ( - error instanceof Prisma.PrismaClientKnownRequestError && - error.code === 'P2002' - ) { - continue; - } - throw error; - } - } + 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( -- 2.53.0.windows.1
    {t('salaryUpdated')}{tCommon('name')}{tCommon('action')}
    + {formatTableDate(salarySheet.updatedAt)} + {t('staffSalarySection')} +
    + {canEdit ? ( + + + + ) : null} +
    +