Spaces:
Running
Running
File size: 2,826 Bytes
72eef4f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
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 |