feat: Implement Payment Gateways backend foundation

 Phase 1 Backend Complete:

📦 PaymentGatewaysProvider.php:
- Read WC gateways from WC()->payment_gateways()
- Transform to clean JSON format
- Categorize: manual/provider/other
- Extract settings: basic/api/advanced
- Check requirements (SSL, extensions)
- Generate webhook URLs
- Respect WC bone structure (WC_Payment_Gateway)

📡 PaymentsController.php:
- GET /woonoow/v1/payments/gateways (list all)
- GET /woonoow/v1/payments/gateways/{id} (single)
- POST /woonoow/v1/payments/gateways/{id} (save settings)
- POST /woonoow/v1/payments/gateways/{id}/toggle (enable/disable)
- Permission checks (manage_woocommerce)
- Error handling with proper HTTP codes
- Response caching (5 min)

🔌 Integration:
- Registered in Api/Routes.php
- Auto-discovers all WC-compliant gateways
- No new hooks - listens to WC structure

📋 Checklist Progress:
- [x] PaymentGatewaysProvider.php
- [x] PaymentsController.php
- [x] REST API registration
- [ ] Frontend components (next)
This commit is contained in:
dwindown
2025-11-05 21:09:49 +07:00
parent f205027c6d
commit 247b2c6b74
4 changed files with 1076 additions and 3 deletions

View File

