Skip to Content
📚 MyStoryFlow Docs — Your guide to preserving family stories
Use Cases & TestingGift Purchase Flow

Gift Purchase Flow - Business Rules & Test Cases

Document Purpose: Comprehensive specification of all business rules, validation logic, and user experience behaviors in the gift purchase flow. This document serves as the source of truth for test case development and change management.

Last Updated: July 12, 2025
Version: 2.0
Flow Path: /dashboard/purchase-gift


📋 Table of Contents

  1. Flow Overview
  2. Step 1: Gift Details
  3. Step 2: Family Members
  4. Step 3: Gift Message
  5. Step 4: Books Selection
  6. Step 5: Payment
  7. Step 6: Thank You
  8. Navigation Rules
  9. Data Persistence
  10. UI/UX Rules
  11. Test Case Categories

Flow Overview

Flow Types

  • Authenticated User Flow: 5 steps (Gift Details → Family → Message → Books → Payment → Thank You)
  • Anonymous User Flow: 6 steps (adds Info collection step before Payment)

Core Principles

  1. Gift recipients are different from purchasers - validation prevents self-gifting
  2. Two admin members by default - purchaser and recipient get admin roles
  3. Data persistence across navigation - form data maintained during back/forward navigation
  4. Responsive design priority - optimized for tablet usage
  5. Progressive disclosure - only show relevant information at each step

Step 1: Gift Details

Purpose

Collect recipient information for the gift

Required Fields

  • Recipient Name (text, required)
  • Recipient Email (email, required, validated)

Business Rules

BR-GD-001: Form Initialization

  • Rule: Form starts completely empty (no auto-population)
  • Rationale: Prevents confusion between personal and gift flows
  • Test: Verify no fields are pre-filled on first load

BR-GD-002: Data Persistence

  • Rule: Previously entered data is restored when navigating back from later steps
  • Implementation: Uses giftDetails state as initialData
  • Test: Enter data, go to next step, return - data should be preserved

BR-GD-003: Email Validation

  • Rule: Standard email format validation using regex /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  • Test: Test valid/invalid email formats

BR-GD-004: Flow Switcher (Authenticated Users Only)

  • Rule: Authenticated users see option to switch to Personal Story Collection
  • Trigger: showFlowSwitcher={!!user}
  • Action: Redirects to /campaigns/create
  • Test: Verify switcher appears for logged-in users, not for anonymous

BR-GD-005: Self-Gift Detection (Primary Validation)

  • Rule: Prevent users from entering their own email as recipient
  • Validation: Email comparison is case-insensitive
  • Error Message: “It looks like you’re creating a book for yourself. Consider switching to the Personal Story Collection flow instead.”
  • Implementation: Validates on form submission in Gift Details step
  • Priority: Primary validation point - prevents invalid flow progression
  • Test: Enter current user email as recipient, verify error appears and blocks progression

BR-GD-006: Continue Button State

  • Rule: Continue button disabled until both name and email are filled
  • Implementation: isNextDisabled={!form.recipientName || !form.recipientEmail}
  • Test: Button state changes as fields are filled/cleared

BR-GD-007: Progress Indicator

  • Rule: Shows current step (1 of 5 for auth, 1 of 6 for anon)
  • Test: Verify correct step count and current position

Step 2: Family Members

Purpose

Set up family collaboration team with automatic admin members and optional additional contributors

Default Members (Auto-Generated)

BR-FM-001: Current User as Admin

  • Rule: Logged-in user automatically added as admin member
  • Display Label: “[User Name] (You)” - shows actual user name with “(You)” indicator
  • Fields: Name and email from user profile, role locked to ‘admin’
  • Editability: Fields disabled (name/email cannot be changed)
  • Removability: Cannot be removed
  • Test: Verify user appears with correct name and “(You)” indicator, locked fields

BR-FM-002: Recipient as Admin

  • Rule: Gift recipient automatically added as admin member
  • Display Label: “[Recipient Name] (Recipient)” (uses actual name from step 1)
  • Fields: Name and email from gift details, role locked to ‘admin’
  • Editability: Fields disabled (name/email cannot be changed)
  • Removability: Cannot be removed
  • Clarification: Role is admin but labeled as “Recipient” for clarity
  • Test: Verify recipient appears with data from step 1 and “(Recipient)” label

BR-FM-003: Self-Gift Detection (Secondary Validation)

  • Rule: If recipient email matches current user email, show validation error
  • Error Message: “It looks like you’re creating a book for yourself. Consider switching to the Personal Story Collection flow instead.”
  • Validation Timing: On continue button click (backup validation)
  • Case Sensitivity: Email comparison is case-insensitive
  • Priority: Secondary validation - primary validation is in Gift Details step
  • Test: This should not be reachable under normal flow, but test as fallback

Additional Family Members

BR-FM-004: Adding Members

  • Rule: Users can add up to 8 additional family members (10 total max)
  • Button: “Add Member” button available when < 10 total members
  • Default Role: New members default to ‘contributor’
  • ID Generation: member-${Date.now()}
  • Test: Verify adding members works up to limit

BR-FM-005: Member Validation

  • Rule: Additional members must have name, email, and valid email format
  • Validation Scope: Only validates additional members (not core admins)
  • Email Uniqueness: All member emails must be unique (case-insensitive)
  • Test: Test various validation scenarios

BR-FM-006: Member Roles

  • Available Roles:
    • Admin: Can manage family and edit all stories
    • Contributor: Can add and edit their own stories
    • Viewer: Can view stories but not edit
  • Core Member Restriction: Current user and recipient locked to admin
  • Test: Verify role options and restrictions

BR-FM-007: Member Removal

  • Rule: Only additional members can be removed (not core admins)
  • UI: Remove button (X) only appears for non-admin members
  • Test: Verify remove button visibility and functionality

BR-FM-008: Member Display

  • Card Design: Each member in white card with border and subtle shadow
  • Hover Effect: Card shadow increases on hover for interactivity
  • Responsive Layout: Single column on mobile/tablet, two columns on desktop for name/email fields
  • Test: Verify responsive behavior and visual styling

UI/UX Rules

