Merge pull request 'improvements: statements pdf layout added. staff salary report improved.' (#133) from improvements/billing-v4 into master
All checks were successful
Registry — build, push, deploy / build-and-push (push) Successful in 17m56s
Registry — build, push, deploy / deploy (push) Successful in 1m13s

Reviewed-on: #133
Reviewed-by: Babak Safarnezhad <babak.safarnezhad@gmail.com>
This commit was merged in pull request #133.
This commit is contained in:
2026-11-23 02:17:43 +03:30
22 changed files with 1755 additions and 97 deletions

View File

@@ -11,10 +11,10 @@ alwaysApply: false
- **Sheet kinds:** clinic `CLINIC_PRICE` / `CLINIC_COMMISSION`; lab `LAB_PRICE` (outsourcing tab first) / `LAB_COMMISSION`. Commission lines are **fixed amounts**.
- **Partner ledger is shared:** Accept/Decline for the other org; typed `externalPartyName` is local (no ack).
- **Transactions:** Clinic RECEIPT → patient or linked org; PAYMENT → linked org or staff (`StaffPayment`, outbound only). Lab RECEIPT/PAYMENT → linked org; PAYMENT may also be staff. Grouped `GET /billing/party-search`. Merged list: `GET /billing/transactions` (+ optional party filter + signed **net**: RECEIPT +, PAYMENT −).
- **Inline party ledger:** default table is cash only. Selecting a patient/staff/org swaps that same table to `GET /billing/party-report` obligations + cash, one neutral Amount column with a Debit/Credit marker, and an aligned balance footer. Only the final balance uses green/red (green = they owe us, red = we owe them). Case rows show Received/Generated/From lab origin. Staff selection shows closed-month commission and salary, plus an unsaved preview of the open month through the report day. A notification link selects the sender the same way, with no date range.
- **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. An organization selection can **Print statement**: the same rows and `totals.net`, oldest first, one page when the rows fit, bordered columns for number, date, reference, and amount. The Persian table is RTL; its cell text stays left-to-right and is shifted up so the glyphs sit in the row. The Case Sheet header stays LTR. No payment-note block. The staff card is the open month only, summed from the preview rows. **Show details** on that card, or on a commission row, loads `GET /billing/staff-income` (job, unit price, quantity, amount, and earning lines). A clinic line’s reference is the patient; a lab line’s reference is the referring clinic and dentist. Salary rows have no details, and that response does not repeat the salary. A notification link selects the sender the same way, with no date range.
- **Cash edits:** amount, note, and valid allocations edit inside the selected table row. Allocations open under that row. 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; a case fee is mirrored only when every current-round task is done (received, outsourced, and generated-with-partner); monthly commission and fixed salary → staff. Send/Start stores the case price and does not post the debt. Reopening a step removes that case’s debt. 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 the full month once and sums that month's commissions; both are separate staff payables dated on the last day. The open month shows the same two rows unsaved: commissions earned so far, and the sheet amount times days elapsed over days in the month. 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 model. The stored month-end salary is the full month.
- **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 the full month once and sums that month's commissions; both are separate staff payables dated on the last day. A null or zero rate creates no salary row. The open month shows the same two rows unsaved when each amount is above zero: commissions earned so far, and the sheet amount times days elapsed over days in the month. **Show details** is commission only. 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 model. The stored month-end salary is the full month.
- **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, the price stays empty until the destination lab sets it. The pending obligation appears when every step is done; the lab can type the fee on the case before that, and that amount is what the debt uses.
- 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).

View File

