- Added models for loyalty points allocation, redemption, rewards, tiers, tier history, and referrals. - Created business credit ledger entries, settlements, and settlement items models. - Developed services for loyalty operations including account management, point allocation, redemption, and referral handling. - Implemented wholesale credit management services for transactions and settlements. - Established routes for loyalty and wholesale admin and customer operations with appropriate middleware for authentication and permission checks. - Introduced validation schemas for loyalty and wholesale operations. - Set up cron jobs for loyalty reconciliation tasks such as birthday rewards and point expirations. - Created migration scripts to set up the database schema for loyalty and wholesale features. - Added unit tests for validation and policy enforcement in loyalty and wholesale services.
4.8 KiB
ZUMRI Phase 9 Loyalty and Wholesale Completion
Objective
Connect immutable loyalty rewards and wholesale credit/settlement accounting to existing users, paid orders, reviews, coupons, payments, and invoices.
Existing Components Reused
User/Profile DOB, BusinessCustomer/Tier/CreditAccount/SettlementTerm, Orders, Payments, Refunds, Invoices, Reviews, Coupons, pricing money helpers, ReferenceNumber, cron, notifications, audit, and RBAC.
Loyalty Architecture
One account caches balances while an append-only ledger remains authoritative. All mutations lock the account and use unique events.
Loyalty Account
ACTIVE/SUSPENDED/CLOSED state, spendable/pending/debt balances, lifetime totals, tier, and last activity are maintained transactionally.
Points Ledger
Integer EARN, REDEEM, EXPIRE, ADJUSTMENT, and REVERSAL entries store source, resulting balance, expiry, and sanitized metadata.
Earning Rules
Data-driven effective rules support amount-based purchases and fixed review/referral/birthday awards.
Purchase Rewards
Confirmed PAID processing awards discounted merchandise value only, with integer-safe floor rounding and deterministic Order event identity.
Refund Reversals
Reversals append history. Insufficient available points produce tracked debt rather than silently discarding value.
Verified Review Rewards
Only APPROVED verified-purchase reviews earn, once per review.
Referral Rewards
Opaque random codes prevent self/multiple referral claims; signup alone does not reward, while a qualifying paid Order does.
Birthday Rewards
Daily bounded reconciliation uses a unique user/calendar-year event, preventing DOB edits or retries from duplicating rewards.
Points Expiry
Earn rules may assign expiry. Allocation records support earliest-expiring-first redemption and idempotent expiry debits.
Membership Tiers
Active data-driven LIFETIME_POINTS thresholds select the highest rank and append tier history.
Reward Catalogue
Scheduled, limited COUPON or MANUAL rewards use integer point costs.
Reward Redemption
Account/reward/allocation locks enforce balance, stock, per-user limits, FIFO spending, and idempotency.
Voucher Integration
COUPON rewards reference Phase 5 Coupon and issue customer entitlements rather than creating another coupon engine.
Loyalty Notifications and Permissions
Phase 2 notification/audit remain the delivery boundaries. Accounts read, points adjustment, management, and referral-read permissions were added.
Wholesale Architecture
Existing business identity/pricing remain authoritative. Phase 9 adds financial ledgers and period snapshots.
Business Credit Ledger
Unique immutable events store amount, balance delta/after, currency, Order/Payment references, and event time.
Credit Utilization
Account row locks prevent limits being exceeded. Cached usedCredit was not added to BusinessCreditAccount; the latest ledger balance is authoritative.
Credit Purchase Integration
An eligible pending wholesale Order is captured, inventory-consumed, paid, and invoiced in one transaction.
Settlement Terms and Lifecycle
Existing term days derive due dates. DRAFT, ISSUED, PARTIALLY_PAID, PAID, OVERDUE, and CANCELLED use explicit transitions.
Business Statements, Invoice Integration, Payment Allocation
Settlement items reference source Orders/Invoices/ledger entries. Existing Invoice and Payment are reused; allocation persistence prepares later bank matching.
Wholesale Dashboard and Analytics
Owner-scoped SQL aggregates provide monthly/lifetime volume, discount totals, credit utilization, next settlement, and recent Orders without loading all history.
Security, Audit, Idempotency, Concurrency
No IDs select another organization on business routes. Strict schemas reject balance/tier/client financial fields. Unique event keys plus account/settlement/reward locks protect retries and competing writes.
Database Changes
Forward-only 20260909090000 creates fourteen focused loyalty/wholesale tables. Earlier migrations are unchanged.
Tests
Policy tests cover integer money conversion, configured caps, referral entropy, strict inputs, terminal settlement state, and permission denial, alongside Phase 0–8 regression.
Remaining Known Issues
Refund-completion reversal wiring, coupon-entitlement enforcement in the Phase 6 quote path, payment allocation APIs, settlement document generation, notification fan-out, and broader integration/concurrency tests require hardening.
Phase 10 Prerequisites
Run legacy loyalty/credit/voucher/DOB/reference prechecks, migrate restored staging, seed rules/tiers/rewards/permissions, and test real concurrent redemptions, credit purchases, settlements, webhook rewards, refunds, birthday, and expiry jobs.
Module 16 AI Customer Support Chatbot is intentionally excluded and will be developed as a separate service.