Skip to content

VentaService now correctly deducts inventory stock upon sale completion #57

@Richard117297

Description

@Richard117297

🎯 Objective
This implementation fixes the critical bug where VentaService failed to deduct product stock from inventory when a sale was finalized. This commit ensures inventory integrity by coupling the stock update and the sale creation in a single transaction.

✅ Summary of Changes
To resolve this issue, the following logic was implemented in VentaService:

Transactional Integrity (@transactional):

The finalizeSale(SaleDto saleDto) method has been marked as @transactional.

This guarantees that both the SaleRepository.save(sale) operation and the multiple ProductRepository.updateStock(...) calls are treated as a single, atomic unit. If the stock update fails for any reason (e.g., optimistic lock, constraint violation), the entire sale creation is rolled back.

Stock Pre-Validation:

Implemented a robust pre-validation check before initiating the transaction.

The service now iterates through all items in the SaleDto and verifies that the requested_quantity is less than or equal to the available_stock for each product.

Exception Handling & Rollback:

If the pre-validation fails for any product, the service immediately throws a NotEnoughStockException (or a similar 400 Bad Request error).

This prevents the system from attempting to save a sale that would violate database constraints and provides clear feedback to the UI (e.g., "Error: Insufficient stock for product [Product Name]").

🧪 QA & Verification
The fix has been verified against the acceptance criteria defined in the issue:

Test 1: (Success Scenario)

Given: Product A has 100 units in stock.

When: A new sale is finalized for 5 units of Product A.

Then: The Sale is successfully saved, and the Product A stock in the database is correctly updated to 95.

Test 2: (Failure/Rollback Scenario)

Given: Product B has 5 units in stock.

When: An attempt is made to finalize a sale for 10 units of Product B.

Then: The service throws a NotEnoughStockException, the transaction is rolled back, the Sale is not saved, and the Product B stock correctly remains at 5.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requesthigh-priorityMust be addressed urgently or blocks critical functionality

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions