from pymongo import ASCENDING, DESCENDING import time from .extensions import mongo def backfill_orders(): t=time.time() print("Starting backfill process for order serial numbers...") # 1. Find the highest existing serial number to know where to start. highest_order = mongo.db.orders.find_one( {'serial_no': {'$exists': True}}, sort=[('serial_no', DESCENDING)] ) next_serial_to_assign = 1 if highest_order and 'serial_no' in highest_order: next_serial_to_assign = highest_order['serial_no'] + 1 print(f"Highest existing serial is {highest_order['serial_no']}. New serials will start from {next_serial_to_assign}.") else: print("No existing serial numbers found. Starting from 1.") # 2. Find all orders that are missing a serial number, sorted by creation date. orders_to_update = list(mongo.db.orders.find( {'serial_no': {'$exists': False}}, sort=[('created_at', ASCENDING)] )) if not orders_to_update: print("No orders found without a serial number. All good!") return print(f"Found {len(orders_to_update)} orders to update.") # 3. Iterate and assign the new serial numbers. for order in orders_to_update: mongo.db.orders.update_one( {'_id': order['_id']}, {'$set': {'serial_no': next_serial_to_assign}} ) print(f" - Updated order {order['_id']} with Serial No: {next_serial_to_assign}") next_serial_to_assign += 1 # 4. Finally, update the global counter to the last assigned value. final_serial_value = next_serial_to_assign - 1 mongo.db.counters.update_one( {'_id': 'order_serial'}, {'$set': {'sequence_value': final_serial_value}}, upsert=True ) print(time.time()-t) print(f"\nBackfill complete. Updated {len(orders_to_update)} orders.") print(f"Global order serial counter has been set to {final_serial_value}.") # --- NEW: Define functions for the AI model --- def get_next_order_serial(): """ Atomically retrieves and increments the global order serial number from the 'counters' collection. """ # find_one_and_update is atomic. upsert=True creates the doc if it doesn't exist. # By default, it returns the document *before* the update. counter_doc = mongo.db.counters.find_one_and_update( {'_id': 'order_serial'}, {'$inc': {'sequence_value': 1}}, upsert=True ) # If counter_doc is None, it means the document was just created (upserted) with a value of 1. if counter_doc is None: return 1 # Otherwise, it returns the old document, so we add 1 to get the new value. else: return counter_doc['sequence_value'] + 1