Files
boursecu_server/app/Http/Controllers/Admin/DashboardController.php
T
2026-02-16 09:29:37 +00:00

307 lines
16 KiB
PHP

<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Cnt;
use App\Models\Customer;
use App\Models\Order;
use App\Models\Price;
use App\Models\TransactionsAdmin;
use App\Models\Withdraw;
use Carbon\Carbon;
use Hekmatinasser\Verta\Verta;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Rooyesh\Wallet\models\Wallet;
class DashboardController extends Controller
{
public function dashboardMaster(){
$tallaPrice = Price::latest()->first();
// $talla->update_date = Verta::instance(Carbon::parse($talla->updated_at))->format('Y/n/j-H:i');
$new_customer_major = Customer::where('type',1)->whereDate('created_at','<=',now())->whereDate('created_at','>=',now()->subMonths(3))
->count();
$new_customer_single = Customer::where('type',2)->whereDate('created_at','<=',now())->whereDate('created_at','>=',now()->subMonths(3))
->count();
$all_customer_major = Customer::where('type',1)->count();
$all_customer_single = Customer::where('type',2)->count();
$archive_customer_major = Customer::where('type',1)->where('is_archive',true)->count();
$archive_customer_single = Customer::where('type',2)->where('is_archive',true)->count();
$all_gold = Order::where('direction',2)->where('type',1)->sum('amount');// جمع طلاهایی که از مشتری خریدیم
$all_gold_single = Order::where('direction',2)->where('type',2)->sum('amount');// جمع طلاهایی که از مشتری خریدیم
$await_list = Order::where('direction',1)->where('sts',1)->get();
$best_customer_major=Order::with('customer')->where('type',1)->where('sts',2)->select('customer_id',DB::raw('sum(amount) as amount'))
->groupBy('customer_id')->limit(10)->get();
$best_customer_single=Wallet::with('customer')->whereNull('fund_id')->where('owner_type',2)->orderBy('gold','desc')->limit(10)->get();
// GT
$GT_all_customers = Customer::where('type',2)->where('is_archive',false)->count();
$GT_no_login_customers = Customer::where('type',2)->where('is_archive',false)->where('last_seen_at',null)->count();
$GT_no_valid_customers = Customer::where('type',2)->where('is_archive',false)->where('is_legal',0)->count();
$GT_no_valid_customers_data = Customer::where('type',2)->where('is_archive',false)->where('is_legal',0)->get(['id','name','mobile']);
$GT_active_customers = Customer::where('type', 2)
->where('is_archive', false)
->whereIn('id', function($query) {
$query->select('owner')
->from('wallets');
})->count();
$GT_active_customers_data = Customer::where('type', 2)
->where('is_archive', false)
->whereIn('id', function($query) {
$query->select('owner')
->from('wallets');
})->get(['id','name','mobile']);
$transactions_admins = TransactionsAdmin::with(['withdraw','order',"user",'customerTo','customer'])->get();
return response()->json([
'GT_all_customers'=>$GT_all_customers,
'GT_no_login_customers'=>$GT_no_login_customers,
'GT_no_valid_customers'=>$GT_no_valid_customers,
'GT_no_valid_customers_data'=>$GT_no_valid_customers_data,
'GT_active_customers'=>$GT_active_customers,
'GT_active_customers_data'=>$GT_active_customers_data,
'GT_deActive_customers'=>$GT_all_customers-$GT_active_customers,
'GT_transactions_admins'=>$transactions_admins,
'price'=>$tallaPrice->price,
'new_customer_major'=>$new_customer_major,
'new_customer_single'=>$new_customer_single,
'all_customer_major'=>$all_customer_major,
'all_customer_single'=>$all_customer_single,
'archive_customer_major'=>$archive_customer_major,
'archive_customer_single'=>$archive_customer_single,
'all_gold'=>$all_gold,
'all_gold_single'=>$all_gold_single,
'await_order'=>$await_list,
'best_customer'=>$best_customer_major,
'best_customer_single'=>$best_customer_single,
]);
}
public function getBalance(Request $request)
{
$startDate = Carbon::parse($request->startDate)->startOfDay();
$endDate = Carbon::parse($request->endDate)->endOfDay();
$response=[];
$response["liman"]=[];
$response["kalhor"]=[];
$response["pay_at_update"] = Order::whereNull('pay_at')->update(['pay_at' => DB::raw('created_at')]);
//liman
$response["liman"]["orders"] = Order::with(['transactions.product'])->where('customer_id', '!=', 4)->where('sts', 2)->whereBetween('pay_at', [$startDate, $endDate])->get();
$response["liman"]["balance"]["gold"] = 0;
$response["liman"]["balance"]["cash"] = 0;
$response["liman"]["balance_abs"]["gold"] = 0;
$response["liman"]["balance_abs"]["cash"] = 0;
foreach ($response["liman"]["orders"] as $OrderGoldBalanceRow) {
if ($OrderGoldBalanceRow->direction == 1){
$response["liman"]["balance"]["gold"] += $OrderGoldBalanceRow->amount;
$response["liman"]["balance"]["cash"] -= $OrderGoldBalanceRow->total_price;
}
if ($OrderGoldBalanceRow->direction == 2){
$response["liman"]["balance"]["gold"] -= $OrderGoldBalanceRow->amount;
$response["liman"]["balance"]["cash"] += $OrderGoldBalanceRow->total_price;
}
$response["liman"]["balance_abs"]["gold"] += $OrderGoldBalanceRow->amount;
$response["liman"]["balance_abs"]["cash"] += $OrderGoldBalanceRow->total_price;
}
$response['goldBalanceOfLiman']= -$response["liman"]["balance"]["gold"];
$response['cashBalanceOfLiman']= -$response["liman"]["balance"]["cash"];
//kalhor
// $response["kalhor"]["orders"] = Cache::remember("kalhor_orders_" . md5($startDate . $endDate), 900, function () use ($startDate, $endDate) {
// $body = [
// 'FromDate' => Jalalian::forge($startDate)->format('Y/m/d'),
// 'ItemId' => 0,
// 'OrderIndex' => 0,
// 'ToDate' => Jalalian::forge($endDate)->format('Y/m/d'),
// ];
//
// return Http::withHeaders(config('kalhor.headers'))
// ->withCookies(config('kalhor.cookies'), 'b750.ir')
// ->post('https://b750.ir/Deal/DealsList', $body)->json();
// });
$response["kalhor"]["balance"]["gold"] = 0;
$response["kalhor"]["balance"]["cash"] = 0;
$response["kalhor"]["balance_abs"]["gold"] = 0;
$response["kalhor"]["balance_abs"]["cash"] = 0;
if (!empty($response["kalhor"]["orders"]['Data'])) {
foreach ($response["kalhor"]["orders"]['Data'] as &$data) {
$data['0_save_in_liman']= 0;
if ($data['DeclineReason'] == 0 and $data['OrderStatusStr'] !="لغو شده") { //رد نشده بود
$data['0_save_in_liman']= 1;
if ($data['DealTypeStr'] == "خرید" or $data['DealTypeStr'] == "خرید _ دستی") {
$response["kalhor"]["balance"]['gold'] += $data['Count'];
$response["kalhor"]["balance"]['cash'] -= $data['TotalPrice'];
$direction =2;
} elseif ($data['DealTypeStr'] == "فروش" or $data['DealTypeStr'] == "فروش _ دستی") {
$response["kalhor"]["balance"]['gold'] -= $data['Count'];
$response["kalhor"]["balance"]['cash'] += $data['TotalPrice'];
$direction =1;
}
$response["kalhor"]["balance_abs"]['gold'] += $data['Count'];
$response["kalhor"]["balance_abs"]['cash'] += $data['TotalPrice'];
if (Order::where('ref_id', $data['OrderCode'])->doesntExist()){
$request = new Request([
'amount' => $data['Count'],
'customer_id' => 12,
'method' => "liman",
'direction' => $direction,
'product_id' => 2,
"price"=>$data['Mazane'],
"cash"=>$data['TotalPrice'],
'ref_id' => $data['OrderCode'],
'pay_at' =>Jalalian::fromFormat('Y/m/d', explode('_', $data['ModifiedDateStr'])[0])->toCarbon()->format('Y-m-d') . ' ' . explode('_', $data['ModifiedDateStr'])[1],
'description' => "FROM KALHOR"
]);
// $AdminOrderController = new AdminOrderController();
// $response["kalhor"]["newOrders"][$data['OrderCode']] = $AdminOrderController->store($request);
}
}
}
}
$response['goldBalanceOfKalhor']= $response["kalhor"]["balance"]["gold"];
$response['cashBalanceOfKalhor']= $response["kalhor"]["balance"]["cash"];
//main
$response['cashBalance']= -$response["liman"]["balance"]["cash"]+$response["kalhor"]["balance"]["cash"];
$response['goldBalance']= -$response["liman"]["balance"]["gold"]+$response["kalhor"]["balance"]["gold"];
//mazaneh
$changeMesghal = config('change_mesghal');
/* $response['mazanehBalanceOfKalhor'] = $response["kalhor"]["balance_abs"]["gold"] != 0
? ( $response["kalhor"]["balance_abs"]["cash"] / $response["kalhor"]["balance_abs"]["gold"])
* $changeMesghal : 0;
$response['mazanehBalanceOfLiman'] = $response["kalhor"]["balance_abs"]["gold"] != 0
? ( $response["liman"]["balance_abs"]["cash"] / $response["liman"]["balance_abs"]["gold"])
* $changeMesghal : 0;
$response['mazanehBalance'] = $response["kalhor"]["balance_abs"]["gold"] != 0
? (($response["liman"]["balance_abs"]["cash"]+$response["kalhor"]["balance_abs"]["cash"]) /
($response["liman"]["balance_abs"]["gold"]+$response["kalhor"]["balance_abs"]["gold"]))
* $changeMesghal : 0;*/
$response['mazanehBalanceOfKalhor'] = $response["kalhor"]["balance_abs"]["gold"] != 0
? ($response["kalhor"]["balance_abs"]["cash"] / $response["kalhor"]["balance_abs"]["gold"]) * $changeMesghal
: 0;
$response['mazanehBalanceOfLiman'] = $response["liman"]["balance_abs"]["gold"] != 0
? ($response["liman"]["balance_abs"]["cash"] / $response["liman"]["balance_abs"]["gold"]) * $changeMesghal
: 0;
$totalGold = $response["liman"]["balance_abs"]["gold"] + $response["kalhor"]["balance_abs"]["gold"];
$response['mazanehBalance'] = $totalGold != 0
? (($response["liman"]["balance_abs"]["cash"] + $response["kalhor"]["balance_abs"]["cash"]) / $totalGold) * $changeMesghal
: 0;
$response['income_money'] = Withdraw::whereNotNull('zify_code')->where('sts',2)->whereBetween('updated_at', [$startDate, $endDate])->sum('cash');
return $response;
}
public function finance(Request $request)
{
$startDate = $request->startDate ? Carbon::parse($request->startDate)->startOfDay() : Carbon::now()->subDays(30)->startOfDay();
$endDate = $request->endDate ? Carbon::parse($request->endDate)->endOfDay() : Carbon::now()->endOfDay();
// Fetch orders and transactions within the date range
$ords = Order::whereBetween('created_at', [$startDate, $endDate])->get();
$TransactionsAdmin = TransactionsAdmin::whereBetween('created_at', [$startDate, $endDate])->get();
// Initialize response data
$response = [
"fullPriceM1" => 0,
"fullPriceM2" => 0,
"fullPriceSood" => 0,
"fullPriceKarmozd" => 0,
"orderCount" => $ords->count(),
"Gifts" => 0,
"GiftsPrise" => 0,
"sumAll" => 0
];
// Calculate total gold gifts from transactions
foreach ($TransactionsAdmin as $TransactionAdmin) {
$response['Gifts'] += $TransactionAdmin->gold;
}
$response['Gifts'] = number_format($response['Gifts'], 3);
// Calculate total price of gold gifts
$response['GiftsPrise'] = floor($response['Gifts'] * Price::latest()->first()->price);
// Calculate order-related sums
foreach ($ords as $ord) {
$response['fullPriceM1'] += abs($ord->total_price_original - $ord->payment_amount);
$response['fullPriceM2'] += $ord->service_charge_price + $ord->total_fee;
$response['fullPriceSood'] += $ord->total_fee;
$response['fullPriceKarmozd'] += $ord->service_charge_price;
}
$response['sumAll'] = $response['fullPriceM1']-$response['GiftsPrise'];
return $response;
}
public function sumSellToCustomerMajor(Request $request){
$data = $request->all();
$order = Order::where('direction',1)
->where('sts',2)
->whereDate('created_at','>=',Carbon::parse($data['start_at']))
->whereDate('created_at','<=',Carbon::parse($data['end_at']))
->where('type',1)
->sum('amount');
return response()->json($order);
}
public function sumSellToCustomerSingle(Request $request){
$data = $request->all();
$order = Order::where('direction',1)
->where('sts',2)
->whereDate('created_at','>=',Carbon::parse($data['start_at']))
->whereDate('created_at','<=',Carbon::parse($data['end_at']))
->where('type',2)
->sum('amount');
return response()->json($order);
}
public function flow(Request $request){
$data = $request->all();
if ($data['type'] == 'week'){
$query=Order::where('sts',2)
->whereDate('created_at','<=',now())
->whereDate('created_at','>=',now()->subWeek())
->select(['direction',DB::raw('Date(created_at) as date'),DB::raw('sum(amount) as total')])
->groupBy(['date','direction'])
->get();
}
elseif ($data['type'] == 'month'){
$query=Order::where('sts',2)
->whereDate('created_at','<=',now())
->whereDate('created_at','>=',now()->subMonth())
->select(['direction',DB::raw('Date(created_at) as date'),DB::raw('sum(amount) as total')])
->groupBy(['date','direction'])
->get();
}
if (in_array($data['type'],['week','month'])){
$send = [];
foreach ($query as $i){
if(in_array($i['date'],array_keys($send))){
$send[$i['date']][$i['direction']] = $i['total'];
}else{
$send[$i['date']]['date'] =$i['date'];
$send[$i['date']][$i['direction']] = $i['total'];
}
}
}
else{
$query=Order::where('sts',2)
->whereDate('created_at','<=',now())
->whereDate('created_at','>=',now()->subYear())
->select(['direction',DB::raw('MONTH(created_at) as month'),DB::raw('sum(amount) as total')])
->groupBy(['month','direction'])
->get();
for ($i=0;$i<count($query);$i++){
$query[$i]['month_fa'] = Verta::instance( $query[$i]['month'])->format('%B');
}
}
return response()->json(array_values($send));
}
}