validate([ 'q' => ['required', 'string', 'min:2'], ]); $query = User::query() ->where(function ($q) use ($validated) { $q->where('name', 'LIKE', "%{$validated['q']}%") ->orWhere('email', 'LIKE', "%{$validated['q']}%") ->orWhere('phone', 'LIKE', "%{$validated['q']}%"); }) ->with('wallet'); $customers = $query->take(20)->get()->map(function ($customer) { return [ 'id' => $customer->id, 'name' => $customer->name, 'email' => $customer->email, 'phone' => $customer->phone, 'wallet_balance' => $customer->wallet ? $customer->wallet->balance : 0, ]; }); return response()->json([ 'success' => true, 'data' => $customers, ]); } /** * دریافت وضعیت مالی کامل مشتری * GET /api/v1/staff/customers/{customer}/financial-status */ public function financialStatus(User $customer): JsonResponse { // دریافت سفارشات در انتظار پرداخت (تأیید شده) $pending_orders = Shipment::where('user_id', $customer->id) ->where('status', ShipmentStatus::Approved) ->with(['fromCountry', 'toCountry']) ->orderBy('created_at', 'desc') ->get(); // بدهی‌های چندارزی واقعی (از customer_credits) — به ارز خارجی، نه معادل ریالی $foreign_credits = app(CustomerCreditService::class)->getCustomerDebtsByCurrency($customer); // دریافت تراکنش‌های اخیر $recent_transactions = WalletTransaction::whereHas('wallet', function ($q) use ($customer) { $q->where('user_id', $customer->id); }) ->orderBy('created_at', 'desc') ->take(10) ->get() ->map(fn ($tx) => [ 'id' => $tx->id, 'type' => $tx->type, 'amount' => $tx->amount, 'description' => $tx->description, 'created_at' => $tx->created_at->format('Y-m-d H:i'), ]); // دریافت سفارشات اخیر $recent_orders = Shipment::where('user_id', $customer->id) ->with(['fromCountry', 'toCountry']) ->orderBy('created_at', 'desc') ->take(10) ->get() ->map(fn ($order) => [ 'id' => $order->id, 'awb_no' => $order->awb_no, 'status' => [ 'value' => $order->status?->value, 'label' => $order->status?->label(), ], 'direction' => $order->direction?->value, 'total_fee' => $order->total_fee, 'from_country' => $order->fromCountry?->name, 'to_country' => $order->toCountry?->name, 'created_at' => $order->created_at->format('Y-m-d H:i'), ]); // تعهدات ریالی (سفارشات تأییدشده‌ی پرداخت‌نشده) $total_pending_irr = $pending_orders->sum('total_fee'); // موجودی کیف پول $wallet_balance = $customer->wallet ? $customer->wallet->balance : 0; // مانده حساب = کیف پول منهای تعهدات ریالی // بدهی‌های چندارزی (foreign_credits) جداگانه تسویه می‌شوند و از کیف پول کسر نمی‌شوند. $account_balance = $wallet_balance - $total_pending_irr; return response()->json([ 'success' => true, 'customer' => [ 'id' => $customer->id, 'name' => $customer->name, 'email' => $customer->email, 'phone' => $customer->phone, ], 'financial' => [ 'wallet_balance' => $wallet_balance, 'account_balance' => $account_balance, 'total_pending_irr' => $total_pending_irr, 'pending_orders_count' => $pending_orders->count(), 'foreign_credits' => $foreign_credits, ], 'recent_transactions' => $recent_transactions, 'recent_orders' => $recent_orders, ]); } }