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>
252 lines
9 KiB
Python
Executable file
252 lines
9 KiB
Python
Executable file
from __future__ import annotations
|
|
|
|
from typing import Any, Dict
|
|
from datetime import datetime
|
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
from adapters.db.models.tax_setting import TaxSetting
|
|
from app.integrations.moadian.client import uses_moadian_v2
|
|
from app.services.encryption_service import encrypt_private_key, decrypt_private_key
|
|
|
|
|
|
def get_tax_setting(db: Session, business_id: int) -> TaxSetting | None:
|
|
"""
|
|
دریافت تنظیمات مالیاتی کسبوکار
|
|
کلید خصوصی به صورت خودکار رمزگشایی میشود
|
|
"""
|
|
setting = (
|
|
db.query(TaxSetting)
|
|
.filter(TaxSetting.business_id == int(business_id))
|
|
.first()
|
|
)
|
|
|
|
if setting and setting.private_key:
|
|
# رمزگشایی کلید خصوصی
|
|
try:
|
|
setting.private_key = decrypt_private_key(setting.private_key)
|
|
except Exception:
|
|
# اگر رمزگشایی ناموفق بود، احتمالا کلید رمز نشده است (دادههای قدیمی)
|
|
pass
|
|
|
|
return setting
|
|
|
|
|
|
def upsert_tax_setting(
|
|
db: Session,
|
|
*,
|
|
business_id: int,
|
|
user_id: int,
|
|
payload: Dict[str, Any],
|
|
) -> TaxSetting:
|
|
"""
|
|
ایجاد یا بهروزرسانی تنظیمات مالیاتی
|
|
کلید خصوصی به صورت خودکار رمزنگاری میشود
|
|
"""
|
|
setting = (
|
|
db.query(TaxSetting)
|
|
.filter(TaxSetting.business_id == int(business_id))
|
|
.first()
|
|
)
|
|
|
|
now = datetime.utcnow()
|
|
|
|
if setting is None:
|
|
setting = TaxSetting(
|
|
business_id=int(business_id),
|
|
created_by_user_id=int(user_id),
|
|
created_at=now,
|
|
)
|
|
db.add(setting)
|
|
|
|
# بهروزرسانی فیلدها
|
|
setting.tax_memory_id = payload.get("tax_memory_id")
|
|
setting.economic_code = payload.get("economic_code")
|
|
|
|
# رمزنگاری کلید خصوصی قبل از ذخیره
|
|
private_key = payload.get("private_key")
|
|
if private_key:
|
|
try:
|
|
setting.private_key = encrypt_private_key(private_key)
|
|
except Exception:
|
|
# اگر رمزنگاری ناموفق بود، به صورت plain text ذخیره میشود (fallback)
|
|
setting.private_key = private_key
|
|
|
|
pub = payload.get("public_key")
|
|
if pub is not None and str(pub).strip():
|
|
setting.public_key = str(pub).strip()
|
|
cert = payload.get("certificate")
|
|
if cert is not None and str(cert).strip():
|
|
setting.certificate = str(cert).strip()
|
|
csr = payload.get("certificate_request")
|
|
if csr is not None and str(csr).strip():
|
|
setting.certificate_request = str(csr).strip()
|
|
setting.sandbox_mode = bool(payload.get("sandbox_mode", False))
|
|
setting.updated_at = now
|
|
|
|
db.flush()
|
|
db.refresh(setting)
|
|
|
|
# رمزگشایی برای برگرداندن به کاربر
|
|
if setting.private_key:
|
|
try:
|
|
setting.private_key = decrypt_private_key(setting.private_key)
|
|
except Exception:
|
|
pass
|
|
|
|
return setting
|
|
|
|
|
|
def validate_tax_setting_complete(setting: TaxSetting | None) -> list[str]:
|
|
"""فیلدهای الزامی برای اتصال (v1: کلید خصوصی؛ v2: علاوه بر آن گواهی PEM)."""
|
|
if setting is None:
|
|
return ["tax_memory_id", "economic_code", "private_key"]
|
|
missing: list[str] = []
|
|
if not (setting.tax_memory_id or "").strip():
|
|
missing.append("tax_memory_id")
|
|
if not (setting.economic_code or "").strip():
|
|
missing.append("economic_code")
|
|
if not (setting.private_key or "").strip():
|
|
missing.append("private_key")
|
|
if uses_moadian_v2(setting) and not (setting.certificate or "").strip():
|
|
missing.append("certificate")
|
|
return missing
|
|
|
|
|
|
def merge_tax_setting_for_test(
|
|
stored: TaxSetting | None,
|
|
payload: Any | None,
|
|
*,
|
|
business_id: int,
|
|
) -> TaxSetting:
|
|
"""
|
|
ادغام تنظیمات DB با مقادیر فرم UI برای تست اتصال بدون ذخیره اجباری.
|
|
یک نمونه جدا (detached) برمیگرداند تا رکورد DB تغییر نکند.
|
|
"""
|
|
setting = TaxSetting(business_id=int(business_id))
|
|
if stored is not None:
|
|
setting.tax_memory_id = stored.tax_memory_id
|
|
setting.economic_code = stored.economic_code
|
|
setting.private_key = stored.private_key
|
|
setting.public_key = stored.public_key
|
|
setting.certificate = stored.certificate
|
|
setting.certificate_request = stored.certificate_request
|
|
setting.sandbox_mode = bool(stored.sandbox_mode)
|
|
|
|
if payload is None:
|
|
return setting
|
|
|
|
def _pick(new_val: Any, old_val: Any) -> Any:
|
|
if new_val is None:
|
|
return old_val
|
|
if isinstance(new_val, str) and not new_val.strip():
|
|
return old_val
|
|
return new_val
|
|
|
|
setting.tax_memory_id = _pick(getattr(payload, "tax_memory_id", None), setting.tax_memory_id)
|
|
setting.economic_code = _pick(getattr(payload, "economic_code", None), setting.economic_code)
|
|
setting.private_key = _pick(getattr(payload, "private_key", None), setting.private_key)
|
|
setting.public_key = _pick(getattr(payload, "public_key", None), setting.public_key)
|
|
setting.certificate = _pick(getattr(payload, "certificate", None), setting.certificate)
|
|
setting.certificate_request = _pick(
|
|
getattr(payload, "certificate_request", None),
|
|
setting.certificate_request,
|
|
)
|
|
sandbox = getattr(payload, "sandbox_mode", None)
|
|
if sandbox is not None:
|
|
setting.sandbox_mode = bool(sandbox)
|
|
return setting
|
|
|
|
|
|
def serialize_tax_setting(
|
|
setting: TaxSetting | None,
|
|
business_id: int,
|
|
*,
|
|
db: Session | None = None,
|
|
) -> Dict[str, Any]:
|
|
"""
|
|
سریالایز کردن تنظیمات مالیاتی برای API response
|
|
کلید خصوصی به صورت خودکار رمزگشایی میشود
|
|
"""
|
|
suggested_person_type = _resolve_suggested_person_type(db, business_id)
|
|
|
|
if setting is None:
|
|
from app.services.tax_provider_service import get_business_provider_state
|
|
provider_state = get_business_provider_state(db, int(business_id)) if db is not None else {
|
|
"submission_provider": "moadian_direct", "fanava_available": False, "fanava_account": None,
|
|
"motamed_asa_available": False, "motamed_asa_account": None,
|
|
}
|
|
return {
|
|
"business_id": int(business_id),
|
|
"tax_memory_id": None,
|
|
"economic_code": None,
|
|
"private_key": None,
|
|
"public_key": None,
|
|
"certificate": None,
|
|
"certificate_request": None,
|
|
"sandbox_mode": False,
|
|
"has_private_key": False,
|
|
"updated_at": None,
|
|
"configuration_warnings": [],
|
|
"identity_check": None,
|
|
"suggested_person_type": suggested_person_type,
|
|
**provider_state,
|
|
}
|
|
|
|
# رمزگشایی کلید خصوصی برای نمایش
|
|
private_key = setting.private_key
|
|
if private_key:
|
|
try:
|
|
private_key = decrypt_private_key(private_key)
|
|
except Exception:
|
|
pass
|
|
|
|
from app.services.tax_setting_health_service import (
|
|
build_configuration_warnings,
|
|
build_identity_check,
|
|
)
|
|
|
|
warnings = build_configuration_warnings(setting)
|
|
identity_check = None
|
|
if db is not None:
|
|
identity_check = build_identity_check(db, int(business_id))
|
|
|
|
from app.services.tax_provider_service import get_business_provider_state
|
|
provider_state = get_business_provider_state(db, int(business_id)) if db is not None else {
|
|
"submission_provider": getattr(setting, "submission_provider", "moadian_direct"),
|
|
"fanava_available": False,
|
|
"fanava_account": None,
|
|
"motamed_asa_available": False,
|
|
"motamed_asa_account": None,
|
|
}
|
|
|
|
return {
|
|
"business_id": int(setting.business_id),
|
|
"tax_memory_id": setting.tax_memory_id,
|
|
"economic_code": setting.economic_code,
|
|
"private_key": private_key,
|
|
"public_key": setting.public_key,
|
|
"certificate": setting.certificate,
|
|
"certificate_request": setting.certificate_request,
|
|
"sandbox_mode": bool(setting.sandbox_mode),
|
|
"has_private_key": bool(setting.private_key),
|
|
"updated_at": setting.updated_at.isoformat() if setting.updated_at else None,
|
|
"configuration_warnings": warnings,
|
|
"identity_check": identity_check,
|
|
"suggested_person_type": suggested_person_type,
|
|
**provider_state,
|
|
}
|
|
|
|
|
|
def _resolve_suggested_person_type(db: Session | None, business_id: int) -> str:
|
|
if db is None:
|
|
return "legal"
|
|
from adapters.db.models.business import Business
|
|
from app.services.tax_key_material_service import suggested_moadian_person_type
|
|
|
|
business = db.query(Business).filter(Business.id == int(business_id)).first()
|
|
if not business:
|
|
return "legal"
|
|
return suggested_moadian_person_type(business.business_type)
|
|
|
|
|