Spanische Rechnungen aus Bestellungen: gesetzliche Nummerierung, vereinfacht/voll, Korrekturen, Hash-Kette
Installieren
genpm add @core/invoicesWas du bekommst
- Quellcode in src/lib/invoices/, 8 Dateien. (30,3 kB)
- KI-Regeln in src/lib/invoices/AGENTS.md, dazu Regeldateien für die IDE.
- Umgebungsvariablen in .env.example ergänzt: INVOICE_ISSUER_NIF, INVOICE_ISSUER_NAME, INVOICE_ISSUER_ADDRESS, INVOICE_SERIES, INVOICE_VAT_RATE, INVOICE_RETAIL, INVOICE_QR_ENV.
- Löst @core/contracts, @core/db, @core/orders für dich auf.
README
Dieses Paket hat keine README.
Genau das liest deine KI, wenn sie in src/lib/invoices arbeitet. Sonst wird ihrem Kontext nichts hinzugefügt.
@core/invoices — rules for AI agents
Purpose
Spanish invoices for paid orders (@core/orders): correlative numbering per series and year without gaps, simplified
invoice up to the legal limit and full invoice above it, credit notes (rectificativas por diferencias) for refunds in
their own series, full invoices that replace simplified ones when the customer gives their tax details, printable HTML
with the mandatory content, and VeriFactu-style registration records: each record carries the SHA-256 hash of the
previous one (format verified against the AEAT example) and the AEAT verification QR URL. Invoices are never edited
or deleted. Tables: invoices, invoice_counters, invoice_records.
Scope of 1.0 (tell the person): this package prepares the data required by RD 1007/2023 and Order HAC/1177/2024, but it does not yet sign records (non-VeriFactu mode) nor send them to the AEAT (VeriFactu mode), and it is not a certified billing system. Deadlines changed several times (RD-ley 15/2025 set 2027; in October 2026 the Ministry announced a move to October 2028): check the current official calendar with the AEAT or a tax advisor.
Map
index.ts—invoiceOrder,rectifyRefund,rectifyInFull,remainingToRectify,replaceSimplified,verifyChain,invoiceHtml,invoiceQrUrl,invoicesAdminResource.invoices.ts— issuing and order events.verifactu.ts— hash input, hash, Madrid dates, amounts, QR URL.html.ts— printable invoice.
Integration
- Env:
INVOICE_ISSUER_NIF,INVOICE_ISSUER_NAME,INVOICE_ISSUER_ADDRESS; optionalINVOICE_SERIES(defaultA; credit notes use<series>R),INVOICE_VAT_RATE(default 21, prices include VAT),INVOICE_RETAIL=1(simplified limit 3,000 € instead of 400 €),INVOICE_QR_ENV=testwhile testing. - Migrations as in
src/lib/db/AGENTS.md. Import@/lib/invoicesonce at startup (e.g.src/genpm/commerce.ts): it issues invoices when orders are paid and credit notes when they are refunded (background jobs, retried). - Admin: add
invoicesAdminResource({ printPath: (i) => \/invoices/${i.number}` })tosrc/genpm/admin.ts`. - Printable page for the owner (protected by
invoices:read) or the customer (signed order link): returnnew Response(invoiceHtml(inv, { qrImageSrc }), { headers: { 'content-type': 'text/html' } }). Generate the QR image frominvoiceQrUrl(inv)with a QR library in the app. - Verify: pay a test order → invoice
A<year>-000001; refund part → credit noteAR<year>-000001with a negative total;verifyChain(nif)returnsok: true.
Conventions
- Lines add up to the total: products at their pre-discount amount, one "Discount" line, "Shipping (<method>)" and "Tax" if added on top.
- "Rectify in full" (admin,
rectifyInFull) credits only what earlier credit notes left; it refuses when nothing remains. - All lines use one VAT rate in 1.0; mixed rates (reduced, exempt) need per-line taxes before using this package.
- Issue invoices in EUR only; convert other currencies before.
- Keep invoices and records at least as long as tax law requires (typically 4–6 years); never prune these tables.
Don't
- Don't edit, renumber or delete invoices or records; correct with credit notes.
- Don't print "VERI*FACTU" on invoices until records are actually sent to the AEAT.
- Don't present this package as certified or as legal/tax advice.
# @core/invoices — rules for AI agents
## Purpose
Spanish invoices for paid orders (@core/orders): correlative numbering per series and year without gaps, simplified
invoice up to the legal limit and full invoice above it, credit notes (rectificativas por diferencias) for refunds in
their own series, full invoices that replace simplified ones when the customer gives their tax details, printable HTML
with the mandatory content, and VeriFactu-style registration records: each record carries the SHA-256 hash of the
previous one (format verified against the AEAT example) and the AEAT verification QR URL. Invoices are never edited
or deleted. Tables: `invoices`, `invoice_counters`, `invoice_records`.
**Scope of 1.0 (tell the person):** this package prepares the data required by RD 1007/2023 and Order HAC/1177/2024,
but it does not yet sign records (non-VeriFactu mode) nor send them to the AEAT (VeriFactu mode), and it is not a
certified billing system. Deadlines changed several times (RD-ley 15/2025 set 2027; in October 2026 the Ministry
announced a move to October 2028): check the current official calendar with the AEAT or a tax advisor.
## Map
- `index.ts` — `invoiceOrder`, `rectifyRefund`, `rectifyInFull`, `remainingToRectify`, `replaceSimplified`, `verifyChain`, `invoiceHtml`, `invoiceQrUrl`, `invoicesAdminResource`.
- `invoices.ts` — issuing and order events. `verifactu.ts` — hash input, hash, Madrid dates, amounts, QR URL. `html.ts` — printable invoice.
## Integration
1. Env: `INVOICE_ISSUER_NIF`, `INVOICE_ISSUER_NAME`, `INVOICE_ISSUER_ADDRESS`; optional `INVOICE_SERIES` (default `A`;
credit notes use `<series>R`), `INVOICE_VAT_RATE` (default 21, prices include VAT), `INVOICE_RETAIL=1` (simplified
limit 3,000 € instead of 400 €), `INVOICE_QR_ENV=test` while testing.
2. Migrations as in `src/lib/db/AGENTS.md`. Import `@/lib/invoices` once at startup (e.g. `src/genpm/commerce.ts`):
it issues invoices when orders are paid and credit notes when they are refunded (background jobs, retried).
3. Admin: add `invoicesAdminResource({ printPath: (i) => \`/invoices/${i.number}\` })` to `src/genpm/admin.ts`.
4. Printable page for the owner (protected by `invoices:read`) or the customer (signed order link):
return `new Response(invoiceHtml(inv, { qrImageSrc }), { headers: { 'content-type': 'text/html' } })`. Generate the QR
image from `invoiceQrUrl(inv)` with a QR library in the app.
5. Verify: pay a test order → invoice `A<year>-000001`; refund part → credit note `AR<year>-000001` with a negative total;
`verifyChain(nif)` returns `ok: true`.
## Conventions
- Lines add up to the total: products at their pre-discount amount, one "Discount" line, "Shipping (<method>)" and "Tax" if added on top.
- "Rectify in full" (admin, `rectifyInFull`) credits only what earlier credit notes left; it refuses when nothing remains.
- All lines use one VAT rate in 1.0; mixed rates (reduced, exempt) need per-line taxes before using this package.
- Issue invoices in EUR only; convert other currencies before.
- Keep invoices and records at least as long as tax law requires (typically 4–6 years); never prune these tables.
## Don't
- Don't edit, renumber or delete invoices or records; correct with credit notes.
- Don't print "VERI*FACTU" on invoices until records are actually sent to the AEAT.
- Don't present this package as certified or as legal/tax advice.
Der genaue Baum, der nach .genpmignore eingebunden wird. Gepinnt an
// Tablas de @core/invoices. Las recoge drizzle-kit vía src/lib/db/drizzle.config.ts.
import { index, integer, jsonb, pgTable, primaryKey, text, timestamp, uniqueIndex } from 'drizzle-orm/pg-core';
import { primaryId, timestamps } from '../db/index.ts';
export type Party = { name: string; taxId?: string | null; address?: string | null; country?: string | null };
export type InvoiceLine = { description: string; quantity: number; unitPrice: number; total: number };
/** Contador por serie y año: numeración correlativa sin huecos (se bloquea la fila al emitir). */
export const invoiceCounters = pgTable(
'invoice_counters',
{ series: text('series').notNull(), year: integer('year').notNull(), last: integer('last').notNull().default(0) },
(t) => [primaryKey({ columns: [t.series, t.year] })],
);
export const invoices = pgTable(
'invoices',
{
id: primaryId('inv'),
/** Serie + año + número: `A2026-000123`. */
number: text('number').notNull().unique(),
series: text('series').notNull(),
/** F1 completa, F2 simplificada, F3 en sustitución de simplificada, R1 rectificativa, R5 rectificativa de simplificada. */
type: text('type', { enum: ['F1', 'F2', 'F3', 'R1', 'R5'] }).notNull(),
issuedAt: timestamp('issued_at', { withTimezone: true, mode: 'date' }).notNull(),
orderId: text('order_id'),
/** Factura rectificada o sustituida. */
rectifiesId: text('rectifies_id'),
reason: text('reason'),
issuer: jsonb('issuer').$type<Party>().notNull(),
recipient: jsonb('recipient').$type<Party | null>(),
lines: jsonb('lines').$type<InvoiceLine[]>().notNull(),
currency: text('currency').notNull(),
/** Importes en céntimos; en rectificativas por diferencias, negativos. */
base: integer('base').notNull(),
vatRate: integer('vat_rate').notNull(),
vat: integer('vat').notNull(),
total: integer('total').notNull(),
...timestamps,
},
(t) => [index('invoices_order_idx').on(t.orderId), uniqueIndex('invoices_order_type_idx').on(t.orderId, t.type, t.reason)],
);
/**
* Registros de facturación encadenados (RD 1007/2023, Orden HAC/1177/2024): cada alta o anulación lleva la huella
* SHA-256 del anterior del mismo emisor. Son inalterables: nunca se actualizan ni se borran.
*/
export const invoiceRecords = pgTable(
'invoice_records',
{
id: primaryId('irc'),
invoiceId: text('invoice_id').notNull(),
issuerTaxId: text('issuer_tax_id').notNull(),
seq: integer('seq').notNull(),
kind: text('kind', { enum: ['alta', 'anulacion'] }).notNull(),
huella: text('huella').notNull(),
previousHuella: text('previous_huella'),
/** `FechaHoraHusoGenRegistro` tal y como entra en la huella. */
generatedAt: text('generated_at').notNull(),
/** Campos del registro tal y como entran en la huella (para verificar la cadena). */
fields: jsonb('fields').$type<Record<string, string>>().notNull(),
createdAt: timestamp('created_at', { withTimezone: true, mode: 'date' }).notNull().defaultNow(),
},
(t) => [uniqueIndex('invoice_records_chain_idx').on(t.issuerTaxId, t.seq)],
);
export type Invoice = typeof invoices.$inferSelect;
export type InvoiceRecord = typeof invoiceRecords.$inferSelect;
Dieses Paket deklariert keine MCP-Server.
| Version | Commit | Veröffentlicht | Prüfung |
|---|---|---|---|
| 1.0.1 | 6912dca | vor 4 Stunden | Prüfung bestanden |
- npm
- zod ^4.0.0
- vorgeschlagen
- GenPM schlägt den npm-Befehl vor und führt ihn nur aus, wenn du zustimmst.
- Verwendet von (0)
- Noch hängt kein öffentliches Paket davon ab.
- Prüfung
- Prüfung bestanden · 0 Befunde
- Commit
- v1.0.1 → 6912dca67ec74a456be4abfe09c9584156cc7e4a · nach dem Abruf verifiziert
- Skripte
- Keine. GenPM führt niemals Paketcode aus.
- Lizenz
- MIT
- Qualität
- 100/100
- Anerkannte Lizenzerfüllt
- AGENTS.md erklärt den Zweckerfüllt
- AGENTS.md enthält Integrationsschritteerfüllt
- AGENTS.md nennt Konventionen oder Verboteerfüllt
- Enthält Testserfüllt
- Sicherheitsscan bestandenerfüllt
- In den letzten 6 Monaten veröffentlichterfüllt
- Verifizierter Herausgebererfüllt
- Zusammenfassung und Schlagwörtererfüllt
- Meldung
- Stimmt etwas nicht?