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(); // محاسبه بدهی به هر ارز $debts_by_currency = $pending_orders->groupBy(function ($order) { return $order->fromCountry?->iso_code ?? 'unknown'; })->map(function ($orders, $currency) { return [ 'currency' => $currency, 'total' => $orders->sum('total_fee'), 'count' => $orders->count(), ]; }); // دریافت تراکنش‌های اخیر $recent_transactions = WalletTransaction::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_debt = $pending_orders->sum('total_fee'); // موجودی کیف پول $wallet_balance = $customer->wallet ? $customer->wallet->balance : 0; // مانده حساب $account_balance = $wallet_balance - $total_debt; return response()->json([ 'success' => true, 'customer' => [ 'id' => $customer->id, 'name' => $customer->name, 'email' => $customer->email, 'phone' => $customer->phone, ], 'financial' => [ 'wallet_balance' => $wallet_balance, 'total_debt' => $total_debt, 'account_balance' => $account_balance, 'debts_by_currency' => array_values($debts_by_currency->toArray()), 'pending_orders_count' => $pending_orders->count(), ], 'recent_transactions' => $recent_transactions, 'recent_orders' => $recent_orders, ]); } }