fix(retry): pass ANAF kwargs on retry/resync so VAT-payer partner is matched
retry_service called import_single_order without cod_fiscal_override / anaf_strict / denumire_override, so re-imports searched the partner by the raw GoMag CUI in dual mode and could match the non-payer twin (bare CUI) of a payer (RO CUI). Add anaf_import_kwargs mirroring the sync flow, plus test and agent docs for prod partner diagnostics. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L3v311J3SfjroTebzR96ng
This commit is contained in:
@@ -9,6 +9,40 @@ from ..constants import OrderStatus
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def anaf_import_kwargs(order) -> dict:
|
||||
"""ANAF-derived kwargs for import_single_order (mirrors the sync flow).
|
||||
|
||||
Without these, a re-import searches the partner by the raw GoMag CUI in dual
|
||||
mode and can match the non-VAT-payer twin (bare CUI) of a VAT payer (RO CUI).
|
||||
Empty dict when not an RO company or ANAF has no verdict (sync tolerates that too).
|
||||
"""
|
||||
from . import sqlite_service, import_service, anaf_service
|
||||
|
||||
b = order.billing
|
||||
if not (b.is_company and b.company_code and (b.country or "").strip().lower() == "romania"):
|
||||
return {}
|
||||
bare, _ = anaf_service.sanitize_cui(import_service.clean_web_text(b.company_code) or "")
|
||||
if not anaf_service.validate_cui(bare):
|
||||
return {}
|
||||
data = await sqlite_service.get_anaf_cache(bare)
|
||||
if not data:
|
||||
try:
|
||||
fresh = await anaf_service.check_vat_status_batch([bare])
|
||||
if fresh:
|
||||
await sqlite_service.bulk_populate_anaf_cache(fresh)
|
||||
data = fresh.get(bare)
|
||||
except Exception as e:
|
||||
logger.warning(f"ANAF check failed for {bare}: {e}")
|
||||
if not data or data.get("scpTVA") is None:
|
||||
return {}
|
||||
name = (data.get("denumire_anaf") or "").strip().upper()
|
||||
return {
|
||||
"cod_fiscal_override": anaf_service.determine_correct_cod_fiscal(bare, data["scpTVA"]),
|
||||
"anaf_strict": 1,
|
||||
"denumire_override": name or None,
|
||||
}
|
||||
|
||||
|
||||
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.
|
||||
|
||||
@@ -97,7 +131,8 @@ async def _download_and_reimport(order_number: str, order_date_str: str, custome
|
||||
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
|
||||
app_settings=app_settings, id_gestiuni=id_gestiuni,
|
||||
**await anaf_import_kwargs(target_order),
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Retry import failed for {order_number}: {e}")
|
||||
|
||||
47
api/tests/test_retry_anaf_kwargs.py
Normal file
47
api/tests/test_retry_anaf_kwargs.py
Normal file
@@ -0,0 +1,47 @@
|
||||
"""Retry/resync must pass ANAF-derived kwargs so the VAT-payer partner (RO CUI) is found, not its bare-CUI twin."""
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
_tmpdir = tempfile.mkdtemp()
|
||||
os.environ.setdefault("FORCE_THIN_MODE", "true")
|
||||
os.environ.setdefault("SQLITE_DB_PATH", os.path.join(_tmpdir, "test_retry_anaf.db"))
|
||||
os.environ.setdefault("ORACLE_DSN", "dummy")
|
||||
os.environ.setdefault("ORACLE_USER", "dummy")
|
||||
os.environ.setdefault("ORACLE_PASSWORD", "dummy")
|
||||
os.environ.setdefault("JSON_OUTPUT_DIR", _tmpdir)
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from app.services import retry_service
|
||||
from app.services.order_reader import OrderBilling, OrderData
|
||||
|
||||
|
||||
def _order(country="Romania"):
|
||||
return OrderData(id="1", number="517596384", date="2026-09-23 08:14:51", status="", status_id="",
|
||||
billing=OrderBilling(is_company=True, company_code="40874913", country=country))
|
||||
|
||||
|
||||
async def _kwargs(cache, order):
|
||||
with patch("app.services.sqlite_service.get_anaf_cache", AsyncMock(return_value=cache)), \
|
||||
patch("app.services.anaf_service.check_vat_status_batch", AsyncMock(return_value={})):
|
||||
return await retry_service.anaf_import_kwargs(order)
|
||||
|
||||
|
||||
async def test_vat_payer_gets_ro_cui_and_strict():
|
||||
kw = await _kwargs({"scpTVA": True, "denumire_anaf": "ctc ben prod s.r.l."}, _order())
|
||||
assert kw == {"cod_fiscal_override": "RO40874913", "anaf_strict": 1, "denumire_override": "CTC BEN PROD S.R.L."}
|
||||
|
||||
|
||||
async def test_non_payer_gets_bare_cui_and_strict():
|
||||
kw = await _kwargs({"scpTVA": False, "denumire_anaf": "X"}, _order())
|
||||
assert kw["cod_fiscal_override"] == "40874913" and kw["anaf_strict"] == 1
|
||||
|
||||
|
||||
async def test_no_anaf_verdict_or_foreign_company_gives_nothing():
|
||||
assert await _kwargs(None, _order()) == {}
|
||||
assert await _kwargs({"scpTVA": True, "denumire_anaf": "X"}, _order(country="Germany")) == {}
|
||||
Reference in New Issue
Block a user