Skip to content

Develop#8

Open
SezginYurdakul wants to merge 67 commits intomasterfrom
develop
Open

Develop#8
SezginYurdakul wants to merge 67 commits intomasterfrom
develop

Conversation

@SezginYurdakul
Copy link
Copy Markdown
Owner

No description provided.

- Add 6 PHP backed enums for type-safe business logic:
  - InspectionResult, InspectionDisposition
  - NcrStatus, NcrSeverity, NcrDisposition, DefectType
- Update models to use enums via accessor attributes (*_enum)
- Keep model constants for UI labels (simple approach)
- Add QualityControlSeeder with 8 test scenarios
- Remove LookupValue complexity (YAGNI)
Remove lookup/enum-type settings (inspection_types, sampling_methods,
ncr_statuses, etc.) since these are now handled by PHP Enums and model
constants. Keep only actual configuration values like default_aql_level,
auto_create_ncr_on_failure, etc.
- ReceivingInspectionService: Use InspectionResult/InspectionDisposition Enums
- NonConformanceReportService: Use NcrStatus/NcrSeverity/NcrDisposition Enums
- NonConformanceReport: Add SOURCES/PRIORITIES constants for validation
- NonConformanceReportController: Use Model constants instead of hardcoded arrays
- Create PoStatus Enum with 8 states and state machine transitions
- Create GrnStatus Enum with 5 states and state machine transitions
- Add status_enum accessors to PurchaseOrder and GoodsReceivedNote models
- Update PurchaseOrderService to use PoStatus Enum validation
- Update GoodsReceivedNoteService to use GrnStatus Enum validation
- Add QC zone endpoints: quarantine-zones, rejection-zones, qc-zones
- Add Quarantine Zone and Rejection Zone warehouses to WarehouseSeeder
- Link QC zones to main warehouse (linked_quarantine/rejection_warehouse_id)
- Add transferToQcZone endpoint for receiving inspections
- Implement supplier quality scoring system:
  - getQualityScore() - calculates quality score (0-100) with grade (A-F)
  - getQualityStatistics() - detailed inspection stats by supplier
  - getQualityScoreRanking() - supplier ranking by quality score
- Add API routes for supplier quality endpoints
- Update test scripts with QC zone and quality score tests
Create tables for MRP II manufacturing:
- work_centers: Machine, labor, subcontract work centers
- boms + bom_items: Bill of Materials with components
- routings + routing_operations: Production routes
- work_orders + work_order_operations + work_order_materials
Define status and type enums:
- WorkCenterType: machine, labor, subcontract, tool
- BomStatus/RoutingStatus: draft, active, obsolete
- BomType: manufacturing, engineering, phantom
- WorkOrderStatus: draft, released, in_progress, completed, cancelled, on_hold
- WorkOrderPriority: low, normal, high, urgent
- OperationStatus: pending, in_progress, completed, skipped
Eloquent models with relationships:
- WorkCenter: capacity, efficiency, cost tracking
- Bom/BomItem: bill of materials with components
- Routing/RoutingOperation: production routes with work centers
- WorkOrder/WorkOrderOperation/WorkOrderMaterial: production orders
- Product: add manufacturing relationships (boms, routings, workOrders)
Business logic services:
- WorkCenterService: CRUD, capacity, availability
- BomService: CRUD, items, BOM explosion, material calculation
- RoutingService: CRUD, operations, lead time calculation
- WorkOrderService: workflow, material issue, finished goods receipt
JSON API resources for all manufacturing entities:
- WorkCenterResource/ListResource
- BomResource/ListResource/ItemResource
- RoutingResource/ListResource/OperationResource
- WorkOrderResource/ListResource/OperationResource/MaterialResource
REST API controllers:
- WorkCenterController: CRUD, toggle-active, availability
- BomController: CRUD, items, activate/obsolete, copy, explode
- RoutingController: CRUD, operations, activate
- WorkOrderController: CRUD, workflow actions, material issue/receipt
- api.php: Add all manufacturing routes with permission middleware
- RolePermissionSeeder: Add manufacturing.* permissions for roles
- ManufacturingSeeder: Work centers, BOMs, routings, work orders
- DatabaseSeeder: Include ManufacturingSeeder
- Warehouse: Handle null warehouse_type in getTypeLabelAttribute
- RoutingService: Fix reorderOperations unique constraint conflict
- Migration: Use partial unique indexes for soft-deleted records
- WorkOrderService: Fix calculateEstimatedCost using cost_price with fallback
- WorkCenter: Fix hasCapacity null handling with COALESCE for planned times
- BomService: Add include_optional parameter to explodeBom method
- Migration: Add CHECK constraints for scrap, efficiency, quantities
- Migration: Add performance indexes for BOM and Work Order queries
- Create 7 migrations for customer groups, customers, sales orders, and delivery notes
- Add SalesOrderStatus (9 states with approval workflow) and DeliveryNoteStatus enums
- Create 7 models: CustomerGroup, CustomerGroupPrice, Customer, SalesOrder, SalesOrderItem, DeliveryNote, DeliveryNoteItem
- Add 6 sales permissions and 2 new roles (sales_person, sales_manager) to RolePermissionSeeder
- Add 'qc' as standalone module in config/modules.php with MODULE_QC_ENABLED env var
- Remove quality_control feature from procurement and manufacturing modules
- Move QC routes to separate module:qc middleware group in api.php
- Move supplier quality routes inside procurement with nested module:qc middleware
- Add QC features to ModuleService cache clearing
- Fix exception handler order: ModuleDisabledException before BusinessException
- Update isQualityControlEnabled() to check qc module directly
Controllers (4 files):
- CustomerController: CRUD + code generation
- CustomerGroupController: CRUD + price management
- SalesOrderController: Full workflow (approve, reject, confirm, ship, deliver, cancel)
- DeliveryNoteController: Create from SO, ship, deliver workflow

