# IMPLEMENTATION_PLAN.md — NexStock Build Plan

## Overview

This document defines the phased implementation plan for NexStock. Each phase builds on the previous one, with clear deliverables and verification criteria.

## Environment Setup

Before Phase 1 begins, the development environment must be configured.

### Prerequisites Checklist
- [ ] PHP 8.3+ installed and on PATH
- [ ] Composer installed globally
- [ ] Node.js 20+ and npm installed
- [ ] MySQL 8.x running
- [ ] Redis server running
- [ ] Git configured

### Project Scaffolding
```bash
# Create Laravel 12 project with Vue + Inertia + TypeScript + Tailwind
laravel new nexstock

# During setup, select:
# - Vue starter kit
# - Pest for testing
# - Git initialization

# Install additional dependencies
composer require laravel/horizon
composer require laravel/reverb
composer require maatwebsite/excel    # for imports/exports
composer require barryvdh/laravel-dompdf  # for PDF receipts
composer require spatie/laravel-permission  # optional, evaluate
composer require laravel/fortify    # already included with starter kit

# Dev dependencies
composer require --dev larastan/larastan
composer require --dev pestphp/pest-plugin-laravel

# Frontend dependencies
npm install echarts vue-echarts
npm install @vueuse/core
npm install pinia   # state management for POS cart
```

---

## Phase 1 — FOUNDATION (Weeks 1–2)

### Goal
Set up the core architecture: authentication, tenancy, users, permissions, business, branches, and audit foundation.

### Deliverables

#### 1.1 Laravel Project Setup
- [ ] Create fresh Laravel 12 project with Vue + Inertia + TypeScript
- [ ] Configure Tailwind CSS v4
- [ ] Configure Pest testing
- [ ] Configure PHPStan/Larastan
- [ ] Configure Laravel Pint
- [ ] Set up Docker development environment (docker-compose.yml)
- [ ] Create `.env.example` with all required variables

