test glue

This commit is contained in:
C committed 2026-01-04 11:18:43 -08:00
1 parent 03f6e84965
commit d341684567
3 files changed
+413 -40

No files matched your search

+165 -11
View File
@@ -51,10 +51,93 @@ async def get_itm(sku: str):
return {"name": name, "id": itm_id}
async def update_itm(lego_set: dict):
async def get_item_by_id(item_id: str) -> dict:
"""
Retrieve full item details by Square catalog item ID.
Args:
item_id: Square catalog item ID
Returns:
dict: Item details including name, category_id, variations, etc.
Raises:
Exception: If item not found or API error
"""
try:
result = await client.catalog.retrieve_catalog_object(
object_id=item_id, include_related_objects=True
)
result_json = json.loads(result.model_dump_json())
if not result_json.get("object"):
raise ValueError(f"Item {item_id} not found")
obj = result_json["object"]
item_data = obj.get("item_data", {})
return {
"id": obj["id"],
"name": item_data.get("name", ""),
"description": item_data.get("description", ""),
"category_id": item_data.get("category_id"),
"variations": item_data.get("variations", []),
"updated_at": obj.get("updated_at"),
"version": obj.get("version"),
}
except Exception as e:
print(f"[@ERROR] Failed to get item {item_id}: {e}")
raise
async def get_item_by_variation_id(variation_id: str) -> dict:
"""
Retrieve parent item details from a variation ID.
Webhooks send variation IDs (inventory.count.updated), but we need
the parent item to extract the set number from the name.
Args:
variation_id: Square catalog item variation ID
Returns:
dict: Parent item details
Raises:
Exception: If variation/item not found or API error
"""
try:
# Get variation object
result = await client.catalog.retrieve_catalog_object(
object_id=variation_id, include_related_objects=True
)
result_json = json.loads(result.model_dump_json())
if not result_json.get("object"):
raise ValueError(f"Variation {variation_id} not found")
variation_obj = result_json["object"]
# Get parent item ID from variation
item_id = variation_obj.get("item_variation_data", {}).get("item_id")
if not item_id:
raise ValueError(f"No parent item_id found for variation {variation_id}")
# Retrieve parent item
return await get_item_by_id(item_id)
except Exception as e:
print(f"[@ERROR] Failed to get item from variation {variation_id}: {e}")
raise
async def update_itm(item_id: str, lego_set: dict):
"""
Asynchronously updates an item in the Square catalog based on the provided LEGO set information.
Args:
item_id (str): Square catalog item ID to update
lego_set (dict): A dictionary containing LEGO set details from abricksetapi. Expected keys include:
- "set_num": LEGO set number (e.g., "75192")
- "set_name": Official LEGO set name
@@ -69,19 +152,90 @@ async def update_itm(lego_set: dict):
KeyError: If expected keys are missing from the input dictionary.
Exception: For errors during Square API interaction.
"""
try:
set_number = lego_set["set_num"]
set_name = lego_set["set_name"]
set_theme = lego_set["set_theme"]
set_upc = lego_set["set_barcode"]
set_image = lego_set["set_image"]
pw_name = lego_set["pw_name"]
set_adjustedprice = lego_set["set_adjustredprice"]
set_number = lego_set["set_num"]
set_name = lego_set["set_name"]
set_upc = lego_set["set_barcode"]
set_image = lego_set["set_image"]
pw_name = lego_set["pw_name"]
set_adjustedprice = lego_set["set_adjustredprice"]
# Convert price to cents for Square API
price_in_cents = int(set_adjustedprice * 100)
result = await client.catalog.search_items(text_filter=set_number, limit=1)
itm_id = json.loads(result.model_dump_json())["items"][0]["id"]
# Get current item to retrieve variation ID
item = await get_item_by_id(item_id)
variations = item.get("variations", [])
# await sq.catalog.object.upsert()
return True
if not variations:
print(
f"[@WARNING] Item {item_id} has no variations, creating new variation"
)
variation_id = None
else:
variation_id = variations[0]["id"]
# Build upsert body
upsert_body = {
"idempotency_key": str(uuid.uuid4()),
"object": {
"type": "ITEM",
"id": item_id,
"item_data": {
"name": pw_name,
"description": f"{set_name} - {set_theme}",
"variations": [
{
"type": "ITEM_VARIATION",
"id": (
variation_id if variation_id else "#TEMP_VARIATION_ID"
),
"item_variation_data": {
"item_id": item_id,
"name": "Regular",
"pricing_type": "FIXED_PRICING",
"price_money": {
"amount": price_in_cents,
"currency": "USD",
},
"sku": set_upc if set_upc else None,
},
}
],
},
},
}
# Remove None values
if not set_upc:
del upsert_body["object"]["item_data"]["variations"][0][
"item_variation_data"
]["sku"]
print(f"[@DEBUG] Upserting item {item_id} with name: {pw_name}")
# Perform upsert
result = await client.catalog.upsert_catalog_object(body=upsert_body)
result_json = json.loads(result.model_dump_json())
if result_json.get("catalog_object"):
print(f"[@DEBUG] ✓ Successfully updated item {item_id}")
# TODO: Handle image upload separately (Square Images API)
# This requires multipart/form-data upload
return True
else:
print(
f"[@ERROR] Failed to update item {item_id}: No catalog_object in response"
)
return False
except Exception as e:
print(f"[@ERROR] Failed to update item {item_id}: {e}")
import traceback
traceback.print_exc()
return False
async def acat2id(cat_id: str):