Files
gomag-vending/api/app/services/retry_service.py
Claude Agent bcd65d9fd6 fix(retry): pre-populate price list before re-importing failed orders
Production VENDING orders #485841978 and #485841895 (2026-04-28) crashed
on Retry with PL/SQL COM-001 because the retry path skipped the
CRM_POLITICI_PRET_ART pre-population step that bulk sync runs.

The price-list auto-insert (PRET=0) for missing CODMATs was only invoked
in sync_service.run_sync (lines 592-718). retry_service called
import_single_order directly, hitting pack_comenzi.adauga_articol_comanda
NO_DATA_FOUND on every CODMAT without a price entry.

Extracted the validation block into validation_service.pre_validate_order_prices
and call it from both bulk sync and retry. Single source of truth for
SKU validation, dual-policy routing (cont 341/345 → productie),
ARTICOLE_TERTI mapping resolution, and kit component price gating.

Tests: 3 unit + 3 oracle integration covering the regression scenario,
empty input, dual-policy routing, idempotency, and pre-validation
exception propagation.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-29 10:19:38 +00:00

336 lines
14 KiB
Python

"""Retry service — re-import individual failed/skipped orders."""
import asyncio
import logging
import tempfile
from datetime import datetime, timedelta
from ..constants import OrderStatus
logger = logging.getLogger(__name__)
async def _download_and_reimport(order_number: str, order_date_str: str, customer_name: str, app_settings: dict) -> dict:
"""Download order from GoMag and re-import it into Oracle.
Does NOT check status guard — caller is responsible.
Returns: {"success": bool, "message": str, "status": str|None}
"""
from . import sqlite_service, gomag_client, import_service, order_reader, validation_service
# Parse order date for narrow download window
try:
order_date = datetime.fromisoformat(order_date_str.replace("Z", "+00:00")).date()
except (ValueError, AttributeError):
order_date = datetime.now().date() - timedelta(days=1)
gomag_key = app_settings.get("gomag_api_key") or None
gomag_shop = app_settings.get("gomag_api_shop") or None
with tempfile.TemporaryDirectory() as tmp_dir:
try:
today = datetime.now().date()
days_back = (today - order_date).days + 1
if days_back < 2:
days_back = 2
await gomag_client.download_orders(
tmp_dir, days_back=days_back,
api_key=gomag_key, api_shop=gomag_shop,
limit=200,
)
except Exception as e:
logger.error(f"Retry download failed for {order_number}: {e}")
return {"success": False, "message": f"Eroare download GoMag: {e}"}
# Find the specific order in downloaded data
target_order = None
orders, _ = order_reader.read_json_orders(json_dir=tmp_dir)
for o in orders:
if str(o.number) == str(order_number):
target_order = o
break
if not target_order:
return {"success": False, "message": f"Comanda {order_number} nu a fost gasita in GoMag API"}
# Import the order
id_pol = int(app_settings.get("id_pol") or 0)
id_sectie = int(app_settings.get("id_sectie") or 0)
id_gestiune = app_settings.get("id_gestiune", "")
id_gestiuni = [int(g.strip()) for g in id_gestiune.split(",") if g.strip()] if id_gestiune else None
# Pre-validate prices: auto-insert PRET=0 in CRM_POLITICI_PRET_ART for missing
# CODMATs so PL/SQL doesn't crash with COM-001. Mirrors sync_service flow.
from .. import database
validation = {"mapped": set(), "direct": set(), "missing": set(), "direct_id_map": {}}
if database.pool is not None:
conn = await asyncio.to_thread(database.get_oracle_connection)
try:
skus = {item.sku for item in target_order.items if item.sku}
if skus:
validation = await asyncio.to_thread(
validation_service.validate_skus, skus, conn, id_gestiuni,
)
if id_pol and skus:
id_pol_productie = int(app_settings.get("id_pol_productie") or 0) or None
cota_tva = float(app_settings.get("discount_vat") or 21)
await asyncio.to_thread(
validation_service.pre_validate_order_prices,
[target_order], app_settings, conn, id_pol, id_pol_productie,
id_gestiuni, validation, None, cota_tva,
)
except Exception as e:
logger.error(f"Retry pre-validation failed for {order_number}: {e}")
await sqlite_service.upsert_order(
sync_run_id="retry",
order_number=order_number,
order_date=order_date_str,
customer_name=customer_name,
status=OrderStatus.ERROR.value,
error_message=f"Retry pre-validation failed: {e}",
)
return {"success": False, "message": f"Eroare pre-validare preturi: {e}"}
finally:
await asyncio.to_thread(database.pool.release, conn)
try:
result = await asyncio.to_thread(
import_service.import_single_order,
target_order, id_pol=id_pol, id_sectie=id_sectie,
app_settings=app_settings, id_gestiuni=id_gestiuni
)
except Exception as e:
logger.error(f"Retry import failed for {order_number}: {e}")
await sqlite_service.upsert_order(
sync_run_id="retry",
order_number=order_number,
order_date=order_date_str,
customer_name=customer_name,
status=OrderStatus.ERROR.value,
error_message=f"Retry failed: {e}",
)
return {"success": False, "message": f"Eroare import: {e}"}
order_items_data = [
{
"sku": item.sku, "product_name": item.name,
"quantity": item.quantity, "price": item.price,
"baseprice": item.baseprice, "vat": item.vat,
"mapping_status": "mapped" if item.sku in validation["mapped"] else "direct",
"codmat": None, "id_articol": None, "cantitate_roa": None,
}
for item in target_order.items
]
if result.get("success"):
await sqlite_service.upsert_order(
sync_run_id="retry",
order_number=order_number,
order_date=order_date_str,
customer_name=customer_name,
status=OrderStatus.IMPORTED.value,
id_comanda=result.get("id_comanda"),
id_partener=result.get("id_partener"),
error_message=None,
)
if result.get("id_adresa_facturare") or result.get("id_adresa_livrare"):
await sqlite_service.update_import_order_addresses(
order_number=order_number,
id_adresa_facturare=result.get("id_adresa_facturare"),
id_adresa_livrare=result.get("id_adresa_livrare"),
)
await sqlite_service.add_order_items(order_number, order_items_data)
logger.info(f"Retry successful for order {order_number} → IMPORTED ({len(order_items_data)} items)")
return {"success": True, "message": "Comanda reimportata cu succes", "status": OrderStatus.IMPORTED.value}
else:
error = result.get("error", "Unknown error")
await sqlite_service.upsert_order(
sync_run_id="retry",
order_number=order_number,
order_date=order_date_str,
customer_name=customer_name,
status=OrderStatus.ERROR.value,
error_message=f"Retry: {error}",
)
await sqlite_service.add_order_items(order_number, order_items_data)
return {"success": False, "message": f"Import esuat: {error}", "status": OrderStatus.ERROR.value}
async def retry_single_order(order_number: str, app_settings: dict) -> dict:
"""Re-download and re-import a single order from GoMag.
Steps:
1. Read order from SQLite to get order_date / customer_name
2. Check sync lock (no retry during active sync)
3. Download narrow date range from GoMag (order_date ± 1 day)
4. Find the specific order in downloaded data
5. Run import_single_order()
6. Update status in SQLite
Returns: {"success": bool, "message": str, "status": str|None}
"""
from . import sqlite_service, sync_service
# Check sync lock
if sync_service._sync_lock.locked():
return {"success": False, "message": "Sync in curs — asteapta finalizarea"}
# Get order from SQLite
detail = await sqlite_service.get_order_detail(order_number)
if not detail:
return {"success": False, "message": "Comanda nu a fost gasita"}
order_data = detail["order"]
status = order_data.get("status", "")
if status not in (OrderStatus.ERROR.value, OrderStatus.SKIPPED.value,
OrderStatus.DELETED_IN_ROA.value, OrderStatus.MALFORMED.value):
return {"success": False,
"message": f"Retry permis doar pentru ERROR/SKIPPED/DELETED_IN_ROA/MALFORMED (status actual: {status})"}
order_date_str = order_data.get("order_date", "")
customer_name = order_data.get("customer_name", "")
return await _download_and_reimport(order_number, order_date_str, customer_name, app_settings)
async def resync_single_order(order_number: str, app_settings: dict) -> dict:
"""Soft-delete an imported order from Oracle then re-import it from GoMag.
Steps:
1. Check sync lock
2. Load order from SQLite
3. Validate status is IMPORTED/ALREADY_IMPORTED with id_comanda
4. Invoice safety gate (check Oracle for invoices)
5. Soft-delete from Oracle
6. Mark DELETED_IN_ROA in SQLite
7. Re-import via _download_and_reimport
Returns: {"success": bool, "message": str, "status": str|None}
"""
from . import sqlite_service, sync_service, import_service, invoice_service
from .. import database
# Check sync lock
if sync_service._sync_lock.locked():
return {"success": False, "message": "Sync in curs — asteapta finalizarea"}
# Get order from SQLite
detail = await sqlite_service.get_order_detail(order_number)
if not detail:
return {"success": False, "message": "Comanda nu a fost gasita"}
order_data = detail["order"]
status = order_data.get("status", "")
id_comanda = order_data.get("id_comanda")
if status not in (OrderStatus.IMPORTED.value, OrderStatus.ALREADY_IMPORTED.value) or not id_comanda:
return {"success": False, "message": f"Resync permis doar pentru IMPORTED/ALREADY_IMPORTED cu id_comanda (status actual: {status})"}
# Invoice safety gate
if database.pool is None:
return {"success": False, "message": "Oracle indisponibil"}
if order_data.get("factura_numar"):
return {"success": False, "message": "Comanda este facturata"}
try:
invoice_result = await asyncio.to_thread(
invoice_service.check_invoices_for_orders, [id_comanda]
)
except Exception as e:
logger.error(f"Invoice check failed for {order_number}: {e}")
return {"success": False, "message": "Nu se poate verifica factura — Oracle indisponibil"}
if invoice_result.get(id_comanda):
return {"success": False, "message": "Comanda este facturata"}
# Soft-delete from Oracle
try:
delete_result = await asyncio.to_thread(
import_service.soft_delete_order_in_roa, id_comanda
)
if not delete_result.get("success"):
return {"success": False, "message": f"Eroare stergere din Oracle: {delete_result.get('error', 'Unknown')}"}
except Exception as e:
logger.error(f"Soft-delete failed for {order_number} (id_comanda={id_comanda}): {e}")
return {"success": False, "message": f"Eroare stergere din Oracle: {e}"}
# Mark deleted in SQLite
await sqlite_service.mark_order_deleted_in_roa(order_number)
order_date_str = order_data.get("order_date", "")
customer_name = order_data.get("customer_name", "")
# Re-import
reimport_result = await _download_and_reimport(order_number, order_date_str, customer_name, app_settings)
if not reimport_result.get("success"):
logger.warning(f"Resync: order {order_number} deleted from Oracle but reimport failed")
return {
"success": False,
"message": "Comanda stearsa din Oracle dar reimportul a esuat — foloseste Reimporta pentru a reincerca",
}
return reimport_result
async def delete_single_order(order_number: str) -> dict:
"""Soft-delete an imported order from Oracle without re-importing.
Same invoice safety gate as resync_single_order.
Returns: {"success": bool, "message": str}
"""
from . import sqlite_service, sync_service, import_service, invoice_service
from .. import database
# Check sync lock
if sync_service._sync_lock.locked():
return {"success": False, "message": "Sync in curs — asteapta finalizarea"}
# Get order from SQLite
detail = await sqlite_service.get_order_detail(order_number)
if not detail:
return {"success": False, "message": "Comanda nu a fost gasita"}
order_data = detail["order"]
status = order_data.get("status", "")
id_comanda = order_data.get("id_comanda")
if status not in (OrderStatus.IMPORTED.value, OrderStatus.ALREADY_IMPORTED.value) or not id_comanda:
return {"success": False, "message": f"Stergere permisa doar pentru IMPORTED/ALREADY_IMPORTED cu id_comanda (status actual: {status})"}
# Invoice safety gate
if database.pool is None:
return {"success": False, "message": "Oracle indisponibil"}
if order_data.get("factura_numar"):
return {"success": False, "message": "Comanda este facturata"}
try:
invoice_result = await asyncio.to_thread(
invoice_service.check_invoices_for_orders, [id_comanda]
)
except Exception as e:
logger.error(f"Invoice check failed for {order_number}: {e}")
return {"success": False, "message": "Nu se poate verifica factura — Oracle indisponibil"}
if invoice_result.get(id_comanda):
return {"success": False, "message": "Comanda este facturata"}
# Soft-delete from Oracle
try:
delete_result = await asyncio.to_thread(
import_service.soft_delete_order_in_roa, id_comanda
)
if not delete_result.get("success"):
return {"success": False, "message": f"Eroare stergere din Oracle: {delete_result.get('error', 'Unknown')}"}
except Exception as e:
logger.error(f"Soft-delete failed for {order_number} (id_comanda={id_comanda}): {e}")
return {"success": False, "message": f"Eroare stergere din Oracle: {e}"}
# Mark deleted in SQLite
await sqlite_service.mark_order_deleted_in_roa(order_number)
logger.info(f"Order {order_number} (id_comanda={id_comanda}) deleted from ROA")
return {"success": True, "message": "Comanda stearsa din ROA"}