HyperFlow / backend /flagship /commerce.py
Gaurav711's picture
Deploy 891f179
2b86c60 verified
Raw History Blame Contribute Delete
29.1 kB
"""Versioned proposals, approval enforcement, and conservative uncertain-response recovery."""
from copy import deepcopy
import time
from datetime import datetime
from .store import digest, Conflict
from .provider import MUTATIONS, ORDERS, CART_TOOL, cart_snapshot, minor, ProviderRejected, item_quantities, coordinates
from .basket import catalog_variants, optimize
from .parsing import extract_intent
class Commerce:
def __init__(self, store, provider):
self.store, self.provider = store, provider
def plan(self, account, request):
use_llm = request.get('use_llm', False)
if type(use_llm) is not bool:
raise ValueError('use_llm must be a boolean')
intent = request.get('intent')
if not intent:
if use_llm:
from .agent import reserve_paid_request
reserve_paid_request(self.store, account)
intent = extract_intent(request.get('text', ''), use_llm=use_llm)
if not isinstance(intent, dict):
raise ValueError('Intent must be an object')
if intent.get('clarifications'):
return {'intent': intent, 'result': {'status': 'needs_clarification'}, 'source': intent.get('source', 'user_input')}
if not isinstance(intent.get('items'), list) or not 1 <= len(intent['items']) <= 30:
raise ValueError('Provide 1 to 30 explicit item requirements')
mode = request.get('mode', 'live')
address = request.get('address_id')
if not address:
raise ValueError('Select a returned delivery address before planning')
requirements, catalog = [], []
for item in intent['items']:
if not isinstance(item, dict) or not isinstance(item.get('name'), str) or not item['name'].strip():
raise ValueError('Every requirement needs a product name')
read = self.provider.call(account, 'im', 'search_products', {'query': item['name'], 'addressId': address}, mode)
variants = catalog_variants(read['data'])
catalog.extend(variants)
requirements.append({**item, 'category': item.get('category', item['name']), 'variants': variants})
result = optimize(requirements, request.get('budget_minor') if request.get('budget_minor') is not None else intent.get('budget_minor'))
arguments = {'selectedAddressId': address, 'items': [
{'spinId': v['spin_id'], 'skuId': v['sku_id'], 'quantity': v['quantity']} for v in result.get('selected_items', [])]}
source = 'simulation' if mode == 'replay' else 'live_provider'
record = self.store.create('basketplan', account['id'], {'source': source, 'requirements': requirements,
'result': result, 'budget_minor': request.get('budget_minor') if request.get('budget_minor') is not None else intent.get('budget_minor'), 'arguments': arguments})
return {'intent': intent, 'catalog': catalog, 'result': result, 'source': source, 'plan_id': record['id'], 'requirements': requirements, 'proposal_arguments': arguments}
def snapshot(self, account, provider, args, mode, scenario='success'):
if provider == 'dineout':
read_args = {key: args[key] for key in ('restaurantId', 'date', 'latitude', 'longitude')}
elif provider == 'food':
read_args = {'addressId': args['addressId']}
else:
read_args = {}
read = self.provider.call(account, provider, CART_TOOL[provider], read_args, mode, scenario)
snap = cart_snapshot(read['data'])
if not snap:
raise ValueError('Provider supplied no authoritative cart or slot snapshot')
return snap
def _validate_arguments(self, account, provider, tool, args, mode):
if provider not in MUTATIONS or tool not in MUTATIONS[provider]:
raise ValueError('Mutation is not supported; inspect capabilities')
if any(k.lower() in {'token', 'access_token', 'authorization', 'account_id', 'user_id'} for k in args):
raise ValueError('Provider identity cannot be supplied in action arguments')
if tool in ('update_cart', 'update_food_cart'):
address_field = 'selectedAddressId' if provider == 'im' else 'addressId'
if not isinstance(args.get(address_field), str) or not args[address_field].strip():
raise ValueError('Select a returned delivery address before changing the cart')
if provider == 'food' and not args.get('restaurantId'):
raise ValueError('Food cart requires its returned restaurantId')
if not isinstance(args.get('items'), list) or not 1 <= len(args['items']) <= 100:
raise ValueError('Provide 1 to 100 explicit cart items')
for item in args['items']:
if not isinstance(item, dict):
raise ValueError('Cart items must be objects')
if not isinstance(item.get('quantity'), int) or isinstance(item['quantity'], bool) or not 0 < item['quantity'] <= 10000:
raise ValueError('Cart quantities must be positive integers')
if provider == 'im' and not (item.get('spinId') and item.get('skuId')):
raise ValueError('Use returned SKU-level spinId and skuId')
if provider == 'food' and not (item.get('menu_item_id') or item.get('itemId') or item.get('id')):
raise ValueError('Use the returned menu item identity')
if provider == 'food' and any(item.get(k) for k in ('variants', 'variations', 'variantsV2', 'addons')):
raise ValueError('Customized Food items require a dedicated reviewed selection flow')
if mode == 'live':
reads = self.store.list('provider_read', account['id'], 500)
candidates = [r['data'] for r in reads if r['data']['provider'] == provider
and r['data']['source'] == 'live_provider'
and time.time() - datetime.fromisoformat(r['created_at']).timestamp() < 300]
if provider == 'im':
address = args.get('selectedAddressId')
known = [v for read in candidates if read.get('arguments', {}).get('addressId') == address
for v in catalog_variants(read['data'])]
for item in args['items']:
variants = [v for v in known if v['spin_id'] == item['spinId'] and v['sku_id'] == item['skuId']]
if not variants or not any(v['available'] and item['quantity'] <= v['purchase_limit'] for v in variants):
raise ValueError('Refresh discovery: unknown, unavailable, or quantity-capped variant')
else:
def menu_ids(value):
found = set()
if isinstance(value, dict):
identifier = value.get('menu_item_id') or value.get('itemId') or value.get('id')
if identifier and any(k in value for k in ('price', 'defaultPrice')) and value.get('available') is not False and value.get('inStock') != 0 and not any(value.get(k) for k in ('hasVariants', 'hasAddons', 'variations', 'variantsV2', 'addons')):
found.add(str(identifier))
for key in ('items', 'categories', 'subcategories'):
found.update(menu_ids(value.get(key)))
elif isinstance(value, list):
for child in value:
found.update(menu_ids(child))
return found
known = set()
for read in candidates:
discovered = read.get('arguments', {})
restaurant = discovered.get('restaurantId') or discovered.get('restaurantIdOfAddedItem')
if restaurant == args.get('restaurantId') and discovered.get('addressId') == args.get('addressId') and read.get('tool') in ('get_restaurant_menu', 'search_menu'):
known.update(menu_ids(read['data']))
if any(str(x.get('menu_item_id') or x.get('itemId') or x.get('id')) not in known for x in args['items']):
raise ValueError('Refresh the restaurant menu at this address; only returned uncustomized items are supported')
elif provider in ('food', 'im'):
if not args.get('addressId') or not args.get('paymentMethod'):
raise ValueError('Select a returned address and an available payment method')
if args.get('confirmDuplicate'):
raise ValueError('Duplicate override requires provider-specific review and is not supported')
if mode == 'live' and args['paymentMethod'] not in ('Cash', 'COD'):
raise ValueError('Only returned Cash/COD methods are enabled; UPI and wallet confirmation are not implemented')
elif provider == 'dineout':
if not all(args.get(k) for k in ('restaurantId', 'slotId', 'itemId', 'reservationTime')):
raise ValueError('Select returned restaurant, slot, item and reservation time')
if args.get('isFree') is not True:
raise ValueError('Only free reservations are enabled; paid booking flow is unavailable')
if not isinstance(args.get('guestCount'), int) or isinstance(args['guestCount'], bool) or not 1 <= args['guestCount'] <= 20:
raise ValueError('Reservation guestCount must be an integer from 1 to 20')
for field in ('slotId', 'reservationTime'):
if not isinstance(args[field], int) or isinstance(args[field], bool) or args[field] <= 0:
raise ValueError('Use the returned numeric slotId and reservationTime')
coordinates(args)
if not isinstance(args.get('date'), str):
raise ValueError('Copy the selected slot date into the proposal context')
try:
datetime.strptime(args['date'], '%Y-%m-%d')
except ValueError:
raise ValueError('Reservation date must be YYYY-MM-DD') from None
if any(args.get(k) for k in ('cartKey', 'intentApp', 'generateUPIQR')) or args.get('paymentMethod') not in (None, 'Cash'):
raise ValueError('Paid reservation parameters are not allowed in the free booking flow')
def propose(self, account, req):
provider, tool = req['provider'], req['tool']
args = deepcopy(req.get('arguments', {}))
if provider == 'food' and tool == 'update_food_cart' and 'cartItems' in args:
if 'items' in args:
raise ValueError('Provide cartItems or items, never both')
args['items'] = args.pop('cartItems')
mode = req.get('mode', 'live')
scenario = req.get('scenario', 'success')
if account['role'] == 'reviewer' and mode != 'replay':
raise PermissionError('Reviewer mode supports only isolated simulations')
self._validate_arguments(account, provider, tool, args, mode)
with self.store.atomic(account['id']):
snap = self.snapshot(account, provider, args, mode)
actual_address = args.get('selectedAddressId') or args.get('addressId')
if req.get('address_id') and actual_address and req['address_id'] != actual_address:
raise ValueError('Displayed address must match action payload')
address = req.get('address_id') or actual_address
total = minor(snap['cartTotalAmount']) if 'cartTotalAmount' in snap else None
if tool in ('update_cart', 'update_food_cart'):
# An existing cart's amount does not quote its proposed replacement.
total = None
if provider == 'dineout':
if snap.get('restaurantId') != args['restaurantId']:
raise ValueError('Returned slots belong to a different restaurant')
if any(snap.get(key) != args[key] for key in ('latitude', 'longitude')):
raise ValueError('Returned slots belong to a different selected location')
matching = []
for slot in snap.get('slots', []):
if not isinstance(slot, dict) or slot.get('reservationTime') != args['reservationTime'] or slot.get('dateStr', snap.get('date')) != args['date']:
continue
for deal in slot.get('deals', [slot]):
if isinstance(deal, dict) and deal.get('slotId') == args['slotId'] and deal.get('itemId') == args['itemId'] and deal.get('isFree') is True:
if deal.get('bookingPrice') is not None and minor(deal['bookingPrice']) != 0:
continue
capacity = deal.get('availableInventory', deal.get('availableInventoryCount', slot.get('availableInventory')))
if capacity is not None and (not isinstance(capacity, (int, float)) or capacity < args['guestCount']):
continue
matching.append(deal)
if len(matching) != 1:
raise ValueError('Reservation must match returned free slot, deal and time')
total = 0
if tool in ('checkout', 'place_food_order'):
quoted_address = snap.get('selectedAddressDetails', {}).get('id') or snap.get('selectedAddress')
if quoted_address != args.get('addressId'):
raise Conflict('Delivery address differs from the authoritative cart; refresh at selected address')
if not snap.get('items') or total is None:
raise ValueError('An authoritative non-empty cart and total are required')
methods = snap.get('availablePaymentMethods', [])
if args['paymentMethod'] not in methods:
raise ValueError('Selected payment method is not present in the current cart')
plan_id = req.get('plan_id')
if plan_id:
plan = self.store.get('basketplan', plan_id, account['id'])['data']
expected_source = 'simulation' if mode == 'replay' else 'live_provider'
if plan.get('source') != expected_source or tool != 'update_cart' or provider != 'im':
raise Conflict('Basket plan belongs to a different mode or provider')
if plan['arguments'] != args:
raise Conflict('Edited basket no longer matches the reviewed plan')
total = plan['result']['subtotal_minor']
data = {'state': 'PROPOSED', 'provider': provider, 'tool': tool, 'arguments': args,
'address_id': address, 'mode': mode, 'scenario': scenario, 'snapshot': snap,
'snapshot_hash': digest(snap), 'total_minor': total, 'plan_id': plan_id,
'pricing_scope': 'items_only' if tool in ('update_cart', 'update_food_cart') else 'provider_cart',
'source': 'simulation' if mode == 'replay' else 'live_provider', 'expires_at': time.time() + 600}
data['approval_payload_hash'] = digest(data)
return self.store.create('proposal', account['id'], data)
def approve(self, account, proposal_id, version):
with self.store.atomic(account['id']):
proposal = self.store.get('proposal', proposal_id, account['id'])
if proposal['data'].get('action_id'):
if proposal['version'] not in (version, version + 1):
raise Conflict('Approval version differs from original proposal')
return self.store.get('action', proposal['data']['action_id'], account['id'])
try:
existing = self.store.get('action', 'action-' + proposal_id, account['id'])
if existing['data']['proposal_version'] != version:
raise Conflict('Approval version differs from original proposal')
return existing
except LookupError:
pass
if proposal['version'] != version or proposal['data']['state'] != 'PROPOSED':
raise Conflict('Proposal changed; review its current version')
if proposal['data']['expires_at'] < time.time():
raise Conflict('Approval expired; refresh proposal')
data = {**proposal['data'], 'state': 'APPROVED', 'proposal_id': proposal_id,
'proposal_version': version, 'approved_by': account['id']}
action = self.store.create('action', account['id'], data, 'action-' + proposal_id)
self.store.update('proposal', proposal_id, account['id'], {**proposal['data'], 'state': 'APPROVED', 'action_id': action['id']}, version)
return action
def _save(self, account, action, state, **fields):
return self.store.update('action', action['id'], account['id'], {**action['data'], **fields, 'state': state}, action['version'], 'action.' + state.lower())
def execute(self, account, action_id, key):
if not key or len(key) > 128 or not key.isascii() or any(ord(c) < 33 or ord(c) > 126 for c in key):
raise ValueError('Idempotency-Key must contain 1 to 128 visible ASCII characters')
with self.store.atomic(account['id']):
action = self.store.get('action', action_id, account['id'])
data = action['data']
key_id = 'exec-' + digest([account['id'], key])[:40]
try:
previous = self.store.get('execution_key', key_id, account['id'])
if previous['data']['action_id'] != action_id:
raise Conflict('Idempotency-Key is bound to another action')
except LookupError:
self.store.create('execution_key', account['id'], {'action_id': action_id, 'payload_hash': data['approval_payload_hash']}, key_id)
if data['state'] == 'EXECUTING':
return self._save(account, action, 'UNKNOWN', reason='Execution interrupted; reconcile before continuing')
if data['state'] != 'APPROVED':
return action
if data['expires_at'] < time.time():
return self._save(account, action, 'SUPERSEDED', reason='Approval expired')
if data['tool'] in ORDERS:
uncertain = [a for a in self.store.scan('action', account['id']) if a['id'] != action_id
and a['data']['provider'] == data['provider'] and a['data']['tool'] in ORDERS
and a['data'].get('mode', 'live') == data['mode']
and a['data']['state'] in ('UNKNOWN', 'EXECUTING', 'PENDING_PAYMENT')]
if uncertain:
raise Conflict('Resolve existing uncertain placement before another order')
current = self.snapshot(account, data['provider'], data['arguments'], data['mode'])
if data['mode'] == 'replay' and data['scenario'] in ('price_change', 'external_edit'):
current = {**current, 'cartTotalAmount': '999.00'}
if digest(current) != data['snapshot_hash']:
repair = self.propose(account, {**data, 'scenario': 'success'})
return self._save(account, action, 'SUPERSEDED', reason='Cart or price changed; review a new proposal', repair_proposal_id=repair['id'])
action = self._save(account, action, 'EXECUTING', started_at=time.time())
try:
response = self.provider.call(account, data['provider'], data['tool'], data['arguments'],
data['mode'], data['scenario'], action_id)
if data['provider'] == 'food' and data['tool'] == 'update_food_cart':
# Food update does not reliably include location/payment
# context. Its documented follow-up cart read verifies both.
mutation_response = response
response = self.provider.call(account, 'food', 'get_food_cart',
{'addressId': data['arguments']['addressId']}, data['mode'])
response = {**response, 'mutation_response': mutation_response}
receipt = response['data']
if not isinstance(receipt, dict):
raise ValueError('A structured transaction receipt is required')
changed_quantities = data['tool'] not in ORDERS and (receipt.get('removedOutOfStockItems') or receipt.get('reducedQuantityItems'))
# Changed item quantities necessarily change price. First reject
# a changed address, then build the renewed quantity proposal.
mismatch = self._receipt_mismatch({**data, 'total_minor': None} if changed_quantities else data, receipt)
if mismatch:
return self._save(account, action, 'UNKNOWN', receipt=response, reason=mismatch)
if data['tool'] in ORDERS:
status = receipt.get('status', '')
if status == 'PENDING_PAYMENT':
return self._save(account, action, 'PENDING_PAYMENT', receipt=response, reason='Payment not confirmed; inspect provider status')
if not (receipt.get('orderId') and status in ('CONFIRMED', 'SUCCESS', 'PLACED', 'ORDER_PLACED')):
return self._save(account, action, 'UNKNOWN', receipt=response, reason='No confirmed terminal provider receipt')
elif receipt.get('removedOutOfStockItems') or receipt.get('reducedQuantityItems'):
repair = self._repair(account, data, receipt)
return self._save(account, action, 'SUPERSEDED', receipt=response,
reason='Provider changed quantities; renewed approval required', repair_proposal_id=repair['id'] if repair else None)
if data['tool'] not in ORDERS:
returned = item_quantities(receipt.get('items'))
if returned != item_quantities(data['arguments']['items']):
return self._save(account, action, 'UNKNOWN', receipt=response, reason='Cart response differs from approved item quantities')
return self._save(account, action, 'SUCCEEDED', receipt=response, completed_at=time.time())
except PermissionError:
return self._save(account, action, 'FAILED', reason='Provider authentication expired; reconnect')
except (TimeoutError, OSError):
return self._save(account, action, 'UNKNOWN', reason='Response lost; inspect provider state before another attempt')
except ProviderRejected:
return self._save(account, action, 'FAILED', reason='Provider explicitly rejected the request')
except ValueError:
return self._save(account, action, 'UNKNOWN', reason='Invalid provider response; inspect before another placement')
except Exception:
return self._save(account, action, 'UNKNOWN', reason='Execution interrupted; inspect provider state')
def _repair(self, account, data, receipt):
if not data.get('plan_id'):
return None
plan = deepcopy(self.store.get('basketplan', data['plan_id'], account['id'])['data'])
caps = {x['spinId']: 0 for x in receipt.get('removedOutOfStockItems', [])}
caps.update({x['spinId']: x['cappedQuantity'] for x in receipt.get('reducedQuantityItems', [])})
for req in plan['requirements']:
for variant in req['variants']:
if variant['spin_id'] in caps:
variant['purchase_limit'] = caps[variant['spin_id']]
variant['available'] = caps[variant['spin_id']] > 0
plan['result'] = optimize(plan['requirements'], plan.get('budget_minor'))
if plan['result']['status'] != 'optimal':
self.store.create('basketplan', account['id'], plan)
return None
plan['arguments']['items'] = [{'spinId': x['spin_id'], 'skuId': x['sku_id'], 'quantity': x['quantity']}
for x in plan['result']['selected_items']]
new_plan = self.store.create('basketplan', account['id'], plan)
return self.propose(account, {**data, 'arguments': plan['arguments'], 'plan_id': new_plan['id'], 'scenario': 'success'})
@staticmethod
def _receipt_mismatch(data, receipt, require_address=False):
"""Never treat conflicting receipt evidence as approval of changed terms.
Cart totals may include fees absent from catalogue prices. Without an
independently comparable item subtotal, a changed amount stays unresolved.
"""
expected = data.get('address_id')
details = receipt.get('selectedAddressDetails') or {}
returned = receipt.get('addressId') or receipt.get('selectedAddress') or details.get('id')
if isinstance(returned, dict):
returned = returned.get('id')
if expected and (returned != expected if require_address else returned is not None and returned != expected):
return 'Receipt delivery address differs from approval or cannot be verified'
restaurant = receipt.get('restaurantId') or (receipt.get('restaurant') or {}).get('id')
expected_restaurant = data['arguments'].get('restaurantId')
if restaurant is not None and expected_restaurant is not None and restaurant != expected_restaurant:
return 'Receipt restaurant differs from approval'
quoted = data.get('total_minor')
if data.get('provider') == 'dineout':
for field in ('restaurantId', 'guestCount'):
if receipt.get(field) is not None and receipt[field] != data['arguments'].get(field):
return 'Reservation receipt differs from the approved restaurant or guest count'
if quoted is not None:
fields = ('itemSubtotal', 'subtotal') if data['pricing_scope'] == 'items_only' else ()
amount = next((receipt[k] for k in fields if receipt.get(k) is not None), None)
if amount is None:
amount = receipt.get('cartTotalAmount', receipt.get('cartTotal', receipt.get('totalAmount')))
if amount is not None and minor(amount) != quoted:
return 'Receipt amount differs from approved quote; review current prices and fees'
return None
def reconcile(self, account, action_id):
with self.store.atomic(account['id']):
action = self.store.get('action', action_id, account['id'])
data = action['data']
if data['state'] not in ('UNKNOWN', 'EXECUTING', 'PENDING_PAYMENT'):
return action
if data['tool'] not in ORDERS:
snap = self.snapshot(account, data['provider'], data['arguments'], data['mode'])
desired = data['arguments'].get('items', [])
if item_quantities(snap.get('items')) == item_quantities(desired) and not self._receipt_mismatch(data, snap, require_address=True):
return self._save(account, action, 'SUCCEEDED', receipt={'data': snap, 'source': data['source']}, reason='Authoritative cart inspected')
else:
tool = {'im': 'get_orders', 'food': 'get_food_orders', 'dineout': 'get_booking_status'}[data['provider']]
order_id = data.get('receipt', {}).get('data', {}).get('orderId')
if data['provider'] == 'dineout' and not order_id and data['mode'] == 'live':
return self._save(account, action, 'UNKNOWN', reason='No booking ID available; inspect provider account manually')
response = self.provider.call(account, data['provider'], tool, {'orderId': order_id} if order_id else {}, data['mode'])
body = response['data']
orders = body.get('orders', []) if isinstance(body, dict) else body
if isinstance(body, dict) and body.get('orderId'):
orders = [body]
# A list of similar orders is insufficient proof of this attempt. Require exact ID.
matches = [x for x in orders if (order_id and x.get('orderId') == order_id) or
(data['mode'] == 'replay' and x.get('action_id') == action_id)]
if len(matches) == 1 and matches[0].get('status') in ('CONFIRMED', 'SUCCESS', 'PLACED', 'ORDER_PLACED') and not self._receipt_mismatch(data, matches[0]):
return self._save(account, action, 'SUCCEEDED', receipt={**response, 'data': matches[0]}, reason='Exact provider receipt reconciled')
return self._save(account, action, 'UNKNOWN', reason='No exact evidence; do not repeat placement')