improvements: a data migration added for prod deployment.

This commit is contained in:
2026-11-11 23:12:07 +03:30
parent 1dfe152f54
commit 3198eae47b
6 changed files with 48 additions and 45 deletions

View File

@@ -15,7 +15,7 @@ alwaysApply: false
- **Cash edits:** amount, note, and valid allocations only; identity/type/currency/date/creator stay immutable. Patient/staff cash is org-editable; shared partner cash is editable only by `recorderOrganizationId`. Every shared edit resets acknowledgement to pending, uses `expectedUpdatedAt`, and appends a `BillingCashTransactionEvent`.
- **Obligations are automatic:** approved treatment → patient; sent/started/outsource case → mirrored org rows; monthly commission and fixed salary → staff. Cash creation remains separate and manual. Party reports union obligations with cash; on a party account, RECEIPT is credit and PAYMENT is debit. Shared partner cash counts for the recorder while pending; accepted cash counts for both; rejected cash stays visible to both but counts only for the recorder.
- **Fixed salary:** one sheet on Commissions/Salary (`GET`/`PUT /billing/staff-salaries`) for the owner and active members. Amounts stay on `Membership.fixedMonthlySalary`. Saving does not write a ledger row. After a month ends, the hourly job snapshots that rate once and sums that month's commissions; both are separate staff payables dated on the last day. A later edit does not change a closed month. A missed month is closed on the next run with the rate then on the sheet. Toman uses Jalali months; Dollar/Euro use Gregorian months. V1 has no attendance or proration.
- **Unpriced types:** price sheets can set `hideUnpricedTypes`. Clinic and lab chart pickers hide zero/missing-price types but keep already-selected jobs visible. An active lab sheet with the flag blocks clinic dispatch for unsupported jobs. If the flag is off and any case job is unpriced, dispatch creates mirrored pending obligations with no amount; only the destination lab's Billing editor sets the fee, which updates both sides.
- **Unpriced types:** price sheets can set `hideUnpricedTypes`. Commission sheets always store it false, and migration `20261111233000_sheet_flag_and_subscription_courtesy` sets every existing commission sheet unchecked. Existing fee sheets received false when `20261111130000_billing_obligations` added the column; their lines, targets, and dates are not rewritten. Clinic and lab chart pickers hide zero/missing-price types but keep already-selected jobs visible. An active lab sheet with the flag blocks clinic dispatch for unsupported jobs. If the flag is off and any case job is unpriced, dispatch creates mirrored pending obligations with no amount; only the destination lab's Billing editor sets the fee, which updates both sides.
- Money UI: `AppMoneyInput`; party field: `BillingPartyCombobox` (sections); list chrome: `BillingListToolbar` + `Table`. Cash/sheet labels: **Amount** (with org currency suffix).
- Billing is visible for CLINIC and LAB (`billingOrgTypes` is empty).
- Lab case pickers sort by `listedAt` desc (same COALESCE as Cases — never `sentAt` then `startedAt`).

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 + cash ledger (org currency lock, staff PAYMENT, party net) — `.cursor/rules/billing.mdc`, skill `.cursor/skills/billing/SKILL.md`.
- **Billing** (clinic + lab): fee/commission sheets, automatic obligations, and a cash ledger. The Commissions/Salary tab holds one current salary sheet; month-end rows are posted after the month ends. `hideUnpricedTypes` defaults off and commission sheets cannot turn it on. See `.cursor/rules/billing.mdc` and `.cursor/skills/billing/SKILL.md`.
## Agent behavior

View File

