@molecule/api-resource-invoice 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +115 -0
- package/dist/browser-guard.d.ts +2 -0
- package/dist/browser-guard.d.ts.map +1 -0
- package/dist/browser-guard.js +18 -0
- package/dist/index.d.ts +75 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +74 -0
- package/dist/routes.d.ts +19 -0
- package/dist/routes.d.ts.map +1 -0
- package/dist/routes.js +101 -0
- package/dist/service.d.ts +51 -0
- package/dist/service.d.ts.map +1 -0
- package/dist/service.js +164 -0
- package/dist/types.d.ts +38 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +1 -0
- package/dist/validation.d.ts +47 -0
- package/dist/validation.d.ts.map +1 -0
- package/dist/validation.js +31 -0
- package/package.json +45 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work.
|
|
38
|
+
|
|
39
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
40
|
+
form, that is based on (or derived from) the Work and for which the
|
|
41
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
42
|
+
represent, as a whole, an original work of authorship.
|
|
43
|
+
|
|
44
|
+
"Contribution" shall mean any work of authorship, including the
|
|
45
|
+
original version of the Work and any modifications or additions
|
|
46
|
+
to that Work, that is intentionally submitted to the Licensor for
|
|
47
|
+
inclusion in the Work by the copyright owner or by an individual or
|
|
48
|
+
Legal Entity authorized to submit on behalf of the copyright owner.
|
|
49
|
+
|
|
50
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
51
|
+
on behalf of whom a Contribution has been received by the Licensor and
|
|
52
|
+
subsequently incorporated within the Work.
|
|
53
|
+
|
|
54
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
55
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
56
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
57
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
58
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
59
|
+
Work and such Derivative Works in Source or Object form.
|
|
60
|
+
|
|
61
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
62
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
63
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
64
|
+
patent license to make, have made, use, offer to sell, sell, import,
|
|
65
|
+
and otherwise transfer the Work.
|
|
66
|
+
|
|
67
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
68
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
69
|
+
modifications, and in Source or Object form, provided that You
|
|
70
|
+
meet the following conditions:
|
|
71
|
+
|
|
72
|
+
(a) You must give any other recipients of the Work or
|
|
73
|
+
Derivative Works a copy of this License; and
|
|
74
|
+
|
|
75
|
+
(b) You must cause any modified files to carry prominent notices
|
|
76
|
+
stating that You changed the files; and
|
|
77
|
+
|
|
78
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
79
|
+
that You distribute, all copyright, patent, trademark, and
|
|
80
|
+
attribution notices from the Source form of the Work,
|
|
81
|
+
excluding those notices that do not pertain to any part of
|
|
82
|
+
the Derivative Works; and
|
|
83
|
+
|
|
84
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
85
|
+
distribution, then any Derivative Works that You distribute must
|
|
86
|
+
include a readable copy of the attribution notices contained
|
|
87
|
+
within such NOTICE file.
|
|
88
|
+
|
|
89
|
+
5. Submission of Contributions.
|
|
90
|
+
|
|
91
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
92
|
+
names, trademarks, service marks, or product names of the Licensor.
|
|
93
|
+
|
|
94
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
95
|
+
agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
|
|
96
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
|
|
97
|
+
|
|
98
|
+
8. Limitation of Liability. In no event and under no legal theory shall
|
|
99
|
+
any Contributor be liable to You for damages.
|
|
100
|
+
|
|
101
|
+
9. Accepting Warranty or Additional Liability.
|
|
102
|
+
|
|
103
|
+
Copyright 2026 Molecule Dev, Inc.
|
|
104
|
+
|
|
105
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
106
|
+
you may not use this file except in compliance with the License.
|
|
107
|
+
You may obtain a copy of the License at
|
|
108
|
+
|
|
109
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
110
|
+
|
|
111
|
+
Unless required by applicable law or agreed to in writing, software
|
|
112
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
113
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
114
|
+
See the License for the specific language governing permissions and
|
|
115
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"browser-guard.d.ts","sourceRoot":"","sources":["../src/browser-guard.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,CAAA"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser guard — `@molecule/api-resource-invoice` is SERVER-ONLY.
|
|
3
|
+
*
|
|
4
|
+
* Generated by scripts/gen-browser-guards.mjs (workspace root) — edit THAT, not this.
|
|
5
|
+
* Evaluating a server package in a browser bundle is always an import-graph mistake
|
|
6
|
+
* (node APIs, secrets); without this guard it surfaces as a cryptic downstream crash
|
|
7
|
+
* ("Buffer is not defined") far from the culprit. Throwing here names the package and
|
|
8
|
+
* the fix at the exact moment the client bundle evaluates it. jsdom tests and SSR are
|
|
9
|
+
* unaffected: the throw requires browser globals AND the absence of a node runtime.
|
|
10
|
+
*/
|
|
11
|
+
const g = globalThis;
|
|
12
|
+
if (g.window !== undefined && g.document !== undefined && !g.process?.versions?.node) {
|
|
13
|
+
throw new Error('@molecule/api-resource-invoice is SERVER-ONLY: it was bundled into browser/client code. Import it only ' +
|
|
14
|
+
'from server code (a server route/function or your API), or dynamic-import it inside ' +
|
|
15
|
+
'the server handler — never from components or shared client modules, and never ' +
|
|
16
|
+
'polyfill Buffer/process to silence this.');
|
|
17
|
+
}
|
|
18
|
+
export {};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@molecule/api-resource-invoice` — line-item-based invoice CRUD with
|
|
3
|
+
* auto-computed totals (subtotal + tax), draft/sent/partial/paid/overdue/void
|
|
4
|
+
* status, and a `recordPayment(invoiceId, userId, amount)` helper that
|
|
5
|
+
* advances status automatically.
|
|
6
|
+
*
|
|
7
|
+
* Extracted from the invoice-billing flagship.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```ts
|
|
11
|
+
* import { createInvoiceRouter } from '@molecule/api-resource-invoice'
|
|
12
|
+
* app.use('/invoices', createInvoiceRouter())
|
|
13
|
+
* ```
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```ts
|
|
17
|
+
* import { createInvoiceForUser, recordPayment } from '@molecule/api-resource-invoice'
|
|
18
|
+
*
|
|
19
|
+
* const inv = await createInvoiceForUser(userId, {
|
|
20
|
+
* client_id: 'acme-co',
|
|
21
|
+
* items: [{ description: 'Consulting', quantity: 10, unit_price: 250 }],
|
|
22
|
+
* tax_rate: 8.5,
|
|
23
|
+
* })
|
|
24
|
+
* await recordPayment(inv.id, userId, 2710.00) // marks paid
|
|
25
|
+
* ```
|
|
26
|
+
*
|
|
27
|
+
* @remarks
|
|
28
|
+
* Table: `src/__setup__/invoices.sql` creates the single `invoices` table. An
|
|
29
|
+
* mlcl-scaffolded API replays `__setup__/*.sql` automatically on migrate;
|
|
30
|
+
* anywhere else run it once. The bundled `computeTotals(items, taxRate)`
|
|
31
|
+
* helper is exported for client-side total previews.
|
|
32
|
+
*
|
|
33
|
+
* Everything is owner-scoped: service functions take the authenticated
|
|
34
|
+
* `userId` and return `null`/`false` for rows the caller doesn't own, and the
|
|
35
|
+
* router reads the caller from `res.locals.session` (mount behind your global
|
|
36
|
+
* auth middleware; 401 otherwise). `recordPayment` is bookkeeping — "record a
|
|
37
|
+
* payment I received" against my own invoice — it never talks to a payment
|
|
38
|
+
* provider; wire actual charging separately (see `@molecule/api-payments`).
|
|
39
|
+
*
|
|
40
|
+
* @e2e
|
|
41
|
+
* Integration checklist — drive the real UI (live preview, no mocks), adapt
|
|
42
|
+
* each item to this app's actual screens/flows, and check every box off one
|
|
43
|
+
* by one. A box you can't check is an integration bug to fix — not a skip:
|
|
44
|
+
* - [ ] Creating an invoice with line items auto-computes the money: add a
|
|
45
|
+
* line (quantity × unit_price) and the subtotal updates, the tax_rate is
|
|
46
|
+
* applied (tax_amount = subtotal × rate / 100), and total = subtotal +
|
|
47
|
+
* tax_amount — matching `computeTotals` down to the rounded cents shown in
|
|
48
|
+
* the UI. Change a quantity or add another line and every figure re-computes.
|
|
49
|
+
* - [ ] The status lifecycle advances correctly through INVOICE_STATUSES: a
|
|
50
|
+
* freshly created invoice reads `draft`; sending it moves it to `sent`; a
|
|
51
|
+
* `recordPayment` for LESS than the balance flips it to `partial`; paying the
|
|
52
|
+
* remaining balance flips it to `paid` and stamps a paid date. The
|
|
53
|
+
* balance-due shown to the user (total - amount_paid) is correct after each
|
|
54
|
+
* step.
|
|
55
|
+
* - [ ] Terminal/edge states read right: an unpaid invoice past its due_date
|
|
56
|
+
* shows `overdue`, a cancelled one shows `void`, and once an invoice is `paid`
|
|
57
|
+
* or `void` the UI blocks further line-item/total edits as designed.
|
|
58
|
+
* - [ ] Overpayment and dead-invoice payments are rejected, not silently
|
|
59
|
+
* over-applied: recording an amount greater than the outstanding balance, or
|
|
60
|
+
* any payment against an already-`paid` or `void` invoice, fails with a
|
|
61
|
+
* visible error and leaves amount_paid + status unchanged.
|
|
62
|
+
* - [ ] AUTHORIZATION: a signed-in user sees and mutates only THEIR OWN
|
|
63
|
+
* invoices — every path is `*ForUser`-scoped (listInvoicesForUser /
|
|
64
|
+
* getInvoiceForUser / updateInvoiceForUser / recordPayment). Guessing or
|
|
65
|
+
* tampering another user's invoice id on GET/PUT/DELETE/:id/payment returns
|
|
66
|
+
* 403/404 — never that invoice's data and never a cross-user payment.
|
|
67
|
+
*
|
|
68
|
+
* @module
|
|
69
|
+
*/
|
|
70
|
+
export * from './browser-guard.js';
|
|
71
|
+
export * from './routes.js';
|
|
72
|
+
export * from './service.js';
|
|
73
|
+
export * from './types.js';
|
|
74
|
+
export * from './validation.js';
|
|
75
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoEG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA;AAC5B,cAAc,YAAY,CAAA;AAC1B,cAAc,iBAAiB,CAAA"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@molecule/api-resource-invoice` — line-item-based invoice CRUD with
|
|
3
|
+
* auto-computed totals (subtotal + tax), draft/sent/partial/paid/overdue/void
|
|
4
|
+
* status, and a `recordPayment(invoiceId, userId, amount)` helper that
|
|
5
|
+
* advances status automatically.
|
|
6
|
+
*
|
|
7
|
+
* Extracted from the invoice-billing flagship.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```ts
|
|
11
|
+
* import { createInvoiceRouter } from '@molecule/api-resource-invoice'
|
|
12
|
+
* app.use('/invoices', createInvoiceRouter())
|
|
13
|
+
* ```
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```ts
|
|
17
|
+
* import { createInvoiceForUser, recordPayment } from '@molecule/api-resource-invoice'
|
|
18
|
+
*
|
|
19
|
+
* const inv = await createInvoiceForUser(userId, {
|
|
20
|
+
* client_id: 'acme-co',
|
|
21
|
+
* items: [{ description: 'Consulting', quantity: 10, unit_price: 250 }],
|
|
22
|
+
* tax_rate: 8.5,
|
|
23
|
+
* })
|
|
24
|
+
* await recordPayment(inv.id, userId, 2710.00) // marks paid
|
|
25
|
+
* ```
|
|
26
|
+
*
|
|
27
|
+
* @remarks
|
|
28
|
+
* Table: `src/__setup__/invoices.sql` creates the single `invoices` table. An
|
|
29
|
+
* mlcl-scaffolded API replays `__setup__/*.sql` automatically on migrate;
|
|
30
|
+
* anywhere else run it once. The bundled `computeTotals(items, taxRate)`
|
|
31
|
+
* helper is exported for client-side total previews.
|
|
32
|
+
*
|
|
33
|
+
* Everything is owner-scoped: service functions take the authenticated
|
|
34
|
+
* `userId` and return `null`/`false` for rows the caller doesn't own, and the
|
|
35
|
+
* router reads the caller from `res.locals.session` (mount behind your global
|
|
36
|
+
* auth middleware; 401 otherwise). `recordPayment` is bookkeeping — "record a
|
|
37
|
+
* payment I received" against my own invoice — it never talks to a payment
|
|
38
|
+
* provider; wire actual charging separately (see `@molecule/api-payments`).
|
|
39
|
+
*
|
|
40
|
+
* @e2e
|
|
41
|
+
* Integration checklist — drive the real UI (live preview, no mocks), adapt
|
|
42
|
+
* each item to this app's actual screens/flows, and check every box off one
|
|
43
|
+
* by one. A box you can't check is an integration bug to fix — not a skip:
|
|
44
|
+
* - [ ] Creating an invoice with line items auto-computes the money: add a
|
|
45
|
+
* line (quantity × unit_price) and the subtotal updates, the tax_rate is
|
|
46
|
+
* applied (tax_amount = subtotal × rate / 100), and total = subtotal +
|
|
47
|
+
* tax_amount — matching `computeTotals` down to the rounded cents shown in
|
|
48
|
+
* the UI. Change a quantity or add another line and every figure re-computes.
|
|
49
|
+
* - [ ] The status lifecycle advances correctly through INVOICE_STATUSES: a
|
|
50
|
+
* freshly created invoice reads `draft`; sending it moves it to `sent`; a
|
|
51
|
+
* `recordPayment` for LESS than the balance flips it to `partial`; paying the
|
|
52
|
+
* remaining balance flips it to `paid` and stamps a paid date. The
|
|
53
|
+
* balance-due shown to the user (total - amount_paid) is correct after each
|
|
54
|
+
* step.
|
|
55
|
+
* - [ ] Terminal/edge states read right: an unpaid invoice past its due_date
|
|
56
|
+
* shows `overdue`, a cancelled one shows `void`, and once an invoice is `paid`
|
|
57
|
+
* or `void` the UI blocks further line-item/total edits as designed.
|
|
58
|
+
* - [ ] Overpayment and dead-invoice payments are rejected, not silently
|
|
59
|
+
* over-applied: recording an amount greater than the outstanding balance, or
|
|
60
|
+
* any payment against an already-`paid` or `void` invoice, fails with a
|
|
61
|
+
* visible error and leaves amount_paid + status unchanged.
|
|
62
|
+
* - [ ] AUTHORIZATION: a signed-in user sees and mutates only THEIR OWN
|
|
63
|
+
* invoices — every path is `*ForUser`-scoped (listInvoicesForUser /
|
|
64
|
+
* getInvoiceForUser / updateInvoiceForUser / recordPayment). Guessing or
|
|
65
|
+
* tampering another user's invoice id on GET/PUT/DELETE/:id/payment returns
|
|
66
|
+
* 403/404 — never that invoice's data and never a cross-user payment.
|
|
67
|
+
*
|
|
68
|
+
* @module
|
|
69
|
+
*/
|
|
70
|
+
export * from './browser-guard.js';
|
|
71
|
+
export * from './routes.js';
|
|
72
|
+
export * from './service.js';
|
|
73
|
+
export * from './types.js';
|
|
74
|
+
export * from './validation.js';
|
package/dist/routes.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Express router for invoices.
|
|
3
|
+
*
|
|
4
|
+
* Routes (mounted at e.g. `/invoices`):
|
|
5
|
+
* - `GET /` — list
|
|
6
|
+
* - `GET /:id` — single
|
|
7
|
+
* - `POST /` — create
|
|
8
|
+
* - `PUT /:id` — update (incl. status changes)
|
|
9
|
+
* - `DELETE /:id` — delete
|
|
10
|
+
* - `POST /:id/payment` — record a payment (auto-promotes status)
|
|
11
|
+
*
|
|
12
|
+
* @module
|
|
13
|
+
*/
|
|
14
|
+
import { Router } from 'express';
|
|
15
|
+
/**
|
|
16
|
+
* Creates and returns an Express router with all CRUD + payment routes for invoices.
|
|
17
|
+
*/
|
|
18
|
+
export declare function createInvoiceRouter(): Router;
|
|
19
|
+
//# sourceMappingURL=routes.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAoD,MAAM,EAAE,MAAM,SAAS,CAAA;AAkBlF;;GAEG;AACH,wBAAgB,mBAAmB,IAAI,MAAM,CA+F5C"}
|
package/dist/routes.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Express router for invoices.
|
|
3
|
+
*
|
|
4
|
+
* Routes (mounted at e.g. `/invoices`):
|
|
5
|
+
* - `GET /` — list
|
|
6
|
+
* - `GET /:id` — single
|
|
7
|
+
* - `POST /` — create
|
|
8
|
+
* - `PUT /:id` — update (incl. status changes)
|
|
9
|
+
* - `DELETE /:id` — delete
|
|
10
|
+
* - `POST /:id/payment` — record a payment (auto-promotes status)
|
|
11
|
+
*
|
|
12
|
+
* @module
|
|
13
|
+
*/
|
|
14
|
+
import { Router } from 'express';
|
|
15
|
+
import { getParamId, requireUser } from '@molecule/api-bonds-default-express';
|
|
16
|
+
import { t } from '@molecule/api-i18n';
|
|
17
|
+
import { validateBody as validateBodyRaw } from '@molecule/api-middleware-validation';
|
|
18
|
+
import { createInvoiceForUser, deleteInvoiceForUser, getInvoiceForUser, listInvoicesForUser, recordPayment, updateInvoiceForUser, } from './service.js';
|
|
19
|
+
import { invoiceCreateSchema, invoiceUpdateSchema, recordPaymentSchema } from './validation.js';
|
|
20
|
+
const validateBody = validateBodyRaw;
|
|
21
|
+
/**
|
|
22
|
+
* Creates and returns an Express router with all CRUD + payment routes for invoices.
|
|
23
|
+
*/
|
|
24
|
+
export function createInvoiceRouter() {
|
|
25
|
+
const router = Router();
|
|
26
|
+
router.get('/', async (req, res) => {
|
|
27
|
+
const userId = requireUser(res);
|
|
28
|
+
if (!userId)
|
|
29
|
+
return;
|
|
30
|
+
const q = req.query;
|
|
31
|
+
res.json(await listInvoicesForUser(userId, {
|
|
32
|
+
client_id: typeof q.client_id === 'string' ? q.client_id : undefined,
|
|
33
|
+
status: typeof q.status === 'string'
|
|
34
|
+
? q.status
|
|
35
|
+
: undefined,
|
|
36
|
+
page: typeof q.page === 'string' ? Number(q.page) : undefined,
|
|
37
|
+
limit: typeof q.limit === 'string' ? Number(q.limit) : undefined,
|
|
38
|
+
}));
|
|
39
|
+
});
|
|
40
|
+
router.get('/:id', async (req, res) => {
|
|
41
|
+
const userId = requireUser(res);
|
|
42
|
+
if (!userId)
|
|
43
|
+
return;
|
|
44
|
+
const inv = await getInvoiceForUser(getParamId(req), userId);
|
|
45
|
+
if (!inv) {
|
|
46
|
+
res
|
|
47
|
+
.status(404)
|
|
48
|
+
.json({ error: t('invoice.notFound', undefined, { defaultValue: 'Invoice not found' }) });
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
res.json(inv);
|
|
52
|
+
});
|
|
53
|
+
router.post('/', validateBody(invoiceCreateSchema), async (req, res) => {
|
|
54
|
+
const userId = requireUser(res);
|
|
55
|
+
if (!userId)
|
|
56
|
+
return;
|
|
57
|
+
res
|
|
58
|
+
.status(201)
|
|
59
|
+
.json(await createInvoiceForUser(userId, req.body));
|
|
60
|
+
});
|
|
61
|
+
router.put('/:id', validateBody(invoiceUpdateSchema), async (req, res) => {
|
|
62
|
+
const userId = requireUser(res);
|
|
63
|
+
if (!userId)
|
|
64
|
+
return;
|
|
65
|
+
const inv = await updateInvoiceForUser(getParamId(req), userId, req.body);
|
|
66
|
+
if (!inv) {
|
|
67
|
+
res
|
|
68
|
+
.status(404)
|
|
69
|
+
.json({ error: t('invoice.notFound', undefined, { defaultValue: 'Invoice not found' }) });
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
res.json(inv);
|
|
73
|
+
});
|
|
74
|
+
router.delete('/:id', async (req, res) => {
|
|
75
|
+
const userId = requireUser(res);
|
|
76
|
+
if (!userId)
|
|
77
|
+
return;
|
|
78
|
+
const ok = await deleteInvoiceForUser(getParamId(req), userId);
|
|
79
|
+
if (!ok) {
|
|
80
|
+
res
|
|
81
|
+
.status(404)
|
|
82
|
+
.json({ error: t('invoice.notFound', undefined, { defaultValue: 'Invoice not found' }) });
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
res.status(204).end();
|
|
86
|
+
});
|
|
87
|
+
router.post('/:id/payment', validateBody(recordPaymentSchema), async (req, res) => {
|
|
88
|
+
const userId = requireUser(res);
|
|
89
|
+
if (!userId)
|
|
90
|
+
return;
|
|
91
|
+
const inv = await recordPayment(getParamId(req), userId, req.body.amount);
|
|
92
|
+
if (!inv) {
|
|
93
|
+
res
|
|
94
|
+
.status(404)
|
|
95
|
+
.json({ error: t('invoice.notFound', undefined, { defaultValue: 'Invoice not found' }) });
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
res.json(inv);
|
|
99
|
+
});
|
|
100
|
+
return router;
|
|
101
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Invoice service — line-item-based invoicing with totals/tax computation.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
import type { Invoice, InvoiceRow, InvoiceStatus, LineItem } from './types.js';
|
|
7
|
+
/** Compute subtotal/tax/total from line items + tax rate (percent 0-100). */
|
|
8
|
+
export declare function computeTotals(items: LineItem[], taxRate: number): {
|
|
9
|
+
subtotal: number;
|
|
10
|
+
tax_amount: number;
|
|
11
|
+
total: number;
|
|
12
|
+
};
|
|
13
|
+
/** Map a raw database InvoiceRow to a normalized Invoice with ISO date strings. */
|
|
14
|
+
export declare function toInvoice(row: InvoiceRow): Invoice;
|
|
15
|
+
/** List all invoices for a user, with optional client/status filters and pagination. */
|
|
16
|
+
export declare function listInvoicesForUser(userId: string, opts?: {
|
|
17
|
+
client_id?: string;
|
|
18
|
+
status?: InvoiceStatus;
|
|
19
|
+
page?: number;
|
|
20
|
+
limit?: number;
|
|
21
|
+
}): Promise<{
|
|
22
|
+
data: Invoice[];
|
|
23
|
+
total: number;
|
|
24
|
+
page: number;
|
|
25
|
+
limit: number;
|
|
26
|
+
}>;
|
|
27
|
+
/** Fetch a single invoice by ID, returning null if not found or not owned by the user. */
|
|
28
|
+
export declare function getInvoiceForUser(invoiceId: string, userId: string): Promise<Invoice | null>;
|
|
29
|
+
/** Create a new draft invoice for a user, computing totals from line items and tax rate. */
|
|
30
|
+
export declare function createInvoiceForUser(userId: string, data: {
|
|
31
|
+
client_id: string;
|
|
32
|
+
items: LineItem[];
|
|
33
|
+
due_date?: string;
|
|
34
|
+
notes?: string;
|
|
35
|
+
tax_rate?: number;
|
|
36
|
+
currency?: string;
|
|
37
|
+
}): Promise<Invoice>;
|
|
38
|
+
/** Apply a partial update to a user-owned invoice, recomputing totals and marking paid_at when status becomes paid. */
|
|
39
|
+
export declare function updateInvoiceForUser(invoiceId: string, userId: string, patch: Partial<{
|
|
40
|
+
items: LineItem[];
|
|
41
|
+
due_date: string;
|
|
42
|
+
notes: string;
|
|
43
|
+
tax_rate: number;
|
|
44
|
+
currency: string;
|
|
45
|
+
status: InvoiceStatus;
|
|
46
|
+
}>): Promise<Invoice | null>;
|
|
47
|
+
/** Delete a user-owned invoice by ID, returning false if not found or not owned by the user. */
|
|
48
|
+
export declare function deleteInvoiceForUser(invoiceId: string, userId: string): Promise<boolean>;
|
|
49
|
+
/** Record a payment amount against an invoice, updating amount_paid and transitioning status to partial or paid. */
|
|
50
|
+
export declare function recordPayment(invoiceId: string, userId: string, amount: number): Promise<Invoice | null>;
|
|
51
|
+
//# sourceMappingURL=service.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../src/service.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAaH,OAAO,KAAK,EAAE,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAA;AAS9E,6EAA6E;AAC7E,wBAAgB,aAAa,CAC3B,KAAK,EAAE,QAAQ,EAAE,EACjB,OAAO,EAAE,MAAM,GACd;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAKzD;AAgBD,mFAAmF;AACnF,wBAAgB,SAAS,CAAC,GAAG,EAAE,UAAU,GAAG,OAAO,CAiBlD;AASD,wFAAwF;AACxF,wBAAsB,mBAAmB,CACvC,MAAM,EAAE,MAAM,EACd,IAAI,GAAE;IACJ,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,MAAM,CAAC,EAAE,aAAa,CAAA;IACtB,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,KAAK,CAAC,EAAE,MAAM,CAAA;CACV,GACL,OAAO,CAAC;IAAE,IAAI,EAAE,OAAO,EAAE,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC,CAgB1E;AAED,0FAA0F;AAC1F,wBAAsB,iBAAiB,CACrC,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC,CAIzB;AAED,4FAA4F;AAC5F,wBAAsB,oBAAoB,CACxC,MAAM,EAAE,MAAM,EACd,IAAI,EAAE;IACJ,SAAS,EAAE,MAAM,CAAA;IACjB,KAAK,EAAE,QAAQ,EAAE,CAAA;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAA;CAClB,GACA,OAAO,CAAC,OAAO,CAAC,CAuBlB;AAED,uHAAuH;AACvH,wBAAsB,oBAAoB,CACxC,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,OAAO,CAAC;IACb,KAAK,EAAE,QAAQ,EAAE,CAAA;IACjB,QAAQ,EAAE,MAAM,CAAA;IAChB,KAAK,EAAE,MAAM,CAAA;IACb,QAAQ,EAAE,MAAM,CAAA;IAChB,QAAQ,EAAE,MAAM,CAAA;IAChB,MAAM,EAAE,aAAa,CAAA;CACtB,CAAC,GACD,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC,CAuBzB;AAED,gGAAgG;AAChG,wBAAsB,oBAAoB,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAK9F;AAED,oHAAoH;AACpH,wBAAsB,aAAa,CACjC,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC,CAgBzB"}
|
package/dist/service.js
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Invoice service — line-item-based invoicing with totals/tax computation.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
import { count, create, deleteById, findById, findMany, updateById, } from '@molecule/api-database';
|
|
7
|
+
const TABLE = 'invoices';
|
|
8
|
+
/** Round a number to two decimal places for currency precision. */
|
|
9
|
+
function round2(n) {
|
|
10
|
+
return Math.round(n * 100) / 100;
|
|
11
|
+
}
|
|
12
|
+
/** Compute subtotal/tax/total from line items + tax rate (percent 0-100). */
|
|
13
|
+
export function computeTotals(items, taxRate) {
|
|
14
|
+
const subtotal = round2(items.reduce((sum, i) => sum + i.quantity * i.unit_price, 0));
|
|
15
|
+
const taxAmount = round2(subtotal * (taxRate / 100));
|
|
16
|
+
const total = round2(subtotal + taxAmount);
|
|
17
|
+
return { subtotal, tax_amount: taxAmount, total };
|
|
18
|
+
}
|
|
19
|
+
/** Convert a string, Date, or null to an ISO 8601 string, or null if absent. */
|
|
20
|
+
function toIso(value) {
|
|
21
|
+
if (!value)
|
|
22
|
+
return null;
|
|
23
|
+
if (value instanceof Date)
|
|
24
|
+
return value.toISOString();
|
|
25
|
+
return String(value);
|
|
26
|
+
}
|
|
27
|
+
/** Convert a string, Date, or null to a YYYY-MM-DD date string, or null if absent. */
|
|
28
|
+
function toDateString(value) {
|
|
29
|
+
const iso = toIso(value);
|
|
30
|
+
if (!iso)
|
|
31
|
+
return null;
|
|
32
|
+
return iso.length >= 10 ? iso.slice(0, 10) : iso;
|
|
33
|
+
}
|
|
34
|
+
/** Map a raw database InvoiceRow to a normalized Invoice with ISO date strings. */
|
|
35
|
+
export function toInvoice(row) {
|
|
36
|
+
return {
|
|
37
|
+
...row,
|
|
38
|
+
// pg returns `numeric` columns as strings (precision guard); the Invoice
|
|
39
|
+
// contract and every downstream math site expect numbers. Coerce here so
|
|
40
|
+
// comparisons ("paid >= total") and JSON responses are numeric.
|
|
41
|
+
subtotal: Number(row.subtotal),
|
|
42
|
+
tax_rate: Number(row.tax_rate),
|
|
43
|
+
tax_amount: Number(row.tax_amount),
|
|
44
|
+
total: Number(row.total),
|
|
45
|
+
amount_paid: Number(row.amount_paid),
|
|
46
|
+
issue_date: toDateString(row.issue_date) ?? '',
|
|
47
|
+
due_date: toDateString(row.due_date),
|
|
48
|
+
paid_at: toIso(row.paid_at),
|
|
49
|
+
created_at: toIso(row.created_at) ?? '',
|
|
50
|
+
updated_at: toIso(row.updated_at) ?? '',
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
/** Generate an invoice number like INV-2026-0001 for a user's next invoice. */
|
|
54
|
+
async function nextInvoiceNumber(userId) {
|
|
55
|
+
const year = new Date().getFullYear();
|
|
56
|
+
const existing = await count(TABLE, [{ field: 'user_id', operator: '=', value: userId }]);
|
|
57
|
+
return `INV-${year}-${String(existing + 1).padStart(4, '0')}`;
|
|
58
|
+
}
|
|
59
|
+
/** List all invoices for a user, with optional client/status filters and pagination. */
|
|
60
|
+
export async function listInvoicesForUser(userId, opts = {}) {
|
|
61
|
+
const page = opts.page ?? 1;
|
|
62
|
+
const limit = opts.limit ?? 50;
|
|
63
|
+
const where = [{ field: 'user_id', operator: '=', value: userId }];
|
|
64
|
+
if (opts.client_id)
|
|
65
|
+
where.push({ field: 'client_id', operator: '=', value: opts.client_id });
|
|
66
|
+
if (opts.status)
|
|
67
|
+
where.push({ field: 'status', operator: '=', value: opts.status });
|
|
68
|
+
const orderBy = [
|
|
69
|
+
{ field: 'issue_date', direction: 'desc' },
|
|
70
|
+
{ field: 'created_at', direction: 'desc' },
|
|
71
|
+
];
|
|
72
|
+
const offset = (page - 1) * limit;
|
|
73
|
+
const [rows, total] = await Promise.all([
|
|
74
|
+
findMany(TABLE, { where, orderBy, limit, offset }),
|
|
75
|
+
count(TABLE, where),
|
|
76
|
+
]);
|
|
77
|
+
return { data: rows.map(toInvoice), total, page, limit };
|
|
78
|
+
}
|
|
79
|
+
/** Fetch a single invoice by ID, returning null if not found or not owned by the user. */
|
|
80
|
+
export async function getInvoiceForUser(invoiceId, userId) {
|
|
81
|
+
const row = await findById(TABLE, invoiceId);
|
|
82
|
+
if (!row || row.user_id !== userId)
|
|
83
|
+
return null;
|
|
84
|
+
return toInvoice(row);
|
|
85
|
+
}
|
|
86
|
+
/** Create a new draft invoice for a user, computing totals from line items and tax rate. */
|
|
87
|
+
export async function createInvoiceForUser(userId, data) {
|
|
88
|
+
const taxRate = data.tax_rate ?? 0;
|
|
89
|
+
const totals = computeTotals(data.items, taxRate);
|
|
90
|
+
const number = await nextInvoiceNumber(userId);
|
|
91
|
+
const today = new Date().toISOString().slice(0, 10);
|
|
92
|
+
const result = await create(TABLE, {
|
|
93
|
+
user_id: userId,
|
|
94
|
+
client_id: data.client_id,
|
|
95
|
+
number,
|
|
96
|
+
status: 'draft',
|
|
97
|
+
items: data.items,
|
|
98
|
+
subtotal: totals.subtotal,
|
|
99
|
+
tax_rate: taxRate,
|
|
100
|
+
tax_amount: totals.tax_amount,
|
|
101
|
+
total: totals.total,
|
|
102
|
+
amount_paid: 0,
|
|
103
|
+
currency: data.currency ?? 'USD',
|
|
104
|
+
issue_date: today,
|
|
105
|
+
due_date: data.due_date ?? null,
|
|
106
|
+
paid_at: null,
|
|
107
|
+
notes: data.notes ?? null,
|
|
108
|
+
});
|
|
109
|
+
return toInvoice(result.data);
|
|
110
|
+
}
|
|
111
|
+
/** Apply a partial update to a user-owned invoice, recomputing totals and marking paid_at when status becomes paid. */
|
|
112
|
+
export async function updateInvoiceForUser(invoiceId, userId, patch) {
|
|
113
|
+
const existing = await findById(TABLE, invoiceId);
|
|
114
|
+
if (!existing || existing.user_id !== userId)
|
|
115
|
+
return null;
|
|
116
|
+
const updates = { ...patch };
|
|
117
|
+
if (patch.items || patch.tax_rate !== undefined) {
|
|
118
|
+
const items = patch.items ?? existing.items;
|
|
119
|
+
// pg numerics arrive as strings — the ?? fallback must be numeric before
|
|
120
|
+
// it reaches computeTotals' multiplication.
|
|
121
|
+
const taxRate = patch.tax_rate ?? Number(existing.tax_rate);
|
|
122
|
+
const totals = computeTotals(items, taxRate);
|
|
123
|
+
updates.subtotal = totals.subtotal;
|
|
124
|
+
updates.tax_amount = totals.tax_amount;
|
|
125
|
+
updates.total = totals.total;
|
|
126
|
+
}
|
|
127
|
+
if (patch.status === 'paid' && existing.status !== 'paid') {
|
|
128
|
+
updates.paid_at = new Date().toISOString();
|
|
129
|
+
updates.amount_paid = patch.items
|
|
130
|
+
? computeTotals(patch.items, patch.tax_rate ?? existing.tax_rate).total
|
|
131
|
+
: existing.total;
|
|
132
|
+
}
|
|
133
|
+
await updateById(TABLE, invoiceId, updates);
|
|
134
|
+
const next = await findById(TABLE, invoiceId);
|
|
135
|
+
return next ? toInvoice(next) : null;
|
|
136
|
+
}
|
|
137
|
+
/** Delete a user-owned invoice by ID, returning false if not found or not owned by the user. */
|
|
138
|
+
export async function deleteInvoiceForUser(invoiceId, userId) {
|
|
139
|
+
const row = await findById(TABLE, invoiceId);
|
|
140
|
+
if (!row || row.user_id !== userId)
|
|
141
|
+
return false;
|
|
142
|
+
await deleteById(TABLE, invoiceId);
|
|
143
|
+
return true;
|
|
144
|
+
}
|
|
145
|
+
/** Record a payment amount against an invoice, updating amount_paid and transitioning status to partial or paid. */
|
|
146
|
+
export async function recordPayment(invoiceId, userId, amount) {
|
|
147
|
+
const existing = await findById(TABLE, invoiceId);
|
|
148
|
+
if (!existing || existing.user_id !== userId)
|
|
149
|
+
return null;
|
|
150
|
+
// pg numerics arrive as strings — coerce before arithmetic or the addition
|
|
151
|
+
// string-concats ("0.00" + 42000 → "0.0042000") and the paid check compares
|
|
152
|
+
// strings lexicographically.
|
|
153
|
+
const newPaid = round2(Number(existing.amount_paid) + amount);
|
|
154
|
+
const isFullyPaid = newPaid >= Number(existing.total);
|
|
155
|
+
const updates = {
|
|
156
|
+
amount_paid: newPaid,
|
|
157
|
+
status: isFullyPaid ? 'paid' : 'partial',
|
|
158
|
+
};
|
|
159
|
+
if (isFullyPaid)
|
|
160
|
+
updates.paid_at = new Date().toISOString();
|
|
161
|
+
await updateById(TABLE, invoiceId, updates);
|
|
162
|
+
const next = await findById(TABLE, invoiceId);
|
|
163
|
+
return next ? toInvoice(next) : null;
|
|
164
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/** Lifecycle states an invoice can be in, from initial draft through payment or cancellation. */
|
|
2
|
+
export type InvoiceStatus = 'draft' | 'sent' | 'partial' | 'paid' | 'overdue' | 'void';
|
|
3
|
+
/** A single billable line on an invoice, with description, quantity, and unit price. */
|
|
4
|
+
export interface LineItem {
|
|
5
|
+
description: string;
|
|
6
|
+
quantity: number;
|
|
7
|
+
unit_price: number;
|
|
8
|
+
}
|
|
9
|
+
/** Raw database row shape for an invoice, with date fields typed as string or Date. */
|
|
10
|
+
export interface InvoiceRow {
|
|
11
|
+
id: string;
|
|
12
|
+
user_id: string;
|
|
13
|
+
client_id: string;
|
|
14
|
+
number: string;
|
|
15
|
+
status: InvoiceStatus;
|
|
16
|
+
items: LineItem[];
|
|
17
|
+
subtotal: number;
|
|
18
|
+
tax_rate: number;
|
|
19
|
+
tax_amount: number;
|
|
20
|
+
total: number;
|
|
21
|
+
amount_paid: number;
|
|
22
|
+
currency: string;
|
|
23
|
+
issue_date: string | Date;
|
|
24
|
+
due_date: string | Date | null;
|
|
25
|
+
paid_at: string | Date | null;
|
|
26
|
+
notes: string | null;
|
|
27
|
+
created_at: string | Date;
|
|
28
|
+
updated_at: string | Date;
|
|
29
|
+
}
|
|
30
|
+
/** Normalized invoice with all date fields serialized to ISO strings for API responses. */
|
|
31
|
+
export interface Invoice extends Omit<InvoiceRow, 'issue_date' | 'due_date' | 'paid_at' | 'created_at' | 'updated_at'> {
|
|
32
|
+
issue_date: string;
|
|
33
|
+
due_date: string | null;
|
|
34
|
+
paid_at: string | null;
|
|
35
|
+
created_at: string;
|
|
36
|
+
updated_at: string;
|
|
37
|
+
}
|
|
38
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,iGAAiG;AACjG,MAAM,MAAM,aAAa,GAAG,OAAO,GAAG,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,GAAG,MAAM,CAAA;AAEtF,wFAAwF;AACxF,MAAM,WAAW,QAAQ;IACvB,WAAW,EAAE,MAAM,CAAA;IACnB,QAAQ,EAAE,MAAM,CAAA;IAChB,UAAU,EAAE,MAAM,CAAA;CACnB;AAED,uFAAuF;AACvF,MAAM,WAAW,UAAU;IACzB,EAAE,EAAE,MAAM,CAAA;IACV,OAAO,EAAE,MAAM,CAAA;IACf,SAAS,EAAE,MAAM,CAAA;IACjB,MAAM,EAAE,MAAM,CAAA;IACd,MAAM,EAAE,aAAa,CAAA;IACrB,KAAK,EAAE,QAAQ,EAAE,CAAA;IACjB,QAAQ,EAAE,MAAM,CAAA;IAChB,QAAQ,EAAE,MAAM,CAAA;IAChB,UAAU,EAAE,MAAM,CAAA;IAClB,KAAK,EAAE,MAAM,CAAA;IACb,WAAW,EAAE,MAAM,CAAA;IACnB,QAAQ,EAAE,MAAM,CAAA;IAChB,UAAU,EAAE,MAAM,GAAG,IAAI,CAAA;IACzB,QAAQ,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,CAAA;IAC9B,OAAO,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,CAAA;IAC7B,KAAK,EAAE,MAAM,GAAG,IAAI,CAAA;IACpB,UAAU,EAAE,MAAM,GAAG,IAAI,CAAA;IACzB,UAAU,EAAE,MAAM,GAAG,IAAI,CAAA;CAC1B;AAED,2FAA2F;AAC3F,MAAM,WAAW,OAAQ,SAAQ,IAAI,CACnC,UAAU,EACV,YAAY,GAAG,UAAU,GAAG,SAAS,GAAG,YAAY,GAAG,YAAY,CACpE;IACC,UAAU,EAAE,MAAM,CAAA;IAClB,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAA;IACvB,OAAO,EAAE,MAAM,GAAG,IAAI,CAAA;IACtB,UAAU,EAAE,MAAM,CAAA;IAClB,UAAU,EAAE,MAAM,CAAA;CACnB"}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
/** All valid lifecycle statuses an invoice can hold. */
|
|
3
|
+
export declare const INVOICE_STATUSES: readonly ["draft", "sent", "partial", "paid", "overdue", "void"];
|
|
4
|
+
/** Zod schema for a single invoice line item (description, quantity, unit price). */
|
|
5
|
+
export declare const lineItemSchema: z.ZodObject<{
|
|
6
|
+
description: z.ZodString;
|
|
7
|
+
quantity: z.ZodNumber;
|
|
8
|
+
unit_price: z.ZodNumber;
|
|
9
|
+
}, z.core.$strip>;
|
|
10
|
+
/** Zod schema for creating a new invoice (client, items, optional due date / notes / tax / currency). */
|
|
11
|
+
export declare const invoiceCreateSchema: z.ZodObject<{
|
|
12
|
+
client_id: z.ZodString;
|
|
13
|
+
items: z.ZodArray<z.ZodObject<{
|
|
14
|
+
description: z.ZodString;
|
|
15
|
+
quantity: z.ZodNumber;
|
|
16
|
+
unit_price: z.ZodNumber;
|
|
17
|
+
}, z.core.$strip>>;
|
|
18
|
+
due_date: z.ZodOptional<z.ZodString>;
|
|
19
|
+
notes: z.ZodOptional<z.ZodString>;
|
|
20
|
+
tax_rate: z.ZodOptional<z.ZodNumber>;
|
|
21
|
+
currency: z.ZodOptional<z.ZodString>;
|
|
22
|
+
}, z.core.$strip>;
|
|
23
|
+
/** Zod schema for partially updating an existing invoice (all fields optional). */
|
|
24
|
+
export declare const invoiceUpdateSchema: z.ZodObject<{
|
|
25
|
+
items: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
26
|
+
description: z.ZodString;
|
|
27
|
+
quantity: z.ZodNumber;
|
|
28
|
+
unit_price: z.ZodNumber;
|
|
29
|
+
}, z.core.$strip>>>;
|
|
30
|
+
due_date: z.ZodOptional<z.ZodString>;
|
|
31
|
+
notes: z.ZodOptional<z.ZodString>;
|
|
32
|
+
tax_rate: z.ZodOptional<z.ZodNumber>;
|
|
33
|
+
currency: z.ZodOptional<z.ZodString>;
|
|
34
|
+
status: z.ZodOptional<z.ZodEnum<{
|
|
35
|
+
draft: "draft";
|
|
36
|
+
sent: "sent";
|
|
37
|
+
partial: "partial";
|
|
38
|
+
paid: "paid";
|
|
39
|
+
overdue: "overdue";
|
|
40
|
+
void: "void";
|
|
41
|
+
}>>;
|
|
42
|
+
}, z.core.$strip>;
|
|
43
|
+
/** Zod schema for recording a payment against an invoice (positive amount required). */
|
|
44
|
+
export declare const recordPaymentSchema: z.ZodObject<{
|
|
45
|
+
amount: z.ZodNumber;
|
|
46
|
+
}, z.core.$strip>;
|
|
47
|
+
//# sourceMappingURL=validation.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validation.d.ts","sourceRoot":"","sources":["../src/validation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAEvB,wDAAwD;AACxD,eAAO,MAAM,gBAAgB,kEAAmE,CAAA;AAEhG,qFAAqF;AACrF,eAAO,MAAM,cAAc;;;;iBAIzB,CAAA;AAEF,yGAAyG;AACzG,eAAO,MAAM,mBAAmB;;;;;;;;;;;iBAO9B,CAAA;AAEF,mFAAmF;AACnF,eAAO,MAAM,mBAAmB;;;;;;;;;;;;;;;;;;iBAO9B,CAAA;AAEF,wFAAwF;AACxF,eAAO,MAAM,mBAAmB;;iBAE9B,CAAA"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
/** All valid lifecycle statuses an invoice can hold. */
|
|
3
|
+
export const INVOICE_STATUSES = ['draft', 'sent', 'partial', 'paid', 'overdue', 'void'];
|
|
4
|
+
/** Zod schema for a single invoice line item (description, quantity, unit price). */
|
|
5
|
+
export const lineItemSchema = z.object({
|
|
6
|
+
description: z.string().min(1),
|
|
7
|
+
quantity: z.number().positive(),
|
|
8
|
+
unit_price: z.number().nonnegative(),
|
|
9
|
+
});
|
|
10
|
+
/** Zod schema for creating a new invoice (client, items, optional due date / notes / tax / currency). */
|
|
11
|
+
export const invoiceCreateSchema = z.object({
|
|
12
|
+
client_id: z.string().min(1),
|
|
13
|
+
items: z.array(lineItemSchema).min(1),
|
|
14
|
+
due_date: z.string().optional(),
|
|
15
|
+
notes: z.string().optional(),
|
|
16
|
+
tax_rate: z.number().min(0).max(100).optional(),
|
|
17
|
+
currency: z.string().min(3).max(8).optional(),
|
|
18
|
+
});
|
|
19
|
+
/** Zod schema for partially updating an existing invoice (all fields optional). */
|
|
20
|
+
export const invoiceUpdateSchema = z.object({
|
|
21
|
+
items: z.array(lineItemSchema).optional(),
|
|
22
|
+
due_date: z.string().optional(),
|
|
23
|
+
notes: z.string().optional(),
|
|
24
|
+
tax_rate: z.number().min(0).max(100).optional(),
|
|
25
|
+
currency: z.string().min(3).max(8).optional(),
|
|
26
|
+
status: z.enum(INVOICE_STATUSES).optional(),
|
|
27
|
+
});
|
|
28
|
+
/** Zod schema for recording a payment against an invoice (positive amount required). */
|
|
29
|
+
export const recordPaymentSchema = z.object({
|
|
30
|
+
amount: z.number().positive(),
|
|
31
|
+
});
|
package/package.json
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@molecule/api-resource-invoice",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Invoice CRUD + line items + draft/sent/paid/overdue status. Extracted from invoice-billing flagship.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"scripts": {
|
|
9
|
+
"build": "tsc",
|
|
10
|
+
"test": "vitest run",
|
|
11
|
+
"test:watch": "vitest"
|
|
12
|
+
},
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"types": "./dist/index.d.ts",
|
|
16
|
+
"import": "./dist/index.js"
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"dist"
|
|
21
|
+
],
|
|
22
|
+
"keywords": [
|
|
23
|
+
"molecule",
|
|
24
|
+
"invoice",
|
|
25
|
+
"billing",
|
|
26
|
+
"resource"
|
|
27
|
+
],
|
|
28
|
+
"license": "Apache-2.0",
|
|
29
|
+
"devDependencies": {
|
|
30
|
+
"@types/express": "5.0.6",
|
|
31
|
+
"@types/node": "26.1.2",
|
|
32
|
+
"express": "5.2.1",
|
|
33
|
+
"typescript": "6.0.3",
|
|
34
|
+
"vitest": "4.1.10",
|
|
35
|
+
"zod": "4.4.3"
|
|
36
|
+
},
|
|
37
|
+
"peerDependencies": {
|
|
38
|
+
"@molecule/api-bonds-default-express": "^1.0.0",
|
|
39
|
+
"@molecule/api-database": "^1.0.0",
|
|
40
|
+
"@molecule/api-i18n": "^1.0.0",
|
|
41
|
+
"@molecule/api-middleware-validation": "^1.0.0",
|
|
42
|
+
"express": "^5.0.0",
|
|
43
|
+
"zod": "^4.0.0"
|
|
44
|
+
}
|
|
45
|
+
}
|