BR-FM-009: Empty State

  • Trigger: When only 2 core admin members present
  • Display: Simple message “Want to add more family members? Click ‘Add Member’ above.”
  • Icon: Small users icon, subtle styling
  • Test: Verify appears with 2 members, disappears when adding more

BR-FM-010: Continue Button

  • Rule: Always enabled (since 2 core admins provide minimum viable family)
  • Previous Behavior: Was disabled with 0 members - no longer applicable
  • Test: Verify button always enabled

BR-FM-011: Right Panel Benefits

  • Display: Shows benefits of adding family members in subtle gray box
  • Content: 4 bullet points about collaboration benefits
  • Tone: Encouraging but not pushy, acknowledges members can be added later
  • Test: Verify content appears and styling is subtle

Step 3: Gift Message

Purpose

Collect personalized message and delivery date for the gift

Required Fields

  • Gift Message (textarea, required)
  • Delivery Date (date, required, defaults to today)
  • From (text array, optional - can be multiple names)

Business Rules

BR-GM-001: Default Delivery Date

  • Rule: Delivery date defaults to current date
  • Format: ISO date string (YYYY-MM-DD)
  • Implementation: new Date().toISOString().slice(0, 10)
  • Test: Verify today’s date appears by default

BR-GM-002: Message Validation

  • Rule: Gift message cannot be empty and must be ≤ 300 characters
  • Required: Message is mandatory (cannot be empty after trimming)
  • Character Limit: 300 characters maximum
  • Character Counter: Shows current count and limit in footer
  • Color Coding: Counter turns orange when > 90% of limit (270+ chars)
  • Prevention: Input blocks typing beyond 300 characters
  • Test: Verify empty validation, character limit enforcement, counter display

BR-GM-003: Date Restrictions

  • Rule: Delivery date cannot be in the past
  • Browser Validation: min={today} attribute prevents past date selection
  • Application Validation: Additional validation in submit handler
  • Error Message: “Delivery date cannot be in the past”
  • Test: Verify past dates are blocked both in picker and validation

BR-GM-004: Future Date Scheduling

  • Rule: Future dates schedule email delivery for midnight on selected date
  • Immediate Confirmation: Purchaser receives immediate purchase confirmation
  • Scheduled Delivery: Gift recipient and family members receive emails at midnight on delivery date
  • Display: Show scheduling message when future date selected
  • Format: ”📅 Gift emails will be sent at midnight on [date]. You’ll receive an immediate purchase confirmation.”
  • Test: Verify scheduling message appears and email timing works correctly

BR-GM-005: From Field Behavior

  • Rule: Optional field for gift sender names (up to 5 names)
  • Purpose: Names appear in gift email as purchasers
  • Multiple Names: Can include multiple people giving the gift
  • Default Behavior: If empty, only purchaser’s name used
  • Explanation: Helper text explains “These names will appear in the email as the people who purchased this gift”
  • Test: Verify optional nature, multi-name support, and email integration

BR-GM-006: Character Counter Display

  • Rule: Real-time character count shown in message footer
  • Format: “X/300” display in bottom right of textarea
  • Color States:
    • Gray: 0-269 characters
    • Orange: 270-300 characters (warning state)
  • Helper Text: “This message will be included in the gift notification email”
  • Test: Verify counter updates in real-time and color changes appropriately

BR-GM-007: Email Scheduling Integration

  • Rule: Email service must handle both immediate and scheduled sending
  • Immediate Sending: When delivery date = today
  • Scheduled Sending: When delivery date > today, schedule for midnight UTC
  • Purchase Confirmation: Always sent immediately regardless of delivery date
  • API Integration: Delivery date passed to email service for scheduling
  • Test: Verify immediate vs scheduled email behavior

BR-GM-008: Data Persistence Between Steps

  • Rule: All gift message data must be preserved during navigation
  • Preserved Fields: Message content, delivery date, from array
  • Implementation: Parent component passes initialMessage, initialDeliveryDate, initialFrom
  • Navigation: Data retained when going back from Books step or forward to Books step
  • State Management: Uses giftMessage state object in parent component
  • Test: Enter message data, navigate to Books, navigate back - verify all data preserved

BR-GM-009: Gift Delivery Date Scenarios

  • Rule: System behavior changes based on selected delivery date
  • Scenario 1 - Immediate Delivery (Today’s Date):
    • Email sending: All gift emails sent immediately after purchase
    • User notification: “Gift emails will be sent immediately”
    • Recipients: Purchaser, gift recipient, and family members all receive emails within minutes
    • API behavior: delivery_date = today, no scheduling required
  • Scenario 2 - Future Delivery (Date > Today):
    • Email sending: Gift emails scheduled for midnight UTC on selected date
    • User notification: ”📅 Gift emails will be sent at midnight on [date]. You’ll receive an immediate purchase confirmation.”
    • Purchase confirmation: Sent immediately to purchaser only
    • Scheduled emails: Gift recipient and family members receive emails on delivery date
    • API behavior: delivery_date = future_date, email service schedules delivery
  • Technical Implementation: Email service must handle both immediate and scheduled sending
  • Test Cases:
    • Today’s date: Verify immediate email delivery to all recipients
    • Future date: Verify immediate purchase confirmation, scheduled delivery emails
    • Date validation: Verify past dates blocked, future dates show scheduling message

Step 4: Books Selection

Purpose

Choose number of physical books to create

Consistency Note: This step shares the same book pricing structure with the Book Creation Wizard’s PrintOrderStep. See Book Creation Wizard - Print Order for the equivalent step in the self/family book creation flow.

Business Rules

BR-BS-001: Book Quantity and Pricing

  • Rule: Minimum 1 book, maximum 5 books in dropdown
  • Default: 1 book selected
  • Pricing Structure:
    • First book: $79 (base price)
    • Additional books: $59 each (bulk pricing)
  • Savings Calculation: Shows discount vs individual book pricing
  • Shared Pricing Logic: Uses calculateBookPricing() from config/pricing.ts
  • Test: Verify quantity limits and pricing calculations

BR-BS-002: Pricing Display in Select Options

  • Rule: Each option shows total price and savings in the dropdown
  • Format Examples:
    • “1 book - $79”
    • “2 books - $138 (Save $20)”
    • “3 books - $197 (Save $40)”
  • Implementation: Calculated using calculateBookPricing() function
  • Test: Verify pricing accuracy and savings display for all quantities

BR-BS-003: Family-Based Recommendations

  • Rule: Recommend number of books based on family member count with maximum book limit consideration
  • Recommendation Logic:
    • 1-2 members: Recommend 2 books (“Perfect for the recipient and one extra copy to share”)
    • 3-4 members: Recommend 3 books (“Ideal for sharing among your family members”)
    • 5 members: Recommend 4 books (“Great for larger families - everyone can have their own copy”)
    • 6+ members: Recommend 5 books (“Maximum books available - additional books can be ordered separately”)
  • Visual Display: Blue recommendation box with member count and reasoning
  • Quick Select: Button to instantly select recommended quantity
  • Large Family Handling: When family size > 5 members, show additional information about ordering more books
  • Test: Verify recommendations change based on family size and handle large families appropriately

BR-BS-004: Recommendation Interaction

  • Rule: Show recommendation prominently with family context
  • Display Elements:
    • Circular badge with recommended number
    • “Recommended for your family (X members)” headline
    • Contextual reason for recommendation
    • Quick select button (only shown when current selection ≠ recommendation)
  • User Action: One-click selection of recommended quantity
  • Test: Verify recommendation appears and quick select works

BR-BS-005: Gift Preview Display

  • Rule: Show preview of gift message and details to enhance purchase experience
  • Conditional Display: Only appears if gift message has been entered
  • Preview Content:
    • Recipient name (“To: [Name]”)
    • Gift message in quotes
    • From names (formatted list or “Your gift giver” if empty)
    • Delivery date (formatted as “Today” or full date)
  • Visual Design:
    • Orange gradient background for warmth
    • Gift icon for visual appeal
    • White card with shadow for message content
    • Icons for “From” and delivery date
  • Purpose: Make gift feel tangible and increase purchase confidence
  • Formatting Rules:
    • From names: Single name, “A and B”, or “A, B, and C” format
    • Delivery date: “Today” for today’s date, full date for future dates
  • Test: Verify preview appears with message data, proper formatting, and visual appeal

BR-BS-006: Order Summary Pricing Breakdown

  • Rule: Display pricing breakdown showing full price with clear discount structure
  • Pricing Display Method: Show all books at full price, then subtract bulk discount
  • Breakdown Components:
    • Books line: “X books at $79 each - $YYY” (shows total at full price)
    • Bulk discount line: “Bulk discount (X books) - $ZZZ” (shows discount amount in green)
    • Total: Shows final discounted amount
  • Pricing Display Format:
    • “5 books at $79 each - $395”
    • “Bulk discount (4 books) - $80” (green text)
    • “Total - $315”
  • Discount Calculation: (additional_books) × ($79 - $59) = discount_amount
  • Visual Design:
    • Discount line in green color to highlight savings
    • Border separators between pricing sections
  • Consistency: Same pricing display used in both Books step and Payment step
  • Test Cases:
    • 1 book: Shows “1 book at $79 each - $79”, no discount line, total $79
    • 2 books: Shows “2 books at $79 each - $158”, “Bulk discount (1 books) - $20”, total $138
    • 5 books: Shows “5 books at $79 each - $395”, “Bulk discount (4 books) - $80”, total $315

BR-BS-007: Large Family Book Limitations

  • Rule: Handle families with more than 5 members who need additional books
  • Maximum Books: 5 books maximum in initial dropdown selection
  • Large Family Detection: When family size > 5 members
  • Additional Information Display:
    • Show informational box explaining additional book options
    • Message: “Need more books for your large family?”
    • Explanation: “You can order additional books during checkout or place a separate order later. Each family member will still be able to collaborate on the story collection.”
  • Visual Design: Gray informational box with ”+” icon to indicate additional options
  • User Experience: Reassure users that all family members can still participate regardless of book count
  • Future Enhancement: Link to additional book ordering during checkout
  • Test Cases:
    • Family with 6 members: Shows informational box and recommends 5 books
    • Family with 10 members: Shows informational box and recommends 5 books
    • Verify informational box only appears when family size > 5
    • Verify recommendation caps at 5 books for large families

Step 5: Payment

Purpose

Complete purchase transaction with enhanced order summary and gift preview

Order Summary Display

BR-PAY-001: Enhanced Order Summary with Gift Preview

  • Design: Use GiftSummaryPanel component for consistent experience
  • Gift Preview: Show gift message card with recipient, message, from names, and delivery date
  • Order Information:
    • Recipient name (not email in main section - email moved to gift preview)
    • Number of books and family size
    • Detailed pricing breakdown with full price and bulk discount
  • Pricing Display: Same format as Books step for consistency
  • Visual Design: Professional layout with gift preview prominently displayed
  • Content Removal: Remove generic “Story Flow Memoir” label - no predefined product name
  • Test: Verify gift preview appears, pricing matches previous step, clean professional layout

BR-PAY-002: Payment Integration and Success Handling

  • Method: Stripe integration (implementation status: incomplete per test results)
  • Required Data: Amount, recipient info, family members, delivery details
  • Success Response Handling: Frontend checks both res.ok AND data.success for proper redirect
  • Response Processing: Parse JSON response and check success field before redirecting
  • Invoice Creation: Automatic invoice generation for authenticated users with gift-specific details
  • Screen Flashing Fix: Use window.location.href immediately instead of router.push to prevent multiple state changes
  • Navigation Logic:
    • If data.redirect_to provided, use window.location.href for immediate redirect (prevents screen flashing)
    • Simplified redirect logic eliminates multiple state updates during navigation
    • Fallback: Show Thank You step (step 5 for auth, step 6 for anon)
    • Priority: Thank You page → Family workspace → Dashboard fallback
  • Redirect Implementation:
    • Store purchase data in localStorage before redirect
    • Use window.location.href = redirectUrl for reliable, immediate navigation
    • Avoid router.push to prevent UI state conflicts and screen flashing
  • Redirect Destinations:
    • /dashboard/purchase-gift?step=thank-you (primary - shows gift confirmation)
    • /families/{family_id} (secondary - if family created)
    • /dashboard (fallback)
  • Data Storage: Purchase data stored in localStorage for thank you page display
  • Error Handling: Display error message from API response
  • Anonymous Users: Must provide giver email and name (no invoice created)
  • Invoice Response: API includes invoice_id and invoice_number for authenticated users
  • Test: Verify proper redirect to thank you page without screen flashing and invoice creation after purchase success