@@ -54,7 +54,7 @@ Keep chrome identical: `BillingListToolbar`, outline labels, `AppMoneyInput`, eq
## Fee / commission editor
- Start date required. Empty Apply-to = everyone. Lines store money `amount`.
- `CLINIC_PRICE` / `LAB_PRICE` may set `hideUnpricedTypes`. Missing or zero prosthesis lines are hidden from the applicable chart. A destination lab's active flagged sheet also blocks clinic Send.
- `CLINIC_PRICE` / `LAB_PRICE` may set `hideUnpricedTypes`. Commission kinds always save it false. Existing production sheets become unchecked when the column is added; a later one-time migration forces commission sheets false again. Missing or zero prosthesis lines are hidden from the applicable chart. A destination lab's active flagged sheet also blocks clinic Send.
- With a destination `LAB_PRICE` flag off, missing/zero case prices do not become zero or partial obligations: Send creates mirrored pending obligations (`amount = null`). The destination lab's Billing editor sets the manual case fee; the service updates `LabCase.billedAmount` and both ledger rows atomically.
- Treatment dispatch / outsource quote previews are not stored.
- A save replaces the lines the editor shows and keeps every stored line the editor does not send (`stain`, `glaze`, `build_up`, inactive prosthesis types). Those hidden lines still price existing tasks.

View File

@@ -68,9 +68,9 @@ frontend/src/
**Staff (quick ref):** Owner / `TAB_STAFF_EDIT` can **remove** a password (`POST /staff/members/:id/clear-password`) and copy a setup link — never set one for someone else. Login page unchanged (`passwordHash: null` cannot sign in). `/accept-invite` `password_setup` is password-only. See `.cursor/rules/staff.mdc`.
**Subscriptions (quick ref):** One **Base** plan includes 3 seats (the owner holds one). Extra seats are separate rows with their own end dates. Each owner gets one free month (`User.trialUsedAt`), stamped only after `grantForNewOwner` starts it. Do not set `trialUsedAt` before that call. A later organization gets Base seats that end immediately. Another organization with the same owner that already has `trialEndsAt` or any seat counts as later, even when `trialUsedAt` is still null. Migration `20261018120000_subscription_seats` runs once on deploy: every real organization gets Base for 30 days from that instant, 3 included seats, and an extra seat for each staff member past those 3. It does not set `trialUsedAt` and does not insert charge rows. Disabled members who are not the owner and have no open invite do not take a seat. Migration `20261023140000_drop_unreferenced_legacy_plans` deletes unused `trial`, `Small`, `Medium`, `Large`, and `Enterprise` plans and does not change any end date. Signup ensures the `base` plan. The free month is labeled Trial in the UI; the stored plan name stays `base`. Invitation placeholders (no members, and an invite that is still unaccepted) are left unchanged. During the free month an added seat costs $0 and ends with the base seats. After it, Add seat and Extend selected show the quote and then stop (`SUBSCRIPTION_PAYMENT_UNAVAILABLE`, contact Nudenticco@gmail.com). An overdue occupied seat is read-only. An overdue empty seat cannot be reserved. Owners and `TAB_BILLING_READ` manage Subscriptions. Cards show the assigned user. Other members get a `SEAT_EXPIRING` inbox notice 5 days before their seat ends.
**Subscriptions (quick ref):** One **Base** plan includes 3 seats (the owner holds one). Extra seats are separate rows with their own end dates. Each owner gets one free month (`User.trialUsedAt`), stamped only after `grantForNewOwner` starts it. Do not set `trialUsedAt` before that call. A later organization gets Base seats that end immediately. Another organization with the same owner that already has `trialEndsAt` or any seat counts as later, even when `trialUsedAt` is still null. Migration `20261018120000_subscription_seats` runs once on deploy: every real organization gets Base for 30 days from that instant, 3 included seats, and an extra seat for each staff member past those 3. It does not set `trialUsedAt` and does not insert charge rows. Disabled members who are not the owner and have no open invite do not take a seat. Migration `20261023140000_drop_unreferenced_legacy_plans` deletes unused `trial`, `Small`, `Medium`, `Large`, and `Enterprise` plans and does not change any end date. Migration `20261111233000_sheet_flag_and_subscription_courtesy` runs once: every existing seat and every non-null `trialEndsAt` gains 60 days (two 30-day subscription months). A date still in the future grows from itself; a date already past grows from that deploy. It does not insert seats or charge rows, and later deploys must not repeat it. Signup ensures the `base` plan. The free month is labeled Trial in the UI; the stored plan name stays `base`. Invitation placeholders (no members, and an invite that is still unaccepted) are left unchanged. During the free month an added seat costs $0 and ends with the base seats. After it, Add seat and Extend selected show the quote and then stop (`SUBSCRIPTION_PAYMENT_UNAVAILABLE`, contact Nudenticco@gmail.com). An overdue occupied seat is read-only. An overdue empty seat cannot be reserved. Owners and `TAB_BILLING_READ` manage Subscriptions. Cards show the assigned user. Other members get a `SEAT_EXPIRING` inbox notice 5 days before their seat ends.
**Billing (quick ref):** Same three-tab hub for CLINIC + LAB (`/billing?view=`). Clinic: `CLINIC_PRICE` / `CLINIC_COMMISSION` + patient receipts + partner payments. Lab: `LAB_PRICE` (prosthesis fees plus an outsourcing tab) / `LAB_COMMISSION` + partner ledger only. Commissions are **fixed amounts**. Automatic `BillingLedgerEntry` obligations come from treatment Approve, case Send/Start/outsource, and staff commission plus fixed salary after each month ends; Toman uses Jalali months, Dollar/Euro Gregorian. Selecting a party swaps the cash table to an inline obligation+cash ledger with signed amount/net; selected staff also show commission, fixed salary, and gross from closed months. Partner cash remains shared Accept/Decline; rejected rows stay visible to both but count only for the recorder. Only the exact recorder can edit shared cash, and edits reset acknowledgement. Salary is one editable sheet on Commissions/Salary for the owner and active members; editing it does not change a closed month. Salary and commission may both apply; v1 has no proration/attendance. Price sheets may hide unpriced prosthesis types; an active flagged lab sheet blocks clinic dispatch for unsupported jobs. If the flag is off, an unpriced case creates mirrored amount-pending obligations; only the destination lab sets the fee and it updates both orgs. Collapsed workflow prices and hidden legacy lines remain preserved. Money inputs: `AppMoneyInput`. See `.cursor/rules/billing.mdc`, `.cursor/skills/billing/SKILL.md`.
**Billing (quick ref):** Same three-tab hub for CLINIC + LAB (`/billing?view=`). Clinic: `CLINIC_PRICE` / `CLINIC_COMMISSION` + patient receipts + partner payments. Lab: `LAB_PRICE` (prosthesis fees plus an outsourcing tab) / `LAB_COMMISSION` + partner ledger only. Commissions are **fixed amounts**. Automatic `BillingLedgerEntry` obligations come from treatment Approve, case Send/Start/outsource, and staff commission plus fixed salary after each month ends; Toman uses Jalali months, Dollar/Euro Gregorian. Selecting a party swaps the cash table to an inline obligation+cash ledger with signed amount/net; selected staff also show commission, fixed salary, and gross from closed months. Partner cash remains shared Accept/Decline; rejected rows stay visible to both but count only for the recorder. Only the exact recorder can edit shared cash, and edits reset acknowledgement. Salary is one editable sheet on Commissions/Salary for the owner and active members; editing it does not change a closed month. Salary and commission may both apply; v1 has no proration/attendance. Price sheets may hide unpriced prosthesis types; existing fee and commission sheets deploy with that box unchecked, and commission sheets cannot turn it on. An active flagged lab sheet blocks clinic dispatch for unsupported jobs. If the flag is off, an unpriced case creates mirrored amount-pending obligations; only the destination lab sets the fee and it updates both orgs. Collapsed workflow prices and hidden legacy lines remain preserved. Money inputs: `AppMoneyInput`. See `.cursor/rules/billing.mdc`, `.cursor/skills/billing/SKILL.md`.
**Lab Tasks tab:** Newest case first (`listedAt`); grouping only for date sort; filters include completed step, origin, due date, assignment, and prosthesis. New tasks are plan-scoped: one scan → prosthesis sections → optional Model design/creation (when any type has `requiresModelSteps`) → packing/shipping. `lineCount` stays 1. `__line__` tasks are independently completable. A type with both dry milling and sintering generates `milling_dry_sinter`; both wet milling and sintering generate `milling_wet_sinter`; both stain and glaze generate `stain_glaze`. A type with only one half keeps that half, and existing task rows are not rewritten. Model design and model create can be outsourced with that line’s teeth, or the whole plan for a historical `__case__` model step; scan, packing, and shipping cannot. Historical `__case__` scan keeps whole-case fan-out. Same-type exclusive steps coalesce across matching teeth; duplicate non-model steps for stacked types become `typeA+typeB` sections. Pontics fold into connected crown/indirect sections. Task identity includes source, first tooth, section type, and workflow code because one section may produce different tooth sets across steps. Job titles use `ProsthesisJobLineLabel`; task assignment is in Cases; only assignee/unassigned pool can update status in Tasks. `CASE_COMPLETED` drives inbox/tab badges only after all case tasks finish. See `.cursor/skills/lab-tasks/SKILL.md`.

