# Shop Manager - Master Implementation Plan

## Overview

Integration of a new **Shop Manager** profile in the mobile app, enabling vendors/employees to manage product sales, carts, customers, and checkout flows from the app. This includes a comprehensive dashboard with revenue analytics, inventory tracking, and sales performance metrics. All new entities are also accessible in the Filament back-office.

---

## Scope Summary

| Feature Area | Description |
|---|---|
| **Multi-Cart System** | Vendors can create and manage multiple carts for different customers simultaneously |
| **Product Management** | Browse, search, filter products; scan barcodes; toggle active/inactive; SKU support |
| **Customer Management** | Select existing customers, create new ones on the spot |
| **Checkout & Payments** | Wallet, Crypto, Stripe + 2 new: POS (with receipt photo) and Cash (with change calculation + photo) |
| **Invoice System** | Auto-generate and email invoice after checkout; option to send to alternate email |
| **Dashboard** | Revenue analytics, checkout metrics, basket stats, risk signals, sales performance, best-sellers, recent activity, top categories |
| **Inventory** | Stock levels, low-stock alerts, reorder status, vendor stock adjustments |
| **Product Reviews** | Ratings, verified buyer feedback, average scores |
| **Refunds** | Product order refunds (wallet, Stripe, manual for POS/Cash) |
| **Failed Payment Tracking** | Log declined/failed payment attempts for risk dashboard |
| **Filament Admin** | InvoiceResource, updated ProductResource, OrderResource, EmployeeResource, permissions |

---

## Architecture Decisions

### 1. User Role
- Reuse existing `UserType::EMPLOYEE` with a new `AdminRole::SHOP_MANAGER` enum value
- Vendor operates within a `Place` context (existing `EnsureEmployeeOfPlace` middleware)
- New Spatie permissions group for shop_manager module

### 2. Cart = Order in WAITING_PAYMENT
- Reuse existing `Order` model with `OrderStatus::WAITING_PAYMENT` as cart
- Multi-cart: Multiple orders in WAITING_PAYMENT per employee, each linked to a different customer
- `employee_id` already exists on Order model

### 3. Payment Providers
- Extend `PaymentProvider` enum with `POS` and `CASH` values
- Store receipt/cash photos via existing Spatie MediaLibrary on Order model
- Cash payments store amount received/returned in `payment_details` JSON

### 4. Invoice Generation
- New `Invoice` model with immutable snapshots of order data
- PDF generation via `barryvdh/laravel-dompdf` or `spatie/laravel-pdf`
- Send via existing Sendinblue notification channel
- Sequential invoice numbers per place

### 5. Dashboard API
- New controller group under `Api/Employee/ShopManager/Dashboard/`
- Aggregation queries on Order, OrderItem, Product models
- Period-based filtering (today, 7D, 30D, custom range)
- Sparkline data for charts

### 6. New Models
- `Invoice` — Immutable order snapshot with PDF
- `ProductReview` — Customer feedback with rating

### 7. Schema Extensions
- `products.is_active` — Active toggle
- `product_variations.sku` — Stock Keeping Unit
- `product_variations.barcode` — Barcode for scanner
- `product_variations.low_stock_threshold` — Per-variation alert threshold
- `orders.payment_details` — JSON for POS/Cash metadata
- `orders.notes` — Vendor order notes
- `orders.refund_*` — Refund tracking fields

---

## Development Phases

| Phase | Name | Doc | Scope |
|---|---|---|---|
| **1** | Foundation & Role Setup | [01-PHASE-FOUNDATION.md](01-PHASE-FOUNDATION.md) | Role, middleware, routes skeleton, permissions |
| **2** | Product API for Vendors | [02-PHASE-PRODUCTS.md](02-PHASE-PRODUCTS.md) | List, search, barcode scan, toggle active, product details with stats |
| **3** | Customer & Cart Management | [03-PHASE-CART.md](03-PHASE-CART.md) | Multi-cart, customer selection/creation, cart CRUD |
| **4** | New Payment Methods | [04-PHASE-PAYMENTS.md](04-PHASE-PAYMENTS.md) | POS and Cash payment flows with photo capture |
| **5** | Invoice System | [05-PHASE-INVOICES.md](05-PHASE-INVOICES.md) | PDF generation, auto-send, alternate email |
| **6** | Dashboard API | [06-PHASE-DASHBOARD.md](06-PHASE-DASHBOARD.md) | Revenue, checkout snapshot, sales performance, best-sellers, activity feed, top categories |
| **7** | Inventory & Alerts | [07-PHASE-INVENTORY.md](07-PHASE-INVENTORY.md) | Stock levels, low-stock alerts, reorder status |
| **8** | Orders History & Filtering | [08-PHASE-ORDERS-HISTORY.md](08-PHASE-ORDERS-HISTORY.md) | Filterable order list, order detail, date/customer/type filters |
| **9** | Filament Admin Updates | [09-PHASE-FILAMENT-ADMIN.md](09-PHASE-FILAMENT-ADMIN.md) | InvoiceResource, Product/Order/Employee resource updates, permissions |
| **10** | Missing Features & Schema | [10-PHASE-MISSING-FEATURES.md](10-PHASE-MISSING-FEATURES.md) | SKU, barcode, reviews, badges, stock validation/adjustment, refunds, cart cleanup, order notes |

