2026-06-25 22:20:40 +03:30
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
namespace App\Services;
|
|
|
|
|
|
|
|
|
|
use App\Http\Controllers\Admin\TahesabController;
|
|
|
|
|
use App\Models\Customer;
|
|
|
|
|
use App\Models\Tahesab;
|
2026-06-27 22:10:29 +03:30
|
|
|
use Illuminate\Support\Facades\Cache;
|
|
|
|
|
use Illuminate\Support\Facades\Log;
|
2026-06-25 22:20:40 +03:30
|
|
|
use Illuminate\Support\Facades\Schema;
|
|
|
|
|
|
|
|
|
|
class TahesabSyncService
|
|
|
|
|
{
|
|
|
|
|
public const STATUS_PENDING = 'pending';
|
|
|
|
|
public const STATUS_SUCCESS = 'success';
|
|
|
|
|
public const STATUS_FAILED = 'failed';
|
|
|
|
|
|
|
|
|
|
public function responseOk(mixed $response): bool
|
|
|
|
|
{
|
|
|
|
|
return is_array($response) && ! empty($response['OK']);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function buildLog(mixed $response = null, ?string $extra = null): string
|
|
|
|
|
{
|
|
|
|
|
$parts = array_filter([
|
|
|
|
|
$extra,
|
|
|
|
|
is_array($response) ? json_encode($response, JSON_UNESCAPED_UNICODE) : (is_string($response) ? $response : null),
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
return implode("\n", $parts);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function markSuccess(Tahesab $tahesab, array $response, ?array $payload = null): void
|
|
|
|
|
{
|
|
|
|
|
$update = [
|
|
|
|
|
'sh_factor' => $response['Sh_factor'] ?? null,
|
|
|
|
|
'tahesab_id' => $response['OK'],
|
|
|
|
|
'factor_number' => $response['Factor_Number'] ?? null,
|
|
|
|
|
'tah_id' => $response['ID'] ?? null,
|
|
|
|
|
'res' => json_encode($response, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT),
|
|
|
|
|
'sync_status' => self::STATUS_SUCCESS,
|
|
|
|
|
'sync_log' => null,
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
if ($payload !== null) {
|
|
|
|
|
$update['data'] = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if ($this->hasSyncColumns()) {
|
|
|
|
|
Tahesab::where('id', $tahesab->id)->update($update);
|
|
|
|
|
} else {
|
|
|
|
|
unset($update['sync_status'], $update['sync_log']);
|
|
|
|
|
Tahesab::where('id', $tahesab->id)->update($update);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function markFailed(Tahesab $tahesab, mixed $response = null, ?string $extra = null): void
|
|
|
|
|
{
|
|
|
|
|
$update = [
|
|
|
|
|
'res' => is_array($response)
|
|
|
|
|
? json_encode($response, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)
|
|
|
|
|
: (is_string($response) ? $response : null),
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
if ($this->hasSyncColumns()) {
|
|
|
|
|
$update['sync_status'] = self::STATUS_FAILED;
|
|
|
|
|
$update['sync_log'] = $this->buildLog($response, $extra);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Tahesab::where('id', $tahesab->id)->update($update);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function isFailed(Tahesab $tahesab): bool
|
|
|
|
|
{
|
|
|
|
|
if ($this->hasSyncColumns()) {
|
|
|
|
|
return ($tahesab->sync_status ?? null) === self::STATUS_FAILED
|
|
|
|
|
|| (empty($tahesab->tahesab_id) && ($tahesab->sync_status ?? null) !== self::STATUS_SUCCESS);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return empty($tahesab->tahesab_id);
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-27 22:10:29 +03:30
|
|
|
public function registerOnCreate(Customer $customer): void
|
|
|
|
|
{
|
|
|
|
|
if (! empty($customer->moshtari_code) || ! $this->isSyncEnabled()) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$customerId = (int) $customer->id;
|
|
|
|
|
|
|
|
|
|
dispatch(function () use ($customerId) {
|
|
|
|
|
$service = app(TahesabSyncService::class);
|
|
|
|
|
$customer = Customer::find($customerId);
|
|
|
|
|
if ($customer === null || ! empty($customer->moshtari_code) || ! $service->isSyncEnabled()) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
$result = $service->registerCustomer($customer);
|
|
|
|
|
if (! ($result['ok'] ?? false)) {
|
|
|
|
|
Log::warning('Tahesab auto-register on customer create failed', [
|
|
|
|
|
'customer_id' => $customerId,
|
|
|
|
|
'message' => $result['message'] ?? null,
|
|
|
|
|
]);
|
|
|
|
|
}
|
|
|
|
|
} catch (\Throwable $e) {
|
|
|
|
|
Log::warning('Tahesab auto-register on customer create threw', [
|
|
|
|
|
'customer_id' => $customerId,
|
|
|
|
|
'error' => $e->getMessage(),
|
|
|
|
|
]);
|
|
|
|
|
}
|
|
|
|
|
})->afterResponse();
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-25 22:20:40 +03:30
|
|
|
public function registerCustomer(Customer $customer): array
|
|
|
|
|
{
|
2026-06-27 22:10:29 +03:30
|
|
|
$customer->refresh();
|
|
|
|
|
|
|
|
|
|
if (! empty($customer->moshtari_code)) {
|
|
|
|
|
return [
|
|
|
|
|
'ok' => true,
|
|
|
|
|
'message' => 'مشتری قبلاً در تهحساب ثبت شده است',
|
|
|
|
|
'moshtari_code' => $customer->moshtari_code,
|
|
|
|
|
];
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-25 22:20:40 +03:30
|
|
|
$controller = app(TahesabController::class);
|
|
|
|
|
$result = $controller->createCustomerInTahesab($customer->id);
|
|
|
|
|
|
2026-06-27 22:10:29 +03:30
|
|
|
if (is_string($result)) {
|
2026-06-25 22:20:40 +03:30
|
|
|
return ['ok' => false, 'message' => $result];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$customer->refresh();
|
|
|
|
|
|
|
|
|
|
if (empty($customer->moshtari_code)) {
|
|
|
|
|
return ['ok' => false, 'message' => 'ثبت مشتری در تهحساب ناموفق بود'];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return [
|
|
|
|
|
'ok' => true,
|
|
|
|
|
'message' => 'مشتری با موفقیت در تهحساب ثبت شد',
|
|
|
|
|
'moshtari_code' => $customer->moshtari_code,
|
|
|
|
|
];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function retry(Tahesab $tahesab): array
|
|
|
|
|
{
|
|
|
|
|
if (! $this->isFailed($tahesab) && ! empty($tahesab->tahesab_id)) {
|
|
|
|
|
return ['ok' => false, 'message' => 'این سند قبلاً در تهحساب ثبت شده است'];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$payload = json_decode((string) $tahesab->data, true) ?: [];
|
|
|
|
|
$handler = $payload['handler'] ?? $this->inferHandler($tahesab);
|
|
|
|
|
$controller = app(TahesabController::class);
|
|
|
|
|
|
|
|
|
|
$result = match ($handler) {
|
|
|
|
|
'wallet' => $controller->wallet(array_merge($payload, ['_retry_tahesab_id' => $tahesab->id]), $tahesab),
|
|
|
|
|
'walletGold' => $controller->walletGold(array_merge($payload, ['_retry_tahesab_id' => $tahesab->id]), $tahesab),
|
|
|
|
|
'storeTrade' => $controller->storeTrade(array_merge($payload, ['_retry_tahesab_id' => $tahesab->id]), $tahesab),
|
|
|
|
|
'goldReward' => $controller->goldReward(array_merge($payload, ['_retry_tahesab_id' => $tahesab->id]), $tahesab),
|
|
|
|
|
default => false,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
$tahesab->refresh();
|
|
|
|
|
|
|
|
|
|
if ($result !== false && ! empty($tahesab->tahesab_id)) {
|
|
|
|
|
return ['ok' => true, 'message' => 'سند با موفقیت در تهحساب ثبت شد', 'tahesab' => $tahesab];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return [
|
|
|
|
|
'ok' => false,
|
|
|
|
|
'message' => $tahesab->sync_log ?: 'ارسال مجدد به تهحساب ناموفق بود',
|
|
|
|
|
'tahesab' => $tahesab,
|
|
|
|
|
];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private function inferHandler(Tahesab $tahesab): string
|
|
|
|
|
{
|
|
|
|
|
if ($tahesab->order_id) {
|
|
|
|
|
return 'storeTrade';
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if ($tahesab->type === 'ريال') {
|
|
|
|
|
return 'wallet';
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$desc = (string) $tahesab->desc;
|
|
|
|
|
|
|
|
|
|
if (str_contains($desc, 'شارژ کیف') || str_contains($desc, 'برداشت از کیف')) {
|
|
|
|
|
return 'walletGold';
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return 'goldReward';
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-27 22:10:29 +03:30
|
|
|
public function isSyncEnabled(): bool
|
|
|
|
|
{
|
|
|
|
|
$config = app(ConfigService::class);
|
|
|
|
|
|
2026-07-05 16:43:34 +03:30
|
|
|
return $config->isTahesabAccounting()
|
|
|
|
|
&& trim($config->getString('tahesab_host', '')) !== ''
|
|
|
|
|
&& trim($config->getString('tahesab_port', '')) !== ''
|
|
|
|
|
&& trim($config->getString('tahesab_token', '')) !== ''
|
|
|
|
|
&& trim($config->getString('tahesab_db', '')) !== '';
|
2026-06-27 22:10:29 +03:30
|
|
|
}
|
|
|
|
|
|
2026-08-27 16:16:20 +03:30
|
|
|
/** ردیفهای محلی که هنوز در تهحساب ثبت نشدهاند */
|
|
|
|
|
public function unsyncedRowsQuery()
|
|
|
|
|
{
|
|
|
|
|
return Tahesab::query()->where(function ($q) {
|
|
|
|
|
$q->where(function ($inner) {
|
|
|
|
|
$inner->whereNull('tahesab_id')->orWhere('tahesab_id', '');
|
|
|
|
|
})->orWhere('sync_status', self::STATUS_FAILED);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* خلاصهٔ سندهای جاافتاده / ناموفق برای بنر ادمین.
|
|
|
|
|
*
|
2026-09-02 21:00:22 +03:30
|
|
|
* @return array{failed_rows:int,missing_withdraws:int,missing_orders:int,total:int,doc_sync:array}
|
2026-08-27 16:16:20 +03:30
|
|
|
*/
|
|
|
|
|
public function pendingSummary(?int $customerId = null): array
|
|
|
|
|
{
|
2026-09-02 21:00:22 +03:30
|
|
|
if (! Schema::hasTable('tahesab')) {
|
|
|
|
|
return $this->emptyPendingPayload();
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-27 16:16:20 +03:30
|
|
|
$failedRows = (int) $this->unsyncedRowsQuery()
|
|
|
|
|
->when($customerId, fn ($q) => $q->where('customer_id', $customerId))
|
|
|
|
|
->count();
|
|
|
|
|
$missingWithdraws = count($this->missingWithdrawIds(200, $customerId));
|
|
|
|
|
$missingOrders = count($this->missingOrderIds(200, $customerId));
|
|
|
|
|
|
|
|
|
|
return [
|
|
|
|
|
'failed_rows' => $failedRows,
|
|
|
|
|
'missing_withdraws' => $missingWithdraws,
|
|
|
|
|
'missing_orders' => $missingOrders,
|
|
|
|
|
'total' => $failedRows + $missingWithdraws + $missingOrders,
|
2026-09-02 20:48:14 +03:30
|
|
|
'doc_sync' => app(TahesabDocSyncService::class)->snapshot(),
|
2026-08-27 16:16:20 +03:30
|
|
|
];
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-02 20:48:14 +03:30
|
|
|
/**
|
|
|
|
|
* تعداد واقعی جاافتادهها بدون سقف ۲۰۰ — برای جاب ارسال همه.
|
|
|
|
|
*
|
|
|
|
|
* @return array{failed_rows:int,missing_withdraws:int,missing_orders:int,total:int}
|
|
|
|
|
*/
|
|
|
|
|
public function pendingTotals(?int $customerId = null): array
|
|
|
|
|
{
|
2026-09-02 21:00:22 +03:30
|
|
|
if (! Schema::hasTable('tahesab')) {
|
|
|
|
|
$empty = $this->emptyPendingPayload();
|
|
|
|
|
unset($empty['doc_sync']);
|
|
|
|
|
|
|
|
|
|
return $empty;
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-02 20:48:14 +03:30
|
|
|
$failedRows = (int) $this->unsyncedRowsQuery()
|
|
|
|
|
->when($customerId, fn ($q) => $q->where('customer_id', $customerId))
|
|
|
|
|
->count();
|
|
|
|
|
$missingWithdraws = $this->countMissingWithdraws($customerId);
|
|
|
|
|
$missingOrders = $this->countMissingOrders($customerId);
|
|
|
|
|
|
|
|
|
|
return [
|
|
|
|
|
'failed_rows' => $failedRows,
|
|
|
|
|
'missing_withdraws' => $missingWithdraws,
|
|
|
|
|
'missing_orders' => $missingOrders,
|
|
|
|
|
'total' => $failedRows + $missingWithdraws + $missingOrders,
|
|
|
|
|
];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @param array{row?:list<int>,withdraw?:list<int>,order?:list<int>} $skip
|
|
|
|
|
* @return array{type:string,id:int,label:string}|null
|
|
|
|
|
*/
|
|
|
|
|
public function peekNextPending(array $skip = []): ?array
|
|
|
|
|
{
|
2026-09-02 21:00:22 +03:30
|
|
|
if (! Schema::hasTable('tahesab')) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-02 20:48:14 +03:30
|
|
|
$skipRow = array_values(array_filter($skip['row'] ?? []));
|
|
|
|
|
$row = $this->unsyncedRowsQuery()
|
|
|
|
|
->when($skipRow !== [], fn ($q) => $q->whereNotIn('id', $skipRow))
|
|
|
|
|
->orderBy('id')
|
|
|
|
|
->first();
|
|
|
|
|
if ($row) {
|
|
|
|
|
return [
|
|
|
|
|
'type' => 'row',
|
|
|
|
|
'id' => (int) $row->id,
|
|
|
|
|
'label' => 'سند محلی #'.$row->id,
|
|
|
|
|
];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$wIds = $this->missingWithdrawIds(1, null, array_values(array_filter($skip['withdraw'] ?? [])));
|
|
|
|
|
if ($wIds !== []) {
|
|
|
|
|
$id = (int) $wIds[0];
|
|
|
|
|
|
|
|
|
|
return [
|
|
|
|
|
'type' => 'withdraw',
|
|
|
|
|
'id' => $id,
|
|
|
|
|
'label' => 'شارژ/برداشت #'.$id,
|
|
|
|
|
];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$oIds = $this->missingOrderIds(1, null, array_values(array_filter($skip['order'] ?? [])));
|
|
|
|
|
if ($oIds !== []) {
|
|
|
|
|
$id = (int) $oIds[0];
|
|
|
|
|
|
|
|
|
|
return [
|
|
|
|
|
'type' => 'order',
|
|
|
|
|
'id' => $id,
|
|
|
|
|
'label' => 'سفارش #'.$id,
|
|
|
|
|
];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-27 16:16:20 +03:30
|
|
|
/**
|
|
|
|
|
* لیست یکپارچهٔ خطا خورده + جاافتاده برای تب ادمین.
|
|
|
|
|
*
|
|
|
|
|
* @return list<array<string, mixed>>
|
|
|
|
|
*/
|
|
|
|
|
public function pendingDocs(?int $customerId = null, int $limit = 200): array
|
|
|
|
|
{
|
2026-09-02 21:00:22 +03:30
|
|
|
if (! Schema::hasTable('tahesab')) {
|
|
|
|
|
return [];
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-27 16:16:20 +03:30
|
|
|
$limit = max(1, min(500, $limit));
|
|
|
|
|
$rows = [];
|
|
|
|
|
|
|
|
|
|
$local = $this->unsyncedRowsQuery()
|
|
|
|
|
->with('customer')
|
|
|
|
|
->when($customerId, fn ($q) => $q->where('customer_id', $customerId))
|
|
|
|
|
->orderByDesc('id')
|
|
|
|
|
->limit($limit)
|
|
|
|
|
->get();
|
|
|
|
|
|
|
|
|
|
foreach ($local as $row) {
|
|
|
|
|
$arr = $row->toArray();
|
|
|
|
|
$arr['issue_kind'] = 'failed';
|
|
|
|
|
$arr['sync_target'] = ['type' => 'row', 'id' => (int) $row->id];
|
|
|
|
|
$rows[] = $arr;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$remaining = $limit - count($rows);
|
|
|
|
|
if ($remaining > 0) {
|
|
|
|
|
$withdrawIds = $this->missingWithdrawIds($remaining, $customerId);
|
|
|
|
|
if ($withdrawIds !== []) {
|
|
|
|
|
$withdraws = \App\Models\Withdraw::query()
|
|
|
|
|
->with('customer')
|
|
|
|
|
->whereIn('id', $withdrawIds)
|
|
|
|
|
->orderByDesc('id')
|
|
|
|
|
->get();
|
|
|
|
|
foreach ($withdraws as $w) {
|
|
|
|
|
$cash = (float) ($w->cash ?? 0);
|
|
|
|
|
$gold = (float) ($w->gold ?? 0);
|
|
|
|
|
$isGold = abs($gold) > 1e-9;
|
|
|
|
|
$rows[] = [
|
|
|
|
|
'id' => null,
|
|
|
|
|
'customer_id' => $w->customer_id,
|
|
|
|
|
'customer' => $w->customer,
|
|
|
|
|
'amount' => $isGold ? abs($gold) : abs($cash),
|
|
|
|
|
'type' => $isGold ? 'طلا' : 'ريال',
|
|
|
|
|
'desc' => 'شارژ/برداشت بدون سند محلی #'.$w->id.($w->note ? ' — '.$w->note : ''),
|
|
|
|
|
'withdraw_id' => (int) $w->id,
|
|
|
|
|
'order_id' => null,
|
|
|
|
|
'sync_status' => 'missing',
|
|
|
|
|
'sync_log' => 'سند در تهحساب ساخته نشده (جاافتاده)',
|
|
|
|
|
'tahesab_id' => null,
|
|
|
|
|
'created_at' => optional($w->created_at)?->toDateTimeString(),
|
|
|
|
|
'issue_kind' => 'missing',
|
|
|
|
|
'sync_target' => ['type' => 'withdraw', 'id' => (int) $w->id],
|
|
|
|
|
];
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$remaining = $limit - count($rows);
|
|
|
|
|
if ($remaining > 0) {
|
|
|
|
|
$orderIds = $this->missingOrderIds($remaining, $customerId);
|
|
|
|
|
if ($orderIds !== []) {
|
|
|
|
|
$orders = \App\Models\Order::query()
|
|
|
|
|
->with(['customer', 'product'])
|
|
|
|
|
->whereIn('id', $orderIds)
|
|
|
|
|
->orderByDesc('id')
|
|
|
|
|
->get();
|
|
|
|
|
foreach ($orders as $order) {
|
|
|
|
|
$direction = (int) ($order->direction ?? 0);
|
|
|
|
|
$dirLabel = $direction === 1 ? 'خرید' : ($direction === 2 ? 'فروش' : 'سفارش');
|
|
|
|
|
$productTitle = $order->product->title ?? 'محصول';
|
|
|
|
|
$rows[] = [
|
|
|
|
|
'id' => null,
|
|
|
|
|
'customer_id' => $order->customer_id,
|
|
|
|
|
'customer' => $order->customer,
|
|
|
|
|
'amount' => (float) ($order->amount ?? 0),
|
|
|
|
|
'type' => 'طلا',
|
|
|
|
|
'desc' => $dirLabel.' '.$productTitle.' بدون سند محلی #'.$order->id,
|
|
|
|
|
'withdraw_id' => null,
|
|
|
|
|
'order_id' => (int) $order->id,
|
|
|
|
|
'sync_status' => 'missing',
|
|
|
|
|
'sync_log' => 'سند در تهحساب ساخته نشده (جاافتاده)',
|
|
|
|
|
'tahesab_id' => null,
|
|
|
|
|
'created_at' => optional($order->pay_at ?? $order->created_at)?->toDateTimeString(),
|
|
|
|
|
'issue_kind' => 'missing',
|
|
|
|
|
'sync_target' => ['type' => 'order', 'id' => (int) $order->id],
|
|
|
|
|
];
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
usort($rows, function ($a, $b) {
|
|
|
|
|
return strcmp((string) ($b['created_at'] ?? ''), (string) ($a['created_at'] ?? ''));
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return $rows;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* ثبت یک مورد: ردیف محلی / شارژ جاافتاده / سفارش جاافتاده.
|
|
|
|
|
*
|
|
|
|
|
* @return array{ok:bool,message:string}
|
|
|
|
|
*/
|
|
|
|
|
public function syncOne(string $type, int $id): array
|
|
|
|
|
{
|
|
|
|
|
if (! $this->isSyncEnabled()) {
|
|
|
|
|
return ['ok' => false, 'message' => 'همگامسازی تهحساب فعال نیست یا تنظیمات ناقص است'];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$controller = app(TahesabController::class);
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
if ($type === 'row') {
|
|
|
|
|
$row = Tahesab::with('customer')->findOrFail($id);
|
|
|
|
|
|
|
|
|
|
return $this->retry($row);
|
|
|
|
|
}
|
|
|
|
|
if ($type === 'withdraw') {
|
|
|
|
|
$ok = $this->backfillWithdraw($controller, $id);
|
|
|
|
|
|
|
|
|
|
return ['ok' => $ok, 'message' => $ok ? 'سند شارژ/برداشت ثبت شد' : 'ارسال شارژ/برداشت ناموفق بود'];
|
|
|
|
|
}
|
|
|
|
|
if ($type === 'order') {
|
|
|
|
|
$ok = $this->backfillOrder($controller, $id);
|
|
|
|
|
|
|
|
|
|
return ['ok' => $ok, 'message' => $ok ? 'سند سفارش ثبت شد' : 'ارسال سفارش ناموفق بود'];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return ['ok' => false, 'message' => 'نوع نامعتبر است'];
|
|
|
|
|
} catch (\Throwable $e) {
|
|
|
|
|
report($e);
|
|
|
|
|
|
|
|
|
|
return ['ok' => false, 'message' => $e->getMessage()];
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* ارسال مجدد همهٔ ناموفقها + ساخت و ارسال سندهای جاافتاده از شارژ/سفارش.
|
|
|
|
|
*
|
|
|
|
|
* @return array{ok:bool,retried:int,backfilled_withdraws:int,backfilled_orders:int,failed:int,errors:list<string>,summary:array}
|
|
|
|
|
*/
|
|
|
|
|
public function syncAllPending(int $limit = 80, ?int $customerId = null): array
|
|
|
|
|
{
|
|
|
|
|
if (! $this->isSyncEnabled()) {
|
|
|
|
|
return [
|
|
|
|
|
'ok' => false,
|
|
|
|
|
'retried' => 0,
|
|
|
|
|
'backfilled_withdraws' => 0,
|
|
|
|
|
'backfilled_orders' => 0,
|
|
|
|
|
'failed' => 0,
|
|
|
|
|
'errors' => ['همگامسازی تهحساب فعال نیست یا تنظیمات ناقص است'],
|
|
|
|
|
'summary' => $this->pendingSummary($customerId),
|
|
|
|
|
];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$retried = 0;
|
|
|
|
|
$backfilledWithdraws = 0;
|
|
|
|
|
$backfilledOrders = 0;
|
|
|
|
|
$failed = 0;
|
|
|
|
|
$errors = [];
|
|
|
|
|
$controller = app(TahesabController::class);
|
|
|
|
|
$used = 0;
|
|
|
|
|
|
|
|
|
|
$rows = $this->unsyncedRowsQuery()
|
|
|
|
|
->when($customerId, fn ($q) => $q->where('customer_id', $customerId))
|
|
|
|
|
->orderBy('id')
|
|
|
|
|
->limit($limit)
|
|
|
|
|
->get();
|
|
|
|
|
foreach ($rows as $row) {
|
|
|
|
|
$used++;
|
|
|
|
|
try {
|
|
|
|
|
$result = $this->retry($row);
|
|
|
|
|
if ($result['ok'] ?? false) {
|
|
|
|
|
$retried++;
|
|
|
|
|
} else {
|
|
|
|
|
$failed++;
|
|
|
|
|
$errors[] = 'سند #'.$row->id.': '.($result['message'] ?? 'ناموفق');
|
|
|
|
|
}
|
|
|
|
|
} catch (\Throwable $e) {
|
|
|
|
|
$failed++;
|
|
|
|
|
$errors[] = 'سند #'.$row->id.': '.$e->getMessage();
|
|
|
|
|
report($e);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
foreach ($this->missingWithdrawIds(max(0, $limit - $used), $customerId) as $withdrawId) {
|
|
|
|
|
$used++;
|
|
|
|
|
try {
|
|
|
|
|
$ok = $this->backfillWithdraw($controller, (int) $withdrawId);
|
|
|
|
|
if ($ok) {
|
|
|
|
|
$backfilledWithdraws++;
|
|
|
|
|
} else {
|
|
|
|
|
$failed++;
|
|
|
|
|
$errors[] = 'شارژ/برداشت #'.$withdrawId.': ارسال به تهحساب ناموفق';
|
|
|
|
|
}
|
|
|
|
|
} catch (\Throwable $e) {
|
|
|
|
|
$failed++;
|
|
|
|
|
$errors[] = 'شارژ/برداشت #'.$withdrawId.': '.$e->getMessage();
|
|
|
|
|
report($e);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
foreach ($this->missingOrderIds(max(0, $limit - $used), $customerId) as $orderId) {
|
|
|
|
|
$used++;
|
|
|
|
|
try {
|
|
|
|
|
$ok = $this->backfillOrder($controller, (int) $orderId);
|
|
|
|
|
if ($ok) {
|
|
|
|
|
$backfilledOrders++;
|
|
|
|
|
} else {
|
|
|
|
|
$failed++;
|
|
|
|
|
$errors[] = 'سفارش #'.$orderId.': ارسال به تهحساب ناموفق';
|
|
|
|
|
}
|
|
|
|
|
} catch (\Throwable $e) {
|
|
|
|
|
$failed++;
|
|
|
|
|
$errors[] = 'سفارش #'.$orderId.': '.$e->getMessage();
|
|
|
|
|
report($e);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return [
|
|
|
|
|
'ok' => $failed === 0,
|
|
|
|
|
'retried' => $retried,
|
|
|
|
|
'backfilled_withdraws' => $backfilledWithdraws,
|
|
|
|
|
'backfilled_orders' => $backfilledOrders,
|
|
|
|
|
'failed' => $failed,
|
|
|
|
|
'errors' => array_slice($errors, 0, 20),
|
|
|
|
|
'summary' => $this->pendingSummary($customerId),
|
|
|
|
|
];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** @return list<int> */
|
2026-09-02 20:48:14 +03:30
|
|
|
private function missingWithdrawIds(int $limit, ?int $customerId = null, array $exclude = []): array
|
2026-08-27 16:16:20 +03:30
|
|
|
{
|
2026-09-02 20:48:14 +03:30
|
|
|
$query = $this->missingWithdrawQuery($customerId, $exclude);
|
|
|
|
|
if ($query === null || $limit <= 0) {
|
2026-08-27 16:16:20 +03:30
|
|
|
return [];
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-02 20:48:14 +03:30
|
|
|
return $query
|
|
|
|
|
->orderBy('id')
|
|
|
|
|
->limit($limit)
|
|
|
|
|
->pluck('id')
|
|
|
|
|
->map(fn ($id) => (int) $id)
|
2026-08-27 16:16:20 +03:30
|
|
|
->all();
|
2026-09-02 20:48:14 +03:30
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function countMissingWithdraws(?int $customerId = null): int
|
|
|
|
|
{
|
|
|
|
|
$query = $this->missingWithdrawQuery($customerId);
|
|
|
|
|
|
|
|
|
|
return $query ? (int) $query->count() : 0;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private function missingWithdrawQuery(?int $customerId = null, array $exclude = [])
|
|
|
|
|
{
|
2026-09-02 21:00:22 +03:30
|
|
|
if (! Schema::hasTable('withdraws') || ! Schema::hasTable('tahesab')) {
|
2026-09-02 20:48:14 +03:30
|
|
|
return null;
|
|
|
|
|
}
|
2026-08-27 16:16:20 +03:30
|
|
|
|
|
|
|
|
return \App\Models\Withdraw::query()
|
|
|
|
|
->where('sts', 4)
|
|
|
|
|
->where(function ($q) {
|
|
|
|
|
$q->where('cash', '!=', 0)->orWhere('gold', '!=', 0);
|
|
|
|
|
})
|
|
|
|
|
->where(function ($q) {
|
|
|
|
|
$q->whereNull('note')
|
|
|
|
|
->orWhere('note', 'not like', 'fix:intval-gold-loss%');
|
|
|
|
|
})
|
|
|
|
|
->when($customerId, fn ($q) => $q->where('customer_id', $customerId))
|
2026-09-02 20:48:14 +03:30
|
|
|
->when($exclude !== [], fn ($q) => $q->whereNotIn('id', $exclude))
|
|
|
|
|
->whereNotExists(function ($sub) {
|
|
|
|
|
$sub->from('tahesab')->selectRaw('1')->whereColumn('tahesab.withdraw_id', 'withdraws.id');
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** @return list<int> */
|
|
|
|
|
private function missingOrderIds(int $limit, ?int $customerId = null, array $exclude = []): array
|
|
|
|
|
{
|
|
|
|
|
$query = $this->missingOrderQuery($customerId, $exclude);
|
|
|
|
|
if ($query === null || $limit <= 0) {
|
|
|
|
|
return [];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return $query
|
2026-08-27 16:16:20 +03:30
|
|
|
->orderBy('id')
|
|
|
|
|
->limit($limit)
|
|
|
|
|
->pluck('id')
|
|
|
|
|
->map(fn ($id) => (int) $id)
|
|
|
|
|
->all();
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-02 20:48:14 +03:30
|
|
|
public function countMissingOrders(?int $customerId = null): int
|
2026-08-27 16:16:20 +03:30
|
|
|
{
|
2026-09-02 20:48:14 +03:30
|
|
|
$query = $this->missingOrderQuery($customerId);
|
2026-08-27 16:16:20 +03:30
|
|
|
|
2026-09-02 20:48:14 +03:30
|
|
|
return $query ? (int) $query->count() : 0;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private function missingOrderQuery(?int $customerId = null, array $exclude = [])
|
|
|
|
|
{
|
2026-09-02 21:00:22 +03:30
|
|
|
if (! Schema::hasTable('orders') || ! Schema::hasTable('tahesab')) {
|
2026-09-02 20:48:14 +03:30
|
|
|
return null;
|
|
|
|
|
}
|
2026-08-27 16:16:20 +03:30
|
|
|
|
|
|
|
|
return \App\Models\Order::query()
|
|
|
|
|
->where('sts', 2)
|
|
|
|
|
->where('payment_sts', 4)
|
|
|
|
|
->whereIn('direction', [1, 2])
|
|
|
|
|
->when($customerId, fn ($q) => $q->where('customer_id', $customerId))
|
2026-09-02 20:48:14 +03:30
|
|
|
->when($exclude !== [], fn ($q) => $q->whereNotIn('id', $exclude))
|
|
|
|
|
->whereNotExists(function ($sub) {
|
|
|
|
|
$sub->from('tahesab')->selectRaw('1')->whereColumn('tahesab.order_id', 'orders.id');
|
|
|
|
|
});
|
2026-08-27 16:16:20 +03:30
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private function backfillWithdraw(TahesabController $controller, int $withdrawId): bool
|
|
|
|
|
{
|
|
|
|
|
$withdraw = \App\Models\Withdraw::query()->find($withdrawId);
|
|
|
|
|
if (! $withdraw || ! $withdraw->customer_id) {
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$cash = (float) ($withdraw->cash ?? 0);
|
|
|
|
|
$gold = (float) ($withdraw->gold ?? 0);
|
|
|
|
|
|
|
|
|
|
if (abs($cash) > 1e-9) {
|
|
|
|
|
$result = $controller->wallet([
|
|
|
|
|
'customer_id' => (int) $withdraw->customer_id,
|
|
|
|
|
'value' => abs($cash),
|
|
|
|
|
'direction' => $cash >= 0 ? 0 : 1,
|
|
|
|
|
'withdraw_id' => $withdrawId,
|
|
|
|
|
'note' => $withdraw->note,
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
return $result !== false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (abs($gold) > 1e-9) {
|
|
|
|
|
$result = $controller->walletGold([
|
|
|
|
|
'customer_id' => (int) $withdraw->customer_id,
|
|
|
|
|
'value' => abs($gold),
|
|
|
|
|
'direction' => $gold >= 0 ? 1 : 0,
|
|
|
|
|
'withdraw_id' => $withdrawId,
|
|
|
|
|
'note' => $withdraw->note,
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
return $result !== false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private function backfillOrder(TahesabController $controller, int $orderId): bool
|
|
|
|
|
{
|
|
|
|
|
$order = \App\Models\Order::query()->with('product')->find($orderId);
|
|
|
|
|
if (! $order || ! $order->customer_id) {
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$product = $order->product;
|
|
|
|
|
$payload = [
|
|
|
|
|
'customer_id' => (int) $order->customer_id,
|
|
|
|
|
'amount' => (float) $order->amount,
|
|
|
|
|
'direction' => (int) $order->direction,
|
|
|
|
|
'price' => (float) $order->price,
|
|
|
|
|
'total_price' => (float) $order->total_price,
|
|
|
|
|
'pay_at' => $order->pay_at ?? $order->created_at,
|
|
|
|
|
'product_id' => $order->product_id ? (int) $order->product_id : null,
|
|
|
|
|
'product' => $product ? [
|
|
|
|
|
'id' => (int) $product->id,
|
|
|
|
|
'title' => $product->title,
|
|
|
|
|
'group_type' => $product->group_type,
|
|
|
|
|
'metal_id' => $product->metal_id,
|
|
|
|
|
'amount' => $product->amount,
|
|
|
|
|
'unit' => $product->unit,
|
|
|
|
|
'trade_by_quantity' => $product->trade_by_quantity,
|
|
|
|
|
] : ['metal_id' => 1],
|
|
|
|
|
'order' => ['id' => $orderId, 'product_id' => $order->product_id],
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
$result = $controller->storeTrade($payload);
|
|
|
|
|
|
|
|
|
|
return $result !== false;
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-02 21:00:22 +03:30
|
|
|
private function emptyPendingPayload(): array
|
|
|
|
|
{
|
|
|
|
|
return [
|
|
|
|
|
'failed_rows' => 0,
|
|
|
|
|
'missing_withdraws' => 0,
|
|
|
|
|
'missing_orders' => 0,
|
|
|
|
|
'total' => 0,
|
|
|
|
|
'doc_sync' => app(TahesabDocSyncService::class)->snapshot(),
|
|
|
|
|
];
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-25 22:20:40 +03:30
|
|
|
private function hasSyncColumns(): bool
|
|
|
|
|
{
|
|
|
|
|
return Schema::hasTable('tahesab') && Schema::hasColumn('tahesab', 'sync_status');
|
|
|
|
|
}
|
|
|
|
|
}
|