BR-PAY-003: Gift Processing Backend Logic

  • Gift Subscription Strategy: Subscription system not yet implemented (skipped to avoid errors)
  • Subscription Details:
    • Status: Temporarily disabled pending subscription table implementation
    • Warning logged but doesn’t block gift purchase
    • For recipient only - purchaser doesn’t get subscription
  • Family Creation Strategy: Always create family for authenticated gift purchasers with subscription bypass
  • Family Creation Bypass: Skip subscription checks for gift purchases using skipSubscriptionCheck = true
  • Family Membership:
    • Purchaser: Added as ‘contributor’ (can participate without subscription)
    • Recipient: Added as ‘contributor’ (they’ll be the main story owner)
    • Additional members: As specified in purchase
  • Campaign Creation: Create campaign linked to family for dashboard access
  • Campaign Details:
    • Title: “Gift for [Recipient Name]”
    • Links: gift_id, user_id, family_group_id
    • Enables immediate family workspace access
  • Invoice Generation: Automatic invoice generation for authenticated users with complete system
  • Invoice Database Migration: Applied migration 20250712_170000_add_invoice_system.sql with proper function creation
  • Invoice Details:
    • Transaction type: ‘gift_purchase’
    • Auto-generated invoice number (YYYYMM-NNNN format) using generate_invoice_number() function
    • Line items with bulk discount breakdown using InvoiceService.createGiftPurchaseLineItems()
    • Gift-specific metadata (recipient, message, delivery date, number_of_books)
    • Status: ‘paid’ (immediate payment completion)
    • Proper RLS policies for user access
  • Dashboard Access: Family membership enables dashboard access (no subscription needed for purchaser)
  • Email Requirements: All users must provide giver_email for confirmation emails
  • Database Permissions: Use service role key for gift/campaign/family/invoice operations
  • Error Handling: Family/email/invoice failures don’t block gift purchase success (warnings added)
  • Test: Verify family, campaign, and invoice created; purchaser can access family workspace and billing history

BR-PAY-004: Purchase Payload

  • Authenticated Users: Include user ID, profile name
  • Anonymous Users: Include provided giver name and email
  • Family Data: Map admin roles correctly (admin → contributor for gifts)
  • API Endpoint: /api/gifts/purchase
  • Test: Verify payload structure for both user types

Step 6: Thank You

Purpose

Confirm successful purchase and provide next steps

Business Rules

BR-TY-001: Confirmation Display

  • Rule: Show purchase confirmation with order details
  • Navigation: Provide link to dashboard/gifts for tracking
  • Email: Reference email that will be sent
  • Test: Verify confirmation appears after successful payment

BR-TY-002: Enhanced Gift Purchase Confirmation

  • Gift-Specific Display: Show detailed gift information instead of generic thank you
  • Confirmation Details:
    • Recipient name and email
    • Gift message (if provided)
    • Delivery date and timing
    • Number of books ordered
    • Invoice number (for authenticated users)
    • Next steps explanation
  • What Happens Next Section:
    • Recipient will receive gift notification email
    • 1-year access explanation
    • Book creation details
    • Collaboration opportunity
    • Link to billing/invoice history
  • Action Button: “Go to Family Workspace” instead of generic dashboard
  • Redirect Logic: Family workspace → Campaign → Dashboard fallback
  • Data Storage: Purchase data stored in localStorage for thank you page
  • Invoice Access: Link to /dashboard/billing for purchase history
  • URL Parameter Handling: Detects ?step=thank-you and shows appropriate step
  • Test: Verify all gift details displayed accurately with clear next steps and invoice information

BR-TY-003: Email Correction (Anonymous Users)

  • Rule: Anonymous users can correct their email if needed
  • Implementation: allowEmailCorrection={!user}
  • Test: Verify email correction option for anonymous users only

Forward Navigation

BR-NAV-001: Step Progression

  • Rule: Must complete current step validation to proceed
  • Implementation: onNext handlers with validation
  • Test: Verify cannot skip steps or proceed with invalid data

BR-NAV-002: Step Dependencies

  • Rule: Each step requires data from previous steps
  • Family Step: Requires recipient info from gift details
  • Message Step: References recipient name
  • Test: Verify data flow between steps

Backward Navigation

BR-NAV-003: Data Preservation

  • Rule: All form data preserved when navigating backward and forward
  • Implementation: Each step receives initial* props from parent state
  • Covered Data:
    • Gift Details: initialData preserves recipient name/email
    • Family Members: initialMembers preserves family member list
    • Gift Message: initialMessage, initialDeliveryDate, initialFrom preserve all message data
    • Books: initialNumberOfBooks preserves book quantity selection
  • State Management: Parent component maintains complete flow state
  • Test: Navigate forward and back between any steps, verify no data loss

BR-NAV-004: Back Button Behavior

  • Rule: Each step provides back navigation to previous step
  • Exception: First step uses window.history.back()
  • Data Restoration: Previous step data fully restored from state
  • Test: Verify back navigation works from all steps with data intact

Data Persistence

Browser Storage

BR-DP-001: LocalStorage (Currently Disabled)

  • Status: Temporarily disabled due to infinite loop issues
  • Previous Behavior: Saved flow state to localStorage
  • Recovery Plan: Re-enable after fixing loop issue
  • Test: Currently no localStorage persistence to test

BR-DP-002: Component State Persistence

  • Rule: State maintained in parent component during session
  • Scope: Data persists during browser tab session
  • Limitation: Lost on page refresh (until localStorage restored)
  • Test: Verify state persistence during navigation

API Integration

BR-DP-003: Gift Creation

  • Endpoint: /api/gifts/purchase
  • Timing: Only on final payment submission
  • Data: Complete gift package with all step data
  • Test: Verify API payload includes all collected information

