# Digital Aura Business Suite — Implementation Plan

## Architecture Overview

**Stack:** Laravel 12 + React 19 (PWA) + Inertia.js v2 + Tailwind CSS + Shadcn UI + Vite + Dexie.js (Offline)

**Key Architectural Patterns:**
- **Offline-First POS**: IndexedDB (Dexie.js) as primary data store, syncs to Laravel API in background
- **Service Layer + Repository**: Business logic in `app/Services/`, data access in `app/Repositories/`
- **Store Scoping**: Middleware sets active store context; all queries scoped to current store
- **Event-Driven**: Stock updates, notifications, audit logs triggered via Events/Observers
- **Configurable Notifications**: Multi-provider (Twilio SMS, Meta WhatsApp, Email) via Laravel Notification system

---

## Tech Stack

### Backend
- Laravel 12
- PHP 8.3+
- MySQL
- Eloquent ORM
- REST API
- Laravel Policies / Gates
- Laravel Events / Queues / Notifications
- Laravel Scheduler
- Laravel Sanctum

### Frontend
- React 19
- Inertia.js
- Tailwind CSS
- Shadcn UI
- Vite
- Lucide Icons
- ApexCharts
- TanStack Table
- React Hook Form + Zod
- Sonner Toast
- Dexie.js (Offline IndexedDB)

### Packages
- `laravel/breeze` — Auth scaffolding
- `laravel/sanctum` — API tokens
- `spatie/laravel-permission` — Roles & permissions
- `barryvdh/laravel-dompdf` — PDF generation
- `maatwebsite/excel` — Excel export
- `spatie/laravel-activitylog` — Audit logs
- `mr-rijal/laravel-sms` — Multi-provider SMS
- `crenspire/laravel-whatsapp` — WhatsApp Business API
- `thomasjohnkane/snooze` — Scheduled reminders

---

## Complete Database Schema (65+ Tables)

### Auth & Users
| Table | Key Fields |
|-------|-----------|
| `users` | uuid, name, email, password, role, is_active, two_factor_* |
| `password_reset_tokens` | email, token |
| `personal_access_tokens` | Sanctum API tokens |
| `sessions` | Laravel session |

### Multi-Store
| Table | Key Fields |
|-------|-----------|
| `stores` | uuid, name, address, phone, timezone, is_active, opening_cash |
| `store_users` | store_id, user_id, role (admin/manager/cashier/delivery_staff), is_active |
| `store_terminals` | uuid, store_id, name, is_active |
| `settings` | key, value, store_id (nullable), group |

### Daily Cash Management (CRITICAL)
| Table | Key Fields |
|-------|-----------|
| `cash_registers` | uuid, store_id, name, is_active |
| `cash_shifts` | uuid, store_id, register_id, user_id, opening_cash, closing_cash, expected_cash, difference, status (open/closed), opened_at, closed_at |
| `cash_shift_movements` | uuid, shift_id, type (cash_in/cash_out/cash_drop/sale_cash/refund), amount, description, user_id |
| `daily_balances` | uuid, store_id, date, opening_balance (B/F), closing_balance (C/F), total_cash_sales, total_cash_refunds, total_pay_ins, total_pay_outs, expected_balance, counted_balance, difference, status, closed_by, closed_at |
| `cash_daily_summary` | uuid, store_id, date, brought_forward, total_receipts, total_payments, carried_forward, banked_amount, notes |

### Products & Inventory
| Table | Key Fields |
|-------|-----------|
| `categories` | uuid, parent_id, name, slug, image, sort_order, is_active |
| `brands` | uuid, name, slug, logo, is_active |
| `units` | uuid, name, short_name, base_unit_id, conversion_factor |
| `products` | uuid, name, slug, sku, barcode, qr_code, category_id, brand_id, unit_id, cost_price, selling_price, tax_id, reorder_level, is_active, has_variants |
| `product_variants` | uuid, product_id, name, sku, barcode, cost_price, selling_price, attributes (JSON), is_active |
| `product_images` | uuid, product_id, path, sort_order, is_primary |
| `product_stores` | product_id/store_id, quantity, reorder_level |
| `product_vehicles` | product_id/vehicle_id, quantity, loaded_at |
| `stock_movements` | uuid, product_id, variant_id, store_id/vehicle_id, type (in/out/transfer/adjustment), quantity, reference_type, reference_id |
| `stock_adjustments` | uuid, store_id, adjustment_date, reason, status, approved_by |
| `stock_adjustment_items` | uuid, adjustment_id, product_id, variant_id, counted_qty, system_qty, difference |
| `stock_transfers` | uuid, from_store_id, to_store_id, transfer_date, status, notes |
| `stock_transfer_items` | uuid, transfer_id, product_id, variant_id, quantity, received_quantity |

