added some feature for accounting and enhance performance for dashboard

This commit is contained in:
2026-08-30 20:18:48 +03:30
parent e059a4709e
commit 283f17561c
6 changed files with 1251 additions and 84 deletions
+275 -27
View File
@@ -84,7 +84,8 @@ class TahesabController extends Controller
])->json();
if (! is_array($response)) return [];
return $response;
return $this->tahesabCustomerRows($response);
} catch (\Exception $e) {
return [];
}
@@ -113,44 +114,83 @@ class TahesabController extends Controller
$tahesabOnlyCount = null;
$tahesabOnlyResult = ['data' => [], 'total' => 0, 'current_page' => 1, 'last_page' => 1];
$tahesabWithPhoneCount = null;
$tahesabWithoutPhoneCount = null;
$tahesabImportableCount = null;
$phoneMatchCount = null;
$phoneConflictCount = null;
$phoneMatches = [];
$phoneConflicts = [];
if ($request->boolean('include_tahesab')) {
$tahesabCustomers = $this->fetchAllTahesabCustomers();
$tahesabTotal = count($tahesabCustomers);
// موبایل‌های پنل بدون صفر ابتدایی
$panelMobiles = Customer::whereNull('deleted_at')
->whereNotNull('mobile')
->pluck('mobile')
->mapWithKeys(fn ($m) => [ltrim((string) $m, '0') => true])
->toArray();
// کدهای مشتریِ قبلاً ثبت‌شده در پنل (برای جلوگیری از تکرار)
$panelCodes = Customer::whereNull('deleted_at')
->whereNotNull('moshtari_code')
->pluck('moshtari_code')
->mapWithKeys(fn ($c) => [(string) $c => true])
->toArray();
$walletService = app(TahesabInboundWalletService::class);
$maps = $this->panelAccountingMaps();
$tahesabOnlyList = [];
$debugSample = [];
$withPhone = 0;
$withoutPhone = 0;
foreach ($tahesabCustomers as $item) {
if (! is_array($item)) continue;
if (count($debugSample) < 3) $debugSample[] = $item; // نمونهٔ خام برای تشخیص نام فیلدها
$code = $item['Code'] ?? null;
if ($code !== null && isset($panelCodes[(string) $code])) continue;
if (count($debugSample) < 3) $debugSample[] = $item;
$code = $this->extractTahesabCode($item);
$codeKey = $this->accountingCodeKey($code);
$phone = $this->extractTahesabPhone($item);
$tel = ltrim($phone, '0');
if ($tel && isset($panelMobiles[$tel])) continue;
$hasPhone = Customer::normalizeMobile($phone) !== null;
if ($hasPhone) {
$withPhone++;
} else {
$withoutPhone++;
}
if ($codeKey !== null && isset($maps['by_code'][$codeKey])) {
continue;
}
$mobileKey = Customer::normalizeMobile($phone);
if ($mobileKey && isset($maps['by_mobile'][$mobileKey])) {
$panel = $maps['by_mobile'][$mobileKey];
$panelCodeKey = $this->accountingCodeKey($panel->moshtari_code);
$row = [
'code' => $code !== null ? (int) $code : null,
'name' => trim((string) ($item['Name'] ?? $item['name'] ?? '')),
'tel' => $phone,
'panel_id' => (int) $panel->id,
'panel_name' => $panel->name,
'panel_code' => $panelCodeKey,
];
if ($panelCodeKey && $panelCodeKey !== $codeKey) {
$phoneConflicts[] = $row;
} else {
$phoneMatches[] = $row;
}
continue;
}
if ($codeKey === null) {
continue;
}
$mande = $walletService->mandeFromAccountingRow($item);
$tahesabOnlyList[] = [
'code' => $item['Code'] ?? null,
'name' => $item['Name'] ?? '',
'code' => $code !== null ? (int) $code : null,
'name' => trim((string) ($item['Name'] ?? $item['name'] ?? '')),
'tel' => $phone,
'gid' => $item['GID'] ?? null,
'group' => $item['GoroupName'] ?? '',
'gid' => $item['GID'] ?? $item['gid'] ?? null,
'group' => $item['GoroupName'] ?? $item['group'] ?? '',
'has_phone' => $hasPhone,
'gold' => $mande['gold'] ?? null,
'cash' => $mande['cash'] ?? null,
];
}
$tahesabOnlyCount = count($tahesabOnlyList);
// همه رو برمی‌گردونیم — frontend خودش paginate می‌کنه
$tahesabWithPhoneCount = $withPhone;
$tahesabWithoutPhoneCount = $withoutPhone;
$tahesabImportableCount = count(array_filter($tahesabOnlyList, fn ($r) => ! empty($r['has_phone'])));
$phoneMatchCount = count($phoneMatches);
$phoneConflictCount = count($phoneConflicts);
$tahesabOnlyResult = [
'data' => array_values($tahesabOnlyList),
'total' => $tahesabOnlyCount,
@@ -165,6 +205,13 @@ class TahesabController extends Controller
'panel_only' => $panelOnly,
'tahesab_total' => $tahesabTotal,
'tahesab_only_count' => $tahesabOnlyCount,
'tahesab_with_phone_count' => $tahesabWithPhoneCount,
'tahesab_without_phone_count' => $tahesabWithoutPhoneCount,
'tahesab_importable_count' => $tahesabImportableCount,
'phone_match_count' => $phoneMatchCount,
'phone_conflict_count' => $phoneConflictCount,
'phone_matches' => $phoneMatches,
'phone_conflicts' => $phoneConflicts,
'panel_only_list' => $panelOnlyList,
'tahesab_only_list' => $tahesabOnlyResult,
];
@@ -198,6 +245,206 @@ class TahesabController extends Controller
return '';
}
/**
* @param array<string, mixed> $response
* @return list<array<string, mixed>>
*/
private function tahesabCustomerRows(array $response): array
{
if ($response === []) {
return [];
}
if (isset($response[0]) && is_array($response[0])) {
return array_values(array_filter($response, 'is_array'));
}
foreach (['Moshtari', 'ListMoshtari', 'data', 'Data'] as $key) {
if (isset($response[$key]) && is_array($response[$key])) {
return array_values(array_filter($response[$key], 'is_array'));
}
}
return array_values(array_filter($response, 'is_array'));
}
/** @param array<string, mixed> $item */
private function extractTahesabCode(array $item): mixed
{
foreach (['Code', 'code', 'MoshtariCode', 'moshtari_code'] as $key) {
if (isset($item[$key]) && $item[$key] !== '' && $item[$key] !== null) {
return $item[$key];
}
}
return null;
}
private function accountingCodeKey(mixed $code): ?string
{
if ($code === null || $code === '' || $code === false) {
return null;
}
$s = trim((string) $code);
if ($s === '' || $s === '0' || $s === '-') {
return null;
}
if (is_numeric($s)) {
$n = (int) $s;
return $n > 0 ? (string) $n : null;
}
return $s;
}
/**
* @return array{by_code: array<string, Customer>, by_mobile: array<string, Customer>}
*/
private function panelAccountingMaps(): array
{
$byCode = [];
$byMobile = [];
$rows = Customer::whereNull('deleted_at')->get(['id', 'name', 'mobile', 'moshtari_code', 'type']);
foreach ($rows as $row) {
$codeKey = $this->accountingCodeKey($row->moshtari_code);
if ($codeKey !== null) {
$byCode[$codeKey] = $row;
}
$mobile = Customer::normalizeMobile((string) ($row->mobile ?? ''));
if ($mobile !== null) {
$byMobile[$mobile] = $row;
}
}
return ['by_code' => $byCode, 'by_mobile' => $byMobile];
}
/** لینک کد ته‌حساب روی مشتری پنل وقتی شماره یکسان است */
public function linkMatchingPhones(): \Illuminate\Http\JsonResponse
{
$tahesabCustomers = $this->fetchAllTahesabCustomers();
$maps = $this->panelAccountingMaps();
$linked = [];
$conflicts = [];
$toSync = [];
foreach ($tahesabCustomers as $item) {
if (! is_array($item)) {
continue;
}
$code = $this->extractTahesabCode($item);
$codeKey = $this->accountingCodeKey($code);
if ($codeKey === null) {
continue;
}
$phone = $this->extractTahesabPhone($item);
$mobileKey = Customer::normalizeMobile($phone);
if ($mobileKey === null || ! isset($maps['by_mobile'][$mobileKey])) {
continue;
}
$panel = $maps['by_mobile'][$mobileKey];
$panelCodeKey = $this->accountingCodeKey($panel->moshtari_code);
if (isset($maps['by_code'][$codeKey]) && (int) $maps['by_code'][$codeKey]->id !== (int) $panel->id) {
$conflicts[] = [
'code' => (int) $codeKey,
'name' => trim((string) ($item['Name'] ?? '')),
'tel' => $phone,
'panel_id' => (int) $panel->id,
'panel_name' => $panel->name,
'error' => 'این کد ته‌حساب روی مشتری دیگری در پنل است',
];
continue;
}
if ($panelCodeKey === $codeKey) {
continue;
}
if ($panelCodeKey) {
$conflicts[] = [
'code' => (int) $codeKey,
'name' => trim((string) ($item['Name'] ?? '')),
'tel' => $phone,
'panel_id' => (int) $panel->id,
'panel_name' => $panel->name,
'panel_code' => $panelCodeKey,
'error' => 'مشتری پنل کد دیگری دارد — دستی تصمیم بگیرید',
];
continue;
}
$panel->moshtari_code = (int) $codeKey;
$panel->save();
$maps['by_code'][$codeKey] = $panel;
$toSync[] = $panel;
$linked[] = [
'code' => (int) $codeKey,
'name' => $panel->name,
'tel' => $phone,
'panel_id' => (int) $panel->id,
];
}
if ($toSync !== []) {
try {
app(TahesabInboundWalletService::class)->syncAfterImport($toSync);
} catch (\Throwable $e) {
\Log::warning('Tahesab link-by-phone wallet sync failed', ['error' => $e->getMessage()]);
}
}
return response()->json([
'ok' => true,
'linked' => count($linked),
'conflicts' => count($conflicts),
'linked_rows' => $linked,
'conflict_rows' => $conflicts,
'message' => count($linked)
? (count($linked).' کد روی مشتری پنل با شماره یکسان نشست')
: (count($conflicts) ? 'کد یکسانی برای لینک خودکار نبود' : 'شماره یکسانی برای لینک پیدا نشد'),
]);
}
public function previewCustomerWallet(Request $request, $customerId): \Illuminate\Http\JsonResponse
{
if (! app(ConfigService::class)->isTahesabAccounting()) {
return response()->json(['ok' => false, 'message' => 'حسابداری ته‌حساب فعال نیست'], 422);
}
$customer = Customer::findOrFail($customerId);
$code = (int) $request->input('code', $customer->moshtari_code);
$result = app(TahesabInboundWalletService::class)->previewForCustomer($customer, $code);
$needsDecision = (bool) ($result['needs_decision'] ?? false);
return response()->json([
'ok' => (bool) ($result['ok'] ?? false),
'needs_decision' => $needsDecision,
'message' => $result['message'] ?? '',
'result' => $result,
]);
}
public function mandeByCodes(Request $request): \Illuminate\Http\JsonResponse
{
$codes = $request->input('codes', []);
if (! is_array($codes) || $codes === []) {
return response()->json(['ok' => true, 'mandes' => []]);
}
if (count($codes) > 50) {
return response()->json(['ok' => false, 'message' => 'حداکثر ۵۰ کد در هر درخواست'], 422);
}
$mandes = app(TahesabInboundWalletService::class)->fetchMandeByCodes($codes);
$out = [];
foreach ($mandes as $code => $row) {
$out[(string) $code] = [
'gold' => $row['gold'] ?? 0,
'cash' => $row['cash'] ?? 0,
];
}
return response()->json(['ok' => true, 'mandes' => $out]);
}
public function syncPanelToTahesab(): \Illuminate\Http\JsonResponse
{
$customers = Customer::whereNull('deleted_at')
@@ -494,8 +741,8 @@ class TahesabController extends Controller
$overwrite = $request->boolean('overwrite');
$keep = $request->boolean('keep');
// اگر صراحتاً overwrite/keep نباشد → از ادمین بپرس وقتی تداخل هست
$askIfConflict = $request->boolean('ask_if_conflict', ! $overwrite && ! $keep);
$alwaysAsk = $request->boolean('always_ask');
$askIfConflict = $request->boolean('ask_if_conflict', ! $overwrite && ! $keep && ! $alwaysAsk);
$result = app(TahesabInboundWalletService::class)->syncWalletFromTahesab(
$customer,
@@ -504,6 +751,7 @@ class TahesabController extends Controller
'overwrite' => $overwrite,
'keep' => $keep,
'ask_if_conflict' => $askIfConflict,
'always_ask' => $alwaysAsk,
]
);