Sheet Order Dashboard Development Assistant
An AI assistant for developing and maintaining a radish cake ordering system dashboard with dual API architecture, dynamic API switching, and modern React frontend.
Project Overview
This is a backend management dashboard for a radish cake ordering system with order management, customer management, and analytics. The system uses a separated frontend-backend architecture with React + TypeScript + Tailwind CSS frontend, dual API backends (traditional PHP and modern Cloudflare Workers), and Supabase integration for data storage.
Architecture Understanding
Frontend Stack
**Technology**: React 18 + TypeScript + Vite + Tailwind CSS v4 + shadcn/ui**State Management**: TanStack Query for server state, React Context for authentication**Routing**: React Router v6 (main routes in `src/App.tsx`, admin routes in `src/routes/adminRoutes.tsx`)**UI Components**: shadcn/ui component library with complete Radix UI system**Charts**: Recharts for data visualization**Error Handling**: ErrorBoundary wrapper for the entire applicationBackend Stack
**Traditional API**: PHP API (`api/` directory) - Google Sheets integration, backup solution**Modern API**: Cloudflare Workers (`sheet-order-api/` directory) - Hono framework + OpenAPI**Data Layer**: Supabase integration (`src/integrations/supabase/`)**API Routes**: Modern REST endpoints and PHP-compatible endpointsDynamic API Configuration
The system implements intelligent API endpoint switching:
1. **Production**: Prioritize Cloudflare Workers API (`https://sheet-order-api.ruby7677.workers.dev`)
2. **Local Development**: Try local Workers API (`http://127.0.0.1:5714`), auto-fallback to PHP API on failure
3. **Environment Detection**: Auto-detect based on hostname and port
4. **Fallback Mechanism**: Multi-layer fallback to ensure service availability
Development Workflow
When working on this project, follow these steps:
1. Environment Setup
Verify the development server port is `8080` (configured in package.json and vite.config.ts)Cloudflare Workers local port is `5714` (configured in sheet-order-api/wrangler.jsonc)Check environment variables are properly configured (use `VITE_` prefix for frontend)2. Starting Development Servers
**Frontend Development:**
```bash
npm run dev # Start frontend dev server (port 8080)
npm run dev:debug # Start with debug mode
npm run dev:clean # Clear cache and start (Windows PowerShell)
```
**Cloudflare Workers API:**
```bash
cd sheet-order-api
npm run dev # Start local Workers (port 5714)
npm run deploy # Deploy to Cloudflare (requires credentials)
npm run cf-typegen # Generate TypeScript types
```
3. Understanding Core Services
**API Service Layer (`src/services/`):**
`orderService.ts`: Order management with dynamic API configuration and fallback logic`customerService.ts`: Customer management with phone number normalization and order history`migrationService.ts`: Data migration service`secureApiService.ts`: Secure API call service**Component Architecture (`src/components/`):**
Main page: `src/pages/Index.tsx` - Dual mode interface (order/customer management)Sidebar: `ModernSidebar.tsx` - Mode switching and statistics displayControl panel: `CompactControlPanel.tsx` - Unified filters and action buttonsDetail components: `OrderDetail.tsx`, `CustomerDetail.tsx` - Detailed information display4. Working with APIs
**Key API Endpoints:**
Orders: `/api/orders` (Workers) or `/api/get_orders_from_sheet.php` (PHP)Customers: `/api/customers` (Workers) or `/api/get_customers_from_sheet.php` (PHP)Customer Orders: `/api/customers/orders` (Workers) or `/api/get_customer_orders.php` (PHP)Order Updates: `/api/orders/status`, `/api/orders/payment`, `/api/orders/items`**API Development Strategy:**
Prioritize Cloudflare Workers API over PHP APIImplement automatic detection and fallback for service stabilityManage all API calls through corresponding service filesUse dual-layer caching: TanStack Query (frontend) + Cloudflare KV (Workers)5. Phone Number Handling
**Standardization Process:**
Remove all non-numeric characters using `/[^0-9]/g`Match using last 9 digits for consistency with PHP APIUse standardized phone number as cache key6. Code Quality Standards
**File Size Limits:**
Strictly control single file size to under 500 linesProactively split large files into logically clear small modules**TypeScript Configuration:**
Strict mode enabled with `noImplicitAny`, `noUnusedParameters`, `noUnusedLocals`, `strictNullChecks`Path alias `@/*` points to `./src/*`Separate TypeScript configs for app and Workers**Code Style:**
Follow TypeScript strict mode guidelinesUse consistent naming conventionsImplement proper error handling with ErrorBoundary7. Building and Deployment
```bash
npm run build # Production build
npm run build:dev # Development build
npm run preview # Preview production build
npm run clean # Clear node_modules cache and dist (Windows PowerShell)
npm run lint # ESLint check and fix
```
8. Customer Order History
**Important Implementation Details:**
Data source: Google Sheets "Customer List" worksheet (NOT order sheet)Phone matching: Use last 9 digits standardization logicAPI endpoint: Prioritize `/api/customers/orders`, fallback to `/api/get_customer_orders.php`Cache key: Use last 9 digits of standardized phone number9. Dual Mode Interface
**Order Mode:**
Order management, filtering, statistics, batch operations**Customer Mode:**
Customer management, statistics, order history queriesMode switching controlled via `ModernSidebar` component10. Windows Development Environment
**Command Compatibility:**
Use PowerShell-compatible syntaxUse semicolon (`;`) to separate multiple commandsAvoid `curl` commands, use fetch API or alternativesSupport Windows path format with URI decode error handling**Proxy and CORS Setup:**
Development proxy automatically rewrites `/api` paths to `/sheet-order-dashboard-main/api`CORS setup supports multiple allowed domains and iframe embeddingSafe fallback mechanism for URI decode failuresCritical Implementation Notes
1. **All API calls must go through service layer** - Never call APIs directly from components
2. **Phone number normalization is required** - Always use `/[^0-9]/g` regex and last 9 digits matching
3. **Implement proper error boundaries** - Wrap components with ErrorBoundary
4. **Cache management** - All services provide `clearCache()` function
5. **iframe mode support** - Main page supports iframe embedding with PostMessage API
6. **Environment detection** - Auto-detect production vs local development environment
7. **TypeScript strict mode** - Follow strict type checking guidelines
8. **File size discipline** - Keep files under 500 lines, split when necessary
9. **Customer order data source** - Always use "Customer List" worksheet, not order sheet
10. **Multi-layer fallback** - Implement graceful degradation for all API calls
Testing Your Changes
1. Test both API backends (Workers and PHP) by toggling between production and local development
2. Verify phone number matching works correctly with various formats
3. Test iframe mode if changes affect main page layout
4. Test dual mode interface (order/customer) switching
5. Verify cache invalidation works after data updates
6. Test Windows PowerShell command compatibility
7. Verify CORS and proxy settings for cross-domain requests
Common Troubleshooting
**API connection issues**: Check dynamic API configuration and fallback logic in `orderService.ts`**Phone number matching fails**: Verify normalization using `/[^0-9]/g` and last 9 digits**Build errors**: Check TypeScript strict mode compliance and file size limits**CORS errors**: Verify vite.config.ts proxy and CORS configuration**Workers deployment fails**: Check wrangler.jsonc configuration and Cloudflare credentials**Cache issues**: Call `clearCache()` on affected services