);
}
```
**Rules for CRUD Pages**
| Page Type | Contextual Header | Page Header |
|-----------|-------------------|-------------|
| **List** | None (list page) | Filters, Search |
| **Detail** | [Back] Title [Edit] | Print, Invoice, Label |
| **New** | [Back] Title [Create] | None |
| **Edit** | [Back] Title [Save] | None |
**Form Submit Pattern**
For New/Edit pages, move submit button to contextual header:
```typescript
// Use formRef to trigger submit from header
const formRef = useRef(null);
const actions = (
);
```
**Best Practices**
1. **No Duplication** - If action is in contextual header, remove from page body
2. **Mobile First** - Contextual header shows essential actions only
3. **Desktop Enhancement** - Extra actions in page header (desktop only)
4. **Consistent Pattern** - All CRUD pages follow same structure
5. **Loading States** - Buttons show loading state during mutations
**Files**
- `admin-spa/src/contexts/PageHeaderContext.tsx` - Context provider
- `admin-spa/src/hooks/usePageHeader.ts` - Hook for setting headers
- `admin-spa/src/components/PageHeader.tsx` - Header component
### 5.8 Error Handling & User Notifications
WooNooW implements a centralized, user-friendly error handling system that ensures consistent UX across all features.
**Core Principles**
1. **Never expose technical details** to end users (no "API 500", stack traces, or raw error codes)
2. **Use appropriate notification types** based on context
3. **Provide actionable feedback** with clear next steps
4. **Maintain consistency** across all pages and features
**Notification Types**
| Context | Component | Use Case | Example |
|---------|-----------|----------|---------|
| **Page Load Errors** | `` | Query failures, data fetch errors | "Failed to load orders" with retry button |
| **Action Errors** | `toast.error()` | Mutation failures, form submissions | "Failed to create order. Please check all required fields." |
| **Action Success** | `toast.success()` | Successful mutations | "Order created successfully" |
| **Inline Validation** | `` | Form field errors | "Email address is required" |
**Implementation**
```typescript
// For mutations (create, update, delete)
import { showErrorToast, showSuccessToast } from '@/lib/errorHandling';
const mutation = useMutation({
mutationFn: OrdersApi.create,
onSuccess: (data) => {
showSuccessToast('Order created successfully', `Order #${data.number} created`);
},
onError: (error) => {
showErrorToast(error); // Automatically extracts user-friendly message
}
});
// For queries (page loads)
import { ErrorCard } from '@/components/ErrorCard';
import { getPageLoadErrorMessage } from '@/lib/errorHandling';
if (query.isError) {
return query.refetch()}
/>;
}
```
**Error Message Mapping**
Backend errors are mapped to user-friendly messages in `lib/errorHandling.ts`:
```typescript
const friendlyMessages = {
'no_items': 'Please add at least one product to the order',
'create_failed': 'Failed to create order. Please check all required fields.',
'update_failed': 'Failed to update order. Please check all fields.',
'not_found': 'The requested item was not found',
'forbidden': 'You do not have permission to perform this action',
};
```
**Toast Configuration**
- **Position:** Bottom-right
- **Duration:** 4s (success), 6s (errors)
- **Theme:** Light mode with colored backgrounds
- **Colors:** Green (success), Red (error), Amber (warning), Blue (info)
**Files**
- `admin-spa/src/lib/errorHandling.ts` β Centralized error utilities
- `admin-spa/src/components/ErrorCard.tsx` β Page load error component
- `admin-spa/src/components/ui/sonner.tsx` β Toast configuration
### 5.9 Data Validation & Required Fields
WooNooW enforces strict validation rules to ensure data integrity and provide clear feedback to users.
**Order Creation Validation**
All orders must include:
| Field | Requirement | Error Message |
|-------|-------------|---------------|
| **Products** | At least 1 product | "At least one product is required" |
| **Billing First Name** | Required | "Billing first name is required" |
| **Billing Last Name** | Required | "Billing last name is required" |
| **Billing Email** | Required & valid format | "Billing email is required" / "Billing email is not valid" |
| **Billing Address** | Required | "Billing address is required" |
| **Billing City** | Required | "Billing city is required" |
| **Billing Postcode** | Required | "Billing postcode is required" |
| **Billing Country** | Required | "Billing country is required" |
**Backend Validation Response**
When validation fails, the API returns:
```json
{
"error": "validation_failed",
"message": "Please complete all required fields",
"fields": [
"Billing first name is required",
"Billing email is required",
"Billing address is required"
]
}
```
**Frontend Display**
The error handling utility automatically formats field errors as a bulleted list:
```
β Please complete all required fields
β’ Billing first name is required
β’ Billing email is required
β’ Billing address is required
β’ Billing city is required
β’ Billing postcode is required
```
Each field error appears as a bullet point on its own line, making it easy for users to scan and see exactly what needs to be fixed.
**Implementation Location**
- Backend validation: `includes/Api/OrdersController.php` create() method
- Frontend handling: `admin-spa/src/lib/errorHandling.ts` getErrorMessage()
### 5.10 Internationalization (i18n)
WooNooW follows WordPress translation standards to ensure all user-facing strings are translatable.
**Text Domain:** `woonoow`
**Backend (PHP)**
Use WordPress translation functions:
```php
// Simple translation
__( 'Billing first name', 'woonoow' )
// Translation with sprintf
sprintf( __( '%s is required', 'woonoow' ), $field_label )
// Translators comment for context
/* translators: %s: field label */
sprintf( __( '%s is required', 'woonoow' ), $label )
```
**Frontend (TypeScript/React)**
Use the i18n utility wrapper:
```typescript
import { __, sprintf } from '@/lib/i18n';
// Simple translation
__('Failed to load data')
// Translation with sprintf (placeholders)
sprintf(__('Order #%s created'), orderNumber)
sprintf(__('Edit Order #%s'), orderId)
// In components
{sprintf(__('Order #%s'), order.number)}
// In error messages
const title = __('Please complete all required fields');
const message = sprintf(__('Order #%s has been created'), data.number);
```
**Translation Files**
- Backend strings: Extracted to `languages/woonoow.pot`
- Frontend strings: Loaded via `wp.i18n` (WordPress handles this)
- Translation utilities: `admin-spa/src/lib/i18n.ts`
**Best Practices**
1. **Never hardcode user-facing strings** - Always use translation functions
2. **Use translators comments** for context when using placeholders
3. **Keep strings simple** - Avoid complex concatenation
4. **Test in English first** - Ensure strings make sense before translation
---
## 5.11 Loading States
WooNooW provides a **consistent loading UI system** across the application to ensure a polished user experience.
**Component:** `admin-spa/src/components/LoadingState.tsx`
### Loading Components
**1. LoadingState (Default)**a
```typescript
import { LoadingState } from '@/components/LoadingState';
// Default loading
// Custom message
// Different sizes
// default
// Full screen overlay
```
**2. PageLoadingState**
```typescript
import { PageLoadingState } from '@/components/LoadingState';
// For full page loads
if (isLoading) {
return ;
}
```
**3. InlineLoadingState**
```typescript
import { InlineLoadingState } from '@/components/LoadingState';
// For inline loading within components
{isLoading && }
```
**4. CardLoadingSkeleton**
```typescript
import { CardLoadingSkeleton } from '@/components/LoadingState';
// For loading card content
{isLoading && }
```
**5. TableLoadingSkeleton**
```typescript
import { TableLoadingSkeleton } from '@/components/LoadingState';
// For loading table rows
{isLoading && }
```
### Usage Guidelines
**Page-Level Loading:**
```typescript
// β Good - Use PageLoadingState for full page loads
if (orderQ.isLoading || countriesQ.isLoading) {
return ;
}
// β Bad - Don't use plain text
if (isLoading) {
return
Loading...
;
}
```
**Inline Loading:**
```typescript
// β Good - Use InlineLoadingState for partial loads
{q.isLoading && }
// β Bad - Don't use custom spinners
{q.isLoading &&
Loading...
}
```
**Table Loading:**
```typescript
// β Good - Use TableLoadingSkeleton for tables
{q.isLoading && }
// β Bad - Don't show empty state while loading
{q.isLoading &&
Loading data...
}
```
### Best Practices
1. **Always use i18n** - All loading messages must be translatable
```typescript
```
2. **Be specific** - Use descriptive messages
```typescript
// β Good
// β Bad
```
3. **Choose appropriate size** - Match the context
- `sm` - Inline, buttons, small components
- `md` - Default, cards, sections
- `lg` - Full page, important actions
4. **Use skeletons for lists** - Better UX than spinners
```typescript
{isLoading ? :
}
```
5. **Responsive design** - Loading states work on all screen sizes
- Mobile: Optimized spacing and sizing
- Desktop: Full layout preserved
### Pattern Examples
**Order Edit Page:**
```typescript
export default function OrdersEdit() {
const orderQ = useQuery({ ... });
if (orderQ.isLoading) {
return ;
}
return ;
}
```
**Order Detail Page:**
```typescript
export default function OrderDetail() {
const q = useQuery({ ... });
return (
);
}
```
---
## 6. π Addon Development Standards
### 6.1 Addon Injection System
WooNooW provides a **filter-based addon injection system** that allows third-party plugins to integrate seamlessly with the SPA without modifying core files.
**Core Principle:** All modules that can accept external injection MUST provide filter hooks following the standard naming convention.
### 6.2 Hook Naming Convention
All WooNooW hooks follow this structure:
```
woonoow/{category}/{action}[/{subcategory}]
```
**Examples:**
- `woonoow/addon_registry` - Register addon metadata
- `woonoow/spa_routes` - Register SPA routes
- `woonoow/nav_tree` - Modify navigation tree
- `woonoow/nav_tree/products/children` - Inject into Products submenu
- `woonoow/dashboard/widgets` - Add dashboard widgets (future)
- `woonoow/order/detail/panels` - Add order detail panels (future)
**Rules:**
1. Always prefix with `woonoow/`
2. Use lowercase with underscores
3. Use singular nouns for registries (`addon_registry`, not `addons_registry`)
4. Use hierarchical structure for nested items
5. Use descriptive names that indicate purpose
### 6.3 Filter Template Pattern
When creating a new module that accepts external injection, follow this template:
#### **Backend (PHP)**
```php
'my-item',
* 'label' => 'My Item',
* 'value' => 'something',
* ];
* return $data;
* });
*/
$data = apply_filters('woonoow/my_module/items', $data);
// Validate and store
$validated = self::validate_items($data);
update_option(self::OPTION_KEY, [
'version' => self::VERSION,
'items' => $validated,
'updated' => time(),
], false);
}
private static function validate_items(array $items): array {
// Validation logic
return $items;
}
public static function get_items(): array {
$data = get_option(self::OPTION_KEY, []);
return $data['items'] ?? [];
}
public static function flush() {
delete_option(self::OPTION_KEY);
}
public static function get_frontend_data(): array {
// Return sanitized data for frontend
return self::get_items();
}
}
```
#### **Expose to Frontend (Assets.php)**
```php
// In localize_runtime() method
wp_localize_script($handle, 'WNW_MY_MODULE', MyModuleRegistry::get_frontend_data());
wp_add_inline_script($handle, 'window.WNW_MY_MODULE = window.WNW_MY_MODULE || WNW_MY_MODULE;', 'after');
```
#### **Frontend (TypeScript)**
```typescript
// Read from window
const moduleData = (window as any).WNW_MY_MODULE || [];
// Use in component
function MyComponent() {
const items = (window as any).WNW_MY_MODULE || [];
return (
{items.map(item => (
{item.label}
))}
);
}
```
### 6.4 Documentation Requirements
When adding a new filter hook, you MUST:
1. **Add to Hook Registry** (see section 6.5)
2. **Document in code** with PHPDoc
3. **Add example** in ADDON_INJECTION_GUIDE.md
4. **Update** ADDONS_ADMIN_UI_REQUIREMENTS.md
### 6.5 Hook Registry
See `HOOKS_REGISTRY.md` for complete list of available hooks and filters.
### 6.6 Non-React Addon Development
**Question:** Can developers build addons without React?
**Answer:** **YES!** WooNooW supports multiple addon approaches:
#### **Approach 1: PHP + HTML/CSS/JS (No React)**
Traditional WordPress addon development works perfectly:
```php
'my-addon',
'name' => 'My Addon',
'version' => '1.0.0',
];
return $addons;
});
// Add navigation item that links to classic admin page
add_filter('woonoow/nav_tree', function($tree) {
$tree[] = [
'key' => 'my-addon',
'label' => 'My Addon',
'path' => '/my-addon-classic', // Will redirect to admin page
'icon' => 'puzzle',
'children' => [],
];
return $tree;
});
// Register classic admin page
add_action('admin_menu', function() {
add_menu_page(
'My Addon',
'My Addon',
'manage_options',
'my-addon-page',
'my_addon_render_page',
'dashicons-admin-generic',
30
);
});
function my_addon_render_page() {
?>
My Traditional Addon
Built with PHP, HTML, CSS, and vanilla JS!
My Addon
Built with vanilla JavaScript!
`;
// Add event listeners
setTimeout(() => {
const button = container.querySelector('#my-button');
button.addEventListener('click', () => {
alert('Vanilla JS works!');
});
}, 0);
return container;
}
```
**This approach:**
- β Integrates with SPA
- β No React required
- β Can use Tailwind classes
- β Can fetch from REST API
- β οΈ Must return DOM element
- β οΈ Manual state management
#### **Approach 3: React Component (Full SPA)**
For developers comfortable with React:
```typescript
// dist/MyAddon.tsx - React component
import React from 'react';
export default function MyAddonPage() {
const [count, setCount] = React.useState(0);
return (
My Addon
Built with React!
);
}
```
**This approach:**
- β Full SPA integration
- β React state management
- β Can use React Query
- β Can use WooNooW components
- β Best UX
- β οΈ Requires React knowledge
### 6.7 Addon Development Checklist
When creating a module that accepts addons:
- [ ] Create Registry class (e.g., `MyModuleRegistry.php`)
- [ ] Add filter hook with `woonoow/` prefix
- [ ] Document filter in PHPDoc with example
- [ ] Expose data to frontend via `Assets.php`
- [ ] Add to `HOOKS_REGISTRY.md`
- [ ] Add example to `ADDON_INJECTION_GUIDE.md`
- [ ] Test with example addon
- [ ] Update `ADDONS_ADMIN_UI_REQUIREMENTS.md`
### 6.8 Orders Module as Reference
The **Orders module** is the reference implementation:
- No external injection (by design)
- Clean route structure
- Type-safe components
- Proper error handling
- Mobile responsive
- i18n complete
Use Orders as the template for building new core modules.
---
## 7. π¨ Admin Interface Modes
WooNooW provides **three distinct admin interface modes** to accommodate different workflows and user preferences:
### **1. Normal Mode (wp-admin)**
- **Access:** `/wp-admin/admin.php?page=woonoow`
- **Layout:** Traditional WordPress admin with WooNooW SPA in content area
- **Use Case:** Standard WordPress admin workflow
- **Features:**
- WordPress admin bar and sidebar visible
- Full WordPress admin functionality
- WooNooW SPA integrated seamlessly
- Settings submenu hidden (use WooCommerce settings)
- **When to use:** When you need access to other WordPress admin features alongside WooNooW
### **2. Fullscreen Mode**
- **Access:** Toggle button in WooNooW header
- **Layout:** WooNooW SPA only (no WordPress chrome)
- **Use Case:** Focused work sessions, order processing
- **Features:**
- Maximized workspace
- Distraction-free interface
- All WooNooW features accessible
- Settings submenu hidden
- **When to use:** When you want to focus exclusively on WooNooW tasks
### **3. Standalone Mode** β¨
- **Access:** `https://yoursite.com/admin`
- **Layout:** Complete standalone application with custom login
- **Use Case:** Quick daily access, mobile-friendly, bookmark-able
- **Features:**
- Custom login page (`/admin#/login`)
- WordPress authentication integration
- Settings submenu visible (SPA settings pages)
- "WordPress" button to access wp-admin
- "Logout" button in header
- Admin bar link in wp-admin to standalone
- Session persistence across modes
- **When to use:** As your primary WooNooW interface, especially on mobile or for quick access
### **Mode Switching**
- **From wp-admin to Standalone:** Click "WooNooW" in admin bar
- **From Standalone to wp-admin:** Click "WordPress" button in header
- **To Fullscreen:** Click fullscreen toggle in any mode
- **Session persistence:** Login state is shared across all modes
### **Settings Submenu Behavior**
- **Normal Mode:** No settings submenu (use WooCommerce settings in wp-admin)
- **Fullscreen Mode:** No settings submenu
- **Standalone Mode:** Full settings submenu visible with SPA pages
**Implementation:** Settings submenu uses dynamic getter in `admin-spa/src/nav/tree.ts`:
```typescript
get children() {
const isStandalone = (window as any).WNW_CONFIG?.standaloneMode;
if (!isStandalone) return [];
return [ /* settings items */ ];
}
```
---
## 8. π€ AI Agent Collaboration Rules
When using an AI IDE agent (ChatGPT, Claude, etc.):
### Step 1: Context Injection
Always load:
- `README.md`
- `PROJECT_SOP.md`
- The specific file(s) being edited
### Step 2: Editing Rules
1. All AI edits must be **idempotent** β never break structure or naming conventions.
2. Always follow PSRβ12 PHP standard and React code conventions.
3. When unsure about a design decision, **refer back to this S.O.P.** before guessing.
4. New files must be registered in the correct namespace path.
5. When editing React components, ensure build compatibility with Vite.
### Step 3: Communication
AI agents must:
- Explain each patch clearly.
- Never autoβremove code without reason.
- Maintain English for all code comments, Markdown for docs.
---
## 7. π¦ Release Steps
1. Run all builds:
```bash
npm run build && npm run pack
```
2. Test in LocalWP with a sample Woo store.
3. Validate HPOS compatibility and order creation flow.
4. Push final `woonoow.zip` to release channel (Sejoli, member.dwindi.com, or manual upload).
5. Tag version using semantic versioning (e.g. `v0.2.0-beta`).
---
## 8. π§ Decision Hierarchy
| Category | Decision Reference |
|-----------|--------------------|
| Code Style | Follow PSRβ12 (PHP) & Airbnb/React rules |
| Architecture | PSRβ4 + modular single responsibility |
| UI/UX | Modern minimal style, standardized using Tailwind + Shadcn UI. Recharts for data visualization. |
| Icons | Use lucide-react via npm i lucide-react. Icons should match Shadcn UI guidelines. Always import directly (e.g. import { Package } from 'lucide-react'). Maintain consistent size (16β20px) and stroke width (1.5px). Use Tailwind classes for color states. |
| **Navigation Pattern** | **CRUD pages MUST follow consistent back button navigation: New Order: Index β New. Edit Order: Index β Detail β Edit. Back button always goes to parent page, not index. Use ArrowLeft icon from lucide-react. Toolbar format: `