feat(inventory): add support for selling in negative stock

Implement functionality to allow sales even when stock is insufficient, tracking pending quantities and resolving them when new stock arrives via incoming documents. This includes new fields in Sale model (is_pending_cost, pending_quantity), updates to batch manager for negative write-offs, and signal handlers for automatic processing.

- Add is_pending_cost and pending_quantity fields to Sale model
- Modify write_off_by_fifo to support allow_negative flag and return pending quantity
- Update incoming document service to allocate pending sales to new batches
- Enhance sale processor and signals to handle pending sales
- Remove outdated tests.py file
- Add migration for new Sale fields
This commit is contained in:
2026-01-04 12:27:10 +03:00
parent 123f330a26
commit a03f3df086
7 changed files with 223 additions and 570 deletions

View File

@@ -70,11 +70,10 @@ class StockBatchManager:
return batch
@staticmethod
def write_off_by_fifo(product, warehouse, quantity_to_write_off, exclude_order=None, exclude_transformation=None):
def write_off_by_fifo(product, warehouse, quantity_to_write_off, exclude_order=None, exclude_transformation=None, allow_negative=False):
"""
Списать товар по FIFO (старые партии первыми).
ВАЖНО: Учитывает зарезервированное количество товара.
Возвращает список (batch, written_off_quantity) кортежей.
Args:
product: объект Product
@@ -86,12 +85,16 @@ class StockBatchManager:
exclude_transformation: (опционально) объект Transformation - исключить резервы этой трансформации из расчёта.
Используется при переводе трансформации в 'completed', когда резервы
трансформации ещё не переведены в 'converted_to_transformation'.
allow_negative: (опционально) bool - разрешить продажи "в минус".
Если True и товара не хватает, возвращает pending_quantity вместо исключения.
Returns:
list: [(batch, qty_written), ...] - какие партии и сколько списано
tuple: (allocations, pending_quantity)
- allocations: [(batch, qty_written), ...] - какие партии и сколько списано
- pending_quantity: Decimal - сколько не удалось списать (для продаж "в минус")
Raises:
ValueError: если недостаточно свободного товара на складе
ValueError: если недостаточно свободного товара на складе и allow_negative=False
"""
from inventory.models import Reservation
@@ -191,16 +194,21 @@ class StockBatchManager:
batch.save(update_fields=['is_active'])
if remaining > 0:
raise ValueError(
f"Недостаточно СВОБОДНОГО товара на складе. "
f"Требуется {quantity_to_write_off}, доступно {quantity_to_write_off - remaining}. "
f"(Общий резерв: {total_reserved})"
)
if allow_negative:
# Возвращаем сколько не удалось списать (для продаж "в минус")
StockBatchManager.refresh_stock_cache(product, warehouse)
return (allocations, remaining)
else:
raise ValueError(
f"Недостаточно СВОБОДНОГО товара на складе. "
f"Требуется {quantity_to_write_off}, доступно {quantity_to_write_off - remaining}. "
f"(Общий резерв: {total_reserved})"
)
# Обновляем кеш остатков
StockBatchManager.refresh_stock_cache(product, warehouse)
return allocations
return (allocations, Decimal('0'))
@staticmethod
def transfer_batch(batch, to_warehouse, quantity):