• Overview

    **LIFE** (LEGO Integrated Factory Execution) is a production-ready prototype that modernizes manufacturing operations through intelligent digital workflows. The platform provides:

  • Acknowledgement

    - **Spring Boot** team for the excellent framework - **React** community for the vibrant ecosystem - **Docker** for simplifying deployment - LEGO Group for inspiration

  • License

    This project is licensed under the **MIT License** - see the [LICENSE](LICENSE) file for details.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.

 
Software Development Specification

1. Project Overview & Objectives

This document serves as a detailed specification for developing a digital control system for the LEGO Sample Factory, based on the requirements and analyses presented in the thesis “DATA FLOW DESIGN AND TESTING OF AN IOS BASED APPLICATION FOR DIGITAL INTEGRATED CONTROL IN THE ‘LEGO SAMPLE FACTORY’”. The primary goal is to replace the current paper-based and untraceable processes with a modern software application that enhances supply chain management through digital control, real-time monitoring, and optimized data flow.

Key Objectives:

  • Digital Transformation: Migrate from manual, paper-based processes to a fully digital system for information and material flow management.
  • Supply Chain Optimization: Implement data flow design modifications to reduce time costs, optimize material storage, and improve resource utilization.
  • Real-time Control & Monitoring: Enable real-time tracking of production processes, material movements, and order fulfillment.
  • Modular & Scalable Architecture: Design a microservice-based application using Java/Spring for the backend and React for the frontend to ensure flexibility and scalability.
  • Robust Authentication: Incorporate API Key, JWT, and OAuth 2.0 for secure access control.
  • Comprehensive Documentation: Provide a clear and accurate specification for development and future maintenance.

2. Core Business Domain: LEGO Sample Factory Logistics

The LEGO Sample Factory simulates a manufacturing supply chain process where LEGO blocks are used to produce seven variants of drills (A-G). The system involves various workstations, orders, and material flows.

2.1. Key Entities & Their Roles:

  • Customer: Initiates the supply chain by placing a Customer Order for drill variants.
  • Plant Warehouse:
    • Receives and fulfills Customer Orders from its stock.
    • Places Warehouse Orders to the Modules Supermarket if stock is low for small lot sizes.
    • Places Production Orders directly to Production Planning if stock is low for large lot sizes.
  • Modules Supermarket:
    • Receives and fulfills Warehouse Orders from the Plant Warehouse.
    • Manages manufactured and assembled modules.
    • Places Production Orders to Production Planning if it doesn’t have enough modules to fulfill a Warehouse Order.
    • Forwards completed modules to the Final Assembly workstation.
  • Production Planning:
    • Receives Warehouse Orders or Production Orders.
    • Uses SimAL.Scheduler (external system) to plan production, scheduling start and finish times for module manufacturing and assembly.
    • Creates Production Control Orders and Assembly Control Orders based on the schedule.
  • Production Control:
    • Controls the manufacturing of modules.
    • Receives Production Control Orders from Production Planning.
    • Creates Production Part Supply Orders for Parts Supply Warehouse.
    • Creates Injection Mold OrderPart Pre-Production Order, and Part Finishing Order for the respective manufacturing workstations.
  • Manufacturing Workstations:
    • Injection Molding: Produces parts without raw material.
    • Parts Pre-Production: Produces pre-produced modules from parts (requires supply from Parts Supply Warehouse).
    • Part Finishing: Finishes pre-produced modules (requires supply from Parts Supply Warehouse).
    • Receive specific Production Orders from Production Control.
    • Update Production Planning with actual start/finish times.
  • Assembly Control:
    • Controls the assembly of modules.
    • Receives Assembly Control Orders from Production Planning.
    • Creates Assembly Supply Orders for Parts Supply Warehouse.
    • Creates Motor Assembly OrderGear Assembly Order, and Final Assembly Order for the respective assembly workstations.
  • Parts Supply Warehouse:
    • Supplies parts for manufacturing (Pre-Production, Finishing) and assembly (Motor, Gear, Final Assembly).
    • Receives Production Part Supply Orders from Production Control and Assembly Supply Orders from Assembly Control.
  • Assembly Workstations:
    • Motor Assembly: Assembles parts into motor modules.
    • Gear Assembly: Assembles parts into gear modules.
    • Final Assembly: Assembles all modules into the final drill product.
    • Receive specific Assembly Orders from Assembly Control.
    • Update Assembly Control with actual start/finish times.
  • Users: Human operators interacting with the system, categorized by their workstation roles (e.g., Administrator, Plant Warehouse User, Production Planning User, etc.).

2.2. Order Types & Data Flow:

  1. Customer Order: Placed by the Customer to the Plant Warehouse.
  2. Warehouse Order: Placed by the Plant Warehouse to the Modules Supermarket (for lot size below threshold).
  3. Production Order (Modules Supermarket): Placed by Modules Supermarket to Production Planning (for missing modules to fulfill Warehouse Order).
  4. Production Order (Plant Warehouse): Placed by Plant Warehouse to Production Planning (for lot size above threshold).
  5. Production Control Order: Placed by Production Planning to Production Control.
  6. Assembly Control Order: Placed by Production Planning to Assembly Control.
  7. Production Part Supply Order: Placed by Production Control to Parts Supply Warehouse.
  8. Injection Mold Order: Placed by Production Control to Injection Molding.
  9. Part Pre-Production Order: Placed by Production Control to Parts Pre-Production.
  10. Part Finishing Order: Placed by Production Control to Parts Finishing.
  11. Assembly Part Supply Order: Placed by Assembly Control to Parts Supply Warehouse.
  12. Motor Assembly Order: Placed by Assembly Control to Motor Assembly.
  13. Gear Assembly Order: Placed by Assembly Control to Gear Assembly.
  14. Final Assembly Order: Placed by Assembly Control to Final Assembly.

2.3. Key Business Rules/Scenarios:

  • Variant G Priority: Orders for ‘G-variants’ are high priority; any station receiving them must stop current processes and handle immediately. G-variants are built from raw materials, not preassembled stock.
  • Lot Sizes: Except for G-variant (lot size 1), all orders have a lot size of 3.
  • SimAL.Scheduler Integration: Critical for production planning and scheduling, communicating via JSON for order submission (POST) and status retrieval (GET).
  • Stock Management: Real-time update of stock levels at Plant Warehouse, Modules Supermarket, and Parts Supply Warehouse based on fulfillment and production.
  • Time Tracking: Start and finish times for production and assembly are estimated by Production Planning and updated with actual times by workstations.

System Architecture & Components

The application will follow a microservice architecture, comprising:

  • Backend: Java with Spring Boot (Spring Web, Spring Data JPA, Spring Security).
  • Database: PostgreSQL (recommended for persistence, H2 for local development).
  • Frontend: ReactJS application.
  • External Integration: SimAL.Scheduler (via REST API, as described in thesis).

Development Environment: Visual Studio Code.

4. Backend Specification (Java/Spring Boot)

The backend will expose RESTful APIs for the frontend and integrate with SimAL.Scheduler.

4.1. Core Entities (Java Classes for Data Model)

These classes will represent the core business objects and map to database tables using Spring Data JPA.

  • User
    • id (Long)
    • username (String)
    • passwordHash (String)
    • role (Enum: ADMINPLANT_WAREHOUSEMODULES_SUPERMARKET, etc.)
    • workstation (String/Enum, linked to Workstation)
    • isEnabled (Boolean)
  • Workstation
    • id (Long)
    • name (String: “Plant Warehouse”, “Modules Supermarket”, etc.)
    • type (Enum: SUPPLYPRODUCTIONASSEMBLYCONTROL)
    • description (String)
  • ProductVariant (e.g., Drill A, Drill B)
    • id (Long)
    • name (String: “Variant A”, “Variant G”)
    • voltagePower (String)
    • gear (String)
    • colour (String)
    • isPriority (Boolean, e.g., for G-variant)
  • Part (Raw materials for modules)
    • id (Long)
    • name (String)
    • description (String)
  • Module (Components manufactured/assembled from parts)
    • id (Long)
    • name (String)
    • description (String)
    • requiredParts (Map<Part, Integer>) // Or a separate ModulePart entity
  • StockRecord
    • id (Long)
    • itemType (Enum: PRODUCT_VARIANTPARTMODULE)
    • itemId (Long, foreign key to ProductVariant, Part, or Module)
    • workstation (ManyToOne, linked to Workstation)
    • quantity (Integer)
    • lastUpdated (LocalDateTime)
  • Order (Abstract base class or interface)
    • id (Long)
    • orderNumber (String)
    • orderDate (LocalDateTime)
    • status (Enum: PENDINGPLANNEDIN_PROGRESSFULFILLEDCANCELED)
    • sourceWorkstation (ManyToOne, linked to Workstation)
    • targetWorkstation (ManyToOne, linked to Workstation)
    • items (List)
  • OrderItem
    • id (Long)
    • order (ManyToOne, linked to Order)
    • itemType (Enum: PRODUCT_VARIANTPARTMODULE)
    • itemId (Long, foreign key to ProductVariant, Part, or Module)
    • quantity (Integer)
    • variant (String, e.g., “A”, “B”) – as per SimAL format
  • CustomerOrder (Extends Order)
    • customerName (String)
    • deliveryAddress (String)
  • WarehouseOrder (Extends Order)
    • thresholdLotSize (Integer)
  • ProductionOrder (Extends Order)
    • estimatedStartTime (LocalDateTime)
    • estimatedFinishTime (LocalDateTime)
    • actualStartTime (LocalDateTime)
    • actualFinishTime (LocalDateTime)
    • simALOrderId (String, for tracking with SimAL.Scheduler)
  • SupplyOrder (Extends Order)
    • supplyType (Enum: PRODUCTION_PARTASSEMBLY_PART)

4.2. Repository Layer (Spring Data JPA)

Interfaces extending JpaRepository for basic CRUD operations on all entities.

  • UserRepository
  • WorkstationRepository
  • ProductVariantRepository
  • PartRepository
  • ModuleRepository
  • StockRecordRepository
  • OrderRepository (and specific repositories for CustomerOrderProductionOrder, etc.)
  • OrderItemRepository

4.3. Service Layer (Spring @Service Classes)

These classes encapsulate the business logic and orchestrate data access.

  • UserService
    • createUser(User user)
    • updateUser(User user)
    • deleteUser(Long userId)
    • getUserByUsername(String username)
    • assignWorkstation(Long userId, Long workstationId)
  • WorkstationService
    • getAllWorkstations()
    • getWorkstationById(Long id)
  • ProductCatalogService
    • getAllProductVariants()
    • getProductVariantById(Long id)
  • StockService
    • getStockForWorkstation(Long workstationId)
    • updateStock(Long stockRecordId, Integer quantityChange)
    • checkStockAvailability(Long workstationId, Long itemId, Integer quantity)
  • OrderService (General operations for all orders)
    • createOrder(Order order)
    • updateOrderStatus(Long orderId, OrderStatus newStatus)
    • getOrderById(Long orderId)
    • getOrdersByWorkstation(Long workstationId)
    • cancelOrder(Long orderId)
  • CustomerOrderService
    • placeCustomerOrder(CustomerOrder customerOrder)
    • fulfillCustomerOrder(Long customerOrderId) (checks stock, updates, generates Warehouse/Production Orders if needed)
  • WarehouseOrderService
    • createWarehouseOrder(WarehouseOrder order)
    • processWarehouseOrder(Long warehouseOrderId) (checks Modules Supermarket stock, generates Production Order if needed)
  • ProductionPlanningService
    • planProduction(ProductionOrder order) (communicates with SimAL.Scheduler)
    • updateProductionTimes(Long productionOrderId, LocalDateTime actualStart, LocalDateTime actualFinish)
    • getPlannedOrdersForWorkstation(Long workstationId)
  • ProductionControlService
    • createProductionSupplyOrders(Long productionControlOrderId)
    • createManufacturingOrders(Long productionControlOrderId)
    • updateManufacturingStatus(Long manufacturingOrderId, Status newStatus)
  • AssemblyControlService
    • createAssemblySupplyOrders(Long assemblyControlOrderId)
    • createAssemblyOrders(Long assemblyControlOrderId)
    • updateAssemblyStatus(Long assemblyOrderId, Status newStatus)
  • SimALSchedulerAdapter (Responsible for integration with SimAL.Scheduler)
    • sendWarehouseOrder(WarehouseOrder order) (POST, maps to SimAL JSON format)
    • getScheduledOrders(Long workstationId) (GET, parses SimAL JSON response)
    • updateTimeStatus(Long simALOrderId, LocalDateTime timestamp, Integer amount, Integer status) (POST, maps to SimAL JSON format)

4.4. REST API Endpoints (Spring @RestController Classes)

