Files
boursecu_server/app/Http/Controllers/Admin/CustomerController.php
T

647 lines
25 KiB
PHP
Raw Normal View History

2026-01-24 14:03:11 +00:00
<?php
namespace App\Http\Controllers\Admin;
use App\DB\Te\TableEngine;
use App\Http\Controllers\SuperController;
use App\Models\Cnt;
2026-01-24 14:03:11 +00:00
use App\Models\Customer;
use Carbon\Carbon;
use Hekmatinasser\Verta\Verta;
2026-01-24 14:03:11 +00:00
use Illuminate\Http\Request;
use Rooyesh\Wallet\models\Wallet;
2026-05-28 12:52:30 +03:30
use App\Models\Setting;
2026-06-26 22:19:51 +03:30
use App\Services\AssetSummaryService;
2026-06-23 21:04:29 +03:30
use App\Services\BalanceReportService;
2026-06-15 14:38:58 +03:30
use App\Services\ConfigService;
2026-07-22 17:37:33 +03:30
use App\Services\CustomerPresenceService;
2026-07-01 22:27:51 +03:30
use App\Services\ReferralGiftService;
2026-06-15 14:38:58 +03:30
use App\Services\WalletBalanceService;
2026-01-24 14:03:11 +00:00
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
class CustomerController extends SuperController
{
2026-06-26 22:19:51 +03:30
/** فیلدهای محصول لازم برای محاسبهٔ صحیح وزن موجودی */
private const WALLET_PRODUCT_COLUMNS = [
'id', 'metal_id', 'unit', 'amount', 'group_type', 'trade_by_quantity', 'direct_price', 'title',
];
2026-01-24 14:03:11 +00:00
public function __construct()
{
$this->with = [];
$this->select = ['*'];
$search=['name','mobile'];
$this->query = Customer::with($this->with,'wallet')->where('is_archive',false)->where('type',1);
// $this->query = Customer::where('is_archive',false)->get();
parent::__construct(Customer::class, $this->with, $this->select, 'customer', $this->query, $search);
}
/**
* @param $id
* @return \Illuminate\Http\JsonResponse
*/
public function listUser(){
2026-07-14 12:35:03 +03:30
$balanceService = app(WalletBalanceService::class);
$catalogMetalIds = $balanceService->catalogMetalIds();
$users = Customer::with(['wallet'])->select('id', 'name', 'mobile', 'type')->get()->map(function ($user) use ($balanceService, $catalogMetalIds) {
$wallets = collect($user->wallet ?? []);
$ownerType = (int) $user->type;
$user->wallet_cash = $balanceService->mainWalletCash($wallets, $ownerType);
$metalMap = $balanceService->buildCustomerWalletMetalDisplayMap($wallets, $catalogMetalIds);
$user->wallet_gold = array_sum($metalMap);
return $user;
});
return response()->json($users);
2026-01-24 14:03:11 +00:00
}
2026-07-22 17:37:33 +03:30
/**
* مشتریان با SSE فعال در بازهٔ آنلاین بودن (last_seen_at تازه).
*/
public function onlineList()
{
$threshold = now()->subSeconds(CustomerPresenceService::ONLINE_THRESHOLD_SECONDS);
$rows = Customer::query()
2026-07-22 18:14:36 +03:30
->with('referral')
2026-07-22 17:37:33 +03:30
->where('is_archive', false)
->whereNotNull('last_seen_at')
->where('last_seen_at', '>=', $threshold)
->orderByDesc('last_seen_at')
2026-07-22 18:14:36 +03:30
->get();
2026-07-22 17:37:33 +03:30
return response()->json([
'count' => $rows->count(),
'online_within_seconds' => CustomerPresenceService::ONLINE_THRESHOLD_SECONDS,
'rows' => $rows,
]);
}
2026-08-01 15:53:10 +03:30
/**
* حضور سبک برای چت پشتیبانی: chat_room_id / chat_user_id → last_seen_at
* (همان منبع آنلاین بودن صفحه‌ی کاربران آنلاین).
*/
public function chatPresence()
{
$hasRoom = \Schema::hasColumn('customers', 'chat_room_id');
$hasUser = \Schema::hasColumn('customers', 'chat_user_id');
if (! $hasRoom && ! $hasUser) {
return response()->json([
'online_within_seconds' => CustomerPresenceService::ONLINE_THRESHOLD_SECONDS,
'rows' => [],
]);
}
$columns = ['id', 'last_seen_at'];
if ($hasRoom) {
$columns[] = 'chat_room_id';
}
if ($hasUser) {
$columns[] = 'chat_user_id';
}
$query = Customer::query()
->where('is_archive', false)
->select($columns);
$query->where(function ($q) use ($hasRoom, $hasUser) {
if ($hasRoom) {
$q->orWhere(function ($inner) {
$inner->whereNotNull('chat_room_id')->where('chat_room_id', '!=', '');
});
}
if ($hasUser) {
$q->orWhere(function ($inner) {
$inner->whereNotNull('chat_user_id')->where('chat_user_id', '!=', '');
});
}
});
return response()->json([
'online_within_seconds' => CustomerPresenceService::ONLINE_THRESHOLD_SECONDS,
'rows' => $query->get(),
]);
}
2026-01-24 14:03:11 +00:00
public function updateAdmin(Request $request , $id)
{
$data = $request->all();
if (isset($data['mobile']) && !is_null($data['mobile'])){
2026-07-06 19:21:20 +03:30
$data['mobile'] = Customer::normalizeMobile($data['mobile']);
2026-07-02 16:12:39 +03:30
Customer::assertMobileUnique($data['mobile'], (int) $id);
2026-01-24 14:03:11 +00:00
}
if (array_key_exists('pargar_account_id', $data)) {
$data['pargar_account_id'] = $this->normalizeAndAssertUniqueAccountingCode(
$data['pargar_account_id'],
'pargar_account_id',
(int) $id
);
}
if (array_key_exists('moshtari_code', $data)) {
$data['moshtari_code'] = $this->normalizeAndAssertUniqueAccountingCode(
$data['moshtari_code'],
'moshtari_code',
(int) $id
);
}
2026-01-24 14:03:11 +00:00
if (isset($data['gold'])){
$user = Customer::find($id);
if ($user) {
$user->gold = $data['gold'];
$user->save();
$user["g"]=true;
}
}
$user["u"] = Customer::findOrFail($id)->update($data);
return response()->json($user);
}
/**
* خالی / 0 / -1 → null؛ در غیر این صورت یکتا بودن کد بین مشتریان فعال.
*/
private function normalizeAndAssertUniqueAccountingCode(mixed $value, string $column, int $customerId): ?string
{
if ($value === null) {
return null;
}
$code = trim((string) $value);
if ($code === '' || in_array($code, ['0', '-1'], true)) {
return null;
}
$exists = Customer::whereNull('deleted_at')
->where($column, $code)
->where('id', '!=', $customerId)
->exists();
if ($exists) {
throw new UnprocessableEntityHttpException('این کد حسابداری قبلاً برای مشتری دیگری ثبت شده است');
}
return $code;
}
2026-01-24 14:03:11 +00:00
public function referrals(Request $request,$customer_id)
{
$customer_referral_id = Customer::where("id",$customer_id)->first()->referral_id;
$query_table = Customer::where("referral_to_id",$customer_referral_id);
TableEngine::create($query_table, $request)
->initSearch($this->search)
->select(['*',Customer::$SELECT_TYPE_STR])
->export($query_table);
return response()->json($query_table);
}
public function funds(Request $request,$customer_id)
{
2026-06-10 17:31:38 +03:30
$mainWalletProductIds = app(\App\Services\ConfigService::class)->mainWalletProductIds();
2026-07-21 22:23:09 +03:30
$balanceService = app(WalletBalanceService::class);
$catalogMetalIds = $balanceService->catalogMetalIds();
$mainWalletMetalId = $balanceService->resolveMainWalletMetalId();
$productCols = implode(',', self::WALLET_PRODUCT_COLUMNS);
2026-08-01 17:30:14 +03:30
$ownerType = (int) (Customer::find($customer_id)?->type ?? 0);
2026-01-24 14:03:11 +00:00
2026-08-01 17:30:14 +03:30
// فقط کیف محصول آزاد (نه کیف اصلی، نه قلک) — هر ردیف = یک دارایی
2026-07-21 22:23:09 +03:30
$query_table = Wallet::with([
'product' => static function ($q) use ($productCols) {
$q->withTrashed()->select(explode(',', $productCols));
},
])
2026-06-10 16:57:31 +03:30
->where('owner', $customer_id)
2026-08-01 17:30:14 +03:30
->whereNull('fund_id')
2026-06-10 16:57:31 +03:30
->whereNotNull('product_id');
2026-06-10 17:31:38 +03:30
if ($mainWalletProductIds !== []) {
// کیف‌های قدیمیِ محصولات متصل به کیف اصلی نمایش داده نمی‌شوند
$query_table->whereNotIn('product_id', $mainWalletProductIds);
}
2026-01-24 14:03:11 +00:00
TableEngine::create($query_table, $request)
->initSearch($this->search)
2026-06-10 16:57:31 +03:30
->select(['id', 'owner', 'cash', 'gold', 'fund_id', 'product_id', 'created_at', 'updated_at'])
2026-01-24 14:03:11 +00:00
->export($query_table);
2026-06-10 17:31:38 +03:30
// محصولات متصل به کیف اصلی: یک ردیف نماینده با موجودی کیف اصلی
if ($mainWalletProductIds !== []) {
$representative = null;
foreach ($mainWalletProductIds as $pid) {
2026-07-21 22:23:09 +03:30
$representative = \App\Models\Product::withTrashed()
->select(self::WALLET_PRODUCT_COLUMNS)
->find($pid);
2026-06-10 17:31:38 +03:30
if ($representative) {
break;
}
}
$mainWallet = Wallet::where('owner', $customer_id)
->whereNull('fund_id')
->whereNull('product_id')
->first();
if ($representative && $mainWallet) {
2026-08-01 17:30:14 +03:30
$freeGold = $balanceService->effectiveMainWalletGold((int) $customer_id, $ownerType);
$fundGold = $balanceService->fundGoldForMainWalletProducts((int) $customer_id, $ownerType);
2026-06-10 17:31:38 +03:30
$mainRow = [
'id' => $mainWallet->id,
'owner' => (int) $customer_id,
'cash' => 0,
2026-08-01 17:30:14 +03:30
'gold' => $freeGold + $fundGold,
'free_gold' => $freeGold,
'fund_gold' => $fundGold,
2026-06-10 17:31:38 +03:30
'fund_id' => null,
'product_id' => (int) $representative->id,
'created_at' => $mainWallet->created_at,
'updated_at' => $mainWallet->updated_at,
'product' => $representative,
'is_main_wallet' => true,
];
$query_table['rows'] = collect($query_table['rows'] ?? [])->prepend($mainRow)->values();
$query_table['query']['total'] = (int) ($query_table['query']['total'] ?? 0) + 1;
}
}
2026-07-21 22:23:09 +03:30
if (isset($query_table['rows'])) {
foreach ($query_table['rows'] as &$row) {
$balanceService->enrichWalletTableRow($row, $catalogMetalIds, $mainWalletMetalId);
$productId = (int) (is_array($row) ? ($row['product_id'] ?? 0) : ($row->product_id ?? 0));
$hasProduct = is_array($row)
? ! empty($row['product'])
: ! empty($row->product);
if ($productId > 0 && ! $hasProduct) {
$product = \App\Models\Product::withTrashed()
->select(self::WALLET_PRODUCT_COLUMNS)
->find($productId);
if ($product) {
if (is_array($row)) {
$row['product'] = $product;
} else {
$row->setRelation('product', $product);
}
$balanceService->enrichWalletTableRow($row, $catalogMetalIds, $mainWalletMetalId);
}
}
2026-08-01 17:30:14 +03:30
// جمع دارایی = آزاد + قلک‌های همان محصول (برای ردیف اصلی قبلاً ست شده)
$isMain = is_array($row)
? ! empty($row['is_main_wallet'])
: ! empty($row->is_main_wallet);
if ($productId > 0 && ! $isMain) {
$freeGold = $balanceService->freeProductGold((int) $customer_id, $productId, $ownerType);
$fundGold = $balanceService->fundGoldForProduct((int) $customer_id, $productId, $ownerType);
if (is_array($row)) {
$row['free_gold'] = $freeGold;
$row['fund_gold'] = $fundGold;
$row['gold'] = $freeGold + $fundGold;
} else {
$row->free_gold = $freeGold;
$row->fund_gold = $fundGold;
$row->gold = $freeGold + $fundGold;
}
}
2026-07-21 22:23:09 +03:30
}
unset($row);
}
2026-01-24 14:03:11 +00:00
return response()->json($query_table);
}
2026-08-01 17:30:14 +03:30
/** جدول قلک‌های واقعی مشتری (مدل Fund) */
public function piggyFunds(Request $request, $customer_id)
{
$query_table = \App\Models\Fund::with(['wallet', 'product'])
->where('customer_id', $customer_id);
TableEngine::create($query_table, $request)
->initSearch(['title'])
->select(['*'])
->export($query_table);
if (isset($query_table['rows'])) {
foreach ($query_table['rows'] as &$row) {
$wallets = is_array($row)
? collect($row['wallet'] ?? [])
: collect($row->wallet ?? []);
$gold = (float) $wallets->sum('gold');
if (is_array($row)) {
$row['gold'] = $gold;
$row['product_title'] = $row['product']['title'] ?? ($row['product']->title ?? null);
} else {
$row->gold = $gold;
$row->product_title = $row->product?->title;
}
}
unset($row);
}
return response()->json($query_table);
}
/** قلک‌های یک دارایی (محصول) */
public function assetPiggyFunds(Request $request, $customer_id, $product_id)
{
$request->merge(['product_id' => (int) $product_id]);
$query_table = \App\Models\Fund::with(['wallet', 'product'])
->where('customer_id', $customer_id)
->where('product_id', (int) $product_id);
TableEngine::create($query_table, $request)
->initSearch(['title'])
->select(['*'])
->export($query_table);
if (isset($query_table['rows'])) {
foreach ($query_table['rows'] as &$row) {
$wallets = is_array($row)
? collect($row['wallet'] ?? [])
: collect($row->wallet ?? []);
$gold = (float) $wallets->sum('gold');
if (is_array($row)) {
$row['gold'] = $gold;
} else {
$row->gold = $gold;
}
}
unset($row);
}
return response()->json($query_table);
}
/** تراکنش‌های مربوط به یک دارایی (کیف آزاد + قلک‌های همان محصول) */
public function assetTransactions(Request $request, $customer_id, $product_id)
{
$config = app(ConfigService::class);
$productId = (int) $product_id;
$walletIds = Wallet::query()
->where('owner', $customer_id)
->where(function ($q) use ($config, $productId) {
if ($config->isMainWalletProduct($productId)) {
$q->where(function ($inner) {
$inner->whereNull('fund_id')->whereNull('product_id');
})->orWhere(function ($inner) use ($productId) {
$inner->whereNotNull('fund_id')
->where(function ($f) use ($productId) {
$f->where('product_id', $productId)->orWhereNull('product_id');
});
});
} else {
$q->where('product_id', $productId);
}
})
->pluck('id');
$records = \Rooyesh\Wallet\models\Transaction::whereIn('wallet', $walletIds);
TableEngine::create($records, $request->all())
->initSearch([])
->select([
'*',
\Rooyesh\Wallet\models\Transaction::$SELECT_CAJ,
\Rooyesh\Wallet\models\Transaction::$SELECT_TYPE_STR,
])->export($records);
return response()->json($records);
}
/** تراکنش‌های یک قلک */
public function piggyFundTransactions(Request $request, $customer_id, $fund_id)
{
$fund = \App\Models\Fund::where('customer_id', $customer_id)->findOrFail($fund_id);
$walletIds = Wallet::query()
->where('owner', $customer_id)
->where('fund_id', $fund->id)
->pluck('id');
$records = \Rooyesh\Wallet\models\Transaction::whereIn('wallet', $walletIds);
TableEngine::create($records, $request->all())
->initSearch([])
->select([
'*',
\Rooyesh\Wallet\models\Transaction::$SELECT_CAJ,
\Rooyesh\Wallet\models\Transaction::$SELECT_TYPE_STR,
])->export($records);
return response()->json($records);
}
2026-01-24 14:03:11 +00:00
public function archive($id){
$query = Customer::findOrFail($id);
$query->update([
'is_archive'=>!$query->is_archive
]);
return response()->json(true);
}
public function tableWallets(Request $request){
2026-06-26 22:19:51 +03:30
$productSelect = 'product:'.implode(',', self::WALLET_PRODUCT_COLUMNS);
$query_table = Customer::with(['wallet.'.$productSelect, 'referral'])->where('is_archive', false);
2026-01-24 14:03:11 +00:00
TableEngine::create($query_table, $request)
->initSearch($this->search)
->select(['*',Customer::$SELECT_TYPE_STR])
->export($query_table);
2026-06-15 14:38:58 +03:30
$balanceService = app(WalletBalanceService::class);
2026-06-23 21:04:29 +03:30
$balanceReport = app(BalanceReportService::class);
$catalogMetalIds = $balanceService->catalogMetalIds();
$query_table['catalogMetals'] = $balanceReport->catalogMetalsMeta();
2026-06-15 14:38:58 +03:30
if (isset($query_table['rows'])) {
2026-06-23 21:04:29 +03:30
$query_table['rows'] = collect($query_table['rows'])->map(function ($row) use ($balanceService, $catalogMetalIds) {
2026-06-15 14:38:58 +03:30
$wallets = collect($row['wallet'] ?? []);
2026-07-14 12:35:03 +03:30
$row['wallet_cash'] = $balanceService->mainWalletCash($wallets, (int) ($row['type'] ?? 0));
2026-06-23 21:04:29 +03:30
$metalMap = $balanceService->buildCustomerWalletMetalDisplayMap($wallets, $catalogMetalIds);
$row['wallet_metal_gold'] = $metalMap;
foreach ($catalogMetalIds as $metalId) {
$row['wallet_metal_gold_' . $metalId] = $metalMap[(string) $metalId] ?? 0.0;
}
$row['wallet_gold'] = array_sum($metalMap);
2026-06-15 14:38:58 +03:30
return $row;
})->values();
}
2026-01-24 14:03:11 +00:00
return response()->json($query_table);
}
2026-06-26 22:19:51 +03:30
public function assetsSummary($customerId, AssetSummaryService $assetSummaryService)
{
$customer = Customer::findOrFail($customerId);
return response()->json(
2026-07-11 17:59:50 +03:30
$assetSummaryService->buildForCustomer((int) $customer->id, (int) $customer->type, true)
2026-06-26 22:19:51 +03:30
);
}
2026-01-24 14:03:11 +00:00
public function archiveTable(Request $request)
{
$query_table = Customer::with($this->with)->where("is_archive",true)/*->where('type',1)*/;
TableEngine::create($query_table, $request)
->initSearch($this->search)
->select($this->select)
->export($query_table);
return response()->json($query_table);
}
/**
* @param $id
* @return \Illuminate\Http\JsonResponse
*/
public function active($id){
$query = Customer::findOrFail($id);
$active = !$query->active;
$query->update([
'active'=>!$query->active
]);
if ($active){
$message ='اکانت شما توسط کارشناس سیستم تایید شد '."\n".
'با رفتن به لینک زیر وارد حساب کاربری خود شوید'."\n".
2026-07-21 13:25:18 +03:30
self::publicSiteUrl(request())."\n".
2026-01-24 14:03:11 +00:00
'با تشکر'.$this->Config('name_fa');
}
else{
$message ='اکانت شما توسط کارشناس سیستم غیر فعال شد '."\n".
'با کارشناسان ما تماس بگیرید'."\n".
'با تشکر'.$this->Config('name_fa');
}
$this->Send($query->mobile,$message);
return response()->json(true);
}
public function changeTradeActive($id){
$query = Customer::findOrFail($id);
$query->update([
'trade_active'=>!$query->trade_active
]);
return response()->json(true);
}
2026-07-21 21:23:26 +03:30
public function changeConditionalOrderActive($id)
{
$query = Customer::findOrFail($id);
$query->update([
'conditional_order_active' => ! $query->conditional_order_active,
]);
return response()->json([
'conditional_order_active' => (bool) $query->fresh()->conditional_order_active,
]);
}
public function updateConditionalOrderLimit(Request $request, $id)
{
$query = Customer::findOrFail($id);
$data = $request->validate([
'conditional_order_limit' => 'nullable|integer|min:1',
]);
$query->update([
'conditional_order_limit' => $data['conditional_order_limit'] ?? null,
]);
return response()->json([
'conditional_order_limit' => $query->fresh()->conditional_order_limit,
]);
}
2026-01-24 14:03:11 +00:00
// single customer-------------------
public function singleArchiveTable(Request $request)
{
$query_table = Customer::with($this->with)->where("is_archive",true)->where('type',2);
TableEngine::create($query_table, $request)
->initSearch($this->search)
->select($this->select)
->export($query_table);
return response()->json($query_table);
}
public function singleCustomerTable(Request $request)
{
$query_table = Customer::with($this->with)->where("is_archive",false)->where('type',2);
TableEngine::create($query_table, $request)
->initSearch($this->search)
->select($this->select)
->export($query_table);
return response()->json($query_table);
}
public function MakeValidByAdmin(Request $request,$id)
{
$customer = Customer::with('referral')->where('id', $id)->first();
if ($customer->is_legal == 2 or $customer->is_legal == 3){
return response()->json(true);
}
$customer->is_legal = 2;
$customer->save();
2026-06-07 18:27:04 +03:30
if ($this->Config('has_page_earn_money') == 'true') {
$referrer = $customer->referrer();
if (
$referrer
&& Customer::where('referral_to_id', $referrer->referral_id)->where('is_legal', '!=', 0)->count() < 4
) {
2026-07-01 22:27:51 +03:30
$gift_permision = app(ReferralGiftService::class)->resolveReferrerGiftPermission($referrer);
app(ReferralGiftService::class)->tryGiveOnRegistration(
$customer,
$referrer,
$gift_permision,
false
);
2026-06-07 18:27:04 +03:30
}
2026-01-24 14:03:11 +00:00
}
$companyName = $this->Config('name_fa');
2026-07-21 13:25:18 +03:30
$companyurl = self::publicSiteUrl(request());
2026-01-24 14:03:11 +00:00
$message ='حساب کاربری شما توسط کارشناس سیستم تایید شد '."\n".
'با رفتن به لینک زیر وارد حساب کاربری خود شوید'."\n".
2026-07-21 13:25:18 +03:30
$companyurl."\n".
2026-01-24 14:03:11 +00:00
'با تشکر'.$this->Config('name_fa');
$this->Send($customer->mobile, $message);
$referrer = $customer->referral;
// if ($referrer) {
// if (Customer::where('referral_to_id', $referrer->referral_id)->get()->count()<=$referrer->add_user_limit) {
// $referrerWallet = Wallet::where('owner',$customer->referral->id)->first();
// $message = "سلام {$referrer->name} عزیز،\n\n{$gift_for_invite} گرم طلا بابت معرفی {$customer->name} به حساب شما واریز شد.\nموجودی فعلی: {$referrerWallet->gold} گرم.\n\nاطلاعات بیشتر: $companyurl\n\nبا احترام،\n$companyName";
// $this->Send($referrer->mobile, $message);
// }
// }
return response()->json(true);
}
public function cardChecker(Request $request){
2026-07-22 01:05:00 +03:30
if (!app(ConfigService::class)->isJibitEnabled()) {
throw new UnprocessableEntityHttpException('سرویس احراز هویت جیبیت غیرفعال است.');
}
if (strlen($request->cart_number) != 16) {
throw new UnprocessableEntityHttpException('شماره کارت اشتباه می‌باشد.');
}
if (empty($request->national_code)) {
throw new UnprocessableEntityHttpException('لطفا شماره ملی وارد کنید.');
}
if(!empty($request->birth_date)){
$birth_date = Verta::instance(Carbon::parse($request->birth_date))->format('Ymd');
}
$card_number = preg_replace('/\D/', '', $request->cart_number);
$response = $this->jibit("cartMatching", $card_number, $request->national_code, $birth_date ?? null);
if(isset($response['refresh'])){
unset($response['refresh']);
}
if(!empty($response)){
if(!empty($response['message'])){
throw new UnprocessableEntityHttpException($response['message']);
}else{
return response()->json($response);
}
}else{
throw new UnprocessableEntityHttpException('ارتباط با سامانه قطع میباشد.');
}
}
2026-01-24 14:03:11 +00:00
}