جلوگیری از صدور تکراری فاکتور ووکامرس با کلید عملیات #60

Merged
morrning merged 1 commit from Seyyed/Seyyed_arc:codex/team-base-26-woo-order-create-retry into master 2026-11-15 10:06:09 +03:30
7 changed files with 270 additions and 61 deletions

View file

@ -39,6 +39,44 @@ class Hesabix_V2_DB_Service
$this->business_id = get_option('hesabix_v2_business_id'); $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 * Save mapping
* *

View file

@ -123,7 +123,12 @@ class Hesabix_V2_Queue_Service
'skipped_pause' => true, 'skipped_pause' => true,
); );
} else { } 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; break;
case 'order_return': case 'order_return':
@ -226,6 +231,11 @@ class Hesabix_V2_Queue_Service
); );
$formats = array('%s', '%d', '%s', '%d', '%s', '%d'); $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) { if ($payload !== null && array() !== $payload) {
$data['payload'] = wp_json_encode($payload); $data['payload'] = wp_json_encode($payload);
$formats[] = '%s'; $formats[] = '%s';

View file

@ -1064,7 +1064,7 @@ class Hesabix_V2_Sync_Service
* @param int $order_id * @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} * @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); $order = wc_get_order($order_id);
if (!$order) { 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()); $gate = Hesabix_V2_Currency_Service::evaluate_currency_sync($this->api, $order->get_currency());
if (!$gate['ok']) { if (!$gate['ok']) {
return array( return array(
@ -1215,7 +1232,7 @@ class Hesabix_V2_Sync_Service
$queued = array(); $queued = array();
foreach ($order_ids as $oid) { 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'])) { if (empty($p['success'])) {
$res['failed']++; $res['failed']++;
$res['errors'][] = array( $res['errors'][] = array(
@ -1262,6 +1279,18 @@ class Hesabix_V2_Sync_Service
? absint($prep['hesabix_invoice_id']) ? absint($prep['hesabix_invoice_id'])
: 0; : 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( $rp_gate_b = array(
'had_positive_rp' => false, 'had_positive_rp' => false,
'omitted_payments' => false, 'omitted_payments' => false,
@ -1403,7 +1432,7 @@ class Hesabix_V2_Sync_Service
* @param int $order_id * @param int $order_id
* @return array * @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); $start_time = microtime(true);
@ -1501,71 +1530,81 @@ class Hesabix_V2_Sync_Service
$api_last_result = null; $api_last_result = null;
try { try {
$existing_mapping = $this->db->get_mapping('order', $order_id);
// Get or create customer (با توجه به تنظیم create_customer_on_order) if ($retry_create && $existing_mapping) {
$create_customer_on_order = !empty($sync_settings['create_customer_on_order']); return array('success' => true, 'hesabix_id' => (int) $existing_mapping['hesabix_id']);
$customer_id = $order->get_customer_id(); }
$person_id = null; $saved_create = $existing_mapping ? null : $this->db->get_or_start_invoice_create($order_id);
$invoice_data = $saved_create;
if ($customer_id) { $person_id = $saved_create['extra_info']['person_id'] ?? null;
// Registered customer if (!$existing_mapping && !$invoice_data && !$allow_new_create) {
$person_id = $this->db->get_hesabix_id('customer', $customer_id); return array(
'success' => false,
if (!$person_id) { 'non_retryable' => true,
if (!$create_customer_on_order) { 'message' => __('درخواست قدیمی کلید صدور ندارد. پیش از ارسال دوباره، فاکتور را در حسابیکس تطبیق دهید.', 'hesabix-v2'),
throw new Exception(__('مشتری در حسابیکس وجود ندارد. گزینه «ایجاد مشتری از سفارش» را در تنظیمات فعال کنید.', '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 } else {
$customer_result = $this->sync_customer($customer_id, $order_id); // Guest customer
if ($customer_result['success']) { if (!$create_customer_on_order) {
$person_id = $customer_result['hesabix_id']; throw new Exception(__('برای ثبت سفارش مهمان، گزینه «ایجاد مشتری از سفارش» را در تنظیمات فعال کنید.', 'hesabix-v2'));
}
$guest_result = $this->sync_guest_customer($order_id);
if ($guest_result['success']) {
$person_id = $guest_result['hesabix_id'];
} else { } 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); throw new Exception($msg);
} }
} }
} else { // Prepare invoice data
// Guest customer $fiscal_dates = array();
if (!$create_customer_on_order) { if (!empty($fiscal['document_date'])) {
throw new Exception(__('برای ثبت سفارش مهمان، گزینه «ایجاد مشتری از سفارش» را در تنظیمات فعال کنید.', 'hesabix-v2')); $fiscal_dates['document_date'] = $fiscal['document_date'];
} }
$guest_result = $this->sync_guest_customer($order_id); if (!empty($fiscal['payment_date_ymd'])) {
if ($guest_result['success']) { $fiscal_dates['payment_date_ymd'] = $fiscal['payment_date_ymd'];
$person_id = $guest_result['hesabix_id'];
} else {
$msg = isset($guest_result['message']) ? (string) $guest_result['message'] : __('خطا در ایجاد مشتری مهمان', 'hesabix-v2');
throw new Exception($msg);
} }
$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; $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( $rp_gate = array(
'had_positive_rp' => false, 'had_positive_rp' => false,
@ -1707,12 +1746,12 @@ class Hesabix_V2_Sync_Service
$should_queue = false; $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( Hesabix_V2_Queue_Service::enqueue(
'order', 'order',
$order_id, $order_id,
'sync_order', 'sync_order',
null, array('retry_create' => !empty($invoice_data['woo_create_key'])),
Hesabix_V2_Queue_Service::PRIORITY_ORDER Hesabix_V2_Queue_Service::PRIORITY_ORDER
); );
} }

View file

@ -225,6 +225,10 @@ def create_invoice_endpoint(
# پس از کنترل ویژگی فروش سریع، تنظیمات کسب‌وکار و مجوز کاربر در سرور ساخته می‌شود. # پس از کنترل ویژگی فروش سریع، تنظیمات کسب‌وکار و مجوز کاربر در سرور ساخته می‌شود.
extra = dict(payload.get("extra_info") or {}) extra = dict(payload.get("extra_info") or {})
extra.pop("_stock_override", None) 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 extra.get("quick_sale") is True:
if payload.get("invoice_type") != "invoice_sales": if payload.get("invoice_type") != "invoice_sales":
raise ApiError( raise ApiError(

View file

@ -162,6 +162,8 @@ def bulk_upsert_invoices_integration(
} }
) )
except ApiError as ae: except ApiError as ae:
if "woo_create_key" in payload:
db.rollback()
p = _api_error_parts(ae) p = _api_error_parts(ae)
results.append( results.append(
{ {
@ -173,6 +175,8 @@ def bulk_upsert_invoices_integration(
} }
) )
except IntegrityError as e: except IntegrityError as e:
if "woo_create_key" in payload:
db.rollback()
results.append( results.append(
{ {
**base, **base,

View file

@ -4,6 +4,8 @@ from typing import Any, Dict, List, Optional, Set, Tuple
from datetime import datetime, date, timedelta, timezone from datetime import datetime, date, timedelta, timezone
from app.core.datetime_utils import utc_now, utc_now_aware, utc_naive_to_iso_z from app.core.datetime_utils import utc_now, utc_now_aware, utc_naive_to_iso_z
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
import hashlib
import json
import logging import logging
import re import re
from collections import defaultdict, deque from collections import defaultdict, deque
@ -6877,6 +6879,53 @@ def _calculate_invoice_profit(
return result 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( def create_invoice(
db: Session, db: Session,
business_id: int, business_id: int,
@ -6896,6 +6945,12 @@ def create_invoice(
if invoice_type not in SUPPORTED_INVOICE_TYPES: if invoice_type not in SUPPORTED_INVOICE_TYPES:
raise ApiError("INVALID_INVOICE_TYPE", "Unsupported invoice_type", http_status=400) 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())) document_date = _parse_iso_date(data.get("document_date", datetime.now()))
currency_id = data.get("currency_id") currency_id = data.get("currency_id")
if not currency_id: if not currency_id:
@ -7318,6 +7373,9 @@ def create_invoice(
http_status=409, 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 from app.services.invoice_line_unit_price_guard import validate_invoice_lines_unit_price_policy
validate_invoice_lines_unit_price_policy( validate_invoice_lines_unit_price_policy(

View file

@ -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")