feat: Implement Phase 6 Shopping and Checkout
CI / test (push) Has been cancelled
CI / test (pull_request) Has been cancelled

- Introduced authenticated shopping state and atomic checkout process without creating orders or payments.
- Reused existing components from previous phases including identities, addresses, catalogues, pricing, and inventory.
- Developed cart architecture to support one active cart per user with unique items per variant.
- Implemented dynamic cart pricing with various precedence rules for promotions and coupons.
- Created a wishlist feature that exposes only visible active products without reserving inventory.
- Integrated inventory validation to ensure availability of items before adding to cart.
- Developed a checkout architecture that locks the cart, revalidates pricing and shipping, and reserves inventory.
- Added shipping zones, methods, and rates with configurable options for international shipping and duty/tax boundaries.
- Implemented checkout snapshots to capture immutable checkout details.
- Introduced idempotency for checkout requests to prevent duplicate processing.
- Added functionality for coupon integration and business checkout validation.
- Established permissions for managing shipping zones, methods, and rates.
- Created comprehensive unit tests covering various aspects of the shopping and checkout processes.
- Added cron job for handling checkout expiry reconciliation.
- Created migration script to set up new database tables and constraints for carts, checkout sessions, and shipping.
This commit is contained in:
Sathira Sri Sathara
2026-09-03 23:45:01 +05:30
parent 5643d89236
commit ad9287b804
33 changed files with 187 additions and 10 deletions
+42
View File
@@ -0,0 +1,42 @@
# Shopping and Checkout API
All endpoints use `/api/v1` and require authentication unless stated otherwise. Ownership is derived exclusively from the authenticated identity; request bodies never accept `userId`.
## Cart
- `GET /cart`
- `POST /cart/items` with `variantId`, `quantity`
- `PATCH /cart/items/:itemId` with `quantity`; zero removes the item
- `DELETE /cart/items/:itemId`
- `DELETE /cart`
- `PUT /cart/coupon` and `DELETE /cart/coupon`
Only one ACTIVE cart exists per user. Adding items does not reserve inventory. Responses revalidate catalogue state, availability, MOQ, business pricing, promotions, coupons, and integer-scaled totals. Unavailable items remain visible with an explanatory status.
## Wishlist
- `GET /wishlist`
- `POST /wishlist` with `productId`
- `DELETE /wishlist/:productId`
Wishlist entries are owner-scoped, contain no quantity, and never reserve stock.
## Shipping
- `POST /shipping/quote` with an owned `addressId`; subtotal is read from the authoritative cart.
- Admin CRUD: `/admin/shipping/zones`, `/admin/shipping/methods`, `/admin/shipping/rates`.
Zones match country, then optional province/district. Rates support schedules, subtotal bands, currency, and configurable free-shipping thresholds. Unsupported destinations return an explicit error. Duty mode is descriptive; tax is zero until authoritative configuration exists.
## Checkout
- `POST /checkout` requires `Idempotency-Key` and owned shipping/billing address IDs plus a shipping method ID.
- `GET /checkout/active`
- `GET /checkout/:id`
- `POST /checkout/:id/cancel`
The server recalculates all prices, shipping, discounts, and availability. Client price/total fields are rejected. Checkout snapshots commerce-critical item/address/shipping data and atomically reserves every item using sorted lock order. The cart becomes `CHECKOUT_LOCKED`. Cancellation or bounded expiry reconciliation releases reservations and restores the cart. Same user/key/payload returns the existing checkout; a changed payload conflicts.
Business checkout uses the same cart/session and revalidates active approved status, customer/tier pricing, MOQ, and volume tiers. Business credit is not consumed.
No guest cart, Order, Payment, coupon redemption, tax provider, customs calculator, shipment, or delivery workflow exists in Phase 6.
+3
View File
@@ -414,3 +414,6 @@ Remaining identity work is operational: validate/deduplicate deployed RBAC data
## Phase 5 Completion Update
Date: 2026-09-03. Inventory/reservation foundations, business pricing, promotions/coupons, and localized scheduled banners are implemented behind new permissions and a forward-only migration. Phase 5 adds 13 models, secured administration routes, public availability/banner projections, audit calls, a bounded expiry reconciliation cron, and Phase 6 pricing/reservation service boundaries. Module 05 is 85%, Module 07 is 78%, and Module 13 is 75%. Inventory is 90%, reservations 90%, business pricing 82%, promotions/coupons 78%, and banners 82%. Automated verification: 18 suites and 89 tests passed; syntax passed for 232 JavaScript files. Migration was not executed. Staging must precheck legacy stock/pricing/promotion/banner data, apply the migration, seed permissions/default warehouse, and test genuine MySQL locking plus cron behavior before Phase 6 production use.
## Phase 6 Completion Update
Date: 2026-09-03. Module 06 is 91%, Module 08 is 84%, and Module 07 is revised to 86%. Authenticated cart is 92%, wishlist 92%, shipping 86%, checkout 88%, and reservation integration 90%. Nine models, a forward-only migration, owner-scoped shopping APIs, permission-protected shipping administration, server-authoritative totals, atomic inventory reservation composition, idempotent checkout creation, and bounded expiry/cancellation release are implemented. Verification passes 20 suites/95 tests and 258 JavaScript syntax checks. The migration was not executed. Before Phase 7, staging must precheck legacy shopping/shipping tables and address/currency compatibility, seed shipping configuration/permissions, apply migrations, and validate real multi-connection InnoDB concurrency plus multi-instance expiry behavior.
@@ -0,0 +1,76 @@
# ZUMRI Phase 6 Shopping and Checkout
## Objective
Add authenticated shopping state and an atomic, priced, inventory-reserved checkout handoff without creating orders or payments.
## Existing Components Reused
Phase 3 identities/addresses/business accounts, Phase 4 catalogue, Phase 5 pricing/inventory/promotions, Phase 1 permissions, Phase 2 audit, Sequelize, Zod, and cron bootstrap.
## Cart Architecture
One ACTIVE cart per identity; items are unique per variant and owner-scoped. Guest carts were intentionally omitted. Version increments detect state changes and checkout locks mutation.
## Cart Pricing
Cart items are dynamically requoted with retail/business/volume/promotion/coupon precedence. DECIMAL strings use BigInt-scaled arithmetic.
## Wishlist
Unique owner/product entries expose only visible active products and never reserve inventory.
## Inventory Validation
Adding and projecting items checks authoritative aggregate availability. Unavailable items remain explainable.
## Reservation Integration
Cart does not reserve. Checkout extends the Phase 5 service with external transaction composition and reserves sorted variants all-or-nothing.
## Shipping Zones
Normalized country/province/district records provide deterministic destination matching, including international zones.
## Shipping Methods
Configurable methods include delivery estimates and tracking capability.
## Shipping Rates
Scheduled DECIMAL rates support currency, subtotal bands, and configurable free-shipping thresholds.
## International Shipping
Only configured zones are eligible; unsupported destinations fail explicitly.
## Duty/Tax Boundary
Zones declare NONE, ESTIMATED, PAYABLE_ON_DELIVERY, INCLUDED, or UNKNOWN. No customs amount is fabricated. Tax remains zero without authoritative configuration.
## Checkout Architecture
A user-scoped transaction locks the cart, revalidates catalogue/pricing/shipping, reserves inventory, writes snapshots, and locks the cart.
## Checkout Snapshots
Immutable checkout items capture product/variant/SKU, price, discount, total, currency, and pricing source. Owned address and shipping selections are copied as JSON.
## Checkout Totals
Merchandise subtotal minus discounts plus shipping plus configured tax/duty equals grand total. Client totals are prohibited.
## Idempotency
Unique `(userId, idempotencyKey)` plus SHA-256 request fingerprint returns the same session or rejects changed payloads.
## Checkout Expiry
A no-overlap minute reconciliation processes 100 sessions, locks each session, releases reservations idempotently, marks EXPIRED, and restores its cart.
## Coupon Integration
Cart coupons are provisional and revalidated at checkout. Authoritative redemption remains Phase 7.
## Business Checkout
The shared flow revalidates approved ACTIVE business context, MOQ, customer/tier price, and volume tier. Credit is untouched.
## Permissions
Shipping zone/method/rate read/manage permissions protect all administration.
## Audit
Cart, wishlist, checkout, expiry/cancellation, and shipping configuration use stable Phase 2 activity types without full addresses or carts.
## Database Changes
Forward-only migration `20260903060000` creates nine Phase 6 tables and required uniqueness/status-expiry indexes.
## Tests
Phase 6 unit tests cover decimal totals, strict client-total rejection, quantity validation, deterministic fingerprints, safe address snapshots, and shipping permission denial. Existing suites remain green.
## Remaining Known Issues
Real InnoDB concurrent checkout, migration, and multi-instance cron behavior require staging. Shipping weight bands, authoritative tax/duty, and coupon redemption are intentionally deferred.
## Phase 7 Prerequisites
Run legacy table/address/currency/reservation prechecks, migrate staging, seed zones/methods/rates and permissions, and prove concurrent final-stock and duplicate-idempotency behavior with real MySQL connections.