Compare commits

..

133 Commits

Author SHA1 Message Date
Mihir Motiyani b4f61ff65e Merge pull request 'feat(catalog): add product photos' (#54) from feat/product-images into main
continuous-integration/drone/push Build is passing Details
Reviewed-on: #54
2026-11-26 13:11:17 +05:30
mihir 58d3f55b35 feat(catalog): add product photos
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/pr Build is passing Details
Staff with catalog.manage upload JPEG, PNG or WebP photos (2 MiB, 8 per
product, signature checked) and remove them. Published products serve
photos publicly from the storefront with one-day caching; storefront and
admin product views list photo IDs in upload order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 12:52:46 +05:30
Mihir Motiyani b81e8ddad2 Merge pull request 'feat(identity): add customer self-registration' (#53) from feat/customer-registration into main
continuous-integration/drone/push Build is passing Details
Reviewed-on: #53
2026-11-26 01:15:20 +05:30
mihir 38f58ee3b1 feat(identity): add customer self-registration
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/pr Build is passing Details
POST /auth/register creates an ACTIVE, role-less account in the given
organization and returns a session. Customers can use their own cart,
checkout, addresses, orders and wishlist, and nothing permissioned.
Throttled by the auth guard plus 10 registrations per IP per hour;
duplicates return 409. Email verification is not implemented yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 00:53:16 +05:30
Mihir Motiyani 1b7d7362de Merge pull request 'fix(security): rate-limit per client IP behind trusted proxies' (#52) from fix/client-ip-behind-proxy into main
continuous-integration/drone/push Build is passing Details
Reviewed-on: #52
2026-11-24 16:03:53 +05:30
mihir 74c129ba6c fix(security): rate-limit per client IP behind trusted proxies
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/pr Build is passing Details
- Add TRUST_PROXY (IPs, CIDRs or loopback/linklocal/uniquelocal; never
  "true") so request.ip uses X-Forwarded-For only from known hops.
  Without it every visitor shares the proxy's rate-limit bucket.
- Occasionally sweep long-expired rate_limits rows.
- Patch zod, nodemailer, multer, fast-uri and effect advisories; the
  production audit reports no known vulnerabilities.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 15:52:49 +05:30
Mihir Motiyani a229d6a657 Update .drone.yml
continuous-integration/drone/push Build is passing Details
2026-10-09 22:41:11 +05:30
Mihir Motiyani 29f0a2b7b8 Update .drone.yml
continuous-integration/drone/push Build is passing Details
2026-10-09 22:22:06 +05:30
Mihir Motiyani b610ef71f2 Merge pull request 'feat/production-readiness' (#51) from feat/production-readiness into main
continuous-integration/drone/push Build is failing Details
Reviewed-on: #51
2026-10-09 00:26:24 +05:30
mihir a83a0c0742 feat(ci): require native concurrency evidence and document release gates
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/pr Build is passing Details
2026-10-08 22:36:12 +05:30
mihir 04e7f1f9b6 fix(security): patch Express proxy trust subnet handling 2026-10-08 22:20:21 +05:30
Mihir Motiyani 6c72f8ce96 Merge pull request 'feat(workflows): add atomic audited order expiry sweeps' (#50) from feat/order-expiry-workflow into main
continuous-integration/drone/push Build is failing Details
Reviewed-on: #50
2026-10-08 22:13:43 +05:30
mihir e3ee5ef019 feat(workflows): add atomic audited order expiry sweeps
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/pr Build is passing Details
2026-10-08 22:12:43 +05:30
Mihir Motiyani 07966121fa Merge pull request 'feat/batch-contribution' (#49) from feat/batch-contribution into main
continuous-integration/drone/push Build is failing Details
Reviewed-on: #49
2026-10-08 22:10:45 +05:30
mihir 4c1af3262b Merge remote-tracking branch 'origin/main' into feat/batch-contribution
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/pr Build is passing Details
2026-10-08 22:09:04 +05:30
mihir 549f87f078 Merge branch 'feat/batch-contribution' of ssh://git.midastix.com:2212/internal/manicanldes-backend into feat/batch-contribution
continuous-integration/drone/push Build is passing Details
2026-10-08 22:04:14 +05:30
mihir 5f729571cb feat(profitability): add sealed batch contribution scenarios 2026-10-08 22:02:51 +05:30
mihir 83f2584133 feat(accounting): add scoped financial source event feed 2026-10-08 22:02:51 +05:30
mihir 6da3aaad19 feat(forecasts): add transparent capture-rate planning baseline 2026-10-08 22:02:51 +05:30
mihir 2e605262a9 feat(analytics): add bounded commerce activity reports 2026-10-08 22:02:51 +05:30
mihir 727968729c fix(database): enforce UTC for pooled connections 2026-10-08 22:02:51 +05:30
mihir 28af830548 feat(forum): add independently moderated threads and replies 2026-10-08 22:02:51 +05:30
mihir 0ec26dc532 feat(segments): add live consent-aware customer audiences 2026-10-08 22:02:51 +05:30
mihir fa0073e109 feat(blog): add reviewed publication snapshots and SEO metadata 2026-10-08 22:02:51 +05:30
mihir 779496cc15 feat(messaging): add explicit versioned consent and eligibility 2026-10-08 22:02:51 +05:30
mihir 0f4e73f06e feat(cart): add private idle cart recovery 2026-10-08 22:02:51 +05:30
mihir 7bcce6fe4d feat(discounts): apply campaign offers to eligible collection merchandise 2026-10-08 22:02:51 +05:30
mihir 9f12fc686e fix(test): use stored campaign dates for coupon window checks 2026-10-08 22:02:51 +05:30
mihir ceb881e30a feat(discounts): bind immutable coupons to versioned campaign drafts 2026-10-08 22:02:51 +05:30
mihir 8431fbca4b feat(discounts): define collection-only campaign discount policy 2026-10-08 22:02:51 +05:30
mihir c8cf3515ba feat(campaigns): publish versioned seasonal campaign windows 2026-10-08 22:02:51 +05:30
mihir fae73b38b0 feat(campaigns): add scoped versioned campaign drafts 2026-10-08 22:02:51 +05:30
mihir d60d5d79d0 feat(campaigns): define seasonal campaign schedule contracts 2026-10-08 22:02:51 +05:30
mihir 600bed2ada feat(reviews): add verified purchases and review moderation 2026-10-08 22:02:50 +05:30
mihir 5a8087b51a feat(wishlist): add private variant wishlists 2026-10-08 22:02:50 +05:30
mihir eb02a059b8 feat(b2b): add partner order and payment reports 2026-10-08 22:02:50 +05:30
mihir 16296e5e22 feat(b2b): add custom candle requests and independent review 2026-10-08 22:02:50 +05:30
mihir 93db8564a7 chore(graphify): add queryable backend source graph 2026-10-08 22:02:50 +05:30
mihir eb37578e1d feat(profitability): add sealed batch contribution scenarios
continuous-integration/drone/push Build is passing Details
2026-10-08 16:03:29 +05:30
Mihir Motiyani 7f1937dc54 Merge pull request 'feat(accounting): add scoped financial source event feed' (#48) from feat/accounting-source-feed into main
continuous-integration/drone/push Build is failing Details
Reviewed-on: #48
2026-10-08 12:01:51 +05:30
mihir 5ac4e20ccf feat(accounting): add scoped financial source event feed
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/pr Build is passing Details
2026-10-08 11:23:58 +05:30
Mihir Motiyani fa38e1f491 Merge pull request 'feat(forecasts): add transparent capture-rate planning baseline' (#47) from feat/capture-forecasts into main
continuous-integration/drone/push Build is failing Details
Reviewed-on: #47
2026-10-08 02:34:20 +05:30
mihir e30fdae2ea feat(forecasts): add transparent capture-rate planning baseline
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/pr Build is passing Details
2026-10-08 02:32:35 +05:30
Mihir Motiyani 26225c4b9e Merge pull request 'feat/commerce-analytics' (#46) from feat/commerce-analytics into main
continuous-integration/drone/push Build is failing Details
Reviewed-on: #46
2026-10-07 18:32:38 +05:30
mihir 490c3a0155 feat(analytics): add bounded commerce activity reports
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/pr Build is passing Details
2026-10-07 18:31:18 +05:30
mihir d9917b9ee1 fix(database): enforce UTC for pooled connections 2026-10-07 18:31:17 +05:30
Mihir Motiyani 0d3e219fd1 Merge pull request 'feat(forum): add independently moderated threads and replies' (#45) from feat/moderated-forums into main
continuous-integration/drone/push Build is failing Details
Reviewed-on: #45
2026-10-07 17:18:31 +05:30
mihir 8cefd212fd feat(forum): add independently moderated threads and replies
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/pr Build is passing Details
2026-10-07 17:16:32 +05:30
Mihir Motiyani 0a86e50de2 Merge pull request 'feat(segments): add live consent-aware customer audiences' (#44) from feat/customer-segmentation into main
continuous-integration/drone/push Build is failing Details
Reviewed-on: #44
2026-10-07 15:47:38 +05:30
mihir b88bb466b1 feat(segments): add live consent-aware customer audiences
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/pr Build is passing Details
2026-10-07 15:46:17 +05:30
Mihir Motiyani 866b10a0a4 Merge pull request 'feat(blog): add reviewed publication snapshots and SEO metadata' (#43) from feat/blog-publishing into main
continuous-integration/drone/push Build is failing Details
Reviewed-on: #43
2026-10-07 15:23:21 +05:30
mihir afcf32caa7 feat(blog): add reviewed publication snapshots and SEO metadata
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/pr Build is passing Details
2026-10-07 12:45:10 +05:30
Mihir Motiyani 282a6ee6f1 Merge pull request 'feat(messaging): add explicit versioned consent and eligibility' (#42) from feat/messaging-consent into main
continuous-integration/drone/push Build is failing Details
Reviewed-on: #42
2026-10-07 12:26:59 +05:30
mihir 0476cb82a1 feat(messaging): add explicit versioned consent and eligibility
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/pr Build is passing Details
2026-10-07 12:23:20 +05:30
Mihir Motiyani 44a9a30d35 Merge pull request 'feat(cart): add private idle cart recovery' (#41) from feat/cart-recovery into main
continuous-integration/drone/push Build is failing Details
Reviewed-on: #41
2026-10-07 12:06:56 +05:30
mihir de82fa1af6 feat(cart): add private idle cart recovery
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/pr Build is passing Details
2026-10-07 12:05:51 +05:30
Mihir Motiyani 6ac37fdea0 Merge pull request 'feat/campaign-discounts' (#40) from feat/campaign-discounts into main
continuous-integration/drone/push Build is failing Details
Reviewed-on: #40
2026-10-07 00:17:43 +05:30
mihir 94460eefa4 feat(discounts): apply campaign offers to eligible collection merchandise
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/pr Build is passing Details
2026-10-07 00:08:52 +05:30
mihir 5812578849 fix(test): use stored campaign dates for coupon window checks 2026-10-06 17:34:59 +05:30
mihir 42044e84f6 feat(discounts): bind immutable coupons to versioned campaign drafts 2026-10-06 17:28:39 +05:30
mihir ae23c497a2 feat(discounts): define collection-only campaign discount policy 2026-10-06 17:17:10 +05:30
Mihir Motiyani 55e00986bd Merge pull request 'feat/seasonal-campaigns' (#39) from feat/seasonal-campaigns into main
continuous-integration/drone/push Build is failing Details
Reviewed-on: #39
2026-10-06 17:08:36 +05:30
mihir af9c9150a5 feat(campaigns): publish versioned seasonal campaign windows
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/pr Build is passing Details
2026-10-06 16:59:44 +05:30
mihir 1dae07cc60 feat(campaigns): add scoped versioned campaign drafts 2026-10-06 12:21:37 +05:30
mihir a021d079ad feat(campaigns): define seasonal campaign schedule contracts 2026-10-06 12:13:02 +05:30
Mihir Motiyani 7849be8193 Merge pull request 'feat(reviews): add verified purchases and review moderation' (#38) from feat/verified-product-reviews into main
continuous-integration/drone/push Build is failing Details
Reviewed-on: #38
2026-10-05 10:37:20 +05:30
mihir 43aec1395c feat(reviews): add verified purchases and review moderation
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/pr Build is passing Details
2026-10-05 10:28:04 +05:30
Mihir Motiyani fcc30a069d Merge pull request 'feat(wishlist): add private variant wishlists' (#37) from feat/private-wishlists into main
continuous-integration/drone/push Build is failing Details
Reviewed-on: #37
2026-10-05 10:03:13 +05:30
mihir 213c1d8552 feat(wishlist): add private variant wishlists
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/pr Build is passing Details
2026-10-05 09:54:51 +05:30
Mihir Motiyani 990ffa4148 Merge pull request 'feat(b2b): add partner order and payment reports' (#36) from feat/b2b-partner-reporting into main
continuous-integration/drone/push Build is failing Details
Reviewed-on: #36
2026-10-04 11:40:14 +05:30
mihir 1e69d307f1 feat(b2b): add partner order and payment reports
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/pr Build is passing Details
2026-10-04 11:35:28 +05:30
Mihir Motiyani 424d9d0c56 Merge pull request 'feat(b2b): add custom candle requests and independent review' (#35) from feat/b2b-custom-candle-requests into main
continuous-integration/drone/push Build is failing Details
Reviewed-on: #35
2026-10-04 00:46:51 +05:30
mihir f96cb7a455 feat(b2b): add custom candle requests and independent review
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/pr Build is passing Details
2026-10-04 00:42:40 +05:30
Mihir Motiyani 9ca8c11bde Merge pull request 'chore(graphify): add queryable backend source graph' (#34) from chore/graphify-integration into main
continuous-integration/drone/push Build is failing Details
Reviewed-on: #34
2026-10-04 00:22:08 +05:30
mihir 2cfa6cc98c chore(graphify): add queryable backend source graph
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/pr Build is passing Details
2026-10-04 00:13:21 +05:30
Mihir Motiyani 131aef7958 Merge pull request 'feat/b2b-partial-payments' (#33) from feat/b2b-partial-payments into main
continuous-integration/drone/push Build is failing Details
Reviewed-on: #33
2026-10-03 23:56:34 +05:30
mihir 60ccbc92a1 feat(b2b): record partial partner order payments
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/pr Build is passing Details
2026-10-03 19:00:34 +05:30
mihir c00f93bb77 fix(format): ignore generated architecture artifacts 2026-10-03 18:41:22 +05:30
mihir 0400275db9 fix(test): limit Jest discovery to application sources 2026-10-03 18:40:15 +05:30
Mihir Motiyani 5a503c7520 Merge pull request 'feat(b2b): add partner purchase orders' (#32) from feat/b2b-partner-orders into main
continuous-integration/drone/push Build is failing Details
Reviewed-on: #32
2026-10-03 17:01:02 +05:30
mihir aca127aafe feat(b2b): add partner purchase orders
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/pr Build is passing Details
2026-10-03 16:59:30 +05:30
Mihir Motiyani dfc7da2dfe Merge pull request 'feat/b2b-artwork-approvals' (#31) from feat/b2b-artwork-approvals into main
continuous-integration/drone/push Build is failing Details
Reviewed-on: #31
2026-10-03 00:16:17 +05:30
mihir a5e450abce feat(b2b): add versioned artwork approvals
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/pr Build is passing Details
2026-10-03 00:14:04 +05:30
mihir 7c6035741a fix(ci): end Drone config with newline 2026-10-03 00:07:50 +05:30
Mihir Motiyani c4e4607a3b Merge pull request 'feat/b2b-sample-requests' (#30) from feat/b2b-sample-requests into main
continuous-integration/drone/push Build is failing Details
Reviewed-on: #30
2026-10-02 23:59:18 +05:30
mihir cbc89a001c Merge remote-tracking branch 'origin/main' into feat/b2b-sample-requests
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/pr Build is passing Details
2026-10-02 23:56:43 +05:30
hardik 4cad2c3cc4 Add Docker and Drone CI/CD deployment 2026-10-02 10:30:51 +05:30
mihir 9ea8f4ccc3 feat(b2b): add reviewed sample requests 2026-10-02 00:05:00 +05:30
Mihir Motiyani fcb8b5be6f Merge pull request 'feat(b2b): add reviewed credit policies' (#29) from feat/b2b-credit-policies into main
Reviewed-on: #29
2026-10-01 23:47:03 +05:30
mihir fd1b1f34f8 feat(b2b): add reviewed credit policies 2026-10-01 13:02:28 +05:30
Mihir Motiyani ccb8fcef2d Merge pull request 'feat/b2b-quotations' (#28) from feat/b2b-quotations into main
Reviewed-on: #28
2026-09-30 19:51:26 +05:30
mihir 11086f1fa2 fix(deps): patch fast-uri advisory and audit moderate issues 2026-09-30 19:37:55 +05:30
mihir a7f07d7325 feat(b2b): add immutable merchandise quotations 2026-09-30 19:30:02 +05:30
Mihir Motiyani 2a0d3ad394 Merge pull request 'feat(b2b): add partner price lists and minimum quantities' (#27) from feat/b2b-price-lists into main
Reviewed-on: #27
2026-09-30 01:41:09 +05:30
mihir 5908d68a9e feat(b2b): add partner price lists and minimum quantities 2026-09-30 01:39:29 +05:30
Mihir Motiyani 7577fb98f4 Merge pull request 'feat(b2b): add business profiles and manual verification' (#26) from feat/b2b-business-verification into main
Reviewed-on: #26
2026-09-30 01:13:32 +05:30
mihir 98b0a898f6 feat(b2b): add business profiles and manual verification 2026-09-30 01:11:59 +05:30
Mihir Motiyani 832baccf77 Merge pull request 'feat/material-stock-adjustments' (#25) from feat/material-stock-adjustments into main
Reviewed-on: #25
2026-09-30 00:52:13 +05:30
mihir 1947f2ffab fix(deps): patch Swagger js-yaml advisory 2026-09-30 00:50:47 +05:30
mihir de57022412 feat(inventory): add audited material stock adjustments 2026-09-30 00:50:28 +05:30
Mihir Motiyani 06ef0df5f5 Merge pull request 'feat(inventory): transfer material stock between warehouses' (#24) from feat/material-warehouse-transfers into main
Reviewed-on: #24
2026-09-30 00:35:01 +05:30
mihir 41e9b17bd1 feat(inventory): transfer material stock between warehouses 2026-09-30 00:33:21 +05:30
Mihir Motiyani 4d2a9556a1 Merge pull request 'feat(production): receive finished goods into warehouse stock' (#23) from feat/finished-goods-receipt into main
Reviewed-on: #23
2026-09-29 21:12:34 +05:30
mihir 2b448d22e3 feat(production): receive finished goods into warehouse stock 2026-09-29 20:51:49 +05:30
Mihir Motiyani 8405e15bd5 Merge pull request 'feat(production): post packaging use to warehouse stock' (#22) from feat/packaging-material-stock into main
Reviewed-on: #22
2026-09-29 20:12:02 +05:30
mihir 6651ed3f4e feat(production): post packaging use to warehouse stock 2026-09-29 20:09:37 +05:30
Mihir Motiyani 68e243d461 Merge pull request 'feat(production): post material usage to warehouse stock' (#21) from feat/production-material-stock into main
Reviewed-on: #21
2026-09-29 19:53:36 +05:30
mihir ede522a441 feat(production): post material usage to warehouse stock 2026-09-29 17:58:00 +05:30
Mihir Motiyani fe408ab3de Merge pull request 'feat(inventory): post QC receipts to warehouse material stock' (#20) from feat/material-warehouse-stock into main
Reviewed-on: #20
2026-09-29 17:29:50 +05:30
mihir 33692b0163 feat(inventory): post QC receipts to warehouse material stock 2026-09-29 17:28:17 +05:30
Mihir Motiyani d722d13020 Merge pull request 'feat(costing): snapshot completed batch material costs' (#19) from feat/batch-cost-snapshots into main
Reviewed-on: #19
2026-09-29 17:11:24 +05:30
mihir 37bcebaac3 feat(costing): snapshot completed batch material costs 2026-09-29 17:08:32 +05:30
Mihir Motiyani 0093c768c3 Merge pull request 'feat(costing): add versioned material rates and BOM estimates' (#18) from feat/material-costing into main
Reviewed-on: #18
2026-09-29 16:49:38 +05:30
mihir 307afdb510 feat(costing): add versioned material rates and BOM estimates 2026-09-29 16:47:13 +05:30
Mihir Motiyani 1586936ef3 Merge pull request 'feat/packaging-execution' (#17) from feat/packaging-execution into main
Reviewed-on: #17
2026-09-29 16:03:47 +05:30
mihir 6eca988664 fix(deps): update vulnerable mailer and upload packages 2026-09-29 12:41:07 +05:30
mihir a90b30df7c feat(production): record packaging execution for completed batches 2026-09-29 11:51:23 +05:30
Mihir Motiyani d726102435 Merge pull request 'feat(production): add independent packaging BOM revisions' (#16) from feat/packaging-bom into main
Reviewed-on: #16
2026-09-29 01:21:16 +05:30
mihir 9c5eb2eeea feat(production): add independent packaging BOM revisions 2026-09-29 01:18:37 +05:30
Mihir Motiyani fbbb888be8 Merge pull request 'feat(production): record material consumption and wastage' (#15) from feat/material-consumption into main
Reviewed-on: #15
2026-09-29 01:00:28 +05:30
mihir 76e7d416b0 feat(production): record material consumption and wastage 2026-09-29 00:58:02 +05:30
Mihir Motiyani f26766c62b Merge pull request 'feat/production-batches' (#14) from feat/production-batches into main
Reviewed-on: #14
2026-09-29 00:37:38 +05:30
mihir cc3fb9d62a fix(identity): restrict Windows local admin credential ACL 2026-09-29 00:35:20 +05:30
mihir d4aa7d5c79 feat(identity): prepare guarded local admin seed credentials 2026-09-29 00:30:48 +05:30
mihir c7e2160b10 feat(production): track batches against active BOM revisions 2026-09-29 00:30:05 +05:30
Mihir Motiyani cbb5df9496 Merge pull request 'feat/material-bom' (#13) from feat/material-bom into main
Reviewed-on: #13
2026-09-29 00:01:19 +05:30
mihir cbb53d74db fix(test): allow database setup time across integration suites 2026-09-28 21:26:14 +05:30
mihir f280df5dd0 feat(production): add versioned product bills of materials 2026-09-28 21:26:04 +05:30
Mihir Motiyani 643589180f Merge pull request 'feat(procurement): add private versioned supplier documents' (#12) from feat/private-documents into main
Reviewed-on: #12
2026-09-28 15:41:23 +05:30
mihir ba201e831c feat(procurement): add private versioned supplier documents 2026-09-28 15:40:13 +05:30
Mihir Motiyani f30d90e677 Merge pull request 'feat(procurement): record supplier payments and reversals' (#11) from feat/supplier-payments into main
Reviewed-on: #11
2026-09-28 15:16:13 +05:30
mihir 1be408bf4f feat(procurement): record supplier payments and reversals 2026-09-28 15:14:42 +05:30
Mihir Motiyani 6d570c722e Merge pull request 'feat(procurement): match supplier invoices to accepted receipts' (#10) from feat/supplier-invoices into main
Reviewed-on: #10
2026-09-28 14:56:16 +05:30
468 changed files with 130383 additions and 188 deletions

12
.dockerignore Normal file
View File

@ -0,0 +1,12 @@
node_modules
dist
.env
.env.*
!.env.example
.git
.gitignore
coverage
*.log
Dockerfile
docker-compose.yml

41
.drone.yml Normal file
View File

@ -0,0 +1,41 @@
kind: pipeline
type: docker
name: build-deploy
steps:
- name: Build Docker Image
image: plugins/docker
settings:
registry: git.midastix.com
repo: git.midastix.com/ci-docker-repo-user/manicandle-backend
username:
from_secret: docker_username
password:
from_secret: docker_password
tags:
- latest
when:
branch:
- main
event:
- push
- name: Deploy
image: appleboy/drone-ssh
settings:
host: manicandles-backend.midastix.com
username: manicandle-backend
key:
from_secret: server_ssh_pkey
port: 22
command_timeout: 3m
script:
- set -e
- echo "Deploying manicandle-backend"
- sudo -n /opt/deployable/manicandle-backend/docker/deploy.sh
- echo "Deployment completed"
when:
branch:
- main
event:
- push

View File

@ -14,5 +14,10 @@ RECOVERY_TTL_MINUTES=15
# RECOVERY_URL=https://shop.example.com/reset
DATABASE_POOL_SIZE=10
# Reverse proxies whose X-Forwarded-For is trusted for client IPs (rate limits).
# Comma-separated IPs, CIDRs, or loopback/linklocal/uniquelocal. Empty = trust none.
# Behind the local Nginx plus the frontend server's Nginx, list both hops, e.g.:
# TRUST_PROXY=loopback,172.17.0.0/16,<frontend server IP>
# Optional; defaults to true only in development.
# SWAGGER_ENABLED=true

View File

@ -7,27 +7,47 @@ on:
jobs:
quality:
runs-on: ubuntu-latest
container: node:24.15-bookworm
timeout-minutes: 30
env:
DATABASE_URL: postgresql://postgres:postgres@127.0.0.1:5432/postgres
TEST_DATABASE_URL: ''
steps:
- uses: https://github.com/actions/checkout@v4
- name: Install locked dependencies
run: npm install --global pnpm@11.19.0 && pnpm install --frozen-lockfile
- name: Audit production dependencies
run: pnpm security:audit
- name: Generate Prisma client
run: pnpm db:generate
- name: Validate embedded migration upgrade and schema drift
run: pnpm db:test
- name: Formatting, types, tooling, coverage and build
run: pnpm check
native-postgres:
runs-on: ubuntu-latest
container: node:24.15-bookworm
timeout-minutes: 15
services:
postgres:
image: postgres:17
env:
POSTGRES_USER: mani
POSTGRES_PASSWORD: ci_only_password
POSTGRES_PASSWORD: ${{ secrets.CI_POSTGRES_PASSWORD }}
POSTGRES_DB: mani_ci
options: >-
--health-cmd "pg_isready -U mani -d mani_ci"
--health-interval 5s --health-timeout 5s --health-retries 10
env:
DATABASE_URL: postgresql://mani:ci_only_password@postgres:5432/mani_ci
TEST_DATABASE_URL: postgresql://mani:ci_only_password@postgres:5432/mani_ci
DATABASE_URL: postgresql://mani:${{ secrets.CI_POSTGRES_PASSWORD }}@postgres:5432/mani_ci
TEST_DATABASE_URL: postgresql://mani:${{ secrets.CI_POSTGRES_PASSWORD }}@postgres:5432/mani_ci
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '24'
- run: npm install --global pnpm@11.19.0
- run: pnpm install --frozen-lockfile
- run: pnpm security:audit
- run: pnpm db:generate
- run: node scripts/verify-migrations.mjs
- run: pnpm check
- uses: https://github.com/actions/checkout@v4
- name: Install locked dependencies
run: npm install --global pnpm@11.19.0 && pnpm install --frozen-lockfile
- name: Generate Prisma client
run: pnpm db:generate
- name: Validate native migration upgrade and schema drift
run: node scripts/verify-migrations.mjs
- name: Require native concurrency tests without skips
run: pnpm test:native

1
.gitignore vendored
View File

@ -7,3 +7,4 @@ coverage/
src/generated/
*.log
.tmp/
graphify-out/

3
.gitmodules vendored Normal file
View File

@ -0,0 +1,3 @@
[submodule "tools/graphify"]
path = tools/graphify
url = https://github.com/Graphify-Labs/graphify.git

10
.graphifyignore Normal file
View File

@ -0,0 +1,10 @@
tools/
.archify/
.tmp/
graphify-out/
test/
prisma/migrations/
src/generated/
node_modules/
dist/
coverage/

View File

@ -3,3 +3,7 @@ src/generated
dist
coverage
node_modules
.tmp
.archify
tools
graphify-out

24
Dockerfile Normal file
View File

@ -0,0 +1,24 @@
FROM node:24.15-alpine
WORKDIR /app
RUN corepack enable && corepack prepare pnpm@11.19.0 --activate
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
COPY prisma ./prisma
COPY prisma.config.ts ./
RUN pnpm install --frozen-lockfile
COPY tsconfig.json tsconfig.build.json ./
COPY src ./src
RUN pnpm db:generate
RUN pnpm build
ENV NODE_ENV=production
ENV PORT=3000
EXPOSE 3000
CMD ["pnpm", "start"]

View File

@ -1,5 +1,7 @@
# Mani Candles backend
Explore the [Graphify code graph](docs/graphify.md) to trace source-level dependencies and open the interactive backend map.
Phase 1A provides the service foundation. Phase 1B adds staff account provisioning, authentication, sessions, recovery, configurable RBAC, and audit records. Phase 1C implements core commerce APIs.
## Setup
@ -35,8 +37,66 @@ Phase 1E provides a [provider-independent blueprint and test matrix](docs/phase1
Phase 2A adds organization-scoped [supplier and material master data](docs/procurement-api.md).
Phase 2B adds [purchase-order drafts and issuance](docs/purchase-orders-api.md).
Phase 2C adds [partial goods receipts and quality inspection](docs/goods-receipts-api.md).
Phase 2D adds [supplier invoice matching and voids](docs/supplier-invoices-api.md). Supplier payments, material stock movements, and production remain later milestones.
Phase 2D adds [supplier invoice matching and voids](docs/supplier-invoices-api.md).
Phase 2E adds [supplier payment records and reversals](docs/supplier-payments-api.md). Material stock movements and production remain later milestones.
Phase 2F adds [private versioned supplier documents and review](docs/supplier-documents-api.md).
Phase 2G adds [versioned product bills of materials](docs/bom-api.md).
Phase 2H adds [production batches](docs/production-batches-api.md).
Phase 2I adds [material consumption and wastage records](docs/material-usage-api.md).
Phase 2J adds [versioned packaging BOMs](docs/packaging-boms-api.md).
For a development owner, see [local admin setup](docs/local-admin.md).
### Swagger UI
Open http://localhost:3000/api/docs in development to browse and test the API. See [API explorer](docs/swagger.md) for authentication and configuration.
Packaging execution: see [Phase 2K API guide](docs/packaging-execution-api.md).
Cost estimates: see [Phase 2L API guide](docs/costing-api.md).
Batch cost snapshots: see [Phase 2M API guide](docs/batch-cost-api.md).
Warehouse material stock: see [Phase 2N API guide](docs/material-warehouse-stock-api.md).
Production material stock posting: see [Phase 2O API guide](docs/production-material-stock-api.md).
Packaging material stock posting: see [Phase 2P API guide](docs/packaging-material-stock-api.md).
Finished-goods receipts: see [Phase 2Q API guide](docs/finished-goods-receipt-api.md).
Material warehouse transfers: see [Phase 2R API guide](docs/material-transfers-api.md).
Manual material-stock adjustments: see [Phase 2S API guide](docs/material-adjustments-api.md).
Business-account profiles and manual verification: see [Phase 3A API guide](docs/b2b-business-verification-api.md).
Partner price lists and minimum quantities: see [Phase 3B API guide](docs/b2b-price-lists-api.md).
B2B quotations and response tracking: see [Phase 3C API guide](docs/b2b-quotations-api.md).
B2B credit proposals and independent review: see [Phase 3D API guide](docs/b2b-credit-policies-api.md).
B2B sample requests, review, and dispatch records: see [Phase 3E API guide](docs/b2b-samples-api.md).
B2B branding and artwork approvals: see [Phase 3F API guide](docs/b2b-artwork-api.md).
B2B partner purchase orders: see [Phase 3G API guide](docs/b2b-partner-orders-api.md).
B2B partner partial payments: see [Phase 3H API guide](docs/b2b-partner-payments-api.md).
B2B custom candle requests and staff review: see [Phase 3I API guide](docs/b2b-custom-candles-api.md).
B2B partner reports: see [Phase 3J API guide](docs/b2b-partner-reporting-api.md).
Private wishlists: see [Phase 4A API guide](docs/wishlist-api.md).
Verified product reviews and moderation: see [Phase 4B API guide](docs/product-reviews-api.md).
Seasonal campaigns and scheduled collection discovery: see [Phase 4C API guide](docs/seasonal-campaigns-api.md).
Campaign-linked collection discounts: see [Phase 4D API guide](docs/campaign-discounts-api.md).
Private idle cart recovery: see [Phase 4E API guide](docs/cart-recovery-api.md).
Explicit messaging consent and eligibility: see [Phase 4F API guide](docs/messaging-consent-api.md).
Blog drafts, publication and SEO metadata: see [Phase 4G API guide](docs/blog-publishing-api.md).
Live customer segments and consent-aware audience checks: see [Phase 4H API guide](docs/customer-segments-api.md).
Moderated community discussions: see [Phase 5A API guide](docs/forum-api.md).
Commerce activity analytics: see [Phase 5B API guide](docs/commerce-analytics-api.md).
Captured-request forecast baseline: see [Phase 5C API guide](docs/capture-forecasts-api.md).
Accounting source events: see [Phase 5D API guide](docs/accounting-source-feed-api.md).
Indicative batch material contribution: see [Phase 5E API guide](docs/batch-contribution-api.md).
Bounded order expiry automation: see [Phase 5F API guide](docs/order-expiry-workflow-api.md).
Production verification gates and launch procedure: see [Phase 6A runbook](docs/production-readiness.md).

View File

@ -0,0 +1,30 @@
# Accounting source feed (Phase 5D)
This provider-independent contract exposes recorded supplier invoices, supplier payments and corrections, plus external partner receipts and corrections. It supplies immutable source facts for future reconciliation/adapters. It does not assign a chart of accounts, generate journal debits/credits, post to an external system, or infer retail paid sales. Source records, source approvals, and their existing audit trail remain unchanged.
`GET /api/v1/accounting/source-events` requires `accounting.read`, rechecked against the live session and caller's organization in the read transaction. Existing system Owners gain the permission; custom roles must grant it explicitly. Other finance/analytics permissions do not implicitly grant access to this feed.
Required `from` and `to` reuse the bounded analytics datetime contract: explicit UTC/offsets, at most millisecond precision, supported normalized years, increasing by at most 366 elapsed days. Start is inclusive and end exclusive. Selection uses each source record's **recorded timestamp**, not its invoice/payment business date. Optional `currency` is a three-uppercase-letter filter, `kind` one of the six types below, and `limit` an integer 1–100 (default 25). Extra fields, offset pagination, invalid windows/types, and malformed/incompatible cursors return 400; absent sessions return 401 and insufficient permission 403.
| Event type | Operation | Amount and relationship |
| --------------------------- | --------- | -------------------------------------------------------------------------------------- |
| `SUPPLIER_INVOICE` | `RECORD` | Captured payable total, merchandise/tax/shipping components; invoice and supplier IDs. |
| `SUPPLIER_INVOICE_VOID` | `VOID` | Original captured invoice amounts; links to its original invoice event. |
| `SUPPLIER_PAYMENT` | `RECORD` | Captured external payment amount; related invoice and supplier IDs. |
| `SUPPLIER_PAYMENT_REVERSAL` | `REVERSE` | Original payment amount; links to that payment event. |
| `PARTNER_RECEIPT` | `RECORD` | Captured external partner receipt; related partner order and business-account IDs. |
| `PARTNER_RECEIPT_REVERSAL` | `REVERSE` | Original receipt amount; links to that receipt event. |
The response is `{ schemaVersion: 1, window, events, nextCursor }`. Each event contains `eventType`, `operation`, `sourceId`, `eventKey`, `occurredAt`, nullable `businessDate`, `currency`, positive two-decimal `amount`, nullable component amounts, `relatedId`/`relatedType`, `counterpartyId`/`counterpartyType`, and nullable `reversesEventKey`. `eventKey` is `<eventType>:<sourceId>`, unique within the organization. A correction can use the same source UUID under a different event type. Every original remains present after later void/reversal, so a consumer can process both original and correcting facts rather than silently losing history.
Invoice/payment/receipt business dates are copied from their source. Corrections have no separately recorded business date and return null; their recording timestamp and original-event link remain available. All amounts remain positive; `operation` expresses the source correction without assuming a provider's signed-value/debit/credit convention. Invoice tax/shipping are captured charges, not a tax treatment decision. Payment reversal records invalidate an external payment entry and are not proof of a bank refund. Currencies are retained separately, with no conversion or combined amount.
Results are ordered by recorded timestamp, event type using deterministic C collation, then UUID. Fetch the next page by sending the returned opaque `cursor` with the same organization/window/currency/type; page size may change. The token validates a timestamp/type/UUID position and a filter/scope fingerprint. It is a pagination hint, not an authorization credential; every query independently enforces caller scope. `limit + 1` lookahead determines whether another cursor is needed. Missing/empty pages return `nextCursor: null`, and tied timestamps remain traversable by type/UUID.
**Synchronization limit:** pages are independent live database snapshots, not a durable change-data-capture stream or exactly-once export. A transaction committed later can have an earlier recording timestamp and arrive behind a consumed cursor. Consumers must repeatedly scan overlapping closed windows and deduplicate by `(organization, eventKey)`, including correction events, before advancing their own reconciliation checkpoint. Do not treat the last page as certification that a period can never gain a late record. Persistent export batches/acknowledgements can follow when a concrete accounting provider and delivery guarantees are selected.
The feed omits invoice numbers, bank/payment references, methods, contact/profile/address data, staff reasons/IDs, evidence files, hashes, and request keys. Stable technical document/counterparty IDs allow explicit external mappings later. Only recorded supplier liabilities and external receipt/payment facts are included; retail pending orders, quotes, production estimates and unfinalized tax/shipping are not invented as accounting entries.
One parameterized UNION query supplies each page's snapshot without taking the organization write lock. Scoped joins protect every correction/original relationship. Six additive source timestamp indexes support bounded scans; no export table, queue, provider credential, CSV conversion, or new dependency is introduced. Deploy the indexes/Owner-permission migration before the application, scheduling index builds appropriately for large source tables. Older code ignores them on rollback. Preserve financial records, corrections and audit evidence; historical migrations are not edited.
Verification covers all six source types, original/correction coexistence, exact positive amounts/components, original-event links, recording-time boundaries versus business dates, deterministic tie pagination, filter/scope-bound cursors, malformed tokens, private-field omission, permission/organization isolation, strict limits, and migration drift. External ledger posting, chart-of-account/tax mapping, durable synchronization and native multi-connection PostgreSQL CI remain outside this milestone.

19
docs/b2b-artwork-api.md Normal file
View File

@ -0,0 +1,19 @@
# B2B branding and artwork approvals (Phase 3F)
Staff can create an artwork project for a verified business account, upload private versions, and review the latest version independently. All endpoints use a bearer session under `/api/v1/b2b`. Records and decisions are organization-scoped and immutable.
| Method | Path | Permission | Purpose |
| ------ | -------------------------------- | -------------------- | ------------------------------------------------------ |
| GET | `/artworks` | `b2b.artwork.read` | List projects; optional `accountId`, `limit`, `offset` |
| POST | `/artworks` | `b2b.artwork.manage` | Create a project |
| GET | `/artworks/:id` | `b2b.artwork.read` | Read project and version metadata |
| POST | `/artworks/:id/versions` | `b2b.artwork.manage` | Upload the next private version |
| GET | `/artwork-versions/:id` | `b2b.artwork.read` | Read version metadata and decision |
| GET | `/artwork-versions/:id/download` | `b2b.artwork.read` | Download allowed version |
| POST | `/artwork-versions/:id/decision` | `b2b.artwork.review` | Approve or reject latest version |
Create a project with `{ "accountId": "<uuid>", "name": "Seasonal gift branding", "placement": "PACKAGING", "brief": "Use the supplied mark on a matte kraft box" }`. Placement is `LABEL`, `PACKAGING`, `CANDLE`, or `OTHER`. Upload a file in multipart field `file`. Supported attachments are PDF, PNG, and JPEG, up to 2 MiB, with a safe filename and content signature matching the declared media type. File bytes live in PostgreSQL; metadata responses never include them. Downloads are attachments with `nosniff`, sandbox CSP, and `no-store` headers.
Review with `{ "outcome": "APPROVED", "note": "Brand mark is legible" }` or `REJECTED` and a concrete note. The uploader cannot review their own version. Approval rechecks business verification. Only the newest version may be reviewed, and a new version can be uploaded only after the previous one receives a decision. The version limit is 20 per project; each account may have up to 100 projects. A reader can download an approved version. A reviewer or the uploader can download pending or rejected versions for work and review. A later approved version does not mutate earlier approvals; downstream production must reference a specific approved version ID.
This approval covers the submitted file only. It does not establish trademark rights, clear third-party content, run malware scanning, reserve inventory, or authorize production. Production integration must verify the selected version has an `APPROVED` decision and must pin its immutable version ID and digest. Set a retention and malware-scanning policy before accepting untrusted artwork in production.

View File

@ -0,0 +1,21 @@
# B2B business verification (Phase 3A)
Business accounts belong to a merchant organization. Staff manage profiles and manually review submissions. A business account is not a staff user or a separate tenant. A decision records a staff attestation based on the submitted details; this phase does not check a government registry or collect evidence documents.
All routes require a bearer session and are available in Swagger UI under `/api/v1/b2b/accounts`.
| Method | Route | Permission | Purpose |
| ------ | ----------------------------------- | ------------ | ------------------------------------------------------------ |
| GET | `/api/v1/b2b/accounts` | `b2b.read` | List profiles, with `limit`, `offset`, and optional `search` |
| POST | `/api/v1/b2b/accounts` | `b2b.manage` | Create a draft profile |
| GET | `/api/v1/b2b/accounts/:id` | `b2b.read` | Read a profile and its current state |
| PATCH | `/api/v1/b2b/accounts/:id` | `b2b.manage` | Update draft or rejected profile fields |
| GET | `/api/v1/b2b/accounts/:id/events` | `b2b.read` | Read immutable review history |
| POST | `/api/v1/b2b/accounts/:id/submit` | `b2b.manage` | Submit a profile snapshot for review |
| POST | `/api/v1/b2b/accounts/:id/decision` | `b2b.verify` | Approve or reject a pending submission |
Create requires `code`, `legalName`, `tradingName` (nullable), `registrationNumber`, `taxIdentifier` (nullable), `countryCode`, `contactEmail`, `contactPhone` (nullable), `billingLine1`, `billingCity`, `billingRegion`, and `billingPostalCode`. Codes and country codes normalize to uppercase; email normalizes to lowercase. The code cannot change after creation. Country plus registration number is unique within an organization.
Submit takes `{ "idempotencyKey": "<UUID>" }`. Decision takes `{ "decision": "APPROVED", "note": "Registry details checked", "idempotencyKey": "<UUID>" }`, where decision can also be `REJECTED`. A different staff user must decide than the one who submitted. The states are `DRAFT → PENDING → VERIFIED`, or `PENDING → REJECTED → PENDING` after correction and resubmission. A submitted or verified profile cannot be edited. Each submission stores a fixed profile snapshot and each decision stores its reviewer and note. Repeating an identical command with the same key returns the original event; reusing the key for different content returns a conflict.
Apply migrations with `pnpm db:deploy` before starting the updated API. Existing system Owner roles gain the three B2B permissions through the migration; custom roles must be granted them explicitly.

View File

@ -0,0 +1,30 @@
# B2B credit policies (Phase 3D)
All endpoints are under `/api/v1/b2b/credit-policies` and require a bearer session. Policies belong to the caller's organization. The proposal and event history are append-only; a policy has at most one approval or rejection and, if approved, one later suspension.
| Method | Path | Permission | Purpose |
| ------ | --------------- | -------------------- | ---------------------------------------------------------------- |
| GET | `/` | `b2b.credit.read` | List policies; optional `accountId`, `status`, `limit`, `offset` |
| GET | `/:id` | `b2b.credit.read` | Read one policy and its ordered decision events |
| POST | `/` | `b2b.credit.propose` | Propose terms for a verified business account |
| POST | `/:id/decision` | `b2b.credit.review` | Approve or reject a proposal |
| POST | `/:id/suspend` | `b2b.credit.review` | Suspend an active policy |
Proposal example:
```json
{
"accountId": "b92c23e5-794d-47e7-a7f4-428b84543fa1",
"currency": "INR",
"creditLimit": "10000.00",
"netDays": 30,
"rationale": "Established wholesale customer",
"idempotencyKey": "10fc5585-34a6-4ead-b5ce-d83418eb50df"
}
```
`creditLimit` is a positive decimal string with exactly two fractional digits and at most fourteen integer digits; `netDays` is 1–180. Review body: `{ "decision": "APPROVED", "note": "Reviewed account documents", "idempotencyKey": "..." }` (or `REJECTED`). Suspension body: `{ "note": "Temporary credit hold", "idempotencyKey": "..." }`. Each key is a UUID, unique within the organization. Reusing it with different content returns 409. Retrying an identical request returns the policy's current representation.
The proposer cannot review their own terms. Approval rechecks business verification and allows only one active policy per account and currency. The database enforces immutable terms, transition and event sequencing, and the active-policy uniqueness constraint. API errors have distinct codes/messages for unverified accounts, self-review, state conflicts, active overlap, replay conflicts, and scoped not-found responses.
This phase records approved limits and payment terms. It does **not** grant credit at checkout or track utilization, balances, payments, delinquency, or holds against orders. Those require a separate B2B order and receivables workflow. Do not interpret `ACTIVE` as permission to bypass the existing checkout payment boundary.

View File

@ -0,0 +1,34 @@
# B2B custom candle requests (Phase 3I)
Staff capture requests for verified business accounts under `/api/v1/b2b/custom-candles`. All endpoints require a bearer session and are scoped to its organization.
| Method | Path | Permission | Purpose |
| ------ | --------------- | -------------------- | ----------------------------------------------------------- |
| GET | `/` | `b2b.custom.read` | List with optional `accountId`, `status`, `limit`, `offset` |
| GET | `/:id` | `b2b.custom.read` | Read specifications and decision |
| POST | `/` | `b2b.custom.request` | Capture immutable specifications |
| POST | `/:id/decision` | `b2b.custom.review` | Independently approve or reject |
Request example:
```json
{
"accountId": "b92c23e5-794d-47e7-a7f4-428b84543fa1",
"quantity": 500,
"waxType": "Soy",
"fragrance": "Rose",
"container": "Glass jar, 200g fill",
"color": "Ivory",
"brandingRequirements": "Printed logo label",
"specifications": "Cotton wick; individual gift boxes",
"idempotencyKey": "10fc5585-34a6-4ead-b5ce-d83418eb50df"
}
```
Quantity must be an integer from 1 to 1,000,000. Wax type and color allow 100 characters; fragrance and container 160; branding requirements 1,000; specifications 2,000 (minimum three). Text is trimmed and required; use `None` or `Unscented` where appropriate. Unknown fields are rejected.
Decision body: `{ "decision": "APPROVED", "note": "Feasibility reviewed", "idempotencyKey": "<uuid>" }`, or `REJECTED`. Notes require 3–1,000 characters. The requester cannot review their own request. Approval rechecks business verification. Each request permits one decision, enforced by a unique constraint; request and decision updates/deletes are blocked by database triggers.
Responses include the decision (initially null) and computed `status`: `REQUESTED`, `APPROVED`, or `REJECTED`. Request and decision idempotency keys each have their own organization-scoped namespace. Identical retries return the current representation; different content using the same key returns 409. Unauthorized commands return 403, out-of-scope resources 404, unverified accounts and repeat decisions 409. Audit events record request capture and the decision in the same transaction.
Approval means staff accepted the specifications for further commercial work. It creates no quotation, price, order, credit exposure, BOM, stock reservation, production batch, or artwork approval. Revised specifications require a new request and review. Existing system Owner roles receive permissions through the migration; custom roles require explicit grants through RBAC.

View File

@ -0,0 +1,27 @@
# B2B partner purchase orders (Phase 3G)
All endpoints are under `/api/v1/b2b/partner-orders` and require a bearer session. Staff record a partner purchase order only from an **accepted, unexpired** quotation for a verified business account. The order copies the quotation's account profile snapshot, currency, merchandise total, and every line's variant, SKU, name, quantity, minimum quantity, unit price, and line total. Those records are immutable.
| Method | Path | Permission | Purpose |
| ------ | ------------- | ------------------ | --------------------------------------------- |
| GET | `/` | `b2b.order.read` | List; optional `accountId`, `limit`, `offset` |
| GET | `/:id` | `b2b.order.read` | Read order, lines, and cancellation |
| POST | `/` | `b2b.order.manage` | Record purchase order from a quote |
| POST | `/:id/cancel` | `b2b.order.manage` | Record one reasoned cancellation |
Create example:
```json
{
"quoteId": "b92c23e5-794d-47e7-a7f4-428b84543fa1",
"partnerReference": "CUSTOMER-PO-123",
"note": "Requested by purchasing team",
"idempotencyKey": "10fc5585-34a6-4ead-b5ce-d83418eb50df"
}
```
The partner reference is required and unique within the business account; `note` may be omitted or null. One quotation can produce only one order. An identical retry returns the existing order, while reuse of an idempotency key for different content returns a distinct 409 error. A cancellation body is `{ "reason": "Partner withdrew purchase order", "idempotencyKey": "<uuid>" }`. Cancellation is append-only and changes the computed response status from `RECEIVED` to `CANCELLED`; an identical retry returns the current order.
These are **merchandise-only** purchase-order records. Recording one does not reserve inventory, schedule production or delivery, calculate tax or shipping, charge a payment method, or draw on a credit policy. The order number and its snapshot can be used as stable inputs to later fulfillment and receivables workflows. Those workflows must explicitly validate a non-cancelled order and define their own financial and stock transitions.
Phase 3H adds [manual partial payment records](b2b-partner-payments-api.md). Cancellation now requires reversing any active receipt first.

View File

@ -0,0 +1,28 @@
# B2B partner partial payments (Phase 3H)
Staff can record externally received payments against a partner purchase order. The order's frozen `merchandiseTotal` and `currency` are the balance basis. These are manual receipt records: this API does not call a gateway, capture money, issue tax invoices, calculate shipping, or consume credit. Staff must verify the external receipt before recording it. A reversal corrects an erroneous record; it does not send a refund.
All paths are under `/api/v1/b2b/partner-orders/:orderId/payments` and require a bearer session. Access is organization scoped.
| Method | Suffix | Permission | Purpose |
| ------ | --------------------- | -------------------- | ---------------------------------------------------------------------------- |
| GET | `/` | `b2b.payment.read` | List records and exact paid/outstanding totals; accepts `limit` and `offset` |
| GET | `/:paymentId` | `b2b.payment.read` | Read one record and its optional reversal |
| POST | `/` | `b2b.payment.manage` | Record an external receipt |
| POST | `/:paymentId/reverse` | `b2b.payment.manage` | Append one reasoned reversal |
Example receipt:
```json
{
"idempotencyKey": "901a9906-cec5-4eaa-b6d5-d6ac7e23c6d2",
"reference": "UTR-123456",
"method": "BANK_TRANSFER",
"amount": "100.25",
"receivedOn": "2026-10-03"
}
```
`amount` must be positive, have exactly two decimal places, and fit the remaining order balance. Methods are `BANK_TRANSFER`, `UPI`, `CHEQUE`, `CASH`, or `OTHER`. The server normalizes the reference to uppercase and requires it to be unique across the organization, including reversed records. A retry with the same key and payload returns the original record; a changed payload returns a specific 409 error. The list reports `merchandiseTotal`, `paidTotal`, and `outstandingTotal` as two-decimal strings and includes reversed records for audit, but excludes their amounts from the paid total.
To reverse, send `{ "reason": "Recorded against the wrong bank entry", "idempotencyKey": "<uuid>" }`. Reversals are append-only and idempotent. An order with an active receipt cannot be cancelled; reverse all receipts first. A cancelled order cannot accept new receipts. Database guards enforce these balance and cancellation rules even for writes outside the API. Credit exposure, refunds, fulfillment, tax, and freight remain separate milestones.

View File

@ -0,0 +1,23 @@
# B2B partner reporting (Phase 3J)
`GET /api/v1/b2b/accounts/:id/report` requires a bearer session and the dedicated `b2b.report.read` permission. The account must belong to the caller's organization; missing or out-of-scope accounts return 404. A report is available even when an account has no orders or is not verified, so staff can inspect its history.
The response contains `accountId` and a `currencies` array sorted by currency code. Each currency contains:
| Field | Meaning |
| ------------------------- | --------------------------------------------------------- |
| `orderCount` | All partner orders, including cancelled orders |
| `activeOrderCount` | Orders without cancellation |
| `cancelledOrderCount` | Orders with a recorded cancellation |
| `unpaidOrderCount` | Active orders with no unreversed receipts |
| `partiallyPaidOrderCount` | Active orders paid above zero but below merchandise total |
| `paidOrderCount` | Active orders with merchandise fully paid |
| `merchandiseTotal` | Total merchandise value of active orders |
| `paidTotal` | Unreversed receipts against active orders |
| `outstandingTotal` | Active merchandise value minus unreversed receipts |
All amounts are exact decimal strings with two fractional digits. Different currencies are never combined or converted. Each order contributes once regardless of how many receipts it has. Reversals restore outstanding balances; cancelled orders retain their counts but contribute no financial totals. An account with no orders returns `{ "accountId": "<uuid>", "currencies": [] }`.
Reports cover all recorded history. A repeatable-read transaction provides a consistent account lookup and aggregate. Reads create no audit events and change no order/payment records. This is a merchandise-balance report; it does not establish credit utilization, overdue status, tax, shipping, refunds, gateway settlement, or accounting receivables.
The permission migration grants access to existing system Owner roles. Custom roles need an explicit RBAC grant. No schema, provider, or configuration change is required beyond deploying the append-only permission migration. Removing a custom role's report permission disables access; financial records remain intact.

View File

@ -0,0 +1,20 @@
# B2B partner price lists and minimum quantities (Phase 3B)
Staff create organization-scoped price lists for a business account. A draft can be edited; activating it requires a verified account, at least one eligible variant, and no other active list for the same account and currency. Active and archived terms cannot be changed. Archive the current list before activating its replacement.
| Method | Route | Permission | Purpose |
| ------ | ---------------------------------------------- | ------------------ | ---------------------------------------------------------------------- |
| GET | `/api/v1/b2b/accounts/:accountId/price-lists` | `b2b.price.read` | List the account's lists with `limit`, `offset`, and optional `status` |
| POST | `/api/v1/b2b/accounts/:accountId/price-lists` | `b2b.price.manage` | Create a draft with `name` and `currency` |
| GET | `/api/v1/b2b/price-lists/:id` | `b2b.price.read` | Read the list and its variant terms |
| PUT | `/api/v1/b2b/price-lists/:id/items/:variantId` | `b2b.price.manage` | Set draft `unitPrice` and `minQuantity` |
| DELETE | `/api/v1/b2b/price-lists/:id/items/:variantId` | `b2b.price.manage` | Remove a draft item |
| POST | `/api/v1/b2b/price-lists/:id/activate` | `b2b.price.manage` | Freeze and activate the list |
| POST | `/api/v1/b2b/price-lists/:id/archive` | `b2b.price.manage` | Retire the active list |
| POST | `/api/v1/b2b/price-lists/:id/price-check` | `b2b.price.read` | Check quantities and preview merchandise total |
Supported currencies are INR, USD, EUR, and GBP. `unitPrice` is a positive decimal string with exactly two fractional digits; `minQuantity` is an integer from 1 to 1,000,000. A variant must be active, belong to a published product in the same organization, and use the list currency. A price check takes `{ "lines": [{ "variantId": "<UUID>", "quantity": 12 }] }` with 1–100 distinct variants. It returns each unit price, minimum, line total, currency, and merchandise total. The check revalidates variant eligibility even after activation.
This merchandise preview excludes stock, discounts, tax, shipping, credit, and payment terms. It does not create a quotation or order. Those rules belong to later B2B phases and must snapshot the selected terms before an order can use them. Existing retail checkout prices are unchanged.
Run `pnpm db:deploy` before starting the updated API. The migration grants `b2b.price.read` and `b2b.price.manage` to existing system Owner roles; grant custom roles explicitly.

View File

@ -0,0 +1,16 @@
# B2B quotations (Phase 3C)
Staff issue quotations to verified business accounts using an active account-specific price list. Issuance saves the account profile, price-list name, variant SKU and name, unit prices, MOQs, quantities, and merchandise total as immutable snapshots. An archived price list or later catalog price change cannot alter an issued quote.
| Method | Route | Permission | Purpose |
| ------ | --------------------------------- | ------------------ | ------------------------------------------------------------------- |
| GET | `/api/v1/b2b/quotes` | `b2b.quote.read` | List scoped quotes with `limit`, `offset`, and optional `accountId` |
| POST | `/api/v1/b2b/quotes` | `b2b.quote.manage` | Issue a quotation |
| GET | `/api/v1/b2b/quotes/:id` | `b2b.quote.read` | Read the full snapshot and response |
| POST | `/api/v1/b2b/quotes/:id/response` | `b2b.quote.manage` | Record customer acceptance, decline, or staff withdrawal |
Issue with `accountId`, `priceListId`, `expiresAt` (RFC 3339 with timezone, within the next 90 days), optional `customerReference`, 1–100 distinct `lines` of `{ "variantId": "<UUID>", "quantity": 12 }`, and `idempotencyKey` (UUID). Every quantity must meet its price-list MOQ. The response includes an opaque `BQ-...` quotation number, currency, fixed two-decimal merchandise total, account snapshot, and line snapshots. Repeating the same request and key returns the original quotation even if its price list has since been archived; changing the request with the same key returns a conflict.
A new quotation has status `ISSUED`, or `EXPIRED` once its deadline passes without a response. Recording `{ "kind": "ACCEPTED", "note": "Customer accepted by email", "idempotencyKey": "<UUID>" }` changes the displayed status to `ACCEPTED`. `DECLINED` and `WITHDRAWN` are also available. Staff must record a note identifying the basis for the response. Only one response is allowed, and it must be recorded before expiry. Responses are immutable and support idempotent retries.
This is a merchandise-only quotation. It excludes tax, shipping, stock reservation, payment, and credit terms, and `ACCEPTED` does not create an order. Staff should communicate those limits before seeking acceptance; B2B order conversion belongs to a later phase. Apply the timestamped migration with `pnpm db:deploy`. Existing system Owner roles gain the quotation permissions; custom roles must be granted them explicitly.

29
docs/b2b-samples-api.md Normal file
View File

@ -0,0 +1,29 @@
# B2B sample requests (Phase 3E)
All endpoints are under `/api/v1/b2b/samples` and require a bearer session. Every request is scoped to the caller's organization. Request fields and event history are immutable; status changes are checked in the database.
| Method | Path | Permission | Purpose |
| ------ | --------------- | --------------------- | ------------------------------------------------------- |
| GET | `/` | `b2b.sample.read` | List; optional `accountId`, `status`, `limit`, `offset` |
| GET | `/:id` | `b2b.sample.read` | Read request and ordered events |
| POST | `/` | `b2b.sample.request` | Request samples for a verified business account |
| POST | `/:id/decision` | `b2b.sample.review` | Approve or reject, by a different staff member |
| POST | `/:id/dispatch` | `b2b.sample.dispatch` | Record manual dispatch of an approved request |
Request body example:
```json
{
"accountId": "b92c23e5-794d-47e7-a7f4-428b84543fa1",
"variantId": "842b4658-2c2c-4626-8feb-1842ecf8726a",
"quantity": 4,
"purpose": "Fragrance evaluation",
"idempotencyKey": "10fc5585-34a6-4ead-b5ce-d83418eb50df"
}
```
Quantity is 1–100. The variant must be active and its product published. The request stores the variant SKU and name at creation. A decision body contains `decision` (`APPROVED` or `REJECTED`), `note`, and `idempotencyKey`. An approval rechecks business verification. A dispatch body contains `dispatchReference`, `note`, and `idempotencyKey`. Notes and purpose require 3–500 characters; dispatch reference requires 3–100 characters.
The lifecycle is `REQUESTED → APPROVED → DISPATCHED` or `REQUESTED → REJECTED`. Duplicate requests with the same key and payload return the current request; a changed payload returns a distinct 409 error. Event retries work the same way. The event response includes actor, time, and dispatch reference where applicable. Authorization and tenant boundaries apply to reads as well as writes.
`DISPATCHED` is a staff-recorded dispatch claim. This phase does not reserve or deduct stock, purchase postage, verify carrier delivery, or bill the partner. Those steps require later inventory/shipping and receivables integration. Operators should only record dispatch after a real handoff.

View File

@ -0,0 +1,30 @@
# Indicative batch contribution (Phase 5E)
Staff can compare a completed batch's sealed standard material/packaging cost with an explicit net unit-price assumption. The report reuses immutable actual-consumption/wastage and packaging cost evidence from Phase 2M, including frozen standard rate revisions. It does not infer costs from current catalog prices, pending orders, or unrelated batches.
`GET /api/v1/profitability/batches/:batchId?currency=INR&unitNetPrice=5.00` requires `profitability.read`. The active session, user/organization scope, and permission are rechecked inside the read transaction. `cost.read` alone does not grant access, and a profitability-only reader can see this summary without receiving detailed material/rate evidence. Existing system Owners gain the new permission; custom roles remain explicit.
Both query fields are required. Currency uses the existing supported currency set and must match the sealed snapshot; there is no FX conversion. `unitNetPrice` is a nonnegative two-decimal string up to `9999999999.99`, interpreted as a staff-selected selling-price assumption after discounts and excluding selling taxes/freight charges. No price is taken automatically from the catalog or an order. Negative, imprecise, oversized, missing, or extra fields return 400. Missing sessions return 401, insufficient permission 403, and currency mismatch `PROFITABILITY_CURRENCY` (409).
Only a sealed cost snapshot attached to a completed batch in the caller's organization is eligible. Missing, unsealed, unknown and foreign-scope evidence returns `BATCH_COST_NOT_FOUND` (404). Snapshot creation stays in the existing cost workflow; this read does not seal, recost, or rewrite any batch. The scoped response includes batch/variant/snapshot IDs, seal date, currency, good output quantity, explicit price, production/packaging subtotals, and `basis: "SEALED_BATCH_STANDARD_MATERIAL_COST"`.
The returned calculations are:
| Field | Definition |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `comparisonNetValue` | Price assumption multiplied by all good units. |
| `standardMaterialCost` | Sealed production plus packaging material total, including recorded wastage. |
| `materialContribution` | Comparison value minus sealed material cost; negative amounts are retained. |
| `contributionRateBps` | Contribution/value × 10,000, nearest integer with half away from zero; signed integer string, or null when comparison value is zero. |
| `breakEvenUnitNetPrice` | Sealed cost divided by good units, rounded **up** to a whole cent; null when no good units exist. |
| `comparisonState` | `ABOVE_MATERIAL_BREAK_EVEN`, `AT_MATERIAL_BREAK_EVEN`, `BELOW_MATERIAL_BREAK_EVEN`, or `NO_GOOD_OUTPUT`. |
Money uses exact integer cents and two-decimal strings. Scenario totals can exceed the per-order money limit without floating-point loss. Basis-point rates use strings so large negative values remain exact. A zero-price scenario returns the signed material shortfall and null rate. A batch with zero good output returns zero comparison value, negative captured material cost, null break-even/rate, and `NO_GOOD_OUTPUT`, avoiding division by zero. Break-even is calculated from the full batch cost; rounding a display unit cost down must not understate it.
The summary lists excluded categories: labour, overhead, fulfillment, channel fees, marketing and finance. These costs are not recorded here and are not silently estimated or treated as zero in a net-profit claim. The report is an indicative **material contribution scenario**, not realized revenue, recognized net profit, a complete margin statement, cost-of-goods-sold allocation, or evidence that all good units were sold. No sale-to-batch attribution, tax treatment, inventory valuation policy, or external ledger posting is invented.
Sealed rate changes and later catalog repricing do not change cost evidence or the chosen price assumption. Staff must supply a new price to evaluate another scenario. No customer data, supplier contact/evidence, creator identities, hashes or keys are returned. No audit event or report table is created for this read. Full cost lines remain behind their existing permission.
Deploy the additive Owner-permission migration before the application. No schema table, dependency, pricing policy, source amount or historical migration changes. Older code ignores the permission on rollback. This branch is stacked on the pushed Phase 5D accounting source branch; merge that prerequisite first or review the stacked diff accordingly.
Verification covers positive/negative/zero contribution, exact large values, upward break-even rounding, signed basis-point rounding, zero price/output, sealed evidence, frozen rates and ignored catalog changes, explicit currency matching, independent permission, organization isolation, strict price input and migration drift. Realized profitability, complete expense/COGS attribution, margin dashboards and native multi-connection PostgreSQL checks remain separate work.

14
docs/batch-cost-api.md Normal file
View File

@ -0,0 +1,14 @@
# Batch cost snapshots (Phase 2M)
Create one immutable standard-cost snapshot after a production batch is completed. The snapshot prices recorded material consumption and wastage, plus recorded packaging use and wastage, using the latest material cost rates in one selected currency at creation time. It stores the exact rate IDs, material quantities, line costs and totals, so later rate revisions cannot change it.
| Method | Path | Permission |
| ------ | --------------------------------------------------- | ------------- |
| GET | `/api/v1/production-batches/:batchId/cost-snapshot` | `cost.read` |
| POST | `/api/v1/production-batches/:batchId/cost-snapshot` | `cost.manage` |
POST body: `{ "currency": "INR", "idempotencyKey": "<uuid>" }`. Supported currencies are INR, USD, EUR and GBP. A batch has at most one snapshot. An exact retry with the same key returns the saved snapshot; a changed request returns `BATCH_COST_REPLAY_CONFLICT`.
Every production BOM line must have at least one material usage event before batch completion. A batch with good output also needs its packaging execution record. A fully rejected batch with zero good pieces can be costed without packaging. Missing usage, packaging or cost rates return distinct errors. Completed legacy batches without usage events cannot be costed retroactively because material usage is append-only and closes with the batch.
Each line adds used and wasted quantities, multiplies by its selected standard rate, and rounds half-up to two decimal places. Production and packaging totals sum their rounded lines; the overall total sums those subtotals. Quantities stay in each material's native unit. These snapshots are operational standard-cost reports, not stock valuation or accounting COGS; they exclude labor, overhead, tax and freight. Physical stock posting remains a separate milestone pending a stock-location policy.

View File

@ -0,0 +1,28 @@
# Blog publishing and SEO metadata (Phase 4G)
Staff create and edit organization-scoped blog articles, explicitly publish reviewed draft versions, and withdraw content with a reason. Revisions to a published article remain private working text until publication replaces the public snapshot at its existing slug. This is the next provider-independent growth milestone while Instagram, Etsy and WhatsApp integrations remain deferred.
| Method | Route | Access |
| ------ | ----------------------------------------------- | ----------------------------------------------------------------------------------- |
| GET | `/api/v1/blog-articles` | `blog.read`; paginated staff records, optional `state` filter. |
| GET | `/api/v1/blog-articles/:id` | `blog.read`; working text and latest publication metadata/snapshot. |
| POST | `/api/v1/blog-articles` | `blog.manage`; create a draft. |
| PATCH | `/api/v1/blog-articles/:id` | `blog.manage`; edit working text at its current version. |
| POST | `/api/v1/blog-articles/:id/publication` | `blog.publish`; publish `{ "version": 0 }`. |
| POST | `/api/v1/blog-articles/:id/withdrawal` | `blog.publish`; withdraw with `{ "reason": "Editorial correction needed" }`. |
| GET | `/api/v1/storefront/:organizationId/blog` | Public, shared storefront rate limit; published article summaries and SEO metadata. |
| GET | `/api/v1/storefront/:organizationId/blog/:slug` | Public, shared storefront rate limit; latest published text and SEO metadata. |
Create with `slug`, `title`, `summary`, `body`, and a UUID `idempotencyKey`. Slugs use the existing lowercase, hyphen-separated catalog convention and are permanent within an organization. Title is single-line plain text up to 160 characters, summary up to 500, and body multiline plain text up to 20,000. All are required and trimmed. HTML, angle brackets, and unsafe control characters are rejected; body line breaks and tabs are supported. PATCH accepts the current `version` and at least one of title/summary/body. Identity, slug, scope, lifecycle metadata, and public snapshot are never client-editable.
Creation retries with the same key and normalized input return the same article; changed input returns `IDEMPOTENCY_CONFLICT` (409). Duplicate organization/slug returns `RECORD_CONFLICT` (409). Successful edits increment version and record `blog.updated`. Publishing checks the reviewed version, copies title/summary/body into the public snapshot, records publication version/time/staff, increments the working version, and audits `blog.published`. Repeating the **latest** successful publication version makes no new changes or audit record. Older publication commands after republishing return `BLOG_CHANGED` (409). An exact latest-publication retry after further draft edits leaves those edits unpublished. Editors do not require publication permission to save private changes.
Public responses expose only slug, published title/summary, publication date, and `seo: { title, description }` derived from that snapshot. Detail adds published `body`; list omits body and uses existing limit/offset pagination. Draft content, staff identities, internal scope, keys, hashes, and version counters are absent. Draft, withdrawn, and foreign-organization detail requests return `BLOG_NOT_FOUND` (404). Staff reads are separately permission-gated, and all writes recheck live session and permission inside the existing organization lock.
Withdrawal is terminal, immediate, and reasoned; it does not erase the last public snapshot or audit evidence. Repeating the same reason is safe; a different reason, edit, or publication after withdrawal returns `BLOG_STATE_CONFLICT` (409). The slug remains reserved. Public routing no longer exposes withdrawn records. Replace an irreversibly withdrawn article with a new slug when needed.
The frontend must render body as text, preserving paragraphs, and escape all text used in HTML metadata. This API supplies content and metadata; it does not render pages, generate HTML/Markdown, invent a canonical domain, submit a sitemap, or guarantee search indexing/ranking. Frontend canonical links, sitemap/robots integration, rich text, media and structured data are separate delivery work.
Deploy the additive table/type migration before the application. Existing system Owners gain `blog.read`, `blog.manage`, and `blog.publish`; custom roles require explicit grants. Scoped staff foreign keys, unique slugs/creation keys, native revision/transition guards, and exact snapshot checks protect persistence. Deletes and withdrawn-record rewrites are rejected. Prior migrations remain unchanged. Older code ignores this table; preserve article rows and audit events on rollback.
The latest public snapshot is retained, while the audit trail records editorial actions without storing old article bodies. Full revision history and restoration can be added when editorial rollback is required. Verification covers unpublished/draft privacy, live text separation, republication, metadata projection, independent permissions, scoped access, plain-text/size validation, stale and concurrent commands, creation retries, reasoned withdrawal, native snapshot/delete guards, and migration drift. Native multi-connection concurrency verification remains dependent on the existing PostgreSQL CI setup.

24
docs/bom-api.md Normal file
View File

@ -0,0 +1,24 @@
# Product bills of materials (Phase 2G)
Every BOM belongs to one product variant and organization. A revision specifies the number of finished pieces it yields and the required quantity of each material for that yield. Quantities use the material's native unit and exactly three input decimal places. The API does not convert grams to kilograms or assume a wastage rate.
| Method | Path | Permission | Purpose |
| ------ | --------------------------------------------------------- | ------------ | --------------------------------------------------------- |
| GET | `/api/v1/variants/:variantId/boms?status=&limit=&offset=` | `bom.read` | List revision metadata, newest first |
| GET | `/api/v1/variants/:variantId/boms/active` | `bom.read` | Get the current active revision with lines |
| POST | `/api/v1/variants/:variantId/boms` | `bom.manage` | Create a complete draft revision |
| GET | `/api/v1/boms/:id` | `bom.read` | Get one revision with material snapshots |
| POST | `/api/v1/boms/:id/activate` | `bom.manage` | Activate a draft and supersede the former active revision |
Create body:
```json
{
"outputQuantity": 10,
"lines": [{ "materialId": "a-valid-uuid", "quantity": "125.000" }]
}
```
Use an actual UUID for `materialId`. One to 50 distinct active materials are required. The output is 1–100,000 pieces, and a variant can have at most 100 revisions. Only active variants and materials may be used. Material name, code and unit are copied into the revision and do not change when master data changes. Drafts are complete when created; corrections use another revision. Activating an older draft after a newer revision has been activated is rejected. An existing activation remains auditable even if its material master is subsequently deactivated.
All reads and writes are organization scoped. The create and activate paths write audit events. Database constraints and triggers enforce sequential revisions, positive quantities, one active revision per variant, immutable lines, and permitted lifecycle transitions. Production batches, actual consumption, wastage, packaging and costing remain later milestones; a BOM is a planned recipe, not a stock movement.

View File

@ -0,0 +1,17 @@
# Campaign discounts (Phase 4D)
Campaign offers reuse existing coupons and exact checkout money rules. A campaign can have one coupon, created while the campaign is a draft. Coupon terms and association are immutable; the existing coupon status endpoint can pause/resume the code. Configure the campaign window first, then its coupon, then publish the updated campaign version.
`POST /api/v1/coupons` accepts the existing fixed/percentage coupon body plus optional `campaignId` and `campaignVersion`. Both must be supplied together. Linking requires `coupons.manage` and `campaigns.manage`, a draft in the caller's organization, and its current version. The coupon's start/end must fit inside the campaign window. Successful creation increments campaign version atomically, preventing publication of an offer not seen in the staff member's last read. Existing unlinked coupon requests retain their behavior.
Draft edits must keep the campaign window around its linked coupon. Terms cannot be replaced by another code in this milestone; create a new campaign/code for a different offer. The code remains the coupon creation identity; duplicate code or campaign association returns a conflict. No existing applied migration is edited.
Public campaign responses gain an optional `offer` with code, currency, kind, fixed amount/percentage basis points, minimum subtotal, and coupon start/end dates. It appears only when both the campaign and coupon are active and within their windows. Usage limits and per-customer eligibility remain authoritative at checkout; published terms do not promise a reservation or remaining use. Internal coupon IDs and usage counts are not public.
Customers continue submitting one `couponCode` to the existing checkout endpoint. A linked code additionally requires an active published campaign and a current collection. Only cart variants belonging to that collection contribute to the discount base and minimum-spend test. Other cart lines keep their full price. Percentage rounding and fixed-amount caps use the existing minor-unit arithmetic. No matching lines, draft/future/ended/cancelled campaigns, wrong currency, disabled/expired coupons, and exhausted limits fail before order/stock/cart writes.
New campaign-coupon order snapshots also retain campaign ID/slug, collection ID, campaign/coupon windows, eligible variant IDs, and exact eligible subtotal. These facts are frozen alongside coupon/price snapshots. Retrying a successful checkout returns its original order even after campaign cancellation or coupon disablement. New attempts use current eligibility. Order cancellation/expiry retain the existing usage-release behavior. Payment enablement, tax, shipping and gateway behavior do not change.
Acceptance: collection-only discounts in mixed carts; exact fixed/percentage amounts; scoped binding and version checks; window compatibility; public offer privacy; campaign/coupon cancellation gates; coupon quotas; checkout rollback/idempotency; immutable linkage and order evidence; unchanged generic coupons.
Deploy the additive migration before the application. Existing coupons receive a null campaign link and remain generic. New scoped foreign keys/unique constraints prevent cross-organization or duplicate binding; native guards freeze linked coupon terms and prevent invalid linked campaign rescheduling. Rollback to older code requires disabling campaign-linked coupons first so an older checkout cannot treat them as generic coupons. Preserve rows, order snapshots and audit history. No new dependencies or provider accounts are required.

View File

@ -0,0 +1,23 @@
# Captured-request forecasting baseline (Phase 5C)
Staff can project a historical daily checkout-capture rate over a bounded future horizon. This provides an explicit planning baseline from currently non-cancelled checkout captures, including expired pending-payment orders. It does not imply completed sales, paid demand, revenue, stock requirements, or statistical confidence. The response names its method and evidence basis; no stock or production operation is triggered.
`GET /api/v1/forecasts/captures` requires `forecasts.read`, rechecked with the live session inside the existing read transaction. `analytics.read` alone does not grant forecasting access. Existing system Owners receive the new permission through the additive migration; custom roles remain explicit.
Required `from` and `to` reuse analytics ISO-offset datetime validation, normalize to UTC, and must be UTC midnight boundaries covering 7–366 complete past UTC days. Start is inclusive, end exclusive; the end cannot exceed today's UTC midnight. An offset such as `05:30:00+05:30` is valid when it normalizes to midnight UTC. Partial days, future history, excessive precision, unsupported normalized years, invalid/oversized windows, and extra fields return 400.
Optional `horizonDays` is an integer 1–90, default 30. Optional `currency` is a three-uppercase-letter historical cohort filter; currency groups remain separate. `limit` defaults to 25 (maximum 100) and `offset` to zero (maximum 10,000), using existing pagination. Queries are scoped to the caller's organization and accept no organization/account override. Missing sessions return 401 and missing permission 403.
The response includes `asOf`, `method: "MEAN_DAILY_CAPTURE_RATE"`, `basis: "NON_CANCELLED_CHECKOUT_CAPTURES"`, normalized `history`, `lookbackDays`, `horizonDays`, `historyAgeDays`, and `projection`. Projection starts at the next UTC midnight and ends exclusively after the requested whole-day horizon. History age measures days between the selected historical end and today's UTC midnight, making an old source window visible instead of silently presenting it as recent.
Each variant/currency row includes current catalog ID/SKU/product/variant labels, `currentlySellable`, historical `orderCount`, `activityDays`, exact-string `observedQuantity`, and exact-string `projectedCaptureQuantity`. Historical quantities come from immutable order lines; current labels can change without rewriting those quantities. Older descriptor versions of the same variant/currency are combined. Currently inactive/unpublished variants are retained with `currentlySellable: false`; this flag is current catalog activity/publication, not a stock reservation or historical-currency price promise.
The baseline is `ceil(observedQuantity × horizonDays / lookbackDays)`, calculated with integer arithmetic. The divisor includes every calendar day in the window, including days without captures. `activityDays` separately counts distinct UTC days with qualifying records. Currently cancelled orders are excluded, and later cancellation affects the next read. Empty cohorts return empty rows rather than invented observations; an empty paginated page is not a claim that no qualifying history exists elsewhere.
Rows rank by observed quantity descending, then stable variant ID/currency. Each response is a live evaluation; no persistent cohort, total-count cursor, or backtest snapshot is implied. Historical status is evaluated as currently stored, so this is not a reconstruction of what staff knew at a past date. Monetary values, customer/order identifiers, contacts, addresses, coupon information, keys, and hashes are absent.
The SQL reuses the same scoped, parameterized creation-time cohort as Phase 5B and the existing order date index. One aggregate statement provides a database snapshot; reads do not take the organization write lock. Inputs and pagination are bounded. No model-training dependency, new forecast table, scheduler, cache, confidence interval, seasonal adjustment, automatic purchasing, or production planning rule is introduced. Replace the simple daily mean with a validated model when suitable completed-sale/fulfillment history and forecasting requirements are available.
Deploy the additive Owner-permission migration before the application. Existing tables, timestamps, order snapshots, and historical migrations remain unchanged. Older code ignores the permission on rollback. Native PostgreSQL concurrency verification remains subject to the existing CI database setup.
Verification covers zero-activity days, cancellation exclusion and live re-evaluation, exclusive end dates, exact ceiling arithmetic beyond JavaScript safe integers, current labels/inactive flags, currency separation, deterministic pagination, empty cohorts, independent permissions, organization scope, past/full-day/horizon limits, inherited analytics bounds, and migration drift.

20
docs/cart-recovery-api.md Normal file
View File

@ -0,0 +1,20 @@
# Private cart recovery (Phase 4E)
Authenticated customers can resume their persisted cart after at least 24 hours without a successful cart edit, recovery, or checkout. Cart reads and failed commands do not refresh activity. A cart must contain at least one line and have a known activity timestamp. This milestone provides in-app recovery; outbound reminders require the later consent-aware messaging milestone.
All routes use the caller's live active session and own organization/user scope. No staff permission, user ID parameter, public token, customer directory, or new provider is involved. Existing access rate limits apply.
| Method | Route | Behavior |
| ------ | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| GET | `/api/v1/cart/recovery` | Returns `version`, nullable `lastActivityAt`, `recoverable`, and current lines; does not create a cart or change activity. |
| POST | `/api/v1/cart/recovery` | Strict body `{ "version": 1 }`; resumes the eligible cart at its current version. Returns 201 with the next `version` and `removedVariantIds`. |
Each preview line contains `variantId`, `quantity`, `available`, and `variant`. Available variants expose current name, SKU, decimal price, currency, and product name. Inactive variants and unpublished products return `available: false, variant: null`; their private catalog details are redacted. The response contains no user profile or contact details.
The customer explicitly confirms removal of unavailable lines when posting recovery. Resumption rechecks catalog availability, preserves all available quantities, removes unavailable lines atomically, refreshes activity, increments the cart version once, and appends `cart.recovered` to the audit trail. A competing edit, checkout, or recovery is serialized by the existing organization lock. Stale versions return `CART_CHANGED` (409); empty, undated, or recently active carts return `CART_NOT_RECOVERABLE` (409). Invalid bodies return 400; missing/inactive sessions are rejected by the existing access guard. A lost successful response is resolved by reading the new version, rather than blindly retrying the old command.
Availability means currently active and published merchandise, not a stock reservation. Recovery neither freezes prices nor copies coupons from earlier orders. Checkout remains authoritative for current prices, currency consistency, campaign/coupon eligibility, stock, and immutable order snapshots. Customers can edit the recovered cart with the existing versioned cart endpoints.
Deploy the additive nullable `last_activity_at` migration before the application. Existing carts retain all lines but have unknown historical activity; they become eligible only after a new successful cart edit followed by 24 idle hours. This avoids inventing old activity timestamps. No historical migrations are edited. Older code ignores the new column; if rolling back and later re-enabling recovery, clear timestamps for carts that may have been edited by the older code before enabling recovery again. Preserve cart lines, orders, and audit history.
Acceptance covers the exact 24-hour boundary, empty/unknown/future activity, current prices, read-only activity semantics, customer and organization isolation, schema validation, stale and concurrent commands, audit uniqueness, inactive/unpublished redaction and removal, and edit/checkout reset. Native PostgreSQL concurrency checks remain subject to the project's existing CI database setup.

View File

@ -0,0 +1,26 @@
# Commerce activity analytics (Phase 5B)
Staff can inspect UTC daily checkout activity and frozen variant demand for a bounded creation-time cohort. Both endpoints require `analytics.read`; live session, user/organization scope, and permission are rechecked within the read transaction. Existing system Owners gain the permission through the additive migration; custom roles remain explicit.
| Method | Route | Result |
| ------ | ------------------------------------- | ------------------------------------------------------------- |
| GET | `/api/v1/analytics/commerce/daily` | `window`, `asOf`, and daily/currency aggregate `days`. |
| GET | `/api/v1/analytics/commerce/variants` | `window`, `asOf`, and paginated frozen-descriptor `variants`. |
Required query fields `from` and `to` are ISO datetimes with explicit UTC/offsets, up to millisecond precision, and normalized UTC years 0001–9999. The start is inclusive, end exclusive, and the window must increase by at most 366 elapsed days. Responses normalize both to UTC. Optional `currency` is three uppercase letters and filters rather than converts values. Variants support the existing `limit` (default 25, maximum 100) and `offset` (default 0, maximum 10,000). Extra fields, missing endpoints, reversed/oversized windows, and invalid filters return 400. Missing sessions return 401 and insufficient permission 403. Organization overrides are rejected.
Daily rows group the cohort by UTC creation date and currency, sorted ascending. Each contains `orderCount`, `openOrderCount`, `expiredOrderCount`, and `cancelledOrderCount`. Open means `PENDING_PAYMENT` with expiry strictly after the response's `asOf`; expired means pending with expiry at/before it. Cancelled uses current stored status. These are current states of orders **created in the window**, not a reconstruction of state at the window end or a count of cancellations occurring during that period.
Money fields are exact two-decimal strings: `capturedSubtotal`, `capturedDiscount`, `capturedMerchandiseValue`, `openMerchandiseValue`, `expiredMerchandiseValue`, and `cancelledMerchandiseValue`. Values come from immutable order snapshots; daily queries do not join lines and therefore cannot multiply order totals for multi-line orders. Captured values include all supported states. Days/currencies with no activity are omitted; empty windows return an empty array. Currencies remain separate, with no FX conversion or combined total.
Variant rows group by currency, variant ID, frozen SKU, product name and variant name. Renaming or repricing the current catalog does not rewrite those descriptors or values. A variant whose snapshot descriptors changed can appear in several rows. `orderCount` counts orders represented in that descriptor group, `capturedQuantity`/`openQuantity`/`expiredQuantity`/`cancelledQuantity` are exact integer strings, and `capturedLineValue` is the frozen line-total sum **before order-level coupon discounts**. Discounts are not allocated arbitrarily across variants. Rows rank by captured quantity descending, then stable variant/currency/descriptors; pages are independent live evaluations and no total-count/cursor snapshot is implied.
These reports cover retail checkout captures and current demand activity. Payment remains deferred; captured merchandise value is not recognized revenue, fulfilled sales, profit, tax liability, or cash receipts. Existing partner receipt/account reports retain their separate contracts. Paid/fulfilled analytics, financial recognition, margin attribution, forecasts, cross-channel data, BI exports, caching, and dashboard UI remain later milestones.
Each aggregate is one parameterized SQL statement using a single database snapshot. The permission wrapper runs without the organization write lock, so reads do not serialize commerce mutations. One server `asOf` is used for expiry classification. Only aggregate order counts/values and frozen catalog descriptors leave the store; customer IDs, order IDs, addresses, contacts, coupon details, keys, and hashes are omitted. SQL values are bound, windows/pagination bounded, and the new `(organization_id, created_at, id)` order index supports date scans.
The UTC boundary check exposed the installed `adapter-pg` timestamp codec's dependence on UTC sessions. Application connection URLs now append the UTC startup option after preserving existing URL options; each real PostgreSQL pool connection receives it. The embedded socket test emulator ignores startup options, so its database is explicitly initialized to UTC. This follows the [PostgreSQL connection startup options](https://www.postgresql.org/docs/17/libpq-connect.html) and addresses the behavior documented in the [Prisma adapter timezone issue](https://github.com/prisma/prisma/issues/26786), also confirmed against the installed adapter source. No stored timestamps are rewritten. Deployments previously using non-UTC sessions should review historical timestamp interpretation before adopting corrected serialization.
Deploy the additive date-index/Owner-permission migration before the application. No new reporting table or provider is introduced, and historical migrations/order snapshots stay unchanged. Index creation uses the project's normal migration runner; schedule it appropriately for a large existing order table. Older code ignores the index/new permission on rollback. Removing the UTC application setting would reintroduce the non-UTC codec behavior on affected connections.
Verification covers exact decimals, separate currencies/current states, UTC midnight and offset normalization, inclusive/exclusive boundaries, empty periods, multi-line fanout prevention, coupon/replay/cancellation behavior, frozen descriptors, stable pagination, scoped permissions, strict window limits, preserved connection options, migration drift and existing recovery/campaign regressions. Native multi-connection PostgreSQL CI remains dependent on the existing test setup.

View File

@ -25,3 +25,13 @@ Stock quantities are integers. Opening stock is an adjustment. Adjustments requi
Availability equals on-hand stock minus unexpired active reservations. Stock row locks serialize changes. Expired holds stop consuming availability and cannot be committed. Release and commit are idempotent. Commit decrements stock and appends one ledger entry in the same transaction. A database trigger rejects ledger updates/deletes.
Existing system roles receive permissions through migration; custom roles require explicit grants. This phase covers finished goods. Checkout/orders and pricing snapshots follow in Phase 1D; procurement and production in Phase 2.
## Product photos
| Method | Path | Permission | Request / result |
| ------ | -------------------------------------------------------- | ----------------- | -------------------------------------------------------------------- |
| POST | /products/:id/images | catalog.manage | multipart `file`: JPEG, PNG or WebP up to 2 MiB → id, mimeType, size |
| DELETE | /products/:id/images/:imageId | catalog.manage | 204; 404 if missing or out of scope |
| GET | /storefront/:organizationId/products/:id/images/:imageId | Public; throttled | Image bytes for published products only; cached publicly for one day |
The file signature must match the declared type, so renamed scripts or SVGs are rejected. A product holds at most 8 photos, ordered by upload; the first is the main photo. Storefront lists include `images` with the main photo ID; storefront and admin product details include all photos. Images are immutable rows; replace one by deleting and uploading again. Archived products cannot change photos.

16
docs/costing-api.md Normal file
View File

@ -0,0 +1,16 @@
# Material costing estimates (Phase 2L)
Record an internal standard cost per material and currency. Each new rate is an immutable revision; rates are entered in the material's native unit. These are planning inputs, independent of supplier quotes, invoices, tax, freight and physical inventory valuation.
| Method | Path | Permission |
| ------ | ---------------------------------------------------------------------- | ------------- |
| GET | `/api/v1/materials/:materialId/cost-rates?currency=INR&limit=&offset=` | `cost.read` |
| POST | `/api/v1/materials/:materialId/cost-rates` | `cost.manage` |
| GET | `/api/v1/boms/:id/cost-estimate?currency=INR` | `cost.read` |
| GET | `/api/v1/packaging-boms/:id/cost-estimate?currency=INR` | `cost.read` |
Example rate body: `{ "currency": "INR", "unitCost": "0.1250" }`. Supported currencies are INR, USD, EUR and GBP. Unit cost is positive with exactly four decimal places. Revisions are numbered independently for each material and currency; a material can have at most 1,000 revisions per currency.
An estimate multiplies each BOM-line quantity by the latest rate in the requested currency, rounds each line half-up to two decimal places, then sums the rounded lines. The response includes each rate ID and revision, the line amounts, total for the BOM's output quantity, and the time of calculation. Missing rates return `COST_RATE_MISSING`; no exchange conversion or cross-currency addition occurs. Production and packaging BOM estimates use separate paths and cannot be confused.
Estimates are calculated from current rates when requested. Updating a rate changes future estimates, including estimates of older BOM revisions. Save the returned rate IDs and amounts externally if a planning decision needs a point-in-time reference. Actual batch costing, labor and overhead, tax, shipping, and stock valuation require separate policies and milestones.

View File

@ -0,0 +1,25 @@
# Live customer segmentation (Phase 4H)
Staff can inspect three fixed, live segments based on current commerce records. Accounts must be active and belong to the caller's organization. Membership contains only account IDs, not names, contacts, addresses, purchase evidence, or cart/wishlist contents. Accounts with staff roles are included if they have the same qualifying commerce activity; the current identity model has no separate customer-only account type.
| Segment key | Definition |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `WISHLIST_INTEREST` | At least one saved wishlist variant is currently active and its product published. Multiple saved items count the account once. |
| `RECOVERABLE_CART` | A nonempty cart has a known activity timestamp at least 24 hours old, using the same cutoff as private cart recovery. Empty/undated/recently edited carts are excluded. Catalog/stock eligibility remains authoritative at recovery and checkout. |
| `VERIFIED_BUYER` | At least one unrevoked external purchase verification exists under the verified-review evidence workflow. Pending-payment orders and cancelled orders do not establish completed purchase evidence. |
`GET /api/v1/customer-segments` requires `segments.read` and returns `asOf` plus a `segments` array of `{ key, description, total }`. The groups can overlap; their counts should not be summed to infer unique customers. No account without the qualifying evidence is included merely because it is active.
`GET /api/v1/customer-segments/:segment/members` requires `segments.read` and returns `{ segment, asOf, total, members: [{ userId }] }`. Members are distinct and ordered by UUID ascending. `limit` defaults to 25 with a maximum of 100, and `offset` defaults to zero with a maximum of 10,000. `total` is the complete filtered count, not the size of this page. Unknown segment keys, invalid pagination, scope overrides, and extra query fields return 400. Missing sessions return 401; missing permission returns 403.
Both routes optionally accept `channel=EMAIL&purpose=PROMOTIONS` (also `WHATSAPP` and `CART_RECOVERY`). Supply both fields together. This intersects the segment with the latest explicit grant for that channel and purpose; absent consent and later withdrawal exclude the account. A grant for another channel/purpose does not qualify, and replaying an old grant after withdrawal does not restore membership. Consent-filtered reads additionally require the caller's **live** `messaging.read` permission, preventing consent disclosure through a segment-only role.
Inactive accounts, unavailable wishlist merchandise, cart edits/clearing, and purchase-evidence revocation affect the next read immediately. Reads recheck the staff session and permissions inside the existing organization-locked transaction. One server time is used across each response's segment checks; total and page use the same query predicate. Source API writes share the lock. Different requests/pages are live evaluations and can change between reads; `asOf` is an evaluation timestamp, not a persistent audience snapshot or paging token.
All SQL values are bound parameters. Fixed predicate fragments use scoped joins and `EXISTS`, so multiple qualifying source records do not duplicate accounts. Queries use the existing user, wishlist, cart, verification, and consent indexes. No materialized audience, copied contact list, custom rule DSL, saved segment, scheduler, CSV export, or provider delivery is introduced. Keep live reads until measured dataset size and query latency justify cached/materialized audiences.
These are staff analysis and planning APIs, not permission to deliver messages. Future adapters must recheck live consent, recipient status/contact ownership, channel policy, campaign/cart eligibility and suppressions at dispatch and retries. A filtered preview can become stale after withdrawal. Existing transactional notifications and customer preferences are unchanged.
Deploy the additive permission migration before the application. Existing system Owners gain `segments.read`; custom roles remain explicit. There are no new audience tables or schema changes. Existing migrations and source evidence remain unchanged. Older code ignores the new permission; rollback preserves all commerce records and consent history. Existing native PostgreSQL CI requirements continue to apply.
Verification covers deduplication, live catalog/account changes, shared recovery timing and empty/undated carts, revoked purchase evidence, unpaid-order exclusion, newest consent and stale-grant replay, channel/purpose isolation, separate permissions, organization isolation, strict inputs, pagination, private projections, migration drift, and prior recovery regressions.

View File

@ -0,0 +1,12 @@
# Finished-goods receipt (Phase 2Q)
Once a production batch is completed, packaging is recorded, and both production and packaging materials have been posted to stock, receive the batch's **good quantity** into a chosen warehouse. Rejected pieces never enter finished-goods stock. The receipt creates the variant's warehouse stock item when needed and appends a `PRODUCTION_OUTPUT` entry to the existing finished-goods stock ledger.
| Method | Path | Permission |
| ------ | ------------------------------------------------------------ | ------------------ |
| GET | `/api/v1/production-batches/:batchId/finished-goods-receipt` | `inventory.read` |
| POST | `/api/v1/production-batches/:batchId/finished-goods-receipt` | `inventory.manage` |
POST body: `{ "warehouseId": "<uuid>", "idempotencyKey": "<uuid>" }`. A batch can be received once. A retry with the same key and warehouse returns the original receipt; a changed retry returns `FINISHED_GOODS_REPLAY_CONFLICT`. A new key for an already received batch returns `FINISHED_GOODS_ALREADY_POSTED`.
The response includes batch, variant, warehouse, stock-item and ledger-entry IDs plus the received quantity. The database independently verifies the completed batch and good quantity, both material-stock postings, source variant and warehouse. The ledger insert updates on-hand stock in the same transaction, with a capacity bound. Receipt and ledger records are immutable. Existing inventory availability and reservation endpoints then include the newly received units.

32
docs/forum-api.md Normal file
View File

@ -0,0 +1,32 @@
# Moderated community discussions (Phase 5A)
Active accounts can submit immutable discussion threads and flat replies. Everything begins pending and stays private until an independent staff moderator approves it. Customers explicitly choose the public display alias; the application never substitutes their account name or contact details. Submission and moderation history remain append-only.
| Method | Route | Access |
| ------ | ------------------------------------------------------ | --------------------------------------------------------------------------------- |
| POST | `/api/v1/forum/threads` | Active session; create a pending thread. |
| POST | `/api/v1/forum/threads/:id/replies` | Active session; create a pending reply under an available approved thread. |
| GET | `/api/v1/forum/posts` | Active session; own submissions and moderation status, paginated. |
| GET | `/api/v1/forum-moderation` | `forum.read`; scoped queue/history with optional `status` and `threadId` filters. |
| POST | `/api/v1/forum-moderation/:id/decision` | `forum.moderate`; approve, reject, or hide with an immutable reason. |
| GET | `/api/v1/storefront/:organizationId/forum` | Public; available approved threads. |
| GET | `/api/v1/storefront/:organizationId/forum/:id` | Public; one available approved thread. |
| GET | `/api/v1/storefront/:organizationId/forum/:id/replies` | Public; available approved replies under that thread. |
Thread input is `{ "title": "Candle care question", "displayName": "Candle fan", "body": "How do I care for my candle?", "idempotencyKey": "<uuid>" }`. Replies omit `title`; reply targets must be root threads, not other replies. Title is 3–160 single-line characters, alias 1–80, and body 10–5,000 with line breaks/tabs supported. All text is trimmed, bounded plain text; HTML and unsafe control characters are rejected. Identity, organization, timestamps, and moderation metadata are never client-editable. Frontends must render/escape content as text.
Each account may have at most 20 pending posts across threads/replies in its organization. Existing authentication and request rate limits also apply. Moderation releases pending capacity; approved posts do not consume that quota. Submission retries with the same account/key and normalized input return the existing post/current status without another audit event. Changed input, including a different parent thread, returns `IDEMPOTENCY_CONFLICT` (409). Exact reply retries remain readable by their author even if the parent later becomes unavailable, without creating or publishing content.
Own responses contain only post ID, thread ID, alias, title/body, submission date, and `moderationStatus`. Staff queue/decision responses additionally provide author ID, current account status, and moderation records/notes. `forum.read` and `forum.moderate` are separate permissions; self-moderation returns `FORUM_SELF_MODERATION` (403) even for Owners. Existing system Owners gain both permissions; custom roles remain explicit.
Moderation input is `{ "decision": "APPROVED", "note": "Content checked by staff", "idempotencyKey": "<uuid>" }`, with note 3–1,000 characters. Pending posts can receive one approval or rejection; only approved posts can subsequently be hidden. Rejection and hiding are terminal. Invalid transitions return `FORUM_MODERATION_STATE` (409); inactive authors cannot be approved (`FORUM_AUTHOR_INACTIVE`, 409). Approval of a reply also requires a currently available root thread. Exact latest or historical decision-key retries return the current record without repeating decisions or audits; changed commands return `IDEMPOTENCY_CONFLICT` (409).
Public queries require approval, no hiding event, and an active author. Replies additionally require the parent thread to meet those conditions. Hiding a root therefore removes it and every reply from public discovery without rewriting reply evidence. Public responses expose only IDs/parent IDs, chosen alias, title/body and submission date; account IDs, profile/contact information, staff notes, decision history, hashes and keys are absent. Missing, private, unavailable, reply-as-thread, and foreign-scope roots return `FORUM_NOT_FOUND` (404). All public routes use the existing shared storefront rate limit and pagination (default 25, maximum 100; offset maximum 10,000).
Writes recheck live account/permission inside the existing organization lock. Native guards serialize pending quotas, require scoped approved root targets, reject self-moderation, enforce decision sequence/transitions, and freeze both submissions and decisions. Audit actions are `forum.submitted`, `forum.approved`, `forum.rejected`, and `forum.hidden`. Publishing or hiding occurs through evidence append, with no mutable status flag to bypass moderation.
Deploy the additive enum/tables/permission migration before the application. Composite user/parent/post foreign keys enforce organization scope. Existing migrations and commerce records are untouched. Older code ignores the new tables; preserve submission, moderation, and audit history on rollback. Shared multiline validation preserves blog behavior.
This milestone provides moderated flat discussions, not editing/deletion, nested replies, categories, attachments, voting, reporting/appeals, moderator restoration, realtime chat, outbound notifications, or a forum frontend. Immutable posts avoid edits bypassing review; customers can submit corrected text under a fresh key. Additional community delivery work can follow actual usage and policy decisions.
Verification covers private pending submissions, independent moderation, public alias projection, separately moderated replies, parent hiding/inactive authors, scoped access, replay conflicts, immutable native records, pending quotas, competing decisions, strict text/shape validation, schema drift, and prior blog validation. Multi-connection native PostgreSQL CI remains subject to the existing test setup.

42
docs/graphify.md Normal file
View File

@ -0,0 +1,42 @@
# Graphify code graph
The [interactive graph](../graphify-out/graph.html) maps the backend's source symbols and relationships. Search for a class or file, select a node, and follow its connections. The [graph report](../graphify-out/GRAPH_REPORT.md) and [queryable graph](../graphify-out/graph.json) are committed alongside it. This snapshot was extracted from source commit `131aef79` on 2026-10-04. Regenerate it after meaningful source changes.
Graphify is pinned as a Git submodule at `tools/graphify` (commit `0b60d47e6cd9338c51143f39f35b6c45c8453385`, version `0.9.74`). Its repository includes Apache-2.0 and MIT license files. Initialize it after cloning:
```sh
git submodule update --init --depth 1 tools/graphify
```
On Windows, run the command through Git Bash if PowerShell's Git submodule wrapper cannot find its shell utilities:
```powershell
& "C:\Program Files\Git\bin\bash.exe" -lc "git submodule update --init --depth 1 tools/graphify"
```
Use Python 3.10 or newer and an isolated environment. From the backend root:
```sh
python -m venv .tmp/graphify-venv
# Activate the environment, then:
python -m pip install -e "tools/graphify[sql]"
python -m graphify extract . --code-only --max-workers 4
python -m graphify cluster-only . --no-label
python -m graphify explain PartnerPaymentWriteStore --graph graphify-out/graph.json
```
In PowerShell, you can run the virtual environment directly without activating it:
```powershell
python -m venv .tmp\graphify-venv
& .\.tmp\graphify-venv\Scripts\python.exe -m pip install -e "tools/graphify[sql]"
& .\.tmp\graphify-venv\Scripts\python.exe -m graphify extract . --code-only --max-workers 4
& .\.tmp\graphify-venv\Scripts\python.exe -m graphify cluster-only . --no-label
Invoke-Item graphify-out\graph.html
```
Open `graphify-out/graph.html` in a desktop browser. The page loads `vis-network` from a pinned CDN URL with a Subresource Integrity hash, so it needs network access for its viewer script. Graph data is embedded in the HTML; do not publish it outside the development team. The committed graph and report can be queried without regenerating, but local extraction is needed to reflect later code changes.
`.graphifyignore` excludes local tooling, tests, migrations, generated code, and caches. `--code-only` uses local AST parsing and does not send source to an LLM. The ignored `graphify-out` cache, analysis, and machine-specific root files stay local; only the graph, report, viewer, and portable manifest are tracked. No application runtime dependency, database migration, or API route is added.
This graph is an automatic source map, not a live service dashboard. It complements the manually curated Archify experiment on its separate branch and the running API's Swagger UI.

View File

@ -1,26 +1,27 @@
# Phase 1B: identity and access API
All paths below start with `/api/v1`. Protected endpoints require `Authorization: Bearer <accessToken>`. There are no public account-creation or owner-creation endpoints. Staff account provisioning is available to authorized administrators; storefront self-registration and verified email onboarding can be added with the customer milestone.
All paths below start with `/api/v1`. Protected endpoints require `Authorization: Bearer <accessToken>`. Customers create their own accounts with `/auth/register`; there is no public owner-creation endpoint. Staff accounts are provisioned by authorized administrators. Email verification is not yet implemented.
## Endpoints
| Method | Path | Permission | Request / result |
| ------ | ---------------------- | ------------------ | ------------------------------------------------------------------- |
| POST | /auth/login | Public; throttled | organizationId, email, password → accessToken, tokenType, expiresAt |
| GET | /auth/me | Authenticated | userId, organizationId, sessionId, effective permissions |
| POST | /auth/logout | Authenticated | Revoke current session; 204 |
| POST | /auth/logout-all | Authenticated | Revoke all current user sessions; 204 |
| POST | /auth/recovery/request | Public; throttled | organizationId, email → generic 202; 503 if SMTP is unconfigured |
| POST | /auth/recovery/reset | Public; throttled | token, password → 204; token expires and can be consumed once |
| GET | /users | users.read | Paginated safe user records |
| POST | /users | users.create | name, email, password → PENDING account |
| PATCH | /users/:id/status | users.approve | status: ACTIVE or SUSPENDED |
| PATCH | /users/:id/roles | users.roles.assign | roleIds: UUID array; replaces assignments |
| GET | /roles/permissions | roles.read | Current permission catalogue |
| GET | /roles | roles.read | Paginated roles |
| POST | /roles | roles.manage | name, permissions |
| PATCH | /roles/:id | roles.manage | Complete replacement of name and permissions |
| GET | /audit-events | audit.read | Paginated append-only organization audit history |
| Method | Path | Permission | Request / result |
| ------ | ---------------------- | ------------------ | ------------------------------------------------------------------------------------------------ |
| POST | /auth/login | Public; throttled | organizationId, email, password → accessToken, tokenType, expiresAt |
| POST | /auth/register | Public; throttled | organizationId, email, name, password → active customer + session; 409 duplicate; 10/hour per IP |
| GET | /auth/me | Authenticated | userId, organizationId, sessionId, effective permissions |
| POST | /auth/logout | Authenticated | Revoke current session; 204 |
| POST | /auth/logout-all | Authenticated | Revoke all current user sessions; 204 |
| POST | /auth/recovery/request | Public; throttled | organizationId, email → generic 202; 503 if SMTP is unconfigured |
| POST | /auth/recovery/reset | Public; throttled | token, password → 204; token expires and can be consumed once |
| GET | /users | users.read | Paginated safe user records |
| POST | /users | users.create | name, email, password → PENDING account |
| PATCH | /users/:id/status | users.approve | status: ACTIVE or SUSPENDED |
| PATCH | /users/:id/roles | users.roles.assign | roleIds: UUID array; replaces assignments |
| GET | /roles/permissions | roles.read | Current permission catalogue |
| GET | /roles | roles.read | Paginated roles |
| POST | /roles | roles.manage | name, permissions |
| PATCH | /roles/:id | roles.manage | Complete replacement of name and permissions |
| GET | /audit-events | audit.read | Paginated append-only organization audit history |
List queries accept `limit` (1–100, default 25) and `offset` (0–10000, default 0). Unknown fields, malformed UUIDs, duplicate role assignments/permissions and unknown permissions are rejected. Errors use Nest's JSON error contract: 400 invalid input, 401 unauthenticated, 403 denied, 404 missing/out-of-scope target, 409 duplicate record, 429 throttled, 503 unavailable.
@ -36,7 +37,7 @@ Example login:
## Access rules
Organization scope comes from the persisted session, never from an administration request body. Email uniqueness is per organization and normalized to lowercase. New accounts have no roles and cannot sign in until approved. Multiple roles combine their permissions. Permissions are reloaded on every request and rechecked inside administration transactions.
Organization scope comes from the persisted session, never from an administration request body. Email uniqueness is per organization and normalized to lowercase. Staff-created accounts have no roles and cannot sign in until approved. Self-registered customers are active immediately with no roles: they can use their own cart, checkout, addresses, orders and wishlist, and nothing that requires a permission. Multiple roles combine their permissions. Permissions are reloaded on every request and rechecked inside administration transactions.
Administrators cannot grant permissions they do not hold, modify a more privileged role, change their own role assignments, assign the system Owner role, or change the owner's approval state. A single installation owner is created by the CLI; API-supplied owner flags are rejected. Suspending a user revokes sessions and recovery tokens; reactivation does not restore them.

14
docs/local-admin.md Normal file
View File

@ -0,0 +1,14 @@
# Local admin account
The development-only seed uses the existing one-time owner bootstrap. It creates no committed default password. A local PostgreSQL server must be available using the `DATABASE_URL` in `.env`, and `NODE_ENV` must be `development`.
```sh
pnpm db:generate
pnpm db:deploy
pnpm build
pnpm admin:prepare-local
pnpm admin:seed-local
```
`admin:prepare-local` creates an ignored `.env.local-admin` file with `OWNER_EMAIL=admin@manicandles.local`, organization/name settings and a random password. The command refuses to overwrite it. Read the password from that local file; do not commit or share it. `admin:seed-local` passes those values to the existing bootstrap command and prints only the resulting organization and user IDs. The seed accepts only a development environment with a loopback PostgreSQL URL. A second seed fails if an owner already exists; it does not reset the existing password. Use the normal identity workflow to change credentials. Create production administrators separately using fresh credentials and a controlled deployment procedure.
On Windows, preparation removes inherited file permissions and grants access only to the running user, SYSTEM and Administrators; it fails and removes the file if that restriction cannot be applied.

View File

@ -0,0 +1,13 @@
# Manual material-stock adjustments (Phase 2S)
Authorized inventory adjusters can correct a material's on-hand quantity in one organization-scoped warehouse. Every correction requires a reason and creates one immutable signed ledger entry. Use goods receipts, production or packaging postings, and warehouse transfers for their normal movements; adjustments are for counted discrepancies or corrections.
| Method | Path | Permission |
| ------ | -------------------------------------------------------------------------------- | ------------------ |
| GET | `/api/v1/inventory/material-adjustments?materialId=&warehouseId=&limit=&offset=` | `inventory.read` |
| GET | `/api/v1/inventory/material-adjustments/:id` | `inventory.read` |
| POST | `/api/v1/inventory/material-adjustments` | `inventory.adjust` |
POST body: `{ "materialId": "<uuid>", "warehouseId": "<uuid>", "delta": "-0.250", "reason": "Counted physical inventory", "idempotencyKey": "<uuid>" }`. Delta must be nonzero, signed if negative, and have exactly three decimal places in the material's native unit. Reason is trimmed and must contain 3–200 characters. A positive adjustment creates the warehouse material-stock item when missing; a negative adjustment requires existing, sufficient stock.
The API rejects adjustments that would make on-hand stock negative or exceed the supported balance. A retry with the same key and request returns the original adjustment; a changed request returns `MATERIAL_ADJUSTMENT_REPLAY_CONFLICT`. The database independently checks the material, warehouse, signed quantity and ledger kind, then changes the balance in the same transaction. Adjustment records and ledger entries cannot be edited or deleted.

View File

@ -0,0 +1,13 @@
# Material warehouse transfers (Phase 2R)
Move a material's on-hand quantity between two organization-scoped warehouses. The transfer posts one negative ledger entry to the source and one equal positive entry to the destination in a single transaction. It creates the destination material-stock item when needed. It never changes the organization's total quantity of that material.
| Method | Path | Permission |
| ------ | ------------------------------------------------------------------------------------------------- | ------------------ |
| GET | `/api/v1/inventory/material-transfers?materialId=&fromWarehouseId=&toWarehouseId=&limit=&offset=` | `inventory.read` |
| GET | `/api/v1/inventory/material-transfers/:id` | `inventory.read` |
| POST | `/api/v1/inventory/material-transfers` | `inventory.manage` |
POST body: `{ "materialId": "<uuid>", "fromWarehouseId": "<uuid>", "toWarehouseId": "<uuid>", "quantity": "0.600", "idempotencyKey": "<uuid>" }`. Quantity is positive, in the material's native unit, with exactly three decimal places. Source and destination must differ. A same-key, same-request retry returns the original transfer; a changed request returns `MATERIAL_TRANSFER_REPLAY_CONFLICT`.
The full quantity must be on hand in the source, and the destination balance must remain within the supported limit. Otherwise the entire transfer rolls back. PostgreSQL verifies the transfer's material and warehouse relationships, both exact signed ledger entries, and each balance bound. Transfer records and ledger entries cannot be edited or deleted. Manual material adjustments are a separate milestone.

View File

@ -0,0 +1,24 @@
# Production material usage (Phase 2I)
Usage events record material consumed into a batch or wasted while it is `IN_PROGRESS`. Each event references a material line in that batch's immutable BOM revision. Events are append-only and organization scoped. They document actual usage; they do not deduct inventory or price the material.
| Method | Path | Permission | Purpose |
| ------ | ------------------------------------------------------------------- | ---------------------------- | ------------------------------------------------------- |
| GET | `/api/v1/production-batches/:batchId/material-usage?limit=&offset=` | `production.read` | Get paginated events and full plan-versus-actual totals |
| POST | `/api/v1/production-batches/:batchId/material-usage` | `production.material.record` | Record consumption or wastage |
Example record:
```json
{
"bomLineId": "<uuid>",
"kind": "WASTED",
"quantity": "0.125",
"reason": "Spill during pouring",
"idempotencyKey": "<uuid>"
}
```
`kind` is `CONSUMED` or `WASTED`. Quantity is positive with exactly three decimal places, in the BOM material's unit. Waste requires a reason. A batch accepts at most 500 usage events. Retrying the same request with the same idempotency key returns the original event, even after the batch closes; reusing the key with changed content returns `USAGE_REPLAY_CONFLICT`.
The GET response includes `total`, an `events` page and a `materials` summary for every BOM line. For each line, `varianceQuantity = plannedQuantity − consumedQuantity − wastedQuantity`; a negative number shows overuse. Totals use exact decimal arithmetic and include all events, regardless of pagination. A completed batch need not have usage records because the earlier batch lifecycle does not require them. Stock-location policy, physical stock posting, reconciliation and costing are later decisions.

View File

@ -0,0 +1,15 @@
# Warehouse material stock (Phase 2N)
Raw-material balances are tracked per organization, material and warehouse. Use the existing `/api/v1/inventory/warehouses` endpoints to create and list warehouses. A goods receipt affects stock only after every line has a QC decision and an operator explicitly posts its accepted quantities to one warehouse. Rejected quantities never enter on-hand stock.
| Method | Path | Permission |
| ------ | -------------------------------------------------------------------------------- | ------------------ |
| GET | `/api/v1/inventory/material-stock-items?warehouseId=&materialId=&limit=&offset=` | `inventory.read` |
| GET | `/api/v1/inventory/material-stock-items/:id` | `inventory.read` |
| GET | `/api/v1/inventory/material-stock-items/:id/ledger?limit=&offset=` | `inventory.read` |
| GET | `/api/v1/goods-receipts/:receiptId/stock-posting` | `inventory.read` |
| POST | `/api/v1/goods-receipts/:receiptId/stock-posting` | `inventory.manage` |
POST body: `{ "warehouseId": "<uuid>", "idempotencyKey": "<uuid>" }`. A receipt can be posted once. A retry with the same key and warehouse returns the original posting; a changed retry returns `MATERIAL_RECEIPT_REPLAY_CONFLICT`. Posting again with a different key returns `MATERIAL_RECEIPT_ALREADY_POSTED`. The response lists one ledger entry for each line with a positive accepted quantity. A fully rejected receipt can be posted with no entries.
Balances and ledger deltas use each material's native unit and three decimal places. Posting is atomic: either all accepted lines reach the selected warehouse or none do. PostgreSQL checks that ledger entries match the receipt's QC decisions and updates balances in the same transaction. The ledger and receipt posting are append-only. Production, packaging, transfer and manual adjustment operations are documented separately.

View File

@ -0,0 +1,26 @@
# Consent-aware messaging (Phase 4F)
Customers explicitly choose optional promotions and cart recovery reminders for email and WhatsApp independently. All four preferences default to off. Preferences are self-service; staff can check eligibility but cannot grant consent on a customer's behalf. The existing order outbox and account-recovery mail retain their separate transactional contracts.
| Method | Route | Access and result |
| ------ | ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------- |
| GET | `/api/v1/messaging/preferences` | Own active session; current notice texts and four current channel/purpose preferences. |
| POST | `/api/v1/messaging/preferences` | Own active session; append a versioned grant or withdrawal and return its receipt plus the current preference. |
| GET | `/api/v1/messaging/preferences/history` | Own active session; immutable receipts, newest first, with existing `limit`/`offset` pagination. |
| GET | `/api/v1/messaging/eligibility/:userId?channel=EMAIL&purpose=PROMOTIONS` | `messaging.read`; scoped recipient's current preference and eligibility. |
To grant, send `{ "channel": "EMAIL", "purpose": "PROMOTIONS", "granted": true, "version": 0, "noticeVersion": "2026-10-07", "idempotencyKey": "<uuid>" }`. Supported channels are `EMAIL` and `WHATSAPP`; supported purposes are `PROMOTIONS` and `CART_RECOVERY`. The UI must show the returned notice for the selected purpose and channel before submitting a customer's affirmative choice. Never preselect opt-in or infer consent from an order, login, wishlist, cart activity, review, or business verification.
To withdraw, send the same channel/purpose with `granted: false`, the current `version`, and a fresh `idempotencyKey`, omitting `noticeVersion`. Withdrawal requires no notice agreement. Bodies are strict: no target user, contact data, arbitrary purpose, or client timestamp is accepted. All successful decisions, including repeated choices with new keys, append the next revision and a `messaging.consent.recorded` audit event atomically. Timestamps come from the server/database; notice versions and decision receipts are retained as evidence.
Each channel/purpose has its own version starting at zero. Stale writes return `CONSENT_CHANGED` (409). Reusing a key with changed input returns `IDEMPOTENCY_CONFLICT` (409). Exact retries return the original immutable `decision` and the **live** `current` preference, so replaying an old grant after withdrawal cannot revive consent or imply current eligibility. Receipt/history responses omit user profile, contact details, internal organization/user scope, hashes, and idempotency keys.
Staff eligibility returns `channel`, `purpose`, `granted`, `version`, and `eligible`. Eligibility requires a current grant and an active recipient in the staff member's organization. Missing/foreign recipients return `MESSAGING_RECIPIENT_NOT_FOUND` (404), unauthorized staff return 403, and inactive customer sessions cannot change preferences. The additive migration grants `messaging.read` to existing system Owners; custom roles remain explicit.
The shared `messagingEligibility` function reads the latest decision and live recipient status. A staff preview is not a delivery authorization: future adapters must recheck this gate inside the existing serialized dispatch transaction, including retries, and also validate recipient contact ownership, provider/channel policy, suppression and content eligibility. Consent withdrawal must suppress unsent optional messages. Recovery messages additionally need a currently recoverable cart; promotions need current campaign eligibility. Consent alone does not prove a verified email or WhatsApp destination.
This milestone stores preferences and exposes the reusable eligibility gate. It sends no messages and adds no provider credentials, contact directory, campaign audience export, guest unsubscribe tokens, templates, scheduler, or promotional outbox. Those belong with enabled provider delivery; existing transactional notifications are not converted into promotional messages.
Deploy the new table and permission migration before the application. Existing accounts remain opted out with no inferred decisions. Composite user/organization foreign keys enforce scope; native checks validate terms, a serialized insert guard enforces consecutive revisions, and update/delete triggers protect immutable evidence. No historical migration is changed. Older application code ignores the table; preserve decisions and audit evidence on rollback, and keep optional delivery disabled until it uses the consent gate.
Verification covers default-off and purpose/channel isolation, explicit notice requirements, strict schemas, withdrawal without agreement, stale/conflicting retries, old-grant replay, scoped permission checks, inactive recipients, competing revisions, privacy-preserving history, immutable database records, and migration drift. Multi-connection PostgreSQL verification remains dependent on the project's existing native CI setup.

View File

@ -0,0 +1,28 @@
# Bounded order expiry workflow (Phase 5F)
An authenticated operator/service account can run a bounded expiry sweep through HTTP or the scheduler-friendly one-shot command. The workflow selects only the caller's organization, `PENDING_PAYMENT` orders whose expiry is at/before one captured server time, then uses the same cancellation routine as the existing customer/staff order endpoints. Live payments remain deferred; future paid states are not selected.
| Method | Route | Access |
| ------ | ------------------------------------- | ------------------------------------------------------------------- |
| POST | `/api/v1/workflows/order-expiry/runs` | Both `workflows.run` and `orders.manage`; execute one atomic sweep. |
| GET | `/api/v1/workflows/order-expiry/runs` | `workflows.read`; paginated immutable run history. |
POST body is `{ "limit": 10, "idempotencyKey": "<uuid>" }`. Limit defaults to 10, ranges 1–25, and bounds orders per transaction. Invalid/extra fields and organization overrides return 400; missing sessions return 401; missing either execution permission returns 403. Both execution permissions and active session are checked again inside the organization-locked transaction. Existing system Owners receive `workflows.read`/`workflows.run`; custom roles remain explicit.
Orders are considered in expiry/UUID order. The workflow locks all affected stock IDs in deterministic order before shared cancellation logic releases active order-bound holds, stores `CANCELLED`, and enqueues the existing `order.cancelled` event. Physical on-hand stock is unchanged. Already cancelled orders, future pending orders, foreign organizations, and standalone reservations are not selected. Existing reads already exclude expired holds from availability; this sweep finalizes their stored status and audit evidence.
Audit action `order.expired` distinguishes workflow expiry from manual `order.cancelled`. A successful sweep appends `workflow.order_expiry_completed` and one immutable run record with operator ID, limit, evaluation/completion times and processed order IDs/count. Customer-visible expired orders become stored cancellations; detailed cause remains in the run/audit trail. No money, order prices, addresses, coupons or stock ledger quantities are rewritten. Existing cancellation retry behavior remains unchanged.
Run keys are organization-scoped. Exact retries return the original result and do not reselect newer expired orders or duplicate holds/events/audits. Changing the limit with the same key returns `IDEMPOTENCY_CONFLICT` (409). New invocations use fresh keys, including empty successful runs. A failure anywhere before commit rolls back every cancellation/release/event and the run record; there is no partial-success report. Failed attempts are not persisted as successful history and can be retried with the same key.
History contains technical IDs, operator ID, parameters and result counts; tokens, customer profiles, addresses, request hashes and idempotency keys are absent. Existing pagination defaults/maxima apply. Native guards freeze run history, validate limits/hash/time order and ensure listed IDs are distinct, scoped cancelled orders with expired evidence.
After `pnpm build`, `pnpm workflows:expire` opens an application context, authenticates `WORKFLOW_TOKEN`, and invokes the same permission-checked workflow. Supply a normal active session token for a dedicated account with execution permissions. Optional `WORKFLOW_LIMIT` defaults to 10; optional UUID `WORKFLOW_RUN_KEY` fixes retry identity, otherwise a new UUID is generated. Result JSON contains only the safe run view; errors omit credentials and exit nonzero. Connections close on success/failure. Session expiry, account suspension and permission revocation apply to the command normally.
Configure the chosen deployment's scheduler to invoke the one-shot command periodically using a secret-managed token and non-overlapping job policy. Keep the same run key when retrying an uncertain attempt and rotate it for the next scheduled invocation. Drain larger backlogs with repeated bounded invocations; timeout/failure remains atomic, so reduce the batch size if needed. This repository does not install or enable a live scheduler, store a bypass/service password, refresh credentials, or create recurring Codex tasks.
The existing organization lock serializes sweeps and cancellation/catalog work; stock locks also coordinate independent inventory transactions. The batch limit bounds work but a busy organization can still experience lock latency; use a lower limit/cadence, then dedicated job workers if measured load requires it. No generic rule engine, configurable financial posting, stock reorder, production planning, standalone reservation cleanup, message delivery or ledger integration is enabled.
Deploy the additive run-table, pending-expiry scan index and Owner-permission migration before the application. Source order snapshots, previous migrations and historical financial records remain unchanged. Older code ignores run history, but cannot reopen orders already cancelled by a successful sweep. This branch is stacked on the pushed accounting and contribution branches; merge prerequisites first. Native multi-connection CI and deployment scheduler operation remain pending.
Verification covers eligible selection, untouched future/foreign orders, hold release/on-hand preservation, exact/conflicting retries, competing sweeps, run-history immutability, transaction rollback, dual permissions/live account status, strict limits, authenticated CLI/resource closure, schema drift and existing manual checkout/cancellation regressions.

View File

@ -0,0 +1,15 @@
# Packaging bills of materials (Phase 2J)
Packaging BOMs describe boxes, labels and other packaging materials required for a product variant. They reuse the production BOM revision model but have an independent revision sequence and active revision. Existing production BOMs remain `PRODUCTION`; packaging BOMs are `PACKAGING`. Both use immutable material name, code, unit and quantity snapshots.
| Method | Path | Permission | Purpose |
| ------ | ------------------------------------------------------------------- | ------------------ | ----------------------------------------------------------- |
| GET | `/api/v1/variants/:variantId/packaging-boms?status=&limit=&offset=` | `packaging.read` | List packaging revisions |
| GET | `/api/v1/variants/:variantId/packaging-boms/active` | `packaging.read` | Get active packaging recipe |
| POST | `/api/v1/variants/:variantId/packaging-boms` | `packaging.manage` | Create a complete draft |
| GET | `/api/v1/packaging-boms/:id` | `packaging.read` | Get one revision and its lines |
| POST | `/api/v1/packaging-boms/:id/activate` | `packaging.manage` | Activate a draft and supersede the previous active revision |
Creation uses the same body as the production BOM API: `outputQuantity` is the number of finished pieces yielded, and `lines` is an array of distinct `{ "materialId": "<uuid>", "quantity": "10.000" }` entries. Quantities use each material's native unit and exactly three decimal places. Packaging BOMs accept only active materials of kind `PACKAGING` or `LABEL`. Activation rechecks that those materials and the product variant remain active and compatible.
The database enforces independent sequential revisions, at most one active BOM of each kind per variant, immutable BOM kind and lines, and allowed lifecycle transitions. Production batches require a `PRODUCTION` BOM and reject packaging BOM IDs. Packaging usage, physical stock deduction and costing remain later milestones; creating or activating a packaging BOM does not move inventory.

View File

@ -0,0 +1,29 @@
# Packaging execution (Phase 2K)
After a production batch is completed, record the packaging and label materials used for its good output. One immutable record is allowed per batch. The selected packaging BOM must be active for the batch's variant when recorded; its revision and line identities remain attached afterward.
| Method | Path | Permission |
| ------ | ----------------------------------------------- | ------------------ |
| GET | `/api/v1/production-batches/:batchId/packaging` | `packaging.read` |
| POST | `/api/v1/production-batches/:batchId/packaging` | `packaging.record` |
Example POST:
```json
{
"bomId": "<active packaging BOM uuid>",
"idempotencyKey": "<uuid>",
"lines": [
{
"bomLineId": "<packaging BOM line uuid>",
"usedQuantity": "19.000",
"wastedQuantity": "1.000",
"wasteReason": "Torn box"
}
]
}
```
Submit every BOM line exactly once. Quantities are nonnegative, use exactly three decimal places, and use the line's material unit. Waste needs a reason. Good output must be a positive multiple of the packaging BOM output quantity. The response provides planned, used, wasted, and variance quantities for each line. An exact idempotent retry returns the existing record; a changed request with the same key returns `PACKAGING_REPLAY_CONFLICT`.
Packaging records are operational observations. They do not deduct physical stock or calculate costs. Those remain separate milestones pending a stock-location and costing policy.

View File

@ -0,0 +1,12 @@
# Packaging material stock (Phase 2P)
An operator can post an immutable packaging record's used and wasted material quantities to one warehouse. Each positive quantity becomes a separate negative material-stock ledger entry. Zero quantities create no entry. Packaging records do not change stock until explicitly posted.
| Method | Path | Permission |
| ------ | ------------------------------------------------------------- | ------------------ |
| GET | `/api/v1/production-batches/:batchId/packaging-stock-posting` | `inventory.read` |
| POST | `/api/v1/production-batches/:batchId/packaging-stock-posting` | `inventory.manage` |
POST body: `{ "warehouseId": "<uuid>", "idempotencyKey": "<uuid>" }`. A packaging record can be posted once. A same-key, same-request retry returns the original posting; reusing the key for another warehouse returns `PACKAGING_STOCK_REPLAY_CONFLICT`. A new key for an already posted record returns `PACKAGING_STOCK_ALREADY_POSTED`. The response identifies the source packaging line, material, kind and signed quantity for every ledger entry.
The selected warehouse must have enough of every packaging or label material for the **sum** of used and wasted quantities. `PACKAGING_STOCK_INSUFFICIENT` rejects the entire posting if any material is short. The database verifies each entry's source line, material, warehouse, kind and exact signed quantity, and prevents negative balances. Posting headers and ledger entries are append-only. Finished-goods output is documented separately; material transfers and adjustments remain later milestones.

View File

@ -0,0 +1,56 @@
# Verified product reviews (Phase 4B)
Purchase eligibility uses **manual staff verification of external completed-purchase evidence**, as selected for this milestone. It does not infer a purchase from a pending checkout, reserve stock, change order status, or claim gateway/delivery verification. Public reviews identify the method as `MANUAL`.
| Method | Path under `/api/v1` | Access |
| ------ | --------------------------------------------------------- | -------------------------------------------------------------------- |
| GET | `/reviews/eligibility` | Active user; own eligible verification IDs/variant IDs/dates |
| GET | `/reviews` | Active user; own submissions and computed moderation status |
| POST | `/reviews` | Active user; submit against own active verification |
| GET | `/review-verifications` | `reviews.verify`; optional `userId`, `variantId` filters |
| POST | `/review-verifications` | `reviews.verify`; record checked external purchase evidence |
| POST | `/review-verifications/:id/revoke` | `reviews.verify`; permanently revoke incorrect evidence |
| GET | `/review-moderation` | `reviews.read`; optional `variantId`, `status` filters |
| POST | `/review-moderation/:id/decision` | `reviews.moderate`; approve/reject, or hide an approved review |
| GET | `/storefront/:organizationId/products/:productId/reviews` | Public, shared storefront rate limit; approved verified reviews only |
All list endpoints use `limit` (1–100, default 25) and `offset` (0–10,000, default 0). Private resources are scoped to the authenticated organization; customers cannot read another user's eligibility or submissions. Unknown input fields are rejected.
Staff first check external evidence for the specific active customer and variant, then submit:
```json
{
"userId": "b92c23e5-794d-47e7-a7f4-428b84543fa1",
"variantId": "983a3a76-b3b7-4a63-9796-1393a63c2e0b",
"reference": "EXTERNAL-RECEIPT-123",
"note": "Receipt and completed purchase checked",
"idempotencyKey": "10fc5585-34a6-4ead-b5ce-d83418eb50df"
}
```
The verifier must differ from the customer. References are exact, trimmed identifiers (3–100 characters), unique per organization and variant, so one receipt may cover different variants but cannot be reassigned to multiple customers for the same variant. Notes require 3–1,000 characters. Historical variants can receive verification records, but new reviews require an active variant and published product.
Customer submission example:
```json
{
"verificationId": "62386f2a-4a74-4de2-93cc-ab60490c33e2",
"rating": 5,
"displayName": "Candle customer",
"title": "Lovely fragrance",
"body": "The candle burns evenly and smells wonderful.",
"idempotencyKey": "4aeec80a-4a4b-4d72-9b44-b385b2d06147"
}
```
Rating is an integer 1–5. Display name is an explicit public alias of 1–80 characters, title 3–160, body 10–2,000. Text is trimmed, plain single-line text. The API publishes the supplied alias rather than the user's private account name or email. One immutable submission is allowed per customer/organization/variant, even with repeated purchases. Editing, replacement after rejection, and customer withdrawal are outside this milestone; staff can hide approved content.
Moderation body: `{ "decision": "APPROVED", "note": "Content checked", "idempotencyKey": "<uuid>" }`. `REJECTED` is also allowed for a pending submission. A different staff member must moderate the customer's review. An approved review may receive one `HIDDEN` decision; hidden/rejected content cannot be republished. Notes require 3–1,000 characters. Revoked purchase evidence prevents approval. Moderation history is immutable and ordered; status is computed as `PENDING`, `APPROVED`, `REJECTED`, or `HIDDEN`.
Revocation body: `{ "reason": "Evidence was invalidated", "idempotencyKey": "<uuid>" }`, with a 3–1,000-character reason. Revoking evidence blocks new submissions and immediately excludes any associated review from public results. It does not rewrite moderation history. Customers' own review responses expose `purchaseVerified: false` after revocation.
Public responses include only review ID, variant ID, rating, explicit display name, title, body, creation date, `verifiedPurchase: true`, and `verificationMethod: "MANUAL"`. No customer/account identifiers, evidence references, staff notes, hashes, or moderation history are exposed. Public publication additionally requires a currently published product and active variant. Missing/private products return 404; a published product with no eligible reviews returns an empty array.
Each write uses a UUID idempotency key. Verification/revocation/moderation namespaces are separately organization-scoped; submissions are customer/organization-scoped. Identical retries return the current record; changed content returns a specific 409 replay conflict. Retries do not duplicate audit events. Self-verification/moderation and missing permissions return 403; scoped misses return 404; duplicate submissions, revoked eligibility, and invalid transitions return 409.
Deploy the append-only migration before the application. It adds four tables, scoped foreign keys, unique constraints, rating/text checks, immutable-record guards, and moderation/verification transition guards. Existing system Owner roles receive `reviews.verify`, `reviews.read`, and `reviews.moderate`; custom roles need explicit grants. Evidence references and notes are available only through the verification permission. Moderation queues expose the customer ID and decision history but omit evidence references and notes. Existing checkout/payment/provider behavior remains unchanged.

View File

@ -0,0 +1,18 @@
# Production batches (Phase 2H)
A batch records a planned number of finished pieces against one active BOM revision. Creation requires an active product variant and a planned quantity divisible by the BOM yield. The response includes planned material quantities scaled with exact decimal arithmetic from the immutable BOM lines. If that BOM is later superseded, the batch retains its original revision.
| Method | Path | Permission | Purpose |
| ------ | -------------------------------------------------------------- | ------------------- | --------------------------------------------- |
| GET | `/api/v1/production-batches?status=&variantId=&limit=&offset=` | `production.read` | List scoped batch metadata |
| GET | `/api/v1/production-batches/:id` | `production.read` | Read batch, BOM, planned materials and events |
| POST | `/api/v1/production-batches` | `production.manage` | Create a draft |
| POST | `/api/v1/production-batches/:id/start` | `production.manage` | Start a draft |
| POST | `/api/v1/production-batches/:id/complete` | `production.manage` | Record good and rejected output |
| POST | `/api/v1/production-batches/:id/cancel` | `production.manage` | Cancel a draft or started batch |
Create body: `{ "bomId": "<uuid>", "reference": "BATCH-001", "plannedQuantity": 20, "scheduledDate": "2026-10-01" }`. The date is optional. References are unique per organization, uppercase and at most 32 characters. Planned quantity is 1–100,000 pieces.
Completion body: `{ "goodQuantity": 18, "rejectedQuantity": 2, "rejectionReason": "Surface defects" }`. Good and rejected quantities must total the plan. A nonzero rejected quantity requires a reason. Cancellation body: `{ "reason": "Production halted" }`.
The permitted lifecycle is `DRAFT → IN_PROGRESS → COMPLETED` or `DRAFT/IN_PROGRESS → CANCELLED`. Every transition is audited. Completion and cancellation records are immutable. Database checks and triggers enforce state transitions, event reconciliation, organization scope and unique references. A batch does **not** adjust finished-goods stock or consume material; those require stock-location, consumption and QC decisions in later milestones.

View File

@ -0,0 +1,12 @@
# Production material stock (Phase 2O)
After a production batch is completed and usage has been recorded for every production BOM line, post its consumed and wasted material to one selected warehouse. Both quantities reduce on-hand stock in each material's native unit. Packaging consumption is documented separately; finished-goods receipts are a later milestone.
| Method | Path | Permission |
| ------ | ------------------------------------------------------------ | ------------------ |
| GET | `/api/v1/production-batches/:batchId/material-stock-posting` | `inventory.read` |
| POST | `/api/v1/production-batches/:batchId/material-stock-posting` | `inventory.manage` |
POST body: `{ "warehouseId": "<uuid>", "idempotencyKey": "<uuid>" }`. The posting returns one negative ledger entry per recorded production material usage event. A batch can be posted only once. Repeating the same key and request returns the original posting; changing the warehouse with that key returns `PRODUCTION_STOCK_REPLAY_CONFLICT`. A new key for an already posted batch returns `PRODUCTION_STOCK_ALREADY_POSTED`.
The requested warehouse must contain enough of every material for the batch's **total** consumed plus wasted quantity. Otherwise `PRODUCTION_STOCK_INSUFFICIENT` is returned and neither the posting nor any ledger entry is committed. Posting, ledger entries and balance changes share one database transaction. PostgreSQL independently checks the batch state, the usage event and material/warehouse relationship, exact signed quantity, and nonnegative balance. Posting headers and ledger entries cannot be edited or deleted.

View File

@ -0,0 +1,42 @@
# Phase 6A: release gates and production readiness
This milestone prepares repeatable verification and the launch procedure. It does not deploy the service or establish that the production environment is ready.
## Required merge checks
The `Backend quality` workflow runs on feature/fix pushes, main pushes and pull requests targeting main. Two independent jobs must pass:
| Job | Evidence |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `quality` | Frozen dependency installation, production dependency audit, embedded migration deployment/status/drift, immutable migration hashes, formatting, Prisma validation, TypeScript, tooling tests, coverage and compilation. |
| `native-postgres` | PostgreSQL 17 migration deployment/status/drift and the existing checkout, inventory, recovery and outbox concurrency tests. The gate fails on missing configuration, failures, empty results or any skipped/todo test. |
Configure a Docker-capable Gitea runner with the existing `ubuntu-latest` label, able to pull Node/PostgreSQL images, GitHub checkout and npm packages. Both jobs explicitly run in `node:24.15-bookworm`; the native job reaches its database by the `postgres` service hostname. Absolute action URLs avoid dependence on the instance's default action host; see [Gitea action compatibility](https://docs.gitea.com/usage/actions/comparison/).
Enable Actions for the repository and instance if it is disabled. An unavailable Actions page does not establish whether execution is disabled or the viewer lacks permission; inspect the authenticated settings and runner status before claiming the gates are active.
Add repository Actions secret `CI_POSTGRES_PASSWORD`: a random alphanumeric password used only for the disposable CI PostgreSQL service. Alphanumeric characters keep the connection URL valid without URL encoding. CI tests create and drop isolated databases, so the CI role needs `CREATEDB`. Never supply a production database URL or credentials. No service port is published to the runner host.
Express's transitive `proxy-addr` is pinned to 2.0.8 through the existing workspace override mechanism to address [GHSA-jqcg-44mw-7w3h](https://github.com/advisories/GHSA-jqcg-44mw-7w3h). Keep the production audit gate enabled; remove the override when the upstream dependency graph resolves a patched version itself.
In Gitea branch protection for `main`, require both job statuses using their exact names from the first successful run, require review, and disable force pushes. These repository settings are operational prerequisites; committing YAML does not enable branch protection or register a runner.
The existing `.drone.yml` is a separate build/deploy pipeline: a push to `main` publishes `git.midastix.com/ci-docker-repo-user/manicandle-backend:latest` and then invokes the server deployment script. It does not wait for the new Gitea jobs. Require the reviewed commit's checks before merging and avoid direct main pushes; otherwise deployment can run before validation completes. Its registry secrets are Drone repository secrets `docker_username` and `docker_password`, not `CI_POSTGRES_PASSWORD`. For `unauthorized: reqPackageAccess`, verify that the credentials belong to the target package owner or an authorized publisher, and use a Gitea token with package write access. Retrying a successful main build also runs deployment; server credentials and settings are managed manually by the operator.
Locally, run `pnpm check` and `pnpm db:test`. To exercise all six native-only tests and the surrounding regression cases, provide `TEST_DATABASE_URL` for a disposable native PostgreSQL administrator connection, then run `pnpm test:native`. The native command uses the normal test helper to create separate randomly named databases and remove them afterward. Embedded PostgreSQL is useful for ordinary tests but does not prove multi-connection locking behavior.
## Staging and launch procedure
1. Select a reviewed commit whose two CI jobs pass. Record its SHA, the previous release SHA and migration manifest. Agree on the launch feature cut: payments, carriers, live marketing and automated scheduler invocation remain deferred.
2. Provision the deployment target, TLS boundary and PostgreSQL 17 service. Store secrets outside Git and logs; separate migration, application and CI database roles. Verify connection limits against `DATABASE_POOL_SIZE` and replica count. Configure explicit HTTPS `CORS_ORIGINS`, `NODE_ENV=production` and `SWAGGER_ENABLED=false`. Configure recovery SMTP and the HTTPS recovery URL together before promising password recovery. Validate network-boundary rate limiting and proxy behavior against [VAPT readiness](vapt-readiness.md). Rate limits key on the client IP: set `TRUST_PROXY` to exactly the proxy hops in front of the service (for example the backend host's Nginx or Docker bridge, plus the frontend server whose Nginx forwards `/api`), and make every hop append `X-Forwarded-For $proxy_add_x_forwarded_for`. Without it, all visitors share one proxy IP and one rate-limit bucket. Never trust all addresses; a direct caller could then spoof its IP.
3. Build the existing image or compiled application from that exact commit. For a source installation: `pnpm install --frozen-lockfile`, `pnpm db:generate`, `pnpm build`. The current Dockerfile is a development-derived build; non-root runtime, graceful shutdown verification, image scanning and a tested deployment definition remain launch work, not proven by this CI milestone.
4. Take a database backup and restore it into isolated staging. Verify representative immutable audit, order, supplier-payment and inventory records after restore. Keep production secrets and outbound provider access out of the staging restore.
5. Run `pnpm migrations:check`, then `pnpm db:deploy` and `pnpm db:status` against staging with migration credentials. Start the built service with restricted application credentials. Verify `/api/v1/health/live` and `/api/v1/health/ready`; readiness must fail when PostgreSQL is unavailable.
6. Smoke-test login, denied/foreign-organization access, checkout and cancellation/hold release, procurement and stock reads, and expiry replay using staging identities. Confirm errors/logs omit credentials, tokens, addresses and document bodies. Exercise the deployment's shutdown/restart behavior before enabling traffic.
7. After the restore drill and staging checks pass, take a fresh production backup, apply reviewed additive migrations, deploy the same artifact and verify readiness before routing traffic. Keep a named operator monitoring health, errors, latency, database connections and integrity-sensitive flows during the first hour. Define alert destinations and acceptable baselines for the actual environment before launch.
## Rollback and remaining decisions
Stop scheduler invocation and route traffic back to the previous compatible application artifact if readiness, authentication, stock integrity or error/latency checks regress. Preserve additive tables, audit history, completed expiry runs and released holds; an application rollback cannot reopen cancelled orders. Never edit committed migration SQL or reverse financial/stock history with database deletes. A destructive schema rollback or database restore requires a separate incident decision, an assessed data-loss window and reconciliation.
Before public launch, the operator still needs to select the host/database/secret store, enable and observe both CI jobs, configure branch protection, validate backup restoration, complete monitoring and incident ownership, verify the runtime container/process lifecycle, settle tax/shipping/retention policy and perform deployed-environment security testing. Live providers and SaaS tenancy/billing remain separate decisions.

View File

@ -18,23 +18,70 @@ Suppliers, material/urli classification and compatibility, procurement, purchase
- 2B (implemented): purchase-order drafts, issuance, and immutable price snapshots.
- 2C (implemented): partial goods receipts and QC decisions.
- 2D (implemented): supplier invoice matching and auditable voids. Tax rules, payments, and documents remain separate milestones.
- 2E (implemented): external supplier payment records, partial balances, idempotent retries, and auditable reversals. Bank reconciliation and proof documents remain separate milestones.
- 2F (implemented): private PDF versions for supplier documents, independent validation, and gated downloads. Retention and malware scanning remain deployment decisions.
- 2G (implemented): versioned, organization-scoped product BOM drafts and activation with material snapshots. Production batches, consumption, wastage, packaging BOM and costing remain later milestones.
- 2H (implemented): production batch planning, lifecycle, yield reconciliation and immutable completion/cancellation records. Material consumption, stock posting, wastage, packaging BOM and costing remain later milestones.
- 2I (implemented): append-only material consumption and wastage events with plan-versus-actual summaries and idempotent retries. Physical stock posting, packaging BOM and costing remain later milestones.
- 2J (implemented): separate versioned packaging BOMs for packaging and label materials, with independent activation and permissions. Packaging execution, physical stock posting and costing remain later milestones.
- 2K (implemented): immutable packaging execution for completed batches, with BOM-line reconciliation, quantity variance, and idempotent retries. Physical stock posting and costing remain later milestones.
- 2L (implemented): append-only standard material cost rates by currency and live production/packaging BOM cost estimates with exact decimal arithmetic. Batch actual costing and physical stock posting remain later milestones.
- 2M (implemented): immutable completed-batch standard-cost snapshots from actual material and packaging use, frozen rate revisions, and exact totals. Physical stock posting remains dependent on the stock-location policy.
- 2N (implemented): per-warehouse raw-material balances and append-only stock postings from QC-accepted goods receipts. Production and packaging stock deduction, transfers, adjustments and finished-goods output remain later milestones.
- 2O (implemented): atomic per-warehouse production material stock deduction from completed-batch consumption and wastage events. Packaging stock deduction, transfers, adjustments and finished-goods output remain later milestones.
- 2P (implemented): atomic per-warehouse packaging and label stock deduction from recorded packaging use and wastage. Transfers, adjustments and finished-goods output remain later milestones.
- 2Q (implemented): single, idempotent finished-goods receipt per completed and stock-posted batch, crediting only good units to an organization-scoped warehouse variant balance. Material transfers and adjustments remain later milestones.
- 2R (implemented): atomic, idempotent warehouse-to-warehouse material transfers with balanced append-only ledger entries and scoped history. Manual material adjustments remain a later milestone.
- 2S (implemented): reasoned, permission-gated manual material-stock adjustments with signed immutable ledger entries, idempotent retries and nonnegative warehouse balances.
## Phase 3: B2B and white label
Business verification, price lists, MOQ, quotations, credit policies, samples, branding/artwork approvals, partner purchase orders, partial payments, custom candle requests and partner reporting.
- 3A (implemented): organization-scoped business profiles and manual staff verification with immutable submission/decision history. Partner login and automated external registry checks are outside this milestone.
- 3B (implemented): account-specific, currency-scoped variant price lists and minimum quantities, with verified-account activation, immutable active terms, and a merchandise price check. Order integration remains a later milestone.
- 3C (implemented): staff-issued merchandise quotations with immutable account and price snapshots, expiry, idempotent issuance, and one auditable customer response. Tax, shipping, stock reservation, and order conversion remain later milestones.
- 3D (implemented): staff-proposed credit limits and net terms with independent review, immutable decision history, suspension, and one active policy per business account and currency. Credit exposure, receivables, payment collection, and order enforcement remain later milestones.
- 3E (implemented): verified-account sample requests with immutable variant snapshots, independent review, and auditable manual dispatch references. Stock deduction, carrier integration, and sample billing remain later milestones.
- 3F (implemented): verified-account branding/artwork projects with private PostgreSQL file versions, independent per-version review, restricted downloads, and immutable approval history. Trademark clearance, malware scanning, and production linkage remain separate work.
- 3G (implemented): partner purchase orders captured from accepted, unexpired quotations with immutable merchandise snapshots, idempotent creation, unique partner references, and auditable cancellation. Fulfillment, stock reservation, tax, shipping, payments, and credit utilization remain separate milestones.
- 3H (implemented): manual, partial external receipt records for partner orders with exact merchandise-balance checks, idempotent reversals, and cancellation protection. Gateway collection, refunds, tax, shipping, and credit utilization remain separate milestones.
- 3I (implemented): verified-account custom candle specifications with immutable request capture, independent one-time staff review, scoped permissions, and idempotent retries. Quotation, artwork approval, BOM, and production linkage remain separate milestones.
- 3J (implemented): read-only partner order and payment summaries by currency, with exact outstanding merchandise balances, reversal/cancellation handling, and dedicated report permissions. Credit utilization, overdue receivables, and accounting remain separate milestones.
## Phase 4: Growth channels
Wishlist, verified reviews/moderation, seasonal campaigns, discounts, cart recovery, consent-aware messaging, Instagram, Etsy, WhatsApp, blogs/SEO and segmentation.
- 4A (implemented): private user wishlists with published-variant eligibility, duplicate-safe saves, repeatable removal, paginated current catalog views, unavailable-item redaction, and a per-user quota. Public sharing, guest lists, cart conversion, and notifications remain separate milestones.
- 4B (implemented): customer reviews gated by independent staff verification of external purchase evidence, immutable submissions, independent approval/rejection/hiding, evidence revocation, and a privacy-preserving public feed. Automated checkout/payment verification, review revisions, and rating analytics remain separate milestones.
- 4C (implemented): organization-scoped seasonal campaign drafts, versioned editing/publication, immutable published terms, reasoned cancellation, and time-windowed public collection discovery. Campaign discounts, media assets, outbound messaging, and channel integrations remain separate milestones.
- 4D (implemented): draft-bound campaign coupons, version-aware offer publication, public offer terms, and collection-only fixed/percentage checkout discounts with exact eligible-subtotal snapshots. Generic coupons retain their behavior; payment enablement, media assets and messaging remain separate milestones.
- 4E (implemented): private discovery and versioned resumption of carts idle for 24 hours, current catalog previews, unavailable-item redaction/removal, and audited activity tracking. Outbound recovery reminders remain dependent on consent-aware messaging and provider enablement.
- 4F (consent and eligibility implemented; live delivery deferred): explicit, independent email/WhatsApp opt-in and withdrawal for promotions/cart reminders, immutable versioned evidence, private history, and scoped live eligibility checks. Provider delivery, verified channel destinations, suppression-aware dispatch and unsubscribe links remain separate milestones.
- 4G (backend implemented): versioned blog drafts, separate publication permission, stable-slug public snapshots, private revisions, reasoned withdrawal, and public SEO metadata. Frontend pages, sitemap/canonical integration, rich text/media and historical revision restoration remain separate milestones; live channel integrations remain deferred.
- 4H (implemented): live staff segmentation for wishlist interest, recoverable carts and externally verified buyers, with deduplicated scoped account IDs/counts and optional separately permissioned current-consent filtering. Saved/custom rules, materialized audiences, exports and provider dispatch remain separate milestones.
## Phase 5: Community and optimization
Moderated forums, advanced analytics, forecasts, accounting adapters, profitability and workflow automation. SaaS tenancy/billing requires a separate architecture decision before implementation; an organization table alone does not provide tenant isolation.
- 5A (backend implemented): immutable discussion threads and flat replies, independent append-only approval/rejection/hiding, private author history, public alias-only discovery, parent visibility gates, and pending-submission quotas. Forum UI, editing/appeals, media, realtime features and notifications remain separate milestones.
- 5B (implemented): bounded UTC daily checkout activity and frozen variant-demand analytics, current-state/currency separation, exact snapshot values, scoped reporting permissions, and UTC application sessions. Paid/fulfilled revenue, financial recognition, forecasts, cross-channel analytics and dashboard UI remain separate milestones.
- 5C (baseline implemented): bounded historical daily capture-rate projections with exact unit arithmetic, zero-day inclusion, cancellation exclusion, visible evidence/staleness and current catalog flags. Validated sales/seasonal forecasts, confidence intervals, stock actions and automated production planning remain separate milestones.
- 5D (source contract implemented): scoped, bounded accounting source-event pages for supplier invoices/payments and partner receipts, with original/correction links, exact captured amounts and deterministic cursor traversal. Provider posting, ledger/tax mapping and durable export acknowledgements remain separate milestones.
- 5E (material-contribution baseline implemented): explicit net-price scenarios against sealed batch material/packaging cost, signed exact contribution, upward break-even prices and zero-output handling. Realized net profit, complete expense/COGS attribution, sales-to-batch linkage and dashboards remain separate milestones.
- 5F (expiry workflow implemented): bounded, idempotent expired-order sweeps with shared cancellation/hold-release logic, immutable run history, atomic rollback and an authenticated scheduler-ready command. Deployment scheduling, broader workflow rules, live providers and complete production launch work remain separate milestones.
## Phase 6: Production readiness
- 6A (release gates implemented; operational activation pending): separate embedded quality and native PostgreSQL concurrency jobs, fail-closed native test evidence, and a staging/backup/rollback runbook. Runner/secret setup, required branch checks, observed remote CI, hardened runtime, deployment infrastructure, restore drills, monitoring and live launch remain operational or later milestones.
## Definition of done for every feature
Small cohesive files; no duplicated business rules; unit tests for success, failure and boundaries; HTTP/integration tests where behavior crosses boundaries; schema migration and upgrade validation when persistence changes; documented API and permission contract; passing checks; focused Conventional Commit; reviewed pull request. Do not mark an entire phase complete until its end-to-end acceptance criteria pass.
## Decisions still needed
Provider accounts; deployment target and PostgreSQL service; tax/invoice and retention rules; stock location model; approval thresholds; Etsy sync direction; launch feature cut. Resolve each before its dependent milestone.
Provider accounts; deployment target and PostgreSQL service; tax/invoice and retention rules; approval thresholds; Etsy sync direction; launch feature cut. Raw-material and finished-goods stock use organization-scoped warehouses, with an explicit warehouse selected for each posting.

View File

@ -0,0 +1,32 @@
# Seasonal campaigns (Phase 4C)
Seasonal campaigns promote existing catalog collections during an explicit time window. They contain public title/summary copy and a collection link. Collection membership remains live; checkout prices and coupon eligibility continue to use the existing commerce rules.
| Method | Path under `/api/v1` | Access |
| ------ | --------------------------------------------- | --------------------------------------------------------------------- |
| GET | `/campaigns` | `campaigns.read`; optional persisted `state` filter |
| GET | `/campaigns/:id` | `campaigns.read`; scoped campaign and live status |
| POST | `/campaigns` | `campaigns.manage`; create draft with a reusable UUID idempotency key |
| PATCH | `/campaigns/:id` | `campaigns.manage`; edit draft with its current version |
| POST | `/campaigns/:id/publication` | `campaigns.manage`; publish/schedule the specified draft version |
| POST | `/campaigns/:id/cancellation` | `campaigns.manage`; cancel with a reason |
| GET | `/storefront/:organizationId/campaigns` | Public; active campaigns only |
| GET | `/storefront/:organizationId/campaigns/:slug` | Public; active campaign by slug |
Lists use the existing `limit` (1–100, default 25) and `offset` (0–10,000, default 0) contract. Staff resources are organization-scoped. Public routes share the existing storefront rate limit.
Create body: `slug` (existing collection slug format, at most 100 characters), `title` (1–160), `summary` (0–500; default empty), `collectionId` (UUID), `startsAt`, `endsAt`, and `idempotencyKey` (UUID). Times must be ISO timestamps with a timezone/UTC offset and are normalized to UTC milliseconds; end must be after start at that precision. Unknown fields and HTML/control characters in copy are rejected.
PATCH takes the current integer `version` plus one or more of `title`, `summary`, `collectionId`, `startsAt`, or `endsAt`. Slug and original creation identity are fixed. A stale version returns 409; callers should refetch after an ambiguous timeout before deciding whether to retry. A patch that changes no values leaves version and audit history unchanged. Actual changes increment version.
Persisted `state` is `DRAFT`, `PUBLISHED`, or `CANCELLED`. Staff responses also include computed `status`: `DRAFT`, `SCHEDULED`, `ACTIVE`, `ENDED`, or `CANCELLED`. Status describes the lifecycle/time window; public visibility additionally requires an eligible collection. Active visibility uses `startsAt <= now < endsAt`; it requires no scheduler, worker, or cron job. Publication requires an unexpired end time and a collection in the caller's organization containing at least one published product with an active variant.
Publication body is `{ "version": 0 }`, using the draft version just read. A stale version returns 409. Published campaign terms cannot be edited. Repeating the original publication version returns its current representation without another audit event; a different version conflicts. Cancelled campaigns cannot be published. Cancellation body is `{ "reason": "Campaign withdrawn" }` (3–500 characters). Cancellation applies to drafts and published campaigns; repeating the same reason returns the current record, while a conflicting reason returns 409. Cancellation metadata is immutable. No hard-delete endpoint exists.
Public responses include only campaign ID, slug, title, summary, UTC start/end, and collection ID/name/slug. Drafts, future, expired, and cancelled campaigns are absent. Changing a linked group to a category or removing all eligible products also hides the campaign. An inactive or unknown public slug returns 404. Public collection links can use the existing storefront product list with `groupId`.
Creation keys are organization-scoped and retained with the campaign. Identical retries return the current representation; different original content using the same key returns 409. Unique slugs are organization-scoped. All actual writes record audit events within the existing transaction/organization lock. Inputs derive organization and staff identity from the bearer session.
Acceptance: private drafts; exact start/end boundaries; versioned edits; immutable published terms; repeatable publication/cancellation; scoped permissions/collections; dynamic collection suppression; public-field allowlist; preserved checkout behavior. Verify with `pnpm check` and `pnpm db:test`, plus focused Jest campaign tests. Implementation lives in `src/campaigns`, tests in `test`, and the additive migration in `prisma/migrations`.
Deploy the migration before the application. It adds one campaign table, scoped foreign keys, unique/index/time constraints, and lifecycle guards, and grants `campaigns.read`/`campaigns.manage` to existing system Owner roles. Custom roles require explicit grants. Rollback can redeploy the previous application while retaining the new table and audit history. This milestone provides collection discovery; campaign discounts, media assets, outbound messaging, and channel integrations are separate work.

View File

@ -0,0 +1,21 @@
# Phase 2F: private supplier documents
Supplier documents are stored as PostgreSQL `bytea` with a strict 2 MiB PDF limit. The API has no public file URL. Metadata responses never contain file bytes.
All routes are under `/api/v1` and require a bearer token. `supplier_document.read` permits metadata reads and approved downloads. `supplier_document.manage` permits creating document records and uploading versions. `supplier_document.validate` permits an independent reviewer to approve or reject a version and to download pending versions for review. A reviewer also needs `supplier_document.read` to use the review download route. Records are organization scoped.
| Method | Route | Purpose |
| ------ | ------------------------------------------ | -------------------------------------------------- |
| GET | `/suppliers/:supplierId/documents` | Page through a supplier's document records |
| POST | `/suppliers/:supplierId/documents` | Create a document identity |
| GET | `/supplier-documents/:id` | Read metadata and all versions, newest first |
| POST | `/supplier-documents/:id/versions` | Upload a new PDF version as multipart field `file` |
| GET | `/supplier-document-versions/:id` | Read version metadata and decision |
| GET | `/supplier-document-versions/:id/download` | Download approved PDF or review a pending version |
| POST | `/supplier-document-versions/:id/decision` | Approve or reject a version exactly once |
Create a document with `{"code":"TAX-CERT","kind":"TAX_CERTIFICATE","title":"Supplier tax certificate"}`. Kinds are `REGISTRATION`, `TAX_CERTIFICATE`, `COMPLIANCE_CERTIFICATE`, and `OTHER`. The code is normalized to uppercase and unique per supplier. Up to 100 documents per supplier and 20 sequential versions per document are supported. Lists use `limit` (default 25, maximum 100) and `offset` (default 0).
Upload a PDF with a simple ASCII `.pdf` filename. The server checks filename, MIME type, PDF signature, EOF marker, and byte size, then records SHA-256, uploader, and version number. Each version and validation decision is immutable. Reject with `{"outcome":"REJECTED","reason":"Expired"}` or approve with `{"outcome":"APPROVED"}`. The uploader cannot validate their own version. General readers can download only approved versions. Downloads are checksum-verified and sent with `Content-Disposition: attachment`, `nosniff`, `no-store`, and a sandbox content-security policy.
Validation is a human review step, not an antivirus scan or a legal certification. Operators should review files in an isolated environment. PostgreSQL backup access and retention need the same controls as the API; the product retention policy and automated malware scanning remain deployment decisions. A later storage adapter can move bytes to private object storage without changing document identities or version decisions.

View File

@ -15,4 +15,4 @@ The list accepts `limit` (default 25, maximum 100) and `offset` (default 0) quer
An invoice must refer to one issued purchase order. Each line uses the order's unit price; total merchandise, tax, and shipping charges are added with exact decimal arithmetic. Cumulative active invoice quantity cannot exceed QC-accepted receipt quantity. A voided invoice releases its billed quantity, but its original record and number remain in the audit trail. The database also enforces scoped foreign keys, line and header totals, invoice price matching, accepted-quantity limits, and immutability.
Tax and shipping amounts are transcribed from the supplier document. The backend does not calculate tax rules or approve price variances in this phase. Supplier payments, payment status, and document attachments remain future work. No payment should be initiated solely from a recorded invoice until those controls exist.
Tax and shipping amounts are transcribed from the supplier document. The backend does not calculate tax rules or approve price variances in this phase. [Supplier payment records](supplier-payments-api.md) can now be attached to invoices, but bank reconciliation and document attachments remain future work.

View File

@ -0,0 +1,18 @@
# Phase 2E: supplier payment records
This API records evidence of payments made outside Mani Candles. It does not initiate a bank transfer, call a payment gateway, or verify settlement with a bank.
All routes are under `/api/v1` and require a bearer token. Reads require `procurement.read`. Recording and reversing a payment require the separate `supplier_payment.manage` permission. Every lookup is scoped to the signed-in organization.
| Method | Route | Purpose |
| ------ | ---------------------------------------- | ---------------------------------------------------------- |
| GET | `/supplier-invoices/:invoiceId/payments` | Page through payments and read paid and outstanding totals |
| POST | `/supplier-invoices/:invoiceId/payments` | Record a partial or full payment |
| GET | `/supplier-payments/:id` | Read a payment and its reversal, if any |
| POST | `/supplier-payments/:id/reverse` | Reverse one payment with a reason |
Record with `{"idempotencyKey":"<uuid>","reference":"UTR-12345","method":"BANK_TRANSFER","amount":"50.00","paidDate":"2026-09-28"}`. Methods are `BANK_TRANSFER`, `UPI`, `CHEQUE`, `CASH`, and `OTHER`. The reference is normalized to uppercase and must be unique within the organization, including after reversal. For cash, use a unique internal voucher reference. Payment amount uses exactly two decimal places and must be positive. Currency comes from the invoice.
Reusing the same idempotency key with the same invoice and payload returns the original payment; a different payload returns `PAYMENT_REPLAY_CONFLICT`. A payment cannot exceed the invoice's outstanding total or be recorded against a void invoice. Reverse with `{"reason":"Bank transfer returned"}`. The reversal is immutable, releases the amount from the invoice balance, and can occur only once. An invoice with an active payment cannot be voided; reverse its payments first. All writes create audit events.
The list accepts `limit` (default 25, maximum 100) and `offset` (default 0). It returns `payableTotal`, `paidTotal`, `outstandingTotal`, `currency`, and the requested page of `payments`. Totals include all active payments regardless of the page. These are recorded accounting amounts, not bank-verified settlement status. Bank reconciliation, proof documents, and approval thresholds remain future work.

17
docs/wishlist-api.md Normal file
View File

@ -0,0 +1,17 @@
# Private wishlists (Phase 4A)
Endpoints under `/api/v1/wishlist` require an active bearer session. Like private addresses and carts, they need no staff permission. Ownership comes exclusively from the session; there is no staff endpoint for another user's wishlist and caller-supplied ownership fields are rejected.
| Method | Path | Purpose |
| ------ | ------------- | ---------------------------------------------------------------------------------- |
| GET | `/` | List own saved variants; `limit` defaults to 25 (1–100), `offset` to 0 (0–10,000) |
| PUT | `/:variantId` | Save a published, active variant in the current organization; send no body or `{}` |
| DELETE | `/:variantId` | Remove own saved variant; returns 204, including when already absent |
Each list/save response item contains `id`, `variantId`, `savedAt`, `available`, and `variant`. Available items include current variant name, SKU, exact two-decimal price, currency, and product ID/name/slug. Prices are live catalog prices, not frozen checkout prices. `available` means published and active; it does not indicate warehouse stock or reserve inventory.
Unpublished, archived, or inactive saved variants remain in the list with `available: false` and `variant: null`. This prevents leaking private catalog details while allowing removal. Repeating PUT for an existing saved item returns its current representation, even if it has become unavailable. A new save of an unavailable, missing, or out-of-organization variant returns 404 (`WISHLIST_ITEM_UNAVAILABLE`).
A user may save at most 100 variants. A new item at the limit returns 409 (`WISHLIST_LIMIT`); existing-item retries remain valid. List ordering is newest saved first, with ID as a stable tie-breaker. PUT retries keep the same ID and timestamp. After deletion, a later save creates a new item. Concurrent API mutations use the existing transaction/organization lock; a database unique constraint also prevents duplicate user/organization/variant entries.
Save/remove actions produce one audit event per actual change. There are no public shares, guest wishlists, notifications, cart conversion, or inventory effects in this milestone. Composite database foreign keys enforce user and variant organization scope. Deploy the append-only migration before the application; existing records and permissions are unchanged.

View File

@ -0,0 +1,408 @@
# Graph Report - backend (2026-10-04)
## Corpus Check
- cluster-only mode — file stats not available
## Summary
- 1832 nodes · 6368 edges · 81 communities (65 shown, 16 thin omitted)
- Extraction: 95% EXTRACTED · 5% INFERRED · 0% AMBIGUOUS · INFERRED: 293 edges (avg confidence: 0.8)
- Token cost: 0 input · 0 output
## Graph Freshness
- Built from commit: `131aef79`
- Run `git rev-parse HEAD` and compare to check if the graph is stale.
- Run `graphify update .` after code changes (no API cost).
## Community Hubs (Navigation)
- Community 0
- Community 1
- Community 2
- Community 3
- Community 4
- Community 5
- Community 6
- Community 7
- Community 8
- Community 9
- Community 10
- Community 11
- Community 12
- Community 13
- Community 14
- Community 15
- Community 16
- Community 17
- Community 18
- Community 19
- Community 20
- Community 21
- Community 22
- Community 23
- Community 24
- Community 25
- Community 26
- Community 27
- Community 28
- Community 29
- Community 30
- Community 31
- Community 32
- Community 33
- Community 34
- Community 35
- Community 36
- Community 37
- Community 38
- Community 39
- Community 40
- Community 41
- Community 42
- Community 43
- Community 44
- Community 45
- Community 46
- Community 47
- Community 48
- Community 49
- Community 50
- Community 51
- Community 52
- Community 53
- Community 54
- Community 55
- Community 56
- Community 57
- Community 58
- Community 59
- Community 60
- Community 61
- Community 62
- Community 63
- Community 64
- Community 65
- Community 66
- Community 67
- Community 68
- Community 69
- Community 70
- Community 71
- Community 72
- Community 73
- Community 74
- Community 75
- Community 76
- Community 77
- Community 78
- Community 79
## God Nodes (most connected - your core abstractions)
1. `Principal` - 434 edges
2. `AppError` - 267 edges
3. `CurrentPrincipal` - 219 edges
4. `RequirePermission()` - 198 edges
5. `@nestjs/common` - 141 edges
6. `recordAudit()` - 134 edges
7. `DatabaseService` - 115 edges
8. `AccessStore` - 103 edges
9. `PageInput` - 55 edges
10. `SchemaPipe` - 51 edges
## Surprising Connections (you probably didn't know these)
- `assertReturn()` --calls--> `AppError` [EXTRACTED]
src/fulfillment/fulfillment.policy.ts → src/common/errors/app-error.ts
- `assertShipment()` --calls--> `AppError` [EXTRACTED]
src/fulfillment/fulfillment.policy.ts → src/common/errors/app-error.ts
- `captureDecision()` --calls--> `AppError` [EXTRACTED]
src/payments/payment.policy.ts → src/common/errors/app-error.ts
- `refundAmount()` --calls--> `AppError` [EXTRACTED]
src/payments/payment.policy.ts → src/common/errors/app-error.ts
- `RecoveryController` --references--> `Public()` [EXTRACTED]
src/identity/recovery.controller.ts → src/identity/access.decorator.ts
## Import Cycles
- None detected.
## Communities (81 total, 16 thin omitted)
### Community 0 - "Community 0"
Cohesion: 0.05
Nodes (27): PartnerOrderCancelStore, CancelPartnerOrderInput, cancelPartnerOrderSchema, CreatePartnerOrderInput, createPartnerOrderSchema, PartnerOrderQuery, partnerOrderQuerySchema, PartnerOrderStore (+19 more)
### Community 1 - "Community 1"
Cohesion: 0.07
Nodes (29): BomLine, calculateBatchCost(), Decimal, PackagingLine, quantity(), Rate, Usage, estimateLineCost() (+21 more)
### Community 2 - "Community 2"
Cohesion: 0.12
Nodes (17): latest, Db, Db, Db, requireSample(), sampleInclude, Snapshot, snapshotView (+9 more)
### Community 3 - "Community 3"
Cohesion: 0.11
Nodes (16): ensureDefault(), artworkInclude, artworkVersionSelect, Db, requireArtwork(), requireArtworkVersion(), isVerifiedBusinessAccount(), editableProduct() (+8 more)
### Community 4 - "Community 4"
Cohesion: 0.07
Nodes (10): catalogWhere(), CatalogQuery, ProductInput, VariantInput, ProductStore, ProductsController, StorefrontController, StorefrontStore (+2 more)
### Community 5 - "Community 5"
Cohesion: 0.09
Nodes (11): BomListQuery, CreateBomInput, createBomSchema, quantity, auditFor(), BomStore, permissionFor(), BomsController (+3 more)
### Community 6 - "Community 6"
Cohesion: 0.10
Nodes (16): BusinessController, businessStatus(), presentBusiness(), businessProfileSchema, BusinessQuery, businessQuerySchema, CreateBusinessInput, createBusinessSchema (+8 more)
### Community 7 - "Community 7"
Cohesion: 0.07
Nodes (15): CheckoutInput, checkoutSnapshot(), CheckoutStore, decimal(), discountFor(), minor(), OrderAdminController, OrderStore (+7 more)
### Community 8 - "Community 8"
Cohesion: 0.08
Nodes (4): BatchCostStore, DatabaseService, AccessStore, RoleStore
### Community 9 - "Community 9"
Cohesion: 0.20
Nodes (12): @nestjs/common, @nestjs/core, SchemaPipe, Argument, CurrentPrincipal, Public(), PUBLIC_ROUTE, REQUIRED_PERMISSION (+4 more)
### Community 10 - "Community 10"
Cohesion: 0.12
Nodes (15): orderStatus(), orderView(), holdOrderStock(), assertReplay(), commandHash(), enqueueEvent(), adjustedBalance(), Adjustment (+7 more)
### Community 11 - "Community 11"
Cohesion: 0.08
Nodes (11): MAX_ARTWORK_BYTES, ArtworkReviewStore, ArtworkDecisionInput, artworkDecisionSchema, ArtworkQuery, artworkQuerySchema, CreateArtworkInput, createArtworkSchema (+3 more)
### Community 12 - "Community 12"
Cohesion: 0.09
Nodes (18): profileSnapshot(), calculatePriceCheck(), PriceTerms, assertEligiblePriceVariants(), Db, requireBusinessAccount(), requirePriceList(), PriceListItemStore (+10 more)
### Community 13 - "Community 13"
Cohesion: 0.09
Nodes (13): BatchCostController, MaterialCostRatesController, PackagingCostController, ProductionCostController, CostingModule, CostHistoryQuery, costHistoryQuerySchema, CostQuery (+5 more)
### Community 14 - "Community 14"
Cohesion: 0.10
Nodes (24): zod, addressSchema, optionalText(), createPriceListSchema, priceCheckSchema, priceListItemSchema, priceListQuerySchema, groupSchema (+16 more)
### Community 15 - "Community 15"
Cohesion: 0.12
Nodes (10): ProcurementController, code, MaterialInput, materialSchema, ProcurementQuery, SupplierInput, SupplierMaterialInput, supplierMaterialSchema (+2 more)
### Community 16 - "Community 16"
Cohesion: 0.13
Nodes (11): BatchListQuery, CancelBatchInput, cancelBatchSchema, CompleteBatchInput, completeBatchSchema, CreateBatchInput, createBatchSchema, BatchStore (+3 more)
### Community 17 - "Community 17"
Cohesion: 0.08
Nodes (17): assignmentsSchema, createUserSchema, email, name, password, recoveryRequestSchema, recoveryResetSchema, RoleInput (+9 more)
### Community 18 - "Community 18"
Cohesion: 0.12
Nodes (21): ErrorCode, formatMaterialQuantity(), parseMaterialQuantity(), plannedMaterialQuantity(), requireAvailableMaterials(), stockPostingHash(), requestHash(), usageSelect (+13 more)
### Community 19 - "Community 19"
Cohesion: 0.12
Nodes (11): AddressesModule, AppModule, B2bModule, CatalogModule, CheckoutModule, DatabaseModule, HealthModule, IdentityModule (+3 more)
### Community 20 - "Community 20"
Cohesion: 0.12
Nodes (11): SampleActionStore, SampleDecisionInput, sampleDecisionSchema, SampleDispatchInput, sampleDispatchSchema, SampleQuery, sampleQuerySchema, SampleRequestInput (+3 more)
### Community 21 - "Community 21"
Cohesion: 0.13
Nodes (3): RequirePermission(), PageInput, StockController
### Community 22 - "Community 22"
Cohesion: 0.14
Nodes (18): helmet, @nestjs/platform-express, @nestjs/swagger, @nestjs/testing, reflect-metadata, supertest, ApiExceptionFilter, ERRORS (+10 more)
### Community 23 - "Community 23"
Cohesion: 0.08
Nodes (25): engines, node, name, packageManager, private, version, dotenv, @electric-sql/pglite (+17 more)
### Community 24 - "Community 24"
Cohesion: 0.13
Nodes (7): StorefrontGuard, AuditController, AuthRateGuard, AuthService, LoginInput, loginSchema, RateLimitService
### Community 25 - "Community 25"
Cohesion: 0.12
Nodes (9): amount, SupplierPaymentInput, SupplierPaymentReversalInput, supplierPaymentReversalSchema, supplierPaymentSchema, activePayments(), SupplierPaymentStore, InvoicePaymentsController (+1 more)
### Community 26 - "Community 26"
Cohesion: 0.12
Nodes (12): B2B_ARTWORK_ERRORS, B2B_CREDIT_ERRORS, B2B_ERRORS, B2B_ORDER_ERRORS, B2B_PAYMENT_ERRORS, B2B_PRICE_ERRORS, B2B_QUOTE_ERRORS, B2B_SAMPLE_ERRORS (+4 more)
### Community 27 - "Community 27"
Cohesion: 0.14
Nodes (6): DeliveryMessage, DeliveryPort, DeliveryService, DeliveryStore, DisabledDelivery, OperationsModule
### Community 28 - "Community 28"
Cohesion: 0.12
Nodes (5): RecoveryInput, RecoveryController, RecoveryMailer, RecoveryService, RecoveryStore
### Community 29 - "Community 29"
Cohesion: 0.14
Nodes (8): MaterialTransferController, MaterialTransferInput, MaterialTransferQuery, materialTransferSchema, MaterialTransferStore, present(), Transfer, transferView
### Community 30 - "Community 30"
Cohesion: 0.14
Nodes (8): QuoteResponseStore, IssueQuoteInput, issueQuoteSchema, QuoteQuery, quoteQuerySchema, QuoteResponseInput, quoteResponseSchema, QuotesController
### Community 31 - "Community 31"
Cohesion: 0.17
Nodes (9): CreditPoliciesController, CreditDecisionInput, creditDecisionSchema, CreditQuery, creditQuerySchema, ProposeCreditInput, proposeCreditSchema, SuspendCreditInput (+1 more)
### Community 32 - "Community 32"
Cohesion: 0.09
Nodes (22): scripts, admin:prepare-local, admin:seed-local, bootstrap:owner, build, check, db:deploy, db:generate (+14 more)
### Community 33 - "Community 33"
Cohesion: 0.11
Nodes (7): amount, common, CouponInput, couponSchema, couponStatusSchema, CouponStore, CouponsController
### Community 34 - "Community 34"
Cohesion: 0.14
Nodes (5): PurchaseOrderInput, PurchaseOrderQuery, PurchaseOrderStore, reference(), PurchaseOrdersController
### Community 35 - "Community 35"
Cohesion: 0.14
Nodes (4): SupplierDocumentStore, SupplierDocumentController, SupplierDocumentsController, SupplierDocumentVersionsController
### Community 37 - "Community 37"
Cohesion: 0.16
Nodes (6): MaterialStockController, MaterialStockQuery, receiptStockPostingSchema, itemView, MaterialStockStore, present()
### Community 38 - "Community 38"
Cohesion: 0.14
Nodes (6): MaterialAdjustmentController, MaterialAdjustmentInput, MaterialAdjustmentQuery, MaterialAdjustmentStore, present(), scaledDelta()
### Community 39 - "Community 39"
Cohesion: 0.13
Nodes (11): folder, hashes, manifest, names, root, stamps, commands, credentialFile (+3 more)
### Community 40 - "Community 40"
Cohesion: 0.15
Nodes (3): AddressInput, AddressStore, AddressesController
### Community 41 - "Community 41"
Cohesion: 0.18
Nodes (9): inspectArtwork(), TYPES, verifiedArtwork(), fileDigest(), inspectPdf(), UploadedDocument, verifiedContent(), documentView (+1 more)
### Community 42 - "Community 42"
Cohesion: 0.17
Nodes (6): creditInclude, Db, presentCreditPolicy(), requireCreditPolicy(), CreditReviewStore, CreditStore
### Community 43 - "Community 43"
Cohesion: 0.16
Nodes (3): CreateUserInput, UserStore, UsersController
### Community 44 - "Community 44"
Cohesion: 0.12
Nodes (17): devDependencies, @electric-sql/pglite, @electric-sql/pglite-socket, jest, @nestjs/testing, pg, prettier, prisma (+9 more)
### Community 45 - "Community 45"
Cohesion: 0.18
Nodes (3): CreatePriceListInput, PriceListQuery, PriceListsController
### Community 46 - "Community 46"
Cohesion: 0.16
Nodes (3): GroupInput, GroupStore, GroupsController
### Community 47 - "Community 47"
Cohesion: 0.15
Nodes (3): PricingController, PricingInput, PricingStore
### Community 49 - "Community 49"
Cohesion: 0.17
Nodes (3): ReservationInput, ReservationTransitionStore, ReservationsController
### Community 50 - "Community 50"
Cohesion: 0.12
Nodes (15): compilerOptions, emitDecoratorMetadata, esModuleInterop, experimentalDecorators, isolatedModules, module, moduleResolution, noUnusedLocals (+7 more)
### Community 51 - "Community 51"
Cohesion: 0.20
Nodes (3): Principal, OperationsController, OperationsStore
### Community 52 - "Community 52"
Cohesion: 0.18
Nodes (4): MaterialReceiptPostingController, MaterialReceiptPostingStore, present(), ReceiptStockPostingInput
### Community 53 - "Community 53"
Cohesion: 0.22
Nodes (3): GoodsReceiptStore, GoodsReceiptsController, ReceiptInspectionController
### Community 54 - "Community 54"
Cohesion: 0.15
Nodes (13): dependencies, dotenv, helmet, @nestjs/common, @nestjs/core, @nestjs/platform-express, @nestjs/swagger, nodemailer (+5 more)
### Community 55 - "Community 55"
Cohesion: 0.22
Nodes (6): InspectionInput, inspectionSchema, quantity, ReceiptInput, receiptSchema, quantity()
### Community 56 - "Community 56"
Cohesion: 0.27
Nodes (5): MAX_DOCUMENT_BYTES, DocumentDecisionInput, documentDecisionSchema, SupplierDocumentInput, supplierDocumentSchema
### Community 58 - "Community 58"
Cohesion: 0.18
Nodes (3): PackagingStockPostingController, PackagingStockPostingStore, present()
### Community 61 - "Community 61"
Cohesion: 0.18
Nodes (7): CapturedPayment, GatewayPort, PaymentRequest, RefundRequest, captureDecision(), ExpectedPayment, refundAmount()
### Community 63 - "Community 63"
Cohesion: 0.25
Nodes (3): BootstrapService, derive(), PasswordService
### Community 67 - "Community 67"
Cohesion: 0.46
Nodes (4): nodemailer, ENVIRONMENT, hashToken(), issueToken()
### Community 70 - "Community 70"
Cohesion: 0.29
Nodes (6): ./tsconfig.json, compilerOptions, rootDir, exclude, extends, include
### Community 72 - "Community 72"
Cohesion: 0.38
Nodes (4): BomKind, bomView, isPackagingMaterial(), PACKAGING_MATERIAL_KINDS
### Community 73 - "Community 73"
Cohesion: 0.33
Nodes (4): assertReturn(), assertShipment(), rank, TrackingStatus
### Community 75 - "Community 75"
Cohesion: 0.40
Nodes (4): cartLineSchema, cartVersionSchema, checkoutSchema, couponCode
### Community 76 - "Community 76"
Cohesion: 0.70
Nodes (3): MaterialUsageInput, MaterialUsageQuery, materialUsageSchema
### Community 77 - "Community 77"
Cohesion: 0.60
Nodes (3): PackagingRunInput, packagingRunSchema, quantity
## Knowledge Gaps
- **175 isolated node(s):** `Db`, `BomLine`, `Decimal`, `PackagingLine`, `Rate` (+170 more)
These have ≤1 connection - possible missing edges. (Counts symbols only; 457 node(s) total have ≤1 connection when file, concept and rationale nodes are included.)
- **16 thin communities (<3 nodes) omitted from report** — run `graphify query` to explore isolated nodes.
## Suggested Questions
_Questions this graph is uniquely positioned to answer:_
- **Why does `Principal` connect `Community 51` to `Community 0`, `Community 1`, `Community 2`, `Community 3`, `Community 4`, `Community 5`, `Community 6`, `Community 7`, `Community 9`, `Community 10`, `Community 11`, `Community 12`, `Community 13`, `Community 14`, `Community 15`, `Community 16`, `Community 17`, `Community 18`, `Community 20`, `Community 21`, `Community 24`, `Community 25`, `Community 29`, `Community 30`, `Community 31`, `Community 33`, `Community 34`, `Community 35`, `Community 36`, `Community 37`, `Community 38`, `Community 40`, `Community 41`, `Community 42`, `Community 43`, `Community 45`, `Community 46`, `Community 47`, `Community 48`, `Community 49`, `Community 52`, `Community 53`, `Community 55`, `Community 56`, `Community 57`, `Community 58`, `Community 59`, `Community 62`, `Community 65`, `Community 66`, `Community 68`, `Community 69`, `Community 72`, `Community 74`, `Community 76`, `Community 77`?**
_High betweenness centrality (0.314) - this node is a cross-community bridge._
- **Why does `@nestjs/common` connect `Community 9` to `Community 0`, `Community 1`, `Community 2`, `Community 3`, `Community 4`, `Community 5`, `Community 6`, `Community 10`, `Community 11`, `Community 12`, `Community 13`, `Community 14`, `Community 15`, `Community 16`, `Community 17`, `Community 18`, `Community 19`, `Community 20`, `Community 22`, `Community 23`, `Community 24`, `Community 27`, `Community 29`, `Community 30`, `Community 31`, `Community 37`, `Community 41`, `Community 42`, `Community 53`, `Community 56`, `Community 63`, `Community 67`, `Community 72`, `Community 76`, `Community 77`?**
_High betweenness centrality (0.145) - this node is a cross-community bridge._
- **Why does `AppError` connect `Community 3` to `Community 0`, `Community 1`, `Community 2`, `Community 4`, `Community 5`, `Community 6`, `Community 7`, `Community 9`, `Community 10`, `Community 11`, `Community 12`, `Community 13`, `Community 15`, `Community 16`, `Community 17`, `Community 18`, `Community 21`, `Community 24`, `Community 25`, `Community 27`, `Community 28`, `Community 29`, `Community 34`, `Community 35`, `Community 36`, `Community 37`, `Community 38`, `Community 40`, `Community 41`, `Community 42`, `Community 46`, `Community 48`, `Community 52`, `Community 53`, `Community 55`, `Community 56`, `Community 57`, `Community 58`, `Community 60`, `Community 61`, `Community 62`, `Community 63`, `Community 67`, `Community 68`, `Community 69`, `Community 72`, `Community 73`, `Community 74`?**
_High betweenness centrality (0.112) - this node is a cross-community bridge._
- **What connects `Db`, `BomLine`, `Decimal` to the rest of the system?**
_175 weakly-connected nodes found - possible documentation gaps or missing edges._
- **Should `Community 0` be split into smaller, more focused modules?**
_Cohesion score 0.05485232067510549 - nodes in this community are weakly interconnected._
- **Should `Community 1` be split into smaller, more focused modules?**
_Cohesion score 0.07197763801537387 - nodes in this community are weakly interconnected._
- **Should `Community 2` be split into smaller, more focused modules?**
_Cohesion score 0.11901306240928883 - nodes in this community are weakly interconnected._

360
graphify-out/graph.html Normal file

File diff suppressed because one or more lines are too long

96840
graphify-out/graph.json Normal file

File diff suppressed because it is too large Load Diff

1502
graphify-out/manifest.json Normal file

File diff suppressed because it is too large Load Diff

View File

@ -2,6 +2,8 @@ module.exports = {
preset: 'ts-jest',
moduleNameMapper: { '^(\\.{1,2}/.*)\\.js$': '$1' },
testEnvironment: 'node',
roots: ['<rootDir>/src', '<rootDir>/test'],
testTimeout: 60000,
testMatch: ['**/*.spec.ts'],
collectCoverageFrom: [
'src/**/*.ts',

View File

@ -19,13 +19,18 @@
"db:validate": "prisma validate",
"db:migrate": "prisma migrate dev",
"db:deploy": "prisma migrate deploy",
"check": "pnpm migrations:check && pnpm format:check && pnpm db:validate && pnpm typecheck && pnpm test:coverage && pnpm build",
"check": "pnpm migrations:check && pnpm format:check && pnpm db:validate && pnpm typecheck && pnpm test:tooling && pnpm test:coverage && pnpm build",
"test:tooling": "node --test scripts/test/*.test.mjs",
"test:native": "node scripts/test-native.mjs",
"start:watch": "node --watch dist/main.js",
"db:status": "prisma migrate status",
"bootstrap:owner": "node dist/cli/bootstrap-owner.js",
"workflows:expire": "node dist/cli/workflow-expiry.js",
"admin:prepare-local": "node dist/cli/local-admin.js prepare",
"admin:seed-local": "node dist/cli/local-admin.js seed",
"db:test": "node scripts/test-migrations.mjs",
"migrations:check": "node scripts/check-migrations.mjs",
"security:audit": "pnpm audit --prod --audit-level=high"
"security:audit": "pnpm audit --prod --audit-level=moderate"
},
"dependencies": {
"@nestjs/common": "^11.1.0",
@ -36,10 +41,10 @@
"@prisma/client": "^7.0.0",
"dotenv": "^17.0.0",
"helmet": "^8.0.0",
"nodemailer": "^10.0.1",
"nodemailer": "^10.6.1",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.2",
"zod": "^4.0.0"
"zod": "^4.6.7"
},
"devDependencies": {
"@electric-sql/pglite": "^0.5.8",

View File

@ -6,8 +6,12 @@ settings:
overrides:
'@prisma/config>deepmerge-ts': 8.0.0
'@prisma/config>effect': 3.22.5
prisma>mysql2: 3.23.1
'@nestjs/platform-express>multer': 2.3.0
'@nestjs/platform-express>multer': 2.5.0
'@nestjs/swagger>js-yaml': 5.4.1
ajv>fast-uri: 3.1.9
express>proxy-addr: 2.0.8
importers:
@ -38,8 +42,8 @@ importers:
specifier: ^8.0.0
version: 8.3.0
nodemailer:
specifier: ^10.0.1
version: 10.0.1
specifier: ^10.6.1
version: 10.6.1
reflect-metadata:
specifier: ^0.2.2
version: 0.2.2
@ -47,8 +51,8 @@ importers:
specifier: ^7.8.2
version: 7.8.2
zod:
specifier: ^4.0.0
version: 4.5.4
specifier: ^4.6.7
version: 4.6.7
devDependencies:
'@electric-sql/pglite':
specifier: ^0.5.8
@ -1337,8 +1341,8 @@ packages:
better-result@2.10.0:
resolution: {integrity: sha512-oQhh0y1qo2/ZKdAAEvHZAqKKiHOFU5k/bW96fE2ScgQOVkJRiHwB+nOS1SgFsYqRlxMDWvefXi9Q3px7QvgNDw==}
body-parser@2.3.0:
resolution: {integrity: sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==}
body-parser@2.4.0:
resolution: {integrity: sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==}
engines: {node: '>=18'}
brace-expansion@2.1.4:
@ -1360,9 +1364,6 @@ packages:
bser@2.1.1:
resolution: {integrity: sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ==}
buffer-from@1.1.2:
resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==}
busboy@1.6.0:
resolution: {integrity: sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==}
engines: {node: '>=10.16.0'}
@ -1449,10 +1450,6 @@ packages:
component-emitter@1.3.1:
resolution: {integrity: sha512-T0+barUSQRTUQASh8bx02dl+DhF54GtIDY13Y3m9oWTklKbb3Wv974meRpeZ3lp1JpLVECWWNHC4vaG2XHXouQ==}
concat-stream@2.0.0:
resolution: {integrity: sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==}
engines: {'0': node >= 6.0}
confbox@0.2.4:
resolution: {integrity: sha512-ysOGlgTFbN2/Y6Cg3Iye8YKulHw+R2fNXHrgSmXISQdMnomY6eNDprVdW9R5xBguEqI954+S6709UyiO7B+6OQ==}
@ -1615,8 +1612,8 @@ packages:
ee-first@1.1.1:
resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==}
effect@3.20.0:
resolution: {integrity: sha512-qMLfDJscrNG8p/aw+IkT9W7fgj50Z4wG5bLBy0Txsxz8iUHjDIkOgO3SV0WZfnQbNG2VJYb0b+rDLMrhM4+Krw==}
effect@3.22.5:
resolution: {integrity: sha512-AdIU4llI19BzhJ4xUBZix7kS8oiYSlCsJ61j3UM3UyJw9ecDrsrrweDFm/Ku1nHbJWMLoynK+1Me4it3Zkmjpw==}
electron-to-chromium@1.5.422:
resolution: {integrity: sha512-UvA/32XqrLDdZSn7Jllo1AYNcWji/G0d5M0GTViE7KoGBiMunw3a34Sb2KO4ZZyrSEhqsxFoVhWWJshdyfKqJA==}
@ -1731,8 +1728,8 @@ packages:
fast-safe-stringify@2.1.1:
resolution: {integrity: sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==}
fast-uri@3.1.7:
resolution: {integrity: sha512-dOvZVzjdZdz7phd9v6jCbwxrBW3fK6n8Rc0CtdmM4bumzMnxywBYhuph6J819RRw/ku+rLbelwfMunktuzVVHg==}
fast-uri@3.1.9:
resolution: {integrity: sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==}
fb-watchman@2.0.2:
resolution: {integrity: sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA==}
@ -2093,8 +2090,8 @@ packages:
resolution: {integrity: sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==}
hasBin: true
js-yaml@5.3.0:
resolution: {integrity: sha512-muutsYr+e2+d3rTgUGslq5rxbBlUy3cJ61IsHag2QNDQV+7zXWjkUpmALIajhrlLlrgRUiymj6U3zUr/TMK84Q==}
js-yaml@5.4.1:
resolution: {integrity: sha512-28R/k+NAjeuf7+CKlTxWZVExJGwVVLwY06DgEnOMz2gEpfNkDcD7QvyiVPT0xy0XXhU8vHsd4Ot42OOPdJG7dQ==}
hasBin: true
jsesc@3.1.0:
@ -2224,8 +2221,8 @@ packages:
ms@2.1.3:
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
multer@2.3.0:
resolution: {integrity: sha512-cjNbm3sttszgZeGfJR124D+jFEfkXCVAsoPBmFn9X7UxmDSFHWqE2CoEj0vrmSpuAFnqWR1Szcm9QTsiHr60Xw==}
multer@2.5.0:
resolution: {integrity: sha512-BsqOzYGVq49JcW2IzoSAxeKYRevb+dGGPPWleOR8Lrlk4igwxu1/9pwSXlByhCb7MVZDrNJFC0IBP5/O5nLYRw==}
engines: {node: '>= 10.16.0'}
mysql2@3.23.1:
@ -2263,8 +2260,8 @@ packages:
resolution: {integrity: sha512-YHs7BmmcsdAI5Ozuf8JZo6PT0mv2GIWC9vMfvUC3dp65M8hn7Ux8CPL+2oBI7juNuj9d0ndhTcznq2ODBps9cQ==}
engines: {node: '>=18'}
nodemailer@10.0.1:
resolution: {integrity: sha512-c+gU9cL9HLDax3vjxL88kW+6NOgdtEUWaZ+AUtxdJR6LLhf0kGdCLExof7yiKW7zdO9EfXCSIgmhGyFmUM0mYQ==}
nodemailer@10.6.1:
resolution: {integrity: sha512-d7kfFfS/tR4Aca+SBvRaQ+MXKNv7d2JiRe5TxaRcFT/kYMh4GGPnW9aKksTIEvyEbA7d/7HYWE4YPDEHxzJj/g==}
engines: {node: '>=20.0.0'}
normalize-path@3.0.0:
@ -2454,8 +2451,8 @@ packages:
proper-lockfile@4.1.2:
resolution: {integrity: sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==}
proxy-addr@2.0.7:
resolution: {integrity: sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==}
proxy-addr@2.0.8:
resolution: {integrity: sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==}
engines: {node: '>= 0.10'}
pure-rand@6.1.0:
@ -2464,8 +2461,8 @@ packages:
pure-rand@7.0.1:
resolution: {integrity: sha512-oTUZM/NAZS8p7ANR3SHh30kXB+zK2r2BPcEn/awJIbOvq82WoMN4p62AWWp3Hhw50G0xMsw1mhIBLqHw64EcNQ==}
qs@6.16.0:
resolution: {integrity: sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==}
qs@6.17.1:
resolution: {integrity: sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==}
engines: {node: '>=0.6'}
range-parser@1.3.0:
@ -2494,10 +2491,6 @@ packages:
resolution: {integrity: sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw==}
engines: {node: '>=0.10.0'}
readable-stream@3.6.2:
resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==}
engines: {node: '>= 6'}
readdirp@5.1.1:
resolution: {integrity: sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA==}
engines: {node: '>= 20.19.0'}
@ -2542,9 +2535,6 @@ packages:
rxjs@7.8.2:
resolution: {integrity: sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==}
safe-buffer@5.2.1:
resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==}
safe-regex2@5.1.1:
resolution: {integrity: sha512-mOSBvHGDZMuIEZMdOz/aCEYDCv0E7nfcNsIhUF+/P+xC7Hyf3FkvymqgPbg9D1EdSGu+uKbJgy09K/RKKc7kJA==}
hasBin: true
@ -2652,9 +2642,6 @@ packages:
resolution: {integrity: sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==}
engines: {node: '>=12'}
string_decoder@1.3.0:
resolution: {integrity: sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==}
strip-ansi@6.0.1:
resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==}
engines: {node: '>=8'}
@ -2764,9 +2751,6 @@ packages:
resolution: {integrity: sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==}
engines: {node: '>= 18'}
typedarray@0.0.6:
resolution: {integrity: sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==}
typescript@5.9.3:
resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==}
engines: {node: '>=14.17'}
@ -2801,9 +2785,6 @@ packages:
peerDependencies:
browserslist: '>= 4.21.0'
util-deprecate@1.0.2:
resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}
v8-to-istanbul@9.3.0:
resolution: {integrity: sha512-kiGUalWN+rgBJ/1OHZsBtU4rXZOfj/7rKQxULKlIzwzQSvMJUUNgPwJEEh7gU6xEVxC0ahoOBvN2YI8GH6FNgA==}
engines: {node: '>=10.12.0'}
@ -2869,8 +2850,8 @@ packages:
zeptomatch@2.1.0:
resolution: {integrity: sha512-KiGErG2J0G82LSpniV0CtIzjlJ10E04j02VOudJsPyPwNZgGnRKQy7I1R7GMyg/QswnE4l7ohSGrQbQbjXPPDA==}
zod@4.5.4:
resolution: {integrity: sha512-sC95tT5iHHH9gtpj6A81kh+NEaRAUFN+qlUPDUbRfOMvNf5QCBqsb3WgvnpVtK5Y+4UfA6KqufotuTvMGiTlsA==}
zod@4.6.7:
resolution: {integrity: sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==}
snapshots:
@ -3474,7 +3455,7 @@ snapshots:
'@nestjs/core': 11.2.3(@nestjs/common@11.2.3(reflect-metadata@0.2.2)(rxjs@7.8.2)(supports-color@8.1.1))(@nestjs/platform-express@11.2.3)(reflect-metadata@0.2.2)(rxjs@7.8.2)
cors: 2.8.6
express: 5.2.1(supports-color@8.1.1)
multer: 2.3.0
multer: 2.5.0
path-to-regexp: 8.4.2
tslib: 2.8.1
transitivePeerDependencies:
@ -3486,7 +3467,7 @@ snapshots:
'@nestjs/common': 11.2.3(reflect-metadata@0.2.2)(rxjs@7.8.2)(supports-color@8.1.1)
'@nestjs/core': 11.2.3(@nestjs/common@11.2.3(reflect-metadata@0.2.2)(rxjs@7.8.2)(supports-color@8.1.1))(@nestjs/platform-express@11.2.3)(reflect-metadata@0.2.2)(rxjs@7.8.2)
'@nestjs/mapped-types': 2.1.1(@nestjs/common@11.2.3(reflect-metadata@0.2.2)(rxjs@7.8.2)(supports-color@8.1.1))(reflect-metadata@0.2.2)
js-yaml: 5.3.0
js-yaml: 5.4.1
lodash: 4.18.1
path-to-regexp: 8.4.2
reflect-metadata: 0.2.2
@ -3589,7 +3570,7 @@ snapshots:
dependencies:
c12: 3.3.4
deepmerge-ts: 8.0.0
effect: 3.20.0
effect: 3.22.5
empathic: 2.0.0
transitivePeerDependencies:
- magicast
@ -4061,7 +4042,7 @@ snapshots:
ajv@8.20.0:
dependencies:
fast-deep-equal: 3.1.3
fast-uri: 3.1.7
fast-uri: 3.1.9
json-schema-traverse: 1.0.0
require-from-string: 2.0.2
@ -4160,7 +4141,7 @@ snapshots:
better-result@2.10.0: {}
body-parser@2.3.0(supports-color@8.1.1):
body-parser@2.4.0(supports-color@8.1.1):
dependencies:
bytes: 3.1.2
content-type: 2.1.0
@ -4168,7 +4149,7 @@ snapshots:
http-errors: 2.0.1
iconv-lite: 0.7.3
on-finished: 2.4.1
qs: 6.16.0
qs: 6.17.1
raw-body: 3.0.2
type-is: 2.1.0
transitivePeerDependencies:
@ -4198,8 +4179,6 @@ snapshots:
dependencies:
node-int64: 0.4.0
buffer-from@1.1.2: {}
busboy@1.6.0:
dependencies:
streamsearch: 1.1.0
@ -4278,13 +4257,6 @@ snapshots:
component-emitter@1.3.1: {}
concat-stream@2.0.0:
dependencies:
buffer-from: 1.1.2
inherits: 2.0.4
readable-stream: 3.6.2
typedarray: 0.0.6
confbox@0.2.4: {}
confbox@0.3.1: {}
@ -4409,7 +4381,7 @@ snapshots:
ee-first@1.1.1: {}
effect@3.20.0:
effect@3.22.5:
dependencies:
'@standard-schema/spec': 1.1.0
fast-check: 3.23.2
@ -4517,7 +4489,7 @@ snapshots:
express@5.2.1(supports-color@8.1.1):
dependencies:
accepts: 2.0.0
body-parser: 2.3.0(supports-color@8.1.1)
body-parser: 2.4.0(supports-color@8.1.1)
content-disposition: 1.1.0
content-type: 1.0.5
cookie: 0.7.2
@ -4535,8 +4507,8 @@ snapshots:
on-finished: 2.4.1
once: 1.4.0
parseurl: 1.3.3
proxy-addr: 2.0.7
qs: 6.16.0
proxy-addr: 2.0.8
qs: 6.17.1
range-parser: 1.3.0
router: 2.2.0(supports-color@8.1.1)
send: 1.2.1(supports-color@8.1.1)
@ -4565,7 +4537,7 @@ snapshots:
fast-safe-stringify@2.1.1: {}
fast-uri@3.1.7: {}
fast-uri@3.1.9: {}
fb-watchman@2.0.2:
dependencies:
@ -5117,7 +5089,7 @@ snapshots:
argparse: 1.0.10
esprima: 4.0.1
js-yaml@5.3.0:
js-yaml@5.4.1:
dependencies:
argparse: 2.0.1
@ -5203,11 +5175,10 @@ snapshots:
ms@2.1.3: {}
multer@2.3.0:
multer@2.5.0:
dependencies:
append-field: 1.0.0
busboy: 1.6.0
concat-stream: 2.0.0
type-is: 1.6.18
mysql2@3.23.1(@types/node@24.13.3):
@ -5242,7 +5213,7 @@ snapshots:
node-releases@2.0.54: {}
nodemailer@10.0.1: {}
nodemailer@10.6.1: {}
normalize-path@3.0.0: {}
@ -5413,7 +5384,7 @@ snapshots:
retry: 0.12.0
signal-exit: 3.0.7
proxy-addr@2.0.7:
proxy-addr@2.0.8:
dependencies:
forwarded: 0.2.0
ipaddr.js: 1.9.1
@ -5422,7 +5393,7 @@ snapshots:
pure-rand@7.0.1: {}
qs@6.16.0:
qs@6.17.1:
dependencies:
es-define-property: 1.0.1
side-channel: 1.1.1
@ -5452,12 +5423,6 @@ snapshots:
react@19.2.8: {}
readable-stream@3.6.2:
dependencies:
inherits: 2.0.4
string_decoder: 1.3.0
util-deprecate: 1.0.2
readdirp@5.1.1: {}
reflect-metadata@0.2.2: {}
@ -5494,8 +5459,6 @@ snapshots:
dependencies:
tslib: 2.8.1
safe-buffer@5.2.1: {}
safe-regex2@5.1.1:
dependencies:
ret: 0.5.0
@ -5610,10 +5573,6 @@ snapshots:
emoji-regex: 9.2.2
strip-ansi: 7.2.0
string_decoder@1.3.0:
dependencies:
safe-buffer: 5.2.1
strip-ansi@6.0.1:
dependencies:
ansi-regex: 5.0.1
@ -5642,7 +5601,7 @@ snapshots:
formidable: 3.5.4
methods: 1.1.2
mime: 2.6.0
qs: 6.16.0
qs: 6.17.1
transitivePeerDependencies:
- supports-color
@ -5724,8 +5683,6 @@ snapshots:
media-typer: 1.1.1
mime-types: 3.0.2
typedarray@0.0.6: {}
typescript@5.9.3: {}
uglify-js@3.19.3:
@ -5774,8 +5731,6 @@ snapshots:
escalade: 3.2.0
picocolors: 1.1.1
util-deprecate@1.0.2: {}
v8-to-istanbul@9.3.0:
dependencies:
'@jridgewell/trace-mapping': 0.3.31
@ -5838,4 +5793,4 @@ snapshots:
grammex: 3.1.13
graphmatch: 1.1.1
zod@4.5.4: {}
zod@4.6.7: {}

View File

@ -7,5 +7,9 @@ allowBuilds:
unrs-resolver: true
overrides:
'@prisma/config>deepmerge-ts': 8.0.0
'@prisma/config>effect': 3.22.5
'prisma>mysql2': 3.23.1
'@nestjs/platform-express>multer': 2.3.0
'@nestjs/platform-express>multer': 2.5.0
'@nestjs/swagger>js-yaml': 5.4.1
'ajv>fast-uri': 3.1.9
'express>proxy-addr': 2.0.8

65
prisma/artwork.prisma Normal file
View File

@ -0,0 +1,65 @@
enum B2bArtworkPlacement {
LABEL
PACKAGING
CANDLE
OTHER
}
enum B2bArtworkOutcome {
APPROVED
REJECTED
}
model B2bArtwork {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
accountId String @map("account_id") @db.Uuid
createdById String @map("created_by_id") @db.Uuid
name String @db.VarChar(160)
placement B2bArtworkPlacement
brief String @db.VarChar(1000)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
account BusinessAccount @relation(fields: [accountId, organizationId], references: [id, organizationId], onDelete: Restrict)
createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
versions B2bArtworkVersion[]
@@unique([id, organizationId])
@@index([organizationId, accountId, createdAt, id])
@@map("b2b_artworks")
}
model B2bArtworkVersion {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
artworkId String @map("artwork_id") @db.Uuid
uploadedById String @map("uploaded_by_id") @db.Uuid
version Int
filename String @db.VarChar(120)
mimeType String @map("mime_type") @db.VarChar(32)
sha256 String @db.Char(64)
size Int
content Bytes @db.ByteA
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
artwork B2bArtwork @relation(fields: [artworkId, organizationId], references: [id, organizationId], onDelete: Restrict)
uploadedBy User @relation(fields: [uploadedById, organizationId], references: [id, organizationId], onDelete: Restrict)
decision B2bArtworkDecision?
@@unique([artworkId, version])
@@unique([id, organizationId])
@@index([organizationId, artworkId, version])
@@map("b2b_artwork_versions")
}
model B2bArtworkDecision {
versionId String @id @map("version_id") @db.Uuid
organizationId String @map("organization_id") @db.Uuid
reviewerId String @map("reviewer_id") @db.Uuid
outcome B2bArtworkOutcome
note String @db.VarChar(500)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
version B2bArtworkVersion @relation(fields: [versionId, organizationId], references: [id, organizationId], onDelete: Restrict)
reviewer User @relation(fields: [reviewerId, organizationId], references: [id, organizationId], onDelete: Restrict)
@@unique([versionId, organizationId])
@@map("b2b_artwork_decisions")
}

181
prisma/b2b.prisma Normal file
View File

@ -0,0 +1,181 @@
enum BusinessVerificationKind {
SUBMITTED
APPROVED
REJECTED
}
enum B2bPriceListStatus {
DRAFT
ACTIVE
ARCHIVED
}
enum B2bQuoteResponseKind {
ACCEPTED
DECLINED
WITHDRAWN
}
model BusinessAccount {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
createdById String @map("created_by_id") @db.Uuid
code String @db.VarChar(32)
legalName String @map("legal_name") @db.VarChar(160)
tradingName String? @map("trading_name") @db.VarChar(160)
registrationNumber String @map("registration_number") @db.VarChar(64)
taxIdentifier String? @map("tax_identifier") @db.VarChar(64)
countryCode String @map("country_code") @db.Char(2)
contactEmail String @map("contact_email") @db.VarChar(254)
contactPhone String? @map("contact_phone") @db.VarChar(24)
billingLine1 String @map("billing_line1") @db.VarChar(200)
billingCity String @map("billing_city") @db.VarChar(100)
billingRegion String @map("billing_region") @db.VarChar(100)
billingPostalCode String @map("billing_postal_code") @db.VarChar(20)
profileVersion Int @default(1) @map("profile_version")
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
events BusinessVerificationEvent[]
priceLists B2bPriceList[]
quotes B2bQuote[]
creditPolicies B2bCreditPolicy[]
customCandleRequests B2bCustomCandleRequest[]
sampleRequests B2bSampleRequest[]
artworks B2bArtwork[]
partnerOrders B2bPartnerOrder[]
@@unique([organizationId, code])
@@unique([organizationId, countryCode, registrationNumber])
@@unique([id, organizationId])
@@index([organizationId, createdAt, id])
@@map("business_accounts")
}
model B2bPriceList {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
accountId String @map("account_id") @db.Uuid
createdById String @map("created_by_id") @db.Uuid
name String @db.VarChar(100)
currency String @db.Char(3)
status B2bPriceListStatus @default(DRAFT)
activeSlot Boolean? @map("active_slot")
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
account BusinessAccount @relation(fields: [accountId, organizationId], references: [id, organizationId], onDelete: Restrict)
createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
items B2bPriceListItem[]
quotes B2bQuote[]
@@unique([id, organizationId])
@@unique([organizationId, accountId, currency, activeSlot])
@@index([organizationId, accountId, status, createdAt, id])
@@map("b2b_price_lists")
}
model B2bPriceListItem {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
priceListId String @map("price_list_id") @db.Uuid
variantId String @map("variant_id") @db.Uuid
unitPrice Decimal @map("unit_price") @db.Decimal(12,2)
minQuantity Int @map("min_quantity")
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
priceList B2bPriceList @relation(fields: [priceListId, organizationId], references: [id, organizationId], onDelete: Restrict)
variant ProductVariant @relation(fields: [variantId, organizationId], references: [id, organizationId], onDelete: Restrict)
@@unique([priceListId, variantId])
@@index([organizationId, priceListId, id])
@@map("b2b_price_list_items")
}
model BusinessVerificationEvent {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
accountId String @map("account_id") @db.Uuid
actorId String @map("actor_id") @db.Uuid
sequence Int
kind BusinessVerificationKind
profileSnapshot Json? @map("profile_snapshot") @db.JsonB
note String? @db.VarChar(500)
idempotencyKey String @map("idempotency_key") @db.Uuid
requestHash String @map("request_hash") @db.Char(64)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
account BusinessAccount @relation(fields: [accountId, organizationId], references: [id, organizationId], onDelete: Restrict)
actor User @relation(fields: [actorId, organizationId], references: [id, organizationId], onDelete: Restrict)
@@unique([accountId, sequence])
@@unique([organizationId, idempotencyKey])
@@index([organizationId, accountId, sequence])
@@map("business_verification_events")
}
model B2bQuote {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
accountId String @map("account_id") @db.Uuid
priceListId String @map("price_list_id") @db.Uuid
createdById String @map("created_by_id") @db.Uuid
number String @db.VarChar(24)
accountSnapshot Json @map("account_snapshot") @db.JsonB
priceListName String @map("price_list_name") @db.VarChar(100)
currency String @db.Char(3)
merchandiseTotal Decimal @map("merchandise_total") @db.Decimal(18,2)
customerReference String? @map("customer_reference") @db.VarChar(100)
expiresAt DateTime @map("expires_at") @db.Timestamptz(3)
idempotencyKey String @map("idempotency_key") @db.Uuid
requestHash String @map("request_hash") @db.Char(64)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
account BusinessAccount @relation(fields: [accountId, organizationId], references: [id, organizationId], onDelete: Restrict)
priceList B2bPriceList @relation(fields: [priceListId, organizationId], references: [id, organizationId], onDelete: Restrict)
createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
lines B2bQuoteLine[]
response B2bQuoteResponse?
partnerOrder B2bPartnerOrder?
@@unique([id, organizationId])
@@unique([organizationId, number])
@@unique([organizationId, idempotencyKey])
@@index([organizationId, accountId, createdAt, id])
@@map("b2b_quotes")
}
model B2bQuoteLine {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
quoteId String @map("quote_id") @db.Uuid
variantId String @map("variant_id") @db.Uuid
sku String @db.VarChar(64)
name String @db.VarChar(160)
quantity Int
minQuantity Int @map("min_quantity")
unitPrice Decimal @map("unit_price") @db.Decimal(12,2)
lineTotal Decimal @map("line_total") @db.Decimal(18,2)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
quote B2bQuote @relation(fields: [quoteId, organizationId], references: [id, organizationId], onDelete: Restrict)
variant ProductVariant @relation(fields: [variantId, organizationId], references: [id, organizationId], onDelete: Restrict)
@@unique([quoteId, variantId])
@@index([organizationId, quoteId, id])
@@map("b2b_quote_lines")
}
model B2bQuoteResponse {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
quoteId String @map("quote_id") @db.Uuid
actorId String @map("actor_id") @db.Uuid
kind B2bQuoteResponseKind
note String @db.VarChar(500)
idempotencyKey String @map("idempotency_key") @db.Uuid
requestHash String @map("request_hash") @db.Char(64)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
quote B2bQuote @relation(fields: [quoteId, organizationId], references: [id, organizationId], onDelete: Restrict)
actor User @relation(fields: [actorId, organizationId], references: [id, organizationId], onDelete: Restrict)
@@unique([quoteId, organizationId])
@@unique([organizationId, idempotencyKey])
@@index([organizationId, quoteId])
@@map("b2b_quote_responses")
}

48
prisma/batch-cost.prisma Normal file
View File

@ -0,0 +1,48 @@
enum BatchCostLineKind {
PRODUCTION
PACKAGING
}
model BatchCostSnapshot {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
batchId String @unique @map("batch_id") @db.Uuid
createdById String @map("created_by_id") @db.Uuid
idempotencyKey String @map("idempotency_key") @db.Uuid
requestHash String @map("request_hash") @db.Char(64)
currency String @db.Char(3)
goodQuantity Int @map("good_quantity")
productionTotal Decimal @map("production_total") @db.Decimal(12,2)
packagingTotal Decimal @map("packaging_total") @db.Decimal(12,2)
total Decimal @db.Decimal(12,2)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
sealedAt DateTime? @map("sealed_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
batch ProductionBatch @relation(fields: [batchId, organizationId], references: [id, organizationId], onDelete: Restrict)
createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
lines BatchCostLine[]
@@unique([organizationId, idempotencyKey])
@@unique([batchId, organizationId])
@@unique([id, organizationId])
@@map("batch_cost_snapshots")
}
model BatchCostLine {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
snapshotId String @map("snapshot_id") @db.Uuid
kind BatchCostLineKind
bomId String @map("bom_id") @db.Uuid
bomLineId String @map("bom_line_id") @db.Uuid
materialId String @map("material_id") @db.Uuid
rateId String @map("rate_id") @db.Uuid
usedQuantity Decimal @map("used_quantity") @db.Decimal(12,3)
wastedQuantity Decimal @map("wasted_quantity") @db.Decimal(12,3)
unitCost Decimal @map("unit_cost") @db.Decimal(12,4)
lineCost Decimal @map("line_cost") @db.Decimal(12,2)
snapshot BatchCostSnapshot @relation(fields: [snapshotId, organizationId], references: [id, organizationId], onDelete: Restrict)
bomLine ProductBomLine @relation(fields: [bomLineId, bomId, materialId, organizationId], references: [id, bomId, materialId, organizationId], onDelete: Restrict, map: "batch_cost_lines_bom_scope_fkey")
rate MaterialCostRate @relation(fields: [rateId, materialId, organizationId], references: [id, materialId, organizationId], onDelete: Restrict, map: "batch_cost_lines_rate_scope_fkey")
@@unique([snapshotId, bomLineId])
@@map("batch_cost_lines")
}

35
prisma/blog.prisma Normal file
View File

@ -0,0 +1,35 @@
enum BlogState {
DRAFT
PUBLISHED
WITHDRAWN
}
model BlogArticle {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
createdById String @map("created_by_id") @db.Uuid
slug String @db.VarChar(100)
title String @db.VarChar(160)
summary String @db.VarChar(500)
body String
state BlogState @default(DRAFT)
version Int @default(0)
publishedContent Json? @map("published_content")
publicationVersion Int? @map("publication_version")
publishedAt DateTime? @map("published_at") @db.Timestamptz(3)
publishedById String? @map("published_by_id") @db.Uuid
withdrawnAt DateTime? @map("withdrawn_at") @db.Timestamptz(3)
withdrawnById String? @map("withdrawn_by_id") @db.Uuid
withdrawalReason String? @map("withdrawal_reason") @db.VarChar(500)
idempotencyKey String @map("idempotency_key") @db.Uuid
requestHash String @map("request_hash") @db.Char(64)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz(3)
createdBy User @relation("BlogCreator", fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
publishedBy User? @relation("BlogPublisher", fields: [publishedById, organizationId], references: [id, organizationId], onDelete: Restrict)
withdrawnBy User? @relation("BlogWithdrawer", fields: [withdrawnById, organizationId], references: [id, organizationId], onDelete: Restrict)
@@unique([organizationId, slug])
@@unique([organizationId, idempotencyKey])
@@index([organizationId, state, publishedAt, id])
@@index([organizationId, createdAt, id])
@@map("blog_articles")
}

54
prisma/bom.prisma Normal file
View File

@ -0,0 +1,54 @@
enum BomStatus {
DRAFT
ACTIVE
SUPERSEDED
}
enum BomKind {
PRODUCTION
PACKAGING
}
model ProductBom {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
variantId String @map("variant_id") @db.Uuid
createdById String @map("created_by_id") @db.Uuid
revision Int
kind BomKind @default(PRODUCTION)
outputQuantity Int @map("output_quantity")
status BomStatus @default(DRAFT)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
activatedAt DateTime? @map("activated_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
variant ProductVariant @relation(fields: [variantId, organizationId], references: [id, organizationId], onDelete: Restrict)
createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
lines ProductBomLine[]
batches ProductionBatch[]
packagingRuns PackagingRun[]
@@unique([variantId, kind, revision])
@@unique([id, organizationId])
@@index([organizationId, variantId, createdAt, id])
@@map("product_boms")
}
model ProductBomLine {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
bomId String @map("bom_id") @db.Uuid
materialId String @map("material_id") @db.Uuid
materialName String @map("material_name") @db.VarChar(160)
materialCode String @map("material_code") @db.VarChar(32)
unit MaterialUnit
quantity Decimal @db.Decimal(12,3)
bom ProductBom @relation(fields: [bomId, organizationId], references: [id, organizationId], onDelete: Restrict)
material Material @relation(fields: [materialId, organizationId], references: [id, organizationId], onDelete: Restrict)
materialUsage ProductionMaterialUsage[]
packagingRunLines PackagingRunLine[]
batchCostLines BatchCostLine[]
@@unique([id, bomId, materialId, organizationId], map: "product_bom_lines_cost_scope_key")
@@unique([bomId, materialId])
@@unique([id, bomId, organizationId])
@@index([organizationId, materialId])
@@map("product_bom_lines")
}

39
prisma/campaigns.prisma Normal file
View File

@ -0,0 +1,39 @@
enum CampaignState {
DRAFT
PUBLISHED
CANCELLED
}
model SeasonalCampaign {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
collectionId String @map("collection_id") @db.Uuid
createdById String @map("created_by_id") @db.Uuid
slug String @db.VarChar(100)
title String @db.VarChar(160)
summary String @default("") @db.VarChar(500)
startsAt DateTime @map("starts_at") @db.Timestamptz(3)
endsAt DateTime @map("ends_at") @db.Timestamptz(3)
state CampaignState @default(DRAFT)
version Int @default(0)
idempotencyKey String @map("idempotency_key") @db.Uuid
requestHash String @map("request_hash") @db.Char(64)
publishedById String? @map("published_by_id") @db.Uuid
publishedAt DateTime? @map("published_at") @db.Timestamptz(3)
cancelledById String? @map("cancelled_by_id") @db.Uuid
cancelledAt DateTime? @map("cancelled_at") @db.Timestamptz(3)
cancellationReason String? @map("cancellation_reason") @db.VarChar(500)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz(3)
collection CatalogGroup @relation(fields: [collectionId, organizationId], references: [id, organizationId], onDelete: Restrict)
createdBy User @relation("CampaignCreator", fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
publishedBy User? @relation("CampaignPublisher", fields: [publishedById, organizationId], references: [id, organizationId], onDelete: Restrict)
cancelledBy User? @relation("CampaignCanceller", fields: [cancelledById, organizationId], references: [id, organizationId], onDelete: Restrict)
coupon Coupon?
@@unique([id, organizationId])
@@unique([organizationId, slug])
@@unique([organizationId, idempotencyKey])
@@index([organizationId, state, startsAt, endsAt, id])
@@index([organizationId, createdAt, id])
@@map("seasonal_campaigns")
}

View File

@ -19,6 +19,7 @@ model Product {
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
variants ProductVariant[]
groups ProductGroup[]
images ProductImage[]
@@unique([organizationId, slug])
@@unique([id, organizationId])
@@index([organizationId, status, createdAt, id])
@ -36,7 +37,15 @@ model ProductVariant {
active Boolean @default(true)
stockItems StockItem[]
cartLines CartLine[]
wishlistItems WishlistItem[]
reviewVerifications ReviewPurchaseVerification[]
reviews ProductReview[]
orderLines OrderLine[]
boms ProductBom[]
b2bPriceListItems B2bPriceListItem[]
b2bQuoteLines B2bQuoteLine[]
b2bSampleRequests B2bSampleRequest[]
b2bPartnerOrderLines B2bPartnerOrderLine[]
product Product @relation(fields: [productId, organizationId], references: [id, organizationId], onDelete: Restrict)
@@unique([organizationId, sku])
@@unique([id, organizationId])
@ -44,6 +53,7 @@ model ProductVariant {
@@map("product_variants")
}
model CatalogGroup {
seasonalCampaigns SeasonalCampaign[]
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
name String @db.VarChar(100)

View File

@ -11,6 +11,7 @@ model Cart {
organizationId String @map("organization_id") @db.Uuid
userId String @map("user_id") @db.Uuid
version Int @default(0)
lastActivityAt DateTime? @map("last_activity_at") @db.Timestamptz(3)
user User @relation(fields: [userId, organizationId], references: [id, organizationId], onDelete: Restrict)
lines CartLine[]
@@unique([userId, organizationId])
@ -31,6 +32,7 @@ model CartLine {
model Coupon {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
campaignId String? @unique @map("campaign_id") @db.Uuid
code String @db.VarChar(40)
kind CouponKind
currency String @db.Char(3)
@ -44,6 +46,8 @@ model Coupon {
active Boolean @default(true)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
orders Order[]
campaign SeasonalCampaign? @relation(fields: [campaignId, organizationId], references: [id, organizationId], onDelete: Restrict)
@@unique([campaignId, organizationId])
@@unique([organizationId, code])
@@unique([id, organizationId])
@@map("coupons")
@ -73,6 +77,8 @@ model Order {
@@unique([userId, organizationId, idempotencyKey])
@@unique([id, organizationId])
@@index([organizationId, userId, createdAt, id])
@@index([organizationId, createdAt, id])
@@index([organizationId, status, expiresAt, id])
@@unique([id, userId, organizationId])
@@index([couponId, status, expiresAt])
@@map("orders")

58
prisma/credit.prisma Normal file
View File

@ -0,0 +1,58 @@
enum B2bCreditStatus {
PROPOSED
ACTIVE
REJECTED
SUSPENDED
}
enum B2bCreditEventKind {
APPROVED
REJECTED
SUSPENDED
}
model B2bCreditPolicy {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
accountId String @map("account_id") @db.Uuid
proposedById String @map("proposed_by_id") @db.Uuid
currency String @db.Char(3)
creditLimit Decimal @map("credit_limit") @db.Decimal(16,2)
netDays Int @map("net_days")
rationale String @db.VarChar(500)
status B2bCreditStatus @default(PROPOSED)
activeSlot Boolean? @map("active_slot")
idempotencyKey String @map("idempotency_key") @db.Uuid
requestHash String @map("request_hash") @db.Char(64)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
account BusinessAccount @relation(fields: [accountId, organizationId], references: [id, organizationId], onDelete: Restrict)
proposedBy User @relation(fields: [proposedById, organizationId], references: [id, organizationId], onDelete: Restrict)
events B2bCreditEvent[]
@@unique([id, organizationId])
@@unique([organizationId, idempotencyKey])
@@unique([organizationId, accountId, currency, activeSlot])
@@index([organizationId, accountId, createdAt, id])
@@map("b2b_credit_policies")
}
model B2bCreditEvent {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
policyId String @map("policy_id") @db.Uuid
actorId String @map("actor_id") @db.Uuid
sequence Int
kind B2bCreditEventKind
note String @db.VarChar(500)
idempotencyKey String @map("idempotency_key") @db.Uuid
requestHash String @map("request_hash") @db.Char(64)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
policy B2bCreditPolicy @relation(fields: [policyId, organizationId], references: [id, organizationId], onDelete: Restrict)
actor User @relation(fields: [actorId, organizationId], references: [id, organizationId], onDelete: Restrict)
@@unique([policyId, sequence])
@@unique([organizationId, idempotencyKey])
@@index([organizationId, policyId, sequence])
@@map("b2b_credit_events")
}

View File

@ -0,0 +1,47 @@
enum B2bCustomCandleDecisionKind {
APPROVED
REJECTED
}
model B2bCustomCandleRequest {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
accountId String @map("account_id") @db.Uuid
requestedById String @map("requested_by_id") @db.Uuid
quantity Int
waxType String @map("wax_type") @db.VarChar(100)
fragrance String @db.VarChar(160)
container String @db.VarChar(160)
color String @db.VarChar(100)
brandingRequirements String @map("branding_requirements") @db.VarChar(1000)
specifications String @db.VarChar(2000)
idempotencyKey String @map("idempotency_key") @db.Uuid
requestHash String @map("request_hash") @db.Char(64)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
account BusinessAccount @relation(fields: [accountId, organizationId], references: [id, organizationId], onDelete: Restrict)
requestedBy User @relation(fields: [requestedById, organizationId], references: [id, organizationId], onDelete: Restrict)
decision B2bCustomCandleDecision?
@@unique([id, organizationId])
@@unique([organizationId, idempotencyKey])
@@index([organizationId, accountId, createdAt, id])
@@map("b2b_custom_candle_requests")
}
model B2bCustomCandleDecision {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
requestId String @unique @map("request_id") @db.Uuid
actorId String @map("actor_id") @db.Uuid
kind B2bCustomCandleDecisionKind
note String @db.VarChar(1000)
idempotencyKey String @map("idempotency_key") @db.Uuid
requestHash String @map("request_hash") @db.Char(64)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
request B2bCustomCandleRequest @relation(fields: [requestId, organizationId], references: [id, organizationId], onDelete: Restrict)
actor User @relation(fields: [actorId, organizationId], references: [id, organizationId], onDelete: Restrict)
@@unique([requestId, organizationId])
@@unique([organizationId, idempotencyKey])
@@map("b2b_custom_candle_decisions")
}

66
prisma/documents.prisma Normal file
View File

@ -0,0 +1,66 @@
enum SupplierDocumentKind {
REGISTRATION
TAX_CERTIFICATE
COMPLIANCE_CERTIFICATE
OTHER
}
enum SupplierDocumentOutcome {
APPROVED
REJECTED
}
model SupplierDocument {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
supplierId String @map("supplier_id") @db.Uuid
createdById String @map("created_by_id") @db.Uuid
code String @db.VarChar(32)
kind SupplierDocumentKind
title String @db.VarChar(160)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
supplier Supplier @relation(fields: [supplierId, organizationId], references: [id, organizationId], onDelete: Restrict)
createdBy User @relation(fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
versions SupplierDocumentVersion[]
@@unique([organizationId, supplierId, code])
@@unique([id, organizationId])
@@index([organizationId, supplierId, createdAt, id], map: "supplier_documents_supplier_created_idx")
@@map("supplier_documents")
}
model SupplierDocumentVersion {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
documentId String @map("document_id") @db.Uuid
uploadedById String @map("uploaded_by_id") @db.Uuid
version Int
filename String @db.VarChar(120)
mimeType String @map("mime_type") @db.VarChar(32)
sha256 String @db.Char(64)
size Int
content Bytes @db.ByteA
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
document SupplierDocument @relation(fields: [documentId, organizationId], references: [id, organizationId], onDelete: Restrict)
uploadedBy User @relation(fields: [uploadedById, organizationId], references: [id, organizationId], onDelete: Restrict)
decision SupplierDocumentDecision?
@@unique([documentId, version])
@@unique([id, organizationId])
@@index([organizationId, documentId, version])
@@map("supplier_document_versions")
}
model SupplierDocumentDecision {
versionId String @id @map("version_id") @db.Uuid
organizationId String @map("organization_id") @db.Uuid
validatedById String @map("validated_by_id") @db.Uuid
outcome SupplierDocumentOutcome
reason String? @db.VarChar(500)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
version SupplierDocumentVersion @relation(fields: [versionId, organizationId], references: [id, organizationId], onDelete: Restrict, map: "supplier_document_decision_version_scope_fkey")
validatedBy User @relation(fields: [validatedById, organizationId], references: [id, organizationId], onDelete: Restrict, map: "supplier_document_decision_actor_scope_fkey")
@@unique([versionId, organizationId])
@@map("supplier_document_decisions")
}

43
prisma/forum.prisma Normal file
View File

@ -0,0 +1,43 @@
enum ForumDecisionKind {
APPROVED
REJECTED
HIDDEN
}
model ForumPost {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
userId String @map("user_id") @db.Uuid
threadId String? @map("thread_id") @db.Uuid
displayName String @map("display_name") @db.VarChar(80)
title String? @db.VarChar(160)
body String @db.VarChar(5000)
idempotencyKey String @map("idempotency_key") @db.Uuid
requestHash String @map("request_hash") @db.Char(64)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
user User @relation(fields: [userId, organizationId], references: [id, organizationId], onDelete: Restrict)
thread ForumPost? @relation("ForumReplies", fields: [threadId, organizationId], references: [id, organizationId], onDelete: Restrict)
replies ForumPost[] @relation("ForumReplies")
events ForumModeration[]
@@unique([id, organizationId])
@@unique([userId, organizationId, idempotencyKey])
@@index([organizationId, threadId, createdAt, id])
@@index([organizationId, userId, createdAt, id])
@@map("forum_posts")
}
model ForumModeration {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
postId String @map("post_id") @db.Uuid
actorId String @map("actor_id") @db.Uuid
sequence Int
kind ForumDecisionKind
note String @db.VarChar(1000)
idempotencyKey String @map("idempotency_key") @db.Uuid
requestHash String @map("request_hash") @db.Char(64)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
post ForumPost @relation(fields: [postId, organizationId], references: [id, organizationId], onDelete: Restrict)
actor User @relation(fields: [actorId, organizationId], references: [id, organizationId], onDelete: Restrict)
@@unique([postId, sequence])
@@unique([organizationId, idempotencyKey])
@@map("forum_moderation")
}

View File

@ -9,6 +9,14 @@ model Warehouse {
name String @db.VarChar(100)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
items StockItem[]
materialItems MaterialStockItem[]
materialReceiptPostings MaterialReceiptPosting[]
productionStockPostings ProductionStockPosting[]
packagingStockPostings PackagingStockPosting[]
finishedGoodsReceipts FinishedGoodsReceipt[]
transferSources MaterialStockTransfer[] @relation("MaterialTransferSourceWarehouse")
transferDestinations MaterialStockTransfer[] @relation("MaterialTransferDestinationWarehouse")
materialStockAdjustments MaterialStockAdjustment[]
@@unique([organizationId, name])
@@unique([id, organizationId])
@@map("warehouses")
@ -23,6 +31,7 @@ model StockItem {
warehouse Warehouse @relation(fields: [warehouseId, organizationId], references: [id, organizationId], onDelete: Restrict)
entries StockLedger[]
reservations StockReservation[]
finishedGoodsReceipts FinishedGoodsReceipt[]
@@unique([variantId, warehouseId])
@@unique([id, organizationId])
@@index([organizationId, id])
@ -38,9 +47,12 @@ model StockLedger {
reason String @db.VarChar(200)
idempotencyKey String @map("idempotency_key") @db.Uuid
requestHash String @map("request_hash") @db.Char(64)
finishedGoodsReceiptId String? @unique @map("finished_goods_receipt_id") @db.Uuid
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
stockItem StockItem @relation(fields: [stockItemId, organizationId], references: [id, organizationId], onDelete: Restrict)
finishedGoodsReceipt FinishedGoodsReceipt? @relation(fields: [finishedGoodsReceiptId, organizationId], references: [id, organizationId], onDelete: Restrict, map: "stock_ledger_finished_goods_scope_fkey")
@@unique([organizationId, idempotencyKey])
@@unique([finishedGoodsReceiptId, organizationId])
@@index([stockItemId, createdAt, id])
@@map("stock_ledger")
}
@ -64,3 +76,26 @@ model StockReservation {
@@index([userId, organizationId])
@@map("stock_reservations")
}
model FinishedGoodsReceipt {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
batchId String @unique @map("batch_id") @db.Uuid
warehouseId String @map("warehouse_id") @db.Uuid
stockItemId String @map("stock_item_id") @db.Uuid
postedById String @map("posted_by_id") @db.Uuid
quantity Int
idempotencyKey String @map("idempotency_key") @db.Uuid
requestHash String @map("request_hash") @db.Char(64)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
batch ProductionBatch @relation(fields: [batchId, organizationId], references: [id, organizationId], onDelete: Restrict)
warehouse Warehouse @relation(fields: [warehouseId, organizationId], references: [id, organizationId], onDelete: Restrict)
stockItem StockItem @relation(fields: [stockItemId, organizationId], references: [id, organizationId], onDelete: Restrict)
postedBy User @relation(fields: [postedById, organizationId], references: [id, organizationId], onDelete: Restrict)
entry StockLedger?
@@unique([organizationId, idempotencyKey])
@@unique([batchId, organizationId])
@@unique([id, organizationId])
@@map("finished_goods_receipts")
}

View File

@ -0,0 +1,18 @@
model MaterialCostRate {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
materialId String @map("material_id") @db.Uuid
recordedById String @map("recorded_by_id") @db.Uuid
currency String @db.Char(3)
revision Int
unitCost Decimal @map("unit_cost") @db.Decimal(12,4)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
material Material @relation(fields: [materialId, organizationId], references: [id, organizationId], onDelete: Restrict)
recordedBy User @relation(fields: [recordedById, organizationId], references: [id, organizationId], onDelete: Restrict)
batchCostLines BatchCostLine[]
@@unique([materialId, currency, revision])
@@unique([id, materialId, organizationId])
@@index([organizationId, materialId, currency, revision], map: "material_cost_rates_scope_revision_idx")
@@map("material_cost_rates")
}

View File

@ -0,0 +1,174 @@
enum MaterialStockKind {
RECEIPT_ACCEPTED
PRODUCTION_CONSUMED
PRODUCTION_WASTED
PACKAGING_USED
PACKAGING_WASTED
TRANSFER_OUT
TRANSFER_IN
ADJUSTMENT_IN
ADJUSTMENT_OUT
}
model MaterialStockItem {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
materialId String @map("material_id") @db.Uuid
warehouseId String @map("warehouse_id") @db.Uuid
onHand Decimal @default(0) @map("on_hand") @db.Decimal(12,3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
material Material @relation(fields: [materialId, organizationId], references: [id, organizationId], onDelete: Restrict)
warehouse Warehouse @relation(fields: [warehouseId, organizationId], references: [id, organizationId], onDelete: Restrict)
entries MaterialStockLedger[]
transferSources MaterialStockTransfer[] @relation("MaterialTransferSource")
transferDestinations MaterialStockTransfer[] @relation("MaterialTransferDestination")
adjustments MaterialStockAdjustment[]
@@unique([materialId, warehouseId])
@@unique([id, materialId, organizationId])
@@index([organizationId, warehouseId, materialId], map: "material_stock_items_scope_idx")
@@map("material_stock_items")
}
model MaterialReceiptPosting {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
receiptId String @unique @map("receipt_id") @db.Uuid
warehouseId String @map("warehouse_id") @db.Uuid
postedById String @map("posted_by_id") @db.Uuid
idempotencyKey String @map("idempotency_key") @db.Uuid
requestHash String @map("request_hash") @db.Char(64)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
receipt GoodsReceipt @relation(fields: [receiptId, organizationId], references: [id, organizationId], onDelete: Restrict)
warehouse Warehouse @relation(fields: [warehouseId, organizationId], references: [id, organizationId], onDelete: Restrict)
postedBy User @relation(fields: [postedById, organizationId], references: [id, organizationId], onDelete: Restrict)
entries MaterialStockLedger[]
@@unique([organizationId, idempotencyKey])
@@unique([receiptId, organizationId])
@@unique([id, organizationId])
@@map("material_receipt_postings")
}
model ProductionStockPosting {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
batchId String @unique @map("batch_id") @db.Uuid
warehouseId String @map("warehouse_id") @db.Uuid
postedById String @map("posted_by_id") @db.Uuid
idempotencyKey String @map("idempotency_key") @db.Uuid
requestHash String @map("request_hash") @db.Char(64)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
batch ProductionBatch @relation(fields: [batchId, organizationId], references: [id, organizationId], onDelete: Restrict)
warehouse Warehouse @relation(fields: [warehouseId, organizationId], references: [id, organizationId], onDelete: Restrict)
postedBy User @relation(fields: [postedById, organizationId], references: [id, organizationId], onDelete: Restrict)
entries MaterialStockLedger[]
@@unique([organizationId, idempotencyKey])
@@unique([batchId, organizationId])
@@unique([id, organizationId])
@@map("production_stock_postings")
}
model PackagingStockPosting {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
runId String @unique @map("run_id") @db.Uuid
warehouseId String @map("warehouse_id") @db.Uuid
postedById String @map("posted_by_id") @db.Uuid
idempotencyKey String @map("idempotency_key") @db.Uuid
requestHash String @map("request_hash") @db.Char(64)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
run PackagingRun @relation(fields: [runId, organizationId], references: [id, organizationId], onDelete: Restrict)
warehouse Warehouse @relation(fields: [warehouseId, organizationId], references: [id, organizationId], onDelete: Restrict)
postedBy User @relation(fields: [postedById, organizationId], references: [id, organizationId], onDelete: Restrict)
entries MaterialStockLedger[]
@@unique([organizationId, idempotencyKey])
@@unique([runId, organizationId])
@@unique([id, organizationId])
@@map("packaging_stock_postings")
}
model MaterialStockTransfer {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
materialId String @map("material_id") @db.Uuid
fromWarehouseId String @map("from_warehouse_id") @db.Uuid
toWarehouseId String @map("to_warehouse_id") @db.Uuid
fromStockItemId String @map("from_stock_item_id") @db.Uuid
toStockItemId String @map("to_stock_item_id") @db.Uuid
postedById String @map("posted_by_id") @db.Uuid
quantity Decimal @db.Decimal(12,3)
idempotencyKey String @map("idempotency_key") @db.Uuid
requestHash String @map("request_hash") @db.Char(64)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
material Material @relation(fields: [materialId, organizationId], references: [id, organizationId], onDelete: Restrict)
fromWarehouse Warehouse @relation("MaterialTransferSourceWarehouse", fields: [fromWarehouseId, organizationId], references: [id, organizationId], onDelete: Restrict)
toWarehouse Warehouse @relation("MaterialTransferDestinationWarehouse", fields: [toWarehouseId, organizationId], references: [id, organizationId], onDelete: Restrict)
fromStockItem MaterialStockItem @relation("MaterialTransferSource", fields: [fromStockItemId, materialId, organizationId], references: [id, materialId, organizationId], onDelete: Restrict, map: "material_stock_transfers_from_stock_scope_fkey")
toStockItem MaterialStockItem @relation("MaterialTransferDestination", fields: [toStockItemId, materialId, organizationId], references: [id, materialId, organizationId], onDelete: Restrict, map: "material_stock_transfers_to_stock_scope_fkey")
postedBy User @relation(fields: [postedById, organizationId], references: [id, organizationId], onDelete: Restrict)
entries MaterialStockLedger[]
@@unique([organizationId, idempotencyKey])
@@unique([id, organizationId])
@@index([organizationId, materialId, createdAt, id], map: "material_stock_transfers_scope_idx")
@@map("material_stock_transfers")
}
model MaterialStockAdjustment {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
materialId String @map("material_id") @db.Uuid
warehouseId String @map("warehouse_id") @db.Uuid
stockItemId String @map("stock_item_id") @db.Uuid
adjustedById String @map("adjusted_by_id") @db.Uuid
delta Decimal @db.Decimal(12,3)
reason String @db.VarChar(200)
idempotencyKey String @map("idempotency_key") @db.Uuid
requestHash String @map("request_hash") @db.Char(64)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
material Material @relation(fields: [materialId, organizationId], references: [id, organizationId], onDelete: Restrict)
warehouse Warehouse @relation(fields: [warehouseId, organizationId], references: [id, organizationId], onDelete: Restrict)
stockItem MaterialStockItem @relation(fields: [stockItemId, materialId, organizationId], references: [id, materialId, organizationId], onDelete: Restrict, map: "material_stock_adjustments_item_scope_fkey")
adjustedBy User @relation(fields: [adjustedById, organizationId], references: [id, organizationId], onDelete: Restrict)
entry MaterialStockLedger?
@@unique([organizationId, idempotencyKey])
@@unique([id, organizationId])
@@index([organizationId, materialId, createdAt, id], map: "material_stock_adjustments_scope_idx")
@@map("material_stock_adjustments")
}
model MaterialStockLedger {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
stockItemId String @map("stock_item_id") @db.Uuid
materialId String @map("material_id") @db.Uuid
postingId String? @map("posting_id") @db.Uuid
receiptLineId String? @unique @map("receipt_line_id") @db.Uuid
productionPostingId String? @map("production_posting_id") @db.Uuid
usageEventId String? @unique @map("usage_event_id") @db.Uuid
packagingPostingId String? @map("packaging_posting_id") @db.Uuid
packagingRunLineId String? @map("packaging_run_line_id") @db.Uuid
transferId String? @map("transfer_id") @db.Uuid
adjustmentId String? @unique @map("adjustment_id") @db.Uuid
kind MaterialStockKind
delta Decimal @db.Decimal(12,3)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
stockItem MaterialStockItem @relation(fields: [stockItemId, materialId, organizationId], references: [id, materialId, organizationId], onDelete: Restrict, map: "material_stock_ledger_item_scope_fkey")
posting MaterialReceiptPosting? @relation(fields: [postingId, organizationId], references: [id, organizationId], onDelete: Restrict, map: "material_stock_ledger_posting_scope_fkey")
receiptLine GoodsReceiptLine? @relation(fields: [receiptLineId, organizationId], references: [id, organizationId], onDelete: Restrict, map: "material_stock_ledger_receipt_scope_fkey")
productionPosting ProductionStockPosting? @relation(fields: [productionPostingId, organizationId], references: [id, organizationId], onDelete: Restrict, map: "material_stock_ledger_production_scope_fkey")
usageEvent ProductionMaterialUsage? @relation(fields: [usageEventId], references: [id], onDelete: Restrict, map: "material_stock_ledger_usage_fkey")
packagingPosting PackagingStockPosting? @relation(fields: [packagingPostingId, organizationId], references: [id, organizationId], onDelete: Restrict, map: "material_stock_ledger_packaging_scope_fkey")
packagingRunLine PackagingRunLine? @relation(fields: [packagingRunLineId], references: [id], onDelete: Restrict, map: "material_stock_ledger_packaging_line_fkey")
transfer MaterialStockTransfer? @relation(fields: [transferId, organizationId], references: [id, organizationId], onDelete: Restrict, map: "material_stock_ledger_transfer_scope_fkey")
adjustment MaterialStockAdjustment? @relation(fields: [adjustmentId, organizationId], references: [id, organizationId], onDelete: Restrict, map: "material_stock_ledger_adjustment_scope_fkey")
@@index([organizationId, stockItemId, createdAt, id], map: "material_stock_ledger_item_created_idx")
@@unique([receiptLineId, organizationId])
@@unique([packagingRunLineId, kind])
@@unique([transferId, kind])
@@unique([adjustmentId, organizationId])
@@map("material_stock_ledger")
}

View File

@ -0,0 +1,27 @@
enum MaterialUsageKind {
CONSUMED
WASTED
}
model ProductionMaterialUsage {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
batchId String @map("batch_id") @db.Uuid
bomId String @map("bom_id") @db.Uuid
bomLineId String @map("bom_line_id") @db.Uuid
recordedById String @map("recorded_by_id") @db.Uuid
kind MaterialUsageKind
quantity Decimal @db.Decimal(12,3)
reason String? @db.VarChar(500)
idempotencyKey String @map("idempotency_key") @db.Uuid
requestHash String @map("request_hash") @db.Char(64)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
batch ProductionBatch @relation(fields: [batchId, bomId, organizationId], references: [id, bomId, organizationId], onDelete: Restrict, map: "production_material_usage_batch_scope_fkey")
bomLine ProductBomLine @relation(fields: [bomLineId, bomId, organizationId], references: [id, bomId, organizationId], onDelete: Restrict, map: "production_material_usage_line_scope_fkey")
recordedBy User @relation(fields: [recordedById, organizationId], references: [id, organizationId], onDelete: Restrict, map: "production_material_usage_actor_scope_fkey")
stockEntry MaterialStockLedger?
@@unique([organizationId, idempotencyKey], map: "production_material_usage_idempotency_key")
@@index([organizationId, batchId, createdAt, id], map: "production_material_usage_batch_created_idx")
@@map("production_material_usage")
}

18
prisma/messaging.prisma Normal file
View File

@ -0,0 +1,18 @@
model MessagingConsentDecision {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
userId String @map("user_id") @db.Uuid
channel String @db.VarChar(20)
purpose String @db.VarChar(20)
granted Boolean
version Int
noticeVersion String? @map("notice_version") @db.VarChar(40)
idempotencyKey String @map("idempotency_key") @db.Uuid
requestHash String @map("request_hash") @db.Char(64)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
user User @relation(fields: [userId, organizationId], references: [id, organizationId], onDelete: Restrict)
@@unique([userId, organizationId, channel, purpose, version])
@@unique([userId, organizationId, idempotencyKey])
@@index([userId, organizationId, createdAt, id])
@@map("messaging_consent_decisions")
}

View File

@ -17,5 +17,45 @@
"20260923000116_purchase_order_integrity": "ed14ce76d1b29c8de890a89c8dd84216edd002e43732b75d0cdeab4fd8f51fb8",
"20260923001040_purchase_order_reconciliation": "63ddf7618ff14916512597cc16af2de07e0c093d345bb35e607ed830d3ef067e",
"20260928123638_goods_receipts_qc": "a09646d8a3a1f520495ddbe611c61437ddfcec4585486f94fc383d9b1312006c",
"20260928130714_supplier_invoices": "63945cff1725929e90fe73ade79348480e04a36976dbdb2a021a574569c35049"
"20260928130714_supplier_invoices": "63945cff1725929e90fe73ade79348480e04a36976dbdb2a021a574569c35049",
"20260928145745_supplier_payments": "012ff1c33c1afa8e6fd883925616f014e7cfdac258fac37ac2ae56739e95bf6d",
"20260928151912_supplier_documents": "65ec974aa6bd0e8f85dc0dbde00f5ef5d9ab81811aba17d89299b6464d4ee6c1",
"20260928153219_product_boms": "b548e6e5c2f11b52374ba0ad3eedbc127244b2752f07cdcd8bf951641d4525a1",
"20260928183508_production_batches": "53b3fbabe17d3270ae3c5d74393a07abb28858ca2af8d3a1aa19c92686c84a0a",
"20260928190933_material_usage": "950a2f1861e88c052b1e4d40aff178524c3a7c198e9fb27a3c47cb77fb984e1e",
"20260928193354_packaging_boms": "1f78a1f42b905ea7d371fadba6180a9f756fc4c360a04b92d58b37ec1dd2bad3",
"20260929013000_packaging_execution": "63c0fb096c769478ba9422fb606fd421188abd70eeef1375dd07bef2cbc731c1",
"20260929132000_material_cost_rates": "b7a9068407b6caf5f2c226969929c8e435ca37cc4e7fd7632da1140f79f77b0c",
"20260929170000_batch_cost_snapshots": "ef59558614f6bfe7fe07a095a4bafef2d3ffdb0ea514dfb1761a02d8d4da0bab",
"20260929171600_material_warehouse_stock": "47645ff022037ea486ca82902bdf09ca36ebf05a94500b160dcd57c2d812eab8",
"20260929173800_production_material_stock": "68f5755167f87a646901835be9fe6318a3ae6bb9a3d70d8a722915d1eff3c7a4",
"20260929195800_packaging_material_stock": "2b11c19499d917bcdd53ade20175235ef83cc64cdafda2118ea2dac2096a6f8d",
"20260929203400_finished_goods_receipt": "7745c23f9037d7bb0de7bdfaf94610794b83213f041583c0f9678c4e837f53f0",
"20260930002200_material_warehouse_transfers": "0f193ecd186971e19fdc823944312be70646b348a1a846ab41703d269936e21a",
"20260930003800_material_stock_adjustments": "2002d6826f34da5a999a0098a7191aa00f5fdc4ca54446b776270021d48ef5eb",
"20260930010000_b2b_business_verification": "1ab6537ff21436ce3421024f6f61e647c2c82a35a09a769833c6b82cdccca32b",
"20260930011800_b2b_price_lists": "c2f29a61c6fee93cbffb9d67654c323b2894b3aad7bb296b514f46b623db62d9",
"20260930190500_b2b_quotations": "0497ece6cb035687548773ce265842125fa1a655e5951e8d958290d664f5c3f0",
"20261001124700_b2b_credit_policies": "a831dc4568c19d8856be27dcb60ae4a7f8155dbeeb797cec2c2dd9f80b392837",
"20261001234900_b2b_sample_requests": "f4fb334341d996188dbea3fb85dbe5166bffd35bc8872f2c8404b6458bc7c142",
"20261003000100_b2b_artwork_approvals": "1359390fc3692bdc2dea8a4cc12223d97c7c15b0cdd2181b082b5e5acbe33677",
"20261003151400_b2b_partner_orders": "ffbba39ed98a16c122b0756a97d721adde9268904f9a7d9770407f341ef848ba",
"20261003183000_b2b_partner_payments": "bc43c5a713c62aa201affa2f2595156a2fc68882774504cdf12ac4cf0f641452",
"20261004003000_b2b_custom_candle_requests": "ab78d0a7e214ab226e042f29b42e961ddbae3a3e338fd65983d5aa87e2c736ac",
"20261004010000_b2b_partner_reporting": "44086ecc27278b9499fbcf5fa97ed754f056fcf49f6b155e1ed377527616dc89",
"20261005120000_private_wishlists": "8ded2f27a4e08ea6af3e5ae92f15b832cea66156a7489f28e178d3df6404f5e4",
"20261005160000_verified_product_reviews": "1f71f6d49622c48a37c88f2eb7740174cbc9aea7d0027f6fc27d81301d87c757",
"20261006120000_seasonal_campaigns": "4f81582f91a8d3cb30bf49051281ca05c862b794925c0643a7237d1a1efb6f40",
"20261006160000_campaign_discounts": "99485a5b252f01057dfa6300c567c79586555a76cec5c2dc0d9c3fef9fc61017",
"20261007120000_cart_recovery": "a415f3b458c55bf37a95f8d2f3b31dfc7ae4427f04aabc9f0910f1201caa6d31",
"20261007130000_messaging_consent": "b4fd5b1cf6a7cd17083a4b5fbef815ec1ebc25ba7538c6de18c05e16212155dd",
"20261007140000_blog_publishing": "92e8d98a8e89f3eda28b6cf5c3b45125a325e5d8e852f1e5a0a3cf5d7eff65a4",
"20261007150000_customer_segments": "bcafd50bc12dc44b7ee532ba4ca23da0b12eb3f0e89ad4b168789a22e110969a",
"20261007160000_moderated_forums": "3a7dce2115e06acd0f4b02d366721db5ebcf8b5f31106b5d85093c1374a2b6a5",
"20261007170000_commerce_analytics": "800e392f788e176e3fb27c04f956a18e5f1505b820af6bb2364fc990aa8d26ea",
"20261008100000_capture_forecasts": "69b94ac61b9f1c3f47268d5586d7f73c4c392cabdd3049d01f34e5e033cac043",
"20261008110000_accounting_sources": "47b89e83291dbdf7b9fc7f1f25e7260a9f06bde0291ae2f7db01200e75eed396",
"20261008120000_batch_contribution": "4d6c577e6d59e9163c41253b828ed19729b76d881f21197f6b863c2f79233471",
"20261008130000_order_expiry_workflow": "e9ff103b0870e6998e2a906924a4f0394ac8ccbbe811b323d8485c3ee0dd92ff",
"20261126080000_product_images": "ce59729946f37d8958bb9f42974859b76cdaaa67e85491dc5a7eb3fa9e07d9eb"
}

View File

@ -0,0 +1,92 @@
CREATE TYPE "SupplierPaymentMethod" AS ENUM ('BANK_TRANSFER', 'UPI', 'CHEQUE', 'CASH', 'OTHER');
CREATE TABLE "supplier_payments" (
"id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"invoice_id" UUID NOT NULL,
"created_by_id" UUID NOT NULL,
"idempotency_key" UUID NOT NULL,
"request_hash" CHAR(64) NOT NULL,
"reference" VARCHAR(80) NOT NULL,
"method" "SupplierPaymentMethod" NOT NULL,
"currency" CHAR(3) NOT NULL,
"amount" DECIMAL(12,2) NOT NULL,
"paid_at" DATE NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "supplier_payments_pkey" PRIMARY KEY ("id"),
CONSTRAINT "supplier_payments_valid" CHECK (
"amount" > 0 AND "reference" ~ '^[A-Z0-9][A-Z0-9._/-]{0,79}$'
AND "request_hash" ~ '^[a-f0-9]{64}$'
)
);
CREATE UNIQUE INDEX "supplier_payments_organization_id_idempotency_key_key" ON "supplier_payments"("organization_id", "idempotency_key");
CREATE UNIQUE INDEX "supplier_payments_organization_id_reference_key" ON "supplier_payments"("organization_id", "reference");
CREATE UNIQUE INDEX "supplier_payments_id_organization_id_key" ON "supplier_payments"("id", "organization_id");
CREATE INDEX "supplier_payments_invoice_created_idx" ON "supplier_payments"("organization_id", "invoice_id", "created_at", "id");
ALTER TABLE "supplier_payments" ADD CONSTRAINT "supplier_payments_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "supplier_payments" ADD CONSTRAINT "supplier_payments_invoice_id_organization_id_fkey" FOREIGN KEY ("invoice_id", "organization_id") REFERENCES "supplier_invoices"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "supplier_payments" ADD CONSTRAINT "supplier_payments_created_by_id_organization_id_fkey" FOREIGN KEY ("created_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE TABLE "supplier_payment_reversals" (
"payment_id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"reversed_by_id" UUID NOT NULL,
"reason" VARCHAR(500) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "supplier_payment_reversals_pkey" PRIMARY KEY ("payment_id"),
CONSTRAINT "supplier_payment_reversals_reason" CHECK (LENGTH(TRIM("reason")) > 0)
);
CREATE UNIQUE INDEX "supplier_payment_reversals_payment_id_organization_id_key" ON "supplier_payment_reversals"("payment_id", "organization_id");
ALTER TABLE "supplier_payment_reversals" ADD CONSTRAINT "supplier_payment_reversals_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "supplier_payment_reversals" ADD CONSTRAINT "supplier_payment_reversal_payment_scope_fkey" FOREIGN KEY ("payment_id", "organization_id") REFERENCES "supplier_payments"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "supplier_payment_reversals" ADD CONSTRAINT "supplier_payment_reversal_actor_scope_fkey" FOREIGN KEY ("reversed_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
UPDATE "roles" SET "permissions" = array_append("permissions", 'supplier_payment.manage')
WHERE "is_system" = true AND "name" = 'Owner' AND NOT ('supplier_payment.manage' = ANY("permissions"));
CREATE FUNCTION check_supplier_payment() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE payable NUMERIC; invoice_currency CHAR(3); paid NUMERIC;
BEGIN
SELECT payable_total, currency INTO payable, invoice_currency FROM supplier_invoices WHERE id = NEW.invoice_id FOR UPDATE;
IF EXISTS (SELECT 1 FROM supplier_invoice_voids WHERE invoice_id = NEW.invoice_id) THEN
RAISE EXCEPTION 'Cannot pay a void supplier invoice';
END IF;
IF invoice_currency IS DISTINCT FROM NEW.currency THEN
RAISE EXCEPTION 'Supplier payment currency does not match invoice';
END IF;
SELECT COALESCE(SUM(sp.amount), 0) INTO paid
FROM supplier_payments sp LEFT JOIN supplier_payment_reversals sr ON sr.payment_id = sp.id
WHERE sp.invoice_id = NEW.invoice_id AND sr.payment_id IS NULL;
IF paid + NEW.amount > payable THEN
RAISE EXCEPTION 'Supplier payment exceeds invoice balance';
END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER supplier_payment_balance BEFORE INSERT ON supplier_payments FOR EACH ROW EXECUTE FUNCTION check_supplier_payment();
CREATE FUNCTION check_supplier_invoice_void_payment() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
PERFORM id FROM supplier_invoices WHERE id = NEW.invoice_id FOR UPDATE;
IF EXISTS (
SELECT 1 FROM supplier_payments sp LEFT JOIN supplier_payment_reversals sr ON sr.payment_id = sp.id
WHERE sp.invoice_id = NEW.invoice_id AND sr.payment_id IS NULL
) THEN RAISE EXCEPTION 'Cannot void an invoice with active payments'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER supplier_invoice_void_payment_guard BEFORE INSERT ON supplier_invoice_voids FOR EACH ROW EXECUTE FUNCTION check_supplier_invoice_void_payment();
CREATE FUNCTION lock_supplier_payment_invoice() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
PERFORM id FROM supplier_invoices WHERE id = (SELECT invoice_id FROM supplier_payments WHERE id = NEW.payment_id) FOR UPDATE;
RETURN NEW;
END;
$$;
CREATE TRIGGER supplier_payment_reversal_lock BEFORE INSERT ON supplier_payment_reversals FOR EACH ROW EXECUTE FUNCTION lock_supplier_payment_invoice();
CREATE FUNCTION reject_supplier_payment_mutation() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN RAISE EXCEPTION 'Supplier payment records are immutable'; END;
$$;
CREATE TRIGGER supplier_payments_immutable BEFORE UPDATE OR DELETE ON supplier_payments FOR EACH ROW EXECUTE FUNCTION reject_supplier_payment_mutation();
CREATE TRIGGER supplier_payment_reversals_immutable BEFORE UPDATE OR DELETE ON supplier_payment_reversals FOR EACH ROW EXECUTE FUNCTION reject_supplier_payment_mutation();

View File

@ -0,0 +1,86 @@
CREATE TYPE "SupplierDocumentKind" AS ENUM ('REGISTRATION', 'TAX_CERTIFICATE', 'COMPLIANCE_CERTIFICATE', 'OTHER');
CREATE TYPE "SupplierDocumentOutcome" AS ENUM ('APPROVED', 'REJECTED');
CREATE TABLE "supplier_documents" (
"id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"supplier_id" UUID NOT NULL,
"created_by_id" UUID NOT NULL,
"code" VARCHAR(32) NOT NULL,
"kind" "SupplierDocumentKind" NOT NULL,
"title" VARCHAR(160) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "supplier_documents_pkey" PRIMARY KEY ("id"),
CONSTRAINT "supplier_documents_code" CHECK ("code" ~ '^[A-Z0-9][A-Z0-9_-]{0,31}$' AND LENGTH(TRIM("title")) > 0)
);
CREATE UNIQUE INDEX "supplier_documents_organization_id_supplier_id_code_key" ON "supplier_documents"("organization_id", "supplier_id", "code");
CREATE UNIQUE INDEX "supplier_documents_id_organization_id_key" ON "supplier_documents"("id", "organization_id");
CREATE INDEX "supplier_documents_supplier_created_idx" ON "supplier_documents"("organization_id", "supplier_id", "created_at", "id");
ALTER TABLE "supplier_documents" ADD CONSTRAINT "supplier_documents_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "supplier_documents" ADD CONSTRAINT "supplier_documents_supplier_id_organization_id_fkey" FOREIGN KEY ("supplier_id", "organization_id") REFERENCES "suppliers"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "supplier_documents" ADD CONSTRAINT "supplier_documents_created_by_id_organization_id_fkey" FOREIGN KEY ("created_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE TABLE "supplier_document_versions" (
"id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"document_id" UUID NOT NULL,
"uploaded_by_id" UUID NOT NULL,
"version" INTEGER NOT NULL,
"filename" VARCHAR(120) NOT NULL,
"mime_type" VARCHAR(32) NOT NULL,
"sha256" CHAR(64) NOT NULL,
"size" INTEGER NOT NULL,
"content" BYTEA NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "supplier_document_versions_pkey" PRIMARY KEY ("id"),
CONSTRAINT "supplier_document_versions_valid" CHECK (
"version" BETWEEN 1 AND 20 AND "size" BETWEEN 1 AND 2097152
AND OCTET_LENGTH("content") = "size"
AND SUBSTRING("content" FROM 1 FOR 5) = decode('255044462d', 'hex')
AND "mime_type" = 'application/pdf'
AND "sha256" ~ '^[a-f0-9]{64}$'
AND "filename" ~ '^[A-Za-z0-9][A-Za-z0-9._-]{0,115}[.]pdf$'
)
);
CREATE UNIQUE INDEX "supplier_document_versions_document_id_version_key" ON "supplier_document_versions"("document_id", "version");
CREATE UNIQUE INDEX "supplier_document_versions_id_organization_id_key" ON "supplier_document_versions"("id", "organization_id");
CREATE INDEX "supplier_document_versions_organization_id_document_id_vers_idx" ON "supplier_document_versions"("organization_id", "document_id", "version");
ALTER TABLE "supplier_document_versions" ADD CONSTRAINT "supplier_document_versions_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "supplier_document_versions" ADD CONSTRAINT "supplier_document_versions_document_id_organization_id_fkey" FOREIGN KEY ("document_id", "organization_id") REFERENCES "supplier_documents"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "supplier_document_versions" ADD CONSTRAINT "supplier_document_versions_uploaded_by_id_organization_id_fkey" FOREIGN KEY ("uploaded_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE TABLE "supplier_document_decisions" (
"version_id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"validated_by_id" UUID NOT NULL,
"outcome" "SupplierDocumentOutcome" NOT NULL,
"reason" VARCHAR(500),
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "supplier_document_decisions_pkey" PRIMARY KEY ("version_id"),
CONSTRAINT "supplier_document_decisions_reason" CHECK ("outcome" <> 'REJECTED' OR ("reason" IS NOT NULL AND LENGTH(TRIM("reason")) > 0))
);
CREATE UNIQUE INDEX "supplier_document_decisions_version_id_organization_id_key" ON "supplier_document_decisions"("version_id", "organization_id");
ALTER TABLE "supplier_document_decisions" ADD CONSTRAINT "supplier_document_decisions_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "supplier_document_decisions" ADD CONSTRAINT "supplier_document_decision_version_scope_fkey" FOREIGN KEY ("version_id", "organization_id") REFERENCES "supplier_document_versions"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "supplier_document_decisions" ADD CONSTRAINT "supplier_document_decision_actor_scope_fkey" FOREIGN KEY ("validated_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
UPDATE "roles" SET "permissions" = array_append(array_append(array_append("permissions", 'supplier_document.read'), 'supplier_document.manage'), 'supplier_document.validate')
WHERE "is_system" = true AND "name" = 'Owner' AND NOT ('supplier_document.read' = ANY("permissions"));
CREATE FUNCTION check_supplier_document_version() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE previous_version INTEGER;
BEGIN
PERFORM id FROM supplier_documents WHERE id = NEW.document_id FOR UPDATE;
SELECT COALESCE(MAX(version), 0) INTO previous_version FROM supplier_document_versions WHERE document_id = NEW.document_id;
IF NEW.version <> previous_version + 1 THEN RAISE EXCEPTION 'Supplier document version must be sequential'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER supplier_document_version_sequence BEFORE INSERT ON supplier_document_versions FOR EACH ROW EXECUTE FUNCTION check_supplier_document_version();
CREATE FUNCTION reject_supplier_document_mutation() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN RAISE EXCEPTION 'Supplier document records are immutable'; END;
$$;
CREATE TRIGGER supplier_documents_immutable BEFORE UPDATE OR DELETE ON supplier_documents FOR EACH ROW EXECUTE FUNCTION reject_supplier_document_mutation();
CREATE TRIGGER supplier_document_versions_immutable BEFORE UPDATE OR DELETE ON supplier_document_versions FOR EACH ROW EXECUTE FUNCTION reject_supplier_document_mutation();
CREATE TRIGGER supplier_document_decisions_immutable BEFORE UPDATE OR DELETE ON supplier_document_decisions FOR EACH ROW EXECUTE FUNCTION reject_supplier_document_mutation();

View File

@ -0,0 +1,77 @@
CREATE TYPE "BomStatus" AS ENUM ('DRAFT', 'ACTIVE', 'SUPERSEDED');
CREATE TABLE "product_boms" (
"id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"variant_id" UUID NOT NULL,
"created_by_id" UUID NOT NULL,
"revision" INTEGER NOT NULL,
"output_quantity" INTEGER NOT NULL,
"status" "BomStatus" NOT NULL DEFAULT 'DRAFT',
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"activated_at" TIMESTAMPTZ(3),
CONSTRAINT "product_boms_pkey" PRIMARY KEY ("id"),
CONSTRAINT "product_boms_quantity" CHECK ("revision" BETWEEN 1 AND 100 AND "output_quantity" BETWEEN 1 AND 100000),
CONSTRAINT "product_boms_activation" CHECK (("status" = 'DRAFT' AND "activated_at" IS NULL) OR ("status" <> 'DRAFT' AND "activated_at" IS NOT NULL))
);
CREATE UNIQUE INDEX "product_boms_variant_id_revision_key" ON "product_boms"("variant_id", "revision");
CREATE UNIQUE INDEX "product_boms_id_organization_id_key" ON "product_boms"("id", "organization_id");
CREATE UNIQUE INDEX "product_boms_one_active_idx" ON "product_boms"("variant_id") WHERE "status" = 'ACTIVE';
CREATE INDEX "product_boms_organization_id_variant_id_created_at_id_idx" ON "product_boms"("organization_id", "variant_id", "created_at", "id");
ALTER TABLE "product_boms" ADD CONSTRAINT "product_boms_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "product_boms" ADD CONSTRAINT "product_boms_variant_id_organization_id_fkey" FOREIGN KEY ("variant_id", "organization_id") REFERENCES "product_variants"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "product_boms" ADD CONSTRAINT "product_boms_created_by_id_organization_id_fkey" FOREIGN KEY ("created_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE TABLE "product_bom_lines" (
"id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"bom_id" UUID NOT NULL,
"material_id" UUID NOT NULL,
"material_name" VARCHAR(160) NOT NULL,
"material_code" VARCHAR(32) NOT NULL,
"unit" "MaterialUnit" NOT NULL,
"quantity" DECIMAL(12,3) NOT NULL,
CONSTRAINT "product_bom_lines_pkey" PRIMARY KEY ("id"),
CONSTRAINT "product_bom_lines_quantity" CHECK ("quantity" > 0)
);
CREATE UNIQUE INDEX "product_bom_lines_bom_id_material_id_key" ON "product_bom_lines"("bom_id", "material_id");
CREATE INDEX "product_bom_lines_organization_id_material_id_idx" ON "product_bom_lines"("organization_id", "material_id");
ALTER TABLE "product_bom_lines" ADD CONSTRAINT "product_bom_lines_bom_id_organization_id_fkey" FOREIGN KEY ("bom_id", "organization_id") REFERENCES "product_boms"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "product_bom_lines" ADD CONSTRAINT "product_bom_lines_material_id_organization_id_fkey" FOREIGN KEY ("material_id", "organization_id") REFERENCES "materials"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE FUNCTION check_product_bom_revision() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE previous_revision INTEGER;
BEGIN
PERFORM id FROM product_variants WHERE id = NEW.variant_id FOR UPDATE;
SELECT COALESCE(MAX(revision), 0) INTO previous_revision FROM product_boms WHERE variant_id = NEW.variant_id;
IF NEW.revision <> previous_revision + 1 THEN RAISE EXCEPTION 'Product BOM revision must be sequential'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER product_bom_revision_sequence BEFORE INSERT ON product_boms FOR EACH ROW EXECUTE FUNCTION check_product_bom_revision();
CREATE FUNCTION guard_product_bom_mutation() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP = 'DELETE' OR NEW.id <> OLD.id OR NEW.organization_id <> OLD.organization_id OR NEW.variant_id <> OLD.variant_id
OR NEW.created_by_id <> OLD.created_by_id OR NEW.revision <> OLD.revision OR NEW.output_quantity <> OLD.output_quantity
OR NEW.created_at <> OLD.created_at
OR NOT ((OLD.status = 'DRAFT' AND NEW.status = 'ACTIVE' AND OLD.activated_at IS NULL AND NEW.activated_at IS NOT NULL)
OR (OLD.status = 'ACTIVE' AND NEW.status = 'SUPERSEDED' AND NEW.activated_at = OLD.activated_at))
THEN RAISE EXCEPTION 'Product BOM mutation is not allowed'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER product_boms_guard BEFORE UPDATE OR DELETE ON product_boms FOR EACH ROW EXECUTE FUNCTION guard_product_bom_mutation();
CREATE FUNCTION guard_product_bom_line() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Product BOM lines are immutable'; END IF;
IF NOT EXISTS (SELECT 1 FROM product_boms WHERE id = NEW.bom_id AND organization_id = NEW.organization_id AND status = 'DRAFT')
THEN RAISE EXCEPTION 'Product BOM lines require a draft'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER product_bom_lines_guard BEFORE INSERT OR UPDATE OR DELETE ON product_bom_lines FOR EACH ROW EXECUTE FUNCTION guard_product_bom_line();
UPDATE "roles" SET "permissions" = array_append(array_append("permissions", 'bom.read'), 'bom.manage')
WHERE "is_system" = true AND "name" = 'Owner' AND NOT ('bom.read' = ANY("permissions"));

View File

@ -0,0 +1,95 @@
CREATE TYPE "ProductionBatchStatus" AS ENUM ('DRAFT', 'IN_PROGRESS', 'COMPLETED', 'CANCELLED');
CREATE TABLE "production_batches" (
"id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"bom_id" UUID NOT NULL,
"created_by_id" UUID NOT NULL,
"reference" VARCHAR(32) NOT NULL,
"planned_quantity" INTEGER NOT NULL,
"status" "ProductionBatchStatus" NOT NULL DEFAULT 'DRAFT',
"scheduled_date" DATE,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"started_at" TIMESTAMPTZ(3),
CONSTRAINT "production_batches_pkey" PRIMARY KEY ("id"),
CONSTRAINT "production_batches_values" CHECK ("reference" ~ '^[A-Z0-9][A-Z0-9_-]{0,31}$' AND "planned_quantity" BETWEEN 1 AND 100000),
CONSTRAINT "production_batches_started" CHECK (("status" = 'DRAFT' AND "started_at" IS NULL) OR ("status" IN ('IN_PROGRESS', 'COMPLETED') AND "started_at" IS NOT NULL) OR "status" = 'CANCELLED')
);
CREATE UNIQUE INDEX "production_batches_organization_id_reference_key" ON "production_batches"("organization_id", "reference");
CREATE UNIQUE INDEX "production_batches_id_organization_id_key" ON "production_batches"("id", "organization_id");
CREATE INDEX "production_batches_organization_id_status_created_at_id_idx" ON "production_batches"("organization_id", "status", "created_at", "id");
CREATE INDEX "production_batches_organization_id_bom_id_idx" ON "production_batches"("organization_id", "bom_id");
ALTER TABLE "production_batches" ADD CONSTRAINT "production_batches_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "production_batches" ADD CONSTRAINT "production_batches_bom_id_organization_id_fkey" FOREIGN KEY ("bom_id", "organization_id") REFERENCES "product_boms"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "production_batches" ADD CONSTRAINT "production_batches_created_by_id_organization_id_fkey" FOREIGN KEY ("created_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE TABLE "production_batch_completions" (
"batch_id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"completed_by_id" UUID NOT NULL,
"good_quantity" INTEGER NOT NULL,
"rejected_quantity" INTEGER NOT NULL,
"rejection_reason" VARCHAR(500),
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "production_batch_completions_pkey" PRIMARY KEY ("batch_id"),
CONSTRAINT "production_batch_completions_values" CHECK ("good_quantity" >= 0 AND "rejected_quantity" >= 0 AND ("rejected_quantity" = 0 OR ("rejection_reason" IS NOT NULL AND LENGTH(TRIM("rejection_reason")) > 0)))
);
CREATE UNIQUE INDEX "production_batch_completions_batch_id_organization_id_key" ON "production_batch_completions"("batch_id", "organization_id");
ALTER TABLE "production_batch_completions" ADD CONSTRAINT "production_batch_completions_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "production_batch_completions" ADD CONSTRAINT "production_batch_completions_batch_id_organization_id_fkey" FOREIGN KEY ("batch_id", "organization_id") REFERENCES "production_batches"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "production_batch_completions" ADD CONSTRAINT "production_batch_completions_completed_by_id_organization__fkey" FOREIGN KEY ("completed_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE TABLE "production_batch_cancellations" (
"batch_id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"cancelled_by_id" UUID NOT NULL,
"reason" VARCHAR(500) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "production_batch_cancellations_pkey" PRIMARY KEY ("batch_id"),
CONSTRAINT "production_batch_cancellations_reason" CHECK (LENGTH(TRIM("reason")) > 0)
);
CREATE UNIQUE INDEX "production_batch_cancellations_batch_id_organization_id_key" ON "production_batch_cancellations"("batch_id", "organization_id");
ALTER TABLE "production_batch_cancellations" ADD CONSTRAINT "production_batch_cancellations_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "production_batch_cancellations" ADD CONSTRAINT "production_batch_cancellations_batch_id_organization_id_fkey" FOREIGN KEY ("batch_id", "organization_id") REFERENCES "production_batches"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "production_batch_cancellations" ADD CONSTRAINT "production_batch_cancellations_cancelled_by_id_organizatio_fkey" FOREIGN KEY ("cancelled_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE FUNCTION guard_production_batch_transition() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP = 'INSERT' THEN
IF NEW.status <> 'DRAFT' OR NEW.started_at IS NOT NULL THEN RAISE EXCEPTION 'Production batch must begin as draft'; END IF;
RETURN NEW;
END IF;
IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'Production batches cannot be deleted'; END IF;
IF NEW.id <> OLD.id OR NEW.organization_id <> OLD.organization_id OR NEW.bom_id <> OLD.bom_id
OR NEW.created_by_id <> OLD.created_by_id OR NEW.reference <> OLD.reference
OR NEW.planned_quantity <> OLD.planned_quantity OR NEW.scheduled_date IS DISTINCT FROM OLD.scheduled_date
OR NEW.created_at <> OLD.created_at OR NOT (
(OLD.status = 'DRAFT' AND NEW.status = 'IN_PROGRESS' AND OLD.started_at IS NULL AND NEW.started_at IS NOT NULL)
OR (OLD.status = 'DRAFT' AND NEW.status = 'CANCELLED' AND NEW.started_at IS NULL)
OR (OLD.status = 'IN_PROGRESS' AND NEW.status IN ('COMPLETED', 'CANCELLED') AND NEW.started_at = OLD.started_at)
)
THEN RAISE EXCEPTION 'Invalid production batch transition'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER production_batches_guard BEFORE INSERT OR UPDATE OR DELETE ON production_batches FOR EACH ROW EXECUTE FUNCTION guard_production_batch_transition();
CREATE FUNCTION guard_production_batch_event() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE parent production_batches%ROWTYPE;
BEGIN
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Production batch events are immutable'; END IF;
SELECT * INTO parent FROM production_batches WHERE id = NEW.batch_id AND organization_id = NEW.organization_id;
IF TG_TABLE_NAME = 'production_batch_completions' THEN
IF parent.status <> 'COMPLETED' OR NEW.good_quantity + NEW.rejected_quantity <> parent.planned_quantity
THEN RAISE EXCEPTION 'Production batch completion does not reconcile'; END IF;
ELSIF parent.status <> 'CANCELLED' THEN
RAISE EXCEPTION 'Production batch is not cancelled';
END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER production_batch_completions_guard BEFORE INSERT OR UPDATE OR DELETE ON production_batch_completions FOR EACH ROW EXECUTE FUNCTION guard_production_batch_event();
CREATE TRIGGER production_batch_cancellations_guard BEFORE INSERT OR UPDATE OR DELETE ON production_batch_cancellations FOR EACH ROW EXECUTE FUNCTION guard_production_batch_event();
UPDATE "roles" SET "permissions" = array_append(array_append("permissions", 'production.read'), 'production.manage')
WHERE "is_system" = true AND "name" = 'Owner' AND NOT ('production.read' = ANY("permissions"));

View File

@ -0,0 +1,45 @@
CREATE TYPE "MaterialUsageKind" AS ENUM ('CONSUMED', 'WASTED');
CREATE UNIQUE INDEX "production_batches_id_bom_id_organization_id_key" ON "production_batches"("id", "bom_id", "organization_id");
CREATE UNIQUE INDEX "product_bom_lines_id_bom_id_organization_id_key" ON "product_bom_lines"("id", "bom_id", "organization_id");
CREATE TABLE "production_material_usage" (
"id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"batch_id" UUID NOT NULL,
"bom_id" UUID NOT NULL,
"bom_line_id" UUID NOT NULL,
"recorded_by_id" UUID NOT NULL,
"kind" "MaterialUsageKind" NOT NULL,
"quantity" DECIMAL(12,3) NOT NULL,
"reason" VARCHAR(500),
"idempotency_key" UUID NOT NULL,
"request_hash" CHAR(64) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "production_material_usage_pkey" PRIMARY KEY ("id"),
CONSTRAINT "production_material_usage_values" CHECK (
"quantity" > 0 AND "request_hash" ~ '^[a-f0-9]{64}$'
AND ("kind" = 'CONSUMED' OR ("reason" IS NOT NULL AND LENGTH(TRIM("reason")) > 0))
)
);
CREATE UNIQUE INDEX "production_material_usage_idempotency_key" ON "production_material_usage"("organization_id", "idempotency_key");
CREATE INDEX "production_material_usage_batch_created_idx" ON "production_material_usage"("organization_id", "batch_id", "created_at", "id");
ALTER TABLE "production_material_usage" ADD CONSTRAINT "production_material_usage_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "production_material_usage" ADD CONSTRAINT "production_material_usage_batch_scope_fkey" FOREIGN KEY ("batch_id", "bom_id", "organization_id") REFERENCES "production_batches"("id", "bom_id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "production_material_usage" ADD CONSTRAINT "production_material_usage_line_scope_fkey" FOREIGN KEY ("bom_line_id", "bom_id", "organization_id") REFERENCES "product_bom_lines"("id", "bom_id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "production_material_usage" ADD CONSTRAINT "production_material_usage_actor_scope_fkey" FOREIGN KEY ("recorded_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE FUNCTION guard_production_material_usage() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Production material usage is immutable'; END IF;
IF NOT EXISTS (
SELECT 1 FROM production_batches
WHERE id = NEW.batch_id AND bom_id = NEW.bom_id AND organization_id = NEW.organization_id AND status = 'IN_PROGRESS'
) THEN RAISE EXCEPTION 'Material usage requires a started batch'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER production_material_usage_guard BEFORE INSERT OR UPDATE OR DELETE ON production_material_usage FOR EACH ROW EXECUTE FUNCTION guard_production_material_usage();
UPDATE "roles" SET "permissions" = array_append("permissions", 'production.material.record')
WHERE "is_system" = true AND "name" = 'Owner' AND NOT ('production.material.record' = ANY("permissions"));

View File

@ -0,0 +1,42 @@
CREATE TYPE "BomKind" AS ENUM ('PRODUCTION', 'PACKAGING');
ALTER TABLE "product_boms" ADD COLUMN "kind" "BomKind" NOT NULL DEFAULT 'PRODUCTION';
DROP INDEX "product_boms_variant_id_revision_key";
CREATE UNIQUE INDEX "product_boms_variant_id_kind_revision_key" ON "product_boms"("variant_id", "kind", "revision");
DROP INDEX "product_boms_one_active_idx";
CREATE UNIQUE INDEX "product_boms_one_active_idx" ON "product_boms"("variant_id", "kind") WHERE "status" = 'ACTIVE';
CREATE OR REPLACE FUNCTION check_product_bom_revision() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE previous_revision INTEGER;
BEGIN
PERFORM id FROM product_variants WHERE id = NEW.variant_id FOR UPDATE;
SELECT COALESCE(MAX(revision), 0) INTO previous_revision FROM product_boms WHERE variant_id = NEW.variant_id AND kind = NEW.kind;
IF NEW.revision <> previous_revision + 1 THEN RAISE EXCEPTION 'Product BOM revision must be sequential within kind'; END IF;
RETURN NEW;
END;
$$;
CREATE FUNCTION guard_product_bom_kind() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF NEW.kind <> OLD.kind THEN RAISE EXCEPTION 'Product BOM kind is immutable'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER product_boms_kind_guard BEFORE UPDATE ON product_boms FOR EACH ROW EXECUTE FUNCTION guard_product_bom_kind();
CREATE OR REPLACE FUNCTION guard_product_bom_line() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Product BOM lines are immutable'; END IF;
IF NOT EXISTS (SELECT 1 FROM product_boms WHERE id = NEW.bom_id AND organization_id = NEW.organization_id AND status = 'DRAFT')
THEN RAISE EXCEPTION 'Product BOM lines require a draft'; END IF;
IF EXISTS (
SELECT 1 FROM product_boms b JOIN materials m ON m.id = NEW.material_id AND m.organization_id = NEW.organization_id
WHERE b.id = NEW.bom_id AND b.organization_id = NEW.organization_id
AND b.kind = 'PACKAGING' AND m.kind NOT IN ('PACKAGING', 'LABEL')
) THEN RAISE EXCEPTION 'Packaging BOM requires packaging or label material'; END IF;
RETURN NEW;
END;
$$;
UPDATE "roles" SET "permissions" = array_append(array_append("permissions", 'packaging.read'), 'packaging.manage')
WHERE "is_system" = true AND "name" = 'Owner' AND NOT ('packaging.read' = ANY("permissions"));

View File

@ -0,0 +1,66 @@
CREATE TABLE "packaging_runs" (
"id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"batch_id" UUID NOT NULL,
"bom_id" UUID NOT NULL,
"recorded_by_id" UUID NOT NULL,
"idempotency_key" UUID NOT NULL,
"request_hash" CHAR(64) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "packaging_runs_pkey" PRIMARY KEY ("id"),
CONSTRAINT "packaging_runs_hash_check" CHECK ("request_hash" ~ '^[a-f0-9]{64}$')
);
CREATE UNIQUE INDEX "packaging_runs_batch_id_key" ON "packaging_runs"("batch_id");
CREATE UNIQUE INDEX "packaging_runs_batch_id_organization_id_key" ON "packaging_runs"("batch_id", "organization_id");
CREATE UNIQUE INDEX "packaging_runs_organization_id_idempotency_key_key" ON "packaging_runs"("organization_id", "idempotency_key");
CREATE UNIQUE INDEX "packaging_runs_id_bom_id_organization_id_key" ON "packaging_runs"("id", "bom_id", "organization_id");
CREATE INDEX "packaging_runs_organization_id_created_at_id_idx" ON "packaging_runs"("organization_id", "created_at", "id");
ALTER TABLE "packaging_runs" ADD CONSTRAINT "packaging_runs_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "packaging_runs" ADD CONSTRAINT "packaging_runs_batch_id_organization_id_fkey" FOREIGN KEY ("batch_id", "organization_id") REFERENCES "production_batches"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "packaging_runs" ADD CONSTRAINT "packaging_runs_bom_id_organization_id_fkey" FOREIGN KEY ("bom_id", "organization_id") REFERENCES "product_boms"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "packaging_runs" ADD CONSTRAINT "packaging_runs_recorded_by_id_organization_id_fkey" FOREIGN KEY ("recorded_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE TABLE "packaging_run_lines" (
"id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"run_id" UUID NOT NULL,
"bom_id" UUID NOT NULL,
"bom_line_id" UUID NOT NULL,
"used_quantity" DECIMAL(12,3) NOT NULL,
"wasted_quantity" DECIMAL(12,3) NOT NULL,
"waste_reason" VARCHAR(500),
CONSTRAINT "packaging_run_lines_pkey" PRIMARY KEY ("id"),
CONSTRAINT "packaging_run_lines_values" CHECK (
"used_quantity" >= 0 AND "wasted_quantity" >= 0
AND ("wasted_quantity" = 0 OR ("waste_reason" IS NOT NULL AND LENGTH(TRIM("waste_reason")) > 0))
)
);
CREATE UNIQUE INDEX "packaging_run_lines_run_id_bom_line_id_key" ON "packaging_run_lines"("run_id", "bom_line_id");
ALTER TABLE "packaging_run_lines" ADD CONSTRAINT "packaging_run_lines_run_id_bom_id_organization_id_fkey" FOREIGN KEY ("run_id", "bom_id", "organization_id") REFERENCES "packaging_runs"("id", "bom_id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "packaging_run_lines" ADD CONSTRAINT "packaging_run_lines_bom_line_id_bom_id_organization_id_fkey" FOREIGN KEY ("bom_line_id", "bom_id", "organization_id") REFERENCES "product_bom_lines"("id", "bom_id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE FUNCTION guard_packaging_run() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Packaging runs are immutable'; END IF;
IF NOT EXISTS (
SELECT 1 FROM production_batches b JOIN product_boms p ON p.id = NEW.bom_id AND p.organization_id = NEW.organization_id
WHERE b.id = NEW.batch_id AND b.organization_id = NEW.organization_id
AND b.status = 'COMPLETED' AND p.kind = 'PACKAGING' AND p.variant_id = (
SELECT variant_id FROM product_boms WHERE id = b.bom_id
)
) THEN RAISE EXCEPTION 'Packaging run requires a completed matching production batch'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER packaging_runs_guard BEFORE INSERT OR UPDATE OR DELETE ON packaging_runs FOR EACH ROW EXECUTE FUNCTION guard_packaging_run();
CREATE FUNCTION guard_packaging_run_line() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Packaging run lines are immutable'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER packaging_run_lines_guard BEFORE INSERT OR UPDATE OR DELETE ON packaging_run_lines FOR EACH ROW EXECUTE FUNCTION guard_packaging_run_line();
UPDATE "roles" SET "permissions" = array_append("permissions", 'packaging.record')
WHERE "is_system" = true AND "name" = 'Owner' AND NOT ('packaging.record' = ANY("permissions"));

View File

@ -0,0 +1,33 @@
CREATE TABLE "material_cost_rates" (
"id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"material_id" UUID NOT NULL,
"recorded_by_id" UUID NOT NULL,
"currency" CHAR(3) NOT NULL,
"revision" INTEGER NOT NULL,
"unit_cost" DECIMAL(12,4) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "material_cost_rates_pkey" PRIMARY KEY ("id"),
CONSTRAINT "material_cost_rates_values" CHECK ("revision" BETWEEN 1 AND 1000 AND "unit_cost" > 0 AND "currency" IN ('INR', 'USD', 'EUR', 'GBP'))
);
CREATE UNIQUE INDEX "material_cost_rates_material_id_currency_revision_key" ON "material_cost_rates"("material_id", "currency", "revision");
CREATE INDEX "material_cost_rates_scope_revision_idx" ON "material_cost_rates"("organization_id", "material_id", "currency", "revision");
ALTER TABLE "material_cost_rates" ADD CONSTRAINT "material_cost_rates_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "material_cost_rates" ADD CONSTRAINT "material_cost_rates_material_id_organization_id_fkey" FOREIGN KEY ("material_id", "organization_id") REFERENCES "materials"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "material_cost_rates" ADD CONSTRAINT "material_cost_rates_recorded_by_id_organization_id_fkey" FOREIGN KEY ("recorded_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE FUNCTION guard_material_cost_rate() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE previous_revision INTEGER;
BEGIN
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Material cost rates are immutable'; END IF;
PERFORM id FROM materials WHERE id = NEW.material_id AND organization_id = NEW.organization_id FOR UPDATE;
SELECT COALESCE(MAX(revision), 0) INTO previous_revision FROM material_cost_rates
WHERE material_id = NEW.material_id AND currency = NEW.currency;
IF NEW.revision <> previous_revision + 1 THEN RAISE EXCEPTION 'Material cost revision must be sequential'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER material_cost_rates_guard BEFORE INSERT OR UPDATE OR DELETE ON material_cost_rates FOR EACH ROW EXECUTE FUNCTION guard_material_cost_rate();
UPDATE "roles" SET "permissions" = array_append(array_append("permissions", 'cost.read'), 'cost.manage')
WHERE "is_system" = true AND "name" = 'Owner' AND NOT ('cost.read' = ANY("permissions"));

View File

@ -0,0 +1,88 @@
CREATE TYPE "BatchCostLineKind" AS ENUM ('PRODUCTION', 'PACKAGING');
CREATE UNIQUE INDEX "product_bom_lines_cost_scope_key" ON "product_bom_lines"("id", "bom_id", "material_id", "organization_id");
CREATE UNIQUE INDEX "material_cost_rates_id_material_id_organization_id_key" ON "material_cost_rates"("id", "material_id", "organization_id");
CREATE TABLE "batch_cost_snapshots" (
"id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"batch_id" UUID NOT NULL,
"created_by_id" UUID NOT NULL,
"idempotency_key" UUID NOT NULL,
"request_hash" CHAR(64) NOT NULL,
"currency" CHAR(3) NOT NULL,
"good_quantity" INTEGER NOT NULL,
"production_total" DECIMAL(12,2) NOT NULL,
"packaging_total" DECIMAL(12,2) NOT NULL,
"total" DECIMAL(12,2) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"sealed_at" TIMESTAMPTZ(3),
CONSTRAINT "batch_cost_snapshots_pkey" PRIMARY KEY ("id"),
CONSTRAINT "batch_cost_snapshots_values" CHECK (
"request_hash" ~ '^[a-f0-9]{64}$' AND "currency" IN ('INR', 'USD', 'EUR', 'GBP')
AND "good_quantity" >= 0 AND "production_total" >= 0 AND "packaging_total" >= 0
AND "total" = "production_total" + "packaging_total"
)
);
CREATE UNIQUE INDEX "batch_cost_snapshots_batch_id_key" ON "batch_cost_snapshots"("batch_id");
CREATE UNIQUE INDEX "batch_cost_snapshots_batch_id_organization_id_key" ON "batch_cost_snapshots"("batch_id", "organization_id");
CREATE UNIQUE INDEX "batch_cost_snapshots_organization_id_idempotency_key_key" ON "batch_cost_snapshots"("organization_id", "idempotency_key");
CREATE UNIQUE INDEX "batch_cost_snapshots_id_organization_id_key" ON "batch_cost_snapshots"("id", "organization_id");
ALTER TABLE "batch_cost_snapshots" ADD CONSTRAINT "batch_cost_snapshots_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "batch_cost_snapshots" ADD CONSTRAINT "batch_cost_snapshots_batch_id_organization_id_fkey" FOREIGN KEY ("batch_id", "organization_id") REFERENCES "production_batches"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "batch_cost_snapshots" ADD CONSTRAINT "batch_cost_snapshots_created_by_id_organization_id_fkey" FOREIGN KEY ("created_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE TABLE "batch_cost_lines" (
"id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"snapshot_id" UUID NOT NULL,
"kind" "BatchCostLineKind" NOT NULL,
"bom_id" UUID NOT NULL,
"bom_line_id" UUID NOT NULL,
"material_id" UUID NOT NULL,
"rate_id" UUID NOT NULL,
"used_quantity" DECIMAL(12,3) NOT NULL,
"wasted_quantity" DECIMAL(12,3) NOT NULL,
"unit_cost" DECIMAL(12,4) NOT NULL,
"line_cost" DECIMAL(12,2) NOT NULL,
CONSTRAINT "batch_cost_lines_pkey" PRIMARY KEY ("id"),
CONSTRAINT "batch_cost_lines_values" CHECK (
"used_quantity" >= 0 AND "wasted_quantity" >= 0 AND "unit_cost" > 0 AND "line_cost" >= 0
AND ROUND(("used_quantity" + "wasted_quantity") * "unit_cost", 2) = "line_cost"
)
);
CREATE UNIQUE INDEX "batch_cost_lines_snapshot_id_bom_line_id_key" ON "batch_cost_lines"("snapshot_id", "bom_line_id");
ALTER TABLE "batch_cost_lines" ADD CONSTRAINT "batch_cost_lines_snapshot_id_organization_id_fkey" FOREIGN KEY ("snapshot_id", "organization_id") REFERENCES "batch_cost_snapshots"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "batch_cost_lines" ADD CONSTRAINT "batch_cost_lines_bom_scope_fkey" FOREIGN KEY ("bom_line_id", "bom_id", "material_id", "organization_id") REFERENCES "product_bom_lines"("id", "bom_id", "material_id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "batch_cost_lines" ADD CONSTRAINT "batch_cost_lines_rate_scope_fkey" FOREIGN KEY ("rate_id", "material_id", "organization_id") REFERENCES "material_cost_rates"("id", "material_id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE FUNCTION guard_batch_cost_snapshot() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP = 'UPDATE' THEN
IF OLD.sealed_at IS NULL AND NEW.sealed_at IS NOT NULL
AND (to_jsonb(NEW) - 'sealed_at') = (to_jsonb(OLD) - 'sealed_at')
THEN RETURN NEW; END IF;
RAISE EXCEPTION 'Batch cost snapshots are immutable';
END IF;
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Batch cost snapshots are immutable'; END IF;
IF NOT EXISTS (
SELECT 1 FROM production_batches b JOIN production_batch_completions c
ON c.batch_id = b.id AND c.organization_id = b.organization_id
WHERE b.id = NEW.batch_id AND b.organization_id = NEW.organization_id
AND b.status = 'COMPLETED' AND c.good_quantity = NEW.good_quantity
) THEN RAISE EXCEPTION 'Batch cost snapshot requires matching completion'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER batch_cost_snapshots_guard BEFORE INSERT OR UPDATE OR DELETE ON batch_cost_snapshots FOR EACH ROW EXECUTE FUNCTION guard_batch_cost_snapshot();
CREATE FUNCTION guard_batch_cost_line() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Batch cost lines are immutable'; END IF;
IF NOT EXISTS (
SELECT 1 FROM batch_cost_snapshots WHERE id = NEW.snapshot_id
AND organization_id = NEW.organization_id AND sealed_at IS NULL
) THEN RAISE EXCEPTION 'Batch cost snapshot is sealed'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER batch_cost_lines_guard BEFORE INSERT OR UPDATE OR DELETE ON batch_cost_lines FOR EACH ROW EXECUTE FUNCTION guard_batch_cost_line();

View File

@ -0,0 +1,95 @@
CREATE TYPE "MaterialStockKind" AS ENUM ('RECEIPT_ACCEPTED');
CREATE UNIQUE INDEX "goods_receipts_id_organization_id_key" ON "goods_receipts"("id", "organization_id");
CREATE TABLE "material_stock_items" (
"id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"material_id" UUID NOT NULL,
"warehouse_id" UUID NOT NULL,
"on_hand" DECIMAL(12,3) NOT NULL DEFAULT 0,
CONSTRAINT "material_stock_items_pkey" PRIMARY KEY ("id"),
CONSTRAINT "material_stock_items_balance" CHECK ("on_hand" BETWEEN 0 AND 999999999.999)
);
CREATE UNIQUE INDEX "material_stock_items_material_id_warehouse_id_key" ON "material_stock_items"("material_id", "warehouse_id");
CREATE UNIQUE INDEX "material_stock_items_id_material_id_organization_id_key" ON "material_stock_items"("id", "material_id", "organization_id");
CREATE INDEX "material_stock_items_scope_idx" ON "material_stock_items"("organization_id", "warehouse_id", "material_id");
ALTER TABLE "material_stock_items" ADD CONSTRAINT "material_stock_items_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "material_stock_items" ADD CONSTRAINT "material_stock_items_material_id_organization_id_fkey" FOREIGN KEY ("material_id", "organization_id") REFERENCES "materials"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "material_stock_items" ADD CONSTRAINT "material_stock_items_warehouse_id_organization_id_fkey" FOREIGN KEY ("warehouse_id", "organization_id") REFERENCES "warehouses"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE TABLE "material_receipt_postings" (
"id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"receipt_id" UUID NOT NULL,
"warehouse_id" UUID NOT NULL,
"posted_by_id" UUID NOT NULL,
"idempotency_key" UUID NOT NULL,
"request_hash" CHAR(64) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "material_receipt_postings_pkey" PRIMARY KEY ("id"),
CONSTRAINT "material_receipt_postings_hash" CHECK ("request_hash" ~ '^[a-f0-9]{64}$')
);
CREATE UNIQUE INDEX "material_receipt_postings_receipt_id_key" ON "material_receipt_postings"("receipt_id");
CREATE UNIQUE INDEX "material_receipt_postings_receipt_id_organization_id_key" ON "material_receipt_postings"("receipt_id", "organization_id");
CREATE UNIQUE INDEX "material_receipt_postings_organization_id_idempotency_key_key" ON "material_receipt_postings"("organization_id", "idempotency_key");
CREATE UNIQUE INDEX "material_receipt_postings_id_organization_id_key" ON "material_receipt_postings"("id", "organization_id");
ALTER TABLE "material_receipt_postings" ADD CONSTRAINT "material_receipt_postings_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "material_receipt_postings" ADD CONSTRAINT "material_receipt_postings_receipt_id_organization_id_fkey" FOREIGN KEY ("receipt_id", "organization_id") REFERENCES "goods_receipts"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "material_receipt_postings" ADD CONSTRAINT "material_receipt_postings_warehouse_id_organization_id_fkey" FOREIGN KEY ("warehouse_id", "organization_id") REFERENCES "warehouses"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "material_receipt_postings" ADD CONSTRAINT "material_receipt_postings_posted_by_id_organization_id_fkey" FOREIGN KEY ("posted_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE TABLE "material_stock_ledger" (
"id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"stock_item_id" UUID NOT NULL,
"material_id" UUID NOT NULL,
"posting_id" UUID NOT NULL,
"receipt_line_id" UUID NOT NULL,
"kind" "MaterialStockKind" NOT NULL,
"delta" DECIMAL(12,3) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "material_stock_ledger_pkey" PRIMARY KEY ("id"),
CONSTRAINT "material_stock_ledger_quantity" CHECK ("kind" = 'RECEIPT_ACCEPTED' AND "delta" > 0)
);
CREATE UNIQUE INDEX "material_stock_ledger_receipt_line_id_key" ON "material_stock_ledger"("receipt_line_id");
CREATE UNIQUE INDEX "material_stock_ledger_receipt_line_id_organization_id_key" ON "material_stock_ledger"("receipt_line_id", "organization_id");
CREATE INDEX "material_stock_ledger_item_created_idx" ON "material_stock_ledger"("organization_id", "stock_item_id", "created_at", "id");
ALTER TABLE "material_stock_ledger" ADD CONSTRAINT "material_stock_ledger_item_scope_fkey" FOREIGN KEY ("stock_item_id", "material_id", "organization_id") REFERENCES "material_stock_items"("id", "material_id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "material_stock_ledger" ADD CONSTRAINT "material_stock_ledger_posting_scope_fkey" FOREIGN KEY ("posting_id", "organization_id") REFERENCES "material_receipt_postings"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "material_stock_ledger" ADD CONSTRAINT "material_stock_ledger_receipt_scope_fkey" FOREIGN KEY ("receipt_line_id", "organization_id") REFERENCES "goods_receipt_lines"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE FUNCTION guard_material_receipt_posting() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Material receipt postings are immutable'; END IF;
IF EXISTS (
SELECT 1 FROM goods_receipt_lines l WHERE l.receipt_id = NEW.receipt_id
AND l.organization_id = NEW.organization_id AND NOT EXISTS (
SELECT 1 FROM receipt_inspections i WHERE i.receipt_line_id = l.id AND i.organization_id = NEW.organization_id
)
) THEN RAISE EXCEPTION 'Receipt requires complete QC before stock posting'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER material_receipt_postings_guard BEFORE INSERT OR UPDATE OR DELETE ON material_receipt_postings FOR EACH ROW EXECUTE FUNCTION guard_material_receipt_posting();
CREATE FUNCTION guard_material_stock_ledger() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Material stock ledger is immutable'; END IF;
IF NOT EXISTS (
SELECT 1 FROM material_receipt_postings p
JOIN goods_receipt_lines l ON l.receipt_id = p.receipt_id AND l.id = NEW.receipt_line_id AND l.organization_id = NEW.organization_id
JOIN purchase_order_lines ol ON ol.id = l.purchase_order_line_id AND ol.organization_id = NEW.organization_id
JOIN receipt_inspections i ON i.receipt_line_id = l.id AND i.organization_id = NEW.organization_id
JOIN material_stock_items s ON s.id = NEW.stock_item_id AND s.organization_id = NEW.organization_id
WHERE p.id = NEW.posting_id AND p.organization_id = NEW.organization_id
AND s.warehouse_id = p.warehouse_id AND s.material_id = ol.material_id
AND NEW.material_id = ol.material_id AND NEW.delta = i.accepted_quantity
) THEN RAISE EXCEPTION 'Material receipt stock entry does not match accepted QC'; END IF;
UPDATE material_stock_items SET on_hand = on_hand + NEW.delta
WHERE id = NEW.stock_item_id AND organization_id = NEW.organization_id
AND on_hand + NEW.delta <= 999999999.999;
IF NOT FOUND THEN RAISE EXCEPTION 'Material stock capacity exceeded'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER material_stock_ledger_guard BEFORE INSERT OR UPDATE OR DELETE ON material_stock_ledger FOR EACH ROW EXECUTE FUNCTION guard_material_stock_ledger();

View File

@ -0,0 +1,84 @@
ALTER TABLE "material_stock_ledger" DROP CONSTRAINT "material_stock_ledger_quantity";
ALTER TYPE "MaterialStockKind" RENAME TO "MaterialStockKind_old";
CREATE TYPE "MaterialStockKind" AS ENUM ('RECEIPT_ACCEPTED', 'PRODUCTION_CONSUMED', 'PRODUCTION_WASTED');
ALTER TABLE "material_stock_ledger" ALTER COLUMN "kind" TYPE "MaterialStockKind" USING "kind"::text::"MaterialStockKind";
DROP TYPE "MaterialStockKind_old";
CREATE TABLE "production_stock_postings" (
"id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"batch_id" UUID NOT NULL,
"warehouse_id" UUID NOT NULL,
"posted_by_id" UUID NOT NULL,
"idempotency_key" UUID NOT NULL,
"request_hash" CHAR(64) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "production_stock_postings_pkey" PRIMARY KEY ("id"),
CONSTRAINT "production_stock_postings_hash" CHECK ("request_hash" ~ '^[a-f0-9]{64}$')
);
CREATE UNIQUE INDEX "production_stock_postings_batch_id_key" ON "production_stock_postings"("batch_id");
CREATE UNIQUE INDEX "production_stock_postings_batch_id_organization_id_key" ON "production_stock_postings"("batch_id", "organization_id");
CREATE UNIQUE INDEX "production_stock_postings_organization_id_idempotency_key_key" ON "production_stock_postings"("organization_id", "idempotency_key");
CREATE UNIQUE INDEX "production_stock_postings_id_organization_id_key" ON "production_stock_postings"("id", "organization_id");
ALTER TABLE "production_stock_postings" ADD CONSTRAINT "production_stock_postings_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "production_stock_postings" ADD CONSTRAINT "production_stock_postings_batch_id_organization_id_fkey" FOREIGN KEY ("batch_id", "organization_id") REFERENCES "production_batches"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "production_stock_postings" ADD CONSTRAINT "production_stock_postings_warehouse_id_organization_id_fkey" FOREIGN KEY ("warehouse_id", "organization_id") REFERENCES "warehouses"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "production_stock_postings" ADD CONSTRAINT "production_stock_postings_posted_by_id_organization_id_fkey" FOREIGN KEY ("posted_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "material_stock_ledger" ALTER COLUMN "posting_id" DROP NOT NULL;
ALTER TABLE "material_stock_ledger" ALTER COLUMN "receipt_line_id" DROP NOT NULL;
ALTER TABLE "material_stock_ledger" ADD COLUMN "production_posting_id" UUID;
ALTER TABLE "material_stock_ledger" ADD COLUMN "usage_event_id" UUID;
CREATE UNIQUE INDEX "material_stock_ledger_usage_event_id_key" ON "material_stock_ledger"("usage_event_id");
ALTER TABLE "material_stock_ledger" ADD CONSTRAINT "material_stock_ledger_production_scope_fkey" FOREIGN KEY ("production_posting_id", "organization_id") REFERENCES "production_stock_postings"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "material_stock_ledger" ADD CONSTRAINT "material_stock_ledger_usage_fkey" FOREIGN KEY ("usage_event_id") REFERENCES "production_material_usage"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "material_stock_ledger" ADD CONSTRAINT "material_stock_ledger_source" CHECK (
("kind" = 'RECEIPT_ACCEPTED' AND "delta" > 0 AND "posting_id" IS NOT NULL AND "receipt_line_id" IS NOT NULL AND "production_posting_id" IS NULL AND "usage_event_id" IS NULL)
OR ("kind" IN ('PRODUCTION_CONSUMED', 'PRODUCTION_WASTED') AND "delta" < 0 AND "posting_id" IS NULL AND "receipt_line_id" IS NULL AND "production_posting_id" IS NOT NULL AND "usage_event_id" IS NOT NULL)
);
CREATE FUNCTION guard_production_stock_posting() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Production stock postings are immutable'; END IF;
IF NOT EXISTS (
SELECT 1 FROM production_batches b WHERE b.id = NEW.batch_id
AND b.organization_id = NEW.organization_id AND b.status = 'COMPLETED'
) THEN RAISE EXCEPTION 'Production batch must be completed before stock posting'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER production_stock_postings_guard BEFORE INSERT OR UPDATE OR DELETE ON production_stock_postings FOR EACH ROW EXECUTE FUNCTION guard_production_stock_posting();
CREATE OR REPLACE FUNCTION guard_material_stock_ledger() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Material stock ledger is immutable'; END IF;
IF NEW.kind = 'RECEIPT_ACCEPTED' THEN
IF NOT EXISTS (
SELECT 1 FROM material_receipt_postings p
JOIN goods_receipt_lines l ON l.receipt_id = p.receipt_id AND l.id = NEW.receipt_line_id AND l.organization_id = NEW.organization_id
JOIN purchase_order_lines ol ON ol.id = l.purchase_order_line_id AND ol.organization_id = NEW.organization_id
JOIN receipt_inspections i ON i.receipt_line_id = l.id AND i.organization_id = NEW.organization_id
JOIN material_stock_items s ON s.id = NEW.stock_item_id AND s.organization_id = NEW.organization_id
WHERE p.id = NEW.posting_id AND p.organization_id = NEW.organization_id
AND s.warehouse_id = p.warehouse_id AND s.material_id = ol.material_id
AND NEW.material_id = ol.material_id AND NEW.delta = i.accepted_quantity
) THEN RAISE EXCEPTION 'Material receipt stock entry does not match accepted QC'; END IF;
ELSE
IF NOT EXISTS (
SELECT 1 FROM production_stock_postings p
JOIN production_material_usage u ON u.batch_id = p.batch_id AND u.id = NEW.usage_event_id AND u.organization_id = NEW.organization_id
JOIN product_bom_lines bl ON bl.id = u.bom_line_id AND bl.bom_id = u.bom_id AND bl.organization_id = NEW.organization_id
JOIN material_stock_items s ON s.id = NEW.stock_item_id AND s.organization_id = NEW.organization_id
WHERE p.id = NEW.production_posting_id AND p.organization_id = NEW.organization_id
AND s.warehouse_id = p.warehouse_id AND s.material_id = bl.material_id
AND NEW.material_id = bl.material_id AND NEW.delta = -u.quantity
AND ((NEW.kind = 'PRODUCTION_CONSUMED' AND u.kind = 'CONSUMED') OR (NEW.kind = 'PRODUCTION_WASTED' AND u.kind = 'WASTED'))
) THEN RAISE EXCEPTION 'Production stock entry does not match material usage'; END IF;
END IF;
UPDATE material_stock_items SET on_hand = on_hand + NEW.delta
WHERE id = NEW.stock_item_id AND organization_id = NEW.organization_id
AND on_hand + NEW.delta BETWEEN 0 AND 999999999.999;
IF NOT FOUND THEN RAISE EXCEPTION 'Material stock balance outside bounds'; END IF;
RETURN NEW;
END;
$$;

View File

@ -0,0 +1,93 @@
ALTER TABLE "material_stock_ledger" DROP CONSTRAINT "material_stock_ledger_source";
ALTER TYPE "MaterialStockKind" RENAME TO "MaterialStockKind_old";
CREATE TYPE "MaterialStockKind" AS ENUM ('RECEIPT_ACCEPTED', 'PRODUCTION_CONSUMED', 'PRODUCTION_WASTED', 'PACKAGING_USED', 'PACKAGING_WASTED');
ALTER TABLE "material_stock_ledger" ALTER COLUMN "kind" TYPE "MaterialStockKind" USING "kind"::text::"MaterialStockKind";
DROP TYPE "MaterialStockKind_old";
CREATE TABLE "packaging_stock_postings" (
"id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"run_id" UUID NOT NULL,
"warehouse_id" UUID NOT NULL,
"posted_by_id" UUID NOT NULL,
"idempotency_key" UUID NOT NULL,
"request_hash" CHAR(64) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "packaging_stock_postings_pkey" PRIMARY KEY ("id"),
CONSTRAINT "packaging_stock_postings_hash" CHECK ("request_hash" ~ '^[a-f0-9]{64}$')
);
CREATE UNIQUE INDEX "packaging_runs_id_organization_id_key" ON "packaging_runs"("id", "organization_id");
CREATE UNIQUE INDEX "packaging_stock_postings_run_id_key" ON "packaging_stock_postings"("run_id");
CREATE UNIQUE INDEX "packaging_stock_postings_run_id_organization_id_key" ON "packaging_stock_postings"("run_id", "organization_id");
CREATE UNIQUE INDEX "packaging_stock_postings_organization_id_idempotency_key_key" ON "packaging_stock_postings"("organization_id", "idempotency_key");
CREATE UNIQUE INDEX "packaging_stock_postings_id_organization_id_key" ON "packaging_stock_postings"("id", "organization_id");
ALTER TABLE "packaging_stock_postings" ADD CONSTRAINT "packaging_stock_postings_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "packaging_stock_postings" ADD CONSTRAINT "packaging_stock_postings_run_id_organization_id_fkey" FOREIGN KEY ("run_id", "organization_id") REFERENCES "packaging_runs"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "packaging_stock_postings" ADD CONSTRAINT "packaging_stock_postings_warehouse_id_organization_id_fkey" FOREIGN KEY ("warehouse_id", "organization_id") REFERENCES "warehouses"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "packaging_stock_postings" ADD CONSTRAINT "packaging_stock_postings_posted_by_id_organization_id_fkey" FOREIGN KEY ("posted_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "material_stock_ledger" ADD COLUMN "packaging_posting_id" UUID;
ALTER TABLE "material_stock_ledger" ADD COLUMN "packaging_run_line_id" UUID;
CREATE UNIQUE INDEX "material_stock_ledger_packaging_run_line_id_kind_key" ON "material_stock_ledger"("packaging_run_line_id", "kind");
ALTER TABLE "material_stock_ledger" ADD CONSTRAINT "material_stock_ledger_packaging_scope_fkey" FOREIGN KEY ("packaging_posting_id", "organization_id") REFERENCES "packaging_stock_postings"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "material_stock_ledger" ADD CONSTRAINT "material_stock_ledger_packaging_line_fkey" FOREIGN KEY ("packaging_run_line_id") REFERENCES "packaging_run_lines"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "material_stock_ledger" ADD CONSTRAINT "material_stock_ledger_source" CHECK (
("kind" = 'RECEIPT_ACCEPTED' AND "delta" > 0 AND "posting_id" IS NOT NULL AND "receipt_line_id" IS NOT NULL AND "production_posting_id" IS NULL AND "usage_event_id" IS NULL AND "packaging_posting_id" IS NULL AND "packaging_run_line_id" IS NULL)
OR ("kind" IN ('PRODUCTION_CONSUMED', 'PRODUCTION_WASTED') AND "delta" < 0 AND "posting_id" IS NULL AND "receipt_line_id" IS NULL AND "production_posting_id" IS NOT NULL AND "usage_event_id" IS NOT NULL AND "packaging_posting_id" IS NULL AND "packaging_run_line_id" IS NULL)
OR ("kind" IN ('PACKAGING_USED', 'PACKAGING_WASTED') AND "delta" < 0 AND "posting_id" IS NULL AND "receipt_line_id" IS NULL AND "production_posting_id" IS NULL AND "usage_event_id" IS NULL AND "packaging_posting_id" IS NOT NULL AND "packaging_run_line_id" IS NOT NULL)
);
CREATE FUNCTION guard_packaging_stock_posting() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Packaging stock postings are immutable'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER packaging_stock_postings_guard BEFORE INSERT OR UPDATE OR DELETE ON packaging_stock_postings FOR EACH ROW EXECUTE FUNCTION guard_packaging_stock_posting();
CREATE OR REPLACE FUNCTION guard_material_stock_ledger() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Material stock ledger is immutable'; END IF;
IF NEW.kind = 'RECEIPT_ACCEPTED' THEN
IF NOT EXISTS (
SELECT 1 FROM material_receipt_postings p
JOIN goods_receipt_lines l ON l.receipt_id = p.receipt_id AND l.id = NEW.receipt_line_id AND l.organization_id = NEW.organization_id
JOIN purchase_order_lines ol ON ol.id = l.purchase_order_line_id AND ol.organization_id = NEW.organization_id
JOIN receipt_inspections i ON i.receipt_line_id = l.id AND i.organization_id = NEW.organization_id
JOIN material_stock_items s ON s.id = NEW.stock_item_id AND s.organization_id = NEW.organization_id
WHERE p.id = NEW.posting_id AND p.organization_id = NEW.organization_id
AND s.warehouse_id = p.warehouse_id AND s.material_id = ol.material_id
AND NEW.material_id = ol.material_id AND NEW.delta = i.accepted_quantity
) THEN RAISE EXCEPTION 'Material receipt stock entry does not match accepted QC'; END IF;
ELSIF NEW.kind IN ('PRODUCTION_CONSUMED', 'PRODUCTION_WASTED') THEN
IF NOT EXISTS (
SELECT 1 FROM production_stock_postings p
JOIN production_material_usage u ON u.batch_id = p.batch_id AND u.id = NEW.usage_event_id AND u.organization_id = NEW.organization_id
JOIN product_bom_lines bl ON bl.id = u.bom_line_id AND bl.bom_id = u.bom_id AND bl.organization_id = NEW.organization_id
JOIN material_stock_items s ON s.id = NEW.stock_item_id AND s.organization_id = NEW.organization_id
WHERE p.id = NEW.production_posting_id AND p.organization_id = NEW.organization_id
AND s.warehouse_id = p.warehouse_id AND s.material_id = bl.material_id
AND NEW.material_id = bl.material_id AND NEW.delta = -u.quantity
AND ((NEW.kind = 'PRODUCTION_CONSUMED' AND u.kind = 'CONSUMED') OR (NEW.kind = 'PRODUCTION_WASTED' AND u.kind = 'WASTED'))
) THEN RAISE EXCEPTION 'Production stock entry does not match material usage'; END IF;
ELSE
IF NOT EXISTS (
SELECT 1 FROM packaging_stock_postings p
JOIN packaging_runs r ON r.id = p.run_id AND r.organization_id = NEW.organization_id
JOIN packaging_run_lines l ON l.run_id = r.id AND l.id = NEW.packaging_run_line_id AND l.organization_id = NEW.organization_id
JOIN product_bom_lines bl ON bl.id = l.bom_line_id AND bl.bom_id = l.bom_id AND bl.organization_id = NEW.organization_id
JOIN material_stock_items s ON s.id = NEW.stock_item_id AND s.organization_id = NEW.organization_id
WHERE p.id = NEW.packaging_posting_id AND p.organization_id = NEW.organization_id
AND s.warehouse_id = p.warehouse_id AND s.material_id = bl.material_id
AND NEW.material_id = bl.material_id
AND ((NEW.kind = 'PACKAGING_USED' AND NEW.delta = -l.used_quantity AND l.used_quantity > 0)
OR (NEW.kind = 'PACKAGING_WASTED' AND NEW.delta = -l.wasted_quantity AND l.wasted_quantity > 0))
) THEN RAISE EXCEPTION 'Packaging stock entry does not match recorded use'; END IF;
END IF;
UPDATE material_stock_items SET on_hand = on_hand + NEW.delta
WHERE id = NEW.stock_item_id AND organization_id = NEW.organization_id
AND on_hand + NEW.delta BETWEEN 0 AND 999999999.999;
IF NOT FOUND THEN RAISE EXCEPTION 'Material stock balance outside bounds'; END IF;
RETURN NEW;
END;
$$;

View File

@ -0,0 +1,68 @@
CREATE TABLE "finished_goods_receipts" (
"id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"batch_id" UUID NOT NULL,
"warehouse_id" UUID NOT NULL,
"stock_item_id" UUID NOT NULL,
"posted_by_id" UUID NOT NULL,
"quantity" INTEGER NOT NULL,
"idempotency_key" UUID NOT NULL,
"request_hash" CHAR(64) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "finished_goods_receipts_pkey" PRIMARY KEY ("id"),
CONSTRAINT "finished_goods_receipts_quantity" CHECK ("quantity" BETWEEN 1 AND 2000000000),
CONSTRAINT "finished_goods_receipts_hash" CHECK ("request_hash" ~ '^[a-f0-9]{64}$')
);
CREATE UNIQUE INDEX "finished_goods_receipts_batch_id_key" ON "finished_goods_receipts"("batch_id");
CREATE UNIQUE INDEX "finished_goods_receipts_batch_id_organization_id_key" ON "finished_goods_receipts"("batch_id", "organization_id");
CREATE UNIQUE INDEX "finished_goods_receipts_organization_id_idempotency_key_key" ON "finished_goods_receipts"("organization_id", "idempotency_key");
CREATE UNIQUE INDEX "finished_goods_receipts_id_organization_id_key" ON "finished_goods_receipts"("id", "organization_id");
ALTER TABLE "finished_goods_receipts" ADD CONSTRAINT "finished_goods_receipts_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "finished_goods_receipts" ADD CONSTRAINT "finished_goods_receipts_batch_id_organization_id_fkey" FOREIGN KEY ("batch_id", "organization_id") REFERENCES "production_batches"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "finished_goods_receipts" ADD CONSTRAINT "finished_goods_receipts_warehouse_id_organization_id_fkey" FOREIGN KEY ("warehouse_id", "organization_id") REFERENCES "warehouses"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "finished_goods_receipts" ADD CONSTRAINT "finished_goods_receipts_stock_item_id_organization_id_fkey" FOREIGN KEY ("stock_item_id", "organization_id") REFERENCES "stock_items"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "finished_goods_receipts" ADD CONSTRAINT "finished_goods_receipts_posted_by_id_organization_id_fkey" FOREIGN KEY ("posted_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "stock_ledger" ADD COLUMN "finished_goods_receipt_id" UUID;
CREATE UNIQUE INDEX "stock_ledger_finished_goods_receipt_id_key" ON "stock_ledger"("finished_goods_receipt_id");
CREATE UNIQUE INDEX "stock_ledger_finished_goods_receipt_id_organization_id_key" ON "stock_ledger"("finished_goods_receipt_id", "organization_id");
ALTER TABLE "stock_ledger" ADD CONSTRAINT "stock_ledger_finished_goods_scope_fkey" FOREIGN KEY ("finished_goods_receipt_id", "organization_id") REFERENCES "finished_goods_receipts"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE FUNCTION guard_finished_goods_receipt() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Finished-goods receipts are immutable'; END IF;
IF NOT EXISTS (
SELECT 1 FROM production_batches b
JOIN production_batch_completions c ON c.batch_id = b.id AND c.organization_id = NEW.organization_id
JOIN product_boms bom ON bom.id = b.bom_id AND bom.organization_id = NEW.organization_id
JOIN packaging_runs r ON r.batch_id = b.id AND r.organization_id = NEW.organization_id
JOIN production_stock_postings ps ON ps.batch_id = b.id AND ps.organization_id = NEW.organization_id
JOIN packaging_stock_postings ks ON ks.run_id = r.id AND ks.organization_id = NEW.organization_id
JOIN stock_items s ON s.id = NEW.stock_item_id AND s.organization_id = NEW.organization_id
WHERE b.id = NEW.batch_id AND b.organization_id = NEW.organization_id
AND b.status = 'COMPLETED' AND c.good_quantity = NEW.quantity
AND s.variant_id = bom.variant_id AND s.warehouse_id = NEW.warehouse_id
) THEN RAISE EXCEPTION 'Finished-goods receipt requires completed and stock-posted production and packaging'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER finished_goods_receipts_guard BEFORE INSERT OR UPDATE OR DELETE ON finished_goods_receipts FOR EACH ROW EXECUTE FUNCTION guard_finished_goods_receipt();
CREATE FUNCTION post_finished_goods_ledger() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF NEW.finished_goods_receipt_id IS NULL THEN RETURN NEW; END IF;
IF NOT EXISTS (
SELECT 1 FROM finished_goods_receipts r
WHERE r.id = NEW.finished_goods_receipt_id AND r.organization_id = NEW.organization_id
AND r.stock_item_id = NEW.stock_item_id AND r.posted_by_id = NEW.actor_id
AND r.quantity = NEW.delta AND r.idempotency_key = NEW.idempotency_key
AND r.request_hash = NEW.request_hash AND NEW.reason = 'PRODUCTION_OUTPUT'
) THEN RAISE EXCEPTION 'Finished-goods stock entry does not match its receipt'; END IF;
UPDATE stock_items SET on_hand = on_hand + NEW.delta
WHERE id = NEW.stock_item_id AND organization_id = NEW.organization_id
AND on_hand <= 2000000000 - NEW.delta;
IF NOT FOUND THEN RAISE EXCEPTION 'Finished-goods stock capacity exceeded'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER stock_ledger_finished_goods_post BEFORE INSERT ON stock_ledger FOR EACH ROW EXECUTE FUNCTION post_finished_goods_ledger();

View File

@ -0,0 +1,84 @@
ALTER TABLE "material_stock_ledger" DROP CONSTRAINT "material_stock_ledger_source";
ALTER TYPE "MaterialStockKind" RENAME TO "MaterialStockKind_old";
CREATE TYPE "MaterialStockKind" AS ENUM ('RECEIPT_ACCEPTED', 'PRODUCTION_CONSUMED', 'PRODUCTION_WASTED', 'PACKAGING_USED', 'PACKAGING_WASTED', 'TRANSFER_OUT', 'TRANSFER_IN');
ALTER TABLE "material_stock_ledger" ALTER COLUMN "kind" TYPE "MaterialStockKind" USING "kind"::text::"MaterialStockKind";
DROP TYPE "MaterialStockKind_old";
CREATE TABLE "material_stock_transfers" (
"id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"material_id" UUID NOT NULL,
"from_warehouse_id" UUID NOT NULL,
"to_warehouse_id" UUID NOT NULL,
"from_stock_item_id" UUID NOT NULL,
"to_stock_item_id" UUID NOT NULL,
"posted_by_id" UUID NOT NULL,
"quantity" DECIMAL(12,3) NOT NULL,
"idempotency_key" UUID NOT NULL,
"request_hash" CHAR(64) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "material_stock_transfers_pkey" PRIMARY KEY ("id"),
CONSTRAINT "material_stock_transfers_quantity" CHECK ("quantity" BETWEEN 0.001 AND 999999999.999),
CONSTRAINT "material_stock_transfers_different_warehouses" CHECK ("from_warehouse_id" <> "to_warehouse_id" AND "from_stock_item_id" <> "to_stock_item_id"),
CONSTRAINT "material_stock_transfers_hash" CHECK ("request_hash" ~ '^[a-f0-9]{64}$')
);
CREATE UNIQUE INDEX "material_stock_transfers_organization_id_idempotency_key_key" ON "material_stock_transfers"("organization_id", "idempotency_key");
CREATE UNIQUE INDEX "material_stock_transfers_id_organization_id_key" ON "material_stock_transfers"("id", "organization_id");
CREATE INDEX "material_stock_transfers_scope_idx" ON "material_stock_transfers"("organization_id", "material_id", "created_at", "id");
ALTER TABLE "material_stock_transfers" ADD CONSTRAINT "material_stock_transfers_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "material_stock_transfers" ADD CONSTRAINT "material_stock_transfers_material_id_organization_id_fkey" FOREIGN KEY ("material_id", "organization_id") REFERENCES "materials"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "material_stock_transfers" ADD CONSTRAINT "material_stock_transfers_from_warehouse_id_organization_id_fkey" FOREIGN KEY ("from_warehouse_id", "organization_id") REFERENCES "warehouses"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "material_stock_transfers" ADD CONSTRAINT "material_stock_transfers_to_warehouse_id_organization_id_fkey" FOREIGN KEY ("to_warehouse_id", "organization_id") REFERENCES "warehouses"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "material_stock_transfers" ADD CONSTRAINT "material_stock_transfers_from_stock_scope_fkey" FOREIGN KEY ("from_stock_item_id", "material_id", "organization_id") REFERENCES "material_stock_items"("id", "material_id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "material_stock_transfers" ADD CONSTRAINT "material_stock_transfers_to_stock_scope_fkey" FOREIGN KEY ("to_stock_item_id", "material_id", "organization_id") REFERENCES "material_stock_items"("id", "material_id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "material_stock_transfers" ADD CONSTRAINT "material_stock_transfers_posted_by_id_organization_id_fkey" FOREIGN KEY ("posted_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "material_stock_ledger" ADD COLUMN "transfer_id" UUID;
CREATE UNIQUE INDEX "material_stock_ledger_transfer_id_kind_key" ON "material_stock_ledger"("transfer_id", "kind");
ALTER TABLE "material_stock_ledger" ADD CONSTRAINT "material_stock_ledger_transfer_scope_fkey" FOREIGN KEY ("transfer_id", "organization_id") REFERENCES "material_stock_transfers"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "material_stock_ledger" ADD CONSTRAINT "material_stock_ledger_source" CHECK (
("kind" = 'RECEIPT_ACCEPTED' AND "delta" > 0 AND "posting_id" IS NOT NULL AND "receipt_line_id" IS NOT NULL AND "production_posting_id" IS NULL AND "usage_event_id" IS NULL AND "packaging_posting_id" IS NULL AND "packaging_run_line_id" IS NULL AND "transfer_id" IS NULL)
OR ("kind" IN ('PRODUCTION_CONSUMED', 'PRODUCTION_WASTED') AND "delta" < 0 AND "posting_id" IS NULL AND "receipt_line_id" IS NULL AND "production_posting_id" IS NOT NULL AND "usage_event_id" IS NOT NULL AND "packaging_posting_id" IS NULL AND "packaging_run_line_id" IS NULL AND "transfer_id" IS NULL)
OR ("kind" IN ('PACKAGING_USED', 'PACKAGING_WASTED') AND "delta" < 0 AND "posting_id" IS NULL AND "receipt_line_id" IS NULL AND "production_posting_id" IS NULL AND "usage_event_id" IS NULL AND "packaging_posting_id" IS NOT NULL AND "packaging_run_line_id" IS NOT NULL AND "transfer_id" IS NULL)
OR ("kind" IN ('TRANSFER_OUT', 'TRANSFER_IN') AND "delta" <> 0 AND "posting_id" IS NULL AND "receipt_line_id" IS NULL AND "production_posting_id" IS NULL AND "usage_event_id" IS NULL AND "packaging_posting_id" IS NULL AND "packaging_run_line_id" IS NULL AND "transfer_id" IS NOT NULL)
);
CREATE FUNCTION guard_material_stock_transfer() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Material stock transfers are immutable'; END IF;
IF NOT EXISTS (
SELECT 1 FROM material_stock_items src
JOIN material_stock_items dst ON dst.id = NEW.to_stock_item_id AND dst.organization_id = NEW.organization_id
WHERE src.id = NEW.from_stock_item_id AND src.organization_id = NEW.organization_id
AND src.material_id = NEW.material_id AND dst.material_id = NEW.material_id
AND src.warehouse_id = NEW.from_warehouse_id AND dst.warehouse_id = NEW.to_warehouse_id
) THEN RAISE EXCEPTION 'Material transfer stock items do not match the selected warehouses'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER material_stock_transfers_guard BEFORE INSERT OR UPDATE OR DELETE ON material_stock_transfers FOR EACH ROW EXECUTE FUNCTION guard_material_stock_transfer();
CREATE FUNCTION guard_material_transfer_ledger() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM material_stock_transfers t
WHERE t.id = NEW.transfer_id AND t.organization_id = NEW.organization_id
AND t.material_id = NEW.material_id
AND ((NEW.kind = 'TRANSFER_OUT' AND NEW.stock_item_id = t.from_stock_item_id AND NEW.delta = -t.quantity)
OR (NEW.kind = 'TRANSFER_IN' AND NEW.stock_item_id = t.to_stock_item_id AND NEW.delta = t.quantity))
) THEN RAISE EXCEPTION 'Material transfer stock entry does not match its transfer'; END IF;
UPDATE material_stock_items SET on_hand = on_hand + NEW.delta
WHERE id = NEW.stock_item_id AND organization_id = NEW.organization_id
AND on_hand + NEW.delta BETWEEN 0 AND 999999999.999;
IF NOT FOUND THEN RAISE EXCEPTION 'Material transfer stock balance outside bounds'; END IF;
RETURN NEW;
END;
$$;
DROP TRIGGER material_stock_ledger_guard ON material_stock_ledger;
CREATE TRIGGER material_stock_ledger_existing_insert BEFORE INSERT ON material_stock_ledger FOR EACH ROW
WHEN (NEW.kind IN ('RECEIPT_ACCEPTED', 'PRODUCTION_CONSUMED', 'PRODUCTION_WASTED', 'PACKAGING_USED', 'PACKAGING_WASTED'))
EXECUTE FUNCTION guard_material_stock_ledger();
CREATE TRIGGER material_stock_ledger_transfer_insert BEFORE INSERT ON material_stock_ledger FOR EACH ROW
WHEN (NEW.kind IN ('TRANSFER_OUT', 'TRANSFER_IN')) EXECUTE FUNCTION guard_material_transfer_ledger();
CREATE TRIGGER material_stock_ledger_immutable BEFORE UPDATE OR DELETE ON material_stock_ledger FOR EACH ROW
EXECUTE FUNCTION guard_material_stock_ledger();

View File

@ -0,0 +1,83 @@
DROP TRIGGER material_stock_ledger_existing_insert ON material_stock_ledger;
DROP TRIGGER material_stock_ledger_transfer_insert ON material_stock_ledger;
ALTER TABLE "material_stock_ledger" DROP CONSTRAINT "material_stock_ledger_source";
ALTER TYPE "MaterialStockKind" RENAME TO "MaterialStockKind_old";
CREATE TYPE "MaterialStockKind" AS ENUM ('RECEIPT_ACCEPTED', 'PRODUCTION_CONSUMED', 'PRODUCTION_WASTED', 'PACKAGING_USED', 'PACKAGING_WASTED', 'TRANSFER_OUT', 'TRANSFER_IN', 'ADJUSTMENT_IN', 'ADJUSTMENT_OUT');
ALTER TABLE "material_stock_ledger" ALTER COLUMN "kind" TYPE "MaterialStockKind" USING "kind"::text::"MaterialStockKind";
DROP TYPE "MaterialStockKind_old";
CREATE TABLE "material_stock_adjustments" (
"id" UUID NOT NULL,
"organization_id" UUID NOT NULL,
"material_id" UUID NOT NULL,
"warehouse_id" UUID NOT NULL,
"stock_item_id" UUID NOT NULL,
"adjusted_by_id" UUID NOT NULL,
"delta" DECIMAL(12,3) NOT NULL,
"reason" VARCHAR(200) NOT NULL,
"idempotency_key" UUID NOT NULL,
"request_hash" CHAR(64) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "material_stock_adjustments_pkey" PRIMARY KEY ("id"),
CONSTRAINT "material_stock_adjustments_delta" CHECK ("delta" <> 0 AND "delta" BETWEEN -999999999.999 AND 999999999.999),
CONSTRAINT "material_stock_adjustments_reason" CHECK (char_length(btrim("reason")) BETWEEN 3 AND 200),
CONSTRAINT "material_stock_adjustments_hash" CHECK ("request_hash" ~ '^[a-f0-9]{64}$')
);
CREATE UNIQUE INDEX "material_stock_adjustments_organization_id_idempotency_key_key" ON "material_stock_adjustments"("organization_id", "idempotency_key");
CREATE UNIQUE INDEX "material_stock_adjustments_id_organization_id_key" ON "material_stock_adjustments"("id", "organization_id");
CREATE INDEX "material_stock_adjustments_scope_idx" ON "material_stock_adjustments"("organization_id", "material_id", "created_at", "id");
ALTER TABLE "material_stock_adjustments" ADD CONSTRAINT "material_stock_adjustments_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "material_stock_adjustments" ADD CONSTRAINT "material_stock_adjustments_material_id_organization_id_fkey" FOREIGN KEY ("material_id", "organization_id") REFERENCES "materials"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "material_stock_adjustments" ADD CONSTRAINT "material_stock_adjustments_warehouse_id_organization_id_fkey" FOREIGN KEY ("warehouse_id", "organization_id") REFERENCES "warehouses"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "material_stock_adjustments" ADD CONSTRAINT "material_stock_adjustments_item_scope_fkey" FOREIGN KEY ("stock_item_id", "material_id", "organization_id") REFERENCES "material_stock_items"("id", "material_id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "material_stock_adjustments" ADD CONSTRAINT "material_stock_adjustments_adjusted_by_id_organization_id_fkey" FOREIGN KEY ("adjusted_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "material_stock_ledger" ADD COLUMN "adjustment_id" UUID;
CREATE UNIQUE INDEX "material_stock_ledger_adjustment_id_key" ON "material_stock_ledger"("adjustment_id");
CREATE UNIQUE INDEX "material_stock_ledger_adjustment_id_organization_id_key" ON "material_stock_ledger"("adjustment_id", "organization_id");
ALTER TABLE "material_stock_ledger" ADD CONSTRAINT "material_stock_ledger_adjustment_scope_fkey" FOREIGN KEY ("adjustment_id", "organization_id") REFERENCES "material_stock_adjustments"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "material_stock_ledger" ADD CONSTRAINT "material_stock_ledger_source" CHECK (
("kind" = 'RECEIPT_ACCEPTED' AND "delta" > 0 AND "posting_id" IS NOT NULL AND "receipt_line_id" IS NOT NULL AND "production_posting_id" IS NULL AND "usage_event_id" IS NULL AND "packaging_posting_id" IS NULL AND "packaging_run_line_id" IS NULL AND "transfer_id" IS NULL AND "adjustment_id" IS NULL)
OR ("kind" IN ('PRODUCTION_CONSUMED', 'PRODUCTION_WASTED') AND "delta" < 0 AND "posting_id" IS NULL AND "receipt_line_id" IS NULL AND "production_posting_id" IS NOT NULL AND "usage_event_id" IS NOT NULL AND "packaging_posting_id" IS NULL AND "packaging_run_line_id" IS NULL AND "transfer_id" IS NULL AND "adjustment_id" IS NULL)
OR ("kind" IN ('PACKAGING_USED', 'PACKAGING_WASTED') AND "delta" < 0 AND "posting_id" IS NULL AND "receipt_line_id" IS NULL AND "production_posting_id" IS NULL AND "usage_event_id" IS NULL AND "packaging_posting_id" IS NOT NULL AND "packaging_run_line_id" IS NOT NULL AND "transfer_id" IS NULL AND "adjustment_id" IS NULL)
OR ("kind" IN ('TRANSFER_OUT', 'TRANSFER_IN') AND "delta" <> 0 AND "posting_id" IS NULL AND "receipt_line_id" IS NULL AND "production_posting_id" IS NULL AND "usage_event_id" IS NULL AND "packaging_posting_id" IS NULL AND "packaging_run_line_id" IS NULL AND "transfer_id" IS NOT NULL AND "adjustment_id" IS NULL)
OR ("kind" IN ('ADJUSTMENT_IN', 'ADJUSTMENT_OUT') AND "delta" <> 0 AND "posting_id" IS NULL AND "receipt_line_id" IS NULL AND "production_posting_id" IS NULL AND "usage_event_id" IS NULL AND "packaging_posting_id" IS NULL AND "packaging_run_line_id" IS NULL AND "transfer_id" IS NULL AND "adjustment_id" IS NOT NULL)
);
CREATE FUNCTION guard_material_stock_adjustment() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Material stock adjustments are immutable'; END IF;
IF NOT EXISTS (
SELECT 1 FROM material_stock_items s
WHERE s.id = NEW.stock_item_id AND s.organization_id = NEW.organization_id
AND s.material_id = NEW.material_id AND s.warehouse_id = NEW.warehouse_id
) THEN RAISE EXCEPTION 'Material adjustment stock item does not match the warehouse'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER material_stock_adjustments_guard BEFORE INSERT OR UPDATE OR DELETE ON material_stock_adjustments FOR EACH ROW EXECUTE FUNCTION guard_material_stock_adjustment();
CREATE FUNCTION guard_material_adjustment_ledger() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM material_stock_adjustments a
WHERE a.id = NEW.adjustment_id AND a.organization_id = NEW.organization_id
AND a.material_id = NEW.material_id AND a.stock_item_id = NEW.stock_item_id
AND a.delta = NEW.delta
AND ((NEW.kind = 'ADJUSTMENT_IN' AND a.delta > 0)
OR (NEW.kind = 'ADJUSTMENT_OUT' AND a.delta < 0))
) THEN RAISE EXCEPTION 'Material adjustment stock entry does not match its adjustment'; END IF;
UPDATE material_stock_items SET on_hand = on_hand + NEW.delta
WHERE id = NEW.stock_item_id AND organization_id = NEW.organization_id
AND on_hand + NEW.delta BETWEEN 0 AND 999999999.999;
IF NOT FOUND THEN RAISE EXCEPTION 'Material adjustment stock balance outside bounds'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER material_stock_ledger_existing_insert BEFORE INSERT ON material_stock_ledger FOR EACH ROW
WHEN (NEW.kind IN ('RECEIPT_ACCEPTED', 'PRODUCTION_CONSUMED', 'PRODUCTION_WASTED', 'PACKAGING_USED', 'PACKAGING_WASTED'))
EXECUTE FUNCTION guard_material_stock_ledger();
CREATE TRIGGER material_stock_ledger_transfer_insert BEFORE INSERT ON material_stock_ledger FOR EACH ROW
WHEN (NEW.kind IN ('TRANSFER_OUT', 'TRANSFER_IN')) EXECUTE FUNCTION guard_material_transfer_ledger();
CREATE TRIGGER material_stock_ledger_adjustment_insert BEFORE INSERT ON material_stock_ledger FOR EACH ROW
WHEN (NEW.kind IN ('ADJUSTMENT_IN', 'ADJUSTMENT_OUT')) EXECUTE FUNCTION guard_material_adjustment_ledger();

View File

@ -0,0 +1,82 @@
CREATE TYPE "BusinessVerificationKind" AS ENUM ('SUBMITTED', 'APPROVED', 'REJECTED');
CREATE TABLE "business_accounts" (
"id" UUID NOT NULL PRIMARY KEY, "organization_id" UUID NOT NULL, "created_by_id" UUID NOT NULL,
"code" VARCHAR(32) NOT NULL, "legal_name" VARCHAR(160) NOT NULL, "trading_name" VARCHAR(160),
"registration_number" VARCHAR(64) NOT NULL, "tax_identifier" VARCHAR(64), "country_code" CHAR(2) NOT NULL,
"contact_email" VARCHAR(254) NOT NULL, "contact_phone" VARCHAR(24), "billing_line1" VARCHAR(200) NOT NULL,
"billing_city" VARCHAR(100) NOT NULL, "billing_region" VARCHAR(100) NOT NULL,
"billing_postal_code" VARCHAR(20) NOT NULL, "profile_version" INTEGER NOT NULL DEFAULT 1,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, "updated_at" TIMESTAMPTZ(3) NOT NULL,
CONSTRAINT "business_accounts_profile_version" CHECK ("profile_version" > 0),
CONSTRAINT "business_accounts_code" CHECK ("code" ~ '^[A-Z0-9][A-Z0-9_-]*$'),
CONSTRAINT "business_accounts_country" CHECK ("country_code" ~ '^[A-Z]{2}$')
);
CREATE UNIQUE INDEX "business_accounts_organization_id_code_key" ON "business_accounts"("organization_id", "code");
CREATE UNIQUE INDEX "business_accounts_organization_id_country_code_registration_key" ON "business_accounts"("organization_id", "country_code", "registration_number");
CREATE UNIQUE INDEX "business_accounts_id_organization_id_key" ON "business_accounts"("id", "organization_id");
CREATE INDEX "business_accounts_organization_id_created_at_id_idx" ON "business_accounts"("organization_id", "created_at", "id");
ALTER TABLE "business_accounts" ADD CONSTRAINT "business_accounts_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "business_accounts" ADD CONSTRAINT "business_accounts_created_by_id_organization_id_fkey" FOREIGN KEY ("created_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE TABLE "business_verification_events" (
"id" UUID NOT NULL PRIMARY KEY, "organization_id" UUID NOT NULL, "account_id" UUID NOT NULL,
"actor_id" UUID NOT NULL, "sequence" INTEGER NOT NULL, "kind" "BusinessVerificationKind" NOT NULL,
"profile_snapshot" JSONB, "note" VARCHAR(500), "idempotency_key" UUID NOT NULL,
"request_hash" CHAR(64) NOT NULL, "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "business_verification_events_sequence" CHECK ("sequence" > 0),
CONSTRAINT "business_verification_events_hash" CHECK ("request_hash" ~ '^[a-f0-9]{64}$'),
CONSTRAINT "business_verification_events_shape" CHECK (
("kind" = 'SUBMITTED' AND "profile_snapshot" IS NOT NULL AND "note" IS NULL)
OR ("kind" IN ('APPROVED', 'REJECTED') AND "profile_snapshot" IS NULL AND char_length(btrim("note")) BETWEEN 3 AND 500)
)
);
CREATE UNIQUE INDEX "business_verification_events_account_id_sequence_key" ON "business_verification_events"("account_id", "sequence");
CREATE UNIQUE INDEX "business_verification_events_organization_id_idempotency_ke_key" ON "business_verification_events"("organization_id", "idempotency_key");
CREATE INDEX "business_verification_events_organization_id_account_id_seq_idx" ON "business_verification_events"("organization_id", "account_id", "sequence");
ALTER TABLE "business_verification_events" ADD CONSTRAINT "business_verification_events_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "business_verification_events" ADD CONSTRAINT "business_verification_events_account_id_organization_id_fkey" FOREIGN KEY ("account_id", "organization_id") REFERENCES "business_accounts"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "business_verification_events" ADD CONSTRAINT "business_verification_events_actor_id_organization_id_fkey" FOREIGN KEY ("actor_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE FUNCTION guard_business_account() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE latest "BusinessVerificationKind";
BEGIN
IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'Business accounts cannot be deleted'; END IF;
IF (NEW.id, NEW.organization_id, NEW.created_by_id, NEW.code, NEW.created_at)
IS DISTINCT FROM (OLD.id, OLD.organization_id, OLD.created_by_id, OLD.code, OLD.created_at)
THEN RAISE EXCEPTION 'Business account identity is immutable'; END IF;
SELECT kind INTO latest FROM business_verification_events WHERE account_id = OLD.id ORDER BY sequence DESC LIMIT 1;
IF latest IN ('SUBMITTED', 'APPROVED') THEN RAISE EXCEPTION 'Submitted or approved business profiles cannot be edited'; END IF;
IF NEW.profile_version <> OLD.profile_version + 1 THEN RAISE EXCEPTION 'Business profile version must advance by one'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER business_accounts_guard BEFORE UPDATE OR DELETE ON business_accounts FOR EACH ROW EXECUTE FUNCTION guard_business_account();
CREATE FUNCTION guard_business_verification_event() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE previous business_verification_events%ROWTYPE;
DECLARE account business_accounts%ROWTYPE;
BEGIN
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Business verification history is immutable'; END IF;
SELECT * INTO account FROM business_accounts WHERE id = NEW.account_id AND organization_id = NEW.organization_id;
SELECT * INTO previous FROM business_verification_events WHERE account_id = NEW.account_id ORDER BY sequence DESC LIMIT 1;
IF NEW.sequence <> COALESCE(previous.sequence, 0) + 1 THEN RAISE EXCEPTION 'Business verification sequence invalid'; END IF;
IF NEW.kind = 'SUBMITTED' THEN
IF previous.kind IS NOT NULL AND previous.kind <> 'REJECTED' THEN RAISE EXCEPTION 'Business verification submission state invalid'; END IF;
IF NEW.profile_snapshot IS DISTINCT FROM jsonb_build_object(
'legalName', account.legal_name, 'tradingName', account.trading_name,
'registrationNumber', account.registration_number, 'taxIdentifier', account.tax_identifier,
'countryCode', account.country_code, 'contactEmail', account.contact_email,
'contactPhone', account.contact_phone, 'billingLine1', account.billing_line1,
'billingCity', account.billing_city, 'billingRegion', account.billing_region,
'billingPostalCode', account.billing_postal_code, 'profileVersion', account.profile_version
) THEN RAISE EXCEPTION 'Business verification snapshot does not match current profile'; END IF;
ELSIF previous.kind IS DISTINCT FROM 'SUBMITTED' OR previous.actor_id = NEW.actor_id THEN
RAISE EXCEPTION 'Business verification decision state or reviewer invalid';
END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER business_verification_events_guard BEFORE INSERT OR UPDATE OR DELETE ON business_verification_events FOR EACH ROW EXECUTE FUNCTION guard_business_verification_event();
UPDATE "roles" SET "permissions" = ARRAY(SELECT DISTINCT unnest("permissions" || ARRAY['b2b.read', 'b2b.manage', 'b2b.verify']))
WHERE "is_system" = true AND "name" = 'Owner';

View File

@ -0,0 +1,99 @@
CREATE TYPE "B2bPriceListStatus" AS ENUM ('DRAFT', 'ACTIVE', 'ARCHIVED');
CREATE TABLE "b2b_price_lists" (
"id" UUID NOT NULL PRIMARY KEY,
"organization_id" UUID NOT NULL,
"account_id" UUID NOT NULL,
"created_by_id" UUID NOT NULL,
"name" VARCHAR(100) NOT NULL,
"currency" CHAR(3) NOT NULL,
"status" "B2bPriceListStatus" NOT NULL DEFAULT 'DRAFT',
"active_slot" BOOLEAN,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMPTZ(3) NOT NULL,
CONSTRAINT "b2b_price_lists_currency" CHECK ("currency" IN ('INR', 'USD', 'EUR', 'GBP')),
CONSTRAINT "b2b_price_lists_active_slot" CHECK (
("status" = 'ACTIVE' AND "active_slot" IS TRUE) OR
("status" <> 'ACTIVE' AND "active_slot" IS NULL)
)
);
CREATE UNIQUE INDEX "b2b_price_lists_id_organization_id_key" ON "b2b_price_lists"("id", "organization_id");
CREATE UNIQUE INDEX "b2b_price_lists_organization_id_account_id_currency_active__key" ON "b2b_price_lists"("organization_id", "account_id", "currency", "active_slot");
CREATE INDEX "b2b_price_lists_organization_id_account_id_status_created_a_idx" ON "b2b_price_lists"("organization_id", "account_id", "status", "created_at", "id");
ALTER TABLE "b2b_price_lists" ADD CONSTRAINT "b2b_price_lists_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "b2b_price_lists" ADD CONSTRAINT "b2b_price_lists_account_id_organization_id_fkey" FOREIGN KEY ("account_id", "organization_id") REFERENCES "business_accounts"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "b2b_price_lists" ADD CONSTRAINT "b2b_price_lists_created_by_id_organization_id_fkey" FOREIGN KEY ("created_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE TABLE "b2b_price_list_items" (
"id" UUID NOT NULL PRIMARY KEY,
"organization_id" UUID NOT NULL,
"price_list_id" UUID NOT NULL,
"variant_id" UUID NOT NULL,
"unit_price" DECIMAL(12,2) NOT NULL,
"min_quantity" INTEGER NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMPTZ(3) NOT NULL,
CONSTRAINT "b2b_price_list_items_price" CHECK ("unit_price" > 0),
CONSTRAINT "b2b_price_list_items_min_quantity" CHECK ("min_quantity" BETWEEN 1 AND 1000000)
);
CREATE UNIQUE INDEX "b2b_price_list_items_price_list_id_variant_id_key" ON "b2b_price_list_items"("price_list_id", "variant_id");
CREATE INDEX "b2b_price_list_items_organization_id_price_list_id_id_idx" ON "b2b_price_list_items"("organization_id", "price_list_id", "id");
ALTER TABLE "b2b_price_list_items" ADD CONSTRAINT "b2b_price_list_items_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "b2b_price_list_items" ADD CONSTRAINT "b2b_price_list_items_price_list_id_organization_id_fkey" FOREIGN KEY ("price_list_id", "organization_id") REFERENCES "b2b_price_lists"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "b2b_price_list_items" ADD CONSTRAINT "b2b_price_list_items_variant_id_organization_id_fkey" FOREIGN KEY ("variant_id", "organization_id") REFERENCES "product_variants"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE FUNCTION guard_b2b_price_list() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE verified BOOLEAN;
BEGIN
IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'B2B price lists cannot be deleted'; END IF;
IF TG_OP = 'INSERT' THEN RETURN NEW; END IF;
IF (NEW.id, NEW.organization_id, NEW.account_id, NEW.created_by_id, NEW.name, NEW.currency, NEW.created_at)
IS DISTINCT FROM (OLD.id, OLD.organization_id, OLD.account_id, OLD.created_by_id, OLD.name, OLD.currency, OLD.created_at)
THEN RAISE EXCEPTION 'B2B price list identity and terms are immutable'; END IF;
IF OLD.status = 'DRAFT' AND NEW.status = 'ACTIVE' THEN
SELECT kind = 'APPROVED' INTO verified FROM business_verification_events
WHERE account_id = NEW.account_id ORDER BY sequence DESC LIMIT 1;
IF COALESCE(verified, FALSE) IS FALSE THEN RAISE EXCEPTION 'Business account is not verified'; END IF;
IF NOT EXISTS (SELECT 1 FROM b2b_price_list_items WHERE price_list_id = NEW.id) THEN
RAISE EXCEPTION 'B2B price list has no items';
END IF;
IF EXISTS (
SELECT 1 FROM b2b_price_list_items i
JOIN product_variants v ON v.id = i.variant_id
JOIN products p ON p.id = v.product_id
WHERE i.price_list_id = NEW.id AND (NOT v.active OR p.status <> 'PUBLISHED' OR v.currency <> NEW.currency)
) THEN RAISE EXCEPTION 'B2B price list contains ineligible variants'; END IF;
ELSIF NOT (OLD.status = 'ACTIVE' AND NEW.status = 'ARCHIVED') THEN
RAISE EXCEPTION 'B2B price list transition invalid';
END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER b2b_price_lists_guard BEFORE UPDATE OR DELETE ON b2b_price_lists FOR EACH ROW EXECUTE FUNCTION guard_b2b_price_list();
CREATE FUNCTION guard_b2b_price_list_item() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE list_status "B2bPriceListStatus";
DECLARE list_currency CHAR(3);
BEGIN
IF TG_OP = 'DELETE' THEN
SELECT status INTO list_status FROM b2b_price_lists WHERE id = OLD.price_list_id;
IF list_status <> 'DRAFT' THEN RAISE EXCEPTION 'Active or archived price list items are immutable'; END IF;
RETURN OLD;
END IF;
SELECT status, currency INTO list_status, list_currency FROM b2b_price_lists WHERE id = NEW.price_list_id AND organization_id = NEW.organization_id;
IF list_status <> 'DRAFT' THEN RAISE EXCEPTION 'Active or archived price list items are immutable'; END IF;
IF TG_OP = 'UPDATE' AND (NEW.id, NEW.organization_id, NEW.price_list_id, NEW.variant_id, NEW.created_at)
IS DISTINCT FROM (OLD.id, OLD.organization_id, OLD.price_list_id, OLD.variant_id, OLD.created_at)
THEN RAISE EXCEPTION 'B2B price list item identity is immutable'; END IF;
IF NOT EXISTS (
SELECT 1 FROM product_variants v JOIN products p ON p.id = v.product_id
WHERE v.id = NEW.variant_id AND v.organization_id = NEW.organization_id
AND v.active AND p.status = 'PUBLISHED' AND v.currency = list_currency
) THEN RAISE EXCEPTION 'Variant is ineligible for B2B price list'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER b2b_price_list_items_guard BEFORE INSERT OR UPDATE OR DELETE ON b2b_price_list_items FOR EACH ROW EXECUTE FUNCTION guard_b2b_price_list_item();
UPDATE "roles" SET "permissions" = ARRAY(SELECT DISTINCT unnest("permissions" || ARRAY['b2b.price.read', 'b2b.price.manage']))
WHERE "is_system" = true AND "name" = 'Owner';

View File

@ -0,0 +1,141 @@
CREATE TYPE "B2bQuoteResponseKind" AS ENUM ('ACCEPTED', 'DECLINED', 'WITHDRAWN');
CREATE TABLE "b2b_quotes" (
"id" UUID NOT NULL PRIMARY KEY,
"organization_id" UUID NOT NULL,
"account_id" UUID NOT NULL,
"price_list_id" UUID NOT NULL,
"created_by_id" UUID NOT NULL,
"number" VARCHAR(24) NOT NULL,
"account_snapshot" JSONB NOT NULL,
"price_list_name" VARCHAR(100) NOT NULL,
"currency" CHAR(3) NOT NULL,
"merchandise_total" DECIMAL(18,2) NOT NULL,
"customer_reference" VARCHAR(100),
"expires_at" TIMESTAMPTZ(3) NOT NULL,
"idempotency_key" UUID NOT NULL,
"request_hash" CHAR(64) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "b2b_quotes_number_format" CHECK ("number" ~ '^BQ-[A-F0-9]{20}$'),
CONSTRAINT "b2b_quotes_total" CHECK ("merchandise_total" > 0),
CONSTRAINT "b2b_quotes_hash" CHECK ("request_hash" ~ '^[a-f0-9]{64}$')
);
CREATE UNIQUE INDEX "b2b_quotes_id_organization_id_key" ON "b2b_quotes"("id", "organization_id");
CREATE UNIQUE INDEX "b2b_quotes_organization_id_number_key" ON "b2b_quotes"("organization_id", "number");
CREATE UNIQUE INDEX "b2b_quotes_organization_id_idempotency_key_key" ON "b2b_quotes"("organization_id", "idempotency_key");
CREATE INDEX "b2b_quotes_organization_id_account_id_created_at_id_idx" ON "b2b_quotes"("organization_id", "account_id", "created_at", "id");
ALTER TABLE "b2b_quotes" ADD CONSTRAINT "b2b_quotes_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "b2b_quotes" ADD CONSTRAINT "b2b_quotes_account_id_organization_id_fkey" FOREIGN KEY ("account_id", "organization_id") REFERENCES "business_accounts"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "b2b_quotes" ADD CONSTRAINT "b2b_quotes_price_list_id_organization_id_fkey" FOREIGN KEY ("price_list_id", "organization_id") REFERENCES "b2b_price_lists"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "b2b_quotes" ADD CONSTRAINT "b2b_quotes_created_by_id_organization_id_fkey" FOREIGN KEY ("created_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE TABLE "b2b_quote_lines" (
"id" UUID NOT NULL PRIMARY KEY,
"organization_id" UUID NOT NULL,
"quote_id" UUID NOT NULL,
"variant_id" UUID NOT NULL,
"sku" VARCHAR(64) NOT NULL,
"name" VARCHAR(160) NOT NULL,
"quantity" INTEGER NOT NULL,
"min_quantity" INTEGER NOT NULL,
"unit_price" DECIMAL(12,2) NOT NULL,
"line_total" DECIMAL(18,2) NOT NULL,
CONSTRAINT "b2b_quote_lines_quantity" CHECK ("quantity" BETWEEN 1 AND 1000000 AND "quantity" >= "min_quantity"),
CONSTRAINT "b2b_quote_lines_money" CHECK ("unit_price" > 0 AND "line_total" = "unit_price" * "quantity")
);
CREATE UNIQUE INDEX "b2b_quote_lines_quote_id_variant_id_key" ON "b2b_quote_lines"("quote_id", "variant_id");
CREATE INDEX "b2b_quote_lines_organization_id_quote_id_id_idx" ON "b2b_quote_lines"("organization_id", "quote_id", "id");
ALTER TABLE "b2b_quote_lines" ADD CONSTRAINT "b2b_quote_lines_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "b2b_quote_lines" ADD CONSTRAINT "b2b_quote_lines_quote_id_organization_id_fkey" FOREIGN KEY ("quote_id", "organization_id") REFERENCES "b2b_quotes"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "b2b_quote_lines" ADD CONSTRAINT "b2b_quote_lines_variant_id_organization_id_fkey" FOREIGN KEY ("variant_id", "organization_id") REFERENCES "product_variants"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE TABLE "b2b_quote_responses" (
"id" UUID NOT NULL PRIMARY KEY,
"organization_id" UUID NOT NULL,
"quote_id" UUID NOT NULL,
"actor_id" UUID NOT NULL,
"kind" "B2bQuoteResponseKind" NOT NULL,
"note" VARCHAR(500) NOT NULL,
"idempotency_key" UUID NOT NULL,
"request_hash" CHAR(64) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "b2b_quote_responses_note" CHECK (char_length(btrim("note")) BETWEEN 3 AND 500),
CONSTRAINT "b2b_quote_responses_hash" CHECK ("request_hash" ~ '^[a-f0-9]{64}$')
);
CREATE UNIQUE INDEX "b2b_quote_responses_quote_id_organization_id_key" ON "b2b_quote_responses"("quote_id", "organization_id");
CREATE UNIQUE INDEX "b2b_quote_responses_organization_id_idempotency_key_key" ON "b2b_quote_responses"("organization_id", "idempotency_key");
CREATE INDEX "b2b_quote_responses_organization_id_quote_id_idx" ON "b2b_quote_responses"("organization_id", "quote_id");
ALTER TABLE "b2b_quote_responses" ADD CONSTRAINT "b2b_quote_responses_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "b2b_quote_responses" ADD CONSTRAINT "b2b_quote_responses_quote_id_organization_id_fkey" FOREIGN KEY ("quote_id", "organization_id") REFERENCES "b2b_quotes"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "b2b_quote_responses" ADD CONSTRAINT "b2b_quote_responses_actor_id_organization_id_fkey" FOREIGN KEY ("actor_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE FUNCTION guard_b2b_quote() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE account business_accounts%ROWTYPE;
DECLARE list b2b_price_lists%ROWTYPE;
BEGIN
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Issued B2B quotations are immutable'; END IF;
SELECT * INTO account FROM business_accounts WHERE id = NEW.account_id AND organization_id = NEW.organization_id;
SELECT * INTO list FROM b2b_price_lists WHERE id = NEW.price_list_id AND organization_id = NEW.organization_id;
IF list.status IS DISTINCT FROM 'ACTIVE' OR list.account_id IS DISTINCT FROM NEW.account_id
OR list.currency IS DISTINCT FROM NEW.currency OR list.name IS DISTINCT FROM NEW.price_list_name
THEN RAISE EXCEPTION 'Quotation price list does not match the active account terms'; END IF;
IF NOT EXISTS (SELECT 1 FROM business_verification_events
WHERE account_id = NEW.account_id AND kind = 'APPROVED' AND sequence =
(SELECT MAX(sequence) FROM business_verification_events WHERE account_id = NEW.account_id))
THEN RAISE EXCEPTION 'Quotation business account is not verified'; END IF;
IF NEW.expires_at <= CURRENT_TIMESTAMP OR NEW.expires_at > CURRENT_TIMESTAMP + INTERVAL '90 days'
THEN RAISE EXCEPTION 'Quotation expiry must be within ninety days'; END IF;
IF NEW.account_snapshot IS DISTINCT FROM jsonb_build_object(
'legalName', account.legal_name, 'tradingName', account.trading_name,
'registrationNumber', account.registration_number, 'taxIdentifier', account.tax_identifier,
'countryCode', account.country_code, 'contactEmail', account.contact_email,
'contactPhone', account.contact_phone, 'billingLine1', account.billing_line1,
'billingCity', account.billing_city, 'billingRegion', account.billing_region,
'billingPostalCode', account.billing_postal_code, 'profileVersion', account.profile_version
) THEN RAISE EXCEPTION 'Quotation account snapshot is not current'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER b2b_quotes_guard BEFORE INSERT OR UPDATE OR DELETE ON b2b_quotes FOR EACH ROW EXECUTE FUNCTION guard_b2b_quote();
CREATE FUNCTION guard_b2b_quote_line() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE quote b2b_quotes%ROWTYPE;
DECLARE item b2b_price_list_items%ROWTYPE;
DECLARE variant product_variants%ROWTYPE;
BEGIN
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Issued B2B quotation lines are immutable'; END IF;
SELECT * INTO quote FROM b2b_quotes WHERE id = NEW.quote_id AND organization_id = NEW.organization_id;
SELECT * INTO item FROM b2b_price_list_items WHERE price_list_id = quote.price_list_id AND variant_id = NEW.variant_id;
SELECT * INTO variant FROM product_variants WHERE id = NEW.variant_id AND organization_id = NEW.organization_id;
IF item.id IS NULL OR item.unit_price <> NEW.unit_price OR item.min_quantity <> NEW.min_quantity
OR variant.sku IS DISTINCT FROM NEW.sku OR variant.name IS DISTINCT FROM NEW.name
THEN RAISE EXCEPTION 'Quotation line does not match its price list item and variant snapshot'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER b2b_quote_lines_guard BEFORE INSERT OR UPDATE OR DELETE ON b2b_quote_lines FOR EACH ROW EXECUTE FUNCTION guard_b2b_quote_line();
CREATE FUNCTION check_b2b_quote_total() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF (SELECT COUNT(*) FROM b2b_quote_lines WHERE quote_id = NEW.id) = 0 OR
(SELECT SUM(line_total) FROM b2b_quote_lines WHERE quote_id = NEW.id) <> NEW.merchandise_total
THEN RAISE EXCEPTION 'Quotation total must equal its line snapshots'; END IF;
RETURN NEW;
END;
$$;
CREATE CONSTRAINT TRIGGER b2b_quotes_total_guard AFTER INSERT ON b2b_quotes
DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION check_b2b_quote_total();
CREATE FUNCTION guard_b2b_quote_response() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE deadline TIMESTAMPTZ;
BEGIN
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Quotation responses are immutable'; END IF;
SELECT expires_at INTO deadline FROM b2b_quotes WHERE id = NEW.quote_id AND organization_id = NEW.organization_id;
IF deadline <= CURRENT_TIMESTAMP THEN RAISE EXCEPTION 'Quotation has expired'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER b2b_quote_responses_guard BEFORE INSERT OR UPDATE OR DELETE ON b2b_quote_responses FOR EACH ROW EXECUTE FUNCTION guard_b2b_quote_response();
UPDATE "roles" SET "permissions" = ARRAY(SELECT DISTINCT unnest("permissions" || ARRAY['b2b.quote.read', 'b2b.quote.manage']))
WHERE "is_system" = true AND "name" = 'Owner';

Some files were not shown because too many files have changed in this diff Show More