#### 1.2 Database Foundation
- [ ] Create `businesses` migration
- [ ] Create `branches` migration
- [ ] Create `users` migration (customize Laravel's default)
- [ ] Create `user_permissions` migration
- [ ] Create `platform_admins` migration
- [ ] Create `audit_logs` migration
- [ ] Create `plans` migration
- [ ] Create `plan_entitlements` migration
- [ ] Create `subscriptions` migration
- [ ] Seed default plans and entitlements

#### 1.3 Tenant Architecture
- [ ] Create `Business` model with factory
- [ ] Create `Branch` model with factory
- [ ] Create `BelongsToTenant` trait with global scope
- [ ] Create `TenantContext` singleton
- [ ] Create `TenantMiddleware` to set context
- [ ] Create `EnsureTenantContext` middleware
- [ ] Write cross-tenant isolation tests

#### 1.4 Authentication
- [ ] Configure Laravel Breeze/Fortify with Vue + Inertia
- [ ] Registration flow → creates Business + Owner + default Branch
- [ ] Login/logout
- [ ] Email verification
- [ ] Password reset
- [ ] 2FA setup (optional)
- [ ] Platform admin guard (separate)

#### 1.5 User Management
- [ ] Create `User` model with factory
- [ ] Owner vs Employee role
- [ ] `UserPermission` model
- [ ] Permission enum
- [ ] Employee CRUD (owner only)
- [ ] Permission assignment
- [ ] Authorization policies

#### 1.6 Audit Foundation
- [ ] Create `AuditLog` model
- [ ] Create `Auditable` trait for models
- [ ] Create `AuditAction` for recording events
- [ ] Log auth events

#### 1.7 Entitlement System
- [ ] Create `Subscription` model
- [ ] Create entitlement checking methods on Business
- [ ] `canUse()`, `limitFor()`, `usageFor()`, `checkLimit()`
- [ ] Trial creation on registration

#### 1.8 Base UI
- [ ] App layout with sidebar navigation
- [ ] Auth pages (login, register, forgot password)
- [ ] Dashboard shell (placeholder metrics)
- [ ] Settings page shell
- [ ] Employee management page

### Verification
- [ ] User can register → business created → branch created → logged in
- [ ] Employee can be created with specific permissions
- [ ] Employee cannot access unpermitted routes
- [ ] Cross-tenant access is denied (automated tests)
- [ ] Audit log records login event
- [ ] Trial subscription created automatically

---

## Phase 2 — PRODUCTS & STOCK (Weeks 3–4)

### Goal
Build the product catalog and inventory engine — the foundation that sales and purchases depend on.

### Deliverables

#### 2.1 Reference Data
- [ ] `Category` model, factory, CRUD, migration
- [ ] `Brand` model, factory, CRUD, migration
- [ ] `Unit` model, factory, CRUD, migration
- [ ] `Supplier` model, factory, CRUD, migration
- [ ] Default units seeder (Piece, Box, Kg, Liter, Dozen)
- [ ] UI pages for managing categories, brands, units

#### 2.2 Products
- [ ] `Product` model with factory
- [ ] `ProductVariant` model with factory
- [ ] Product CRUD controller + pages
- [ ] Auto-create default variant for simple products
- [ ] Variant management for products with variants
- [ ] SKU uniqueness (per tenant)
- [ ] Barcode uniqueness (per tenant)
- [ ] Product image upload
- [ ] Product active/inactive/archive
- [ ] Product search (name, SKU, barcode)

#### 2.3 Product Import
- [ ] Downloadable CSV/Excel template
- [ ] Column mapping UI
- [ ] Preview with validation
- [ ] Duplicate SKU/barcode detection
- [ ] Error reporting per row
- [ ] Queued processing for large files
- [ ] Opening stock import

#### 2.4 Inventory Engine
- [ ] `InventoryMovement` model + migration
- [ ] `InventoryBalance` model + migration
- [ ] `InventoryMovementType` enum
- [ ] `RecordInventoryMovementAction`
- [ ] `UpdateInventoryBalanceAction`
- [ ] `CalculateWeightedAverageCostAction`
- [ ] Opening stock recording
- [ ] Stock adjustment (add/remove)
- [ ] Damage/loss recording
- [ ] Balance reconciliation from movements

#### 2.5 Stock UI
- [ ] Stock overview page (all products with current stock)
- [ ] Low stock view (below reorder level)
- [ ] Out of stock view (zero quantity)
- [ ] Stock history page per product
- [ ] Stock adjustment form
- [ ] Opening stock entry form

### Verification
- [ ] Products can be created with and without variants
- [ ] SKU/barcode uniqueness enforced per tenant
- [ ] Opening stock creates correct movement + balance
- [ ] Stock adjustments create traceable movements
- [ ] Balance always matches sum of movements (reconciliation test)
- [ ] WAC calculated correctly
- [ ] Product search works (name, SKU, barcode)
- [ ] Import processes correctly with error reporting
- [ ] Cross-tenant product isolation verified

---

## Phase 3 — PURCHASES (Weeks 5–6)

### Goal
Build the purchasing workflow so stock can be replenished through purchase records.

### Deliverables

#### 3.1 Suppliers
- [ ] Supplier CRUD pages
- [ ] Supplier listing with search
- [ ] Supplier detail with purchase history

#### 3.2 Purchases
- [ ] `Purchase` model + migration + factory
- [ ] `PurchaseLine` model + migration
- [ ] `PurchaseReceiving` model + migration
- [ ] `PurchaseReceivingLine` model + migration
- [ ] `PurchaseStatus` enum
- [ ] `CreatePurchaseAction`
- [ ] `ReceivePurchaseAction`
- [ ] Partial receiving support

#### 3.3 Purchase → Stock Integration
- [ ] Receiving creates `purchase_received` inventory movements
- [ ] Stock balance updates on receiving
- [ ] WAC recalculated on receiving
- [ ] Purchase status auto-updates based on receiving

#### 3.4 Purchase UI
- [ ] Purchase list page
- [ ] Create purchase form (select supplier, add products, enter costs)
- [ ] Purchase detail page
- [ ] Receive stock form (with partial receiving)
- [ ] Purchase history

### Verification
- [ ] Purchase can be created with multiple line items
- [ ] Stock does NOT increase until marked received
- [ ] Partial receiving updates quantities correctly
- [ ] Full receiving marks purchase as received
- [ ] WAC updates correctly after receiving
- [ ] Inventory movements created with correct reference
- [ ] Supplier purchase history shows correctly

---

## Phase 4 — POS & SALES (Weeks 7–9)

### Goal
Build the point of sale and sales system — the primary revenue-generating interface.

### Deliverables

#### 4.1 POS Interface
- [ ] Single-screen POS layout (Vue component)
- [ ] Product search panel (search by name, SKU, barcode)
- [ ] Cart component with add/remove/quantity
- [ ] Discount input (line-level and sale-level)
- [ ] Tax calculation display
- [ ] Customer selection (optional)
- [ ] Payment method selection
- [ ] Split payment support
- [ ] Cart total calculation
- [ ] Pinia store for cart state

#### 4.2 Sale Processing
- [ ] `Sale` model + migration + factory
- [ ] `SaleLine` model + migration
- [ ] `SalePayment` model + migration
- [ ] `SaleStatus` enum
- [ ] `PaymentMethod` enum
- [ ] `CompleteSaleAction` (atomic: sale + lines + payment + stock + receipt)
- [ ] Receipt number generation (sequential per tenant)
- [ ] Idempotency key checking
- [ ] Snapshot data in sale lines
- [ ] Cost price recording in sale lines (for profit calc)

#### 4.3 Hold/Resume
- [ ] Hold sale (save cart as `held` status)
- [ ] Resume held sale
- [ ] List held sales

#### 4.4 Receipts
- [ ] Receipt generation (HTML template)
- [ ] Printable receipt (thermal printer format)
- [ ] Digital receipt (PDF)
- [ ] Receipt contains snapshot data

#### 4.5 Sales History
- [ ] Sales list page with filters
- [ ] Sale detail view
- [ ] Sales by date range
- [ ] Sales by employee
- [ ] Sales by payment method

#### 4.6 Returns
- [ ] `SaleReturn` model + migration
- [ ] `SaleReturnLine` model + migration
- [ ] `ProcessReturnAction`
- [ ] Return form (select original sale, select items/quantities)
- [ ] Refund recording
- [ ] Stock restoration via inventory movement
- [ ] Over-return prevention
- [ ] Return history

### Verification
- [ ] Complete sale creates sale + lines + payment + stock deduction atomically
- [ ] Failed sale rolls back everything
- [ ] Duplicate idempotency key returns original sale
- [ ] Receipt number is sequential and unique per tenant
- [ ] Sale lines contain snapshot data
- [ ] Stock decreases exactly by sold quantity
- [ ] Cost price recorded for profit calculation
- [ ] Split payment totals match sale total
- [ ] Held sale can be resumed and completed
- [ ] Return restores stock correctly
- [ ] Cannot return more than sold quantity
- [ ] Return references original sale

---

## Phase 5 — CASH & EXPENSES (Weeks 10–11)

### Goal
Build cash shift management and basic expense tracking.

### Deliverables

#### 5.1 Cash Shifts
- [ ] `CashShift` model + migration + factory
- [ ] `CashMovement` model + migration
- [ ] `CashMovementType` enum
- [ ] Open shift action
- [ ] Close shift action
- [ ] Cash in / cash out
- [ ] Auto-record cash sales and refunds
- [ ] Expected vs counted vs variance calculation
- [ ] Shift summary

#### 5.2 Cash UI
- [ ] Open shift prompt (if no open shift)
- [ ] Current shift status in POS
- [ ] Cash in/out form
- [ ] Close shift form (enter counted amount)
- [ ] Shift history

#### 5.3 Expenses
- [ ] `ExpenseCategory` model + migration
- [ ] `Expense` model + migration + factory
- [ ] Expense CRUD
- [ ] Default expense categories seeder
- [ ] Expense listing with filters

### Verification
- [ ] Cash shift tracks all cash movements
- [ ] Expected amount = opening + cash sales - cash refunds + cash in - cash out
- [ ] Variance = counted - expected
- [ ] Cash sales auto-recorded as movements
- [ ] Expenses recorded with correct categorization

---

## Phase 6 — DASHBOARD & INSIGHTS (Weeks 12–13)

### Goal
Turn data into useful business information on the dashboard.

### Deliverables

#### 6.1 Dashboard Metrics
- [ ] Today's sales total, count, units, average
- [ ] This week / this month comparison
- [ ] Total products, low stock, out of stock counts
- [ ] Estimated stock value
- [ ] ECharts sales trend chart

#### 6.2 Product Performance
- [ ] Top-selling products (by units)
- [ ] Highest-revenue products (by sales value)
- [ ] Highest estimated-profit products
- [ ] Slow-moving products (no sales in N days)
- [ ] Product performance detail per product

#### 6.3 Business Insights
- [ ] Rule-based insight engine
- [ ] "X products below reorder level"
- [ ] "Y is your top seller this month"
- [ ] "Product Z hasn't sold in N days"
- [ ] "Sales are X% higher/lower than last period"
- [ ] "Higher volume but lower profit" detection
- [ ] Insights displayed on dashboard

#### 6.4 Attention Items
- [ ] Low stock items needing reorder
- [ ] Pending purchase receivings
- [ ] Unusual returns (high return rate)
- [ ] Stock discrepancies

### Verification
- [ ] Dashboard loads in < 2 seconds
- [ ] Metrics match actual data (cross-verified with reports)
- [ ] Insights are accurate and explainable
- [ ] Low stock correctly identified
- [ ] Charts render correctly with ECharts

---

## Phase 7 — REPORTS (Weeks 14–15)

### Goal
Build focused reports with filtering and export capabilities.

### Deliverables

#### 7.1 Sales Reports
- [ ] Sales summary (date range)
- [ ] Sales by product
- [ ] Sales by date
- [ ] Sales by employee
- [ ] Sales by payment method
- [ ] Returns report
- [ ] Discounts report

#### 7.2 Stock Reports
- [ ] Stock on hand
- [ ] Low stock
- [ ] Out of stock
- [ ] Stock movement history
- [ ] Stock valuation
- [ ] Slow movers

#### 7.3 Purchase Reports
- [ ] Purchases summary
- [ ] Purchases by supplier
- [ ] Purchase history
- [ ] Purchase totals

#### 7.4 Other Reports
- [ ] Product performance report
- [ ] Cash shift summary
- [ ] Cash variance report
- [ ] Payment method summary
- [ ] Expenses by category
- [ ] Expenses by period

#### 7.5 Export
- [ ] CSV export
- [ ] Excel export (via Maatwebsite/Excel)
- [ ] Print-friendly PDF (via DomPDF)
- [ ] Queued export for large datasets

#### 7.6 Filters
- [ ] Date range picker
- [ ] Product/category filter
- [ ] Employee filter
- [ ] Branch filter
- [ ] Supplier filter
- [ ] Payment method filter

### Verification
- [ ] Report totals match dashboard metrics
- [ ] Filters work correctly
- [ ] Exports contain correct data
- [ ] Large exports processed via queue
- [ ] Reports are tenant-scoped

---

## Phase 8 — SAAS & PLATFORM (Weeks 16–17)

### Goal
Build the subscription billing system and platform admin console.

### Deliverables

#### 8.1 Billing
- [ ] Plan management (admin)
- [ ] Subscription lifecycle
- [ ] Trial expiry handling
- [ ] Grace period (read-only access)
- [ ] Plan change
- [ ] Entitlement enforcement throughout app

#### 8.2 Onboarding Wizard
- [ ] Step-by-step setup flow
- [ ] Currency selection
- [ ] Timezone selection
- [ ] Tax configuration
- [ ] Create first branch
- [ ] Add first product
- [ ] Enter opening stock
- [ ] Configure payment methods
- [ ] Optional: add employee
- [ ] Progress tracking
- [ ] Skip non-essential steps

#### 8.3 Platform Admin
- [ ] Admin authentication (separate guard)
- [ ] Business listing + detail
- [ ] Subscription management
- [ ] Plan management
- [ ] System health dashboard
- [ ] Failed job monitoring
- [ ] Feature flags
- [ ] Account suspension/reactivation
- [ ] Support access (view business as read-only)

### Verification
- [ ] Trial expires after 14 days
- [ ] Expired trial enters grace period (read-only)
- [ ] Entitlements correctly enforced
- [ ] Onboarding can be completed in ~15 minutes
- [ ] Platform admin can manage businesses
- [ ] Suspension blocks business access

---

## Phase 9 — HARDENING (Weeks 18–19)

### Goal
Final security review, performance optimization, and deployment preparation.

### Deliverables

#### 9.1 Security Review
- [ ] Cross-tenant isolation audit (all models)
- [ ] Authorization audit (all routes)
- [ ] Input validation audit (all endpoints)
- [ ] Rate limiting verification
- [ ] CSRF/XSS verification
- [ ] File upload security verification
- [ ] Session security verification
- [ ] SQL injection review (no raw queries with user input)
- [ ] Dependency audit (`composer audit`, `npm audit`)

#### 9.2 Performance
- [ ] POS response time < 500ms
- [ ] Product search < 200ms
- [ ] Dashboard load < 2s
- [ ] N+1 query audit (Laravel Debugbar)
- [ ] Index effectiveness review
- [ ] Cache strategy verification
- [ ] Large dataset testing (10K+ products, 100K+ sales)

#### 9.3 Testing
- [ ] All unit tests pass
- [ ] All feature tests pass
- [ ] All cross-tenant tests pass
- [ ] Browser E2E tests for critical flows
- [ ] Coverage targets met

#### 9.4 Deployment
- [ ] Docker production configuration
- [ ] Nginx configuration
- [ ] Supervisor configuration (Horizon, Reverb)
- [ ] Database backup strategy
- [ ] Log management
- [ ] Health check endpoint
- [ ] `.env.production` template
- [ ] Deployment script / CI pipeline

#### 9.5 Documentation
- [ ] README.md with setup instructions
- [ ] API documentation (if applicable)
- [ ] User guide basics
- [ ] Deployment guide

### Verification
- [ ] Full E2E scenario passes (Section 52 of requirements)
- [ ] Security audit clean
- [ ] Performance targets met
- [ ] No critical/high severity issues
- [ ] Deployment automated and tested

---

## Risk Assessment

| Risk | Impact | Mitigation |
|------|--------|------------|
| Inventory accuracy errors | HIGH | Atomic transactions, WAC tests, reconciliation |
| Cross-tenant data leak | CRITICAL | Global scopes, automated tests, DB constraints |
| POS too slow | HIGH | Indexing, eager loading, minimal queries per sale |
| Complex onboarding | MEDIUM | Progressive disclosure, skip non-essential steps |
| Import corrupts data | HIGH | Validation, preview, transactional import, rollback |
| Concurrent stock operations | HIGH | Row-level locking on inventory_balances |
| Receipt number gaps | MEDIUM | Sequence generation within transaction |
| Large dataset performance | MEDIUM | Pagination, query optimization, caching |

## Improvement Decisions Made

1. **ProductVariant as universal unit of tracking** — Instead of branching logic for "simple" vs "variant" products everywhere, every product gets a default variant. The user never sees "variant" for simple products, but the code is uniform.

2. **Signed quantities in movements** — Instead of separate `quantity_in` and `quantity_out` columns, use a single signed `quantity`. This simplifies balance calculation to `SUM(quantity)`.

3. **Snapshot data in sale lines** — Store product name, SKU, and price at sale time. This prevents historical receipt corruption when products are later changed.

4. **Separate receiving entities** — Instead of updating purchase line quantities directly, create separate `PurchaseReceiving` records. This provides a complete audit trail of when stock arrived and who received it.

5. **Entitlement pattern over plan name checks** — Using `canUse('feature')` instead of `if ($plan === 'business')` makes plan changes safe and keeps billing logic centralized.

6. **No over-engineering multi-branch in V1** — The schema supports it (everything has `branch_id`), but the UI defaults to single-branch. Multi-branch UI/features can be enabled later without schema changes.