Services (5 files):
- CustomerService: Customer CRUD with auto-generated customer codes
- CustomerGroupService: Group management with delete validation
- CustomerGroupPriceService: Quantity-based pricing with date validity
- SalesOrderService: Complete SO lifecycle with stock reservation
- DeliveryNoteService: Stock deduction on shipment, status management

Resources (12 files):
- Customer, CustomerList, CustomerGroup, CustomerGroupList, CustomerGroupPrice
- SalesOrder, SalesOrderList, SalesOrderItem
- DeliveryNote, DeliveryNoteList, DeliveryNoteItem

Migrations (2 files):
- Add payment_terms_days and credit_limit to customer_groups
- Add company_id, currency_id, is_active to customer_group_prices

Seeder:
- SalesSeeder: Creates demo customer groups, customers, sales orders, and delivery notes
Required by SalesOrderService::getStatuses() for UI status display.
- Add SeederModeTrait for minimal/demo mode switching
- Add db:seed-fresh artisan command with --demo flag
- Update DatabaseSeeder with dual-mode support
- Transform all seeders from Electronics to Agricultural Machinery sector
- Update NCR seeders to use enum classes instead of deprecated constants
- Add pallet and drum units for manufacturing scenarios

Usage:
  php artisan db:seed-fresh          # Minimal mode (system essentials)
  php artisan db:seed-fresh --demo   # Demo mode (with sample data)
- Add UomType PHP enum with 16 types for multi-sector support
- Change uom_type column from enum to varchar in migration
- Update UnitOfMeasure model to cast uom_type to UomType enum
- Remove deprecated TYPES constant from UnitOfMeasure model
- Update UnitOfMeasureController to use UomType::options()
- Create product_uom_conversions table for material-specific conversions
- Add ProductUomConversion model with convert/reverseConvert methods
- Add ProductUomConversionService for business logic
- Add ProductUomConversionController with full CRUD + bulk operations
- Add API routes under /products/{id}/uom-conversions
- Add uomConversions relationship and convertQuantity method to Product
- Remove deprecated category() method from Product model
- Add ProductUomConversionSeeder with sample data

