# Stock Manager Pro with POS — Project Documentation

## Overview

**Stock Manager Pro with POS** is a full-featured **Laravel 10** inventory management and Point-of-Sale (POS) web application. It supports multi-warehouse operations, HR management, manufacturing, eCommerce integration, and multi-tenant (SaaS) deployments.

- **Framework:** Laravel 10 (PHP ^8.2)
- **App Name:** `salepropos`
- **Version:** `5.6.1`
- **Timezone:** Asia/Dhaka (configurable)
- **Mode:** CLIENT (can be DEVELOPER or DEMO)

---

## Root Directory Structure

```
stock-manager-pro-with-pos/
├── app/                    # Core application logic
├── bootstrap/              # Framework bootstrap files
├── config/                 # Laravel configuration files
├── database/               # Migrations, seeders, factories
├── Modules/                # Laravel nwidart modules (Manufacturing, etc.)
├── public/                 # Public web root
├── resources/              # Views, JS, SASS, assets
├── routes/                 # Route definitions
├── storage/                # Logs, cache, uploads
├── tests/                  # PHPUnit test files
├── vendor/                 # Composer dependencies
├── .env                    # Environment configuration
├── .env.example            # Environment template
├── artisan                 # Laravel CLI
├── composer.json           # PHP dependencies
├── package.json            # Node.js dependencies
├── modules_statuses.json   # Active module list
├── manifest.json           # App manifest
└── phpunit.xml             # Test configuration
```

---

## Environment Configuration (`.env`)

| Key | Value / Purpose |
|-----|----------------|
| `APP_NAME` | `salepropos` |
| `APP_ENV` | `local` |
| `APP_URL` | `http://localhost/internal` |
| `APP_TIMEZONE` | `Asia/Dhaka` |
| `PRODUCT_MODE` | `CLIENT` (options: DEVELOPER, DEMO, CLIENT) |
| `VERSION` | `5.6.1` |
| `DB_CONNECTION` | `mysql` |
| `SMS_GATEWAY` | `twilio` |
| `SESSION_LIFETIME` | `4320` minutes |
| `PRINT_NODE_API_KEY` | PrintNode integration for remote printing |
| `PESAPAL_*` | Pesapal payment gateway credentials |
| `PUSHER_*` | Real-time broadcasting (WebSocket) |

### SaaS / Multi-Tenant Keys
- `CPANEL_API_KEY`, `CPANEL_USER_NAME` — cPanel automation
- `CENTRAL_DOMAIN` — Main SaaS domain
- `DB_PREFIX`, `LANDLORD_DB` — Tenant database config

---

## `app/` Directory

### `app/Models/` — 91 Eloquent Models

The models cover every domain of the application:

| Category | Models |
|----------|--------|
| **Core Inventory** | `Product`, `ProductVariant`, `Variant`, `Brand`, `Category`, `Unit`, `Tax`, `Barcode`, `ProductBatch` |
| **Warehouse** | `Warehouse`, `Product_Warehouse` |
| **Sales** | `Sale`, `Product_Sale`, `Returns`, `ProductReturn`, `ReturnPurchase`, `PurchaseProductReturn` |
| **Purchases** | `Purchase`, `ProductPurchase`, `ReturnPurchase` |
| **Quotations** | `Quotation`, `ProductQuotation` |
| **Transfers** | `Transfer`, `ProductTransfer` |
| **Adjustments** | `Adjustment`, `ProductAdjustment` |
| **Payments** | `Payment`, `PaymentWithCheque`, `PaymentWithCreditCard`, `PaymentWithGiftCard`, `PaymentWithPaypal` |
| **Customers** | `Customer`, `CustomerGroup`, `DiscountPlan`, `DiscountPlanCustomer`, `Discount`, `RewardPoint`, `RewardPointSetting` |
| **Suppliers** | `Supplier`, `Product_Supplier` |
| **POS** | `PosSetting`, `CashRegister`, `Table`, `Biller`, `Coupon`, `GiftCard`, `GiftCardRecharge` |
| **Delivery** | `Delivery`, `Challan`, `PackingSlip`, `PackingSlipProduct`, `Courier` |
| **HRM** | `Employee`, `Department`, `Designation`, `Shift`, `Attendance`, `Holiday`, `Leave`, `LeaveType`, `Overtime`, `Payroll`, `EmployeeTransaction` |
| **Finance** | `Account`, `Deposit`, `MoneyTransfer`, `Expense`, `ExpenseCategory`, `Income`, `IncomeCategory`, `Installment`, `InstallmentPlan` |
| **Settings** | `GeneralSetting`, `PosSetting`, `InvoiceSetting`, `InvoiceSchema`, `HrmSetting`, `MailSetting`, `WhatsappSetting`, `RewardPointSetting` |
| **Users & Auth** | `User`, `Roles`, `MobileToken` |
| **Communication** | `SmsTemplate`, `ExternalService` |
| **Localization** | `Language`, `Translation`, `Currency`, `Country` |
| **Misc** | `ActivityLog`, `CustomField`, `StockCount`, `Printer` |

---

### `app/Http/Controllers/` — 73+ Controllers

#### Core Business Controllers
| Controller | Responsibility |
|-----------|---------------|
| `SaleController.php` (274KB) | POS sales, invoices, receipts, hold orders, layaway |
| `PurchaseController.php` (143KB) | Supplier purchases, goods receiving |
| `ReportController.php` (268KB) | All reports: profit/loss, stock, sales, purchases, tax, etc. |
| `ProductController.php` (104KB) | Product CRUD, variants, batches, IMEI, combos, import/export |
| `TransferController.php` (83KB) | Inter-warehouse stock transfers |
| `ReturnController.php` (74KB) | Customer return (sale returns) |
| `ReturnPurchaseController.php` (55KB) | Supplier purchase returns |
| `QuotationController.php` (62KB) | Sales quotations |
| `CustomerController.php` (49KB) | Customer management, deposits, ledger |
| `HomeController.php` (46KB) | Dashboard, analytics, charts |
| `SettingController.php` (30KB) | Application-wide settings |
| `AdjustmentController.php` (30KB) | Stock adjustments |
| `PayrollController.php` (20KB) | Employee payroll processing |
| `ChallanController.php` (23KB) | Delivery challans |
| `DeliveryController.php` (22KB) | Delivery management |
| `PackingSlipController.php` (16KB) | Packing slip generation |
| `SupplierController.php` (19KB) | Supplier CRUD and ledger |
| `CategoryController.php` (17KB) | Product categories (nested/tree) |
| `ExpenseController.php` (14KB) | Business expenses |
| `EmployeeController.php` (12KB) | Employee CRUD |
| `SaleAgentController.php` (11KB) | Sales agent tracking |
| `IncomeController.php` (11KB) | Income tracking |
| `AccountsController.php` (16KB) | Financial accounts (COA) |
| `BarcodeController.php` (10KB) | Barcode generation |
| `AttendanceController.php` (9KB) | Employee attendance |
| `BillerController.php` (9KB) | Billing profiles/companies |
| `WarehouseController.php` (5KB) | Warehouse management |
| `UserController.php` (10KB) | User CRUD, permissions |
| `RoleController.php` (4KB) | Roles & permissions (Spatie) |

#### POS & Utility Controllers
| Controller | Purpose |
|-----------|---------|
| `CashRegisterController.php` | Cash register open/close |
| `TableController.php` | Restaurant table management |
| `CouponController.php` | Discount coupon management |
| `GiftCardController.php` | Gift card issuance & redemption |
| `StockCountController.php` | Physical stock counting |
| `InvoiceSettingController.php` | Invoice customization |
| `PrinterController.php` | Network/thermal printer management |
| `WhatsappController.php` | WhatsApp notifications |
| `LabelsController.php` | Product label printing |
| `TranslationController.php` | Language translation management |
| `InstallController.php` | Application installation wizard |
| `AddonInstallController.php` | Module/addon installation |
| `RazorpayController.php` | Razorpay payment gateway |

---

### `app/Http/Middleware/` — 15 Middleware Classes

| Middleware | Purpose |
|-----------|---------|
| `Active.php` | Checks if user account is active |
| `Authenticate.php` | Standard auth guard |
| `Common.php` | Shared logic (locale, timezone, etc.) |
| `Cors.php` | Cross-Origin Resource Sharing headers |
| `PermissionMiddleware.php` | Spatie permission gate |
| `SuperAdminAuth.php` | Super-admin only access |
| `ValidateMobileToken.php` | Mobile API token validation |
| `HasPermanentDeletePermission.php` | Guards permanent delete actions |
| `CheckSmsBalance.php` | Validates SMS credit before sending |
| `CheckForMaintenanceMode.php` | Maintenance mode handler |
| `VerifyCsrfToken.php` | CSRF protection |

---

### `app/Http/Requests/` — 33 Form Request Classes

Validation classes for all major operations including:
- `StoreSaleRequest`, `PurchaseRequest`, `StoreTransferRequest`
- `StoreProductRequest`, `UpdateProductRequest`
- `StoreCustomerRequest`, `UpdateCustomerRequest`
- `StoreAdjustmentRequest`, `StoreReturnPurchaseRequest`
- `InstallationRequest`, `LoginRequest`, `RegistrationRequest`
- `HrmSettingRequest`, `MailRequest`, `TaxRequest`, etc.

---

### `app/Http/Resources/` — 48 API Resource Classes

Laravel API Resources for structured JSON responses used by the mobile/API layer:
- `SaleResource`, `SaleCollection`, `ProductResource`, `ProductCollection`
- `CustomerResource`, `SupplierResource`, `PurchaseResource`
- `GiftCardResource`, `PayrollResource`, `TransferResource`
- `SuccessResource`, `ErrorResource` — Standardized response wrappers

---

### `app/Services/` — 4 Service Classes

| Service | Purpose |
|---------|---------|
| `DataRetrievalService.php` | Centralized data fetching logic |
| `PaymentService.php` | Payment processing abstraction |
| `PrinterService.php` | ESC/POS & PrintNode printing |
| `SmsService.php` | SMS dispatch abstraction |

---

### `app/SMSProviders/` — 6 SMS Gateway Integrations

| Provider | Notes |
|---------|-------|
| `Twilio.php` | Twilio SMS |
| `BdBulkSms.php` | Bangladesh Bulk SMS |
| `Clickatell.php` | Clickatell SMS |
| `ReveSms.php` | REVE SMS |
| `SmsToday.php` | SmsToday gateway |
| `TonkraSms.php` | Tonkra SMS |

---

### `app/Mail/` — 18 Mail Classes

Mailable classes for transactional emails:
- `SaleDetails`, `PaymentDetails`, `ReturnDetails`
- `QuotationDetails`, `TransferDetails`, `DeliveryDetails`, `DeliveryChallan`
- `CustomerCreate`, `SupplierCreate`, `BillerCreate`
- `PayrollDetails`, `HolidayApprove`
- `TenantCreate` — SaaS tenant onboarding email
- `AdminLogMessage`, `LogMessage`, `UserDetails`, `UserLogMessage`

---

### `app/Traits/` — 7 Reusable Traits

| Trait | Purpose |
|-------|---------|
| `TenantInfo.php` (20KB) | Multi-tenant context & data isolation |
| `AutoUpdateTrait.php` | Self-update mechanism |
| `FileHandleTrait.php` | File upload/delete utilities |
| `MailInfo.php` | Mail configuration helper |
| `StaffAccess.php` | Staff-level permission checks |
| `CacheForget.php` | Cache invalidation helper |
| `ENVFilePutContent.php` | Write to `.env` programmatically |

---

### `app/Enums/` — 3 PHP Enums

| Enum | Values |
|------|--------|
| `CustomerTypeEnum` | Customer type classification |
| `DiscountPlanTypeEnum` | Discount plan types |
| `RewardPointTypeEnum` | Reward point calculation types |

---

### `app/Contracts/`

- `Payble/` — Payment contract interfaces
- `Sms/` — SMS provider interface (`ISmsModel`)

### `app/ViewModels/`

- `ISmsModel.php` — Interface for SMS model
- `SmsModel.php` — Concrete SMS ViewModel

### `app/Providers/`

| Provider | Purpose |
|---------|---------|
| `AppServiceProvider.php` | Boot services, macros, custom validators |
| `AuthServiceProvider.php` | Auth policies |
| `EventServiceProvider.php` | Event–Listener bindings |
| `RouteServiceProvider.php` | Route loading & rate limiting |
| `BroadcastServiceProvider.php` | WebSocket broadcasting |

### `app/Helpers/helpers.php`

Global helper functions auto-loaded via Composer for use throughout the app.

### `app/Console/`

Artisan commands and scheduled tasks (cron jobs).

### `app/Notifications/`

- `SendNotification.php` — Laravel notification for in-app alerts

### `app/Exceptions/`

Custom exception handlers.

---

## `Modules/` Directory

Uses [nwidart/laravel-modules](https://nwidart.com/laravel-modules). Active modules (from `modules_statuses.json`):

| Module | Status |
|--------|--------|
| `Manufacturing` | ✅ Enabled |
| `Woocommerce` | ✅ Enabled |
| `Ecommerce` | ✅ Enabled |
| `Middleware` | ✅ Enabled |
| `Restaurant` | ✅ Enabled |
| `Project` | ✅ Enabled |

### `Modules/Manufacturing/`

Self-contained module with its own MVC structure:

```
Manufacturing/
├── Config/
├── Console/
├── Database/          # Module-specific migrations & seeders
├── Entities/
│   ├── Production.php         # Production batch model
│   └── ProductProduction.php  # Products in a production batch
├── Http/
│   └── Controllers/
│       ├── ManufacturingController.php  # Module entry
│       ├── ProductionController.php     # Production runs
│       └── RecipeController.php        # Bill of Materials / recipes
├── Providers/
├── Resources/         # Module-specific views
├── Routes/
├── Tests/
├── module.json        # Module metadata
└── composer.json      # Module dependencies
```

**Key Features:**
- **Recipes (BOM):** Define raw material ingredients per finished product
- **Productions:** Convert raw materials → finished goods with wastage tracking
- Products have `is_recipe`, `combo_wastage_percent`, `production_cost` fields

---

## `database/` Directory

### Migrations — 257 Files (2014–2025)

Chronological history of the database schema. Key migration groups:

| Period | Additions |
|--------|-----------|
| 2018 | Core tables: products, sales, purchases, customers, payments |
| 2019 | Variants, batches, stock count, HRM foundations |
| 2020 | Cash registers, currencies, notifications, deliveries |
| 2021 | IMEI tracking, discount plans, reward points |
| 2022 | Order discounts, embedded products, daily sale objectives |
| 2023 | ZATCA (Saudi e-invoicing), restaurant tables, custom fields, mail settings |
| 2024 | Packing slips, challans, barcodes, thermal invoice sizes, income module |
| 2025 | Printers, shifts, overtime, leaves, installment plans, reward points v2, WhatsApp, invoice schemas, mobile tokens, soft deletes |

### Seeders

- `DatabaseSeeder.php` — Root seeder
- `Tenant/` — Tenant-specific seed data
- `translations/` — Multi-language seed data

---

## `routes/` Directory

| File | Purpose |
|------|---------|
| `web.php` (46KB) | All web UI routes (auth, admin, POS, reports) |
| `api.php` (30KB) | REST API routes (mobile app, integrations) |
| `console.php` | Artisan schedule definitions |
| `channels.php` | Broadcast channel authorization |

---

## `resources/` Directory

```
resources/
├── assets/        # Static images, icons
├── js/            # JavaScript files (Alpine.js, custom scripts)
├── sass/          # SCSS stylesheets
└── views/
    ├── backend/   # All admin panel Blade templates (55+ modules)
    ├── components/ # Reusable Blade components
    ├── errors/    # 404, 500, etc.
    ├── includes/  # Partials (header, sidebar, footer)
    ├── install/   # Installation wizard views
    ├── vendor/    # Vendor-published views
    └── version_upgrade/ # Upgrade UI views
```

### `resources/views/backend/` — 55+ Feature Modules

Each subdirectory contains Blade templates for CRUD (index, create, edit, show):

`account`, `adjustment`, `attendance`, `barcode`, `biller`, `brand`, `cash_register`, `category`, `challan`, `coupon`, `courier`, `currency`, `custom_field`, `customer`, `customer_group`, `delivery`, `department`, `discount`, `discount_plan`, `employee`, `expense`, `expense_category`, `gift_card`, `hrm`, `income`, `income_category`, `installment_plans`, `labels`, `mail`, `money_transfer`, `notification`, `packing_slip`, `printer`, `product`, `purchase`, `quotation`, `report`, `return`, `return_purchase`, `role`, `sale`, `setting`, `sms_templates`, `stock_count`, `supplier`, `table`, `tax`, `transfer`, `unit`, `user`, `warehouse`, `whatsapp`

Notable standalone views:
- `index.blade.php` (42KB) — Main dashboard
- `customer_index.blade.php` (52KB) — Full customer management UI
- `forms.blade.php` (35KB) — Shared form components
- `charts.blade.php` (13KB) — Chart configurations

---

## `config/` Directory — 19 Configuration Files

| File | Purpose |
|------|---------|
| `app.php` | App name, timezone, providers, aliases |
| `auth.php` | Guards, providers, password resets |
| `database.php` | MySQL, SQLite, Redis connections |
| `modules.php` | nwidart/laravel-modules configuration |
| `printing.php` | PrintNode & ESC/POS printer config |
| `translation.php` | Multi-language support config |
| `sanctum.php` | API token authentication |
| `mail.php` | Mail driver and SMTP configuration |
| `queue.php` | Queue driver and connections |
| `cache.php` | Cache driver settings |
| `logging.php` | Log channels (stack, daily, slack) |
| `filesystems.php` | Local & S3 disk configuration |
| `broadcasting.php` | Pusher/WebSocket config |
| `session.php` | Session driver and lifetime |
| `auto_update.php` | Auto-update feature config |
| `debugbar.php` | Laravel Debugbar (dev only) |

---

## Key PHP Dependencies (`composer.json`)

| Package | Purpose |
|---------|---------|
| `laravel/framework ^10.15` | Core framework |
| `laravel/sanctum ^3.3` | API token authentication |
| `laravel/socialite ^5.23` | OAuth (Google, Facebook login) |
| `spatie/laravel-permission ^5.8` | Role-based access control |
| `nwidart/laravel-modules ^8.3` | Modular application structure |
| `barryvdh/laravel-dompdf` | PDF generation (invoices, reports) |
| `maatwebsite/excel ^3.1` | Excel import/export |
| `milon/barcode ^10.0` | Barcode/QR code generation |
| `mike42/escpos-php ^4.0` | Thermal printer ESC/POS commands |
| `intervention/image ^3` | Image upload & manipulation |
| `twilio/sdk ^6.10` | Twilio SMS |
| `razorpay/razorpay ^2.9` | Razorpay payment gateway |
| `srmklive/paypal ^3.0` | PayPal integration |
| `stripe/stripe-php ^7.57` | Stripe payment gateway |
| `xendit/xendit-php ^5.0` | Xendit payment gateway |
| `salla/zatca ^2.0` | Saudi Arabia ZATCA e-invoicing |
| `automattic/woocommerce ^3.1` | WooCommerce REST API sync |
| `guzzlehttp/guzzle ^7.0` | HTTP client |
| `kwn/number-to-words ^1.12` | Number to words (invoice amounts) |
| `laravel/ui ^4.0` | Auth scaffolding (Bootstrap) |
| `laravelcollective/html ^6.2` | HTML/Form helpers |
| `gladcodes/keygen ^2.0` | License key generation |

---

## Key Features Summary

### 1. Point of Sale (POS)
- Touch-friendly POS interface with barcode scanner support
- Cash register management (open/close with float)
- Hold orders, layaway, split payments
- Coupon & gift card redemption
- Reward points earn & redeem
- Table management (Restaurant mode)
- Thermal receipt printing (ESC/POS + PrintNode)
- Customer-facing display support

### 2. Inventory Management
- Multi-warehouse stock tracking
- Product variants (size, color, etc.)
- Batch/expiry date tracking
- IMEI/Serial number tracking
- Combo products & bundle kits
- Barcode/QR code generation & label printing
- Stock adjustments & physical stock count
- Inter-warehouse transfers
- Daily sale objective (DSO) alerts
- Profit margin management

### 3. Sales & Purchases
- Full sales lifecycle: quotation → sale → delivery → return
- Purchase order management with supplier returns
- Installment payment plans
- Multi-currency support with exchange rates
- Packing slips & delivery challans
- ZATCA-compliant e-invoicing (Saudi Arabia)

### 4. Financial Management
- Chart of Accounts (COA)
- Income & expense tracking
- Money transfers between accounts
- Payroll processing
- Customer deposits
- Payment gateway integrations: PayPal, Stripe, Razorpay, Xendit, Pesapal

### 5. HRM (Human Resource Management)
- Employee profiles with designations & departments
- Shift management
- Attendance tracking
- Leave management with approval workflow
- Overtime management
- Payroll with deductions & allowances
- Holiday management

### 6. Reporting
- Sales, purchase, profit & loss reports
- Stock valuation & movement reports
- Customer & supplier ledgers
- Tax reports
- Attendance & payroll reports
- Expense & income reports
- Cash register reports
- Custom date range & warehouse filtering

### 7. Manufacturing Module
- Bill of Materials (BOM) / Recipe management
- Production run tracking
- Raw material consumption with wastage %
- Finished goods auto-stock update

### 8. eCommerce & Integrations
- WooCommerce sync (products, orders, customers)
- WhatsApp notifications
- SMS notifications (6 gateways)
- Email notifications (18 templates)
- Multi-language & RTL support
- REST API for mobile apps (Laravel Sanctum)

### 9. Multi-Tenant (SaaS)
- Tenant isolation via `TenantInfo` trait
- cPanel API integration for auto-provisioning
- Separate databases per tenant
- Subscription management

### 10. System & Security
- Role-based access control (Spatie Permissions)
- Super-admin level access
- Activity logging
- CSRF protection
- CORS configuration
- Self-update mechanism
- Addon/module installation system
- Installation wizard

---

## Architecture Pattern

```
Request → Middleware → Controller → FormRequest (Validation)
                                  ↓
                             Service Layer (optional)
                                  ↓
                           Eloquent Model / Query
                                  ↓
                        API Resource / Blade View
                                  ↓
                           JSON Response / HTML
```

- **Web routes** return Blade-rendered HTML views
- **API routes** return JSON via Laravel API Resources
- **Services** handle complex business logic (payments, printing, SMS)
- **Traits** provide reusable cross-cutting concerns
- **Modules** provide self-contained feature sets (Manufacturing, Ecommerce, etc.)

---

## Database Overview

The application uses **MySQL** with **257+ migrations** defining the full schema. Key relationships:

- `sales` → `product_sales` → `products`
- `purchases` → `product_purchases` → `products`
- `products` → `product_warehouse` → `warehouses`
- `sales` → `payments` → `accounts`
- `customers` → `sales`, `returns`, `deposits`, `reward_points`
- `employees` → `attendances`, `payrolls`, `leaves`, `overtimes`
- `productions` → `product_productions` → `products` (Manufacturing)

---

*Generated automatically by Antigravity AI — June 2026*
