> ## Documentation Index
> Fetch the complete documentation index at: https://docs.adhdsimple.co.uk/llms.txt
> Use this file to discover all available pages before exploring further.

# Mobile Checkout Flow

> Complete user journey through the unified checkout system for both reorder and order completion flows

# Mobile Checkout Flow

## Overview

This document details the complete user journey through the unified checkout system, including both reorder and order completion flows. The checkout system provides a seamless experience for patients to complete their medication orders with integrated payment processing.

## Flow Types

The mobile app supports two distinct checkout flows that converge into a unified checkout system:

### 1. Reorder Flow

* **Purpose**: Create new order with health data collection
* **Entry Point**: Patient selects medications from previous orders
* **Health Data**: Weight, height, blood pressure collection required
* **Order Type**: `reorder_request`

### 2. Order Completion Flow

* **Purpose**: Complete existing prescription from doctor
* **Entry Point**: Patient views prescription from clinical system
* **Delivery Choice**: ADHD Simple delivery vs Paper Script
* **Order Type**: `order_completion`

## Checkout Flow Diagram

```mermaid theme={null}
flowchart TD
    Start([User Starts Checkout]) --> FlowType{Flow Type?}
    
    FlowType -->|Reorder| ReorderStart["👤 USER INPUT<br/>Select Medications<br/>(checkboxes)"]
    ReorderStart --> ReorderHealth["👤 USER INPUT<br/>Enter Health Data<br/>Weight, Height, BP"]
    ReorderHealth --> ReorderDraft["📱 FRONTEND<br/>Create Local Draft<br/>order_type: reorder"]
    
    FlowType -->|Order Completion| OCStart["📱 FRONTEND<br/>View Prescription<br/>from Doctor"]
    OCStart --> OCUserChoice["👤 USER INPUT<br/>Choose Delivery Option<br/>ADHD Simple vs Paper Script"]
    OCUserChoice --> OCDraft["📱 FRONTEND<br/>Create Local Draft<br/>order_type: order_completion<br/>server_order_id: existing_id"]
    
    ReorderDraft --> UnifiedCheckout{"📱 FRONTEND<br/>Enter Unified<br/>Checkout System"}
    OCDraft --> UnifiedCheckout
    
    UnifiedCheckout --> DeliveryAddr["👤 USER INPUT<br/>Select Delivery Address<br/>/checkout/delivery-address<br/>(saved addresses + add new)"]
    DeliveryAddr --> DeliveryPref["👤 USER INPUT<br/>Choose Delivery Method<br/>/checkout/delivery-preference<br/>(standard/express/pickup)"]
    
    DeliveryPref --> PaymentScreen["👤 USER INPUT<br/>Payment Screen<br/>/checkout/payment<br/>(select saved card or add new)"]
    PaymentScreen --> HasSavedCards{"📱 FRONTEND<br/>Has Saved<br/>Payment Methods?"}
    
    HasSavedCards -->|No| SetupIntent["🔧 EDGE FUNCTION<br/>create-setup-intent<br/>Save New Card"]
    SetupIntent --> StripeSetup["👤 USER INPUT<br/>Stripe: Enter Card Details<br/>(card number, expiry, CVC)"]
    StripeSetup --> PaymentReady["📱 FRONTEND<br/>Payment Method Ready"]
    
    HasSavedCards -->|Yes| GetPaymentMethods["🔧 EDGE FUNCTION<br/>get-payment-methods<br/>Load Saved Cards"]
    GetPaymentMethods --> PaymentReady
    
    PaymentReady --> UserConfirmOrder["👤 USER INPUT<br/>Tap 'Complete Order' Button"]
    UserConfirmOrder --> SubmitOrderFunc["🔧 EDGE FUNCTION<br/>submit-order<br/>Create/Update Order"]
    SubmitOrderFunc --> AssignNumber["🔧 EDGE FUNCTION<br/>assign-order-number<br/>Generate Unique Order Number"]
    AssignNumber --> CreateOrderDB[("💾 DATABASE<br/>Create order_requests<br/>+ order_line_items")]
    CreateOrderDB --> ProcessOrder["🔧 EDGE FUNCTION<br/>process-new-order<br/>Extract Health Data"]
    ProcessOrder --> OrderSubmitted["📱 FRONTEND<br/>Order Status: submitted<br/>(loading spinner)"]
    
    OrderSubmitted --> CreatePaymentIntent["🔧 EDGE FUNCTION<br/>create-payment-intent<br/>Generate Stripe Payment"]
    CreatePaymentIntent --> StripePayment["💳 STRIPE<br/>Process Payment<br/>with Saved Method"]
    StripePayment --> PaymentStatus{"💳 STRIPE<br/>Payment<br/>Status?"}
    
    PaymentStatus -->|Success| StripeWebhook["🔧 EDGE FUNCTION<br/>stripe-webhook-handler<br/>payment.succeeded"]
    StripeWebhook --> UpdateOrderPayment["🔧 EDGE FUNCTION<br/>update-order-payment<br/>Status: processing"]
    UpdateOrderPayment --> PaymentComplete["💾 DATABASE<br/>Create order_payments<br/>Record"]
    PaymentComplete --> SuccessScreen["📱 FRONTEND<br/>Order Complete!<br/>/checkout/success<br/>(celebration animation)"]
    
    PaymentStatus -->|Failed| PaymentFailed["📱 FRONTEND<br/>Payment Failed<br/>Order Status: failed<br/>(error message)"]
    PaymentFailed --> RetryPayment["👤 USER INPUT<br/>Retry Payment?<br/>(button choice)"]
    RetryPayment -->|Yes| PaymentScreen
    RetryPayment -->|No| PaymentAbandoned["📱 FRONTEND<br/>Order Abandoned<br/>(return to orders)"]
    
    SuccessScreen --> ClinicalReview["🏥 BACKEND<br/>Clinical System<br/>Receives Order"]
    ClinicalReview --> DoctorApproval["👨‍⚕️ DOCTOR<br/>Reviews and Approves<br/>(external system)"]
    
    classDef userInput fill:#4caf50,stroke:#2e7d32,stroke-width:3px,color:#ffffff
    classDef frontend fill:#2196f3,stroke:#1565c0,stroke-width:2px,color:#ffffff
    classDef edgeFunction fill:#ff5722,stroke:#d32f2f,stroke-width:3px,color:#ffffff
    classDef database fill:#9c27b0,stroke:#6a1b9a,stroke-width:2px,color:#ffffff
    classDef stripe fill:#673ab7,stroke:#4527a0,stroke-width:2px,color:#ffffff
    classDef external fill:#607d8b,stroke:#37474f,stroke-width:2px,color:#ffffff
    
    class ReorderStart,ReorderHealth,OCUserChoice,DeliveryAddr,DeliveryPref,PaymentScreen,StripeSetup,UserConfirmOrder,RetryPayment userInput
    class OCStart,ReorderDraft,OCDraft,UnifiedCheckout,PaymentReady,OrderSubmitted,SuccessScreen,PaymentFailed,PaymentAbandoned frontend
    class SetupIntent,GetPaymentMethods,SubmitOrderFunc,AssignNumber,ProcessOrder,CreatePaymentIntent,StripeWebhook,UpdateOrderPayment edgeFunction
    class CreateOrderDB,PaymentComplete database
    class StripePayment,PaymentStatus stripe
    class ClinicalReview,DoctorApproval external
```