@@ -13,7 +13,7 @@ Monorepo: `backend/` (NestJS + Prisma), `frontend/` (Next.js + next-intl), `infr
- **LAB** orgs: cases, tasks, lab workflows.
- Named **patients** are scoped to `createdByOrganizationId`. `identification` stays globally unique — other-org / walk-in hit `PATIENT_IDENTIFICATION_UNAVAILABLE` (no shared row). `mobile` is not unique.
- Tab access: `TAB_*_READ` / `TAB_*_EDIT` in `backend/src/common/permissions.ts`. EDIT implies READ.
- **Billing** (clinic + lab): fee/commission sheets, automatic obligations, and a cash ledger. A case fee becomes a debt when every current-round task is done. The Commissions/Salary tab holds one current salary sheet; month-end rows are posted after the month ends, and the open month is only a calculated preview. `hideUnpricedTypes` defaults off and commission sheets cannot turn it on. See `.cursor/rules/billing.mdc` and `.cursor/skills/billing/SKILL.md`.
- **Billing** (clinic + lab): fee/commission sheets, automatic obligations, and a cash ledger. A case fee becomes a debt when every current-round task is done. The Commissions/Salary tab holds one current salary sheet; month-end rows are posted after the month ends, and the open month is only a calculated preview. The staff card shows that preview only. An organization can print the party ledger as a statement. `hideUnpricedTypes` defaults off and commission sheets cannot turn it on. See `.cursor/rules/billing.mdc` and `.cursor/skills/billing/SKILL.md`.
## Agent behavior

View File

@@ -47,10 +47,11 @@ 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, 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.”
- An organization selection can print that same ledger. **Print statement** downloads an A4 PDF (oldest first, header and columns repeated, debit/credit/balance on the last page). A report that fits on one page stays on one page. The table is a bordered grid with row number, date, reference, and amount; debit/credit sits on that amount line. Source and note are not printed. The Persian table is RTL; the page header stays LTR. Persian cell text stays `direction: ltr` — the capture paints `rtl` backwards — and each cell’s text is shifted up 10px so Vazirmatn sits in the 27px row (table font 14px). The printed balance is `totals.net`. Pending and declined cash stay on the page and stay out of the totals, without a status note. The header matches the Case Sheet: organization name, the Nudentic lockup, and the phone (`issuer` on the party report), addressed to the selected org. There is no payment-note or bank block. Patients and staff do not get this button. The party report does not return a separate staff-compensation total; the card sums the preview rows.
- Cash rows expose edit metadata/allocations. Editing happens on the row: amount and note in the cells, allocations on the lines under that row. 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 completion, monthly commission, and monthly salary.
- Case obligations are mirrored when every current-round task is `COMPLETED`: payer books show the destination as creditor; destination books show the payer as debtor. Send, Start, and outsource store `calculatedAmount` / `billedAmount` only. Reopening a step deletes that case’s rows. Stop/recall already do. A received case and an outsourced case notify the destination lab’s billing users in the same write that inserts the obligation. The link selects that payer on Transactions with no date filter.
- The open staff month is not stored. The party report appends commission earned from the month start through the report day, and fixed salary times the elapsed fraction of that month. Both count in the balance and the staff totals, and they disappear once the stored rows exist.
- The open staff month is not stored. The party report appends commission earned from the month start through the report day, and fixed salary times the elapsed fraction of that month. Both count in the balance, and they disappear once the stored rows exist. A null or zero `fixedMonthlySalary` creates no salary preview and no closed salary row. The staff card shows only that open month. **Show details** on the card, or on a commission row, calls `GET /billing/staff-income`. Salary rows have no details action. The response is commission only: jobs grouped by unit price (quantity × unit price, with a sum) plus one line per earning. A clinic line’s reference is the patient name; a lab line’s reference is the referring clinic and dentist. If the listed commission sum differs from the posted month, the panel says the hourly job has not caught up.
## Fee / commission editor
@@ -75,7 +76,7 @@ Keep chrome identical: `BillingListToolbar`, outline labels, `AppMoneyInput`, eq
- One sheet on the Commissions/Salary tab, beside **New commission schedule**. It lists the owner and every active member. `PUT /billing/staff-salaries` updates `Membership.fixedMonthlySalary` and does not create a ledger row or a new sheet.
- After the first save, a Staff salary section with one Edit row sits above Commission history. `Organization.staffSalaryUpdatedAt` is that marker.
- The hourly job writes a finished month only. Commission is that month's earnings. Salary is the full sheet amount, snapshotted once; a later edit does not change it. A month the server missed is closed on the next run with the rate on the sheet then. Rows are dated on the last day. The open month is a calculated preview only. Toman uses Jalali months; Dollar/Euro use Gregorian months.
- Staff summary subtotals include the closed rows in the date range and, while the month is open, the unsaved preview. Commission + fixed salary = gross. Cash affects net only. Staff cash remains `StaffPayment`.
- The staff card shows the unsaved open month only. Commission + fixed salary = gross. **Show details** lists the commission jobs and earning rows for that month, not the salary. Cash affects net only. Staff cash remains `StaffPayment`.
- The stored month-end salary is the full sheet amount. The open-month preview is that amount times days elapsed over days in the month. V1 has no attendance, bonus, or payroll-tax model.
## 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. 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, a case whose every current-round task is done, and staff commission plus fixed salary after each month ends; Toman uses Jalali months, Dollar/Euro Gregorian. Send stores the case price and does not post the debt. 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, including an unsaved preview of the open month through the report day. 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. The stored month-end salary is the full amount; the open-month preview is that amount times the days elapsed. There is no attendance model. 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 keeps an empty fee until the destination lab sets it. The pending obligation is created when every step is done. A received or outsourced case notifies that lab’s billing users then, and the link selects the payer on Transactions. 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, a case whose every current-round task is done, and staff commission plus fixed salary after each month ends; Toman uses Jalali months, Dollar/Euro Gregorian. Send stores the case price and does not post the debt. Selecting a party swaps the cash table to an inline obligation+cash ledger with signed amount/net. Selected staff show one open-month card (commission, fixed salary, and gross through the report day). Show details is that month’s commission by job and unit price; salary stays a ledger row. An organization can print the same ledger as a bordered statement (number, date, reference, amount). The Persian table is RTL; its cell text stays LTR and is shifted up so the glyphs sit in the row. 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. The stored month-end salary is the full amount; the open-month preview is that amount times the days elapsed. There is no attendance model. 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 keeps an empty fee until the destination lab sets it. The pending obligation is created when every step is done. A received or outsourced case notifies that lab’s billing users then, and the link selects the payer on Transactions. 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

@@ -26,6 +26,7 @@ import {
ListPaymentsQueryDto,
PartyReportQueryDto,
PartySearchQueryDto,
StaffIncomeQueryDto,
SaveStaffSalarySheetDto,
UpdateObligationAmountDto,
UpdatePaymentDto,
@@ -150,6 +151,21 @@ export class BillingController {
return this.billingService.listTransactions(req.user.id, organizationId, query);
}
@Get('staff-income')
@ApiOperation({ summary: 'Commission jobs and earning lines for one staff month' })
staffIncome(
@Query() query: StaffIncomeQueryDto,
@Req() req: { user: { id: string; organizationId?: string; language?: string } },
) {
const organizationId = this.billingService.getOrganizationIdFromUser(req.user);
return this.billingService.staffIncome(
req.user.id,
organizationId,
query,
req.user.language,
);
}
@Get('party-report')
@ApiOperation({ summary: 'Unified debit/credit report for one patient, staff member, or org' })
partyReport(

View File

@@ -88,7 +88,14 @@ import {
sharedCashCountsInPartyReport,
signedPartyCashAmount,
} from './party-ledger';
import { SaveStaffSalarySheetDto } from './dto/billing-payment.dto';
import { SaveStaffSalarySheetDto, StaffIncomeQueryDto } from './dto/billing-payment.dto';
import {
explainStaffSalary,
groupCommissionEarnings,
staffIncomeEarningWindow,
staffIncomeReportDay,
sumCommissionEarnings,
} from './staff-income';
import {
finishedStaffBillingPeriods,
previousStaffBillingPeriod,
@@ -793,7 +800,7 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
? BillingLedgerPartyKind.STAFF
: BillingLedgerPartyKind.ORGANIZATION;
const occurredAt = occurredAtWhere(query);
const [obligations, cash] = await Promise.all([
const [obligations, cash, issuerOrg] = await Promise.all([
this.prisma.billingLedgerEntry.findMany({
where: {
organizationId,
@@ -810,6 +817,10 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
partyId: query.partyId,
unlimited: true,
}),
this.prisma.organization.findUnique({
where: { id: organizationId },
select: { name: true, phone: true },
}),
]);
const treatmentIds = obligations
@@ -942,26 +953,6 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
const net = rows
.filter((row) => row.countsInTotals && row.signedAmount != null)
.reduce((sum, row) => sum + Number(row.signedAmount ?? 0), 0);
const commissionSubtotal =
query.partyKind === 'staff'
? rows
.filter(
(row) =>
row.lineKind === 'OBLIGATION' &&
row.sourceType === BillingObligationSourceType.STAFF_COMMISSION_MONTH,
)
.reduce((sum, row) => sum + Number(row.amount ?? 0), 0)
: 0;
const fixedSalarySubtotal =
query.partyKind === 'staff'
? rows
.filter(
(row) =>
row.lineKind === 'OBLIGATION' &&
row.sourceType === BillingObligationSourceType.STAFF_SALARY_MONTH,
)
.reduce((sum, row) => sum + Number(row.amount ?? 0), 0)
: 0;
return {
success: true as const,
data: rows,
@@ -970,16 +961,137 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
credit: roundBillingAmount(credit).toFixed(2),
net: roundSignedBillingAmount(net).toFixed(2),
},
staffCompensation:
query.partyKind === 'staff'
? {
commission: roundBillingAmount(commissionSubtotal).toFixed(2),
fixedSalary: roundBillingAmount(fixedSalarySubtotal).toFixed(2),
gross: roundBillingAmount(
commissionSubtotal + fixedSalarySubtotal,
).toFixed(2),
}
: null,
issuer: {
name: issuerOrg?.name ?? '',
phone: issuerOrg?.phone ?? null,
},
};
}
/** Commission jobs and earning lines behind one staff month. */
async staffIncome(
actorUserId: string,
organizationId: string,
query: StaffIncomeQueryDto,
localeInput?: string | null,
) {
await this.assertCanRead(actorUserId, organizationId);
await this.assertStaffInOrg(organizationId, query.userId);
const currency = await this.staffBillingCurrency(organizationId);
const period = staffBillingPeriodFromKey(query.periodKey);
if (!period || !staffPeriodKeyMatchesCurrency(period.key, currency)) {
throw new AppException(ErrorCode.BILLING_CURRENCY_INVALID, HttpStatus.BAD_REQUEST);
}
const now = new Date();
const reportDay = staffIncomeReportDay(now, query.to);
const current = staffBillingPeriodForDate(now, currency);
const open = period.key === current.key;
const window = staffIncomeEarningWindow({ period, open, reportDay });
const commissionId = `${query.userId}:${period.key}:commission`;
const [earnings, ledger, orgType] = await Promise.all([
window
? this.prisma.commissionEarning.findMany({
where: {
organizationId,
userId: query.userId,
earnedAt: { gte: window.from, lt: window.until },
},
orderBy: [{ earnedAt: 'asc' }, { id: 'asc' }],
select: {
id: true,
catalogCode: true,
qty: true,
baseAmount: true,
earnedAmount: true,
earnedAt: true,
labCase: {
select: { referringClinicName: true, referringDentistName: true },
},
treatment: {
select: { patient: { select: { firstName: true, lastName: true } } },
},
},
})
: Promise.resolve([]),
this.prisma.billingLedgerEntry.findMany({
where: {
organizationId,
partyKind: BillingLedgerPartyKind.STAFF,
partyId: query.userId,
sourceType: BillingObligationSourceType.STAFF_COMMISSION_MONTH,
sourceId: commissionId,
},
select: { amount: true },
}),
getOrganizationTypeName(this.prisma, organizationId),
]);
const amounts = earnings.map((row) => ({
catalogCode: row.catalogCode,
qty: Number(row.qty),
unitAmount: Number(row.baseAmount),
earnedAmount: Number(row.earnedAmount),
}));
const locale = normalizeCatalogLocale(localeInput);
const labelKind =
orgType === 'CLINIC'
? CatalogEntityKind.TREATMENT_TYPE
: CatalogEntityKind.LAB_WORKFLOW_STEP;
const labels = await this.catalogLabels.resolveLabels(
labelKind,
amounts.map((row) => row.catalogCode),
locale,
);
const labelFor = (code: string) => labels.get(code) ?? formatCodeAsLabel(code);
const postedCommission = ledger[0];
const listed = sumCommissionEarnings(amounts);
return {
success: true as const,
data: {
period: {
key: period.key,
label: period.label,
calendar: period.calendar,
start: period.start.toISOString().slice(0, 10),
end: staffPeriodLastDay(period).toISOString().slice(0, 10),
},
open,
reportDay: open ? reportDay.toISOString().slice(0, 10) : null,
commission: {
postedAmount:
postedCommission?.amount == null
? null
: roundBillingAmount(Number(postedCommission.amount)).toFixed(2),
listedAmount: listed.toFixed(2),
groups: groupCommissionEarnings(amounts)
.map((group) => ({
catalogCode: group.code,
label: labelFor(group.code),
unitAmount: group.unitAmount.toFixed(2),
qty: group.qty.toFixed(2),
amount: group.amount.toFixed(2),
}))
.sort(
(a, b) =>
a.label.localeCompare(b.label) ||
a.unitAmount.localeCompare(b.unitAmount) ||
a.catalogCode.localeCompare(b.catalogCode),
),
lines: earnings.map((row) => ({
id: row.id,
earnedAt: row.earnedAt.toISOString(),
catalogCode: row.catalogCode,
label: labelFor(row.catalogCode),
qty: Number(row.qty).toFixed(2),
unitAmount: roundBillingAmount(Number(row.baseAmount)).toFixed(2),
earnedAmount: roundBillingAmount(Number(row.earnedAmount)).toFixed(2),
reference: staffIncomeReference(orgType, row),
})),
},
},
};
}
@@ -992,17 +1104,12 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
) {
const currency = await this.staffBillingCurrency(organizationId);
const now = new Date();
const today = dateOnlyUtc(now.toISOString().slice(0, 10));
let reportDay = today;
if (query.to) {
const to = dateOnlyUtc(query.to);
if (to.getTime() < reportDay.getTime()) reportDay = to;
}
const reportDay = staffIncomeReportDay(now, query.to);
if (query.from && dateOnlyUtc(query.from).getTime() > reportDay.getTime()) return [];
const period = staffBillingPeriodForDate(now, currency);
const window = staffIncomeEarningWindow({ period, open: true, reportDay });
const span = staffPeriodElapsedDays(period, reportDay);
if (!span) return [];
const through = new Date(reportDay.getTime() + 24 * 60 * 60 * 1000);
if (!window || !span) return [];
const occurredAt = reportDay.toISOString();
const rows: Array<{
@@ -1035,7 +1142,7 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
where: {
organizationId,
userId,
earnedAt: { gte: period.start, lt: through },
earnedAt: { gte: window.from, lt: window.until },
},
_sum: { earnedAmount: true },
});
@@ -1058,20 +1165,22 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
where: { userId_organizationId: { userId, organizationId } },
select: { fixedMonthlySalary: true },
});
const salary = roundBillingAmount(Number(membership?.fixedMonthlySalary ?? 0));
if (salary > 0) {
const amount = roundBillingAmount((salary * span.elapsed) / span.days);
if (amount > 0) {
rows.push(
this.staffPreviewRow(
BillingObligationSourceType.STAFF_SALARY_MONTH,
salaryId,
amount,
period.key,
occurredAt,
),
);
}
const salary = explainStaffSalary({
open: true,
postedAmount: null,
monthlyRate: roundBillingAmount(Number(membership?.fixedMonthlySalary ?? 0)),
elapsed: span,
});
if (salary.amount) {
rows.push(
this.staffPreviewRow(
BillingObligationSourceType.STAFF_SALARY_MONTH,
salaryId,
Number(salary.amount),
period.key,
occurredAt,
),
);
}
}
return rows;
@@ -3639,6 +3748,27 @@ function staffPeriodReference(sourceId: string): string {
return '';
}
function staffIncomeReference(
orgType: string,
row: {
labCase: {
referringClinicName: string | null;
referringDentistName: string | null;
} | null;
treatment: { patient: { firstName: string; lastName: string } } | null;
},
): string {
if (orgType === 'LAB') {
return [row.labCase?.referringClinicName, row.labCase?.referringDentistName]
.map((part) => part?.trim() ?? '')
.filter((part) => part.length > 0)
.join(' · ');
}
const patient = row.treatment?.patient;
if (!patient) return '';
return `${patient.firstName} ${patient.lastName}`.trim();
}
function parseMoney(value: string): number {
const amount = Number(value.trim().replace(/,/g, ''));
if (!Number.isFinite(amount) || amount < 0) {

View File

@@ -130,6 +130,19 @@ export class ListPaymentsQueryDto {
partyId?: string;
}
export class StaffIncomeQueryDto {
@IsUUID('all', { message: ErrorCode.BILLING_STAFF_INVALID })
userId: string;
@Matches(/^(J|G):-?\d{1,4}-\d{2}$/, { message: ErrorCode.BILLING_CURRENCY_INVALID })
periodKey: string;
@IsOptional()
@IsString()
@Matches(/^\d{4}-\d{2}-\d{2}$/)
to?: string;
}
export class PartyReportQueryDto {
@IsIn(['patient', 'staff', 'org'], { message: ErrorCode.BILLING_PARTY_INVALID })
partyKind: 'patient' | 'staff' | 'org';

View File

@@ -0,0 +1,84 @@
import { staffBillingPeriodForDate } from './staff-billing-period';
import {
explainStaffSalary,
groupCommissionEarnings,
staffIncomeEarningWindow,
staffIncomeReportDay,
} from './staff-income';
describe('staff income detail', () => {
const period = staffBillingPeriodForDate(new Date('2026-11-15T00:00:00.000Z'), 'DOLLAR');
it('stops the open month on the report day', () => {
const reportDay = staffIncomeReportDay(new Date('2026-11-22T15:00:00.000Z'), '2026-11-10');
expect(reportDay.toISOString()).toBe('2026-11-10T00:00:00.000Z');
const window = staffIncomeEarningWindow({ period, open: true, reportDay });
expect(window).toEqual({
from: period.start,
until: new Date('2026-11-11T00:00:00.000Z'),
});
});
it('uses the whole period once the month is closed', () => {
const reportDay = staffIncomeReportDay(new Date('2026-12-02T00:00:00.000Z'));
expect(
staffIncomeEarningWindow({ period, open: false, reportDay }),
).toEqual({ from: period.start, until: period.end });
});
it('returns no open-month rows when the report day is outside that month', () => {
const reportDay = staffIncomeReportDay(new Date('2026-11-22T00:00:00.000Z'), '2026-10-01');
expect(staffIncomeEarningWindow({ period, open: true, reportDay })).toBeNull();
});
it('groups commission rows by job and unit price', () => {
expect(
groupCommissionEarnings([
{ catalogCode: 'milling_dry_sinter', qty: 2, unitAmount: 15, earnedAmount: 30 },
{ catalogCode: 'milling_dry_sinter', qty: 1, unitAmount: 15, earnedAmount: 15 },
{ catalogCode: 'milling_dry_sinter', qty: 1, unitAmount: 20, earnedAmount: 20 },
{ catalogCode: 'stain_glaze', qty: 1, unitAmount: 8, earnedAmount: 8 },
]),
).toEqual([
{ code: 'milling_dry_sinter', unitAmount: 15, qty: 3, amount: 45 },
{ code: 'milling_dry_sinter', unitAmount: 20, qty: 1, amount: 20 },
{ code: 'stain_glaze', unitAmount: 8, qty: 1, amount: 8 },
]);
});
it('keeps a closed salary at the posted amount when the sheet rate later changes', () => {
expect(
explainStaffSalary({
open: false,
postedAmount: 3000,
monthlyRate: 9000,
elapsed: { elapsed: 10, days: 30 },
}),
).toEqual({
kind: 'closed',
monthlyRate: null,
elapsedDays: null,
daysInMonth: null,
amount: '3000.00',
postedAmount: '3000.00',
});
});
it('prorates the open month from the current rate and the days elapsed', () => {
expect(
explainStaffSalary({
open: true,
postedAmount: null,
monthlyRate: 3000,
elapsed: { elapsed: 10, days: 30 },
}),
).toEqual({
kind: 'preview',
monthlyRate: '3000.00',
elapsedDays: 10,
daysInMonth: 30,
amount: '1000.00',
postedAmount: null,
});
});
});

View File

@@ -0,0 +1,163 @@
import { roundBillingAmount } from './calculate-amounts';
import {
staffPeriodElapsedDays,
type StaffBillingPeriod,
} from './staff-billing-period';
export type StaffIncomeWindow = {
from: Date;
/** Exclusive upper bound, matching `earnedAt < until`. */
until: Date;
};
function utcDay(date: Date): Date {
return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
}
/** Today, or `to` when the report ends earlier. Same cutoff as the open-month preview. */
export function staffIncomeReportDay(now: Date, to?: string): Date {
const today = utcDay(now);
if (!to) return today;
const end = new Date(`${to}T00:00:00.000Z`);
if (Number.isNaN(end.getTime())) return today;
return end.getTime() < today.getTime() ? end : today;
}
/**
* Open month: earnings from the period start through the report day.
* Closed month: the whole period. A report day outside the open period yields no rows.
*/
export function staffIncomeEarningWindow(args: {
period: StaffBillingPeriod;
open: boolean;
reportDay: Date;
}): StaffIncomeWindow | null {
if (!args.open) {
return { from: args.period.start, until: args.period.end };
}
if (!staffPeriodElapsedDays(args.period, args.reportDay)) return null;
return {
from: args.period.start,
until: new Date(args.reportDay.getTime() + 24 * 60 * 60 * 1000),
};
}
export type StaffSalaryExplanation = {
kind: 'preview' | 'closed' | 'none';
monthlyRate: string | null;
elapsedDays: number | null;
daysInMonth: number | null;
amount: string | null;
postedAmount: string | null;
};
function money(value: number): string {
return roundBillingAmount(value).toFixed(2);
}
/**
* A closed month keeps the posted amount. The rate on the sheet today is not
* the rate that was saved, so the day math stays empty.
* An open month with a stored row uses that row, matching the ledger.
*/
export function explainStaffSalary(args: {
open: boolean;
postedAmount: number | null;
monthlyRate: number;
elapsed: { elapsed: number; days: number } | null;
}): StaffSalaryExplanation {
const posted =
args.postedAmount != null && args.postedAmount > 0
? money(args.postedAmount)
: null;
if (!args.open || posted) {
if (!posted) {
return {
kind: 'none',
monthlyRate: null,
elapsedDays: null,
daysInMonth: null,
amount: null,
postedAmount: null,
};
}
return {
kind: 'closed',
monthlyRate: null,
elapsedDays: null,
daysInMonth: null,
amount: posted,
postedAmount: posted,
};
}
if (!args.elapsed || args.monthlyRate <= 0) {
return {
kind: 'none',
monthlyRate: args.monthlyRate > 0 ? money(args.monthlyRate) : null,
elapsedDays: args.elapsed?.elapsed ?? null,
daysInMonth: args.elapsed?.days ?? null,
amount: null,
postedAmount: null,
};
}
const amount = roundBillingAmount(
(args.monthlyRate * args.elapsed.elapsed) / args.elapsed.days,
);
if (amount <= 0) {
return {
kind: 'none',
monthlyRate: money(args.monthlyRate),
elapsedDays: args.elapsed.elapsed,
daysInMonth: args.elapsed.days,
amount: null,
postedAmount: null,
};
}
return {
kind: 'preview',
monthlyRate: money(args.monthlyRate),
elapsedDays: args.elapsed.elapsed,
daysInMonth: args.elapsed.days,
amount: money(amount),
postedAmount: null,
};
}
export type CommissionEarningAmount = {
catalogCode: string;
qty: number;
unitAmount: number;
earnedAmount: number;
};
export function sumCommissionEarnings(lines: readonly CommissionEarningAmount[]): number {
return roundBillingAmount(lines.reduce((sum, line) => sum + line.earnedAmount, 0));
}
/** One row per job and unit price. Amount is quantity times that price. */
export function groupCommissionEarnings(lines: readonly CommissionEarningAmount[]): Array<{
code: string;
unitAmount: number;
qty: number;
amount: number;
}> {
const groups = new Map<string, { code: string; unitAmount: number; qty: number }>();
for (const line of lines) {
const unitAmount = roundBillingAmount(line.unitAmount);
const key = `${line.catalogCode}\0${unitAmount.toFixed(2)}`;
const current = groups.get(key) ?? { code: line.catalogCode, unitAmount, qty: 0 };
current.qty += line.qty;
groups.set(key, current);
}
return [...groups.values()].map((group) => {
const qty = roundBillingAmount(group.qty);
return {
code: group.code,
unitAmount: group.unitAmount,
qty,
amount: roundBillingAmount(qty * group.unitAmount),
};
});
}

View File

@@ -1445,7 +1445,33 @@
"commissionSubtotal": "Commission",
"fixedSalarySubtotal": "Fixed salary",
"grossCompensation": "Gross compensation",
"projectedSoFar": "So far"
"projectedSoFar": "So far",
"printStatement": "Print statement",
"statementTitle": "Account statement",
"statementAddressedTo": "To",
"statementPhone": "Phone",
"statementPrintedOn": "Printed {date}",
"statementRowNumber": "#",
"statementPage": "Page {page} of {pages}",
"statementRange": "{from} – {to}",
"statementRangeFrom": "From {from}",
"statementRangeTo": "Through {to}",
"statementRangeAll": "All dates",
"errorPrintStatement": "Could not print the statement.",
"openMonthCompensation": "This month through {date}",
"showIncomeDetails": "Show details",
"incomeDetailsTitle": "Income for {period}",
"incomeThrough": "Through {date}",
"commissionByStep": "Commission by job",
"earningRecords": "Earning records",
"incomeStep": "Job",
"incomeQuantity": "Quantity",
"incomeUnitAmount": "Unit price",
"incomeAmount": "Amount",
"incomeSum": "Sum",
"incomePostedMismatch": "The saved month total is {posted}. These records add up to {listed}. A reopened step updates the saved total on the next run.",
"incomeEmptyCommission": "No commission records in this month.",
"errorLoadIncome": "Could not load the income details."
},
"localDb": {
"browse": "Browse",

View File

@@ -1446,7 +1446,33 @@
"commissionSubtotal": "کمیسیون",
"fixedSalarySubtotal": "حقوق ثابت",
"grossCompensation": "جمع ناخالص دریافتی",
"projectedSoFar": "تا این روز"
"projectedSoFar": "تا این روز",
"printStatement": "چاپ صورتحساب",
"statementTitle": "صورتحساب",
"statementAddressedTo": "به",
"statementPhone": "تلفن",
"statementPrintedOn": "تاریخ چاپ {date}",
"statementRowNumber": "ردیف",
"statementPage": "صفحه {page} از {pages}",
"statementRange": "از {from} تا {to}",
"statementRangeFrom": "از {from}",
"statementRangeTo": "تا {to}",
"statementRangeAll": "همه تاریخ‌ها",
"errorPrintStatement": "چاپ صورتحساب ناموفق بود.",
"openMonthCompensation": "این ماه تا {date}",
"showIncomeDetails": "نمایش جزئیات",
"incomeDetailsTitle": "درآمد {period}",
"incomeThrough": "تا {date}",
"commissionByStep": "کمیسیون به تفکیک کار",
"earningRecords": "رکوردهای درآمد",
"incomeStep": "کار",
"incomeQuantity": "تعداد",
"incomeUnitAmount": "قیمت واحد",
"incomeAmount": "مبلغ",
"incomeSum": "جمع",
"incomePostedMismatch": "جمع ذخیره‌شده این ماه {posted} است. این رکوردها روی هم {listed} می‌شوند. اگر مرحله‌ای دوباره باز شود، جمع ذخیره‌شده در اجرای بعدی به‌روز می‌شود.",
"incomeEmptyCommission": "در این ماه رکورد کمیسیونی نیست.",
"errorLoadIncome": "بارگذاری جزئیات درآمد ناموفق بود."
},
"localDb": {
"browse": "مرور",

View File

@@ -1445,7 +1445,33 @@
"commissionSubtotal": "Commissie",
"fixedSalarySubtotal": "Vast salaris",
"grossCompensation": "Brutovergoeding",
"projectedSoFar": "Tot nu toe"
"projectedSoFar": "Tot nu toe",
"printStatement": "Overzicht afdrukken",
"statementTitle": "Rekeningoverzicht",
"statementAddressedTo": "Aan",
"statementPhone": "Telefoon",
"statementPrintedOn": "Afgedrukt {date}",
"statementRowNumber": "#",
"statementPage": "Pagina {page} van {pages}",
"statementRange": "{from} – {to}",
"statementRangeFrom": "Vanaf {from}",
"statementRangeTo": "Tot en met {to}",
"statementRangeAll": "Alle datums",
"errorPrintStatement": "Het overzicht kon niet worden afgedrukt.",
"openMonthCompensation": "Deze maand tot en met {date}",
"showIncomeDetails": "Details tonen",
"incomeDetailsTitle": "Inkomen voor {period}",
"incomeThrough": "Tot en met {date}",
"commissionByStep": "Commissie per werk",
"earningRecords": "Inkomstenregels",
"incomeStep": "Werk",
"incomeQuantity": "Aantal",
"incomeUnitAmount": "Eenheidsprijs",
"incomeAmount": "Bedrag",
"incomeSum": "Som",
"incomePostedMismatch": "Het opgeslagen maandtotaal is {posted}. Deze regels tellen op tot {listed}. Een heropende stap werkt het opgeslagen totaal bij bij de volgende run.",
"incomeEmptyCommission": "Geen commissieregels in deze maand.",
"errorLoadIncome": "De inkomstendetails konden niet worden geladen."
},
"localDb": {
"browse": "Bladeren",

View File

@@ -1,11 +1,12 @@
import { describe, expect, it } from 'vitest';
import type { BillingPartyReportRow } from '@/types/billing';
import { staffCompensationTotals } from './staffCompensation';
import { splitStaffCompensation, staffCompensationTotals } from './staffCompensation';
function row(
sourceType: BillingPartyReportRow['sourceType'],
amount: string | null,
lineKind: BillingPartyReportRow['lineKind'] = 'OBLIGATION',
extras: Partial<BillingPartyReportRow> = {},
): BillingPartyReportRow {
return {
id: `${sourceType}:${amount}`,
@@ -22,6 +23,7 @@ function row(
note: null,
acknowledgement: 'none',
countsInTotals: amount != null,
...extras,
};
}
@@ -46,3 +48,34 @@ describe('staffCompensationTotals', () => {
).toEqual({ commission: 0, fixedSalary: 0, gross: 0 });
});
});
describe('splitStaffCompensation', () => {
it('keeps the open-month preview out of the closed totals', () => {
expect(
splitStaffCompensation([
row('STAFF_COMMISSION_MONTH', '40.00', 'OBLIGATION', {
projected: true,
reference: 'J:1404-08',
}),
row('STAFF_SALARY_MONTH', '100.00', 'OBLIGATION', {
projected: true,
reference: 'J:1404-08',
}),
row('STAFF_COMMISSION_MONTH', '200.00'),
row('STAFF_SALARY_MONTH', '1000.00'),
]),
).toEqual({
open: { commission: 40, fixedSalary: 100, gross: 140 },
closed: { commission: 200, fixedSalary: 1000, gross: 1200 },
openPeriodKey: 'J:1404-08',
});
});
it('hides the open month when the preview is outside the range', () => {
expect(splitStaffCompensation([row('STAFF_SALARY_MONTH', '1000.00')])).toEqual({
open: null,
closed: { commission: 0, fixedSalary: 1000, gross: 1000 },
openPeriodKey: null,
});
});
});

View File

@@ -6,7 +6,7 @@ export type StaffCompensationTotals = {
gross: number;
};
/** Gross compensation includes closed months and the unsaved current-month preview. */
/** Sum commission and fixed salary on the rows passed in. */
export function staffCompensationTotals(
rows: readonly BillingPartyReportRow[],
): StaffCompensationTotals {
@@ -19,6 +19,42 @@ export function staffCompensationTotals(
};
}
export type SplitStaffCompensation = {
/** Null when this date range has no open-month preview. */
open: StaffCompensationTotals | null;
closed: StaffCompensationTotals;
/** Period key on the open-month preview, when one is present. */
openPeriodKey: string | null;
};
/** Separate the unsaved current month from closed months already in the ledger. */
export function splitStaffCompensation(
rows: readonly BillingPartyReportRow[],
): SplitStaffCompensation {
const projected = rows.filter((row) => row.projected);
const stored = rows.filter((row) => !row.projected);
const open = staffCompensationTotals(projected);
const hasOpen = projected.some(
(row) =>
row.lineKind === 'OBLIGATION' &&
(row.sourceType === 'STAFF_COMMISSION_MONTH' ||
row.sourceType === 'STAFF_SALARY_MONTH') &&
row.amount != null,
);
const openRow = projected.find(
(row) =>
row.lineKind === 'OBLIGATION' &&
(row.sourceType === 'STAFF_COMMISSION_MONTH' ||
row.sourceType === 'STAFF_SALARY_MONTH') &&
row.reference,
);
return {
open: hasOpen ? open : null,
closed: staffCompensationTotals(stored),
openPeriodKey: hasOpen ? (openRow?.reference ?? null) : null,
};
}
function sumSource(
rows: readonly BillingPartyReportRow[],
sourceType: 'STAFF_COMMISSION_MONTH' | 'STAFF_SALARY_MONTH',

View File

@@ -0,0 +1,52 @@
import { describe, expect, it } from 'vitest';
import { statementPages } from './statementPages';
function row(id: string, occurredAt: string) {
return { id, occurredAt };
}
describe('statementPages', () => {
it('prints an empty statement as one page', () => {
expect(statementPages([])).toEqual([[]]);
});
it('orders rows oldest first', () => {
const pages = statementPages(
[
row('b', '2026-11-02T00:00:00.000Z'),
row('a', '2026-11-03T00:00:00.000Z'),
row('c', '2026-11-01T00:00:00.000Z'),
],
14,
9,
);
expect(pages).toHaveLength(1);
expect(pages[0].map((item) => item.id)).toEqual(['c', 'b', 'a']);
});
it('keeps a short overflow on the same page instead of a one-row sheet', () => {
const rows = Array.from({ length: 10 }, (_, index) =>
row(String(index).padStart(2, '0'), `2026-11-${String(index + 1).padStart(2, '0')}T00:00:00.000Z`),
);
expect(statementPages(rows, 14, 9)).toHaveLength(1);
});
it('keeps the last page short enough for the totals', () => {
const rows = Array.from({ length: 23 }, (_, index) =>
row(String(index).padStart(2, '0'), `2026-11-${String(index + 1).padStart(2, '0')}T00:00:00.000Z`),
);
const pages = statementPages(rows, 14, 9);
expect(pages.map((page) => page.length)).toEqual([14, 9]);
expect(pages[0][0].id).toBe('00');
expect(pages[1][8].id).toBe('22');
});
it('breaks the tie on id when two rows share a time', () => {
const pages = statementPages(
[row('b', '2026-11-01T00:00:00.000Z'), row('a', '2026-11-01T00:00:00.000Z')],
14,
9,
);
expect(pages[0].map((item) => item.id)).toEqual(['a', 'b']);
});
});

View File

@@ -0,0 +1,33 @@
export const STATEMENT_ROWS_PER_PAGE = 20;
export const STATEMENT_ROWS_ON_LAST_PAGE = 15;
type StatementRow = {
id: string;
occurredAt: string;
};
/** Oldest first, with the totals reserved on the last page. */
export function statementPages<T extends StatementRow>(
rows: readonly T[],
rowsPerPage = STATEMENT_ROWS_PER_PAGE,
rowsOnLastPage = STATEMENT_ROWS_ON_LAST_PAGE,
): T[][] {
const ordered = [...rows].sort((a, b) => {
const byTime = a.occurredAt.localeCompare(b.occurredAt);
if (byTime !== 0) return byTime;
return a.id.localeCompare(b.id);
});
if (ordered.length === 0) return [[]];
if (ordered.length <= rowsPerPage) return [ordered];
const pages: T[][] = [];
let offset = 0;
while (ordered.length - offset > rowsOnLastPage) {
const leftover = ordered.length - offset - rowsOnLastPage;
if (leftover < rowsPerPage && leftover + rowsOnLastPage <= rowsPerPage) break;
const take = Math.min(rowsPerPage, leftover);
pages.push(ordered.slice(offset, offset + take));
offset += take;
}
pages.push(ordered.slice(offset));
return pages;
}

View File

@@ -0,0 +1,212 @@
import { createRoot } from 'react-dom/client';
import { createElement } from 'react';
import { jsPDF } from 'jspdf';
import html2canvas from 'html2canvas';
import {
BillingStatementPrintLayout,
STATEMENT_TABLE_ROW_HEIGHT,
type BillingStatementPrintLabels,
type BillingStatementPrintRow,
} from '@/components/ui/billing/BillingStatementPrintLayout';
export type StatementPdfPage = {
rows: readonly BillingStatementPrintRow[];
showTotals: boolean;
pageLabel: string;
};
type DownloadStatementPdfArgs = {
locale: string;
fontFamily: string;
issuerName: string;
issuerPhone: string | null;
partyName: string;
labels: Omit<BillingStatementPrintLabels, 'page'>;
pages: readonly StatementPdfPage[];
debit: string;
credit: string;
balance: string;
fileName: string;
};
export function statementPrintFontFamily(locale: string): string {
if (locale !== 'fa' || typeof document === 'undefined') {
return 'system-ui, -apple-system, "Segoe UI", sans-serif';
}
const style = getComputedStyle(document.documentElement);
const vazir = style.getPropertyValue('--font-vazirmatn').trim();
const noto = style.getPropertyValue('--font-noto-sans-arabic').trim();
return [vazir, noto, 'Tahoma', '"Segoe UI"', 'sans-serif'].filter(Boolean).join(', ');
}
function waitForPaint(): Promise<void> {
return new Promise((resolve) => {
requestAnimationFrame(() => {
requestAnimationFrame(() => resolve());
});
});
}
function stripClonedStyles(clonedDoc: Document) {
clonedDoc.querySelectorAll('style, link[rel="stylesheet"]').forEach((node) => {
const css = node instanceof HTMLStyleElement ? (node.textContent ?? '') : '';
if (css.includes('@font-face') && !/oklch\(|\blab\(/i.test(css)) return;
node.remove();
});
clonedDoc.querySelectorAll('[data-statement-org]').forEach((node) => {
if (!(node instanceof HTMLElement)) return;
node.style.display = 'flex';
node.style.alignItems = 'center';
node.style.justifyContent = 'flex-start';
node.style.height = '56px';
node.style.lineHeight = '56px';
node.style.overflow = 'hidden';
node.style.direction = 'ltr';
node.style.letterSpacing = '0px';
node.style.wordSpacing = '0px';
const text = node.querySelector('[data-statement-org-text]');
if (!(text instanceof HTMLElement)) return;
text.style.display = 'inline-block';
text.style.maxWidth = '100%';
text.style.overflow = 'visible';
text.style.lineHeight = '56px';
text.style.paddingTop = '0';
text.style.paddingBottom = '0';
text.style.letterSpacing = '0px';
text.style.wordSpacing = '0px';
text.style.whiteSpace = 'nowrap';
text.style.unicodeBidi = 'isolate';
});
clonedDoc.querySelectorAll('[data-statement-lockup]').forEach((node) => {
if (!(node instanceof HTMLElement)) return;
node.style.height = '32px';
node.style.lineHeight = '32px';
node.style.overflow = 'hidden';
});
clonedDoc.querySelectorAll('[data-statement-cell]').forEach((node) => {
if (!(node instanceof HTMLElement)) return;
node.style.display = 'flex';
node.style.alignItems = 'center';
node.style.height = `${STATEMENT_TABLE_ROW_HEIGHT}px`;
node.style.boxSizing = 'border-box';
node.style.direction = 'ltr';
});
clonedDoc.querySelectorAll('[data-statement-lockup] svg').forEach((node) => {
if (!(node instanceof SVGSVGElement)) return;
const parts = (node.getAttribute('viewBox') ?? '').trim().split(/[\s,]+/).map(Number);
const vbW = parts[2];
const vbH = parts[3];
if (!vbW || !vbH) return;
const height = 26;
const width = Math.max(1, Math.round(height * (vbW / vbH)));
node.setAttribute('width', String(width));
node.setAttribute('height', String(height));
node.style.width = `${width}px`;
node.style.height = `${height}px`;
node.style.verticalAlign = 'middle';
node.style.overflow = 'hidden';
});
}
/**
* One A4 page per slice. Each page is captured at its own size so a long
* ledger is not shrunk onto a single sheet.
*/
export async function downloadStatementPdf({
locale,
fontFamily,
issuerName,
issuerPhone,
partyName,
labels,
pages,
debit,
credit,
balance,
fileName,
}: DownloadStatementPdfArgs): Promise<void> {
const host = document.createElement('div');
host.setAttribute('aria-hidden', 'true');
host.style.cssText =
'position:fixed;left:-12000px;top:0;z-index:-1;pointer-events:none;background:#fff;';
document.body.appendChild(host);
const root = createRoot(host);
try {
root.render(
createElement(
'div',
null,
pages.map((page, index) =>
createElement(BillingStatementPrintLayout, {
key: index,
locale,
fontFamily,
issuerName,
issuerPhone,
partyName,
labels: { ...labels, page: page.pageLabel },
rows: page.rows,
showTotals: page.showTotals,
debit,
credit,
balance,
}),
),
),
);
await waitForPaint();
await new Promise((resolve) => setTimeout(resolve, 80));
const sheets = [...host.querySelectorAll('[data-statement-root]')];
if (sheets.length === 0) {
throw new Error('Statement root not found');
}
const pdf = new jsPDF({ orientation: 'portrait', unit: 'mm', format: 'a4' });
const pageWidth = pdf.internal.pageSize.getWidth();
const pageHeight = pdf.internal.pageSize.getHeight();
const margin = 4;
const usableWidth = pageWidth - margin * 2;
const usableHeight = pageHeight - margin * 2;
for (let index = 0; index < sheets.length; index += 1) {
const sheet = sheets[index];
if (!(sheet instanceof HTMLElement)) continue;
const canvas = await html2canvas(sheet, {
scale: 2,
backgroundColor: '#ffffff',
useCORS: true,
logging: false,
scrollX: 0,
scrollY: 0,
onclone: stripClonedStyles,
});
if (index > 0) pdf.addPage();
const imgData = canvas.toDataURL('image/png');
let drawWidth = usableWidth;
let drawHeight = (canvas.height * drawWidth) / canvas.width;
if (drawHeight > usableHeight) {
drawHeight = usableHeight;
drawWidth = (canvas.width * drawHeight) / canvas.height;
}
const x = margin + (usableWidth - drawWidth) / 2;
pdf.addImage(imgData, 'PNG', x, margin, drawWidth, drawHeight);
}
pdf.save(fileName);
} finally {
root.unmount();
host.remove();
}
}
export function statementPdfFileName(partyName: string, from?: string, to?: string): string {
const slug =
partyName
.trim()
.toLowerCase()
.replace(/[^\p{L}\p{N}]+/gu, '-')
.replace(/^-+|-+$/g, '') || 'party';
const range = [from, to].filter(Boolean).join('_') || 'all';
return `statement-${slug}-${range}.pdf`;
}

View File

@@ -1,7 +1,7 @@
'use client';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslations } from 'next-intl';
import { useLocale, useTranslations } from 'next-intl';
import { Check, Paperclip, Pencil, Search, X } from 'lucide-react';
import { labBlockedBannerClass } from '@/components/treatment/treatmentStatusStyles';
import { Button } from '@/components/ui/shared/Button';
@@ -34,7 +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 { splitStaffCompensation } from '@/components/billing/staffCompensation';
import type { StaffCompensationTotals } from '@/components/billing/staffCompensation';
import { statementPages } from '@/components/billing/statementPages';
import {
downloadStatementPdf,
statementPdfFileName,
statementPrintFontFamily,
} from '@/components/billing/statementPdf';
import { BillingStaffIncomeDialog } from '@/components/ui/billing/BillingStaffIncomeDialog';
import type {
AllocationCaseHit,
AllocationTreatmentHit,
@@ -96,6 +104,11 @@ function caseOriginLabelKey(
return null;
}
function staffMonthPeriodKey(row: BillingPartyReportRow): string | null {
if (row.sourceType !== 'STAFF_COMMISSION_MONTH') return null;
return row.reference || null;
}
function sectionToPartyKind(section: BillingPartySectionKey): BillingPartyKind {
if (section === 'patients') return 'patient';
if (section === 'staff') return 'staff';
@@ -112,8 +125,9 @@ export function BillingPaymentsPanel({
const t = useTranslations('billing');
const tCommon = useTranslations('common');
const tErrors = useTranslations('errors');
const locale = useLocale();
const toast = useToast();
const { formatDateTime, formatMoney } = useAppFormatters();
const { formatDate, formatDateTime, formatMoney } = useAppFormatters();
const { settings: currencySettings, reload: reloadCurrency } = useBillingCurrency(true);
const isClinic = orgType === 'CLINIC';
@@ -178,6 +192,7 @@ export function BillingPaymentsPanel({
);
const [allocations, setAllocations] = useState<DraftAlloc[]>([]);
const [saving, setSaving] = useState(false);
const [incomePeriodKey, setIncomePeriodKey] = useState<string | null>(null);
const patientSelected = selectedParty?.section === 'patients';
const staffSelected = selectedParty?.section === 'staff';
@@ -469,10 +484,73 @@ export function BillingPaymentsPanel({
: netNumber >= 0
? 'text-emerald-700 dark:text-emerald-400'
: 'text-red-700 dark:text-red-400';
const compensation = useMemo(
() => staffCompensationTotals(report?.data ?? []),
const compensationSplit = useMemo(
() => splitStaffCompensation(report?.data ?? []),
[report?.data],
);
const openThrough = report?.data.find((row) => row.projected)?.occurredAt ?? null;
const reportOrgSelected =
filterParty?.section === 'clinics' || filterParty?.section === 'labs';
async function printStatement() {
if (!report || !filterParty || !reportOrgSelected) return;
const pages = statementPages(report.data);
let number = 0;
const fromLabel = from ? formatDate(`${from}T12:00:00`) : '';
const toLabel = to ? formatDate(`${to}T12:00:00`) : '';
const rangeLabel =
from && to
? t('statementRange', { from: fromLabel, to: toLabel })
: from
? t('statementRangeFrom', { from: fromLabel })
: to
? t('statementRangeTo', { to: toLabel })
: t('statementRangeAll');
try {
await downloadStatementPdf({
locale,
fontFamily: statementPrintFontFamily(locale),
issuerName: report.issuer.name,
issuerPhone: report.issuer.phone,
partyName: filterParty.name,
debit: formatMoney(report.totals.debit),
credit: formatMoney(report.totals.credit),
balance: formatMoney(report.totals.net),
fileName: statementPdfFileName(filterParty.name, from || undefined, to || undefined),
labels: {
title: t('statementTitle'),
addressedTo: t('statementAddressedTo'),
phone: t('statementPhone'),
printedOn: t('statementPrintedOn', { date: formatDate(new Date()) }),
rowNumber: t('statementRowNumber'),
date: t('time'),
reference: t('reference'),
amount: amountLabel,
debit: t('debit'),
credit: t('credit'),
balance: t('balanceTotal'),
range: rangeLabel,
empty: t('reportEmpty'),
},
pages: pages.map((page, index) => ({
showTotals: index === pages.length - 1,
pageLabel: t('statementPage', { page: index + 1, pages: pages.length }),
rows: page.map((row) => {
number += 1;
return {
number,
date: formatDateTime(row.occurredAt),
reference: row.reference,
amount: row.amount == null ? '' : formatMoney(row.amount),
direction: row.direction === 'DEBIT' ? t('debit') : t('credit'),
};
}),
})),
});
} catch (error: unknown) {
toast.showError(getUserFacingError(error, tErrors, t('errorPrintStatement')));
}
}
async function submitCreate() {
const parsedAmount = parseAppMoney(amount);
@@ -766,33 +844,47 @@ export function BillingPaymentsPanel({
</Card>
) : null}
{filterParty && sectionToPartyKind(filterParty.section) === 'staff' ? (
{filterParty &&
sectionToPartyKind(filterParty.section) === 'staff' &&
compensationSplit.open ? (
<Card className="space-y-3">
<div className="grid grid-cols-1 gap-2 text-sm sm:grid-cols-3">
<div className="rounded-[var(--radius-sm)] bg-background-secondary/70 p-3">
<p className="text-text-muted">{t('commissionSubtotal')}</p>
<p className="font-medium tabular-nums text-text-primary">
{formatMoney(compensation.commission)}
</p>
</div>
<div className="rounded-[var(--radius-sm)] bg-background-secondary/70 p-3">
<p className="text-text-muted">{t('fixedSalarySubtotal')}</p>
<p className="font-medium tabular-nums text-text-primary">
{formatMoney(compensation.fixedSalary)}
</p>
</div>
<div className="rounded-[var(--radius-sm)] bg-background-secondary/70 p-3">
<p className="text-text-muted">{t('grossCompensation')}</p>
<p className="font-semibold tabular-nums text-text-primary">
{formatMoney(compensation.gross)}
</p>
</div>
<div className="flex flex-wrap items-center justify-between gap-2">
<h3 className="text-sm font-semibold text-text-primary">
{t('openMonthCompensation', {
date: openThrough ? formatDate(`${openThrough.slice(0, 10)}T12:00:00`) : '',
})}
</h3>
{compensationSplit.openPeriodKey ? (
<Button
size="sm"
variant="outline"
onClick={() => setIncomePeriodKey(compensationSplit.openPeriodKey)}
>
{t('showIncomeDetails')}
</Button>
) : null}
</div>
<CompensationFigures
totals={compensationSplit.open}
formatMoney={formatMoney}
labels={{
commission: t('commissionSubtotal'),
salary: t('fixedSalarySubtotal'),
gross: t('grossCompensation'),
}}
/>
</Card>
) : null}
<div className="space-y-2">
<h2 className="text-sm font-semibold text-text-primary">{t('transactionHistory')}</h2>
<div className="flex flex-wrap items-center justify-between gap-2">
<h2 className="text-sm font-semibold text-text-primary">{t('transactionHistory')}</h2>
{reportOrgSelected && report && !loading ? (
<Button size="sm" variant="outline" onClick={() => printStatement()}>
{t('printStatement')}
</Button>
) : null}
</div>
{loading ? (
<p className="text-sm text-text-muted">{tCommon('loading')}</p>
) : selectedMode && report && filterParty ? (
@@ -945,6 +1037,15 @@ export function BillingPaymentsPanel({
</td>
<td>
<div className="flex items-center gap-1">
{!editingAmount && staffMonthPeriodKey(row) ? (
<Button
size="sm"
variant="ghost"
onClick={() => setIncomePeriodKey(staffMonthPeriodKey(row))}
>
{t('showIncomeDetails')}
</Button>
) : null}
{editingAmount ? (
<>
<Button
@@ -1229,6 +1330,42 @@ export function BillingPaymentsPanel({
/>
)}
</div>
{incomePeriodKey && filterParty && sectionToPartyKind(filterParty.section) === 'staff' ? (
<BillingStaffIncomeDialog
userId={filterParty.id}
periodKey={incomePeriodKey}
to={to || undefined}
staffName={filterParty.name}
onClose={() => setIncomePeriodKey(null)}
/>
) : null}
</div>
);
}
function CompensationFigures({
totals,
formatMoney,
labels,
}: {
totals: StaffCompensationTotals;
formatMoney: (value: number) => string;
labels: { commission: string; salary: string; gross: string };
}) {
return (
<div className="grid grid-cols-1 gap-2 text-sm sm:grid-cols-3">
<div className="rounded-[var(--radius-sm)] bg-background-secondary/70 p-3">
<p className="text-text-muted">{labels.commission}</p>
<p className="font-medium tabular-nums text-text-primary">{formatMoney(totals.commission)}</p>
</div>
<div className="rounded-[var(--radius-sm)] bg-background-secondary/70 p-3">
<p className="text-text-muted">{labels.salary}</p>
<p className="font-medium tabular-nums text-text-primary">{formatMoney(totals.fixedSalary)}</p>
</div>
<div className="rounded-[var(--radius-sm)] bg-background-secondary/70 p-3">
<p className="text-text-muted">{labels.gross}</p>
<p className="font-semibold tabular-nums text-text-primary">{formatMoney(totals.gross)}</p>
</div>
</div>
);
}

View File

@@ -0,0 +1,190 @@
'use client';
import { useEffect, useState } from 'react';
import { useTranslations } from 'next-intl';
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 { billingApi } from '@/lib/api/billing';
import { getUserFacingError } from '@/components/shared/formatApiError';
import { useAppFormatters } from '@/lib/hooks/useAppFormatters';
import type { StaffIncomeDetail } from '@/types/billing';
type BillingStaffIncomeDialogProps = {
userId: string;
periodKey: string;
to?: string;
staffName: string;
onClose: () => void;
};
export function BillingStaffIncomeDialog({
userId,
periodKey,
to,
staffName,
onClose,
}: BillingStaffIncomeDialogProps) {
const t = useTranslations('billing');
const tCommon = useTranslations('common');
const tErrors = useTranslations('errors');
const { formatDate, formatDateTime, formatMoney, formatNumber } = useAppFormatters();
const [detail, setDetail] = useState<StaffIncomeDetail['data'] | null>(null);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
let cancelled = false;
setLoading(true);
setError(null);
void billingApi
.getStaffIncome({ userId, periodKey, to })
.then((response) => {
if (!cancelled) setDetail(response.data);
})
.catch((err: unknown) => {
if (!cancelled) setError(getUserFacingError(err, tErrors, t('errorLoadIncome')));
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [periodKey, t, tErrors, to, userId]);
const commission = detail?.commission;
const mismatch =
commission?.postedAmount != null && commission.postedAmount !== commission.listedAmount;
const groupSum = (commission?.groups ?? []).reduce(
(sum, group) => sum + Number(group.amount),
0,
);
return (
<ResponsiveDialogOverlay onBackdropClick={onClose}>
<ResponsiveDialogPanel
maxWidthClass="sm:max-w-3xl"
role="dialog"
aria-modal="true"
aria-labelledby="staff-income-title"
>
<div className="mb-4 flex items-start justify-between gap-3">
<div className="min-w-0">
<h2 id="staff-income-title" className="text-base font-semibold text-text-primary">
{t('incomeDetailsTitle', { period: detail?.period.label ?? periodKey })}
</h2>
<p className="mt-1 text-sm text-text-muted">{staffName}</p>
{detail?.open && detail.reportDay ? (
<p className="mt-1 text-sm text-text-secondary">
{t('incomeThrough', { date: formatDate(`${detail.reportDay}T12:00:00`) })}
</p>
) : null}
</div>
<DialogCloseButton onClick={onClose} />
</div>
{loading ? <p className="text-sm text-text-muted">{tCommon('loading')}</p> : null}
{error ? <p className="text-sm text-red-700 dark:text-red-400">{error}</p> : null}
{detail && commission ? (
<div className="space-y-5">
<section className="space-y-2">
<h3 className="text-sm font-semibold text-text-primary">{t('commissionByStep')}</h3>
{mismatch ? (
<p className="text-sm text-text-secondary">
{t('incomePostedMismatch', {
posted: formatMoney(commission.postedAmount),
listed: formatMoney(commission.listedAmount),
})}
</p>
) : null}
{commission.groups.length > 0 ? (
<Table
headers={
<tr>
<th className={TABLE_HEADER_CELL_CLASS}>{t('incomeStep')}</th>
<th className={TABLE_HEADER_CELL_CLASS}>{t('incomeUnitAmount')}</th>
<th className={TABLE_HEADER_CELL_CLASS}>{t('incomeQuantity')}</th>
<th className={TABLE_HEADER_CELL_CLASS}>{t('incomeAmount')}</th>
</tr>
}
body={[
...commission.groups.map((group) => (
<tr key={`${group.catalogCode}:${group.unitAmount}`}>
<td className="text-sm text-text-primary">{group.label}</td>
<td className="text-sm tabular-nums text-text-secondary">
{formatMoney(group.unitAmount)}
</td>
<td className="text-sm tabular-nums text-text-secondary">
{formatNumber(Number(group.qty))}
</td>
<td className="text-sm tabular-nums text-text-primary">
{formatMoney(group.amount)}
</td>
</tr>
)),
<tr key="sum">
<td className="text-sm font-semibold text-text-primary">{t('incomeSum')}</td>
<td />
<td />
<td className="text-sm font-semibold tabular-nums text-text-primary">
{formatMoney(groupSum.toFixed(2))}
</td>
</tr>,
]}
/>
) : (
<p className="text-sm text-text-secondary">{t('incomeEmptyCommission')}</p>
)}
</section>
{commission.lines.length > 0 ? (
<section className="space-y-2">
<h3 className="text-sm font-semibold text-text-primary">{t('earningRecords')}</h3>
<Table
headers={
<tr>
<th className={TABLE_HEADER_CELL_CLASS}>{t('time')}</th>
<th className={TABLE_HEADER_CELL_CLASS}>{t('incomeStep')}</th>
<th className={TABLE_HEADER_CELL_CLASS}>{t('reference')}</th>
<th className={TABLE_HEADER_CELL_CLASS}>{t('incomeQuantity')}</th>
<th className={TABLE_HEADER_CELL_CLASS}>{t('incomeUnitAmount')}</th>
<th className={TABLE_HEADER_CELL_CLASS}>{t('incomeAmount')}</th>
</tr>
}
body={commission.lines.map((line) => (
<tr key={line.id}>
<td className="text-sm text-text-secondary">{formatDateTime(line.earnedAt)}</td>
<td className="text-sm text-text-primary">{line.label}</td>
<td className="text-sm text-text-secondary">{line.reference || '—'}</td>
<td className="text-sm tabular-nums text-text-secondary">
{formatNumber(Number(line.qty))}
</td>
<td className="text-sm tabular-nums text-text-secondary">
{formatMoney(line.unitAmount)}
</td>
<td className="text-sm tabular-nums text-text-primary">
{formatMoney(line.earnedAmount)}
</td>
</tr>
))}
/>
</section>
) : null}
<div className="flex justify-end">
<Button variant="ghost" onClick={onClose}>
{t('cancel')}
</Button>
</div>
</div>
) : null}
</ResponsiveDialogPanel>
</ResponsiveDialogOverlay>
);
}

View File

@@ -0,0 +1,438 @@
import type { CSSProperties } from 'react';
import { BrandLockup } from '@/components/ui/shared/BrandLockup';
export type BillingStatementPrintRow = {
number: number;
date: string;
reference: string;
amount: string;
direction: string;
};
export type BillingStatementPrintLabels = {
title: string;
addressedTo: string;
phone: string;
printedOn: string;
rowNumber: string;
date: string;
reference: string;
amount: string;
debit: string;
credit: string;
balance: string;
page: string;
range: string;
empty: string;
};
type BillingStatementPrintLayoutProps = {
locale: string;
fontFamily: string;
issuerName: string;
issuerPhone: string | null;
partyName: string;
labels: BillingStatementPrintLabels;
rows: readonly BillingStatementPrintRow[];
showTotals: boolean;
debit: string;
credit: string;
balance: string;
};
const PAGE = { width: 794, height: 1123 };
const INK = '#0f172a';
const MUTED = '#64748b';
const LINE = '#cbd5e1';
const RULE_GAP = 12;
const FA_RULE_DROP = 6;
const ARABIC_SCRIPT = /[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF]/;
const body = { color: INK, fontSize: 17, lineHeight: '22px' };
function printLabelStyle(rtl: boolean): CSSProperties {
return {
color: MUTED,
fontSize: 14,
fontWeight: 600,
lineHeight: '18px',
margin: 0,
...(rtl
? {
direction: 'rtl',
textAlign: 'right',
letterSpacing: '0px',
wordSpacing: '0px',
textTransform: 'none',
}
: { letterSpacing: '0.04em', textTransform: 'uppercase' }),
};
}
function printHeadingStyle(rtl: boolean): CSSProperties {
return {
margin: 0,
fontSize: 20,
fontWeight: 600,
lineHeight: '26px',
...(rtl
? {
direction: 'rtl',
textAlign: 'right',
letterSpacing: '0px',
wordSpacing: '0px',
textTransform: 'none',
}
: {}),
};
}
function printRtlValueStyle(value: string): CSSProperties {
const arabic = ARABIC_SCRIPT.test(value);
return {
direction: arabic ? 'rtl' : 'ltr',
unicodeBidi: 'isolate',
textAlign: 'right',
letterSpacing: '0px',
wordSpacing: '0px',
};
}
function valueStyle(value: string, rtl: boolean): CSSProperties {
return rtl ? printRtlValueStyle(value) : {};
}
function printRule(rtl: boolean): CSSProperties {
return {
borderTop: `1px solid ${LINE}`,
marginTop: rtl ? RULE_GAP + FA_RULE_DROP : RULE_GAP,
paddingTop: 8,
};
}
/** Previous rows were an 18px line box. 1.5× keeps the text clear of the grid. */
export const STATEMENT_TABLE_ROW_HEIGHT = 27;
const TABLE_FONT = 14;
/**
* Vazirmatn is painted on the bottom rule. 10px is about 2.5mm on the A4 page,
* enough to sit the glyphs in the middle of the row.
*/
const FA_CELL_LIFT = '-10px';
function faTextLift(rtl: boolean): CSSProperties {
return rtl ? { position: 'relative', top: FA_CELL_LIFT } : {};
}
function cellStyle(rtl: boolean): CSSProperties {
return {
boxSizing: 'content-box',
height: STATEMENT_TABLE_ROW_HEIGHT,
border: `1px solid ${LINE}`,
padding: 0,
color: INK,
fontSize: TABLE_FONT,
lineHeight: `${TABLE_FONT}px`,
fontWeight: 400,
verticalAlign: 'middle',
textAlign: rtl ? 'right' : 'left',
letterSpacing: '0px',
wordSpacing: '0px',
textTransform: 'none',
};
}
function cellContent(rtl: boolean): CSSProperties {
return {
boxSizing: 'border-box',
display: 'flex',
alignItems: 'center',
justifyContent: rtl ? 'flex-end' : 'flex-start',
height: STATEMENT_TABLE_ROW_HEIGHT,
margin: 0,
padding: '0 8px',
overflow: rtl ? 'visible' : 'hidden',
whiteSpace: 'nowrap',
// The capture paints `direction: rtl` backwards. Keep LTR here; the table
// direction still places the columns from the right.
direction: 'ltr',
unicodeBidi: 'isolate',
textAlign: rtl ? 'right' : 'left',
letterSpacing: '0px',
wordSpacing: '0px',
};
}
export function BillingStatementPrintLayout({
locale,
fontFamily,
issuerName,
issuerPhone,
partyName,
labels,
rows,
showTotals,
debit,
credit,
balance,
}: BillingStatementPrintLayoutProps) {
const rtl = locale === 'fa';
const head: CSSProperties = {
...cellStyle(rtl),
color: MUTED,
fontWeight: 600,
};
const columns = [labels.rowNumber, labels.date, labels.reference, labels.amount];
return (
<div
data-statement-root
dir="ltr"
style={{
boxSizing: 'border-box',
width: PAGE.width,
height: PAGE.height,
paddingTop: 16,
paddingRight: 24,
paddingBottom: rtl ? 20 : 8,
paddingLeft: 24,
backgroundColor: '#ffffff',
color: INK,
fontFamily,
fontSize: 17,
lineHeight: '22px',
direction: 'ltr',
display: 'flex',
flexDirection: 'column',
...(rtl ? { letterSpacing: '0px', wordSpacing: '0px' } : {}),
}}
>
<header
style={{
display: 'flex',
alignItems: 'center',
gap: 12,
borderBottom: `1px solid ${LINE}`,
paddingBottom: rtl ? RULE_GAP + FA_RULE_DROP : RULE_GAP,
}}
>
<div
data-statement-org
style={{
margin: 0,
minWidth: 0,
flex: 1,
alignSelf: 'center',
display: 'flex',
alignItems: 'center',
justifyContent: 'flex-start',
height: 56,
overflow: 'hidden',
fontSize: 28,
fontWeight: 600,
lineHeight: '56px',
direction: 'ltr',
letterSpacing: '0px',
wordSpacing: '0px',
}}
>
<span
data-statement-org-text
style={{
display: 'inline-block',
maxWidth: '100%',
overflow: 'visible',
lineHeight: '56px',
whiteSpace: 'nowrap',
verticalAlign: 'middle',
letterSpacing: '0px',
wordSpacing: '0px',
unicodeBidi: 'isolate',
direction: ARABIC_SCRIPT.test(issuerName) ? 'rtl' : 'ltr',
textAlign: ARABIC_SCRIPT.test(issuerName) ? 'right' : 'left',
}}
>
{issuerName}
</span>
</div>
<div
data-statement-lockup
style={{
flexShrink: 0,
alignSelf: 'center',
height: 32,
color: INK,
fontSize: 26,
lineHeight: '32px',
}}
>
<BrandLockup
style={{ display: 'inline-flex', alignItems: 'center', height: 32, verticalAlign: 'middle' }}
/>
</div>
<div style={{ flex: 1, minWidth: 0, textAlign: 'right' }}>
<p style={{ ...printLabelStyle(rtl), textAlign: 'right' }}>{labels.printedOn}</p>
{issuerPhone ? (
<p
style={{
...body,
margin: '2px 0 0',
fontWeight: 500,
textAlign: 'right',
direction: 'ltr',
unicodeBidi: 'isolate',
letterSpacing: '0px',
}}
>
{issuerPhone}
</p>
) : null}
</div>
</header>
<section
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'flex-start',
gap: 12,
marginTop: RULE_GAP,
}}
>
<div style={{ minWidth: 0 }}>
<p style={printLabelStyle(rtl)}>{labels.addressedTo}</p>
<p
style={{
margin: '2px 0 0',
fontSize: 20,
fontWeight: 600,
lineHeight: '26px',
...valueStyle(partyName, rtl),
}}
>
{partyName}
</p>
</div>
<div style={{ flexShrink: 0, textAlign: rtl ? 'right' : 'left' }}>
<p style={{ ...body, margin: 0, fontWeight: 500, ...valueStyle(labels.range, rtl) }}>{labels.range}</p>
</div>
</section>
<h1 style={{ ...printHeadingStyle(rtl), marginTop: RULE_GAP }}>{labels.title}</h1>
<table
dir={rtl ? 'rtl' : 'ltr'}
style={{
width: '100%',
borderCollapse: 'collapse',
tableLayout: 'fixed',
marginTop: RULE_GAP,
}}
>
<colgroup>
<col style={{ width: '8%' }} />
<col style={{ width: '24%' }} />
<col style={{ width: '38%' }} />
<col style={{ width: '30%' }} />
</colgroup>
<thead>
<tr>
{columns.map((column) => (
<th key={column} style={head}>
<div data-statement-cell style={cellContent(rtl)}>
<span style={faTextLift(rtl)}>{column}</span>
</div>
</th>
))}
</tr>
</thead>
<tbody>
{rows.length === 0 ? (
<tr>
<td colSpan={4} style={{ ...cellStyle(rtl), color: MUTED }}>
<div data-statement-cell style={{ ...cellContent(false), justifyContent: 'center' }}>
{labels.empty}
</div>
</td>
</tr>
) : (
rows.map((row) => (
<tr key={row.number}>
<td style={cellStyle(rtl)}>
<div data-statement-cell style={cellContent(rtl)}>
<span style={faTextLift(rtl)}>{row.number}</span>
</div>
</td>
<td style={cellStyle(rtl)}>
<div data-statement-cell style={cellContent(rtl)}>
<span style={faTextLift(rtl)}>{row.date}</span>
</div>
</td>
<td style={cellStyle(rtl)}>
<div data-statement-cell style={cellContent(rtl)}>
<span style={faTextLift(rtl)}>{row.reference}</span>
</div>
</td>
<td style={cellStyle(rtl)}>
<div data-statement-cell style={cellContent(rtl)}>
<span style={faTextLift(rtl)}>
{rtl && row.direction ? (
<span style={{ marginRight: 8, color: MUTED }}>{row.direction}</span>
) : null}
{row.amount}
{!rtl && row.direction ? (
<span style={{ marginLeft: 8, color: MUTED }}>{row.direction}</span>
) : null}
</span>
</div>
</td>
</tr>
))
)}
</tbody>
</table>
<div style={{ flex: 1 }} />
{showTotals ? (
<div
style={{
display: 'flex',
justifyContent: 'flex-end',
gap: 24,
...printRule(rtl),
}}
>
{[
[labels.debit, debit],
[labels.credit, credit],
[labels.balance, balance],
].map(([label, value]) => (
<div key={label} style={{ minWidth: 120 }}>
<p style={{ ...printLabelStyle(rtl), textAlign: rtl ? 'right' : 'left' }}>{label}</p>
<p
style={{
...body,
margin: '2px 0 0',
fontWeight: 600,
...valueStyle(value, rtl),
}}
>
{value}
</p>
</div>
))}
</div>
) : null}
<footer
style={{
display: 'flex',
justifyContent: 'space-between',
...printRule(rtl),
}}
>
<span style={printLabelStyle(rtl)}>{labels.page}</span>
</footer>
</div>
);
}

View File

@@ -6,6 +6,7 @@ import type {
BillingLedgerRow,
BillingNamedOrg,
BillingPartyReport,
StaffIncomeDetail,
BillingPartySearchResult,
BillingSheet,
BillingSheetCatalog,
@@ -116,6 +117,15 @@ export const billingApi = {
return response.data;
},
getStaffIncome: async (params: {
userId: string;
periodKey: string;
to?: string;
}): Promise<StaffIncomeDetail> => {
const response = await apiClient.get('/billing/staff-income', { params });
return response.data;
},
getPartyReport: async (params: {
partyKind: 'patient' | 'staff' | 'org';
partyId: string;

View File

@@ -215,11 +215,43 @@ export type BillingPartyReport = {
success: boolean;
data: BillingPartyReportRow[];
totals: { debit: string; credit: string; net: string };
staffCompensation: {
commission: string;
fixedSalary: string;
gross: string;
} | null;
issuer: { name: string; phone: string | null };
};
export type StaffIncomeDetail = {
success: boolean;
data: {
period: {
key: string;
label: string;
calendar: 'JALALI' | 'GREGORIAN';
start: string;
end: string;
};
open: boolean;
reportDay: string | null;
commission: {
postedAmount: string | null;
listedAmount: string;
groups: Array<{
catalogCode: string;
label: string;
unitAmount: string;
qty: string;
amount: string;
}>;
lines: Array<{
id: string;
earnedAt: string;
catalogCode: string;
label: string;
qty: string;
unitAmount: string;
earnedAmount: string;
reference: string;
}>;
};
};
};
export type PartnerPayment = {