Files
wordpress-theme-aksrt/inc/helpers/aksrt-coupon-order.php
T

74 lines
2.4 KiB
PHP

<?php
/**
* Shared coupon burn helpers for cash content orders.
*
* Idempotent via coupon_usage.order_number. Prefer note.coupon snapshot ids
* so burn still works after use_coupon increments used_count past limit.
*
* @package AKSRT
*/
defined('ABSPATH') || exit;
if (!function_exists('aksrt_coupon_usage_exists')) {
/**
* Whether a coupon_usage row already exists for this order.
*/
function aksrt_coupon_usage_exists(string $order_number): bool {
if ($order_number === '' || !class_exists('\AKSRT\Core\DBMigrator')) {
return false;
}
global $wpdb;
$table = \AKSRT\Core\DBMigrator::table('coupon_usage');
if ($table === '') {
return false;
}
$found = $wpdb->get_var($wpdb->prepare(
"SELECT id FROM {$table} WHERE order_number = %s LIMIT 1",
$order_number
));
return !empty($found);
}
}
if (!function_exists('aksrt_burn_order_coupon')) {
/**
* Burn coupon for a paid cash order (use_coupon + log_usage).
*
* @param array<string,mixed> $meta Order note JSON (coupon_code / coupon / coupon_discount).
* @return bool True when a burn was attempted (or already burned).
*/
function aksrt_burn_order_coupon(string $order_number, array $meta, int $buyer_id = 0): bool {
if ($order_number === '' || !class_exists('\AKSRT\Payment\Coupon')) {
return false;
}
if (aksrt_coupon_usage_exists($order_number)) {
return true;
}
$coupon = is_array($meta['coupon'] ?? null) ? $meta['coupon'] : [];
$coupon_code = sanitize_text_field((string) ($coupon['code'] ?? $meta['coupon_code'] ?? ''));
$coupon_discount = (string) ($meta['coupon_discount'] ?? $meta['discount'] ?? ($coupon['discount'] ?? '0.00'));
if ($coupon_code === '') {
return false;
}
try {
$coupon_discount = \AKSRT\Ledger\AssetAmount::balance($coupon_discount)->decimal();
} catch (\InvalidArgumentException $e) {
return false;
}
$coupon_api = \AKSRT\Payment\Coupon::get_instance();
$coupon_id = (int) ($coupon['id'] ?? 0);
if ($coupon_id <= 0) {
return false;
}
if (!$coupon_api->log_usage($coupon_id, max(0, $buyer_id), $order_number, $coupon_discount)) {
return aksrt_coupon_usage_exists($order_number);
}
return $coupon_api->use_coupon($coupon_code);
}
}