BR-DP-004: User Profile Updates (Critical for Dashboard Access)

  • Rule: Gift purchase automatically updates user profile to enable full platform access
  • Profile Changes:
    • subscription_tier set to ‘starter’
    • setup_completed set to true
  • Rationale: Gift purchasers have paid for features and should access them immediately
  • Middleware Impact: Enables family workspace access without redirect to campaign creation
  • Implementation: Profile update happens after successful payment, before email sending
  • Error Handling: Profile update failures logged as warnings but don’t block purchase success
  • Test: Verify family workspace redirect works after gift purchase completion

BR-DP-005: Dashboard Campaign Visibility

  • Rule: Gift purchasers see all campaigns where they are family members (owner/admin/contributor/viewer)
  • Implementation: CampaignOverview component queries both owned campaigns and family-linked campaigns
  • Query Logic:
    1. Fetch campaigns owned by user (campaigns.user_id = user.id)
    2. Fetch family memberships (family_members.user_id = user.id)
    3. Fetch campaigns linked to those families (campaigns.family_group_id IN family_ids)
    4. Combine and deduplicate results
  • Family Member Addition: Gift purchaser automatically added as ‘owner’ role in created family
  • Test: Verify gift purchaser sees campaign created through gift purchase in dashboard

BR-DP-006: Additional Books Purchase Messaging

  • Rule: Thank you page communicates option to purchase additional books later
  • Location: Delivery Details section with informational tip
  • Message: ”💡 Want more books? You can purchase additional copies when you’re ready to place your printing order.”
  • Rationale: Set expectations that initial purchase covers story collection, additional copies available at printing
  • Test: Verify messaging appears in thank you page delivery details section

UI/UX Rules

Responsive Design

BR-UX-001: Tablet Optimization

  • Priority: Tablet users are primary audience
  • Layout: Single column on mobile/tablet, multi-column on desktop
  • Touch Targets: Large enough for tablet interaction
  • Test: Verify usability on tablet devices

BR-UX-002: Form Field Layout

  • Mobile/Tablet: Single column layout for form fields
  • Desktop: Two-column layout where appropriate (name/email pairs)
  • Implementation: grid-cols-1 lg:grid-cols-2
  • Test: Verify responsive breakpoints

Interactive Elements

BR-UX-003: Select Dropdown Behavior

  • Hover Effect: Clear visual feedback on option hover
  • Click Outside: Dropdown closes when clicking outside
  • Background: Solid white background prevents text overlap
  • Test: Verify all dropdown interactions work properly

BR-UX-004: Button States

  • Disabled State: Clear visual indication when buttons disabled
  • Loading State: Shows loading indicator during processing
  • Hover Effects: Consistent hover feedback across buttons
  • Test: Verify all button state variations

Progress Indication

BR-UX-005: Progress Bar

  • Display: Shows current step and total steps
  • Labels: Step names clearly indicated
  • Responsive: Adapts to mobile screen sizes
  • Test: Verify progress indication accuracy

BR-UX-006: Step Naming

  • Authenticated Flow: [‘Recipient’, ‘Family’, ‘Message’, ‘Books’, ‘Purchase’]
  • Anonymous Flow: [‘Recipient’, ‘Family’, ‘Message’, ‘Books’, ‘Info’, ‘Purchase’]
  • Test: Verify correct step names for each flow type

BR-UX-007: Message Step User Experience

  • Character Counter: Real-time feedback on character usage
  • Visual Warnings: Orange color when approaching limit (90%+)
  • Input Prevention: Typing blocked at 300 character limit
  • Scheduling Feedback: Clear visual indication when emails will be sent
  • Helper Text: Contextual information for each field explaining purpose
  • Date Picker: Browser-native date input with min date restriction
  • Test: Verify all interactive feedback elements work correctly

BR-UX-008: Right Panel Content (Message Step)

  • Message Benefits: Shows benefits of personalizing gift message
  • Encouragement: Explains impact of thoughtful messaging
  • Scheduling Info: Explains delivery timing options
  • From Field Usage: Explains multiple gift giver functionality
  • Test: Verify right panel content appears and is helpful

BR-UX-009: Gift Preview Enhancement (Books Step)

  • Visual Hierarchy: Gift preview card prominently displayed at top
  • Emotional Design: Orange gradient and gift icon create warmth and excitement
  • Content Layout: Clean white card with proper spacing for readability
  • Icon Usage: Users and Calendar icons for visual context
  • Responsive Design: Card adapts to different screen sizes
  • Purpose: Transform technical book selection into emotional gift experience
  • Test: Verify visual appeal, readability, and emotional impact of preview

Test Case Categories

Functional Testing

TC-FUNC-001: Happy Path Testing

  • Complete successful gift purchase flow for authenticated user
  • Complete successful gift purchase flow for anonymous user
  • Verify all data correctly submitted and processed

TC-FUNC-002: Validation Testing

  • Test all field validations (required fields, email format, etc.)
  • Test business rule validations (self-gift detection, etc.)
  • Test error message display and recovery

TC-FUNC-003: Navigation Testing

  • Test forward navigation with valid data
  • Test backward navigation with data preservation
  • Test step skipping prevention

TC-FUNC-004: Family Member Management

  • Test adding/removing family members
  • Test role assignment and restrictions
  • Test member validation rules
  • Test large family scenarios (>5 members)

TC-FUNC-005: Gift Delivery Timing Scenarios

  • Immediate Delivery (Today):
    • Select today’s date as delivery date
    • Complete purchase flow
    • Verify all emails (purchaser, recipient, family) sent immediately
    • Verify no scheduling messages shown
  • Future Delivery (Scheduled):
    • Select future date as delivery date
    • Verify scheduling message appears during flow
    • Complete purchase flow
    • Verify immediate purchase confirmation sent to purchaser
    • Verify gift emails scheduled for delivery date (not sent immediately)
    • Verify correct scheduling message in confirmation
  • Date Validation:
    • Attempt to select past dates (should be blocked)
    • Test date picker restrictions
    • Test manual date entry validation