---

## Dependency Graph

```
Phase 1 (Foundation)
   |
   +---> Phase 10 (Schema & Missing Features) ----+
   |        |                                      |
   |        +---> Phase 2 (Products) ----------+   |
   |        |        |                         |   |
   |        |        +---> Phase 7 (Inventory) |   |
   |        |                                  |   |
   |        +---> Phase 3 (Cart & Customers)   |   |
   |                 |                         |   |
   |                 +---> Phase 4 (Payments) -+---+
   |                 |        |                |
   |                 |        +---> Phase 5 (Invoices)
   |                 |                         |
   |                 +---> Phase 8 (Orders)    |
   |                          |                |
   |                 +--------+-------+--------+
   |                 |                |
   |                 v                v
   |           Phase 6 (Dashboard)   Phase 9 (Filament)
   |
   +---> Phase 9 can start partially after Phase 1
```

**Recommended build order:**
1. Phase 1 (Foundation) + Phase 10 (Schema/Migrations)
2. Phase 2 (Products) + Phase 3 (Cart)
3. Phase 7 (Inventory) + Phase 8 (Orders)
4. Phase 4 (Payments)
5. Phase 5 (Invoices)
6. Phase 6 (Dashboard)
7. Phase 9 (Filament) — can be done incrementally alongside each phase

---

## New Models Summary

| Model | Table | Purpose |
|---|---|---|
| `Invoice` | `invoices` | Immutable order snapshot with PDF, sequential numbering |
| `ProductReview` | `product_reviews` | Customer ratings and feedback on products |

---

## Schema Migrations (Consolidated)

### Migration 1: `add_shop_manager_product_fields`
```
products.is_active (boolean, default true)
product_variations.sku (string, nullable, indexed)
product_variations.barcode (string, nullable, indexed)
product_variations.low_stock_threshold (unsigned int, default 5)
```

### Migration 2: `add_shop_manager_order_fields`
```
orders.payment_details (json, nullable)
orders.notes (text, nullable)
orders.refund_reason (string, nullable)
orders.refunded_at (timestamp, nullable)
```

### Migration 3: `create_invoices_table`
```
invoices: id, public_id, order_id, place_id, user_id,
          invoice_number, total_amount, total_currency,
          line_items (json), customer_snapshot (json),
          place_snapshot (json), issued_at, timestamps
```

### Migration 4: `create_product_reviews_table`
```
product_reviews: id, public_id, product_id, user_id, order_id,
                 rating (1-5), comment, is_verified_buyer,
                 is_approved, timestamps, soft_deletes
```

### Migration 5: `add_shop_manager_role`
```
Seed shop_manager role via Spatie
Seed shop_manager permissions
```

---

## Enum Updates

| Enum | Change |
|---|---|
| `AdminRole` | Add `SHOP_MANAGER` |
| `PaymentProvider` | Add `POS`, `CASH` |
| **New** `StockAdjustmentType` | `REFILL`, `CORRECTION`, `RETURN`, `DAMAGED` |

> **OrderStatus is NOT modified.** Refunds are handled as wallet credit-back transactions (order stays PAID).

---

## Files Impact Summary

### New Files (estimated)

| Type | Count |
|---|---|
| Controllers (API) | ~20 |
| Controllers (Dashboard) | ~7 |
| Actions | ~8 |
| Services | ~3 |
| Models | 2 |
| Enums | 1 new + 2 modified |
| Requests | ~10 |
| Resources (API) | ~6 |
| Notifications | ~2 |
| Migrations | ~6 |
| Blade templates | ~1 |
| Filament Resources/RelationManagers | ~5 |
| Tests | ~14 |
| **Total new files** | **~86** |

### Modified Files

| File | Change |
|---|---|
| `app/Enums/PaymentProvider.php` | Add POS, CASH |
| `app/Enums/AdminRole.php` | Add SHOP_MANAGER |
| `app/Enums/OrderStatus.php` | Add REFUNDED, PARTIALLY_REFUNDED |
| `app/Models/Order.php` | HasMedia, payment_details, refund fields, invoice relation |
| `app/Models/Product.php` | is_active, reviews relation, rating/badge accessors, stock accessors |
| `app/Models/ProductVariation.php` | sku, barcode, low_stock_threshold, reorder status |
| `app/Models/User.php` | `is_shop_manager` accessor |
| `app/Http/Controllers/Api/StripeWebhookController.php` | Log failed payments |
| `app/Http/Controllers/Api/NowPaymentsWebhookController.php` | Log failed payments |
| `app/Providers/EventServiceProvider.php` | Register invoice listener |
| `app/Filament/Resources/EmployeeResource.php` | SHOP_MANAGER role option |
| `app/Filament/Resources/ProductResource.php` | is_active, SKU fields |
| `app/Filament/Resources/ProductResource/RelationManagers/VariationsRelationManager.php` | barcode, threshold |
| `app/Filament/Resources/OrderResource.php` | POS/CASH display, receipt photos |
| `app/Filament/Resources/CustomerResource.php` | InvoicesRelationManager |
| `app/Filament/Pages/RolePermissionsManager.php` | shop_manager permissions |
| `routes/api.php` | Shop manager route group |

---

## Complete API Endpoints (34 total)

### Cart Management (9)
| Method | Endpoint | Description |
|---|---|---|
| `GET` | `/v1/places/{place}/shop/carts` | List all active carts for this vendor |
| `POST` | `/v1/places/{place}/shop/carts` | Create a new cart for a customer |
| `GET` | `/v1/places/{place}/shop/carts/{order}` | Get cart details |
| `PUT` | `/v1/places/{place}/shop/carts/{order}` | Update cart (full item list) |
| `DELETE` | `/v1/places/{place}/shop/carts/{order}` | Delete cart |
| `POST` | `/v1/places/{place}/shop/carts/{order}/customer` | Change cart customer |
| `POST` | `/v1/places/{place}/shop/carts/{order}/items` | Add single item (by ID or barcode) |
| `PATCH` | `/v1/places/{place}/shop/carts/{order}/items/{item}` | Update item quantity |
| `DELETE` | `/v1/places/{place}/shop/carts/{order}/items/{item}` | Remove item |

### Product Operations (5)
| Method | Endpoint | Description |
|---|---|---|
| `GET` | `/v1/places/{place}/shop/products` | List products with search, filter, pagination |
| `GET` | `/v1/places/{place}/shop/products/{product}` | Product details with sales/inventory/feedback stats |
| `GET` | `/v1/places/{place}/shop/products/barcode/{code}` | Lookup product by barcode |
| `PATCH` | `/v1/places/{place}/shop/products/{product}/toggle` | Toggle product active/inactive |
| `POST` | `/v1/places/{place}/shop/products/{product}/stock` | Adjust stock (refill/correction) |

### Checkout & Payments (5)
| Method | Endpoint | Description |
|---|---|---|
| `POST` | `/v1/places/{place}/shop/carts/{order}/pay/stripe` | Pay via Stripe |
| `POST` | `/v1/places/{place}/shop/carts/{order}/pay/wallet` | Pay via wallet |
| `POST` | `/v1/places/{place}/shop/carts/{order}/pay/crypto` | Pay via crypto |
| `POST` | `/v1/places/{place}/shop/carts/{order}/pay/pos` | Pay via POS terminal (+ receipt photo) |
| `POST` | `/v1/places/{place}/shop/carts/{order}/pay/cash` | Pay via cash (+ amounts + photo) |

### Orders & Refunds (3)
| Method | Endpoint | Description |
|---|---|---|
| `GET` | `/v1/places/{place}/shop/orders` | List orders with filters (date, customer, type) |
| `GET` | `/v1/places/{place}/shop/orders/{order}` | Order detail |
| `POST` | `/v1/places/{place}/shop/orders/{order}/refund` | Refund order (full or partial) |

### Invoices (2)
| Method | Endpoint | Description |
|---|---|---|
| `GET` | `/v1/places/{place}/shop/orders/{order}/invoice` | Download invoice PDF |
| `POST` | `/v1/places/{place}/shop/orders/{order}/invoice/send` | Send invoice to alternate email |

### Customer Management (2)
| Method | Endpoint | Description |
|---|---|---|
| `GET` | `/v1/places/{place}/shop/customers` | Search customers |
| `POST` | `/v1/places/{place}/shop/customers` | Create customer on the spot |

### Dashboard (7)
| Method | Endpoint | Description |
|---|---|---|
| `GET` | `/v1/places/{place}/shop/dashboard/revenue` | Total revenue with period filter + chart |
| `GET` | `/v1/places/{place}/shop/dashboard/checkout-snapshot` | Checkout, basket, risk metrics with sparklines |
| `GET` | `/v1/places/{place}/shop/dashboard/sales-performance` | Revenue/orders/basket by day of week |
| `GET` | `/v1/places/{place}/shop/dashboard/best-sellers` | Top selling products |
| `GET` | `/v1/places/{place}/shop/dashboard/recent-activity` | Latest events feed (sales, feedback, stock) |
| `GET` | `/v1/places/{place}/shop/dashboard/top-categories` | Category performance with trends |
| `GET` | `/v1/places/{place}/shop/dashboard/inventory-alerts` | Low-stock items |

### Product Reviews (1 — customer-facing, not shop manager)
| Method | Endpoint | Description |
|---|---|---|
| `GET` | `/v1/places/{place}/shop/products/{product}/reviews` | List reviews for a product |

---

## Conventions Reminder

- `declare(strict_types=1)` in every PHP file
- `final` classes by default
- `public_id` in API responses, never `id`
- Conventional Commits
- `./gitCheck.sh` before every commit
- Pest tests for every new feature
- Swagger `@OA\` annotations on every controller
- PHPDoc with `@throws`, `@param`, `@property-read`
- Every new Filament resource needs `HasPermissionChecks` trait
- Translations via `HasDatabaseTranslations` for user-facing text fields