View File

@@ -0,0 +1,25 @@
-- Existing commission sheets never use the price-sheet checkbox.
-- Fee sheets added this column as false and are left as saved.
UPDATE "billing_sheets"
SET "hideUnpricedTypes" = false
WHERE "kind" IN ('CLINIC_COMMISSION', 'LAB_COMMISSION');
-- One courtesy only. Prisma records this migration and does not run it again.
-- A subscription month is 30 days, so two months is 60 days.
-- A due date still in the future grows from that date.
-- A due date already past grows from this deploy, so the extra time is usable.
-- Charge history is not changed.
UPDATE "organization_seats"
SET
"endsAt" = CASE
WHEN "endsAt" > CURRENT_TIMESTAMP THEN "endsAt" + INTERVAL '60 days'
ELSE CURRENT_TIMESTAMP + INTERVAL '60 days'
END,
"updatedAt" = CURRENT_TIMESTAMP;
UPDATE "organizations"
SET "trialEndsAt" = CASE
WHEN "trialEndsAt" > CURRENT_TIMESTAMP THEN "trialEndsAt" + INTERVAL '60 days'
ELSE CURRENT_TIMESTAMP + INTERVAL '60 days'
END
WHERE "trialEndsAt" IS NOT NULL;

View File

@@ -293,47 +293,25 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
select: { userId: true, fixedMonthlySalary: true },
});
const occurredAt = staffPeriodLastDay(period);
await this.prisma.$transaction(async (tx) => {
for (const membership of memberships) {
const amount = roundBillingAmount(Number(membership.fixedMonthlySalary ?? 0));
if (amount <= 0) continue;
const sourceId = `${membership.userId}:${period.key}:salary`;
const existing = await tx.billingLedgerEntry.findUnique({
where: {
organizationId_sourceType_sourceId: {
organizationId,
sourceType: BillingObligationSourceType.STAFF_SALARY_MONTH,
sourceId,
},
},
select: { id: true },
});
if (existing) continue;
try {
await tx.billingLedgerEntry.create({
data: {
organizationId,
partyKind: BillingLedgerPartyKind.STAFF,
partyId: membership.userId,
sourceType: BillingObligationSourceType.STAFF_SALARY_MONTH,
sourceId,
amount: new Prisma.Decimal(amount.toFixed(2)),
signedAmount: new Prisma.Decimal((-amount).toFixed(2)),
balanceSign: -1,
occurredAt,
},
});
} catch (error) {
if (
error instanceof Prisma.PrismaClientKnownRequestError &&
error.code === 'P2002'
) {
continue;
}
throw error;
}
}
const data = memberships.flatMap((membership) => {
const amount = roundBillingAmount(Number(membership.fixedMonthlySalary ?? 0));
if (amount <= 0) return [];
return [
{
organizationId,
partyKind: BillingLedgerPartyKind.STAFF,
partyId: membership.userId,
sourceType: BillingObligationSourceType.STAFF_SALARY_MONTH,
sourceId: `${membership.userId}:${period.key}:salary`,
amount: new Prisma.Decimal(amount.toFixed(2)),
signedAmount: new Prisma.Decimal((-amount).toFixed(2)),
balanceSign: -1,
occurredAt,
},
];
});
if (data.length === 0) return;
await this.prisma.billingLedgerEntry.createMany({ data, skipDuplicates: true });
}
async listSheets(