## Screen Flow Details

### Unified Checkout Screens

All checkout flows converge at these shared screens:

#### 1. Delivery Address (`/checkout/delivery-address`)

* **Purpose**: Select or add delivery address
* **Features**:
  * Load saved addresses from patient profile
  * Add new address option
  * Set default address
  * Address validation
* **Integration**: Uses `usePatientAddresses` hook

#### 2. Delivery Preference (`/checkout/delivery-preference`)

* **Purpose**: Choose delivery method
* **Options**:
  * Standard delivery (free for members)
  * Express delivery (additional cost)
  * Pickup locations (where available)
* **Pricing**: Dynamic pricing based on member status

#### 3. Payment (`/checkout/payment`)

* **Purpose**: Select payment method and complete order
* **Features**:
  * Saved payment methods
  * Add new card with Stripe
  * Order summary and total
  * Final confirmation

#### 4. Success (`/checkout/success`)

* **Purpose**: Order confirmation
* **Features**:
  * Celebration animation
  * Order number display
  * Next steps information
  * Return to orders button

## Edge Functions (Backend Processing)

### Payment Functions

* **`create-setup-intent`** - Saves new payment cards securely
* **`get-payment-methods`** - Retrieves saved payment methods
* **`create-payment-intent`** - Creates Stripe payments

