curiousbud / curiousbud/Pharmore
Inventory Stock Not Updated After Checkout (Django Backend)
- Dominant language
- Python
- Stars
- 2
- Forks
- 0
- PR merge metrics
- No merged PRs in 30d
Description
**_Note: The solutions provided are AI generated and must be used for reference only._**
---
**Description:**
After a user completes the checkout process, the `Product.quantity` field does **not** update to reflect the sold units. This breaks inventory management and introduces a risk of overselling.
---
**Steps to Reproduce:**
1. Add multiple products to the cart (e.g., 2 units of *Product A* and 3 units of *Product B*).
2. Proceed through the checkout process and place the order.
3. Inspect the `quantity` field for each purchased product in the Django Admin or directly via the database.
---
**Expected Behavior:**
Each product’s `quantity` should **decrease** by the amount purchased.
*Example: If Product A had 10 units, and 2 are sold, it should show 8 after checkout.*
---
**Actual Behavior:**
Product quantities remain unchanged, even after a successful checkout.
---
**Root Cause (Suspected):**
- Checkout logic is missing inventory update.
- Signals (if used) are not handling stock adjustments.
- Potential absence of validation to prevent overselling.
---
**Implementation Requirements (Django):**
✅ **Update Stock Logic:**
After saving the order (likely in `CheckoutView`), iterate through `cart.items` and update each product using `F()` expressions for atomicity:
```python
from django.db.models import F
for item in cart.items.all():
Product.objects.filter(id=item.product.id).update(
quantity=F('quantity') - item.quantity
)
```
✅ **Ensure Atomic Transactions:**
Wrap stock update and order creation logic in `transaction.atomic()`:
```python
from django.db import transaction
with transaction.atomic():
order = Order.objects.create(...)
# perform stock update here
```
✅ **Prevent Negative Stock:**
Add pre-checkout validation to ensure sufficient stock:
```python
from django.core.exceptions import ValidationError
for item in cart.items.all():
if item.product.quantity < item.quantity:
raise ValidationError(f"Insufficient stock for {item.product.name}")
```
✅ **Optional: Use Django Signals**
If using signals, ensure post-checkout (e.g., `post_save`) hooks correctly adjust stock.
---
**Testing Requirements:**
Add unit tests to ensure stock updates correctly:
```python
from django.test import TestCase
from .models import Product, Order
class CheckoutTest(TestCase):
def test_stock_updates_after_checkout(self):
product = Product.objects.create(name="Test Product", quantity=10)
self.client.post('/add-to-cart/', {'product_id': product.id, 'quantity': 3})
self.client.post('/checkout/')
product.refresh_from_db()
self.assertEqual(product.quantity, 7)
```
---
**Acceptance Criteria:**
- [ ] Product quantity decrements correctly for all cart items post-checkout.
- [ ] Negative stock is prevented with pre-checkout checks.
- [ ] Order creation and stock updates are wrapped in atomic transactions.
- [ ] Unit tests cover single and multiple product scenarios, including edge cases.
---
**Relevant Files:**
- `orders/views.py` – Checkout logic
- `products/models.py` – Product model
- `cart/models.py` – Cart and CartItem logic
- `orders/tests.py` – Unit tests
---
**Labels:**
`bug` `inventory` `high priority`
**Priority:**
🚨 Critical
---
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.