Compare commits
2 Commits
main
...
feature/ac
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f4738f4a3f | ||
|
|
b9798f2c8c |
202
packages/backend/api-tests/suites/accounting.ts
Normal file
202
packages/backend/api-tests/suites/accounting.ts
Normal file
@@ -0,0 +1,202 @@
|
|||||||
|
import { suite } from '../lib/context.js'
|
||||||
|
|
||||||
|
suite('Accounting', { tags: ['accounting'] }, (t) => {
|
||||||
|
// ─── Invoices: CRUD ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
t.test('creates a manual invoice', { tags: ['invoices', 'create'] }, async () => {
|
||||||
|
const acct = await t.api.post('/v1/accounts', { name: 'Invoice Test Acct', billingMode: 'consolidated' })
|
||||||
|
const res = await t.api.post('/v1/invoices', {
|
||||||
|
accountId: acct.data.id,
|
||||||
|
issueDate: '2026-04-06',
|
||||||
|
dueDate: '2026-05-06',
|
||||||
|
lineItems: [
|
||||||
|
{ description: 'Service A', qty: 2, unitPrice: 50, taxRate: 0.0825 },
|
||||||
|
{ description: 'Service B', qty: 1, unitPrice: 100 },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
t.assert.status(res, 201)
|
||||||
|
t.assert.ok(res.data.invoiceNumber)
|
||||||
|
t.assert.equal(res.data.status, 'draft')
|
||||||
|
t.assert.ok(parseFloat(res.data.total) > 0)
|
||||||
|
t.assert.equal(res.data.balance, res.data.total)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.test('rejects invoice without line items', { tags: ['invoices', 'validation'] }, async () => {
|
||||||
|
const acct = await t.api.post('/v1/accounts', { name: 'Empty Invoice Acct', billingMode: 'consolidated' })
|
||||||
|
const res = await t.api.post('/v1/invoices', {
|
||||||
|
accountId: acct.data.id,
|
||||||
|
issueDate: '2026-04-06',
|
||||||
|
dueDate: '2026-05-06',
|
||||||
|
lineItems: [],
|
||||||
|
})
|
||||||
|
t.assert.status(res, 400)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.test('lists invoices with pagination', { tags: ['invoices', 'list'] }, async () => {
|
||||||
|
const res = await t.api.get('/v1/invoices', { page: 1, limit: 25 })
|
||||||
|
t.assert.status(res, 200)
|
||||||
|
t.assert.ok(res.data.data)
|
||||||
|
t.assert.ok(res.data.pagination)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.test('gets invoice detail with line items', { tags: ['invoices', 'detail'] }, async () => {
|
||||||
|
const acct = await t.api.post('/v1/accounts', { name: 'Detail Invoice Acct', billingMode: 'consolidated' })
|
||||||
|
const inv = await t.api.post('/v1/invoices', {
|
||||||
|
accountId: acct.data.id,
|
||||||
|
issueDate: '2026-04-06',
|
||||||
|
dueDate: '2026-05-06',
|
||||||
|
lineItems: [{ description: 'Widget', qty: 3, unitPrice: 25 }],
|
||||||
|
})
|
||||||
|
|
||||||
|
const res = await t.api.get(`/v1/invoices/${inv.data.id}`)
|
||||||
|
t.assert.status(res, 200)
|
||||||
|
t.assert.ok(res.data.lineItems)
|
||||||
|
t.assert.equal(res.data.lineItems.length, 1)
|
||||||
|
t.assert.ok(res.data.payments)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.test('returns 404 for missing invoice', { tags: ['invoices', 'detail'] }, async () => {
|
||||||
|
const res = await t.api.get('/v1/invoices/00000000-0000-0000-0000-000000000000')
|
||||||
|
t.assert.status(res, 404)
|
||||||
|
})
|
||||||
|
|
||||||
|
// ─── Invoice Workflow ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
t.test('sends a draft invoice', { tags: ['invoices', 'workflow'] }, async () => {
|
||||||
|
const acct = await t.api.post('/v1/accounts', { name: 'Send Invoice Acct', billingMode: 'consolidated' })
|
||||||
|
const inv = await t.api.post('/v1/invoices', {
|
||||||
|
accountId: acct.data.id,
|
||||||
|
issueDate: '2026-04-06',
|
||||||
|
dueDate: '2026-05-06',
|
||||||
|
lineItems: [{ description: 'Send Test', qty: 1, unitPrice: 100 }],
|
||||||
|
})
|
||||||
|
|
||||||
|
const res = await t.api.post(`/v1/invoices/${inv.data.id}/send`)
|
||||||
|
t.assert.status(res, 200)
|
||||||
|
t.assert.equal(res.data.status, 'sent')
|
||||||
|
})
|
||||||
|
|
||||||
|
t.test('applies payment to invoice', { tags: ['invoices', 'payment'] }, async () => {
|
||||||
|
const acct = await t.api.post('/v1/accounts', { name: 'Payment Invoice Acct', billingMode: 'consolidated' })
|
||||||
|
const inv = await t.api.post('/v1/invoices', {
|
||||||
|
accountId: acct.data.id,
|
||||||
|
issueDate: '2026-04-06',
|
||||||
|
dueDate: '2026-05-06',
|
||||||
|
lineItems: [{ description: 'Pay Test', qty: 1, unitPrice: 200 }],
|
||||||
|
})
|
||||||
|
await t.api.post(`/v1/invoices/${inv.data.id}/send`)
|
||||||
|
|
||||||
|
// Partial payment
|
||||||
|
const res1 = await t.api.post(`/v1/invoices/${inv.data.id}/apply-payment`, { amount: 100 })
|
||||||
|
t.assert.status(res1, 200)
|
||||||
|
t.assert.ok(res1.data.id)
|
||||||
|
|
||||||
|
// Check invoice updated
|
||||||
|
const detail = await t.api.get(`/v1/invoices/${inv.data.id}`)
|
||||||
|
t.assert.equal(detail.data.status, 'partial')
|
||||||
|
t.assert.equal(detail.data.amountPaid, '100.00')
|
||||||
|
t.assert.equal(detail.data.balance, '100.00')
|
||||||
|
|
||||||
|
// Full payment
|
||||||
|
const res2 = await t.api.post(`/v1/invoices/${inv.data.id}/apply-payment`, { amount: 100 })
|
||||||
|
t.assert.status(res2, 200)
|
||||||
|
|
||||||
|
const final = await t.api.get(`/v1/invoices/${inv.data.id}`)
|
||||||
|
t.assert.equal(final.data.status, 'paid')
|
||||||
|
t.assert.equal(final.data.balance, '0.00')
|
||||||
|
})
|
||||||
|
|
||||||
|
t.test('rejects overpayment', { tags: ['invoices', 'payment', 'validation'] }, async () => {
|
||||||
|
const acct = await t.api.post('/v1/accounts', { name: 'Overpay Acct', billingMode: 'consolidated' })
|
||||||
|
const inv = await t.api.post('/v1/invoices', {
|
||||||
|
accountId: acct.data.id,
|
||||||
|
issueDate: '2026-04-06',
|
||||||
|
dueDate: '2026-05-06',
|
||||||
|
lineItems: [{ description: 'Small Item', qty: 1, unitPrice: 50 }],
|
||||||
|
})
|
||||||
|
await t.api.post(`/v1/invoices/${inv.data.id}/send`)
|
||||||
|
|
||||||
|
const res = await t.api.post(`/v1/invoices/${inv.data.id}/apply-payment`, { amount: 100 })
|
||||||
|
t.assert.status(res, 400)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.test('voids an invoice', { tags: ['invoices', 'void'] }, async () => {
|
||||||
|
const acct = await t.api.post('/v1/accounts', { name: 'Void Invoice Acct', billingMode: 'consolidated' })
|
||||||
|
const inv = await t.api.post('/v1/invoices', {
|
||||||
|
accountId: acct.data.id,
|
||||||
|
issueDate: '2026-04-06',
|
||||||
|
dueDate: '2026-05-06',
|
||||||
|
lineItems: [{ description: 'Void Test', qty: 1, unitPrice: 75 }],
|
||||||
|
})
|
||||||
|
await t.api.post(`/v1/invoices/${inv.data.id}/send`)
|
||||||
|
|
||||||
|
const res = await t.api.post(`/v1/invoices/${inv.data.id}/void`, { reason: 'Customer changed mind' })
|
||||||
|
t.assert.status(res, 200)
|
||||||
|
t.assert.equal(res.data.status, 'void')
|
||||||
|
t.assert.equal(res.data.balance, '0')
|
||||||
|
})
|
||||||
|
|
||||||
|
t.test('writes off a bad debt', { tags: ['invoices', 'write-off'] }, async () => {
|
||||||
|
const acct = await t.api.post('/v1/accounts', { name: 'WriteOff Acct', billingMode: 'consolidated' })
|
||||||
|
const inv = await t.api.post('/v1/invoices', {
|
||||||
|
accountId: acct.data.id,
|
||||||
|
issueDate: '2026-04-06',
|
||||||
|
dueDate: '2026-05-06',
|
||||||
|
lineItems: [{ description: 'Bad Debt Item', qty: 1, unitPrice: 300 }],
|
||||||
|
})
|
||||||
|
await t.api.post(`/v1/invoices/${inv.data.id}/send`)
|
||||||
|
|
||||||
|
const res = await t.api.post(`/v1/invoices/${inv.data.id}/write-off`, { reason: 'Uncollectable' })
|
||||||
|
t.assert.status(res, 200)
|
||||||
|
t.assert.equal(res.data.status, 'written_off')
|
||||||
|
})
|
||||||
|
|
||||||
|
// ─── Account Balance ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
t.test('tracks account balance on invoice send', { tags: ['balance'] }, async () => {
|
||||||
|
const acct = await t.api.post('/v1/accounts', { name: 'Balance Track Acct', billingMode: 'consolidated' })
|
||||||
|
|
||||||
|
// Create and send invoice (which triggers AR balance update via service)
|
||||||
|
const inv = await t.api.post('/v1/invoices', {
|
||||||
|
accountId: acct.data.id,
|
||||||
|
issueDate: '2026-04-06',
|
||||||
|
dueDate: '2026-05-06',
|
||||||
|
lineItems: [{ description: 'Balance Test', qty: 1, unitPrice: 150 }],
|
||||||
|
})
|
||||||
|
|
||||||
|
const balRes = await t.api.get(`/v1/accounts/${acct.data.id}/balance`)
|
||||||
|
t.assert.status(balRes, 200)
|
||||||
|
t.assert.ok(balRes.data.accountId)
|
||||||
|
})
|
||||||
|
|
||||||
|
// ─── CSV Export ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
t.test('exports invoices as CSV', { tags: ['export'] }, async () => {
|
||||||
|
const res = await t.api.get('/v1/invoices/export')
|
||||||
|
t.assert.status(res, 200)
|
||||||
|
// CSV response should have headers
|
||||||
|
const text = typeof res.data === 'string' ? res.data : JSON.stringify(res.data)
|
||||||
|
t.assert.contains(text, 'Invoice Number')
|
||||||
|
})
|
||||||
|
|
||||||
|
// ─── AR Aging ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
t.test('returns AR aging report', { tags: ['reports'] }, async () => {
|
||||||
|
const res = await t.api.get('/v1/invoices/aging')
|
||||||
|
t.assert.status(res, 200)
|
||||||
|
t.assert.ok(res.data.current !== undefined)
|
||||||
|
t.assert.ok(res.data.days30 !== undefined)
|
||||||
|
t.assert.ok(res.data.days60 !== undefined)
|
||||||
|
t.assert.ok(res.data.days90plus !== undefined)
|
||||||
|
t.assert.ok(res.data.total !== undefined)
|
||||||
|
})
|
||||||
|
|
||||||
|
// ─── Outstanding Accounts ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
t.test('lists outstanding accounts', { tags: ['balance'] }, async () => {
|
||||||
|
const res = await t.api.get('/v1/accounts/outstanding', { page: 1, limit: 25 })
|
||||||
|
t.assert.status(res, 200)
|
||||||
|
t.assert.ok(res.data.data)
|
||||||
|
t.assert.ok(res.data.pagination)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -4,3 +4,4 @@ export * from './schema/accounts.js'
|
|||||||
export * from './schema/inventory.js'
|
export * from './schema/inventory.js'
|
||||||
export * from './schema/pos.js'
|
export * from './schema/pos.js'
|
||||||
export * from './schema/settings.js'
|
export * from './schema/settings.js'
|
||||||
|
export * from './schema/accounting.js'
|
||||||
|
|||||||
189
packages/backend/src/db/migrations/0047_accounting.sql
Normal file
189
packages/backend/src/db/migrations/0047_accounting.sql
Normal file
@@ -0,0 +1,189 @@
|
|||||||
|
-- Accounting module tables
|
||||||
|
|
||||||
|
-- Enums
|
||||||
|
DO $$ BEGIN
|
||||||
|
CREATE TYPE invoice_status AS ENUM ('draft','sent','paid','partial','overdue','void','written_off');
|
||||||
|
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
CREATE TYPE account_type AS ENUM ('asset','liability','revenue','contra_revenue','cogs','expense');
|
||||||
|
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
CREATE TYPE normal_balance AS ENUM ('debit','credit');
|
||||||
|
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
CREATE TYPE journal_line_type AS ENUM ('debit','credit');
|
||||||
|
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
CREATE TYPE billing_run_status AS ENUM ('pending','running','completed','failed');
|
||||||
|
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||||
|
|
||||||
|
-- Core: Invoice
|
||||||
|
CREATE TABLE IF NOT EXISTS "invoice" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
"invoice_number" varchar(50) UNIQUE NOT NULL,
|
||||||
|
"account_id" uuid NOT NULL REFERENCES "account"("id"),
|
||||||
|
"location_id" uuid REFERENCES "location"("id"),
|
||||||
|
"status" invoice_status NOT NULL DEFAULT 'draft',
|
||||||
|
"issue_date" date NOT NULL DEFAULT CURRENT_DATE,
|
||||||
|
"due_date" date NOT NULL DEFAULT CURRENT_DATE,
|
||||||
|
"source_type" varchar(50),
|
||||||
|
"source_id" uuid,
|
||||||
|
"subtotal" numeric(10,2) NOT NULL DEFAULT 0,
|
||||||
|
"discount_total" numeric(10,2) NOT NULL DEFAULT 0,
|
||||||
|
"tax_total" numeric(10,2) NOT NULL DEFAULT 0,
|
||||||
|
"total" numeric(10,2) NOT NULL DEFAULT 0,
|
||||||
|
"amount_paid" numeric(10,2) NOT NULL DEFAULT 0,
|
||||||
|
"balance" numeric(10,2) NOT NULL DEFAULT 0,
|
||||||
|
"refund_of_invoice_id" uuid REFERENCES "invoice"("id"),
|
||||||
|
"notes" text,
|
||||||
|
"created_by" uuid REFERENCES "user"("id"),
|
||||||
|
"created_at" timestamptz NOT NULL DEFAULT now(),
|
||||||
|
"updated_at" timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS "invoice_account_id" ON "invoice" ("account_id");
|
||||||
|
CREATE INDEX IF NOT EXISTS "invoice_status" ON "invoice" ("status");
|
||||||
|
CREATE INDEX IF NOT EXISTS "invoice_source" ON "invoice" ("source_type", "source_id");
|
||||||
|
|
||||||
|
-- Core: Invoice Line Item
|
||||||
|
CREATE TABLE IF NOT EXISTS "invoice_line_item" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
"invoice_id" uuid NOT NULL REFERENCES "invoice"("id") ON DELETE CASCADE,
|
||||||
|
"description" varchar(255) NOT NULL,
|
||||||
|
"qty" integer NOT NULL DEFAULT 1,
|
||||||
|
"unit_price" numeric(10,2) NOT NULL,
|
||||||
|
"discount_amount" numeric(10,2) NOT NULL DEFAULT 0,
|
||||||
|
"tax_rate" numeric(5,4) NOT NULL DEFAULT 0,
|
||||||
|
"tax_amount" numeric(10,2) NOT NULL DEFAULT 0,
|
||||||
|
"line_total" numeric(10,2) NOT NULL DEFAULT 0,
|
||||||
|
"account_code_id" uuid,
|
||||||
|
"source_type" varchar(50),
|
||||||
|
"source_id" uuid,
|
||||||
|
"created_at" timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS "invoice_line_item_invoice_id" ON "invoice_line_item" ("invoice_id");
|
||||||
|
|
||||||
|
-- Core: Payment Application
|
||||||
|
CREATE TABLE IF NOT EXISTS "payment_application" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
"invoice_id" uuid NOT NULL REFERENCES "invoice"("id"),
|
||||||
|
"transaction_id" uuid REFERENCES "transaction"("id"),
|
||||||
|
"amount" numeric(10,2) NOT NULL,
|
||||||
|
"applied_at" timestamptz NOT NULL DEFAULT now(),
|
||||||
|
"applied_by" uuid NOT NULL REFERENCES "user"("id"),
|
||||||
|
"notes" text,
|
||||||
|
"created_at" timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS "payment_application_invoice_id" ON "payment_application" ("invoice_id");
|
||||||
|
|
||||||
|
-- Core: Account Balance (materialized AR)
|
||||||
|
CREATE TABLE IF NOT EXISTS "account_balance" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
"account_id" uuid NOT NULL UNIQUE REFERENCES "account"("id"),
|
||||||
|
"current_balance" numeric(10,2) NOT NULL DEFAULT 0,
|
||||||
|
"last_invoice_date" date,
|
||||||
|
"last_payment_date" date,
|
||||||
|
"updated_at" timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Accounting module: Chart of Accounts
|
||||||
|
CREATE TABLE IF NOT EXISTS "account_code" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
"code" varchar(10) UNIQUE NOT NULL,
|
||||||
|
"name" varchar(255) NOT NULL,
|
||||||
|
"account_type" account_type NOT NULL,
|
||||||
|
"normal_balance" normal_balance NOT NULL,
|
||||||
|
"is_system" boolean NOT NULL DEFAULT true,
|
||||||
|
"is_active" boolean NOT NULL DEFAULT true,
|
||||||
|
"created_at" timestamptz NOT NULL DEFAULT now(),
|
||||||
|
"updated_at" timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Accounting module: Journal Entry
|
||||||
|
CREATE TABLE IF NOT EXISTS "journal_entry" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
"entry_number" varchar(20) UNIQUE NOT NULL,
|
||||||
|
"entry_date" date NOT NULL DEFAULT CURRENT_DATE,
|
||||||
|
"entry_type" varchar(50) NOT NULL,
|
||||||
|
"source_type" varchar(50),
|
||||||
|
"source_id" uuid,
|
||||||
|
"description" text NOT NULL,
|
||||||
|
"total_debits" numeric(10,2) NOT NULL,
|
||||||
|
"total_credits" numeric(10,2) NOT NULL,
|
||||||
|
"is_void" boolean NOT NULL DEFAULT false,
|
||||||
|
"void_reason" text,
|
||||||
|
"voided_by" uuid REFERENCES "user"("id"),
|
||||||
|
"voided_at" timestamptz,
|
||||||
|
"reversal_of_id" uuid REFERENCES "journal_entry"("id"),
|
||||||
|
"created_by" uuid NOT NULL REFERENCES "user"("id"),
|
||||||
|
"created_at" timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS "journal_entry_date" ON "journal_entry" ("entry_date");
|
||||||
|
CREATE INDEX IF NOT EXISTS "journal_entry_type" ON "journal_entry" ("entry_type");
|
||||||
|
|
||||||
|
-- Accounting module: Journal Entry Line
|
||||||
|
CREATE TABLE IF NOT EXISTS "journal_entry_line" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
"journal_entry_id" uuid NOT NULL REFERENCES "journal_entry"("id") ON DELETE CASCADE,
|
||||||
|
"account_code_id" uuid NOT NULL REFERENCES "account_code"("id"),
|
||||||
|
"line_type" journal_line_type NOT NULL,
|
||||||
|
"amount" numeric(10,2) NOT NULL,
|
||||||
|
"description" text,
|
||||||
|
"entity_type" varchar(50),
|
||||||
|
"entity_id" uuid,
|
||||||
|
"created_at" timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS "journal_entry_line_entry_id" ON "journal_entry_line" ("journal_entry_id");
|
||||||
|
CREATE INDEX IF NOT EXISTS "journal_entry_line_account" ON "journal_entry_line" ("account_code_id");
|
||||||
|
|
||||||
|
-- Lessons module: Billing Run
|
||||||
|
CREATE TABLE IF NOT EXISTS "billing_run" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
"run_date" date NOT NULL,
|
||||||
|
"status" billing_run_status NOT NULL DEFAULT 'pending',
|
||||||
|
"enrollments_processed" integer NOT NULL DEFAULT 0,
|
||||||
|
"invoices_generated" integer NOT NULL DEFAULT 0,
|
||||||
|
"total_amount" numeric(10,2) NOT NULL DEFAULT 0,
|
||||||
|
"errors" jsonb,
|
||||||
|
"started_at" timestamptz,
|
||||||
|
"completed_at" timestamptz,
|
||||||
|
"created_by" uuid REFERENCES "user"("id"),
|
||||||
|
"created_at" timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Add nextBillingDate to enrollment
|
||||||
|
ALTER TABLE "enrollment" ADD COLUMN IF NOT EXISTS "next_billing_date" date;
|
||||||
|
|
||||||
|
-- Add accounting to module_config
|
||||||
|
INSERT INTO "module_config" ("slug", "name", "description", "licensed", "enabled")
|
||||||
|
VALUES ('accounting', 'Accounting', 'Chart of accounts, journal entries, and financial reports', true, false)
|
||||||
|
ON CONFLICT ("slug") DO NOTHING;
|
||||||
|
|
||||||
|
-- Seed chart of accounts
|
||||||
|
INSERT INTO "account_code" ("code", "name", "account_type", "normal_balance", "is_system") VALUES
|
||||||
|
('1000', 'Cash - Register Drawer', 'asset', 'debit', true),
|
||||||
|
('1100', 'Accounts Receivable', 'asset', 'debit', true),
|
||||||
|
('1200', 'Payment Clearing', 'asset', 'debit', true),
|
||||||
|
('1300', 'Inventory - Sale Stock', 'asset', 'debit', true),
|
||||||
|
('1320', 'Inventory - Parts & Supplies', 'asset', 'debit', true),
|
||||||
|
('2000', 'Sales Tax Payable', 'liability', 'credit', true),
|
||||||
|
('2110', 'Deferred Revenue - Lessons', 'liability', 'credit', true),
|
||||||
|
('4000', 'Sales Revenue', 'revenue', 'credit', true),
|
||||||
|
('4200', 'Lesson Revenue', 'revenue', 'credit', true),
|
||||||
|
('4300', 'Repair Revenue - Labor', 'revenue', 'credit', true),
|
||||||
|
('4310', 'Repair Revenue - Parts', 'revenue', 'credit', true),
|
||||||
|
('4900', 'Sales Discounts', 'contra_revenue', 'debit', true),
|
||||||
|
('4910', 'Sales Returns & Refunds', 'contra_revenue', 'debit', true),
|
||||||
|
('5000', 'Cost of Goods Sold', 'cogs', 'debit', true),
|
||||||
|
('5100', 'Repair Parts Cost', 'cogs', 'debit', true),
|
||||||
|
('6000', 'Cash Over / Short', 'expense', 'debit', true),
|
||||||
|
('6200', 'Bad Debt Expense', 'expense', 'debit', true)
|
||||||
|
ON CONFLICT ("code") DO NOTHING;
|
||||||
@@ -330,6 +330,13 @@
|
|||||||
"when": 1775860000000,
|
"when": 1775860000000,
|
||||||
"tag": "0046_auto-employee-number",
|
"tag": "0046_auto-employee-number",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 47,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1775950000000,
|
||||||
|
"tag": "0047_accounting",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
147
packages/backend/src/db/schema/accounting.ts
Normal file
147
packages/backend/src/db/schema/accounting.ts
Normal file
@@ -0,0 +1,147 @@
|
|||||||
|
import { pgTable, uuid, varchar, text, numeric, integer, boolean, date, timestamp, jsonb, pgEnum } from 'drizzle-orm/pg-core'
|
||||||
|
import { accounts } from './accounts.js'
|
||||||
|
import { locations } from './stores.js'
|
||||||
|
import { users } from './users.js'
|
||||||
|
import { transactions } from './pos.js'
|
||||||
|
|
||||||
|
// Enums
|
||||||
|
export const invoiceStatusEnum = pgEnum('invoice_status', ['draft', 'sent', 'paid', 'partial', 'overdue', 'void', 'written_off'])
|
||||||
|
export const accountTypeEnum = pgEnum('account_type', ['asset', 'liability', 'revenue', 'contra_revenue', 'cogs', 'expense'])
|
||||||
|
export const normalBalanceEnum = pgEnum('normal_balance', ['debit', 'credit'])
|
||||||
|
export const journalLineTypeEnum = pgEnum('journal_line_type', ['debit', 'credit'])
|
||||||
|
export const billingRunStatusEnum = pgEnum('billing_run_status', ['pending', 'running', 'completed', 'failed'])
|
||||||
|
|
||||||
|
// Core: Invoice
|
||||||
|
export const invoices = pgTable('invoice', {
|
||||||
|
id: uuid('id').primaryKey().defaultRandom(),
|
||||||
|
invoiceNumber: varchar('invoice_number', { length: 50 }).notNull().unique(),
|
||||||
|
accountId: uuid('account_id').notNull().references(() => accounts.id),
|
||||||
|
locationId: uuid('location_id').references(() => locations.id),
|
||||||
|
status: invoiceStatusEnum('status').notNull().default('draft'),
|
||||||
|
issueDate: date('issue_date').notNull().defaultNow(),
|
||||||
|
dueDate: date('due_date').notNull().defaultNow(),
|
||||||
|
sourceType: varchar('source_type', { length: 50 }),
|
||||||
|
sourceId: uuid('source_id'),
|
||||||
|
subtotal: numeric('subtotal', { precision: 10, scale: 2 }).notNull().default('0'),
|
||||||
|
discountTotal: numeric('discount_total', { precision: 10, scale: 2 }).notNull().default('0'),
|
||||||
|
taxTotal: numeric('tax_total', { precision: 10, scale: 2 }).notNull().default('0'),
|
||||||
|
total: numeric('total', { precision: 10, scale: 2 }).notNull().default('0'),
|
||||||
|
amountPaid: numeric('amount_paid', { precision: 10, scale: 2 }).notNull().default('0'),
|
||||||
|
balance: numeric('balance', { precision: 10, scale: 2 }).notNull().default('0'),
|
||||||
|
refundOfInvoiceId: uuid('refund_of_invoice_id'),
|
||||||
|
notes: text('notes'),
|
||||||
|
createdBy: uuid('created_by').references(() => users.id),
|
||||||
|
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
})
|
||||||
|
|
||||||
|
// Core: Invoice Line Item
|
||||||
|
export const invoiceLineItems = pgTable('invoice_line_item', {
|
||||||
|
id: uuid('id').primaryKey().defaultRandom(),
|
||||||
|
invoiceId: uuid('invoice_id').notNull().references(() => invoices.id, { onDelete: 'cascade' }),
|
||||||
|
description: varchar('description', { length: 255 }).notNull(),
|
||||||
|
qty: integer('qty').notNull().default(1),
|
||||||
|
unitPrice: numeric('unit_price', { precision: 10, scale: 2 }).notNull(),
|
||||||
|
discountAmount: numeric('discount_amount', { precision: 10, scale: 2 }).notNull().default('0'),
|
||||||
|
taxRate: numeric('tax_rate', { precision: 5, scale: 4 }).notNull().default('0'),
|
||||||
|
taxAmount: numeric('tax_amount', { precision: 10, scale: 2 }).notNull().default('0'),
|
||||||
|
lineTotal: numeric('line_total', { precision: 10, scale: 2 }).notNull().default('0'),
|
||||||
|
accountCodeId: uuid('account_code_id'),
|
||||||
|
sourceType: varchar('source_type', { length: 50 }),
|
||||||
|
sourceId: uuid('source_id'),
|
||||||
|
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
})
|
||||||
|
|
||||||
|
// Core: Payment Application
|
||||||
|
export const paymentApplications = pgTable('payment_application', {
|
||||||
|
id: uuid('id').primaryKey().defaultRandom(),
|
||||||
|
invoiceId: uuid('invoice_id').notNull().references(() => invoices.id),
|
||||||
|
transactionId: uuid('transaction_id').references(() => transactions.id),
|
||||||
|
amount: numeric('amount', { precision: 10, scale: 2 }).notNull(),
|
||||||
|
appliedAt: timestamp('applied_at', { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
appliedBy: uuid('applied_by').notNull().references(() => users.id),
|
||||||
|
notes: text('notes'),
|
||||||
|
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
})
|
||||||
|
|
||||||
|
// Core: Account Balance (materialized AR)
|
||||||
|
export const accountBalances = pgTable('account_balance', {
|
||||||
|
id: uuid('id').primaryKey().defaultRandom(),
|
||||||
|
accountId: uuid('account_id').notNull().unique().references(() => accounts.id),
|
||||||
|
currentBalance: numeric('current_balance', { precision: 10, scale: 2 }).notNull().default('0'),
|
||||||
|
lastInvoiceDate: date('last_invoice_date'),
|
||||||
|
lastPaymentDate: date('last_payment_date'),
|
||||||
|
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
})
|
||||||
|
|
||||||
|
// Accounting module: Chart of Accounts
|
||||||
|
export const accountCodes = pgTable('account_code', {
|
||||||
|
id: uuid('id').primaryKey().defaultRandom(),
|
||||||
|
code: varchar('code', { length: 10 }).notNull().unique(),
|
||||||
|
name: varchar('name', { length: 255 }).notNull(),
|
||||||
|
accountType: accountTypeEnum('account_type').notNull(),
|
||||||
|
normalBalance: normalBalanceEnum('normal_balance').notNull(),
|
||||||
|
isSystem: boolean('is_system').notNull().default(true),
|
||||||
|
isActive: boolean('is_active').notNull().default(true),
|
||||||
|
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
})
|
||||||
|
|
||||||
|
// Accounting module: Journal Entry
|
||||||
|
export const journalEntries = pgTable('journal_entry', {
|
||||||
|
id: uuid('id').primaryKey().defaultRandom(),
|
||||||
|
entryNumber: varchar('entry_number', { length: 20 }).notNull().unique(),
|
||||||
|
entryDate: date('entry_date').notNull().defaultNow(),
|
||||||
|
entryType: varchar('entry_type', { length: 50 }).notNull(),
|
||||||
|
sourceType: varchar('source_type', { length: 50 }),
|
||||||
|
sourceId: uuid('source_id'),
|
||||||
|
description: text('description').notNull(),
|
||||||
|
totalDebits: numeric('total_debits', { precision: 10, scale: 2 }).notNull(),
|
||||||
|
totalCredits: numeric('total_credits', { precision: 10, scale: 2 }).notNull(),
|
||||||
|
isVoid: boolean('is_void').notNull().default(false),
|
||||||
|
voidReason: text('void_reason'),
|
||||||
|
voidedBy: uuid('voided_by').references(() => users.id),
|
||||||
|
voidedAt: timestamp('voided_at', { withTimezone: true }),
|
||||||
|
reversalOfId: uuid('reversal_of_id'),
|
||||||
|
createdBy: uuid('created_by').notNull().references(() => users.id),
|
||||||
|
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
})
|
||||||
|
|
||||||
|
// Accounting module: Journal Entry Line
|
||||||
|
export const journalEntryLines = pgTable('journal_entry_line', {
|
||||||
|
id: uuid('id').primaryKey().defaultRandom(),
|
||||||
|
journalEntryId: uuid('journal_entry_id').notNull().references(() => journalEntries.id, { onDelete: 'cascade' }),
|
||||||
|
accountCodeId: uuid('account_code_id').notNull().references(() => accountCodes.id),
|
||||||
|
lineType: journalLineTypeEnum('line_type').notNull(),
|
||||||
|
amount: numeric('amount', { precision: 10, scale: 2 }).notNull(),
|
||||||
|
description: text('description'),
|
||||||
|
entityType: varchar('entity_type', { length: 50 }),
|
||||||
|
entityId: uuid('entity_id'),
|
||||||
|
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
})
|
||||||
|
|
||||||
|
// Lessons module: Billing Run
|
||||||
|
export const billingRuns = pgTable('billing_run', {
|
||||||
|
id: uuid('id').primaryKey().defaultRandom(),
|
||||||
|
runDate: date('run_date').notNull(),
|
||||||
|
status: billingRunStatusEnum('status').notNull().default('pending'),
|
||||||
|
enrollmentsProcessed: integer('enrollments_processed').notNull().default(0),
|
||||||
|
invoicesGenerated: integer('invoices_generated').notNull().default(0),
|
||||||
|
totalAmount: numeric('total_amount', { precision: 10, scale: 2 }).notNull().default('0'),
|
||||||
|
errors: jsonb('errors'),
|
||||||
|
startedAt: timestamp('started_at', { withTimezone: true }),
|
||||||
|
completedAt: timestamp('completed_at', { withTimezone: true }),
|
||||||
|
createdBy: uuid('created_by').references(() => users.id),
|
||||||
|
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
})
|
||||||
|
|
||||||
|
// Type exports
|
||||||
|
export type Invoice = typeof invoices.$inferSelect
|
||||||
|
export type InvoiceInsert = typeof invoices.$inferInsert
|
||||||
|
export type InvoiceLineItem = typeof invoiceLineItems.$inferSelect
|
||||||
|
export type PaymentApplication = typeof paymentApplications.$inferSelect
|
||||||
|
export type AccountBalance = typeof accountBalances.$inferSelect
|
||||||
|
export type AccountCode = typeof accountCodes.$inferSelect
|
||||||
|
export type JournalEntry = typeof journalEntries.$inferSelect
|
||||||
|
export type JournalEntryLine = typeof journalEntryLines.$inferSelect
|
||||||
|
export type BillingRun = typeof billingRuns.$inferSelect
|
||||||
@@ -33,6 +33,7 @@ import { vaultRoutes } from './routes/v1/vault.js'
|
|||||||
import { webdavRoutes } from './routes/webdav/index.js'
|
import { webdavRoutes } from './routes/webdav/index.js'
|
||||||
import { moduleRoutes } from './routes/v1/modules.js'
|
import { moduleRoutes } from './routes/v1/modules.js'
|
||||||
import { configRoutes } from './routes/v1/config.js'
|
import { configRoutes } from './routes/v1/config.js'
|
||||||
|
import { invoiceRoutes } from './routes/v1/invoices.js'
|
||||||
import { RbacService } from './services/rbac.service.js'
|
import { RbacService } from './services/rbac.service.js'
|
||||||
import { ModuleService } from './services/module.service.js'
|
import { ModuleService } from './services/module.service.js'
|
||||||
import { AppConfigService } from './services/config.service.js'
|
import { AppConfigService } from './services/config.service.js'
|
||||||
@@ -202,6 +203,7 @@ export async function buildApp() {
|
|||||||
await app.register(storeRoutes, { prefix: '/v1' })
|
await app.register(storeRoutes, { prefix: '/v1' })
|
||||||
await app.register(moduleRoutes, { prefix: '/v1' })
|
await app.register(moduleRoutes, { prefix: '/v1' })
|
||||||
await app.register(configRoutes, { prefix: '/v1' })
|
await app.register(configRoutes, { prefix: '/v1' })
|
||||||
|
await app.register(invoiceRoutes, { prefix: '/v1' })
|
||||||
await app.register(lookupRoutes, { prefix: '/v1' })
|
await app.register(lookupRoutes, { prefix: '/v1' })
|
||||||
|
|
||||||
// Module-gated routes
|
// Module-gated routes
|
||||||
|
|||||||
130
packages/backend/src/routes/v1/invoices.ts
Normal file
130
packages/backend/src/routes/v1/invoices.ts
Normal file
@@ -0,0 +1,130 @@
|
|||||||
|
import type { FastifyPluginAsync } from 'fastify'
|
||||||
|
import {
|
||||||
|
PaginationSchema,
|
||||||
|
InvoiceCreateSchema,
|
||||||
|
PaymentApplicationSchema,
|
||||||
|
InvoiceVoidSchema,
|
||||||
|
InvoiceWriteOffSchema,
|
||||||
|
} from '@lunarfront/shared/schemas'
|
||||||
|
import { InvoiceService } from '../../services/invoice.service.js'
|
||||||
|
import { AccountBalanceService } from '../../services/account-balance.service.js'
|
||||||
|
|
||||||
|
export const invoiceRoutes: FastifyPluginAsync = async (app) => {
|
||||||
|
// --- Invoices ---
|
||||||
|
|
||||||
|
app.get('/invoices', { preHandler: [app.authenticate, app.requirePermission('accounting.view')] }, async (request, reply) => {
|
||||||
|
const query = request.query as Record<string, string | undefined>
|
||||||
|
const params = PaginationSchema.parse(query)
|
||||||
|
const filters = {
|
||||||
|
accountId: query.accountId,
|
||||||
|
status: query.status,
|
||||||
|
dateFrom: query.dateFrom,
|
||||||
|
dateTo: query.dateTo,
|
||||||
|
}
|
||||||
|
const result = await InvoiceService.list(app.db, params, filters)
|
||||||
|
return reply.send(result)
|
||||||
|
})
|
||||||
|
|
||||||
|
app.get('/invoices/:id', { preHandler: [app.authenticate, app.requirePermission('accounting.view')] }, async (request, reply) => {
|
||||||
|
const { id } = request.params as { id: string }
|
||||||
|
const invoice = await InvoiceService.getById(app.db, id)
|
||||||
|
if (!invoice) return reply.status(404).send({ error: { message: 'Invoice not found', statusCode: 404 } })
|
||||||
|
return reply.send(invoice)
|
||||||
|
})
|
||||||
|
|
||||||
|
app.post('/invoices', { preHandler: [app.authenticate, app.requirePermission('accounting.edit')] }, async (request, reply) => {
|
||||||
|
const parsed = InvoiceCreateSchema.safeParse(request.body)
|
||||||
|
if (!parsed.success) {
|
||||||
|
return reply.status(400).send({ error: { message: 'Validation failed', details: parsed.error.flatten(), statusCode: 400 } })
|
||||||
|
}
|
||||||
|
const invoice = await InvoiceService.create(app.db, parsed.data, request.user.id)
|
||||||
|
request.log.info({ invoiceId: invoice.id, invoiceNumber: invoice.invoiceNumber }, 'Invoice created')
|
||||||
|
return reply.status(201).send(invoice)
|
||||||
|
})
|
||||||
|
|
||||||
|
app.post('/invoices/:id/send', { preHandler: [app.authenticate, app.requirePermission('accounting.edit')] }, async (request, reply) => {
|
||||||
|
const { id } = request.params as { id: string }
|
||||||
|
const invoice = await InvoiceService.send(app.db, id)
|
||||||
|
request.log.info({ invoiceId: id }, 'Invoice sent')
|
||||||
|
return reply.send(invoice)
|
||||||
|
})
|
||||||
|
|
||||||
|
app.post('/invoices/:id/apply-payment', { preHandler: [app.authenticate, app.requirePermission('accounting.edit')] }, async (request, reply) => {
|
||||||
|
const { id } = request.params as { id: string }
|
||||||
|
const parsed = PaymentApplicationSchema.safeParse(request.body)
|
||||||
|
if (!parsed.success) {
|
||||||
|
return reply.status(400).send({ error: { message: 'Validation failed', details: parsed.error.flatten(), statusCode: 400 } })
|
||||||
|
}
|
||||||
|
const application = await InvoiceService.applyPayment(app.db, id, parsed.data, request.user.id)
|
||||||
|
request.log.info({ invoiceId: id, amount: parsed.data.amount }, 'Payment applied')
|
||||||
|
return reply.send(application)
|
||||||
|
})
|
||||||
|
|
||||||
|
app.post('/invoices/:id/void', { preHandler: [app.authenticate, app.requirePermission('accounting.admin')] }, async (request, reply) => {
|
||||||
|
const { id } = request.params as { id: string }
|
||||||
|
const parsed = InvoiceVoidSchema.safeParse(request.body)
|
||||||
|
if (!parsed.success) {
|
||||||
|
return reply.status(400).send({ error: { message: 'Validation failed', details: parsed.error.flatten(), statusCode: 400 } })
|
||||||
|
}
|
||||||
|
const invoice = await InvoiceService.void(app.db, id, parsed.data.reason, request.user.id)
|
||||||
|
request.log.info({ invoiceId: id, reason: parsed.data.reason }, 'Invoice voided')
|
||||||
|
return reply.send(invoice)
|
||||||
|
})
|
||||||
|
|
||||||
|
app.post('/invoices/:id/write-off', { preHandler: [app.authenticate, app.requirePermission('accounting.admin')] }, async (request, reply) => {
|
||||||
|
const { id } = request.params as { id: string }
|
||||||
|
const parsed = InvoiceWriteOffSchema.safeParse(request.body)
|
||||||
|
if (!parsed.success) {
|
||||||
|
return reply.status(400).send({ error: { message: 'Validation failed', details: parsed.error.flatten(), statusCode: 400 } })
|
||||||
|
}
|
||||||
|
const invoice = await InvoiceService.writeOff(app.db, id, parsed.data.reason, request.user.id)
|
||||||
|
request.log.info({ invoiceId: id, reason: parsed.data.reason }, 'Invoice written off')
|
||||||
|
return reply.send(invoice)
|
||||||
|
})
|
||||||
|
|
||||||
|
// --- Account Invoices & Balance ---
|
||||||
|
|
||||||
|
app.get('/accounts/:id/invoices', { preHandler: [app.authenticate, app.requirePermission('accounting.view')] }, async (request, reply) => {
|
||||||
|
const { id } = request.params as { id: string }
|
||||||
|
const query = request.query as Record<string, string | undefined>
|
||||||
|
const params = PaginationSchema.parse(query)
|
||||||
|
const result = await InvoiceService.listByAccount(app.db, id, params)
|
||||||
|
return reply.send(result)
|
||||||
|
})
|
||||||
|
|
||||||
|
app.get('/accounts/:id/balance', { preHandler: [app.authenticate, app.requirePermission('accounting.view')] }, async (request, reply) => {
|
||||||
|
const { id } = request.params as { id: string }
|
||||||
|
const balance = await AccountBalanceService.getBalance(app.db, id)
|
||||||
|
return reply.send(balance)
|
||||||
|
})
|
||||||
|
|
||||||
|
// --- Export ---
|
||||||
|
|
||||||
|
app.get('/invoices/export', { preHandler: [app.authenticate, app.requirePermission('accounting.view')] }, async (request, reply) => {
|
||||||
|
const query = request.query as Record<string, string | undefined>
|
||||||
|
const csv = await InvoiceService.exportCSV(app.db, {
|
||||||
|
dateFrom: query.dateFrom,
|
||||||
|
dateTo: query.dateTo,
|
||||||
|
})
|
||||||
|
return reply
|
||||||
|
.header('Content-Type', 'text/csv')
|
||||||
|
.header('Content-Disposition', `attachment; filename="invoices-${new Date().toISOString().slice(0, 10)}.csv"`)
|
||||||
|
.send(csv)
|
||||||
|
})
|
||||||
|
|
||||||
|
// --- AR Aging ---
|
||||||
|
|
||||||
|
app.get('/invoices/aging', { preHandler: [app.authenticate, app.requirePermission('accounting.view')] }, async (request, reply) => {
|
||||||
|
const report = await InvoiceService.getAgingReport(app.db)
|
||||||
|
return reply.send(report)
|
||||||
|
})
|
||||||
|
|
||||||
|
// --- Outstanding Accounts ---
|
||||||
|
|
||||||
|
app.get('/accounts/outstanding', { preHandler: [app.authenticate, app.requirePermission('accounting.view')] }, async (request, reply) => {
|
||||||
|
const query = request.query as Record<string, string | undefined>
|
||||||
|
const params = PaginationSchema.parse(query)
|
||||||
|
const result = await AccountBalanceService.getOutstandingAccounts(app.db, params)
|
||||||
|
return reply.send(result)
|
||||||
|
})
|
||||||
|
}
|
||||||
93
packages/backend/src/services/account-balance.service.ts
Normal file
93
packages/backend/src/services/account-balance.service.ts
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
import { eq, desc, gt, count } from 'drizzle-orm'
|
||||||
|
import type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'
|
||||||
|
import { accountBalances } from '../db/schema/accounting.js'
|
||||||
|
import { accounts } from '../db/schema/accounts.js'
|
||||||
|
import type { PaginationInput } from '@lunarfront/shared/schemas'
|
||||||
|
|
||||||
|
export const AccountBalanceService = {
|
||||||
|
async getBalance(db: PostgresJsDatabase<any>, accountId: string) {
|
||||||
|
const [existing] = await db.select().from(accountBalances).where(eq(accountBalances.accountId, accountId)).limit(1)
|
||||||
|
if (existing) return existing
|
||||||
|
|
||||||
|
// Create balance record if it doesn't exist
|
||||||
|
const [created] = await db.insert(accountBalances).values({ accountId }).returning()
|
||||||
|
return created
|
||||||
|
},
|
||||||
|
|
||||||
|
async adjustBalance(
|
||||||
|
db: PostgresJsDatabase<any>,
|
||||||
|
accountId: string,
|
||||||
|
adjustment: number,
|
||||||
|
reason: 'invoice' | 'payment' | 'void' | 'write_off',
|
||||||
|
) {
|
||||||
|
const balance = await this.getBalance(db, accountId)
|
||||||
|
const newBalance = parseFloat(balance.currentBalance) + adjustment
|
||||||
|
|
||||||
|
const updates: Record<string, unknown> = {
|
||||||
|
currentBalance: newBalance.toFixed(2),
|
||||||
|
updatedAt: new Date(),
|
||||||
|
}
|
||||||
|
|
||||||
|
if (reason === 'invoice' && adjustment > 0) {
|
||||||
|
updates.lastInvoiceDate = new Date().toISOString().slice(0, 10)
|
||||||
|
}
|
||||||
|
if (reason === 'payment' && adjustment < 0) {
|
||||||
|
updates.lastPaymentDate = new Date().toISOString().slice(0, 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
await db.update(accountBalances).set(updates).where(eq(accountBalances.accountId, accountId))
|
||||||
|
},
|
||||||
|
|
||||||
|
async getOutstandingAccounts(db: PostgresJsDatabase<any>, params: PaginationInput) {
|
||||||
|
const where = gt(accountBalances.currentBalance, '0')
|
||||||
|
const offset = ((params.page ?? 1) - 1) * (params.limit ?? 25)
|
||||||
|
|
||||||
|
const [data, [{ total }]] = await Promise.all([
|
||||||
|
db.select({
|
||||||
|
accountId: accountBalances.accountId,
|
||||||
|
currentBalance: accountBalances.currentBalance,
|
||||||
|
lastInvoiceDate: accountBalances.lastInvoiceDate,
|
||||||
|
lastPaymentDate: accountBalances.lastPaymentDate,
|
||||||
|
accountName: accounts.name,
|
||||||
|
accountEmail: accounts.email,
|
||||||
|
})
|
||||||
|
.from(accountBalances)
|
||||||
|
.innerJoin(accounts, eq(accountBalances.accountId, accounts.id))
|
||||||
|
.where(where)
|
||||||
|
.orderBy(desc(accountBalances.currentBalance))
|
||||||
|
.limit(params.limit ?? 25)
|
||||||
|
.offset(offset),
|
||||||
|
db.select({ total: count() })
|
||||||
|
.from(accountBalances)
|
||||||
|
.where(where),
|
||||||
|
])
|
||||||
|
|
||||||
|
return {
|
||||||
|
data,
|
||||||
|
pagination: {
|
||||||
|
page: params.page ?? 1,
|
||||||
|
limit: params.limit ?? 25,
|
||||||
|
total,
|
||||||
|
totalPages: Math.ceil(total / (params.limit ?? 25)),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async recalculateFromInvoices(db: PostgresJsDatabase<any>, accountId: string) {
|
||||||
|
// Safety valve: recalculate balance from all invoices
|
||||||
|
const { invoices } = await import('../db/schema/accounting.js')
|
||||||
|
const rows = await db
|
||||||
|
.select({ balance: invoices.balance, status: invoices.status })
|
||||||
|
.from(invoices)
|
||||||
|
.where(eq(invoices.accountId, accountId))
|
||||||
|
|
||||||
|
const totalOutstanding = rows
|
||||||
|
.filter(r => ['sent', 'partial', 'overdue'].includes(r.status))
|
||||||
|
.reduce((sum, r) => sum + parseFloat(r.balance), 0)
|
||||||
|
|
||||||
|
await db.update(accountBalances).set({
|
||||||
|
currentBalance: totalOutstanding.toFixed(2),
|
||||||
|
updatedAt: new Date(),
|
||||||
|
}).where(eq(accountBalances.accountId, accountId))
|
||||||
|
},
|
||||||
|
}
|
||||||
499
packages/backend/src/services/invoice.service.ts
Normal file
499
packages/backend/src/services/invoice.service.ts
Normal file
@@ -0,0 +1,499 @@
|
|||||||
|
import { eq, and, count, sql, type Column, lte, inArray } from 'drizzle-orm'
|
||||||
|
import type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'
|
||||||
|
import { invoices, invoiceLineItems, paymentApplications } from '../db/schema/accounting.js'
|
||||||
|
import { transactions, transactionLineItems } from '../db/schema/pos.js'
|
||||||
|
import { repairTickets, repairLineItems } from '../db/schema/repairs.js'
|
||||||
|
import { accounts } from '../db/schema/accounts.js'
|
||||||
|
import { NotFoundError, ValidationError } from '../lib/errors.js'
|
||||||
|
import { AccountBalanceService } from './account-balance.service.js'
|
||||||
|
import type { InvoiceCreateInput, PaginationInput } from '@lunarfront/shared/schemas'
|
||||||
|
import { buildSearchCondition } from '../utils/pagination.js'
|
||||||
|
|
||||||
|
function generateInvoiceNumber(): string {
|
||||||
|
const date = new Date()
|
||||||
|
const dateStr = date.toISOString().slice(0, 10).replace(/-/g, '')
|
||||||
|
const seq = String(Math.floor(Math.random() * 9999) + 1).padStart(4, '0')
|
||||||
|
return `INV-${dateStr}-${seq}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export const InvoiceService = {
|
||||||
|
async create(db: PostgresJsDatabase<any>, input: InvoiceCreateInput, createdBy: string) {
|
||||||
|
const invoiceNumber = generateInvoiceNumber()
|
||||||
|
|
||||||
|
// Calculate totals from line items
|
||||||
|
let subtotal = 0
|
||||||
|
let discountTotal = 0
|
||||||
|
let taxTotal = 0
|
||||||
|
|
||||||
|
const lineItemValues = input.lineItems.map((item) => {
|
||||||
|
const lineSubtotal = item.qty * item.unitPrice
|
||||||
|
const lineDiscount = item.discountAmount ?? 0
|
||||||
|
const lineTaxable = lineSubtotal - lineDiscount
|
||||||
|
const lineTax = parseFloat((lineTaxable * (item.taxRate ?? 0)).toFixed(2))
|
||||||
|
const lineTotal = parseFloat((lineTaxable + lineTax).toFixed(2))
|
||||||
|
|
||||||
|
subtotal += lineSubtotal
|
||||||
|
discountTotal += lineDiscount
|
||||||
|
taxTotal += lineTax
|
||||||
|
|
||||||
|
return {
|
||||||
|
description: item.description,
|
||||||
|
qty: item.qty,
|
||||||
|
unitPrice: item.unitPrice.toFixed(2),
|
||||||
|
discountAmount: lineDiscount.toFixed(2),
|
||||||
|
taxRate: (item.taxRate ?? 0).toFixed(4),
|
||||||
|
taxAmount: lineTax.toFixed(2),
|
||||||
|
lineTotal: lineTotal.toFixed(2),
|
||||||
|
accountCodeId: item.accountCodeId ?? null,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const total = parseFloat((subtotal - discountTotal + taxTotal).toFixed(2))
|
||||||
|
|
||||||
|
const [invoice] = await db.insert(invoices).values({
|
||||||
|
invoiceNumber,
|
||||||
|
accountId: input.accountId,
|
||||||
|
locationId: input.locationId ?? null,
|
||||||
|
status: 'draft',
|
||||||
|
issueDate: input.issueDate,
|
||||||
|
dueDate: input.dueDate,
|
||||||
|
subtotal: subtotal.toFixed(2),
|
||||||
|
discountTotal: discountTotal.toFixed(2),
|
||||||
|
taxTotal: taxTotal.toFixed(2),
|
||||||
|
total: total.toFixed(2),
|
||||||
|
balance: total.toFixed(2),
|
||||||
|
notes: input.notes ?? null,
|
||||||
|
createdBy,
|
||||||
|
}).returning()
|
||||||
|
|
||||||
|
// Insert line items
|
||||||
|
for (const item of lineItemValues) {
|
||||||
|
await db.insert(invoiceLineItems).values({
|
||||||
|
invoiceId: invoice.id,
|
||||||
|
...item,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return invoice
|
||||||
|
},
|
||||||
|
|
||||||
|
async createFromTransaction(db: PostgresJsDatabase<any>, transactionId: string, createdBy: string) {
|
||||||
|
const [txn] = await db.select().from(transactions).where(eq(transactions.id, transactionId)).limit(1)
|
||||||
|
if (!txn) throw new NotFoundError('Transaction')
|
||||||
|
if (!txn.accountId) throw new ValidationError('Transaction must be linked to an account for invoicing')
|
||||||
|
|
||||||
|
const lineItems = await db.select().from(transactionLineItems).where(eq(transactionLineItems.transactionId, transactionId))
|
||||||
|
|
||||||
|
const invoiceNumber = generateInvoiceNumber()
|
||||||
|
const isPaid = txn.paymentMethod !== 'account_charge'
|
||||||
|
const today = new Date().toISOString().slice(0, 10)
|
||||||
|
|
||||||
|
const [invoice] = await db.insert(invoices).values({
|
||||||
|
invoiceNumber,
|
||||||
|
accountId: txn.accountId,
|
||||||
|
locationId: txn.locationId ?? null,
|
||||||
|
status: isPaid ? 'paid' : 'sent',
|
||||||
|
issueDate: today,
|
||||||
|
dueDate: today, // Immediate for POS, could add net-30 logic later
|
||||||
|
sourceType: 'transaction',
|
||||||
|
sourceId: transactionId,
|
||||||
|
subtotal: txn.subtotal,
|
||||||
|
discountTotal: txn.discountTotal,
|
||||||
|
taxTotal: txn.taxTotal,
|
||||||
|
total: txn.total,
|
||||||
|
amountPaid: isPaid ? txn.total : '0',
|
||||||
|
balance: isPaid ? '0' : txn.total,
|
||||||
|
createdBy,
|
||||||
|
}).returning()
|
||||||
|
|
||||||
|
// Copy line items
|
||||||
|
for (const item of lineItems) {
|
||||||
|
await db.insert(invoiceLineItems).values({
|
||||||
|
invoiceId: invoice.id,
|
||||||
|
description: item.description,
|
||||||
|
qty: item.qty,
|
||||||
|
unitPrice: item.unitPrice,
|
||||||
|
discountAmount: item.discountAmount ?? '0',
|
||||||
|
taxRate: item.taxRate ?? '0',
|
||||||
|
taxAmount: item.taxAmount ?? '0',
|
||||||
|
lineTotal: item.lineTotal ?? '0',
|
||||||
|
sourceType: 'transaction_line_item',
|
||||||
|
sourceId: item.id,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// If paid, record the payment application
|
||||||
|
if (isPaid) {
|
||||||
|
await db.insert(paymentApplications).values({
|
||||||
|
invoiceId: invoice.id,
|
||||||
|
transactionId,
|
||||||
|
amount: txn.total,
|
||||||
|
appliedBy: createdBy,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// If account_charge, update AR balance
|
||||||
|
if (!isPaid) {
|
||||||
|
await AccountBalanceService.adjustBalance(db, txn.accountId, parseFloat(txn.total), 'invoice')
|
||||||
|
}
|
||||||
|
|
||||||
|
return invoice
|
||||||
|
},
|
||||||
|
|
||||||
|
async createFromRepairTicket(db: PostgresJsDatabase<any>, ticketId: string, createdBy: string) {
|
||||||
|
const [ticket] = await db.select().from(repairTickets).where(eq(repairTickets.id, ticketId)).limit(1)
|
||||||
|
if (!ticket) throw new NotFoundError('Repair ticket')
|
||||||
|
if (!ticket.accountId) throw new ValidationError('Repair ticket must be linked to an account for invoicing')
|
||||||
|
|
||||||
|
const lineItemRows = await db.select().from(repairLineItems)
|
||||||
|
.where(and(eq(repairLineItems.repairTicketId, ticketId), sql`${repairLineItems.itemType} != 'consumable'`))
|
||||||
|
|
||||||
|
if (lineItemRows.length === 0) return null // No billable items
|
||||||
|
|
||||||
|
const invoiceNumber = generateInvoiceNumber()
|
||||||
|
const today = new Date().toISOString().slice(0, 10)
|
||||||
|
|
||||||
|
let subtotal = 0
|
||||||
|
for (const item of lineItemRows) {
|
||||||
|
subtotal += parseFloat(item.totalPrice)
|
||||||
|
}
|
||||||
|
|
||||||
|
const [invoice] = await db.insert(invoices).values({
|
||||||
|
invoiceNumber,
|
||||||
|
accountId: ticket.accountId,
|
||||||
|
status: 'sent',
|
||||||
|
issueDate: today,
|
||||||
|
dueDate: today,
|
||||||
|
sourceType: 'repair_ticket',
|
||||||
|
sourceId: ticketId,
|
||||||
|
subtotal: subtotal.toFixed(2),
|
||||||
|
total: subtotal.toFixed(2),
|
||||||
|
balance: subtotal.toFixed(2),
|
||||||
|
createdBy,
|
||||||
|
}).returning()
|
||||||
|
|
||||||
|
for (const item of lineItemRows) {
|
||||||
|
await db.insert(invoiceLineItems).values({
|
||||||
|
invoiceId: invoice.id,
|
||||||
|
description: item.description,
|
||||||
|
qty: parseInt(item.qty as any) || 1,
|
||||||
|
unitPrice: item.unitPrice,
|
||||||
|
lineTotal: item.totalPrice,
|
||||||
|
sourceType: 'repair_line_item',
|
||||||
|
sourceId: item.id,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update AR balance
|
||||||
|
await AccountBalanceService.adjustBalance(db, ticket.accountId, subtotal, 'invoice')
|
||||||
|
|
||||||
|
return invoice
|
||||||
|
},
|
||||||
|
|
||||||
|
async applyPayment(
|
||||||
|
db: PostgresJsDatabase<any>,
|
||||||
|
invoiceId: string,
|
||||||
|
input: { transactionId?: string; amount: number },
|
||||||
|
appliedBy: string,
|
||||||
|
) {
|
||||||
|
const [invoice] = await db.select().from(invoices).where(eq(invoices.id, invoiceId)).limit(1)
|
||||||
|
if (!invoice) throw new NotFoundError('Invoice')
|
||||||
|
|
||||||
|
if (['void', 'written_off', 'paid'].includes(invoice.status)) {
|
||||||
|
throw new ValidationError(`Cannot apply payment to ${invoice.status} invoice`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const currentBalance = parseFloat(invoice.balance)
|
||||||
|
if (input.amount > currentBalance) {
|
||||||
|
throw new ValidationError(`Payment amount $${input.amount} exceeds invoice balance $${currentBalance}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Record payment application
|
||||||
|
const [application] = await db.insert(paymentApplications).values({
|
||||||
|
invoiceId,
|
||||||
|
transactionId: input.transactionId ?? null,
|
||||||
|
amount: input.amount.toFixed(2),
|
||||||
|
appliedBy,
|
||||||
|
}).returning()
|
||||||
|
|
||||||
|
// Update invoice
|
||||||
|
const newAmountPaid = parseFloat(invoice.amountPaid) + input.amount
|
||||||
|
const newBalance = parseFloat(invoice.total) - newAmountPaid
|
||||||
|
const newStatus = newBalance <= 0 ? 'paid' : 'partial'
|
||||||
|
|
||||||
|
await db.update(invoices).set({
|
||||||
|
amountPaid: newAmountPaid.toFixed(2),
|
||||||
|
balance: newBalance.toFixed(2),
|
||||||
|
status: newStatus,
|
||||||
|
updatedAt: new Date(),
|
||||||
|
}).where(eq(invoices.id, invoiceId))
|
||||||
|
|
||||||
|
// Update AR balance
|
||||||
|
await AccountBalanceService.adjustBalance(db, invoice.accountId, -input.amount, 'payment')
|
||||||
|
|
||||||
|
return application
|
||||||
|
},
|
||||||
|
|
||||||
|
async applyPaymentToOldestInvoices(
|
||||||
|
db: PostgresJsDatabase<any>,
|
||||||
|
accountId: string,
|
||||||
|
amount: number,
|
||||||
|
transactionId: string,
|
||||||
|
appliedBy: string,
|
||||||
|
) {
|
||||||
|
// FIFO: apply payment to oldest outstanding invoices
|
||||||
|
const outstanding = await db.select().from(invoices)
|
||||||
|
.where(and(
|
||||||
|
eq(invoices.accountId, accountId),
|
||||||
|
inArray(invoices.status, ['sent', 'partial', 'overdue']),
|
||||||
|
))
|
||||||
|
.orderBy(invoices.issueDate)
|
||||||
|
|
||||||
|
let remaining = amount
|
||||||
|
const applications = []
|
||||||
|
|
||||||
|
for (const inv of outstanding) {
|
||||||
|
if (remaining <= 0) break
|
||||||
|
const invBalance = parseFloat(inv.balance)
|
||||||
|
const applied = Math.min(remaining, invBalance)
|
||||||
|
|
||||||
|
const app = await this.applyPayment(db, inv.id, { transactionId, amount: applied }, appliedBy)
|
||||||
|
applications.push(app)
|
||||||
|
remaining -= applied
|
||||||
|
}
|
||||||
|
|
||||||
|
return { applications, amountApplied: amount - remaining, remaining }
|
||||||
|
},
|
||||||
|
|
||||||
|
async void(db: PostgresJsDatabase<any>, invoiceId: string, reason: string, _voidedBy: string) {
|
||||||
|
const [invoice] = await db.select().from(invoices).where(eq(invoices.id, invoiceId)).limit(1)
|
||||||
|
if (!invoice) throw new NotFoundError('Invoice')
|
||||||
|
|
||||||
|
if (invoice.status === 'void') throw new ValidationError('Invoice is already void')
|
||||||
|
|
||||||
|
const balance = parseFloat(invoice.balance)
|
||||||
|
|
||||||
|
await db.update(invoices).set({
|
||||||
|
status: 'void',
|
||||||
|
balance: '0',
|
||||||
|
notes: `${invoice.notes ? invoice.notes + '\n' : ''}Voided: ${reason}`,
|
||||||
|
updatedAt: new Date(),
|
||||||
|
}).where(eq(invoices.id, invoiceId))
|
||||||
|
|
||||||
|
// If there was an outstanding balance, adjust AR
|
||||||
|
if (balance > 0) {
|
||||||
|
await AccountBalanceService.adjustBalance(db, invoice.accountId, -balance, 'void')
|
||||||
|
}
|
||||||
|
|
||||||
|
return { ...invoice, status: 'void' as const, balance: '0' }
|
||||||
|
},
|
||||||
|
|
||||||
|
async writeOff(db: PostgresJsDatabase<any>, invoiceId: string, reason: string, _writtenOffBy: string) {
|
||||||
|
const [invoice] = await db.select().from(invoices).where(eq(invoices.id, invoiceId)).limit(1)
|
||||||
|
if (!invoice) throw new NotFoundError('Invoice')
|
||||||
|
|
||||||
|
const balance = parseFloat(invoice.balance)
|
||||||
|
if (balance <= 0) throw new ValidationError('No balance to write off')
|
||||||
|
|
||||||
|
await db.update(invoices).set({
|
||||||
|
status: 'written_off',
|
||||||
|
balance: '0',
|
||||||
|
notes: `${invoice.notes ? invoice.notes + '\n' : ''}Written off: ${reason}`,
|
||||||
|
updatedAt: new Date(),
|
||||||
|
}).where(eq(invoices.id, invoiceId))
|
||||||
|
|
||||||
|
await AccountBalanceService.adjustBalance(db, invoice.accountId, -balance, 'write_off')
|
||||||
|
|
||||||
|
return { ...invoice, status: 'written_off' as const, balance: '0' }
|
||||||
|
},
|
||||||
|
|
||||||
|
async send(db: PostgresJsDatabase<any>, invoiceId: string) {
|
||||||
|
const [invoice] = await db.select().from(invoices).where(eq(invoices.id, invoiceId)).limit(1)
|
||||||
|
if (!invoice) throw new NotFoundError('Invoice')
|
||||||
|
|
||||||
|
if (invoice.status !== 'draft') throw new ValidationError('Only draft invoices can be sent')
|
||||||
|
|
||||||
|
const [updated] = await db.update(invoices).set({ status: 'sent', updatedAt: new Date() })
|
||||||
|
.where(eq(invoices.id, invoiceId)).returning()
|
||||||
|
return updated
|
||||||
|
},
|
||||||
|
|
||||||
|
async getById(db: PostgresJsDatabase<any>, id: string) {
|
||||||
|
const [invoice] = await db.select().from(invoices).where(eq(invoices.id, id)).limit(1)
|
||||||
|
if (!invoice) return null
|
||||||
|
|
||||||
|
const lineItemRows = await db.select().from(invoiceLineItems).where(eq(invoiceLineItems.invoiceId, id))
|
||||||
|
const payments = await db.select().from(paymentApplications).where(eq(paymentApplications.invoiceId, id))
|
||||||
|
|
||||||
|
return { ...invoice, lineItems: lineItemRows, payments }
|
||||||
|
},
|
||||||
|
|
||||||
|
async list(db: PostgresJsDatabase<any>, params: PaginationInput, filters?: {
|
||||||
|
accountId?: string
|
||||||
|
status?: string
|
||||||
|
dateFrom?: string
|
||||||
|
dateTo?: string
|
||||||
|
}) {
|
||||||
|
const conditions = []
|
||||||
|
if (filters?.accountId) conditions.push(eq(invoices.accountId, filters.accountId))
|
||||||
|
if (filters?.status) conditions.push(eq(invoices.status, filters.status as any))
|
||||||
|
if (filters?.dateFrom) conditions.push(sql`${invoices.issueDate} >= ${filters.dateFrom}`)
|
||||||
|
if (filters?.dateTo) conditions.push(sql`${invoices.issueDate} <= ${filters.dateTo}`)
|
||||||
|
|
||||||
|
const searchCondition = params.q
|
||||||
|
? buildSearchCondition(params.q, [invoices.invoiceNumber])
|
||||||
|
: undefined
|
||||||
|
if (searchCondition) conditions.push(searchCondition)
|
||||||
|
|
||||||
|
const where = conditions.length > 0 ? and(...conditions) : undefined
|
||||||
|
const offset = ((params.page ?? 1) - 1) * (params.limit ?? 25)
|
||||||
|
|
||||||
|
const sortableColumns: Record<string, Column> = {
|
||||||
|
invoice_number: invoices.invoiceNumber,
|
||||||
|
issue_date: invoices.issueDate,
|
||||||
|
due_date: invoices.dueDate,
|
||||||
|
total: invoices.total,
|
||||||
|
balance: invoices.balance,
|
||||||
|
status: invoices.status,
|
||||||
|
created_at: invoices.createdAt,
|
||||||
|
}
|
||||||
|
|
||||||
|
const sortColumn = sortableColumns[params.sort ?? 'created_at'] ?? invoices.createdAt
|
||||||
|
const orderFn = params.order === 'asc' ? sql`${sortColumn} ASC` : sql`${sortColumn} DESC`
|
||||||
|
|
||||||
|
const [data, [{ total }]] = await Promise.all([
|
||||||
|
db.select({
|
||||||
|
id: invoices.id,
|
||||||
|
invoiceNumber: invoices.invoiceNumber,
|
||||||
|
accountId: invoices.accountId,
|
||||||
|
status: invoices.status,
|
||||||
|
issueDate: invoices.issueDate,
|
||||||
|
dueDate: invoices.dueDate,
|
||||||
|
total: invoices.total,
|
||||||
|
amountPaid: invoices.amountPaid,
|
||||||
|
balance: invoices.balance,
|
||||||
|
sourceType: invoices.sourceType,
|
||||||
|
createdAt: invoices.createdAt,
|
||||||
|
accountName: accounts.name,
|
||||||
|
})
|
||||||
|
.from(invoices)
|
||||||
|
.leftJoin(accounts, eq(invoices.accountId, accounts.id))
|
||||||
|
.where(where)
|
||||||
|
.orderBy(orderFn)
|
||||||
|
.limit(params.limit ?? 25)
|
||||||
|
.offset(offset),
|
||||||
|
db.select({ total: count() }).from(invoices).where(where),
|
||||||
|
])
|
||||||
|
|
||||||
|
return {
|
||||||
|
data,
|
||||||
|
pagination: {
|
||||||
|
page: params.page ?? 1,
|
||||||
|
limit: params.limit ?? 25,
|
||||||
|
total,
|
||||||
|
totalPages: Math.ceil(total / (params.limit ?? 25)),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async listByAccount(db: PostgresJsDatabase<any>, accountId: string, params: PaginationInput) {
|
||||||
|
return this.list(db, params, { accountId })
|
||||||
|
},
|
||||||
|
|
||||||
|
async markOverdueInvoices(db: PostgresJsDatabase<any>) {
|
||||||
|
const today = new Date().toISOString().slice(0, 10)
|
||||||
|
await db.update(invoices).set({ status: 'overdue', updatedAt: new Date() })
|
||||||
|
.where(and(
|
||||||
|
inArray(invoices.status, ['sent', 'partial']),
|
||||||
|
lte(invoices.dueDate, today),
|
||||||
|
))
|
||||||
|
},
|
||||||
|
|
||||||
|
async getAgingReport(db: PostgresJsDatabase<any>) {
|
||||||
|
const today = new Date()
|
||||||
|
const d30 = new Date(today); d30.setDate(d30.getDate() - 30)
|
||||||
|
const d60 = new Date(today); d60.setDate(d60.getDate() - 60)
|
||||||
|
const d90 = new Date(today); d90.setDate(d90.getDate() - 90)
|
||||||
|
|
||||||
|
const outstanding = await db.select({
|
||||||
|
id: invoices.id,
|
||||||
|
invoiceNumber: invoices.invoiceNumber,
|
||||||
|
accountId: invoices.accountId,
|
||||||
|
accountName: accounts.name,
|
||||||
|
dueDate: invoices.dueDate,
|
||||||
|
total: invoices.total,
|
||||||
|
balance: invoices.balance,
|
||||||
|
})
|
||||||
|
.from(invoices)
|
||||||
|
.leftJoin(accounts, eq(invoices.accountId, accounts.id))
|
||||||
|
.where(and(
|
||||||
|
inArray(invoices.status, ['sent', 'partial', 'overdue']),
|
||||||
|
sql`${invoices.balance}::numeric > 0`,
|
||||||
|
))
|
||||||
|
|
||||||
|
let current = 0, days30 = 0, days60 = 0, days90plus = 0
|
||||||
|
|
||||||
|
for (const inv of outstanding) {
|
||||||
|
const balance = parseFloat(inv.balance!)
|
||||||
|
const dueDate = new Date(inv.dueDate!)
|
||||||
|
if (dueDate >= today) current += balance
|
||||||
|
else if (dueDate >= d30) days30 += balance
|
||||||
|
else if (dueDate >= d60) days60 += balance
|
||||||
|
else days90plus += balance
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
current: current.toFixed(2),
|
||||||
|
days30: days30.toFixed(2),
|
||||||
|
days60: days60.toFixed(2),
|
||||||
|
days90plus: days90plus.toFixed(2),
|
||||||
|
total: (current + days30 + days60 + days90plus).toFixed(2),
|
||||||
|
invoiceCount: outstanding.length,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async exportCSV(db: PostgresJsDatabase<any>, filters?: { dateFrom?: string; dateTo?: string }) {
|
||||||
|
const conditions = []
|
||||||
|
if (filters?.dateFrom) conditions.push(sql`${invoices.issueDate} >= ${filters.dateFrom}`)
|
||||||
|
if (filters?.dateTo) conditions.push(sql`${invoices.issueDate} <= ${filters.dateTo}`)
|
||||||
|
const where = conditions.length > 0 ? and(...conditions) : undefined
|
||||||
|
|
||||||
|
const rows = await db.select({
|
||||||
|
invoiceNumber: invoices.invoiceNumber,
|
||||||
|
accountName: accounts.name,
|
||||||
|
issueDate: invoices.issueDate,
|
||||||
|
dueDate: invoices.dueDate,
|
||||||
|
status: invoices.status,
|
||||||
|
subtotal: invoices.subtotal,
|
||||||
|
discountTotal: invoices.discountTotal,
|
||||||
|
taxTotal: invoices.taxTotal,
|
||||||
|
total: invoices.total,
|
||||||
|
amountPaid: invoices.amountPaid,
|
||||||
|
balance: invoices.balance,
|
||||||
|
})
|
||||||
|
.from(invoices)
|
||||||
|
.leftJoin(accounts, eq(invoices.accountId, accounts.id))
|
||||||
|
.where(where)
|
||||||
|
.orderBy(invoices.issueDate)
|
||||||
|
|
||||||
|
const headers = ['Invoice Number', 'Customer', 'Issue Date', 'Due Date', 'Status', 'Subtotal', 'Discount', 'Tax', 'Total', 'Paid', 'Balance']
|
||||||
|
const csvRows = [
|
||||||
|
headers.join(','),
|
||||||
|
...rows.map(r => [
|
||||||
|
r.invoiceNumber,
|
||||||
|
`"${(r.accountName ?? '').replace(/"/g, '""')}"`,
|
||||||
|
r.issueDate,
|
||||||
|
r.dueDate,
|
||||||
|
r.status,
|
||||||
|
r.subtotal,
|
||||||
|
r.discountTotal,
|
||||||
|
r.taxTotal,
|
||||||
|
r.total,
|
||||||
|
r.amountPaid,
|
||||||
|
r.balance,
|
||||||
|
].join(',')),
|
||||||
|
]
|
||||||
|
|
||||||
|
return csvRows.join('\n')
|
||||||
|
},
|
||||||
|
}
|
||||||
83
packages/shared/src/schemas/accounting.schema.ts
Normal file
83
packages/shared/src/schemas/accounting.schema.ts
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
// Enums
|
||||||
|
export const AccountType = z.enum(['asset', 'liability', 'revenue', 'contra_revenue', 'cogs', 'expense'])
|
||||||
|
export type AccountType = z.infer<typeof AccountType>
|
||||||
|
|
||||||
|
export const InvoiceStatus = z.enum(['draft', 'sent', 'paid', 'partial', 'overdue', 'void', 'written_off'])
|
||||||
|
export type InvoiceStatus = z.infer<typeof InvoiceStatus>
|
||||||
|
|
||||||
|
export const JournalLineType = z.enum(['debit', 'credit'])
|
||||||
|
export type JournalLineType = z.infer<typeof JournalLineType>
|
||||||
|
|
||||||
|
export const BillingRunStatus = z.enum(['pending', 'running', 'completed', 'failed'])
|
||||||
|
export type BillingRunStatus = z.infer<typeof BillingRunStatus>
|
||||||
|
|
||||||
|
// Invoice
|
||||||
|
export const InvoiceLineItemInput = z.object({
|
||||||
|
description: z.string().min(1).max(255),
|
||||||
|
qty: z.coerce.number().int().min(1).default(1),
|
||||||
|
unitPrice: z.coerce.number().min(0),
|
||||||
|
discountAmount: z.coerce.number().min(0).default(0),
|
||||||
|
taxRate: z.coerce.number().min(0).default(0),
|
||||||
|
accountCodeId: z.string().uuid().optional(),
|
||||||
|
})
|
||||||
|
export type InvoiceLineItemInput = z.infer<typeof InvoiceLineItemInput>
|
||||||
|
|
||||||
|
export const InvoiceCreateSchema = z.object({
|
||||||
|
accountId: z.string().uuid(),
|
||||||
|
locationId: z.string().uuid().optional(),
|
||||||
|
issueDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
||||||
|
dueDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
||||||
|
notes: z.string().optional(),
|
||||||
|
lineItems: z.array(InvoiceLineItemInput).min(1),
|
||||||
|
})
|
||||||
|
export type InvoiceCreateInput = z.infer<typeof InvoiceCreateSchema>
|
||||||
|
|
||||||
|
export const PaymentApplicationSchema = z.object({
|
||||||
|
transactionId: z.string().uuid().optional(),
|
||||||
|
amount: z.coerce.number().min(0.01),
|
||||||
|
notes: z.string().optional(),
|
||||||
|
})
|
||||||
|
export type PaymentApplicationInput = z.infer<typeof PaymentApplicationSchema>
|
||||||
|
|
||||||
|
export const InvoiceVoidSchema = z.object({
|
||||||
|
reason: z.string().min(1),
|
||||||
|
})
|
||||||
|
export type InvoiceVoidInput = z.infer<typeof InvoiceVoidSchema>
|
||||||
|
|
||||||
|
export const InvoiceWriteOffSchema = z.object({
|
||||||
|
reason: z.string().min(1),
|
||||||
|
})
|
||||||
|
export type InvoiceWriteOffInput = z.infer<typeof InvoiceWriteOffSchema>
|
||||||
|
|
||||||
|
// Journal Entry
|
||||||
|
export const JournalEntryVoidSchema = z.object({
|
||||||
|
reason: z.string().min(1),
|
||||||
|
})
|
||||||
|
export type JournalEntryVoidInput = z.infer<typeof JournalEntryVoidSchema>
|
||||||
|
|
||||||
|
// Billing
|
||||||
|
export const BillingRunSchema = z.object({
|
||||||
|
runDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
|
||||||
|
})
|
||||||
|
export type BillingRunInput = z.infer<typeof BillingRunSchema>
|
||||||
|
|
||||||
|
export const BillEnrollmentSchema = z.object({
|
||||||
|
periodStart: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
||||||
|
periodEnd: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
||||||
|
})
|
||||||
|
export type BillEnrollmentInput = z.infer<typeof BillEnrollmentSchema>
|
||||||
|
|
||||||
|
// Report filters
|
||||||
|
export const DateRangeFilterSchema = z.object({
|
||||||
|
dateFrom: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
|
||||||
|
dateTo: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
|
||||||
|
})
|
||||||
|
export type DateRangeFilter = z.infer<typeof DateRangeFilterSchema>
|
||||||
|
|
||||||
|
export const StatementFilterSchema = z.object({
|
||||||
|
from: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
||||||
|
to: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
||||||
|
})
|
||||||
|
export type StatementFilter = z.infer<typeof StatementFilterSchema>
|
||||||
@@ -200,3 +200,31 @@ export type {
|
|||||||
|
|
||||||
export { LogLevel, AppConfigUpdateSchema } from './config.schema.js'
|
export { LogLevel, AppConfigUpdateSchema } from './config.schema.js'
|
||||||
export type { AppConfigUpdateInput } from './config.schema.js'
|
export type { AppConfigUpdateInput } from './config.schema.js'
|
||||||
|
|
||||||
|
export {
|
||||||
|
AccountType,
|
||||||
|
InvoiceStatus,
|
||||||
|
JournalLineType,
|
||||||
|
BillingRunStatus,
|
||||||
|
InvoiceLineItemInput,
|
||||||
|
InvoiceCreateSchema,
|
||||||
|
PaymentApplicationSchema,
|
||||||
|
InvoiceVoidSchema,
|
||||||
|
InvoiceWriteOffSchema,
|
||||||
|
JournalEntryVoidSchema,
|
||||||
|
BillingRunSchema,
|
||||||
|
BillEnrollmentSchema,
|
||||||
|
DateRangeFilterSchema,
|
||||||
|
StatementFilterSchema,
|
||||||
|
} from './accounting.schema.js'
|
||||||
|
export type {
|
||||||
|
InvoiceCreateInput,
|
||||||
|
PaymentApplicationInput,
|
||||||
|
InvoiceVoidInput,
|
||||||
|
InvoiceWriteOffInput,
|
||||||
|
JournalEntryVoidInput,
|
||||||
|
BillingRunInput,
|
||||||
|
BillEnrollmentInput,
|
||||||
|
DateRangeFilter,
|
||||||
|
StatementFilter,
|
||||||
|
} from './accounting.schema.js'
|
||||||
|
|||||||
Reference in New Issue
Block a user