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

@@ -104,33 +104,38 @@ class SaleProcessor:
document_number=document_number,
processed=True, # Сразу отмечаем как обработанную
sales_unit=sales_unit,
unit_name_snapshot=unit_name_snapshot
unit_name_snapshot=unit_name_snapshot,
is_pending_cost=False,
pending_quantity=Decimal('0')
)
try:
# Списываем товар по FIFO в БАЗОВЫХ единицах
# exclude_order позволяет не считать резервы этого заказа как занятые
# (резервы переводятся в converted_to_sale ПОСЛЕ создания Sale)
allocations = StockBatchManager.write_off_by_fifo(
product, warehouse, quantity_base, exclude_order=order
# Списываем товар по FIFO в БАЗОВЫХ единицах
# exclude_order позволяет не считать резервы этого заказа как занятые
# (резервы переводятся в converted_to_sale ПОСЛЕ создания Sale)
# allow_negative=True разрешает продажи "в минус"
allocations, pending = StockBatchManager.write_off_by_fifo(
product, warehouse, quantity_base, exclude_order=order, allow_negative=True
)
# Фиксируем распределение для аудита
for batch, qty_allocated in allocations:
SaleBatchAllocation.objects.create(
sale=sale,
batch=batch,
quantity=qty_allocated,
cost_price=batch.cost_price
)
# Фиксируем распределение для аудита
for batch, qty_allocated in allocations:
SaleBatchAllocation.objects.create(
sale=sale,
batch=batch,
quantity=qty_allocated,
cost_price=batch.cost_price
)
# Если есть pending - это продажа "в минус"
if pending > 0:
sale.is_pending_cost = True
sale.pending_quantity = pending
sale.save(update_fields=['is_pending_cost', 'pending_quantity'])
# processed уже установлен в True при создании Sale
return sale
# Обновляем Stock (теперь учитывает pending_sales)
StockBatchManager.refresh_stock_cache(product, warehouse)
except ValueError as e:
# Если ошибка при списании - удаляем Sale и пробрасываем исключение
sale.delete()
raise
return sale
@staticmethod
def get_sale_cost_analysis(sale):