261 lines
8.3 KiB
PHP
261 lines
8.3 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\Customer;
|
|
use App\Models\PargarSyncLog;
|
|
use Illuminate\Support\Facades\Log;
|
|
use Rooyesh\Wallet\interfaces\TransactionInterface;
|
|
use Rooyesh\Wallet\interfaces\WalletInterface;
|
|
|
|
/**
|
|
* اعمال اسناد ورودی پرگار روی کیف اپ — سندبهسند، نه تعدیل bulk از mande.
|
|
*/
|
|
class PargarInboundWalletService
|
|
{
|
|
public const TX_TYPE_PARGAR = 22;
|
|
|
|
public function __construct(
|
|
private readonly PargarSyncService $sync,
|
|
private readonly WalletBroadcastService $walletBroadcast
|
|
) {
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $data
|
|
* @return array{applied: int, skipped: int, errors: list<string>, logs: list<int>}
|
|
*/
|
|
public function applyDocuments(Customer $customer, array $data): array
|
|
{
|
|
$transactions = is_array($data['transactions'] ?? null) ? $data['transactions'] : [];
|
|
$accountId = trim((string) ($data['accountId'] ?? ''));
|
|
|
|
$result = [
|
|
'applied' => 0,
|
|
'skipped' => 0,
|
|
'errors' => [],
|
|
'logs' => [],
|
|
];
|
|
|
|
if ($transactions === []) {
|
|
return $result;
|
|
}
|
|
|
|
$walletApplied = false;
|
|
|
|
foreach ($transactions as $tx) {
|
|
if (! is_array($tx)) {
|
|
continue;
|
|
}
|
|
|
|
$docId = trim((string) ($tx['docId'] ?? ''));
|
|
if ($docId === '') {
|
|
$result['skipped']++;
|
|
continue;
|
|
}
|
|
|
|
if ($this->isDocumentApplied($docId)) {
|
|
$result['skipped']++;
|
|
continue;
|
|
}
|
|
|
|
$goldDelta = $this->transactionGoldDelta($tx);
|
|
$rialDelta = $this->transactionRialDelta($tx);
|
|
|
|
if (abs($goldDelta) < 0.01 && abs($rialDelta) < 1) {
|
|
$result['skipped']++;
|
|
continue;
|
|
}
|
|
|
|
if ($this->isEchoOfRecentOutbound((int) $customer->id, $goldDelta, $rialDelta)) {
|
|
$this->recordSkippedDocument($customer, $docId, $accountId, $tx, 'echo_outbound');
|
|
$result['skipped']++;
|
|
continue;
|
|
}
|
|
|
|
try {
|
|
$this->applyTransactionDelta($customer, $tx, $goldDelta, $rialDelta);
|
|
$walletApplied = true;
|
|
|
|
$summary = $this->sync->summarizeInboundDocument([
|
|
'accountId' => $accountId,
|
|
'accountName' => $data['accountName'] ?? null,
|
|
'transactions' => [$tx],
|
|
]);
|
|
|
|
$log = PargarSyncLog::create([
|
|
'customer_id' => $customer->id,
|
|
'amount' => $summary['amount'],
|
|
'desc' => $summary['desc'] !== '' ? $summary['desc'] : 'اعمال سند پرگار',
|
|
'type' => PargarSyncService::TYPE_DOCUMENT,
|
|
'sync_status' => PargarSyncService::STATUS_SUCCESS,
|
|
'pargar_ref' => $docId,
|
|
'data' => json_encode([
|
|
'accountId' => $accountId,
|
|
'accountName' => $data['accountName'] ?? null,
|
|
'transaction' => $tx,
|
|
'wallet_applied' => true,
|
|
'gold_delta' => $goldDelta,
|
|
'rial_delta' => $rialDelta,
|
|
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT),
|
|
]);
|
|
|
|
$result['applied']++;
|
|
$result['logs'][] = (int) $log->id;
|
|
} catch (\Throwable $e) {
|
|
Log::warning('Pargar inbound document apply failed', [
|
|
'customer_id' => $customer->id,
|
|
'doc_id' => $docId,
|
|
'error' => $e->getMessage(),
|
|
]);
|
|
$result['errors'][] = "سند {$docId}: " . $e->getMessage();
|
|
}
|
|
}
|
|
|
|
if ($walletApplied) {
|
|
$this->walletBroadcast->broadcastForCustomer(
|
|
(int) $customer->id,
|
|
(int) ($customer->type ?? 2)
|
|
);
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
public function isDocumentApplied(string $docId): bool
|
|
{
|
|
if ($docId === '') {
|
|
return false;
|
|
}
|
|
|
|
return PargarSyncLog::query()
|
|
->where('type', PargarSyncService::TYPE_DOCUMENT)
|
|
->where('pargar_ref', $docId)
|
|
->where('sync_status', PargarSyncService::STATUS_SUCCESS)
|
|
->exists();
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $tx
|
|
*/
|
|
private function applyTransactionDelta(Customer $customer, array $tx, float $goldDelta, float $rialDelta): void
|
|
{
|
|
$ownerType = (int) ($customer->type ?? 2);
|
|
$walletInterface = new WalletInterface((int) $customer->id, $ownerType);
|
|
|
|
$desc = trim((string) ($tx['desc'] ?? ''));
|
|
$docType = trim((string) ($tx['docType'] ?? ''));
|
|
$title = $desc !== '' ? $desc : ($docType !== '' ? $docType : 'سند پرگار');
|
|
|
|
$input = [
|
|
'title' => $title,
|
|
'note' => trim((string) ($tx['docId'] ?? '')),
|
|
'expire_at' => now(),
|
|
'active' => true,
|
|
];
|
|
|
|
if (abs($goldDelta) >= 0.01) {
|
|
$input['gold'] = abs($goldDelta);
|
|
}
|
|
if (abs($rialDelta) >= 1) {
|
|
$input['cash'] = abs($rialDelta);
|
|
}
|
|
|
|
new TransactionInterface(
|
|
$walletInterface,
|
|
$input,
|
|
self::TX_TYPE_PARGAR,
|
|
$goldDelta > 0,
|
|
$rialDelta > 0
|
|
);
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $tx
|
|
*/
|
|
private function transactionGoldDelta(array $tx): float
|
|
{
|
|
$bes = $this->parseNumber($tx['besGold'] ?? 0);
|
|
$bed = $this->parseNumber($tx['bedGold'] ?? 0);
|
|
|
|
return $bes - $bed;
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $tx
|
|
*/
|
|
private function transactionRialDelta(array $tx): float
|
|
{
|
|
$bes = $this->parseNumber($tx['besRial'] ?? 0);
|
|
$bed = $this->parseNumber($tx['bedRial'] ?? 0);
|
|
|
|
return $bes - $bed;
|
|
}
|
|
|
|
private function isEchoOfRecentOutbound(int $customerId, float $goldDelta, float $rialDelta): bool
|
|
{
|
|
$since = now()->subDays(3);
|
|
|
|
$logs = PargarSyncLog::query()
|
|
->where('customer_id', $customerId)
|
|
->whereIn('type', [PargarSyncService::TYPE_WALLET_CASH, PargarSyncService::TYPE_WALLET_GOLD])
|
|
->where('created_at', '>=', $since)
|
|
->whereIn('sync_status', [PargarSyncService::STATUS_PENDING, PargarSyncService::STATUS_SUCCESS])
|
|
->get();
|
|
|
|
foreach ($logs as $log) {
|
|
$payload = json_decode((string) $log->data, true) ?: [];
|
|
$signed = (float) ($payload['signed_amount'] ?? 0);
|
|
$kind = (string) ($payload['kind'] ?? '');
|
|
|
|
if ($kind === 'gold' && abs($goldDelta) >= 0.01 && abs(abs($signed) - abs($goldDelta)) < 0.01) {
|
|
if (($signed > 0 && $goldDelta > 0) || ($signed < 0 && $goldDelta < 0)) {
|
|
return true;
|
|
}
|
|
}
|
|
|
|
if ($kind === 'cash' && abs($rialDelta) >= 1 && abs(abs($signed) - abs($rialDelta)) < 1) {
|
|
if (($signed > 0 && $rialDelta > 0) || ($signed < 0 && $rialDelta < 0)) {
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $tx
|
|
*/
|
|
private function recordSkippedDocument(
|
|
Customer $customer,
|
|
string $docId,
|
|
string $accountId,
|
|
array $tx,
|
|
string $reason
|
|
): void {
|
|
PargarSyncLog::create([
|
|
'customer_id' => $customer->id,
|
|
'desc' => 'سند پرگار — قبلاً از پنل ارسال شده (بدون اعمال مجدد)',
|
|
'type' => PargarSyncService::TYPE_DOCUMENT,
|
|
'sync_status' => PargarSyncService::STATUS_SUCCESS,
|
|
'pargar_ref' => $docId,
|
|
'data' => json_encode([
|
|
'accountId' => $accountId,
|
|
'transaction' => $tx,
|
|
'wallet_applied' => false,
|
|
'skip_reason' => $reason,
|
|
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT),
|
|
]);
|
|
}
|
|
|
|
private function parseNumber(mixed $value): float
|
|
{
|
|
if ($value === null || $value === '') {
|
|
return 0.0;
|
|
}
|
|
|
|
return (float) str_replace('/', '.', (string) $value);
|
|
}
|
|
}
|