From 720ac7a35b7addf50412cf9f3dc57fb05c2296b9 Mon Sep 17 00:00:00 2001 From: Seyyed Date: Sat, 14 Nov 2026 20:54:03 +0330 Subject: [PATCH] fix(arcwoc): replay keyed WooCommerce invoice creates --- .../services/class-hesabix-v2-db-service.php | 38 +++++ .../class-hesabix-v2-queue-service.php | 12 +- .../class-hesabix-v2-sync-service.php | 161 +++++++++++------- hesabixAPI/adapters/api/v1/invoices.py | 4 + .../services/invoice_bulk_upsert_service.py | 4 + hesabixAPI/app/services/invoice_service.py | 58 +++++++ .../tests/test_woo_invoice_create_retry.py | 56 ++++++ 7 files changed, 271 insertions(+), 62 deletions(-) create mode 100644 hesabixAPI/tests/test_woo_invoice_create_retry.py diff --git a/extraScripts/arcwoc/admin/services/class-hesabix-v2-db-service.php b/extraScripts/arcwoc/admin/services/class-hesabix-v2-db-service.php index 02af5b35..6316cca1 100755 --- a/extraScripts/arcwoc/admin/services/class-hesabix-v2-db-service.php +++ b/extraScripts/arcwoc/admin/services/class-hesabix-v2-db-service.php @@ -39,6 +39,44 @@ class Hesabix_V2_DB_Service $this->business_id = get_option('hesabix_v2_business_id'); } + /** + * Freeze the first CREATE payload so all retry paths send the same operation. + * WordPress options has a unique option_name per site, including on HPOS. + */ + public function get_or_start_invoice_create($order_id, ?array $payload = null) + { + global $wpdb; + $name = 'hesabix_v2_invoice_create_' . (int) $this->business_id . '_' . (int) $order_id; + + if ($payload !== null) { + $payload['woo_create_key'] = wp_generate_uuid4(); + $value = wp_json_encode($payload); + if (!is_string($value) || $wpdb->query($wpdb->prepare( + "INSERT INTO {$wpdb->options} (option_name, option_value, autoload) + VALUES (%s, %s, 'no') ON DUPLICATE KEY UPDATE option_name = option_name", + $name, + $value + )) === false) { + throw new RuntimeException(__('ذخیرهٔ کلید صدور فاکتور ووکامرس ناموفق بود.', 'hesabix-v2')); + } + } + + // Read the winning database value, independently of the WordPress option cache. + $value = $wpdb->get_var($wpdb->prepare( + "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s", + $name + )); + $saved = is_string($value) ? json_decode($value, true) : null; + if (!is_array($saved) || empty($saved['woo_create_key'])) { + if ($value === null && $payload === null && !$wpdb->last_error) { + return null; + } + throw new RuntimeException(__('خواندن کلید صدور فاکتور ووکامرس ناموفق بود.', 'hesabix-v2')); + } + return $saved; + } + + /** * Save mapping * diff --git a/extraScripts/arcwoc/admin/services/class-hesabix-v2-queue-service.php b/extraScripts/arcwoc/admin/services/class-hesabix-v2-queue-service.php index d7c2851e..26b45abe 100755 --- a/extraScripts/arcwoc/admin/services/class-hesabix-v2-queue-service.php +++ b/extraScripts/arcwoc/admin/services/class-hesabix-v2-queue-service.php @@ -123,7 +123,12 @@ class Hesabix_V2_Queue_Service 'skipped_pause' => true, ); } else { - $res = $sync->sync_order((int) $row['entity_id']); + $retry_create = !empty($payload['retry_create']); + $res = $sync->sync_order( + (int) $row['entity_id'], + !empty($payload['keyed_create']) && !$retry_create, + $retry_create + ); } break; case 'order_return': @@ -226,6 +231,11 @@ class Hesabix_V2_Queue_Service ); $formats = array('%s', '%d', '%s', '%d', '%s', '%d'); + if ($entity_type === 'order' && $action === 'sync_order') { + $payload = (array) $payload; + $payload['keyed_create'] = true; + } + if ($payload !== null && array() !== $payload) { $data['payload'] = wp_json_encode($payload); $formats[] = '%s'; diff --git a/extraScripts/arcwoc/admin/services/class-hesabix-v2-sync-service.php b/extraScripts/arcwoc/admin/services/class-hesabix-v2-sync-service.php index 1e3d7eeb..d912fd61 100755 --- a/extraScripts/arcwoc/admin/services/class-hesabix-v2-sync-service.php +++ b/extraScripts/arcwoc/admin/services/class-hesabix-v2-sync-service.php @@ -1064,7 +1064,7 @@ class Hesabix_V2_Sync_Service * @param int $order_id * @return array{success?:bool,message?:string,order_id?:int,order?:WC_Order,person_id?:mixed,invoice_data?:array,is_new_invoice?:bool,hesabix_invoice_id?:int|null,fiscal_note?:string} */ - private function prepare_order_bulk_invoice_without_api($order_id) + private function prepare_order_bulk_invoice($order_id) { $order = wc_get_order($order_id); if (!$order) { @@ -1074,6 +1074,23 @@ class Hesabix_V2_Sync_Service ); } + try { + $existing_mapping = $this->db->get_mapping('order', $order_id); + $saved = $existing_mapping ? null : $this->db->get_or_start_invoice_create($order_id); + if ($saved !== null) { + return array( + 'success' => true, + 'order_id' => (int) $order_id, + 'order' => $order, + 'invoice_data' => $saved, + 'is_new_invoice' => true, + 'hesabix_invoice_id' => null, + ); + } + } catch (RuntimeException $e) { + return array('success' => false, 'message' => $e->getMessage()); + } + $gate = Hesabix_V2_Currency_Service::evaluate_currency_sync($this->api, $order->get_currency()); if (!$gate['ok']) { return array( @@ -1215,7 +1232,7 @@ class Hesabix_V2_Sync_Service $queued = array(); foreach ($order_ids as $oid) { - $p = $this->prepare_order_bulk_invoice_without_api((int) $oid); + $p = $this->prepare_order_bulk_invoice((int) $oid); if (empty($p['success'])) { $res['failed']++; $res['errors'][] = array( @@ -1262,6 +1279,18 @@ class Hesabix_V2_Sync_Service ? absint($prep['hesabix_invoice_id']) : 0; + if ($hid_prepare < 1) { + try { + $prep['invoice_data'] = $this->db->get_or_start_invoice_create($prep['order_id'], $prep['invoice_data']); + } catch (RuntimeException $e) { + $res['failed']++; + $failure = array('success' => false, 'message' => $e->getMessage()); + $res['per_order'][$prep['order_id']] = $failure; + $res['errors'][] = array('order_id' => (int) $prep['order_id'], 'message' => $e->getMessage()); + continue; + } + } + $rp_gate_b = array( 'had_positive_rp' => false, 'omitted_payments' => false, @@ -1403,7 +1432,7 @@ class Hesabix_V2_Sync_Service * @param int $order_id * @return array */ - public function sync_order($order_id) + public function sync_order($order_id, $allow_new_create = true, $retry_create = false) { $start_time = microtime(true); @@ -1501,71 +1530,81 @@ class Hesabix_V2_Sync_Service $api_last_result = null; try { - - // Get or create customer (با توجه به تنظیم create_customer_on_order) - $create_customer_on_order = !empty($sync_settings['create_customer_on_order']); - $customer_id = $order->get_customer_id(); - $person_id = null; - - if ($customer_id) { - // Registered customer - $person_id = $this->db->get_hesabix_id('customer', $customer_id); - - if (!$person_id) { - if (!$create_customer_on_order) { - throw new Exception(__('مشتری در حسابیکس وجود ندارد. گزینه «ایجاد مشتری از سفارش» را در تنظیمات فعال کنید.', 'hesabix-v2')); + $existing_mapping = $this->db->get_mapping('order', $order_id); + if ($retry_create && $existing_mapping) { + return array('success' => true, 'hesabix_id' => (int) $existing_mapping['hesabix_id']); + } + $saved_create = $existing_mapping ? null : $this->db->get_or_start_invoice_create($order_id); + $invoice_data = $saved_create; + $person_id = $saved_create['extra_info']['person_id'] ?? null; + if (!$existing_mapping && !$invoice_data && !$allow_new_create) { + return array( + 'success' => false, + 'non_retryable' => true, + 'message' => __('درخواست قدیمی کلید صدور ندارد. پیش از ارسال دوباره، فاکتور را در حسابیکس تطبیق دهید.', 'hesabix-v2'), + ); + } + if ($invoice_data === null) { + // Get or create customer (با توجه به تنظیم create_customer_on_order) + $create_customer_on_order = !empty($sync_settings['create_customer_on_order']); + $customer_id = $order->get_customer_id(); + $person_id = null; + if ($customer_id) { + // Registered customer + $person_id = $this->db->get_hesabix_id('customer', $customer_id); + if (!$person_id) { + if (!$create_customer_on_order) { + throw new Exception(__('مشتری در حسابیکس وجود ندارد. گزینه «ایجاد مشتری از سفارش» را در تنظیمات فعال کنید.', 'hesabix-v2')); + } + // Sync customer first + $customer_result = $this->sync_customer($customer_id, $order_id); + if ($customer_result['success']) { + $person_id = $customer_result['hesabix_id']; + } else { + $msg = isset($customer_result['message']) ? (string) $customer_result['message'] : __('خطا در همگام‌سازی مشتری', 'hesabix-v2'); + throw new Exception($msg); + } } - // Sync customer first - $customer_result = $this->sync_customer($customer_id, $order_id); - if ($customer_result['success']) { - $person_id = $customer_result['hesabix_id']; + } else { + // Guest customer + if (!$create_customer_on_order) { + throw new Exception(__('برای ثبت سفارش مهمان، گزینه «ایجاد مشتری از سفارش» را در تنظیمات فعال کنید.', 'hesabix-v2')); + } + $guest_result = $this->sync_guest_customer($order_id); + if ($guest_result['success']) { + $person_id = $guest_result['hesabix_id']; } else { - $msg = isset($customer_result['message']) ? (string) $customer_result['message'] : __('خطا در همگام‌سازی مشتری', 'hesabix-v2'); + $msg = isset($guest_result['message']) ? (string) $guest_result['message'] : __('خطا در ایجاد مشتری مهمان', 'hesabix-v2'); throw new Exception($msg); } } - } else { - // Guest customer - if (!$create_customer_on_order) { - throw new Exception(__('برای ثبت سفارش مهمان، گزینه «ایجاد مشتری از سفارش» را در تنظیمات فعال کنید.', 'hesabix-v2')); + // Prepare invoice data + $fiscal_dates = array(); + if (!empty($fiscal['document_date'])) { + $fiscal_dates['document_date'] = $fiscal['document_date']; } - $guest_result = $this->sync_guest_customer($order_id); - if ($guest_result['success']) { - $person_id = $guest_result['hesabix_id']; - } else { - $msg = isset($guest_result['message']) ? (string) $guest_result['message'] : __('خطا در ایجاد مشتری مهمان', 'hesabix-v2'); - throw new Exception($msg); + if (!empty($fiscal['payment_date_ymd'])) { + $fiscal_dates['payment_date_ymd'] = $fiscal['payment_date_ymd']; } + $invoice_data = apply_filters( + 'hesabix_v2_invoice_data', + Hesabix_V2_Mapper::wc_order_to_invoice( + $order, + $person_id, + $gate['factor'], + $gate['currency_id'], + $fiscal_dates ? $fiscal_dates : null + ), + $order + ); + $wc_payload_for_log = $invoice_data; + self::assert_invoice_lines_have_warehouse_when_required($order, $invoice_data); } - - // Prepare invoice data - $fiscal_dates = array(); - if (!empty($fiscal['document_date'])) { - $fiscal_dates['document_date'] = $fiscal['document_date']; - } - if (!empty($fiscal['payment_date_ymd'])) { - $fiscal_dates['payment_date_ymd'] = $fiscal['payment_date_ymd']; - } - - $invoice_data = apply_filters( - 'hesabix_v2_invoice_data', - Hesabix_V2_Mapper::wc_order_to_invoice( - $order, - $person_id, - $gate['factor'], - $gate['currency_id'], - $fiscal_dates ? $fiscal_dates : null - ), - $order - ); - - $wc_payload_for_log = $invoice_data; - - self::assert_invoice_lines_have_warehouse_when_required($order, $invoice_data); - - // Check if already synced - $existing_mapping = $this->db->get_mapping('order', $order_id); $is_new_invoice = !$existing_mapping; + if ($is_new_invoice) { + $invoice_data = $saved_create ?? $this->db->get_or_start_invoice_create($order_id, $invoice_data); + $wc_payload_for_log = $invoice_data; + } $rp_gate = array( 'had_positive_rp' => false, @@ -1707,12 +1746,12 @@ class Hesabix_V2_Sync_Service $should_queue = false; } - if ($should_queue) { + if ($should_queue && ($allow_new_create || !empty($existing_mapping) || !empty($invoice_data['woo_create_key']))) { Hesabix_V2_Queue_Service::enqueue( 'order', $order_id, 'sync_order', - null, + array('retry_create' => !empty($invoice_data['woo_create_key'])), Hesabix_V2_Queue_Service::PRIORITY_ORDER ); } diff --git a/hesabixAPI/adapters/api/v1/invoices.py b/hesabixAPI/adapters/api/v1/invoices.py index 5a6dd0ad..4a0a73c9 100755 --- a/hesabixAPI/adapters/api/v1/invoices.py +++ b/hesabixAPI/adapters/api/v1/invoices.py @@ -225,6 +225,10 @@ def create_invoice_endpoint( # پس از کنترل ویژگی فروش سریع، تنظیمات کسب‌وکار و مجوز کاربر در سرور ساخته می‌شود. extra = dict(payload.get("extra_info") or {}) extra.pop("_stock_override", None) + if "woo_create_key" in payload and extra.get("quick_sale"): + raise ApiError( + "INVALID_WOO_CREATE_KEY", "کلید صدور ووکامرس برای فروش سریع معتبر نیست.", http_status=422 + ) if extra.get("quick_sale") is True: if payload.get("invoice_type") != "invoice_sales": raise ApiError( diff --git a/hesabixAPI/app/services/invoice_bulk_upsert_service.py b/hesabixAPI/app/services/invoice_bulk_upsert_service.py index c64a8bd6..1a05a6d3 100755 --- a/hesabixAPI/app/services/invoice_bulk_upsert_service.py +++ b/hesabixAPI/app/services/invoice_bulk_upsert_service.py @@ -162,6 +162,8 @@ def bulk_upsert_invoices_integration( } ) except ApiError as ae: + if "woo_create_key" in payload: + db.rollback() p = _api_error_parts(ae) results.append( { @@ -173,6 +175,8 @@ def bulk_upsert_invoices_integration( } ) except IntegrityError as e: + if "woo_create_key" in payload: + db.rollback() results.append( { **base, diff --git a/hesabixAPI/app/services/invoice_service.py b/hesabixAPI/app/services/invoice_service.py index ccc31bdb..082ce4f0 100755 --- a/hesabixAPI/app/services/invoice_service.py +++ b/hesabixAPI/app/services/invoice_service.py @@ -4,6 +4,8 @@ from typing import Any, Dict, List, Optional, Set, Tuple from datetime import datetime, date, timedelta, timezone from app.core.datetime_utils import utc_now, utc_now_aware, utc_naive_to_iso_z from decimal import Decimal, InvalidOperation, ROUND_HALF_UP +import hashlib +import json import logging import re from collections import defaultdict, deque @@ -6877,6 +6879,53 @@ def _calculate_invoice_profit( return result +def _woo_invoice_create_operation( + db: Session, business_id: int, data: Dict[str, Any] +) -> tuple[dict[str, str] | None, dict[str, Any] | None]: + if "woo_create_key" not in data: + return None, None + key = data["woo_create_key"] + extra = data.get("extra_info") or {} + if not isinstance(extra, dict): + extra = {} + order_id = extra.get("wc_order_id") + if ( + not isinstance(key, str) + or not re.fullmatch(r"[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}", key) + or data.get("invoice_type") != "invoice_sales" + or extra.get("source") != "woocommerce" + or type(order_id) is not int + or order_id < 1 + or extra.get("quick_sale") + ): + raise ApiError( + "INVALID_WOO_CREATE_KEY", "کلید عملیات صدور ووکامرس یا اطلاعات سفارش نامعتبر است.", http_status=422 + ) + fingerprint = hashlib.sha256( + json.dumps(data, sort_keys=True, separators=(",", ":"), default=str).encode() + ).hexdigest() + operation = {"key": key, "fingerprint": fingerprint} + acquire_transaction_lock(db, f"woo_invoice_create:{business_id}:{key}") + matches = db.query(Document).filter( + Document.business_id == business_id, + Document.developer_settings["woo_invoice_create"]["key"].as_string() == key, + ).limit(2).all() + if not matches: + return operation, None + if len(matches) != 1 or matches[0].developer_settings["woo_invoice_create"] != operation: + raise ApiError( + "WOO_CREATE_KEY_REUSED", "این کلید قبلاً برای درخواست صدور دیگری استفاده شده است.", http_status=409 + ) + invoice = matches[0] + return operation, { + "id": invoice.id, + "code": invoice.code, + "document_type": invoice.document_type, + "woo_create_replayed": True, + } + + + def create_invoice( db: Session, business_id: int, @@ -6896,6 +6945,12 @@ def create_invoice( if invoice_type not in SUPPORTED_INVOICE_TYPES: raise ApiError("INVALID_INVOICE_TYPE", "Unsupported invoice_type", http_status=400) + woo_operation, replay = _woo_invoice_create_operation(db, business_id, data) + if replay is not None: + if commit: + db.rollback() # Release the transaction lock before the next bulk item. + return replay + document_date = _parse_iso_date(data.get("document_date", datetime.now())) currency_id = data.get("currency_id") if not currency_id: @@ -7318,6 +7373,9 @@ def create_invoice( http_status=409, ) + if woo_operation is not None: + document.developer_settings = {"woo_invoice_create": woo_operation} + from app.services.invoice_line_unit_price_guard import validate_invoice_lines_unit_price_policy validate_invoice_lines_unit_price_policy( diff --git a/hesabixAPI/tests/test_woo_invoice_create_retry.py b/hesabixAPI/tests/test_woo_invoice_create_retry.py new file mode 100644 index 00000000..cecac883 --- /dev/null +++ b/hesabixAPI/tests/test_woo_invoice_create_retry.py @@ -0,0 +1,56 @@ +from datetime import UTC, date, datetime +from uuid import uuid4 + +import pytest +from sqlalchemy import create_engine +from sqlalchemy.orm import Session +from sqlalchemy.schema import CreateTable + +from adapters.db.models.document import Document +from app.core.responses import ApiError +from app.services.invoice_service import _woo_invoice_create_operation + + +def test_woo_create_marker_scopes_replay_and_rejects_a_different_operation(): + engine = create_engine("sqlite://") + with engine.begin() as conn: + conn.execute(CreateTable(Document.__table__, include_foreign_key_constraints=[])) + request = { + "woo_create_key": str(uuid4()), + "invoice_type": "invoice_sales", + "extra_info": {"source": "woocommerce", "wc_order_id": 100}, + } + with Session(engine) as db: + operation, replay = _woo_invoice_create_operation(db, 1, request) + assert replay is None + db.add(Document( + business_id=1, fiscal_year_id=1, created_by_user_id=1, currency_id=1, + document_type="invoice_sales", code="SALE", document_date=date(2026, 11, 11), + registered_at=datetime.now(UTC), + developer_settings={"woo_invoice_create": operation}, + )) + db.commit() + + with Session(engine) as db: + assert _woo_invoice_create_operation(db, 1, dict(reversed(list(request.items()))))[1] == { + "id": 1, "code": "SALE", "document_type": "invoice_sales", "woo_create_replayed": True, + } + assert _woo_invoice_create_operation(db, 2, request)[1] is None + assert _woo_invoice_create_operation(db, 1, {**request, "woo_create_key": str(uuid4())})[1] is None + assert _woo_invoice_create_operation(db, 1, {"invoice_type": "invoice_sales"}) == (None, None) + changed = {**request, "extra_info": {**request["extra_info"], "wc_order_id": 101}} + with pytest.raises(ApiError) as error: + _woo_invoice_create_operation(db, 1, changed) + assert (error.value.status_code, error.value.code) == (409, "WOO_CREATE_KEY_REUSED") + engine.dispose() + + +@pytest.mark.parametrize("invoice_type, order_id", [("invoice_sales_return", 100), ("invoice_sales", None)]) +def test_woo_create_key_requires_a_sales_order(invoice_type, order_id): + with pytest.raises(ApiError) as error: + _woo_invoice_create_operation(None, 1, { + "woo_create_key": str(uuid4()), + "invoice_type": invoice_type, + "extra_info": {"source": "woocommerce", "wc_order_id": order_id}, + }) + assert (error.value.status_code, error.value.code) == (422, "INVALID_WOO_CREATE_KEY") -- 2.43.0