H36: حفظ دقت مبلغ فاکتور و دریافت ووکامرس #73

Open
Seyyed wants to merge 2 commits from Seyyed/Seyyed_arc:codex/team-base-45-h36-woo-money-precision into master
4 changed files with 456 additions and 55 deletions

View file

@ -24,7 +24,7 @@ class Hesabix_V2_Currency_Service
*/
private static function list_transient_key()
{
return 'hesabix_v2_bc_' . (int) get_option('hesabix_v2_business_id');
return 'hesabix_v2_bc_money_' . (int) get_option('hesabix_v2_business_id');
}
/**
@ -81,12 +81,26 @@ class Hesabix_V2_Currency_Service
'title' => isset($row['title']) ? (string) $row['title'] : '',
'name' => isset($row['name']) ? (string) $row['name'] : '',
'is_default' => !empty($row['is_default']),
'decimal_places' => isset($row['decimal_places']) ? (int) $row['decimal_places'] : null,
'round_monetary_amounts' => isset($row['round_monetary_amounts']) ? (bool) $row['round_monetary_amounts'] : null,
);
}
return $out;
}
/** Currency policy comes from the API, never from the Woo currency label. */
public static function invoice_money_policy($currency_id)
{
foreach (self::get_business_currency_rows() as $row) {
if ((int) $row['id'] === (int) $currency_id && isset($row['decimal_places'], $row['round_monetary_amounts'])) {
return array('decimal_places' => max(0, min(8, (int) $row['decimal_places'])),
'round_monetary_amounts' => (bool) $row['round_monetary_amounts']);
}
}
throw new RuntimeException('دقت و سیاست گردکردن ارز فاکتور از حسابیکس دریافت نشد.');
}
/**
* دریافت لیست ارزهای کسب‌وکار (با کش).
*

View file

@ -0,0 +1,165 @@
<?php
/** Decimal-string arithmetic for invoice payloads; no float or optional extension. */
class Hesabix_V2_Decimal
{
private static function parts($value)
{
$text = is_float($value) ? json_encode($value, JSON_PRESERVE_ZERO_FRACTION) : (string) $value;
if (!preg_match('/^([+-]?)([0-9]+)(?:\.([0-9]*))?(?:[eE]([+-]?[0-9]+))?$/', trim($text), $m)) {
throw new InvalidArgumentException('Invalid decimal amount');
}
$fraction = isset($m[3]) ? $m[3] : '';
$scale = strlen($fraction) - (isset($m[4]) ? (int) $m[4] : 0);
$digits = ltrim($m[2] . $fraction, '0');
if ($scale < 0) {
$digits .= str_repeat('0', -$scale);
$scale = 0;
}
return array($m[1] === '-' ? -1 : 1, $digits === '' ? '0' : $digits, $scale);
}
private static function render($sign, $digits, $scale)
{
$digits = ltrim($digits, '0');
if ($digits === '') {
return '0';
}
if ($scale > 0) {
$digits = str_pad($digits, $scale + 1, '0', STR_PAD_LEFT);
$digits = rtrim(substr($digits, 0, -$scale) . '.' . substr($digits, -$scale), '0');
$digits = rtrim($digits, '.');
}
return ($sign < 0 ? '-' : '') . $digits;
}
private static function cmp_digits($a, $b)
{
$a = ltrim($a, '0');
$b = ltrim($b, '0');
return strlen($a) !== strlen($b) ? strlen($a) <=> strlen($b) : strcmp($a, $b);
}
private static function add_digits($a, $b)
{
$out = '';
$carry = 0;
for ($i = strlen($a) - 1, $j = strlen($b) - 1; $i >= 0 || $j >= 0 || $carry; $i--, $j--) {
$n = ($i >= 0 ? (int) $a[$i] : 0) + ($j >= 0 ? (int) $b[$j] : 0) + $carry;
$out = ($n % 10) . $out;
$carry = intdiv($n, 10);
}
return $out;
}
private static function sub_digits($a, $b)
{
$out = '';
$borrow = 0;
for ($i = strlen($a) - 1, $j = strlen($b) - 1; $i >= 0; $i--, $j--) {
$n = (int) $a[$i] - ($j >= 0 ? (int) $b[$j] : 0) - $borrow;
$borrow = $n < 0 ? 1 : 0;
$out = ($n < 0 ? $n + 10 : $n) . $out;
}
return ltrim($out, '0') ?: '0';
}
public static function add($a, $b)
{
list($sa, $a, $pa) = self::parts($a);
list($sb, $b, $pb) = self::parts($b);
$scale = max($pa, $pb);
$a .= str_repeat('0', $scale - $pa);
$b .= str_repeat('0', $scale - $pb);
if ($sa === $sb) {
return self::render($sa, self::add_digits($a, $b), $scale);
}
return self::cmp_digits($a, $b) >= 0
? self::render($sa, self::sub_digits($a, $b), $scale)
: self::render($sb, self::sub_digits($b, $a), $scale);
}
public static function subtract($a, $b)
{
$b = self::add($b, '0');
return self::add($a, strpos($b, '-') === 0 ? substr($b, 1) : '-' . $b);
}
public static function multiply($a, $b)
{
list($sa, $a, $pa) = self::parts($a);
list($sb, $b, $pb) = self::parts($b);
$out = '0';
for ($i = strlen($b) - 1, $zeros = ''; $i >= 0; $i--, $zeros .= '0') {
$row = '0';
for ($n = 0; $n < (int) $b[$i]; $n++) {
$row = self::add_digits($row, $a);
}
$out = self::add_digits($out, $row . $zeros);
}
return self::render($sa * $sb, $out, $pa + $pb);
}
public static function divide($a, $b, $places = 24)
{
list($sa, $a, $pa) = self::parts($a);
list($sb, $b, $pb) = self::parts($b);
if ($b === '0') {
throw new InvalidArgumentException('Division by zero');
}
$a .= str_repeat('0', $pb + $places);
$b .= str_repeat('0', $pa);
$remainder = '0';
$out = '';
for ($i = 0; $i < strlen($a); $i++) {
$remainder = ltrim($remainder . $a[$i], '0') ?: '0';
$digit = 0;
while (self::cmp_digits($remainder, $b) >= 0) {
$remainder = self::sub_digits($remainder, $b);
$digit++;
}
$out .= (string) $digit;
}
return self::render($sa * $sb, $out, $places);
}
public static function round($value, $places)
{
list($sign, $digits, $scale) = self::parts($value);
if ($scale <= $places) {
return self::render($sign, $digits, $scale);
}
$cut = $scale - $places;
$digits = str_pad($digits, $cut + 1, '0', STR_PAD_LEFT);
$head = substr($digits, 0, -$cut);
if ((int) $digits[strlen($digits) - $cut] >= 5) {
$head = self::add_digits($head, '1');
}
return self::render($sign, $head, $places);
}
/** A positive unit quotient must not put an exact half-cent below its boundary. */
public static function unit_price($amount, $quantity)
{
$price = self::divide($amount, $quantity);
if (self::subtract(self::multiply($price, $quantity), $amount) !== '0') {
$negative = (strpos((string) $amount, '-') === 0) !== (strpos((string) $quantity, '-') === 0);
$price = self::add($price, ($negative ? '-' : '') . '0.000000000000000000000001');
}
return $price;
}
public static function compare($a, $b)
{
$delta = self::subtract($a, $b);
return $delta === '0' ? 0 : (strpos($delta, '-') === 0 ? -1 : 1);
}
public static function money($value, array $policy)
{
$value = !empty($policy['round_monetary_amounts']) ? self::round($value, $policy['decimal_places']) : self::add($value, '0');
if (self::subtract($value, self::round($value, 2)) !== '0') {
throw new RuntimeException('مبلغ سفارش بیش از دو رقم اعشار دارد و در دفتر کل فعلی حسابیکس قابل حفظ نیست.');
}
return $value;
}
}