@@ -1,13 +1,403 @@
# Setup Wizard Design Document
# Settings & Setup Wizard - Implementation Guide
> **Living Document** - Track progress, maintain standards, keep on track
## Overview
A guided onboarding experience for new WooNooW stores, helping merchants configure essential settings in 5-10 minutes.
WooNooW Settings act as a **"better wardrobe"** for WooCommerce configuration - reading WC's bone structure, transforming complexity into simplicity, and enhancing performance.
## Core Philosophy
1. **Read WooCommerce Structure** - Listen to WC's registered entities (gateways, shipping, settings)
2. **Transform & Simplify** - Convert complex WC settings into clean, categorized UI
3. **Enhance Performance** - Direct DB operations where safe (30s → 1-2s)
4. **Respect Ecosystem** - Auto-support WC-compliant addons
5. **No New Hooks** - Listen to WC hooks, don't create parallel system
## Goals
1. **Fast Setup** - Get store operational in < 10 minutes
1. **Fast Setup** - Get store operational in < 10 minutes (wizard)
2. **Smart Defaults** - Pre-configure based on location/industry
3. **Progressive** - Can skip and complete later
4. **Educational** - Teach key concepts without overwhelming
5. **Performance** - Settings save in 1-2s (not 30s like WC)
---
# IMPLEMENTATION CHECKLIST
## Phase 1: Payment Gateways Foundation ⏳
### Backend - Payment Gateways Provider
- [ ] Create `includes/Compat/PaymentGatewaysProvider.php`
- [ ] `get_gateways()` - Read from `WC()->payment_gateways()->payment_gateways()`
- [ ] `categorize_gateway()` - Classify as manual/provider/other
- [ ] `transform_gateway()` - Convert WC format to clean JSON
- [ ] `get_gateway_settings()` - Read gateway form fields
- [ ] `categorize_settings()` - Group into basic/api/advanced
- [ ] `check_requirements()` - Validate PHP extensions, dependencies
- [ ] `get_webhook_url()` - Generate webhook URLs for gateways
- [ ] Handle gateways that don't extend `WC_Payment_Gateway` gracefully
### Backend - REST API Controller
- [ ] Create `includes/API/PaymentsController.php`
- [ ] `GET /woonoow/v1/payments/gateways` - List all gateways
- [ ] `GET /woonoow/v1/payments/gateways/{id}` - Get single gateway
- [ ] `POST /woonoow/v1/payments/gateways/{id}` - Save gateway settings
- [ ] `POST /woonoow/v1/payments/gateways/{id}/toggle` - Enable/disable
- [ ] Permission checks (manage_woocommerce)
- [ ] Error handling with proper HTTP codes
- [ ] Validation using gateway's own validation methods
- [ ] Response caching headers
### Frontend - Generic Form Builder
- [ ] Create `src/components/settings/GenericGatewayForm.tsx`
- [ ] Support field types: text, password, checkbox, select, textarea
- [ ] Support field types: number, email, url
- [ ] Unsupported field types Show link to WC settings
- [ ] Field validation (required, pattern, min, max)
- [ ] Field descriptions and help text
- [ ] Conditional field visibility
- [ ] Multi-page form for 20+ fields (tabs: Basic, API, Advanced)
- [ ] Loading states
- [ ] Error states with helpful messages
- [ ] Success feedback
### Frontend - Update Payments Page
- [ ] Update `src/routes/Settings/Payments.tsx`
- [ ] Replace mock data with API calls
- [ ] Use `useQuery` for fetching gateways
- [ ] Use `useMutation` for saving settings
- [ ] Optimistic updates for enable/disable toggles
- [ ] Refetch on window focus
- [ ] Manual refresh button
- [ ] Loading skeleton while fetching
- [ ] Empty state (no gateways)
- [ ] Error boundary for gateway cards
- [ ] Group by category (manual, providers, other)
### UI Components
- [ ] Create `src/components/settings/GatewayCard.tsx`
- [ ] Show gateway icon, name, description
- [ ] Show enabled/disabled badge
- [ ] Show connected/not connected badge (for providers)
- [ ] Show requirements warning if not met
- [ ] "Manage" button Opens settings modal/page
- [ ] "Enable/Disable" toggle
- [ ] "View in WooCommerce" link for complex gateways
- [ ] Keyboard accessible (tab, enter)
- [ ] Mobile responsive
- [ ] Create `src/components/settings/GatewaySettingsModal.tsx`
- [ ] Modal wrapper for gateway settings
- [ ] Renders GenericGatewayForm or custom component
- [ ] Save/Cancel buttons
- [ ] Dirty state detection
- [ ] Confirm before closing if unsaved changes
- [ ] Create `src/components/settings/WebhookHelper.tsx`
- [ ] Display webhook URL
- [ ] Copy to clipboard button
- [ ] Instructions for common gateways (Stripe, PayPal)
- [ ] Test webhook button (if gateway supports)
### Testing & Quality
- [ ] ESLint: 0 errors, 0 warnings
- [ ] TypeScript: strict mode passes
- [ ] Test with WooCommerce not installed
- [ ] Test with no gateways registered
- [ ] Test with 1 gateway
- [ ] Test with 10+ gateways
- [ ] Test enable/disable toggle
- [ ] Test save settings (valid data)
- [ ] Test save settings (invalid data)
- [ ] Test with Stripe gateway installed
- [ ] Test with PayPal gateway installed
- [ ] Test with custom gateway
- [ ] Test in all 3 admin modes (normal, fullscreen, standalone)
- [ ] Test keyboard navigation
- [ ] Test mobile responsive
- [ ] Performance: API response < 500ms
- [ ] Performance: Settings save < 2s
---
## Phase 2: Custom Gateway UIs ⏳
### Stripe Custom UI
- [ ] Create `src/components/settings/gateways/StripeSettings.tsx`
- [ ] Categorized tabs: Basic, API Keys, Advanced
- [ ] Live/Test mode toggle with visual indicator
- [ ] API key validation (format check)
- [ ] Webhook URL helper
- [ ] Test connection button
- [ ] Supported payment methods checklist
- [ ] 3D Secure settings
- [ ] Statement descriptor preview
### PayPal Custom UI
- [ ] Create `src/components/settings/gateways/PayPalSettings.tsx`
- [ ] Categorized tabs: Basic, API, Advanced
- [ ] Sandbox/Live mode toggle
- [ ] Client ID & Secret fields
- [ ] Webhook URL helper
- [ ] Test connection button
- [ ] PayPal button customization preview
- [ ] Invoice prefix settings
### Gateway Registry
- [ ] Create `src/lib/gatewayRegistry.ts`
- [ ] Map gateway IDs to custom components
- [ ] Fallback to GenericGatewayForm
- [ ] Feature flags for gradual rollout
---
## Phase 3: Shipping Methods ⏳
### Backend - Shipping Provider
- [ ] Create `includes/Compat/ShippingMethodsProvider.php`
- [ ] `get_zones()` - Read from `WC_Shipping_Zones::get_zones()`
- [ ] `get_zone_methods()` - Get methods for each zone
- [ ] `transform_zone()` - Convert WC format to clean JSON
- [ ] `transform_method()` - Convert method settings
- [ ] `get_available_methods()` - List all registered shipping methods
- [ ] Handle methods that don't extend `WC_Shipping_Method` gracefully
### Backend - REST API Controller
- [ ] Create `includes/API/ShippingController.php`
- [ ] `GET /woonoow/v1/shipping/zones` - List all zones
- [ ] `GET /woonoow/v1/shipping/zones/{id}` - Get single zone
- [ ] `POST /woonoow/v1/shipping/zones/{id}/methods/{method_id}` - Save method
- [ ] `POST /woonoow/v1/shipping/zones/{id}/methods/{method_id}/toggle` - Enable/disable
- [ ] Permission checks
- [ ] Error handling
- [ ] Validation
### Frontend - Update Shipping Page
- [ ] Update `src/routes/Settings/Shipping.tsx`
- [ ] Replace mock data with API calls
- [ ] Use `useQuery` for fetching zones
- [ ] Use `useMutation` for saving
- [ ] Optimistic updates
- [ ] Refetch on focus
- [ ] Loading/error states
### UI Components
- [ ] Create `src/components/settings/ShippingZoneCard.tsx`
- [ ] Create `src/components/settings/ShippingMethodCard.tsx`
- [ ] Create `src/components/settings/GenericShippingForm.tsx`
---
## Phase 4: Store Settings ⏳
### Backend - Store Settings Provider
- [ ] Create `includes/Compat/StoreSettingsProvider.php`
- [ ] Read WC general settings
- [ ] Read WC product settings
- [ ] Transform to clean format
- [ ] Group by category
### Backend - REST API
- [ ] Create `includes/API/StoreController.php`
- [ ] `GET /woonoow/v1/store/settings` - Get all store settings
- [ ] `POST /woonoow/v1/store/settings` - Save settings
- [ ] Direct DB operations for performance
- [ ] Validation
### Frontend - Update Store Page
- [ ] Update `src/routes/Settings/Store.tsx`
- [ ] Replace mock data with API calls
- [ ] Currency selector with live preview
- [ ] Country/timezone auto-detection
- [ ] Address autocomplete
- [ ] Save performance < 2s
---
## Phase 5: Setup Wizard ⏳
### Wizard Flow (5 Steps)
#### Step 1: Store Basics
- [ ] Store name, email, country (required)
- [ ] Auto-detect currency, timezone
- [ ] Industry selector (optional)
- [ ] Save to WC general settings
#### Step 2: Payments
- [ ] Show recognized gateways if installed
- [ ] Enable manual methods (Bank Transfer, COD)
- [ ] Minimal fields (enable/disable only)
- [ ] Link to full settings for advanced config
#### Step 3: Shipping
- [ ] Simple flat rate setup
- [ ] Domestic/International zones
- [ ] Free shipping threshold
- [ ] Link to full settings
#### Step 4: Taxes
- [ ] Auto-calculate toggle
- [ ] Tax rate from country
- [ ] Manual rate option
- [ ] Can skip
#### Step 5: First Product
- [ ] Create sample product
- [ ] Import CSV
- [ ] Skip option
### Wizard Components
- [ ] Create `src/routes/Setup/index.tsx`
- [ ] Create `src/routes/Setup/StepProgress.tsx`
- [ ] Create `src/routes/Setup/steps/StoreBasics.tsx`
- [ ] Create `src/routes/Setup/steps/Payments.tsx`
- [ ] Create `src/routes/Setup/steps/Shipping.tsx`
- [ ] Create `src/routes/Setup/steps/Taxes.tsx`
- [ ] Create `src/routes/Setup/steps/FirstProduct.tsx`
- [ ] Create `src/routes/Setup/Complete.tsx`
### Wizard State
- [ ] Create Zustand store for wizard state
- [ ] Save progress at each step
- [ ] Resume from last step
- [ ] Dashboard banner to resume incomplete setup
---
## Phase 6: Polish & Enhancement ⏳
### Error Handling
- [ ] Error boundaries for each gateway/method card
- [ ] Fallback to WC settings on error
- [ ] Helpful error messages
- [ ] Retry mechanisms
### Performance
- [ ] Monitor API response times
- [ ] Cache gateway/method lists (5 min stale time)
- [ ] Optimistic updates for toggles
- [ ] Direct DB writes where safe
- [ ] Lazy load custom gateway components
### Accessibility
- [ ] Keyboard navigation (tab, enter, escape)
- [ ] ARIA labels and roles
- [ ] Focus management in modals
- [ ] Screen reader announcements
- [ ] Color contrast compliance
### Documentation
- [ ] Inline help text for all fields
- [ ] Tooltips for complex options
- [ ] Link to docs for advanced features
- [ ] Video tutorials (future)
### Analytics
- [ ] Track gateway configuration time
- [ ] Track wizard completion rate
- [ ] Track which gateways are used
- [ ] Track settings save performance
---
# TECHNICAL SPECIFICATIONS
## API Response Format
### Payment Gateway
```json
{
"id": "stripe",
"title": "Stripe Payments",
"description": "Accept Visa, Mastercard, Amex",
"enabled": true,
"type": "provider",
"icon": "credit-card",
"connected": true,
"test_mode": false,
"requirements": {
"met": true,
"missing": []
},
"settings": {
"basic": [...],
"api": [...],
"advanced": [...]
},
"webhook_url": "https://example.com/wc-api/stripe",
"has_custom_ui": true,
"wc_settings_url": "admin.php?page=wc-settings&tab=checkout&section=stripe"
}
```
### Shipping Zone
```json
{
"id": 1,
"name": "Domestic",
"regions": ["ID"],
"methods": [
{
"id": "flat_rate:1",
"instance_id": 1,
"title": "Flat Rate",
"enabled": true,
"method_id": "flat_rate",
"settings": {...}
}
]
}
```
## Performance Targets
| Operation | Target | Current WC |
|-----------|--------|------------|
| Load gateways | < 500ms | ~2s |
| Save gateway settings | < 2s | ~30s |
| Load shipping zones | < 500ms | ~3s |
| Save shipping method | < 2s | ~30s |
| Wizard completion | < 10min | N/A |
## Browser Support
- Chrome 90+
- Firefox 88+
- Safari 14+
- Edge 90+
- Mobile Safari 14+
- Chrome Android 90+
---
# COMPATIBILITY MATRIX
## Supported Payment Gateways
| Gateway | Type | Custom UI | Status |
|---------|------|-----------|--------|
| Bank Transfer (BACS) | Manual | Generic | Built-in |
| Cash on Delivery | Manual | Generic | Built-in |
| Check Payments | Manual | Generic | Built-in |
| Stripe | Provider | Custom | 🔄 Phase 2 |
| PayPal | Provider | Custom | 🔄 Phase 2 |
| Square | Provider | Generic | Auto-support |
| Authorize.net | Provider | Generic | Auto-support |
| Other WC-compliant | Any | Generic | Auto-support |
## Supported Shipping Methods
| Method | Custom UI | Status |
|--------|-----------|--------|
| Flat Rate | Generic | Built-in |
| Free Shipping | Generic | Built-in |
| Local Pickup | Generic | Built-in |
| Table Rate | Generic | Auto-support |
| Other WC-compliant | Generic | Auto-support |
---
# WIZARD FLOW DETAILS
---