Implements hybrid conversion approach:
- Standard conversions: units_of_measure table (1 kg = 1000 g)
- Product-specific: product_uom_conversions table (1 box of X = 24 pcs)
- Remove deprecated STATUS_*, SEVERITY_*, DISPOSITION_* constants
- Remove deprecated STATUSES, SEVERITIES, DISPOSITIONS arrays
- Update scopeOpen to use NcrStatus enum
- Update scopeCriticalOrMajor to use NcrSeverity enum
- Merge add_planning_fields_to_products into create_products_table
- Merge add_low_level_code_to_products into create_products_table
- Merge add_qc_fields into create_warehouses_table, create_stock_table, create_stock_movements_table
- Merge add_terms_to_customer_groups into create_customer_groups_table
- Merge add_fields_to_customer_group_prices into create_customer_group_prices_table
- Delete redundant add_ migration files for cleaner migration history
- Add MrpRunStatus enum (pending, running, completed, failed, cancelled)
- Add MrpRecommendationType enum (PURCHASE_ORDER, WORK_ORDER)
- Add MrpRecommendationStatus enum (pending, approved, rejected)
- Add MrpPriority enum (low, normal, high, urgent)
- Add MrpRun model for MRP execution tracking
- Add MrpRecommendation model for purchase/work order recommendations
- Create migration for mrp_runs and mrp_recommendations tables
- Include fields for planning horizon, filters, status tracking
- Implement MrpCacheService for Low-Level Code caching
- Add BOM structure caching to reduce database queries
- Implement distributed locking to prevent concurrent MRP runs
- Add progress tracking using Redis
- Support dirty products tracking for incremental MRP
- Cache TTL: 4 hours, Lock TTL: 3 hours
- Add BomObserver to invalidate cache on BOM changes
- Add ProductObserver to invalidate cache on MRP field changes
- Add CompanyCalendarObserver to invalidate cache on calendar changes
- Register observers in AppServiceProvider
- Mark products as dirty for incremental MRP
…tem settings

- Add mrp.working_days setting (default: Monday-Friday)
- Mark mrp.working_days as system setting (admin-only modification)
- Add shift configuration settings
- Enforce admin-only modification for system settings in SettingController
- Update ProductSeeder to calculate Low-Level Codes after seeding
- Register observers in AppServiceProvider
- Split routes into separate files by module (auth, core, products, inventory, etc.)
- Update main api.php to require modular route files
- Update seeders for consistency
- Fix customer_code field usage in CustomerService and Resources
- Add payment_terms_days and credit_limit defaults in CustomerService
- Add auto code generation in CustomerGroupService
- Add missing relationships (groupPrices, currency)
- Add customer permissions to admin role in RolePermissionSeeder
- Fix issueStock call to use array parameter format
- Add customer_id to delivery note creation
- Fix quantity_shipped field usage in DeliveryNoteService
- Add CONFIRMED status to DeliveryNoteStatus enum
- Add createdBy relationship to DeliveryNote model
- Fix quantity_ordered usage in SalesOrderItemResource
- Update DeliveryNoteStatus transitions and canEdit logic
- Add grouped warnings summary instead of flat array
- Add warnings_summary JSON column to mrp_runs table
- Improve warehouse filter with include/exclude options
- Add getTotalWarningsCount and getWarningsSummary methods
- Update markAsCompleted to accept warnings summary
- Add explodeAllLevels parameter to explode all sub-BOMs
- Add aggregateByProduct parameter for quantity aggregation
- Add asTree parameter for hierarchical tree structure
- Improve explode endpoint with auto-detection of BOM levels
- Add buildTreeStructure and aggregateMaterialsByProduct methods
- Add mrpRecommendation relationship to PurchaseOrder
- Add mrpRecommendation relationship to WorkOrder
- Add createdBy alias to SalesOrder
- Rename approver to approvedBy in SalesOrder for consistency
- Replace STATUSES constant with NcrStatus enum
- Replace SEVERITIES constant with NcrSeverity enum
- Replace DISPOSITIONS constant with NcrDisposition enum
- Update getStatuses, getSeverities, getDispositions methods to use enums
- Add null check before accessing supplier defaults
- Prevent errors when supplier_id is null in create method
- Update routes and config files
- Minor fixes in services and migrations
- Code cleanup and consistency improvements
- Automatically reserve stock for all items when sales order is confirmed
- Automatically release reservations when order is cancelled or rejected
- Automatically release reservations when delivery note is shipped (physical stock issued)
- Release reservations if order status changes from CONFIRMED to another status
- Manual reservation endpoints remain available for flexibility
- Added reserveStockForOrder() and releaseStockForOrder() helper methods
- Add over_delivery_tolerance_percentage field to purchase_order_items table
- Implement 4-level fallback hierarchy: Order Item → Product → Category → System Default
- Add tolerance validation in GoodsReceivedNoteService.addItems()
- Support multiple partial GRNs with total quantity control (including DRAFTs)
- Log warnings when tolerance is used
- Update SYSTEM_DESIGN.md with comprehensive over-delivery tolerance documentation (Section 6.7)
- Renumber Manufacturing section from 6.7 to 6.8