### POS & Sales
| Table | Key Fields |
|-------|-----------|
| `sales` | uuid, store_id, terminal_id, shift_id, customer_id, user_id, subtotal, discount, tax, service_charge, tips, total, payment_status, sale_type (walk_in/online/vehicle) |
| `sale_items` | uuid, sale_id, product_id, variant_id, quantity, unit_price, discount, tax_amount, total |
| `payments` | uuid, payable_type/payable_id, method (cash/card/bank_transfer/mobile/credit/gift_card/store_credit), amount, reference_number, status |
| `quotations` | uuid, store_id, customer_id, user_id, valid_until, status, subtotal, tax, total |
| `quotation_items` | uuid, quotation_id, product_id, variant_id, quantity, unit_price, discount, total |
| `invoices` | uuid, store_id, customer_id, user_id, invoice_number, sale_id, subtotal, tax, discount, total, amount_paid, amount_due, due_date, credit_terms_days, status (draft/sent/partial/paid/overdue/written_off) |
| `invoice_payments` | uuid, invoice_id, amount, payment_method, reference_number, paid_at, recorded_by |
| `returns` | uuid, store_id, sale_id, customer_id, user_id, reason, subtotal, tax, total, status |
| `return_items` | uuid, return_id, sale_item_id, product_id, variant_id, quantity, unit_price, total |
| `coupons` | uuid, code, type (percentage/fixed), value, min_amount, max_uses, used_count, valid_from, valid_until, is_active |
| `gift_cards` | uuid, code, balance, initial_amount, customer_id, issued_by, valid_until, is_active |

### Vehicle Management
| Table | Key Fields |
|-------|-----------|
| `vehicles` | uuid, plate_number, name, make, model, year, fuel_type, capacity, status (active/maintenance/retired), current_odometer, store_id |
| `drivers` | uuid, user_id, name, license_number, license_class, license_expiry, phone, status |
| `vehicle_drivers` | vehicle_id, driver_id, assigned_from, assigned_to |
| `vehicle_daily_assignments` | uuid, vehicle_id, sales_person_id, store_id, assignment_date, start_odometer, end_odometer, status |
| `vehicle_trips` | uuid, vehicle_id, driver_id, assignment_id, start_time, end_time, start_lat/lng, end_lat/lng, distance_km, fuel_consumed, status |
| `vehicle_gps_logs` | uuid, vehicle_id, trip_id, latitude, longitude, speed_kmh, heading, fuel_level, recorded_at |
| `vehicle_fuel_records` | uuid, vehicle_id, trip_id, liters, cost_per_liter, total_cost, odometer_reading, fuel_date, fuel_station, receipt_image |
| `vehicle_maintenance` | uuid, vehicle_id, type (scheduled/repair/inspection), description, cost, service_date, next_service_date |
| `vehicle_stock_movements` | uuid, vehicle_id, product_id, store_id, type (loaded/offloaded/sold), quantity, movement_date, assigned_user_id |
| `geofences` | uuid, store_id, name, center_lat, center_lng, radius_meters, is_active |
| `geofence_alerts` | uuid, geofence_id, vehicle_id, event_type (enter/exit), triggered_at |

### Purchasing
| Table | Key Fields |
|-------|-----------|
| `suppliers` | uuid, name, contact_person, email, phone, address, tax_number, payment_terms, is_active |
| `purchase_orders` | uuid, store_id, supplier_id, user_id, po_number, order_date, expected_date, status, subtotal, tax, total |
| `purchase_order_items` | uuid, po_id, product_id, variant_id, quantity, received_quantity, unit_cost, total |
| `goods_received_notes` | uuid, po_id, store_id, user_id, grn_number, received_date, notes |
| `grn_items` | uuid, grn_id, po_item_id, product_id, variant_id, quantity_received, batch_number, expiry_date |
| `supplier_returns` | uuid, supplier_id, store_id, user_id, return_date, reason, status |
| `supplier_return_items` | uuid, return_id, product_id, variant_id, quantity, unit_cost |

### Credit Management
| Table | Key Fields |
|-------|-----------|
| `credit_accounts` | uuid, customer_id, credit_limit, current_balance, payment_terms_days, is_active |
| `credit_transactions` | uuid, credit_account_id, type (sale/payment/adjustment/write_off), amount, reference_type/id, notes, created_by |
| `credit_reminders` | uuid, invoice_id, reminder_type (sms/whatsapp/email), scheduled_at, sent_at, status (pending/sent/failed) |
| `credit_aging_snapshots` | uuid, customer_id, snapshot_date, current, days_1_30, days_31_60, days_61_90, days_91_plus, total_outstanding |

