fix(loyalty): cross-store enrollment, card scoping, i18n flicker
Some checks failed
Some checks failed
Fix duplicate card creation when the same email enrolls at different stores under the same merchant, and implement cross-location-aware enrollment behavior. - Cross-location enabled (default): one card per customer per merchant. Re-enrolling at another store returns the existing card with a "works at all our locations" message + store list. - Cross-location disabled: one card per customer per store. Enrolling at a different store creates a separate card for that store. Changes: - Migration loyalty_004: replace (merchant_id, customer_id) unique index with (enrolled_at_store_id, customer_id). Per-merchant uniqueness enforced at application layer when cross-location enabled. - card_service.resolve_customer_id: cross-store email lookup via merchant_id param to find existing cardholders at other stores. - card_service.enroll_customer: branch duplicate check on allow_cross_location_redemption setting. - card_service.search_card_for_store: cross-store email search when cross-location enabled so staff at store2 can find cards from store1. - card_service.get_card_by_customer_and_store: new service method. - storefront enrollment: catch LoyaltyCardAlreadyExistsException, return existing card with already_enrolled flag, locations, and cross-location context. Server-rendered i18n via Jinja2 tojson. - enroll-success.html: conditional cross-store/single-store messaging, server-rendered translations and context, i18n_modules block added. - dashboard.html, history.html: replace $t() with server-side _() to fix i18n flicker across all storefront templates. - Fix device-mobile icon → phone icon. - 4 new i18n keys in 4 locales (en, fr, de, lb). - Docs: updated data-model, business-logic, production-launch-plan, user-journeys with cross-location behavior and E2E test checklist. - 12 new unit tests + 3 new integration tests (334 total pass). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -214,14 +214,25 @@ Uses PKCS#7 signed `.pkpass` files and APNs push notifications.
|
||||
|
||||
## Cross-Store Redemption
|
||||
|
||||
When `allow_cross_location_redemption` is enabled in merchant settings:
|
||||
The `allow_cross_location_redemption` merchant setting controls both card scoping and enrollment behavior:
|
||||
|
||||
- Cards are scoped to the **merchant** (not individual stores)
|
||||
### When enabled (default)
|
||||
|
||||
- **One card per customer per merchant** — enforced at the application layer
|
||||
- Customer can earn stamps at Store A and redeem at Store B
|
||||
- Each transaction records which `store_id` it occurred at
|
||||
- The `enrolled_at_store_id` field tracks where the customer first enrolled
|
||||
- If a customer tries to enroll at a second store, the system returns their existing card with a message showing all available locations
|
||||
|
||||
When disabled, stamp/point operations are restricted to the enrollment store.
|
||||
### When disabled
|
||||
|
||||
- **One card per customer per store** — each store under the merchant issues its own card
|
||||
- Stamp/point operations are restricted to the card's enrollment store
|
||||
- A customer can hold separate cards at different stores under the same merchant
|
||||
- Re-enrolling at the **same** store returns the existing card
|
||||
- Enrolling at a **different** store creates a new card scoped to that store
|
||||
|
||||
**Database constraint:** Unique index on `(enrolled_at_store_id, customer_id)` prevents duplicate cards at the same store regardless of the cross-location setting.
|
||||
|
||||
## Enrollment Flow
|
||||
|
||||
@@ -229,21 +240,25 @@ When disabled, stamp/point operations are restricted to the enrollment store.
|
||||
|
||||
Staff enrolls customer via terminal:
|
||||
1. Enter customer email (and optional name)
|
||||
2. System resolves or creates customer record
|
||||
3. Creates loyalty card with unique card number and QR code
|
||||
4. Creates `CARD_CREATED` transaction
|
||||
5. Awards welcome bonus points (if configured) via `WELCOME_BONUS` transaction
|
||||
6. Creates Google Wallet object and Apple Wallet serial
|
||||
7. Returns card details with "Add to Wallet" URLs
|
||||
2. System resolves customer — checks the current store first, then searches across all stores under the merchant for an existing cardholder with the same email
|
||||
3. If the customer already has a card (per-merchant or per-store, depending on the cross-location setting), raises `LoyaltyCardAlreadyExistsException`
|
||||
4. Otherwise creates loyalty card with unique card number and QR code
|
||||
5. Creates `CARD_CREATED` transaction
|
||||
6. Awards welcome bonus points (if configured) via `WELCOME_BONUS` transaction
|
||||
7. Creates Google Wallet object and Apple Wallet serial
|
||||
8. Returns card details with "Add to Wallet" URLs
|
||||
|
||||
### Self-Enrollment (Public)
|
||||
|
||||
Customer enrolls via public page (if `allow_self_enrollment` enabled):
|
||||
1. Customer visits `/loyalty/join` page
|
||||
2. Enters email and name
|
||||
3. System creates customer + card
|
||||
4. Redirected to success page with card number
|
||||
5. Can add to Google/Apple Wallet from success page
|
||||
2. Enters email, name, and optional birthday
|
||||
3. System resolves customer (cross-store lookup for existing cardholders under the same merchant)
|
||||
4. If already enrolled: returns existing card with success page showing location info
|
||||
- Cross-location enabled: "Your card works at all our locations" + store list
|
||||
- Cross-location disabled: "Your card is registered at {original_store}"
|
||||
5. If new: creates customer + card, redirected to success page with card number
|
||||
6. Can add to Google/Apple Wallet from success page
|
||||
|
||||
## Scheduled Tasks
|
||||
|
||||
|
||||
@@ -120,14 +120,21 @@ Merchant-wide loyalty program configuration. One program per merchant, shared ac
|
||||
|
||||
### LoyaltyCard
|
||||
|
||||
Customer loyalty card linking a customer to a merchant's program. One card per customer per merchant.
|
||||
Customer loyalty card linking a customer to a merchant's program.
|
||||
|
||||
**Card uniqueness depends on the `allow_cross_location_redemption` merchant setting:**
|
||||
|
||||
- **Cross-location enabled (default):** One card per customer per merchant. The application layer enforces this by checking all stores under the merchant before creating a card. Re-enrolling at another store returns the existing card.
|
||||
- **Cross-location disabled:** One card per customer per store. A customer can hold separate cards at different stores under the same merchant, each scoped to its enrollment store.
|
||||
|
||||
**Database constraint:** Unique index on `(enrolled_at_store_id, customer_id)` — always enforced. The per-merchant uniqueness (cross-location enabled) is enforced at the application layer in `card_service.enroll_customer`.
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `merchant_id` | FK | Links to program's merchant |
|
||||
| `customer_id` | FK | Card owner |
|
||||
| `program_id` | FK | Associated program |
|
||||
| `enrolled_at_store_id` | FK | Store where customer enrolled |
|
||||
| `enrolled_at_store_id` | FK | Store where customer enrolled (part of unique constraint) |
|
||||
| `card_number` | String (unique) | Formatted XXXX-XXXX-XXXX |
|
||||
| `qr_code_data` | String (unique) | URL-safe token for QR codes |
|
||||
| `stamp_count` | Integer | Current stamp count |
|
||||
|
||||
@@ -40,11 +40,14 @@ This is the active execution plan for taking the Loyalty module to production. I
|
||||
```
|
||||
loyalty_002 (existing)
|
||||
loyalty_003 — CHECK constraints (points_balance >= 0, stamp_count >= 0, etc.)
|
||||
loyalty_004 — seed 28 notification email templates
|
||||
loyalty_005 — add columns: last_expiration_warning_at, last_reengagement_at on cards;
|
||||
loyalty_004 — relax card uniqueness: replace (merchant_id, customer_id) unique index
|
||||
with (enrolled_at_store_id, customer_id) for cross-location support
|
||||
loyalty_005 — seed 28 notification email templates
|
||||
loyalty_006 — add columns: last_expiration_warning_at, last_reengagement_at on cards;
|
||||
acting_admin_id on transactions
|
||||
loyalty_006 — terms_cms_page_slug on programs
|
||||
loyalty_007 — birth_date on customers (P0 — Phase 1.4 fix, dropped data bug)
|
||||
loyalty_007 — terms_cms_page_slug on programs
|
||||
|
||||
customers_003 — birth_date on customers (Phase 1.4 fix, dropped data bug)
|
||||
```
|
||||
|
||||
---
|
||||
@@ -82,7 +85,7 @@ All 8 decisions locked. No external blockers.
|
||||
#### 1.4 Fix dropped birthday data (P0 bug)
|
||||
**Background:** The enrollment form (`enroll.html:87`) collects a birthday, the schema accepts `customer_birthday` (`schemas/card.py:34`), and `card_service.resolve_customer_id` has the parameter (`card_service.py:172`) — but the call to `customer_service.create_customer_for_enrollment` at `card_service.py:215-222` does not pass it, and the `Customer` model has no `birth_date` column at all. Every enrollment silently loses the birthday. Not live yet, so no backfill needed.
|
||||
|
||||
- New migration `loyalty_007_add_customer_birth_date.py` (or place under customers module if that's the convention) adds `birth_date: Date | None` to `customers`.
|
||||
- Migration `customers_003_add_birth_date.py` adds `birth_date: Date | None` to `customers`.
|
||||
- Update `customer_service.create_customer_for_enrollment` to accept and persist `birth_date`.
|
||||
- Update `card_service.py:215-222` to pass `customer_birthday` through, with `date.fromisoformat()` parsing and validation (must be a real past date, sensible age range).
|
||||
- Update `customer_service.update_customer` to allow backfill.
|
||||
@@ -114,7 +117,7 @@ All 8 decisions locked. No external blockers.
|
||||
- New `app/modules/loyalty/tasks/notifications.py` with `@shared_task(name="loyalty.send_notification_email", bind=True, max_retries=3, default_retry_delay=60)`.
|
||||
- Opens fresh `SessionLocal`, calls `EmailService(db).send_template(...)`, retries on SMTP errors.
|
||||
|
||||
#### 2.3 Seed templates `loyalty_004`
|
||||
#### 2.3 Seed templates `loyalty_005`
|
||||
- 7 templates × 4 locales (en, fr, de, lb) = **28 rows** in `email_templates`.
|
||||
- Template codes: `loyalty_enrollment`, `loyalty_welcome_bonus`, `loyalty_points_expiring`, `loyalty_points_expired`, `loyalty_reward_ready`, `loyalty_birthday`, `loyalty_reengagement`.
|
||||
- **Copywriting needs sign-off** before applying to prod.
|
||||
@@ -123,7 +126,7 @@ All 8 decisions locked. No external blockers.
|
||||
- In `card_service.enroll_customer_for_store` (~lines 480-540), call notification service **after** `db.commit()`.
|
||||
|
||||
#### 2.5 Wire expiration warning into expiration task
|
||||
- Migration `loyalty_005` adds `last_expiration_warning_at` to prevent duplicates.
|
||||
- Migration `loyalty_006` adds `last_expiration_warning_at` to prevent duplicates.
|
||||
- In rewritten `tasks/point_expiration.py` (see 3.1), find cards 14 days from expiry, fire warning, stamp timestamp.
|
||||
- **Validation:** time-mocked test — fires once at 14-day mark.
|
||||
|
||||
@@ -137,7 +140,7 @@ All 8 decisions locked. No external blockers.
|
||||
|
||||
#### 2.8 Re-engagement Celery beat task
|
||||
- Weekly schedule. Finds cards inactive > N days (default 60, configurable).
|
||||
- Throttled via `last_reengagement_at` (added in `loyalty_005`) — once per quarter per card.
|
||||
- Throttled via `last_reengagement_at` (added in `loyalty_006`) — once per quarter per card.
|
||||
|
||||
---
|
||||
|
||||
@@ -163,7 +166,7 @@ All 8 decisions locked. No external blockers.
|
||||
### Phase 4 — Accessibility & T&C *(2d)*
|
||||
|
||||
#### 4.1 T&C via store CMS integration
|
||||
- Migration `loyalty_006`: add `terms_cms_page_slug: str | None` to `loyalty_programs`.
|
||||
- Migration `loyalty_007`: add `terms_cms_page_slug: str | None` to `loyalty_programs`.
|
||||
- Update `schemas/program.py` (`ProgramCreate`, `ProgramUpdate`).
|
||||
- `program-form.html:251` — CMS page picker scoped to the program's owning store.
|
||||
- `enroll.html:99-160` — resolve slug to CMS page URL/content; legacy `terms_text` fallback.
|
||||
@@ -224,7 +227,7 @@ All 8 decisions locked. No external blockers.
|
||||
- **Admin "act on behalf"** (`routes/api/admin.py`):
|
||||
- `POST /admin/loyalty/merchants/{merchant_id}/cards/bulk/deactivate` (etc.)
|
||||
- Shared service layer; route stamps `acting_admin_id` in audit log
|
||||
- New `loyalty_transactions.acting_admin_id` column in `loyalty_005`.
|
||||
- New `loyalty_transactions.acting_admin_id` column in `loyalty_006`.
|
||||
|
||||
#### 6.5 Manual override: restore expired points
|
||||
- `POST /admin/loyalty/cards/{card_id}/restore_points` with `{points, reason}`.
|
||||
|
||||
@@ -792,3 +792,109 @@ flowchart TD
|
||||
There is no feature gating on loyalty program creation — you can test them in
|
||||
either order. Journey 0 is listed second because domain setup is about URL
|
||||
presentation, not a functional prerequisite for the loyalty module.
|
||||
|
||||
---
|
||||
|
||||
## Pre-Launch E2E Test Checklist (Fashion Group)
|
||||
|
||||
Manual end-to-end checklist using Fashion Group (merchant 2: FASHIONHUB + FASHIONOUTLET).
|
||||
Covers all customer-facing flows including the cross-store enrollment and redemption features
|
||||
added in the Phase 1 production launch hardening.
|
||||
|
||||
### Pre-requisite: Program Setup (Journey 1)
|
||||
|
||||
If Fashion Group doesn't have a loyalty program yet:
|
||||
|
||||
1. Login as `jane.owner@fashiongroup.com` at `http://localhost:8000/platforms/loyalty/store/FASHIONHUB/login`
|
||||
2. Navigate to: `http://localhost:8000/platforms/loyalty/store/FASHIONHUB/loyalty/settings`
|
||||
3. Create program (hybrid or points), set welcome bonus, enable self-enrollment
|
||||
4. Verify Cross-Location Redemption is **enabled** in merchant settings
|
||||
|
||||
### Test 1: Customer Self-Enrollment (Journey 4)
|
||||
|
||||
| Step | Action | Expected Result |
|
||||
|------|--------|-----------------|
|
||||
| 1.1 | Visit `http://localhost:8000/platforms/loyalty/storefront/FASHIONHUB/loyalty/join` | Enrollment form loads, no console errors |
|
||||
| 1.2 | Fill in: fresh email, name, **birthday** → Submit | Redirected to success page with card number |
|
||||
| 1.3 | Check DB: `SELECT birth_date FROM customers WHERE email = '...'` | `birth_date` is set (not NULL) |
|
||||
| 1.4 | Enroll **without** birthday (different email) | Success, `birth_date` is NULL (no crash) |
|
||||
|
||||
### Test 2: Cross-Store Re-Enrollment (Cross-Location Enabled)
|
||||
|
||||
| Step | Action | Expected Result |
|
||||
|------|--------|-----------------|
|
||||
| 2.1 | Visit `http://localhost:8000/platforms/loyalty/storefront/FASHIONOUTLET/loyalty/join` | Enrollment form loads |
|
||||
| 2.2 | Submit with the **same email** from Test 1 | Success page shows **"You're already a member!"** |
|
||||
| 2.3 | Check: store list shown | Blue box: "Your card works at all our locations:" with Fashion Hub + Fashion Outlet listed |
|
||||
| 2.4 | Check: same card number as Test 1 | Card number matches (no duplicate created) |
|
||||
| 2.5 | Check DB: `SELECT COUNT(*) FROM loyalty_cards WHERE customer_id = ...` | Exactly 1 card |
|
||||
| 2.6 | Re-enroll at FASHIONHUB (same store as original) | Same behavior: "already a member" + locations |
|
||||
| 2.7 | Refresh the success page | Message persists, no flicker, no untranslated i18n keys |
|
||||
|
||||
### Test 3: Staff Operations — Stamps/Points (Journeys 2 & 3)
|
||||
|
||||
| Step | Action | Expected Result |
|
||||
|------|--------|-----------------|
|
||||
| 3.1 | Login as `jane.owner@fashiongroup.com` at FASHIONHUB | Login succeeds |
|
||||
| 3.2 | Open terminal: `.../store/FASHIONHUB/loyalty/terminal` | Terminal loads |
|
||||
| 3.3 | Look up card by card number | Card found, balance displayed |
|
||||
| 3.4 | Look up card by customer email | Card found (same result) |
|
||||
| 3.5 | Add stamp (or earn points with purchase amount) | Count/balance updates |
|
||||
| 3.6 | Add stamp again immediately (within cooldown) | Rejected: cooldown active |
|
||||
|
||||
### Test 4: Cross-Store Redemption (Journey 8)
|
||||
|
||||
| Step | Action | Expected Result |
|
||||
|------|--------|-----------------|
|
||||
| 4.1 | Staff at FASHIONHUB adds stamps/points to the card | Balance updated |
|
||||
| 4.2 | Login as staff at FASHIONOUTLET (e.g., `diana.stylist@fashiongroup.com` or `jane.owner`) | Login succeeds |
|
||||
| 4.3 | Open terminal: `.../store/FASHIONOUTLET/loyalty/terminal` | Terminal loads |
|
||||
| 4.4 | Look up card **by email** | Card found (cross-store email search) |
|
||||
| 4.5 | Look up card **by card number** | Card found |
|
||||
| 4.6 | Redeem reward (if enough stamps/points) | Redemption succeeds |
|
||||
| 4.7 | View card detail | Transaction history shows entries from both FASHIONHUB and FASHIONOUTLET |
|
||||
|
||||
### Test 5: Customer Views Status (Journey 5)
|
||||
|
||||
| Step | Action | Expected Result |
|
||||
|------|--------|-----------------|
|
||||
| 5.1 | Login as the customer at storefront | Customer dashboard loads |
|
||||
| 5.2 | Dashboard: `.../storefront/FASHIONHUB/account/loyalty` | Shows balance, available rewards |
|
||||
| 5.3 | History: `.../storefront/FASHIONHUB/account/loyalty/history` | Shows transactions from both stores |
|
||||
|
||||
### Test 6: Void/Return (Journey 7)
|
||||
|
||||
| Step | Action | Expected Result |
|
||||
|------|--------|-----------------|
|
||||
| 6.1 | Staff at FASHIONHUB opens terminal, looks up card | Card found |
|
||||
| 6.2 | Void a stamp or points transaction | Balance adjusted |
|
||||
| 6.3 | Check transaction history | Void transaction appears, linked to original |
|
||||
|
||||
### Test 7: Admin Oversight (Journey 6)
|
||||
|
||||
| Step | Action | Expected Result |
|
||||
|------|--------|-----------------|
|
||||
| 7.1 | Login as `samir.boulahtit@gmail.com` (admin) | Admin dashboard loads |
|
||||
| 7.2 | Programs: `.../admin/loyalty/programs` | Fashion Group program visible |
|
||||
| 7.3 | Fashion Group detail: `.../admin/loyalty/merchants/2` | Cards, transactions, stats appear correctly |
|
||||
| 7.4 | Fashion Group settings: `.../admin/loyalty/merchants/2/settings` | Cross-location toggle visible and correct |
|
||||
|
||||
### Test 8: Cross-Location Disabled Behavior
|
||||
|
||||
| Step | Action | Expected Result |
|
||||
|------|--------|-----------------|
|
||||
| 8.1 | Admin disables Cross-Location Redemption for Fashion Group | Setting saved |
|
||||
| 8.2 | Enroll a **new email** at FASHIONHUB | New card created for FASHIONHUB |
|
||||
| 8.3 | Enroll **same email** at FASHIONOUTLET | **New card created** for FASHIONOUTLET (separate card) |
|
||||
| 8.4 | Enroll **same email** at FASHIONHUB again | "Already a member" — shows "Your card is registered at Fashion Hub" (single store, no list) |
|
||||
| 8.5 | Staff at FASHIONOUTLET searches by email | Only finds the FASHIONOUTLET card (no cross-store search) |
|
||||
| 8.6 | Re-enable Cross-Location Redemption when done | Restore default state |
|
||||
|
||||
### Key Things to Watch
|
||||
|
||||
- [ ] Birthday persisted after enrollment (check DB)
|
||||
- [ ] No i18n flicker or console warnings on success page
|
||||
- [ ] Cross-store email search works in the terminal (cross-location enabled)
|
||||
- [ ] "Already a member" message shows correct locations/store based on cross-location setting
|
||||
- [ ] No duplicate cards created under same merchant (when cross-location enabled)
|
||||
- [ ] Rate limiting: rapid-fire stamp calls eventually return 429
|
||||
|
||||
Reference in New Issue
Block a user