Merge origin/Abshode_Khanegi and resolve WalletController conflict.

Keep unified charge API from remote while preserving main-wallet metal detection for deposits and transaction labels via BalanceReportService.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-06-24 01:22:56 +03:30
co-authored by Cursor
24 changed files with 1762 additions and 375 deletions
@@ -16,6 +16,7 @@ use Rooyesh\Wallet\interfaces\WalletInterface;
use Rooyesh\Wallet\models\Transaction;
use Rooyesh\Wallet\models\Wallet;
use App\Models\Setting;
use App\Services\BalanceReportService;
use App\Services\ConfigService;
use App\Services\WalletBalanceService;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
@@ -133,19 +134,27 @@ class CustomerController extends SuperController
return response()->json(true);
}
public function tableWallets(Request $request){
$query_table = Customer::with(['wallet','referral'])->where("is_archive",false)/*->where('type',1)*/;
$query_table = Customer::with(['wallet.product:id,metal_id', 'referral'])->where("is_archive",false)/*->where('type',1)*/;
TableEngine::create($query_table, $request)
->initSearch($this->search)
->select(['*',Customer::$SELECT_TYPE_STR])
->export($query_table);
$balanceService = app(WalletBalanceService::class);
$mainWalletProductIds = app(ConfigService::class)->mainWalletProductIds();
$balanceReport = app(BalanceReportService::class);
$catalogMetalIds = $balanceService->catalogMetalIds();
$query_table['catalogMetals'] = $balanceReport->catalogMetalsMeta();
if (isset($query_table['rows'])) {
$query_table['rows'] = collect($query_table['rows'])->map(function ($row) use ($balanceService, $mainWalletProductIds) {
$query_table['rows'] = collect($query_table['rows'])->map(function ($row) use ($balanceService, $catalogMetalIds) {
$wallets = collect($row['wallet'] ?? []);
$row['wallet_cash'] = $balanceService->mainWalletCash($wallets);
$row['wallet_gold'] = $balanceService->totalGoldWeight($wallets, $mainWalletProductIds);
$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);
return $row;
})->values();
@@ -10,6 +10,7 @@ use App\Models\Price;
use App\Models\Product;
use App\Models\TransactionsAdmin;
use App\Models\Withdraw;
use App\Services\BalanceReportService;
use App\Services\ConfigService;
use Carbon\Carbon;
use Hekmatinasser\Verta\Verta;
@@ -149,7 +150,7 @@ class DashboardController extends Controller
return $cnt;
}
public function getBalance(Request $request)
public function getBalance(Request $request, BalanceReportService $balanceReportService)
{
$startDate = Carbon::parse($request->startDate)->startOfDay();
$endDate = Carbon::parse($request->endDate)->endOfDay();
@@ -158,6 +159,12 @@ class DashboardController extends Controller
$response["kalhor"]=[];
$excludeCustomerId = (int) app(ConfigService::class)->getInt('balance_report_exclude_customer_id', 4);
$catalogMetalIds = $balanceReportService->catalogMetalIds();
if ($catalogMetalIds === []) {
$catalogMetalIds = [1];
}
$limanMetalBuckets = $balanceReportService->initMetalBalanceBuckets($catalogMetalIds);
$kalhorMetalBuckets = $balanceReportService->initMetalBalanceBuckets($catalogMetalIds);
$response["pay_at_update"] = Order::whereNull('pay_at')->update(['pay_at' => DB::raw('created_at')]);
//liman
@@ -171,6 +178,8 @@ class DashboardController extends Controller
$response["liman"]["balance_abs"]["gold"] = 0;
$response["liman"]["balance_abs"]["cash"] = 0;
foreach ($response["liman"]["orders"] as $OrderGoldBalanceRow) {
$balanceReportService->applyOrderToBuckets($limanMetalBuckets, $OrderGoldBalanceRow);
if ($OrderGoldBalanceRow->direction == 1){
$response["liman"]["balance"]["gold"] += $OrderGoldBalanceRow->amount;
$response["liman"]["balance"]["cash"] -= $OrderGoldBalanceRow->total_price;
@@ -212,10 +221,22 @@ class DashboardController extends Controller
$response["kalhor"]["balance"]['gold'] += $data['Count'];
$response["kalhor"]["balance"]['cash'] -= $data['TotalPrice'];
$direction =2;
$balanceReportService->applyKalhorSlice(
$kalhorMetalBuckets,
(float) $data['Count'],
(float) $data['TotalPrice'],
2
);
} elseif ($data['DealTypeStr'] == "فروش" or $data['DealTypeStr'] == "فروش _ دستی") {
$response["kalhor"]["balance"]['gold'] -= $data['Count'];
$response["kalhor"]["balance"]['cash'] += $data['TotalPrice'];
$direction =1;
$balanceReportService->applyKalhorSlice(
$kalhorMetalBuckets,
(float) $data['Count'],
(float) $data['TotalPrice'],
1
);
}
$response["kalhor"]["balance_abs"]['gold'] += $data['Count'];
$response["kalhor"]["balance_abs"]['cash'] += $data['TotalPrice'];
@@ -244,6 +265,12 @@ class DashboardController extends Controller
//main
$response['cashBalance']= -$response["liman"]["balance"]["cash"]+$response["kalhor"]["balance"]["cash"];
$response['goldBalance']= -$response["liman"]["balance"]["gold"]+$response["kalhor"]["balance"]["gold"];
$metalBalances = $balanceReportService->buildMetalBalancesResponse($limanMetalBuckets, $kalhorMetalBuckets);
$response['metalBalances'] = $metalBalances['items'];
if (!empty($metalBalances['items'])) {
$response['goldBalance'] = $metalBalances['totalGoldBalance'];
}
//mazaneh
$changeMesghal = config('change_mesghal');
+13 -9
View File
@@ -14,16 +14,20 @@ class FileController extends Controller
*
* @return string
*/
protected function createDir()
protected function createDir(): string
{
$now = Verta();
$path = preg_replace('/-/', '/', $now->formatDate());
if (!Storage::exists($path)) {
Storage::makeDirectory($path);
Storage::makeDirectory($path . '/' . 'thumb');
$disk = Storage::disk('public');
if (! $disk->exists($path)) {
$disk->makeDirectory($path);
$disk->makeDirectory($path.'/thumb');
}
return $path;
}
public function store(Request $request)
{
// Store FIle in Public Storage By Date
@@ -31,17 +35,17 @@ class FileController extends Controller
$data = $request->all();
$path = $this->createDir();
$data['original_name'] = $request->file('file')->getClientOriginalName();
$data['ext'] = $request->file('file')->getClientOriginalExtension();
$uploaded = $request->file('file');
$data['original_name'] = $uploaded->getClientOriginalName();
$data['ext'] = $uploaded->getClientOriginalExtension();
if (!isset($data['title']) || is_null($data['title'])) {
$data['title'] = $data['original_name'];
}
$file_name_src = md5(time() . $data['original_name']);
$file_name = $file_name_src . '.' . $data['ext'];
$file = $request->file('file');
$data['has_thumb'] = false;
$data['size'] = $file->getSize();
$file->move(public_path('storage/' . $path . '/'), $file_name);
$data['size'] = $uploaded->getSize();
Storage::disk('public')->putFileAs($path, $uploaded, $file_name);
$data['src'] = 'storage/' . $path . '/' . $file_name;
// $data['size'] = $file->getSize();
$data['user_id'] = auth()->id();
+37 -2
View File
@@ -5,26 +5,61 @@ namespace App\Http\Controllers\Admin;
use App\DB\Te\TableEngine;
use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Services\BalanceReportService;
use App\Services\WalletBalanceService;
use Illuminate\Http\Request;
class OrderController extends Controller
{
public function table(Request $request){
$records = Order::with(['customer','transactions']);
$balanceReport = app(BalanceReportService::class);
$catalogMetalIds = app(WalletBalanceService::class)->catalogMetalIds();
$records = Order::with([
'customer',
'transactions.product:id,title,unit,metal_id,group_type,amount,trade_by_quantity,direct_price',
]);
TableEngine::create($records, $request->all())
->initSearch(['customer.name'])
->select([
'*',Order::$SELECT_STS_STR
])->export($records);
if (isset($records['rows'])) {
foreach ($records['rows'] as &$row) {
$balanceReport->enrichOrderTableRow($row, $catalogMetalIds);
}
unset($row);
}
$records['catalogMetals'] = $balanceReport->catalogMetalsMeta();
return response()->json($records);
}
public function singleOrderTable(Request $request){
$records = Order::with(['customer'])->where('type',2);
$balanceReport = app(BalanceReportService::class);
$catalogMetalIds = app(WalletBalanceService::class)->catalogMetalIds();
$records = Order::with([
'customer',
'transactions.product:id,title,unit,metal_id,group_type,amount,trade_by_quantity,direct_price',
])->where('type',2);
TableEngine::create($records, $request->all())
->initSearch(['customer.name'])
->select([
'*',Order::$SELECT_STS_STR
])->export($records);
if (isset($records['rows'])) {
foreach ($records['rows'] as &$row) {
$balanceReport->enrichOrderTableRow($row, $catalogMetalIds);
}
unset($row);
}
$records['catalogMetals'] = $balanceReport->catalogMetalsMeta();
return response()->json($records);
}
}
@@ -612,6 +612,10 @@ class ProductController extends SuperController
unset($data['direct_price']);
}
if (!Product::hasInventoryColumn()) {
unset($data['inventory']);
}
return $data;
}
}
+190 -9
View File
@@ -20,8 +20,9 @@ use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
use App\Http\Controllers\Admin\TahesabController;
use App\Models\Setting;
use App\Models\User;
use App\Services\BalanceReportService;
use App\Services\ConfigService;
use App\Services\TransactionMetalService;
use App\Services\WalletBalanceService;
use Hekmatinasser\Verta\Verta;
@@ -221,10 +222,172 @@ class WalletController extends Controller
return response()->json(true);
}
public function index(Request $request, TransactionMetalService $transactionMetalService)
/** گزینه‌های شارژ کیف پول — نقدی + محصولات فعال */
public function chargeTargets()
{
$records = Transaction::with(['customer', 'wallet.product:id,metal_id', 'product:id,metal_id'])
->whereNull('fund_id');
$configService = app(ConfigService::class);
$mainWalletProductIds = $configService->mainWalletProductIds();
$balanceReport = app(BalanceReportService::class);
$targets = [
[
'key' => 'money',
'kind' => 'money',
'label' => 'نقدی (ریال)',
'unit' => 'ریال',
],
];
$products = Product::query()
->where('active', 1)
->orderBy('metal_id')
->orderBy('id')
->get(['id', 'title', 'unit', 'metal_id', 'group_type', 'trade_by_quantity', 'amount', 'direct_price']);
foreach ($products as $product) {
$usesMainWallet = in_array((int) $product->id, $mainWalletProductIds, true);
$label = (string) $product->title;
if ($usesMainWallet) {
$label .= ' (کیف اصلی)';
}
$targets[] = [
'key' => 'product:' . $product->id,
'kind' => 'metal',
'product_id' => (int) $product->id,
'label' => $label,
'unit' => $this->resolveProductChargeUnit($product),
'metal_id' => max(1, (int) ($product->metal_id ?? 1)),
'uses_main_wallet' => $usesMainWallet,
'trade_by_quantity' => (bool) $product->trade_by_quantity,
'group_type' => (string) ($product->group_type ?? ''),
];
}
return response()->json([
'targets' => $targets,
'catalogMetals' => $balanceReport->catalogMetalsMeta(),
]);
}
/**
* شارژ یکپارچه کیف پول — نقدی یا محصول (با رعایت کیف اصلی برای آبشده).
*/
public function charge_wallet(Request $request)
{
$productId = (int) $request->input('product_id', 0);
if ($productId > 0) {
return $this->chargeProductMetal($request, $productId);
}
return $this->charge($request);
}
private function chargeProductMetal(Request $request, int $productId)
{
$data = $request->all();
$product = Product::findOrFail($productId);
$customer = Customer::findOrFail($data['customer_id']);
$deposit = ((float) ($data['value'] ?? 0)) > 0;
$effectiveProductId = Controller::effectiveProductWalletId($productId);
$wallet_interface = new WalletInterface(
(int) $data['customer_id'],
(int) $customer->type,
null,
$effectiveProductId
);
$wallet = $wallet_interface->wallet;
if (!$deposit && $wallet !== null && (float) $wallet->gold < abs((float) $data['value'])) {
throw new UnprocessableEntityHttpException('مقدار موجودی کمتر از درخواست شماست');
}
$goldBlock = 0;
$user = auth()->user();
$unitLabel = $this->resolveProductChargeUnit($product);
$Withdraw = Withdraw::create([
'user_id' => $user->id,
'customer_id' => $customer->id,
'gold' => $data['value'],
'note' => $data['note'] ?? null,
'sts' => 4,
]);
new TransactionInterface($wallet_interface, [
'cash' => 0,
'gold' => $data['value'],
'product_id' => $productId,
'expire_at' => now(),
'note' => $data['note'] ?? null,
'withdraw_id' => $Withdraw->id,
'active' => true,
], 7, $deposit, false, $goldBlock);
if ($this->Config('send_to_tahesab') == 'true') {
try {
$data['direction'] = $deposit ? 1 : 0;
$tahesab = new TahesabController();
$tahesab->walletGold($data);
} catch (\Exception $e) {
return response($e->getMessage(), 500);
}
}
$status = $deposit ? ' شارژ شد ' : ' کسر شد ';
$formatted = self::formatSmsGoldWeight($data['value']);
if ($this->Config('charge_notif') == 'true') {
$message = 'کیف پول کاربر ' . $customer->name . ' به مقدار ' . $formatted . ' ' . $unitLabel . ' در تاریخ ' . verta()->format('Y/n/j H:i:s') . $status . 'بابت' . "\n"
. ($data['note'] ?? '')
. "\n"
. $this->Config('name_fa');
User::where('send_sms', 1)->get()->each(function ($admin) use ($message) {
$this->send($admin->mobile, $message);
});
}
$message = 'کیف پول شما به اندازه ' . $formatted . ' ' . $unitLabel . ' در تاریخ ' . verta()->format('Y/n/j H:i:s') . $status . ' بابت' . "\n"
. ($data['note'] ?? '')
. "\n"
. $this->Config('name_fa');
$this->Send($customer->mobile, $message);
return response()->json(true);
}
private function resolveProductChargeUnit(Product $product): string
{
$payload = Controller::productUnitPayload($product);
if (
Controller::usesQuantityTrade($payload)
&& !Controller::isWeightBasedProductUnit($payload['unit'] ?? null)
) {
$unit = trim((string) ($payload['unit'] ?? ''));
return $unit !== '' ? $unit : 'عدد';
}
if (Controller::isWeightBasedProductUnit($payload['unit'] ?? null)) {
return trim((string) $payload['unit']);
}
return Controller::productStorageWeightUnit($product);
}
public function index(Request $request)
{
$balanceReport = app(BalanceReportService::class);
$balanceService = app(WalletBalanceService::class);
$catalogMetalIds = $balanceService->catalogMetalIds();
$records = Transaction::with([
'customer',
'wallet.product:id,metal_id',
'product:id,title,metal_id,group_type,unit,amount,trade_by_quantity,direct_price',
])->whereNull('fund_id');
TableEngine::create($records, $request->all())
->initSearch(['order_id', 'customer.name'])
->select([
@@ -232,9 +395,13 @@ class WalletController extends Controller
])->export($records);
if (isset($records['rows'])) {
$records['rows'] = $transactionMetalService->enrichTransactionRows($records['rows']);
foreach ($records['rows'] as &$row) {
$balanceReport->enrichTransactionTableRow($row, $catalogMetalIds);
}
unset($row);
}
$records['catalogMetals'] = $transactionMetalService->catalogMetals();
$records['catalogMetals'] = $balanceReport->catalogMetalsMeta();
return response()->json($records);
}
@@ -289,28 +456,42 @@ class WalletController extends Controller
public function indexWallet(Request $request)
{
$lastPrice = (float) (Price::latest()->first()?->price ?? 0);
$balanceService = app(WalletBalanceService::class);
$catalogMetalIds = $balanceService->catalogMetalIds();
$mainWalletMetalId = $balanceService->resolveMainWalletMetalId();
// همان فیلتر/جستجوی جدول — بدون صفحه‌بندی — برای مجموع ردیف‌های قابل مشاهده
$sumQuery = Wallet::query();
TableEngine::create($sumQuery, $request->all())
->initSearch(['customer.name']);
$totalGold = (float) (clone $sumQuery)->sum('gold');
$sumRows = (clone $sumQuery)->with('product:id,metal_id')->get();
$metalBalances = $balanceService->buildWalletMetalSums($sumRows, $catalogMetalIds);
$totalGold = array_sum(array_column($metalBalances, 'gold'));
$totalGoldToCash = array_sum(array_column($metalBalances, 'goldToCash'));
$totalCash = (float) (clone $sumQuery)->sum('cash');
$sums = [
'gold' => round($totalGold, 2),
'goldToCash' => round($totalGold * $lastPrice, 2),
'goldToCash' => round($totalGoldToCash, 2),
'cash' => round($totalCash, 2),
'cashToGold' => $lastPrice > 0 ? round($totalCash / $lastPrice, 2) : 0,
'metalBalances' => $metalBalances,
];
$records = Wallet::with('customer');
$records = Wallet::with(['customer', 'product:id,metal_id']);
TableEngine::create($records, $request->all())
->initSearch(['customer.name'])
->select(['*'])
->export($records);
if (isset($records['rows'])) {
foreach ($records['rows'] as &$row) {
$balanceService->enrichWalletTableRow($row, $catalogMetalIds, $mainWalletMetalId);
}
unset($row);
}
$records['sums'] = $sums;
return response()->json($records);