fix(funds): 加固转账冲正、结算收付幂等与坏账核销
Some checks failed
lotterLaravel CI / test (push) Has been cancelled
lotterLaravel E2E / e2e-api (push) Has been cancelled

- 转入 main_site_timeout 等不可冲正场景直接拒绝,避免假结案
- payment_records / settlement_adjustments 增加 partial unique 索引
- 坏账核销行锁 + meta 幂等回放;补差单记录 result_bill_id
- 新增 FundOperationsHardeningTest 覆盖关键路径
This commit is contained in:
2026-06-26 15:19:17 +08:00
parent 3f04b4ebe3
commit 7ec8f4c5a2
8 changed files with 535 additions and 104 deletions

View File

@@ -17,37 +17,44 @@ final class AgentSettlementBadDebtService
public function writeOff(int $originalBillId, ?string $reason, int $adminUserId): int
{
$original = DB::table('settlement_bills')->where('id', $originalBillId)->first();
if ($original === null) {
throw new \InvalidArgumentException('bill_not_found');
}
return (int) DB::transaction(function () use ($originalBillId, $reason, $adminUserId): int {
/** @var object|null $original */
$original = DB::table('settlement_bills')->where('id', $originalBillId)->lockForUpdate()->first();
if ($original === null) {
throw new \InvalidArgumentException('bill_not_found');
}
if ($this->periodCompletion->isPeriodReadOnly((int) $original->settlement_period_id)) {
throw ValidationException::withMessages([
'period' => ['completed'],
]);
}
$meta = $this->decodeMeta($original->meta_json);
$existingArchiveId = (int) ($meta['bad_debt_bill_id'] ?? 0);
if ($existingArchiveId > 0) {
return $existingArchiveId;
}
if (! in_array((string) $original->status, ['confirmed', 'partial_paid', 'overdue'], true)) {
throw ValidationException::withMessages([
'bill' => ['not_eligible'],
]);
}
if ($this->periodCompletion->isPeriodReadOnly((int) $original->settlement_period_id)) {
throw ValidationException::withMessages([
'period' => ['completed'],
]);
}
$unpaid = (int) $original->unpaid_amount;
if ($unpaid <= 0) {
throw ValidationException::withMessages([
'bill' => ['no_unpaid'],
]);
}
if (! in_array((string) $original->status, ['confirmed', 'partial_paid', 'overdue'], true)) {
throw ValidationException::withMessages([
'bill' => ['not_eligible'],
]);
}
if (in_array((string) $original->bill_type, ['adjustment', 'reversal', 'bad_debt'], true)) {
throw ValidationException::withMessages([
'bill' => ['not_eligible'],
]);
}
$unpaid = (int) $original->unpaid_amount;
if ($unpaid <= 0) {
throw ValidationException::withMessages([
'bill' => ['no_unpaid'],
]);
}
if (in_array((string) $original->bill_type, ['adjustment', 'reversal', 'bad_debt'], true)) {
throw ValidationException::withMessages([
'bill' => ['not_eligible'],
]);
}
return (int) DB::transaction(function () use ($original, $originalBillId, $unpaid, $reason, $adminUserId): int {
$now = now();
$periodId = (int) $original->settlement_period_id;
@@ -93,7 +100,7 @@ final class AgentSettlementBadDebtService
'unpaid_amount' => 0,
'status' => 'settled',
'meta_json' => json_encode(array_merge(
$this->decodeMeta($original->meta_json),
$meta,
[
'bad_debt_bill_id' => $archiveBillId,
'written_off_amount' => $unpaid,
@@ -133,4 +140,4 @@ final class AgentSettlementBadDebtService
return is_array($decoded) ? $decoded : [];
}
}
}

View File

@@ -2,6 +2,8 @@
namespace App\Services\AgentSettlement;
use App\Support\DatabaseUniqueViolation;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
@@ -47,15 +49,9 @@ final class AgentSettlementBillAdjustmentService
}
if ($idempotencyKey !== null && $idempotencyKey !== '') {
$existing = DB::table('settlement_adjustments')
->where('original_bill_id', $originalBillId)
->where('idempotency_key', $idempotencyKey)
->first();
if ($existing !== null) {
return (int) DB::table('settlement_bills')
->where('reversed_bill_id', $originalBillId)
->where('bill_type', 'adjustment')
->value('id');
$existingBillId = $this->findAdjustmentBillByIdempotency($originalBillId, $idempotencyKey);
if ($existingBillId !== null) {
return $existingBillId;
}
}
@@ -63,59 +59,89 @@ final class AgentSettlementBillAdjustmentService
? $adjustmentType
: 'adjustment';
return (int) DB::transaction(function () use ($original, $amount, $type, $reason, $adminUserId, $idempotencyKey): int {
if ($idempotencyKey !== null && $idempotencyKey !== '') {
$existing = DB::table('settlement_adjustments')
->where('original_bill_id', (int) $original->id)
->where('idempotency_key', $idempotencyKey)
->lockForUpdate()
->first();
if ($existing !== null) {
return (int) DB::table('settlement_bills')
->where('reversed_bill_id', (int) $original->id)
->where('bill_type', 'adjustment')
->value('id');
try {
return (int) DB::transaction(function () use ($original, $amount, $type, $reason, $adminUserId, $idempotencyKey): int {
return $this->insertAdjustmentBill($original, $amount, $type, $reason, $adminUserId, $idempotencyKey);
});
} catch (QueryException $e) {
if (
$idempotencyKey !== null
&& $idempotencyKey !== ''
&& DatabaseUniqueViolation::matches($e)
) {
$existingBillId = $this->findAdjustmentBillByIdempotency((int) $original->id, $idempotencyKey);
if ($existingBillId !== null) {
return $existingBillId;
}
}
$now = now();
$newBillId = (int) DB::table('settlement_bills')->insertGetId([
'settlement_period_id' => (int) $original->settlement_period_id,
'bill_type' => $type,
'owner_type' => (string) $original->owner_type,
'owner_id' => (int) $original->owner_id,
'counterparty_type' => (string) $original->counterparty_type,
'counterparty_id' => (int) $original->counterparty_id,
'gross_win_loss' => 0,
'rebate_amount' => 0,
'adjustment_amount' => $amount,
'platform_rounding_adjustment' => 0,
'net_amount' => $amount,
'paid_amount' => 0,
'unpaid_amount' => abs($amount),
'status' => 'pending_confirm',
'reversed_bill_id' => (int) $original->id,
'meta_json' => json_encode([
'original_bill_id' => (int) $original->id,
'original_net_amount' => (int) $original->net_amount,
]),
'created_at' => $now,
'updated_at' => $now,
]);
DB::table('settlement_adjustments')->insert([
'settlement_period_id' => (int) $original->settlement_period_id,
'original_bill_id' => (int) $original->id,
'adjustment_type' => $type,
'amount' => $amount,
'reason' => $reason,
'idempotency_key' => $idempotencyKey,
'created_by' => $adminUserId > 0 ? $adminUserId : null,
'created_at' => $now,
'updated_at' => $now,
]);
return $newBillId;
});
throw $e;
}
}
}
private function insertAdjustmentBill(
object $original,
int $amount,
string $type,
?string $reason,
int $adminUserId,
?string $idempotencyKey,
): int {
if ($idempotencyKey !== null && $idempotencyKey !== '') {
$existingBillId = $this->findAdjustmentBillByIdempotency((int) $original->id, $idempotencyKey);
if ($existingBillId !== null) {
return $existingBillId;
}
}
$now = now();
$newBillId = (int) DB::table('settlement_bills')->insertGetId([
'settlement_period_id' => (int) $original->settlement_period_id,
'bill_type' => $type,
'owner_type' => (string) $original->owner_type,
'owner_id' => (int) $original->owner_id,
'counterparty_type' => (string) $original->counterparty_type,
'counterparty_id' => (int) $original->counterparty_id,
'gross_win_loss' => 0,
'rebate_amount' => 0,
'adjustment_amount' => $amount,
'platform_rounding_adjustment' => 0,
'net_amount' => $amount,
'paid_amount' => 0,
'unpaid_amount' => abs($amount),
'status' => 'pending_confirm',
'reversed_bill_id' => (int) $original->id,
'meta_json' => json_encode([
'original_bill_id' => (int) $original->id,
'original_net_amount' => (int) $original->net_amount,
]),
'created_at' => $now,
'updated_at' => $now,
]);
DB::table('settlement_adjustments')->insert([
'settlement_period_id' => (int) $original->settlement_period_id,
'original_bill_id' => (int) $original->id,
'result_bill_id' => $newBillId,
'adjustment_type' => $type,
'amount' => $amount,
'reason' => $reason,
'idempotency_key' => $idempotencyKey,
'created_by' => $adminUserId > 0 ? $adminUserId : null,
'created_at' => $now,
'updated_at' => $now,
]);
return $newBillId;
}
private function findAdjustmentBillByIdempotency(int $originalBillId, string $idempotencyKey): ?int
{
$resultBillId = DB::table('settlement_adjustments')
->where('original_bill_id', $originalBillId)
->where('idempotency_key', $idempotencyKey)
->value('result_bill_id');
return $resultBillId !== null ? (int) $resultBillId : null;
}
}

View File

@@ -4,6 +4,8 @@ namespace App\Services\AgentSettlement;
use App\Models\Player;
use App\Services\Player\PlayerCreditService;
use App\Support\DatabaseUniqueViolation;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
@@ -38,19 +40,46 @@ final class SettlementPaymentService
}
}
DB::transaction(function () use ($billId, $amount, $adminUserId, $meta, $idempotencyKey): void {
if ($idempotencyKey !== null && $idempotencyKey !== '') {
$existing = DB::table('payment_records')
->where('settlement_bill_id', $billId)
->where('idempotency_key', $idempotencyKey)
->lockForUpdate()
->first();
if ($existing !== null) {
return;
}
try {
DB::transaction(function () use ($billId, $amount, $adminUserId, $meta, $idempotencyKey): void {
$this->insertPaymentRecord($billId, $amount, $adminUserId, $meta, $idempotencyKey);
});
} catch (QueryException $e) {
if (
$idempotencyKey !== null
&& $idempotencyKey !== ''
&& DatabaseUniqueViolation::matches($e)
&& $this->paymentIdempotencyExists($billId, $idempotencyKey)
) {
return;
}
$bill = DB::table('settlement_bills')->where('id', $billId)->lockForUpdate()->first();
throw $e;
}
}
/**
* @param array{method?: string|null, proof?: string|null, remark?: string|null, idempotency_key?: string|null} $meta
*/
private function insertPaymentRecord(
int $billId,
int $amount,
int $adminUserId,
array $meta,
?string $idempotencyKey,
): void {
if ($idempotencyKey !== null && $idempotencyKey !== '') {
$existing = DB::table('payment_records')
->where('settlement_bill_id', $billId)
->where('idempotency_key', $idempotencyKey)
->lockForUpdate()
->first();
if ($existing !== null) {
return;
}
}
$bill = DB::table('settlement_bills')->where('id', $billId)->lockForUpdate()->first();
if ($bill === null) {
throw new \InvalidArgumentException('bill_not_found');
}
@@ -122,7 +151,14 @@ final class SettlementPaymentService
}
$this->periodCompletion->syncIfReady((int) $bill->settlement_period_id);
});
}
private function paymentIdempotencyExists(int $billId, string $idempotencyKey): bool
{
return DB::table('payment_records')
->where('settlement_bill_id', $billId)
->where('idempotency_key', $idempotencyKey)
->exists();
}
/**

View File

@@ -384,6 +384,14 @@ final class LotteryTransferService
);
}
if (! $this->isEligibleForReverse($locked)) {
throw new WalletOperationException(
'reverse_not_eligible',
ErrorCode::WalletExternalRejected->value,
422,
);
}
if ($locked->direction === self::DIR_OUT) {
$idempotentKey = 'reversal:'.$locked->transfer_no;
$alreadyCredited = WalletTxn::query()
@@ -566,6 +574,20 @@ final class LotteryTransferService
&& $this->isEligibleForCompleteCredit($order);
}
/** 后台冲正:转出 pending_reconcile 或转入 lottery_credit_failed 且主站已扣款。 */
public function isEligibleForReverse(TransferOrder $order): bool
{
if ($order->status !== self::ST_PENDING_RECONCILE) {
return false;
}
if ($order->direction === self::DIR_OUT) {
return true;
}
return $this->isEligibleForTransferInReverse($order);
}
public function isEligibleForManualProcess(TransferOrder $order): bool
{
if (! in_array($order->status, [self::ST_PROCESSING, self::ST_FAILED, self::ST_PENDING_RECONCILE], true)) {

View File

@@ -32,9 +32,7 @@ final class AdminTransferOrderCapabilities
$canWrite = self::canWriteWallet($admin);
return [
'can_reverse' => $canWrite
&& $order->status === 'pending_reconcile'
&& ($order->direction === 'out' || $transferService->isEligibleForTransferInReverse($order)),
'can_reverse' => $canWrite && $transferService->isEligibleForReverse($order),
'can_complete_credit' => $canWrite
&& $order->direction === 'in'
&& $order->status === 'pending_reconcile'

View File

@@ -0,0 +1,26 @@
<?php
namespace App\Support;
use Illuminate\Database\QueryException;
/** 识别数据库唯一约束冲突PostgreSQL / SQLite / MySQL。 */
final class DatabaseUniqueViolation
{
public static function matches(QueryException $e): bool
{
$sqlState = (string) $e->getCode();
$errorInfo = $e->errorInfo ?? null;
$driverCode = is_array($errorInfo) ? (int) ($errorInfo[1] ?? 0) : 0;
if ($sqlState === '23505' || $sqlState === '23000' || $sqlState === '19') {
return true;
}
if ($driverCode === 19 || $driverCode === 1062) {
return true;
}
return stripos($e->getMessage(), 'unique') !== false;
}
}