### Order Functions

* **`submit-order`** - Creates/updates orders based on order\_type
* **`assign-order-number`** - Generates unique order numbers
* **`process-new-order`** - Extracts and processes health data

### Webhook Functions

* **`stripe-webhook-handler`** - Handles payment events
* **`update-order-payment`** - Updates payment status

## Key Technical Features

### Duplicate Prevention System

The webhook system includes intelligent duplicate prevention logic to handle cases where a prescription is created from a patient app request before the payment webhook processes:

1. **Webhook checks for existing requests** with the same payment intent ID
2. **Detects if prescription already created** (`clinical_decision: "prescription_created"`)
3. **Skips duplicate processing** and updates payment status only
4. **Continues normal flow** for genuinely new requests

This prevents the creation of duplicate patient app requests during the payment processing flow.

### Unified Checkout System

Both reorder and order completion flows converge at `/checkout/` screens to eliminate code duplication while maintaining distinct business logic through the `order_type` parameter.

### Payment Integration

* **Stripe Elements**: Secure card collection
* **Saved Cards**: Reuse payment methods
* **Webhook Processing**: Reliable payment confirmation
* **Error Handling**: Retry logic for failed payments

### Offline Support

* **Draft Orders**: Created locally before submission
* **Sync on Submit**: Orders sync when internet available
* **Local Storage**: Payment methods cached locally

### Error Handling

* **Payment Failures**: Clear error messages with retry options
* **Network Issues**: Graceful degradation with retry mechanisms
* **Validation**: Client and server-side validation

## Order Status Flow

### Customer-Facing Statuses

1. **Waiting for Review** - Request with clinician
2. **Prescription Processing** - Preparing prescription
3. **Approved** - Prescription ready
4. **Awaiting Payment** - Waiting for payment
5. **Processing** - Preparing order
6. **Sent to Pharmacy** - Forwarded to pharmacy
7. **Being Dispensed** - Pharmacy preparing medication
8. **Packed** - Order packed and ready
9. **Shipped** - On the way
10. **Delivered** - Order arrived

## Security Considerations

### Payment Security

* **PCI Compliance**: Stripe handles card data
* **Tokenization**: Cards stored as tokens
* **3D Secure**: Additional authentication when required

### Data Privacy

* **Patient Data**: Encrypted in transit and at rest
* **Address Data**: Isolated per patient
* **Health Data**: HIPAA-compliant handling

### Authentication

* **Session Management**: Secure token-based auth
* **Multi-factor**: Optional 2FA support
* **Rate Limiting**: Protection against abuse

## Performance Optimizations

### Lazy Loading

* Payment forms loaded on demand
* Stripe Elements initialized when needed
* Images optimized and cached

### Caching Strategy

* Payment methods cached locally
* Address data cached with sync
* Order history available offline

### Network Optimization

* Minimal API calls during checkout
* Batch sync operations
* Retry logic for network failures

This checkout flow provides a seamless, secure, and reliable experience for patients to complete their medication orders across both reorder and prescription completion scenarios.