TC-FUNC-006: Large Family Book Scenarios

  • Small Family (≤5 members):
    • Add 2-5 family members
    • Verify no additional information box appears
    • Verify recommendations follow standard logic
  • Large Family (6+ members):
    • Add 6-10 family members
    • Verify informational box appears about additional books
    • Verify recommendation caps at 5 books regardless of family size
    • Verify message explains additional book ordering options
    • Verify all family members can still collaborate message
  • Edge Cases:
    • Test with exactly 5 members (should not show additional info)
    • Test with exactly 6 members (should show additional info)
    • Test with maximum family members (10) and verify consistent behavior

TC-FUNC-007: Order Summary Pricing Validation

  • Single Book Pricing:
    • Select 1 book
    • Verify shows “1 book at $79 each - $79” and “Total - $79”
    • Verify no bulk discount line appears
  • Multiple Book Pricing:
    • Select 2 books: Verify “2 books at $79 each - $158”, “Bulk discount (1 books) - $20”, “Total - $138”
    • Select 3 books: Verify “3 books at $79 each - $237”, “Bulk discount (2 books) - $40”, “Total - $197”
    • Select 5 books: Verify “5 books at $79 each - $395”, “Bulk discount (4 books) - $80”, “Total - $315”
  • Discount Calculation Verification:
    • Verify bulk discount = (additional_books) × ($79 - $59)
    • 2 books: discount = 1 × $20 = $20
    • 5 books: discount = 4 × $20 = $80
  • Pricing Consistency:
    • Verify Books step and Payment step show identical pricing
    • Verify calculations use correct BOOK_PRICING constants ($79 base, $59 bulk)
    • Verify total = (books × $79) - bulk_discount
  • Visual Formatting:
    • Verify bulk discount line appears in green text
    • Verify proper border separators between pricing sections
    • Verify consistent formatting across both steps

TC-FUNC-008: Payment Step Order Summary Validation

  • Gift Preview Integration:
    • Verify gift message card appears in payment step right panel
    • Verify gift preview shows recipient, message, from names, delivery date
    • Verify gift preview formatting matches Books step
  • Order Summary Enhancement:
    • Verify no generic “Story Flow Memoir” label appears
    • Verify recipient email moved from main order to gift preview card
    • Verify pricing breakdown matches Books step exactly
    • Verify family size displays correctly
  • Component Consistency:
    • Verify GiftSummaryPanel used for both Books and Payment steps
    • Verify identical pricing display format across both steps
    • Verify showGiftPreview=true works correctly in payment context
  • Content Verification:
    • Verify all data from previous steps preserved and displayed
    • Verify clean, professional layout without redundant information

TC-FUNC-009: Gift Campaign, Subscription, and Invoice Validation

  • Campaign Creation:
    • Complete gift purchase flow with authenticated user
    • Verify campaign created for gift purchaser
    • Verify campaign title: “Gift for [Recipient Name]”
    • Verify campaign status is ‘active’
    • Verify campaign links to gift_id and user_id
  • Subscription Creation:
    • Verify gift subscription created for recipient (not purchaser)
    • Verify subscription status is ‘pending_activation’
    • Verify subscription tier is ‘starter’ with 1-year duration
    • Verify no subscription created for purchaser
  • Invoice Generation:
    • Verify invoice created for authenticated users only
    • Verify invoice number follows YYYYMM-NNNN format
    • Verify invoice includes gift metadata (recipient, message, delivery date)
    • Verify line items show bulk discount breakdown
    • Verify invoice status is ‘paid’
    • Verify invoice accessible via /dashboard/billing
  • Family-Campaign Integration:
    • If family members added: verify family created and linked to campaign
    • Verify campaign.family_group_id populated when family exists
    • Verify campaign accessible whether family exists or not
  • API Response Validation:
    • Verify response includes campaign_id, invoice_id, and invoice_number
    • Verify redirect_to points to thank you page: /dashboard/purchase-gift?step=thank-you
    • Verify success message mentions campaign and invoice creation
  • Frontend Redirect:
    • Verify user redirected to thank you page immediately using window.location.href
    • Verify thank you page loads with complete gift details and invoice information
    • Verify link to family workspace from thank you page

UI/UX Testing

TC-UX-001: Responsive Design Testing

  • Test on mobile devices (phone sizes)
  • Test on tablet devices (primary audience)
  • Test on desktop devices
  • Verify layout adapts appropriately

TC-UX-002: Interactive Elements Testing

  • Test all button states and hover effects
  • Test dropdown behavior and accessibility
  • Test form field interactions

TC-UX-003: Visual Design Testing

  • Test card layouts and shadows
  • Test color scheme consistency
  • Test typography and spacing

Integration Testing

TC-INT-001: Authentication Integration

  • Test authenticated vs anonymous user flows
  • Test user profile data integration
  • Test flow switching functionality

TC-INT-002: Payment Integration

  • Test Stripe integration (when implemented)
  • Test order summary accuracy
  • Test payment error handling
  • Test invoice generation after successful payment
  • Test billing dashboard integration
  • Test invoice data consistency with purchase details

TC-INT-003: Email Integration

  • Test email template integration
  • Test family member invitation emails
  • Test purchase confirmation emails

Error Handling Testing

TC-ERR-001: Network Error Testing

  • Test behavior during API failures
  • Test retry mechanisms
  • Test error message display

TC-ERR-002: Data Validation Error Testing

  • Test all validation error scenarios
  • Test error message clarity and helpfulness
  • Test error recovery flows

TC-ERR-003: Browser Compatibility Testing

  • Test on different browsers
  • Test with different browser settings
  • Test with JavaScript disabled scenarios

Invoice System Outcomes

Success Scenarios

INV-SUCCESS-001: Authenticated User Gift Purchase

  • Trigger: Authenticated user completes gift purchase
  • Process:
    1. Payment processed and gift record created
    2. Invoice automatically generated with unique number (YYYYMM-NNNN)
    3. Line items created with bulk discount breakdown
    4. Gift metadata stored (recipient, message, delivery date, book count)
    5. Invoice marked as ‘paid’ with current timestamp
  • User Experience:
    • Thank you page shows invoice number
    • Invoice accessible immediately via /dashboard/billing
    • Professional invoice display with gift context
    • Download functionality available (future PDF generation)
  • Business Benefits: Complete purchase audit trail, tax reporting, customer service support

INV-SUCCESS-002: Anonymous User Gift Purchase

  • Trigger: Anonymous user completes gift purchase
  • Process:
    1. Payment processed and gift record created
    2. No invoice generated (user not authenticated)
    3. Gift completion tracked via gift ID only
  • User Experience:
    • Thank you page shows purchase confirmation without invoice details
    • Encouragement to create account for purchase history tracking
  • Business Benefits: Simplified flow for quick purchases, data available for analysis

Failure Scenarios

INV-FAILURE-001: Invoice Generation Failure

  • Trigger: Gift purchase succeeds but invoice creation fails
  • Process:
    1. Gift purchase marked as successful (payment completed)
    2. Invoice creation failure logged as warning
    3. Warning added to API response but success still returned
    4. Error logged to gift_processing_errors table for retry
  • User Experience:
    • Gift purchase appears successful
    • Warning displayed about billing record delay
    • Manual resolution via retry API or admin intervention
  • Recovery: Admin can trigger invoice creation retry via /api/gifts/retry

INV-FAILURE-002: Billing Dashboard Access Issues

  • Trigger: User cannot access billing dashboard or specific invoices
  • Process:
    1. RLS policies enforce user-only access to invoices
    2. 401/404 errors returned for unauthorized access
    3. Graceful error handling in UI
  • User Experience:
    • Clear error messages about access permissions
    • Retry functionality available
    • Contact support option provided
  • Recovery: User authentication verification, RLS policy validation

Integration Points

Database Integration

  • Tables: invoices, invoice_line_items
  • Migration: Applied 20250712_170000_add_invoice_system.sql with proper function creation
  • Functions: generate_invoice_number() for auto-numbering (YYYYMM-NNNN format)
  • Triggers: update_invoices_updated_at for timestamp management
  • Relationships: Links to gifts, campaigns, auth.users
  • Constraints: RLS policies, foreign key constraints, unique invoice numbers
  • Indexes: Performance indexes on user_id, gift_id, status, transaction_type, date

API Integration

  • Creation: Triggered during gift purchase API (/api/gifts/purchase) with full error handling
  • Service Layer: InvoiceService handles all invoice operations and calculations
  • Calculation Methods:
    • calculateGiftPurchaseTotals() - handles bulk discount pricing
    • createGiftPurchaseLineItems() - structured line item generation
  • Retrieval: Dedicated invoice APIs (/api/invoices, /api/invoices/[id])
  • Security: User authentication required, RLS enforcement
  • Performance: Indexed queries, pagination support
  • Error Recovery: Failed invoice creation logged to gift_processing_errors table

UI Integration

  • Billing Dashboard: Complete invoice management interface at /dashboard/billing
  • Thank You Page: Invoice number display and billing link
  • Navigation: Accessible from dashboard menu
  • Responsive Design: Mobile and tablet optimized
  • Gift Context: Invoices display gift-specific information for clarity

Business Intelligence

  • Revenue Tracking: Detailed transaction history with gift metadata
  • Gift Analytics: Recipient patterns, popular configurations, bulk discount usage
  • Customer Service: Complete purchase context including gift details for support
  • Tax Reporting: Structured data for accounting systems with proper line item breakdown

Recent Changes (Version 2.0)

July 12, 2025 Updates

Fixed Screen Flashing During Purchase Completion

  • Issue: Multiple state changes during redirect caused UI flashing
  • Solution: Use window.location.href for immediate redirect instead of router.push
  • Impact: Eliminates screen flashing, provides smoother user experience
  • Files Modified: /app/(dashboard)/dashboard/purchase-gift/page.tsx

Implemented Complete Invoice System

  • Database Migration: Applied 20250712_170000_add_invoice_system.sql
  • Invoice Generation: Auto-generated invoice numbers (YYYYMM-NNNN format)
  • Service Layer: Complete InvoiceService with pricing calculations
  • UI Integration: Billing dashboard and thank you page invoice display
  • RLS Policies: Proper security for user invoice access
  • Files Added:
    • /lib/database/migrations/20250712_170000_add_invoice_system.sql
    • /lib/billing/invoice-service.ts
    • /app/(dashboard)/dashboard/billing/page.tsx

Fixed Family Creation for Gift Purchases

  • Issue: Subscription checks blocked family creation for gift purchases
  • Solution: Added skipSubscriptionCheck parameter to bypass limits for paid features
  • Impact: Gift purchasers can always create families regardless of subscription status
  • Files Modified:
    • /lib/family/family-service.ts
    • /lib/gift/gift-family-service.ts

