latest changes
This commit is contained in:
+167
-38
@@ -665,45 +665,58 @@ def inventory_change(request, identifier):
|
||||
).select_related('product', 'location', 'category').first()
|
||||
if item is None:
|
||||
return error('inventory_item_not_found', 'Inventory item not found.', 404)
|
||||
remaining = data.get('remaining_amount', item.remaining_amount)
|
||||
if 'remaining_amount' in data and remaining is not None:
|
||||
try:
|
||||
remaining = _decimal(remaining, 'remaining_amount')
|
||||
except ValueError as exc:
|
||||
return _inventory_validation('remaining_amount', str(exc))
|
||||
if item.original_amount is None or item.remaining_amount is None:
|
||||
return _inventory_validation('remaining_amount', 'This item has no known package amount.')
|
||||
if remaining > item.original_amount:
|
||||
return _inventory_validation('remaining_amount', 'Amount exceeds the package capacity.')
|
||||
if remaining != remaining.quantize(Decimal('.001')):
|
||||
return _inventory_validation('remaining_amount', 'Use at most three decimal places.')
|
||||
if remaining > item.remaining_amount:
|
||||
return _inventory_validation('remaining_amount', 'Increasing remaining stock is not supported.')
|
||||
if remaining < item.remaining_amount:
|
||||
conflicting = set(data) & {'product_id', 'quantity', 'original_amount', 'unit'}
|
||||
if conflicting:
|
||||
return _inventory_validation(sorted(conflicting)[0],
|
||||
'Change package identity or size separately from consumption.')
|
||||
if data.get('opened') is False and remaining > 0:
|
||||
return _inventory_validation('opened', 'A partly used package must be opened.')
|
||||
from .services.inventory_consumption import StockError, consume
|
||||
try:
|
||||
consume(request.api_user, item.product, item.remaining_amount - remaining,
|
||||
item.inventory_unit, package_id=item.api_id, source='mcp',
|
||||
description=str(data.get('notes') or '')[:255])
|
||||
except StockError as exc:
|
||||
return _inventory_validation('remaining_amount', str(exc))
|
||||
item.refresh_from_db()
|
||||
data = {key: value for key, value in data.items() if key != 'remaining_amount'}
|
||||
elif 'remaining_amount' in data:
|
||||
return _inventory_validation('remaining_amount', 'Use a number between zero and the package capacity.')
|
||||
item, failure = _save_inventory(request, data, item)
|
||||
return failure or JsonResponse(_inventory_data(item))
|
||||
return _apply_inventory_update(request, item, data)
|
||||
except (ValueError, ValidationError) as exc:
|
||||
if isinstance(exc, ValidationError) and hasattr(exc, 'message_dict'):
|
||||
field, messages = next(iter(exc.message_dict.items()))
|
||||
return _inventory_validation(field, '; '.join(messages))
|
||||
return _inventory_validation('inventory', '; '.join(exc.messages) if isinstance(exc, ValidationError) else str(exc))
|
||||
return _inventory_exception(exc)
|
||||
|
||||
|
||||
def _apply_inventory_update(request, item, data):
|
||||
"""Shared single-item rules for PATCH and batch updates; caller owns the transaction."""
|
||||
data = dict(data)
|
||||
try:
|
||||
remaining = data.get('remaining_amount', item.remaining_amount)
|
||||
if 'remaining_amount' in data and remaining is not None:
|
||||
try:
|
||||
remaining = _decimal(remaining, 'remaining_amount')
|
||||
except ValueError as exc:
|
||||
return _inventory_validation('remaining_amount', str(exc))
|
||||
if item.original_amount is None or item.remaining_amount is None:
|
||||
return _inventory_validation('remaining_amount', 'This item has no known package amount.')
|
||||
if remaining > item.original_amount:
|
||||
return _inventory_validation('remaining_amount', 'Amount exceeds the package capacity.')
|
||||
if remaining != remaining.quantize(Decimal('.001')):
|
||||
return _inventory_validation('remaining_amount', 'Use at most three decimal places.')
|
||||
if remaining > item.remaining_amount:
|
||||
return _inventory_validation('remaining_amount', 'Increasing remaining stock is not supported.')
|
||||
if remaining < item.remaining_amount:
|
||||
conflicting = set(data) & {'product_id', 'quantity', 'original_amount', 'unit'}
|
||||
if conflicting:
|
||||
return _inventory_validation(sorted(conflicting)[0],
|
||||
'Change package identity or size separately from consumption.')
|
||||
if data.get('opened') is False and remaining > 0:
|
||||
return _inventory_validation('opened', 'A partly used package must be opened.')
|
||||
from .services.inventory_consumption import StockError, consume
|
||||
try:
|
||||
consume(request.api_user, item.product, item.remaining_amount - remaining,
|
||||
item.inventory_unit, package_id=item.api_id, source='mcp',
|
||||
description=str(data.get('notes') or '')[:255])
|
||||
except StockError as exc:
|
||||
return _inventory_validation('remaining_amount', str(exc))
|
||||
item.refresh_from_db()
|
||||
data = {key: value for key, value in data.items() if key != 'remaining_amount'}
|
||||
elif 'remaining_amount' in data:
|
||||
return _inventory_validation('remaining_amount', 'Use a number between zero and the package capacity.')
|
||||
item, failure = _save_inventory(request, data, item)
|
||||
return failure or JsonResponse(_inventory_data(item))
|
||||
except (ValueError, ValidationError) as exc:
|
||||
return _inventory_exception(exc)
|
||||
|
||||
|
||||
def _inventory_exception(exc):
|
||||
if isinstance(exc, ValidationError) and hasattr(exc, 'message_dict'):
|
||||
field, messages = next(iter(exc.message_dict.items()))
|
||||
return _inventory_validation(field, '; '.join(messages))
|
||||
return _inventory_validation('inventory', '; '.join(exc.messages) if isinstance(exc, ValidationError) else str(exc))
|
||||
|
||||
|
||||
def _inventory_validation(field, reason):
|
||||
@@ -711,6 +724,122 @@ def _inventory_validation(field, reason):
|
||||
{'field': field, 'reason': reason})
|
||||
|
||||
|
||||
def _inventory_batch_input(request, data, *, deleting=False):
|
||||
rows = data.get('item_ids' if deleting else 'items')
|
||||
if not isinstance(rows, list) or not 1 <= len(rows) <= 20:
|
||||
raise ValueError('Provide between 1 and 20 inventory items.')
|
||||
if set(data) - ({'item_ids', 'dry_run', 'atomic', 'confirm'} if deleting else {'items', 'dry_run', 'atomic'}):
|
||||
raise ValueError('Unknown bulk inventory fields.')
|
||||
if any(type(data.get(key, default)) is not bool for key, default in (('dry_run', False), ('atomic', False))):
|
||||
raise ValueError('dry_run and atomic must be booleans.')
|
||||
if deleting and type(data.get('confirm', False)) is not bool:
|
||||
raise ValueError('confirm must be a boolean.')
|
||||
parsed = []
|
||||
for raw in rows:
|
||||
if deleting:
|
||||
identifier = raw
|
||||
changes = None
|
||||
expected = None
|
||||
else:
|
||||
if not isinstance(raw, dict) or set(raw) - {'item_id', 'changes', 'expected_updated_at'}:
|
||||
raise ValueError('Each update needs item_id and changes.')
|
||||
identifier = raw.get('item_id')
|
||||
changes = raw.get('changes')
|
||||
expected = raw.get('expected_updated_at')
|
||||
if not isinstance(changes, dict) or not changes or set(changes) - {
|
||||
'product_id', 'quantity', 'location', 'category', 'notes', 'opened', 'remaining_amount', 'best_before'}:
|
||||
raise ValueError('Each update needs supported, nonempty changes.')
|
||||
if expected is not None and not isinstance(expected, str):
|
||||
raise ValueError('expected_updated_at must be a timestamp.')
|
||||
parsed.append((_uuid(identifier), changes, expected))
|
||||
if len({identifier for identifier, _, _ in parsed}) != len(parsed):
|
||||
raise ValueError('Duplicate inventory item IDs are not allowed.')
|
||||
return parsed
|
||||
|
||||
|
||||
def _inventory_batch(request, parsed, *, deleting, dry_run, atomic):
|
||||
results = []
|
||||
with transaction.atomic():
|
||||
type(request.api_user).objects.select_for_update().get(pk=request.api_user.pk)
|
||||
for identifier, changes, expected in parsed:
|
||||
with transaction.atomic():
|
||||
item = KitchenInventoryItem.objects.select_for_update().filter(
|
||||
user=request.api_user, api_id=identifier, archived_at__isnull=True,
|
||||
).select_related('product', 'location', 'category').first()
|
||||
if item is None:
|
||||
result = {'item_id': str(identifier), 'status': 'failed', 'error': {
|
||||
'code': 'inventory_item_not_found', 'message': 'Inventory item not found or unavailable.'}}
|
||||
results.append(result)
|
||||
continue
|
||||
before = _inventory_data(item)
|
||||
if expected is not None and expected != item.updated_at.isoformat():
|
||||
results.append({'item_id': str(identifier), 'status': 'failed', 'before': before,
|
||||
'error': {'code': 'inventory_conflict', 'message': 'Item changed since it was read.'}})
|
||||
continue
|
||||
if deleting:
|
||||
item.archived_at = timezone.now()
|
||||
item.save(update_fields=('archived_at', 'updated_at'))
|
||||
after = _inventory_data(item)
|
||||
failed = False
|
||||
else:
|
||||
response = _apply_inventory_update(request, item, changes)
|
||||
failed = response.status_code >= 400
|
||||
if failed:
|
||||
result = {'item_id': str(identifier), 'status': 'failed', 'before': before,
|
||||
'error': json.loads(response.content)['error']}
|
||||
transaction.set_rollback(True)
|
||||
results.append(result)
|
||||
continue
|
||||
after = json.loads(response.content)
|
||||
meaningful = {key: value for key, value in after.items() if key != 'updated_at'} != {
|
||||
key: value for key, value in before.items() if key != 'updated_at'}
|
||||
results.append({'item_id': str(identifier), 'status': 'validated' if dry_run and meaningful else
|
||||
'changed' if meaningful else 'unchanged', 'before': before, 'after': after})
|
||||
if dry_run or not meaningful:
|
||||
transaction.set_rollback(True)
|
||||
failed_count = sum(row['status'] == 'failed' for row in results)
|
||||
if atomic and failed_count and not dry_run:
|
||||
for row in results:
|
||||
if row['status'] == 'changed':
|
||||
row['status'] = 'rolled_back'
|
||||
transaction.set_rollback(True)
|
||||
if dry_run:
|
||||
transaction.set_rollback(True)
|
||||
counts = {status: sum(row['status'] == status for row in results) for status in
|
||||
('validated', 'changed', 'unchanged', 'failed', 'rolled_back')}
|
||||
return JsonResponse({'dry_run': dry_run, 'atomic': atomic, 'items': results, 'counts': counts,
|
||||
'status': 'preview' if dry_run else 'rolled_back' if atomic and failed_count else
|
||||
'partial_success' if failed_count else 'success'})
|
||||
|
||||
|
||||
@api_view('inventory:write', ('POST',))
|
||||
def inventory_bulk_update(request):
|
||||
if len(request.body) > 65536:
|
||||
return error('batch_too_large', 'Batch payload exceeds 64 KB.', 413)
|
||||
data = _json(request)
|
||||
parsed = _inventory_batch_input(request, data)
|
||||
dry_run = data.get('dry_run', True)
|
||||
if not dry_run and not request.headers.get('Idempotency-Key'):
|
||||
return error('idempotency_key_required', 'Provide an Idempotency-Key.', 400)
|
||||
action = lambda: _inventory_batch(request, parsed, deleting=False, dry_run=dry_run, atomic=data.get('atomic', False))
|
||||
return action() if dry_run else _idempotent(request, data, action)
|
||||
|
||||
|
||||
@api_view('inventory:write', ('POST',))
|
||||
def inventory_bulk_delete(request):
|
||||
if len(request.body) > 65536:
|
||||
return error('batch_too_large', 'Batch payload exceeds 64 KB.', 413)
|
||||
data = _json(request)
|
||||
parsed = _inventory_batch_input(request, data, deleting=True)
|
||||
dry_run = data.get('dry_run', True)
|
||||
if not dry_run and not data.get('confirm', False):
|
||||
return error('confirmation_required', 'Preview the items and explicitly confirm deletion.', 400)
|
||||
if not dry_run and not request.headers.get('Idempotency-Key'):
|
||||
return error('idempotency_key_required', 'Provide an Idempotency-Key.', 400)
|
||||
action = lambda: _inventory_batch(request, parsed, deleting=True, dry_run=dry_run, atomic=data.get('atomic', False))
|
||||
return action() if dry_run else _idempotent(request, data, action)
|
||||
|
||||
|
||||
@api_view('food:write', ('POST',))
|
||||
def attachment_create(request, identifier):
|
||||
entry = FoodLogEntry.objects.filter(user=request.api_user, api_id=identifier).first()
|
||||
|
||||
Reference in New Issue
Block a user