- Backend: FastAPI app with all models, services, schemas, routes - Admin Panel: Next.js dashboard with all modules (CRM, POS, repairs, warranties, billing, notifications, etc.) - Ecommerce: storefront (submodule) + product catalog - AI Agents: .agents/ skill library for Antigravity IDE - Docs: architecture, billing, notification gateway markdown - Submodules: Backend/OpenWA, Ecommerce/File 2/storefront
6.5 KiB
Store Credits & Cashback Rewards Engine
1. Overview
The Store Credit & Cashback Engine automates reward generation for customer purchases across both E-Commerce Sales Orders and Repair Service Jobs.
To protect business margins against returns and chargebacks, credits are not awarded immediately. Instead, they are generated in a PENDING state with a dynamic maturity date governed by the configurable Return Window.
2. Configuration & Admin Settings
The engine settings are stored dynamically in the settings table (group = "credits") and editable through the Admin Console under Settings > Credits & Return Windows:
| Key | Default | Description |
|---|---|---|
credits_enabled |
true |
Master switch for store credit generation |
credits_sales_percentage |
5.0 |
Percentage credited on final e-commerce order amount (e.g. 5.0 = 5%) |
credits_sales_return_window_days |
7 |
Duration in days after order delivery before credit matures |
credits_service_percentage |
5.0 |
Percentage credited on captured repair service amount |
credits_service_claim_window_days |
3 |
Duration in days after repair completion before credit matures |
credits_minimum_order_value |
0.0 |
Minimum invoice value eligible for credit |
credits_expiry_days |
365 |
Expiry period for spendable credits in days |
3. Data Models
CustomerWallet (customer_wallets)
wallet_id: Unique identifier (ULID)customer_id: FK toecom_customers.customer_idactive_balance: Spendable, matured wallet balancepending_balance: Credits awaiting return window expirationlifetime_earned: Total historical credits earnedlifetime_redeemed: Total credits spent on checkoutis_locked: Fraud prevention lock
WalletTransaction (wallet_transactions)
transaction_id: Unique identifier (ULID)wallet_id: FK tocustomer_wallets.wallet_idtransaction_type:EARN,REDEEM,VOID_RETURN,ADJUSTMENTreference_type:ORDER,SERVICE_JOB,MANUAL_ADMIN,PURCHASE_REDEMPTIONreference_id: Originating Order ID or Service Job IDreference_no: User-friendly Order No or Job Nobase_amount: Invoice base amountpercentage_applied: Percentage calculated (e.g. 5.0%)credit_amount: Reward credit amountstatus:PENDING,MATURED,VOIDED,EXPIREDmatures_at: Timestamp when the return window expires (delivered_at + window_days)matured_at: Actual maturity timestamp
4. Lifecycle & Workflows
-
Order Delivery Hook:
- Transitioning an order to
DELIVEREDtriggersCreditService.create_pending_credit_for_order(db, order_id). - Pending balance increases on customer wallet.
- Transitioning an order to
-
Service Completion Hook:
- Transitioning a service job to
DELIVEREDorCOMPLETEDtriggersCreditService.create_pending_credit_for_service(db, job_id). - Pending balance increases on customer wallet.
- Transitioning a service job to
-
Cancellation & Return Voiding:
- If an order is marked
RETURNEDorCANCELLED,CreditService.void_pending_credit(db, "ORDER", order_id)immediately cancels the pending transaction and reducespending_balance.
- If an order is marked
-
Maturity Sweep Worker:
- Endpoint:
POST /api/v1/cron/process-credit-maturity - Scans all
PENDINGtransactions wherematures_at <= NOW. - Verifies reference order/service was not returned or refunded.
- Promotes transaction to
MATURED, incrementsactive_balance, and decrementspending_balance.
- Endpoint:
5. API Endpoints
GET /api/v1/credits/settings: Retrieve active credit percentages and return window durations.PUT /api/v1/credits/settings: Update credit percentages and return window durations (Admin only).GET /api/v1/credits/wallets/{customer_id}: Admin view of customer wallet and transaction ledger.POST /api/v1/credits/wallets/{customer_id}/adjust: Admin manual credit/debit adjustment with audit reason.GET /api/v1/credits/my-wallet: Storefront customer wallet summary.POST /api/v1/cron/process-credit-maturity: Scheduled maturity sweep worker.
6. Checkout Redemption & Cancellation Restitution
Redemption Flow
- During checkout (
POST /api/v1/checkout/create), the client can passuse_wallet_credits: true. - The server acquires a row lock (
with_for_update()) onCustomerWalletto prevent race conditions or double-spending. - The spendable amount is calculated as
min(wallet.active_balance, eligible_total)whereeligible_total = subtotal + shipping_fee. - The order's
discount_amountis updated withcredits_applied, andfinal_amountis reduced accordingly. - If
final_amount == 0, payment gateway initiation is bypassed (zero_amount: true), and the order is marked confirmed immediately. - A
REDEEMtransaction entry is written towallet_transactionswith statusMATURED, andwallet.active_balanceis atomically debited whilewallet.lifetime_redeemedis incremented.
Cancellation & Return Restitution
- When an admin marks an order
CANCELLEDorRETURNEDviaAdminOrderRouter, two actions occur:CreditService.void_pending_credit(): Voids any pending future cashback earned on the order.CreditService.refund_redeemed_credits(): Automatically refunds any store credits previously spent/redeemed on that order back to the customer'sactive_balance, logging anADJUSTMENTrefund entry in the audit ledger.
7. Storefront UI Integrations
-
Customer Account Portal (
/account?tab=wallet):- Dashboard Widget: High-level quick card showing current spendable credit balance.
- My Wallet & Credits Tab:
- Three primary metric cards: Spendable Balance, Pending Balance, Lifetime Earned.
- "How Store Credits Work" visual educational guide explaining pending duration, return window security, and checkout usage.
- Itemized transaction ledger table listing Transaction ID, Date, Reference (Order/Service ID), Amount, and Status pills (
✓ Active,⏳ Pending,✕ Voided).
-
Checkout Order Summary (
/checkout):- Interactive "Redeem Store Credits" card showing spendable credits available.
- Toggle to apply credits, dynamically updating order breakdown rows:
- Subtotal, Shipping, Store Credits Applied (-₹X.XX), Final Payable Total.
- Live Estimated Cashback badge calculating rewards to be received after delivery return window.
-
Product Details Page (
ProductInteractiveGrid.tsx):- Dynamic cashback badge under the product price:
- "🎁 Earn 5% Store Credit (≈ ₹XX) after 7-day return window".
- Dynamic cashback badge under the product price: