This commit is contained in:
C committed 2026-01-04 14:09:31 -08:00
1 parent 94af7d9d89
commit ce32abf58c
1 file changed
+42 -32
+42 -32
View File
@@ -17,26 +17,30 @@ from pathlib import Path
# Add parent directory to path for imports # Add parent directory to path for imports
sys.path.insert(0, str(Path(__file__).parent.parent)) sys.path.insert(0, str(Path(__file__).parent.parent))
from asquare import AsyncSquare, get_square_client import get_sq_env
from get_sq_env import SQUARE_LEGO_CAT_ID from square import AsyncSquare
SQUARE_LEGO_CAT_ID = get_sq_env.LEGO_CAT_ID
async def migrate_sku_to_gtin(): async def migrate_sku_to_gtin():
"""Migrate SKU values to GTIN for all LEGO items.""" """Migrate SKU values to GTIN for all LEGO items."""
client = await get_square_client() client = AsyncSquare(
asquare = AsyncSquare() access_token=get_sq_env.SQUARE_TOKEN,
environment=get_sq_env.environment,
)
print(f"[@INFO] Searching for items in LEGO category {SQUARE_LEGO_CAT_ID}...") print(f"[@INFO] Searching for items in LEGO category {SQUARE_LEGO_CAT_ID}...")
# Search all items in LEGO category # Search all items in LEGO category
cursor = None cursor = None
page = 1 page = 1
total_items = 0 total_items = 0
updated_items = 0 updated_items = 0
while True: while True:
print(f"[@INFO] Processing page {page}...") print(f"[@INFO] Processing page {page}...")
result = await client.catalog.search( result = await client.catalog.search(
body={ body={
"object_types": ["ITEM"], "object_types": ["ITEM"],
@@ -50,14 +54,14 @@ async def migrate_sku_to_gtin():
"cursor": cursor, "cursor": cursor,
} }
) )
result_json = json.loads(result.model_dump_json()) result_json = json.loads(result.model_dump_json())
items = result_json.get("objects", []) items = result_json.get("objects", [])
cursor = result_json.get("cursor") cursor = result_json.get("cursor")
if not items: if not items:
break break
# Process each item # Process each item
for item in items: for item in items:
item_id = item["id"] item_id = item["id"]
@@ -65,17 +69,17 @@ async def migrate_sku_to_gtin():
item_name = item_data.get("name", "") item_name = item_data.get("name", "")
variations = item_data.get("variations", []) variations = item_data.get("variations", [])
item_version = item.get("version") item_version = item.get("version")
total_items += 1 total_items += 1
needs_update = False needs_update = False
updated_variations = [] updated_variations = []
# Extract set number from item name if it matches LEGO format # Extract set number from item name if it matches LEGO format
set_number = None set_number = None
match = re.search(r"^(\d{5})\s*-", item_name) match = re.search(r"^(\d{5})\s*-", item_name)
if match: if match:
set_number = match.group(1) set_number = match.group(1)
# Check each variation # Check each variation
for var in variations: for var in variations:
var_data = var.get("item_variation_data", {}) var_data = var.get("item_variation_data", {})
@@ -83,12 +87,12 @@ async def migrate_sku_to_gtin():
var_version = var.get("version") var_version = var.get("version")
sku = var_data.get("sku") sku = var_data.get("sku")
upc = var_data.get("upc") upc = var_data.get("upc")
# If SKU exists but UPC doesn't, migrate # If SKU exists but UPC doesn't, migrate
if sku and not upc: if sku and not upc:
print(f"[@INFO] Item {item_id} ({item_name})") print(f"[@INFO] Item {item_id} ({item_name})")
print(f"[@INFO] Variation {var_id}: Moving SKU '{sku}' to UPC") print(f"[@INFO] Variation {var_id}: Moving SKU '{sku}' to UPC")
# Build updated variation # Build updated variation
updated_var = { updated_var = {
"type": "ITEM_VARIATION", "type": "ITEM_VARIATION",
@@ -97,22 +101,28 @@ async def migrate_sku_to_gtin():
"item_variation_data": { "item_variation_data": {
"item_id": item_id, "item_id": item_id,
"name": var_data.get("name", "Regular"), "name": var_data.get("name", "Regular"),
"pricing_type": var_data.get("pricing_type", "FIXED_PRICING"), "pricing_type": var_data.get(
"pricing_type", "FIXED_PRICING"
),
"upc": sku, # Move SKU value to UPC "upc": sku, # Move SKU value to UPC
"sku": set_number if set_number else None, # Set to LEGO set number if available "sku": (
} set_number if set_number else None
), # Set to LEGO set number if available
},
} }
# Preserve pricing info # Preserve pricing info
if "price_money" in var_data: if "price_money" in var_data:
updated_var["item_variation_data"]["price_money"] = var_data["price_money"] updated_var["item_variation_data"]["price_money"] = var_data[
"price_money"
]
updated_variations.append(updated_var) updated_variations.append(updated_var)
needs_update = True needs_update = True
else: else:
# Keep variation as-is # Keep variation as-is
updated_variations.append(var) updated_variations.append(var)
# Update item if needed # Update item if needed
if needs_update: if needs_update:
try: try:
@@ -125,10 +135,10 @@ async def migrate_sku_to_gtin():
fresh_item = fresh_json["objects"][0] fresh_item = fresh_json["objects"][0]
fresh_item_data = fresh_item.get("item_data", {}) fresh_item_data = fresh_item.get("item_data", {})
fresh_version = fresh_item.get("version") fresh_version = fresh_item.get("version")
# Update variations while preserving all other fields # Update variations while preserving all other fields
fresh_item_data["variations"] = updated_variations fresh_item_data["variations"] = updated_variations
upsert_body = { upsert_body = {
"idempotency_key": str(uuid.uuid4()), "idempotency_key": str(uuid.uuid4()),
"object": { "object": {
@@ -136,25 +146,25 @@ async def migrate_sku_to_gtin():
"id": item_id, "id": item_id,
"version": fresh_version, "version": fresh_version,
"item_data": fresh_item_data, "item_data": fresh_item_data,
} },
} }
await client.catalog.object.upsert(body=upsert_body) await client.catalog.object.upsert(body=upsert_body)
print(f"[@INFO] ✓ Successfully updated item {item_id}") print(f"[@INFO] ✓ Successfully updated item {item_id}")
updated_items += 1 updated_items += 1
# Small delay to avoid rate limits # Small delay to avoid rate limits
await asyncio.sleep(0.1) await asyncio.sleep(0.1)
except Exception as e: except Exception as e:
print(f"[@ERROR] Failed to update item {item_id}: {e}") print(f"[@ERROR] Failed to update item {item_id}: {e}")
page += 1 page += 1
# If no cursor, we're done # If no cursor, we're done
if not cursor: if not cursor:
break break
print(f"\n[@INFO] Migration complete!") print(f"\n[@INFO] Migration complete!")
print(f"[@INFO] Total items processed: {total_items}") print(f"[@INFO] Total items processed: {total_items}")
print(f"[@INFO] Items updated: {updated_items}") print(f"[@INFO] Items updated: {updated_items}")