# Frontend Development Plan - XYZ POS System

## 📋 Overview

This document outlines the frontend architecture and development plan for the XYZ POS (Point of Sale) system - a comprehensive clothing manufacturing and retail management system.

**Technology Stack:**
- **Framework:** Next.js 16.1.1 (App Router)
- **React:** 19.2.3
- **Styling:** Tailwind CSS v4
- **State Management:** (To be decided - Context API / Zustand / Redux)
- **API Client:** Axios / Fetch
- **Form Handling:** React Hook Form
- **Date Handling:** date-fns / Day.js

---

## 🏗️ Project Structure

```
client/
├── app/                          # Next.js App Router
│   ├── (auth)/                   # Auth route group
│   │   ├── login/
│   │   └── setup/
│   ├── (dashboard)/              # Protected dashboard routes
│   │   ├── layout.js            # Dashboard layout with sidebar
│   │   ├── page.js              # Dashboard home
│   │   ├── pos/                  # Point of Sale
│   │   │   └── page.js
│   │   ├── products/             # Product management
│   │   │   ├── page.js          # Product list
│   │   │   ├── new/
│   │   │   ├── [id]/
│   │   │   └── [id]/edit
│   │   ├── inventory/            # Inventory management
│   │   │   ├── page.js
│   │   │   ├── movements/
│   │   │   └── items/
│   │   ├── sales/                # Sales management
│   │   │   ├── page.js
│   │   │   └── [id]/
│   │   ├── customers/            # Customer management
│   │   ├── categories/           # Category management
│   │   ├── pricing/              # Pricing management
│   │   ├── taxes/                # Tax management
│   │   ├── discounts/            # Discount management
│   │   ├── procurement/          # Procurement
│   │   │   ├── vendors/
│   │   │   ├── purchase-orders/
│   │   │   └── grns/
│   │   ├── production/           # Production management
│   │   │   ├── boms/
│   │   │   └── orders/
│   │   ├── returns/              # Returns management
│   │   ├── shifts/               # Shift & cash management
│   │   └── reports/              # Reports & analytics
│   ├── api/                      # API routes (if needed)
│   ├── layout.js                 # Root layout
│   ├── page.js                   # Landing/redirect page
│   └── globals.css
├── components/                   # Reusable components
│   ├── ui/                       # Base UI components
│   │   ├── Button.jsx
│   │   ├── Input.jsx
│   │   ├── Select.jsx
│   │   ├── Table.jsx
│   │   ├── Modal.jsx
│   │   ├── Card.jsx
│   │   ├── Badge.jsx
│   │   └── ...
│   ├── layout/                   # Layout components
│   │   ├── Sidebar.jsx
│   │   ├── Header.jsx
│   │   ├── Navbar.jsx
│   │   └── Footer.jsx
│   ├── forms/                    # Form components
│   │   ├── ProductForm.jsx
│   │   ├── SaleForm.jsx
│   │   ├── CustomerForm.jsx
│   │   └── ...
│   ├── features/                 # Feature-specific components
│   │   ├── pos/
│   │   │   ├── ProductGrid.jsx
│   │   │   ├── Cart.jsx
│   │   │   ├── PaymentModal.jsx
│   │   │   └── Receipt.jsx
│   │   ├── products/
│   │   ├── inventory/
│   │   └── ...
│   └── charts/                   # Chart components
│       ├── SalesChart.jsx
│       └── InventoryChart.jsx
├── lib/                          # Utilities & helpers
│   ├── api/                      # API client
│   │   ├── client.js            # Axios instance
│   │   ├── auth.js              # Auth endpoints
│   │   ├── products.js          # Product endpoints
│   │   ├── sales.js             # Sales endpoints
│   │   └── ...
│   ├── utils/                    # Utility functions
│   │   ├── format.js            # Currency, date formatting
│   │   ├── validation.js        # Client-side validation
│   │   └── constants.js         # Constants
│   └── hooks/                    # Custom React hooks
│       ├── useAuth.js
│       ├── useApi.js
│       └── ...
├── contexts/                     # React Contexts
│   ├── AuthContext.jsx
│   ├── CartContext.jsx
│   └── ...
├── types/                        # TypeScript types (if using TS)
│   └── index.d.ts
├── public/                       # Static assets
│   ├── images/
│   └── icons/
├── styles/                       # Additional styles
│   └── components.css
└── config/                       # Configuration
    ├── api.js                    # API base URL
    └── constants.js
```

