Inventory & Supplier Orders Management System
Keeping stock valuation correct (CUMP) under concurrent orders.
Problem
Inventory valuation using the weighted-average cost (CUMP) must stay correct as supplier orders and stock movements change the quantities and costs of products.
Constraints
- Every movement changes the product's average cost, so the calculation has to be consistent.
- A partially applied order would corrupt stock figures, so writes must be atomic.
- The API contract should not leak the persistence model.
Architecture
A layered Spring Boot service: REST controllers → service layer (@Transactional) → Spring Data JPA repositories → MySQL, with Liquibase managing the schema.
Decision
Centralise valuation in the service layer and run each order as a single transaction, recomputing CUMP from the recorded stock movements.
The average cost is derived from the ordered sequence of movements, so it belongs with the business rules, not the controller or the database. A transaction boundary guarantees the order and its valuation change together or not at all.
Alternatives & trade-offs
Compute the average in the database with a trigger or view.
Fewer round-trips, but hides business logic in the schema, is harder to test in isolation, and is less portable across databases.
Compute valuation on read (materialised on demand).
Keeps writes simple, but repeats expensive work on every read and gives up a single source of truth.
Quality attributes
- Error handling
- Invalid input is rejected by Bean Validation before the service runs; failures inside the transaction roll back the whole unit of work.
- Testing
- The valuation logic lives in plain service code, so it can be exercised with unit tests without a running database.
- Maintainability
- DTOs and MapStruct keep the REST contract decoupled from entities, so the schema can change without breaking the API.
- Schema
- Liquibase changelogs make schema changes reviewable and repeatable across environments.
Future improvements
- Add optimistic locking or a version column to protect against concurrent valuation updates.
- Expose the valuation as an explicit domain operation with clear invariants and unit tests.
- Document the REST contract with example payloads directly from the OpenAPI spec.