### Accounting
| Table | Key Fields |
|-------|-----------|
| `accounts` | uuid, code, name, type (asset/liability/equity/income/expense), parent_id, is_active |
| `journal_entries` | uuid, entry_date, description, reference_type/id, is_reversed, created_by |
| `journal_entry_items` | uuid, journal_entry_id, account_id, debit, credit, notes |
| `bank_accounts` | uuid, store_id, name, bank_name, account_number, opening_balance, current_balance, is_active |
| `bank_transactions` | uuid, bank_account_id, type (deposit/withdrawal/transfer), amount, balance_after, reference_type/id, notes |
| `expenses` | uuid, store_id, account_id, category, description, amount, expense_date, payment_method, receipt_image, approved_by |
| `income_categories` | uuid, name, account_id, is_active |

### CRM & People
| Table | Key Fields |
|-------|-----------|
| `customers` | uuid, name, email, phone, address, tax_number, loyalty_points, is_active |
| `customer_addresses` | uuid, customer_id, label, address, city, state, postal_code, is_default |
| `employees` | uuid, user_id, employee_number, name, email, phone, department_id, designation_id, hire_date, salary, is_active |
| `departments` | uuid, name, manager_id, is_active |
| `designations` | uuid, name, department_id, is_active |

### HR & Payroll
| Table | Key Fields |
|-------|-----------|
| `attendances` | uuid, employee_id, date, check_in, check_out, status, store_id |
| `leaves` | uuid, employee_id, leave_type, start_date, end_date, days, reason, status, approved_by |
| `payrolls` | uuid, employee_id, period_start, period_end, basic_salary, allowances, deductions, net_salary, status, processed_by |
| `payslips` | uuid, payroll_id, employee_id, period, generated_at, paid_at |

### Activity & Audit
| Table | Key Fields |
|-------|-----------|
| `activity_logs` | uuid, user_id, store_id, action, subject_type/id, old_values, new_values, ip_address |
| `audit_logs` | uuid, user_id, store_id, event, auditable_type/id, auditable_data (JSON), ip_address |

### Communications
| Table | Key Fields |
|-------|-----------|
| `notification_logs` | uuid, notifiable_type/id, channel (sms/whatsapp/email), provider, template, payload, status, sent_at |
| `notification_templates` | uuid, name, channel, subject, body, variables (JSON), is_active |
| `notification_settings` | uuid, event, channels (JSON), is_active, store_id |

---

## File Structure

```
digital-aura-business-suite/
├── app/
│   ├── Actions/
│   │   ├── Auth/
│   │   ├── CashManagement/
│   │   │   ├── OpenShiftAction.php
│   │   │   ├── CloseShiftAction.php
│   │   │   ├── RecordCashMovementAction.php
│   │   │   ├── CloseDailyBalanceAction.php
│   │   │   └── CreateNextDayBalanceAction.php
│   │   ├── POS/
│   │   │   ├── CreateSaleAction.php
│   │   │   ├── ProcessPaymentAction.php
│   │   │   └── ReturnSaleAction.php
│   │   ├── Inventory/
│   │   │   ├── TransferStockAction.php
│   │   │   └── AdjustStockAction.php
│   │   ├── Vehicle/
│   │   │   ├── AssignVehicleAction.php
│   │   │   ├── LoadVehicleStockAction.php
│   │   │   ├── OffloadVehicleStockAction.php
│   │   │   └── ProcessTelemetryAction.php
│   │   ├── Credit/
│   │   │   ├── CreateCreditSaleAction.php
│   │   │   ├── RecordCreditPaymentAction.php
│   │   │   └── SendCreditRemindersAction.php
│   │   └── Sync/
│   │       └── ProcessOfflineSyncAction.php
│   ├── Console/Commands/
│   ├── Contracts/
│   ├── DTOs/
│   ├── Events/
│   ├── Exceptions/
│   ├── Http/
│   │   ├── Controllers/
│   │   ├── Middleware/
│   │   └── Requests/
│   ├── Models/
│   ├── Observers/
│   ├── Policies/
│   ├── Repositories/
│   ├── Services/
│   └── Notifications/
├── config/
├── database/
│   ├── factories/
│   ├── migrations/
│   └── seeders/
├── public/
│   ├── sw.js
│   └── manifest.json
├── resources/
│   └── js/
│       ├── Components/
│       ├── Hooks/
│       ├── lib/
│       ├── Pages/
│       └── types/
├── routes/
├── tests/
├── vite.config.ts
├── tailwind.config.ts
├── tsconfig.json
└── PLAN.md
```

