feat(tax): send Motamed ASA invoices to the tax sandbox in sandbox mode #41

Merged
morrning merged 1 commit from asatsp/arc:feature/motamed-asa-sandbox into master 2026-11-07 15:39:23 +03:30
11 changed files with 438 additions and 47 deletions

View file

@ -381,12 +381,6 @@ def save_tax_settings_endpoint(
"فن‌آوا محیط آزمایشی ندارد؛ ابتدا روش ارسال مستقیم را انتخاب کنید.", "فن‌آوا محیط آزمایشی ندارد؛ ابتدا روش ارسال مستقیم را انتخاب کنید.",
http_status=400, 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( setting = upsert_tax_setting(
db, db,

View file

@ -414,12 +414,6 @@ def start_motamed_asa_onboarding(
raise ApiError("BUSINESS_NOT_FOUND", "کسب‌وکار پیدا نشد.", http_status=404) raise ApiError("BUSINESS_NOT_FOUND", "کسب‌وکار پیدا نشد.", http_status=404)
setting = db.query(TaxSetting).filter(TaxSetting.business_id == int(business_id)).first() 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) 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) account = _get_account(db, business_id, lock=True)
if account is None: if account is None:
@ -560,12 +554,6 @@ def save_motamed_asa_business_credentials(
raise ApiError("BUSINESS_NOT_FOUND", "کسب‌وکار پیدا نشد.", http_status=404) raise ApiError("BUSINESS_NOT_FOUND", "کسب‌وکار پیدا نشد.", http_status=404)
setting = db.query(TaxSetting).filter(TaxSetting.business_id == int(business_id)).first() 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) 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) client = MotamedAsaClient(credential.base_url)
try: try:

View file

@ -15,6 +15,14 @@ Operations (API v2 docs, sections 05, 07, 08D):
return document's own lines (the goods taken back) and ASA matches them to 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 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. (RC_IITP.IS_V7.9 table 1, pp. 14-18) with every tax field of the reference.
Sandbox (API v2 docs, section 05F): with the business's sandbox mode on, each
/send member carries sandBox: true; ASA then accepts it only with a Sandbox
fiscal memory of the business and sends it to the tax organisation's sandbox.
editInvoice, cancelInvoice and registerPayment take no sandBox: an invoice stays
in the environment it was registered in. Each document records that environment
(asa_sandbox), and a later change of the setting never moves an invoice ASA
holds (prepare_motamed_asa_environment).
""" """
from __future__ import annotations from __future__ import annotations
@ -74,16 +82,68 @@ _BUYER_FIELDS = ("tob", "bid", "tinb", "sbc", "bpc", "bbc", "bpn")
# --- Identifiers ---------------------------------------------------------------------------- # --- Identifiers ----------------------------------------------------------------------------
def motamed_asa_internal_id(document: Document) -> str: def _new_internal_id(document: Document, *, sandbox: bool) -> str:
# ASA keeps an internalId unique per business across both environments, so a sandbox
# chain has its own id and can never answer for a production invoice of the same document.
return f"hesabix-sandbox-{int(document.id)}" if sandbox else f"hesabix-{int(document.id)}"
def motamed_asa_internal_id(document: Document, *, sandbox: bool = False) -> str:
"""The ASA internalId of the document's invoice chain; stable across retries.""" """The ASA internalId of the document's invoice chain; stable across retries."""
stored = str((document.extra_info or {}).get("asa_internal_id") or "").strip() stored = str((document.extra_info or {}).get("asa_internal_id") or "").strip()
return stored or f"hesabix-{int(document.id)}" return stored or _new_internal_id(document, sandbox=sandbox)
def _cancel_internal_id(internal_id: str) -> str: def _cancel_internal_id(internal_id: str) -> str:
return f"{internal_id}-cancel" return f"{internal_id}-cancel"
# --- Environment (production or the tax organisation's sandbox) -----------------------------
def motamed_asa_document_sandbox(document: Document) -> bool | None:
"""
The environment the document's ASA chain was sent to: True for the sandbox,
False for production, None before its first send. Chains sent before sandbox
support carry no flag and are production.
"""
extra = document.extra_info or {}
if isinstance(extra.get("asa_sandbox"), bool):
return extra["asa_sandbox"]
return False if extra.get("asa_internal_id") else None
def _business_sandbox(db: Session, business_id: int) -> bool:
setting = db.query(TaxSetting).filter(TaxSetting.business_id == int(business_id)).first()
return bool(getattr(setting, "sandbox_mode", False))
def _environment_mismatch(invoice_sandbox: bool) -> ApiError:
if invoice_sandbox:
message = (
"این صورتحساب در محیط آزمایشی (Sandbox) به معتمد آسا ارسال شده است و ارسال، اصلاح، ابطال "
"و ثبت پرداخت آن فقط در همان محیط انجام می‌شود؛ برای ادامه، حالت سندباکس را روشن کنید."
)
else:
message = (
"این صورتحساب در محیط اصلی سامانهٔ مؤدیان ثبت شده است و ارسال، اصلاح، ابطال و ثبت پرداخت آن "
"در حالت سندباکس انجام نمی‌شود؛ برای ادامه، حالت سندباکس را خاموش کنید."
)
return ApiError(
"MOTAMED_ASA_ENVIRONMENT_MISMATCH",
message,
http_status=409,
details={"provider": MOTAMED_ASA_PROVIDER, "invoice_sandbox": invoice_sandbox},
)
def _require_environment(document: Document, sandbox: bool) -> None:
"""A registered chain is changed only in its own environment; reading it is always allowed."""
invoice_sandbox = motamed_asa_document_sandbox(document)
if invoice_sandbox is not None and invoice_sandbox != sandbox:
raise _environment_mismatch(invoice_sandbox)
# --- Payload ---------------------------------------------------------------------------------- # --- Payload ----------------------------------------------------------------------------------
@ -349,6 +409,7 @@ def _send_or_update(
mode: str, mode: str,
fiscal_id: str | None, fiscal_id: str | None,
item_fields: dict[str, Any] | None = None, item_fields: dict[str, Any] | None = None,
sandbox: bool = False,
) -> dict[str, Any]: ) -> dict[str, Any]:
current = _inquire_one(client, token, internal_id) current = _inquire_one(client, token, internal_id)
if current is not None: if current is not None:
@ -390,6 +451,8 @@ def _send_or_update(
item_request: dict[str, Any] = { item_request: dict[str, Any] = {
"internalId": internal_id, "internalId": internal_id,
"send": True, "send": True,
# Explicit for both environments; ASA treats a missing value as production.
"sandBox": bool(sandbox),
"description": _description(document), "description": _description(document),
**(item_fields or {}), **(item_fields or {}),
"data": data, "data": data,
@ -508,10 +571,11 @@ def _cancel(
raise _rejected(response, item) raise _rejected(response, item)
def motamed_asa_return_reference_tax_id(db: Session, document: Document) -> str: def motamed_asa_return_reference_tax_id(db: Session, document: Document, *, sandbox: bool = False) -> str:
""" """
The tax id of the sale a return refers to. Any registered invoice of the reference's 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"). chain will do: ASA finds the chain's latest itself (returnRows "returned"). The sale
must be in the environment the return is sent to.
""" """
reference = resolve_reference_document(db, int(document.business_id), document) reference = resolve_reference_document(db, int(document.business_id), document)
if reference is None: if reference is None:
@ -527,6 +591,18 @@ def motamed_asa_return_reference_tax_id(db: Session, document: Document) -> str:
"فاکتور مرجع از طریق معتمد آسا ارسال نشده است؛ برگشت آن را از همان روشی بفرستید که فاکتور مرجع با آن ارسال شده است.", "فاکتور مرجع از طریق معتمد آسا ارسال نشده است؛ برگشت آن را از همان روشی بفرستید که فاکتور مرجع با آن ارسال شده است.",
http_status=409, http_status=409,
) )
reference_sandbox = bool(motamed_asa_document_sandbox(reference))
if reference_sandbox != sandbox:
raise ApiError(
"MOTAMED_ASA_REFERENCE_OTHER_ENVIRONMENT",
(
"فاکتور مرجع در محیط آزمایشی (Sandbox) ثبت شده است؛ برگشت از فروش آن فقط با حالت سندباکس روشن فرستاده می‌شود."
if reference_sandbox
else "فاکتور مرجع در محیط اصلی سامانهٔ مؤدیان ثبت شده است؛ برگشت از فروش آن در حالت سندباکس فرستاده نمی‌شود."
),
http_status=409,
details={"provider": MOTAMED_ASA_PROVIDER, "reference_sandbox": reference_sandbox},
)
tax_id = str(reference_extra.get("tax_moadian_taxid") or "").strip() tax_id = str(reference_extra.get("tax_moadian_taxid") or "").strip()
if len(tax_id) != 22: if len(tax_id) != 22:
raise ApiError( raise ApiError(
@ -537,6 +613,54 @@ def motamed_asa_return_reference_tax_id(db: Session, document: Document) -> str:
return tax_id return tax_id
def prepare_motamed_asa_environment(
db: Session,
document: Document,
tax_setting: TaxSetting,
*,
submission_mode: str,
) -> None:
"""
Runs before the document is marked as being sent. A document stays in the
environment its chain was sent to, whatever the setting says now: a correction
or cancellation in the other environment is refused. An original or a return
whose chain there is unknown to ASA or was refused starts again in the current
environment under its own internalId; one registered or in flight is refused.
"""
sandbox = bool(getattr(tax_setting, "sandbox_mode", False))
invoice_sandbox = motamed_asa_document_sandbox(document)
if invoice_sandbox is None or invoice_sandbox == sandbox:
return
if submission_mode not in ("normal", "return"):
raise _environment_mismatch(invoice_sandbox)
previous_internal_id = motamed_asa_internal_id(document)
try:
held = motamed_asa_business_call(
db,
int(document.business_id),
lambda client, token, _account: _inquire_one(client, token, previous_internal_id),
)
except MotamedAsaApiError as exc:
# Nothing has been sent yet, so this is not an unknown result.
raise ApiError(
"MOTAMED_ASA_STATUS_INQUIRY_FAILED", str(exc), http_status=502 if exc.is_transient else 400
) from exc
if held is not None and _hesabix_status(held)[0] != "failed":
raise _environment_mismatch(invoice_sandbox)
extra = dict(document.extra_info or {})
# Nothing of the chain in the other environment belongs to the new one.
for key in (
"asa_invoice_ids_by_mode", "asa_tax_ids_by_mode", "asa_latest_invoice_id", "asa_fiscal_id",
"tax_moadian_taxid", "tax_tracking_code",
):
extra.pop(key, None)
extra["asa_internal_id"] = _new_internal_id(document, sandbox=sandbox)
extra["asa_sandbox"] = sandbox
document.extra_info = extra
db.add(document)
db.flush()
def send_document_via_motamed_asa( def send_document_via_motamed_asa(
db: Session, db: Session,
document: Document, document: Document,
@ -546,14 +670,21 @@ def send_document_via_motamed_asa(
submission_mode: str, submission_mode: str,
) -> dict[str, Any]: ) -> dict[str, Any]:
business_id = int(document.business_id) business_id = int(document.business_id)
internal_id = motamed_asa_internal_id(document) sandbox = bool(getattr(tax_setting, "sandbox_mode", False))
# prepare_motamed_asa_environment has already refused, or restarted, a chain of the other environment.
_require_environment(document, sandbox)
internal_id = motamed_asa_internal_id(document, sandbox=sandbox)
extra = dict(document.extra_info or {}) extra = dict(document.extra_info or {})
extra["tax_submission_provider"] = MOTAMED_ASA_PROVIDER extra["tax_submission_provider"] = MOTAMED_ASA_PROVIDER
extra["asa_internal_id"] = internal_id extra["asa_internal_id"] = internal_id
extra["asa_sandbox"] = sandbox
extra["tax_provider_operation"] = submission_mode extra["tax_provider_operation"] = submission_mode
document.extra_info = extra document.extra_info = extra
db.add(document) db.add(document)
db.flush() db.flush()
reference_tax_id = (
motamed_asa_return_reference_tax_id(db, document, sandbox=sandbox) if submission_mode == "return" else None
)
def operation(client: MotamedAsaClient, token: str, account: Any) -> dict[str, Any]: def operation(client: MotamedAsaClient, token: str, account: Any) -> dict[str, Any]:
if submission_mode == "cancel": if submission_mode == "cancel":
@ -561,17 +692,21 @@ def send_document_via_motamed_asa(
if submission_mode == "corrective": if submission_mode == "corrective":
data = build_motamed_asa_invoice(invoice_dto, document_id=int(document.id), subject=_ISSUE_CORRECTION) data = build_motamed_asa_invoice(invoice_dto, document_id=int(document.id), subject=_ISSUE_CORRECTION)
return _correct(db, client, token, document, internal_id, data) return _correct(db, client, token, document, internal_id, data)
fiscal_id = str(account.memory_number or "").strip() or None # The business's memory id from onboarding is a production one. In the sandbox ASA picks
# the business's Sandbox memory itself (its default, or the only active one; section 05F).
fiscal_id = None if sandbox else (str(account.memory_number or "").strip() or None)
if submission_mode == "return": if submission_mode == "return":
# The return document's own lines; ASA matches them to the reference rows (API v2 05, «ارسال اقلام برگشتی»). # 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 = 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) data["Header"]["irtaxid"] = reference_tax_id
return _send_or_update( return _send_or_update(
db, client, token, document, internal_id, data, db, client, token, document, internal_id, data,
mode=submission_mode, fiscal_id=fiscal_id, item_fields={"returnRows": "returned"}, mode=submission_mode, fiscal_id=fiscal_id, item_fields={"returnRows": "returned"}, sandbox=sandbox,
) )
data = build_motamed_asa_invoice(invoice_dto, document_id=int(document.id), subject=_ISSUE_ORIGINAL) 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) return _send_or_update(
db, client, token, document, internal_id, data, mode=submission_mode, fiscal_id=fiscal_id, sandbox=sandbox,
)
try: try:
return motamed_asa_business_call(db, business_id, operation) return motamed_asa_business_call(db, business_id, operation)
@ -793,6 +928,8 @@ def register_motamed_asa_payments(
a lost answer is never re-sent blindly: the rows are read back instead. a lost answer is never re-sent blindly: the rows are read back instead.
""" """
internal_id = _payments_internal_id(document) internal_id = _payments_internal_id(document)
# registerPayment takes no sandBox: the rows go to the invoice's own environment.
_require_environment(document, _business_sandbox(db, business_id))
rows = build_motamed_asa_payment_rows(payments) rows = build_motamed_asa_payment_rows(payments)
request = {"uuid": str(uuid.uuid4()), "internalId": internal_id, "payments": rows} request = {"uuid": str(uuid.uuid4()), "internalId": internal_id, "payments": rows}

View file

@ -278,7 +278,6 @@ def send_document_to_tax_system(
details=rate_info, details=rate_info,
) )
extra = dict(document.extra_info or {})
if provider_code not in {"moadian_direct", "fanava", MOTAMED_ASA_PROVIDER}: if provider_code not in {"moadian_direct", "fanava", MOTAMED_ASA_PROVIDER}:
raise ApiError("TAX_PROVIDER_UNSUPPORTED", "روش ارسال مالیاتی این کسب‌وکار پشتیبانی نمی‌شود.", http_status=400) raise ApiError("TAX_PROVIDER_UNSUPPORTED", "روش ارسال مالیاتی این کسب‌وکار پشتیبانی نمی‌شود.", http_status=400)
if provider_code == "fanava" and bool(getattr(tax_setting, "sandbox_mode", False)): if provider_code == "fanava" and bool(getattr(tax_setting, "sandbox_mode", False)):
@ -287,12 +286,12 @@ def send_document_to_tax_system(
"فن‌آوا محیط آزمایشی ندارد؛ حالت آزمایشی را خاموش کنید یا روش ارسال مستقیم را انتخاب کنید.", "فن‌آوا محیط آزمایشی ندارد؛ حالت آزمایشی را خاموش کنید یا روش ارسال مستقیم را انتخاب کنید.",
http_status=400, http_status=400,
) )
if provider_code == MOTAMED_ASA_PROVIDER and bool(getattr(tax_setting, "sandbox_mode", False)): if provider_code == MOTAMED_ASA_PROVIDER:
raise ApiError( # Before the document is marked as being sent: an invoice registered in one environment
"MOTAMED_ASA_SANDBOX_UNAVAILABLE", # (production or sandbox) is not changed from the other one.
"ارسال از طریق معتمد آسا فقط در محیط اصلی سامانهٔ مؤدیان انجام می‌شود؛ حالت آزمایشی را خاموش کنید.", from app.services.motamed_asa_tax_submission_service import prepare_motamed_asa_environment
http_status=400, prepare_motamed_asa_environment(db, document, tax_setting, submission_mode=mode)
) extra = dict(document.extra_info or {})
extra["tax_submission_provider"] = provider_code extra["tax_submission_provider"] = provider_code
document.extra_info = extra document.extra_info = extra
db.add(document) db.add(document)

View file

@ -0,0 +1,252 @@
"""«معتمد آسا» and the tax organisation's sandbox: which environment each operation goes to."""
from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import MagicMock
import pytest
from app.core.responses import ApiError
from app.services import motamed_asa_tax_submission_service as service
_NOT_FOUND = {"status": 3, "error": ["صورتحساب یافت نشد"]}
def _document(**extra) -> SimpleNamespace:
return SimpleNamespace(id=42, business_id=5, description=None, extra_info=dict(extra))
def _setting(sandbox: bool) -> SimpleNamespace:
return SimpleNamespace(sandbox_mode=sandbox)
def _sandbox_chain(**extra) -> SimpleNamespace:
return _document(
tax_submission_provider="motamed_asa", asa_internal_id="hesabix-sandbox-42", asa_sandbox=True, **extra
)
def _production_chain(**extra) -> SimpleNamespace:
# Sent before sandbox support: no asa_sandbox flag.
return _document(tax_submission_provider="motamed_asa", asa_internal_id="hesabix-42", **extra)
@pytest.fixture
def client() -> MagicMock:
client = MagicMock()
client.inquire_internal_ids.side_effect = lambda token, ids: [{"internalId": ids[0], **_NOT_FOUND}]
client.send_invoices.return_value = {"result": 1, "data": [{"asatspId": 9, "taxId": "T" * 22, "status": 0}]}
return client
@pytest.fixture
def asa(monkeypatch: pytest.MonkeyPatch, client: MagicMock) -> MagicMock:
"""Runs each ASA operation against the mocked client; the business's memory is a production one."""
account = SimpleNamespace(memory_number="PRD123")
calls = MagicMock(side_effect=lambda db, business_id, operation: operation(client, "token", account))
monkeypatch.setattr(service, "motamed_asa_business_call", calls)
monkeypatch.setattr(
service, "build_motamed_asa_invoice",
lambda dto, *, document_id, subject: {"Header": {"ins": subject}, "Body": [], "Payments": []},
)
return calls
def _sent_member(client: MagicMock) -> dict:
return client.send_invoices.call_args.args[1]["data"][0]
def test_sandbox_mode_sends_a_sandbox_member_without_the_production_memory(asa, client) -> None:
document = _document()
service.send_document_via_motamed_asa(
MagicMock(), document, _setting(True), MagicMock(), submission_mode="normal"
)
member = _sent_member(client)
assert member["sandBox"] is True
assert member["internalId"] == "hesabix-sandbox-42"
assert "fiscalId" not in member, "ASA picks the business's Sandbox memory itself"
assert (document.extra_info["asa_sandbox"], document.extra_info["asa_internal_id"]) == (True, "hesabix-sandbox-42")
def test_production_mode_sends_a_production_member_with_its_memory(asa, client) -> None:
document = _document()
service.send_document_via_motamed_asa(
MagicMock(), document, _setting(False), MagicMock(), submission_mode="normal"
)
member = _sent_member(client)
assert (member["sandBox"], member["fiscalId"], member["internalId"]) == (False, "PRD123", "hesabix-42")
assert document.extra_info["asa_sandbox"] is False
@pytest.mark.parametrize("mode", ["corrective", "cancel"])
@pytest.mark.parametrize(
("document", "sandbox_mode"),
[(_production_chain, True), (_sandbox_chain, False)],
ids=["production-invoice-in-sandbox-mode", "sandbox-invoice-in-production-mode"],
)
def test_correction_or_cancellation_never_crosses_environments(asa, client, mode, document, sandbox_mode) -> None:
doc = document()
before = dict(doc.extra_info)
with pytest.raises(ApiError) as error:
service.prepare_motamed_asa_environment(MagicMock(), doc, _setting(sandbox_mode), submission_mode=mode)
assert error.value.code == "MOTAMED_ASA_ENVIRONMENT_MISMATCH"
assert doc.extra_info == before
asa.assert_not_called()
with pytest.raises(ApiError):
service.send_document_via_motamed_asa(MagicMock(), doc, _setting(sandbox_mode), MagicMock(), submission_mode=mode)
client.edit_invoice.assert_not_called()
client.cancel_invoice.assert_not_called()
def test_correction_in_the_invoices_own_environment_keeps_its_chain(asa, client) -> None:
client.edit_invoice.return_value = {
"result": 1, "edit": {"outcome": "correctionIssued", "taxId": "C" * 22},
"data": [{"asatspId": 10, "issue": 2, "status": 0}],
}
document = _sandbox_chain()
service.prepare_motamed_asa_environment(MagicMock(), document, _setting(True), submission_mode="corrective")
service.send_document_via_motamed_asa(MagicMock(), document, _setting(True), MagicMock(), submission_mode="corrective")
body = client.edit_invoice.call_args.args[1]
assert body["internalId"] == "hesabix-sandbox-42"
assert "sandBox" not in body, "editInvoice keeps the invoice's environment and takes no sandBox"
@pytest.mark.parametrize("status", [0, 1, 2])
def test_an_original_registered_or_in_flight_is_not_moved(asa, client, status) -> None:
client.inquire_internal_ids.side_effect = lambda token, ids: [
{"internalId": ids[0], "asatspId": 9, "issue": 1, "status": status}
]
document = _sandbox_chain(tax_moadian_taxid="S" * 22)
before = dict(document.extra_info)
with pytest.raises(ApiError) as error:
service.prepare_motamed_asa_environment(MagicMock(), document, _setting(False), submission_mode="normal")
assert error.value.code == "MOTAMED_ASA_ENVIRONMENT_MISMATCH"
assert client.inquire_internal_ids.call_args.args[1] == ["hesabix-sandbox-42"]
assert document.extra_info == before
client.send_invoices.assert_not_called()
@pytest.mark.parametrize(
"held",
[_NOT_FOUND, {"asatspId": 9, "issue": 1, "status": 3, "error": ["خطای سازمان"]}],
ids=["unknown-to-asa", "refused"],
)
def test_an_original_never_registered_starts_again_in_the_current_environment(asa, client, held) -> None:
client.inquire_internal_ids.side_effect = [[{"internalId": "hesabix-sandbox-42", **held}], [
{"internalId": "hesabix-42", **_NOT_FOUND}
]]
document = _sandbox_chain(
tax_moadian_taxid="S" * 22, tax_tracking_code="9", asa_latest_invoice_id=9,
asa_tax_ids_by_mode={"normal": "S" * 22}, asa_fiscal_id="SND123",
)
service.prepare_motamed_asa_environment(MagicMock(), document, _setting(False), submission_mode="normal")
extra = document.extra_info
assert (extra["asa_internal_id"], extra["asa_sandbox"]) == ("hesabix-42", False)
assert not {"tax_moadian_taxid", "tax_tracking_code", "asa_latest_invoice_id", "asa_tax_ids_by_mode", "asa_fiscal_id"} & set(extra)
service.send_document_via_motamed_asa(MagicMock(), document, _setting(False), MagicMock(), submission_mode="normal")
member = _sent_member(client)
assert (member["internalId"], member["sandBox"]) == ("hesabix-42", False)
def test_same_environment_needs_no_extra_inquiry(asa, client) -> None:
service.prepare_motamed_asa_environment(MagicMock(), _sandbox_chain(), _setting(True), submission_mode="normal")
service.prepare_motamed_asa_environment(MagicMock(), _document(), _setting(True), submission_mode="normal")
asa.assert_not_called()
def _reference(monkeypatch: pytest.MonkeyPatch, **extra) -> SimpleNamespace:
reference = SimpleNamespace(id=41, extra_info={"tax_submission_provider": "motamed_asa", "tax_moadian_taxid": "A" * 22, **extra})
monkeypatch.setattr(service, "resolve_reference_document", lambda db, business_id, document: reference)
return reference
@pytest.mark.parametrize(
("reference_extra", "sandbox"),
[
({"asa_internal_id": "hesabix-41"}, True),
({"asa_internal_id": "hesabix-sandbox-41", "asa_sandbox": True}, False),
],
ids=["production-sale-in-sandbox-mode", "sandbox-sale-in-production-mode"],
)
def test_return_of_a_sale_from_the_other_environment_is_refused(monkeypatch, reference_extra, sandbox) -> None:
_reference(monkeypatch, **reference_extra)
with pytest.raises(ApiError) as error:
service.motamed_asa_return_reference_tax_id(MagicMock(), _document(), sandbox=sandbox)
assert error.value.code == "MOTAMED_ASA_REFERENCE_OTHER_ENVIRONMENT"
def test_sandbox_return_refers_to_a_sandbox_sale(monkeypatch, asa, client) -> None:
_reference(monkeypatch, asa_internal_id="hesabix-sandbox-41", asa_sandbox=True)
document = _document()
service.send_document_via_motamed_asa(MagicMock(), document, _setting(True), MagicMock(), submission_mode="return")
member = _sent_member(client)
assert (member["sandBox"], member["returnRows"]) == (True, "returned")
assert member["data"]["Header"]["irtaxid"] == "A" * 22
def test_payments_of_an_invoice_are_registered_only_in_its_environment(monkeypatch, asa, client) -> None:
monkeypatch.setattr(service, "_business_sandbox", lambda db, business_id: False)
with pytest.raises(ApiError) as error:
service.register_motamed_asa_payments(
MagicMock(), 5, _sandbox_chain(), [{"type": 3, "timestamp": 1789446000000, "price": 1000}]
)
assert error.value.code == "MOTAMED_ASA_ENVIRONMENT_MISMATCH"
client.register_payments.assert_not_called()
def test_payments_of_a_sandbox_invoice_can_still_be_read_in_production_mode(monkeypatch, asa, client) -> None:
monkeypatch.setattr(service, "_business_sandbox", lambda db, business_id: False)
client.inquire_payments.return_value = {"result": 1, "data": [{"taxId": "S" * 22, "payments": []}]}
view = service.motamed_asa_invoice_payments(MagicMock(), 5, _sandbox_chain())
assert view["tax_id"] == "S" * 22
assert client.inquire_payments.call_args.args[1] == "hesabix-sandbox-42"
def test_inquiry_reads_each_chain_where_it_lives(asa, client) -> None:
client.inquire_internal_ids.side_effect = lambda token, ids: [
{"internalId": internal_id, "asatspId": 9, "issue": 1, "status": 2, "taxId": "T" * 22} for internal_id in ids
]
documents = [
_sandbox_chain(tax_last_submission_mode="normal"),
SimpleNamespace(id=43, business_id=5, extra_info={"tax_submission_provider": "motamed_asa", "asa_internal_id": "hesabix-43"}),
]
results = service.motamed_asa_inquire_documents(MagicMock(), 5, documents)
assert client.inquire_internal_ids.call_args.args[1] == ["hesabix-sandbox-42", "hesabix-43"]
assert [result["status"] for _, result in results] == ["finalized", "finalized"]
@pytest.mark.parametrize(
("extra", "expected"),
[
({}, None),
({"asa_internal_id": "hesabix-42"}, False),
({"asa_internal_id": "hesabix-sandbox-42", "asa_sandbox": True}, True),
({"asa_internal_id": "hesabix-42", "asa_sandbox": False}, False),
],
)
def test_document_environment(extra, expected) -> None:
assert service.motamed_asa_document_sandbox(_document(**extra)) is expected

View file

@ -8395,7 +8395,7 @@
"taxSubmissionMotamedAsa": "Send through Motamed ASA", "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.", "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.", "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.", "motamedAsaSandboxNote": "Sandbox mode is on: invoices go through Motamed ASA to the sandbox of the tax system and are not registered in the live tax system. The Sandbox fiscal memory ID of this business, issued in that sandbox, must be registered with Motamed ASA. Invoices registered in the live tax system are only inquired in this mode; correct, cancel or add payments to them after turning sandbox mode off.",
"motamedAsaEconomicCodeRequired": "Enter the 11 or 14 digit economic code of the business first.", "motamedAsaEconomicCodeRequired": "Enter the 11 or 14 digit economic code of the business first.",
"motamedAsaConsentTitle": "Send invoices through Motamed ASA", "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.", "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.",

View file

@ -8437,7 +8437,7 @@
"taxSubmissionMotamedAsa": "ارسال از طریق معتمد آسا", "taxSubmissionMotamedAsa": "ارسال از طریق معتمد آسا",
"taxSubmissionMotamedAsaDescription": "ثبت‌نام در صفحه معتمد آسا و ارسال صورت‌حساب‌ها با امضای شرکت معتمد؛ کلید خصوصی و شناسه حافظه کسب‌وکار در اینجا لازم نیست.", "taxSubmissionMotamedAsaDescription": "ثبت‌نام در صفحه معتمد آسا و ارسال صورت‌حساب‌ها با امضای شرکت معتمد؛ کلید خصوصی و شناسه حافظه کسب‌وکار در اینجا لازم نیست.",
"motamedAsaUnavailable": "اتصال معتمد آسا هنوز توسط مدیر سیستم راه‌اندازی نشده است.", "motamedAsaUnavailable": "اتصال معتمد آسا هنوز توسط مدیر سیستم راه‌اندازی نشده است.",
"motamedAsaSandboxUnavailable": "معتمد آسا فقط به محیط اصلی سامانه مودیان ارسال می‌کند. برای انتخاب آن، حالت آزمایشی را خاموش کنید.", "motamedAsaSandboxNote": "حالت سندباکس روشن است: صورت‌حساب‌ها از طریق معتمد آسا به محیط آزمایشی سازمان امور مالیاتی فرستاده می‌شوند و در سامانه اصلی مودیان ثبت نمی‌شوند. برای این کار، شناسه یکتای حافظه مالیاتی Sandbox این کسب‌وکار که از محیط آزمایشی سازمان گرفته شده است باید در معتمد آسا ثبت شده باشد. صورت‌حساب‌هایی که در محیط اصلی ثبت شده‌اند در این حالت فقط استعلام می‌شوند؛ اصلاح، ابطال و ثبت پرداخت آن‌ها پس از خاموش کردن این حالت انجام می‌شود.",
"motamedAsaEconomicCodeRequired": "ابتدا کد اقتصادی ۱۱ یا ۱۴ رقمی کسب‌وکار را وارد کنید.", "motamedAsaEconomicCodeRequired": "ابتدا کد اقتصادی ۱۱ یا ۱۴ رقمی کسب‌وکار را وارد کنید.",
"motamedAsaConsentTitle": "ارسال صورت‌حساب از طریق معتمد آسا", "motamedAsaConsentTitle": "ارسال صورت‌حساب از طریق معتمد آسا",
"motamedAsaConsentDescription": "معتمد آسا از شرکت‌های معتمد ارائه‌دهنده خدمات مالیاتی است. با ادامه، صفحه ثبت‌نام معتمد آسا باز می‌شود؛ مالک کسب‌وکار در آن صفحه با کد یک‌بارمصرف سامانه مودیان وارد می‌شود، قوانین معتمد آسا را می‌پذیرد و اجازه می‌دهد کلید API این کسب‌وکار به حسابیکس تحویل شود.", "motamedAsaConsentDescription": "معتمد آسا از شرکت‌های معتمد ارائه‌دهنده خدمات مالیاتی است. با ادامه، صفحه ثبت‌نام معتمد آسا باز می‌شود؛ مالک کسب‌وکار در آن صفحه با کد یک‌بارمصرف سامانه مودیان وارد می‌شود، قوانین معتمد آسا را می‌پذیرد و اجازه می‌دهد کلید API این کسب‌وکار به حسابیکس تحویل شود.",

View file

@ -40553,11 +40553,11 @@ abstract class AppLocalizations {
/// **'The Motamed ASA connection has not been set up by the system administrator yet.'** /// **'The Motamed ASA connection has not been set up by the system administrator yet.'**
String get motamedAsaUnavailable; String get motamedAsaUnavailable;
/// No description provided for @motamedAsaSandboxUnavailable. /// No description provided for @motamedAsaSandboxNote.
/// ///
/// In en, this message translates to: /// In en, this message translates to:
/// **'Motamed ASA sends to the production tax system only. Turn off sandbox mode to select it.'** /// **'Sandbox mode is on: invoices go through Motamed ASA to the sandbox of the tax system and are not registered in the live tax system. The Sandbox fiscal memory ID of this business, issued in that sandbox, must be registered with Motamed ASA. Invoices registered in the live tax system are only inquired in this mode; correct, cancel or add payments to them after turning sandbox mode off.'**
String get motamedAsaSandboxUnavailable; String get motamedAsaSandboxNote;
/// No description provided for @motamedAsaEconomicCodeRequired. /// No description provided for @motamedAsaEconomicCodeRequired.
/// ///

View file

@ -22234,8 +22234,8 @@ class AppLocalizationsEn extends AppLocalizations {
'The Motamed ASA connection has not been set up by the system administrator yet.'; 'The Motamed ASA connection has not been set up by the system administrator yet.';
@override @override
String get motamedAsaSandboxUnavailable => String get motamedAsaSandboxNote =>
'Motamed ASA sends to the production tax system only. Turn off sandbox mode to select it.'; 'Sandbox mode is on: invoices go through Motamed ASA to the sandbox of the tax system and are not registered in the live tax system. The Sandbox fiscal memory ID of this business, issued in that sandbox, must be registered with Motamed ASA. Invoices registered in the live tax system are only inquired in this mode; correct, cancel or add payments to them after turning sandbox mode off.';
@override @override
String get motamedAsaEconomicCodeRequired => String get motamedAsaEconomicCodeRequired =>

View file

@ -22107,8 +22107,8 @@ class AppLocalizationsFa extends AppLocalizations {
'اتصال معتمد آسا هنوز توسط مدیر سیستم راه‌اندازی نشده است.'; 'اتصال معتمد آسا هنوز توسط مدیر سیستم راه‌اندازی نشده است.';
@override @override
String get motamedAsaSandboxUnavailable => String get motamedAsaSandboxNote =>
'معتمد آسا فقط به محیط اصلی سامانه مودیان ارسال می‌کند. برای انتخاب آن، حالت آزمایشی را خاموش کنید.'; 'حالت سندباکس روشن است: صورت‌حساب‌ها از طریق معتمد آسا به محیط آزمایشی سازمان امور مالیاتی فرستاده می‌شوند و در سامانه اصلی مودیان ثبت نمی‌شوند. برای این کار، شناسه یکتای حافظه مالیاتی Sandbox این کسب‌وکار که از محیط آزمایشی سازمان گرفته شده است باید در معتمد آسا ثبت شده باشد. صورت‌حساب‌هایی که در محیط اصلی ثبت شده‌اند در این حالت فقط استعلام می‌شوند؛ اصلاح، ابطال و ثبت پرداخت آن‌ها پس از خاموش کردن این حالت انجام می‌شود.';
@override @override
String get motamedAsaEconomicCodeRequired => String get motamedAsaEconomicCodeRequired =>

View file

@ -1442,19 +1442,18 @@ class _TaxSettingsPageState extends State<TaxSettingsPage> {
(_saving || (_saving ||
_providerSaving || _providerSaving ||
_motamedAsaBusy || _motamedAsaBusy ||
_sandboxMode ||
_settings?.motamedAsaAvailable != true) _settings?.motamedAsaAvailable != true)
? null ? null
: (_) => _selectMotamedAsa(), : (_) => _selectMotamedAsa(),
title: Text(t.taxSubmissionMotamedAsa), title: Text(t.taxSubmissionMotamedAsa),
subtitle: Text( subtitle: Text(
_sandboxMode _settings?.motamedAsaAvailable == true
? t.motamedAsaSandboxUnavailable
: _settings?.motamedAsaAvailable == true
? t.taxSubmissionMotamedAsaDescription ? t.taxSubmissionMotamedAsaDescription
: t.motamedAsaUnavailable, : t.motamedAsaUnavailable,
), ),
), ),
if (provider == 'motamed_asa' && _sandboxMode)
_buildMotamedAsaSandboxNote(t),
_buildMotamedAsaStatus(t), _buildMotamedAsaStatus(t),
if (_providerSaving) if (_providerSaving)
const LinearProgressIndicator(minHeight: 2) const LinearProgressIndicator(minHeight: 2)
@ -1530,6 +1529,28 @@ class _TaxSettingsPageState extends State<TaxSettingsPage> {
); );
} }
/// Where Motamed ASA sends while sandbox mode is on, and what the business needs for it.
Widget _buildMotamedAsaSandboxNote(AppLocalizations t) {
final tone = SemanticColorResolver.warning(context);
return Container(
width: double.infinity,
margin: const EdgeInsets.only(top: 8),
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: tone.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(8),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(Icons.science_outlined, color: tone),
const SizedBox(width: 8),
Expanded(child: Text(t.motamedAsaSandboxNote)),
],
),
);
}
Widget _buildMotamedAsaStatus(AppLocalizations t) { Widget _buildMotamedAsaStatus(AppLocalizations t) {
final account = _settings?.motamedAsaAccount; final account = _settings?.motamedAsaAccount;
if (account == null) return const SizedBox.shrink(); if (account == null) return const SizedBox.shrink();