View file

@ -7,6 +7,8 @@
* @subpackage Hesabix_V2/includes
*/
require_once __DIR__ . '/class-hesabix-v2-decimal.php';
class Hesabix_V2_Mapper
{
/**
@ -554,6 +556,9 @@ class Hesabix_V2_Mapper
if ($f <= 0 || is_nan($f)) {
$f = 1.0;
}
$currency_id = $invoice_currency_id !== null
? (int) $invoice_currency_id : Hesabix_V2_Currency_Service::resolve_invoice_currency_id();
$money_policy = Hesabix_V2_Currency_Service::invoice_money_policy($currency_id);
$date_opts = is_array($date_overrides) ? $date_overrides : array();
$document_date_override = isset($date_opts['document_date']) && is_string($date_opts['document_date']) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $date_opts['document_date'])
@ -564,6 +569,7 @@ class Hesabix_V2_Mapper
: null;
$lines = array();
$legacy_line_values = array();
$invoice_adjustments = array();
$shipping_adjustment_net = 0.0;
$shipping_adjustment_tax = 0.0;
@ -654,13 +660,14 @@ class Hesabix_V2_Mapper
}
$quantity = $item->get_quantity();
$total = (float) $item->get_total() * $f;
$unit_price = $quantity > 0 ? $total / $quantity : 0;
$tax_amount = Hesabix_V2_Validation::sanitize_price((float) $item->get_total_tax() * $f);
$line_total = Hesabix_V2_Validation::sanitize_price($total) + $tax_amount;
$total = Hesabix_V2_Decimal::multiply($item->get_total(), $f);
$unit_price = $quantity > 0 ? Hesabix_V2_Decimal::unit_price($total, $quantity) : '0';
// Keep Woo tax shares exact; fractions can sum to whole ledger cents.
$tax_amount = Hesabix_V2_Decimal::multiply($item->get_total_tax(), $f);
$line_total = Hesabix_V2_Decimal::add($total, $tax_amount);
$line_extra = array(
'unit_price' => Hesabix_V2_Validation::sanitize_price($unit_price),
'unit_price' => $unit_price,
'line_discount' => 0,
'tax_amount' => $tax_amount,
'line_total' => $line_total,
@ -694,19 +701,26 @@ class Hesabix_V2_Mapper
$line_row['allocations'] = $alloc;
$line_row['extra_info']['allocations'] = $alloc;
}
// A safe legacy number keeps already-posted invoices editable under #61.
// It is only an encoding candidate, never the source of money arithmetic.
$legacy_line_values[count($lines)] = array(
'unit_price' => $quantity > 0 ? ((float) $item->get_total() * $f) / $quantity : 0.0,
'tax_amount' => (float) $item->get_total_tax() * $f,
'line_discount' => 0,
);
$lines[] = $line_row;
}
// هزینه حمل و نقل
if ($order->get_shipping_total() > 0) {
$ship_total = Hesabix_V2_Validation::sanitize_price((float) $order->get_shipping_total() * $f);
$ship_tax = Hesabix_V2_Validation::sanitize_price((float) $order->get_shipping_tax() * $f);
$ship_total = Hesabix_V2_Decimal::multiply($order->get_shipping_total(), $f);
$ship_tax = Hesabix_V2_Decimal::multiply($order->get_shipping_tax(), $f);
$shipping_as_account = self::shipping_should_be_account_adjustment();
if ($shipping_as_account) {
$shipping_account_id = self::resolve_shipping_adjustment_account_id();
if ($shipping_account_id > 0) {
$shipping_adjustment_net = (float) $ship_total;
$shipping_adjustment_tax = (float) $ship_tax;
$shipping_adjustment_net = $ship_total;
$shipping_adjustment_tax = $ship_tax;
$tax_rate = 0.0;
if ($ship_total > 0 && $ship_tax > 0) {
$tax_rate = ((float) $ship_tax / (float) $ship_total) * 100;
@ -737,11 +751,16 @@ class Hesabix_V2_Mapper
$shipping_product_id = null;
}
if ($shipping_product_id) {
$legacy_line_values[count($lines)] = array(
'unit_price' => (float) $order->get_shipping_total() * $f,
'tax_amount' => (float) $order->get_shipping_tax() * $f,
'line_discount' => 0,
);
$line_extra = array(
'unit_price' => $ship_total,
'line_discount' => 0,
'tax_amount' => $ship_tax,
'line_total' => $ship_total + $ship_tax,
'line_total' => Hesabix_V2_Decimal::add($ship_total, $ship_tax),
'unit' => 'عدد',
'unit_price_source' => 'base',
'discount_type' => 'amount',
@ -774,43 +793,43 @@ class Hesabix_V2_Mapper
);
}
$order_total = (float) $order->get_total() * $f;
$order_tax = (float) $order->get_total_tax() * $f;
$order_discount = (float) $order->get_discount_total() * $f;
$order_total = Hesabix_V2_Decimal::money(Hesabix_V2_Decimal::multiply($order->get_total(), $f), $money_policy);
$order_tax = Hesabix_V2_Decimal::money(Hesabix_V2_Decimal::multiply($order->get_total_tax(), $f), $money_policy);
$order_discount = Hesabix_V2_Decimal::money(Hesabix_V2_Decimal::multiply($order->get_discount_total(), $f), $money_policy);
$target_net_rounded = (int) round($order_total, 0);
$lines_target_net_rounded = (int) round(
$order_total
- $shipping_adjustment_net
- $shipping_adjustment_tax
- $fee_adjustment_net
- $fee_adjustment_tax,
0
);
self::adjust_invoice_lines_rounding_to_order_net($lines, $lines_target_net_rounded, $order->get_id());
$target_net_rounded = $order_total;
$adjustments_net = Hesabix_V2_Decimal::add($shipping_adjustment_net, $fee_adjustment_net);
$adjustments_tax = Hesabix_V2_Decimal::add($shipping_adjustment_tax, $fee_adjustment_tax);
$lines_target_net_rounded = Hesabix_V2_Decimal::subtract($order_total, Hesabix_V2_Decimal::add($adjustments_net, $adjustments_tax));
foreach ($lines as $index => $line) {
if (!isset($legacy_line_values[$index])) {
$legacy_line_values[$index] = array_intersect_key($line['extra_info'], array_flip(array('unit_price', 'tax_amount', 'line_discount')));
}
}
self::adjust_invoice_lines_rounding_to_order_net($lines, $lines_target_net_rounded, $order->get_id(), $legacy_line_values);
self::preserve_safe_numeric_line_encoding($lines, $legacy_line_values, $money_policy['decimal_places']);
$gross = $order_total + $order_discount - $order_tax - $shipping_adjustment_net - $fee_adjustment_net;
$header_tax_total = $order_tax - $shipping_adjustment_tax - $fee_adjustment_tax;
$gross = Hesabix_V2_Decimal::subtract(Hesabix_V2_Decimal::add($order_total, $order_discount), Hesabix_V2_Decimal::add($order_tax, $adjustments_net));
$header_tax_total = Hesabix_V2_Decimal::subtract($order_tax, $adjustments_tax);
if ($header_tax_total < 0) {
$header_tax_total = 0;
}
// حسابیکس مبلغ قطعی فاکتور را از gross − discount + tax می‌گیرد؛ پرداخت افزونه از round(order_total).
// گرد کردن جداگانه ممکن است ۱–۲ واحد اختلاف بدهد؛ gross را در حد تحمل اصلاح می‌کنیم.
$gross_r = (int) round($gross, 0);
$discount_r = (int) round($order_discount, 0);
$tax_r = (int) round($header_tax_total, 0);
$adj_net_r = (int) round($shipping_adjustment_net + $fee_adjustment_net, 0);
$adj_tax_r = (int) round($shipping_adjustment_tax + $fee_adjustment_tax, 0);
$from_header = $gross_r - $discount_r + $tax_r + $adj_net_r + $adj_tax_r;
$hdr_delta = $target_net_rounded - $from_header;
if ($hdr_delta !== 0) {
// Header and payment use the same converted order amount and API currency policy.
$gross_r = Hesabix_V2_Decimal::money($gross, $money_policy);
$discount_r = $order_discount;
$tax_r = $header_tax_total;
$adj_net_r = Hesabix_V2_Decimal::money($adjustments_net, $money_policy);
$adj_tax_r = Hesabix_V2_Decimal::money($adjustments_tax, $money_policy);
$from_header = Hesabix_V2_Decimal::add(Hesabix_V2_Decimal::subtract($gross_r, $discount_r), Hesabix_V2_Decimal::add($tax_r, Hesabix_V2_Decimal::add($adj_net_r, $adj_tax_r)));
$hdr_delta = Hesabix_V2_Decimal::subtract($target_net_rounded, $from_header);
if ($hdr_delta !== '0') {
$hdr_tol = (int) apply_filters('hesabix_v2_invoice_header_totals_tolerance', 5);
if ($hdr_tol < 1) {
$hdr_tol = 1;
}
if (abs($hdr_delta) <= $hdr_tol && ($gross_r + $hdr_delta) >= 0) {
$gross_r += $hdr_delta;
$gross_r = Hesabix_V2_Decimal::add($gross_r, $hdr_delta);
} elseif (abs($hdr_delta) <= $hdr_tol && ($gross_r + $hdr_delta) < 0) {
Hesabix_V2_Log_Service::warning(
'Invoice header gross adjustment skipped (would become negative).',
@ -846,10 +865,6 @@ class Hesabix_V2_Mapper
$is_proforma = false;
}
$currency_id = $invoice_currency_id !== null
? (int) $invoice_currency_id
: Hesabix_V2_Currency_Service::resolve_invoice_currency_id();
$_created = $order->get_date_created();
$document_date = $document_date_override !== null
? $document_date_override
@ -886,38 +901,39 @@ class Hesabix_V2_Mapper
$payload['tag_ids'] = $tag_ids;
}
$payload['payments'] = self::build_wc_order_invoice_payments($order, $is_proforma, $f, $payment_date_ymd);
$payload['payments'] = self::build_wc_order_invoice_payments($order, $is_proforma, $f, $payment_date_ymd, $target_net_rounded);
return $payload;
}
/**
* اختلاف گرد کردن بین جمع line_total خطوط و مبلغ نهایی سفارش ( IRR / واحدهای صحیح ).
* اختلاف جمع line_total خطوط و مبلغ معتبر سفارش در ارز فاکتور.
*
* حداکثر اختلاف قابل قبول با فیلتر `hesabix_v2_invoice_rounding_tolerance` (پیش‌فرض ۲ واحد پول).
*
* @param array<int, array<string, mixed>> $lines
* @param int $target_net_rounded round(order_total)
* @param string $target_net_rounded مبلغ ده‌دهی معتبر سفارش
* @param int $order_id
* @return void
*/
private static function adjust_invoice_lines_rounding_to_order_net(array &$lines, $target_net_rounded, $order_id)
private static function adjust_invoice_lines_rounding_to_order_net(array &$lines, $target_net_rounded, $order_id, array &$legacy_line_values)
{
if (empty($lines)) {
return;
}
$sum = 0.0;
$sum = '0';
foreach ($lines as $ln) {
$ei = isset($ln['extra_info']) && is_array($ln['extra_info']) ? $ln['extra_info'] : array();
if (!isset($ei['line_total'])) {
continue;
}
$sum += (float) $ei['line_total'];
$sum = Hesabix_V2_Decimal::add($sum, $ei['line_total']);
}
$delta = $target_net_rounded - (int) round($sum, 0);
if ($delta === 0) {
// The server quantizes the invoice total to cents, not each tax share.
$delta = Hesabix_V2_Decimal::subtract($target_net_rounded, Hesabix_V2_Decimal::round($sum, 2));
if ($delta === '0') {
return;
}
@ -963,7 +979,7 @@ class Hesabix_V2_Mapper
$idx = count($lines) - 1;
}
$qty = isset($lines[ $idx ]['quantity']) ? (float) $lines[ $idx ]['quantity'] : 1.0;
$qty = isset($lines[ $idx ]['quantity']) ? $lines[ $idx ]['quantity'] : 1;
if ($qty <= 0) {
$qty = 1.0;
}
@ -973,12 +989,15 @@ class Hesabix_V2_Mapper
}
$ei = &$lines[ $idx ]['extra_info'];
$ei['line_total'] = (float) $ei['line_total'] + $delta;
$ei['line_total'] = Hesabix_V2_Decimal::add($ei['line_total'], $delta);
if (!empty($ei['wc_fee_negative'])) {
$ei['line_discount'] = (float) $ei['line_discount'] - $delta;
$ei['line_discount'] = Hesabix_V2_Decimal::subtract($ei['line_discount'], $delta);
$legacy_line_values[$idx]['line_discount'] = (float) $legacy_line_values[$idx]['line_discount'] - (float) $delta;
} else {
$ei['unit_price'] = (float) $ei['unit_price'] + ($delta / $qty);
$net = Hesabix_V2_Decimal::add(Hesabix_V2_Decimal::subtract($ei['line_total'], $ei['tax_amount'] ?? 0), $ei['line_discount'] ?? 0);
$ei['unit_price'] = Hesabix_V2_Decimal::unit_price($net, $qty);
$legacy_line_values[$idx]['unit_price'] = (float) $legacy_line_values[$idx]['unit_price'] + ((float) $delta / (float) $qty);
}
$ei['wc_rounding_adjust'] = $delta;
@ -995,6 +1014,72 @@ class Hesabix_V2_Mapper
}
}
private static function wire_decimal($value)
{
if (is_float($value)) {
$encoded = json_encode($value);
if ($encoded === false) {
throw new InvalidArgumentException('Non-finite invoice amount');
}
return $encoded;
}
return (string) $value;
}
private static function wire_line_totals($quantity, array $info)
{
$gross = Hesabix_V2_Decimal::multiply($quantity, self::wire_decimal($info['unit_price'] ?? 0));
$discount = self::wire_decimal($info['line_discount'] ?? 0);
$tax = self::wire_decimal($info['tax_amount'] ?? 0);
return array($gross, $discount, $tax, Hesabix_V2_Decimal::add(Hesabix_V2_Decimal::subtract($gross, $discount), $tax));
}
/** Keep legacy JSON numbers only when line validation and monetary results agree. */
private static function preserve_safe_numeric_line_encoding(array &$lines, array $legacy, $places)
{
$exact = $lines;
$quant = $places > 0 ? '0.' . str_repeat('0', $places - 1) . '1' : '1';
foreach ($lines as $index => &$line) {
$info = $line['extra_info'];
$candidate = array_replace($info, $legacy[$index]);
try {
$wanted = self::wire_line_totals($line['quantity'], $info);
$encoded = self::wire_line_totals($line['quantity'], $candidate);
$delta = ltrim(Hesabix_V2_Decimal::subtract($encoded[3], self::wire_decimal($info['line_total'])), '-');
$tolerance = Hesabix_V2_Decimal::multiply(ltrim(self::wire_decimal($line['quantity']), '-'), $quant);
if (Hesabix_V2_Decimal::compare($tolerance, $quant) < 0) {
$tolerance = $quant;
}
$safe = Hesabix_V2_Decimal::compare($delta, $tolerance) <= 0;
foreach ($wanted as $key => $amount) {
$safe = $safe && Hesabix_V2_Decimal::round($amount, 2) === Hesabix_V2_Decimal::round($encoded[$key], 2);
}
if ($safe) {
$line['extra_info'] = $candidate;
}
} catch (InvalidArgumentException $e) {
// The exact decimal values remain authoritative.
}
}
unset($line);
$wanted = array('0', '0', '0', '0');
$encoded = $wanted;
foreach ($lines as $index => $line) {
$a = self::wire_line_totals($line['quantity'], $exact[$index]['extra_info']);
$b = self::wire_line_totals($line['quantity'], $line['extra_info']);
foreach ($a as $key => $amount) {
$wanted[$key] = Hesabix_V2_Decimal::add($wanted[$key], $amount);
$encoded[$key] = Hesabix_V2_Decimal::add($encoded[$key], $b[$key]);
}
}
foreach ($wanted as $key => $amount) {
if (Hesabix_V2_Decimal::round($amount, 2) !== Hesabix_V2_Decimal::round($encoded[$key], 2)) {
$lines = $exact;
break;
}
}
}
/**
* پرداخت‌های همراه فاکتور (سند دریافت در حسابیکس) فقط برای فاکتور قطعی و سفارش پرداخت‌شده.
*
@ -1004,7 +1089,7 @@ class Hesabix_V2_Mapper
* @param string|null $payment_date_ymd اگر ست باشد، بخش تاریخ transaction_date هم‌راستا با این مقدار (بخش ساعت از تاریخ پرداخت یا زمان کنونی).
* @return array<int, array<string, mixed>>
*/
private static function build_wc_order_invoice_payments($order, $is_proforma, $amount_factor = 1.0, $payment_date_ymd = null)
private static function build_wc_order_invoice_payments($order, $is_proforma, $amount_factor, $payment_date_ymd, $invoice_amount)
{
$payments = array();
@ -1017,7 +1102,7 @@ class Hesabix_V2_Mapper
$f = 1.0;
}
$amount = round((float) $order->get_total() * $f, 0);
$amount = $invoice_amount;
if ($amount <= 0) {
return apply_filters('hesabix_v2_invoice_payments', $payments, $order, $amount_factor);
}