These controllers will expose the functionality of the service layer via HTTP endpoints.

  • AuthController (/api/auth)
    • POST /login: Authenticates user, returns JWT.
    • POST /register: Creates a new user (admin only).
  • UserController (/api/users)
    • GET /: Get all users (admin only)
    • GET /{id}: Get user by ID
    • PUT /{id}/workstation: Assign workstation to user (admin only)
  • WorkstationController (/api/workstations)
    • GET /: Get all workstations
  • ProductController (/api/products)
    • GET /variants: Get all product variants
  • StockController (/api/stock)
    • GET /workstation/{workstationId}: Get stock for a specific workstation
    • PUT /workstation/{workstationId}/update: Update stock quantity (authenticated users)
  • OrderController (/api/orders)
    • POST /customer: Place new customer order (Plant Warehouse role)
    • POST /warehouse: Create warehouse order (Plant Warehouse role)
    • POST /production: Create production order (Modules Supermarket role)
    • GET /mine: Get orders relevant to the authenticated user’s workstation
    • PUT /{orderId}/status: Update order status
    • PUT /{orderId}/times: Update actual start/finish times (manufacturing/assembly roles)
  • SimALIntegrationController (/api/simal)
    • POST /order: Send order to SimAL (internal, Production Planning role)
    • GET /schedule: Get schedule from SimAL (internal, Production Planning role)
    • POST /update-time: Update SimAL with actual times (internal, triggered by workstations)

4.5. Authentication and Authorization (Spring Security)

  • API Key:
    • Mechanism: A custom Spring Security filter that checks for a specific X-API-Key header.
    • Use Case: Ideal for system-to-system communication or for the SimAL.Scheduler integration if it were to authenticate with our system.
    • Implementation Note: Store API keys securely (hashed or encrypted) and associate them with specific services/users having limited permissions.
  • JWT (JSON Web Tokens):
    • Mechanism:
      1. User authenticates with username/password (/api/auth/login).
      2. Server generates a JWT containing user details (ID, roles, expiration) and signs it.
      3. JWT is returned to the frontend.
      4. Frontend includes JWT in the Authorization: Bearer <token> header for subsequent requests.
      5. Backend validates the JWT (signature, expiration, claims) using a Spring Security filter.
    • Use Case: Primary method for user authentication for the frontend application.
    • Implementation Note: Use jjwt library, ensure secure secret key, configure token expiration, and handle token refresh if needed.
  • OAuth 2.0:
    • Mechanism:
      1. Frontend redirects user to an external Identity Provider (IdP) login page (e.g., Google, Keycloak).
      2. User logs in at the IdP and grants permission to our application.
      3. IdP redirects user back to our application with an authorization code.
      4. Backend exchanges the authorization code for an access token (and potentially ID token/refresh token) with the IdP.
      5. Backend extracts user information from the tokens and creates a session or generates a local JWT for the user.
    • Use Case: Provides delegated authorization and allows users to log in using existing accounts (e.g., institutional logins). This can be an alternative or additional login method alongside username/password.
    • Implementation Note: Use Spring Security OAuth2 client. Configure client ID, client secret, authorization URLs, token URLs, and user info URLs for the chosen IdP. This requires more setup, potentially an external identity server like Keycloak or integration with Google/Azure AD.

5. Frontend Specification (React)

The React frontend will provide user interfaces for each workstation and user role.

5.1. Key Components/Pages:

  • Login Page:
    • Input fields for username and password.
    • Login button.
    • Option for OAuth login (e.g., “Login with Google” button).
    • Display error messages for failed login.
  • Dashboard/Workstation Selector:
    • After login, a page to select the specific workstation role to operate from.
    • Administrator will have an “Admin Panel” option.
  • Admin Panel:
    • User Management: Create, view, update, delete users; assign roles and workstations.
    • Order Overview: View all orders, their statuses, and detailed information.
    • System Configuration: Manage product variants, workstation details.
  • Plant Warehouse Interface:
    • View current stock records.
    • Receive customer orders (UI to input order details, select variants, quantities).
    • Initiate fulfillment (trigger fulfillCustomerOrder API).
    • View and manage generated Warehouse/Production Orders.
  • Modules Supermarket Interface:
    • View module stock.
    • Process incoming Warehouse Orders.
    • Initiate Production Orders for missing modules.
    • Forward completed modules to Final Assembly.
  • Production Planning Interface:
    • View incoming Warehouse/Production Orders.
    • Interface to interact with SimAL.SchedulerAdapter (e.g., “Plan Production” button).
    • Display scheduled production plans.
    • Monitor order progress.
  • Manufacturing/Assembly Workstation Interfaces (e.g., Injection Molding, Final Assembly):
    • View assigned orders and tasks.
    • Input actual start and finish times.
    • Update order status (e.g., “Complete Task”).
    • View relevant stock levels for their workstation.
  • Parts Supply Warehouse Interface:
    • View incoming Production Part Supply Orders and Assembly Part Supply Orders.
    • Mark parts as supplied.

5.2. Frontend Technologies:

  • React: For building the UI components.
  • React Router: For navigation between pages.
  • Axios/Fetch API: For making HTTP requests to the backend.
  • State Management: React Context API or Redux for managing global application state (e.g., authenticated user, current workstation).
  • UI Library (Optional): Material-UI, Ant Design, or Bootstrap for consistent styling and pre-built components.

Containerized microservices demo for a LEGO sample factory, with a React frontend, an API Gateway, and Spring Boot backend services orchestrated via Docker Compose.

Current Status

  • Configuration is driven by a root-level .env file consumed by Docker Compose.
  • A committed .env.example serves as the blueprint for local .env creation.
  • Backend services use H2 in-memory databases for local development.
  • API Gateway routes to internal services using Docker service names.
  • Nginx root proxy exposes the frontend on a single host port.
  • CORS is configured for common localhost dev URLs.
  • Actuator endpoints exposed: health, info, metrics.
  • JPA DDL is create-drop for clean local runs. Do not use in production.

Getting Started

  1. Prerequisites:
    – Windows with Docker Desktop running.
    – VS Code recommended.

  2. Create your local environment file from the blueprint:
    – Copy the example:

     “`

     Copy-Item .env.example .env

     “`

   – Open .env and set values. At minimum, set a secure SECURITY_JWT_SECRET (32+ chars).
– Keep .env private. It should be ignored by Git.

  1. Build and run:

   “`

   docker compose up –build

   “`

  1. Access the app:
    – Frontend via Nginx root proxy: http://localhost:80
    – API Gateway (direct dev port): http://localhost:8011
    – H2 console (per service, if enabled): http://localhost:/h2-console

  2. Tear down:

   “`bash

   docker compose down

   “`

Using .env.example as a Blueprint

  • .env.example is committed and pushed to the repo so collaborators can see required variables.
  • Duplicate it to .env and customize for local development:

  – Security:
– SECURITY_JWT_SECRET: long random string (32+ chars).
– SECURITY_JWT_EXPIRATION: default PT1H.

  – Networking:
– NGINX_ROOT_PROXY_EXTERNAL_PORT: default 80.
– DOCKER_NETWORK_NAME: default lego-network.

  – Frontend:
– VITE_API_GATEWAY_URL: default http://localhost:8011.
– FRONTEND_SERVE_PORT: default 5173.

  – Gateway CORS:
– API_GATEWAY_CORS_ALLOWED_ORIGINS: restrict as needed.

  – Microservice internal ports:
– API_GATEWAY_PORTUSER_SERVICE_PORTMASTERDATA_SERVICE_PORTINVENTORY_SERVICE_PORTORDER_PROCESSING_SERVICE_PORTSIMAL_INTEGRATION_SERVICE_PORT.

  – Databases (H2 in-memory):
– H2_DB_* JDBC URLs with DB_CLOSE_DELAY=-1.

  – Spring Boot common:
– SPRING_JPA_HIBERNATE_DDL_AUTO=create-drop (dev only).
– SPRING_JPA_SHOW_SQL=true.
– SPRING_H2_CONSOLE_ENABLED=true.
– SPRING_H2_CONSOLE_PATH=/h2-console.
– SPRING_JMX_ENABLED=false.

  – Logging:
– LOGGING_LEVEL_IO_LIFE=DEBUGLOG_LEVEL_ROOT=INFO.

  – Management:
– MANAGEMENT_ENDPOINTS_WEB_EXPOSURE_INCLUDE="health,info,metrics".

    – MANAGEMENT_ENDPOINT_HEALTH_SHOW_DETAILS=always.
– Internal service URLs for Gateway routing:

    – API_GATEWAY_*_SERVICE_URL using Docker service names and ports.
– Docker Compose defaults:

    – DOCKER_RESTART_POLICY=unless-stoppedDOCKER_MEMORY_LIMIT=512mDOCKER_CPU_LIMIT=1.0DOCKER_TAG=latest.

Development

  • Frontend dev server:

  npm run dev --prefix frontend

  Ensure VITE_API_GATEWAY_URL points to the gateway.

  • Logs:

  docker compose logs -f

MENU
PAGE TOP