forked from hesabix/arc
«معتمد آسا» becomes a third, optional sending method beside «ارسال مستقیم» and «همراه فنآوا». It follows the Fanava provider pattern and reuses tax_provider_credentials, business_tax_provider_accounts and tax_settings.submission_provider: no new table and no migration. Direct and Fanava behaviour is unchanged; the default stays moadian_direct. Connection (informed consent): - The tax settings page shows what is shared with Motamed ASA and why, with links to its terms and to https://asatsp.ir/privacy#partner-software, and asks for explicit consent; consent user and time are stored as for Fanava. - The owner signs up on Motamed ASA's own page (tax-system one-time code); Hesabix collects no identity documents. The business API key is handed to Hesabix once, after the owner agrees there; a business that already has an ASA API v2 key can enter its client id/secret instead. - The business private key and memory id are not needed: the trusted company signs and sends. Sending (ASA TSP API v2, https://api-v2.asatsp.ir): - original: POST /api/invoice/send with a stable internalId per document; a rejected or unsent invoice is edited in place (editInvoice); - correction: editInvoice with confirmCorrection; - cancellation: cancelInvoice; marked cancelled only once accepted; - sales return: ins=4 whose Body is the rows remaining after the return (RC_IITP.IS_V7.9 table 1), read from the chain's accepted invoice; - timeouts are reconciled by internalId and never re-sent blindly; - ASA issues the tax id; Hesabix stores it from the answer. Inquiry and the tax workspace: - inquire_tax_status, the auto-inquiry loop and the workspace health check read Motamed ASA invoices from ASA (inquiryInternalIds). - The کارپوشه status (buyer reaction) and the Article 6 status (عدول / عدم عدول) of the document's own invoice are kept and shown as two new workspace columns (tax_workspace_status, tax_article6_status). A buyer rejection is shown there and no longer marks a registered invoice failed. - «پرداختها و ثبت در کارپوشه» on a sent Motamed ASA invoice opens its payment table: every row with its registration status, and new rows (method, date/time, amount with VAT, trace and terminal numbers) registered through ASA's registerPayment; locked rows stay read-only and a lost answer reads the rows back instead of sending them again. Admin: «اتصال معتمد آسا» under system settings › external services holds the partner client id/secret Motamed ASA issues for Hesabix. Tests: tests/test_motamed_asa_{client,invoice_payload,provider_service}.py Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
168 lines
6.2 KiB
Python
Executable file
168 lines
6.2 KiB
Python
Executable file
"""
|
|
Health Check برای سامانه مالیاتی
|
|
|
|
توجه: Redis فقط برای cache/صف اختیاری است و نباید وضعیت «اتصال مودیان»
|
|
را قطع نشان دهد. احراز هویت بدون Redis با لاگین مستقیم انجام میشود.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
from typing import Any, Dict
|
|
|
|
from datetime import datetime
|
|
|
|
from app.core.settings import get_settings
|
|
from app.integrations.moadian.client import MoadianClient
|
|
from adapters.db.models.tax_setting import TaxSetting
|
|
from sqlalchemy.orm import Session
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
def check_tax_system_health(
|
|
db: Session,
|
|
business_id: int,
|
|
) -> Dict[str, Any]:
|
|
"""
|
|
بررسی سلامت سامانه مالیاتی (تنظیمات + اتصال واقعی به مودیان).
|
|
|
|
Redis در نتیجه گزارش میشود اما روی ``healthy`` اثر نمیگذارد.
|
|
"""
|
|
result: Dict[str, Any] = {
|
|
"healthy": False,
|
|
"timestamp": datetime.utcnow().isoformat(),
|
|
"checks": {},
|
|
}
|
|
|
|
connection_ok = False
|
|
settings_ok = False
|
|
|
|
# 1. بررسی تنظیمات
|
|
tax_setting = (
|
|
db.query(TaxSetting)
|
|
.filter(TaxSetting.business_id == business_id)
|
|
.first()
|
|
)
|
|
|
|
from app.services.motamed_asa_provider_service import MOTAMED_ASA_PROVIDER, motamed_asa_health
|
|
|
|
if tax_setting is not None and tax_setting.submission_provider == MOTAMED_ASA_PROVIDER:
|
|
# «معتمد آسا» signs and sends with its own memory; its connection is checked instead of a tax-system login.
|
|
result["checks"] = motamed_asa_health(db, business_id)
|
|
result["healthy"] = all(check.get("status") == "ok" for check in result["checks"].values())
|
|
return result
|
|
|
|
if not tax_setting:
|
|
result["checks"]["settings"] = {
|
|
"status": "error",
|
|
"message": "تنظیمات مالیاتی یافت نشد",
|
|
}
|
|
elif not (tax_setting.tax_memory_id and tax_setting.private_key and tax_setting.economic_code):
|
|
result["checks"]["settings"] = {
|
|
"status": "error",
|
|
"message": "تنظیمات مالیاتی ناقص است",
|
|
}
|
|
else:
|
|
settings_ok = True
|
|
result["checks"]["settings"] = {
|
|
"status": "ok",
|
|
"message": "تنظیمات مالیاتی کامل است",
|
|
}
|
|
|
|
# 2. بررسی اتصال به سامانه (مستقل از Redis)
|
|
if tax_setting and settings_ok:
|
|
client = None
|
|
try:
|
|
settings = get_settings()
|
|
client = MoadianClient(settings=settings, tax_setting=tax_setting)
|
|
api_version = getattr(client, "api_version", "v1")
|
|
|
|
# لاگین واقعی؛ توکن در حافظهٔ کلاینت نگه داشته میشود (بدون نیاز به Redis)
|
|
token = client.ensure_authenticated()
|
|
|
|
if token:
|
|
connection_ok = True
|
|
result["checks"]["connection"] = {
|
|
"status": "ok",
|
|
"message": "اتصال به سامانه برقرار است",
|
|
"api_version": api_version,
|
|
}
|
|
result["checks"]["authentication"] = {
|
|
"status": "ok",
|
|
"message": "احراز هویت موفق است",
|
|
"api_version": api_version,
|
|
}
|
|
else:
|
|
result["checks"]["connection"] = {
|
|
"status": "error",
|
|
"message": "توکن احراز هویت دریافت نشد",
|
|
}
|
|
result["checks"]["authentication"] = {
|
|
"status": "error",
|
|
"message": "احراز هویت ناموفق بود",
|
|
}
|
|
except Exception as e:
|
|
logger.warning(
|
|
"tax health connection check failed business_id=%s: %s",
|
|
business_id,
|
|
e,
|
|
exc_info=True,
|
|
)
|
|
result["checks"]["connection"] = {
|
|
"status": "error",
|
|
"message": f"خطا در اتصال: {str(e)}",
|
|
}
|
|
result["checks"]["authentication"] = {
|
|
"status": "error",
|
|
"message": "احراز هویت انجام نشد",
|
|
}
|
|
finally:
|
|
if client is not None:
|
|
try:
|
|
client.close()
|
|
except Exception:
|
|
pass
|
|
else:
|
|
result["checks"]["connection"] = {
|
|
"status": "skipped",
|
|
"message": "بررسی اتصال به دلیل نبود تنظیمات انجام نشد",
|
|
}
|
|
|
|
# 3. Redis — اختیاری؛ هرگز healthy را false نمیکند
|
|
try:
|
|
from app.core.cache import get_cache
|
|
|
|
cache = get_cache()
|
|
if cache.enabled:
|
|
try:
|
|
cache.client.ping()
|
|
result["checks"]["redis"] = {
|
|
"status": "ok",
|
|
"message": "Redis در دسترس است (اختیاری برای کش توکن)",
|
|
"required_for_moadian": False,
|
|
}
|
|
except Exception as e:
|
|
result["checks"]["redis"] = {
|
|
"status": "info",
|
|
"message": (
|
|
f"Redis در دسترس نیست ({e}). "
|
|
"اتصال مودیان بدون Redis هم کار میکند."
|
|
),
|
|
"required_for_moadian": False,
|
|
}
|
|
else:
|
|
result["checks"]["redis"] = {
|
|
"status": "info",
|
|
"message": "Redis غیرفعال است؛ اتصال مودیان بدون Redis برقرار میشود.",
|
|
"required_for_moadian": False,
|
|
}
|
|
except Exception as e:
|
|
result["checks"]["redis"] = {
|
|
"status": "info",
|
|
"message": f"بررسی Redis انجام نشد ({e})؛ برای مودیان الزامی نیست.",
|
|
"required_for_moadian": False,
|
|
}
|
|
|
|
result["healthy"] = bool(settings_ok and connection_ok)
|
|
return result
|