diff --git a/apps/api/src/modules/invoices/index.ts b/apps/api/src/modules/invoices/index.ts index 36613c3..3a5611c 100644 --- a/apps/api/src/modules/invoices/index.ts +++ b/apps/api/src/modules/invoices/index.ts @@ -284,6 +284,10 @@ export const invoicesModule: KcModule = { if (v.status !== 'draft') throw conflict('Nur Entwürfe können bearbeitet werden. Ausgestellte Rechnungen sind unveränderlich (nur Storno möglich).', 'INVOICE_NOT_DRAFT'); let net = 0, tax = 0, gross = 0; await tx(async (c) => { + // Status erst unter derselben Zeilensperre prüfen, die auch "Ausstellen" nimmt: sonst kann ein paralleles + // Ausstellen zwischen obiger Prüfung und dem Ersetzen gewinnen und die Positionen einer offenen Rechnung ändern. + const locked = await one('SELECT status FROM invoices WHERE id = ? FOR UPDATE', [id], c); + if (!locked || locked.status !== 'draft') throw conflict('Die Rechnung wurde inzwischen ausgestellt und ist unveränderlich (nur Storno möglich).', 'INVOICE_NOT_DRAFT'); await run('DELETE FROM invoice_items WHERE invoice_id = ?', [id], c); for (const [idx, it] of b.items.entries()) { const a2 = lineAmounts(it.unitPriceNetCents, it.quantity, it.taxBp, it.discountBp); net += a2.net; tax += a2.tax; gross += a2.gross; @@ -348,20 +352,24 @@ export const invoicesModule: KcModule = { // IBAN, Steuernummer oder die Kundenanschrift, bleibt diese schon ausgestellte Rechnung unverändert, wie es sein muss. const sellerSnap = { name: s.name, street: s.street, zip: s.zip, city: s.city, country: s.country, taxNumber: s.taxNumber, vatId: s.vatId, bankName: s.bankName, iban: s.iban, bic: s.bic, footerText: s.footerText }; const buyerSnap = { name: org?.company || org?.name || null, street: org?.street ?? null, zip: org?.zip ?? null, city: org?.city ?? null, country: org?.country ?? 'DE', vatId: org?.vat_id ?? null }; + let issuedGross = Number(v.total_gross_cents); const number = await tx(async (c) => { // Zeile sperren statt nur zu lesen: verhindert, dass zwei gleichzeitige "Ausstellen"-Aufrufe beide eine Nummer // ziehen (Nummernlücke) oder beide durchlaufen. Der Verlierer sieht nach dem Warten status≠'draft' und bricht ab, // ohne je eine Nummer verbraucht zu haben. - const locked = await one('SELECT status FROM invoices WHERE id = ? FOR UPDATE', [id], c); + const locked = await one('SELECT status, total_gross_cents FROM invoices WHERE id = ? FOR UPDATE', [id], c); if (!locked || locked.status !== 'draft') throw conflict('Die Rechnung wurde inzwischen von einem anderen Vorgang ausgestellt.', 'STALE_STATE'); + // Positionen unter der Sperre erneut zählen (ein paralleles Speichern hat sie evtl. gerade ersetzt). + if (!(await one('SELECT 1 AS x FROM invoice_items WHERE invoice_id = ? LIMIT 1', [id], c))) throw badRequest('Eine Rechnung ohne Positionen kann nicht ausgestellt werden.', 'NO_ITEMS'); + issuedGross = Number(locked.total_gross_cents); const n = await nextInvoiceNumber(c, s.invoicePrefix); await run("UPDATE invoices SET number = ?, status = 'open', issue_date = CURDATE(), due_date = ?, issued_at = UTC_TIMESTAMP(3), seller_snapshot_json = ?, buyer_snapshot_json = ? WHERE id = ?", [n, due, JSON.stringify(sellerSnap), JSON.stringify(buyerSnap), id], c); return n; }); await audit({ actorType: 'user', actorId: a.user.id, orgId: v.org_id, action: 'invoice.issue', resourceType: 'invoice', resourceId: id, correlationId: req.correlationId, ip: clientIp(req), after: { number } }); - await notify('invoice.issued', { number, gross: v.total_gross_cents }, `invoice.issued:${id}`, req.correlationId); - if (org?.billing_email) await mailTo(org.billing_email, 'invoice_issued', { name: org.contact_name || org.company || org.name, number, amount: deMoney(v.total_gross_cents), dueDate: deDate(due), invoiceLink: `${config.baseUrl}/rechnungen/${id}` }, `mail:invoice.issued:${id}`, req.correlationId); + await notify('invoice.issued', { number, gross: issuedGross }, `invoice.issued:${id}`, req.correlationId); + if (org?.billing_email) await mailTo(org.billing_email, 'invoice_issued', { name: org.contact_name || org.company || org.name, number, amount: deMoney(issuedGross), dueDate: deDate(due), invoiceLink: `${config.baseUrl}/rechnungen/${id}` }, `mail:invoice.issued:${id}`, req.correlationId); return { ok: true, number }; }); diff --git a/apps/api/test/invoices.test.ts b/apps/api/test/invoices.test.ts index 9a06b0d..921e21e 100644 --- a/apps/api/test/invoices.test.ts +++ b/apps/api/test/invoices.test.ts @@ -1,7 +1,7 @@ import { beforeAll, describe, expect, it } from 'vitest'; import type { FastifyInstance } from 'fastify'; import { buildApp } from '../src/server.js'; -import { one, run } from '../src/core/db.js'; +import { one, pool, query, run } from '../src/core/db.js'; import { runOnce } from '../../worker/src/jobs.js'; import { call, code, login, makeUser } from './helpers.js'; @@ -247,6 +247,48 @@ describe('Rechnungen: eingefrorener Absender-/Empfänger-Stand, atomare Statuswe const invAfter = (await call(app, acc, 'GET', `/invoices/${draft3.id}`)).json(); expect(invAfter.status).toBe('cancelled'); // nicht doppelt storniert, genau ein Storno-Verweis }); + + it('Positionen speichern während parallel ausgestellt wird: das Speichern wartet und scheitert mit 409, Positionen/Summen bleiben unverändert (#95)', async () => { + const admin = await staff('race3-admin@example.com', 'superadmin'); const acc = await staff('race3-acc@example.com', 'accounting'); + await call(app, admin, 'PUT', '/admin/company-settings', COMPANY); + const A = await customer(admin, 'Kunde Race3', 'race3-a@example.com'); + const draft = (await call(app, acc, 'POST', '/invoices', { orgId: A.org })).json(); + await call(app, acc, 'PUT', `/invoices/${draft.id}/items`, { items: [{ description: 'original', quantity: 1, unitPriceNetCents: 1000, taxBp: 1900 }] }); + + // Deterministisch: ein "Ausstellen" hält die Zeilensperre, das Speichern startet (Vorabprüfung sieht noch draft) + // und muss auf die Sperre warten; danach ist die Rechnung offen -> 409 statt veränderter Positionen. + const holder = await pool.getConnection(); + try { + await holder.beginTransaction(); + await holder.execute('SELECT status FROM invoices WHERE id = ? FOR UPDATE', [draft.id]); + const save = call(app, acc, 'PUT', `/invoices/${draft.id}/items`, { items: [{ description: 'manipuliert', quantity: 5, unitPriceNetCents: 99999, taxBp: 1900 }] }); + await new Promise((r) => setTimeout(r, 300)); + await holder.execute("UPDATE invoices SET status = 'open', number = 'RE-TEST-95', issue_date = CURDATE(), issued_at = UTC_TIMESTAMP(3) WHERE id = ?", [draft.id]); + await holder.commit(); + expect((await save).statusCode).toBe(409); + } finally { holder.release(); } + const items = await query('SELECT description, gross_cents FROM invoice_items WHERE invoice_id = ?', [draft.id]); + expect(items.map((i) => i.description)).toEqual(['original']); + expect(Number((await one('SELECT total_gross_cents FROM invoices WHERE id = ?', [draft.id]))!.total_gross_cents)).toBe(1190); + }); + + it('Speichern und Ausstellen gleichzeitig: Summe der ausgestellten Rechnung passt immer zu ihren Positionen', async () => { + const admin = await staff('race4-admin@example.com', 'superadmin'); const acc = await staff('race4-acc@example.com', 'accounting'); + await call(app, admin, 'PUT', '/admin/company-settings', COMPANY); + const A = await customer(admin, 'Kunde Race4', 'race4-a@example.com'); + for (let i = 0; i < 5; i++) { + const draft = (await call(app, acc, 'POST', '/invoices', { orgId: A.org })).json(); + await call(app, acc, 'PUT', `/invoices/${draft.id}/items`, { items: [{ description: 'a', quantity: 1, unitPriceNetCents: 1000, taxBp: 1900 }] }); + const [save, issue] = await Promise.all([ + call(app, acc, 'PUT', `/invoices/${draft.id}/items`, { items: [{ description: 'b', quantity: 2, unitPriceNetCents: 1000, taxBp: 1900 }] }), + call(app, acc, 'POST', `/invoices/${draft.id}/issue`), + ]); + expect([200, 409]).toContain(save.statusCode); expect(issue.statusCode).toBe(200); + const inv = await one('SELECT total_gross_cents FROM invoices WHERE id = ?', [draft.id]); + const sum = await one('SELECT SUM(gross_cents) AS s FROM invoice_items WHERE invoice_id = ?', [draft.id]); + expect(Number(inv!.total_gross_cents)).toBe(Number(sum!.s)); + } + }); }); describe('Rechnungspositionen: Rabatt je Position', () => {