L14 Abrechnungsübersicht: Services für Einträge, Aufstellung, Abrechnen/Stornieren, Meilensteine und PDF

syncBillingCandidates (idempotent, Event-Hook für work_order.released_for_billing und report.approved), Aufstellung ohne Preise (nur freigegebene Zeiten, Fahrzeit getrennt, Pausen informativ, Anfahrten-Zählung, Material), markBilled mit eingefrorenem Snapshot und Positionszuordnung, voidBilling mit Grund und neuem offenen Eintrag (billed → released_for_billing nur über applyTransition-Option billingVoid), Meilenstein-Flow mit Events, Job billing-pdf (Dokument other/backoffice_only), Sync-Op milestone.reach.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-15 10:35:38 +02:00
co-authored by Claude Opus 5
parent 6358d5762c
commit ac2d857e26
27 changed files with 2179 additions and 5 deletions
+9
View File
@@ -13,4 +13,13 @@ export async function emitEvent(ctx: ServiceCtx, event: DomainEvent): Promise<vo
} catch (err) {
console.error(`[events] ${event.type} for ${event.entityType}:${event.entityId} failed:`, (err as Error).message);
}
// L14 Abrechnungsübersicht: billing candidates after billing release / daily report approval (idempotent, never throws)
if (event.type === "work_order.released_for_billing" || event.type === "report.approved") {
try {
const { onBillingEvent } = await import("@/server/services/billing/events");
await onBillingEvent(ctx, event);
} catch (err) {
console.error(`[events] billing hook for ${event.type} ${event.entityId} failed:`, (err as Error).message);
}
}
}
+19
View File
@@ -0,0 +1,19 @@
import { dbForTenant } from "@/server/db";
import type { ServiceCtx } from "@/server/services/context";
import { generateBillingPdf } from "@/server/services/billing/pdf";
import type { JobPayload } from "../queues";
/**
* Queue "billing-pdf": renders the PDF billing sheet of a billed record (lane L14).
* System context: tenant-bound db, stores the sheet via the central document service.
*/
export async function process(payload: JobPayload): Promise<void> {
const ctx: ServiceCtx = {
db: dbForTenant(payload.tenantId),
tenantId: payload.tenantId,
userId: payload.actorId ?? "system",
permissions: new Set(["billing:read", "work_order:read_all", "document:read_internal", "document:write"]),
};
const res = await generateBillingPdf(ctx, payload.entityId);
console.info(`[billing-pdf] ${payload.entityId}: ${res.skipped ? "already rendered" : `stored ${res.documentId}`}`);
}
+1
View File
@@ -13,6 +13,7 @@ export const PROCESSORS: Partial<Record<JobQueueName, () => Promise<JobProcessor
"report-pdf": () => import(/* turbopackIgnore: true */ "./report-pdf").then((m) => m.process), // worker-only (react-dom/server + Chromium), kept out of the app bundle
"image-derivatives": () => import("./image-derivatives").then((m) => m.process),
"ai-retention": () => import("./ai-retention").then((m) => m.process), // L10b: daily AI log retention (scheduled by the worker)
"billing-pdf": () => import(/* turbopackIgnore: true */ "./billing-pdf").then((m) => m.process), // L14: worker-only billing sheet PDF (react-dom/server + Chromium)
};
/** Inline fallback when no Redis is available (dev/demo). */
+1
View File
@@ -13,6 +13,7 @@ export const JOB_QUEUES = {
reportPdf: "report-pdf",
imageDerivatives: "image-derivatives",
aiRetention: "ai-retention",
billingPdf: "billing-pdf", // L14 Abrechnungsblatt
} as const;
export type JobQueueName = (typeof JOB_QUEUES)[keyof typeof JOB_QUEUES];
+46
View File
@@ -0,0 +1,46 @@
/* eslint-disable @next/next/no-head-element -- standalone print document for Chromium, not a Next.js page */
import { renderToStaticMarkup } from "react-dom/server";
import type { BillingStatement } from "@/lib/billing/statement";
import { DOCUMENT_THEME, documentFooterLine } from "@/lib/document-brand";
import { StatementDocument, statementCss, type Translate } from "@/components/billing/statement-document";
/**
* L14 billing sheet PDF (React SSR → static HTML → src/server/pdf/render.ts). Same markup as the
* detail/print pages (`StatementDocument`), themed with the Craftvia document CD.
*/
const esc = (s: string) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
export function renderBillingHtml(input: { statement: BillingStatement; t: Translate; locale: string; timeZone: string; fontDataUri?: string | null }) {
const { statement: s, t } = input;
const th = DOCUMENT_THEME;
const font = input.fontDataUri ? `"CraftviaInter",${th.bodyFont}` : th.bodyFont;
const css =
`${input.fontDataUri ? `@font-face{font-family:"CraftviaInter";src:url(${input.fontDataUri}) format("truetype");font-weight:100 900;}` : ""}` +
`@page{size:A4;}*{box-sizing:border-box;}html,body{margin:0;padding:0;background:${th.pageBackground};}` +
statementCss({ text: th.text, muted: th.textMuted, accent: th.accent, rule: th.rule, headBg: th.tableHeaderBackground, warn: th.accentStrong, font }).replace(/font-size:13px/, "font-size:9.5pt");
const html =
"<!doctype html>" +
renderToStaticMarkup(
<html lang={input.locale}>
<head>
<meta charSet="utf-8" />
<title>{`${t("sheet.title")} ${s.workOrder.number}`}</title>
<style dangerouslySetInnerHTML={{ __html: css }} />
</head>
<body>
<StatementDocument s={s} t={t} locale={input.locale} timeZone={input.timeZone} />
</body>
</html>,
);
const small = `font-family:${th.bodyFont};font-size:7pt;color:${th.textMuted};width:100%;padding:0 16mm;display:flex;justify-content:space-between;gap:6mm;`;
const created = new Intl.DateTimeFormat(input.locale, { timeZone: input.timeZone, dateStyle: "medium", timeStyle: "short" }).format(new Date(s.record.billedAt ?? s.generatedAt));
const headerHtml = `<div style="${small}"><span>${esc(s.tenant.name)}</span><span>${esc(t("sheet.title"))} ${esc(s.workOrder.number)} · ${esc(t(`kind.${s.record.kind}`))}</span></div>`;
const page = esc(t("pdf.page", { page: "__P__", pages: "__N__" }))
.replace("__P__", '<span class="pageNumber"></span>')
.replace("__N__", '<span class="totalPages"></span>');
const footerHtml =
`<div style="${small}"><span>${esc(t("pdf.recordId"))}: ${esc(s.record.id)} · ${esc(t("pdf.created"))}: ${esc(created)}<br/>${esc(documentFooterLine())}</span>` +
`<span style="white-space:nowrap">${page}</span></div>`;
return { html, headerHtml, footerHtml };
}
+90
View File
@@ -0,0 +1,90 @@
import type { Prisma } from "@prisma/client";
import { dayWindow, dbDateToKey } from "@/lib/reports/dates";
import type { ServiceCtx } from "@/server/services/context";
import { tenantTimezone } from "@/server/services/work-orders/_shared";
/**
* Create missing `open` billing records of a work order (idempotent, L14 §3.2). Internal system
* operation: called from the event hook (work_order.released_for_billing, report.approved), from
* milestone confirmation and from scripts/billing-backfill.ts — it never checks user permissions
* and only reads/writes through the tenant client of `ctx`.
*
* Sources and periods:
* - order_completion: work order `released_for_billing` → from the end of the last billed section
* (or order creation) until now; contains everything of the order not billed yet.
* - milestone: confirmed milestone without record → from the end of the last billed section until
* the confirmation time; contains every unbilled position recorded before the confirmation.
* - daily_report: approved daily report of an order WITHOUT defined milestones → calendar day of
* the report (tenant time zone). A new report version replaces the report of a still open record.
*
* Duplicates are impossible: partial unique indexes (one non-voided record per source) + INSERT … ON
* CONFLICT DO NOTHING, which also keeps a surrounding transaction intact.
*/
export async function syncBillingCandidates(ctx: ServiceCtx, input: { workOrderId: string }, now = new Date()): Promise<{ created: number; updated: number }> {
const wo = await ctx.db.workOrder.findFirst({ where: { id: input.workOrderId, deletedAt: null }, select: { id: true, status: true, createdAt: true } });
if (!wo) return { created: 0, updated: 0 };
const [existing, milestones] = await Promise.all([
ctx.db.billingRecord.findMany({
where: { workOrderId: wo.id, status: { not: "voided" } },
select: { id: true, kind: true, status: true, milestoneId: true, reportId: true, periodTo: true },
}),
ctx.db.workOrderMilestone.findMany({ where: { workOrderId: wo.id, deletedAt: null }, select: { id: true, status: true, confirmedAt: true, billingRecordId: true } }),
]);
const billedTo = existing.filter((r) => r.status === "billed").map((r) => r.periodTo.getTime());
// nothing billed yet → from the first documented activity (work may be recorded before the order row was created, e.g. imports/Notdienst)
const periodFrom = billedTo.length ? new Date(Math.max(...billedTo)) : await firstActivity(ctx, wo.id, wo.createdAt);
const data: Prisma.BillingRecordCreateManyInput[] = [];
let updated = 0;
if (wo.status === "released_for_billing" && !existing.some((r) => r.kind === "order_completion")) {
data.push({ tenantId: ctx.tenantId, workOrderId: wo.id, kind: "order_completion", periodFrom, periodTo: now > periodFrom ? now : periodFrom });
}
for (const m of milestones) {
if (m.status !== "confirmed" || m.billingRecordId) continue;
if (existing.some((r) => r.kind === "milestone" && r.milestoneId === m.id)) continue;
const to = m.confirmedAt ?? now;
data.push({ tenantId: ctx.tenantId, workOrderId: wo.id, kind: "milestone", milestoneId: m.id, periodFrom: periodFrom < to ? periodFrom : to, periodTo: to });
}
if (milestones.length === 0) {
const reports = await ctx.db.report.findMany({
where: { workOrderId: wo.id, type: "daily", status: { in: ["approved", "superseded"] } },
select: { id: true, lineageId: true, status: true, reportDate: true },
});
const approved = reports.filter((r) => r.status === "approved");
if (approved.length) {
const tz = await tenantTimezone(ctx);
const lineageOf = new Map(reports.map((r) => [r.id, r.lineageId]));
for (const r of approved) {
const sameLineage = existing.filter((e) => e.kind === "daily_report" && e.reportId && lineageOf.get(e.reportId) === r.lineageId);
if (sameLineage.length) {
for (const e of sameLineage) {
if (e.status !== "open" || e.reportId === r.id) continue;
updated += (await ctx.db.billingRecord.updateMany({ where: { id: e.id, status: "open" }, data: { reportId: r.id } })).count;
}
continue;
}
const w = dayWindow(dbDateToKey(r.reportDate), tz);
data.push({ tenantId: ctx.tenantId, workOrderId: wo.id, kind: "daily_report", reportId: r.id, periodFrom: w.start, periodTo: w.end });
}
}
}
if (!data.length) return { created: 0, updated };
const res = await ctx.db.billingRecord.createMany({ data, skipDuplicates: true });
return { created: res.count, updated };
}
/** Earliest of: order creation, first time entry, first material entry, first approved report day. */
async function firstActivity(ctx: ServiceCtx, workOrderId: string, createdAt: Date): Promise<Date> {
const [entry, usage, report] = await Promise.all([
ctx.db.timeEntry.findFirst({ where: { workSession: { workOrderId } }, orderBy: { startedAt: "asc" }, select: { startedAt: true } }),
ctx.db.materialUsage.findFirst({ where: { workOrderId }, orderBy: { createdAt: "asc" }, select: { createdAt: true } }),
ctx.db.report.findFirst({ where: { workOrderId, status: "approved" }, orderBy: { reportDate: "asc" }, select: { reportDate: true } }),
]);
const times = [createdAt, entry?.startedAt, usage?.createdAt, report?.reportDate].filter((d): d is Date => !!d).map((d) => d.getTime());
return new Date(Math.min(...times));
}
+31
View File
@@ -0,0 +1,31 @@
import { writeAuditLog } from "@/server/audit";
import type { ServiceCtx } from "@/server/services/context";
/** Shared helpers of the billing overview (L14). */
export async function auditBilling(
ctx: ServiceCtx,
entity: "billing_record" | "work_order_milestone",
action: "create" | "update" | "delete",
entityId: string,
before?: unknown,
after?: unknown,
): Promise<void> {
await writeAuditLog({ tenantId: ctx.tenantId, actorId: ctx.userId, action, entity, entityId, before, after });
}
export function customerDisplay(c: { companyName: string | null; firstName: string | null; lastName: string | null; customerNumber?: string | null }): string {
return c.companyName || [c.firstName, c.lastName].filter(Boolean).join(" ") || c.customerNumber || "—";
}
export function addressOf(x: { street?: string | null; houseNumber?: string | null; postalCode?: string | null; city?: string | null }) {
return {
line1: [x.street, x.houseNumber].filter(Boolean).join(" ") || null,
line2: [x.postalCode, x.city].filter(Boolean).join(" ") || null,
};
}
/** JSON copy for audit before/after and snapshots (Dates → ISO strings). */
export function plain<T>(value: T): unknown {
return JSON.parse(JSON.stringify(value));
}
+16
View File
@@ -0,0 +1,16 @@
import type { DomainEvent } from "@/lib/events";
import type { ServiceCtx } from "@/server/services/context";
import { syncBillingCandidates } from "./candidates";
/**
* Event hook (called from src/server/events.ts#emitEvent): creates billing candidates after the
* existing billing release and daily report approval — without touching those services.
*/
export async function onBillingEvent(ctx: ServiceCtx, event: DomainEvent): Promise<void> {
if (event.type === "work_order.released_for_billing" && event.entityType === "work_order") {
await syncBillingCandidates(ctx, { workOrderId: event.entityId });
} else if (event.type === "report.approved" && event.entityType === "report") {
const report = await ctx.db.report.findFirst({ where: { id: event.entityId }, select: { workOrderId: true, type: true } });
if (report?.type === "daily") await syncBillingCandidates(ctx, { workOrderId: report.workOrderId });
}
}
+172
View File
@@ -0,0 +1,172 @@
import type { WorkOrderMilestone } from "@prisma/client";
import { z } from "zod";
import {
createMilestoneSchema,
milestoneReachPayload,
moveMilestoneSchema,
rejectMilestoneSchema,
updateMilestoneSchema,
type CreateMilestoneInput,
} from "@/lib/billing/schemas";
import { emitEvent } from "@/server/events";
import { assertCan, can, inTransaction, ServiceError, type ServiceCtx } from "@/server/services/context";
import { FINAL_STATUSES, loadVisibleWorkOrder, parseInput } from "@/server/services/work-orders/_shared";
import { syncBillingCandidates } from "./candidates";
import { auditBilling, plain } from "./common";
/**
* Work order milestones (L14 §3.4): back office defines sections (`work_order:write`, only while
* `open`), the field reports "reached" (`field:execute` + order in scope, or back office), back office
* confirms (→ billing record) or rejects with a reason (`billing:write`).
*/
async function requireMilestone(ctx: ServiceCtx, milestoneId: string): Promise<WorkOrderMilestone> {
const m = await ctx.db.workOrderMilestone.findFirst({ where: { id: milestoneId, deletedAt: null } });
if (!m) throw new ServiceError("not_found", "milestone_not_found");
return m;
}
/** Milestones of a visible work order (field roles: scope; back office: all). */
export async function listMilestones(ctx: ServiceCtx, workOrderId: string): Promise<WorkOrderMilestone[]> {
await loadVisibleWorkOrder(ctx, workOrderId);
return ctx.db.workOrderMilestone.findMany({ where: { workOrderId, deletedAt: null }, orderBy: [{ sortOrder: "asc" }, { createdAt: "asc" }] });
}
export async function createMilestone(ctx: ServiceCtx, raw: CreateMilestoneInput): Promise<WorkOrderMilestone> {
assertCan(ctx, "work_order:write");
const input = parseInput(createMilestoneSchema, raw);
const wo = await loadVisibleWorkOrder(ctx, input.workOrderId);
if (FINAL_STATUSES.includes(wo.status)) throw new ServiceError("invalid", "not_editable", { status: wo.status });
const last = await ctx.db.workOrderMilestone.findFirst({ where: { workOrderId: wo.id, deletedAt: null }, orderBy: { sortOrder: "desc" }, select: { sortOrder: true } });
const m = await ctx.db.workOrderMilestone.create({
data: { tenantId: ctx.tenantId, workOrderId: wo.id, title: input.title, description: input.description, sortOrder: (last?.sortOrder ?? 0) + 10, createdById: ctx.userId },
});
await auditBilling(ctx, "work_order_milestone", "create", m.id, undefined, plain(m));
return m;
}
async function requireEditable(ctx: ServiceCtx, milestoneId: string, { openOnly }: { openOnly: boolean }) {
const m = await requireMilestone(ctx, milestoneId);
const wo = await loadVisibleWorkOrder(ctx, m.workOrderId);
if (FINAL_STATUSES.includes(wo.status)) throw new ServiceError("invalid", "not_editable", { status: wo.status });
if (openOnly && m.status !== "open") throw new ServiceError("invalid", "milestone_not_open", { status: m.status });
return { m, wo };
}
export async function updateMilestone(ctx: ServiceCtx, raw: z.input<typeof updateMilestoneSchema>): Promise<WorkOrderMilestone> {
assertCan(ctx, "work_order:write");
const input = parseInput(updateMilestoneSchema, raw);
const { m } = await requireEditable(ctx, input.milestoneId, { openOnly: true });
const data = { ...(input.title !== undefined ? { title: input.title } : {}), ...(input.description !== undefined ? { description: input.description } : {}) };
if (!Object.keys(data).length) return m;
const res = await ctx.db.workOrderMilestone.updateMany({ where: { id: m.id, status: "open", deletedAt: null }, data });
if (res.count !== 1) throw new ServiceError("invalid", "milestone_not_open");
const after = await requireMilestone(ctx, m.id);
await auditBilling(ctx, "work_order_milestone", "update", m.id, plain(m), plain(after));
return after;
}
/** Soft delete (only `open`). */
export async function deleteMilestone(ctx: ServiceCtx, milestoneId: string): Promise<void> {
assertCan(ctx, "work_order:write");
const { m } = await requireEditable(ctx, z.string().min(1).max(64).parse(milestoneId), { openOnly: true });
const res = await ctx.db.workOrderMilestone.updateMany({ where: { id: m.id, status: "open", deletedAt: null }, data: { deletedAt: new Date() } });
if (res.count !== 1) throw new ServiceError("invalid", "milestone_not_open");
await auditBilling(ctx, "work_order_milestone", "delete", m.id, plain(m), { deletedAt: new Date().toISOString() });
}
/** Move one step up/down; sort orders are renumbered (10, 20, …) in one transaction. */
export async function moveMilestone(ctx: ServiceCtx, raw: z.input<typeof moveMilestoneSchema>): Promise<void> {
assertCan(ctx, "work_order:write");
const input = parseInput(moveMilestoneSchema, raw);
const { m } = await requireEditable(ctx, input.milestoneId, { openOnly: false });
await inTransaction(ctx, async (tx) => {
const list = await tx.db.workOrderMilestone.findMany({ where: { workOrderId: m.workOrderId, deletedAt: null }, orderBy: [{ sortOrder: "asc" }, { createdAt: "asc" }], select: { id: true, sortOrder: true } });
const i = list.findIndex((x) => x.id === m.id);
const j = input.direction === "up" ? i - 1 : i + 1;
if (i < 0 || j < 0 || j >= list.length) return;
[list[i], list[j]] = [list[j], list[i]];
for (const [idx, x] of list.entries()) {
if (x.sortOrder !== (idx + 1) * 10) await tx.db.workOrderMilestone.updateMany({ where: { id: x.id }, data: { sortOrder: (idx + 1) * 10 } });
}
await auditBilling(tx, "work_order_milestone", "update", m.id, { sortOrder: m.sortOrder }, { direction: input.direction, order: list.map((x) => x.id) });
});
}
const reachSchema = milestoneReachPayload.extend({ workOrderId: z.string().trim().min(1).max(64).optional() });
/**
* "Erreicht melden" (field or back office). Idempotent: a milestone that is no longer `open`
* stays unchanged (`changed: false`), so a replayed offline op never fails.
*/
export async function markMilestoneReached(ctx: ServiceCtx, raw: z.input<typeof reachSchema>): Promise<{ milestone: WorkOrderMilestone; changed: boolean }> {
if (!can(ctx, "field:execute") && !can(ctx, "work_order:write")) throw new ServiceError("forbidden", "missing permission field:execute");
const input = parseInput(reachSchema, raw);
const m = await requireMilestone(ctx, input.milestoneId);
if (input.workOrderId && input.workOrderId !== m.workOrderId) throw new ServiceError("not_found", "milestone_not_found");
const wo = await loadVisibleWorkOrder(ctx, m.workOrderId);
if (FINAL_STATUSES.includes(wo.status)) throw new ServiceError("invalid", "work_order_status", { status: wo.status });
if (m.status !== "open") return { milestone: m, changed: false };
const res = await ctx.db.workOrderMilestone.updateMany({
where: { id: m.id, status: "open", deletedAt: null },
data: { status: "reached", reachedById: ctx.userId, reachedAt: new Date(), reachedNote: input.note },
});
const after = await requireMilestone(ctx, m.id);
if (res.count !== 1) return { milestone: after, changed: false };
await auditBilling(ctx, "work_order_milestone", "update", m.id, { status: m.status }, { status: after.status, reachedNote: after.reachedNote, op: "reach" });
await emitEvent(ctx, { type: "milestone.reached", entityType: "milestone", entityId: m.id, data: { number: wo.number, milestone: m.title, workOrderId: wo.id } });
return { milestone: after, changed: true };
}
/** Confirm a reported (or still open) milestone → billing record (same transaction). */
export async function confirmMilestone(ctx: ServiceCtx, milestoneId: string): Promise<WorkOrderMilestone> {
assertCan(ctx, "billing:write");
const id = z.string().trim().min(1).max(64).parse(milestoneId);
const { before, after, number } = await inTransaction(ctx, async (tx) => {
const m = await requireMilestone(tx, id);
const wo = await loadVisibleWorkOrder(tx, m.workOrderId);
if (m.status !== "open" && m.status !== "reached") throw new ServiceError("conflict", "milestone_not_confirmable", { status: m.status });
const now = new Date();
const res = await tx.db.workOrderMilestone.updateMany({
where: { id: m.id, status: { in: ["open", "reached"] }, deletedAt: null },
data: { status: "confirmed", confirmedById: tx.userId, confirmedAt: now, ...(m.reachedAt ? {} : { reachedAt: now, reachedById: tx.userId }) },
});
if (res.count !== 1) throw new ServiceError("conflict", "milestone_not_confirmable");
await syncBillingCandidates(tx, { workOrderId: m.workOrderId }, now);
const updated = await requireMilestone(tx, m.id);
await auditBilling(tx, "work_order_milestone", "update", m.id, { status: m.status }, { status: updated.status, op: "confirm" });
return { before: m, after: updated, number: wo.number };
});
await emitEvent(ctx, {
type: "milestone.confirmed",
entityType: "milestone",
entityId: after.id,
data: { number, milestone: after.title, workOrderId: after.workOrderId, reporterId: before.reachedById, occurrenceId: `${after.id}:confirmed` },
});
return after;
}
/** Reject a reported milestone (reason mandatory) → back to `open`, the reporter is informed. */
export async function rejectMilestone(ctx: ServiceCtx, raw: z.input<typeof rejectMilestoneSchema>): Promise<WorkOrderMilestone> {
assertCan(ctx, "billing:write");
const input = parseInput(rejectMilestoneSchema, raw);
const m = await requireMilestone(ctx, input.milestoneId);
const wo = await loadVisibleWorkOrder(ctx, m.workOrderId);
if (m.status !== "reached") throw new ServiceError("conflict", "milestone_not_reached", { status: m.status });
const now = new Date();
const res = await ctx.db.workOrderMilestone.updateMany({
where: { id: m.id, status: "reached", deletedAt: null },
data: { status: "open", rejectedById: ctx.userId, rejectedAt: now, rejectionReason: input.reason, reachedById: null, reachedAt: null, reachedNote: null },
});
if (res.count !== 1) throw new ServiceError("conflict", "milestone_not_reached");
const after = await requireMilestone(ctx, m.id);
await auditBilling(ctx, "work_order_milestone", "update", m.id, { status: m.status, reachedById: m.reachedById }, { status: after.status, rejectionReason: input.reason, op: "reject" });
await emitEvent(ctx, {
type: "milestone.rejected",
entityType: "milestone",
entityId: m.id,
data: { number: wo.number, milestone: m.title, workOrderId: wo.id, reporterId: m.reachedById, reason: input.reason, occurrenceId: `${m.id}:rejected:${now.getTime()}` },
});
return after;
}
+60
View File
@@ -0,0 +1,60 @@
import { existsSync } from "node:fs";
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { createTranslator } from "next-intl";
import type { BillingStatement } from "@/lib/billing/statement";
import { ServiceError, type ServiceCtx } from "@/server/services/context";
import { storeFile } from "@/server/services/documents/store";
import { tenantTimezone } from "@/server/services/work-orders/_shared";
import { auditBilling } from "./common";
async function loadBillingMessages(locale: string): Promise<Record<string, unknown>> {
const file = join(process.cwd(), "messages", locale, "billing.json");
const fallback = join(process.cwd(), "messages", "de", "billing.json");
return JSON.parse(await readFile(existsSync(file) ? file : fallback, "utf8"));
}
/**
* Render the PDF billing sheet of a BILLED record from its frozen snapshot and file it as Document
* (category `other`, visibility `backoffice_only`, title "Abrechnungsblatt …"). Immutable: an existing
* PDF is never replaced. Runs in the worker (jobs/processors/billing-pdf.ts).
*/
export async function generateBillingPdf(ctx: ServiceCtx, recordId: string): Promise<{ documentId: string; checksum: string; skipped: boolean }> {
const record = await ctx.db.billingRecord.findFirst({ where: { id: recordId } });
if (!record) throw new ServiceError("not_found", "billing_record_not_found");
if (record.status !== "billed" || !record.snapshot) throw new ServiceError("invalid", "billing_record_not_billed");
if (record.pdfDocumentId) return { documentId: record.pdfDocumentId, checksum: record.pdfChecksum ?? "", skipped: true };
const snap = record.snapshot as unknown as BillingStatement;
const statement: BillingStatement = { ...snap, record: { ...snap.record, status: "billed", invoiceNumber: record.invoiceNumber } };
const settings = await ctx.db.tenantSettings.findFirst({ select: { locale: true } });
const locale = settings?.locale === "en" ? "en" : "de";
const timeZone = await tenantTimezone(ctx);
const t = createTranslator({ locale, messages: await loadBillingMessages(locale) }) as unknown as (key: string, values?: Record<string, string | number>) => string;
const fontPath = join(process.cwd(), "src", "app", "fonts", "inter-variable.ttf");
const fontDataUri = existsSync(fontPath) ? `data:font/ttf;base64,${(await readFile(fontPath)).toString("base64")}` : null;
const [{ renderBillingHtml }, { renderHtmlToPdf }] = await Promise.all([import("@/server/pdf/templates/billing"), import("@/server/pdf/render")]);
const { html, headerHtml, footerHtml } = renderBillingHtml({ statement, t, locale, timeZone, fontDataUri });
const pdf = await renderHtmlToPdf(html, { headerHtml, footerHtml });
const doc = await storeFile(ctx, {
bytes: pdf,
fileName: `Abrechnungsblatt-${statement.workOrder.number}-${record.id.slice(-8)}.pdf`,
declaredMime: "application/pdf",
category: "other",
visibility: "backoffice_only",
links: { customerId: statement.customer.id, siteId: statement.site?.id ?? null, workOrderId: record.workOrderId },
title: t("pdf.documentTitle", { number: statement.workOrder.number, kind: t(`kind.${statement.record.kind}`) }),
approvalStatus: "approved",
});
const res = await ctx.db.billingRecord.updateMany({ where: { id: record.id, pdfDocumentId: null }, data: { pdfDocumentId: doc.id, pdfChecksum: doc.checksum } });
if (res.count !== 1) {
await ctx.db.document.update({ where: { id: doc.id }, data: { deletedAt: new Date() } });
const current = await ctx.db.billingRecord.findFirstOrThrow({ where: { id: record.id }, select: { pdfDocumentId: true, pdfChecksum: true } });
return { documentId: current.pdfDocumentId ?? doc.id, checksum: current.pdfChecksum ?? "", skipped: true };
}
await auditBilling(ctx, "billing_record", "update", record.id, { pdfDocumentId: null }, { pdfDocumentId: doc.id, pdfChecksum: doc.checksum });
return { documentId: doc.id, checksum: doc.checksum, skipped: false };
}
+183
View File
@@ -0,0 +1,183 @@
import type { BillingRecord, Prisma } from "@prisma/client";
import { billingListFilterSchema, type BillingListFilter } from "@/lib/billing/schemas";
import { countTrips, type BillingStatement } from "@/lib/billing/statement";
import { dayWindow } from "@/lib/reports/dates";
import { assertCan, can, ServiceError, type ServiceCtx } from "@/server/services/context";
import { tenantTimezone } from "@/server/services/work-orders/_shared";
import { customerDisplay } from "./common";
import { positionWindow, statementOf } from "./statement";
/** Read models of the billing overview (L14 §3.5) — all require `billing:read`. */
export type BillingSummary = { workMinutes: number; travelMinutes: number; trips: number; materialCount: number; pendingMinutes: number };
function inWindow(d: Date, w: { gte?: Date; lt?: Date } | undefined): boolean {
if (!w) return true;
return (!w.gte || d >= w.gte) && (!w.lt || d < w.lt);
}
/** Summaries for a page of records: frozen snapshot for billed/voided, two batched queries for open records. */
async function summarize(ctx: ServiceCtx, rows: BillingRecord[]): Promise<Map<string, BillingSummary>> {
const out = new Map<string, BillingSummary>();
for (const r of rows) {
if (r.status === "open" || !r.snapshot) continue;
const s = r.snapshot as unknown as BillingStatement;
out.set(r.id, { workMinutes: s.time.totals.work, travelMinutes: s.time.totals.travel, trips: s.trips.count, materialCount: s.materials.used.length + s.materials.additional.length, pendingMinutes: s.time.pendingMinutes });
}
const open = rows.filter((r) => !out.has(r.id));
if (!open.length) return out;
const tz = await tenantTimezone(ctx);
const woIds = [...new Set(open.map((r) => r.workOrderId))];
const [entries, usages] = await Promise.all([
ctx.db.timeEntry.findMany({
where: { workSession: { workOrderId: { in: woIds } }, billingRecordId: null, approvalStatus: { in: ["approved", "pending"] } },
select: { type: true, startedAt: true, endedAt: true, approvalStatus: true, workSession: { select: { workOrderId: true } } },
}),
ctx.db.materialUsage.findMany({ where: { workOrderId: { in: woIds }, billingRecordId: null }, select: { workOrderId: true, createdAt: true, usageStatus: true } }),
]);
for (const r of open) {
const w = positionWindow(r);
const sum: BillingSummary = { workMinutes: 0, travelMinutes: 0, trips: 0, materialCount: 0, pendingMinutes: 0 };
const travel: Array<{ startedAt: Date; endedAt: Date | null }> = [];
for (const e of entries) {
if (e.workSession.workOrderId !== r.workOrderId || !inWindow(e.startedAt, w)) continue;
const minutes = e.endedAt ? Math.max(0, Math.round((e.endedAt.getTime() - e.startedAt.getTime()) / 60_000)) : 0;
if (e.approvalStatus === "pending") {
if (e.type !== "break" && e.type !== "interruption") sum.pendingMinutes += minutes;
continue;
}
if (!e.endedAt) continue;
if (e.type === "work") sum.workMinutes += minutes;
if (e.type === "travel" || e.type === "return_travel") sum.travelMinutes += minutes;
if (e.type === "travel") travel.push(e);
}
sum.trips = countTrips(travel, tz).count;
sum.materialCount = usages.filter((u) => u.workOrderId === r.workOrderId && u.usageStatus !== "not_used" && inWindow(u.createdAt, w)).length;
out.set(r.id, sum);
}
return out;
}
export async function listBillingRecords(ctx: ServiceCtx, raw: BillingListFilter = {}) {
assertCan(ctx, "billing:read");
const f = billingListFilterSchema.parse(raw);
const tz = await tenantTimezone(ctx);
const workOrder: Prisma.WorkOrderWhereInput = { deletedAt: null };
if (f.customerId) workOrder.customerId = f.customerId;
if (f.teamId) workOrder.assignedTeamId = f.teamId;
if (f.q) {
const contains = { contains: f.q, mode: "insensitive" as const };
workOrder.OR = [
{ number: contains },
{ externalOrderNumber: contains },
{ offerNumber: contains },
{ title: contains },
{ customer: { OR: [{ companyName: contains }, { lastName: contains }, { firstName: contains }, { customerNumber: contains }] } },
];
}
const where: Prisma.BillingRecordWhereInput = { status: f.status, workOrder, ...(f.kind ? { kind: f.kind } : {}) };
if (f.from) where.periodTo = { gt: dayWindow(f.from, tz).start };
if (f.to) where.periodFrom = { lt: dayWindow(f.to, tz).end };
const orderBy: Prisma.BillingRecordOrderByWithRelationInput[] =
f.status === "open" ? [{ createdAt: "asc" }] : f.status === "billed" ? [{ billedAt: "desc" }] : [{ voidedAt: "desc" }];
const [total, rows] = await Promise.all([
ctx.db.billingRecord.count({ where }),
ctx.db.billingRecord.findMany({
where,
orderBy: [...orderBy, { id: "asc" }],
skip: (f.page - 1) * f.pageSize,
take: f.pageSize,
include: {
workOrder: {
select: {
id: true,
number: true,
title: true,
customer: { select: { id: true, companyName: true, firstName: true, lastName: true, customerNumber: true } },
site: { select: { id: true, name: true } },
team: { select: { id: true, name: true } },
},
},
},
}),
]);
const milestoneIds = rows.map((r) => r.milestoneId).filter((x): x is string => !!x);
const reportIds = rows.map((r) => r.reportId).filter((x): x is string => !!x);
const [summaries, milestones, reports] = await Promise.all([
summarize(ctx, rows),
milestoneIds.length ? ctx.db.workOrderMilestone.findMany({ where: { id: { in: milestoneIds } }, select: { id: true, title: true } }) : Promise.resolve([]),
reportIds.length ? ctx.db.report.findMany({ where: { id: { in: reportIds } }, select: { id: true, reportDate: true } }) : Promise.resolve([]),
]);
const titleOf = new Map(milestones.map((m) => [m.id, m.title]));
const dateOf = new Map(reports.map((r) => [r.id, r.reportDate.toISOString().slice(0, 10)]));
const items = rows.map((r) => ({
id: r.id,
kind: r.kind,
status: r.status,
periodFrom: r.periodFrom,
periodTo: r.periodTo,
readySince: r.createdAt,
billedAt: r.billedAt,
voidedAt: r.voidedAt,
voidReason: r.voidReason,
invoiceNumber: r.invoiceNumber,
hasPdf: !!r.pdfDocumentId,
milestoneTitle: r.milestoneId ? (titleOf.get(r.milestoneId) ?? null) : null,
reportDate: r.reportId ? (dateOf.get(r.reportId) ?? null) : null,
workOrder: { id: r.workOrder.id, number: r.workOrder.number, title: r.workOrder.title },
customer: { id: r.workOrder.customer.id, name: customerDisplay(r.workOrder.customer) },
site: r.workOrder.site,
team: r.workOrder.team,
summary: summaries.get(r.id)!,
}));
return { items, total, page: f.page, pageSize: f.pageSize };
}
export type BillingListItem = Awaited<ReturnType<typeof listBillingRecords>>["items"][number];
export async function getBillingRecordDetail(ctx: ServiceCtx, recordId: string) {
assertCan(ctx, "billing:read");
const record = await ctx.db.billingRecord.findFirst({ where: { id: recordId, workOrder: { deletedAt: null } } });
if (!record) throw new ServiceError("not_found", "billing_record_not_found");
const [statement, voidedBy] = await Promise.all([
statementOf(ctx, record),
record.voidedById ? ctx.db.user.findFirst({ where: { id: record.voidedById }, select: { name: true } }) : Promise.resolve(null),
]);
return {
record: {
id: record.id,
kind: record.kind,
status: record.status,
workOrderId: record.workOrderId,
invoiceNumber: record.invoiceNumber,
pdfDocumentId: record.pdfDocumentId,
pdfChecksum: record.pdfChecksum,
billedAt: record.billedAt,
voidedAt: record.voidedAt,
voidReason: record.voidReason,
voidedByName: voidedBy?.name ?? null,
createdAt: record.createdAt,
},
statement,
};
}
/** Records of one work order (detail tab). */
export async function listWorkOrderBillingRecords(ctx: ServiceCtx, workOrderId: string) {
assertCan(ctx, "billing:read");
return ctx.db.billingRecord.findMany({
where: { workOrderId },
orderBy: { createdAt: "desc" },
select: { id: true, kind: true, status: true, periodFrom: true, periodTo: true, invoiceNumber: true, billedAt: true, createdAt: true, milestoneId: true, reportId: true, pdfDocumentId: true },
});
}
/** Dashboard tile "Bereit zur Abrechnung" (0 without billing:read). */
export async function countOpenBillingRecords(ctx: ServiceCtx): Promise<number> {
if (!can(ctx, "billing:read")) return 0;
return ctx.db.billingRecord.count({ where: { status: "open", workOrder: { deletedAt: null } } });
}
+180
View File
@@ -0,0 +1,180 @@
import type { BillingRecord, Prisma } from "@prisma/client";
import { markBilledSchema, updateInvoiceNumberSchema, voidBillingSchema, type MarkBilledInput, type VoidBillingInput } from "@/lib/billing/schemas";
import { assertCan, inTransaction, ServiceError, type ServiceCtx } from "@/server/services/context";
import { loadVisibleWorkOrder, parseInput } from "@/server/services/work-orders/_shared";
import { applyTransition } from "@/server/services/work-orders/transition";
import { auditBilling } from "./common";
import { computeStatement } from "./statement";
/**
* Billing actions (L14 §3.4). Handing over to the external accounting = "Abgerechnet" with an
* optional invoice number + PDF sheet. Nothing here creates invoices, amounts or payments.
*/
export type BillingDeps = {
/** queue the PDF sheet rendering (worker); injectable for tests */
dispatchPdf: (ctx: ServiceCtx, recordId: string) => Promise<void>;
};
export const defaultBillingDeps: BillingDeps = {
async dispatchPdf(ctx, recordId) {
try {
const [{ dispatchJob }, { JOB_QUEUES }] = await Promise.all([import("@/server/jobs/dispatch"), import("@/server/jobs/queues")]);
await dispatchJob(JOB_QUEUES.billingPdf, { tenantId: ctx.tenantId, entityId: recordId, actorId: ctx.userId });
} catch (err) {
// billed stays valid; the PDF can be generated again from the detail page
console.error(`[billing] pdf job for ${recordId} failed:`, (err as Error).message);
}
},
};
const view = (r: Pick<BillingRecord, "id" | "kind" | "status" | "workOrderId" | "invoiceNumber" | "milestoneId" | "reportId">) => ({
id: r.id,
kind: r.kind,
status: r.status,
workOrderId: r.workOrderId,
invoiceNumber: r.invoiceNumber,
milestoneId: r.milestoneId,
reportId: r.reportId,
});
async function requireRecord(ctx: ServiceCtx, recordId: string): Promise<BillingRecord> {
const record = await ctx.db.billingRecord.findFirst({ where: { id: recordId } });
if (!record) throw new ServiceError("not_found", "billing_record_not_found");
return record;
}
/**
* Mark an open record as billed: freeze the statement as snapshot, assign its time/material positions
* (each position belongs to at most one billed section), mark the milestone billed, move the order
* to `billed` for the order completion, audit, then queue the PDF sheet.
* Pending (not approved) time entries in the period → `blocked pending_time_entries` unless
* `confirmPendingExcluded` (they are then NOT part of the section).
*/
export async function markBilled(ctx: ServiceCtx, raw: MarkBilledInput, deps: BillingDeps = defaultBillingDeps): Promise<BillingRecord> {
assertCan(ctx, "billing:write");
const input = parseInput(markBilledSchema, raw);
const updated = await inTransaction(ctx, async (tx) => {
const record = await requireRecord(tx, input.recordId);
if (record.status !== "open") throw new ServiceError("conflict", "billing_record_not_open", { status: record.status });
const statement = await computeStatement(tx, record);
if (statement.time.pendingMinutes > 0 && !input.confirmPendingExcluded) {
throw new ServiceError("blocked", "pending_time_entries", [{ kind: "missing_field", field: "pending_time_entries" }]);
}
const billedAt = new Date();
const billedBy = await tx.db.user.findFirst({ where: { id: tx.userId }, select: { name: true } });
const frozen = {
...statement,
generatedAt: billedAt.toISOString(),
record: { ...statement.record, status: "billed" as const, invoiceNumber: input.invoiceNumber, billedAt: billedAt.toISOString(), billedByName: billedBy?.name ?? null },
};
const res = await tx.db.billingRecord.updateMany({
where: { id: record.id, status: "open" },
data: { status: "billed", snapshot: frozen as unknown as Prisma.InputJsonValue, invoiceNumber: input.invoiceNumber, billedById: tx.userId, billedAt },
});
if (res.count !== 1) throw new ServiceError("conflict", "billing_record_not_open");
const { timeEntryIds, materialUsageIds } = statement.positions;
if (timeEntryIds.length) {
const r = await tx.db.timeEntry.updateMany({ where: { id: { in: timeEntryIds }, billingRecordId: null }, data: { billingRecordId: record.id } });
if (r.count !== timeEntryIds.length) throw new ServiceError("conflict", "positions_already_billed");
}
if (materialUsageIds.length) {
const r = await tx.db.materialUsage.updateMany({ where: { id: { in: materialUsageIds }, billingRecordId: null }, data: { billingRecordId: record.id } });
if (r.count !== materialUsageIds.length) throw new ServiceError("conflict", "positions_already_billed");
}
if (record.kind === "milestone" && record.milestoneId) {
await tx.db.workOrderMilestone.updateMany({ where: { id: record.milestoneId, status: "confirmed" }, data: { status: "billed", billingRecordId: record.id } });
}
if (record.kind === "order_completion") {
const wo = await loadVisibleWorkOrder(tx, record.workOrderId);
if (wo.status === "released_for_billing") await applyTransition(tx, wo, "billed");
}
const after = await tx.db.billingRecord.findFirstOrThrow({ where: { id: record.id } });
await auditBilling(tx, "billing_record", "update", record.id, view(record), {
...view(after),
op: "mark_billed",
timeEntries: timeEntryIds.length,
materialUsages: materialUsageIds.length,
pendingExcluded: statement.time.pendingCount,
});
return after;
});
await deps.dispatchPdf(ctx, updated.id);
return updated;
}
/**
* Void a billed record (reason mandatory): positions become free again, the milestone goes back to
* `confirmed`, a NEW open record for the same source is created and — for the order completion —
* the order returns from `billed` to `released_for_billing` (only allowed through this path).
*/
export async function voidBilling(ctx: ServiceCtx, raw: VoidBillingInput): Promise<{ voided: BillingRecord; reopened: BillingRecord | null }> {
assertCan(ctx, "billing:write");
const input = parseInput(voidBillingSchema, raw);
return inTransaction(ctx, async (tx) => {
const record = await requireRecord(tx, input.recordId);
if (record.status !== "billed") throw new ServiceError("conflict", "billing_record_not_billed", { status: record.status });
const res = await tx.db.billingRecord.updateMany({
where: { id: record.id, status: "billed" },
data: { status: "voided", voidedById: tx.userId, voidedAt: new Date(), voidReason: input.reason },
});
if (res.count !== 1) throw new ServiceError("conflict", "billing_record_not_billed");
const freedTime = await tx.db.timeEntry.updateMany({ where: { billingRecordId: record.id }, data: { billingRecordId: null } });
const freedMaterial = await tx.db.materialUsage.updateMany({ where: { billingRecordId: record.id }, data: { billingRecordId: null } });
if (record.kind === "milestone" && record.milestoneId) {
await tx.db.workOrderMilestone.updateMany({ where: { id: record.milestoneId, billingRecordId: record.id }, data: { status: "confirmed", billingRecordId: null } });
}
if (record.kind === "order_completion") {
const wo = await loadVisibleWorkOrder(tx, record.workOrderId);
if (wo.status === "billed") await applyTransition(tx, wo, "released_for_billing", { reason: input.reason, billingVoid: true });
}
// new open record for the same source (the event hook of the status change may already have created it)
await tx.db.billingRecord.createMany({
data: [{ tenantId: tx.tenantId, workOrderId: record.workOrderId, kind: record.kind, milestoneId: record.milestoneId, reportId: record.reportId, periodFrom: record.periodFrom, periodTo: record.periodTo }],
skipDuplicates: true,
});
const sourceWhere: Prisma.BillingRecordWhereInput =
record.kind === "order_completion" ? { workOrderId: record.workOrderId } : record.kind === "milestone" ? { milestoneId: record.milestoneId } : { reportId: record.reportId };
const reopened = await tx.db.billingRecord.findFirst({ where: { ...sourceWhere, kind: record.kind, status: "open" } });
const voided = await tx.db.billingRecord.findFirstOrThrow({ where: { id: record.id } });
await auditBilling(tx, "billing_record", "update", record.id, view(record), {
...view(voided),
op: "void",
reason: input.reason,
freedTimeEntries: freedTime.count,
freedMaterialUsages: freedMaterial.count,
reopenedId: reopened?.id ?? null,
});
if (reopened) await auditBilling(tx, "billing_record", "create", reopened.id, undefined, { ...view(reopened), reopenedFrom: record.id });
return { voided, reopened };
});
}
/** Set / change the invoice number of the accounting afterwards (billed records only). */
export async function updateInvoiceNumber(ctx: ServiceCtx, raw: { recordId: string; invoiceNumber?: string | null }): Promise<BillingRecord> {
assertCan(ctx, "billing:write");
const input = parseInput(updateInvoiceNumberSchema, raw);
const record = await requireRecord(ctx, input.recordId);
if (record.status !== "billed") throw new ServiceError("conflict", "billing_record_not_billed", { status: record.status });
const res = await ctx.db.billingRecord.updateMany({ where: { id: record.id, status: "billed" }, data: { invoiceNumber: input.invoiceNumber } });
if (res.count !== 1) throw new ServiceError("conflict", "billing_record_not_billed");
const after = await ctx.db.billingRecord.findFirstOrThrow({ where: { id: record.id } });
await auditBilling(ctx, "billing_record", "update", record.id, { invoiceNumber: record.invoiceNumber }, { invoiceNumber: after.invoiceNumber, op: "invoice_number" });
return after;
}
/** Queue the PDF sheet again (billed record without PDF, e.g. worker was down). */
export async function requestBillingPdf(ctx: ServiceCtx, recordId: string, deps: BillingDeps = defaultBillingDeps): Promise<void> {
assertCan(ctx, "billing:write");
const record = await requireRecord(ctx, recordId);
if (record.status !== "billed") throw new ServiceError("conflict", "billing_record_not_billed", { status: record.status });
if (record.pdfDocumentId) return;
await deps.dispatchPdf(ctx, record.id);
}
+261
View File
@@ -0,0 +1,261 @@
import type { BillingRecord, Prisma } from "@prisma/client";
import { dateKeyToDbDate } from "@/lib/reports/dates";
import { countTrips, dateKeyIn, type BillingStatement, type StatementMaterialLine, type StatementPersonTime, type StatementTextBlock } from "@/lib/billing/statement";
import { assertCan, ServiceError, type ServiceCtx } from "@/server/services/context";
import { tenantTimezone } from "@/server/services/work-orders/_shared";
import { addressOf, customerDisplay } from "./common";
/**
* Billing statement ("Abrechnungsblatt", L14 §3.3) — no prices. For `open` records the statement is
* computed live from the positions that are not billed yet; for billed/voided records the frozen
* `snapshot` is returned (only status and invoice number are overlaid from the row).
*
* Positions of a record (time entries and material usages with `billingRecordId = null`):
* - daily_report: recorded on the report day [periodFrom, periodTo)
* - milestone: recorded before the confirmation time (periodTo)
* - order_completion: everything of the order that is not billed yet
* Only approved, finished time entries count; pending entries are reported (`pendingMinutes`), rejected
* entries and running entries are never included.
*/
type Window = { gte?: Date; lt?: Date } | undefined;
export function positionWindow(record: Pick<BillingRecord, "kind" | "periodFrom" | "periodTo">): Window {
if (record.kind === "daily_report") return { gte: record.periodFrom, lt: record.periodTo };
if (record.kind === "milestone") return { lt: record.periodTo };
return undefined;
}
const emptyTime = (): Omit<StatementPersonTime, "userId" | "name"> => ({ work: 0, travel: 0, materialProcurement: 0, breaks: 0, interruption: 0, total: 0, manualMinutes: 0 });
function minutesBetween(a: Date, b: Date): number {
return Math.max(0, Math.round((b.getTime() - a.getTime()) / 60_000));
}
type ReportContentLike = { reportNumber?: unknown; texts?: Record<string, unknown> };
/** Compute the statement of a record from the database (no permission check — callers check). */
export async function computeStatement(ctx: ServiceCtx, record: BillingRecord, now = new Date()): Promise<BillingStatement> {
const tz = await tenantTimezone(ctx);
const window = positionWindow(record);
const [wo, settings, tenantUser, milestone, billedBy] = await Promise.all([
ctx.db.workOrder.findFirst({
where: { id: record.workOrderId },
include: { customer: true, site: true, orderType: { select: { name: true } }, team: { select: { name: true } } },
}),
ctx.db.tenantSettings.findFirst({ select: { orgName: true, address: true, phone: true, email: true } }),
ctx.db.user.findFirst({ where: { id: ctx.userId }, select: { tenant: { select: { name: true } } } }),
record.milestoneId ? ctx.db.workOrderMilestone.findFirst({ where: { id: record.milestoneId }, select: { title: true, description: true } }) : Promise.resolve(null),
record.billedById ? ctx.db.user.findFirst({ where: { id: record.billedById }, select: { name: true } }) : Promise.resolve(null),
]);
if (!wo) throw new ServiceError("not_found", "work_order_not_found");
const unbilled = record.status === "open" ? { billingRecordId: null } : { billingRecordId: record.id };
const timeWhere: Prisma.TimeEntryWhereInput = {
workSession: { workOrderId: wo.id },
approvalStatus: { in: ["approved", "pending"] },
...unbilled,
...(window ? { startedAt: window } : {}),
};
const materialWhere: Prisma.MaterialUsageWhereInput = { workOrderId: wo.id, ...unbilled, ...(window ? { createdAt: window } : {}) };
const reportWhere: Prisma.ReportWhereInput = { workOrderId: wo.id, status: "approved" };
if (record.kind === "daily_report") reportWhere.id = record.reportId ?? "__none__";
else if (record.kind === "milestone") reportWhere.reportDate = { gte: dateKeyToDbDate(dateKeyIn(record.periodFrom, tz)), lte: dateKeyToDbDate(dateKeyIn(record.periodTo, tz)) };
else reportWhere.reportDate = { gte: dateKeyToDbDate(dateKeyIn(record.periodFrom, tz)) };
const [entries, usages, plans, allPlanUsages, reports, dailyReport] = await Promise.all([
ctx.db.timeEntry.findMany({
where: timeWhere,
orderBy: { startedAt: "asc" },
select: { id: true, userId: true, type: true, startedAt: true, endedAt: true, approvalStatus: true, source: true },
}),
ctx.db.materialUsage.findMany({ where: materialWhere, orderBy: { createdAt: "asc" }, include: { materialPlan: true } }),
record.kind === "order_completion" ? ctx.db.materialPlan.findMany({ where: { workOrderId: wo.id }, orderBy: { sortOrder: "asc" } }) : Promise.resolve([]),
record.kind === "order_completion"
? ctx.db.materialUsage.findMany({ where: { workOrderId: wo.id, materialPlanId: { not: null } }, select: { materialPlanId: true } })
: Promise.resolve([]),
ctx.db.report.findMany({
where: reportWhere,
orderBy: [{ reportDate: "asc" }, { version: "asc" }],
select: { id: true, type: true, version: true, reportDate: true, approvedAt: true, content: true, signature: { select: { outcome: true, signerName: true, signedAt: true } } },
}),
record.kind === "daily_report" && record.reportId ? ctx.db.report.findFirst({ where: { id: record.reportId }, select: { reportDate: true } }) : Promise.resolve(null),
]);
// ---- time ----
const persons = new Map<string, StatementPersonTime>();
const timeEntryIds: string[] = [];
const travelSegments: Array<{ startedAt: Date; endedAt: Date | null }> = [];
const workDates = new Set<string>();
let pendingMinutes = 0;
let pendingCount = 0;
let hasRunningEntries = false;
for (const e of entries) {
if (e.approvalStatus === "pending") {
pendingCount++;
if (e.type !== "break" && e.type !== "interruption") pendingMinutes += minutesBetween(e.startedAt, e.endedAt ?? now);
continue;
}
if (!e.endedAt) {
hasRunningEntries = true;
continue;
}
timeEntryIds.push(e.id);
const minutes = minutesBetween(e.startedAt, e.endedAt);
const p = persons.get(e.userId) ?? { userId: e.userId, name: "—", ...emptyTime() };
switch (e.type) {
case "work":
p.work += minutes;
break;
case "travel":
p.travel += minutes;
travelSegments.push({ startedAt: e.startedAt, endedAt: e.endedAt });
break;
case "return_travel":
p.travel += minutes;
break;
case "material_procurement":
p.materialProcurement += minutes;
break;
case "break":
p.breaks += minutes;
break;
case "interruption":
p.interruption += minutes;
break;
}
if (e.type !== "break" && e.type !== "interruption") {
workDates.add(dateKeyIn(e.startedAt, tz));
if (e.source === "manual") p.manualMinutes += minutes;
}
persons.set(e.userId, p);
}
const names = persons.size ? await ctx.db.user.findMany({ where: { id: { in: [...persons.keys()] } }, select: { id: true, name: true } }) : [];
const nameOf = new Map(names.map((u) => [u.id, u.name]));
const totals = emptyTime();
const personList = [...persons.values()]
.map((p) => {
const total = p.work + p.travel + p.materialProcurement;
const withTotal = { ...p, name: nameOf.get(p.userId) ?? "—", total };
for (const k of Object.keys(totals) as Array<keyof typeof totals>) totals[k] += withTotal[k];
return withTotal;
})
.sort((a, b) => a.name.localeCompare(b.name, "de"));
// ---- material ----
const used: StatementMaterialLine[] = [];
const additional: StatementMaterialLine[] = [];
const notUsed: StatementMaterialLine[] = [];
const materialUsageIds: string[] = [];
for (const u of usages) {
materialUsageIds.push(u.id);
const line: StatementMaterialLine = {
usageId: u.id,
planId: u.materialPlanId,
name: u.name,
articleNumber: u.articleNumber,
quantity: u.actualQuantity.toString(),
plannedQuantity: u.materialPlan ? u.materialPlan.plannedQuantity.toString() : null,
unit: u.unit,
status: u.usageStatus,
deviationReason: u.deviationReason,
};
if (u.usageStatus === "not_used") notUsed.push(line);
else if (u.usageStatus === "additional" || !u.materialPlanId) additional.push(line);
else used.push(line);
}
const plansWithUsage = new Set(allPlanUsages.map((u) => u.materialPlanId));
for (const p of plans) {
if (plansWithUsage.has(p.id)) continue;
notUsed.push({ usageId: null, planId: p.id, name: p.name, articleNumber: p.articleNumber, quantity: null, plannedQuantity: p.plannedQuantity.toString(), unit: p.unit, status: null, deviationReason: null });
}
// ---- reports: references + texts ----
const texts: BillingStatement["texts"] = { additionalWork: [], deviations: [], openItems: [] };
const reportRefs: BillingStatement["reports"] = reports.map((r) => {
const c = (r.content ?? {}) as ReportContentLike;
const number = typeof c.reportNumber === "string" ? c.reportNumber : null;
for (const key of ["additionalWork", "deviations", "openItems"] as const) {
const v = c.texts?.[key];
if (typeof v === "string" && v.trim()) (texts[key] as StatementTextBlock[]).push({ reportNumber: number, text: v.trim() });
}
return {
id: r.id,
number,
type: r.type,
version: r.version,
reportDate: r.reportDate.toISOString().slice(0, 10),
approvedAt: r.approvedAt?.toISOString() ?? null,
signature: r.signature ? { outcome: r.signature.outcome, signerName: r.signature.signerName, signedAt: r.signature.signedAt.toISOString() } : null,
};
});
return {
schemaVersion: 1,
generatedAt: now.toISOString(),
record: {
id: record.id,
kind: record.kind,
status: record.status,
periodFrom: record.periodFrom.toISOString(),
periodTo: record.periodTo.toISOString(),
readySince: record.createdAt.toISOString(),
milestoneTitle: milestone?.title ?? null,
milestoneDescription: milestone?.description ?? null,
reportDate: dailyReport ? dailyReport.reportDate.toISOString().slice(0, 10) : null,
invoiceNumber: record.invoiceNumber,
billedAt: record.billedAt?.toISOString() ?? null,
billedByName: billedBy?.name ?? null,
},
tenant: {
name: settings?.orgName || tenantUser?.tenant.name || "—",
address: settings?.address ?? null,
phone: settings?.phone ?? null,
email: settings?.email ?? null,
logoDocumentId: null, // like reports: TenantSettings.logoKey is not a Document yet
},
customer: {
id: wo.customer.id,
number: wo.customer.customerNumber,
name: customerDisplay(wo.customer),
billingAddress: addressOf(wo.customer),
billingNotes: wo.customer.billingNotes,
},
site: wo.site ? { id: wo.site.id, name: wo.site.name, address: addressOf(wo.site) } : null,
workOrder: {
id: wo.id,
number: wo.number,
externalOrderNumber: wo.externalOrderNumber,
offerNumber: wo.offerNumber,
title: wo.title,
orderType: wo.orderType?.name ?? null,
billingType: wo.billingType,
team: wo.team?.name ?? null,
},
reports: reportRefs,
workDates: [...workDates].sort(),
time: { persons: personList, totals, pendingMinutes, pendingCount, hasRunningEntries },
trips: countTrips(travelSegments, tz),
materials: { used, additional, notUsed },
texts,
positions: { timeEntryIds, materialUsageIds },
};
}
/** Statement of a record for the UI/API (`billing:read`). Billed/voided → frozen snapshot. */
export async function buildBillingStatement(ctx: ServiceCtx, recordId: string): Promise<BillingStatement> {
assertCan(ctx, "billing:read");
const record = await ctx.db.billingRecord.findFirst({ where: { id: recordId } });
if (!record) throw new ServiceError("not_found", "billing_record_not_found");
return statementOf(ctx, record);
}
export async function statementOf(ctx: ServiceCtx, record: BillingRecord): Promise<BillingStatement> {
if (record.status !== "open" && record.snapshot) {
const s = record.snapshot as unknown as BillingStatement;
return { ...s, record: { ...s.record, status: record.status, invoiceNumber: record.invoiceNumber } };
}
return computeStatement(ctx, record);
}
+17
View File
@@ -0,0 +1,17 @@
import { milestoneReachPayload } from "@/lib/billing/schemas";
import type { SyncOperationInput } from "@/lib/sync/envelope";
import { ServiceError, type ServiceCtx } from "@/server/services/context";
import type { ExternalOpResult } from "@/server/services/sync/external-ops";
import { markMilestoneReached } from "./milestones";
/**
* Sync op `milestone.reach` (registered in services/sync/external-ops.ts). Idempotent twice over:
* the SyncOperation clientOpId and the service itself (an already reached milestone is unchanged).
*/
export async function applySyncOp(ctx: ServiceCtx, op: SyncOperationInput): Promise<ExternalOpResult> {
if (op.opType !== "milestone.reach") throw new ServiceError("invalid", "unsupported_op");
const parsed = milestoneReachPayload.safeParse(op.payload);
if (!parsed.success) throw new ServiceError("invalid", "sync_payload_invalid");
await markMilestoneReached(ctx, parsed.data);
return {};
}
@@ -156,6 +156,10 @@ export function linkFor(event: DomainEvent, f: EventFacts, permissions: Readonly
// L12: approvers open their approval list, the technician „Meine Zeiten"
if (event.type === "time.approval_requested") return backoffice && permissions.has("time:approve") ? "/work-orders/time-approvals" : "/m/approvals";
return "/m/time";
case "milestone":
// L14: back office → billing tab of the order, field → mobile order detail
if (!f.workOrderId) return null;
return backoffice ? `/work-orders/${f.workOrderId}?tab=billing` : `/m/orders/${f.workOrderId}`;
default:
return null;
}
@@ -317,6 +317,20 @@ export async function resolveRecipients(
}
break;
}
case "milestone.reached":
case "milestone.confirmed":
case "milestone.rejected": {
// L14: reported → billing staff (in-app); confirmed/rejected → the reporting person (in-app)
const milestone = await ctx.db.workOrderMilestone.findFirst({ where: { id: event.entityId }, select: { workOrderId: true } });
if (!milestone) return null;
const wo = await loadWorkOrder(ctx, milestone.workOrderId);
if (!wo) return null;
Object.assign(facts, workOrderFacts(wo));
if (typeof event.data?.reason === "string") facts.rejectionReason = event.data.reason;
if (event.type === "milestone.reached") rule = { users: [hasPermissionWhere("billing:write")], userIds: [], mailToUsers: false };
else rule = { users: [], userIds: typeof event.data?.reporterId === "string" ? [event.data.reporterId] : [], mailToUsers: false };
break;
}
case "sync.failed": {
const op = await ctx.db.syncOperation.findFirst({
where: { id: event.entityId },
+2
View File
@@ -20,6 +20,7 @@ export const EXTERNAL_OP_OWNERS: Partial<Record<SyncOpType, string>> = {
"report.submit": "reports (L5)",
"signature.capture": "reports (L5)",
"emergency.create": "emergency (L8)",
"milestone.reach": "billing (L14)",
};
export const EXTERNAL_OPS: Partial<Record<SyncOpType, () => Promise<ExternalOpHandler>>> = {
@@ -27,4 +28,5 @@ export const EXTERNAL_OPS: Partial<Record<SyncOpType, () => Promise<ExternalOpHa
"report.submit": () => import("@/server/services/reports/sync-ops").then((m) => m.applySyncOp), // L10b
// not registered: "signature.capture" — needs a signature image upload kind in /api/v1/uploads first (see docs/craftvia/lanes/betrieb.md)
"emergency.create": () => import("@/server/services/emergency/sync-ops").then((m) => m.applySyncOp),
"milestone.reach": () => import("@/server/services/billing/sync-ops").then((m) => m.applySyncOp), // L14
};
@@ -76,13 +76,16 @@ export async function applyTransition(
baseVersion?: number;
extra?: Record<string, unknown>;
eventData?: Record<string, string | number | boolean | null>;
/** L14: billed → released_for_billing is ONLY allowed when a billing record is voided (services/billing/records.ts) */
billingVoid?: boolean;
} = {},
): Promise<TransitionResult> {
const from = wo.status;
if (!canTransition(from, to)) throw new ServiceError("invalid", "transition_not_allowed", { from, to });
if (!mayTransition(ctx, from, to)) throw new ServiceError("forbidden", "transition_forbidden", { from, to });
const voidRevert = opts.billingVoid === true && from === "billed" && to === "released_for_billing";
if (!voidRevert && !canTransition(from, to)) throw new ServiceError("invalid", "transition_not_allowed", { from, to });
if (voidRevert ? !can(ctx, "work_order:release_billing") : !mayTransition(ctx, from, to)) throw new ServiceError("forbidden", "transition_forbidden", { from, to });
assertBaseVersion(wo, opts.baseVersion);
if (reasonRequired(from, to) && !opts.reason?.trim()) throw new ServiceError("invalid", "reason_required", { from, to });
if ((voidRevert || reasonRequired(from, to)) && !opts.reason?.trim()) throw new ServiceError("invalid", "reason_required", { from, to });
const blockers = await transitionBlockers(ctx, wo, to);
if (blockers.length) throw new ServiceError("blocked", "transition_blocked", blockers);