# 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 to `ecom_customers.customer_id` * `active_balance`: Spendable, matured wallet balance * `pending_balance`: Credits awaiting return window expiration * `lifetime_earned`: Total historical credits earned * `lifetime_redeemed`: Total credits spent on checkout * `is_locked`: Fraud prevention lock ### `WalletTransaction` (`wallet_transactions`) * `transaction_id`: Unique identifier (ULID) * `wallet_id`: FK to `customer_wallets.wallet_id` * `transaction_type`: `EARN`, `REDEEM`, `VOID_RETURN`, `ADJUSTMENT` * `reference_type`: `ORDER`, `SERVICE_JOB`, `MANUAL_ADMIN`, `PURCHASE_REDEMPTION` * `reference_id`: Originating Order ID or Service Job ID * `reference_no`: User-friendly Order No or Job No * `base_amount`: Invoice base amount * `percentage_applied`: Percentage calculated (e.g. 5.0%) * `credit_amount`: Reward credit amount * `status`: `PENDING`, `MATURED`, `VOIDED`, `EXPIRED` * `matures_at`: Timestamp when the return window expires (`delivered_at + window_days`) * `matured_at`: Actual maturity timestamp --- ## 4. Lifecycle & Workflows 1. **Order Delivery Hook**: * Transitioning an order to `DELIVERED` triggers `CreditService.create_pending_credit_for_order(db, order_id)`. * Pending balance increases on customer wallet. 2. **Service Completion Hook**: * Transitioning a service job to `DELIVERED` or `COMPLETED` triggers `CreditService.create_pending_credit_for_service(db, job_id)`. * Pending balance increases on customer wallet. 3. **Cancellation & Return Voiding**: * If an order is marked `RETURNED` or `CANCELLED`, `CreditService.void_pending_credit(db, "ORDER", order_id)` immediately cancels the pending transaction and reduces `pending_balance`. 4. **Maturity Sweep Worker**: * Endpoint: `POST /api/v1/cron/process-credit-maturity` * Scans all `PENDING` transactions where `matures_at <= NOW`. * Verifies reference order/service was not returned or refunded. * Promotes transaction to `MATURED`, increments `active_balance`, and decrements `pending_balance`. --- ## 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 1. During checkout (`POST /api/v1/checkout/create`), the client can pass `use_wallet_credits: true`. 2. The server acquires a row lock (`with_for_update()`) on `CustomerWallet` to prevent race conditions or double-spending. 3. The spendable amount is calculated as `min(wallet.active_balance, eligible_total)` where `eligible_total = subtotal + shipping_fee`. 4. The order's `discount_amount` is updated with `credits_applied`, and `final_amount` is reduced accordingly. 5. If `final_amount == 0`, payment gateway initiation is bypassed (`zero_amount: true`), and the order is marked confirmed immediately. 6. A `REDEEM` transaction entry is written to `wallet_transactions` with status `MATURED`, and `wallet.active_balance` is atomically debited while `wallet.lifetime_redeemed` is incremented. ### Cancellation & Return Restitution * When an admin marks an order `CANCELLED` or `RETURNED` via `AdminOrderRouter`, two actions occur: 1. `CreditService.void_pending_credit()`: Voids any pending future cashback earned on the order. 2. `CreditService.refund_redeemed_credits()`: Automatically refunds any store credits previously spent/redeemed on that order back to the customer's `active_balance`, logging an `ADJUSTMENT` refund entry in the audit ledger. --- ## 7. Storefront UI Integrations 1. **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`). 2. **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. 3. **Product Details Page (`ProductInteractiveGrid.tsx`)**: * Dynamic cashback badge under the product price: * *"🎁 Earn 5% Store Credit (≈ ₹XX) after 7-day return window"*.