View file

@ -0,0 +1,137 @@
<?php
/** Run with: php extraScripts/arcwoc/tests/test-invoice-money-precision.php */
define('WPINC', true);
require_once __DIR__ . '/../includes/class-hesabix-v2-decimal.php';
require_once __DIR__ . '/../includes/class-hesabix-v2-currency-service.php';
require_once __DIR__ . '/../includes/class-hesabix-v2-mapper.php';
function check($actual, $expected, $name)
{
if ($actual !== $expected) {
throw new RuntimeException($name . ': ' . json_encode(array($actual, $expected)));
}
}
function absint($v) { return abs((int) $v); }
function __($v, $domain = '') { return $v; }
function apply_filters($hook, $value, ...$args) { return $value; }
function get_transient($key) { return false; }
function set_transient(...$args) {}
function get_option($key, $default = false)
{
return array('hesabix_v2_enabled' => true, 'hesabix_v2_business_id' => 1, 'hesabix_v2_currency_id' => 1,
'hesabix_v2_invoice_payment_destination' => 'cash_register', 'hesabix_v2_default_cash_register_id' => '1')[$key] ?? $default;
}
function current_time($format) { return (new DateTimeImmutable('2026-11-11 12:00:00'))->format($format); }
class Hesabix_V2_Api
{
public function get_business_currencies() { return $GLOBALS['currency_response']; }
}
class Hesabix_V2_DB_Service { public function get_hesabix_id(...$args) { return 1; } }
class Hesabix_V2_Invoice_Warehouse_Service { public static function resolve_warehouse_id_for_order($order) { return null; } }
class Hesabix_V2_Invoice_Helper
{
public static function normalize_sync_settings($options) { return array(); }
public static function resolve_invoice_tag_ids() { return array(); }
}
class Hesabix_V2_Log_Service { public static function warning(...$args) {} }
class MoneyItem
{
private $item;
public function __construct($item = null) { $this->item = $item; }
public function get_product() { return new stdClass(); }
public function get_product_id() { return 1; }
public function get_variation_id() { return 0; }
public function get_quantity() { return ($this->item ?? $GLOBALS['money_case'])[0]; }
public function get_total() { return ($this->item ?? $GLOBALS['money_case'])[1]; }
public function get_total_tax() { return ($this->item ?? $GLOBALS['money_case'])[2]; }
public function get_id() { return 77; }
}
class MoneyOrder
{
public function get_items($type = 'line_item')
{
if ($type === 'fee') { return array(); }
return isset($GLOBALS['money_items']) ? array_map(fn($item) => new MoneyItem($item), $GLOBALS['money_items']) : array(new MoneyItem());
}
public function get_total() { return $GLOBALS['money_case'][3]; }
public function get_total_tax() { return $GLOBALS['money_case'][2]; }
public function get_discount_total() { return '0'; }
public function get_shipping_total() { return '0'; }
public function get_currency() { return $GLOBALS['money_currency'] ?? 'USD'; }
public function get_id() { return 100; }
public function get_order_number() { return '100'; }
public function get_date_created() { return null; }
public function get_date_paid() { return null; }
public function is_paid() { return true; }
}
$money_case = array(3, '30.01', '3.01', '33.02');
$money_currency = 'IRT';
$currency_response = array('success' => true, 'data' => array(array('id' => 1, 'code' => 'IRR', 'decimal_places' => 2, 'round_monetary_amounts' => true)));
$gate = Hesabix_V2_Currency_Service::evaluate_currency_sync(null, 'IRT');
$payload = Hesabix_V2_Mapper::wc_order_to_invoice(new MoneyOrder(), 1, $gate['factor'], $gate['currency_id']);
check($payload['lines'][0]['extra_info']['unit_price'], (30.01 * 10 / 3), 'legacy converted price encoding');
check($payload['lines'][0]['extra_info']['tax_amount'], (3.01 * 10), 'legacy converted tax encoding');
check($payload['payments'][0]['amount'], '330.2', 'converted payment is still exact');
unset($money_currency);
foreach (array(
array(array(1, '0.005', '0'), array(1, '0.005', '0'), '0.01'),
array(array(1, '1', '0.005'), array(1, '1', '0.005'), '2.01'),
) as $items) {
$money_case = array(1, '0', '0', $items[2], 2, true);
$money_case[2] = Hesabix_V2_Decimal::add($items[0][2], $items[1][2]);
$money_items = array($items[0], $items[1]);
$currency_response = array('success' => true, 'data' => array(array('id' => 1, 'code' => 'USD', 'decimal_places' => 2, 'round_monetary_amounts' => true)));
$payload = Hesabix_V2_Mapper::wc_order_to_invoice(new MoneyOrder(), 1, 1, 1);
check($payload['payments'][0]['amount'], $items[2], 'multi-line payment');
check(Hesabix_V2_Decimal::subtract($payload['lines'][0]['extra_info']['tax_amount'], $items[0][2]), '0', 'unrounded tax share');
}
unset($money_items);
$money_case = array(1, '0.01', '0.005', '0.02');
$payload = Hesabix_V2_Mapper::wc_order_to_invoice(new MoneyOrder(), 1, 1, 1);
check(Hesabix_V2_Decimal::subtract($payload['lines'][0]['extra_info']['unit_price'], '0.01'), '0', 'half-cent must not increase revenue');
check($payload['lines'][0]['extra_info']['line_total'], '0.015', 'server rounds the aggregate');
check($payload['payments'][0]['amount'], '0.02', 'half-cent payment');
check(Hesabix_V2_Decimal::add('999999999.99', '0.01'), '1000000000', 'carry');
check(Hesabix_V2_Decimal::subtract('-1.01', '-2'), '0.99', 'signed subtraction');
check(Hesabix_V2_Decimal::multiply('30.01', '10'), '300.1', 'toman conversion');
check(Hesabix_V2_Decimal::multiply('1.25', '0.08'), '0.1', 'fractional multiplier');
check(Hesabix_V2_Decimal::round('9.995', 2), '10', 'positive halfway');
check(Hesabix_V2_Decimal::round('-9.995', 2), '-10', 'negative halfway');
check(Hesabix_V2_Decimal::round('0.00001', 2), '0', 'leading zeros');
check(Hesabix_V2_Decimal::divide('999999999.99', '7'), '142857142.855714285714285714285714', 'exact quotient');
check(Hesabix_V2_Decimal::divide('1', '0.125'), '8', 'fractional quantity');
check(Hesabix_V2_Decimal::divide('0', '7'), '0', 'zero');
check(Hesabix_V2_Decimal::round(Hesabix_V2_Decimal::multiply(Hesabix_V2_Decimal::unit_price('0.005', 7), 7), 2), '0.01', 'quotient preserves a half-cent');
foreach (array(
array(7, '999999999.99', '0', '999999999.99', 8, true, '999999999.99'),
array(7, '100.01', '0', '100.01', 2, true, '100.01'),
array(7, '100.4', '0', '100.4', 0, true, '100'),
array(7, '100.01', '0', '100.01', 0, false, '100.01'),
array(3, '30.01', '3.01', '33.02', 2, true, '33.02'),
array(7, '100', '0', '100.01', 2, true, '100.01'),
array(7, '999999999.99', '0', '1000000000.99', 8, true, '1000000000.99'),
) as $money_case) {
$currency_response = array('success' => true, 'data' => array(array('id' => 1, 'code' => 'USD',
'decimal_places' => $money_case[4], 'round_monetary_amounts' => $money_case[5], 'is_default' => true)));
$policy = Hesabix_V2_Currency_Service::invoice_money_policy(1);
check($policy, array('decimal_places' => $money_case[4], 'round_monetary_amounts' => $money_case[5]), 'API currency policy');
$payload = Hesabix_V2_Mapper::wc_order_to_invoice(new MoneyOrder(), 1, 1, 1);
$wire = json_decode(json_encode($payload), true);
check($wire['payments'][0]['amount'], $money_case[6], 'payment amount');
check($wire['extra_info']['totals']['net'], $money_case[6], 'order amount');
check($wire['lines'][0]['extra_info']['line_total'], $money_case[6], 'line amount');
if ($money_case[1] === '999999999.99' && $money_case[3] === $money_case[1]) {
check(is_string($wire['lines'][0]['extra_info']['unit_price']), true, 'insufficient JSON number uses exact price');
}
if ($money_case[1] === '100.01' && $money_case[4] === 2) {
check($wire['lines'][0]['extra_info']['unit_price'], (100.01 / 7), 'safe legacy price encoding remains stable');
}
}
try {
Hesabix_V2_Decimal::money('999999999.99000001', array('decimal_places' => 8, 'round_monetary_amounts' => true));
throw new LogicException('Unsupported GL precision was accepted');
} catch (RuntimeException $e) {
}
echo "PASS: decimal arithmetic, currency policy and eleven Mapper/payment/JSON cases\n";