Watch
1
0
Fork
You've already forked Seyyed_arc
0
forked from hesabix/arc
Seyyed_arc/extraScripts/arcwoc/includes/class-hesabix-v2-native-variants.php
Seyyed bf6cdc93ac fix(variants): harden unified inventory costing and commerce workflows
Apply the C01-C08d and R01/R02 corrections and the reviewed High issue fixes through H33, including Native allocation trust, cancellation, cost/FX/zero handling, order splitting, refunds, dates and root-commit hooks.

Add regression coverage and Persian audit/progress reports. The final validated suite has 894 passing tests, with all 856 previous cases and 44 prior test-file hashes preserved. H34 and the remaining documented issues stay open; this commit is not a deployment-readiness declaration.
2026-11-06 16:49:49 +03:30

588 lines
32 KiB
PHP

<?php
/** Native variants are opt-in; legacy maps are never overwritten or merged. */
if (!defined('WPINC')) { die; }
class Hesabix_V2_Native_Variants
{
private static $event = null;
public static function is_applying() { return !empty($GLOBALS['hesabix_v2_native_applying']); }
public static function boot()
{
add_action('init', array(__CLASS__, 'install'));
add_action('rest_api_init', array(__CLASS__, 'routes'));
add_action('woocommerce_checkout_order_processed', array(__CLASS__, 'reserve_checkout'), 5, 1);
add_action('woocommerce_store_api_checkout_order_processed', array(__CLASS__, 'reserve_checkout'), 5, 1);
add_action('woocommerce_order_status_changed', array(__CLASS__, 'status_changed'), 5, 4);
add_action('woocommerce_order_refunded', array(__CLASS__, 'refunded'), 5, 2);
add_action('woocommerce_refund_created', static function ($refund_id, $args) {
$refund = wc_get_order($refund_id);
if ($refund && self::owns_order($refund->get_parent_id())) {
$refund->update_meta_data('_hesabix_native_restock', !empty($args['restock_items']));
$refund->save();
}
}, 5, 2);
add_action('hesabix_v2_native_event', array(__CLASS__, 'process_event'), 10, 1);
add_action('hesabix_v2_process_queue', array(__CLASS__, 'recover_events'));
add_filter('hesabix_v2_force_allow_wc_reduce_stock', static function ($allow, $order) {
return $allow || self::owns_order($order);
}, 10, 2);
add_filter('woocommerce_order_item_quantity', static function ($quantity, $order, $item) {
$options = Hesabix_V2_Stock_Pull_Service::get_options();
if (!empty($options['disable_wc_stock_reduction']) && self::owns_order($order) && !self::mapping($item->get_variation_id())) { return 0; }
return $quantity;
}, 20, 3);
}
public static function install()
{
if ((int) get_option('hesabix_v2_native_schema', 0) === 1) { return; }
global $wpdb;
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
$charset = $wpdb->get_charset_collate();
$table = $wpdb->prefix . 'hesabix_v2_native_map';
dbDelta("CREATE TABLE {$table} (
id bigint unsigned NOT NULL AUTO_INCREMENT,
connection_key varchar(64) NOT NULL,
generation bigint unsigned NOT NULL,
business_id bigint unsigned NOT NULL,
product_id bigint unsigned NOT NULL,
variant_id bigint unsigned NOT NULL DEFAULT 0,
wc_id bigint unsigned NOT NULL,
wc_parent_id bigint unsigned NOT NULL DEFAULT 0,
inventory_version bigint unsigned NOT NULL DEFAULT 0,
status varchar(24) NOT NULL DEFAULT 'active',
PRIMARY KEY (id),
UNIQUE KEY native_internal (connection_key,product_id,variant_id),
UNIQUE KEY native_external (wc_id)
) {$charset};");
$table = $wpdb->prefix . 'hesabix_v2_native_queue';
dbDelta("CREATE TABLE {$table} (
event_key varchar(190) NOT NULL,
order_id bigint unsigned NOT NULL,
payload longtext NOT NULL,
status varchar(24) NOT NULL DEFAULT 'pending',
attempts int unsigned NOT NULL DEFAULT 0,
locked_until datetime NULL,
claim_token varchar(36) NULL,
last_error varchar(100) NULL,
PRIMARY KEY (event_key),
KEY native_due (status,locked_until)
) {$charset};");
$table = $wpdb->prefix . 'hesabix_v2_native_nonces';
dbDelta("CREATE TABLE {$table} (
nonce_hash varchar(64) NOT NULL,
expires_at bigint unsigned NOT NULL,
PRIMARY KEY (nonce_hash)
) {$charset};");
update_option('hesabix_v2_native_schema', 1, false);
}
public static function routes()
{
foreach (array('configure', 'catalog', 'stock', 'attach_mapping') as $action) {
register_rest_route('hesabix-v2/v2', '/native/' . str_replace('_', '-', $action), array(
'methods' => 'POST', 'permission_callback' => array(__CLASS__, 'permission'),
'callback' => array(__CLASS__, 'route_' . $action),
));
}
}
public static function permission($request)
{
$allowed = Hesabix_V2_Bridge_REST::permission_with_token($request);
if (is_wp_error($allowed)) { return $allowed; }
$timestamp = (string) $request->get_header('X-Hesabix-Timestamp');
$nonce = (string) $request->get_header('X-Hesabix-Nonce');
$signature = (string) $request->get_header('X-Hesabix-Signature');
$token = (string) $request->get_header('X-Hesabix-Bridge-Token');
if (!ctype_digit($timestamp) || abs(time() - (int) $timestamp) > 300 || strlen($nonce) > 64 || strlen($nonce) < 16 || strlen($request->get_body()) > 1048576) {
return new WP_Error('native_signature_invalid', 'Invalid signed request', array('status' => 401));
}
$expected = hash_hmac('sha256', $timestamp . '.' . $nonce . '.' . $request->get_body(), $token);
if (!hash_equals($expected, $signature)) {
return new WP_Error('native_signature_invalid', 'Invalid signed request', array('status' => 401));
}
global $wpdb;
$table = $wpdb->prefix . 'hesabix_v2_native_nonces';
$wpdb->query($wpdb->prepare("DELETE FROM {$table} WHERE expires_at < %d", time()));
$inserted = $wpdb->query($wpdb->prepare("INSERT IGNORE INTO {$table} (nonce_hash,expires_at) VALUES (%s,%d)", hash('sha256', $nonce), time() + 600));
if ($inserted !== 1) {
return new WP_Error('native_replay', 'Request nonce already used', array('status' => 409));
}
return true;
}
public static function mapping($wc_id)
{
$config = get_option('hesabix_v2_native_connection', array());
if (!$wc_id || empty($config['connection_id'])) { return null; }
global $wpdb;
$table = $wpdb->prefix . 'hesabix_v2_native_map';
return $wpdb->get_row($wpdb->prepare("SELECT * FROM {$table} WHERE wc_id=%d AND connection_key=%s AND generation=%d AND status='active'", $wc_id, $config['connection_key'], $config['generation']), ARRAY_A);
}
public static function owns_order($order)
{
if (!$order instanceof WC_Order) { $order = wc_get_order($order); }
if (!$order) { return false; }
if ($order->get_meta('_hesabix_native_order', true)) { return true; }
foreach ($order->get_items() as $item) {
if (self::mapping($item->get_variation_id())) { return true; }
}
return false;
}
private static function lock($key)
{
global $wpdb;
$name = 'hx_native_' . substr(hash('sha256', $key), 0, 40);
if ((int) $wpdb->get_var($wpdb->prepare('SELECT GET_LOCK(%s,10)', $name)) !== 1) {
throw new RuntimeException('Native lock unavailable');
}
return $name;
}
private static function unlock($name)
{
global $wpdb;
$wpdb->get_var($wpdb->prepare('SELECT RELEASE_LOCK(%s)', $name));
}
private static function config($data)
{
$config = get_option('hesabix_v2_native_connection', array());
if (empty($config['connection_key']) || ($data['connection_key'] ?? '') !== $config['connection_key'] || (int) ($data['generation'] ?? 0) !== (int) $config['generation']) {
throw new RuntimeException('Native connection generation mismatch');
}
return $config;
}
public static function route_configure($request)
{
$data = $request->get_json_params();
if (empty($data['connection_key']) || empty($data['connection_id']) || (int) ($data['business_id'] ?? 0) !== (int) get_option('hesabix_v2_business_id')) {
return new WP_Error('native_business_mismatch', 'Business mismatch', array('status' => 409));
}
$current = get_option('hesabix_v2_native_connection', array());
if ($current && (($current['connection_key'] ?? '') !== $data['connection_key'] || (int) ($current['generation'] ?? 0) > (int) ($data['generation'] ?? 0))) {
return new WP_Error('native_generation_conflict', 'Explicit migration required', array('status' => 409));
}
update_option('hesabix_v2_native_connection', array_intersect_key($data, array_flip(array('connection_id', 'connection_key', 'generation', 'business_id'))), false);
return array('success' => true);
}
public static function route_stock($request)
{
$was_applying = self::is_applying();
$GLOBALS['hesabix_v2_native_applying'] = true;
$lock = null;
try {
$data = $request->get_json_params();
$config = self::config($data);
$id = absint($data['variation_id'] ?? 0);
$quantity = (string) ($data['quantity'] ?? '');
if (!preg_match('/^\d+(\.\d{1,6})?$/D', $quantity)) { throw new RuntimeException('Invalid stock quantity'); }
if (wc_format_decimal(wc_stock_amount($quantity), 6) !== wc_format_decimal($quantity, 6)) {
throw new RuntimeException('Store stock precision cannot represent this quantity');
}
$lock = self::lock('stock:' . $id);
$map = self::mapping($id);
if (!$map || (int) $map['variant_id'] === 0) { throw new RuntimeException('Native mapping unavailable'); }
$version = (int) ($data['inventory_version'] ?? 0);
if ($version <= (int) $map['inventory_version']) {
return array('success' => true, 'inventory_version' => (int) $map['inventory_version']);
}
$product = wc_get_product($id);
if (!$product || !$product->is_type('variation')) { throw new RuntimeException('Variation unavailable'); }
$product->set_manage_stock(true);
$product->set_backorders('no');
$product->set_stock_quantity($quantity); // Includes authoritative zero.
$product->save();
global $wpdb;
$table = $wpdb->prefix . 'hesabix_v2_native_map';
if ($wpdb->update($table, array('inventory_version' => $version), array('id' => $map['id'])) === false) { throw new RuntimeException('Stock acknowledgment write failed'); }
return array('success' => true, 'inventory_version' => $version);
} catch (Throwable $error) {
return new WP_Error('native_stock_failed', $error->getMessage(), array('status' => 409));
} finally { $GLOBALS['hesabix_v2_native_applying'] = $was_applying; if ($lock) { self::unlock($lock); } }
}
public static function route_catalog($request)
{
$was_applying = self::is_applying();
$GLOBALS['hesabix_v2_native_applying'] = true;
$lock = null;
try {
$data = $request->get_json_params();
$config = self::config($data);
if (empty($data['variants']) || count($data['variants']) > 100) { throw new RuntimeException('Invalid variant count'); }
$currency = Hesabix_V2_Currency_Service::evaluate_currency_sync(new Hesabix_V2_Api(), get_woocommerce_currency());
if (empty($currency['ok']) || (int) $currency['currency_id'] !== (int) ($data['currency_id'] ?? 0)) {
throw new RuntimeException('Store currency must map to the catalogue price currency');
}
$lock = self::lock('catalog:' . $config['connection_key'] . ':' . absint($data['product_id']));
global $wpdb;
$table = $wpdb->prefix . 'hesabix_v2_native_map';
$parent_id = $wpdb->get_var($wpdb->prepare("SELECT wc_id FROM {$table} WHERE connection_key=%s AND product_id=%d AND variant_id=0", $config['connection_key'], $data['product_id']));
if (!$parent_id) {
$found = get_posts(array('post_type' => 'product', 'post_status' => 'any', 'fields' => 'ids', 'numberposts' => 2,
'meta_key' => '_hesabix_native_identity', 'meta_value' => $config['connection_key'] . ':product:' . $data['product_id']));
if (count($found) > 1) { throw new RuntimeException('Duplicate parent identity'); }
$parent_id = $found ? $found[0] : 0;
}
$parent = $parent_id ? wc_get_product($parent_id) : new WC_Product_Variable();
if (!$parent || !$parent->is_type('variable')) { throw new RuntimeException('Parent type conflict'); }
$catalog_version = (int) ($data['catalog_version'] ?? 0);
if ($catalog_version < 1 || $catalog_version < (int) $parent->get_meta('_hesabix_native_catalog_version', true)) { throw new RuntimeException('Stale catalogue version'); }
$parent->set_name(sanitize_text_field($data['name']));
$parent->set_manage_stock(false);
$parent->update_meta_data('_hesabix_native_identity', $config['connection_key'] . ':product:' . $data['product_id']);
$attributes = array();
$variant_attributes = array();
foreach ($data['variants'] as $variant) {
$values = $variant['attribute_values'] ?? array();
if (count($values) < 1 || count($values) > 2) { throw new RuntimeException('Invalid dimensions'); }
$variant_attributes[(int) $variant['id']] = array();
foreach ($values as $value) {
$slug = 'hx_' . absint($value['attribute_id']);
$taxonomy = wc_attribute_taxonomy_name($slug);
$attribute_id = wc_attribute_taxonomy_id_by_name($slug);
if (!$attribute_id) {
$attribute_id = wc_create_attribute(array('name' => $value['name'], 'slug' => $slug, 'type' => 'select'));
if (is_wp_error($attribute_id)) { throw new RuntimeException('Attribute creation failed'); }
}
if (!taxonomy_exists($taxonomy)) { register_taxonomy($taxonomy, array('product')); }
$term_slug = 'hx-' . absint($value['option_id']);
$term = get_term_by('slug', $term_slug, $taxonomy);
if (!$term) {
$created = wp_insert_term($value['value'], $taxonomy, array('slug' => $term_slug));
if (is_wp_error($created)) { throw new RuntimeException('Option creation failed'); }
$term_id = (int) $created['term_id'];
} else {
$term_id = (int) $term->term_id;
wp_update_term($term_id, $taxonomy, array('name' => $value['value']));
}
if (!isset($attributes[$taxonomy])) {
$attribute = new WC_Product_Attribute();
$attribute->set_id($attribute_id); $attribute->set_name($taxonomy);
$attribute->set_visible(true); $attribute->set_variation(true);
$attributes[$taxonomy] = $attribute;
}
$attributes[$taxonomy]->set_options(array_values(array_unique(array_merge($attributes[$taxonomy]->get_options(), array($term_id)))));
$variant_attributes[(int) $variant['id']][$taxonomy] = $term_slug;
}
}
$parent->set_attributes(array_values($attributes));
$parent->set_status('publish');
$parent_id = $parent->save();
self::save_map($config, $data['product_id'], 0, $parent_id, 0);
$result = array();
foreach ($data['variants'] as $variant) {
$id = $wpdb->get_var($wpdb->prepare("SELECT wc_id FROM {$table} WHERE connection_key=%s AND product_id=%d AND variant_id=%d", $config['connection_key'], $data['product_id'], $variant['id']));
if (!$id) {
$found = get_posts(array('post_type' => 'product_variation', 'post_status' => 'any', 'fields' => 'ids', 'numberposts' => 2,
'meta_key' => '_hesabix_native_identity', 'meta_value' => $config['connection_key'] . ':variant:' . $variant['id']));
if (count($found) > 1) { throw new RuntimeException('Duplicate variation identity'); }
$id = $found ? $found[0] : 0;
}
$variation = $id ? wc_get_product($id) : new WC_Product_Variation();
if (!$variation || !$variation->is_type('variation') || ($id && (int) $variation->get_parent_id() !== (int) $parent_id)) { throw new RuntimeException('Variation parent conflict'); }
$variation->set_parent_id($parent_id);
$variation->set_attributes($variant_attributes[(int) $variant['id']]);
$variation->set_regular_price(self::store_price((string) $variant['price'], $currency['factor']));
$variation->set_status(!empty($variant['is_active']) ? 'publish' : 'private');
$variation->set_manage_stock(true); $variation->set_backorders('no');
if (!$id) { $variation->set_stock_quantity(0); }
if (!empty($variant['code'])) { $variation->set_sku($variant['code']); }
$variation->update_meta_data('_hesabix_native_identity', $config['connection_key'] . ':variant:' . $variant['id']);
if (!empty($variant['barcode'])) { $variation->update_meta_data('_hesabix_barcode', $variant['barcode']); }
$id = $variation->save();
self::save_map($config, $data['product_id'], $variant['id'], $id, $parent_id);
$result[] = array('variant_id' => (int) $variant['id'], 'external_variation_id' => (string) $id);
}
WC_Product_Variable::sync($parent_id);
$parent->update_meta_data('_hesabix_native_catalog_version', $catalog_version);
$parent->save();
return array('success' => true, 'external_product_id' => (string) $parent_id, 'variants' => $result);
} catch (Throwable $error) {
return new WP_Error('native_catalog_failed', $error->getMessage(), array('status' => 409));
} finally { $GLOBALS['hesabix_v2_native_applying'] = $was_applying; if ($lock) { self::unlock($lock); } }
}
public static function route_attach_mapping($request)
{
$lock = null;
try {
$data = $request->get_json_params();
$config = self::config($data);
$parent_id = absint($data['external_product_id'] ?? 0);
$parent = wc_get_product($parent_id);
if (!$parent || !$parent->is_type('variable')) { throw new RuntimeException('Concrete variable parent required'); }
$lock = self::lock('catalog:' . $config['connection_key'] . ':' . absint($data['product_id']));
$children = array_map('intval', $parent->get_children());
$requested = array_map(static function ($row) { return absint($row['external_variation_id']); }, $data['variants'] ?? array());
sort($children); sort($requested);
if (!$requested || $children !== $requested || count($requested) !== count(array_unique($requested))) { throw new RuntimeException('All concrete variations must be mapped exactly once'); }
$legacy = new Hesabix_V2_DB_Service();
global $wpdb;
foreach ($data['variants'] as $row) {
$id = absint($row['external_variation_id']);
$variation = wc_get_product($id);
if (!$variation || $variation->get_parent_id() !== $parent_id || in_array('', $variation->get_attributes(), true)) { throw new RuntimeException('Any or mismatched variation is unsupported'); }
$existing = self::mapping($id);
if ($existing && ((int) $existing['variant_id'] !== (int) $row['variant_id'] || (int) $existing['product_id'] !== (int) $data['product_id'])) { throw new RuntimeException('Mapping identity conflict'); }
if (!$existing && ($legacy->get_mapping('variation', $id, $parent_id) || $legacy->get_mapping('product', $id))) { throw new RuntimeException('Legacy mapping requires an audited cutover; automatic replacement is forbidden'); }
$history = $wpdb->get_var($wpdb->prepare("SELECT order_item_id FROM {$wpdb->prefix}woocommerce_order_itemmeta WHERE meta_key='_variation_id' AND meta_value=%s LIMIT 1", (string) $id));
if (!$existing && $history) { throw new RuntimeException('Historical orders require an audited cutover'); }
}
self::save_map($config, $data['product_id'], 0, $parent_id, 0);
foreach ($data['variants'] as $row) { self::save_map($config, $data['product_id'], $row['variant_id'], $row['external_variation_id'], $parent_id); }
return array('success' => true);
} catch (Throwable $error) {
return new WP_Error('native_mapping_failed', $error->getMessage(), array('status' => 409));
} finally { if ($lock) { self::unlock($lock); } }
}
private static function store_price($value, $factor)
{
if (!preg_match('/^\d+(\.\d{1,2})?$/D', $value)) { throw new RuntimeException('Invalid exact catalogue price'); }
$parts = explode('.', $value, 2);
$whole = $parts[0]; $fraction = $parts[1] ?? '';
if ((float) $factor === 10.0) {
$fraction = substr($whole, -1) . $fraction;
$whole = strlen($whole) > 1 ? substr($whole, 0, -1) : '0';
} elseif ((float) $factor !== 1.0) { throw new RuntimeException('Unsupported exact currency factor'); }
$fraction = rtrim($fraction, '0');
if (strlen($fraction) > wc_get_price_decimals()) { throw new RuntimeException('Store price precision cannot represent this catalogue price'); }
return $whole . ($fraction !== '' ? '.' . $fraction : '');
}
private static function save_map($config, $product_id, $variant_id, $wc_id, $parent_id)
{
global $wpdb;
$table = $wpdb->prefix . 'hesabix_v2_native_map';
$existing = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$table} WHERE connection_key=%s AND product_id=%d AND variant_id=%d", $config['connection_key'], $product_id, $variant_id), ARRAY_A);
if ($existing) {
if ((int) $existing['wc_id'] !== (int) $wc_id) { throw new RuntimeException('Mapping identity conflict'); }
return;
}
if (!$wpdb->insert($table, array('connection_key' => $config['connection_key'], 'generation' => $config['generation'],
'business_id' => $config['business_id'], 'product_id' => $product_id, 'variant_id' => $variant_id,
'wc_id' => $wc_id, 'wc_parent_id' => $parent_id, 'status' => 'active'))) { throw new RuntimeException('Mapping write failed'); }
}
private static function order_lines($order, array $invoice_data)
{
$result = array(); $index = 0;
$db = new Hesabix_V2_DB_Service();
foreach ($order->get_items() as $item) {
$line = $invoice_data['lines'][$index++] ?? null;
if (!$line) { throw new RuntimeException('Incomplete order invoice'); }
$variation_id = $item->get_variation_id();
$map = self::mapping($variation_id);
$entry = array('external_line_id' => (string) $item->get_id(), 'external_product_id' => (string) $item->get_product_id(),
'external_variation_id' => (string) $variation_id, 'quantity' => (string) $item->get_quantity(),
'unit_price' => (string) ($line['extra_info']['unit_price'] ?? '0'), 'extra_info' => $line['extra_info'] ?? array());
if (!$map) {
$pid = $variation_id ? $db->get_hesabix_id('product', $variation_id, $item->get_product_id()) : $db->get_hesabix_id('product', $item->get_product_id(), null);
if (!$pid) { throw new RuntimeException('COMMERCE_MAPPING_REQUIRED'); }
$entry['legacy_product_id'] = (int) $pid;
}
$result[] = $entry;
}
if ($index !== count($invoice_data['lines'])) { throw new RuntimeException('Native orders require shipping and fees as invoice adjustments'); }
return $result;
}
public static function reserve_checkout($order)
{
if (!$order instanceof WC_Order) { $order = wc_get_order($order); }
if (!self::owns_order($order)) { return; }
$invoice = Hesabix_V2_Mapper::wc_order_to_invoice($order, null);
$payload = array('external_order_id' => (string) $order->get_id(), 'lines' => self::order_lines($order, $invoice), 'ttl_seconds' => 1800);
$result = (new Hesabix_V2_Api())->native_request('reservations', $payload, 'checkout:' . $order->get_id() . ':' . wp_generate_uuid4());
if (empty($result['success'])) { throw new RuntimeException('رزرو موجودی حسابیکس ناموفق بود؛ پرداخت انجام نشد.'); }
$order->update_meta_data('_hesabix_native_order', true);
$order->save();
}
private static function next_order_sequence($order_id)
{
// H03: allocate at capture, never at delivery/retry. No queue changes.
global $wpdb;
$name = '_hesabix_native_sequence_' . (int) $order_id;
// Duplicate initialization must never reset a counter via an option cache.
$created = $wpdb->query($wpdb->prepare(
"INSERT INTO {$wpdb->options} (option_name,option_value,autoload) VALUES (%s,'0','no') ON DUPLICATE KEY UPDATE option_name=option_name", $name
));
if ($created === false) { throw new RuntimeException('COMMERCE_ORDER_SEQUENCE_UNAVAILABLE'); }
$updated = $wpdb->query($wpdb->prepare(
"UPDATE {$wpdb->options} SET option_value=LAST_INSERT_ID(CAST(option_value AS UNSIGNED)+1) WHERE option_name=%s AND option_value REGEXP '^[0-9]+$' AND CAST(option_value AS UNSIGNED)<%d",
$name, PHP_INT_MAX
));
if ($updated !== 1) { throw new RuntimeException('COMMERCE_ORDER_SEQUENCE_UNAVAILABLE'); }
$sequence = $wpdb->get_var('SELECT LAST_INSERT_ID()');
if ((string) (int) $sequence !== (string) $sequence || (int) $sequence < 1) {
throw new RuntimeException('COMMERCE_ORDER_SEQUENCE_UNAVAILABLE');
}
wp_cache_delete($name, 'options');
wp_cache_delete('notoptions', 'options');
return (int) $sequence;
}
public static function status_changed($order_id, $from, $to, $order)
{
if (!self::owns_order($order)) { return; }
if (!in_array($to, array('processing', 'completed', 'cancelled', 'failed'), true)) { return; }
self::enqueue($order_id, array('event_type' => $to, 'external_sequence' => self::next_order_sequence($order_id)), 'status:' . $order_id . ':' . wp_generate_uuid4());
}
public static function refunded($order_id, $refund_id)
{
if (!self::owns_order($order_id)) { return; }
$refund = wc_get_order($refund_id);
$lines = array();
foreach ($refund->get_items() as $item) {
$lines[] = array('external_line_id' => (string) $item->get_meta('_refunded_item_id', true),
'external_product_id' => (string) $item->get_product_id(), 'external_variation_id' => (string) $item->get_variation_id(),
'quantity' => (string) abs($item->get_quantity()));
}
// Refund payment and physical return are separate explicit operations.
self::enqueue($order_id, array('event_type' => 'refund', 'external_sequence' => self::next_order_sequence($order_id), 'refund_id' => (string) $refund_id, 'lines' => $lines, 'restock' => (bool) $refund->get_meta('_hesabix_native_restock', true)), 'refund:' . $order_id . ':' . $refund_id);
}
private static function enqueue($order_id, array $payload, $key)
{
if (in_array($payload['event_type'], array('processing', 'completed'), true)) {
try {
$order = wc_get_order($order_id);
$gate = Hesabix_V2_Currency_Service::evaluate_currency_sync(new Hesabix_V2_Api(), $order->get_currency());
if (empty($gate['ok'])) { throw new RuntimeException('Currency unavailable'); }
$invoice = Hesabix_V2_Mapper::wc_order_to_invoice($order, null, $gate['factor'], $gate['currency_id']);
$payload['invoice_snapshot'] = $invoice;
$payload['commerce_lines'] = self::order_lines($order, $invoice);
} catch (Throwable $error) {
$payload['capture_error'] = 'COMMERCE_ORDER_SNAPSHOT_FAILED';
}
}
global $wpdb;
$table = $wpdb->prefix . 'hesabix_v2_native_queue';
$wpdb->query($wpdb->prepare("INSERT IGNORE INTO {$table} (event_key,order_id,payload,status) VALUES (%s,%d,%s,'pending')", $key, $order_id, wp_json_encode($payload)));
wp_schedule_single_event(time() + 1, 'hesabix_v2_native_event', array($key));
}
public static function process_event($key)
{
global $wpdb;
$table = $wpdb->prefix . 'hesabix_v2_native_queue';
$token = wp_generate_uuid4();
$claimed = $wpdb->query($wpdb->prepare("UPDATE {$table} SET status='processing', claim_token=%s, attempts=attempts+1, locked_until=DATE_ADD(UTC_TIMESTAMP(),INTERVAL 120 SECOND) WHERE event_key=%s AND ((status='pending' AND (locked_until IS NULL OR locked_until<=UTC_TIMESTAMP())) OR (status='processing' AND locked_until<UTC_TIMESTAMP()))", $token, $key));
if ($claimed !== 1) { return; }
wp_schedule_single_event(time() + 130, 'hesabix_v2_native_event', array($key));
$row = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$table} WHERE event_key=%s", $key), ARRAY_A);
if (!$row || $row['claim_token'] !== $token) { return; }
self::$event = array_merge(json_decode($row['payload'], true), array('event_key' => $key));
try {
$result = (new Hesabix_V2_Sync_Service())->sync_order((int) $row['order_id']);
if (empty($result['success'])) { throw new RuntimeException('Native order import failed'); }
$wpdb->update($table, array('status' => 'completed', 'locked_until' => null, 'claim_token' => null, 'last_error' => null), array('event_key' => $key, 'claim_token' => $token));
} catch (Throwable $error) {
$status = (int) $row['attempts'] >= 10 ? 'dead_letter' : 'pending';
$delay = min(3600, 1 << min(10, (int) $row['attempts']));
$wpdb->update($table, array('status' => $status, 'locked_until' => $status === 'pending' ? gmdate('Y-m-d H:i:s', time() + $delay) : null, 'claim_token' => null, 'last_error' => 'COMMERCE_ORDER_SYNC_FAILED'), array('event_key' => $key, 'claim_token' => $token));
if ($status === 'pending') { wp_schedule_single_event(time() + $delay, 'hesabix_v2_native_event', array($key)); }
} finally { self::$event = null; }
}
public static function recover_events()
{
global $wpdb;
$table = $wpdb->prefix . 'hesabix_v2_native_queue';
$keys = $wpdb->get_col("SELECT event_key FROM {$table} WHERE (status='pending' AND (locked_until IS NULL OR locked_until<=UTC_TIMESTAMP())) OR (status='processing' AND locked_until<UTC_TIMESTAMP()) ORDER BY order_id LIMIT 50");
foreach ($keys as $key) { wp_schedule_single_event(time() + 1, 'hesabix_v2_native_event', array($key)); }
}
public static function sync_prepared_order($order, array $invoice_data)
{
$event = self::$event;
if (!$event) {
$sequence = self::next_order_sequence($order->get_id());
$event = array('event_type' => $order->get_status(), 'external_sequence' => $sequence,
'event_key' => 'manual:' . $order->get_id() . ':' . $sequence);
}
if (!empty($event['capture_error'])) { throw new RuntimeException('COMMERCE_ORDER_SNAPSHOT_FAILED: manual resolution required'); }
$terminal = in_array($event['event_type'], array('refund', 'cancelled', 'failed', 'release'), true);
$lines = $terminal ? array() : ($event['commerce_lines'] ?? self::order_lines($order, $invoice_data));
$payload = array('external_order_id' => (string) $order->get_id(), 'event_type' => $event['event_type'],
'lines' => $event['lines'] ?? $lines, 'invoice' => $invoice_data,
'external_sequence' => (int) ($event['external_sequence'] ?? 0));
if (isset($event['refund_id'])) { $payload['refund_id'] = $event['refund_id']; $payload['restock'] = !empty($event['restock']); }
$result = (new Hesabix_V2_Api())->native_request('orders/upsert', $payload, $event['event_key']);
if (!empty($result['success'])) {
$result['hesabix_id'] = $result['data']['invoice_id'] ?? null;
$result['message'] = 'Native order synchronized';
}
return $result;
}
public static function invoice_for_event($order, $person_id, array $gate)
{
$event = self::$event ?: array('event_type' => $order->get_status());
if (in_array($event['event_type'], array('refund', 'cancelled', 'failed', 'release'), true)) { return array(); }
$invoice = $event['invoice_snapshot'] ?? Hesabix_V2_Mapper::wc_order_to_invoice($order, $person_id, $gate['factor'], $gate['currency_id']);
if ((int) $invoice['currency_id'] !== (int) $gate['currency_id']) { throw new RuntimeException('Captured currency changed'); }
$invoice['extra_info']['person_id'] = $person_id;
return $invoice;
}
public static function accept_import(array $data)
{
self::install();
$current = get_option('hesabix_v2_native_connection', array());
if ($current && (($current['connection_key'] ?? '') !== $data['connection_key'] || (int) $current['generation'] !== (int) $data['generation'])) { throw new RuntimeException('Connection identity conflict'); }
$config = array_intersect_key($data, array_flip(array('connection_id', 'connection_key', 'generation', 'business_id')));
update_option('hesabix_v2_native_connection', $config, false);
update_post_meta((int) $data['external_product_id'], '_hesabix_native_catalog_source', 'woocommerce');
self::save_map($config, $data['product_id'], 0, $data['external_product_id'], 0);
foreach ($data['variants'] as $row) { self::save_map($config, $data['product_id'], $row['variant_id'], $row['external_variation_id'], $data['external_product_id']); }
}
public static function refresh_stock()
{
$config = get_option('hesabix_v2_native_connection', array());
if (empty($config['connection_id'])) { throw new RuntimeException('Existing native maps require explicit adoption'); }
$response = (new Hesabix_V2_Api())->native_request('stock-snapshot', array(), 'stock-snapshot:' . wp_generate_uuid4());
if (empty($response['success'])) { throw new RuntimeException($response['message'] ?? 'Native stock snapshot failed'); }
$updated = 0;
foreach ($response['data']['items'] as $row) {
$request = new WP_REST_Request('POST'); $request->set_header('Content-Type', 'application/json'); $request->set_body(wp_json_encode($row));
$result = self::route_stock($request);
if (is_wp_error($result)) { throw new RuntimeException($result->get_error_message()); }
$updated++;
}
return $updated;
}
public static function quantity_decimal($value)
{
if (is_float($value)) {
$text = number_format($value, 6, '.', '');
if (!is_finite($value) || (float) $text !== $value) { throw new RuntimeException('Native quantity exceeds six decimal places'); }
} else { $text = (string) $value; }
if (!preg_match('/^\d{1,12}(?:\.\d{1,6})?$/D', $text)) { throw new RuntimeException('Invalid exact native quantity'); }
return $text;
}
public static function add_quantities($left, $right)
{
if (PHP_INT_SIZE < 8) { throw new RuntimeException('Native exact quantities require 64-bit PHP'); }
$values = array();
foreach (array($left, $right) as $raw) {
$parts = explode('.', self::quantity_decimal($raw), 2);
$values[] = (int) $parts[0] * 1000000 + (int) str_pad($parts[1] ?? '', 6, '0');
}
$total = $values[0] + $values[1];
if ($total > 999999999999999999) { throw new RuntimeException('Native quantity exceeds database precision'); }
return (string) intdiv($total, 1000000) . '.' . str_pad((string) ($total % 1000000), 6, '0', STR_PAD_LEFT);
}
}