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.

This commit is contained in:
2026-11-11 18:15:33 +03:30
parent 1c7c96950e
commit e7e107dc51
35 changed files with 2470 additions and 61 deletions

View File

@@ -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`).

View File

@@ -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

View File

@@ -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`.

View File

@@ -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",

View File

@@ -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;

View File

@@ -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');

View File

@@ -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"
)
);

View File

@@ -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")
}

View File

@@ -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();
});

View File

@@ -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',

View File

@@ -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' },
}),
];
}

View File

@@ -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',

View File

@@ -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(

File diff suppressed because it is too large Load Diff

View File

@@ -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()

View File

@@ -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)

View File

@@ -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);
});
});

View File

@@ -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;
}

View File

@@ -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']);
});
});

View File

@@ -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;
}

View File

@@ -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 },

View File

@@ -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;

View File

@@ -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."
}
}

View File

@@ -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": "فقط لابراتوار مقصد می‌تواند هزینه این پرونده را تعیین کند."
}
}

View File

@@ -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."
}
}

View File

@@ -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<BillingPartyReportRow['sourceType'], string> = {
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<BillingPartyReport | null>(null);
const [loading, setLoading] = useState(true);
const [reportEpoch, setReportEpoch] = useState(0);
const [salary, setSalary] = useState('');
const [salarySaving, setSalarySaving] = useState(false);
const [editingObligation, setEditingObligation] =
useState<BillingPartyReportRow | null>(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 (
<ResponsiveDialogOverlay onBackdropClick={onClose}>
<ResponsiveDialogPanel
role="dialog"
aria-modal="true"
aria-labelledby="billing-party-report-title"
maxWidthClass="sm:max-w-4xl"
>
<div className="flex items-start justify-between gap-3">
<div>
<h2 id="billing-party-report-title" className="text-lg font-semibold text-text-primary">
{t('debitCreditReport')}
</h2>
<p className="text-sm text-text-secondary">{party.name}</p>
</div>
<DialogCloseButton onClick={onClose} />
</div>
<div className="mt-5 grid grid-cols-1 gap-3 sm:grid-cols-2">
<AppDateInput
label={t('dateFrom')}
value={from}
onChange={setFrom}
defaultToToday={false}
/>
<AppDateInput
label={t('dateTo')}
value={to}
onChange={setTo}
defaultToToday={false}
/>
</div>
{party.kind === 'staff' ? (
<div className="mt-4 flex flex-col gap-2 rounded-[var(--radius-md)] border border-border/60 p-3 sm:flex-row sm:items-end">
<div className="min-w-0 flex-1">
<AppMoneyInput
label={salaryLabel}
labelPlacement="outline"
value={salary}
onChange={setSalary}
disabled={!canEdit}
/>
</div>
{canEdit ? (
<Button
variant="outline"
onClick={() => void saveSalary()}
isLoading={salarySaving}
>
{t('saveSalary')}
</Button>
) : null}
</div>
) : null}
{editingObligation ? (
<div className="mt-4 flex flex-col gap-2 rounded-[var(--radius-md)] border border-border/60 p-3 sm:flex-row sm:items-end">
<div className="min-w-0 flex-1">
<AppMoneyInput
label={moneyFieldLabel(
t('caseObligationAmount'),
currencySettings.currency,
(code) => tCommon(`currencyName.${code}` as 'currencyName.TOMAN'),
)}
labelPlacement="outline"
value={obligationAmount}
onChange={setObligationAmount}
/>
</div>
<div className="flex gap-2">
<Button
variant="outline"
onClick={() => {
setEditingObligation(null);
setObligationAmount('');
}}
>
{tCommon('cancel')}
</Button>
<Button
onClick={() => void saveObligationAmount()}
isLoading={obligationSaving}
>
{t('saveObligationAmount')}
</Button>
</div>
</div>
) : null}
<div className="mt-5">
{loading ? (
<p className="text-sm text-text-muted">{tCommon('loading')}</p>
) : !report || report.data.length === 0 ? (
<p className="text-sm text-text-muted">{t('reportEmpty')}</p>
) : (
<Table
headers={
<tr>
<th className={TABLE_HEADER_CELL_CLASS}>{t('time')}</th>
<th className={TABLE_HEADER_CELL_CLASS}>{t('reportSource')}</th>
<th className={TABLE_HEADER_CELL_CLASS}>{t('reference')}</th>
<th className={TABLE_HEADER_CELL_CLASS}>{t('debit')}</th>
<th className={TABLE_HEADER_CELL_CLASS}>{t('credit')}</th>
</tr>
}
body={report.data.map((row) => (
<tr key={row.id}>
<td className="text-sm text-text-secondary">{formatDateTime(row.occurredAt)}</td>
<td className="text-sm text-text-primary">
<div className="flex flex-wrap items-center gap-2">
<span>{t(SOURCE_LABEL_KEY[row.sourceType] as 'reportSourceTreatment')}</span>
{row.acknowledgement === 'rejected' ? (
<Badge variant="danger" fixedWidth={false}>
{t('paymentDeclined')}
</Badge>
) : null}
{row.amountPending ? (
<Badge variant="warning" fixedWidth={false}>
{t('obligationAmountRequired')}
</Badge>
) : null}
</div>
</td>
<td className="text-sm text-text-secondary">
<div className="flex flex-wrap items-center gap-2">
<span>{row.reference || row.note || '—'}</span>
{canEdit && row.canEditAmount ? (
<Button
size="sm"
variant="ghost"
onClick={() => {
setEditingObligation(row);
setObligationAmount(row.amount ?? '');
}}
>
{t('setObligationAmount')}
</Button>
) : null}
</div>
</td>
<td className="text-sm tabular-nums text-text-primary">
{row.direction === 'DEBIT' && row.amount != null
? formatMoney(row.amount)
: '—'}
</td>
<td className="text-sm tabular-nums text-text-primary">
{row.direction === 'CREDIT' && row.amount != null
? formatMoney(row.amount)
: '—'}
</td>
</tr>
))}
/>
)}
</div>
{report ? (
<div className="mt-4 flex flex-wrap justify-end gap-x-5 gap-y-1 text-sm tabular-nums">
<span>{t('reportDebitTotal', { amount: formatMoney(report.totals.debit) })}</span>
<span>{t('reportCreditTotal', { amount: formatMoney(report.totals.credit) })}</span>
<span className="font-semibold text-text-primary">
{t('reportNet', { amount: formatMoney(report.totals.net) })}
</span>
</div>
) : null}
<div className="mt-5 flex justify-end">
<Button variant="ghost" onClick={onClose}>
{tCommon('close')}
</Button>
</div>
</ResponsiveDialogPanel>
</ResponsiveDialogOverlay>
);
}

View File

@@ -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<BillingLedgerRow[]>([]);
const [net, setNet] = useState<string | null>(null);
const [formOpen, setFormOpen] = useState(false);
const [reportOpen, setReportOpen] = useState(false);
const [txnType, setTxnType] = useState<CashTransactionType>('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={
<select
className={BILLING_FILTER_SELECT_CLASS}
value={typeFilter}
onChange={(e) => setTypeFilter(e.target.value as TypeFilter)}
aria-label={t('type')}
>
<option value="ALL">{t('typeFilterAll')}</option>
<option value="RECEIPT">{t('receipt')}</option>
<option value="PAYMENT">{t('payment')}</option>
</select>
<div className="flex items-center gap-2">
<select
className={BILLING_FILTER_SELECT_CLASS}
value={typeFilter}
onChange={(e) => setTypeFilter(e.target.value as TypeFilter)}
aria-label={t('type')}
>
<option value="ALL">{t('typeFilterAll')}</option>
<option value="RECEIPT">{t('receipt')}</option>
<option value="PAYMENT">{t('payment')}</option>
</select>
{filterParty ? (
<Button variant="outline" size="sm" onClick={() => setReportOpen(true)}>
<FileText className="me-1.5 h-4 w-4" />
{t('debitCreditReport')}
</Button>
) : null}
</div>
}
/>
{reportOpen && filterParty ? (
<BillingPartyReportDialog
party={{
id: filterParty.id,
name: filterParty.name,
kind: sectionToPartyKind(filterParty.section),
}}
initialFrom={from}
initialTo={to}
canEdit={canEdit}
onClose={() => setReportOpen(false)}
/>
) : null}
{formOpen && canEdit ? (
<Card className="space-y-5">
<p className="text-sm font-medium text-text-primary">{t('addTransaction')}</p>
@@ -667,7 +701,7 @@ export function BillingPaymentsPanel({
{row.acknowledgement === 'pending' && row.recordedByViewer ? (
<span className="text-xs text-text-muted">{t('paymentPending')}</span>
) : null}
{row.acknowledgement === 'rejected' && row.recordedByViewer ? (
{row.acknowledgement === 'rejected' ? (
<span className="text-xs text-text-muted">{t('paymentDeclined')}</span>
) : null}
{canEdit && row.canAcknowledge ? (

View File

@@ -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<ValueMap>(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({
</div>
</div>
{priceSheet ? (
<div className="space-y-2">
<Checkbox
checked={hideUnpricedTypes}
disabled={!canEdit}
onChange={setHideUnpricedTypes}
label={t('hideUnpricedTypes')}
/>
{hideUnpricedTypes ? (
<p className="rounded-[var(--radius-md)] border border-sky-200 bg-sky-50 px-3 py-2 text-sm text-sky-900 dark:border-sky-900/60 dark:bg-sky-950/30 dark:text-sky-200">
{kind === 'LAB_PRICE'
? t('hideUnpricedTypesLabInfo')
: t('hideUnpricedTypesClinicInfo')}
</p>
) : null}
</div>
) : null}
{targetsOpen ? (
<div className="space-y-2 rounded-[var(--radius-md)] border border-border/60 p-3">
<p className="text-sm text-text-secondary">{applyToLabel}</p>

View File

@@ -138,6 +138,7 @@ export function BillingSheetsPanel({
targetClinicIds: [],
targetUsers: [],
targetClinics: [],
hideUnpricedTypes: false,
lines: [],
createdAt: '',
updatedAt: '',

View File

@@ -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<ProsthesisCatalogEntry[]>(
prosthesisCatalog ?? [],
);
const [hideUnpricedTypes, setHideUnpricedTypes] = useState(false);
const [pricedProsthesisCodes, setPricedProsthesisCodes] = useState<Set<string>>(
() => 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({
<VoiceReviewSheet
mode="lab"
result={voiceResult}
prosthesisCatalog={prosthesisOptions}
prosthesisCatalog={assignableProsthesisOptions}
onApply={(selection, applied) => applyVoice(selection, applied)}
onDiscard={() => onVoiceResultHandled?.()}
/>

View File

@@ -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<string | null>(null);
const [unsupportedCodes, setUnsupportedCodes] = useState<string[]>([]);
const [sendBlockedByPriceSheet, setSendBlockedByPriceSheet] = useState(false);
const [fetchedCatalog, setFetchedCatalog] = useState<ProsthesisCatalogEntry[]>([]);
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({
</span>
</p>
) : null}
{quoteLabId &&
unsupportedCodes.length > 0 &&
!sendBlockedByPriceSheet ? (
<p className={labBlockedBannerClass}>
{t('labFeeNeedsBillingAmount')}
</p>
) : null}
{sendBlockedByPriceSheet ? (
<p className={labBlockedBannerClass}>
{t('labDoesNotProvideTypes', {
types: unsupportedCodes
.map((code) => catalog.find((entry) => entry.code === code)?.label ?? code)
.join(', '),
})}
</p>
) : null}
<div className="flex flex-wrap items-center gap-3 pt-1">
<Button
@@ -489,7 +518,8 @@ export function LabCasesDispatchPanel({
!activeLabCase.destinationOrganizationId ||
!activeLabCase.detailClientId ||
!prosthesisComplete ||
!ponticBridgeOk
!ponticBridgeOk ||
sendBlockedByPriceSheet
}
isLoading={sendBusyId === activeLabCase.clientId}
onClick={() => onSendLabCase(activeLabCase, pendingComment.trim())}

View File

@@ -53,6 +53,7 @@ interface ProsthesisAssignChartProps {
toothProsthesis: LabCaseToothProsthesisDraft[];
detailClientId: string;
catalog: readonly ProsthesisCatalogEntry[];
pickerCatalog?: readonly ProsthesisCatalogEntry[];
disabled?: boolean;
className?: string;
headerControl?: ReactNode;
@@ -68,6 +69,7 @@ export function ProsthesisAssignChart({
toothProsthesis,
detailClientId,
catalog,
pickerCatalog,
disabled,
className,
headerControl,
@@ -143,6 +145,12 @@ export function ProsthesisAssignChart({
: anchor
? codesOnTooth(toothProsthesis, detailClientId, anchor)
: [];
const popoverCatalog = useMemo(() => {
if (!pickerCatalog) return catalog;
const available = new Set(pickerCatalog.map((entry) => entry.code));
const current = new Set(jobCodes);
return catalog.filter((entry) => available.has(entry.code) || current.has(entry.code));
}, [catalog, jobCodes, pickerCatalog]);
function groupIdForTooth(tooth: string, nextGroups: ToothSelectionGroup[]): string {
return nextGroups.find((g) => g.teeth.includes(tooth as FdiToothId))?.groupId ?? '';
@@ -415,7 +423,7 @@ export function ProsthesisAssignChart({
<ProsthesisJobPopover
open={open}
mobile={mobile}
catalog={catalog}
catalog={popoverCatalog}
step={step}
scope={scope}
lockedArch={scope === 'arch' ? lockedArch : undefined}

View File

@@ -530,6 +530,7 @@ export function TreatmentWorkspace({
const [planBilledManual, setPlanBilledManual] = useState(false);
const [approveBusy, setApproveBusy] = useState(false);
const [clinicPriceLines, setClinicPriceLines] = useState<BillingPriceLine[]>([]);
const [hideUnpricedClinicTypes, setHideUnpricedClinicTypes] = useState(false);
const [billingMetaByCode, setBillingMetaByCode] = useState<Map<string, ProsthesisQtyMeta>>(
() => new Map(),
);
@@ -802,12 +803,14 @@ export function TreatmentWorkspace({
amount: line.amount,
})),
);
setHideUnpricedClinicTypes(res.data.hideUnpricedTypes);
setBillingMetaByCode(
new Map(res.data.prosthesisMeta.map((row) => [row.code, row])),
);
} catch {
if (!cancelled) {
setClinicPriceLines([]);
setHideUnpricedClinicTypes(false);
setBillingMetaByCode(new Map());
}
}
@@ -817,6 +820,16 @@ export function TreatmentWorkspace({
};
}, [billingUserId, canView, currentOrganization, treatmentAsOf]);
const assignableProsthesisCatalog = useMemo(() => {
if (!hideUnpricedClinicTypes) return prosthesisCatalog;
const pricedCodes = new Set(
clinicPriceLines
.filter((line) => line.catalogKind === 'PROSTHESIS_TYPE' && line.amount > 0)
.map((line) => line.catalogCode),
);
return prosthesisCatalog.filter((entry) => pricedCodes.has(entry.code));
}, [clinicPriceLines, hideUnpricedClinicTypes, prosthesisCatalog]);
const liveDetailAmounts = useMemo(() => {
const map = new Map<string, number>();
for (const detail of details) {
@@ -3185,6 +3198,7 @@ export function TreatmentWorkspace({
}
detailClientId={activeDetailId}
catalog={prosthesisCatalog}
pickerCatalog={assignableProsthesisCatalog}
disabled={!canEditTreatmentForDay || activeLocked}
headerControl={
<WholePlanToggle
@@ -3464,7 +3478,7 @@ export function TreatmentWorkspace({
<VoiceReviewSheet
result={voiceResult}
treatmentCatalog={treatmentCatalog}
prosthesisCatalog={prosthesisCatalog}
prosthesisCatalog={assignableProsthesisCatalog}
labDependentCodes={labDependentCodes}
labs={orgs}
onApply={(selection, applied) => applyVoiceResult(applied, selection)}

View File

@@ -5,6 +5,7 @@ import type {
BillingCurrencySettings,
BillingLedgerRow,
BillingNamedOrg,
BillingPartyReport,
BillingPartySearchResult,
BillingSheet,
BillingSheetCatalog,
@@ -112,6 +113,33 @@ export const billingApi = {
return response.data;
},
getPartyReport: async (params: {
partyKind: 'patient' | 'staff' | 'org';
partyId: string;
from?: string;
to?: string;
}): Promise<BillingPartyReport> => {
const response = await apiClient.get('/billing/party-report', { params });
return response.data;
},
getStaffSalary: async (
userId: string,
): Promise<{ success: boolean; data: { fixedMonthlySalary: string } }> => {
const response = await apiClient.get(`/billing/staff/${userId}/salary`);
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,
});
return response.data;
},
getResolvedLines: async (params: {
kind: BillingSheetKind;
asOf: string;
@@ -209,11 +237,25 @@ export const billingApi = {
quoteLabPrice: async (body: {
labOrganizationId: string;
jobs: Array<{ tooth: string; prosthesisTypeCode: string }>;
}): Promise<{ success: boolean; data: { amount: string } }> => {
}): Promise<{
success: boolean;
data: { amount: string | null; unpricedCodes: string[]; blocksSend: boolean };
}> => {
const response = await apiClient.post('/billing/lab-price-quote', body);
return response.data;
},
updateObligationAmount: async (
entryId: string,
amount: string,
): Promise<{ success: boolean; data: { amount: string } }> => {
const response = await apiClient.put(
`/billing/obligations/${encodeURIComponent(entryId)}/amount`,
{ amount },
);
return response.data;
},
quoteOutsource: async (body: {
destinationOrganizationId: string;
caseId: string;

View File

@@ -27,6 +27,7 @@ export type BillingSheet = {
targetClinicIds: string[];
targetUsers: BillingNamedTarget[];
targetClinics: BillingNamedTarget[];
hideUnpricedTypes: boolean;
lines: BillingSheetLine[];
createdAt: string;
updatedAt: string;
@@ -55,6 +56,7 @@ export type UpsertBillingSheetInput = {
effectiveOn: string;
targetUserIds?: string[];
targetClinicIds?: string[];
hideUnpricedTypes?: boolean;
lines: Array<{
catalogKind: BillingCatalogKind;
catalogCode: string;
@@ -152,6 +154,36 @@ export type BillingLedgerRow = {
recordedByViewer: boolean;
};
export type BillingPartyReportRow = {
id: string;
lineKind: 'OBLIGATION' | 'CASH';
direction: 'DEBIT' | 'CREDIT';
amount: string | null;
signedAmount: string | null;
amountPending: boolean;
canEditAmount: boolean;
occurredAt: string;
sourceType:
| 'TREATMENT_APPROVE'
| 'LAB_CASE'
| 'OUTSOURCE_CASE'
| 'STAFF_COMMISSION_MONTH'
| 'STAFF_SALARY_MONTH'
| 'CASH_RECEIPT'
| 'CASH_PAYMENT';
sourceId: string;
reference: string;
note: string | null;
acknowledgement: PaymentAcknowledgement;
countsInTotals: boolean;
};
export type BillingPartyReport = {
success: boolean;
data: BillingPartyReportRow[];
totals: { debit: string; credit: string; net: string };
};
export type PartnerPayment = {
id: string;
amount: string;
@@ -223,6 +255,7 @@ export type BillingProsthesisMeta = {
};
export type ResolvedBillingLines = {
hideUnpricedTypes: boolean;
lines: BillingPriceLine[];
prosthesisMeta: BillingProsthesisMeta[];
};