---

## 🎨 Design System

### Color Palette
- **Primary:** (To be defined - clothing brand colors)
- **Secondary:** (To be defined)
- **Success:** Green
- **Warning:** Yellow/Orange
- **Error:** Red
- **Neutral:** Gray scale

### Typography
- **Font:** Geist (already configured)
- **Headings:** Bold, varying sizes
- **Body:** Regular weight

### Components
- Consistent button styles
- Form inputs with validation states
- Data tables with sorting/pagination
- Modals for confirmations/details
- Cards for product display
- Badges for status indicators

---

## 📱 Key Features & Pages

### 1. Authentication (`/login`, `/setup`)
- **Login Page:**
  - Username/Password login
  - PIN code quick login (for cashiers)
  - Remember me option
  - Forgot password (future)

- **Setup Page:**
  - Initial system setup
  - Create admin user

### 2. Dashboard (`/`)
- Overview cards:
  - Today's sales
  - Total inventory value
  - Low stock alerts
  - Pending orders
- Quick actions
- Recent activity
- Sales charts (daily/weekly/monthly)

### 3. Point of Sale (`/pos`)
**Core POS Features:**
- Product search/scan
- Product grid/categories
- Shopping cart
- Customer selection (optional)
- Discount application
- Tax calculation
- Payment processing (Cash, Paystack, Mobile Money)
- Receipt generation
- KRA eTIMS fiscalization

**UI Layout:**
- Left: Product categories/search
- Center: Product grid
- Right: Cart & checkout panel

### 4. Products (`/products`)
- Product list (table view)
- Search & filters
- Create/Edit product
- Product variants management
- Product images
- Bulk operations
- Categories assignment

### 5. Inventory (`/inventory`)
- Inventory list
- Quantity tracking
- UID-based items (barcode scanning)
- Inventory movements (audit trail)
- Low stock alerts
- Adjustments
- Reorder levels

### 6. Sales (`/sales`)
- Sales list
- Sale details
- Sale cancellation
- Receipt reprint
- Filters (date, customer, status)

### 7. Customers (`/customers`)
- Customer list
- Create/Edit customer
- Customer details
- Customer type (B2B/B2C)
- Credit limits (B2B)
- Purchase history

### 8. Categories (`/categories`)
- Category tree (hierarchical)
- Create/Edit category
- Category assignment to products
- Drag & drop ordering (future)

### 9. Pricing (`/pricing`)
- Price lists management
- Product pricing
- Customer-specific pricing
- Price history

### 10. Taxes (`/taxes`)
- Tax rates management
- Tax categories
- Tax exemptions (customer/product)
- Tax calculation preview

### 11. Discounts (`/discounts`)
- Discount list
- Create discount (percentage/fixed)
- Discount rules
- Discount codes

### 12. Procurement (`/procurement`)
- **Vendors:**
  - Vendor list
  - Create/Edit vendor
  
- **Purchase Orders:**
  - PO list
  - Create PO
  - PO status tracking
  
- **GRNs (Goods Receipt Notes):**
  - GRN list
  - Create GRN
  - Process GRN (add to inventory)

### 13. Production (`/production`)
- **BOMs (Bill of Materials):**
  - BOM list
  - Create/Edit BOM
  
- **Production Orders:**
  - Order list
  - Create order
  - Confirm order (consume RM, create FG)
  - Status tracking

### 14. Returns (`/returns`)
- Return list
- Create return
- Complete return (update inventory)
- Credit note generation

### 15. Shifts (`/shifts`)
- Shift list
- Open/Close shift
- Cash count
- Shift reports

### 16. Reports (`/reports`)
- **Sales Reports:**
  - By date range
  - By product
  - By customer
  - By cashier
  
- **Inventory Reports:**
  - Low stock
  - Stock movements
  - Inventory valuation
  
- **Financial Reports:**
  - Revenue
  - Profit/Loss
  - Tax reports

### 17. Settings (`/settings`)
- User management
- System configuration
- KRA eTIMS settings
- Backup/Restore

---

## 🔌 API Integration