---

## Implementation Phases

| Phase | Module | Priority | Status | Details |
|-------|--------|----------|--------|---------|
| 1 | Project Setup (Laravel 12 + React + PWA) | HIGH | ✅ Done | Laravel 12, React 19, Inertia.js, Tailwind, Shadcn, Vite |
| 2 | Authentication (Breeze + Inertia) | HIGH | ✅ Done | Login, Register, ForgotPassword, Profile, ConfirmPassword |
| 3 | Database (84 migrations, 74 models, 9 seeders) | HIGH | ✅ Done | All tables migrated, factories, seeders for stores/products/users |
| 4 | Core UI (Layouts, Sidebar, Store Selector, Theme) | HIGH | ✅ Done | AppLayout, Sidebar, TopBar, StoreSelector, ThemeToggle |
| 5 | Multi-Store Management | HIGH | ✅ Done | Store CRUD, user assignment, store switching, super admin bypass |
| 6 | Daily Cash Management (B/F, C/F, Shifts) | CRITICAL | ✅ Done | OpenShift, CloseShift, Movements, DailyBalance, Action classes |
| 7 | Dashboard (Stats, Charts, Date Range Filter) | HIGH | ✅ Done | KPI cards, 7/30-day charts, hourly, store comparison, date range picker |
| 8 | POS (Offline-first with Dexie.js) | CRITICAL | ✅ Done | ProductGrid, Cart, PaymentModal, Receipt, barcode scan, 5 payment methods, offline queue, PWA |
| 9 | Inventory (Products, Stock, Transfers) | HIGH | 🔶 Partial | Models exist, Product CRUD pages exist, Stock/Transfers need UI |
| 10 | Vehicle Management (GPS, Fuel, Assignment) | CRITICAL | 🔶 Partial | Models exist, need GPS tracking, fuel, assignment UI |
| 11 | Vehicle Sales (On-site POS, Stock deduction) | CRITICAL | 🔶 Partial | VehicleStock model exists, need vehicle POS flow |
| 12 | Credit Management (Aging, Auto-reminders) | CRITICAL | 🔶 Partial | CreditController stub exists, need aging reports, reminders |
| 13 | Purchasing (PO, GRN) | MEDIUM | 🔶 Partial | PurchaseOrderController stub exists, need PO/GRN UI |
| 14 | Sales (Invoices, Quotations, Returns) | MEDIUM | ✅ Done | Sales Index/Show, Quotation CRUD, Invoice CRUD, Returns |
| 15 | Accounting (COA, Journal, GL, Bank) | MEDIUM | 🔶 Partial | AccountingController stub exists, need COA/Journal/Bank UI |
| 16 | CRM (Customers, Suppliers) | MEDIUM | ✅ Done | Customer CRUD, Supplier CRUD |
| 17 | HR & Payroll | MEDIUM | ✅ Done | Employees, Departments, Leaves, Payroll, Attendance |
| 18 | Settings (Company, Tax, Roles) | MEDIUM | 🔶 Partial | SettingsController stub exists, need full settings UI |
| 19 | Communications (SMS/WhatsApp/Email) | HIGH | ❌ Pending | NotificationController stub, need provider integration |
| 20 | Reports (Cash, Vehicle, Credit Aging, Sales) | MEDIUM | ❌ Pending | Need report generation UI and PDF export |
| 21 | REST API + Sync Endpoint | MEDIUM | 🔶 Partial | SalesApiController exists for offline sync, need full API |
| 22 | Offline Support (Dexie.js, SW, Sync) | HIGH | ✅ Done | Dexie schema, syncService, useOffline hook, Service Worker |
| 23 | Testing (Unit + Feature) | MEDIUM | 🔶 Partial | 9 CashManagement tests passing, need more coverage |
| 24 | Deployment & Documentation | LOW | ❌ Pending | Need deployment docs and README |

### Summary
- **✅ Done:** 13 phases
- **🔶 Partial:** 9 phases
- **❌ Pending:** 2 phases

---

## Key Decisions

| Decision | Choice |
|----------|--------|
| Cash in hand | Per-store independent with store selector |
| GPS tracking | Both device push + mobile browser geolocation |
| Vehicle sales | Browser-based POS on tablet/mobile (PWA) |
| SMS/WhatsApp | Twilio + Meta API + Configurable multi-provider |
| Stock model | Store stock + Vehicle stock (separate) |
| Offline support | Dexie.js (IndexedDB) + Workbox SW + Outbox sync |
| Conflict resolution | LWW + append-only + UUID |
| IDs | UUIDs everywhere (client-generated for offline) |
