Fix billing provisioning and admin defaults
Agent-Logs-Url: https://github.com/GameServerPanel/GSP/sessions/1e47877f-c80e-4514-bdff-2bd022c84f13 Co-authored-by: iaretechnician <2749183+iaretechnician@users.noreply.github.com>
This commit is contained in:
parent
3e70455179
commit
439e57b333
15 changed files with 772 additions and 185 deletions
|
|
@ -101,7 +101,87 @@ mysqli_set_charset($mysqli, 'utf8mb4');
|
|||
|
||||
$prefix = $table_prefix ?? 'gsp_';
|
||||
$repo = new BillingRepository($mysqli, $prefix);
|
||||
$svc = new BillingService($repo);
|
||||
|
||||
function cap_invoice_ids_from_custom_id(?string $customId): array {
|
||||
if (!is_string($customId) || $customId === '') {
|
||||
return [];
|
||||
}
|
||||
if (ctype_digit($customId)) {
|
||||
return [intval($customId)];
|
||||
}
|
||||
if (stripos($customId, 'cart:') !== 0) {
|
||||
return [];
|
||||
}
|
||||
$parts = explode(',', substr($customId, 5));
|
||||
$invoiceIds = [];
|
||||
foreach ($parts as $part) {
|
||||
$part = trim($part);
|
||||
if ($part !== '' && ctype_digit($part)) {
|
||||
$invoiceIds[] = intval($part);
|
||||
}
|
||||
}
|
||||
return array_values(array_unique($invoiceIds));
|
||||
}
|
||||
|
||||
function cap_duration_metadata(array $invoice): array {
|
||||
$duration = strtolower((string)($invoice['invoice_duration'] ?? $invoice['rate_type'] ?? 'month'));
|
||||
switch ($duration) {
|
||||
case 'day':
|
||||
case 'daily':
|
||||
return ['invoice_duration' => 'day', 'rate_type' => 'daily', 'days' => 1];
|
||||
case 'year':
|
||||
case 'yearly':
|
||||
return ['invoice_duration' => 'year', 'rate_type' => 'yearly', 'days' => 365];
|
||||
case 'month':
|
||||
case 'monthly':
|
||||
default:
|
||||
return ['invoice_duration' => 'month', 'rate_type' => 'monthly', 'days' => 31];
|
||||
}
|
||||
}
|
||||
|
||||
function cap_end_date(array $invoice, ?string $fromDate = null): string {
|
||||
$meta = cap_duration_metadata($invoice);
|
||||
$qty = max(1, intval($invoice['qty'] ?? 1));
|
||||
$baseTs = time();
|
||||
if (!empty($fromDate)) {
|
||||
$fromTs = strtotime($fromDate);
|
||||
if ($fromTs !== false && $fromTs > time()) {
|
||||
$baseTs = $fromTs;
|
||||
}
|
||||
}
|
||||
return date('Y-m-d H:i:s', $baseTs + ($meta['days'] * $qty * 86400));
|
||||
}
|
||||
|
||||
function cap_discount_map(array $invoices, float $paidAmount): array {
|
||||
$baseTotals = [];
|
||||
$baseAmount = 0.0;
|
||||
foreach ($invoices as $invoice) {
|
||||
$invoiceId = intval($invoice['invoice_id'] ?? 0);
|
||||
$lineBase = round((float)($invoice['subtotal'] ?? $invoice['total_due'] ?? $invoice['amount'] ?? 0), 2);
|
||||
$baseTotals[$invoiceId] = $lineBase;
|
||||
$baseAmount += $lineBase;
|
||||
}
|
||||
|
||||
$discountTotal = round(max(0, $baseAmount - $paidAmount), 2);
|
||||
if ($discountTotal <= 0 || $baseAmount <= 0) {
|
||||
return array_fill_keys(array_keys($baseTotals), 0.0);
|
||||
}
|
||||
|
||||
$discounts = [];
|
||||
$remaining = $discountTotal;
|
||||
$lastInvoiceId = array_key_last($baseTotals);
|
||||
foreach ($baseTotals as $invoiceId => $lineBase) {
|
||||
if ($invoiceId === $lastInvoiceId) {
|
||||
$lineDiscount = $remaining;
|
||||
} else {
|
||||
$lineDiscount = round($discountTotal * ($lineBase / $baseAmount), 2);
|
||||
$remaining = round($remaining - $lineDiscount, 2);
|
||||
}
|
||||
$discounts[$invoiceId] = min($lineBase, max(0, $lineDiscount));
|
||||
}
|
||||
|
||||
return $discounts;
|
||||
}
|
||||
|
||||
// Capture payment via PayPal gateway
|
||||
try {
|
||||
|
|
@ -160,104 +240,157 @@ if (!$capture['success']) {
|
|||
}
|
||||
|
||||
$txid = $capture['transaction_id'] ?? '';
|
||||
$paidAmount = round((float)($capture['amount'] ?? 0), 2);
|
||||
$capture['payment_method'] = 'paypal';
|
||||
$invoiceIds = cap_invoice_ids_from_custom_id($capture['custom_id'] ?? null);
|
||||
$invoices = !empty($invoiceIds)
|
||||
? $repo->getInvoicesForUserByIds($userId, $invoiceIds, true)
|
||||
: $repo->getUnpaidInvoicesForUser($userId);
|
||||
$invoicesPaid = 0;
|
||||
$ordersCreated = 0;
|
||||
$newOrderIds = [];
|
||||
$now = date('Y-m-d H:i:s');
|
||||
$couponId = intval($_SESSION['cart_coupon_id'] ?? 0);
|
||||
$discountMap = cap_discount_map($invoices, $paidAmount);
|
||||
$couponCode = trim((string)($_SESSION['cart_coupon_code'] ?? ''));
|
||||
|
||||
// Process each unpaid invoice for this user
|
||||
$invoices = $repo->getUnpaidInvoicesForUser($userId);
|
||||
$invoicesPaid = 0;
|
||||
$ordersCreated = 0;
|
||||
$newOrderIds = [];
|
||||
$now = date('Y-m-d H:i:s');
|
||||
if ($couponId <= 0 && $couponCode !== '') {
|
||||
$coupon = $repo->getCouponByCode($couponCode);
|
||||
$couponId = intval($coupon['coupon_id'] ?? 0);
|
||||
}
|
||||
|
||||
if (empty($invoices)) {
|
||||
cap_log('NO_INVOICES', ['user_id' => $userId]);
|
||||
cap_log('NO_INVOICES', ['user_id' => $userId, 'custom_id' => $capture['custom_id'] ?? null]);
|
||||
ob_clean();
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'error_code' => 'no_matching_invoices',
|
||||
'message' => 'No matching unpaid invoices were found for this payment.',
|
||||
'timestamp' => date('c'),
|
||||
'request_id' => $requestId,
|
||||
]);
|
||||
mysqli_close($mysqli);
|
||||
exit;
|
||||
}
|
||||
|
||||
foreach ($invoices as $inv) {
|
||||
$invoiceId = intval($inv['invoice_id']);
|
||||
$homeId = intval($inv['home_id'] ?? 0);
|
||||
$homeId = intval($inv['home_id'] ?? 0);
|
||||
$invoiceBase = round((float)($inv['subtotal'] ?? $inv['total_due'] ?? $inv['amount'] ?? 0), 2);
|
||||
$lineDiscount = round((float)($discountMap[$invoiceId] ?? 0), 2);
|
||||
$lineTotal = round(max(0, $invoiceBase - $lineDiscount), 2);
|
||||
$durationMeta = cap_duration_metadata($inv);
|
||||
|
||||
$result = $svc->processPaymentSuccess($capture, $invoiceId, $userId, $homeId, $inv);
|
||||
if (!$result['success']) {
|
||||
cap_log('INVOICE_PAY_FAILED', ['invoice_id' => $invoiceId, 'error' => $result['error'] ?? '']);
|
||||
$invoiceUpdate = [
|
||||
'coupon_id' => $couponId,
|
||||
'discount_amount' => $lineDiscount,
|
||||
'subtotal' => $invoiceBase,
|
||||
'amount' => $lineTotal,
|
||||
'total_due' => $lineTotal,
|
||||
'status' => 'paid',
|
||||
'billing_status' => 'Active',
|
||||
'payment_status' => 'paid',
|
||||
'payment_txid' => $txid,
|
||||
'payment_method' => 'paypal',
|
||||
'paid_date' => $now,
|
||||
'invoice_duration' => $durationMeta['invoice_duration'],
|
||||
'rate_type' => $durationMeta['rate_type'],
|
||||
];
|
||||
|
||||
if (!$repo->updateInvoiceFields($invoiceId, $invoiceUpdate)) {
|
||||
cap_log('INVOICE_PAY_FAILED', ['invoice_id' => $invoiceId, 'db_error' => $mysqli->error]);
|
||||
continue;
|
||||
}
|
||||
|
||||
$invoicesPaid++;
|
||||
cap_log('INVOICE_PAID', ['invoice_id' => $invoiceId, 'txid' => $txid]);
|
||||
cap_log('INVOICE_PAID', ['invoice_id' => $invoiceId, 'txid' => $txid, 'amount' => $lineTotal]);
|
||||
|
||||
// Record transaction in billing_transactions (idempotent — skip on duplicate external ID)
|
||||
$rawCapture = $capture['raw_response'] ?? [];
|
||||
if (is_array($rawCapture)) {
|
||||
unset($rawCapture['client_secret'], $rawCapture['access_token']); // never log secrets
|
||||
}
|
||||
$repo->logTransaction([
|
||||
'invoice_id' => $invoiceId,
|
||||
'user_id' => $userId,
|
||||
'home_id' => $homeId,
|
||||
'payment_method' => 'paypal',
|
||||
'transaction_external_id' => $txid,
|
||||
'amount' => (float)($inv['amount'] ?? $inv['total_due'] ?? 0),
|
||||
'currency' => (string)($inv['currency'] ?? 'USD'),
|
||||
'status' => 'completed',
|
||||
'raw_response' => $rawCapture,
|
||||
]);
|
||||
|
||||
// Resolve (or create) the billing_orders row for this invoice so the provisioner can run.
|
||||
// billing_orders.status='Active' is what create_servers.php queries.
|
||||
$orderId = intval($inv['order_id'] ?? 0);
|
||||
|
||||
$durMap = [
|
||||
'daily' => '+1 day', 'monthly' => '+1 month', 'yearly' => '+1 year',
|
||||
'day' => '+1 day', 'month' => '+1 month', 'year' => '+1 year',
|
||||
];
|
||||
$dur = strtolower($inv['rate_type'] ?? $inv['invoice_duration'] ?? 'month');
|
||||
$newEnd = date('Y-m-d H:i:s', strtotime($durMap[$dur] ?? '+1 month'));
|
||||
$currentHomeId = $homeId;
|
||||
|
||||
if ($orderId > 0) {
|
||||
// Existing order linked to this invoice — extend it and mark Active.
|
||||
$order = $repo->getOrder($orderId);
|
||||
if ($order) {
|
||||
$fromTs = (strtotime($order['end_date'] ?? '') > time()) ? strtotime($order['end_date']) : time();
|
||||
$newEnd = date('Y-m-d H:i:s', strtotime($durMap[$dur] ?? '+1 month', $fromTs));
|
||||
$repo->extendOrder($orderId, $newEnd, $txid, $now);
|
||||
$newEnd = cap_end_date($inv, $order['end_date'] ?? null);
|
||||
$currentHomeId = intval($order['home_id'] ?? 0);
|
||||
$repo->updateOrderFields($orderId, [
|
||||
'status' => 'Active',
|
||||
'end_date' => $newEnd,
|
||||
'payment_txid' => $txid,
|
||||
'paid_ts' => $now,
|
||||
'price' => $lineTotal,
|
||||
'discount_amount' => $lineDiscount,
|
||||
'coupon_id' => $couponId,
|
||||
]);
|
||||
if ($currentHomeId > 0) {
|
||||
$repo->updateInvoiceFields($invoiceId, ['home_id' => $currentHomeId]);
|
||||
}
|
||||
$ordersCreated++;
|
||||
// Queue for provisioning only if not yet provisioned (home_id still '0' / empty).
|
||||
$currentHomeId = (string)($order['home_id'] ?? '0');
|
||||
if ($currentHomeId === '' || $currentHomeId === '0') {
|
||||
if ($currentHomeId <= 0) {
|
||||
$newOrderIds[] = $orderId;
|
||||
cap_log('ORDER_QUEUED_PROVISION', ['order_id' => $orderId]);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// No billing_orders row yet — create one now so the provisioner can run.
|
||||
$newEnd = cap_end_date($inv, null);
|
||||
$newOrderId = $repo->createOrder([
|
||||
'user_id' => intval($inv['user_id']),
|
||||
'service_id' => intval($inv['service_id']),
|
||||
'home_name' => $inv['home_name'] ?? '',
|
||||
'ip' => (string)($inv['ip'] ?? '0'),
|
||||
'qty' => intval($inv['qty'] ?? 1),
|
||||
'invoice_duration' => $inv['invoice_duration'] ?? 'month',
|
||||
'invoice_duration' => $durationMeta['invoice_duration'],
|
||||
'max_players' => intval($inv['max_players'] ?? 0),
|
||||
'price' => (float)($inv['amount'] ?? $inv['total_due'] ?? 0),
|
||||
'price' => $lineTotal,
|
||||
'discount_amount' => $lineDiscount,
|
||||
'remote_control_password' => $inv['remote_control_password'] ?? '',
|
||||
'ftp_password' => $inv['ftp_password'] ?? '',
|
||||
'status' => 'Active',
|
||||
'end_date' => $newEnd,
|
||||
'payment_txid' => $txid,
|
||||
'paid_ts' => $now,
|
||||
'coupon_id' => intval($inv['coupon_id'] ?? 0),
|
||||
'coupon_id' => $couponId,
|
||||
]);
|
||||
if ($newOrderId > 0) {
|
||||
// Link invoice → order so retried captures are idempotent.
|
||||
$repo->updateInvoiceOrderId($invoiceId, $newOrderId);
|
||||
$repo->updateInvoiceFields($invoiceId, ['order_id' => $newOrderId]);
|
||||
$newOrderIds[] = $newOrderId;
|
||||
$ordersCreated++;
|
||||
cap_log('ORDER_CREATED', ['invoice_id' => $invoiceId, 'order_id' => $newOrderId]);
|
||||
} else {
|
||||
cap_log('ORDER_CREATE_FAILED', ['invoice_id' => $invoiceId, 'db_error' => $mysqli->error]);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
$repo->logTransaction([
|
||||
'invoice_id' => $invoiceId,
|
||||
'user_id' => $userId,
|
||||
'home_id' => $currentHomeId,
|
||||
'payment_method' => 'paypal',
|
||||
'transaction_external_id' => $txid,
|
||||
'amount' => $lineTotal,
|
||||
'currency' => (string)($inv['currency'] ?? 'USD'),
|
||||
'status' => 'completed',
|
||||
'raw_response' => $rawCapture,
|
||||
]);
|
||||
}
|
||||
|
||||
if ($couponId > 0 && $invoicesPaid > 0) {
|
||||
$mysqli->query("UPDATE `{$prefix}billing_coupons`
|
||||
SET current_uses = current_uses + 1
|
||||
WHERE coupon_id = " . intval($couponId));
|
||||
}
|
||||
|
||||
// Auto-provision new servers (orders without a home_id)
|
||||
|
|
@ -278,12 +411,15 @@ if (!empty($newOrderIds)) {
|
|||
}
|
||||
}
|
||||
|
||||
unset($_SESSION['cart_coupon_code'], $_SESSION['cart_coupon_id']);
|
||||
|
||||
mysqli_close($mysqli);
|
||||
|
||||
cap_log('COMPLETE', ['invoices_paid' => $invoicesPaid, 'txid' => $txid]);
|
||||
cap_log('COMPLETE', ['invoices_paid' => $invoicesPaid, 'txid' => $txid, 'orders' => $newOrderIds]);
|
||||
|
||||
ob_clean();
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'status' => 'COMPLETED',
|
||||
'txid' => $txid,
|
||||
'invoices_paid' => $invoicesPaid,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue