diff --git a/apps/api/src/modules/invoices/index.ts b/apps/api/src/modules/invoices/index.ts index f45ecda..d03ab9e 100644 --- a/apps/api/src/modules/invoices/index.ts +++ b/apps/api/src/modules/invoices/index.ts @@ -18,6 +18,7 @@ import type { KcModule } from '../../core/module.js'; import { config } from '../../core/config.js'; import { renderInvoicePdf, type CompanySettings, type InvoiceForPdf } from './pdf.js'; import { csvSafe, csvCell } from '@kc/platform/csv'; +import { autoBillingEnabled, duePeriods, releaseCancelledPeriods, runBilling } from '@kc/platform/billing'; /** Kaufmännisches Runden (halb auf), wie in @kc/platform/pricing – hier lokal, weil Rechnungspositionen * (Freitext, Dezimalmenge) sich nicht in das Produkt-Preisschema von calculatePrice pressen lassen. */ @@ -192,7 +193,7 @@ export const invoicesModule: KcModule = { app.get('/admin/company-settings', async (req) => { requirePermission(req, 'invoices.read'); const s = await settings(); const d = await datevSettings(); - return { ...s, complete: complete(s), datev: { ...d, complete: datevComplete(d) } }; + return { ...s, complete: complete(s), datev: { ...d, complete: datevComplete(d) }, autoBillingRuns: await autoBillingEnabled() }; }); app.put('/admin/company-settings', async (req) => { const a = requirePermission(req, 'settings.write'); @@ -206,11 +207,12 @@ export const invoicesModule: KcModule = { datevFiscalYearStart: z.string().regex(/^\d{2}-\d{2}$/).optional(), datevErloeskonto19: z.number().int().min(0).max(999999999).nullable().optional(), datevErloeskonto7: z.number().int().min(0).max(999999999).nullable().optional(), datevErloeskonto0: z.number().int().min(0).max(999999999).nullable().optional(), datevDiktatkuerzel: z.string().trim().max(2).nullable().optional(), + autoBillingRuns: z.boolean().optional(), }).parse(req.body); const cols: Record = { name: 'name', street: 'street', zip: 'zip', city: 'city', country: 'country', taxNumber: 'tax_number', vatId: 'vat_id', bankName: 'bank_name', iban: 'iban', bic: 'bic', invoicePrefix: 'invoice_prefix', defaultDueDays: 'default_due_days', footerText: 'footer_text', datevBeraterNr: 'datev_berater_nr', datevMandantNr: 'datev_mandant_nr', datevSkr: 'datev_skr', datevSachkontenlaenge: 'datev_sachkontenlaenge', datevFiscalYearStart: 'datev_fiscal_year_start', - datevErloeskonto19: 'datev_erloeskonto_19', datevErloeskonto7: 'datev_erloeskonto_7', datevErloeskonto0: 'datev_erloeskonto_0', datevDiktatkuerzel: 'datev_diktatkuerzel', + datevErloeskonto19: 'datev_erloeskonto_19', datevErloeskonto7: 'datev_erloeskonto_7', datevErloeskonto0: 'datev_erloeskonto_0', datevDiktatkuerzel: 'datev_diktatkuerzel', autoBillingRuns: 'auto_billing_runs', }; const sets: string[] = []; const params: unknown[] = []; for (const [k, col] of Object.entries(cols)) if ((b as Record)[k] !== undefined) { sets.push(`${col} = ?`); params.push((b as Record)[k]); } @@ -255,6 +257,26 @@ export const invoicesModule: KcModule = { return { overdueInvoices: overdue, dueContracts }; }); + // ---- Abrechnungslauf (#50): Entwürfe je fälliger Vertragsperiode, jede Periode genau einmal ---------------- + app.get('/invoices/billing-run/preview', async (req) => { + requirePermission(req, 'invoices.read'); + return { periods: await duePeriods(), auto: await autoBillingEnabled() }; + }); + app.post('/invoices/billing-run', async (req) => { + const a = requirePermission(req, 'invoices.write'); + const r = await runBilling(a.user.id); + await audit({ actorType: 'user', actorId: a.user.id, action: 'invoice.billing_run', resourceType: 'invoice', resourceId: 'run', correlationId: req.correlationId, ip: clientIp(req), after: { drafts: r.drafts.length, items: r.drafts.reduce((n, d) => n + d.items, 0), skipped: r.skipped } }); + return r; + }); + /** Storno einer Laufrechnung: Periode bleibt belegt, bis das Personal sie hier ausdrücklich zur erneuten Abrechnung freigibt. */ + app.post('/invoices/:id/release-periods', async (req) => { + const a = requirePermission(req, 'invoices.write'); const { id } = z.object({ id: z.string().uuid() }).parse(req.params); + const n = await releaseCancelledPeriods(id); + if (n < 0) throw conflict('Nur Perioden stornierter Rechnungen können erneut abgerechnet werden.', 'INVOICE_NOT_CANCELLED'); + await audit({ actorType: 'user', actorId: a.user.id, action: 'invoice.release_periods', resourceType: 'invoice', resourceId: id, correlationId: req.correlationId, ip: clientIp(req), after: { periods: n } }); + return { released: n }; + }); + app.post('/invoices', async (req) => { const a = requirePermission(req, 'invoices.write'); const b = z.object({ orgId: z.string().uuid(), note: z.string().trim().max(500).optional(), paymentMethod: z.string().max(50).optional() }).parse(req.body); @@ -270,7 +292,8 @@ export const invoicesModule: KcModule = { const staff = can(a.principal, 'invoices.read'); const res = await loadInvoice(id); if (!res || !canInOrg(a.principal, res.v.org_id, 'invoices.read', 'invoices.read') || (!staff && res.v.status === 'draft')) throw notFound(); - return { ...invoiceView(res.v), items: res.items.map(itemView), canWrite: staff }; + const periods = staff ? await query('SELECT contract_id, period_start, period_end FROM invoice_billing_periods WHERE invoice_id = ? ORDER BY period_start', [id]) : []; + return { ...invoiceView(res.v), items: res.items.map(itemView), canWrite: staff, billingPeriods: periods.map((p) => ({ contractId: p.contract_id, start: p.period_start, end: p.period_end })) }; }); /** Ersetzt die Positionen eines Entwurfs vollständig (einfacher als Einzel-CRUD, ausreichend für eine Entwurfsphase). */ diff --git a/apps/api/test/billing.test.ts b/apps/api/test/billing.test.ts new file mode 100644 index 0000000..ec4bbf6 --- /dev/null +++ b/apps/api/test/billing.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, it } from 'vitest'; +import { randomUUID } from 'node:crypto'; +import { one, query, run } from '../src/core/db.js'; +import { duePeriods, releaseCancelledPeriods, runBilling } from '@kc/platform/billing'; + +let seq = 0; +async function contract(o: { interval: 'monthly' | 'yearly'; startedAt: string; net?: number; cancelEffective?: string }) { + seq++; + const org = randomUUID(); await run("INSERT INTO organizations (id, customer_number, name, customer_type) VALUES (?,?,?, 'business')", [org, `K-BIL${seq}`, `Abrechnung ${seq}`]); + const tax = (await one('SELECT id FROM tax_rates LIMIT 1'))!.id; + const prod = randomUUID(); const ver = randomUUID(); + await run("INSERT INTO products (id, sku, category) VALUES (?,?, 'hosting')", [prod, `BIL-${seq}-${prod.slice(0, 6)}`]); + await run('INSERT INTO product_versions (id, product_id, version, name, tax_rate_id, tax_bp, billing_interval) VALUES (?,?,1,?,?,1900,?)', [ver, prod, `Paket ${seq}`, tax, o.interval]); + const ord = randomUUID(); const item = randomUUID(); const id = randomUUID(); + await run("INSERT INTO orders (id, number, org_id, status, placed_via) VALUES (?,?,?, 'completed', 'staff')", [ord, `B-BIL${seq}`, org]); + const snap = { name: `Paket ${seq}`, interval: o.interval, taxBp: 1900, quantity: 1, discountBp: 0, recurring: { net: o.net ?? 1000, tax: 190, gross: 1190 }, setup: { net: 0, tax: 0, gross: 0 } }; + await run('INSERT INTO order_items (id, order_id, product_version_id, snapshot_json) VALUES (?,?,?,?)', [item, ord, ver, JSON.stringify(snap)]); + await run("INSERT INTO contracts (id, number, org_id, order_item_id, product_version_id, status, started_at, renewal, renewal_term_months, cancel_effective_at, price_snapshot_json) VALUES (?,?,?,?,?, 'active', ?, 'auto', 12, ?, ?)", + [id, `V-BIL${seq}`, org, item, ver, new Date(o.startedAt), o.cancelEffective ? new Date(o.cancelEffective) : null, JSON.stringify(snap)]); + return { id, org }; +} +const periodsOf = (cid: string) => query('SELECT period_start FROM invoice_billing_periods WHERE contract_id = ? ORDER BY period_start', [cid]).then((r) => r.map((x) => new Date(x.period_start).toISOString().slice(0, 10))); + +describe('Abrechnungslauf (#50)', () => { + const now = new Date('2026-10-06T12:00:00Z'); + it('monatlich: alle fälligen Perioden seit Beginn, im Voraus; zweiter Lauf erzeugt nichts', async () => { + const c = await contract({ interval: 'monthly', startedAt: '2026-08-15T00:00:00Z' }); + const r = await runBilling(null, now); + expect(await periodsOf(c.id)).toEqual(['2026-08-15', '2026-09-15']); // 15.10. noch nicht fällig + const d = r.drafts.find((x) => x.orgId === c.org)!; expect(d.items).toBe(2); + const inv = await one('SELECT status, number, total_gross_cents FROM invoices WHERE id = ?', [d.invoiceId]); + expect(inv!.status).toBe('draft'); expect(inv!.number).toBeNull(); expect(Number(inv!.total_gross_cents)).toBe(2380); + expect((await runBilling(null, now)).drafts.find((x) => x.orgId === c.org)).toBeUndefined(); + }); + it('zwei parallele Läufe ergeben genau eine Rechnung je Periode', async () => { + const c = await contract({ interval: 'yearly', startedAt: '2026-01-10T00:00:00Z' }); + const [a, b] = await Promise.all([runBilling(null, now), runBilling(null, now)]); + expect(await periodsOf(c.id)).toEqual(['2026-01-10']); + const drafts = [...a.drafts, ...b.drafts].filter((x) => x.orgId === c.org); + expect(drafts).toHaveLength(1); + expect(Number((await one("SELECT COUNT(*) AS n FROM invoices WHERE org_id = ?", [c.org]))!.n)).toBe(1); // kein leerer Entwurf übrig + }); + it('gelöschter Entwurf gibt die Periode frei; Storno hält sie belegt bis zur ausdrücklichen Freigabe', async () => { + const c = await contract({ interval: 'yearly', startedAt: '2026-03-01T00:00:00Z' }); + const d1 = (await runBilling(null, now)).drafts.find((x) => x.orgId === c.org)!; + await run('DELETE FROM invoice_items WHERE invoice_id = ?', [d1.invoiceId]); await run('DELETE FROM invoices WHERE id = ?', [d1.invoiceId]); + expect(await periodsOf(c.id)).toEqual([]); + const d2 = (await runBilling(null, now)).drafts.find((x) => x.orgId === c.org)!; + await run("UPDATE invoices SET status = 'cancelled' WHERE id = ?", [d2.invoiceId]); // vereinfacht: ausgestellt + storniert + expect((await runBilling(null, now)).drafts.find((x) => x.orgId === c.org)).toBeUndefined(); // keine stille Neuabrechnung + expect(await releaseCancelledPeriods(d2.invoiceId)).toBe(1); + expect((await runBilling(null, now)).drafts.find((x) => x.orgId === c.org)?.items).toBe(1); + expect(await releaseCancelledPeriods((await runBilling(null, now)).drafts[0]?.invoiceId ?? d2.invoiceId)).toBe(0); + }); + it('keine Abrechnung über das wirksame Kündigungsdatum hinaus', async () => { + const c = await contract({ interval: 'monthly', startedAt: '2026-07-01T00:00:00Z', cancelEffective: '2026-09-01T00:00:00Z' }); + await runBilling(null, now); + expect(await periodsOf(c.id)).toEqual(['2026-07-01', '2026-08-01']); + }); + it('von Hand abgerechnete Verträge: keine Doppelrechnung für die bereits berechnete Periode', async () => { + const c = await contract({ interval: 'monthly', startedAt: '2026-08-01T00:00:00Z' }); + const inv = randomUUID(); + await run("INSERT INTO invoices (id, number, org_id, status, issue_date) VALUES (?, ?, ?, 'open', '2026-09-03')", [inv, `RE-HAND-${seq}`, c.org]); + await run("INSERT INTO invoice_items (id, invoice_id, contract_id, description, quantity, unit_price_net_cents, tax_bp, net_cents, tax_cents, gross_cents, sort_order) VALUES (?,?,?,'Hand',1,1000,1900,1000,190,1190,0)", [randomUUID(), inv, c.id]); + const due = (await duePeriods(now)).filter((p) => p.contractId === c.id).map((p) => p.start); + expect(due).toEqual(['2026-10-01']); // August/September gelten mit der Handrechnung vom 03.09. als berechnet + }); +}); diff --git a/apps/web/src/app/(app)/einstellungen/firma/page.tsx b/apps/web/src/app/(app)/einstellungen/firma/page.tsx index 47e5def..1b63520 100644 --- a/apps/web/src/app/(app)/einstellungen/firma/page.tsx +++ b/apps/web/src/app/(app)/einstellungen/firma/page.tsx @@ -5,7 +5,7 @@ import { useSession } from '@/lib/session'; import { Alert, Field } from '@/components/ui'; interface Datev { beraterNr: number | null; mandantNr: number | null; skr: string | null; sachkontenlaenge: number; fiscalYearStart: string; erloeskonto19: number | null; erloeskonto7: number | null; erloeskonto0: number | null; diktatkuerzel: string | null; complete: boolean } -interface Settings { name: string | null; street: string | null; zip: string | null; city: string | null; country: string; taxNumber: string | null; vatId: string | null; bankName: string | null; iban: string | null; bic: string | null; invoicePrefix: string; defaultDueDays: number; paymentMethods: string[]; footerText: string | null; complete: boolean; datev: Datev } +interface Settings { name: string | null; street: string | null; zip: string | null; city: string | null; country: string; taxNumber: string | null; vatId: string | null; bankName: string | null; iban: string | null; bic: string | null; invoicePrefix: string; defaultDueDays: number; paymentMethods: string[]; footerText: string | null; complete: boolean; datev: Datev; autoBillingRuns?: boolean } export default function Firma() { const { can } = useSession(); const w = can('settings.write'); @@ -23,6 +23,7 @@ export default function Firma() { invoicePrefix: v('invoicePrefix'), defaultDueDays: Number(f.get('defaultDueDays') ?? 14), paymentMethods: String(f.get('paymentMethods') ?? '').split(',').map((x) => x.trim()).filter(Boolean), footerText: v('footerText') ?? null, + autoBillingRuns: f.get('autoBillingRuns') === 'on', datevBeraterNr: n('datevBeraterNr'), datevMandantNr: n('datevMandantNr'), datevSkr: (v('datevSkr') as '03' | '04' | undefined) ?? null, datevSachkontenlaenge: Number(f.get('datevSachkontenlaenge') ?? 4), datevFiscalYearStart: v('datevFiscalYearStart') ?? '01-01', datevErloeskonto19: n('datevErloeskonto19'), datevErloeskonto7: n('datevErloeskonto7'), datevErloeskonto0: n('datevErloeskonto0'), @@ -60,6 +61,7 @@ export default function Firma() { +

DATEV-Export

Für den Buchungsstapel-Export unter Rechnungen → Export. Werte vom Steuerberater erfragen; ohne Beraternummer und Mandantennummer ist der DATEV-Export nicht möglich (das generische CSV/ZIP funktioniert unabhängig davon immer).

{!s.datev.complete && DATEV-Stammdaten unvollständig: Beraternummer und Mandantennummer fehlen noch.} diff --git a/apps/web/src/app/(app)/rechnungen/[id]/page.tsx b/apps/web/src/app/(app)/rechnungen/[id]/page.tsx index 4496251..4af2821 100644 --- a/apps/web/src/app/(app)/rechnungen/[id]/page.tsx +++ b/apps/web/src/app/(app)/rechnungen/[id]/page.tsx @@ -7,7 +7,7 @@ import { useSession } from '@/lib/session'; import { Alert, Field, InvoiceStatusBadge, eur, fmt, fmtDay } from '@/components/ui'; interface Item { id: string; description: string; quantity: number; unitPriceNetCents: number; taxBp: number; discountBp: number; netCents: number; taxCents: number; grossCents: number } -interface Inv { id: string; number: string | null; orgId: string; orgName: string; status: string; overdue: boolean; issueDate: string | null; dueDate: string | null; paymentMethod: string | null; note: string | null; totalNetCents: number; totalTaxCents: number; totalGrossCents: number; cancelsInvoiceId: string | null; cancelledByInvoiceId: string | null; items: Item[]; canWrite: boolean } +interface Inv { id: string; number: string | null; orgId: string; orgName: string; status: string; overdue: boolean; issueDate: string | null; dueDate: string | null; paymentMethod: string | null; note: string | null; totalNetCents: number; totalTaxCents: number; totalGrossCents: number; cancelsInvoiceId: string | null; cancelledByInvoiceId: string | null; items: Item[]; canWrite: boolean; billingPeriods?: { contractId: string; start: string; end: string }[] } type Row = { description: string; quantity: string; unitPrice: string; taxBp: string; discount: string }; const emptyRow = (): Row => ({ description: '', quantity: '1', unitPrice: '', taxBp: '19', discount: '0' }); interface Suggested { description: string; quantity: number; unitPriceNetCents: number; taxBp: number; discountBp?: number } @@ -95,6 +95,7 @@ export default function RechnungDetail() { {!isDraft &&
PDF ansehen {inv.canWrite && inv.status === 'open' && } + {inv.canWrite && inv.status === 'cancelled' && (inv.billingPeriods?.length ?? 0) > 0 && } {inv.canWrite && inv.status === 'open' && }
} {inv.note &&

Notiz: {inv.note}

} diff --git a/apps/web/src/app/(app)/rechnungen/faellig/page.tsx b/apps/web/src/app/(app)/rechnungen/faellig/page.tsx index e730e3d..a0bb307 100644 --- a/apps/web/src/app/(app)/rechnungen/faellig/page.tsx +++ b/apps/web/src/app/(app)/rechnungen/faellig/page.tsx @@ -8,11 +8,34 @@ import { Alert, Empty, eur, fmt, fmtDay } from '@/components/ui'; interface OverdueInv { id: string; number: string | null; orgName: string; customerNumber: string; dueDate: string | null; totalGrossCents: number } interface DueContract { id: string; number: string; orgId: string; orgName: string; customerNumber: string; productName: string | null; lastInvoicedAt: string | null; dueSince: string; lastGrossCents: number | null } interface Data { overdueInvoices: OverdueInv[]; dueContracts: DueContract[] } +interface Period { contractId: string; contractNumber: string; orgId: string; start: string; end: string; description: string; unitPriceNetCents: number; taxBp: number } + +/** Abrechnungslauf (#50): fällige Vertragsperioden als Entwürfe anlegen – jede Periode genau einmal, nichts wird ausgestellt. */ +function BillingRun({ onDone }: { onDone: () => void }) { + const [p, setP] = useState<{ periods: Period[]; auto: boolean } | null>(null); const [msg, setMsg] = useState<{ k: 'ok' | 'err'; t: string } | null>(null); const [busy, setBusy] = useState(false); + const load = () => api<{ periods: Period[]; auto: boolean }>('GET', '/invoices/billing-run/preview').then(setP).catch((e) => setMsg({ k: 'err', t: errMsg(e) })); + useEffect(() => { void load(); }, []); + async function go() { + setBusy(true); setMsg(null); + try { const r = await api<{ drafts: { items: number }[] }>('POST', '/invoices/billing-run'); setMsg({ k: 'ok', t: r.drafts.length ? `${r.drafts.length} Entwürfe mit ${r.drafts.reduce((n, d) => n + d.items, 0)} Positionen angelegt. Bitte unter Rechnungen prüfen und ausstellen.` : 'Nichts abzurechnen.' }); await load(); onDone(); } + catch (x) { setMsg({ k: 'err', t: errMsg(x) }); } finally { setBusy(false); } + } + return (
+

Abrechnungslauf

+

Fällige Vertragsperioden nach dem Abrechnungsintervall des Vertrags (monatlich/jährlich, im Voraus). Je Kunde ein Entwurf; jede Periode wird genau einmal abgerechnet. Automatischer Lauf: {p?.auto ? 'eingeschaltet' : 'aus'} (Einstellungen → Firma).

+ {msg && {msg.t}} + {p === null ?

Wird geladen …

: p.periods.length === 0 ? : +
+ {p.periods.map((x) => ())} +
VertragZeitraumPositionNetto
{x.contractNumber}{fmtDay(x.start)} – {fmtDay(x.end)}{x.description}{eur(x.unitPriceNetCents)}
} +
); +} export default function Faellig() { const r = useRouter(); const [d, setD] = useState(null); const [err, setErr] = useState(''); const [busy, setBusy] = useState(''); - useEffect(() => { api('GET', '/invoices/reminders').then(setD).catch((e) => setErr(errMsg(e))); }, []); + const reload = () => api('GET', '/invoices/reminders').then(setD).catch((e) => setErr(errMsg(e))); + useEffect(() => { void reload(); }, []); async function createFor(c: DueContract) { setErr(''); setBusy(c.id); try { const inv = await api<{ id: string }>('POST', '/invoices', { orgId: c.orgId }); r.push(`/rechnungen/${inv.id}?fromContract=${c.id}`); } @@ -22,6 +45,7 @@ export default function Faellig() {

Fällig

← Rechnungen

Überfällige, bereits ausgestellte Rechnungen und aktive Verträge, bei denen die letzte Rechnung länger zurückliegt als ihre Verlängerungslaufzeit.

{err && {err}} + void reload()} /> {d === null ?

Wird geladen …

: (<>

Überfällige Rechnungen ({d.overdueInvoices.length})

diff --git a/apps/worker/src/index.ts b/apps/worker/src/index.ts index 9c397b1..11fa930 100644 --- a/apps/worker/src/index.ts +++ b/apps/worker/src/index.ts @@ -97,6 +97,17 @@ const purgeAudit = async () => { }; setInterval(() => void purgeAudit(), 24 * 3600_000); void purgeAudit(); +// Abrechnungslauf (#50): nur wenn unter Einstellungen > Firma eingeschaltet; erzeugt ausschließlich Entwürfe. +import { autoBillingEnabled, runBilling } from '@kc/platform/billing'; +const billing = async () => { + try { + if (!(await autoBillingEnabled())) return; + const r = await runBilling(null); + if (r.drafts.length) log(`Abrechnungslauf: ${r.drafts.length} Entwürfe mit ${r.drafts.reduce((n, d) => n + d.items, 0)} Positionen angelegt`); + } catch (e) { log(`Abrechnungslauf fehlgeschlagen: ${(e as Error).message}`); } +}; +setInterval(() => void billing(), 6 * 3600_000); void billing(); + // Ticket-Posteingang: eingehende Mails abrufen und zuordnen (siehe mailbox.ts) setInterval(() => void checkMailbox(log).catch((e) => log(`IMAP-Lauf fehlgeschlagen: ${(e as Error).message}`)), 120_000); void checkMailbox(log).catch((e) => log(`IMAP-Lauf fehlgeschlagen: ${(e as Error).message}`)); diff --git a/migrations/041_billing_periods.sql b/migrations/041_billing_periods.sql new file mode 100644 index 0000000..b831755 --- /dev/null +++ b/migrations/041_billing_periods.sql @@ -0,0 +1,19 @@ +-- Abrechnungsläufe (#50): jede Vertragsperiode wird genau einmal abgerechnet. Der Primärschlüssel (Vertrag, Periodenbeginn) +-- verhindert Doppelrechnungen auch bei parallelen Läufen. Wird ein ENTWURF gelöscht, wird die Periode wieder frei +-- (ON DELETE CASCADE); eine stornierte Rechnung hält die Periode dagegen belegt, bis das Personal sie ausdrücklich +-- zur erneuten Abrechnung freigibt. +CREATE TABLE invoice_billing_periods ( + contract_id CHAR(36) NOT NULL, + period_start DATE NOT NULL, + period_end DATE NOT NULL, + invoice_id CHAR(36) NOT NULL, + created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + PRIMARY KEY (contract_id, period_start), + INDEX (invoice_id), + FOREIGN KEY (contract_id) REFERENCES contracts(id), + FOREIGN KEY (invoice_id) REFERENCES invoices(id) ON DELETE CASCADE +); +-- Automatischer täglicher Lauf (nur Entwürfe) – standardmäßig AUS, Einschalten unter Einstellungen > Firma. +ALTER TABLE company_settings ADD COLUMN auto_billing_runs TINYINT(1) NOT NULL DEFAULT 0; +-- Vom automatischen Lauf angelegte Entwürfe haben keinen menschlichen Ersteller (Vermerk „Abrechnungslauf“ in note). +ALTER TABLE invoices MODIFY created_by CHAR(36) NULL; diff --git a/packages/platform/src/billing.ts b/packages/platform/src/billing.ts new file mode 100644 index 0000000..d0f6f8e --- /dev/null +++ b/packages/platform/src/billing.ts @@ -0,0 +1,99 @@ +import { randomUUID } from 'node:crypto'; +import { one, query, run, tx } from './db.js'; +import { addMonths } from './contractterms.js'; +import { divRound } from './pricing.js'; + +/** + * Abrechnungslauf (#50): erzeugt für fällige Vertragsperioden RECHNUNGSENTWÜRFE (nie automatisch ausgestellt – das + * Personal prüft und stellt aus). Regeln: + * - Perioden folgen dem Intervall im Preis-Snapshot des Vertrags (monatlich/jährlich), beginnend bei started_at, + * Abrechnung im Voraus: fällig, sobald der Periodenbeginn erreicht ist. + * - Jede Periode genau einmal: PRIMARY KEY (contract_id, period_start) in invoice_billing_periods; INSERT IGNORE in der + * Transaktion – ein paralleler Lauf wartet auf die Sperre und überspringt danach. + * - Bereits von Hand abgerechnete Verträge (Rechnungsposition mit contract_id, offen/bezahlt) gelten bis einschließlich + * der Periode der letzten solchen Rechnung als abgerechnet – keine nachträgliche Doppelrechnung. + * - Keine Abrechnung über das Vertragsende hinaus (wirksame Kündigung bzw. Laufzeitende ohne Verlängerung). + * - Je Kunde und Lauf ein Entwurf mit einer Position je Vertragsperiode. Höchstens MAX_PERIODS je Vertrag und Lauf. + */ +const MAX_PERIODS = 12; +const ymd = (d: Date) => d.toISOString().slice(0, 10); + +export interface DuePeriod { contractId: string; contractNumber: string; orgId: string; start: string; end: string; description: string; unitPriceNetCents: number; taxBp: number } + +export async function duePeriods(now = new Date()): Promise { + const contracts = await query(` + SELECT c.id, c.number, c.org_id, c.started_at, c.term_end, c.renewal, c.cancel_effective_at, c.price_snapshot_json, + (SELECT MAX(p.period_start) FROM invoice_billing_periods p WHERE p.contract_id = c.id) AS last_period, + (SELECT MAX(i.issue_date) FROM invoices i JOIN invoice_items ii ON ii.invoice_id = i.id + WHERE ii.contract_id = c.id AND i.status IN ('open','paid') AND NOT EXISTS (SELECT 1 FROM invoice_billing_periods p2 WHERE p2.invoice_id = i.id)) AS last_manual + FROM contracts c JOIN organizations o ON o.id = c.org_id AND o.status = 'active' + WHERE c.status = 'active' AND c.started_at IS NOT NULL`); + const out: DuePeriod[] = []; + for (const c of contracts) { + const snap = typeof c.price_snapshot_json === 'string' ? JSON.parse(c.price_snapshot_json) : c.price_snapshot_json; + const months = snap?.interval === 'monthly' ? 1 : snap?.interval === 'yearly' ? 12 : 0; + const net = Number(snap?.recurring?.net ?? 0); + if (!months || net <= 0) continue; + const end = c.cancel_effective_at ? new Date(c.cancel_effective_at) : c.renewal === 'none' && c.term_end ? new Date(c.term_end) : null; + const started = new Date(c.started_at); + let n = 0; let start = started; + const startOf = (k: number) => addMonths(started, k * months); + // erste offene Periode: nach der zuletzt automatisch abgerechneten bzw. nach der Periode der letzten Handrechnung + const after = (d: Date) => { while (startOf(n + 1) <= d) n++; n++; }; + if (c.last_period) { n = 0; after(new Date(`${ymd(new Date(c.last_period))}T00:00:00Z`)); } + else if (c.last_manual) { n = 0; after(new Date(`${ymd(new Date(c.last_manual))}T00:00:00Z`)); } + let count = 0; + while (count < MAX_PERIODS) { + start = startOf(n); + if (start > now) break; + if (end && start >= end) break; + const pEnd = new Date(startOf(n + 1).getTime() - 86400000); + out.push({ contractId: c.id, contractNumber: c.number, orgId: c.org_id, start: ymd(start), end: ymd(pEnd), + description: `${snap.name ?? 'Vertrag'} – ${c.number}, Zeitraum ${ymd(start).split('-').reverse().join('.')}–${ymd(pEnd).split('-').reverse().join('.')}`, + unitPriceNetCents: net, taxBp: Number(snap.taxBp ?? 1900) }); + n++; count++; + } + } + return out; +} + +export interface BillingRunResult { drafts: { invoiceId: string; orgId: string; items: number }[]; skipped: number } + +/** Legt je Kunde einen Entwurf mit allen fälligen, noch nicht belegten Perioden an. Idempotent und parallel sicher. */ +export async function runBilling(createdBy: string | null, now = new Date()): Promise { + const due = await duePeriods(now); + const byOrg = new Map(); + for (const p of due) byOrg.set(p.orgId, [...(byOrg.get(p.orgId) ?? []), p]); + const res: BillingRunResult = { drafts: [], skipped: 0 }; + for (const [orgId, periods] of byOrg) { + const invoiceId = randomUUID(); + const items = await tx(async (c) => { + await run("INSERT INTO invoices (id, org_id, note, created_by) VALUES (?,?,'Abrechnungslauf',?)", [invoiceId, orgId, createdBy], c); + let k = 0; let net = 0, tax = 0, gross = 0; + for (const p of periods) { + const r = await run('INSERT IGNORE INTO invoice_billing_periods (contract_id, period_start, period_end, invoice_id) VALUES (?,?,?,?)', [p.contractId, p.start, p.end, invoiceId], c); + if (r.affectedRows === 0) { res.skipped++; continue; } // von einem parallelen Lauf schon belegt + const lNet = p.unitPriceNetCents; const lTax = divRound(lNet * p.taxBp, 10000); // gleiche Rundung wie Rechnungspositionen + net += lNet; tax += lTax; gross += lNet + lTax; + await run('INSERT INTO invoice_items (id, invoice_id, contract_id, description, quantity, unit_price_net_cents, tax_bp, discount_bp, net_cents, tax_cents, gross_cents, sort_order) VALUES (?,?,?,?,1,?,?,0,?,?,?,?)', + [randomUUID(), invoiceId, p.contractId, p.description.slice(0, 300), lNet, p.taxBp, lNet, lTax, lNet + lTax, k++], c); + } + if (k === 0) { await run('DELETE FROM invoices WHERE id = ?', [invoiceId], c); return 0; } + await run('UPDATE invoices SET total_net_cents = ?, total_tax_cents = ?, total_gross_cents = ? WHERE id = ?', [net, tax, gross, invoiceId], c); + return k; + }); + if (items > 0) res.drafts.push({ invoiceId, orgId, items }); + } + return res; +} + +/** Gibt die Periode(n) einer STORNIERTEN Rechnung zur erneuten Abrechnung frei (bewusste Entscheidung des Personals). */ +export async function releaseCancelledPeriods(invoiceId: string): Promise { + const inv = await one('SELECT status FROM invoices WHERE id = ?', [invoiceId]); + if (!inv || inv.status !== 'cancelled') return -1; + return (await run('DELETE FROM invoice_billing_periods WHERE invoice_id = ?', [invoiceId])).affectedRows; +} + +export async function autoBillingEnabled(): Promise { + return !!(await one('SELECT auto_billing_runs FROM company_settings WHERE id = 1'))?.auto_billing_runs; +} diff --git a/packages/platform/src/pricing.ts b/packages/platform/src/pricing.ts index 3f2923c..19e292d 100644 --- a/packages/platform/src/pricing.ts +++ b/packages/platform/src/pricing.ts @@ -15,7 +15,7 @@ export interface PriceSnapshot { setup: { net: number; tax: number; gross: number }; recurring: { net: number; tax: number; gross: number }; } /** Kaufmännisches Runden (halb auf) für nicht-negative Ganzzahl-Division. */ -const divRound = (n: number, d: number): number => Math.floor((n * 2 + d) / (d * 2)); +export const divRound = (n: number, d: number): number => Math.floor((n * 2 + d) / (d * 2)); export function calculatePrice(i: PriceInput): PriceSnapshot { const ints: [string, number][] = [['setupCents', i.setupCents], ['recurringCents', i.recurringCents], ['taxBp', i.taxBp], ['quantity', i.quantity], ['discountBp', i.discountBp]];