This feature allows flexible over-delivery control for purchase orders while
preventing excessive quantities through hierarchical tolerance settings.
- Remove Auth::id() fallback from MrpRecommendation::reject() and markAsActioned()
- Remove Auth::id() fallback from Stock::placeQualityHold() and setConditionalStatus()
- Remove use Illuminate\Support\Facades\Auth imports from models
- Update MrpService to pass Auth::id() as parameter to model methods

This improves testability and follows separation of concerns principle.
…l table migrations

- Add over_delivery_tolerance_percentage to categories table migration
- Add over_delivery_tolerance_percentage to products table migration
- Add over_delivery_tolerance_percentage to sales_order_items table migration
- Add over_delivery_tolerance_percentage to purchase_order_items table migration
- Remove separate "add" migration files (4 files deleted)

This consolidates schema changes into original migrations for cleaner migration history.
… orders

- Add over_delivery_tolerance_percentage field to categories, products, sales_order_items, and purchase_order_items tables
- Implement 5-level fallback logic: Order Item > Product > Category > Company > System Default
- Add tolerance validation in DeliveryNoteService for sales orders
- Add tolerance validation in GoodsReceivedNoteService for purchase orders
- Create OverDeliveryToleranceController with CRUD endpoints for company-specific settings
- Update SYSTEM_DESIGN.md with over-delivery tolerance system documentation
- Prevent over-delivery exceeding tolerance limits with detailed error messages

This allows flexible control over delivery quantity tolerances at multiple levels.
…th routes

- Update AuthController::me() to use UserResource for consistent response format
- Load company and roles relationships before returning user data
- Add 401 response when user is not authenticated
- Add auth:sanctum middleware to protected auth routes (logout, me, refresh)

This ensures consistent user data structure across API responses and proper authentication.
- Add StockDebt model and migration to track negative stock occurrences
- Implement StockDebtController with CRUD endpoints for debt management
- Add StockAlertService to monitor and alert on stock debts
- Create AllowNegativeStock validation rule for order processing
- Update StockService with negative stock policy logic:
  - canGoNegative() method checks policy and limits
  - createStockDebt() records negative stock transactions
  - reconcileStockDebts() automatically reconciles debts on stock receipt
  - Support for NEVER, ALLOWED, and LIMITED policies
- Add negative_stock_policy and negative_stock_limit fields to Product model
- Update ProductController with validation for negative stock policy
- Include negative stock policy fields in ProductResource responses
- Add API routes for stock debt management

This system allows controlled negative stock scenarios while tracking
all debt occurrences for reconciliation and reporting purposes.
…n for work orders

- Create ReservationPolicy enum with FULL, PARTIAL, REJECT, and WAIT policies
- Implement reservation policy logic in StockService::reserveStock()
  - FULL: Only reserve if full quantity available
  - PARTIAL: Reserve available quantity even if less than requested
  - REJECT: Reject reservation if insufficient stock
  - WAIT: Queue for future auto-retry (TODO: requires queue implementation)
- Add automatic material reservation in WorkOrderService:
  - Automatically reserve materials when work order is released
  - Automatically release reservations when work order is cancelled
  - Automatically release reservations when materials are issued
- Add reserveMaterialsForOrder() and releaseMaterialsForOrder() helper methods
- Add transaction handling and error logging for reservation operations

