Spanish invoices from paid orders: legal numbering, simplified/full, credit notes and VeriFactu-style hash chain
Install
genpm add @core/invoicesWhat you get
- Source in src/lib/invoices/, 8 files. (30.3 kB)
- AI rules in src/lib/invoices/AGENTS.md, plus IDE rule files.
- Env vars added to .env.example: INVOICE_ISSUER_NIF, INVOICE_ISSUER_NAME, INVOICE_ISSUER_ADDRESS, INVOICE_SERIES, INVOICE_VAT_RATE, INVOICE_RETAIL, INVOICE_QR_ENV.
- Resolves @core/contracts, @core/db, @core/orders for you.
README
This package has no README.
This is exactly what your AI reads when it works in src/lib/invoices. Nothing else is added to its context.
@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.
The exact tree that will be injected, after .genpmignore. Pinned to
// Recurso "Facturas" para @core/admin: solo lectura (las facturas no se editan), sustituir simplificada por completa
// y rectificar el total; enlace a la versión imprimible.
import { count, desc, eq, ilike, or } from 'drizzle-orm';
import { z } from 'zod';
import type { AdminContext, AdminResource } from '../contracts/index.ts';
import { getDb } from '../db/index.ts';
import { InvoiceError, rectifyInFull, replaceSimplified } from './invoices.ts';
import { type Invoice, invoices } from './schema.ts';
async function need(ctx: AdminContext, p: string) {
if (!(await ctx.can(p))) throw new InvoiceError('forbidden', `forbidden: ${p}`);
}
const ReplaceInput = z.object({ name: z.string().min(1).max(120), taxId: z.string().min(8).max(14), address: z.string().min(5).max(300), country: z.string().length(2).default('ES') });
export const invoicesAdminResource = (opts: { printPath?: (inv: Invoice) => string } = {}): AdminResource<Invoice> => ({
name: 'invoices',
label: { singular: 'Invoice', plural: 'Invoices' },
group: 'Store',
fields: [
{ name: 'number', label: 'Number', type: 'text', readOnly: true, list: true },
{ name: 'type', label: 'Type', type: 'text', readOnly: true, list: true },
{ name: 'issuedAt', label: 'Issued', type: 'datetime', readOnly: true, list: true },
{ name: 'total', label: 'Total', type: 'money', readOnly: true, list: true },
{ name: 'recipient', label: 'Recipient', type: 'json', readOnly: true },
{ name: 'lines', label: 'Lines', type: 'json', readOnly: true },
{ name: 'reason', label: 'Reason', type: 'text', readOnly: true },
],
input: z.never(),
title: (i) => i.number,
async list(q, ctx) {
await need(ctx, 'invoices:read');
const where = q.search ? or(ilike(invoices.number, `%${q.search.replace(/[%_\\]/g, (m) => `\\${m}`)}%`), eq(invoices.orderId, q.search)) : undefined;
const [total] = await getDb().select({ n: count() }).from(invoices).where(where);
const rows = await getDb().select().from(invoices).where(where).orderBy(desc(invoices.issuedAt)).limit(q.pageSize).offset((Math.max(q.page, 1) - 1) * q.pageSize);
return { rows, total: total?.n ?? 0 };
},
async get(id, ctx) {
await need(ctx, 'invoices:read');
const [r] = await getDb().select().from(invoices).where(eq(invoices.id, id));
return r ?? null;
},
...(opts.printPath && { links: (i: Invoice) => [{ label: 'Print / PDF', href: opts.printPath!(i) }] }),
actions: [
{
name: 'replace',
label: 'Issue full invoice (customer tax details)',
permission: 'invoices:create',
input: ReplaceInput,
available: (i) => i.type === 'F2',
async run(id, input, ctx) {
await need(ctx, 'invoices:create');
return replaceSimplified(id, ReplaceInput.parse(input));
},
},
{
name: 'rectify-total',
label: 'Rectify in full (credit note)',
permission: 'invoices:create',
confirm: true,
available: (i) => ['F1', 'F2', 'F3'].includes(i.type) && !!i.orderId,
async run(id, _i, ctx) {
await need(ctx, 'invoices:create');
// Solo lo que quede sin rectificar (reembolsos anteriores ya tienen su rectificativa).
return rectifyInFull(id);
},
},
],
});
This package declares no MCP servers.
| Version | Commit | Published | Scan |
|---|---|---|---|
| 1.0.1 | 6912dca | 6 hours ago | scan passed |
- npm
- zod ^4.0.0
- proposed
- GenPM proposes the npm command and runs it only if you say yes.
- Used by (0)
- No public package depends on it yet.
- scan
- scan passed · 0 findings
- commit
- v1.0.1 → 6912dca67ec74a456be4abfe09c9584156cc7e4a · verified after fetch
- scripts
- None. GenPM never runs package code.
- license
- MIT
- Quality
- 100/100
- Recognized licensepassed
- AGENTS.md explains its purposepassed
- AGENTS.md has integration stepspassed
- AGENTS.md lists conventions or don'tspassed
- Includes testspassed
- Security scan passedpassed
- Released in the last 6 monthspassed
- Verified publisherpassed
- Summary and keywordspassed
- report
- See something wrong?