Add inventory adjustment service
Problem Context
Inventory needs manual adjustments sometimes. Each adjustment must be logged for auditing purposes.
Advanced
200 points
File Changes (1)
src/main/java/com/example/service/InventoryAdjustmentService.java
ADDED
@@ -0 +1 @@
| 1 | +package com.example.service; |
|
| 2 | + |
|
| 3 | +import org.springframework.stereotype.Service; |
|
| 4 | +import org.springframework.transaction.annotation.Transactional; |
|
| 5 | +import lombok.RequiredArgsConstructor; |
|
| 6 | + |
|
| 7 | +@Service |
|
| 8 | +@RequiredArgsConstructor |
|
| 9 | +public class InventoryAdjustmentService { |
|
| 10 | + |
|
| 11 | + private final InventoryRepository inventoryRepository; |
|
| 12 | + private final AuditLogRepository auditLogRepository; |
|
| 13 | + |
|
| 14 | + public void adjustInventory(Long productId, int adjustment, String reason) { |
|
| 15 | + // Log the adjustment first |
|
| 16 | + AuditLog log = new AuditLog(); |
|
| 17 | + log.setAction("INVENTORY_ADJUSTMENT"); |
|
| 18 | + log.setProductId(productId); |
|
| 19 | + log.setAdjustment(adjustment); |
|
| 20 | + log.setReason(reason); |
|
| 21 | + auditLogRepository.save(log); |
|
| 22 | + |
|
| 23 | + // Perform the actual adjustment |
|
| 24 | + performAdjustment(productId, adjustment); |
|
| 25 | + } |
|
| 26 | + |
|
| 27 | + @Transactional |
|
| 28 | + private void performAdjustment(Long productId, int adjustment) { |
|
| 29 | + Inventory inventory = inventoryRepository.findByProductId(productId) |
|
| 30 | + .orElseThrow(() -> new ProductNotFoundException(productId)); |
|
| 31 | + |
|
| 32 | + int newQuantity = inventory.getQuantity() + adjustment; |
|
| 33 | + if (newQuantity < 0) { |
|
| 34 | + throw new InvalidAdjustmentException("Cannot reduce below zero"); |
|
| 35 | + } |
|
| 36 | + |
|
| 37 | + inventory.setQuantity(newQuantity); |
|
| 38 | + inventoryRepository.save(inventory); |
|
| 39 | + } |
|
| 40 | +} |
Login Required: You must be registered to submit reviews and receive AI feedback.
Register or
login to start reviewing!
Your Review
Review Tips
- Look for security vulnerabilities (SQL injection, XSS, etc.)
- Check for null pointer exceptions and error handling
- Consider performance implications
- Evaluate code maintainability and readability
- Check for proper resource management
- Look for logic errors or edge cases