This complements the reservation_policy field added to Product model
in previous commit, allowing flexible reservation behavior based on
product-level policies.
- Remove system-level tolerance from DeliveryNoteService and GoodsReceivedNoteService
- Update OverDeliveryToleranceController to remove system-level references
- Company-level is now the final fallback (no system-level in SaaS)
- Update documentation to reflect 4-level fallback instead of 5-level
- Add BelongsToCompany trait to User model with strict mode
- Add scopeForLogin() for authentication (bypasses company scope)
- Implement strict security check in withoutCompanyScope() - only platform admins (company_id = null) can bypass
- Update CompanyScope to skip scope for platform admins
- Add company ownership checks in UserController (show, update, destroy, restore, forceDelete)
- Update UserService to set company_id from authenticated user
- Update AuthController login to validate company (skip for platform admins)
- Update AuthController register to require company_id
- Add platform_admin role in RolePermissionSeeder with all permissions
- Create platform admin user (company_id = null) in UserSeeder
- Add BelongsToCompany trait to CompanyCalendar model

Security improvements:
- Normal company admins cannot bypass company isolation
- Platform admins (company_id = null) can access all companies
- Strict mode prevents unauthorized cross-company access
…er changes

- Fix undefined $company variable in SalesSeeder.php (line 59)
- Add Company model import and proper company initialization
- Revert ProductPriceObserver changes (removed observer registration)
- All number generation services now use NumberFormatService
- Unique constraints updated for categories, products, and product_variants (company-scoped)
- Seeders updated to support multiple companies
…r type

- Change validation rule for company_id in the register method from 'required|exists:companies,id' to 'required|integer|exists:companies,id' to ensure proper data type handling.
…ail template

- Make role_ids field required in invitation creation (min 1 role)
- Update email template: change 'Create Account' to 'Accept Invitation'
- Add InvitationController, InvitationService, UserInvitation model
- Add invitation email template and UserInvitationMail mailable
- Add user invitations table migration
- Add invitation routes to API
- Add soft-deleted user check in UserService (prevent duplicate emails)
- Improve role_ids validation: add required and integer rules
- Fix role assignment: check for empty array before assigning
- Change fresh(['roles']) to load('roles') for better performance
- Add Mailpit service to docker-compose for local email testing
- Add mail environment variables to backend service
- Update Postman environment with invitation-related variables
- Add AuditLogService for centralized audit logging
- Add AuditLog model and audit_logs table migration
- Add Blameable trait for automatic user tracking (created_by, updated_by, deleted_by)
- Add LogAuditEvent queue job for async logging
- Add audit configuration file with sync/async, retention, and critical events settings
- Integrate audit logging into Observers (Product, BOM, BomItem, CompanyCalendar)
- Add business event logging to Services (SalesOrder, PurchaseOrder, WorkOrder, MRP)
- Optimize ProductObserver: remove unnecessary MRP cache invalidation on creation
- Optimize AuditLogService: exclude Blameable fields (updated_by, deleted_by) from change tracking
- Add Blameable trait to Product model with migration
- Support field-level change tracking, sensitive field masking, and company isolation

Features:
- Async logging via queue (non-blocking)
- Field-level change tracking
- Sensitive field masking
- Company isolation
- Transaction-safe logging (afterCommit)
- Retry mechanism for failed jobs

Coverage:
- 4 Observers with CRUD event logging
- 4 Services with business event logging
- 13 different event types
- ~1000 lines of code added/updated
…ling

- Fix MRP net requirement calculation to handle negative stock scenarios
- Add BOM validation before creating Work Order recommendations
- Fix priority mapping from MRP (critical) to Work Order (urgent)
- Add uom_id to Work Order creation from MRP recommendations
- Fix bulkApprove to create Purchase Orders/Work Orders (not just approve status)
- Fix sales order expected_delivery_date to requested_delivery_date mapping
- Remove billing_address field from sales orders (not in database)
- Fix CapacityController date parameter parsing (DateTimeInterface)
- Standardize sales order endpoints (submit, mark-as-shipped, mark-as-delivered)
- Add Redis Commander service to docker-compose for development
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant