feat(accounting): add scoped financial source event feed #48
|
|
@ -92,3 +92,5 @@ Moderated community discussions: see [Phase 5A API guide](docs/forum-api.md).
|
|||
Commerce activity analytics: see [Phase 5B API guide](docs/commerce-analytics-api.md).
|
||||
|
||||
Captured-request forecast baseline: see [Phase 5C API guide](docs/capture-forecasts-api.md).
|
||||
|
||||
Accounting source events: see [Phase 5D API guide](docs/accounting-source-feed-api.md).
|
||||
|
|
|
|||
|
|
@ -0,0 +1,30 @@
|
|||
# Accounting source feed (Phase 5D)
|
||||
|
||||
This provider-independent contract exposes recorded supplier invoices, supplier payments and corrections, plus external partner receipts and corrections. It supplies immutable source facts for future reconciliation/adapters. It does not assign a chart of accounts, generate journal debits/credits, post to an external system, or infer retail paid sales. Source records, source approvals, and their existing audit trail remain unchanged.
|
||||
|
||||
`GET /api/v1/accounting/source-events` requires `accounting.read`, rechecked against the live session and caller's organization in the read transaction. Existing system Owners gain the permission; custom roles must grant it explicitly. Other finance/analytics permissions do not implicitly grant access to this feed.
|
||||
|
||||
Required `from` and `to` reuse the bounded analytics datetime contract: explicit UTC/offsets, at most millisecond precision, supported normalized years, increasing by at most 366 elapsed days. Start is inclusive and end exclusive. Selection uses each source record's **recorded timestamp**, not its invoice/payment business date. Optional `currency` is a three-uppercase-letter filter, `kind` one of the six types below, and `limit` an integer 1–100 (default 25). Extra fields, offset pagination, invalid windows/types, and malformed/incompatible cursors return 400; absent sessions return 401 and insufficient permission 403.
|
||||
|
||||
| Event type | Operation | Amount and relationship |
|
||||
| --------------------------- | --------- | -------------------------------------------------------------------------------------- |
|
||||
| `SUPPLIER_INVOICE` | `RECORD` | Captured payable total, merchandise/tax/shipping components; invoice and supplier IDs. |
|
||||
| `SUPPLIER_INVOICE_VOID` | `VOID` | Original captured invoice amounts; links to its original invoice event. |
|
||||
| `SUPPLIER_PAYMENT` | `RECORD` | Captured external payment amount; related invoice and supplier IDs. |
|
||||
| `SUPPLIER_PAYMENT_REVERSAL` | `REVERSE` | Original payment amount; links to that payment event. |
|
||||
| `PARTNER_RECEIPT` | `RECORD` | Captured external partner receipt; related partner order and business-account IDs. |
|
||||
| `PARTNER_RECEIPT_REVERSAL` | `REVERSE` | Original receipt amount; links to that receipt event. |
|
||||
|
||||
The response is `{ schemaVersion: 1, window, events, nextCursor }`. Each event contains `eventType`, `operation`, `sourceId`, `eventKey`, `occurredAt`, nullable `businessDate`, `currency`, positive two-decimal `amount`, nullable component amounts, `relatedId`/`relatedType`, `counterpartyId`/`counterpartyType`, and nullable `reversesEventKey`. `eventKey` is `<eventType>:<sourceId>`, unique within the organization. A correction can use the same source UUID under a different event type. Every original remains present after later void/reversal, so a consumer can process both original and correcting facts rather than silently losing history.
|
||||
|
||||
Invoice/payment/receipt business dates are copied from their source. Corrections have no separately recorded business date and return null; their recording timestamp and original-event link remain available. All amounts remain positive; `operation` expresses the source correction without assuming a provider's signed-value/debit/credit convention. Invoice tax/shipping are captured charges, not a tax treatment decision. Payment reversal records invalidate an external payment entry and are not proof of a bank refund. Currencies are retained separately, with no conversion or combined amount.
|
||||
|
||||
Results are ordered by recorded timestamp, event type using deterministic C collation, then UUID. Fetch the next page by sending the returned opaque `cursor` with the same organization/window/currency/type; page size may change. The token validates a timestamp/type/UUID position and a filter/scope fingerprint. It is a pagination hint, not an authorization credential; every query independently enforces caller scope. `limit + 1` lookahead determines whether another cursor is needed. Missing/empty pages return `nextCursor: null`, and tied timestamps remain traversable by type/UUID.
|
||||
|
||||
**Synchronization limit:** pages are independent live database snapshots, not a durable change-data-capture stream or exactly-once export. A transaction committed later can have an earlier recording timestamp and arrive behind a consumed cursor. Consumers must repeatedly scan overlapping closed windows and deduplicate by `(organization, eventKey)`, including correction events, before advancing their own reconciliation checkpoint. Do not treat the last page as certification that a period can never gain a late record. Persistent export batches/acknowledgements can follow when a concrete accounting provider and delivery guarantees are selected.
|
||||
|
||||
The feed omits invoice numbers, bank/payment references, methods, contact/profile/address data, staff reasons/IDs, evidence files, hashes, and request keys. Stable technical document/counterparty IDs allow explicit external mappings later. Only recorded supplier liabilities and external receipt/payment facts are included; retail pending orders, quotes, production estimates and unfinalized tax/shipping are not invented as accounting entries.
|
||||
|
||||
One parameterized UNION query supplies each page's snapshot without taking the organization write lock. Scoped joins protect every correction/original relationship. Six additive source timestamp indexes support bounded scans; no export table, queue, provider credential, CSV conversion, or new dependency is introduced. Deploy the indexes/Owner-permission migration before the application, scheduling index builds appropriately for large source tables. Older code ignores them on rollback. Preserve financial records, corrections and audit evidence; historical migrations are not edited.
|
||||
|
||||
Verification covers all six source types, original/correction coexistence, exact positive amounts/components, original-event links, recording-time boundaries versus business dates, deterministic tie pagination, filter/scope-bound cursors, malformed tokens, private-field omission, permission/organization isolation, strict limits, and migration drift. External ledger posting, chart-of-account/tax mapping, durable synchronization and native multi-connection PostgreSQL CI remain outside this milestone.
|
||||
|
|
@ -70,6 +70,7 @@ Moderated forums, advanced analytics, forecasts, accounting adapters, profitabil
|
|||
- 5A (backend implemented): immutable discussion threads and flat replies, independent append-only approval/rejection/hiding, private author history, public alias-only discovery, parent visibility gates, and pending-submission quotas. Forum UI, editing/appeals, media, realtime features and notifications remain separate milestones.
|
||||
- 5B (implemented): bounded UTC daily checkout activity and frozen variant-demand analytics, current-state/currency separation, exact snapshot values, scoped reporting permissions, and UTC application sessions. Paid/fulfilled revenue, financial recognition, forecasts, cross-channel analytics and dashboard UI remain separate milestones.
|
||||
- 5C (baseline implemented): bounded historical daily capture-rate projections with exact unit arithmetic, zero-day inclusion, cancellation exclusion, visible evidence/staleness and current catalog flags. Validated sales/seasonal forecasts, confidence intervals, stock actions and automated production planning remain separate milestones.
|
||||
- 5D (source contract implemented): scoped, bounded accounting source-event pages for supplier invoices/payments and partner receipts, with original/correction links, exact captured amounts and deterministic cursor traversal. Provider posting, ledger/tax mapping and durable export acknowledgements remain separate milestones.
|
||||
|
||||
## Definition of done for every feature
|
||||
|
||||
|
|
|
|||
|
|
@ -53,5 +53,6 @@
|
|||
"20261007150000_customer_segments": "bcafd50bc12dc44b7ee532ba4ca23da0b12eb3f0e89ad4b168789a22e110969a",
|
||||
"20261007160000_moderated_forums": "3a7dce2115e06acd0f4b02d366721db5ebcf8b5f31106b5d85093c1374a2b6a5",
|
||||
"20261007170000_commerce_analytics": "800e392f788e176e3fb27c04f956a18e5f1505b820af6bb2364fc990aa8d26ea",
|
||||
"20261008100000_capture_forecasts": "69b94ac61b9f1c3f47268d5586d7f73c4c392cabdd3049d01f34e5e033cac043"
|
||||
"20261008100000_capture_forecasts": "69b94ac61b9f1c3f47268d5586d7f73c4c392cabdd3049d01f34e5e033cac043",
|
||||
"20261008110000_accounting_sources": "47b89e83291dbdf7b9fc7f1f25e7260a9f06bde0291ae2f7db01200e75eed396"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,8 @@
|
|||
CREATE INDEX supplier_invoices_accounting_idx ON supplier_invoices (organization_id, created_at, id);
|
||||
CREATE INDEX supplier_invoice_voids_accounting_idx ON supplier_invoice_voids (organization_id, created_at, invoice_id);
|
||||
CREATE INDEX supplier_payments_accounting_idx ON supplier_payments (organization_id, created_at, id);
|
||||
CREATE INDEX supplier_payment_reversals_accounting_idx ON supplier_payment_reversals (organization_id, created_at, payment_id);
|
||||
CREATE INDEX partner_payments_accounting_idx ON b2b_partner_payments (organization_id, created_at, id);
|
||||
CREATE INDEX partner_payment_reversals_accounting_idx ON b2b_partner_payment_reversals (organization_id, created_at, payment_id);
|
||||
UPDATE roles SET permissions = ARRAY(SELECT DISTINCT unnest(permissions || ARRAY['accounting.read']))
|
||||
WHERE is_system = true AND name = 'Owner';
|
||||
|
|
@ -86,6 +86,7 @@ model B2bPartnerPayment {
|
|||
@@unique([organizationId, reference])
|
||||
@@index([organizationId, orderId, createdAt, id])
|
||||
@@map("b2b_partner_payments")
|
||||
@@index([organizationId, createdAt, id], map: "partner_payments_accounting_idx")
|
||||
}
|
||||
|
||||
model B2bPartnerPaymentReversal {
|
||||
|
|
@ -102,4 +103,5 @@ model B2bPartnerPaymentReversal {
|
|||
@@unique([paymentId, organizationId])
|
||||
@@unique([organizationId, idempotencyKey])
|
||||
@@map("b2b_partner_payment_reversals")
|
||||
@@index([organizationId, createdAt, paymentId], map: "partner_payment_reversals_accounting_idx")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -224,6 +224,7 @@ model SupplierInvoice {
|
|||
@@unique([id, organizationId])
|
||||
@@index([organizationId, purchaseOrderId, createdAt, id], map: "supplier_invoices_order_created_idx")
|
||||
@@map("supplier_invoices")
|
||||
@@index([organizationId, createdAt, id], map: "supplier_invoices_accounting_idx")
|
||||
}
|
||||
|
||||
model SupplierInvoiceLine {
|
||||
|
|
@ -253,6 +254,7 @@ model SupplierInvoiceVoid {
|
|||
voidedBy User @relation(fields: [voidedById, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
@@unique([invoiceId, organizationId])
|
||||
@@map("supplier_invoice_voids")
|
||||
@@index([organizationId, createdAt, invoiceId], map: "supplier_invoice_voids_accounting_idx")
|
||||
}
|
||||
|
||||
model SupplierPayment {
|
||||
|
|
@ -277,6 +279,7 @@ model SupplierPayment {
|
|||
@@unique([id, organizationId])
|
||||
@@index([organizationId, invoiceId, createdAt, id], map: "supplier_payments_invoice_created_idx")
|
||||
@@map("supplier_payments")
|
||||
@@index([organizationId, createdAt, id], map: "supplier_payments_accounting_idx")
|
||||
}
|
||||
|
||||
model SupplierPaymentReversal {
|
||||
|
|
@ -290,4 +293,5 @@ model SupplierPaymentReversal {
|
|||
reversedBy User @relation(fields: [reversedById, organizationId], references: [id, organizationId], onDelete: Restrict, map: "supplier_payment_reversal_actor_scope_fkey")
|
||||
@@unique([paymentId, organizationId])
|
||||
@@map("supplier_payment_reversals")
|
||||
@@index([organizationId, createdAt, paymentId], map: "supplier_payment_reversals_accounting_idx")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,21 @@
|
|||
import { Controller, Get, Query } from '@nestjs/common';
|
||||
import {
|
||||
CurrentPrincipal,
|
||||
RequirePermission,
|
||||
} from '../identity/access.decorator';
|
||||
import type { Principal } from '../identity/identity.types';
|
||||
import { SchemaPipe } from '../common/validation.pipe';
|
||||
import { sourceQuerySchema, type SourceQuery } from './source.schemas';
|
||||
import { AccountingSourceStore } from './source.store';
|
||||
@Controller('accounting')
|
||||
@RequirePermission('accounting.read')
|
||||
export class AccountingController {
|
||||
constructor(private readonly sources: AccountingSourceStore) {}
|
||||
@Get('source-events')
|
||||
events(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Query(new SchemaPipe(sourceQuerySchema)) query: SourceQuery,
|
||||
) {
|
||||
return this.sources.events(actor, query);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
import { Module } from '@nestjs/common';
|
||||
import { IdentityModule } from '../identity/identity.module';
|
||||
import { AccountingController } from './accounting.controller';
|
||||
import { AccountingSourceStore } from './source.store';
|
||||
@Module({
|
||||
imports: [IdentityModule],
|
||||
controllers: [AccountingController],
|
||||
providers: [AccountingSourceStore],
|
||||
})
|
||||
export class AccountingModule {}
|
||||
|
|
@ -0,0 +1,53 @@
|
|||
import { AppError } from '../common/errors/app-error';
|
||||
import { commandHash } from '../common/idempotency';
|
||||
import {
|
||||
sourceCursorSchema,
|
||||
type SourceQuery,
|
||||
type SourceCursor,
|
||||
} from './source.schemas';
|
||||
export function sourceScope(organizationId: string, query: SourceQuery) {
|
||||
return commandHash(
|
||||
organizationId,
|
||||
query.from.toISOString(),
|
||||
query.to.toISOString(),
|
||||
query.currency ?? '',
|
||||
query.kind ?? '',
|
||||
);
|
||||
}
|
||||
export function decodeSourceCursor(
|
||||
value: string | undefined,
|
||||
scope: string,
|
||||
query: SourceQuery,
|
||||
): SourceCursor | null {
|
||||
if (!value) return null;
|
||||
try {
|
||||
const parsed = sourceCursorSchema.safeParse(
|
||||
JSON.parse(Buffer.from(value, 'base64url').toString('utf8')),
|
||||
);
|
||||
if (
|
||||
parsed.success &&
|
||||
parsed.data.scope === scope &&
|
||||
parsed.data.at >= query.from &&
|
||||
parsed.data.at < query.to
|
||||
)
|
||||
return parsed.data;
|
||||
} catch {
|
||||
/* Invalid bytes/JSON become the same public validation error. */
|
||||
}
|
||||
throw new AppError('REQUEST_INVALID', 'Invalid accounting source cursor', [
|
||||
'cursor',
|
||||
]);
|
||||
}
|
||||
export function encodeSourceCursor(
|
||||
row: { occurredAt: Date; eventType: string; sourceId: string },
|
||||
scope: string,
|
||||
) {
|
||||
return Buffer.from(
|
||||
JSON.stringify({
|
||||
at: row.occurredAt.toISOString(),
|
||||
type: row.eventType,
|
||||
id: row.sourceId,
|
||||
scope,
|
||||
}),
|
||||
).toString('base64url');
|
||||
}
|
||||
|
|
@ -0,0 +1,57 @@
|
|||
import { Prisma } from '../generated/prisma/client';
|
||||
import type { SourceQuery, SourceCursor } from './source.schemas';
|
||||
export function accountingSourceQuery(
|
||||
organizationId: string,
|
||||
query: SourceQuery,
|
||||
cursor: SourceCursor | null,
|
||||
) {
|
||||
const currency = query.currency
|
||||
? Prisma.sql`AND e.currency = ${query.currency}`
|
||||
: Prisma.empty;
|
||||
const kind = query.kind
|
||||
? Prisma.sql`AND e.event_type = ${query.kind}`
|
||||
: Prisma.empty;
|
||||
const after = cursor
|
||||
? Prisma.sql`AND (e.occurred_at, e.event_type COLLATE "C", e.source_id) > (${cursor.at}, ${cursor.type}::text COLLATE "C", ${cursor.id}::uuid)`
|
||||
: Prisma.empty;
|
||||
return Prisma.sql`WITH events AS (
|
||||
SELECT 'SUPPLIER_INVOICE'::text event_type, 'RECORD'::text operation, i.id source_id, i.created_at occurred_at,
|
||||
i.invoice_date::text business_date, i.currency, i.payable_total::text amount,
|
||||
i.merchandise_total::text merchandise_amount, i.tax_amount::text tax_amount, i.shipping_amount::text shipping_amount,
|
||||
i.id related_id, 'SUPPLIER_INVOICE'::text related_type, i.supplier_id counterparty_id, 'SUPPLIER'::text counterparty_type,
|
||||
NULL::text reverses_event_key
|
||||
FROM supplier_invoices i WHERE i.organization_id = ${organizationId}::uuid
|
||||
UNION ALL
|
||||
SELECT 'SUPPLIER_INVOICE_VOID', 'VOID', v.invoice_id, v.created_at, NULL::text, i.currency, i.payable_total::text,
|
||||
i.merchandise_total::text, i.tax_amount::text, i.shipping_amount::text, i.id, 'SUPPLIER_INVOICE', i.supplier_id, 'SUPPLIER', 'SUPPLIER_INVOICE:' || i.id::text
|
||||
FROM supplier_invoice_voids v JOIN supplier_invoices i ON i.id = v.invoice_id AND i.organization_id = v.organization_id
|
||||
WHERE v.organization_id = ${organizationId}::uuid
|
||||
UNION ALL
|
||||
SELECT 'SUPPLIER_PAYMENT', 'RECORD', p.id, p.created_at, p.paid_at::text, p.currency, p.amount::text,
|
||||
NULL::text, NULL::text, NULL::text, p.invoice_id, 'SUPPLIER_INVOICE', i.supplier_id, 'SUPPLIER', NULL::text
|
||||
FROM supplier_payments p JOIN supplier_invoices i ON i.id = p.invoice_id AND i.organization_id = p.organization_id
|
||||
WHERE p.organization_id = ${organizationId}::uuid
|
||||
UNION ALL
|
||||
SELECT 'SUPPLIER_PAYMENT_REVERSAL', 'REVERSE', r.payment_id, r.created_at, NULL::text, p.currency, p.amount::text,
|
||||
NULL::text, NULL::text, NULL::text, p.invoice_id, 'SUPPLIER_INVOICE', i.supplier_id, 'SUPPLIER', 'SUPPLIER_PAYMENT:' || p.id::text
|
||||
FROM supplier_payment_reversals r JOIN supplier_payments p ON p.id = r.payment_id AND p.organization_id = r.organization_id
|
||||
JOIN supplier_invoices i ON i.id = p.invoice_id AND i.organization_id = p.organization_id
|
||||
WHERE r.organization_id = ${organizationId}::uuid
|
||||
UNION ALL
|
||||
SELECT 'PARTNER_RECEIPT', 'RECORD', p.id, p.created_at, p.received_on::text, p.currency, p.amount::text,
|
||||
NULL::text, NULL::text, NULL::text, p.order_id, 'PARTNER_ORDER', o.account_id, 'B2B_ACCOUNT', NULL::text
|
||||
FROM b2b_partner_payments p JOIN b2b_partner_orders o ON o.id = p.order_id AND o.organization_id = p.organization_id
|
||||
WHERE p.organization_id = ${organizationId}::uuid
|
||||
UNION ALL
|
||||
SELECT 'PARTNER_RECEIPT_REVERSAL', 'REVERSE', r.payment_id, r.created_at, NULL::text, p.currency, p.amount::text,
|
||||
NULL::text, NULL::text, NULL::text, p.order_id, 'PARTNER_ORDER', o.account_id, 'B2B_ACCOUNT', 'PARTNER_RECEIPT:' || p.id::text
|
||||
FROM b2b_partner_payment_reversals r JOIN b2b_partner_payments p ON p.id = r.payment_id AND p.organization_id = r.organization_id
|
||||
JOIN b2b_partner_orders o ON o.id = p.order_id AND o.organization_id = p.organization_id
|
||||
WHERE r.organization_id = ${organizationId}::uuid
|
||||
) SELECT e.event_type AS "eventType", e.operation, e.source_id AS "sourceId", e.occurred_at AS "occurredAt",
|
||||
e.business_date AS "businessDate", e.currency, e.amount, e.merchandise_amount AS "merchandiseAmount",
|
||||
e.tax_amount AS "taxAmount", e.shipping_amount AS "shippingAmount", e.related_id AS "relatedId", e.related_type AS "relatedType",
|
||||
e.counterparty_id AS "counterpartyId", e.counterparty_type AS "counterpartyType", e.reverses_event_key AS "reversesEventKey"
|
||||
FROM events e WHERE e.occurred_at >= ${query.from} AND e.occurred_at < ${query.to} ${currency} ${kind} ${after}
|
||||
ORDER BY e.occurred_at, e.event_type COLLATE "C", e.source_id LIMIT ${query.limit + 1}`;
|
||||
}
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
import { z } from 'zod';
|
||||
import { analyticsWindowSchema } from '../analytics/analytics.schemas';
|
||||
export const SOURCE_KINDS = [
|
||||
'SUPPLIER_INVOICE',
|
||||
'SUPPLIER_INVOICE_VOID',
|
||||
'SUPPLIER_PAYMENT',
|
||||
'SUPPLIER_PAYMENT_REVERSAL',
|
||||
'PARTNER_RECEIPT',
|
||||
'PARTNER_RECEIPT_REVERSAL',
|
||||
] as const;
|
||||
export const sourceQuerySchema = analyticsWindowSchema.safeExtend({
|
||||
kind: z.enum(SOURCE_KINDS).optional(),
|
||||
limit: z.coerce.number().int().min(1).max(100).default(25),
|
||||
cursor: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(900)
|
||||
.regex(/^[A-Za-z0-9_-]+$/)
|
||||
.optional(),
|
||||
});
|
||||
export const sourceCursorSchema = z
|
||||
.object({
|
||||
at: analyticsWindowSchema.shape.from,
|
||||
type: z.enum(SOURCE_KINDS),
|
||||
id: z.uuid(),
|
||||
scope: z.string().regex(/^[a-f0-9]{64}$/),
|
||||
})
|
||||
.strict();
|
||||
export type SourceQuery = z.infer<typeof sourceQuerySchema>;
|
||||
export type SourceCursor = z.infer<typeof sourceCursorSchema>;
|
||||
|
|
@ -0,0 +1,73 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
import { AccessStore } from '../identity/access.store';
|
||||
import type { Principal } from '../identity/identity.types';
|
||||
import { Prisma } from '../generated/prisma/client';
|
||||
import { accountingSourceQuery } from './source-query';
|
||||
import {
|
||||
sourceScope,
|
||||
decodeSourceCursor,
|
||||
encodeSourceCursor,
|
||||
} from './source-cursor';
|
||||
import type { SourceQuery } from './source.schemas';
|
||||
type SourceRow = {
|
||||
eventType: string;
|
||||
operation: string;
|
||||
sourceId: string;
|
||||
occurredAt: Date;
|
||||
businessDate: string | null;
|
||||
currency: string;
|
||||
amount: string;
|
||||
merchandiseAmount: string | null;
|
||||
taxAmount: string | null;
|
||||
shippingAmount: string | null;
|
||||
relatedId: string;
|
||||
relatedType: string;
|
||||
counterpartyId: string;
|
||||
counterpartyType: string;
|
||||
reversesEventKey: string | null;
|
||||
};
|
||||
const fixed = (amount: string) => new Prisma.Decimal(amount).toFixed(2);
|
||||
@Injectable()
|
||||
export class AccountingSourceStore {
|
||||
constructor(private readonly access: AccessStore) {}
|
||||
events(actor: Principal, query: SourceQuery) {
|
||||
return this.access.mutate(
|
||||
actor,
|
||||
'accounting.read',
|
||||
async (tx) => {
|
||||
const scope = sourceScope(actor.organizationId, query);
|
||||
const cursor = decodeSourceCursor(query.cursor, scope, query);
|
||||
const rows = await tx.$queryRaw<SourceRow[]>(
|
||||
accountingSourceQuery(actor.organizationId, query, cursor),
|
||||
);
|
||||
const page = rows.slice(0, query.limit);
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
window: {
|
||||
from: query.from.toISOString(),
|
||||
to: query.to.toISOString(),
|
||||
currency: query.currency ?? null,
|
||||
kind: query.kind ?? null,
|
||||
},
|
||||
events: page.map((row) => ({
|
||||
...row,
|
||||
eventKey: row.eventType + ':' + row.sourceId,
|
||||
amount: fixed(row.amount),
|
||||
merchandiseAmount:
|
||||
row.merchandiseAmount === null
|
||||
? null
|
||||
: fixed(row.merchandiseAmount),
|
||||
taxAmount: row.taxAmount === null ? null : fixed(row.taxAmount),
|
||||
shippingAmount:
|
||||
row.shippingAmount === null ? null : fixed(row.shippingAmount),
|
||||
})),
|
||||
nextCursor:
|
||||
rows.length > query.limit
|
||||
? encodeSourceCursor(page[page.length - 1], scope)
|
||||
: null,
|
||||
};
|
||||
},
|
||||
false,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -19,9 +19,11 @@ import { BlogModule } from './blog/blog.module';
|
|||
import { SegmentsModule } from './segments/segments.module';
|
||||
import { ForumModule } from './forum/forum.module';
|
||||
import { AnalyticsModule } from './analytics/analytics.module';
|
||||
import { AccountingModule } from './accounting/accounting.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
AccountingModule,
|
||||
AnalyticsModule,
|
||||
ForumModule,
|
||||
SegmentsModule,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
export const PERMISSIONS = [
|
||||
'accounting.read',
|
||||
'forecasts.read',
|
||||
'analytics.read',
|
||||
'forum.read',
|
||||
|
|
|
|||
|
|
@ -0,0 +1,56 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { sourceQuerySchema } from '../src/accounting/source.schemas';
|
||||
import {
|
||||
sourceScope,
|
||||
encodeSourceCursor,
|
||||
decodeSourceCursor,
|
||||
} from '../src/accounting/source-cursor';
|
||||
|
||||
it('round-trips validated positions and binds them to scope, window and filters', () => {
|
||||
const query = sourceQuerySchema.parse({
|
||||
from: '2026-01-01T00:00:00Z',
|
||||
to: '2026-01-02T00:00:00Z',
|
||||
});
|
||||
const scope = sourceScope(randomUUID(), query);
|
||||
const row = {
|
||||
occurredAt: query.from,
|
||||
eventType: 'SUPPLIER_INVOICE',
|
||||
sourceId: randomUUID(),
|
||||
};
|
||||
const token = encodeSourceCursor(row, scope);
|
||||
expect(decodeSourceCursor(token, scope, query)).toMatchObject({
|
||||
at: query.from,
|
||||
type: row.eventType,
|
||||
id: row.sourceId,
|
||||
scope,
|
||||
});
|
||||
expect(decodeSourceCursor(undefined, scope, query)).toBeNull();
|
||||
expect(() =>
|
||||
decodeSourceCursor(token, sourceScope(randomUUID(), query), query),
|
||||
).toThrow();
|
||||
expect(() => decodeSourceCursor('not-json', scope, query)).toThrow();
|
||||
expect(() =>
|
||||
decodeSourceCursor(
|
||||
encodeSourceCursor({ ...row, occurredAt: query.to }, scope),
|
||||
scope,
|
||||
query,
|
||||
),
|
||||
).toThrow();
|
||||
const extra = Buffer.from(
|
||||
JSON.stringify({
|
||||
at: query.from,
|
||||
type: row.eventType,
|
||||
id: row.sourceId,
|
||||
scope,
|
||||
organizationId: randomUUID(),
|
||||
}),
|
||||
).toString('base64url');
|
||||
expect(() => decodeSourceCursor(extra, scope, query)).toThrow();
|
||||
expect(
|
||||
sourceQuerySchema.safeParse({
|
||||
from: query.from.toISOString(),
|
||||
to: query.to.toISOString(),
|
||||
kind: 'UNKNOWN',
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
|
@ -0,0 +1,258 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { identityApp, type IdentityApp } from './helpers/identity-app';
|
||||
import {
|
||||
seedPurchaseOrder,
|
||||
receiveAccepted,
|
||||
seedSupplierInvoice,
|
||||
} from './helpers/procurement';
|
||||
import { seedPartnerOrder } from './helpers/b2b-partner-order';
|
||||
import { secondActor } from './helpers/commerce';
|
||||
|
||||
describe('provider-independent accounting source events', () => {
|
||||
let ctx: IdentityApp;
|
||||
beforeAll(async () => {
|
||||
ctx = await identityApp();
|
||||
});
|
||||
afterAll(async () => {
|
||||
await ctx.close();
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await ctx.clearLimits();
|
||||
});
|
||||
const window = { from: '2026-01-01T00:00:00Z', to: '2026-12-31T00:00:00Z' };
|
||||
const auth = { type: 'bearer' as const };
|
||||
const feed = (query: object = window, token = ctx.token) =>
|
||||
ctx
|
||||
.api()
|
||||
.get('/api/v1/accounting/source-events')
|
||||
.auth(token, auth)
|
||||
.query(query);
|
||||
async function evidence() {
|
||||
const order = await seedPurchaseOrder(ctx);
|
||||
await receiveAccepted(ctx, order, '1.000');
|
||||
const invoice = await ctx
|
||||
.api()
|
||||
.post('/api/v1/purchase-orders/' + order.id + '/invoices')
|
||||
.auth(ctx.token, auth)
|
||||
.send({
|
||||
invoiceNumber: randomUUID(),
|
||||
invoiceDate: '2026-09-28',
|
||||
taxAmount: '18.05',
|
||||
shippingAmount: '1.20',
|
||||
lines: [{ purchaseOrderLineId: order.lineId, quantity: '1.000' }],
|
||||
})
|
||||
.expect(201);
|
||||
const payment = await ctx
|
||||
.api()
|
||||
.post('/api/v1/supplier-invoices/' + invoice.body.id + '/payments')
|
||||
.auth(ctx.token, auth)
|
||||
.send({
|
||||
reference: randomUUID(),
|
||||
method: 'BANK_TRANSFER',
|
||||
amount: '50.01',
|
||||
paidDate: '2026-09-28',
|
||||
idempotencyKey: randomUUID(),
|
||||
})
|
||||
.expect(201);
|
||||
await ctx
|
||||
.api()
|
||||
.post('/api/v1/supplier-payments/' + payment.body.id + '/reverse')
|
||||
.auth(ctx.token, auth)
|
||||
.send({ reason: 'Entered in error' })
|
||||
.expect(201);
|
||||
await ctx
|
||||
.api()
|
||||
.post('/api/v1/supplier-invoices/' + invoice.body.id + '/void')
|
||||
.auth(ctx.token, auth)
|
||||
.send({ reason: 'Invoice superseded' })
|
||||
.expect(201);
|
||||
const partner = await seedPartnerOrder(ctx);
|
||||
const receipt = await ctx
|
||||
.api()
|
||||
.post('/api/v1/b2b/partner-orders/' + partner.order.id + '/payments')
|
||||
.auth(ctx.token, auth)
|
||||
.send({
|
||||
reference: randomUUID(),
|
||||
method: 'BANK_TRANSFER',
|
||||
amount: '0.10',
|
||||
receivedOn: '2026-10-03',
|
||||
idempotencyKey: randomUUID(),
|
||||
})
|
||||
.expect(201);
|
||||
await ctx
|
||||
.api()
|
||||
.post(
|
||||
'/api/v1/b2b/partner-orders/' +
|
||||
partner.order.id +
|
||||
'/payments/' +
|
||||
receipt.body.id +
|
||||
'/reverse',
|
||||
)
|
||||
.auth(ctx.token, auth)
|
||||
.send({ reason: 'Entered in error', idempotencyKey: randomUUID() })
|
||||
.expect(201);
|
||||
return {
|
||||
invoice: invoice.body,
|
||||
payment: payment.body,
|
||||
receipt: receipt.body,
|
||||
partner,
|
||||
};
|
||||
}
|
||||
it('retains originals and correction events with exact amounts and source links', async () => {
|
||||
const f = await evidence();
|
||||
const result = await feed().expect(200);
|
||||
expect(result.body.schemaVersion).toBe(1);
|
||||
expect(result.body.events).toHaveLength(6);
|
||||
const by = (type: string) =>
|
||||
result.body.events.find((e: any) => e.eventType === type);
|
||||
expect(by('SUPPLIER_INVOICE')).toMatchObject({
|
||||
sourceId: f.invoice.id,
|
||||
amount: '139.25',
|
||||
merchandiseAmount: '120.00',
|
||||
taxAmount: '18.05',
|
||||
shippingAmount: '1.20',
|
||||
businessDate: '2026-09-28',
|
||||
operation: 'RECORD',
|
||||
});
|
||||
expect(by('SUPPLIER_INVOICE_VOID')).toMatchObject({
|
||||
sourceId: f.invoice.id,
|
||||
amount: '139.25',
|
||||
operation: 'VOID',
|
||||
reversesEventKey: 'SUPPLIER_INVOICE:' + f.invoice.id,
|
||||
});
|
||||
expect(by('SUPPLIER_PAYMENT')).toMatchObject({
|
||||
sourceId: f.payment.id,
|
||||
amount: '50.01',
|
||||
relatedId: f.invoice.id,
|
||||
operation: 'RECORD',
|
||||
});
|
||||
expect(by('SUPPLIER_PAYMENT_REVERSAL')).toMatchObject({
|
||||
sourceId: f.payment.id,
|
||||
amount: '50.01',
|
||||
operation: 'REVERSE',
|
||||
reversesEventKey: 'SUPPLIER_PAYMENT:' + f.payment.id,
|
||||
});
|
||||
expect(by('PARTNER_RECEIPT')).toMatchObject({
|
||||
sourceId: f.receipt.id,
|
||||
amount: '0.10',
|
||||
counterpartyId: f.partner.accountId,
|
||||
relatedId: f.partner.order.id,
|
||||
});
|
||||
expect(by('PARTNER_RECEIPT_REVERSAL')).toMatchObject({
|
||||
sourceId: f.receipt.id,
|
||||
amount: '0.10',
|
||||
reversesEventKey: 'PARTNER_RECEIPT:' + f.receipt.id,
|
||||
});
|
||||
expect(new Set(result.body.events.map((e: any) => e.eventKey)).size).toBe(
|
||||
6,
|
||||
);
|
||||
expect(JSON.stringify(result.body)).not.toMatch(
|
||||
/contactEmail|contactPhone|reference|reason|requestHash|idempotencyKey|invoiceNumber|recordedById/,
|
||||
);
|
||||
expect(
|
||||
(await feed({ ...window, currency: 'USD' }).expect(200)).body.events,
|
||||
).toEqual([]);
|
||||
});
|
||||
it('pages without duplicate keys and rejects reuse with changed window or filters', async () => {
|
||||
await evidence();
|
||||
const initial = await feed({ ...window, limit: 1 }).expect(200);
|
||||
expect(initial.body.nextCursor).toEqual(expect.any(String));
|
||||
const keys = [initial.body.events[0].eventKey];
|
||||
let cursor = initial.body.nextCursor;
|
||||
for (let i = 0; cursor && i < 20; i++) {
|
||||
const page = await feed({ ...window, limit: 1, cursor }).expect(200);
|
||||
keys.push(...page.body.events.map((e: any) => e.eventKey));
|
||||
cursor = page.body.nextCursor;
|
||||
}
|
||||
expect(cursor).toBeNull();
|
||||
expect(new Set(keys).size).toBe(keys.length);
|
||||
expect(keys.length).toBeGreaterThanOrEqual(6);
|
||||
await feed({
|
||||
...window,
|
||||
cursor: initial.body.nextCursor,
|
||||
currency: 'INR',
|
||||
}).expect(400);
|
||||
await feed({
|
||||
...window,
|
||||
cursor: initial.body.nextCursor,
|
||||
to: '2026-12-30T00:00:00Z',
|
||||
}).expect(400);
|
||||
await feed({ ...window, cursor: 'not-json' }).expect(400);
|
||||
});
|
||||
it('bounds recorded timestamps independently of business dates and preserves scoped permissions', async () => {
|
||||
const f = await evidence();
|
||||
const event = await ctx.db.supplierInvoice.findUniqueOrThrow({
|
||||
where: { id: f.invoice.id },
|
||||
});
|
||||
const from = event.createdAt.toISOString();
|
||||
const to = new Date(event.createdAt.getTime() + 1).toISOString();
|
||||
const result = await feed({ from, to, kind: 'SUPPLIER_INVOICE' }).expect(
|
||||
200,
|
||||
);
|
||||
expect(result.body.events).toHaveLength(1);
|
||||
expect(result.body.events[0].businessDate).toBe('2026-09-28');
|
||||
const customer = await secondActor(ctx);
|
||||
await feed(window, customer.token).expect(403);
|
||||
const foreign = await secondActor(ctx, false, ['accounting.read']);
|
||||
expect((await feed(window, foreign.token).expect(200)).body.events).toEqual(
|
||||
[],
|
||||
);
|
||||
const accountant = await secondActor(ctx, true, ['accounting.read']);
|
||||
await feed(window, accountant.token).expect(200);
|
||||
await ctx
|
||||
.api()
|
||||
.get('/api/v1/accounting/source-events')
|
||||
.query(window)
|
||||
.expect(401);
|
||||
for (const query of [
|
||||
{ ...window, limit: 101 },
|
||||
{ ...window, kind: 'PAID_RETAIL_SALE' },
|
||||
{ ...window, organizationId: foreign.organizationId },
|
||||
{ ...window, to: '2028-01-01T00:00:00Z' },
|
||||
{ ...window, offset: 1 },
|
||||
])
|
||||
await feed(query).expect(400);
|
||||
});
|
||||
it('uses source IDs to traverse events sharing a recorded timestamp', async () => {
|
||||
const { invoice } = await seedSupplierInvoice(ctx);
|
||||
const recordedAt = new Date();
|
||||
const payments = await ctx.db.$transaction(async (tx) => {
|
||||
const rows = [];
|
||||
for (const amount of ['25.01', '25.02'])
|
||||
rows.push(
|
||||
await tx.supplierPayment.create({
|
||||
data: {
|
||||
organizationId: ctx.owner.organizationId,
|
||||
invoiceId: invoice.id,
|
||||
createdById: ctx.owner.userId,
|
||||
idempotencyKey: randomUUID(),
|
||||
requestHash: 'a'.repeat(64),
|
||||
reference: randomUUID().toUpperCase(),
|
||||
method: 'BANK_TRANSFER',
|
||||
currency: 'INR',
|
||||
createdAt: recordedAt,
|
||||
amount,
|
||||
paidAt: new Date('2026-09-28T00:00:00Z'),
|
||||
},
|
||||
}),
|
||||
);
|
||||
return rows;
|
||||
});
|
||||
expect(payments[0].createdAt).toEqual(payments[1].createdAt);
|
||||
const query = {
|
||||
from: payments[0].createdAt.toISOString(),
|
||||
to: new Date(payments[0].createdAt.getTime() + 1).toISOString(),
|
||||
kind: 'SUPPLIER_PAYMENT',
|
||||
limit: 1,
|
||||
};
|
||||
const first = await feed(query).expect(200);
|
||||
const next = await feed({ ...query, cursor: first.body.nextCursor }).expect(
|
||||
200,
|
||||
);
|
||||
expect([
|
||||
first.body.events[0].sourceId,
|
||||
next.body.events[0].sourceId,
|
||||
]).toEqual(payments.map((p) => p.id).sort());
|
||||
expect(next.body.nextCursor).toBeNull();
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue