Operations Module Overview
Introduction
The Operations Module is the core inventory and supply chain management system of the CRM/ERP platform. It provides comprehensive functionality for product catalog management, multi-warehouse inventory tracking, purchase order workflows, and stock movement auditing. Built using Domain-Driven Design (DDD) principles, it serves as the reference implementation for CQRS patterns used throughout the application.
Purpose and Scope
The Operations module handles all aspects of product operations:
- Product Catalog - Manage simple and master/variant products
- Inventory Management - Multi-warehouse stock tracking with reservations
- Purchase Orders - Complete supplier ordering workflow
- Stock Movements - Immutable audit trail for compliance
- Warehouse Management - Multi-location inventory control
- Product Attributes - Flexible EAV (Entity-Attribute-Value) system
- Supplier Management - Vendor relationships and performance tracking
Key Features
1. Product Management
Simple Products
- Single SKU, straightforward inventory tracking
- Suitable for unique items or non-varying products
- Direct pricing and stock management
Master/Variant Products
- Master product defines configuration (attributes like size, color)
- Automatic variant generation (cartesian product of attributes)
- Individual SKU, pricing, and inventory per variant
- Ideal for e-commerce catalogs with variations
Product Lifecycle
Draft → Active → Discontinued- Draft: New products under development
- Active: Available for sale, inventory tracked
- Discontinued: No longer sold, historical data preserved
2. Multi-Warehouse Inventory
Stock Tracking
- Track inventory across unlimited warehouses
- Real-time available vs reserved stock calculation
- Reorder point monitoring with auto-alerts
- Physical count reconciliation
Warehouse Types
- Main Warehouse: Primary distribution center
- Satellite Warehouse: Regional fulfillment locations
- Virtual Warehouse: Dropshipping or external stock
- Consignment Warehouse: Supplier-owned inventory on premises
Stock Reservations
- Reserve stock for pending orders
- Automatic release on cancellation
- Prevents overselling
- Configurable reservation timeouts
3. Purchase Order Workflow
Complete procurement lifecycle from requisition to receipt:
graph LR
A[Draft] --> B[Approved]
B --> C[Sent to Supplier]
C --> D[Partial Received]
C --> E[Fully Received]
D --> E
E --> F[Closed]
A -.Cancel.-> G[Cancelled]
B -.Cancel.-> G
C -.Cancel.-> GWorkflow Stages:
- Draft - Create PO, add line items
- Approved - Management approval obtained
- Sent - Transmitted to supplier
- Partial Received - Some items received
- Fully Received - All items received
- Closed - PO completed and archived
Key Features:
- Multi-item purchase orders
- Partial receiving support
- Automatic inventory updates on receipt
- Supplier performance tracking
- Overdue order monitoring
- Auto-generation from low stock alerts
4. Stock Movement Tracking
Immutable audit trail for regulatory compliance:
Movement Types:
- IN: Stock received (from suppliers)
- OUT: Stock sold or consumed
- ADJUSTMENT: Manual corrections (physical counts)
- TRANSFER: Inter-warehouse movements
- RESERVATION: Stock reserved for orders
- RELEASE: Reservation released
Audit Information:
- Timestamp (immutable)
- User who initiated movement
- Source and destination warehouses
- Quantity and product details
- Related transaction (PO, order, adjustment)
- Reason/notes
5. Product Attributes (EAV)
Flexible attribute system for custom product properties:
Attribute Types:
- TEXT: Short text values
- TEXTAREA: Long descriptions
- NUMBER: Numeric values
- BOOLEAN: Yes/No flags
- DATE: Date values
- SELECT: Single choice from options
- MULTISELECT: Multiple choices
Use Cases:
- Product specifications (weight, dimensions, material)
- Variant attributes (size, color, style)
- Custom properties per category
- Marketing attributes (eco-friendly, bestseller)
Architecture Overview
The Operations module follows strict DDD layering:
┌─────────────────────────────────────────────────────┐
│ Presentation Layer │
│ Controllers, Requests, Resources, Routes │
└─────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────┐
│ Application Layer │
│ Commands, Queries, Handlers, DTOs, Services │
└─────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────┐
│ Domain Layer │
│ Models, ValueObjects, Events, Services, Contracts │
└─────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────┐
│ Infrastructure Layer │
│ Repositories, Persistence, External Services │
└─────────────────────────────────────────────────────┘Layer Responsibilities
Presentation Layer (Presentation/)
- HTTP request handling
- Input validation (Form Requests)
- Response formatting (API Resources)
- Route definitions
- No business logic
Application Layer (Application/)
- Use case orchestration
- CQRS implementation (Commands/Queries)
- DTO transformations
- Application services
- Transaction boundaries
Domain Layer (Domain/)
- Core business logic
- Domain models (entities)
- Value Objects (Money, SKU, Quantity)
- Domain events
- Business rules validation
- Framework-agnostic
Infrastructure Layer (Infrastructure/)
- Data persistence (repositories)
- Database migrations
- External API integrations
- Framework-specific implementations
CQRS Pattern Implementation
The Operations module implements Command Query Responsibility Segregation as the gold standard:
Commands (Write Operations)
Commands represent intent to change state:
// Create a product
$command = new CreateProductCommand(
dto: CreateProductDTO::fromArray($request->validated())
);
$product = $this->commandBus->dispatch($command);Key Commands:
CreateProductCommand- Create new productUpdateProductCommand- Modify existing productActivateProductCommand- Change status to activeAdjustStockCommand- Update inventory levelsCreatePurchaseOrderCommand- Create new POReceivePurchaseOrderCommand- Process goods receipt
Queries (Read Operations)
Queries retrieve data without side effects:
// Get products with filters
$query = new GetProductsQuery(
filterDTO: ProductFilterDTO::fromArray($request->getFilters())
);
$products = $this->queryBus->dispatch($query);Key Queries:
GetProductsQuery- List products with filtersGetProductByIdQuery- Single product detailsGetLowStockProductsQuery- Products below reorder pointGetPurchaseOrdersQuery- List POs with filtersGetInventoryByWarehouseQuery- Warehouse stock levels
Benefits
- Clear separation - Reads and writes are explicit
- Testability - Commands and queries tested independently
- Optimization - Read and write paths optimized separately
- Maintainability - Business logic isolated in handlers
- Transaction management - CommandBus handles transactions automatically
Domain Models
Core Entities
Product (app/Modules/Operations/Domain/Models/Product.php)
- Aggregate root for product catalog
- Manages simple and master products
- Handles lifecycle transitions
- Emits domain events (
ProductCreated,ProductActivated, etc.)
Inventory (app/Modules/Operations/Domain/Models/Inventory.php)
- Tracks stock per product per warehouse
- Manages available vs reserved quantities
- Enforces reorder points
- Validates stock sufficiency
PurchaseOrder (app/Modules/Operations/Domain/Models/PurchaseOrder.php)
- Aggregate root for procurement
- Manages PO lifecycle and workflow
- Handles partial receiving
- Calculates totals and validates line items
Warehouse (app/Modules/Operations/Domain/Models/Warehouse.php)
- Defines storage locations
- Manages warehouse types
- Tracks capacity and settings
StockMovement (app/Modules/Operations/Domain/Models/StockMovement.php)
- Immutable audit record
- Records all inventory transactions
- Compliance and reconciliation support
Value Objects
Money (app/Shared/Domain/ValueObjects/Money.php)
- Represents monetary amounts
- Stored as integers (cents) for precision
- Currency-aware calculations
- Prevents floating-point errors
SKU (app/Modules/Operations/Domain/ValueObjects/SKU.php)
- Product identification code
- Validation and formatting
- Uniqueness enforcement
Quantity (app/Modules/Operations/Domain/ValueObjects/Quantity.php)
- Stock quantity with unit of measure
- Arithmetic operations
- Negative value prevention
StockLevel (app/Modules/Operations/Domain/ValueObjects/StockLevel.php)
- Available vs reserved stock
- Reorder point checking
- Stock status calculation
ProductDimensions (app/Modules/Operations/Domain/ValueObjects/ProductDimensions.php)
- Length, width, height, weight
- Shipping calculations
- Storage planning
Domain Events
Operations module emits events for cross-module integration:
Product Events
ProductCreated- New product added to catalogProductUpdated- Product details changedProductActivated- Product became availableProductDeactivated- Product removed from saleProductDiscontinued- Product permanently discontinued
Inventory Events
InventoryAdjusted- Stock level manually adjustedStockReserved- Inventory reserved for orderStockReleased- Reservation cancelledLowStockDetected- Product below reorder pointOutOfStockDetected- Product completely depleted
Purchase Order Events
PurchaseOrderCreated- New PO initiatedPurchaseOrderApproved- PO approved for sendingPurchaseOrderSent- PO transmitted to supplierPurchaseOrderReceived- Goods receipt completedPurchaseOrderCancelled- PO cancelled
Stock Movement Events
StockMovementRecorded- Audit entry createdWarehouseTransferCompleted- Inter-warehouse transfer done
API Structure
All Operations endpoints follow REST conventions:
Base Path: /api/v1/operations
Resource Groups
| Resource | Endpoints | Description |
|---|---|---|
/products | 14 | Product CRUD and lifecycle |
/purchase-orders | 14 | PO workflow management |
/inventory | 12 | Stock tracking and adjustments |
/master-products | 5 | Variant generation |
/categories | 9 | Product categorization |
/stock-movements | 9 | Audit trail queries |
/tags | 8 | Product tagging |
/suppliers | 7 | Vendor management |
/brands | 7 | Brand management |
/attributes | 6 | EAV attribute definitions |
/warehouses | 5 | Warehouse management |
/attribute-values | 2 | Attribute value operations |
Total: 99 endpoints
API Documentation
Interactive API documentation available via Scramble UI:
- URL:
https://api.crm.test:40443/docs/api - OpenAPI Spec:
https://api.crm.test:40443/docs/api.json
Try-it-out functionality for testing all endpoints directly.
Technology Stack
Backend
- Laravel 12 - PHP framework
- PHP 8.3+ - Language version
- MySQL 8.0 - Primary database
- Redis - Caching and queue backend
Architecture Patterns
- Domain-Driven Design (DDD) - Bounded contexts and ubiquitous language
- CQRS - Command Query Responsibility Segregation
- Event-Driven Architecture - Domain events for decoupling
- Repository Pattern - Data access abstraction
Supporting Libraries
- Spatie Laravel Multitenancy - Database-per-tenant isolation
- Laravel Sanctum - API authentication
- Scramble - OpenAPI documentation generation
- Laravel Horizon - Queue monitoring
Directory Structure
app/Modules/Operations/
├── Application/
│ ├── Commands/ # Write operations (CQRS)
│ ├── Queries/ # Read operations (CQRS)
│ ├── Handlers/ # Command/Query handlers
│ ├── DTOs/ # Data Transfer Objects
│ └── Services/ # Application services
├── Domain/
│ ├── Models/ # Eloquent models (entities)
│ ├── ValueObjects/ # Immutable value objects
│ ├── Events/ # Domain events
│ ├── Services/ # Domain services
│ ├── Contracts/ # Interfaces
│ ├── Enums/ # Domain enumerations
│ └── Exceptions/ # Domain exceptions
├── Infrastructure/
│ ├── Repositories/ # Repository implementations
│ └── Persistence/
│ └── Migrations/ # Database schema
└── Presentation/
├── Controllers/ # HTTP controllers
├── Requests/ # Form request validation
├── Resources/ # API response formatters
└── Routes/ # Route definitionsQuick Start
1. Explore the API
Visit the interactive documentation:
https://api.crm.test:40443/docs/apiBrowse Operations endpoints and try sample requests.
2. Create Your First Product
# Authenticate
curl -X POST https://api.crm.test/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"admin@example.com","password":"password"}'
# Create product
curl -X POST https://api.crm.test/api/v1/operations/products \
-H "Authorization: Bearer {token}" \
-H "Content-Type: application/json" \
-d '{
"name": "Laptop - Dell XPS 13",
"sku": "DELL-XPS13-001",
"selling_price": 99999,
"cost_price": 75000,
"stock_quantity": 10,
"reorder_point": 5
}'See the Creating Products Tutorial for complete walkthrough.
3. Generate Product Variants
# Create master product
curl -X POST https://api.crm.test/api/v1/operations/products \
-H "Authorization: Bearer {token}" \
-d '{
"name": "T-Shirt - Cotton Basic",
"type": "master",
"variant_attributes": {
"Size": ["S", "M", "L", "XL"],
"Color": ["Red", "Blue", "Black"]
}
}'
# Generate all variants (12 combinations)
curl -X POST https://api.crm.test/api/v1/operations/master-products/1/variants/generate \
-H "Authorization: Bearer {token}" \
-d '{
"auto_generate_sku": true,
"sku_prefix": "TSHIRT-",
"initial_stock": 0
}'See the Product Variants Guide for details.
4. Create a Purchase Order
# Create draft PO
curl -X POST https://api.crm.test/api/v1/operations/purchase-orders \
-H "Authorization: Bearer {token}" \
-d '{
"supplier_id": 1,
"expected_delivery_date": "2025-02-15",
"items": [
{
"product_id": 1,
"quantity": 50,
"unit_price": 750.00
}
]
}'
# Approve PO
curl -X POST https://api.crm.test/api/v1/operations/purchase-orders/1/approve \
-H "Authorization: Bearer {token}"
# Receive goods
curl -X POST https://api.crm.test/api/v1/operations/purchase-orders/1/receive \
-H "Authorization: Bearer {token}" \
-d '{
"items": [
{
"product_id": 1,
"quantity_received": 50,
"warehouse_id": 1
}
]
}'See the Purchase Order Workflow Tutorial for complete workflow.
Related Guides
Operations Features
- Product Management - Catalog management and lifecycle
- Product Variants - Master/variant products
- Multi-Warehouse Inventory - Stock tracking
- Purchase Order Workflow - Procurement process
- Warehouse Management - Location management
- Stock Movement Tracking - Audit trail
DDD Patterns
- CQRS Pattern - Command/Query separation
- Domain Events - Event-driven architecture
- Value Objects - Money, SKU, Quantity
- Aggregates - Product and PurchaseOrder
- Repository Pattern - Data access
Support and Resources
- API Reference: https://api.crm.test:40443/docs/api
- Source Code:
app/Modules/Operations/ - Tests:
tests/Feature/Operations/ - Migrations:
app/Modules/Operations/Infrastructure/Persistence/Migrations/
Next Steps
- Learn Product Management - Read the Product Management Guide
- Understand Variants - Explore the Product Variants Guide
- Try CQRS - Follow the CQRS Pattern Guide
- Build a Feature - Complete the Creating Products Tutorial