Fixed Family Workspace Access for Gift Purchasers

  • Issue: Middleware redirected gift purchasers to campaign creation when accessing family workspace
  • Root Cause: Middleware required setup_completed = true for all dashboard routes, including /families/*
  • Solution: Added specific exception for family workspace routes in middleware
  • Location: /lib/supabase/middleware.ts lines 113-118
  • Logic: Gift purchasers can access family workspace even without completing initial setup
  • Impact: “Go to Family Workspace” button now works correctly for gift purchasers
  • Business Rationale: Gift purchasers have paid for family features and should access them immediately

Fixed Dashboard Campaign Query for Family Members

  • Issue: Dashboard only showed campaigns owned by user, not family member campaigns
  • Root Cause: CampaignOverview component query limited to user_id = current_user
  • Solution: Enhanced query to include campaigns through family membership
  • Implementation:
    • Query owned campaigns: user_id = user.id
    • Query family campaigns: family_group_id IN (user's family memberships)
    • Combine results to show all accessible campaigns
  • Files Modified: /app/components/dashboard/CampaignOverview.tsx
  • Impact: Users see campaigns they can access as family members, preventing empty state redirects

Fixed Family Database Query Errors

  • Issue: Family creation failed with database query errors
  • Root Cause: Incorrect column references in family service queries
  • Fixes Applied:
    • Fixed profiles table query: .eq('user_id', invitedBy).eq('id', invitedBy)
    • Fixed member existence check to properly query by email then user_id
    • Fixed foreign key references in gift family service
  • Files Modified:
    • /lib/family/family-service.ts
    • /lib/gift/gift-family-service.ts
  • Impact: Family creation now succeeds for gift purchases

Disabled Subscription Creation Temporarily

  • Issue: Subscription system database tables not yet implemented
  • Solution: Skip subscription creation with warning logs instead of errors
  • Impact: Gift purchases complete successfully without subscription system dependency
  • Files Modified: /app/api/gifts/purchase/route.ts

Enhanced Error Handling and Recovery

  • Gift Processing Errors: Non-critical failures logged to gift_processing_errors table
  • Graceful Degradation: Invoice, family, or email failures don’t block gift purchase success
  • Warning System: Warnings returned in API response for partial failures
  • Retry Mechanism: Error tracking enables future retry operations

TypeScript Compilation Fixes

  • Fixed: Property access errors with proper type annotations
  • Fixed: Optional chaining for undefined object properties
  • Impact: Application builds successfully without TypeScript errors

Migration Applied

-- Invoice System Migration -- Applied: 2025-07-12T17:00:00Z -- Tables: invoices, invoice_line_items -- Functions: generate_invoice_number() -- Policies: User-only access via RLS -- Status: Successfully applied ``` --> ## Change Management Process ### Rule Modification Protocol 1. **Documentation Update**: Update this document first 2. **Impact Assessment**: Identify affected test cases 3. **Implementation**: Make code changes 4. **Test Update**: Update or create new test cases 5. **Validation**: Run full test suite 6. **Review**: Team review of changes and tests ### Version Control - **Document Version**: Increment on any rule changes - **Change Log**: Maintain record of what changed and why - **Test Mapping**: Maintain mapping between rules and test cases ### Stakeholder Communication - **Business Rules**: Communicate rule changes to business stakeholders - **Technical Changes**: Communicate implementation details to dev team - **Test Impact**: Communicate test changes to QA team --- ## Appendix ### Error Messages Reference #### Validation Errors - Self-gift detection: "It looks like you're creating a book for yourself. Consider switching to the Personal Story Collection flow instead." - Missing family member data: "Please fill in all additional family member names and emails" - Invalid email format: "Please enter valid email addresses for all additional family members" - Duplicate emails: "Each family member must have a unique email address" - Missing required fields: "All fields are required" - Empty gift message: "Gift message is required" - Message too long: "Gift message must be 300 characters or less" - Missing delivery date: "Delivery date is required" - Past delivery date: "Delivery date cannot be in the past" #### System Errors - Payment failure: "Failed to purchase gift." (+ specific error details) - Network errors: "Internal server error" (generic fallback) ### API Endpoints #### Gift Purchase - **Endpoint**: `POST /api/gifts/purchase` - **Authentication**: Optional (handles both authenticated and anonymous) - **Payload**: Complete gift data including recipient, family, message, books - **Response**: Success confirmation or error details - **Side Effects**: Creates invoice record for billing history #### Gift Error Handling - **Endpoint**: `GET /api/gifts/errors` - **Purpose**: Retrieve gift processing errors for user - **Authentication**: Required #### Gift Retry - **Endpoint**: `POST /api/gifts/retry` - **Purpose**: Retry failed gift processing operations - **Authentication**: Required #### Invoice Management - **Endpoint**: `GET /api/invoices` - **Purpose**: Retrieve user's purchase history and invoices - **Authentication**: Required - **Response**: List of invoices with gift details and payment information - **Query Parameters**: `limit` (default: 50) for pagination - **Sorting**: Most recent invoices first #### Invoice Details - **Endpoint**: `GET /api/invoices/[id]` - **Purpose**: Get detailed invoice information for specific purchase - **Authentication**: Required (must own invoice) - **Response**: Complete invoice with line items and payment details - **Includes**: Gift metadata, recipient info, pricing breakdown #### Billing Dashboard - **Page**: `/dashboard/billing` - **Purpose**: User-friendly interface for viewing purchase history - **Features**: Invoice list, detailed breakdowns, gift context, download functionality - **Authentication**: Required - **Mobile Responsive**: Optimized for tablet and mobile viewing ### Middleware Routing Rules #### Setup Completion Requirements **Location**: `/lib/supabase/middleware.ts` **General Rule**: Dashboard access requires `setup_completed = true` in user profile **Route-Specific Exceptions**: - **Purchase Gift Flow**: `/dashboard/purchase-gift` - Always allowed (gifts shouldn't require setup) - **Family Workspace**: `/families/*` - Allowed for gift purchasers even without setup completion - **Campaign Creation**: `/campaigns/create` - Redirects to dashboard if setup already completed **Business Logic**: ```typescript // Dashboard protection (lines 100-106) if (isDashboard && !setupCompleted && !isPurchaseGift) { // Redirect to campaign creation to complete setup return NextResponse.redirect(new URL('/campaigns/create?step=1', request.url)) } // Family workspace exception (lines 113-118) if (isFamilyWorkspace && !setupCompleted) { // Allow access - gift purchasers need immediate family access return response } ``` --> **Impact on Gift Purchase Flow**: 1. Gift purchasers can complete purchase without initial setup 2. Gift purchasers can access family workspace immediately after purchase 3. Regular dashboard features require completing campaign creation first 4. This ensures gift purchasers get immediate value while encouraging full onboarding ### Business Constants #### Limits - Maximum family members: 10 - Maximum books: 5 per gift purchase (configurable) - Maximum gift message length: 300 characters - Maximum "From" names: 5 - Email validation regex: `/^[^\s@]+@[^\s@]+\.[^\s@]+$/` - Invoice history limit: 50 per API call (paginated) - Invoice number format: YYYYMM-NNNN (auto-generated) #### Default Values - Default delivery date: Current date - Default new member role: 'contributor' - Default book quantity: 1 - Default invoice status: 'paid' (immediate payment) - Default currency: 'USD' - Default transaction type: 'gift_purchase' #### Character Counter Thresholds - Warning color threshold: 90% of limit (270 characters for 300 char limit) - Normal color: Gray (#6B7280) - Warning color: Orange (#EA580C) #### Email Scheduling - Scheduled email time: Midnight UTC on delivery date - Immediate confirmation: Sent regardless of delivery timing - Time zone handling: All scheduled emails use UTC midnight --- *End of Document* **Document Maintained By**: Development Team **Review Schedule**: After each significant flow change **Test Case Repository**: Link to test management system **Related Documents**: API documentation, UI component library docs