### API Client Setup
```javascript
// lib/api/client.js
import axios from 'axios';

const apiClient = axios.create({
  baseURL: process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/api',
  headers: {
    'Content-Type': 'application/json',
  },
});

// Request interceptor - Add auth token
apiClient.interceptors.request.use((config) => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

// Response interceptor - Handle errors
apiClient.interceptors.response.use(
  (response) => response.data,
  (error) => {
    if (error.response?.status === 401) {
      // Handle unauthorized - redirect to login
    }
    return Promise.reject(error);
  }
);
```

### API Modules
Each backend module should have a corresponding API module:
- `lib/api/auth.js` - Authentication endpoints
- `lib/api/products.js` - Product endpoints
- `lib/api/sales.js` - Sales endpoints
- `lib/api/inventory.js` - Inventory endpoints
- ... (one per backend module)

---

## 🗂️ State Management

### Recommended Approach:
1. **React Context API** for:
   - Authentication state
   - Cart state (POS)
   - Current user
   - Global UI state (theme, notifications)

2. **React Query / SWR** for:
   - Server state (API data)
   - Caching
   - Automatic refetching
   - Optimistic updates

3. **Local State (useState)** for:
   - Form state
   - UI component state
   - Temporary data

---

## 🔐 Authentication & Authorization

### Auth Flow:
1. User logs in → Store JWT token
2. Token stored in localStorage/cookies
3. Protected routes check auth status
4. API requests include token in Authorization header
5. On 401, redirect to login

### Role-Based Access:
- **Cashier:** POS, Sales (view)
- **Manager:** POS, Sales, Inventory, Reports, Settings
- **System Admin:** Full access

### Implementation:
```javascript
// Middleware for protected routes
export function withAuth(Component) {
  return function AuthenticatedComponent(props) {
    const { user, isLoading } = useAuth();
    
    if (isLoading) return <Loading />;
    if (!user) redirect('/login');
    
    return <Component {...props} />;
  };
}
```

---

## 📦 Key Dependencies to Add

```json
{
  "dependencies": {
    "axios": "^1.6.0",              // API client
    "react-hook-form": "^7.49.0",   // Form handling
    "@hookform/resolvers": "^3.3.0", // Form validation
    "zod": "^3.22.0",                // Schema validation
    "date-fns": "^3.0.0",            // Date formatting
    "@tanstack/react-query": "^5.0.0", // Server state
    "react-hot-toast": "^2.4.0",     // Notifications
    "zustand": "^4.4.0",             // State management (optional)
    "lucide-react": "^0.300.0",      // Icons
    "recharts": "^2.10.0"            // Charts
  }
}
```

---

## 🚀 Development Phases

### Phase 1: Foundation (Week 1)
- [ ] Project setup & configuration
- [ ] API client setup
- [ ] Authentication flow
- [ ] Layout components (Sidebar, Header)
- [ ] Basic routing
- [ ] Dashboard shell

### Phase 2: Core Features (Week 2-3)
- [ ] POS interface
- [ ] Products management
- [ ] Sales management
- [ ] Basic inventory

### Phase 3: Advanced Features (Week 4-5)
- [ ] Customers
- [ ] Categories
- [ ] Pricing
- [ ] Taxes

### Phase 4: Business Operations (Week 6-7)
- [ ] Procurement
- [ ] Production
- [ ] Returns
- [ ] Shifts

### Phase 5: Reports & Polish (Week 8)
- [ ] Reports
- [ ] Charts & analytics
- [ ] UI/UX improvements
- [ ] Testing
- [ ] Documentation

---

## 🎯 Next Steps

1. **Install Dependencies:**
   ```bash
   cd client
   npm install axios react-hook-form @hookform/resolvers zod date-fns @tanstack/react-query react-hot-toast lucide-react recharts
   ```

2. **Create API Client:**
   - Set up axios instance
   - Create API modules

3. **Create Authentication:**
   - Login page
   - Auth context
   - Protected route middleware

4. **Create Layout:**
   - Sidebar navigation
   - Header with user info
   - Dashboard layout

5. **Start with POS:**
   - Product grid
   - Cart
   - Checkout flow

---

## 📝 Notes

- **Responsive Design:** Mobile-first approach, especially for POS
- **Performance:** Optimize for fast product search, quick checkout
- **Offline Support:** Consider PWA for offline capability (future)
- **Printing:** Receipt printing support needed
- **Barcode Scanning:** Support for barcode scanners in POS
- **Keyboard Shortcuts:** For faster POS operations
- **Theming:** Support light/dark mode (optional)

---

**Last Updated:** 2025-12-29

