in order/utils/order_actions.py [0:0]
def write_orders(store:Store, orders:List[Dict]):
''' write orders and order items. create Customer object if customer info is new.
populate orders with 'merchant_order_reference' for acknowledge step
note: retailer_id is a REQUIRED field of the items
params:
store: the store the orders belongs to
orders: list of orders
'''
for order in orders:
buyer = order.pop('buyer_details')
shipping_addr_str = json.dumps(order.pop('shipping_address'))
try:
customer = Customer.objects.get(store=store, full_name=buyer['name'], email=buyer['email'], addr=shipping_addr_str)
except Exception:
print("Buyer info not found in Customer table. Creating Customer entry for {} ({})".format(buyer['name'], buyer['email']))
customer = Customer(
store=store,
full_name=buyer['name'],
email=buyer['email'],
addr=shipping_addr_str,
)
customer.save()
try:
order_model = Order.objects.get(store=store, customer=customer, ext_order_id=order['id'])
print("Order with ext order id {} already exists".format(order['id']))
continue
except Exception:
print("Order not found or is new, writing...")
order_model = Order(
store=store,
customer=customer,
ext_order_id=order['id'],
)
if order['order_status']['state'] == "IN_PROGRESS":
print("WARN: order is already IN_PROGRESS and missing from orders table. Filling.")
order_model.order_status = OrderStatus.IN_PROGRESS
order_model.save()
items = order.pop('items')
try:
items_products = [(item, Product.objects.get(id=item['retailer_id'])) for item in items]
except Exception:
# at least 1 product does not exist in db (anymore)
order_model.missing_items = True
order_model.save()
print("WARN: order contains products that no longer exist")
continue
# update order with 'merchant_order_reference' for the acknowledge step
order['merchant_order_reference'] = order_model.id
for item, product in items_products:
try:
item_model = OrderItem.objects.get(order=order_model, product=product)
print("item product id {} already on order with id {}".format(product.id, order_model.id))
except Exception:
item_model = OrderItem(
order=order_model,
product=product,
quantity=int(item['quantity']),
)
item_model.save()