diff --git a/hesabixAPI/adapters/api/v1/admin/tax_providers.py b/hesabixAPI/adapters/api/v1/admin/tax_providers.py index c3b3a6b5..58172a90 100644 --- a/hesabixAPI/adapters/api/v1/admin/tax_providers.py +++ b/hesabixAPI/adapters/api/v1/admin/tax_providers.py @@ -14,6 +14,12 @@ from app.services.tax_provider_service import ( serialize_provider_credential, test_provider_connection, ) +from app.services.motamed_asa_provider_service import ( + get_motamed_asa_credential, + save_motamed_asa_credential, + serialize_motamed_asa_credential, + test_motamed_asa_connection, +) router = APIRouter(prefix="/admin/tax-providers", tags=["مدیریت ارائه‌دهندگان مالیاتی"]) @@ -56,3 +62,38 @@ def test_fanava_settings( _require_admin(ctx) data = test_provider_connection(db) return success_response(data, request, "اتصال خواندنی فن‌آوا موفق بود.") + + +@router.get("/motamed-asa") +def get_motamed_asa_settings( + request: Request, + db: Session = Depends(get_db), + ctx: AuthContext = Depends(get_current_user), +) -> Dict[str, Any]: + _require_admin(ctx) + return success_response(serialize_motamed_asa_credential(get_motamed_asa_credential(db)), request) + + +@router.put("/motamed-asa") +def put_motamed_asa_settings( + request: Request, + payload: Dict[str, Any] = Body(...), + db: Session = Depends(get_db), + ctx: AuthContext = Depends(get_current_user), +) -> Dict[str, Any]: + _require_admin(ctx) + credential = save_motamed_asa_credential(db, payload) + db.commit() + db.refresh(credential) + return success_response(serialize_motamed_asa_credential(credential), request, "تنظیم معتمد آسا ذخیره شد.") + + +@router.post("/motamed-asa/test-connection") +def test_motamed_asa_settings( + request: Request, + db: Session = Depends(get_db), + ctx: AuthContext = Depends(get_current_user), +) -> Dict[str, Any]: + _require_admin(ctx) + data = test_motamed_asa_connection(db) + return success_response(data, request, "اتصال حسابیکس به معتمد آسا برقرار است.") diff --git a/hesabixAPI/adapters/api/v1/tax_settings.py b/hesabixAPI/adapters/api/v1/tax_settings.py index e0580aef..c3128f5d 100755 --- a/hesabixAPI/adapters/api/v1/tax_settings.py +++ b/hesabixAPI/adapters/api/v1/tax_settings.py @@ -4,6 +4,7 @@ from fastapi import APIRouter, Depends, Request, Body from sqlalchemy.orm import Session from adapters.db.session import get_db +from adapters.db.models.document import Document from adapters.api.v1.schema_models.tax_settings import ( TaxSettingsSaveRequest, TaxSettingsTestConnectionRequest, @@ -36,6 +37,16 @@ from app.services.tax_provider_service import ( fanava_business_call, sync_business_fanava_account, ) +from app.services.motamed_asa_provider_service import ( + MOTAMED_ASA_PROVIDER, + renew_motamed_asa_link, + save_motamed_asa_business_credentials, + sync_motamed_asa_account, +) +from app.services.motamed_asa_tax_submission_service import ( + motamed_asa_invoice_payments, + register_motamed_asa_payments, +) from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.primitives import serialization @@ -84,23 +95,125 @@ def select_tax_provider_endpoint( ensure_moadian_plugin_active(db, business_id) provider_code = str(payload.get("provider_code") or "").strip().lower() consented_by_user_id = ctx.get_user_id() - if provider_code == "fanava" and not consented_by_user_id: + if provider_code in ("fanava", MOTAMED_ASA_PROVIDER) and not consented_by_user_id: raise ApiError("UNAUTHORIZED", "برای ثبت رضایت باید کاربر وارد شده باشد.", http_status=401) - select_business_provider( + enrollment = payload.get("enrollment") if isinstance(payload.get("enrollment"), dict) else {} + if provider_code == MOTAMED_ASA_PROVIDER and payload.get("economic_code"): + enrollment = {**enrollment, "economic_code": str(payload.get("economic_code"))} + result = select_business_provider( db, business_id=business_id, provider_code=provider_code, consent=bool(payload.get("consent")), consented_by_user_id=consented_by_user_id, - enrollment=payload.get("enrollment") if isinstance(payload.get("enrollment"), dict) else {}, + enrollment=enrollment, ) # Keep the response shape identical to GET /tax-settings/business/{id}; # the client model also owns the existing key material and memory settings. setting = get_tax_setting(db, business_id) data = serialize_tax_setting(setting, business_id=business_id, db=db) + if isinstance(result, dict) and result.get("motamed_asa_onboarding"): + # The sign-up link is returned once and never stored. + data["motamed_asa_onboarding"] = result["motamed_asa_onboarding"] return success_response(data, request, "TAX_PROVIDER_UPDATED") +@router.post("/business/{business_id}/motamed-asa/sync") +@require_business_access("business_id") +def sync_motamed_asa_account_endpoint( + request: Request, + business_id: int, + ctx: AuthContext = Depends(get_current_user), + db: Session = Depends(get_db), + _: None = Depends(require_business_permission_dep("moadian", "manage_settings")), +): + ensure_moadian_plugin_active(db, business_id) + return success_response(sync_motamed_asa_account(db, business_id), request, "MOTAMED_ASA_ACCOUNT_SYNCED") + + +@router.post("/business/{business_id}/motamed-asa/link") +@require_business_access("business_id") +def renew_motamed_asa_link_endpoint( + request: Request, + business_id: int, + ctx: AuthContext = Depends(get_current_user), + db: Session = Depends(get_db), + _: None = Depends(require_business_permission_dep("moadian", "manage_settings")), +): + ensure_moadian_plugin_active(db, business_id) + return success_response(renew_motamed_asa_link(db, business_id), request, "MOTAMED_ASA_LINK_ISSUED") + + +@router.post("/business/{business_id}/motamed-asa/credentials") +@require_business_access("business_id") +def save_motamed_asa_credentials_endpoint( + request: Request, + business_id: int, + payload: Dict[str, Any] = Body(...), + ctx: AuthContext = Depends(get_current_user), + db: Session = Depends(get_db), + _: None = Depends(require_business_permission_dep("moadian", "manage_settings")), +): + ensure_moadian_plugin_active(db, business_id) + consented_by_user_id = ctx.get_user_id() + if not consented_by_user_id: + raise ApiError("UNAUTHORIZED", "برای ثبت رضایت باید کاربر وارد شده باشد.", http_status=401) + state = save_motamed_asa_business_credentials( + db, + business_id=business_id, + client_id=str(payload.get("client_id") or ""), + client_secret=str(payload.get("client_secret") or ""), + consent=payload.get("consent") is True, + consented_by_user_id=consented_by_user_id, + economic_code=str(payload.get("economic_code") or "") or None, + ) + return success_response(state, request, "MOTAMED_ASA_ACCOUNT_CONNECTED") + + +def _motamed_asa_document(db: Session, business_id: int, invoice_id: int) -> Document: + document = ( + db.query(Document) + .filter(Document.id == int(invoice_id), Document.business_id == int(business_id)) + .first() + ) + if document is None: + raise ApiError("INVOICE_NOT_FOUND", "فاکتور پیدا نشد.", http_status=404) + return document + + +@router.get("/business/{business_id}/motamed-asa/invoices/{invoice_id}/payments") +@require_business_access("business_id") +def get_motamed_asa_payments_endpoint( + request: Request, + business_id: int, + invoice_id: int, + ctx: AuthContext = Depends(get_current_user), + db: Session = Depends(get_db), + _: None = Depends(require_business_permission_dep("moadian", "operate")), +): + ensure_moadian_plugin_active(db, business_id) + document = _motamed_asa_document(db, business_id, invoice_id) + return success_response(motamed_asa_invoice_payments(db, business_id, document), request, "MOTAMED_ASA_PAYMENTS_FETCHED") + + +@router.post("/business/{business_id}/motamed-asa/invoices/{invoice_id}/payments") +@require_business_access("business_id") +def register_motamed_asa_payments_endpoint( + request: Request, + business_id: int, + invoice_id: int, + payload: Dict[str, Any] = Body(...), + ctx: AuthContext = Depends(get_current_user), + db: Session = Depends(get_db), + _: None = Depends(require_business_permission_dep("moadian", "operate")), +): + ensure_moadian_plugin_active(db, business_id) + document = _motamed_asa_document(db, business_id, invoice_id) + result = register_motamed_asa_payments(db, business_id, document, payload.get("payments")) + db.commit() + return success_response(result, request, "MOTAMED_ASA_PAYMENTS_REGISTERED") + + @router.post("/business/{business_id}/fanava/sync") @require_business_access("business_id") def sync_fanava_account_endpoint( @@ -268,6 +381,12 @@ def save_tax_settings_endpoint( "فن‌آوا محیط آزمایشی ندارد؛ ابتدا روش ارسال مستقیم را انتخاب کنید.", http_status=400, ) + if current_setting and current_setting.submission_provider == MOTAMED_ASA_PROVIDER and payload.sandbox_mode: + raise ApiError( + "MOTAMED_ASA_SANDBOX_UNAVAILABLE", + "ارسال از طریق معتمد آسا فقط در محیط اصلی سامانهٔ مؤدیان انجام می‌شود؛ ابتدا روش ارسال مستقیم را انتخاب کنید.", + http_status=400, + ) setting = upsert_tax_setting( db, diff --git a/hesabixAPI/app/integrations/motamed_asa/__init__.py b/hesabixAPI/app/integrations/motamed_asa/__init__.py new file mode 100644 index 00000000..fc00d287 --- /dev/null +++ b/hesabixAPI/app/integrations/motamed_asa/__init__.py @@ -0,0 +1 @@ +"""«معتمد آسا» trusted tax provider integration (ASA TSP API v2).""" diff --git a/hesabixAPI/app/integrations/motamed_asa/client.py b/hesabixAPI/app/integrations/motamed_asa/client.py new file mode 100644 index 00000000..de2bc223 --- /dev/null +++ b/hesabixAPI/app/integrations/motamed_asa/client.py @@ -0,0 +1,253 @@ +from __future__ import annotations + +from typing import Any +from urllib.parse import quote + +import httpx + +DEFAULT_BASE_URL = "https://api-v2.asatsp.ir" + +# Invoice routes answer HTTP 200 with a numeric «result»; -1 is an authentication failure. +_RESULT_UNAUTHORIZED = -1 + + +class MotamedAsaApiError(RuntimeError): + def __init__( + self, + message: str, + *, + status_code: int | None = None, + code: str | None = None, + details: Any = None, + ): + super().__init__(message) + self.status_code = status_code + self.code = code + self.details = details + + @property + def is_transient(self) -> bool: + """The request may have been applied remotely: inquire before acting again.""" + return self.code in {"TIMEOUT", "NETWORK_ERROR"} or (self.status_code or 0) >= 500 + + +def _envelope_error(payload: Any) -> tuple[str | None, str | None]: + """First error of the partner envelope ({status, data, errors, fieldErrors, correlationId}).""" + if not isinstance(payload, dict): + return None, None + errors = payload.get("errors") + if isinstance(errors, list): + for item in errors: + if isinstance(item, dict) and (item.get("message") or item.get("code")): + return item.get("code"), item.get("message") + field_errors = payload.get("fieldErrors") + if isinstance(field_errors, list): + for item in field_errors: + if isinstance(item, dict) and item.get("errorMessage"): + return "validation_failed", f"{item.get('field') or ''}: {item['errorMessage']}".strip(": ") + error = payload.get("error") + if isinstance(error, str) and error: + return error, payload.get("message") or payload.get("error_description") + message = payload.get("message") + if isinstance(message, str) and message: + return None, message + return None, None + + +class MotamedAsaClient: + """HTTP client for the «معتمد آسا» API v2: partner onboarding, invoice sending and inquiry.""" + + def __init__( + self, + base_url: str = DEFAULT_BASE_URL, + *, + timeout_seconds: float = 60, + transport: httpx.BaseTransport | None = None, + ) -> None: + self.base_url = (base_url or DEFAULT_BASE_URL).rstrip("/") + self._http = httpx.Client( + timeout=httpx.Timeout(timeout_seconds, connect=min(timeout_seconds, 10)), + transport=transport, + follow_redirects=False, + headers={"Accept": "application/json", "User-Agent": "Hesabix-TaxProvider/1.0"}, + ) + + def close(self) -> None: + self._http.close() + + def __enter__(self) -> "MotamedAsaClient": + return self + + def __exit__(self, *_: Any) -> None: + self.close() + + def request( + self, + method: str, + path: str, + *, + body: Any = None, + params: dict[str, Any] | None = None, + token: str | None = None, + ) -> Any: + headers: dict[str, str] = {} + if token: + headers["Authorization"] = f"Bearer {token}" + try: + response = self._http.request( + method, + f"{self.base_url}{path}", + params=params, + json=body, + headers=headers, + ) + except httpx.TimeoutException as exc: + raise MotamedAsaApiError( + "پاسخی از معتمد آسا دریافت نشد؛ وضعیت عملیات باید استعلام شود.", code="TIMEOUT" + ) from exc + except httpx.HTTPError as exc: + raise MotamedAsaApiError("ارتباط با معتمد آسا برقرار نشد.", code="NETWORK_ERROR") from exc + + try: + payload = response.json() if response.content else None + except ValueError: + payload = None + if response.is_error: + code, message = _envelope_error(payload) + if response.status_code == 401: + code = code or "UNAUTHORIZED" + message = message or "دسترسی به معتمد آسا تأیید نشد." + raise MotamedAsaApiError( + str(message or f"پاسخ ناموفق معتمد آسا ({response.status_code}).")[:500], + status_code=response.status_code, + code=str(code or "HTTP_ERROR"), + details=payload, + ) + return payload + + # --- OAuth2 client credentials ------------------------------------------------------- + + def issue_token(self, client_id: str, client_secret: str) -> tuple[str, int]: + """POST /api/auth/v2/token → (access_token, expires_in seconds).""" + payload = self.request( + "POST", + "/api/auth/v2/token", + body={"grant_type": "client_credentials", "client_id": client_id, "client_secret": client_secret}, + ) + token = payload.get("access_token") if isinstance(payload, dict) else None + if not token: + raise MotamedAsaApiError("معتمد آسا توکن دسترسی برنگرداند.", code="TOKEN_MISSING") + try: + expires_in = int(payload.get("expires_in") or 3600) + except (TypeError, ValueError): + expires_in = 3600 + return str(token), expires_in + + # --- Partner routes (partner token, scope v2.register) -------------------------------- + + @staticmethod + def _envelope_data(payload: Any) -> Any: + if isinstance(payload, dict) and "data" in payload: + return payload["data"] + return payload + + def partner_profile(self, token: str) -> dict[str, Any]: + data = self._envelope_data(self.request("GET", "/api/v2/partner/profile", token=token)) + return data if isinstance(data, dict) else {} + + def create_onboarding_session(self, token: str, body: dict[str, Any]) -> dict[str, Any]: + data = self._envelope_data( + self.request("POST", "/api/v2/partner/onboarding-sessions", body=body, token=token) + ) + if not isinstance(data, dict) or not data.get("sessionId"): + raise MotamedAsaApiError("پاسخ ساخت لینک ثبت‌نام معتمد آسا ساختار معتبری ندارد.", code="INVALID_RESPONSE") + return data + + def list_onboarding_sessions(self, token: str, *, reference: str, page_size: int = 20) -> list[dict[str, Any]]: + data = self._envelope_data( + self.request( + "GET", + "/api/v2/partner/onboarding-sessions", + params={"reference": reference, "page": 1, "pageSize": page_size}, + token=token, + ) + ) + items = data.get("items") if isinstance(data, dict) else None + return [item for item in items if isinstance(item, dict)] if isinstance(items, list) else [] + + def get_onboarding_session(self, token: str, session_id: str) -> dict[str, Any]: + path = f"/api/v2/partner/onboarding-sessions/{quote(str(session_id), safe='')}" + data = self._envelope_data(self.request("GET", path, token=token)) + return data if isinstance(data, dict) else {} + + def renew_onboarding_link(self, token: str, session_id: str) -> dict[str, Any]: + path = f"/api/v2/partner/onboarding-sessions/{quote(str(session_id), safe='')}/link" + data = self._envelope_data(self.request("POST", path, body={}, token=token)) + return data if isinstance(data, dict) else {} + + def claim_credentials(self, token: str, session_id: str) -> dict[str, Any]: + """One-shot: the secret is shown once and a repeated call answers 409 credentials_already_claimed.""" + path = f"/api/v2/partner/onboarding-sessions/{quote(str(session_id), safe='')}/credentials" + data = self._envelope_data(self.request("POST", path, body={}, token=token)) + return data if isinstance(data, dict) else {} + + # --- Invoice routes (the business's customer token) ----------------------------------- + + @staticmethod + def _invoice_result(payload: Any) -> dict[str, Any]: + if not isinstance(payload, dict): + raise MotamedAsaApiError("پاسخ صورتحساب معتمد آسا ساختار معتبری ندارد.", code="INVALID_RESPONSE") + if payload.get("result") == _RESULT_UNAUTHORIZED: + raise MotamedAsaApiError( + str(payload.get("message") or "دسترسی به معتمد آسا تأیید نشد."), + status_code=401, + code="UNAUTHORIZED", + details=payload, + ) + return payload + + def send_invoices(self, token: str, body: dict[str, Any]) -> dict[str, Any]: + return self._invoice_result(self.request("POST", "/api/invoice/send", body=body, token=token)) + + def edit_invoice(self, token: str, body: dict[str, Any]) -> dict[str, Any]: + return self._invoice_result(self.request("POST", "/api/invoice/editInvoice", body=body, token=token)) + + def cancel_invoice(self, token: str, body: dict[str, Any]) -> dict[str, Any]: + return self._invoice_result(self.request("POST", "/api/invoice/cancelInvoice", body=body, token=token)) + + def register_payments(self, token: str, body: dict[str, Any]) -> dict[str, Any]: + """POST /api/invoice/registerPayment: new payment rows of a sent invoice, registered in the کارپوشه.""" + return self._invoice_result(self.request("POST", "/api/invoice/registerPayment", body=body, token=token)) + + def inquire_payments(self, token: str, internal_id: str) -> dict[str, Any]: + """POST /api/invoice/inquiryPayment: every payment row of the chain's latest invoice and its registration.""" + return self._invoice_result( + self.request("POST", "/api/invoice/inquiryPayment", body={"internalId": internal_id}, token=token) + ) + + def queue_invoices(self, token: str, internal_ids: list[str]) -> dict[str, Any]: + return self._invoice_result( + self.request("POST", "/api/invoice/sendInvoice", body={"internalIds": internal_ids}, token=token) + ) + + def inquire_internal_ids(self, token: str, internal_ids: list[str]) -> list[dict[str, Any]]: + """Each item is the latest invoice of the chain the internalId belongs to, in request order.""" + if not internal_ids: + return [] + payload = self.request( + "POST", "/api/invoice/inquiryInternalIds", body={"internalIds": internal_ids}, token=token + ) + items = [item for item in payload if isinstance(item, dict)] if isinstance(payload, list) else [] + if len(items) != len(internal_ids) or any( + not item.get("internalId") and not item.get("asatspId") for item in items + ): + # Authentication and batch failures come back as one item without an internalId. + first = items[0] if items else {} + errors = first.get("error") if isinstance(first.get("error"), list) else [] + raise MotamedAsaApiError( + str(errors[0] if errors else "استعلام صورتحساب از معتمد آسا پذیرفته نشد."), + status_code=401, + code="UNAUTHORIZED" if errors else "INQUIRY_REJECTED", + details=payload, + ) + return items diff --git a/hesabixAPI/app/services/motamed_asa_provider_service.py b/hesabixAPI/app/services/motamed_asa_provider_service.py new file mode 100644 index 00000000..5a49d341 --- /dev/null +++ b/hesabixAPI/app/services/motamed_asa_provider_service.py @@ -0,0 +1,695 @@ +""" +اتصال کسب‌وکار به ارائه‌دهندهٔ مالیاتی «معتمد آسا». + +The business signs up on ASA's own hosted page (its owner signs in with the tax +organisation's one-time code and agrees there to hand the API key to Hesabix); +Hesabix never collects identity documents for ASA. The partner credential +(client id/secret of Hesabix in ASA's «همکاران API») lives in +tax_provider_credentials; each business's own client id/secret, ASA company id +and fiscal memory id live in business_tax_provider_accounts. +""" +from __future__ import annotations + +import re +from datetime import datetime, timedelta +from typing import Any, Callable, TypeVar +from urllib.parse import urlsplit + +from sqlalchemy.orm import Session + +from adapters.db.models.business import Business +from adapters.db.models.tax_provider import BusinessTaxProviderAccount, TaxProviderCredential +from adapters.db.models.tax_setting import TaxSetting +from adapters.db.models.user import User +from app.core.responses import ApiError +from app.integrations.motamed_asa.client import DEFAULT_BASE_URL, MotamedAsaApiError, MotamedAsaClient +from app.services.tax_provider_service import ( + _decrypt, + _encrypt, + _latin_digits, + _mask, + _normalize_iranian_mobile, + get_provider_credential, +) + +T = TypeVar("T") + +MOTAMED_ASA_PROVIDER = "motamed_asa" +MOTAMED_ASA_DISPLAY_NAME = "معتمد آسا" +MOTAMED_ASA_BASE_URL = DEFAULT_BASE_URL + +_REFERENCE_PREFIX = "hesabix-business-" +_CUSTOMER_CLIENT_ID = re.compile(r"^v2-customer-(\d{1,10})$") +_OPEN_SESSION_STATUSES = {"created", "opened", "in_progress"} +_READY_SESSION_STATUSES = {"business_ready", "completed"} +_TOKEN_REFRESH_MARGIN = timedelta(minutes=2) + +# business_tax_provider_accounts.status values used for this provider +STATUS_NOT_CONNECTED = "not_connected" +STATUS_ONBOARDING = "onboarding" +STATUS_CREDENTIALS_REQUIRED = "credentials_required" +STATUS_CONNECTED = "connected" + +_MESSAGE_EXISTING_CREDENTIALS = ( + "این کسب‌وکار پیش‌تر کلید API نسخهٔ ۲ معتمد آسا داشته و کلید تازه‌ای تحویل نشد. " + "شناسه و رمز کلاینت را از پنل معتمد آسا (تنظیمات کسب‌وکار › API نسخه ۲) وارد کنید." +) +_MESSAGE_CREDENTIALS_CLAIMED = ( + "کلید API این کسب‌وکار پیش‌تر تحویل شده و دوباره نمایش داده نمی‌شود. " + "در پنل معتمد آسا (تنظیمات کسب‌وکار › API نسخه ۲) رمز تازه بسازید و شناسه و رمز را اینجا وارد کنید." +) +_MESSAGE_CREDENTIALS_NOT_ALLOWED = ( + "مالک کسب‌وکار در صفحهٔ ثبت‌نام معتمد آسا تحویل کلید API به حسابیکس را تأیید نکرد. " + "می‌توانید دوباره لینک ثبت‌نام را باز کنید یا شناسه و رمز کلاینت را از پنل معتمد آسا وارد کنید." +) +_MESSAGE_SESSION_CLOSED = "لینک ثبت‌نام معتمد آسا منقضی یا لغو شده است؛ برای ادامه، لینک تازه بگیرید." + + +# --- System-wide credential (admin) --------------------------------------------------------- + + +def get_motamed_asa_credential(db: Session) -> TaxProviderCredential | None: + return get_provider_credential(db, MOTAMED_ASA_PROVIDER) + + +def motamed_asa_available(credential: TaxProviderCredential | None) -> bool: + return bool( + credential + and credential.is_active + and credential.username_encrypted + and credential.password_encrypted + ) + + +def serialize_motamed_asa_credential(credential: TaxProviderCredential | None) -> dict[str, Any]: + client_id = _decrypt(credential.username_encrypted, "شناسه کلاینت همکار") if credential else None + return { + "provider_code": MOTAMED_ASA_PROVIDER, + "display_name": credential.display_name if credential else MOTAMED_ASA_DISPLAY_NAME, + "base_url": credential.base_url if credential else MOTAMED_ASA_BASE_URL, + "client_id_masked": _mask(client_id), + "client_id_configured": bool(client_id), + "client_secret_configured": bool(credential and credential.password_encrypted), + "is_active": bool(credential and credential.is_active), + "updated_at": credential.updated_at.isoformat() if credential and credential.updated_at else None, + } + + +def save_motamed_asa_credential(db: Session, payload: dict[str, Any]) -> TaxProviderCredential: + base_url = str(payload.get("base_url") or MOTAMED_ASA_BASE_URL).strip().rstrip("/") + parsed = urlsplit(base_url) + if parsed.scheme != "https" or not parsed.netloc or parsed.username or parsed.password: + raise ApiError("INVALID_PROVIDER_URL", "نشانی API معتمد آسا باید HTTPS معتبر باشد.", http_status=400) + if parsed.query or parsed.fragment or parsed.path not in ("", "/"): + raise ApiError("INVALID_PROVIDER_URL", "نشانی API معتمد آسا فقط دامنه است و مسیر، query یا fragment ندارد.", http_status=400) + + client_id = str(payload.get("client_id") or "").strip() + client_secret = str(payload.get("client_secret") or "") + if client_id and not client_id.startswith("v2-partner-"): + raise ApiError("INVALID_CLIENT_ID", "شناسه کلاینت همکار باید با v2-partner- شروع شود.", http_status=400) + + credential = get_motamed_asa_credential(db) + if credential is None: + credential = TaxProviderCredential( + provider_code=MOTAMED_ASA_PROVIDER, + display_name=MOTAMED_ASA_DISPLAY_NAME, + base_url=base_url, + is_active=False, + ) + db.add(credential) + credential.base_url = base_url + credential.is_active = payload.get("is_active") is True + if client_id: + credential.username_encrypted = _encrypt(client_id) + if client_secret: + credential.password_encrypted = _encrypt(client_secret) + if not credential.username_encrypted or not credential.password_encrypted: + credential.is_active = False + db.flush() + return credential + + +def _partner_secrets(credential: TaxProviderCredential) -> tuple[str, str]: + client_id = _decrypt(credential.username_encrypted, "شناسه کلاینت همکار") + client_secret = _decrypt(credential.password_encrypted, "رمز کلاینت همکار") + if not client_id or not client_secret: + raise ApiError( + "TAX_PROVIDER_NOT_CONFIGURED", + "شناسه و رمز کلاینت حسابیکس در معتمد آسا در مدیریت سیستم کامل نیست.", + http_status=503, + ) + return client_id, client_secret + + +def _partner_token(client: MotamedAsaClient, credential: TaxProviderCredential) -> str: + client_id, client_secret = _partner_secrets(credential) + token, _ = client.issue_token(client_id, client_secret) + return token + + +def test_motamed_asa_connection(db: Session) -> dict[str, Any]: + credential = get_motamed_asa_credential(db) + if credential is None: + raise ApiError("TAX_PROVIDER_NOT_CONFIGURED", "ابتدا شناسه و رمز کلاینت معتمد آسا را ثبت کنید.", http_status=400) + client = MotamedAsaClient(credential.base_url) + try: + profile = client.partner_profile(_partner_token(client, credential)) + capabilities = profile.get("capabilities") if isinstance(profile.get("capabilities"), dict) else {} + return { + "connected": True, + "partner_status": profile.get("status"), + "display_name": profile.get("displayName"), + "hosted_onboarding": capabilities.get("hostedOnboarding") is True, + "credential_handover": capabilities.get("credentialHandover") is True, + "default_return_url": profile.get("defaultReturnUrl"), + } + except MotamedAsaApiError as exc: + raise ApiError("TAX_PROVIDER_CONNECTION_FAILED", str(exc), http_status=502) from exc + finally: + client.close() + + +# --- Business account --------------------------------------------------------------------- + + +def _get_account(db: Session, business_id: int, *, lock: bool = False) -> BusinessTaxProviderAccount | None: + query = db.query(BusinessTaxProviderAccount).filter_by( + business_id=int(business_id), provider_code=MOTAMED_ASA_PROVIDER + ) + if lock: + query = query.with_for_update() + return query.first() + + +def _is_connected(account: BusinessTaxProviderAccount | None) -> bool: + return bool( + account + and account.status == STATUS_CONNECTED + and account.username_encrypted + and account.password_encrypted + ) + + +def serialize_motamed_asa_account(account: BusinessTaxProviderAccount | None) -> dict[str, Any] | None: + if account is None: + return None + return { + "status": account.status, + "connected": _is_connected(account), + "company_id": account.cartable_id, + "memory_unique_id": account.memory_number, + "last_error": account.last_error if account.status != STATUS_CONNECTED else None, + "consented_at": account.consented_at.isoformat() if account.consented_at else None, + "registered_at": account.registered_at.isoformat() if account.registered_at else None, + "last_synced_at": account.last_synced_at.isoformat() if account.last_synced_at else None, + } + + +def motamed_asa_provider_state(db: Session, business_id: int) -> dict[str, Any]: + return { + "motamed_asa_available": motamed_asa_available(get_motamed_asa_credential(db)), + "motamed_asa_account": serialize_motamed_asa_account(_get_account(db, business_id)), + } + + +def _require_active_credential(db: Session) -> TaxProviderCredential: + credential = get_motamed_asa_credential(db) + if not motamed_asa_available(credential): + raise ApiError( + "TAX_PROVIDER_NOT_CONFIGURED", + "ارسال از طریق معتمد آسا هنوز در مدیریت سیستم فعال نشده است.", + http_status=503, + ) + return credential # type: ignore[return-value] + + +def _onboarding_reference(business_id: int) -> str: + return f"{_REFERENCE_PREFIX}{int(business_id)}" + + +def _latest_session(client: MotamedAsaClient, token: str, business_id: int) -> dict[str, Any] | None: + sessions = client.list_onboarding_sessions(token, reference=_onboarding_reference(business_id)) + if not sessions: + return None + return max(sessions, key=lambda item: str(item.get("createdAt") or "")) + + +def _ensure_economic_code(db: Session, business_id: int, setting: TaxSetting | None, economic_code: str | None, user_id: int | None) -> TaxSetting: + requested = _latin_digits(economic_code) + if setting is not None and setting.economic_code: + saved = _latin_digits(setting.economic_code) + if requested and requested != saved: + raise ApiError( + "TAX_SETTINGS_UNSAVED", + "کد اقتصادی واردشده با کد ذخیره‌شده یکی نیست؛ ابتدا تنظیمات را ذخیره کنید.", + http_status=400, + ) + return setting + if not re.fullmatch(r"\d{11}|\d{14}", requested or ""): + raise ApiError( + "TAX_SETTINGS_INCOMPLETE", + "برای اتصال به معتمد آسا ابتدا کد اقتصادی ۱۱ یا ۱۴ رقمی کسب‌وکار را وارد کنید.", + http_status=400, + ) + if setting is None: + setting = TaxSetting(business_id=int(business_id), created_by_user_id=user_id) + db.add(setting) + setting.economic_code = requested + db.flush() + return setting + + +def _session_body(db: Session, business: Business, setting: TaxSetting) -> dict[str, Any]: + owner = db.query(User).filter(User.id == int(business.owner_id)).first() + mobile = _normalize_iranian_mobile((owner.mobile if owner else None) or business.mobile) + body: dict[str, Any] = { + "economicCode": _latin_digits(setting.economic_code), + "businessName": (business.name or "")[:200] or None, + "reference": _onboarding_reference(int(business.id)), + "issueMemoryUniqueId": True, + "requestCredentials": True, + } + if re.fullmatch(r"09\d{9}", mobile or ""): + body["mobile"] = mobile + return {key: value for key, value in body.items() if value is not None} + + +def _onboarding_link(session: dict[str, Any]) -> dict[str, Any] | None: + url = session.get("url") + if not url: + return None + return { + "url": url, + "expires_at": session.get("expiresAt"), + "session_status": session.get("status"), + } + + +def _store_business_credentials( + db: Session, + account: BusinessTaxProviderAccount, + setting: TaxSetting | None, + *, + client_id: str, + client_secret: str, + company_id: int | None, + memory_unique_id: str | None, +) -> None: + account.username_encrypted = _encrypt(client_id) + account.password_encrypted = _encrypt(client_secret) + account.access_token_encrypted = None + account.token_expires_at = None + if company_id: + account.cartable_id = int(company_id) + if memory_unique_id: + account.memory_number = str(memory_unique_id) + account.status = STATUS_CONNECTED + account.last_error = None + account.registered_at = account.registered_at or datetime.utcnow() + account.last_synced_at = datetime.utcnow() + if setting is not None: + setting.submission_provider = MOTAMED_ASA_PROVIDER + # The handover secret is shown once: persist it before anything else can fail. + db.commit() + + +def _complete_from_session( + db: Session, + client: MotamedAsaClient, + token: str, + account: BusinessTaxProviderAccount, + setting: TaxSetting | None, + session: dict[str, Any], +) -> None: + business = session.get("business") if isinstance(session.get("business"), dict) else {} + memory = session.get("memory") if isinstance(session.get("memory"), dict) else {} + credentials = session.get("credentials") if isinstance(session.get("credentials"), dict) else {} + if business.get("companyId"): + account.cartable_id = int(business["companyId"]) + if memory.get("memoryUniqueId"): + account.memory_number = str(memory["memoryUniqueId"]) + + if credentials.get("available") is True and credentials.get("claimed") is not True: + try: + handed = client.claim_credentials(token, str(session["sessionId"])) + except MotamedAsaApiError as exc: + if exc.status_code == 409 and exc.code == "credentials_already_claimed": + account.status = STATUS_CREDENTIALS_REQUIRED + account.last_error = _MESSAGE_CREDENTIALS_CLAIMED + db.commit() + return + raise + secret = handed.get("clientSecret") + if handed.get("secretIssued") is True and secret: + _store_business_credentials( + db, + account, + setting, + client_id=str(handed.get("clientId") or ""), + client_secret=str(secret), + company_id=handed.get("companyId") or business.get("companyId"), + memory_unique_id=memory.get("memoryUniqueId"), + ) + return + account.status = STATUS_CREDENTIALS_REQUIRED + account.last_error = _MESSAGE_EXISTING_CREDENTIALS + elif credentials.get("claimed") is True: + account.status = STATUS_CREDENTIALS_REQUIRED + account.last_error = _MESSAGE_CREDENTIALS_CLAIMED + else: + account.status = STATUS_CREDENTIALS_REQUIRED + account.last_error = _MESSAGE_CREDENTIALS_NOT_ALLOWED + account.last_synced_at = datetime.utcnow() + db.commit() + + +def _apply_session( + db: Session, + client: MotamedAsaClient, + token: str, + account: BusinessTaxProviderAccount, + setting: TaxSetting | None, + session: dict[str, Any] | None, +) -> None: + status = str((session or {}).get("status") or "") + if session is None: + account.status = STATUS_NOT_CONNECTED + account.last_error = None + elif status in _READY_SESSION_STATUSES: + _complete_from_session(db, client, token, account, setting, session) + return + elif status in _OPEN_SESSION_STATUSES: + account.status = STATUS_ONBOARDING + last_error = session.get("lastError") if isinstance(session.get("lastError"), dict) else None + account.last_error = str(last_error.get("message"))[:500] if last_error and last_error.get("message") else None + else: + account.status = STATUS_NOT_CONNECTED + account.last_error = _MESSAGE_SESSION_CLOSED + account.last_synced_at = datetime.utcnow() + db.commit() + + +def start_motamed_asa_onboarding( + db: Session, + *, + business_id: int, + consent: bool, + consented_by_user_id: int | None, + economic_code: str | None = None, +) -> dict[str, Any]: + """ + Selects «معتمد آسا» for the business. A connected account switches at once; + otherwise a hosted sign-up link on ASA is returned under "motamed_asa_onboarding". + """ + if not consent: + raise ApiError( + "MOTAMED_ASA_CONSENT_REQUIRED", + "برای اتصال به معتمد آسا، تأیید صریح شما لازم است.", + http_status=400, + ) + credential = _require_active_credential(db) + # The business row is the serialisation point, as for the other providers. + business = db.query(Business).filter(Business.id == int(business_id)).with_for_update().first() + if not business: + raise ApiError("BUSINESS_NOT_FOUND", "کسب‌وکار پیدا نشد.", http_status=404) + setting = db.query(TaxSetting).filter(TaxSetting.business_id == int(business_id)).first() + setting = _ensure_economic_code(db, business_id, setting, economic_code, consented_by_user_id) + if setting.sandbox_mode: + raise ApiError( + "MOTAMED_ASA_SANDBOX_UNAVAILABLE", + "ارسال از طریق معتمد آسا فقط در محیط اصلی سامانهٔ مؤدیان انجام می‌شود؛ حالت آزمایشی را خاموش کنید.", + http_status=400, + ) + + account = _get_account(db, business_id, lock=True) + if account is None: + account = BusinessTaxProviderAccount(business_id=int(business_id), provider_code=MOTAMED_ASA_PROVIDER) + db.add(account) + account.consented_by_user_id = consented_by_user_id + account.consented_at = datetime.utcnow() + if _is_connected(account): + setting.submission_provider = MOTAMED_ASA_PROVIDER + db.commit() + return motamed_asa_provider_state(db, business_id) + account.status = STATUS_ONBOARDING + account.last_error = None + db.commit() + + client = MotamedAsaClient(credential.base_url) + try: + return _link_or_complete(db, client, credential, account, business, setting) + except MotamedAsaApiError as exc: + account.last_error = str(exc)[:500] + db.commit() + raise ApiError("MOTAMED_ASA_ONBOARDING_FAILED", str(exc), http_status=502 if exc.is_transient else 400) from exc + finally: + client.close() + + +def _link_or_complete( + db: Session, + client: MotamedAsaClient, + credential: TaxProviderCredential, + account: BusinessTaxProviderAccount, + business: Business, + setting: TaxSetting, +) -> dict[str, Any]: + """ + The session is found by its reference, so a create whose answer was lost is + found again instead of opening a second sign-up for the same business. + """ + business_id = int(business.id) + token = _partner_token(client, credential) + session = _latest_session(client, token, business_id) + status = str((session or {}).get("status") or "") + if session and status in _READY_SESSION_STATUSES: + # The owner finished on ASA earlier: take the handed-over key instead of a new link. + _complete_from_session(db, client, token, account, setting, session) + return motamed_asa_provider_state(db, business_id) + if session and status in _OPEN_SESSION_STATUSES: + session = {**session, **client.renew_onboarding_link(token, str(session["sessionId"]))} + else: + session = client.create_onboarding_session(token, _session_body(db, business, setting)) + account.status = STATUS_ONBOARDING + account.last_error = None + account.last_synced_at = datetime.utcnow() + db.commit() + state = motamed_asa_provider_state(db, business_id) + state["motamed_asa_onboarding"] = _onboarding_link(session) + return state + + +def renew_motamed_asa_link(db: Session, business_id: int) -> dict[str, Any]: + """A fresh sign-up link for the business's open session (or a new session after consent).""" + credential = _require_active_credential(db) + account = _get_account(db, business_id, lock=True) + if account is None or not account.consented_at: + raise ApiError( + "MOTAMED_ASA_CONSENT_REQUIRED", + "ابتدا روش ارسال «معتمد آسا» را انتخاب و شرایط آن را تأیید کنید.", + http_status=400, + ) + if _is_connected(account): + raise ApiError("MOTAMED_ASA_ALREADY_CONNECTED", "این کسب‌وکار به معتمد آسا متصل است.", http_status=409) + business = db.query(Business).filter(Business.id == int(business_id)).first() + setting = db.query(TaxSetting).filter(TaxSetting.business_id == int(business_id)).first() + if business is None or setting is None or not setting.economic_code: + raise ApiError("TAX_SETTINGS_INCOMPLETE", "کد اقتصادی کسب‌وکار ثبت نشده است.", http_status=400) + + client = MotamedAsaClient(credential.base_url) + try: + return _link_or_complete(db, client, credential, account, business, setting) + except MotamedAsaApiError as exc: + raise ApiError("MOTAMED_ASA_ONBOARDING_FAILED", str(exc), http_status=502 if exc.is_transient else 400) from exc + finally: + client.close() + + +def sync_motamed_asa_account(db: Session, business_id: int) -> dict[str, Any]: + """Reads the sign-up result from ASA, takes the handed-over key once, or re-checks a connected key.""" + credential = _require_active_credential(db) + account = _get_account(db, business_id, lock=True) + if account is None: + raise ApiError("MOTAMED_ASA_ACCOUNT_NOT_FOUND", "این کسب‌وکار هنوز به معتمد آسا وصل نشده است.", http_status=404) + setting = db.query(TaxSetting).filter(TaxSetting.business_id == int(business_id)).first() + client = MotamedAsaClient(credential.base_url) + try: + if _is_connected(account): + _customer_token(db, client, account, force=True) + account.last_synced_at = datetime.utcnow() + db.commit() + return motamed_asa_provider_state(db, business_id) + token = _partner_token(client, credential) + _apply_session(db, client, token, account, setting, _latest_session(client, token, business_id)) + return motamed_asa_provider_state(db, business_id) + except MotamedAsaApiError as exc: + raise ApiError("MOTAMED_ASA_SYNC_FAILED", str(exc), http_status=502 if exc.is_transient else 400) from exc + finally: + client.close() + + +def save_motamed_asa_business_credentials( + db: Session, + *, + business_id: int, + client_id: str, + client_secret: str, + consent: bool, + consented_by_user_id: int | None, + economic_code: str | None = None, +) -> dict[str, Any]: + """The owner's own API v2 customer client id/secret, copied from the ASA panel.""" + if not consent: + raise ApiError( + "MOTAMED_ASA_CONSENT_REQUIRED", + "برای اتصال به معتمد آسا، تأیید صریح شما لازم است.", + http_status=400, + ) + credential = _require_active_credential(db) + client_id = str(client_id or "").strip() + client_secret = str(client_secret or "").strip() + match = _CUSTOMER_CLIENT_ID.fullmatch(client_id) + if not match or not client_secret or len(client_secret) > 512: + raise ApiError( + "MOTAMED_ASA_CREDENTIALS_INVALID", + "شناسه کلاینت باید به شکل v2-customer-شماره باشد و رمز کلاینت خالی نباشد.", + http_status=400, + ) + business = db.query(Business).filter(Business.id == int(business_id)).with_for_update().first() + if not business: + raise ApiError("BUSINESS_NOT_FOUND", "کسب‌وکار پیدا نشد.", http_status=404) + setting = db.query(TaxSetting).filter(TaxSetting.business_id == int(business_id)).first() + setting = _ensure_economic_code(db, business_id, setting, economic_code, consented_by_user_id) + if setting.sandbox_mode: + raise ApiError( + "MOTAMED_ASA_SANDBOX_UNAVAILABLE", + "ارسال از طریق معتمد آسا فقط در محیط اصلی سامانهٔ مؤدیان انجام می‌شود؛ حالت آزمایشی را خاموش کنید.", + http_status=400, + ) + + client = MotamedAsaClient(credential.base_url) + try: + client.issue_token(client_id, client_secret) + except MotamedAsaApiError as exc: + if exc.is_transient: + raise ApiError("MOTAMED_ASA_UNAVAILABLE", str(exc), http_status=502) from exc + raise ApiError( + "MOTAMED_ASA_CREDENTIALS_INVALID", + "معتمد آسا این شناسه و رمز کلاینت را نپذیرفت؛ مقدارها را از پنل معتمد آسا دوباره کپی کنید.", + http_status=400, + ) from exc + finally: + client.close() + + account = _get_account(db, business_id, lock=True) + if account is None: + account = BusinessTaxProviderAccount(business_id=int(business_id), provider_code=MOTAMED_ASA_PROVIDER) + db.add(account) + account.consented_by_user_id = consented_by_user_id + account.consented_at = datetime.utcnow() + _store_business_credentials( + db, + account, + setting, + client_id=client_id, + client_secret=client_secret, + company_id=int(match.group(1)), + memory_unique_id=None, + ) + return motamed_asa_provider_state(db, business_id) + + +def motamed_asa_health(db: Session, business_id: int) -> dict[str, dict[str, Any]]: + """Health checks of a business that sends through ASA: its connection replaces the tax-system login.""" + if not motamed_asa_available(get_motamed_asa_credential(db)): + return {"settings": {"status": "error", "message": "ارسال از طریق معتمد آسا در مدیریت سیستم فعال نیست."}} + account = _get_account(db, business_id) + if not _is_connected(account): + return {"settings": {"status": "error", "message": "حساب این کسب‌وکار در معتمد آسا هنوز متصل نشده است."}} + checks: dict[str, dict[str, Any]] = { + "settings": {"status": "ok", "message": "کسب‌وکار به معتمد آسا متصل است.", "provider": MOTAMED_ASA_PROVIDER}, + } + credential = get_motamed_asa_credential(db) + client = MotamedAsaClient(credential.base_url) # type: ignore[union-attr] + try: + _customer_token(db, client, account, force=True) # type: ignore[arg-type] + checks["connection"] = {"status": "ok", "message": "اتصال به معتمد آسا برقرار است."} + checks["authentication"] = {"status": "ok", "message": "معتمد آسا کلید API کسب‌وکار را پذیرفت."} + except ApiError as exc: + checks["authentication"] = {"status": "error", "message": exc.message} + except MotamedAsaApiError as exc: + checks["connection"] = {"status": "error", "message": f"خطا در اتصال به معتمد آسا: {exc}"} + finally: + client.close() + return checks + + +# --- Customer calls (sending and inquiry) --------------------------------------------------- + + +def _customer_token( + db: Session, + client: MotamedAsaClient, + account: BusinessTaxProviderAccount, + *, + force: bool = False, +) -> str: + if not force: + cached = _decrypt(account.access_token_encrypted, "توکن معتمد آسا") + if cached and account.token_expires_at and account.token_expires_at > datetime.utcnow() + _TOKEN_REFRESH_MARGIN: + return cached + client_id = _decrypt(account.username_encrypted, "شناسه کلاینت کسب‌وکار") + client_secret = _decrypt(account.password_encrypted, "رمز کلاینت کسب‌وکار") + if not client_id or not client_secret: + raise ApiError( + "MOTAMED_ASA_ACCOUNT_NOT_CONNECTED", + "کلید API معتمد آسا برای این کسب‌وکار ثبت نشده است.", + http_status=409, + ) + try: + token, expires_in = client.issue_token(client_id, client_secret) + except MotamedAsaApiError as exc: + if exc.is_transient: + raise + account.status = STATUS_CREDENTIALS_REQUIRED + account.last_error = "معتمد آسا کلید API این کسب‌وکار را دیگر نمی‌پذیرد؛ شناسه و رمز تازه را وارد کنید." + db.flush() + raise ApiError("MOTAMED_ASA_CREDENTIALS_REJECTED", account.last_error, http_status=409) from exc + account.access_token_encrypted = _encrypt(token) + account.token_expires_at = datetime.utcnow() + timedelta(seconds=max(expires_in - 60, 60)) + account.last_synced_at = datetime.utcnow() + db.flush() + return token + + +def get_motamed_asa_account(db: Session, business_id: int) -> tuple[TaxProviderCredential, BusinessTaxProviderAccount]: + credential = _require_active_credential(db) + account = _get_account(db, business_id) + if not _is_connected(account): + raise ApiError( + "MOTAMED_ASA_ACCOUNT_NOT_CONNECTED", + "حساب این کسب‌وکار در معتمد آسا هنوز متصل نشده است.", + http_status=409, + ) + return credential, account # type: ignore[return-value] + + +def motamed_asa_business_call( + db: Session, + business_id: int, + operation: Callable[[MotamedAsaClient, str, BusinessTaxProviderAccount], T], +) -> T: + """Runs one customer operation with a cached token, renewing it once when ASA refuses it.""" + credential, account = get_motamed_asa_account(db, business_id) + client = MotamedAsaClient(credential.base_url) + try: + token = _customer_token(db, client, account) + try: + return operation(client, token, account) + except MotamedAsaApiError as exc: + if exc.code != "UNAUTHORIZED": + raise + token = _customer_token(db, client, account, force=True) + return operation(client, token, account) + finally: + client.close() diff --git a/hesabixAPI/app/services/motamed_asa_tax_submission_service.py b/hesabixAPI/app/services/motamed_asa_tax_submission_service.py new file mode 100644 index 00000000..a3d59487 --- /dev/null +++ b/hesabixAPI/app/services/motamed_asa_tax_submission_service.py @@ -0,0 +1,822 @@ +""" +ارسال و استعلام صورتحساب از طریق «معتمد آسا» (ASA TSP API v2). + +ASA issues the tax id and the fiscal-memory serial itself, so the Hesabix taxid +in the DTO is not sent. Each Hesabix document is one ASA invoice chain keyed by +its internalId; ASA answers an inquiry with the latest invoice of that chain. + +Operations (API v2 docs, sections 05, 07, 08D): +- original sale: POST /api/invoice/send (ins=1); a rejected or unsent invoice + is edited in place with /api/invoice/editInvoice; +- correction: /api/invoice/editInvoice with confirmCorrection (ASA sets ins=2 + and the reference); +- cancellation: /api/invoice/cancelInvoice on the chain; +- sales return: /send with ins=4 and returnRows "returned": the Body is the + return document's own lines (the goods taken back) and ASA matches them to + the registered reference rows and builds the rows left after the return + (RC_IITP.IS_V7.9 table 1, pp. 14-18) with every tax field of the reference. +""" +from __future__ import annotations + +import datetime as dt +import uuid +from decimal import Decimal, InvalidOperation +from typing import Any + +from sqlalchemy.orm import Session + +from adapters.db.models.document import Document +from adapters.db.models.tax_setting import TaxSetting +from app.core.responses import ApiError +from app.integrations.moadian.dto import InvoiceDto +from app.integrations.moadian.utils import normalize_invoice_number, timestamp_to_unix_ms +from app.integrations.motamed_asa.client import MotamedAsaApiError, MotamedAsaClient +from app.services.motamed_asa_provider_service import ( + MOTAMED_ASA_PROVIDER, + motamed_asa_business_call, +) +from app.services.tax_reference_service import resolve_reference_document + +# InvoicePhases of API v2 results +_PHASE_AWAITING_SEND = 0 +_PHASE_PENDING = 1 +_PHASE_SUCCESS = 2 +_PHASE_ERROR = 3 +_PHASE_NAMES = {"awaitingsend": 0, "pending": 1, "success": 2, "haserror": 3, "proforma": 7} + +# InvoiceIssues (Header.ins) +_ISSUE_ORIGINAL = 1 +_ISSUE_CORRECTION = 2 +_ISSUE_CANCELLATION = 3 +_ISSUE_RETURN = 4 + +_INQUIRY_BATCH = 250 +_NOT_FOUND_MARKER = "یافت نشد" +# Spellings of the Article 6 status the tax system and the ASA panel use (MegaPay GetArticle6StatusText). +_ARTICLE6_NOT_VIOLATED = {"NOT_EXCEEDED", "NO_DEVIATION", "NOT_DEVIATED", "NOT_VIOLATED", "NO", "FALSE", "0"} +_ARTICLE6_VIOLATED = {"EXCEEDED", "DEVIATION", "DEVIATED", "VIOLATION", "VIOLATED", "YES", "TRUE", "1"} +_PAYMENT_TYPES = range(1, 9) +_PAYMENT_ROWS_MAX = 50 + +_HEADER_FIELDS = ( + "indatim", "inty", "inp", "ins", "inno", "tins", "irtaxid", "tob", "bid", "tinb", + "sbc", "bpc", "bbc", "bpn", "scln", "scc", "crn", "billid", "cdcn", "cdcd", + "tprdis", "tdis", "tadis", "tvam", "todam", "tbill", "setm", "cap", "insp", "tvop", +) +_BODY_FIELDS = ( + "sstid", "sstt", "mu", "am", "fee", "prdis", "dis", "adis", "vra", "vam", "tsstam", + "vop", "ssrv", "bsrn", "nw", +) +_PAYMENT_FIELDS = ("iinn", "acn", "trmn", "trn", "pcn", "pid", "pdt", "pmt", "pv") +_BUYER_FIELDS = ("tob", "bid", "tinb", "sbc", "bpc", "bbc", "bpn") + + +# --- Identifiers ---------------------------------------------------------------------------- + + +def motamed_asa_internal_id(document: Document) -> str: + """The ASA internalId of the document's invoice chain; stable across retries.""" + stored = str((document.extra_info or {}).get("asa_internal_id") or "").strip() + return stored or f"hesabix-{int(document.id)}" + + +def _cancel_internal_id(internal_id: str) -> str: + return f"{internal_id}-cancel" + + +# --- Payload ---------------------------------------------------------------------------------- + + +def build_motamed_asa_invoice(invoice_dto: InvoiceDto, *, document_id: int, subject: int) -> dict[str, Any]: + """ + The official JSON (Header, Body, Payments) for API v2. Hesabix issues sales of + pattern 1; its own inp/ins mark the operation, so both are set here. + """ + payload = invoice_dto.to_dict() + source_header = payload.get("header") or {} + header = {key: source_header[key] for key in _HEADER_FIELDS if source_header.get(key) is not None} + header["inp"] = 1 + header["ins"] = int(subject) + header["inno"] = normalize_invoice_number(document_id) + if subject == _ISSUE_ORIGINAL: + header.pop("irtaxid", None) + if subject == _ISSUE_RETURN: + # In a return the buyer is outside the pattern and comes from the reference (V7.9 table 1). + for key in _BUYER_FIELDS: + header.pop(key, None) + + body = [ + {key: row[key] for key in _BODY_FIELDS if row.get(key) is not None} + for row in payload.get("body") or [] + if isinstance(row, dict) + ] + payments: list[dict[str, Any]] = [] + if header.get("inty") == 1: + for payment in payload.get("payments") or []: + if not isinstance(payment, dict) or payment.get("pmt") in (None, ""): + continue + row = {key: payment[key] for key in _PAYMENT_FIELDS if payment.get(key) not in (None, "")} + row["pmt"] = int(_decimal(row["pmt"])) + if "pdt" in row: + row["pdt"] = _unix_ms(row["pdt"]) + payments.append({key: value for key, value in row.items() if value is not None}) + return {"Header": header, "Body": body, "Payments": payments} + + +def _unix_ms(value: Any) -> int | None: + """API v2 takes payment times as Unix milliseconds; Hesabix may keep them as dates.""" + if isinstance(value, bool): + return None + if isinstance(value, (int, float)) or (isinstance(value, str) and value.strip().isdigit()): + return int(value) + if isinstance(value, str): + try: + value = dt.datetime.fromisoformat(value.strip().replace("Z", "+00:00")) + except ValueError: + # An unreadable payment time is left out rather than replaced by "now". + return None + if isinstance(value, (dt.datetime, dt.date)): + return timestamp_to_unix_ms(value) + return None + + +def _decimal(value: Any) -> Decimal: + try: + return Decimal(str(value if value not in (None, "") else 0)) + except (InvalidOperation, ValueError): + return Decimal(0) + + +# --- Results ---------------------------------------------------------------------------------- + + +def _phase(info: dict[str, Any]) -> int | None: + value = info.get("status") + if isinstance(value, str): + named = _PHASE_NAMES.get(value.strip().lower()) + if named is not None: + return named + try: + return int(value) + except (TypeError, ValueError): + return None + + +def _issue(info: dict[str, Any]) -> int | None: + value = info.get("issue") + if isinstance(value, str): + named = {"original": 1, "correction": 2, "cancellation": 3, "salesreturn": 4, "return": 4}.get( + value.strip().lower().replace("_", "") + ) + if named is not None: + return named + try: + return int(value) + except (TypeError, ValueError): + return None + + +def _errors(info: dict[str, Any]) -> list[str]: + raw = info.get("error") + if isinstance(raw, list): + return [str(item) for item in raw if item] + return [str(raw)] if raw else [] + + +def _not_found(info: dict[str, Any] | None) -> bool: + if not info: + return True + return not info.get("asatspId") and any(_NOT_FOUND_MARKER in message for message in _errors(info)) + + +def normalize_article6_status(value: Any) -> str | None: + """ + «violated» (عدول) or «not_violated» (عدم عدول) for the Article 6 status the + tax system reports; None when the value is not one of the known spellings, + so the raw value is shown instead of a guess. + """ + text = str(value or "").strip() + if not text: + return None + upper = text.upper() + if upper in _ARTICLE6_NOT_VIOLATED or "عدم" in text: + return "not_violated" + if upper in _ARTICLE6_VIOLATED or "عدول" in text: + return "violated" + return None + + +def _hesabix_status(info: dict[str, Any]) -> tuple[str | None, str | None]: + """(tax_status, error message) in Hesabix's vocabulary for one API v2 result.""" + phase = _phase(info) + if phase in (_PHASE_AWAITING_SEND, _PHASE_PENDING): + if phase == _PHASE_AWAITING_SEND and _errors(info): + return "failed", "؛ ".join(_errors(info)) + return "pending", None + if phase == _PHASE_SUCCESS: + # Registered by the tax system; the buyer's reaction is the separate «وضعیت کارپوشه». + return "finalized", None + if phase == _PHASE_ERROR: + return "failed", "؛ ".join(_errors(info)) or "سامانهٔ مؤدیان صورتحساب را نپذیرفت." + return None, None + + +def _raw(info: dict[str, Any], *, state: str | None = None) -> dict[str, Any]: + # The accepted invoice JSON («json») is not kept: it repeats the invoice and buyer data. + raw = { + "provider": MOTAMED_ASA_PROVIDER, + "asatsp_id": info.get("asatspId"), + "tax_id": info.get("taxId"), + "status": info.get("status"), + "issue": info.get("issue"), + "reference_number": info.get("refrenceNumber"), + "status_inquiry": info.get("statusInquery"), + "article6_status": info.get("article6Status"), + "fiscal_id": info.get("fiscalId"), + "errors": _errors(info) or None, + } + if state: + raw["state"] = state + return {key: value for key, value in raw.items() if value not in (None, "")} + + +def _record( + db: Session, + document: Document, + info: dict[str, Any], + *, + mode: str, + status: str, + error_message: str | None = None, + record_tax_id: bool = True, +) -> dict[str, Any]: + extra = dict(document.extra_info or {}) + asatsp_id = info.get("asatspId") + if asatsp_id: + ids = dict(extra.get("asa_invoice_ids_by_mode") or {}) + ids[mode] = int(asatsp_id) + extra["asa_invoice_ids_by_mode"] = ids + extra["asa_latest_invoice_id"] = int(asatsp_id) + if info.get("taxId"): + tax_ids = dict(extra.get("asa_tax_ids_by_mode") or {}) + tax_ids[mode] = str(info["taxId"]) + extra["asa_tax_ids_by_mode"] = tax_ids + if info.get("fiscalId"): + extra["asa_fiscal_id"] = info["fiscalId"] + document.extra_info = extra + db.add(document) + db.flush() + return { + "mode": MOTAMED_ASA_PROVIDER, + "provider": MOTAMED_ASA_PROVIDER, + "status": status, + "tracking_code": str(asatsp_id) if asatsp_id else extra.get("tax_tracking_code"), + "tax_id": str(info["taxId"]) if record_tax_id and info.get("taxId") else None, + "error_message": error_message, + "raw_response": _raw(info, state="submitted"), + "sent_at": dt.datetime.utcnow().isoformat(), + } + + +def _rejected( + response: dict[str, Any], + item: dict[str, Any] | None = None, + *, + code: str = "MOTAMED_ASA_INVOICE_REJECTED", +) -> ApiError: + messages = _errors(item or {}) + errors = response.get("errors") if isinstance(response.get("errors"), list) else [] + for error in errors: + if isinstance(error, dict) and error.get("message"): + text = str(error["message"]) + if text not in messages: + messages.append(text) + if not messages and response.get("message"): + messages.append(str(response["message"])) + return ApiError( + code, + "؛ ".join(messages) or "معتمد آسا درخواست را نپذیرفت.", + http_status=400, + details={ + "provider": MOTAMED_ASA_PROVIDER, + "trace_id": response.get("traceId"), + "errors": [ + {key: error.get(key) for key in ("code", "path", "field", "message") if error.get(key)} + for error in errors + if isinstance(error, dict) + ], + }, + ) + + +def _first_item(response: dict[str, Any]) -> dict[str, Any] | None: + data = response.get("data") + if isinstance(data, list): + return next((item for item in data if isinstance(item, dict)), None) + return None + + +def _inquire_one(client: MotamedAsaClient, token: str, internal_id: str) -> dict[str, Any] | None: + items = client.inquire_internal_ids(token, [internal_id]) + info = items[0] if items else None + return None if _not_found(info) else info + + +def _duplicate_internal_id(response: dict[str, Any], item: dict[str, Any] | None) -> bool: + texts = _errors(item or {}) + for error in response.get("errors") or []: + if isinstance(error, dict): + texts.append(f"{error.get('path') or ''} {error.get('message') or ''}") + return any("internalId" in text and "قبلاً" in text for text in texts) + + +def _description(document: Document) -> str | None: + text = str(document.description or "").strip() + return text[:1000] or None + + +# --- Sending ---------------------------------------------------------------------------------- + + +def _send_or_update( + db: Session, + client: MotamedAsaClient, + token: str, + document: Document, + internal_id: str, + data: dict[str, Any], + *, + mode: str, + fiscal_id: str | None, + item_fields: dict[str, Any] | None = None, +) -> dict[str, Any]: + current = _inquire_one(client, token, internal_id) + if current is not None: + status, error = _hesabix_status(current) + if status in ("pending", "finalized"): + return _record(db, document, current, mode=mode, status=status) + if mode == "return": + # editInvoice takes a return's Body as the rows left after it, not as returned goods, so a + # rejected return is not rewritten from here. + raise ApiError( + "MOTAMED_ASA_RETURN_REJECTED", + "برگشت از فروش این سند پیش‌تر به معتمد آسا رسیده و پذیرفته نشده است" + + (f" ({error})" if error else "") + + "؛ آن را در پنل معتمد آسا اصلاح و ارسال کنید.", + http_status=409, + ) + # Rejected or never sent: a new version of the same invoice (same serial) is sent. + response = client.edit_invoice( + token, + { + "uuid": str(uuid.uuid4()), + "internalId": internal_id, + "send": True, + "confirmCorrection": False, + "description": _description(document), + "data": data, + }, + ) + outcome = str((response.get("edit") or {}).get("outcome") or "") + if outcome == "unchanged": + queued = client.queue_invoices(token, [internal_id]) + if queued.get("result") != 1: + raise _rejected(queued) + return _record(db, document, current, mode=mode, status="pending") + if response.get("result") == 1 and outcome in ("draftUpdated", "paymentUpdated", "correctionIssued"): + return _record(db, document, _first_item(response) or current, mode=mode, status="pending") + raise _rejected(response, _first_item(response)) + + item_request: dict[str, Any] = { + "internalId": internal_id, + "send": True, + "description": _description(document), + **(item_fields or {}), + "data": data, + } + if fiscal_id: + item_request["fiscalId"] = fiscal_id + try: + response = client.send_invoices( + token, + {"uuid": str(uuid.uuid4()), "data": [{k: v for k, v in item_request.items() if v is not None}]}, + ) + except MotamedAsaApiError as exc: + if not exc.is_transient: + raise + # The save may have committed remotely; the internalId finds it without a second save. + found = _inquire_one(client, token, internal_id) + if found is None: + raise + status, error = _hesabix_status(found) + return _record(db, document, found, mode=mode, status=status or "pending", error_message=error) + + item = _first_item(response) + if item is not None and item.get("asatspId") and _phase(item) != _PHASE_ERROR: + return _record(db, document, item, mode=mode, status="pending") + if _duplicate_internal_id(response, item): + found = _inquire_one(client, token, internal_id) + if found is not None: + status, error = _hesabix_status(found) + return _record(db, document, found, mode=mode, status=status or "pending", error_message=error) + raise _rejected(response, item) + + +def _correct( + db: Session, + client: MotamedAsaClient, + token: str, + document: Document, + internal_id: str, + data: dict[str, Any], +) -> dict[str, Any]: + request_uuid = str(uuid.uuid4()) + try: + response = client.edit_invoice( + token, + { + "uuid": request_uuid, + "internalId": internal_id, + "send": True, + # The user asked for the correction in Hesabix; ASA must not wait for a second confirmation. + "confirmCorrection": True, + "description": _description(document), + "data": data, + }, + ) + except MotamedAsaApiError as exc: + if not exc.is_transient: + raise + latest = _inquire_one(client, token, internal_id) + if latest is not None and _issue(latest) == _ISSUE_CORRECTION: + return _record(db, document, latest, mode="corrective", status="pending") + raise + edit = response.get("edit") or {} + outcome = str(edit.get("outcome") or "") + if outcome == "unchanged": + raise ApiError( + "MOTAMED_ASA_NOTHING_TO_CORRECT", + "این صورتحساب با نسخهٔ ثبت‌شده در سامانهٔ مؤدیان فرقی ندارد؛ صورتحساب اصلاحی صادر نشد.", + http_status=409, + ) + if response.get("result") == 1 and outcome in ("correctionIssued", "draftUpdated", "paymentUpdated"): + item = dict(_first_item(response) or {}) + if edit.get("taxId") and not item.get("taxId"): + item["taxId"] = edit["taxId"] + return _record(db, document, item, mode="corrective", status="pending") + raise _rejected(response, _first_item(response)) + + +def _cancel( + db: Session, + client: MotamedAsaClient, + token: str, + document: Document, + internal_id: str, +) -> dict[str, Any]: + cancel_id = _cancel_internal_id(internal_id) + existing = _inquire_one(client, token, cancel_id) + if existing is not None and _issue(existing) == _ISSUE_CANCELLATION: + status, error = _hesabix_status(existing) + return _record(db, document, existing, mode="cancel", status=status or "pending", + error_message=error, record_tax_id=False) + body = { + "uuid": str(uuid.uuid4()), + "internalId": internal_id, + "cancelInternalId": cancel_id, + "send": True, + "description": _description(document), + } + try: + response = client.cancel_invoice(token, {k: v for k, v in body.items() if v is not None}) + except MotamedAsaApiError as exc: + if not exc.is_transient: + raise + found = _inquire_one(client, token, cancel_id) + if found is None: + raise + return _record(db, document, found, mode="cancel", status="pending", record_tax_id=False) + if response.get("result") == -2: + found = _inquire_one(client, token, cancel_id) + if found is not None: + status, error = _hesabix_status(found) + return _record(db, document, found, mode="cancel", status=status or "pending", + error_message=error, record_tax_id=False) + item = _first_item(response) + if response.get("result") == 1 and item is not None and item.get("asatspId"): + return _record(db, document, item, mode="cancel", status="pending", record_tax_id=False) + raise _rejected(response, item) + + +def motamed_asa_return_reference_tax_id(db: Session, document: Document) -> str: + """ + The tax id of the sale a return refers to. Any registered invoice of the reference's + chain will do: ASA finds the chain's latest itself (returnRows "returned"). + """ + reference = resolve_reference_document(db, int(document.business_id), document) + if reference is None: + raise ApiError( + "TAX_REFERENCE_INVOICE_MISSING", + "برای برگشت از فروش، فاکتور مرجع (فروش اصلی) باید مشخص شود.", + http_status=400, + ) + reference_extra = reference.extra_info or {} + if reference_extra.get("tax_submission_provider") != MOTAMED_ASA_PROVIDER: + raise ApiError( + "MOTAMED_ASA_REFERENCE_OTHER_PROVIDER", + "فاکتور مرجع از طریق معتمد آسا ارسال نشده است؛ برگشت آن را از همان روشی بفرستید که فاکتور مرجع با آن ارسال شده است.", + http_status=409, + ) + tax_id = str(reference_extra.get("tax_moadian_taxid") or "").strip() + if len(tax_id) != 22: + raise ApiError( + "MOTAMED_ASA_REFERENCE_NOT_REGISTERED", + "شماره مالیاتی فاکتور مرجع از معتمد آسا ثبت نشده است؛ پس از ثبت آن در سامانهٔ مؤدیان، برگشت از فروش را بفرستید.", + http_status=409, + ) + return tax_id + + +def send_document_via_motamed_asa( + db: Session, + document: Document, + tax_setting: TaxSetting, + invoice_dto: InvoiceDto, + *, + submission_mode: str, +) -> dict[str, Any]: + business_id = int(document.business_id) + internal_id = motamed_asa_internal_id(document) + extra = dict(document.extra_info or {}) + extra["tax_submission_provider"] = MOTAMED_ASA_PROVIDER + extra["asa_internal_id"] = internal_id + extra["tax_provider_operation"] = submission_mode + document.extra_info = extra + db.add(document) + db.flush() + + def operation(client: MotamedAsaClient, token: str, account: Any) -> dict[str, Any]: + if submission_mode == "cancel": + return _cancel(db, client, token, document, internal_id) + if submission_mode == "corrective": + data = build_motamed_asa_invoice(invoice_dto, document_id=int(document.id), subject=_ISSUE_CORRECTION) + return _correct(db, client, token, document, internal_id, data) + fiscal_id = str(account.memory_number or "").strip() or None + if submission_mode == "return": + # The return document's own lines; ASA matches them to the reference rows (API v2 05, «ارسال اقلام برگشتی»). + data = build_motamed_asa_invoice(invoice_dto, document_id=int(document.id), subject=_ISSUE_RETURN) + data["Header"]["irtaxid"] = motamed_asa_return_reference_tax_id(db, document) + return _send_or_update( + db, client, token, document, internal_id, data, + mode=submission_mode, fiscal_id=fiscal_id, item_fields={"returnRows": "returned"}, + ) + data = build_motamed_asa_invoice(invoice_dto, document_id=int(document.id), subject=_ISSUE_ORIGINAL) + return _send_or_update(db, client, token, document, internal_id, data, mode=submission_mode, fiscal_id=fiscal_id) + + try: + return motamed_asa_business_call(db, business_id, operation) + except MotamedAsaApiError as exc: + if exc.is_transient: + raise ApiError( + "MOTAMED_ASA_RESULT_UNKNOWN", + "نتیجهٔ عملیات معتمد آسا نامشخص است؛ وضعیت آن را استعلام کنید و تا روشن شدن نتیجه دوباره نفرستید.", + http_status=502, + details={"provider": MOTAMED_ASA_PROVIDER, "operation": submission_mode}, + ) from exc + raise ApiError( + "MOTAMED_ASA_SUBMISSION_FAILED", + str(exc), + http_status=exc.status_code if exc.status_code and 400 <= exc.status_code < 500 else 400, + details={"provider": MOTAMED_ASA_PROVIDER, "code": exc.code}, + ) from exc + + +# --- Inquiry ---------------------------------------------------------------------------------- + + +def _inquiry_key(document: Document) -> str: + extra = document.extra_info or {} + internal_id = motamed_asa_internal_id(document) + if extra.get("tax_last_submission_mode") == "cancel" or extra.get("tax_provider_operation") == "cancel": + return _cancel_internal_id(internal_id) + return internal_id + + +def _document_result(document: Document, info: dict[str, Any] | None) -> dict[str, Any]: + """ + The document's state from the latest invoice of its chain. A later invoice in + the chain (a correction, return or cancellation registered afterwards) means + the document's own invoice was registered by the tax organisation. + """ + extra = document.extra_info or {} + mode = str(extra.get("tax_last_submission_mode") or extra.get("tax_provider_operation") or "normal") + updates: dict[str, Any] = {} + if info is None or _not_found(info): + return {"status": "unknown", "error_message": None, "raw": None, "updates": updates} + issue = _issue(info) + own_issue = {"normal": _ISSUE_ORIGINAL, "corrective": _ISSUE_CORRECTION, "return": _ISSUE_RETURN, + "cancel": _ISSUE_CANCELLATION}.get(mode, _ISSUE_ORIGINAL) + own_tax_id = (extra.get("asa_tax_ids_by_mode") or {}).get(mode) + is_own = issue == own_issue and (mode != "return" or not own_tax_id or own_tax_id == info.get("taxId")) + + if is_own: + status, error = _hesabix_status(info) + if mode == "cancel" and status == "finalized": + updates["tax_cancelled_in_modian"] = True + elif mode in ("normal", "corrective", "return") and info.get("taxId"): + updates["tax_moadian_taxid"] = str(info["taxId"]) + # The کارپوشه status and Article 6 status describe this invoice only, not a later one of its chain. + if info.get("statusInquery"): + updates["tax_provider_invoice_status"] = str(info["statusInquery"]) + if info.get("article6Status"): + updates["tax_article6_status"] = normalize_article6_status(info["article6Status"]) or str(info["article6Status"]) + else: + status, error = "finalized", None + if issue == _ISSUE_CANCELLATION and _phase(info) == _PHASE_SUCCESS and mode != "return": + updates["tax_cancelled_in_modian"] = True + return {"status": status, "error_message": error, "raw": _raw(info), "updates": updates} + + +def motamed_asa_inquire_documents( + db: Session, + business_id: int, + documents: list[Document], +) -> list[tuple[Document, dict[str, Any]]]: + """Latest API v2 state of each document, read in batches of 250 internalIds.""" + keys = [_inquiry_key(document) for document in documents] + + def operation(client: MotamedAsaClient, token: str, _account: Any) -> list[dict[str, Any]]: + answers: list[dict[str, Any]] = [] + for start in range(0, len(keys), _INQUIRY_BATCH): + answers.extend(client.inquire_internal_ids(token, keys[start:start + _INQUIRY_BATCH])) + return answers + + try: + answers = motamed_asa_business_call(db, business_id, operation) + except MotamedAsaApiError as exc: + raise ApiError("MOTAMED_ASA_STATUS_INQUIRY_FAILED", str(exc), http_status=502 if exc.is_transient else 400) from exc + return [(document, _document_result(document, info)) for document, info in zip(documents, answers)] + + +# --- Payments registered in the کارپوشه (API v2 docs, section 08C) ------------------------------ + + +def _payments_internal_id(document: Document) -> str: + extra = document.extra_info or {} + if extra.get("tax_submission_provider") != MOTAMED_ASA_PROVIDER or not extra.get("asa_internal_id"): + raise ApiError( + "MOTAMED_ASA_PAYMENTS_NOT_APPLICABLE", + "ثبت پرداخت در کارپوشه فقط برای صورت‌حساب‌هایی است که از طریق معتمد آسا ارسال شده‌اند.", + http_status=409, + ) + return str(extra["asa_internal_id"]) + + +def _payment_view(row: dict[str, Any]) -> dict[str, Any]: + registration = row.get("registration") if isinstance(row.get("registration"), dict) else {} + return { + "id": row.get("id"), + "type": row.get("type"), + "date_time": row.get("dateTime"), + "timestamp": row.get("timestamp"), + "price": row.get("price"), + "trace_no": row.get("traceNo"), + "terminal_number": row.get("terminalNumber"), + "description": row.get("description"), + "locked": row.get("locked") is True, + "registration_status": registration.get("status"), + "registration_code": registration.get("code"), + "registration_message": registration.get("message"), + "registered_amount": registration.get("registeredAmount"), + "registered_at": registration.get("registeredAt"), + } + + +def _payments_view(response: dict[str, Any]) -> dict[str, Any]: + info = _first_item(response) or {} + eligibility = info.get("paymentRegistration") if isinstance(info.get("paymentRegistration"), dict) else {} + rows = info.get("payments") if isinstance(info.get("payments"), list) else [] + return { + "tax_id": info.get("taxId"), + "eligible": eligibility.get("eligible") is True, + "rows_locked": eligibility.get("rowsLocked") is True, + "reason_code": eligibility.get("code"), + "reason": eligibility.get("reason"), + "payments": [_payment_view(row) for row in rows if isinstance(row, dict)], + } + + +def _digits(value: Any, *, field: str, label: str, max_length: int, index: int) -> str | None: + text = str(value or "").strip().translate(str.maketrans("۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩", "01234567890123456789")) + if not text: + return None + if not text.isdigit() or len(text) > max_length: + raise ApiError( + "MOTAMED_ASA_PAYMENT_INVALID", + f"ردیف {index}: {label} فقط رقم و حداکثر {max_length} رقم است.", + http_status=400, + details={"row": index, "field": field}, + ) + return text + + +def build_motamed_asa_payment_rows(payments: Any) -> list[dict[str, Any]]: + """The registerPayment rows for the payments entered in Hesabix; each row is checked before sending.""" + if not isinstance(payments, list) or not 1 <= len(payments) <= _PAYMENT_ROWS_MAX: + raise ApiError( + "MOTAMED_ASA_PAYMENT_INVALID", + f"بین ۱ تا {_PAYMENT_ROWS_MAX} ردیف پرداخت بفرستید.", + http_status=400, + ) + rows: list[dict[str, Any]] = [] + for index, payment in enumerate(payments, start=1): + if not isinstance(payment, dict): + raise ApiError("MOTAMED_ASA_PAYMENT_INVALID", f"ردیف {index} پرداخت معتبر نیست.", http_status=400) + try: + payment_type = int(payment.get("type")) + except (TypeError, ValueError): + payment_type = 0 + if payment_type not in _PAYMENT_TYPES: + raise ApiError( + "MOTAMED_ASA_PAYMENT_INVALID", f"ردیف {index}: روش پرداخت را انتخاب کنید.", + http_status=400, details={"row": index, "field": "type"}, + ) + timestamp = _unix_ms(payment.get("timestamp")) + if not timestamp or timestamp <= 0: + raise ApiError( + "MOTAMED_ASA_PAYMENT_INVALID", f"ردیف {index}: تاریخ و زمان پرداخت را وارد کنید.", + http_status=400, details={"row": index, "field": "timestamp"}, + ) + price = _decimal(payment.get("price")) + if price <= 0 or price != price.to_integral_value() or len(str(int(price))) > 18: + raise ApiError( + "MOTAMED_ASA_PAYMENT_INVALID", f"ردیف {index}: مبلغ پرداخت باید عدد ریالی صحیح و بزرگ‌تر از صفر باشد.", + http_status=400, details={"row": index, "field": "price"}, + ) + row: dict[str, Any] = { + "type": payment_type, + "dateTime": str(timestamp), + "price": int(price), + "traceNo": _digits(payment.get("trace_no"), field="trace_no", label="شماره پیگیری", max_length=14, index=index), + "terminalNumber": _digits( + payment.get("terminal_number"), field="terminal_number", label="شماره پایانه", max_length=8, index=index + ), + "description": str(payment.get("description") or "").strip()[:500] or None, + } + rows.append({key: value for key, value in row.items() if value is not None}) + return rows + + +def motamed_asa_invoice_payments(db: Session, business_id: int, document: Document) -> dict[str, Any]: + """Every payment row of the invoice at ASA with its registration status in the کارپوشه.""" + internal_id = _payments_internal_id(document) + try: + response = motamed_asa_business_call( + db, business_id, lambda client, token, _account: client.inquire_payments(token, internal_id) + ) + except MotamedAsaApiError as exc: + raise ApiError("MOTAMED_ASA_PAYMENTS_UNAVAILABLE", str(exc), http_status=502 if exc.is_transient else 400) from exc + if response.get("result") != 1: + raise _rejected(response, code="MOTAMED_ASA_PAYMENTS_UNAVAILABLE") + return _payments_view(response) + + +def register_motamed_asa_payments( + db: Session, + business_id: int, + document: Document, + payments: Any, +) -> dict[str, Any]: + """ + Adds payment rows to a sent invoice and registers them in the کارپوشه + (registerPayment). Rows already held by the tax system cannot be changed; + a lost answer is never re-sent blindly: the rows are read back instead. + """ + internal_id = _payments_internal_id(document) + rows = build_motamed_asa_payment_rows(payments) + request = {"uuid": str(uuid.uuid4()), "internalId": internal_id, "payments": rows} + + def operation(client: MotamedAsaClient, token: str, _account: Any) -> dict[str, Any]: + try: + return client.register_payments(token, request) + except MotamedAsaApiError as exc: + if not exc.is_transient: + raise + # The request may have been saved: show the rows as ASA holds them now. + answer = client.inquire_payments(token, internal_id) + answer["_state"] = "result_unknown" + return answer + + try: + response = motamed_asa_business_call(db, business_id, operation) + except MotamedAsaApiError as exc: + raise ApiError("MOTAMED_ASA_PAYMENTS_UNAVAILABLE", str(exc), http_status=502 if exc.is_transient else 400) from exc + if response.get("result") != 1: + raise _rejected(response, code="MOTAMED_ASA_PAYMENT_REJECTED") + view = _payments_view(response) + view["result_unknown"] = response.get("_state") == "result_unknown" + extra = dict(document.extra_info or {}) + extra["tax_payments_registered_at"] = dt.datetime.utcnow().isoformat() + document.extra_info = extra + db.add(document) + return view diff --git a/hesabixAPI/app/services/tax_auto_inquiry_service.py b/hesabixAPI/app/services/tax_auto_inquiry_service.py index 7b36abaa..c5f76433 100755 --- a/hesabixAPI/app/services/tax_auto_inquiry_service.py +++ b/hesabixAPI/app/services/tax_auto_inquiry_service.py @@ -13,6 +13,7 @@ from sqlalchemy import and_ from adapters.db.models.document import Document from adapters.db.models.tax_setting import TaxSetting +from app.services.motamed_asa_provider_service import MOTAMED_ASA_PROVIDER from app.services.tax_submission_service import inquire_tax_status logger = logging.getLogger(__name__) @@ -128,7 +129,31 @@ def auto_inquire_pending_invoices( if not tax_setting: logger.warning(f"Tax settings not found for business {bid}") continue - + + # «معتمد آسا» invoices are inquired from ASA, not from the tax system with the business's own key. + asa_docs = [ + doc for doc in docs + if (doc.extra_info or {}).get("tax_submission_provider") == MOTAMED_ASA_PROVIDER + ] + if asa_docs: + asa_ids = {int(doc.id) for doc in asa_docs} + docs = [doc for doc in docs if int(doc.id) not in asa_ids] + try: + response = inquire_tax_status(db, bid, invoice_ids=sorted(asa_ids)) + db.commit() + total_inquired += len(response.get("results") or []) + for doc in asa_docs: + extra = doc.extra_info or {} + all_results.append({ + "invoice_id": doc.id, + "business_id": bid, + "tracking_code": extra.get("tax_tracking_code"), + "status": extra.get("tax_status"), + }) + except Exception as e: + logger.error(f"Error inquiring motamed_asa status for business {bid}: {e}", exc_info=True) + db.rollback() + # جمع‌آوری tracking codes tracking_codes: List[str] = [] doc_by_tracking: Dict[str, Document] = {} diff --git a/hesabixAPI/app/services/tax_health_check.py b/hesabixAPI/app/services/tax_health_check.py index 49b1379b..2baac641 100755 --- a/hesabixAPI/app/services/tax_health_check.py +++ b/hesabixAPI/app/services/tax_health_check.py @@ -45,6 +45,14 @@ def check_tax_system_health( .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", diff --git a/hesabixAPI/app/services/tax_provider_service.py b/hesabixAPI/app/services/tax_provider_service.py index 8066ddac..2661c743 100644 --- a/hesabixAPI/app/services/tax_provider_service.py +++ b/hesabixAPI/app/services/tax_provider_service.py @@ -174,7 +174,10 @@ def get_business_provider_state(db: Session, business_id: int) -> dict[str, Any] .first() ) credential = get_provider_credential(db) + from app.services.motamed_asa_provider_service import motamed_asa_provider_state + return { + **motamed_asa_provider_state(db, int(business_id)), "submission_provider": setting.submission_provider if setting else DIRECT_PROVIDER, "fanava_available": bool(credential and credential.is_active and credential.username_encrypted and credential.password_encrypted and credential.broker_code), "enrollment_prefill": { @@ -361,6 +364,17 @@ def select_business_provider( enrollment: dict[str, Any] | None = None, ) -> dict[str, Any]: provider_code = str(provider_code or "").strip().lower() + from app.services.motamed_asa_provider_service import MOTAMED_ASA_PROVIDER, start_motamed_asa_onboarding + + if provider_code == MOTAMED_ASA_PROVIDER: + # ASA signs as the trusted company: the business's own private key and memory id are not needed. + return start_motamed_asa_onboarding( + db, + business_id=int(business_id), + consent=consent, + consented_by_user_id=consented_by_user_id, + economic_code=(enrollment or {}).get("economic_code"), + ) if provider_code not in {DIRECT_PROVIDER, FANAVA_PROVIDER}: raise ApiError("INVALID_TAX_PROVIDER", "روش ارسال مالیاتی نامعتبر است.", http_status=400) setting = db.query(TaxSetting).filter(TaxSetting.business_id == int(business_id)).first() diff --git a/hesabixAPI/app/services/tax_setting_service.py b/hesabixAPI/app/services/tax_setting_service.py index 2b78ed6b..2111f6c8 100755 --- a/hesabixAPI/app/services/tax_setting_service.py +++ b/hesabixAPI/app/services/tax_setting_service.py @@ -173,7 +173,8 @@ def serialize_tax_setting( 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 + "submission_provider": "moadian_direct", "fanava_available": False, "fanava_account": None, + "motamed_asa_available": False, "motamed_asa_account": None, } return { "business_id": int(business_id), @@ -215,6 +216,8 @@ def serialize_tax_setting( "submission_provider": getattr(setting, "submission_provider", "moadian_direct"), "fanava_available": False, "fanava_account": None, + "motamed_asa_available": False, + "motamed_asa_account": None, } return { diff --git a/hesabixAPI/app/services/tax_submission_service.py b/hesabixAPI/app/services/tax_submission_service.py index 970d1e0e..915f7463 100755 --- a/hesabixAPI/app/services/tax_submission_service.py +++ b/hesabixAPI/app/services/tax_submission_service.py @@ -28,6 +28,7 @@ from app.services.tax_reference_service import ( get_document_extra, ) from app.core.moadian_plugin_dependency import ensure_moadian_plugin_active +from app.services.motamed_asa_provider_service import MOTAMED_ASA_PROVIDER logger = logging.getLogger(__name__) @@ -139,6 +140,23 @@ def normalize_stored_tax_status(extra: dict | None) -> str: return status +def _resolve_submission_provider(document: Document, tax_setting: TaxSetting) -> str: + # Keep each invoice bound to its original provider. Older direct invoices + # predate this field, so infer their provider from a prior send attempt. + extra = document.extra_info or {} + stored_provider = str(extra.get("tax_submission_provider") or "").strip().lower() + has_legacy_send = bool( + extra.get("tax_last_send_at") + or extra.get("tax_tracking_code") + or extra.get("tax_provider_last_response") + ) + return stored_provider or ( + "moadian_direct" + if has_legacy_send + else str(getattr(tax_setting, "submission_provider", "moadian_direct") or "moadian_direct").strip().lower() + ) + + def _resolve_submission_mode(document: Document, submission_mode: str | None) -> str: mode = (submission_mode or "").strip().lower() doc_type = (document.document_type or "").lower() @@ -185,7 +203,16 @@ def send_document_to_tax_system( http_status=400, ) - if not ( + provider_code = _resolve_submission_provider(document, tax_setting) + if provider_code == MOTAMED_ASA_PROVIDER: + # The trusted company signs with its own key and memory; only the seller's economic code is needed. + if not tax_setting.economic_code: + raise ApiError( + "TAX_SETTINGS_INCOMPLETE", + "کد اقتصادی کسب‌وکار در تنظیمات سامانه مودیان ثبت نشده است.", + http_status=400, + ) + elif not ( tax_setting.tax_memory_id and tax_setting.private_key and tax_setting.economic_code @@ -228,7 +255,8 @@ def send_document_to_tax_system( irtaxid=irtaxid, ) - if mode == "normal": + if mode == "normal" and provider_code != MOTAMED_ASA_PROVIDER: + # «معتمد آسا» issues the tax id itself; it is stored from its answer. taxid = compute_taxid_for_document(document, tax_setting) persist_taxid_on_document(document, taxid, db) @@ -250,21 +278,8 @@ def send_document_to_tax_system( details=rate_info, ) - # Keep each invoice bound to its original provider. Older direct invoices - # predate this field, so infer their provider from a prior send attempt. extra = dict(document.extra_info or {}) - stored_provider = str(extra.get("tax_submission_provider") or "").strip().lower() - has_legacy_send = bool( - extra.get("tax_last_send_at") - or extra.get("tax_tracking_code") - or extra.get("tax_provider_last_response") - ) - provider_code = stored_provider or ( - "moadian_direct" - if has_legacy_send - else str(getattr(tax_setting, "submission_provider", "moadian_direct") or "moadian_direct").strip().lower() - ) - if provider_code not in {"moadian_direct", "fanava"}: + if provider_code not in {"moadian_direct", "fanava", MOTAMED_ASA_PROVIDER}: raise ApiError("TAX_PROVIDER_UNSUPPORTED", "روش ارسال مالیاتی این کسب‌وکار پشتیبانی نمی‌شود.", http_status=400) if provider_code == "fanava" and bool(getattr(tax_setting, "sandbox_mode", False)): raise ApiError( @@ -272,6 +287,12 @@ def send_document_to_tax_system( "فن‌آوا محیط آزمایشی ندارد؛ حالت آزمایشی را خاموش کنید یا روش ارسال مستقیم را انتخاب کنید.", http_status=400, ) + if provider_code == MOTAMED_ASA_PROVIDER and bool(getattr(tax_setting, "sandbox_mode", False)): + raise ApiError( + "MOTAMED_ASA_SANDBOX_UNAVAILABLE", + "ارسال از طریق معتمد آسا فقط در محیط اصلی سامانهٔ مؤدیان انجام می‌شود؛ حالت آزمایشی را خاموش کنید.", + http_status=400, + ) extra["tax_submission_provider"] = provider_code document.extra_info = extra db.add(document) @@ -295,8 +316,8 @@ def send_document_to_tax_system( max_retries = settings.tax_system_retry_max_attempts initial_retry_delay = settings.tax_system_retry_initial_delay_seconds # Provider save/send operations can have committed remotely even when the response timed out. - # Fanava reconciles by taxId/status and must never be blindly retried here. - retry_count = 1 if provider_code == "fanava" else max_retries + # Fanava reconciles by taxId/status and «معتمد آسا» by internalId; neither is blindly retried here. + retry_count = 1 if provider_code in ("fanava", MOTAMED_ASA_PROVIDER) else max_retries try: if provider_code == "moadian_direct": @@ -310,6 +331,11 @@ def send_document_to_tax_system( submission = send_document_via_fanava( db, document, tax_setting, invoice_dto, submission_mode=mode ) + elif provider_code == MOTAMED_ASA_PROVIDER: + from app.services.motamed_asa_tax_submission_service import send_document_via_motamed_asa + submission = send_document_via_motamed_asa( + db, document, tax_setting, invoice_dto, submission_mode=mode + ) else: submission = client.send_invoice(invoice_dto) submission.setdefault("provider", provider_code) @@ -381,6 +407,19 @@ def send_document_to_tax_system( } _apply_submission_result(document, submission, db, submission_mode=mode) return submission + if provider_code == MOTAMED_ASA_PROVIDER and getattr(e, "code", None) == "MOTAMED_ASA_RESULT_UNKNOWN": + extra = dict(document.extra_info or {}) + submission = { + "mode": MOTAMED_ASA_PROVIDER, + "provider": MOTAMED_ASA_PROVIDER, + "status": "pending", + "tracking_code": extra.get("tax_tracking_code"), + "error_message": e.message, + "raw_response": {"provider": MOTAMED_ASA_PROVIDER, "state": "result_unknown"}, + "sent_at": datetime.datetime.utcnow().isoformat(), + } + _apply_submission_result(document, submission, db, submission_mode=mode) + return submission # خطاهای validation یا business logic را retry نمی‌کنیم status_code = getattr(e, "status_code", None) if status_code in (400, 401, 403, 404): @@ -536,7 +575,15 @@ def inquire_tax_status( if merged_codes: doc_by_tracking.update(_documents_by_tracking_codes(db, business_id, sorted(merged_codes))) - if not merged_codes: + # «معتمد آسا» is inquired by the document's internalId, so a send whose + # answer was lost (no tracking code yet) can still be inquired. + asa_documents: Dict[int, Document] = { + int(doc.id): doc + for doc in [*documents_by_id.values(), *doc_by_tracking.values()] + if (doc.extra_info or {}).get("tax_submission_provider") == MOTAMED_ASA_PROVIDER + } + + if not merged_codes and not asa_documents: raise ApiError("TAX_TRACKING_CODE_MISSING", "هیچ کد رهگیری معتبری یافت نشد.", http_status=400) tax_setting = ( @@ -560,6 +607,10 @@ def inquire_tax_status( if extra.get("tax_submission_provider") == "fanava": direct_codes.discard(code) fanava_documents[int(doc.id)] = doc + elif extra.get("tax_submission_provider") == MOTAMED_ASA_PROVIDER: + direct_codes.discard(code) + + asa_results = _inquire_motamed_asa_documents(db, business_id, list(asa_documents.values()), now=now) if fanava_documents: from app.services.fanava_tax_submission_service import fanava_status_for_document, map_fanava_inquiry @@ -646,14 +697,70 @@ def inquire_tax_status( else: direct_results = [] - results = direct_results + fanava_results + results = direct_results + fanava_results + asa_results + provider_modes = [code for code, found in (("fanava", fanava_results), (MOTAMED_ASA_PROVIDER, asa_results)) if found] + if (direct_codes and provider_modes) or len(provider_modes) > 1: + mode = "mixed" + elif not direct_codes and provider_modes: + mode = provider_modes[0] + else: + mode = direct_response.get("mode", "fanava") return { - "mode": "mixed" if direct_codes and fanava_results else direct_response.get("mode", "fanava"), + "mode": mode, "results": results, } +def _inquire_motamed_asa_documents( + db: Session, + business_id: int, + documents: List[Document], + *, + now: str, +) -> List[Dict[str, Any]]: + if not documents: + return [] + from app.services.motamed_asa_tax_submission_service import motamed_asa_inquire_documents + + try: + answers = motamed_asa_inquire_documents(db, business_id, documents) + except ApiError as exc: + return [ + { + "reference_number": str((doc.extra_info or {}).get("tax_tracking_code") or ""), + "status": "unknown", + "error_message": exc.message, + "provider": MOTAMED_ASA_PROVIDER, + } + for doc in documents + ] + + results: List[Dict[str, Any]] = [] + for doc, answer in answers: + extra = doc.extra_info or {} + tracking = str(extra.get("tax_tracking_code") or "") + item = { + "reference_number": tracking, + "tracking_code": tracking, + "status": answer["status"], + "error_message": answer["error_message"], + "raw_data": answer["raw"], + "inquiry_at": now, + "provider": MOTAMED_ASA_PROVIDER, + } + _apply_inquiry_result_to_document(doc, item, now=now) + if answer["updates"]: + updated_extra = dict(doc.extra_info or {}) + updated_extra.update(answer["updates"]) + if updated_extra.get("tax_cancelled_in_modian") and not extra.get("tax_cancelled_at"): + updated_extra["tax_cancelled_at"] = now + doc.extra_info = updated_extra + db.add(doc) + results.append(item) + return results + + def enrich_tax_timeline_event(event: Dict[str, Any], extra: dict | None) -> Dict[str, Any]: """افزودن خطاها به رویدادهای تایم‌لاین.""" enriched = dict(event) @@ -704,7 +811,7 @@ def _apply_submission_result( extra["tax_last_send_at"] = submission.get("sent_at") or datetime.datetime.utcnow().isoformat() extra["tax_last_submission_mode"] = submission_mode provider_code = submission.get("provider") or submission.get("mode") - if provider_code in ("moadian_direct", "fanava"): + if provider_code in ("moadian_direct", "fanava", MOTAMED_ASA_PROVIDER): extra["tax_submission_provider"] = provider_code if submission.get("fanava_invoice_id"): extra["fanava_latest_invoice_id"] = int(submission["fanava_invoice_id"]) @@ -712,7 +819,8 @@ def _apply_submission_result( extra["tax_moadian_taxid"] = submission["tax_id"] if submission.get("raw_response"): extra["tax_provider_last_response"] = submission["raw_response"] - if submission_mode == "cancel" and provider_code != "fanava": + # Brokers report a cancellation only once the tax system accepts it (see inquire_tax_status). + if submission_mode == "cancel" and provider_code not in ("fanava", MOTAMED_ASA_PROVIDER): extra["tax_cancelled_in_modian"] = True extra["tax_cancelled_at"] = extra["tax_last_send_at"] if submission_mode == "corrective": @@ -792,6 +900,10 @@ def build_tax_status_fields_for_api(extra: dict | None) -> Dict[str, Any]: "tax_corrective_sent_at": extra.get("tax_corrective_sent_at"), "reference_invoice_id": extra.get("reference_invoice_id"), "reference_tax_id": extra.get("reference_tax_id"), + "tax_submission_provider": extra.get("tax_submission_provider"), + # کارپوشه status (buyer reaction) and Article 6 status, as last inquired through a provider. + "tax_workspace_status": extra.get("tax_provider_invoice_status"), + "tax_article6_status": extra.get("tax_article6_status"), } moadian_errors = extract_moadian_errors_from_extra(extra) if moadian_errors: diff --git a/hesabixAPI/tests/test_motamed_asa_client.py b/hesabixAPI/tests/test_motamed_asa_client.py new file mode 100644 index 00000000..eaee42e9 --- /dev/null +++ b/hesabixAPI/tests/test_motamed_asa_client.py @@ -0,0 +1,137 @@ +"""«معتمد آسا» API v2 client: the three answer conventions it has to read.""" + +from __future__ import annotations + +import json + +import httpx +import pytest + +from app.integrations.motamed_asa.client import MotamedAsaApiError, MotamedAsaClient + + +def _client(handler) -> MotamedAsaClient: + return MotamedAsaClient("https://api-v2.example.test/", transport=httpx.MockTransport(handler)) + + +def test_issue_token_posts_client_credentials() -> None: + seen: dict = {} + + def handler(request: httpx.Request) -> httpx.Response: + seen["url"] = str(request.url) + seen["body"] = json.loads(request.content) + return httpx.Response(200, json={"access_token": "a.b.c", "token_type": "Bearer", "expires_in": 3600}) + + with _client(handler) as client: + token, expires_in = client.issue_token("v2-customer-12", "secret") + + assert (token, expires_in) == ("a.b.c", 3600) + assert seen["url"] == "https://api-v2.example.test/api/auth/v2/token" + assert seen["body"] == { + "grant_type": "client_credentials", + "client_id": "v2-customer-12", + "client_secret": "secret", + } + + +def test_rejected_token_is_unauthorized() -> None: + with _client(lambda request: httpx.Response(401)) as client: + with pytest.raises(MotamedAsaApiError) as error: + client.issue_token("v2-customer-12", "wrong") + assert error.value.status_code == 401 + assert error.value.code == "UNAUTHORIZED" + assert not error.value.is_transient + + +def test_partner_envelope_error_keeps_code_and_message() -> None: + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response( + 409, + json={ + "status": "CONFLICT", + "data": None, + "errors": [{"code": "credentials_already_claimed", "message": "already claimed"}], + "fieldErrors": [], + "correlationId": "c1", + }, + ) + + with _client(handler) as client: + with pytest.raises(MotamedAsaApiError) as error: + client.claim_credentials("partner-token", "6f1c0b9e-0000-4000-8000-000000000001") + assert (error.value.status_code, error.value.code, str(error.value)) == ( + 409, + "credentials_already_claimed", + "already claimed", + ) + + +def test_create_session_unwraps_envelope_and_sends_bearer() -> None: + seen: dict = {} + + def handler(request: httpx.Request) -> httpx.Response: + seen["auth"] = request.headers.get("Authorization") + return httpx.Response(201, json={"status": "OK", "data": {"sessionId": "s-1", "url": "https://x/join/t"}}) + + with _client(handler) as client: + session = client.create_onboarding_session("partner-token", {"reference": "hesabix-business-1"}) + + assert seen["auth"] == "Bearer partner-token" + assert session["url"] == "https://x/join/t" + + +def test_invoice_result_minus_one_is_unauthorized_although_http_200() -> None: + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response(200, json={"result": -1, "traceId": "t", "message": "token expired", "data": []}) + + with _client(handler) as client: + with pytest.raises(MotamedAsaApiError) as error: + client.send_invoices("customer-token", {"uuid": "u", "data": []}) + assert error.value.code == "UNAUTHORIZED" + + +def test_inquiry_keeps_request_order() -> None: + def handler(request: httpx.Request) -> httpx.Response: + ids = json.loads(request.content)["internalIds"] + return httpx.Response(200, json=[{"internalId": value, "asatspId": index + 1, "status": 2} for index, value in enumerate(ids)]) + + with _client(handler) as client: + items = client.inquire_internal_ids("customer-token", ["hesabix-1", "hesabix-2"]) + assert [item["internalId"] for item in items] == ["hesabix-1", "hesabix-2"] + + +def test_inquiry_auth_failure_is_one_item_without_internal_id() -> None: + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response(200, json=[{"status": 3, "error": ["توکن نامعتبر است"]}]) + + with _client(handler) as client: + with pytest.raises(MotamedAsaApiError) as error: + client.inquire_internal_ids("customer-token", ["hesabix-1", "hesabix-2"]) + assert error.value.code == "UNAUTHORIZED" + + +def test_timeout_is_transient() -> None: + def handler(request: httpx.Request) -> httpx.Response: + raise httpx.ReadTimeout("slow", request=request) + + with _client(handler) as client: + with pytest.raises(MotamedAsaApiError) as error: + client.send_invoices("customer-token", {"uuid": "u", "data": []}) + assert error.value.code == "TIMEOUT" + assert error.value.is_transient + + +def test_payment_routes_post_to_register_and_inquire() -> None: + seen: list[tuple[str, dict]] = [] + + def handler(request: httpx.Request) -> httpx.Response: + seen.append((request.url.path, json.loads(request.content))) + return httpx.Response(200, json={"result": 1, "traceId": "t", "data": [{"internalId": "hesabix-1", "payments": []}]}) + + with _client(handler) as client: + client.register_payments("customer-token", {"uuid": "u", "internalId": "hesabix-1", "payments": [{"type": 6}]}) + answer = client.inquire_payments("customer-token", "hesabix-1") + + assert [path for path, _ in seen] == ["/api/invoice/registerPayment", "/api/invoice/inquiryPayment"] + assert seen[1][1] == {"internalId": "hesabix-1"} + assert answer["result"] == 1 diff --git a/hesabixAPI/tests/test_motamed_asa_invoice_payload.py b/hesabixAPI/tests/test_motamed_asa_invoice_payload.py new file mode 100644 index 00000000..9f66d615 --- /dev/null +++ b/hesabixAPI/tests/test_motamed_asa_invoice_payload.py @@ -0,0 +1,275 @@ +"""«معتمد آسا»: the invoice JSON sent to API v2 and the document state read back from it.""" + +from __future__ import annotations + +from types import SimpleNamespace +from unittest.mock import MagicMock + +import pytest + +from app.core.responses import ApiError +from app.integrations.moadian.dto import InvoiceBodyDto, InvoiceDto, InvoiceHeaderDto, InvoicePaymentDto +from app.services import motamed_asa_tax_submission_service as service +from app.services.motamed_asa_tax_submission_service import ( + _document_result, + _hesabix_status, + _payments_internal_id, + build_motamed_asa_invoice, + build_motamed_asa_payment_rows, + motamed_asa_internal_id, + normalize_article6_status, +) + + +def _row(sstid: str, am: int, fee: int, dis: int = 0, vra: int = 10) -> InvoiceBodyDto: + prdis = am * fee + adis = prdis - dis + vam = round(adis * vra / 100) + return InvoiceBodyDto( + sstid=sstid, sstt=f"کالا {sstid[-2:]}", mu="1627", am=am, fee=fee, prdis=prdis, + dis=dis, adis=adis, vra=vra, vam=vam, tsstam=adis + vam, + ) + + +def _dto(body: list[InvoiceBodyDto], *, inty: int = 1, inp: int = 1, ins: int = 1, payments=None) -> InvoiceDto: + header = InvoiceHeaderDto( + taxid="A1B2C3D4E5F6G7H8I9J0K1", indatim=1782940800000, indati2m=1782940800000, + inno="0000000042", inty=inty, inp=inp, ins=ins, tins="14001234567", + tob=2 if inty == 1 else None, tinb="10987654321" if inty == 1 else None, + tprdis=sum(b.prdis for b in body), tdis=sum(b.dis for b in body), + tadis=sum(b.adis for b in body), tvam=sum(b.vam for b in body), todam=0, + tbill=sum(b.adis + b.vam for b in body), tax17=0, + setm=1 if inty == 1 else None, cap=sum(b.adis + b.vam for b in body) if inty == 1 else None, + ) + return InvoiceDto(header=header, body=body, payments=payments or []) + + +def test_original_invoice_drops_hesabix_taxid_and_marks_sale_pattern() -> None: + dto = _dto([_row("2720000114542", 2, 500_000)], inp=4, ins=4) + data = build_motamed_asa_invoice(dto, document_id=42, subject=1) + header = data["Header"] + assert "taxid" not in header and "indati2m" not in header and "tax17" not in header + assert (header["inp"], header["ins"], header["inno"]) == (1, 1, "000000002A") + assert header["tbill"] == sum(row["tsstam"] for row in data["Body"]) + assert data["Body"][0]["sstid"] == "2720000114542" + + +def test_payments_without_type_are_left_out_and_dates_become_unix_ms() -> None: + payments = [ + InvoicePaymentDto(), + InvoicePaymentDto(pmt="3", pdt="2026-07-01T00:00:00+00:00", trn="123"), + ] + data = build_motamed_asa_invoice(_dto([_row("2720000114542", 1, 1000)], payments=payments), document_id=1, subject=1) + assert data["Payments"] == [{"trn": "123", "pdt": 1782864000000, "pmt": 3}] + + +def test_type_two_sends_no_payments() -> None: + data = build_motamed_asa_invoice( + _dto([_row("2720000114542", 1, 1000)], inty=2, payments=[InvoicePaymentDto(pmt=3)]), document_id=1, subject=1 + ) + assert data["Payments"] == [] + + +def test_return_sends_the_return_document_lines_without_the_buyer() -> None: + returned = _dto([_row("2720000114542", 1, 1000, dis=100)], ins=5) + data = build_motamed_asa_invoice(returned, document_id=77, subject=4) + + header = data["Header"] + assert (header["ins"], header["inp"], header["inno"]) == (4, 1, "000000004D") + assert not set(header) & {"tob", "tinb", "bid", "bpc"}, "the buyer of a return comes from the reference" + assert [(row["sstid"], row["am"], row["dis"]) for row in data["Body"]] == [("2720000114542", 1, 100)] + assert header["tbill"] == sum(row["tsstam"] for row in data["Body"]) + + +def _return_document(monkeypatch: pytest.MonkeyPatch, reference_extra: dict | None) -> SimpleNamespace: + reference = None if reference_extra is None else SimpleNamespace(id=42, extra_info=reference_extra) + monkeypatch.setattr(service, "resolve_reference_document", lambda db, business_id, document: reference) + return SimpleNamespace(id=77, business_id=5, extra_info={"reference_invoice_id": 42}) + + +def test_return_refers_to_the_sale_tax_id_asa_gave(monkeypatch: pytest.MonkeyPatch) -> None: + document = _return_document( + monkeypatch, {"tax_submission_provider": "motamed_asa", "tax_moadian_taxid": "A" * 22} + ) + assert service.motamed_asa_return_reference_tax_id(MagicMock(), document) == "A" * 22 + + +@pytest.mark.parametrize( + ("reference_extra", "code"), + [ + (None, "TAX_REFERENCE_INVOICE_MISSING"), + ({"tax_submission_provider": "moadian_direct", "tax_moadian_taxid": "A" * 22}, "MOTAMED_ASA_REFERENCE_OTHER_PROVIDER"), + ({"tax_submission_provider": "motamed_asa"}, "MOTAMED_ASA_REFERENCE_NOT_REGISTERED"), + ], +) +def test_return_needs_a_sale_registered_through_motamed_asa( + monkeypatch: pytest.MonkeyPatch, reference_extra: dict | None, code: str +) -> None: + document = _return_document(monkeypatch, reference_extra) + with pytest.raises(ApiError) as error: + service.motamed_asa_return_reference_tax_id(MagicMock(), document) + assert error.value.code == code + + +def test_return_goes_to_send_as_returned_goods() -> None: + client = MagicMock() + client.inquire_internal_ids.return_value = [{"internalId": "hesabix-77", "status": 3, "error": ["صورتحساب یافت نشد"]}] + client.send_invoices.return_value = {"result": 1, "data": [{"asatspId": 9, "taxId": "B" * 22, "status": 0}]} + document = SimpleNamespace(id=77, description=None, extra_info={}) + data = {"Header": {"ins": 4, "irtaxid": "A" * 22}, "Body": [], "Payments": []} + + result = service._send_or_update( + MagicMock(), client, "token", document, "hesabix-77", data, + mode="return", fiscal_id=None, item_fields={"returnRows": "returned"}, + ) + + item = client.send_invoices.call_args.args[1]["data"][0] + assert item["returnRows"] == "returned" and item["internalId"] == "hesabix-77" + assert (result["status"], result["tax_id"]) == ("pending", "B" * 22) + + +def test_a_rejected_return_is_not_rewritten_as_remaining_rows() -> None: + client = MagicMock() + client.inquire_internal_ids.return_value = [ + {"internalId": "hesabix-77", "asatspId": 9, "issue": 4, "status": 3, "error": ["خطای سازمان"]} + ] + document = SimpleNamespace(id=77, description=None, extra_info={}) + + with pytest.raises(ApiError) as error: + service._send_or_update( + MagicMock(), client, "token", document, "hesabix-77", {"Header": {}, "Body": []}, + mode="return", fiscal_id=None, item_fields={"returnRows": "returned"}, + ) + + assert error.value.code == "MOTAMED_ASA_RETURN_REJECTED" + client.edit_invoice.assert_not_called() + + +@pytest.mark.parametrize( + ("info", "expected"), + [ + ({"status": 0}, ("pending", None)), + ({"status": 1}, ("pending", None)), + ({"status": 2, "statusInquery": "APPROVED"}, ("finalized", None)), + ({"status": 3, "error": ["خطای ۱", "خطای ۲"]}, ("failed", "خطای ۱؛ خطای ۲")), + ({"status": "Success"}, ("finalized", None)), + ], +) +def test_hesabix_status(info: dict, expected: tuple) -> None: + assert _hesabix_status(info) == expected + + +def test_buyer_rejection_keeps_the_invoice_registered() -> None: + # The buyer's reaction is the separate کارپوشه status, not a sending failure. + assert _hesabix_status({"status": 2, "statusInquery": "REJECTED"}) == ("finalized", None) + + +@pytest.mark.parametrize( + ("raw", "expected"), + [ + ("NOT_EXCEEDED", "not_violated"), + ("false", "not_violated"), + ("عدم عدول", "not_violated"), + ("EXCEEDED", "violated"), + ("1", "violated"), + ("عدول", "violated"), + ("SOMETHING_NEW", None), + ("", None), + ], +) +def test_article6_status(raw: str, expected: str | None) -> None: + assert normalize_article6_status(raw) == expected + + +def test_own_invoice_carries_workspace_and_article6_status() -> None: + result = _document_result( + _document(tax_last_submission_mode="normal"), + {"internalId": "hesabix-42", "asatspId": 5, "issue": 1, "status": 2, "taxId": "T" * 22, + "statusInquery": "AWAITING_REACTION", "article6Status": "NOT_EXCEEDED"}, + ) + assert result["updates"]["tax_provider_invoice_status"] == "AWAITING_REACTION" + assert result["updates"]["tax_article6_status"] == "not_violated" + + +def test_later_invoice_status_is_not_copied_to_the_original() -> None: + result = _document_result( + _document(tax_last_submission_mode="normal"), + {"internalId": "hesabix-42", "asatspId": 9, "issue": 4, "status": 2, "statusInquery": "REJECTED"}, + ) + assert "tax_provider_invoice_status" not in result["updates"] + + +def test_payment_rows_are_checked_and_shaped_for_register_payment() -> None: + rows = build_motamed_asa_payment_rows([ + {"type": "6", "timestamp": 1789446000000, "price": "25000000", "trace_no": "۱۳۰۲۳۸۷۸۶۵۶۴۳۱", + "terminal_number": "1302387", "description": " قسط دوم "}, + ]) + assert rows == [{ + "type": 6, "dateTime": "1789446000000", "price": 25000000, "traceNo": "13023878656431", + "terminalNumber": "1302387", "description": "قسط دوم", + }] + + +@pytest.mark.parametrize( + "payment", + [ + {"type": 9, "timestamp": 1789446000000, "price": 1}, + {"type": 3, "timestamp": None, "price": 1}, + {"type": 3, "timestamp": 1789446000000, "price": 0}, + {"type": 3, "timestamp": 1789446000000, "price": "12.5"}, + {"type": 3, "timestamp": 1789446000000, "price": 1, "terminal_number": "123456789"}, + ], +) +def test_invalid_payment_rows_are_refused(payment: dict) -> None: + with pytest.raises(ApiError) as error: + build_motamed_asa_payment_rows([payment]) + assert error.value.code == "MOTAMED_ASA_PAYMENT_INVALID" + + +def test_payments_need_an_invoice_sent_through_motamed_asa() -> None: + with pytest.raises(ApiError) as error: + _payments_internal_id(_document(tax_submission_provider="moadian_direct")) + assert error.value.code == "MOTAMED_ASA_PAYMENTS_NOT_APPLICABLE" + + +def _document(**extra) -> SimpleNamespace: + return SimpleNamespace(id=42, extra_info=extra) + + +def test_internal_id_is_stable() -> None: + assert motamed_asa_internal_id(_document()) == "hesabix-42" + assert motamed_asa_internal_id(_document(asa_internal_id="hesabix-7")) == "hesabix-7" + + +def test_original_follows_its_own_invoice() -> None: + result = _document_result( + _document(tax_last_submission_mode="normal"), + {"internalId": "hesabix-42", "asatspId": 5, "issue": 1, "status": 3, "error": ["رد شد"]}, + ) + assert (result["status"], result["error_message"]) == ("failed", "رد شد") + + +def test_a_later_invoice_in_the_chain_means_the_original_was_registered() -> None: + result = _document_result( + _document(tax_last_submission_mode="normal"), + {"internalId": "hesabix-42", "asatspId": 9, "issue": 4, "status": 1}, + ) + assert result["status"] == "finalized" + assert "tax_cancelled_in_modian" not in result["updates"] + + +def test_accepted_cancellation_marks_the_document_cancelled() -> None: + result = _document_result( + _document(tax_last_submission_mode="cancel"), + {"internalId": "hesabix-42-cancel", "asatspId": 9, "issue": 3, "status": 2}, + ) + assert result["status"] == "finalized" + assert result["updates"]["tax_cancelled_in_modian"] is True + + +def test_unknown_document_keeps_its_status() -> None: + result = _document_result( + _document(tax_last_submission_mode="normal"), + {"internalId": "hesabix-42", "status": 3, "error": ["صورتحساب یافت نشد"]}, + ) + assert result["status"] == "unknown" diff --git a/hesabixAPI/tests/test_motamed_asa_provider_service.py b/hesabixAPI/tests/test_motamed_asa_provider_service.py new file mode 100644 index 00000000..c9dce3e8 --- /dev/null +++ b/hesabixAPI/tests/test_motamed_asa_provider_service.py @@ -0,0 +1,179 @@ +"""«معتمد آسا» connection of a business: partner settings, the one-shot key handover and the token cache.""" + +from __future__ import annotations + +from datetime import datetime, timedelta +from types import SimpleNamespace +from unittest.mock import MagicMock + +import pytest + +from app.core.responses import ApiError +from app.integrations.motamed_asa.client import MotamedAsaApiError +from app.services import motamed_asa_provider_service as service + + +@pytest.fixture(autouse=True) +def _plain_secrets(monkeypatch: pytest.MonkeyPatch) -> None: + # The real helpers need the deployment's encryption key; the flow is what is tested here. + monkeypatch.setattr(service, "_encrypt", lambda value: f"enc:{value}" if value else None) + monkeypatch.setattr(service, "_decrypt", lambda value, _label: value[4:] if value else None) + + +def _account(**values) -> SimpleNamespace: + fields = { + "status": "onboarding", "cartable_id": None, "memory_number": None, "last_error": None, + "username_encrypted": None, "password_encrypted": None, "access_token_encrypted": None, + "token_expires_at": None, "registered_at": None, "last_synced_at": None, + } + fields.update(values) + return SimpleNamespace(**fields) + + +def _session(**credentials) -> dict: + return { + "sessionId": "6f1c0b9e-0000-4000-8000-000000000001", + "status": "completed", + "business": {"companyId": 812, "economicCode": "14001234567", "name": "نمونه", "created": True}, + "memory": {"memoryUniqueId": "A1B2C3", "issued": True}, + "credentials": {"available": True, "claimed": False, "clientId": "v2-customer-812", **credentials}, + } + + +@pytest.mark.parametrize( + ("payload", "code"), + [ + ({"base_url": "http://api-v2.asatsp.ir"}, "INVALID_PROVIDER_URL"), + ({"base_url": "https://api-v2.asatsp.ir/api"}, "INVALID_PROVIDER_URL"), + ({"client_id": "v2-customer-1"}, "INVALID_CLIENT_ID"), + ], +) +def test_partner_settings_are_validated(monkeypatch: pytest.MonkeyPatch, payload: dict, code: str) -> None: + monkeypatch.setattr(service, "get_motamed_asa_credential", lambda db: None) + with pytest.raises(ApiError) as error: + service.save_motamed_asa_credential(MagicMock(), payload) + assert error.value.code == code + + +def test_partner_settings_stay_inactive_without_a_secret(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(service, "get_motamed_asa_credential", lambda db: None) + credential = service.save_motamed_asa_credential( + MagicMock(), {"client_id": "v2-partner-7", "is_active": True} + ) + assert credential.provider_code == "motamed_asa" + assert credential.base_url == "https://api-v2.asatsp.ir" + assert credential.is_active is False + + +def test_handed_over_key_connects_the_business() -> None: + db = MagicMock() + client = MagicMock() + client.claim_credentials.return_value = { + "companyId": 812, "clientId": "v2-customer-812", "clientSecret": "s3cret", "secretIssued": True, + } + account = _account() + setting = SimpleNamespace(submission_provider="moadian_direct") + + service._complete_from_session(db, client, "partner-token", account, setting, _session()) + + assert account.status == "connected" + assert (account.username_encrypted, account.password_encrypted) == ("enc:v2-customer-812", "enc:s3cret") + assert (account.cartable_id, account.memory_number) == (812, "A1B2C3") + assert setting.submission_provider == "motamed_asa" + db.commit.assert_called() + + +def test_existing_key_is_not_handed_over() -> None: + client = MagicMock() + client.claim_credentials.return_value = {"companyId": 812, "clientId": "v2-customer-812", "secretIssued": False} + account = _account() + setting = SimpleNamespace(submission_provider="moadian_direct") + + service._complete_from_session(MagicMock(), client, "partner-token", account, setting, _session()) + + assert account.status == "credentials_required" + assert account.password_encrypted is None + assert setting.submission_provider == "moadian_direct" + + +def test_key_claimed_before_asks_for_manual_entry() -> None: + client = MagicMock() + client.claim_credentials.side_effect = MotamedAsaApiError( + "already", status_code=409, code="credentials_already_claimed" + ) + account = _account() + + service._complete_from_session(MagicMock(), client, "partner-token", account, None, _session()) + + assert account.status == "credentials_required" + assert account.last_error + + +def test_owner_who_did_not_allow_the_handover_is_told_so() -> None: + client = MagicMock() + account = _account() + + service._complete_from_session( + MagicMock(), client, "partner-token", account, None, _session(available=False) + ) + + client.claim_credentials.assert_not_called() + assert account.status == "credentials_required" + + +def test_session_body_prefills_only_what_the_link_needs() -> None: + db = MagicMock() + db.query.return_value.filter.return_value.first.return_value = SimpleNamespace(mobile="+98 912 000 0000") + business = SimpleNamespace(id=5, name="فروشگاه نمونه", owner_id=1, mobile=None) + setting = SimpleNamespace(economic_code="۱۴۰۰۱۲۳۴۵۶۷") + + body = service._session_body(db, business, setting) + + assert body == { + "economicCode": "14001234567", + "businessName": "فروشگاه نمونه", + "reference": "hesabix-business-5", + "issueMemoryUniqueId": True, + "requestCredentials": True, + "mobile": "09120000000", + } + + +def test_customer_token_is_reused_until_close_to_expiry() -> None: + client = MagicMock() + account = _account( + status="connected", + username_encrypted="enc:v2-customer-812", + password_encrypted="enc:s3cret", + access_token_encrypted="enc:cached", + token_expires_at=datetime.utcnow() + timedelta(minutes=30), + ) + assert service._customer_token(MagicMock(), client, account) == "cached" + client.issue_token.assert_not_called() + + account.token_expires_at = datetime.utcnow() + timedelta(seconds=30) + client.issue_token.return_value = ("fresh", 3600) + assert service._customer_token(MagicMock(), client, account) == "fresh" + assert account.access_token_encrypted == "enc:fresh" + + +def test_health_without_a_connected_account_is_not_healthy(monkeypatch: pytest.MonkeyPatch) -> None: + credential = SimpleNamespace(is_active=True, username_encrypted="enc:p", password_encrypted="enc:s", base_url="https://x") + monkeypatch.setattr(service, "get_motamed_asa_credential", lambda db: credential) + monkeypatch.setattr(service, "_get_account", lambda db, business_id, lock=False: _account(status="onboarding")) + + checks = service.motamed_asa_health(MagicMock(), 5) + + assert checks["settings"]["status"] == "error" + + +def test_revoked_customer_key_asks_for_a_new_one() -> None: + client = MagicMock() + client.issue_token.side_effect = MotamedAsaApiError("no", status_code=401, code="UNAUTHORIZED") + account = _account(status="connected", username_encrypted="enc:id", password_encrypted="enc:secret") + + with pytest.raises(ApiError) as error: + service._customer_token(MagicMock(), client, account, force=True) + + assert error.value.code == "MOTAMED_ASA_CREDENTIALS_REJECTED" + assert account.status == "credentials_required" diff --git a/hesabixUI/hesabix_ui/lib/l10n/app_en.arb b/hesabixUI/hesabix_ui/lib/l10n/app_en.arb index 8694a3ee..f2c94b3d 100755 --- a/hesabixUI/hesabix_ui/lib/l10n/app_en.arb +++ b/hesabixUI/hesabix_ui/lib/l10n/app_en.arb @@ -7764,5 +7764,104 @@ "taxProviderActiveBrokerCount": "Active brokers", "taxProviderEnabledHint": "The connection is active. Businesses may register with Fanava after approval.", "taxProviderDisabledHint": "The connection is disabled. Businesses cannot select Fanava.", - "taxProviderSaveBeforeTest": "Save the new broker credentials before testing the connection." + "taxProviderSaveBeforeTest": "Save the new broker credentials before testing the connection.", + "taxSubmissionMotamedAsa": "Send through Motamed ASA", + "taxSubmissionMotamedAsaDescription": "Sign up on the Motamed ASA page; the trusted company signs and sends the invoices, so the business private key and memory ID are not needed here.", + "motamedAsaUnavailable": "The Motamed ASA connection has not been set up by the system administrator yet.", + "motamedAsaSandboxUnavailable": "Motamed ASA sends to the production tax system only. Turn off sandbox mode to select it.", + "motamedAsaEconomicCodeRequired": "Enter the 11 or 14 digit economic code of the business first.", + "motamedAsaConsentTitle": "Send invoices through Motamed ASA", + "motamedAsaConsentDescription": "Motamed ASA is a trusted tax service provider. If you continue, the Motamed ASA sign-up page opens. There the business owner signs in with the one-time code of the tax system, accepts the Motamed ASA terms and allows the API key of this business to be handed to Hesabix.", + "motamedAsaSharedDataTitle": "What Hesabix shares with Motamed ASA", + "motamedAsaSharedDataSignup": "For sign-up: the economic code, the business name and the mobile number of the owner, to fill in the sign-up form.", + "motamedAsaSharedDataInvoices": "For every invoice you send: the data the tax system requires, including the buyer identifiers, items, amounts and payments.", + "motamedAsaSharedDataPurpose": "Motamed ASA uses this data to issue, send and follow up your invoices in the tax system, under its terms and privacy policy. Your choice is not limited: you can change the sending method at any time.", + "motamedAsaTermsLink": "Motamed ASA terms", + "motamedAsaPrivacyLink": "Motamed ASA privacy policy", + "motamedAsaConsentCheckbox": "I have read the above and agree that the data of this business is shared with Motamed ASA for sending invoices.", + "motamedAsaContinueButton": "Continue on Motamed ASA", + "motamedAsaConnected": "This business is connected to Motamed ASA.", + "motamedAsaOnboarding": "Sign-up on Motamed ASA is in progress. When it is finished there, check the connection.", + "motamedAsaCredentialsRequired": "The API key of this business was not received. Enter the client ID and secret from the Motamed ASA panel.", + "motamedAsaNotConnected": "This business is not connected to Motamed ASA.", + "motamedAsaMemoryId": "Fiscal memory ID", + "motamedAsaOpenSignup": "Open the sign-up page", + "motamedAsaEnterCredentials": "Enter API key", + "motamedAsaCheckConnection": "Check connection", + "motamedAsaConnectedSuccess": "The business is connected to Motamed ASA and its invoices are sent through it.", + "motamedAsaSignupOpened": "The Motamed ASA sign-up page was opened. After finishing there, select Check connection.", + "motamedAsaLinkCopyHint": "The page did not open. Open this link in your browser:", + "motamedAsaSyncSuccess": "The Motamed ASA connection status was updated.", + "motamedAsaCredentialsTitle": "Motamed ASA API key", + "motamedAsaCredentialsDescription": "In the Motamed ASA panel, open Business settings › API v2 and copy the client ID and client secret of this business.", + "motamedAsaClientId": "Client ID", + "motamedAsaClientSecret": "Client secret", + "motamedAsaClientIdInvalid": "The client ID looks like v2-customer-12345.", + "motamedAsaSaveCredentials": "Connect", + "motamedAsaAdminTitle": "Motamed ASA connection", + "motamedAsaAdminDescription": "Enter the partner client ID and secret that Motamed ASA issued for Hesabix in its API partners section. Businesses then sign up on the Motamed ASA page, and their API key is handed to Hesabix after the owner agrees.", + "motamedAsaBaseUrl": "Motamed ASA API address", + "motamedAsaPartnerClientId": "Partner client ID", + "motamedAsaPartnerClientIdInvalid": "The partner client ID starts with v2-partner-.", + "motamedAsaPartnerClientSecret": "Partner client secret", + "motamedAsaKeepSecretHint": "Leave empty to keep the saved value.", + "motamedAsaActivate": "Allow sending through Motamed ASA", + "motamedAsaEnabledHint": "Businesses can select Motamed ASA as their sending method.", + "motamedAsaDisabledHint": "Businesses cannot select Motamed ASA.", + "motamedAsaSave": "Save Motamed ASA settings", + "motamedAsaSaved": "Motamed ASA settings were saved.", + "motamedAsaNotConfigured": "The partner client ID and secret are not saved yet.", + "motamedAsaTestSuccess": "Hesabix signed in to Motamed ASA. No business or invoice was created.", + "motamedAsaHostedOnboarding": "Sign-up link", + "motamedAsaCredentialHandover": "API key handover", + "settingsMotamedAsa": "Motamed ASA connection", + "settingsMotamedAsaDescription": "Partner credentials for the Motamed ASA trusted tax company", + "taxWorkspaceStatusColumn": "Workspace status", + "taxWorkspaceStatusNoNeedReaction": "No reaction needed", + "taxWorkspaceStatusAwaitingReaction": "Awaiting buyer reaction", + "taxWorkspaceStatusApproved": "Approved by buyer", + "taxWorkspaceStatusSystemicApproved": "Systemically approved", + "taxWorkspaceStatusImpossibleReaction": "Reaction not possible", + "taxWorkspaceStatusRejected": "Rejected by buyer", + "taxWorkspaceStatusSystemicRejected": "Systemically rejected", + "taxWorkspaceStatusCanceled": "Cancelled", + "taxArticle6Column": "Article 6", + "taxArticle6Violated": "Limit exceeded", + "taxArticle6NotViolated": "Within the limit", + "motamedAsaPaymentsAction": "Payments in the tax workspace", + "motamedAsaPaymentsTitle": "Payment table of invoice", + "motamedAsaPaymentsDescription": "Payments made after the invoice was sent are registered in the tax workspace through Motamed ASA. Enter the amount the buyer paid, including VAT; the tax workspace keeps the share without VAT. Rows held by the tax system cannot be edited or deleted.", + "motamedAsaPaymentsNotEligible": "New payments cannot be registered on this invoice.", + "motamedAsaPaymentsEmpty": "No payment row yet.", + "motamedAsaPaymentsAddRow": "Add payment", + "motamedAsaPaymentsRegister": "Register in tax workspace", + "motamedAsaPaymentsRegistered": "The payments were sent for registration in the tax workspace.", + "motamedAsaPaymentsResultUnknown": "The answer did not arrive. The rows below are what Motamed ASA holds now; check them before sending anything again.", + "motamedAsaPaymentType": "Payment method", + "motamedAsaPaymentDate": "Payment date", + "motamedAsaPaymentAmount": "Amount paid (rial, including VAT)", + "motamedAsaPaymentTraceNo": "Trace number", + "motamedAsaPaymentTerminal": "Terminal number", + "motamedAsaPaymentDescription": "Description", + "motamedAsaPaymentRegisteredAmount": "Registered amount", + "motamedAsaPaymentRemoveRow": "Remove row", + "motamedAsaPaymentAmountInvalid": "Enter a whole rial amount greater than zero.", + "motamedAsaPaymentDigitsInvalid": "Digits only, within the allowed length.", + "motamedAsaPaymentDateRequired": "Choose the payment date of every row.", + "motamedAsaPaymentTypeCheque": "Cheque", + "motamedAsaPaymentTypeBarter": "Offset", + "motamedAsaPaymentTypeCash": "Cash", + "motamedAsaPaymentTypePos": "Card reader (POS)", + "motamedAsaPaymentTypeInternet": "Payment gateway", + "motamedAsaPaymentTypeCard": "Card to card", + "motamedAsaPaymentTypeTransfer": "Bank transfer", + "motamedAsaPaymentTypeOther": "Other", + "motamedAsaPaymentStatusRegistered": "Registered", + "motamedAsaPaymentStatusSentWithInvoice": "Sent with the invoice", + "motamedAsaPaymentStatusQueued": "Queued for registration", + "motamedAsaPaymentStatusNotRegistered": "Goes with the invoice", + "motamedAsaPaymentStatusUnknown": "Result unknown", + "motamedAsaPaymentStatusRejected": "Rejected", + "motamedAsaPaymentStatusFailed": "Failed", + "motamedAsaPaymentStatusNotApplicable": "Not sent" } diff --git a/hesabixUI/hesabix_ui/lib/l10n/app_fa.arb b/hesabixUI/hesabix_ui/lib/l10n/app_fa.arb index bea7a629..86226256 100755 --- a/hesabixUI/hesabix_ui/lib/l10n/app_fa.arb +++ b/hesabixUI/hesabix_ui/lib/l10n/app_fa.arb @@ -7806,5 +7806,104 @@ "taxProviderActiveBrokerCount": "بروکرهای فعال", "taxProviderEnabledHint": "اتصال فعال است و کسب‌وکارها می‌توانند پس از تأیید، در فن‌آوا ثبت شوند.", "taxProviderDisabledHint": "اتصال غیرفعال است و کسب‌وکارها نمی‌توانند فن‌آوا را انتخاب کنند.", - "taxProviderSaveBeforeTest": "ابتدا اعتبارنامه‌های جدید را ذخیره کنید؛ سپس اتصال را بررسی کنید." + "taxProviderSaveBeforeTest": "ابتدا اعتبارنامه‌های جدید را ذخیره کنید؛ سپس اتصال را بررسی کنید.", + "taxSubmissionMotamedAsa": "ارسال از طریق معتمد آسا", + "taxSubmissionMotamedAsaDescription": "ثبت‌نام در صفحه معتمد آسا و ارسال صورت‌حساب‌ها با امضای شرکت معتمد؛ کلید خصوصی و شناسه حافظه کسب‌وکار در اینجا لازم نیست.", + "motamedAsaUnavailable": "اتصال معتمد آسا هنوز توسط مدیر سیستم راه‌اندازی نشده است.", + "motamedAsaSandboxUnavailable": "معتمد آسا فقط به محیط اصلی سامانه مودیان ارسال می‌کند. برای انتخاب آن، حالت آزمایشی را خاموش کنید.", + "motamedAsaEconomicCodeRequired": "ابتدا کد اقتصادی ۱۱ یا ۱۴ رقمی کسب‌وکار را وارد کنید.", + "motamedAsaConsentTitle": "ارسال صورت‌حساب از طریق معتمد آسا", + "motamedAsaConsentDescription": "معتمد آسا از شرکت‌های معتمد ارائه‌دهنده خدمات مالیاتی است. با ادامه، صفحه ثبت‌نام معتمد آسا باز می‌شود؛ مالک کسب‌وکار در آن صفحه با کد یک‌بارمصرف سامانه مودیان وارد می‌شود، قوانین معتمد آسا را می‌پذیرد و اجازه می‌دهد کلید API این کسب‌وکار به حسابیکس تحویل شود.", + "motamedAsaSharedDataTitle": "اطلاعاتی که حسابیکس در اختیار معتمد آسا می‌گذارد", + "motamedAsaSharedDataSignup": "برای ثبت‌نام: کد اقتصادی، نام کسب‌وکار و شماره همراه مالک، برای پر کردن فرم ثبت‌نام.", + "motamedAsaSharedDataInvoices": "برای هر صورت‌حسابی که ارسال می‌کنید: اطلاعاتی که سامانه مودیان لازم دارد، از جمله شناسه خریدار، اقلام، مبالغ و پرداخت‌ها.", + "motamedAsaSharedDataPurpose": "معتمد آسا این اطلاعات را برای صدور، ارسال و پیگیری صورت‌حساب‌های شما در سامانه مودیان و طبق قوانین و سیاست حریم خصوصی خود به کار می‌برد. انتخاب شما محدود نمی‌شود و هر زمان بخواهید می‌توانید روش ارسال را تغییر دهید.", + "motamedAsaTermsLink": "قوانین و مقررات معتمد آسا", + "motamedAsaPrivacyLink": "حریم خصوصی معتمد آسا", + "motamedAsaConsentCheckbox": "توضیحات بالا را خواندم و موافقم اطلاعات این کسب‌وکار برای ارسال صورت‌حساب در اختیار معتمد آسا قرار گیرد.", + "motamedAsaContinueButton": "ادامه در معتمد آسا", + "motamedAsaConnected": "این کسب‌وکار به معتمد آسا متصل است.", + "motamedAsaOnboarding": "ثبت‌نام در معتمد آسا در جریان است. پس از پایان ثبت‌نام در آن صفحه، اتصال را بررسی کنید.", + "motamedAsaCredentialsRequired": "کلید API این کسب‌وکار دریافت نشد. شناسه و رمز کلاینت را از پنل معتمد آسا وارد کنید.", + "motamedAsaNotConnected": "این کسب‌وکار به معتمد آسا متصل نیست.", + "motamedAsaMemoryId": "شناسه یکتای حافظه مالیاتی", + "motamedAsaOpenSignup": "باز کردن صفحه ثبت‌نام", + "motamedAsaEnterCredentials": "ورود کلید API", + "motamedAsaCheckConnection": "بررسی اتصال", + "motamedAsaConnectedSuccess": "کسب‌وکار به معتمد آسا متصل شد و صورت‌حساب‌ها از این راه ارسال می‌شوند.", + "motamedAsaSignupOpened": "صفحه ثبت‌نام معتمد آسا باز شد. پس از پایان ثبت‌نام، «بررسی اتصال» را بزنید.", + "motamedAsaLinkCopyHint": "صفحه باز نشد. این لینک را در مرورگر باز کنید:", + "motamedAsaSyncSuccess": "وضعیت اتصال معتمد آسا به‌روز شد.", + "motamedAsaCredentialsTitle": "کلید API معتمد آسا", + "motamedAsaCredentialsDescription": "در پنل معتمد آسا به «تنظیمات کسب‌وکار › API نسخه ۲» بروید و شناسه و رمز کلاینت همین کسب‌وکار را کپی کنید.", + "motamedAsaClientId": "شناسه کلاینت (Client ID)", + "motamedAsaClientSecret": "رمز کلاینت (Client Secret)", + "motamedAsaClientIdInvalid": "شناسه کلاینت به شکل v2-customer-12345 است.", + "motamedAsaSaveCredentials": "اتصال", + "motamedAsaAdminTitle": "اتصال معتمد آسا", + "motamedAsaAdminDescription": "شناسه و رمز کلاینت همکاری را که معتمد آسا در بخش «همکاران API» برای حسابیکس صادر کرده است وارد کنید. کسب‌وکارها در صفحه معتمد آسا ثبت‌نام می‌کنند و کلید API آن‌ها پس از موافقت مالک به حسابیکس تحویل می‌شود.", + "motamedAsaBaseUrl": "نشانی API معتمد آسا", + "motamedAsaPartnerClientId": "شناسه کلاینت همکار", + "motamedAsaPartnerClientIdInvalid": "شناسه کلاینت همکار با v2-partner- شروع می‌شود.", + "motamedAsaPartnerClientSecret": "رمز کلاینت همکار", + "motamedAsaKeepSecretHint": "برای نگه‌داشتن مقدار ذخیره‌شده، این کادر را خالی بگذارید.", + "motamedAsaActivate": "فعال بودن ارسال از طریق معتمد آسا", + "motamedAsaEnabledHint": "کسب‌وکارها می‌توانند معتمد آسا را به‌عنوان روش ارسال انتخاب کنند.", + "motamedAsaDisabledHint": "کسب‌وکارها نمی‌توانند معتمد آسا را انتخاب کنند.", + "motamedAsaSave": "ذخیره تنظیمات معتمد آسا", + "motamedAsaSaved": "تنظیمات معتمد آسا ذخیره شد.", + "motamedAsaNotConfigured": "شناسه و رمز کلاینت همکار هنوز ذخیره نشده است.", + "motamedAsaTestSuccess": "حسابیکس با موفقیت به معتمد آسا وارد شد. هیچ کسب‌وکار یا صورت‌حسابی ساخته نشد.", + "motamedAsaHostedOnboarding": "لینک ثبت‌نام", + "motamedAsaCredentialHandover": "تحویل کلید API", + "settingsMotamedAsa": "اتصال معتمد آسا", + "settingsMotamedAsaDescription": "اعتبارنامه همکاری با شرکت معتمد مالیاتی «معتمد آسا»", + "taxWorkspaceStatusColumn": "وضعیت کارپوشه", + "taxWorkspaceStatusNoNeedReaction": "عدم نیاز به واکنش", + "taxWorkspaceStatusAwaitingReaction": "در انتظار واکنش خریدار", + "taxWorkspaceStatusApproved": "تأیید شده توسط خریدار", + "taxWorkspaceStatusSystemicApproved": "تأیید سیستمی", + "taxWorkspaceStatusImpossibleReaction": "عدم امکان واکنش", + "taxWorkspaceStatusRejected": "رد شده توسط خریدار", + "taxWorkspaceStatusSystemicRejected": "رد سیستمی", + "taxWorkspaceStatusCanceled": "باطل شده", + "taxArticle6Column": "ماده ۶", + "taxArticle6Violated": "عدول", + "taxArticle6NotViolated": "عدم عدول", + "motamedAsaPaymentsAction": "پرداخت‌ها و ثبت در کارپوشه", + "motamedAsaPaymentsTitle": "جدول پرداخت صورت‌حساب", + "motamedAsaPaymentsDescription": "پرداخت‌هایی که پس از ارسال صورت‌حساب انجام شده‌اند از طریق معتمد آسا در کارپوشه سامانه مودیان ثبت می‌شوند. مبلغی را که خریدار پرداخته است (با مالیات بر ارزش افزوده) وارد کنید؛ کارپوشه سهم بدون مالیات را نگه می‌دارد. ردیف‌هایی که نزد سازمان ثبت شده‌اند قابل ویرایش یا حذف نیستند.", + "motamedAsaPaymentsNotEligible": "ثبت پرداخت تازه روی این صورت‌حساب ممکن نیست.", + "motamedAsaPaymentsEmpty": "هنوز ردیف پرداختی برای این صورت‌حساب نیست.", + "motamedAsaPaymentsAddRow": "افزودن پرداخت", + "motamedAsaPaymentsRegister": "ثبت در کارپوشه", + "motamedAsaPaymentsRegistered": "پرداخت‌ها برای ثبت در کارپوشه ارسال شد.", + "motamedAsaPaymentsResultUnknown": "پاسخ ثبت نرسید. ردیف‌های زیر وضعیت فعلی نزد معتمد آسا است؛ پیش از ارسال دوباره آن‌ها را بررسی کنید.", + "motamedAsaPaymentType": "روش پرداخت", + "motamedAsaPaymentDate": "تاریخ پرداخت", + "motamedAsaPaymentAmount": "مبلغ پرداختی (ریال، با مالیات)", + "motamedAsaPaymentTraceNo": "شماره پیگیری", + "motamedAsaPaymentTerminal": "شماره پایانه", + "motamedAsaPaymentDescription": "توضیح", + "motamedAsaPaymentRegisteredAmount": "مبلغ ثبت‌شده", + "motamedAsaPaymentRemoveRow": "حذف ردیف", + "motamedAsaPaymentAmountInvalid": "مبلغ را به ریال، عدد صحیح و بزرگ‌تر از صفر وارد کنید.", + "motamedAsaPaymentDigitsInvalid": "فقط رقم و در حد طول مجاز وارد کنید.", + "motamedAsaPaymentDateRequired": "تاریخ پرداخت همه ردیف‌ها را انتخاب کنید.", + "motamedAsaPaymentTypeCheque": "چک", + "motamedAsaPaymentTypeBarter": "تهاتر", + "motamedAsaPaymentTypeCash": "نقد", + "motamedAsaPaymentTypePos": "کارت‌خوان", + "motamedAsaPaymentTypeInternet": "درگاه پرداخت اینترنتی", + "motamedAsaPaymentTypeCard": "کارت به کارت", + "motamedAsaPaymentTypeTransfer": "انتقال به حساب", + "motamedAsaPaymentTypeOther": "سایر", + "motamedAsaPaymentStatusRegistered": "ثبت شده", + "motamedAsaPaymentStatusSentWithInvoice": "همراه صورت‌حساب ارسال شده", + "motamedAsaPaymentStatusQueued": "در صف ثبت", + "motamedAsaPaymentStatusNotRegistered": "همراه صورت‌حساب ارسال می‌شود", + "motamedAsaPaymentStatusUnknown": "نتیجه نامشخص", + "motamedAsaPaymentStatusRejected": "رد شده", + "motamedAsaPaymentStatusFailed": "ناموفق", + "motamedAsaPaymentStatusNotApplicable": "ارسال نمی‌شود" } diff --git a/hesabixUI/hesabix_ui/lib/l10n/app_localizations.dart b/hesabixUI/hesabix_ui/lib/l10n/app_localizations.dart index 66801c00..d33e4e6d 100644 --- a/hesabixUI/hesabix_ui/lib/l10n/app_localizations.dart +++ b/hesabixUI/hesabix_ui/lib/l10n/app_localizations.dart @@ -37474,6 +37474,600 @@ abstract class AppLocalizations { /// In en, this message translates to: /// **'Save the new broker credentials before testing the connection.'** String get taxProviderSaveBeforeTest; + + /// No description provided for @taxSubmissionMotamedAsa. + /// + /// In en, this message translates to: + /// **'Send through Motamed ASA'** + String get taxSubmissionMotamedAsa; + + /// No description provided for @taxSubmissionMotamedAsaDescription. + /// + /// In en, this message translates to: + /// **'Sign up on the Motamed ASA page; the trusted company signs and sends the invoices, so the business private key and memory ID are not needed here.'** + String get taxSubmissionMotamedAsaDescription; + + /// No description provided for @motamedAsaUnavailable. + /// + /// In en, this message translates to: + /// **'The Motamed ASA connection has not been set up by the system administrator yet.'** + String get motamedAsaUnavailable; + + /// No description provided for @motamedAsaSandboxUnavailable. + /// + /// In en, this message translates to: + /// **'Motamed ASA sends to the production tax system only. Turn off sandbox mode to select it.'** + String get motamedAsaSandboxUnavailable; + + /// No description provided for @motamedAsaEconomicCodeRequired. + /// + /// In en, this message translates to: + /// **'Enter the 11 or 14 digit economic code of the business first.'** + String get motamedAsaEconomicCodeRequired; + + /// No description provided for @motamedAsaConsentTitle. + /// + /// In en, this message translates to: + /// **'Send invoices through Motamed ASA'** + String get motamedAsaConsentTitle; + + /// No description provided for @motamedAsaConsentDescription. + /// + /// In en, this message translates to: + /// **'Motamed ASA is a trusted tax service provider. If you continue, the Motamed ASA sign-up page opens. There the business owner signs in with the one-time code of the tax system, accepts the Motamed ASA terms and allows the API key of this business to be handed to Hesabix.'** + String get motamedAsaConsentDescription; + + /// No description provided for @motamedAsaSharedDataTitle. + /// + /// In en, this message translates to: + /// **'What Hesabix shares with Motamed ASA'** + String get motamedAsaSharedDataTitle; + + /// No description provided for @motamedAsaSharedDataSignup. + /// + /// In en, this message translates to: + /// **'For sign-up: the economic code, the business name and the mobile number of the owner, to fill in the sign-up form.'** + String get motamedAsaSharedDataSignup; + + /// No description provided for @motamedAsaSharedDataInvoices. + /// + /// In en, this message translates to: + /// **'For every invoice you send: the data the tax system requires, including the buyer identifiers, items, amounts and payments.'** + String get motamedAsaSharedDataInvoices; + + /// No description provided for @motamedAsaSharedDataPurpose. + /// + /// In en, this message translates to: + /// **'Motamed ASA uses this data to issue, send and follow up your invoices in the tax system, under its terms and privacy policy. Your choice is not limited: you can change the sending method at any time.'** + String get motamedAsaSharedDataPurpose; + + /// No description provided for @motamedAsaTermsLink. + /// + /// In en, this message translates to: + /// **'Motamed ASA terms'** + String get motamedAsaTermsLink; + + /// No description provided for @motamedAsaPrivacyLink. + /// + /// In en, this message translates to: + /// **'Motamed ASA privacy policy'** + String get motamedAsaPrivacyLink; + + /// No description provided for @motamedAsaConsentCheckbox. + /// + /// In en, this message translates to: + /// **'I have read the above and agree that the data of this business is shared with Motamed ASA for sending invoices.'** + String get motamedAsaConsentCheckbox; + + /// No description provided for @motamedAsaContinueButton. + /// + /// In en, this message translates to: + /// **'Continue on Motamed ASA'** + String get motamedAsaContinueButton; + + /// No description provided for @motamedAsaConnected. + /// + /// In en, this message translates to: + /// **'This business is connected to Motamed ASA.'** + String get motamedAsaConnected; + + /// No description provided for @motamedAsaOnboarding. + /// + /// In en, this message translates to: + /// **'Sign-up on Motamed ASA is in progress. When it is finished there, check the connection.'** + String get motamedAsaOnboarding; + + /// No description provided for @motamedAsaCredentialsRequired. + /// + /// In en, this message translates to: + /// **'The API key of this business was not received. Enter the client ID and secret from the Motamed ASA panel.'** + String get motamedAsaCredentialsRequired; + + /// No description provided for @motamedAsaNotConnected. + /// + /// In en, this message translates to: + /// **'This business is not connected to Motamed ASA.'** + String get motamedAsaNotConnected; + + /// No description provided for @motamedAsaMemoryId. + /// + /// In en, this message translates to: + /// **'Fiscal memory ID'** + String get motamedAsaMemoryId; + + /// No description provided for @motamedAsaOpenSignup. + /// + /// In en, this message translates to: + /// **'Open the sign-up page'** + String get motamedAsaOpenSignup; + + /// No description provided for @motamedAsaEnterCredentials. + /// + /// In en, this message translates to: + /// **'Enter API key'** + String get motamedAsaEnterCredentials; + + /// No description provided for @motamedAsaCheckConnection. + /// + /// In en, this message translates to: + /// **'Check connection'** + String get motamedAsaCheckConnection; + + /// No description provided for @motamedAsaConnectedSuccess. + /// + /// In en, this message translates to: + /// **'The business is connected to Motamed ASA and its invoices are sent through it.'** + String get motamedAsaConnectedSuccess; + + /// No description provided for @motamedAsaSignupOpened. + /// + /// In en, this message translates to: + /// **'The Motamed ASA sign-up page was opened. After finishing there, select Check connection.'** + String get motamedAsaSignupOpened; + + /// No description provided for @motamedAsaLinkCopyHint. + /// + /// In en, this message translates to: + /// **'The page did not open. Open this link in your browser:'** + String get motamedAsaLinkCopyHint; + + /// No description provided for @motamedAsaSyncSuccess. + /// + /// In en, this message translates to: + /// **'The Motamed ASA connection status was updated.'** + String get motamedAsaSyncSuccess; + + /// No description provided for @motamedAsaCredentialsTitle. + /// + /// In en, this message translates to: + /// **'Motamed ASA API key'** + String get motamedAsaCredentialsTitle; + + /// No description provided for @motamedAsaCredentialsDescription. + /// + /// In en, this message translates to: + /// **'In the Motamed ASA panel, open Business settings › API v2 and copy the client ID and client secret of this business.'** + String get motamedAsaCredentialsDescription; + + /// No description provided for @motamedAsaClientId. + /// + /// In en, this message translates to: + /// **'Client ID'** + String get motamedAsaClientId; + + /// No description provided for @motamedAsaClientSecret. + /// + /// In en, this message translates to: + /// **'Client secret'** + String get motamedAsaClientSecret; + + /// No description provided for @motamedAsaClientIdInvalid. + /// + /// In en, this message translates to: + /// **'The client ID looks like v2-customer-12345.'** + String get motamedAsaClientIdInvalid; + + /// No description provided for @motamedAsaSaveCredentials. + /// + /// In en, this message translates to: + /// **'Connect'** + String get motamedAsaSaveCredentials; + + /// No description provided for @motamedAsaAdminTitle. + /// + /// In en, this message translates to: + /// **'Motamed ASA connection'** + String get motamedAsaAdminTitle; + + /// No description provided for @motamedAsaAdminDescription. + /// + /// In en, this message translates to: + /// **'Enter the partner client ID and secret that Motamed ASA issued for Hesabix in its API partners section. Businesses then sign up on the Motamed ASA page, and their API key is handed to Hesabix after the owner agrees.'** + String get motamedAsaAdminDescription; + + /// No description provided for @motamedAsaBaseUrl. + /// + /// In en, this message translates to: + /// **'Motamed ASA API address'** + String get motamedAsaBaseUrl; + + /// No description provided for @motamedAsaPartnerClientId. + /// + /// In en, this message translates to: + /// **'Partner client ID'** + String get motamedAsaPartnerClientId; + + /// No description provided for @motamedAsaPartnerClientIdInvalid. + /// + /// In en, this message translates to: + /// **'The partner client ID starts with v2-partner-.'** + String get motamedAsaPartnerClientIdInvalid; + + /// No description provided for @motamedAsaPartnerClientSecret. + /// + /// In en, this message translates to: + /// **'Partner client secret'** + String get motamedAsaPartnerClientSecret; + + /// No description provided for @motamedAsaKeepSecretHint. + /// + /// In en, this message translates to: + /// **'Leave empty to keep the saved value.'** + String get motamedAsaKeepSecretHint; + + /// No description provided for @motamedAsaActivate. + /// + /// In en, this message translates to: + /// **'Allow sending through Motamed ASA'** + String get motamedAsaActivate; + + /// No description provided for @motamedAsaEnabledHint. + /// + /// In en, this message translates to: + /// **'Businesses can select Motamed ASA as their sending method.'** + String get motamedAsaEnabledHint; + + /// No description provided for @motamedAsaDisabledHint. + /// + /// In en, this message translates to: + /// **'Businesses cannot select Motamed ASA.'** + String get motamedAsaDisabledHint; + + /// No description provided for @motamedAsaSave. + /// + /// In en, this message translates to: + /// **'Save Motamed ASA settings'** + String get motamedAsaSave; + + /// No description provided for @motamedAsaSaved. + /// + /// In en, this message translates to: + /// **'Motamed ASA settings were saved.'** + String get motamedAsaSaved; + + /// No description provided for @motamedAsaNotConfigured. + /// + /// In en, this message translates to: + /// **'The partner client ID and secret are not saved yet.'** + String get motamedAsaNotConfigured; + + /// No description provided for @motamedAsaTestSuccess. + /// + /// In en, this message translates to: + /// **'Hesabix signed in to Motamed ASA. No business or invoice was created.'** + String get motamedAsaTestSuccess; + + /// No description provided for @motamedAsaHostedOnboarding. + /// + /// In en, this message translates to: + /// **'Sign-up link'** + String get motamedAsaHostedOnboarding; + + /// No description provided for @motamedAsaCredentialHandover. + /// + /// In en, this message translates to: + /// **'API key handover'** + String get motamedAsaCredentialHandover; + + /// No description provided for @settingsMotamedAsa. + /// + /// In en, this message translates to: + /// **'Motamed ASA connection'** + String get settingsMotamedAsa; + + /// No description provided for @settingsMotamedAsaDescription. + /// + /// In en, this message translates to: + /// **'Partner credentials for the Motamed ASA trusted tax company'** + String get settingsMotamedAsaDescription; + + /// No description provided for @taxWorkspaceStatusColumn. + /// + /// In en, this message translates to: + /// **'Workspace status'** + String get taxWorkspaceStatusColumn; + + /// No description provided for @taxWorkspaceStatusNoNeedReaction. + /// + /// In en, this message translates to: + /// **'No reaction needed'** + String get taxWorkspaceStatusNoNeedReaction; + + /// No description provided for @taxWorkspaceStatusAwaitingReaction. + /// + /// In en, this message translates to: + /// **'Awaiting buyer reaction'** + String get taxWorkspaceStatusAwaitingReaction; + + /// No description provided for @taxWorkspaceStatusApproved. + /// + /// In en, this message translates to: + /// **'Approved by buyer'** + String get taxWorkspaceStatusApproved; + + /// No description provided for @taxWorkspaceStatusSystemicApproved. + /// + /// In en, this message translates to: + /// **'Systemically approved'** + String get taxWorkspaceStatusSystemicApproved; + + /// No description provided for @taxWorkspaceStatusImpossibleReaction. + /// + /// In en, this message translates to: + /// **'Reaction not possible'** + String get taxWorkspaceStatusImpossibleReaction; + + /// No description provided for @taxWorkspaceStatusRejected. + /// + /// In en, this message translates to: + /// **'Rejected by buyer'** + String get taxWorkspaceStatusRejected; + + /// No description provided for @taxWorkspaceStatusSystemicRejected. + /// + /// In en, this message translates to: + /// **'Systemically rejected'** + String get taxWorkspaceStatusSystemicRejected; + + /// No description provided for @taxWorkspaceStatusCanceled. + /// + /// In en, this message translates to: + /// **'Cancelled'** + String get taxWorkspaceStatusCanceled; + + /// No description provided for @taxArticle6Column. + /// + /// In en, this message translates to: + /// **'Article 6'** + String get taxArticle6Column; + + /// No description provided for @taxArticle6Violated. + /// + /// In en, this message translates to: + /// **'Limit exceeded'** + String get taxArticle6Violated; + + /// No description provided for @taxArticle6NotViolated. + /// + /// In en, this message translates to: + /// **'Within the limit'** + String get taxArticle6NotViolated; + + /// No description provided for @motamedAsaPaymentsAction. + /// + /// In en, this message translates to: + /// **'Payments in the tax workspace'** + String get motamedAsaPaymentsAction; + + /// No description provided for @motamedAsaPaymentsTitle. + /// + /// In en, this message translates to: + /// **'Payment table of invoice'** + String get motamedAsaPaymentsTitle; + + /// No description provided for @motamedAsaPaymentsDescription. + /// + /// In en, this message translates to: + /// **'Payments made after the invoice was sent are registered in the tax workspace through Motamed ASA. Enter the amount the buyer paid, including VAT; the tax workspace keeps the share without VAT. Rows held by the tax system cannot be edited or deleted.'** + String get motamedAsaPaymentsDescription; + + /// No description provided for @motamedAsaPaymentsNotEligible. + /// + /// In en, this message translates to: + /// **'New payments cannot be registered on this invoice.'** + String get motamedAsaPaymentsNotEligible; + + /// No description provided for @motamedAsaPaymentsEmpty. + /// + /// In en, this message translates to: + /// **'No payment row yet.'** + String get motamedAsaPaymentsEmpty; + + /// No description provided for @motamedAsaPaymentsAddRow. + /// + /// In en, this message translates to: + /// **'Add payment'** + String get motamedAsaPaymentsAddRow; + + /// No description provided for @motamedAsaPaymentsRegister. + /// + /// In en, this message translates to: + /// **'Register in tax workspace'** + String get motamedAsaPaymentsRegister; + + /// No description provided for @motamedAsaPaymentsRegistered. + /// + /// In en, this message translates to: + /// **'The payments were sent for registration in the tax workspace.'** + String get motamedAsaPaymentsRegistered; + + /// No description provided for @motamedAsaPaymentsResultUnknown. + /// + /// In en, this message translates to: + /// **'The answer did not arrive. The rows below are what Motamed ASA holds now; check them before sending anything again.'** + String get motamedAsaPaymentsResultUnknown; + + /// No description provided for @motamedAsaPaymentType. + /// + /// In en, this message translates to: + /// **'Payment method'** + String get motamedAsaPaymentType; + + /// No description provided for @motamedAsaPaymentDate. + /// + /// In en, this message translates to: + /// **'Payment date'** + String get motamedAsaPaymentDate; + + /// No description provided for @motamedAsaPaymentAmount. + /// + /// In en, this message translates to: + /// **'Amount paid (rial, including VAT)'** + String get motamedAsaPaymentAmount; + + /// No description provided for @motamedAsaPaymentTraceNo. + /// + /// In en, this message translates to: + /// **'Trace number'** + String get motamedAsaPaymentTraceNo; + + /// No description provided for @motamedAsaPaymentTerminal. + /// + /// In en, this message translates to: + /// **'Terminal number'** + String get motamedAsaPaymentTerminal; + + /// No description provided for @motamedAsaPaymentDescription. + /// + /// In en, this message translates to: + /// **'Description'** + String get motamedAsaPaymentDescription; + + /// No description provided for @motamedAsaPaymentRegisteredAmount. + /// + /// In en, this message translates to: + /// **'Registered amount'** + String get motamedAsaPaymentRegisteredAmount; + + /// No description provided for @motamedAsaPaymentRemoveRow. + /// + /// In en, this message translates to: + /// **'Remove row'** + String get motamedAsaPaymentRemoveRow; + + /// No description provided for @motamedAsaPaymentAmountInvalid. + /// + /// In en, this message translates to: + /// **'Enter a whole rial amount greater than zero.'** + String get motamedAsaPaymentAmountInvalid; + + /// No description provided for @motamedAsaPaymentDigitsInvalid. + /// + /// In en, this message translates to: + /// **'Digits only, within the allowed length.'** + String get motamedAsaPaymentDigitsInvalid; + + /// No description provided for @motamedAsaPaymentDateRequired. + /// + /// In en, this message translates to: + /// **'Choose the payment date of every row.'** + String get motamedAsaPaymentDateRequired; + + /// No description provided for @motamedAsaPaymentTypeCheque. + /// + /// In en, this message translates to: + /// **'Cheque'** + String get motamedAsaPaymentTypeCheque; + + /// No description provided for @motamedAsaPaymentTypeBarter. + /// + /// In en, this message translates to: + /// **'Offset'** + String get motamedAsaPaymentTypeBarter; + + /// No description provided for @motamedAsaPaymentTypeCash. + /// + /// In en, this message translates to: + /// **'Cash'** + String get motamedAsaPaymentTypeCash; + + /// No description provided for @motamedAsaPaymentTypePos. + /// + /// In en, this message translates to: + /// **'Card reader (POS)'** + String get motamedAsaPaymentTypePos; + + /// No description provided for @motamedAsaPaymentTypeInternet. + /// + /// In en, this message translates to: + /// **'Payment gateway'** + String get motamedAsaPaymentTypeInternet; + + /// No description provided for @motamedAsaPaymentTypeCard. + /// + /// In en, this message translates to: + /// **'Card to card'** + String get motamedAsaPaymentTypeCard; + + /// No description provided for @motamedAsaPaymentTypeTransfer. + /// + /// In en, this message translates to: + /// **'Bank transfer'** + String get motamedAsaPaymentTypeTransfer; + + /// No description provided for @motamedAsaPaymentTypeOther. + /// + /// In en, this message translates to: + /// **'Other'** + String get motamedAsaPaymentTypeOther; + + /// No description provided for @motamedAsaPaymentStatusRegistered. + /// + /// In en, this message translates to: + /// **'Registered'** + String get motamedAsaPaymentStatusRegistered; + + /// No description provided for @motamedAsaPaymentStatusSentWithInvoice. + /// + /// In en, this message translates to: + /// **'Sent with the invoice'** + String get motamedAsaPaymentStatusSentWithInvoice; + + /// No description provided for @motamedAsaPaymentStatusQueued. + /// + /// In en, this message translates to: + /// **'Queued for registration'** + String get motamedAsaPaymentStatusQueued; + + /// No description provided for @motamedAsaPaymentStatusNotRegistered. + /// + /// In en, this message translates to: + /// **'Goes with the invoice'** + String get motamedAsaPaymentStatusNotRegistered; + + /// No description provided for @motamedAsaPaymentStatusUnknown. + /// + /// In en, this message translates to: + /// **'Result unknown'** + String get motamedAsaPaymentStatusUnknown; + + /// No description provided for @motamedAsaPaymentStatusRejected. + /// + /// In en, this message translates to: + /// **'Rejected'** + String get motamedAsaPaymentStatusRejected; + + /// No description provided for @motamedAsaPaymentStatusFailed. + /// + /// In en, this message translates to: + /// **'Failed'** + String get motamedAsaPaymentStatusFailed; + + /// No description provided for @motamedAsaPaymentStatusNotApplicable. + /// + /// In en, this message translates to: + /// **'Not sent'** + String get motamedAsaPaymentStatusNotApplicable; } class _AppLocalizationsDelegate diff --git a/hesabixUI/hesabix_ui/lib/l10n/app_localizations_en.dart b/hesabixUI/hesabix_ui/lib/l10n/app_localizations_en.dart index 2f634a6a..20bc778e 100644 --- a/hesabixUI/hesabix_ui/lib/l10n/app_localizations_en.dart +++ b/hesabixUI/hesabix_ui/lib/l10n/app_localizations_en.dart @@ -20435,4 +20435,334 @@ class AppLocalizationsEn extends AppLocalizations { @override String get taxProviderSaveBeforeTest => 'Save the new broker credentials before testing the connection.'; + + @override + String get taxSubmissionMotamedAsa => 'Send through Motamed ASA'; + + @override + String get taxSubmissionMotamedAsaDescription => + 'Sign up on the Motamed ASA page; the trusted company signs and sends the invoices, so the business private key and memory ID are not needed here.'; + + @override + String get motamedAsaUnavailable => + 'The Motamed ASA connection has not been set up by the system administrator yet.'; + + @override + String get motamedAsaSandboxUnavailable => + 'Motamed ASA sends to the production tax system only. Turn off sandbox mode to select it.'; + + @override + String get motamedAsaEconomicCodeRequired => + 'Enter the 11 or 14 digit economic code of the business first.'; + + @override + String get motamedAsaConsentTitle => 'Send invoices through Motamed ASA'; + + @override + String get motamedAsaConsentDescription => + 'Motamed ASA is a trusted tax service provider. If you continue, the Motamed ASA sign-up page opens. There the business owner signs in with the one-time code of the tax system, accepts the Motamed ASA terms and allows the API key of this business to be handed to Hesabix.'; + + @override + String get motamedAsaSharedDataTitle => + 'What Hesabix shares with Motamed ASA'; + + @override + String get motamedAsaSharedDataSignup => + 'For sign-up: the economic code, the business name and the mobile number of the owner, to fill in the sign-up form.'; + + @override + String get motamedAsaSharedDataInvoices => + 'For every invoice you send: the data the tax system requires, including the buyer identifiers, items, amounts and payments.'; + + @override + String get motamedAsaSharedDataPurpose => + 'Motamed ASA uses this data to issue, send and follow up your invoices in the tax system, under its terms and privacy policy. Your choice is not limited: you can change the sending method at any time.'; + + @override + String get motamedAsaTermsLink => 'Motamed ASA terms'; + + @override + String get motamedAsaPrivacyLink => 'Motamed ASA privacy policy'; + + @override + String get motamedAsaConsentCheckbox => + 'I have read the above and agree that the data of this business is shared with Motamed ASA for sending invoices.'; + + @override + String get motamedAsaContinueButton => 'Continue on Motamed ASA'; + + @override + String get motamedAsaConnected => + 'This business is connected to Motamed ASA.'; + + @override + String get motamedAsaOnboarding => + 'Sign-up on Motamed ASA is in progress. When it is finished there, check the connection.'; + + @override + String get motamedAsaCredentialsRequired => + 'The API key of this business was not received. Enter the client ID and secret from the Motamed ASA panel.'; + + @override + String get motamedAsaNotConnected => + 'This business is not connected to Motamed ASA.'; + + @override + String get motamedAsaMemoryId => 'Fiscal memory ID'; + + @override + String get motamedAsaOpenSignup => 'Open the sign-up page'; + + @override + String get motamedAsaEnterCredentials => 'Enter API key'; + + @override + String get motamedAsaCheckConnection => 'Check connection'; + + @override + String get motamedAsaConnectedSuccess => + 'The business is connected to Motamed ASA and its invoices are sent through it.'; + + @override + String get motamedAsaSignupOpened => + 'The Motamed ASA sign-up page was opened. After finishing there, select Check connection.'; + + @override + String get motamedAsaLinkCopyHint => + 'The page did not open. Open this link in your browser:'; + + @override + String get motamedAsaSyncSuccess => + 'The Motamed ASA connection status was updated.'; + + @override + String get motamedAsaCredentialsTitle => 'Motamed ASA API key'; + + @override + String get motamedAsaCredentialsDescription => + 'In the Motamed ASA panel, open Business settings › API v2 and copy the client ID and client secret of this business.'; + + @override + String get motamedAsaClientId => 'Client ID'; + + @override + String get motamedAsaClientSecret => 'Client secret'; + + @override + String get motamedAsaClientIdInvalid => + 'The client ID looks like v2-customer-12345.'; + + @override + String get motamedAsaSaveCredentials => 'Connect'; + + @override + String get motamedAsaAdminTitle => 'Motamed ASA connection'; + + @override + String get motamedAsaAdminDescription => + 'Enter the partner client ID and secret that Motamed ASA issued for Hesabix in its API partners section. Businesses then sign up on the Motamed ASA page, and their API key is handed to Hesabix after the owner agrees.'; + + @override + String get motamedAsaBaseUrl => 'Motamed ASA API address'; + + @override + String get motamedAsaPartnerClientId => 'Partner client ID'; + + @override + String get motamedAsaPartnerClientIdInvalid => + 'The partner client ID starts with v2-partner-.'; + + @override + String get motamedAsaPartnerClientSecret => 'Partner client secret'; + + @override + String get motamedAsaKeepSecretHint => 'Leave empty to keep the saved value.'; + + @override + String get motamedAsaActivate => 'Allow sending through Motamed ASA'; + + @override + String get motamedAsaEnabledHint => + 'Businesses can select Motamed ASA as their sending method.'; + + @override + String get motamedAsaDisabledHint => 'Businesses cannot select Motamed ASA.'; + + @override + String get motamedAsaSave => 'Save Motamed ASA settings'; + + @override + String get motamedAsaSaved => 'Motamed ASA settings were saved.'; + + @override + String get motamedAsaNotConfigured => + 'The partner client ID and secret are not saved yet.'; + + @override + String get motamedAsaTestSuccess => + 'Hesabix signed in to Motamed ASA. No business or invoice was created.'; + + @override + String get motamedAsaHostedOnboarding => 'Sign-up link'; + + @override + String get motamedAsaCredentialHandover => 'API key handover'; + + @override + String get settingsMotamedAsa => 'Motamed ASA connection'; + + @override + String get settingsMotamedAsaDescription => + 'Partner credentials for the Motamed ASA trusted tax company'; + + @override + String get taxWorkspaceStatusColumn => 'Workspace status'; + + @override + String get taxWorkspaceStatusNoNeedReaction => 'No reaction needed'; + + @override + String get taxWorkspaceStatusAwaitingReaction => 'Awaiting buyer reaction'; + + @override + String get taxWorkspaceStatusApproved => 'Approved by buyer'; + + @override + String get taxWorkspaceStatusSystemicApproved => 'Systemically approved'; + + @override + String get taxWorkspaceStatusImpossibleReaction => 'Reaction not possible'; + + @override + String get taxWorkspaceStatusRejected => 'Rejected by buyer'; + + @override + String get taxWorkspaceStatusSystemicRejected => 'Systemically rejected'; + + @override + String get taxWorkspaceStatusCanceled => 'Cancelled'; + + @override + String get taxArticle6Column => 'Article 6'; + + @override + String get taxArticle6Violated => 'Limit exceeded'; + + @override + String get taxArticle6NotViolated => 'Within the limit'; + + @override + String get motamedAsaPaymentsAction => 'Payments in the tax workspace'; + + @override + String get motamedAsaPaymentsTitle => 'Payment table of invoice'; + + @override + String get motamedAsaPaymentsDescription => + 'Payments made after the invoice was sent are registered in the tax workspace through Motamed ASA. Enter the amount the buyer paid, including VAT; the tax workspace keeps the share without VAT. Rows held by the tax system cannot be edited or deleted.'; + + @override + String get motamedAsaPaymentsNotEligible => + 'New payments cannot be registered on this invoice.'; + + @override + String get motamedAsaPaymentsEmpty => 'No payment row yet.'; + + @override + String get motamedAsaPaymentsAddRow => 'Add payment'; + + @override + String get motamedAsaPaymentsRegister => 'Register in tax workspace'; + + @override + String get motamedAsaPaymentsRegistered => + 'The payments were sent for registration in the tax workspace.'; + + @override + String get motamedAsaPaymentsResultUnknown => + 'The answer did not arrive. The rows below are what Motamed ASA holds now; check them before sending anything again.'; + + @override + String get motamedAsaPaymentType => 'Payment method'; + + @override + String get motamedAsaPaymentDate => 'Payment date'; + + @override + String get motamedAsaPaymentAmount => 'Amount paid (rial, including VAT)'; + + @override + String get motamedAsaPaymentTraceNo => 'Trace number'; + + @override + String get motamedAsaPaymentTerminal => 'Terminal number'; + + @override + String get motamedAsaPaymentDescription => 'Description'; + + @override + String get motamedAsaPaymentRegisteredAmount => 'Registered amount'; + + @override + String get motamedAsaPaymentRemoveRow => 'Remove row'; + + @override + String get motamedAsaPaymentAmountInvalid => + 'Enter a whole rial amount greater than zero.'; + + @override + String get motamedAsaPaymentDigitsInvalid => + 'Digits only, within the allowed length.'; + + @override + String get motamedAsaPaymentDateRequired => + 'Choose the payment date of every row.'; + + @override + String get motamedAsaPaymentTypeCheque => 'Cheque'; + + @override + String get motamedAsaPaymentTypeBarter => 'Offset'; + + @override + String get motamedAsaPaymentTypeCash => 'Cash'; + + @override + String get motamedAsaPaymentTypePos => 'Card reader (POS)'; + + @override + String get motamedAsaPaymentTypeInternet => 'Payment gateway'; + + @override + String get motamedAsaPaymentTypeCard => 'Card to card'; + + @override + String get motamedAsaPaymentTypeTransfer => 'Bank transfer'; + + @override + String get motamedAsaPaymentTypeOther => 'Other'; + + @override + String get motamedAsaPaymentStatusRegistered => 'Registered'; + + @override + String get motamedAsaPaymentStatusSentWithInvoice => 'Sent with the invoice'; + + @override + String get motamedAsaPaymentStatusQueued => 'Queued for registration'; + + @override + String get motamedAsaPaymentStatusNotRegistered => 'Goes with the invoice'; + + @override + String get motamedAsaPaymentStatusUnknown => 'Result unknown'; + + @override + String get motamedAsaPaymentStatusRejected => 'Rejected'; + + @override + String get motamedAsaPaymentStatusFailed => 'Failed'; + + @override + String get motamedAsaPaymentStatusNotApplicable => 'Not sent'; } diff --git a/hesabixUI/hesabix_ui/lib/l10n/app_localizations_fa.dart b/hesabixUI/hesabix_ui/lib/l10n/app_localizations_fa.dart index bf1278fa..4351955a 100644 --- a/hesabixUI/hesabix_ui/lib/l10n/app_localizations_fa.dart +++ b/hesabixUI/hesabix_ui/lib/l10n/app_localizations_fa.dart @@ -20329,4 +20329,336 @@ class AppLocalizationsFa extends AppLocalizations { @override String get taxProviderSaveBeforeTest => 'ابتدا اعتبارنامه‌های جدید را ذخیره کنید؛ سپس اتصال را بررسی کنید.'; + + @override + String get taxSubmissionMotamedAsa => 'ارسال از طریق معتمد آسا'; + + @override + String get taxSubmissionMotamedAsaDescription => + 'ثبت‌نام در صفحه معتمد آسا و ارسال صورت‌حساب‌ها با امضای شرکت معتمد؛ کلید خصوصی و شناسه حافظه کسب‌وکار در اینجا لازم نیست.'; + + @override + String get motamedAsaUnavailable => + 'اتصال معتمد آسا هنوز توسط مدیر سیستم راه‌اندازی نشده است.'; + + @override + String get motamedAsaSandboxUnavailable => + 'معتمد آسا فقط به محیط اصلی سامانه مودیان ارسال می‌کند. برای انتخاب آن، حالت آزمایشی را خاموش کنید.'; + + @override + String get motamedAsaEconomicCodeRequired => + 'ابتدا کد اقتصادی ۱۱ یا ۱۴ رقمی کسب‌وکار را وارد کنید.'; + + @override + String get motamedAsaConsentTitle => 'ارسال صورت‌حساب از طریق معتمد آسا'; + + @override + String get motamedAsaConsentDescription => + 'معتمد آسا از شرکت‌های معتمد ارائه‌دهنده خدمات مالیاتی است. با ادامه، صفحه ثبت‌نام معتمد آسا باز می‌شود؛ مالک کسب‌وکار در آن صفحه با کد یک‌بارمصرف سامانه مودیان وارد می‌شود، قوانین معتمد آسا را می‌پذیرد و اجازه می‌دهد کلید API این کسب‌وکار به حسابیکس تحویل شود.'; + + @override + String get motamedAsaSharedDataTitle => + 'اطلاعاتی که حسابیکس در اختیار معتمد آسا می‌گذارد'; + + @override + String get motamedAsaSharedDataSignup => + 'برای ثبت‌نام: کد اقتصادی، نام کسب‌وکار و شماره همراه مالک، برای پر کردن فرم ثبت‌نام.'; + + @override + String get motamedAsaSharedDataInvoices => + 'برای هر صورت‌حسابی که ارسال می‌کنید: اطلاعاتی که سامانه مودیان لازم دارد، از جمله شناسه خریدار، اقلام، مبالغ و پرداخت‌ها.'; + + @override + String get motamedAsaSharedDataPurpose => + 'معتمد آسا این اطلاعات را برای صدور، ارسال و پیگیری صورت‌حساب‌های شما در سامانه مودیان و طبق قوانین و سیاست حریم خصوصی خود به کار می‌برد. انتخاب شما محدود نمی‌شود و هر زمان بخواهید می‌توانید روش ارسال را تغییر دهید.'; + + @override + String get motamedAsaTermsLink => 'قوانین و مقررات معتمد آسا'; + + @override + String get motamedAsaPrivacyLink => 'حریم خصوصی معتمد آسا'; + + @override + String get motamedAsaConsentCheckbox => + 'توضیحات بالا را خواندم و موافقم اطلاعات این کسب‌وکار برای ارسال صورت‌حساب در اختیار معتمد آسا قرار گیرد.'; + + @override + String get motamedAsaContinueButton => 'ادامه در معتمد آسا'; + + @override + String get motamedAsaConnected => 'این کسب‌وکار به معتمد آسا متصل است.'; + + @override + String get motamedAsaOnboarding => + 'ثبت‌نام در معتمد آسا در جریان است. پس از پایان ثبت‌نام در آن صفحه، اتصال را بررسی کنید.'; + + @override + String get motamedAsaCredentialsRequired => + 'کلید API این کسب‌وکار دریافت نشد. شناسه و رمز کلاینت را از پنل معتمد آسا وارد کنید.'; + + @override + String get motamedAsaNotConnected => 'این کسب‌وکار به معتمد آسا متصل نیست.'; + + @override + String get motamedAsaMemoryId => 'شناسه یکتای حافظه مالیاتی'; + + @override + String get motamedAsaOpenSignup => 'باز کردن صفحه ثبت‌نام'; + + @override + String get motamedAsaEnterCredentials => 'ورود کلید API'; + + @override + String get motamedAsaCheckConnection => 'بررسی اتصال'; + + @override + String get motamedAsaConnectedSuccess => + 'کسب‌وکار به معتمد آسا متصل شد و صورت‌حساب‌ها از این راه ارسال می‌شوند.'; + + @override + String get motamedAsaSignupOpened => + 'صفحه ثبت‌نام معتمد آسا باز شد. پس از پایان ثبت‌نام، «بررسی اتصال» را بزنید.'; + + @override + String get motamedAsaLinkCopyHint => + 'صفحه باز نشد. این لینک را در مرورگر باز کنید:'; + + @override + String get motamedAsaSyncSuccess => 'وضعیت اتصال معتمد آسا به‌روز شد.'; + + @override + String get motamedAsaCredentialsTitle => 'کلید API معتمد آسا'; + + @override + String get motamedAsaCredentialsDescription => + 'در پنل معتمد آسا به «تنظیمات کسب‌وکار › API نسخه ۲» بروید و شناسه و رمز کلاینت همین کسب‌وکار را کپی کنید.'; + + @override + String get motamedAsaClientId => 'شناسه کلاینت (Client ID)'; + + @override + String get motamedAsaClientSecret => 'رمز کلاینت (Client Secret)'; + + @override + String get motamedAsaClientIdInvalid => + 'شناسه کلاینت به شکل v2-customer-12345 است.'; + + @override + String get motamedAsaSaveCredentials => 'اتصال'; + + @override + String get motamedAsaAdminTitle => 'اتصال معتمد آسا'; + + @override + String get motamedAsaAdminDescription => + 'شناسه و رمز کلاینت همکاری را که معتمد آسا در بخش «همکاران API» برای حسابیکس صادر کرده است وارد کنید. کسب‌وکارها در صفحه معتمد آسا ثبت‌نام می‌کنند و کلید API آن‌ها پس از موافقت مالک به حسابیکس تحویل می‌شود.'; + + @override + String get motamedAsaBaseUrl => 'نشانی API معتمد آسا'; + + @override + String get motamedAsaPartnerClientId => 'شناسه کلاینت همکار'; + + @override + String get motamedAsaPartnerClientIdInvalid => + 'شناسه کلاینت همکار با v2-partner- شروع می‌شود.'; + + @override + String get motamedAsaPartnerClientSecret => 'رمز کلاینت همکار'; + + @override + String get motamedAsaKeepSecretHint => + 'برای نگه‌داشتن مقدار ذخیره‌شده، این کادر را خالی بگذارید.'; + + @override + String get motamedAsaActivate => 'فعال بودن ارسال از طریق معتمد آسا'; + + @override + String get motamedAsaEnabledHint => + 'کسب‌وکارها می‌توانند معتمد آسا را به‌عنوان روش ارسال انتخاب کنند.'; + + @override + String get motamedAsaDisabledHint => + 'کسب‌وکارها نمی‌توانند معتمد آسا را انتخاب کنند.'; + + @override + String get motamedAsaSave => 'ذخیره تنظیمات معتمد آسا'; + + @override + String get motamedAsaSaved => 'تنظیمات معتمد آسا ذخیره شد.'; + + @override + String get motamedAsaNotConfigured => + 'شناسه و رمز کلاینت همکار هنوز ذخیره نشده است.'; + + @override + String get motamedAsaTestSuccess => + 'حسابیکس با موفقیت به معتمد آسا وارد شد. هیچ کسب‌وکار یا صورت‌حسابی ساخته نشد.'; + + @override + String get motamedAsaHostedOnboarding => 'لینک ثبت‌نام'; + + @override + String get motamedAsaCredentialHandover => 'تحویل کلید API'; + + @override + String get settingsMotamedAsa => 'اتصال معتمد آسا'; + + @override + String get settingsMotamedAsaDescription => + 'اعتبارنامه همکاری با شرکت معتمد مالیاتی «معتمد آسا»'; + + @override + String get taxWorkspaceStatusColumn => 'وضعیت کارپوشه'; + + @override + String get taxWorkspaceStatusNoNeedReaction => 'عدم نیاز به واکنش'; + + @override + String get taxWorkspaceStatusAwaitingReaction => 'در انتظار واکنش خریدار'; + + @override + String get taxWorkspaceStatusApproved => 'تأیید شده توسط خریدار'; + + @override + String get taxWorkspaceStatusSystemicApproved => 'تأیید سیستمی'; + + @override + String get taxWorkspaceStatusImpossibleReaction => 'عدم امکان واکنش'; + + @override + String get taxWorkspaceStatusRejected => 'رد شده توسط خریدار'; + + @override + String get taxWorkspaceStatusSystemicRejected => 'رد سیستمی'; + + @override + String get taxWorkspaceStatusCanceled => 'باطل شده'; + + @override + String get taxArticle6Column => 'ماده ۶'; + + @override + String get taxArticle6Violated => 'عدول'; + + @override + String get taxArticle6NotViolated => 'عدم عدول'; + + @override + String get motamedAsaPaymentsAction => 'پرداخت‌ها و ثبت در کارپوشه'; + + @override + String get motamedAsaPaymentsTitle => 'جدول پرداخت صورت‌حساب'; + + @override + String get motamedAsaPaymentsDescription => + 'پرداخت‌هایی که پس از ارسال صورت‌حساب انجام شده‌اند از طریق معتمد آسا در کارپوشه سامانه مودیان ثبت می‌شوند. مبلغی را که خریدار پرداخته است (با مالیات بر ارزش افزوده) وارد کنید؛ کارپوشه سهم بدون مالیات را نگه می‌دارد. ردیف‌هایی که نزد سازمان ثبت شده‌اند قابل ویرایش یا حذف نیستند.'; + + @override + String get motamedAsaPaymentsNotEligible => + 'ثبت پرداخت تازه روی این صورت‌حساب ممکن نیست.'; + + @override + String get motamedAsaPaymentsEmpty => + 'هنوز ردیف پرداختی برای این صورت‌حساب نیست.'; + + @override + String get motamedAsaPaymentsAddRow => 'افزودن پرداخت'; + + @override + String get motamedAsaPaymentsRegister => 'ثبت در کارپوشه'; + + @override + String get motamedAsaPaymentsRegistered => + 'پرداخت‌ها برای ثبت در کارپوشه ارسال شد.'; + + @override + String get motamedAsaPaymentsResultUnknown => + 'پاسخ ثبت نرسید. ردیف‌های زیر وضعیت فعلی نزد معتمد آسا است؛ پیش از ارسال دوباره آن‌ها را بررسی کنید.'; + + @override + String get motamedAsaPaymentType => 'روش پرداخت'; + + @override + String get motamedAsaPaymentDate => 'تاریخ پرداخت'; + + @override + String get motamedAsaPaymentAmount => 'مبلغ پرداختی (ریال، با مالیات)'; + + @override + String get motamedAsaPaymentTraceNo => 'شماره پیگیری'; + + @override + String get motamedAsaPaymentTerminal => 'شماره پایانه'; + + @override + String get motamedAsaPaymentDescription => 'توضیح'; + + @override + String get motamedAsaPaymentRegisteredAmount => 'مبلغ ثبت‌شده'; + + @override + String get motamedAsaPaymentRemoveRow => 'حذف ردیف'; + + @override + String get motamedAsaPaymentAmountInvalid => + 'مبلغ را به ریال، عدد صحیح و بزرگ‌تر از صفر وارد کنید.'; + + @override + String get motamedAsaPaymentDigitsInvalid => + 'فقط رقم و در حد طول مجاز وارد کنید.'; + + @override + String get motamedAsaPaymentDateRequired => + 'تاریخ پرداخت همه ردیف‌ها را انتخاب کنید.'; + + @override + String get motamedAsaPaymentTypeCheque => 'چک'; + + @override + String get motamedAsaPaymentTypeBarter => 'تهاتر'; + + @override + String get motamedAsaPaymentTypeCash => 'نقد'; + + @override + String get motamedAsaPaymentTypePos => 'کارت‌خوان'; + + @override + String get motamedAsaPaymentTypeInternet => 'درگاه پرداخت اینترنتی'; + + @override + String get motamedAsaPaymentTypeCard => 'کارت به کارت'; + + @override + String get motamedAsaPaymentTypeTransfer => 'انتقال به حساب'; + + @override + String get motamedAsaPaymentTypeOther => 'سایر'; + + @override + String get motamedAsaPaymentStatusRegistered => 'ثبت شده'; + + @override + String get motamedAsaPaymentStatusSentWithInvoice => + 'همراه صورت‌حساب ارسال شده'; + + @override + String get motamedAsaPaymentStatusQueued => 'در صف ثبت'; + + @override + String get motamedAsaPaymentStatusNotRegistered => + 'همراه صورت‌حساب ارسال می‌شود'; + + @override + String get motamedAsaPaymentStatusUnknown => 'نتیجه نامشخص'; + + @override + String get motamedAsaPaymentStatusRejected => 'رد شده'; + + @override + String get motamedAsaPaymentStatusFailed => 'ناموفق'; + + @override + String get motamedAsaPaymentStatusNotApplicable => 'ارسال نمی‌شود'; } diff --git a/hesabixUI/hesabix_ui/lib/main.dart b/hesabixUI/hesabix_ui/lib/main.dart index 332a7bec..de66474d 100755 --- a/hesabixUI/hesabix_ui/lib/main.dart +++ b/hesabixUI/hesabix_ui/lib/main.dart @@ -274,6 +274,7 @@ import 'pages/admin/ai_marketplace_settings_page.dart'; import 'pages/admin/ai_eval_admin_page.dart'; import 'pages/admin/tax_product_codes_page.dart'; import 'pages/admin/tax_provider_admin_page.dart'; +import 'pages/admin/motamed_asa_provider_admin_page.dart'; import 'pages/admin/zohal_settings_page.dart'; import 'pages/admin/zohal_services_admin_page.dart'; import 'pages/admin/zohal_statistics_page.dart'; @@ -2039,6 +2040,22 @@ class _MyAppState extends State { return const TaxProviderAdminPage(); }, ), + GoRoute( + path: 'tax-provider-motamed-asa', + name: 'system_settings_tax_provider_motamed_asa', + builder: (context, state) { + if (_authStore == null) { + return PermissionGuard.buildAccessDeniedPage(); + } + final allowed = + _authStore!.isSuperAdmin || + _authStore!.hasAppPermission('system_settings'); + if (!allowed) { + return PermissionGuard.buildAccessDeniedPage(); + } + return const MotamedAsaProviderAdminPage(); + }, + ), GoRoute( path: 'storage-plans', name: 'system_settings_storage_plans', diff --git a/hesabixUI/hesabix_ui/lib/models/tax_settings_model.dart b/hesabixUI/hesabix_ui/lib/models/tax_settings_model.dart index a81917f9..979b8aa7 100755 --- a/hesabixUI/hesabix_ui/lib/models/tax_settings_model.dart +++ b/hesabixUI/hesabix_ui/lib/models/tax_settings_model.dart @@ -16,6 +16,10 @@ class TaxSettingsModel { final bool fanavaAvailable; final Map? fanavaAccount; final Map enrollmentPrefill; + final bool motamedAsaAvailable; + final Map? motamedAsaAccount; + /// The sign-up link on Motamed ASA; only in the answer that issued it. + final Map? motamedAsaOnboarding; const TaxSettingsModel({ required this.businessId, @@ -35,8 +39,16 @@ class TaxSettingsModel { this.fanavaAvailable = false, this.fanavaAccount, this.enrollmentPrefill = const {}, + this.motamedAsaAvailable = false, + this.motamedAsaAccount, + this.motamedAsaOnboarding, }); + String? get motamedAsaOnboardingUrl { + final url = motamedAsaOnboarding?['url']?.toString(); + return url == null || url.isEmpty ? null : url; + } + factory TaxSettingsModel.fromJson(Map json) { return TaxSettingsModel( businessId: json['business_id'] is int @@ -66,6 +78,13 @@ class TaxSettingsModel { enrollmentPrefill: json['enrollment_prefill'] is Map ? Map.from(json['enrollment_prefill'] as Map) : const {}, + motamedAsaAvailable: json['motamed_asa_available'] == true, + motamedAsaAccount: json['motamed_asa_account'] is Map + ? Map.from(json['motamed_asa_account'] as Map) + : null, + motamedAsaOnboarding: json['motamed_asa_onboarding'] is Map + ? Map.from(json['motamed_asa_onboarding'] as Map) + : null, ); } @@ -106,6 +125,8 @@ class TaxSettingsModel { bool? fanavaAvailable, Map? fanavaAccount, Map? enrollmentPrefill, + bool? motamedAsaAvailable, + Map? motamedAsaAccount, }) { return TaxSettingsModel( businessId: businessId, @@ -125,6 +146,8 @@ class TaxSettingsModel { fanavaAvailable: fanavaAvailable ?? this.fanavaAvailable, fanavaAccount: fanavaAccount ?? this.fanavaAccount, enrollmentPrefill: enrollmentPrefill ?? this.enrollmentPrefill, + motamedAsaAvailable: motamedAsaAvailable ?? this.motamedAsaAvailable, + motamedAsaAccount: motamedAsaAccount ?? this.motamedAsaAccount, ); } } diff --git a/hesabixUI/hesabix_ui/lib/pages/admin/motamed_asa_provider_admin_page.dart b/hesabixUI/hesabix_ui/lib/pages/admin/motamed_asa_provider_admin_page.dart new file mode 100644 index 00000000..f28dd3be --- /dev/null +++ b/hesabixUI/hesabix_ui/lib/pages/admin/motamed_asa_provider_admin_page.dart @@ -0,0 +1,270 @@ +import 'package:flutter/material.dart'; + +import '../../l10n/app_localizations.dart'; +import '../../services/tax_provider_admin_service.dart'; +import '../../utils/error_extractor.dart'; +import '../../utils/snackbar_helper.dart'; + +class MotamedAsaProviderAdminPage extends StatefulWidget { + const MotamedAsaProviderAdminPage({super.key}); + + @override + State createState() => _MotamedAsaProviderAdminPageState(); +} + +class _MotamedAsaProviderAdminPageState extends State { + static const _defaultBaseUrl = 'https://api-v2.asatsp.ir'; + + final _service = TaxProviderAdminService(); + final _formKey = GlobalKey(); + final _baseUrl = TextEditingController(text: _defaultBaseUrl); + final _clientId = TextEditingController(); + final _clientSecret = TextEditingController(); + + Map _settings = const {}; + bool _loading = true; + bool _saving = false; + bool _testing = false; + bool _active = false; + String? _loadError; + + @override + void initState() { + super.initState(); + _load(); + } + + @override + void dispose() { + _baseUrl.dispose(); + _clientId.dispose(); + _clientSecret.dispose(); + super.dispose(); + } + + Future _load() async { + setState(() { + _loading = true; + _loadError = null; + }); + try { + final result = await _service.getMotamedAsaSettings(); + if (!mounted) return; + setState(() { + _settings = result; + _baseUrl.text = result['base_url']?.toString() ?? _defaultBaseUrl; + _active = result['is_active'] == true; + }); + } catch (error) { + if (mounted) setState(() => _loadError = ErrorExtractor.forContext(error, context)); + } finally { + if (mounted) setState(() => _loading = false); + } + } + + Future _save() async { + final t = AppLocalizations.of(context); + if (!(_formKey.currentState?.validate() ?? false)) return; + if (_active && + ((_settings['client_id_configured'] != true && _clientId.text.trim().isEmpty) || + (_settings['client_secret_configured'] != true && _clientSecret.text.isEmpty))) { + SnackBarHelper.showError(context, message: t.motamedAsaNotConfigured); + return; + } + + setState(() => _saving = true); + try { + final result = await _service.saveMotamedAsaSettings({ + 'base_url': _baseUrl.text.trim(), + 'is_active': _active, + if (_clientId.text.trim().isNotEmpty) 'client_id': _clientId.text.trim(), + if (_clientSecret.text.isNotEmpty) 'client_secret': _clientSecret.text, + }); + if (!mounted) return; + setState(() { + _settings = result; + _active = result['is_active'] == true; + _clientId.clear(); + _clientSecret.clear(); + }); + SnackBarHelper.show(context, message: t.motamedAsaSaved); + } catch (error) { + if (mounted) { + SnackBarHelper.showError(context, message: ErrorExtractor.forContext(error, context)); + } + } finally { + if (mounted) setState(() => _saving = false); + } + } + + Future _testConnection() async { + final t = AppLocalizations.of(context); + if (_clientId.text.trim().isNotEmpty || + _clientSecret.text.isNotEmpty || + _baseUrl.text.trim() != (_settings['base_url']?.toString() ?? _defaultBaseUrl)) { + SnackBarHelper.showError(context, message: t.taxProviderSaveBeforeTest); + return; + } + setState(() => _testing = true); + try { + final result = await _service.testMotamedAsaConnection(); + if (!mounted) return; + String state(bool value) => value ? t.taxProviderActive : t.taxProviderInactive; + await showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + icon: const Icon(Icons.cloud_done_outlined), + title: Text(t.motamedAsaAdminTitle), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(t.motamedAsaTestSuccess), + const SizedBox(height: 12), + if (result['display_name'] != null) Text(result['display_name'].toString()), + Text('${t.motamedAsaHostedOnboarding}: ${state(result['hosted_onboarding'] == true)}'), + Text('${t.motamedAsaCredentialHandover}: ${state(result['credential_handover'] == true)}'), + ], + ), + actions: [ + TextButton(onPressed: () => Navigator.pop(dialogContext), child: Text(t.close)), + ], + ), + ); + } catch (error) { + if (mounted) { + SnackBarHelper.showError(context, message: ErrorExtractor.forContext(error, context)); + } + } finally { + if (mounted) setState(() => _testing = false); + } + } + + @override + Widget build(BuildContext context) { + final t = AppLocalizations.of(context); + final cs = Theme.of(context).colorScheme; + return Scaffold( + appBar: AppBar(title: Text(t.motamedAsaAdminTitle)), + body: _loading + ? const Center(child: CircularProgressIndicator()) + : _loadError != null + ? Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text(_loadError!, textAlign: TextAlign.center), + const SizedBox(height: 12), + OutlinedButton.icon(onPressed: _load, icon: const Icon(Icons.refresh), label: Text(t.reload)), + ], + ), + ) + : Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 760), + child: SingleChildScrollView( + padding: const EdgeInsets.all(20), + child: Form( + key: _formKey, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Card( + child: Padding( + padding: const EdgeInsets.all(20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(t.motamedAsaAdminDescription), + const SizedBox(height: 20), + TextFormField( + controller: _baseUrl, + textDirection: TextDirection.ltr, + decoration: InputDecoration(labelText: t.motamedAsaBaseUrl), + validator: (value) { + final uri = Uri.tryParse(value?.trim() ?? ''); + if (uri == null || uri.scheme != 'https' || uri.host.isEmpty) { + return t.taxProviderInvalidUrl; + } + return null; + }, + ), + const SizedBox(height: 12), + TextFormField( + controller: _clientId, + textDirection: TextDirection.ltr, + decoration: InputDecoration( + labelText: t.motamedAsaPartnerClientId, + hintText: 'v2-partner-12345', + helperText: _settings['client_id_configured'] == true + ? '${t.motamedAsaKeepSecretHint} (${_settings['client_id_masked'] ?? '•••'})' + : null, + ), + validator: (value) { + final text = value?.trim() ?? ''; + if (text.isNotEmpty && !text.startsWith('v2-partner-')) { + return t.motamedAsaPartnerClientIdInvalid; + } + return null; + }, + ), + const SizedBox(height: 12), + TextFormField( + controller: _clientSecret, + obscureText: true, + textDirection: TextDirection.ltr, + decoration: InputDecoration( + labelText: t.motamedAsaPartnerClientSecret, + helperText: t.motamedAsaKeepSecretHint, + ), + ), + const SizedBox(height: 12), + SwitchListTile( + contentPadding: EdgeInsets.zero, + value: _active, + onChanged: (value) => setState(() => _active = value), + title: Text(t.motamedAsaActivate), + subtitle: Text( + _active ? t.motamedAsaEnabledHint : t.motamedAsaDisabledHint, + style: TextStyle(color: cs.onSurfaceVariant), + ), + ), + if (_settings['updated_at'] != null) ...[ + const SizedBox(height: 8), + Text('${t.taxProviderActiveState}: ${_settings['is_active'] == true ? t.taxProviderActive : t.taxProviderInactive}'), + ], + ], + ), + ), + ), + const SizedBox(height: 16), + Wrap( + spacing: 12, + runSpacing: 12, + alignment: WrapAlignment.end, + children: [ + OutlinedButton.icon( + onPressed: (_saving || _testing) ? null : _testConnection, + icon: _testing + ? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2)) + : const Icon(Icons.network_check), + label: Text(t.motamedAsaCheckConnection), + ), + FilledButton.icon( + onPressed: (_saving || _testing) ? null : _save, + icon: _saving + ? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2)) + : const Icon(Icons.save_outlined), + label: Text(t.motamedAsaSave), + ), + ], + ), + ], + ), + ), + ), + ), + ), + ); + } +} diff --git a/hesabixUI/hesabix_ui/lib/pages/business/tax_settings_page.dart b/hesabixUI/hesabix_ui/lib/pages/business/tax_settings_page.dart index 136e197a..af3e67d7 100755 --- a/hesabixUI/hesabix_ui/lib/pages/business/tax_settings_page.dart +++ b/hesabixUI/hesabix_ui/lib/pages/business/tax_settings_page.dart @@ -3,6 +3,7 @@ import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:intl/intl.dart'; +import 'package:url_launcher/url_launcher.dart'; import '../../l10n/app_localizations.dart'; import '../../models/tax_settings_model.dart'; @@ -39,6 +40,7 @@ class _TaxSettingsPageState extends State { bool _saving = false; bool _providerSaving = false; bool _fanavaSyncing = false; + bool _motamedAsaBusy = false; String? _error; TaxSettingsModel? _settings; TaxDataQualityReport? _dataQuality; @@ -85,6 +87,10 @@ class _TaxSettingsPageState extends State { _loading = false; }); _loadDataQuality(); + // Coming back from the Motamed ASA sign-up page: pick up the result without a click. + if (_settings?.motamedAsaAccount?['status'] == 'onboarding') { + _syncMotamedAsa(silent: true); + } } } } @@ -362,6 +368,333 @@ class _TaxSettingsPageState extends State { } } + static final Uri _motamedAsaRulesUri = Uri.parse('https://asatsp.ir/rules'); + static final Uri _motamedAsaPrivacyUri = Uri.parse('https://asatsp.ir/privacy#partner-software'); + + Future _requestMotamedAsaConsent() async { + final t = AppLocalizations.of(context); + bool consent = false; + final result = await showDialog( + context: context, + barrierDismissible: false, + builder: (dialogContext) => StatefulBuilder( + builder: (dialogContext, setDialogState) { + final textTheme = Theme.of(dialogContext).textTheme; + return AlertDialog( + title: Text(t.motamedAsaConsentTitle), + content: SizedBox( + width: 560, + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(t.motamedAsaConsentDescription), + const SizedBox(height: 16), + Text(t.motamedAsaSharedDataTitle, style: textTheme.titleSmall), + const SizedBox(height: 8), + _consentBullet(t.motamedAsaSharedDataSignup), + _consentBullet(t.motamedAsaSharedDataInvoices), + const SizedBox(height: 8), + Text(t.motamedAsaSharedDataPurpose, style: textTheme.bodySmall), + const SizedBox(height: 8), + Wrap( + spacing: 8, + children: [ + TextButton.icon( + onPressed: () => launchUrl(_motamedAsaRulesUri, mode: LaunchMode.externalApplication), + icon: const Icon(Icons.gavel_outlined, size: 18), + label: Text(t.motamedAsaTermsLink), + ), + TextButton.icon( + onPressed: () => launchUrl(_motamedAsaPrivacyUri, mode: LaunchMode.externalApplication), + icon: const Icon(Icons.privacy_tip_outlined, size: 18), + label: Text(t.motamedAsaPrivacyLink), + ), + ], + ), + CheckboxListTile( + contentPadding: EdgeInsets.zero, + value: consent, + controlAffinity: ListTileControlAffinity.leading, + onChanged: (value) => setDialogState(() => consent = value == true), + title: Text(t.motamedAsaConsentCheckbox), + ), + ], + ), + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext, false), + child: Text(t.cancel), + ), + FilledButton.icon( + onPressed: consent ? () => Navigator.pop(dialogContext, true) : null, + icon: const Icon(Icons.open_in_new), + label: Text(t.motamedAsaContinueButton), + ), + ], + ); + }, + ), + ); + return result == true; + } + + Widget _consentBullet(String text) { + return Padding( + padding: const EdgeInsets.only(bottom: 6), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Padding( + padding: EdgeInsets.only(top: 2), + child: Icon(Icons.check_circle_outline, size: 18), + ), + const SizedBox(width: 8), + Expanded(child: Text(text)), + ], + ), + ); + } + + String? _validMotamedAsaEconomicCode() { + final economicCode = _convertDigitsToEnglish(_economicCodeController.text.trim()); + if (!RegExp(r'^(\d{11}|\d{14})$').hasMatch(economicCode)) { + SnackBarHelper.showError(context, message: AppLocalizations.of(context).motamedAsaEconomicCodeRequired); + return null; + } + return economicCode; + } + + Future _selectMotamedAsa() async { + final t = AppLocalizations.of(context); + if (_providerSaving || _saving || _motamedAsaBusy) return; + if (_settings?.submissionProvider == 'motamed_asa' && + _settings?.motamedAsaAccount?['connected'] == true) { + return; + } + final economicCode = _validMotamedAsaEconomicCode(); + if (economicCode == null) return; + if (!await _requestMotamedAsaConsent() || !mounted) return; + + setState(() => _providerSaving = true); + try { + final result = await _service.selectProvider( + businessId: widget.businessId, + providerCode: 'motamed_asa', + consent: true, + economicCode: economicCode, + ); + if (!mounted) return; + setState(() => _settings = result); + final url = result.motamedAsaOnboardingUrl; + if (url != null) { + await _openMotamedAsaSignup(url); + } else if (result.motamedAsaAccount?['connected'] == true) { + SnackBarHelper.show(context, message: t.motamedAsaConnectedSuccess); + } + } catch (e) { + if (mounted) { + SnackBarHelper.showError(context, message: ErrorExtractor.forContext(e, context)); + await _load(); + } + } finally { + if (mounted) setState(() => _providerSaving = false); + } + } + + Future _openMotamedAsaSignup(String url) async { + final t = AppLocalizations.of(context); + final uri = Uri.tryParse(url); + var opened = false; + if (uri != null && uri.scheme == 'https') { + try { + opened = await launchUrl(uri, mode: LaunchMode.externalApplication); + } catch (_) { + opened = false; + } + } + if (!mounted) return; + if (opened) { + SnackBarHelper.show(context, message: t.motamedAsaSignupOpened); + return; + } + await showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: Text(t.motamedAsaOpenSignup), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(t.motamedAsaLinkCopyHint), + const SizedBox(height: 8), + SelectableText(url, textDirection: TextDirection.ltr), + ], + ), + actions: [ + TextButton.icon( + onPressed: () => _copyToClipboard(url), + icon: const Icon(Icons.copy, size: 18), + label: Text(t.copyLink), + ), + TextButton(onPressed: () => Navigator.pop(dialogContext), child: Text(t.close)), + ], + ), + ); + } + + Future _renewMotamedAsaLink() async { + if (_motamedAsaBusy) return; + setState(() => _motamedAsaBusy = true); + try { + final data = await _service.renewMotamedAsaLink(widget.businessId); + final onboarding = data['motamed_asa_onboarding']; + final url = onboarding is Map ? onboarding['url']?.toString() : null; + final refreshed = await _service.fetchSettings(widget.businessId); + if (!mounted) return; + setState(() => _settings = refreshed); + if (url != null && url.isNotEmpty) { + await _openMotamedAsaSignup(url); + } else if (refreshed.motamedAsaAccount?['connected'] == true) { + SnackBarHelper.show(context, message: AppLocalizations.of(context).motamedAsaConnectedSuccess); + } + } catch (e) { + if (mounted) SnackBarHelper.showError(context, message: ErrorExtractor.forContext(e, context)); + } finally { + if (mounted) setState(() => _motamedAsaBusy = false); + } + } + + Future _syncMotamedAsa({bool silent = false}) async { + if (_motamedAsaBusy) return; + setState(() => _motamedAsaBusy = true); + try { + await _service.syncMotamedAsaAccount(widget.businessId); + final refreshed = await _service.fetchSettings(widget.businessId); + if (!mounted) return; + setState(() => _settings = refreshed); + final t = AppLocalizations.of(context); + if (refreshed.motamedAsaAccount?['connected'] == true && + refreshed.submissionProvider == 'motamed_asa') { + if (!silent) SnackBarHelper.show(context, message: t.motamedAsaConnectedSuccess); + } else if (!silent) { + SnackBarHelper.show(context, message: t.motamedAsaSyncSuccess); + } + } catch (e) { + if (mounted && !silent) { + SnackBarHelper.showError(context, message: ErrorExtractor.forContext(e, context)); + } + } finally { + if (mounted) setState(() => _motamedAsaBusy = false); + } + } + + Future _enterMotamedAsaCredentials() async { + final t = AppLocalizations.of(context); + if (_motamedAsaBusy) return; + final economicCode = _validMotamedAsaEconomicCode(); + if (economicCode == null) return; + final formKey = GlobalKey(); + final clientId = TextEditingController(); + final clientSecret = TextEditingController(); + bool consent = false; + try { + final submitted = await showDialog( + context: context, + barrierDismissible: false, + builder: (dialogContext) => StatefulBuilder( + builder: (dialogContext, setDialogState) => AlertDialog( + title: Text(t.motamedAsaCredentialsTitle), + content: SizedBox( + width: 520, + child: SingleChildScrollView( + child: Form( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(t.motamedAsaCredentialsDescription), + const SizedBox(height: 16), + TextFormField( + controller: clientId, + textDirection: TextDirection.ltr, + decoration: InputDecoration( + labelText: t.motamedAsaClientId, + hintText: 'v2-customer-12345', + border: const OutlineInputBorder(), + ), + validator: (value) => RegExp(r'^v2-customer-\d+$').hasMatch(value?.trim() ?? '') + ? null + : t.motamedAsaClientIdInvalid, + ), + const SizedBox(height: 12), + TextFormField( + controller: clientSecret, + obscureText: true, + textDirection: TextDirection.ltr, + decoration: InputDecoration( + labelText: t.motamedAsaClientSecret, + border: const OutlineInputBorder(), + ), + validator: (value) => value == null || value.trim().isEmpty ? t.required : null, + ), + const SizedBox(height: 12), + CheckboxListTile( + contentPadding: EdgeInsets.zero, + value: consent, + controlAffinity: ListTileControlAffinity.leading, + onChanged: (value) => setDialogState(() => consent = value == true), + title: Text(t.motamedAsaConsentCheckbox), + ), + ], + ), + ), + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext, false), + child: Text(t.cancel), + ), + FilledButton.icon( + onPressed: consent + ? () { + if (!(formKey.currentState?.validate() ?? false)) return; + Navigator.pop(dialogContext, true); + } + : null, + icon: const Icon(Icons.link), + label: Text(t.motamedAsaSaveCredentials), + ), + ], + ), + ), + ); + if (submitted != true || !mounted) return; + setState(() => _motamedAsaBusy = true); + await _service.saveMotamedAsaCredentials( + businessId: widget.businessId, + clientId: clientId.text.trim(), + clientSecret: clientSecret.text.trim(), + economicCode: economicCode, + ); + final refreshed = await _service.fetchSettings(widget.businessId); + if (!mounted) return; + setState(() => _settings = refreshed); + SnackBarHelper.show(context, message: t.motamedAsaConnectedSuccess); + } catch (e) { + if (mounted) SnackBarHelper.showError(context, message: ErrorExtractor.forContext(e, context)); + } finally { + clientId.dispose(); + clientSecret.dispose(); + if (mounted) setState(() => _motamedAsaBusy = false); + } + } + Future _testConnection() async { final t = AppLocalizations.of(context); @@ -950,6 +1283,24 @@ class _TaxSettingsPageState extends State { : t.fanavaUnavailable, ), ), + RadioListTile( + contentPadding: EdgeInsets.zero, + value: 'motamed_asa', + groupValue: provider, + onChanged: (_saving || _providerSaving || _motamedAsaBusy || _sandboxMode || + _settings?.motamedAsaAvailable != true) + ? null + : (_) => _selectMotamedAsa(), + title: Text(t.taxSubmissionMotamedAsa), + subtitle: Text( + _sandboxMode + ? t.motamedAsaSandboxUnavailable + : _settings?.motamedAsaAvailable == true + ? t.taxSubmissionMotamedAsaDescription + : t.motamedAsaUnavailable, + ), + ), + _buildMotamedAsaStatus(t), if (_providerSaving) const LinearProgressIndicator(minHeight: 2) else if (status != 'not_connected' || connected) @@ -1005,6 +1356,84 @@ class _TaxSettingsPageState extends State { ); } + Widget _buildMotamedAsaStatus(AppLocalizations t) { + final account = _settings?.motamedAsaAccount; + if (account == null) return const SizedBox.shrink(); + final status = account['status']?.toString() ?? 'not_connected'; + final connected = account['connected'] == true; + final lastError = account['last_error']?.toString(); + if (!connected && status == 'not_connected' && (lastError == null || lastError.trim().isEmpty)) { + return const SizedBox.shrink(); + } + final memoryId = account['memory_unique_id']?.toString(); + final tone = connected + ? SemanticColorResolver.positive(context) + : SemanticColorResolver.warning(context); + final label = connected + ? t.motamedAsaConnected + : switch (status) { + 'onboarding' => t.motamedAsaOnboarding, + 'credentials_required' => t.motamedAsaCredentialsRequired, + _ => t.motamedAsaNotConnected, + }; + final busy = _motamedAsaBusy || _providerSaving || _saving; + + return Container( + width: double.infinity, + margin: const EdgeInsets.only(top: 8, bottom: 8), + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: tone.withValues(alpha: connected ? 0.10 : 0.12), + borderRadius: BorderRadius.circular(8), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon(connected ? Icons.check_circle_outline : Icons.sync_problem_outlined, color: tone), + const SizedBox(width: 8), + Expanded(child: Text(label)), + ], + ), + if (connected && memoryId != null && memoryId.isNotEmpty) ...[ + const SizedBox(height: 6), + Text('${t.motamedAsaMemoryId}: $memoryId', style: Theme.of(context).textTheme.bodySmall), + ], + if (!connected && lastError != null && lastError.trim().isNotEmpty) ...[ + const SizedBox(height: 6), + Text(lastError, style: Theme.of(context).textTheme.bodySmall), + ], + const SizedBox(height: 4), + Wrap( + spacing: 4, + children: [ + if (!connected && status != 'credentials_required') + TextButton.icon( + onPressed: busy ? null : _renewMotamedAsaLink, + icon: const Icon(Icons.open_in_new, size: 18), + label: Text(t.motamedAsaOpenSignup), + ), + if (!connected) + TextButton.icon( + onPressed: busy ? null : _enterMotamedAsaCredentials, + icon: const Icon(Icons.vpn_key_outlined, size: 18), + label: Text(t.motamedAsaEnterCredentials), + ), + TextButton.icon( + onPressed: busy ? null : () => _syncMotamedAsa(), + icon: _motamedAsaBusy + ? const SizedBox(width: 14, height: 14, child: CircularProgressIndicator(strokeWidth: 2)) + : const Icon(Icons.refresh, size: 18), + label: Text(t.motamedAsaCheckConnection), + ), + ], + ), + ], + ), + ); + } + String _fanavaStatusLabel(AppLocalizations t, String status) { switch (status) { case 'registering': diff --git a/hesabixUI/hesabix_ui/lib/pages/business/tax_workspace_page.dart b/hesabixUI/hesabix_ui/lib/pages/business/tax_workspace_page.dart index b4b7207e..dcee7ce4 100755 --- a/hesabixUI/hesabix_ui/lib/pages/business/tax_workspace_page.dart +++ b/hesabixUI/hesabix_ui/lib/pages/business/tax_workspace_page.dart @@ -11,6 +11,7 @@ import 'package:hesabix_ui/widgets/data_table/data_table_widget.dart'; import 'package:hesabix_ui/widgets/data_table/data_table_config.dart'; import 'package:hesabix_ui/widgets/date_input_field.dart'; import 'package:hesabix_ui/widgets/tax/tax_workspace_widgets.dart'; +import 'package:hesabix_ui/widgets/tax/motamed_asa_payments_dialog.dart'; import 'package:hesabix_ui/services/list_filter_preferences_service.dart'; import 'package:hesabix_ui/core/date_utils.dart' show HesabixDateUtils; import '../../utils/error_extractor.dart'; @@ -965,6 +966,12 @@ class _TaxWorkspacePageState extends State { return _taxIsSubmitted(map) && map['tax_cancelled_in_modian'] != true; }, ), + DataTableAction( + icon: Icons.payments_outlined, + label: t.motamedAsaPaymentsAction, + onTap: (item) => _onMotamedAsaPayments(item as Map), + enabled: (item) => _canRegisterMotamedAsaPayments(item as Map), + ), DataTableAction( icon: Icons.remove_circle_outline, label: t.taxRemoveFromWorkspaceSingle, @@ -1052,6 +1059,20 @@ class _TaxWorkspacePageState extends State { ); }, ), + TextColumn( + 'tax_workspace_status', + t.taxWorkspaceStatusColumn, + formatter: (item) => + taxWorkspaceStatusLabel(t, (item as Map)['tax_workspace_status']) ?? '-', + width: ColumnWidth.medium, + ), + TextColumn( + 'tax_article6_status', + t.taxArticle6Column, + formatter: (item) => + taxArticle6Label(t, (item as Map)['tax_article6_status']) ?? '-', + width: ColumnWidth.small, + ), TextColumn( 'tax_error_message', t.taxErrorMessageColumn, @@ -1134,6 +1155,8 @@ class _TaxWorkspacePageState extends State { PopupMenuItem(value: 'cancel', child: Text(t.taxCancelInModian)), if (_taxIsSubmitted(item) && item['tax_cancelled_in_modian'] != true) PopupMenuItem(value: 'corrective', child: Text(t.taxSendCorrective)), + if (_canRegisterMotamedAsaPayments(item)) + PopupMenuItem(value: 'payments', child: Text(t.motamedAsaPaymentsAction)), PopupMenuItem(value: 'open', child: Text(t.taxOpenInvoice)), ], onMoreSelected: (value) { @@ -1144,6 +1167,9 @@ class _TaxWorkspacePageState extends State { case 'corrective': _onSendCorrective(item); break; + case 'payments': + _onMotamedAsaPayments(item); + break; case 'open': _openInvoice(id); break; @@ -1157,6 +1183,27 @@ class _TaxWorkspacePageState extends State { return status == 'sent' || status == 'finalized' || status == 'accepted'; } + /// Payments are registered in the کارپوشه through Motamed ASA for invoices sent that way. + bool _canRegisterMotamedAsaPayments(Map map) { + return map['tax_submission_provider'] == 'motamed_asa' && + _taxIsSubmitted(map) && + map['tax_cancelled_in_modian'] != true && + map['document_type']?.toString() != 'invoice_sales_return'; + } + + Future _onMotamedAsaPayments(Map item) async { + final id = item['id'] is int ? item['id'] as int : int.tryParse(item['id']?.toString() ?? ''); + if (id == null) return; + await MotamedAsaPaymentsDialog.show( + context, + businessId: widget.businessId, + invoiceId: id, + invoiceCode: item['code']?.toString() ?? '', + apiClient: widget.apiClient, + calendarController: widget.calendarController, + ); + } + Future _pickTaxReferenceInvoice() async { final t = AppLocalizations.of(context); final api = widget.apiClient; diff --git a/hesabixUI/hesabix_ui/lib/pages/system_settings/services/settings_categorization_service.dart b/hesabixUI/hesabix_ui/lib/pages/system_settings/services/settings_categorization_service.dart index 1b9f2eae..6a6c8afb 100755 --- a/hesabixUI/hesabix_ui/lib/pages/system_settings/services/settings_categorization_service.dart +++ b/hesabixUI/hesabix_ui/lib/pages/system_settings/services/settings_categorization_service.dart @@ -473,6 +473,16 @@ class SettingsCategorizationService { categoryId: 'external_services', order: 4, ), + SettingsItem( + id: 'tax_provider_motamed_asa', + title: 'settingsMotamedAsa', + description: 'settingsMotamedAsaDescription', + icon: Icons.verified_outlined, + color: const Color(0xFF00695C), + route: '/user/profile/system-settings/tax-provider-motamed-asa', + categoryId: 'external_services', + order: 5, + ), ], ), diff --git a/hesabixUI/hesabix_ui/lib/pages/system_settings/utils/localization_helper.dart b/hesabixUI/hesabix_ui/lib/pages/system_settings/utils/localization_helper.dart index d8cee564..4c98e796 100755 --- a/hesabixUI/hesabix_ui/lib/pages/system_settings/utils/localization_helper.dart +++ b/hesabixUI/hesabix_ui/lib/pages/system_settings/utils/localization_helper.dart @@ -82,6 +82,8 @@ class LocalizationHelper { return t.settingsTaxProductCodes; case 'settingsTaxProviders': return t.settingsTaxProviders; + case 'settingsMotamedAsa': + return t.settingsMotamedAsa; case 'settingsSystemMonitoring': return t.settingsSystemMonitoring; case 'settingsServiceLogs': @@ -172,6 +174,8 @@ class LocalizationHelper { return t.settingsTaxProductCodesDescription; case 'settingsTaxProvidersDescription': return t.settingsTaxProvidersDescription; + case 'settingsMotamedAsaDescription': + return t.settingsMotamedAsaDescription; case 'settingsSystemMonitoringDescription': return t.settingsSystemMonitoringDescription; case 'settingsServiceLogsDescription': diff --git a/hesabixUI/hesabix_ui/lib/services/tax_provider_admin_service.dart b/hesabixUI/hesabix_ui/lib/services/tax_provider_admin_service.dart index 5fab960a..8a5bbc64 100644 --- a/hesabixUI/hesabix_ui/lib/services/tax_provider_admin_service.dart +++ b/hesabixUI/hesabix_ui/lib/services/tax_provider_admin_service.dart @@ -26,4 +26,24 @@ class TaxProviderAdminService { ); return Map.from(response.data?['data'] as Map? ?? const {}); } + + Future> getMotamedAsaSettings() async { + final response = await _api.get>('/api/v1/admin/tax-providers/motamed-asa'); + return Map.from(response.data?['data'] as Map? ?? const {}); + } + + Future> saveMotamedAsaSettings(Map data) async { + final response = await _api.put>( + '/api/v1/admin/tax-providers/motamed-asa', + data: data, + ); + return Map.from(response.data?['data'] as Map? ?? const {}); + } + + Future> testMotamedAsaConnection() async { + final response = await _api.post>( + '/api/v1/admin/tax-providers/motamed-asa/test-connection', + ); + return Map.from(response.data?['data'] as Map? ?? const {}); + } } diff --git a/hesabixUI/hesabix_ui/lib/services/tax_settings_service.dart b/hesabixUI/hesabix_ui/lib/services/tax_settings_service.dart index 9fbe1b3f..9c0366c2 100755 --- a/hesabixUI/hesabix_ui/lib/services/tax_settings_service.dart +++ b/hesabixUI/hesabix_ui/lib/services/tax_settings_service.dart @@ -110,6 +110,7 @@ class TaxSettingsService { required String providerCode, bool consent = false, Map? enrollment, + String? economicCode, }) async { try { final response = await _apiClient.post>( @@ -118,6 +119,7 @@ class TaxSettingsService { 'provider_code': providerCode, 'consent': consent, if (enrollment != null) 'enrollment': enrollment, + if (economicCode != null && economicCode.isNotEmpty) 'economic_code': economicCode, }, ); final data = response.data?['data']; @@ -143,6 +145,57 @@ class TaxSettingsService { } } + Future> syncMotamedAsaAccount(int businessId) async { + try { + final response = await _apiClient.post>( + '/tax-settings/business/$businessId/motamed-asa/sync', + ); + final data = response.data?['data']; + if (data is Map) return data; + throw Exception('پاسخ نامعتبر از سرور'); + } on DioException catch (e) { + throw _extractMessage(e, defaultMessage: 'بررسی اتصال معتمد آسا ناموفق بود'); + } + } + + /// A fresh sign-up link on Motamed ASA, under `motamed_asa_onboarding.url`. + Future> renewMotamedAsaLink(int businessId) async { + try { + final response = await _apiClient.post>( + '/tax-settings/business/$businessId/motamed-asa/link', + ); + final data = response.data?['data']; + if (data is Map) return data; + throw Exception('پاسخ نامعتبر از سرور'); + } on DioException catch (e) { + throw _extractMessage(e, defaultMessage: 'دریافت لینک ثبت‌نام معتمد آسا ناموفق بود'); + } + } + + Future> saveMotamedAsaCredentials({ + required int businessId, + required String clientId, + required String clientSecret, + String? economicCode, + }) async { + try { + final response = await _apiClient.post>( + '/tax-settings/business/$businessId/motamed-asa/credentials', + data: { + 'client_id': clientId, + 'client_secret': clientSecret, + 'consent': true, + if (economicCode != null && economicCode.isNotEmpty) 'economic_code': economicCode, + }, + ); + final data = response.data?['data']; + if (data is Map) return data; + throw Exception('پاسخ نامعتبر از سرور'); + } on DioException catch (e) { + throw _extractMessage(e, defaultMessage: 'ثبت کلید API معتمد آسا ناموفق بود'); + } + } + Exception _extractMessage(DioException exception, {required String defaultMessage}) { final data = exception.response?.data; if (data is Map) { diff --git a/hesabixUI/hesabix_ui/lib/widgets/tax/motamed_asa_payments_dialog.dart b/hesabixUI/hesabix_ui/lib/widgets/tax/motamed_asa_payments_dialog.dart new file mode 100644 index 00000000..e6a88aba --- /dev/null +++ b/hesabixUI/hesabix_ui/lib/widgets/tax/motamed_asa_payments_dialog.dart @@ -0,0 +1,518 @@ +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart' show NumberFormat; + +import '../../core/api_client.dart'; +import '../../core/calendar_controller.dart'; +import '../../l10n/app_localizations.dart'; +import '../../utils/error_extractor.dart'; +import '../../utils/snackbar_helper.dart'; +import '../date_input_field.dart'; +import 'package:hesabix_ui/theme/semantic_color_resolver.dart'; + +/// جدول پرداخت صورت‌حسابی که از طریق معتمد آسا ارسال شده و ثبت ردیف‌های تازه در کارپوشه سامانه مودیان. +class MotamedAsaPaymentsDialog extends StatefulWidget { + final int businessId; + final int invoiceId; + final String invoiceCode; + final ApiClient apiClient; + final CalendarController calendarController; + + const MotamedAsaPaymentsDialog({ + super.key, + required this.businessId, + required this.invoiceId, + required this.invoiceCode, + required this.apiClient, + required this.calendarController, + }); + + static Future show( + BuildContext context, { + required int businessId, + required int invoiceId, + required String invoiceCode, + required ApiClient apiClient, + required CalendarController calendarController, + }) { + return showDialog( + context: context, + barrierDismissible: false, + builder: (_) => MotamedAsaPaymentsDialog( + businessId: businessId, + invoiceId: invoiceId, + invoiceCode: invoiceCode, + apiClient: apiClient, + calendarController: calendarController, + ), + ); + } + + @override + State createState() => _MotamedAsaPaymentsDialogState(); +} + +class _NewPaymentRow { + int? type; + DateTime? date; + TimeOfDay time = TimeOfDay.now(); + final amount = TextEditingController(); + final traceNo = TextEditingController(); + final terminal = TextEditingController(); + final description = TextEditingController(); + + void dispose() { + amount.dispose(); + traceNo.dispose(); + terminal.dispose(); + description.dispose(); + } +} + +class _MotamedAsaPaymentsDialogState extends State { + static final _amountFormat = NumberFormat.decimalPattern(); + final _formKey = GlobalKey(); + final List<_NewPaymentRow> _rows = []; + + Map? _state; + String? _loadError; + bool _loading = true; + bool _submitting = false; + bool _resultUnknown = false; + + String get _path => + '/tax-settings/business/${widget.businessId}/motamed-asa/invoices/${widget.invoiceId}/payments'; + + @override + void initState() { + super.initState(); + _load(); + } + + @override + void dispose() { + for (final row in _rows) { + row.dispose(); + } + super.dispose(); + } + + Future _load() async { + setState(() { + _loading = true; + _loadError = null; + }); + try { + final response = await widget.apiClient.get>(_path); + final data = response.data?['data']; + if (!mounted) return; + setState(() => _state = data is Map ? Map.from(data) : const {}); + } catch (e) { + if (mounted) setState(() => _loadError = ErrorExtractor.forContext(e, context)); + } finally { + if (mounted) setState(() => _loading = false); + } + } + + static String _latinDigits(String value) { + const persian = '۰۱۲۳۴۵۶۷۸۹'; + const arabic = '٠١٢٣٤٥٦٧٨٩'; + final buffer = StringBuffer(); + for (final char in value.split('')) { + final p = persian.indexOf(char); + final a = arabic.indexOf(char); + buffer.write(p >= 0 ? '$p' : a >= 0 ? '$a' : char); + } + return buffer.toString(); + } + + static String _digitsOnly(String value) => + _latinDigits(value).replaceAll(RegExp(r'[\s,٬،]'), ''); + + void _addRow() { + setState(() => _rows.add(_NewPaymentRow()..date = DateTime.now())); + } + + void _removeRow(_NewPaymentRow row) { + setState(() => _rows.remove(row)); + row.dispose(); + } + + Future _pickTime(_NewPaymentRow row) async { + final picked = await showTimePicker(context: context, initialTime: row.time); + if (picked != null && mounted) setState(() => row.time = picked); + } + + Future _submit() async { + final t = AppLocalizations.of(context); + if (_rows.isEmpty || !(_formKey.currentState?.validate() ?? false)) return; + for (final row in _rows) { + if (row.date == null) { + SnackBarHelper.showError(context, message: t.motamedAsaPaymentDateRequired); + return; + } + } + final payments = _rows.map((row) { + final date = row.date!; + final moment = DateTime(date.year, date.month, date.day, row.time.hour, row.time.minute); + return { + 'type': row.type, + 'timestamp': moment.millisecondsSinceEpoch, + 'price': int.parse(_digitsOnly(row.amount.text)), + if (row.traceNo.text.trim().isNotEmpty) 'trace_no': _digitsOnly(row.traceNo.text), + if (row.terminal.text.trim().isNotEmpty) 'terminal_number': _digitsOnly(row.terminal.text), + if (row.description.text.trim().isNotEmpty) 'description': row.description.text.trim(), + }; + }).toList(); + + setState(() => _submitting = true); + try { + final response = await widget.apiClient.post>( + _path, + data: {'payments': payments}, + ); + final data = response.data?['data']; + if (!mounted) return; + final state = data is Map ? Map.from(data) : {}; + setState(() { + _state = state; + _resultUnknown = state['result_unknown'] == true; + for (final row in _rows) { + row.dispose(); + } + _rows.clear(); + }); + if (_resultUnknown) { + SnackBarHelper.showWarning(context, message: t.motamedAsaPaymentsResultUnknown); + } else { + SnackBarHelper.showSuccess(context, message: t.motamedAsaPaymentsRegistered); + } + } catch (e) { + if (mounted) SnackBarHelper.showError(context, message: ErrorExtractor.forContext(e, context)); + } finally { + if (mounted) setState(() => _submitting = false); + } + } + + String _typeLabel(AppLocalizations t, Object? type) { + switch (int.tryParse(type?.toString() ?? '')) { + case 1: + return t.motamedAsaPaymentTypeCheque; + case 2: + return t.motamedAsaPaymentTypeBarter; + case 3: + return t.motamedAsaPaymentTypeCash; + case 4: + return t.motamedAsaPaymentTypePos; + case 5: + return t.motamedAsaPaymentTypeInternet; + case 6: + return t.motamedAsaPaymentTypeCard; + case 7: + return t.motamedAsaPaymentTypeTransfer; + case 8: + return t.motamedAsaPaymentTypeOther; + default: + return type?.toString() ?? '-'; + } + } + + ({String label, Color color}) _registration(AppLocalizations t, ColorScheme cs, Object? status) { + switch (status?.toString()) { + case 'registered': + return (label: t.motamedAsaPaymentStatusRegistered, color: SemanticColorResolver.positive(context)); + case 'sentWithInvoice': + return (label: t.motamedAsaPaymentStatusSentWithInvoice, color: SemanticColorResolver.positive(context)); + case 'queued': + return (label: t.motamedAsaPaymentStatusQueued, color: SemanticColorResolver.warning(context)); + case 'notRegistered': + return (label: t.motamedAsaPaymentStatusNotRegistered, color: SemanticColorResolver.warning(context)); + case 'unknown': + return (label: t.motamedAsaPaymentStatusUnknown, color: SemanticColorResolver.warning(context)); + case 'rejected': + return (label: t.motamedAsaPaymentStatusRejected, color: cs.error); + case 'failed': + return (label: t.motamedAsaPaymentStatusFailed, color: cs.error); + case 'notApplicable': + return (label: t.motamedAsaPaymentStatusNotApplicable, color: cs.onSurfaceVariant); + default: + return (label: status?.toString() ?? '-', color: cs.onSurfaceVariant); + } + } + + String _money(Object? value) { + final number = num.tryParse(value?.toString() ?? ''); + return number == null ? '-' : _amountFormat.format(number); + } + + Widget _existingPayment(AppLocalizations t, Map payment) { + final theme = Theme.of(context); + final cs = theme.colorScheme; + final status = _registration(t, cs, payment['registration_status']); + final message = payment['registration_message']?.toString(); + final registeredAmount = payment['registered_amount']; + return Container( + margin: const EdgeInsets.only(bottom: 8), + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(8), + border: Border.all(color: cs.outline.withValues(alpha: 0.25)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Expanded( + child: Text( + '${_typeLabel(t, payment['type'])} · ${payment['date_time'] ?? '-'}', + style: theme.textTheme.bodyMedium?.copyWith(fontWeight: FontWeight.w600), + ), + ), + Text(_money(payment['price'])), + ], + ), + const SizedBox(height: 6), + Wrap( + spacing: 8, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), + decoration: BoxDecoration( + color: status.color.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(6), + ), + child: Text(status.label, style: theme.textTheme.bodySmall?.copyWith(color: status.color)), + ), + if (registeredAmount != null) + Text('${t.motamedAsaPaymentRegisteredAmount}: ${_money(registeredAmount)}', + style: theme.textTheme.bodySmall), + if (payment['trace_no'] != null) + Text('${t.motamedAsaPaymentTraceNo}: ${payment['trace_no']}', style: theme.textTheme.bodySmall), + if (payment['locked'] == true) Icon(Icons.lock_outline, size: 16, color: cs.onSurfaceVariant), + ], + ), + if (message != null && message.isNotEmpty) ...[ + const SizedBox(height: 4), + Text(message, style: theme.textTheme.bodySmall?.copyWith(color: cs.error)), + ], + ], + ), + ); + } + + Widget _newPayment(AppLocalizations t, _NewPaymentRow row) { + final theme = Theme.of(context); + final cs = theme.colorScheme; + String? digits(String? value, int max) { + final text = _digitsOnly(value ?? ''); + if (text.isEmpty) return null; + if (!RegExp(r'^\d+$').hasMatch(text) || text.length > max) return t.motamedAsaPaymentDigitsInvalid; + return null; + } + + return Container( + margin: const EdgeInsets.only(bottom: 10), + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: cs.primary.withValues(alpha: 0.04), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: cs.primary.withValues(alpha: 0.25)), + ), + child: Column( + children: [ + Row( + children: [ + Expanded( + child: DropdownButtonFormField( + initialValue: row.type, + decoration: InputDecoration(labelText: t.motamedAsaPaymentType, isDense: true), + items: [ + for (var type = 1; type <= 8; type++) + DropdownMenuItem(value: type, child: Text(_typeLabel(t, type))), + ], + onChanged: (value) => setState(() => row.type = value), + validator: (value) => value == null ? t.required : null, + ), + ), + IconButton( + tooltip: t.motamedAsaPaymentRemoveRow, + onPressed: () => _removeRow(row), + icon: const Icon(Icons.delete_outline), + ), + ], + ), + const SizedBox(height: 10), + Row( + children: [ + Expanded( + child: DateInputField( + value: row.date, + labelText: t.motamedAsaPaymentDate, + calendarController: widget.calendarController, + lastDate: DateTime.now(), + isDense: true, + onChanged: (value) => setState(() => row.date = value), + ), + ), + const SizedBox(width: 8), + OutlinedButton.icon( + onPressed: () => _pickTime(row), + icon: const Icon(Icons.schedule, size: 18), + label: Text(row.time.format(context)), + ), + ], + ), + const SizedBox(height: 10), + TextFormField( + controller: row.amount, + keyboardType: TextInputType.number, + textDirection: TextDirection.ltr, + decoration: InputDecoration(labelText: t.motamedAsaPaymentAmount, isDense: true), + validator: (value) { + final amount = int.tryParse(_digitsOnly(value ?? '')); + return amount == null || amount <= 0 ? t.motamedAsaPaymentAmountInvalid : null; + }, + ), + const SizedBox(height: 10), + Row( + children: [ + Expanded( + child: TextFormField( + controller: row.traceNo, + keyboardType: TextInputType.number, + textDirection: TextDirection.ltr, + decoration: InputDecoration(labelText: t.motamedAsaPaymentTraceNo, isDense: true), + validator: (value) => digits(value, 14), + ), + ), + const SizedBox(width: 8), + Expanded( + child: TextFormField( + controller: row.terminal, + keyboardType: TextInputType.number, + textDirection: TextDirection.ltr, + decoration: InputDecoration(labelText: t.motamedAsaPaymentTerminal, isDense: true), + validator: (value) => digits(value, 8), + ), + ), + ], + ), + const SizedBox(height: 10), + TextFormField( + controller: row.description, + maxLength: 500, + decoration: InputDecoration(labelText: t.motamedAsaPaymentDescription, isDense: true, counterText: ''), + ), + ], + ), + ); + } + + @override + Widget build(BuildContext context) { + final t = AppLocalizations.of(context); + final theme = Theme.of(context); + final cs = theme.colorScheme; + final state = _state ?? const {}; + final eligible = state['eligible'] == true; + final reason = state['reason']?.toString(); + final payments = (state['payments'] is List ? state['payments'] as List : const []) + .whereType() + .map((e) => Map.from(e)) + .toList(); + + Widget body; + if (_loading) { + body = const Padding( + padding: EdgeInsets.all(32), + child: Center(child: CircularProgressIndicator()), + ); + } else if (_loadError != null) { + body = Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text(_loadError!, textAlign: TextAlign.center), + const SizedBox(height: 12), + OutlinedButton.icon(onPressed: _load, icon: const Icon(Icons.refresh), label: Text(t.reload)), + ], + ); + } else { + body = Form( + key: _formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text(t.motamedAsaPaymentsDescription, style: theme.textTheme.bodySmall), + const SizedBox(height: 12), + if (!eligible) + Container( + padding: const EdgeInsets.all(10), + margin: const EdgeInsets.only(bottom: 12), + decoration: BoxDecoration( + color: SemanticColorResolver.warning(context).withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(8), + ), + child: Text( + [t.motamedAsaPaymentsNotEligible, if (reason != null && reason.isNotEmpty) reason].join(' '), + ), + ), + if (_resultUnknown) + Container( + padding: const EdgeInsets.all(10), + margin: const EdgeInsets.only(bottom: 12), + decoration: BoxDecoration( + color: SemanticColorResolver.warning(context).withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(8), + ), + child: Text(t.motamedAsaPaymentsResultUnknown), + ), + if (payments.isEmpty) + Padding( + padding: const EdgeInsets.symmetric(vertical: 8), + child: Text(t.motamedAsaPaymentsEmpty, style: TextStyle(color: cs.onSurfaceVariant)), + ) + else + ...payments.map((payment) => _existingPayment(t, payment)), + if (eligible) ...[ + const SizedBox(height: 8), + for (final row in _rows) _newPayment(t, row), + Align( + alignment: AlignmentDirectional.centerStart, + child: TextButton.icon( + onPressed: _submitting || _rows.length >= 50 ? null : _addRow, + icon: const Icon(Icons.add), + label: Text(t.motamedAsaPaymentsAddRow), + ), + ), + ], + ], + ), + ); + } + + return AlertDialog( + title: Text('${t.motamedAsaPaymentsTitle} ${widget.invoiceCode}'.trim()), + content: SizedBox( + width: 620, + child: SingleChildScrollView(child: body), + ), + actions: [ + TextButton( + onPressed: _submitting ? null : () => Navigator.pop(context), + child: Text(t.close), + ), + if (eligible && _rows.isNotEmpty) + FilledButton.icon( + onPressed: _submitting ? null : _submit, + icon: _submitting + ? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2)) + : const Icon(Icons.cloud_upload_outlined), + label: Text(t.motamedAsaPaymentsRegister), + ), + ], + ); + } +} diff --git a/hesabixUI/hesabix_ui/lib/widgets/tax/tax_workspace_widgets.dart b/hesabixUI/hesabix_ui/lib/widgets/tax/tax_workspace_widgets.dart index 9331e046..0642ae36 100644 --- a/hesabixUI/hesabix_ui/lib/widgets/tax/tax_workspace_widgets.dart +++ b/hesabixUI/hesabix_ui/lib/widgets/tax/tax_workspace_widgets.dart @@ -372,6 +372,8 @@ class TaxWorkspaceMobileCard extends StatelessWidget { final canSend = status != 'sent' && status != 'finalized' && item['tax_cancelled_in_modian'] != true; final hasFailure = status == 'failed' || (err != null && err.isNotEmpty); + final workspaceStatus = taxWorkspaceStatusLabel(t, item['tax_workspace_status']); + final article6 = taxArticle6Label(t, item['tax_article6_status']); return Container( width: double.infinity, @@ -439,6 +441,10 @@ class TaxWorkspaceMobileCard extends StatelessWidget { _miniMeta(theme, Icons.payments_outlined, '$amount $currency'), if (tracking != null && tracking.isNotEmpty) _miniMeta(theme, Icons.tag, tracking), + if (workspaceStatus != null) + _miniMeta(theme, Icons.fact_check_outlined, workspaceStatus), + if (article6 != null) + _miniMeta(theme, Icons.rule, '${t.taxArticle6Column}: $article6'), ], ), if (hasFailure && err != null && err.isNotEmpty) ...[ @@ -745,3 +751,39 @@ class TaxErrorPlaybookCard extends StatelessWidget { ); } } + +/// «وضعیت کارپوشه» صورت‌حساب (واکنش خریدار در سامانه مودیان)؛ مقدار ناشناخته همان‌طور نشان داده می‌شود. +String? taxWorkspaceStatusLabel(AppLocalizations t, Object? raw) { + final value = raw?.toString().trim() ?? ''; + if (value.isEmpty) return null; + switch (value.toUpperCase()) { + case 'NO_NEED_REACTION': + return t.taxWorkspaceStatusNoNeedReaction; + case 'AWAITING_REACTION': + return t.taxWorkspaceStatusAwaitingReaction; + case 'APPROVED': + return t.taxWorkspaceStatusApproved; + case 'SYSTEMIC_APPROVED': + return t.taxWorkspaceStatusSystemicApproved; + case 'IMPOSSIBLE_REACTION': + return t.taxWorkspaceStatusImpossibleReaction; + case 'REJECTED': + return t.taxWorkspaceStatusRejected; + case 'SYSTEMIC_REJECTED': + return t.taxWorkspaceStatusSystemicRejected; + case 'CANCELED': + case 'CANCELLED': + return t.taxWorkspaceStatusCanceled; + default: + return value; + } +} + +/// وضعیت ماده ۶ (عدول / عدم عدول)؛ مقدار ناشناخته همان‌طور نشان داده می‌شود. +String? taxArticle6Label(AppLocalizations t, Object? raw) { + final value = raw?.toString().trim() ?? ''; + if (value.isEmpty) return null; + if (value == 'violated') return t.taxArticle6Violated; + if (value == 'not_violated') return t.taxArticle6NotViolated; + return value; +}