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:
@@ -35,7 +35,7 @@ class AssetSummaryService
|
||||
->where('owner_type', $ownerType)
|
||||
->get();
|
||||
|
||||
$mainWallet = $userWallets->first(fn (Wallet $w) => $w->product_id === null);
|
||||
$mainWallet = $this->resolveMainWallet($userWallets);
|
||||
$metalIds = $this->catalogMetalIds($catalog);
|
||||
$weightUnit = Controller::tradeWeightUnit();
|
||||
$hasCountBased = $this->catalogHasCountBased($catalog);
|
||||
@@ -46,13 +46,13 @@ class AssetSummaryService
|
||||
// محصولات متصل به کیف اصلی (main_wallet_products) — موجودیشان = gold کیف اصلی
|
||||
$mainWalletProductIds = $this->configService->mainWalletProductIds();
|
||||
|
||||
$metalsWithProductWallet = $this->metalIdsWithProductWallet($userWallets, $catalogById, $mainWalletProductIds);
|
||||
$metalsWithProductWallet = $this->metalIdsWithProductWallet($userWallets, $catalogById, $mainWalletProductIds, $mainWallet);
|
||||
$inventoryCards = array_merge(
|
||||
$this->buildMeltedInventoryCards($catalog, $catalogById, $mainWallet, $metalIds, $metalsWithProductWallet, $mainWalletProductIds),
|
||||
$this->buildInventoryCards($userWallets, $catalogById, $mainWalletProductIds)
|
||||
$this->buildInventoryCards($userWallets, $catalogById, $mainWalletProductIds, $mainWallet),
|
||||
);
|
||||
$metalTotals = $this->buildMetalTotals($userWallets, $mainWallet, $metalIds, $weightUnit, $catalogById, $metalsWithProductWallet, $mainWalletProductIds);
|
||||
$cashWallet = (float) ($mainWallet->cash ?? 0);
|
||||
$cashWallet = (float) ($mainWallet?->cash ?? 0);
|
||||
$assetsRialValue = $this->sumAssetsRialValue(
|
||||
$metalTotals,
|
||||
$userWallets,
|
||||
@@ -112,7 +112,7 @@ class AssetSummaryService
|
||||
array $mainWalletProductIds = []
|
||||
): array {
|
||||
$cards = [];
|
||||
$mainWalletGrams = Controller::weightToGrams((float) ($mainWallet->gold ?? 0));
|
||||
$mainWalletGrams = Controller::weightToGrams((float) ($mainWallet?->gold ?? 0));
|
||||
$assignedMetalIds = [];
|
||||
$mainProductId = $this->configService->mainProductId();
|
||||
|
||||
@@ -123,7 +123,7 @@ class AssetSummaryService
|
||||
return [];
|
||||
}
|
||||
|
||||
$mainWalletWeight = (float) ($mainWallet->gold ?? 0);
|
||||
$mainWalletWeight = (float) ($mainWallet?->gold ?? 0);
|
||||
if ($mainWalletWeight <= 0) {
|
||||
return [];
|
||||
}
|
||||
@@ -186,6 +186,66 @@ class AssetSummaryService
|
||||
return $cards;
|
||||
}
|
||||
|
||||
private function resolveMainWallet(Collection $userWallets): ?Wallet
|
||||
{
|
||||
return $userWallets->first(
|
||||
fn (Wallet $w) => $w->fund_id === null && $w->product_id === null
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* کیف legacy محصول آبشده/کاتد — وقتی همان فلز روی کیف اصلی موجودی دارد نباید دوباره شمرده شود.
|
||||
*/
|
||||
private function shouldIgnoreLegacyProductWalletLine(
|
||||
Product $catalogProduct,
|
||||
?Wallet $mainWallet,
|
||||
Collection $catalogById,
|
||||
array $mainWalletProductIds
|
||||
): bool {
|
||||
if (in_array((int) $catalogProduct->id, $mainWalletProductIds, true)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ((float) ($mainWallet?->gold ?? 0) <= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!$this->isMeltedTradeProduct($catalogProduct)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$mainMetalId = $this->resolveMainWalletMetalId($mainWallet, $catalogById, $mainWalletProductIds);
|
||||
|
||||
return $mainMetalId > 0 && (int) ($catalogProduct->metal_id ?? 0) === $mainMetalId;
|
||||
}
|
||||
|
||||
private function resolveMainWalletMetalId(
|
||||
?Wallet $mainWallet,
|
||||
Collection $catalogById,
|
||||
array $mainWalletProductIds
|
||||
): int {
|
||||
if ($mainWalletProductIds !== []) {
|
||||
$representative = $this->resolveMainWalletRepresentative($catalogById, $mainWalletProductIds);
|
||||
if ($representative) {
|
||||
return max(1, (int) ($representative->metal_id ?? 1));
|
||||
}
|
||||
}
|
||||
|
||||
if ((float) ($mainWallet?->gold ?? 0) <= 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$mainProductId = $this->configService->mainProductId();
|
||||
if ($mainProductId) {
|
||||
$mainProduct = $catalogById->get((int) $mainProductId);
|
||||
if ($mainProduct) {
|
||||
return max(1, (int) ($mainProduct->metal_id ?? 1));
|
||||
}
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
private function catalogProduct(Product $product, Collection $catalogById): Product
|
||||
{
|
||||
return $catalogById->get((int) $product->id) ?? $product;
|
||||
@@ -246,9 +306,14 @@ class AssetSummaryService
|
||||
}
|
||||
|
||||
/** فلزهایی که کاربر روی کیف محصول موجودی دارد — برای جلوگیری از کارت آبشدهٔ تکراری. */
|
||||
private function metalIdsWithProductWallet(Collection $userWallets, Collection $catalogById, array $mainWalletProductIds = []): array
|
||||
{
|
||||
private function metalIdsWithProductWallet(
|
||||
Collection $userWallets,
|
||||
Collection $catalogById,
|
||||
array $mainWalletProductIds = [],
|
||||
?Wallet $mainWallet = null
|
||||
): array {
|
||||
$metalIds = [];
|
||||
$mainWallet ??= $this->resolveMainWallet($userWallets);
|
||||
|
||||
foreach ($userWallets as $walletLine) {
|
||||
if ($walletLine->product_id === null || (float) $walletLine->gold <= 0) {
|
||||
@@ -265,7 +330,12 @@ class AssetSummaryService
|
||||
continue;
|
||||
}
|
||||
|
||||
$metalId = (int) ($this->catalogProduct($product, $catalogById)->metal_id ?? 0);
|
||||
$catalogProduct = $this->catalogProduct($product, $catalogById);
|
||||
if ($this->shouldIgnoreLegacyProductWalletLine($catalogProduct, $mainWallet, $catalogById, $mainWalletProductIds)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$metalId = (int) ($catalogProduct->metal_id ?? 0);
|
||||
if ($metalId > 0) {
|
||||
$metalIds[] = $metalId;
|
||||
}
|
||||
@@ -296,11 +366,20 @@ class AssetSummaryService
|
||||
return $catalog->first(fn (Product $product) => (int) ($product->metal_id ?? 0) === $metalId);
|
||||
}
|
||||
|
||||
private function buildInventoryCards(Collection $userWallets, Collection $catalogById, array $mainWalletProductIds = []): array
|
||||
{
|
||||
private function buildInventoryCards(
|
||||
Collection $userWallets,
|
||||
Collection $catalogById,
|
||||
array $mainWalletProductIds = [],
|
||||
?Wallet $mainWallet = null
|
||||
): array {
|
||||
$cards = [];
|
||||
$mainWallet ??= $this->resolveMainWallet($userWallets);
|
||||
|
||||
foreach ($userWallets as $walletLine) {
|
||||
if ($walletLine->fund_id !== null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($walletLine->product_id === null || (float) $walletLine->gold <= 0) {
|
||||
continue;
|
||||
}
|
||||
@@ -316,6 +395,10 @@ class AssetSummaryService
|
||||
}
|
||||
|
||||
$catalogProduct = $this->catalogProduct($product, $catalogById);
|
||||
if ($this->shouldIgnoreLegacyProductWalletLine($catalogProduct, $mainWallet, $catalogById, $mainWalletProductIds)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$productPayload = $this->productPayload($catalogProduct);
|
||||
$isCountBased = $this->isCountBasedProduct($catalogProduct);
|
||||
|
||||
@@ -349,7 +432,7 @@ class AssetSummaryService
|
||||
return [];
|
||||
}
|
||||
|
||||
$mainWalletGrams = Controller::weightToGrams((float) ($mainWallet->gold ?? 0));
|
||||
$mainWalletGrams = Controller::weightToGrams((float) ($mainWallet?->gold ?? 0));
|
||||
$totals = [];
|
||||
|
||||
// فلز نمایندهٔ کیف اصلی در حالت main_wallet_products
|
||||
@@ -373,6 +456,10 @@ class AssetSummaryService
|
||||
}
|
||||
|
||||
$catalogProduct = $this->catalogProduct($walletLine->product, $catalogById);
|
||||
if ($this->shouldIgnoreLegacyProductWalletLine($catalogProduct, $mainWallet, $catalogById, $mainWalletProductIds)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ((int) ($catalogProduct->metal_id ?? 0) !== (int) $metalId) {
|
||||
continue;
|
||||
}
|
||||
@@ -532,11 +619,16 @@ class AssetSummaryService
|
||||
'direct_price' => $product->direct_price ?? null,
|
||||
'group_type' => $product->group_type ?? null,
|
||||
'amount' => $product->amount ?? null,
|
||||
'trade_by_quantity' => $product->trade_by_quantity ?? null,
|
||||
];
|
||||
}
|
||||
|
||||
private function productUnitWeightLabel(Product $product): ?string
|
||||
{
|
||||
if (!$this->isCountBasedProduct($product)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!Controller::hasProductUnitWeight($this->productPayload($product))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,563 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Order;
|
||||
use App\Models\Product;
|
||||
|
||||
class BalanceReportService
|
||||
{
|
||||
public const METAL_LABELS = [
|
||||
1 => 'طلا',
|
||||
2 => 'نقره',
|
||||
3 => 'مس',
|
||||
];
|
||||
|
||||
public function __construct(
|
||||
private readonly ConfigService $configService
|
||||
) {
|
||||
}
|
||||
|
||||
/** @return list<int> */
|
||||
public function catalogMetalIds(): array
|
||||
{
|
||||
return Product::query()
|
||||
->where('active', 1)
|
||||
->whereNotNull('metal_id')
|
||||
->where('metal_id', '>', 0)
|
||||
->distinct()
|
||||
->orderBy('metal_id')
|
||||
->pluck('metal_id')
|
||||
->map(static fn ($id) => (int) $id)
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
public function metalLabel(int $metalId): string
|
||||
{
|
||||
return self::METAL_LABELS[$metalId] ?? "فلز {$metalId}";
|
||||
}
|
||||
|
||||
/** واحد نمایش موجودی/تراز هر فلز در ادمین — مس کیلوگرم، بقیه گرم */
|
||||
public function metalDisplayUnit(int $metalId): string
|
||||
{
|
||||
return (int) $metalId === 3 ? 'کیلوگرم' : 'گرم';
|
||||
}
|
||||
|
||||
public function gramsToMetalDisplay(float $grams, int $metalId): float
|
||||
{
|
||||
return (int) $metalId === 3 ? $grams / 1000.0 : $grams;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function catalogMetalsMeta(): array
|
||||
{
|
||||
$items = [];
|
||||
foreach ($this->catalogMetalIds() as $metalId) {
|
||||
$metalId = (int) $metalId;
|
||||
$items[] = [
|
||||
'metal_id' => $metalId,
|
||||
'label' => $this->metalLabel($metalId),
|
||||
'display_unit' => $this->metalDisplayUnit($metalId),
|
||||
];
|
||||
}
|
||||
|
||||
return $items;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, array{gold: float, cash: float}>
|
||||
*/
|
||||
public function resolveOrderMetalSlices(Order $order): array
|
||||
{
|
||||
$order->loadMissing(['transactions.product']);
|
||||
|
||||
$slices = [];
|
||||
$txWithProduct = $order->transactions->filter(
|
||||
static fn ($tx) => $tx->product_id && abs((float) ($tx->gold ?? 0)) > 0
|
||||
);
|
||||
|
||||
if ($txWithProduct->isNotEmpty()) {
|
||||
foreach ($txWithProduct as $tx) {
|
||||
$metalId = (int) ($tx->product?->metal_id ?? 1);
|
||||
if ($metalId <= 0) {
|
||||
$metalId = 1;
|
||||
}
|
||||
$gold = abs((float) ($tx->gold ?? 0));
|
||||
if ($gold <= 0) {
|
||||
continue;
|
||||
}
|
||||
$slices[$metalId] = ($slices[$metalId] ?? 0.0) + $gold;
|
||||
}
|
||||
|
||||
$totalGold = array_sum($slices);
|
||||
$result = [];
|
||||
foreach ($slices as $metalId => $gold) {
|
||||
$cashShare = $totalGold > 0
|
||||
? (float) $order->total_price * ($gold / $totalGold)
|
||||
: 0.0;
|
||||
$result[(int) $metalId] = ['gold' => $gold, 'cash' => $cashShare];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
$amount = (float) ($order->amount ?? 0);
|
||||
$totalPrice = (float) ($order->total_price ?? 0);
|
||||
if ($amount <= 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$metalId = 1;
|
||||
$tx = $order->transactions->first(static fn ($t) => $t->product_id);
|
||||
if ($tx?->product) {
|
||||
$metalId = max(1, (int) ($tx->product->metal_id ?? 1));
|
||||
}
|
||||
|
||||
return [$metalId => ['gold' => $amount, 'cash' => $totalPrice]];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<int> $metalIds
|
||||
* @return array<int, array{gold: float, cash: float, gold_abs: float, cash_abs: float}>
|
||||
*/
|
||||
public function initMetalBalanceBuckets(array $metalIds): array
|
||||
{
|
||||
$buckets = [];
|
||||
foreach ($metalIds as $metalId) {
|
||||
$buckets[(int) $metalId] = [
|
||||
'gold' => 0.0,
|
||||
'cash' => 0.0,
|
||||
'gold_abs' => 0.0,
|
||||
'cash_abs' => 0.0,
|
||||
];
|
||||
}
|
||||
|
||||
return $buckets;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, array{gold: float, cash: float, gold_abs: float, cash_abs: float}> $buckets
|
||||
*/
|
||||
public function applyOrderToBuckets(array &$buckets, Order $order): void
|
||||
{
|
||||
$slices = $this->resolveOrderMetalSlices($order);
|
||||
foreach ($slices as $metalId => $slice) {
|
||||
$metalId = (int) $metalId;
|
||||
if (! isset($buckets[$metalId])) {
|
||||
$buckets[$metalId] = [
|
||||
'gold' => 0.0,
|
||||
'cash' => 0.0,
|
||||
'gold_abs' => 0.0,
|
||||
'cash_abs' => 0.0,
|
||||
];
|
||||
}
|
||||
|
||||
$gold = (float) $slice['gold'];
|
||||
$cash = (float) $slice['cash'];
|
||||
|
||||
if ((int) $order->direction === 1) {
|
||||
$buckets[$metalId]['gold'] += $gold;
|
||||
$buckets[$metalId]['cash'] -= $cash;
|
||||
} elseif ((int) $order->direction === 2) {
|
||||
$buckets[$metalId]['gold'] -= $gold;
|
||||
$buckets[$metalId]['cash'] += $cash;
|
||||
}
|
||||
|
||||
$buckets[$metalId]['gold_abs'] += $gold;
|
||||
$buckets[$metalId]['cash_abs'] += $cash;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, array{gold: float, cash: float, gold_abs: float, cash_abs: float}> $limanBuckets
|
||||
* @param array<int, array{gold: float, cash: float, gold_abs: float, cash_abs: float}> $kalhorBuckets
|
||||
*/
|
||||
public function buildMetalBalancesResponse(array $limanBuckets, array $kalhorBuckets): array
|
||||
{
|
||||
$metalIds = array_values(array_unique(array_merge(
|
||||
array_keys($limanBuckets),
|
||||
array_keys($kalhorBuckets)
|
||||
)));
|
||||
sort($metalIds);
|
||||
|
||||
$items = [];
|
||||
$totalGoldBalance = 0.0;
|
||||
|
||||
foreach ($metalIds as $metalId) {
|
||||
$metalId = (int) $metalId;
|
||||
$liman = $limanBuckets[$metalId] ?? [
|
||||
'gold' => 0.0,
|
||||
'cash' => 0.0,
|
||||
'gold_abs' => 0.0,
|
||||
'cash_abs' => 0.0,
|
||||
];
|
||||
$kalhor = $kalhorBuckets[$metalId] ?? [
|
||||
'gold' => 0.0,
|
||||
'cash' => 0.0,
|
||||
'gold_abs' => 0.0,
|
||||
'cash_abs' => 0.0,
|
||||
];
|
||||
|
||||
$goldBalance = -$liman['gold'] + $kalhor['gold'];
|
||||
$cashBalance = -$liman['cash'] + $kalhor['cash'];
|
||||
$goldBalanceOfLiman = -$liman['gold'];
|
||||
$goldBalanceOfKalhor = $kalhor['gold'];
|
||||
|
||||
$items[] = [
|
||||
'metal_id' => $metalId,
|
||||
'label' => $this->metalLabel($metalId),
|
||||
'balance' => round($goldBalance, 4),
|
||||
'goldBalance' => round($goldBalance, 4),
|
||||
'cashBalance' => round($cashBalance, 2),
|
||||
'goldBalanceOfLiman' => round($goldBalanceOfLiman, 4),
|
||||
'goldBalanceOfKalhor' => round($goldBalanceOfKalhor, 4),
|
||||
];
|
||||
|
||||
$totalGoldBalance += $goldBalance;
|
||||
}
|
||||
|
||||
return [
|
||||
'items' => $items,
|
||||
'totalGoldBalance' => round($totalGoldBalance, 4),
|
||||
];
|
||||
}
|
||||
|
||||
/** @param array<int, array{gold: float, cash: float, gold_abs: float, cash_abs: float}> $buckets */
|
||||
public function applyKalhorSlice(
|
||||
array &$buckets,
|
||||
float $gold,
|
||||
float $cash,
|
||||
int $direction,
|
||||
int $metalId = 1
|
||||
): void {
|
||||
if (! isset($buckets[$metalId])) {
|
||||
$buckets[$metalId] = [
|
||||
'gold' => 0.0,
|
||||
'cash' => 0.0,
|
||||
'gold_abs' => 0.0,
|
||||
'cash_abs' => 0.0,
|
||||
];
|
||||
}
|
||||
|
||||
if ($direction === 2) {
|
||||
$buckets[$metalId]['gold'] += $gold;
|
||||
$buckets[$metalId]['cash'] -= $cash;
|
||||
} elseif ($direction === 1) {
|
||||
$buckets[$metalId]['gold'] -= $gold;
|
||||
$buckets[$metalId]['cash'] += $cash;
|
||||
}
|
||||
|
||||
$buckets[$metalId]['gold_abs'] += $gold;
|
||||
$buckets[$metalId]['cash_abs'] += $cash;
|
||||
}
|
||||
|
||||
public function resolveTransactionMetalId(mixed $transaction): int
|
||||
{
|
||||
$product = $this->transactionProduct($transaction);
|
||||
if ($product !== null) {
|
||||
$metalId = (int) ($product->metal_id ?? 0);
|
||||
|
||||
return $metalId > 0 ? $metalId : 1;
|
||||
}
|
||||
|
||||
$walletProduct = $this->transactionWalletProduct($transaction);
|
||||
if ($walletProduct !== null) {
|
||||
$metalId = (int) ($walletProduct->metal_id ?? 0);
|
||||
|
||||
return $metalId > 0 ? $metalId : 1;
|
||||
}
|
||||
|
||||
if ($this->isMainWalletMetalTransaction($transaction)) {
|
||||
return $this->configService->mainWalletMetalId();
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
public function resolveTransactionDisplayTypeStr(mixed $transaction, ?int $metalId = null): ?string
|
||||
{
|
||||
$type = (int) ($this->lineValue($transaction, 'type') ?? 0);
|
||||
if (!in_array($type, [1, 2, 7, 10], true)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$metalId ??= $this->resolveTransactionMetalId($transaction);
|
||||
$label = $this->metalLabel($metalId);
|
||||
|
||||
return match ($type) {
|
||||
1 => 'خرید ' . $label,
|
||||
2 => 'فروش ' . $label,
|
||||
7 => 'واریز ' . $label,
|
||||
10 => 'برداشت ' . $label,
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
public function transactionGoldGrams(mixed $transaction): float
|
||||
{
|
||||
$gold = (float) ($this->lineValue($transaction, 'gold') ?? 0);
|
||||
if (abs($gold) < 0.0000001) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
$product = $this->transactionProduct($transaction);
|
||||
if ($product !== null) {
|
||||
return Controller::productLineWeightToGrams($product, $gold);
|
||||
}
|
||||
|
||||
return Controller::weightToGrams($gold);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<int> $catalogMetalIds
|
||||
* @return array<string, float>
|
||||
*/
|
||||
public function buildTransactionMetalDisplayMap(mixed $transaction, array $catalogMetalIds): array
|
||||
{
|
||||
$map = [];
|
||||
foreach ($catalogMetalIds as $metalId) {
|
||||
$map[(string) (int) $metalId] = 0.0;
|
||||
}
|
||||
|
||||
$type = (int) ($this->lineValue($transaction, 'type') ?? 0);
|
||||
if (in_array($type, [3, 4], true)) {
|
||||
return $map;
|
||||
}
|
||||
|
||||
$gold = (float) ($this->lineValue($transaction, 'gold') ?? 0);
|
||||
if (abs($gold) < 0.0000001) {
|
||||
return $map;
|
||||
}
|
||||
|
||||
$metalId = $this->resolveTransactionMetalId($transaction);
|
||||
$grams = abs($this->transactionGoldGrams($transaction));
|
||||
$display = $this->gramsToMetalDisplay($grams, $metalId);
|
||||
if ($gold < 0) {
|
||||
$display *= -1;
|
||||
}
|
||||
|
||||
$map[(string) $metalId] = round($display, 3);
|
||||
|
||||
return $map;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<int> $catalogMetalIds
|
||||
*/
|
||||
public function enrichTransactionTableRow(mixed &$row, array $catalogMetalIds): void
|
||||
{
|
||||
$metalMap = $this->buildTransactionMetalDisplayMap($row, $catalogMetalIds);
|
||||
$metalId = $this->resolveTransactionMetalId($row);
|
||||
$metalLabel = $this->metalLabel($metalId);
|
||||
$displayType = $this->resolveTransactionDisplayTypeStr($row, $metalId);
|
||||
|
||||
if (is_array($row)) {
|
||||
$row['metal_gold'] = $metalMap;
|
||||
$row['transaction_metal_id'] = $metalId;
|
||||
$row['transaction_metal_label'] = $metalLabel;
|
||||
if ($displayType !== null) {
|
||||
$row['type_str'] = $displayType;
|
||||
}
|
||||
foreach ($catalogMetalIds as $mid) {
|
||||
$row['metal_gold_' . $mid] = $metalMap[(string) $mid] ?? 0.0;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (is_object($row)) {
|
||||
$row->metal_gold = $metalMap;
|
||||
$row->transaction_metal_id = $metalId;
|
||||
$row->transaction_metal_label = $metalLabel;
|
||||
if ($displayType !== null) {
|
||||
$row->type_str = $displayType;
|
||||
}
|
||||
foreach ($catalogMetalIds as $mid) {
|
||||
$row->{'metal_gold_' . $mid} = $metalMap[(string) $mid] ?? 0.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function transactionProduct(mixed $transaction): ?object
|
||||
{
|
||||
if (is_object($transaction) && isset($transaction->product)) {
|
||||
return $transaction->product;
|
||||
}
|
||||
|
||||
if (is_array($transaction) && isset($transaction['product'])) {
|
||||
$product = $transaction['product'];
|
||||
|
||||
return is_object($product) ? $product : (object) $product;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function transactionWalletProduct(mixed $transaction): ?object
|
||||
{
|
||||
$wallet = $this->lineValue($transaction, 'wallet');
|
||||
if ($wallet === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (is_object($wallet)) {
|
||||
return isset($wallet->product) ? $wallet->product : null;
|
||||
}
|
||||
|
||||
if (is_array($wallet) && isset($wallet['product'])) {
|
||||
$product = $wallet['product'];
|
||||
|
||||
return is_object($product) ? $product : (object) $product;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function isMainWalletMetalTransaction(mixed $transaction): bool
|
||||
{
|
||||
$type = (int) ($this->lineValue($transaction, 'type') ?? 0);
|
||||
if (!in_array($type, [1, 2, 7, 10], true)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$wallet = $this->lineValue($transaction, 'wallet');
|
||||
if ($wallet === null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (is_object($wallet)) {
|
||||
return $wallet->product_id === null && $wallet->fund_id === null;
|
||||
}
|
||||
|
||||
if (is_array($wallet)) {
|
||||
return ($wallet['product_id'] ?? null) === null && ($wallet['fund_id'] ?? null) === null;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function resolveOrderMetalId(mixed $order): int
|
||||
{
|
||||
$product = $this->resolveOrderProduct($order);
|
||||
if ($product !== null) {
|
||||
$metalId = (int) ($product->metal_id ?? 0);
|
||||
|
||||
return $metalId > 0 ? $metalId : 1;
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<int> $catalogMetalIds
|
||||
*/
|
||||
public function enrichOrderTableRow(mixed &$row, array $catalogMetalIds = []): void
|
||||
{
|
||||
$product = $this->resolveOrderProduct($row);
|
||||
$unit = $this->resolveOrderAmountUnit($product);
|
||||
$amount = (float) ($this->lineValue($row, 'amount') ?? 0);
|
||||
$displayAmount = $this->resolveOrderDisplayAmount($amount, $product);
|
||||
$metalId = $this->resolveOrderMetalId($row);
|
||||
$metalLabel = $this->metalLabel($metalId);
|
||||
$price = (float) ($this->lineValue($row, 'price') ?? 0);
|
||||
|
||||
$metalPrices = [];
|
||||
foreach ($catalogMetalIds as $mid) {
|
||||
$mid = (int) $mid;
|
||||
$metalPrices[(string) $mid] = $mid === $metalId ? $price : 0.0;
|
||||
}
|
||||
|
||||
$payload = [
|
||||
'amount_unit' => $unit,
|
||||
'amount_display' => $displayAmount,
|
||||
'order_metal_id' => $metalId,
|
||||
'order_metal_label' => $metalLabel,
|
||||
'metal_prices' => $metalPrices,
|
||||
];
|
||||
|
||||
foreach ($catalogMetalIds as $mid) {
|
||||
$payload['metal_price_' . (int) $mid] = $metalPrices[(string) (int) $mid] ?? 0.0;
|
||||
}
|
||||
|
||||
if (is_array($row)) {
|
||||
foreach ($payload as $key => $value) {
|
||||
$row[$key] = $value;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (is_object($row)) {
|
||||
foreach ($payload as $key => $value) {
|
||||
$row->{$key} = $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function resolveOrderAmountUnit(?object $product): string
|
||||
{
|
||||
if ($product === null) {
|
||||
return Controller::tradeWeightUnit();
|
||||
}
|
||||
|
||||
return Controller::productQuantityUnit(Controller::productUnitPayload($product));
|
||||
}
|
||||
|
||||
private function resolveOrderDisplayAmount(float $amount, ?object $product): float
|
||||
{
|
||||
if ($product === null || abs($amount) < 0.0000001) {
|
||||
return round($amount, 3);
|
||||
}
|
||||
|
||||
$payload = Controller::productUnitPayload($product);
|
||||
$productUnit = trim((string) ($payload['unit'] ?? ''));
|
||||
if (!Controller::isWeightBasedProductUnit($productUnit)) {
|
||||
return round($amount, 3);
|
||||
}
|
||||
|
||||
$tradeUnit = Controller::tradeWeightUnit();
|
||||
if ($productUnit !== $tradeUnit) {
|
||||
return round(Controller::convertWeight($amount, $tradeUnit, $productUnit), 3);
|
||||
}
|
||||
|
||||
return round($amount, 3);
|
||||
}
|
||||
|
||||
private function resolveOrderProduct(mixed $order): ?object
|
||||
{
|
||||
$transactions = $this->lineValue($order, 'transactions');
|
||||
if ($transactions instanceof \Illuminate\Support\Collection) {
|
||||
$transactions = $transactions->all();
|
||||
}
|
||||
|
||||
if (!is_array($transactions)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach ($transactions as $tx) {
|
||||
$product = is_object($tx) ? ($tx->product ?? null) : ($tx['product'] ?? null);
|
||||
if ($product) {
|
||||
return is_object($product) ? $product : (object) $product;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function lineValue(mixed $line, string $key): mixed
|
||||
{
|
||||
if (is_array($line)) {
|
||||
return $line[$key] ?? null;
|
||||
}
|
||||
|
||||
if (is_object($line)) {
|
||||
return $line->{$key} ?? null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -97,27 +97,22 @@ class CategoryService
|
||||
{
|
||||
$names = $this->collectTargetCategoryNames();
|
||||
$created = 0;
|
||||
$order = 0;
|
||||
$maxOrder = (int) Category::max('sort_order');
|
||||
|
||||
foreach ($names as $name) {
|
||||
$order++;
|
||||
$existing = Category::where('name', $name)->first();
|
||||
|
||||
if ($existing) {
|
||||
if ((int) $existing->sort_order !== $order) {
|
||||
$existing->sort_order = $order;
|
||||
$existing->save();
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$maxOrder++;
|
||||
Category::create([
|
||||
'name' => $name,
|
||||
'active' => 1,
|
||||
'show_in_filter' => 1,
|
||||
'show_in_select' => 1,
|
||||
'sort_order' => $order,
|
||||
'sort_order' => $maxOrder,
|
||||
]);
|
||||
$created++;
|
||||
}
|
||||
|
||||
@@ -78,12 +78,9 @@ class MontzarService
|
||||
|
||||
$response = Http::timeout(7)
|
||||
->acceptJson()
|
||||
->withOptions([
|
||||
'curl' => [
|
||||
CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
|
||||
CURLOPT_TCP_FASTOPEN => 1,
|
||||
],
|
||||
])
|
||||
->withOptions(self::httpClientOptions(
|
||||
defined('CURLOPT_TCP_FASTOPEN') ? [(int) constant('CURLOPT_TCP_FASTOPEN') => 1] : []
|
||||
))
|
||||
->withToken($token)
|
||||
->get($this->endpoint('/server/customer/product/list'))
|
||||
->json();
|
||||
|
||||
@@ -30,7 +30,22 @@ class ProductDisplayPriceService
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->isMeltedTradeProduct($product);
|
||||
return $this->isMeltedTradeProduct($product)
|
||||
|| $this->usesQuantityAppPrice($product);
|
||||
}
|
||||
|
||||
/** معامله مقداری با قیمت اپ — نه قیمت دستی قدیمی با price پر در DB */
|
||||
private function usesQuantityAppPrice(Product $product): bool
|
||||
{
|
||||
if (! ($product->trade_by_quantity ?? false)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($product->reading_method || (int) ($product->direct_price ?? 0) === 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (int) ($product->price ?? 0) <= 0;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -73,6 +88,19 @@ class ProductDisplayPriceService
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($product->reading_method && ! $this->productUsesLastPriceIfZero($product)) {
|
||||
$product->setAttribute('reference_provider_active', false);
|
||||
$this->zeroProductPrice($product);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($product->reading_method) {
|
||||
$product->setAttribute('reference_provider_active', true);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($this->isWeightBasedStoreProduct($product)) {
|
||||
$this->enrichWeightBasedPrice($product);
|
||||
}
|
||||
@@ -262,25 +290,12 @@ class ProductDisplayPriceService
|
||||
/** @param array<int, array<string, mixed>> $feed */
|
||||
private function applyReferenceFeedPrice(Product $product, array $feed, ZaarboxPriceService $zaarbox): void
|
||||
{
|
||||
if (Product::hasStoredPriceColumns()) {
|
||||
$stored = (int) ($product->price ?? 0) + (int) ($product->price_profit ?? 0);
|
||||
if ($stored > 0) {
|
||||
$product->setAttribute('price', (int) ($product->price ?? 0));
|
||||
if (Schema::hasColumn($product->getTable(), 'price_profit')) {
|
||||
$product->setAttribute('price_profit', (int) ($product->price_profit ?? 0));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
$useLast = $this->productUsesLastPriceIfZero($product);
|
||||
$row = $zaarbox->findFeedRow($feed, (string) $product->reading_method);
|
||||
if ($row === null) {
|
||||
$useLast = $this->productUsesLastPriceIfZero($product);
|
||||
$product->setAttribute('reference_provider_active', $useLast);
|
||||
$offset = ProductPriceService::offsetPercent($product);
|
||||
$historical = app(ConfigService::class)->getBool('show_last_price', false)
|
||||
? $this->resolveHistoricalBasePrice()
|
||||
: 0;
|
||||
$historical = $useLast ? $this->resolveHistoricalBasePrice() : 0;
|
||||
$computed = $historical > 0
|
||||
? ProductPriceService::adjustedTotal($historical, 0, $offset)
|
||||
: 0;
|
||||
@@ -289,9 +304,19 @@ class ProductDisplayPriceService
|
||||
return;
|
||||
}
|
||||
|
||||
$providerRaw = $zaarbox->resolveReferenceProviderTotal($row);
|
||||
$providerActive = $useLast || $providerRaw > 0;
|
||||
$product->setAttribute('reference_provider_active', $providerActive);
|
||||
|
||||
if (! $useLast && $providerRaw <= 0) {
|
||||
$this->zeroProductPrice($product);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$computed = $zaarbox->computeAdjustedProductPrice($product, $row);
|
||||
if ($computed <= 0) {
|
||||
if ($this->productUsesLastPriceIfZero($product)) {
|
||||
if ($useLast) {
|
||||
$fallback = $this->resolveLastPriceFallback($product);
|
||||
if ($fallback > 0) {
|
||||
$product->setAttribute('price', $fallback);
|
||||
@@ -424,7 +449,7 @@ class ProductDisplayPriceService
|
||||
|
||||
$row = app(ZaarboxPriceService::class)->normalizeFeedRow($row);
|
||||
|
||||
return (int) round((float) ($row['price'] ?? 0) + (float) ($row['profit'] ?? 0));
|
||||
return app(ZaarboxPriceService::class)->resolveReferenceProviderTotal($row);
|
||||
}
|
||||
|
||||
private function isMeltedTradeProduct(Product $product): bool
|
||||
|
||||
@@ -1,154 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Product;
|
||||
use Rooyesh\Wallet\models\Wallet;
|
||||
|
||||
class TransactionMetalService
|
||||
{
|
||||
private const METAL_LABELS = [
|
||||
1 => 'طلا',
|
||||
2 => 'نقره',
|
||||
3 => 'مس',
|
||||
];
|
||||
|
||||
public function __construct(
|
||||
private readonly ConfigService $configService
|
||||
) {
|
||||
}
|
||||
|
||||
public function metalLabel(int $metalId): string
|
||||
{
|
||||
return self::METAL_LABELS[$metalId] ?? Controller::metalTypeLabel();
|
||||
}
|
||||
|
||||
/** @return array<int, array{metal_id: int, label: string, display_unit: string}> */
|
||||
public function catalogMetals(): array
|
||||
{
|
||||
return Product::query()
|
||||
->where('active', 1)
|
||||
->pluck('metal_id')
|
||||
->filter(fn ($id) => (int) $id > 0)
|
||||
->map(fn ($id) => (int) $id)
|
||||
->unique()
|
||||
->sort()
|
||||
->values()
|
||||
->map(fn (int $metalId) => [
|
||||
'metal_id' => $metalId,
|
||||
'label' => $this->metalLabel($metalId),
|
||||
'display_unit' => Controller::tradeWeightUnit(),
|
||||
])
|
||||
->all();
|
||||
}
|
||||
|
||||
public function resolveMetalIdForTransaction(object $transaction): int
|
||||
{
|
||||
$productId = (int) ($transaction->product_id ?? 0);
|
||||
if ($productId > 0) {
|
||||
$metalId = (int) (Product::query()->whereKey($productId)->value('metal_id') ?? 0);
|
||||
if ($metalId > 0) {
|
||||
return $metalId;
|
||||
}
|
||||
}
|
||||
|
||||
$wallet = $transaction->wallet ?? null;
|
||||
if (is_numeric($wallet)) {
|
||||
$wallet = Wallet::with('product:id,metal_id')->find($wallet);
|
||||
} elseif (is_object($wallet) && !$wallet->relationLoaded('product')) {
|
||||
$wallet->load('product:id,metal_id');
|
||||
}
|
||||
|
||||
if (is_object($wallet) && $wallet->product_id && $wallet->product) {
|
||||
$metalId = (int) ($wallet->product->metal_id ?? 0);
|
||||
if ($metalId > 0) {
|
||||
return $metalId;
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->isMainWalletMetalTransaction($transaction, $wallet)) {
|
||||
return $this->configService->mainWalletMetalId();
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
private function isMainWalletMetalTransaction(object $transaction, mixed $wallet): bool
|
||||
{
|
||||
$type = (int) ($transaction->type ?? 0);
|
||||
if (!in_array($type, [1, 2, 7, 10], true)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!$wallet || !is_object($wallet)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return $wallet->product_id === null && $wallet->fund_id === null;
|
||||
}
|
||||
|
||||
public function resolveDisplayTypeStr(object $transaction): ?string
|
||||
{
|
||||
$type = (int) ($transaction->type ?? 0);
|
||||
if (!in_array($type, [1, 2, 7, 10], true)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$metalLabel = $this->metalLabel($this->resolveMetalIdForTransaction($transaction));
|
||||
|
||||
return match ($type) {
|
||||
1 => Controller::productBuyTitle($metalLabel),
|
||||
2 => Controller::productSellTitle($metalLabel),
|
||||
7 => 'واریز ' . $metalLabel,
|
||||
10 => 'برداشت ' . $metalLabel,
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
/** @param iterable<int, array<string, mixed>|object> $rows */
|
||||
public function enrichTransactionRows(iterable $rows): array
|
||||
{
|
||||
$metalIds = array_column($this->catalogMetals(), 'metal_id');
|
||||
$enriched = [];
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$record = is_array($row) ? (object) $row : $row;
|
||||
$metalId = $this->resolveMetalIdForTransaction($record);
|
||||
$displayType = $this->resolveDisplayTypeStr($record);
|
||||
$type = (int) (is_array($row) ? ($row['type'] ?? 0) : ($row->type ?? 0));
|
||||
$gold = (float) (is_array($row) ? ($row['gold'] ?? 0) : ($row->gold ?? 0));
|
||||
$isMoney = in_array($type, [3, 4], true);
|
||||
|
||||
if ($displayType !== null) {
|
||||
if (is_array($row)) {
|
||||
$row['type_str'] = $displayType;
|
||||
} else {
|
||||
$row->type_str = $displayType;
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($metalIds as $mid) {
|
||||
$key = "metal_gold_{$mid}";
|
||||
$value = (!$isMoney && $metalId === $mid) ? $gold : 0;
|
||||
if (is_array($row)) {
|
||||
$row[$key] = $value;
|
||||
} else {
|
||||
$row->{$key} = $value;
|
||||
}
|
||||
}
|
||||
|
||||
if (is_array($row)) {
|
||||
$row['transaction_metal_id'] = $metalId;
|
||||
$row['transaction_metal_label'] = $this->metalLabel($metalId);
|
||||
} else {
|
||||
$row->transaction_metal_id = $metalId;
|
||||
$row->transaction_metal_label = $this->metalLabel($metalId);
|
||||
}
|
||||
|
||||
$enriched[] = $row;
|
||||
}
|
||||
|
||||
return $enriched;
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,9 @@
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Price;
|
||||
use App\Models\Product;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
@@ -12,8 +15,10 @@ use Illuminate\Support\Collection;
|
||||
*/
|
||||
class WalletBalanceService
|
||||
{
|
||||
public function __construct(private ConfigService $configService)
|
||||
{
|
||||
public function __construct(
|
||||
private ConfigService $configService,
|
||||
private BalanceReportService $balanceReportService
|
||||
) {
|
||||
}
|
||||
|
||||
public function mainWalletProductIds(): array
|
||||
@@ -79,6 +84,240 @@ class WalletBalanceService
|
||||
return $sum;
|
||||
}
|
||||
|
||||
/** @return list<int> */
|
||||
public function catalogMetalIds(): array
|
||||
{
|
||||
$ids = $this->balanceReportService->catalogMetalIds();
|
||||
|
||||
return $ids !== [] ? $ids : [1];
|
||||
}
|
||||
|
||||
public function resolveMainWalletMetalId(): int
|
||||
{
|
||||
$mainWalletProductIds = $this->mainWalletProductIds();
|
||||
if ($mainWalletProductIds !== []) {
|
||||
$product = Product::query()
|
||||
->whereIn('id', $mainWalletProductIds)
|
||||
->orderBy('id')
|
||||
->first();
|
||||
|
||||
return max(1, (int) ($product?->metal_id ?? 1));
|
||||
}
|
||||
|
||||
$metalIds = $this->catalogMetalIds();
|
||||
|
||||
return count($metalIds) === 1 ? (int) $metalIds[0] : 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* فلز مرتبط با یک ردیف کیف در جدول ادمین.
|
||||
*
|
||||
* @param Collection|array<int, mixed>|null $wallets
|
||||
*/
|
||||
public function resolveWalletLineMetalId(mixed $line, ?int $mainWalletMetalId = null): int
|
||||
{
|
||||
$fundId = $this->lineValue($line, 'fund_id');
|
||||
$productId = $this->lineValue($line, 'product_id');
|
||||
|
||||
if ($fundId !== null) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
if ($productId !== null) {
|
||||
$product = $this->lineProduct($line);
|
||||
$metalId = (int) ($product?->metal_id ?? 0);
|
||||
|
||||
return $metalId > 0 ? $metalId : 1;
|
||||
}
|
||||
|
||||
return $mainWalletMetalId ?? $this->resolveMainWalletMetalId();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<int> $catalogMetalIds
|
||||
* @return array<string, float>
|
||||
*/
|
||||
public function walletLineMetalGoldMap(
|
||||
mixed $line,
|
||||
array $catalogMetalIds,
|
||||
?int $mainWalletMetalId = null
|
||||
): array {
|
||||
$map = [];
|
||||
foreach ($catalogMetalIds as $metalId) {
|
||||
$map[(string) $metalId] = 0.0;
|
||||
}
|
||||
|
||||
$goldGrams = $this->walletLineGoldGrams($line);
|
||||
if ($goldGrams <= 0) {
|
||||
return $map;
|
||||
}
|
||||
|
||||
$metalId = $this->resolveWalletLineMetalId($line, $mainWalletMetalId);
|
||||
$map[(string) $metalId] = round(
|
||||
$this->balanceReportService->gramsToMetalDisplay($goldGrams, $metalId),
|
||||
3
|
||||
);
|
||||
|
||||
return $map;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection|array<int, mixed> $walletLines
|
||||
* @param list<int> $catalogMetalIds
|
||||
* @return array<string, float> جمع به گرم
|
||||
*/
|
||||
public function sumWalletMetalGrams(Collection|array $walletLines, array $catalogMetalIds): array
|
||||
{
|
||||
$buckets = [];
|
||||
foreach ($catalogMetalIds as $metalId) {
|
||||
$buckets[(string) (int) $metalId] = 0.0;
|
||||
}
|
||||
|
||||
$mainWalletMetalId = $this->resolveMainWalletMetalId();
|
||||
foreach ($this->walletLines($walletLines) as $line) {
|
||||
$goldGrams = $this->walletLineGoldGrams($line);
|
||||
if ($goldGrams <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$metalId = (string) $this->resolveWalletLineMetalId($line, $mainWalletMetalId);
|
||||
$buckets[$metalId] = ($buckets[$metalId] ?? 0.0) + $goldGrams;
|
||||
}
|
||||
|
||||
return $buckets;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection|array<int, mixed> $walletLines
|
||||
* @param list<int> $catalogMetalIds
|
||||
* @return list<array{metal_id: int, label: string, gold: float, display_unit: string, goldToCash: float}>
|
||||
*/
|
||||
public function buildWalletMetalSums(Collection|array $walletLines, array $catalogMetalIds): array
|
||||
{
|
||||
$gramBuckets = $this->sumWalletMetalGrams($walletLines, $catalogMetalIds);
|
||||
|
||||
$items = [];
|
||||
foreach ($catalogMetalIds as $metalId) {
|
||||
$metalId = (int) $metalId;
|
||||
$goldGrams = (float) ($gramBuckets[(string) $metalId] ?? 0.0);
|
||||
$displayGold = round($this->balanceReportService->gramsToMetalDisplay($goldGrams, $metalId), 3);
|
||||
$price = $this->livePricePerGram($metalId);
|
||||
$items[] = [
|
||||
'metal_id' => $metalId,
|
||||
'label' => $this->balanceReportService->metalLabel($metalId),
|
||||
'gold' => $displayGold,
|
||||
'display_unit' => $this->balanceReportService->metalDisplayUnit($metalId),
|
||||
'goldToCash' => round($goldGrams * $price, 2),
|
||||
];
|
||||
}
|
||||
|
||||
return $items;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection|array<int, mixed> $walletLines
|
||||
* @param list<int> $catalogMetalIds
|
||||
* @return array<string, float> مقادیر نمایشی
|
||||
*/
|
||||
public function buildCustomerWalletMetalDisplayMap(Collection|array $walletLines, array $catalogMetalIds): array
|
||||
{
|
||||
$gramBuckets = $this->sumWalletMetalGrams($walletLines, $catalogMetalIds);
|
||||
$map = [];
|
||||
|
||||
foreach ($catalogMetalIds as $metalId) {
|
||||
$metalId = (int) $metalId;
|
||||
$goldGrams = (float) ($gramBuckets[(string) $metalId] ?? 0.0);
|
||||
$map[(string) $metalId] = round(
|
||||
$this->balanceReportService->gramsToMetalDisplay($goldGrams, $metalId),
|
||||
3
|
||||
);
|
||||
}
|
||||
|
||||
return $map;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<int> $catalogMetalIds
|
||||
*/
|
||||
public function enrichWalletTableRow(mixed &$row, array $catalogMetalIds, int $mainWalletMetalId): void
|
||||
{
|
||||
$metalMap = $this->walletLineMetalGoldMap($row, $catalogMetalIds, $mainWalletMetalId);
|
||||
|
||||
if (is_array($row)) {
|
||||
$row['metal_gold'] = $metalMap;
|
||||
foreach ($catalogMetalIds as $metalId) {
|
||||
$row['metal_gold_' . $metalId] = $metalMap[(string) $metalId] ?? 0.0;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (is_object($row)) {
|
||||
$row->metal_gold = $metalMap;
|
||||
foreach ($catalogMetalIds as $metalId) {
|
||||
$row->{'metal_gold_' . $metalId} = $metalMap[(string) $metalId] ?? 0.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function livePricePerGram(int $metalId): float
|
||||
{
|
||||
if ($metalId === 1) {
|
||||
$live = (int) app(ProductDisplayPriceService::class)->resolveAppBasePrice();
|
||||
if ($live > 0) {
|
||||
return (float) $live;
|
||||
}
|
||||
|
||||
return (float) (Price::latest('id')->value('price') ?? 0);
|
||||
}
|
||||
|
||||
$product = Product::query()
|
||||
->where('active', 1)
|
||||
->where('metal_id', $metalId)
|
||||
->where('price', '>', 0)
|
||||
->orderBy('id')
|
||||
->first();
|
||||
|
||||
if (!$product) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
$unitPrice = (float) $product->price + (float) ($product->price_profit ?? 0);
|
||||
$amount = (float) ($product->amount ?? 1);
|
||||
|
||||
return $amount > 0 ? $unitPrice * $amount : $unitPrice;
|
||||
}
|
||||
|
||||
private function lineProduct(mixed $line): ?object
|
||||
{
|
||||
if (is_object($line) && isset($line->product)) {
|
||||
return $line->product;
|
||||
}
|
||||
|
||||
if (is_array($line) && isset($line['product'])) {
|
||||
$product = $line['product'];
|
||||
|
||||
return is_object($product) ? $product : (object) $product;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function walletLineGoldGrams(mixed $line): float
|
||||
{
|
||||
$gold = (float) ($this->lineValue($line, 'gold') ?? 0);
|
||||
if ($gold <= 0) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
$product = $this->lineProduct($line);
|
||||
if ($product !== null) {
|
||||
return Controller::productLineWeightToGrams($product, $gold);
|
||||
}
|
||||
|
||||
return Controller::weightToGrams($gold);
|
||||
}
|
||||
|
||||
/** @param Collection|array<int, mixed>|null $wallets */
|
||||
private function mainWalletLine(Collection|array|null $wallets): mixed
|
||||
{
|
||||
|
||||
@@ -84,11 +84,7 @@ class WebsocketBroadcastService
|
||||
try {
|
||||
$response = Http::timeout(3)
|
||||
->withHeaders(['Content-Type' => 'application/json'])
|
||||
->withOptions([
|
||||
'curl' => [
|
||||
CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
|
||||
],
|
||||
])
|
||||
->withOptions(\App\Http\Controllers\Controller::httpClientOptions())
|
||||
->post($url, $body);
|
||||
|
||||
if (! $response->successful()) {
|
||||
|
||||
@@ -221,9 +221,7 @@ class ZaarboxPriceService
|
||||
return $empty;
|
||||
}
|
||||
|
||||
$base = (float) ($row['price'] ?? 0);
|
||||
$profit = (float) ($row['profit'] ?? 0);
|
||||
$orderPrice = (int) round($base + $profit);
|
||||
$orderPrice = $this->resolveReferenceProviderTotal($row);
|
||||
|
||||
return ['price' => $orderPrice, 'order_price' => $orderPrice, 'raw' => $row];
|
||||
} catch (\Throwable $e) {
|
||||
@@ -339,7 +337,7 @@ class ZaarboxPriceService
|
||||
return $empty;
|
||||
}
|
||||
|
||||
$orderPrice = (int) round((float) ($row['price'] ?? 0) + (float) ($row['profit'] ?? 0));
|
||||
$orderPrice = $this->resolveReferenceProviderTotal($row);
|
||||
|
||||
return ['order_price' => $orderPrice, 'raw' => $row];
|
||||
} catch (\Throwable $e) {
|
||||
@@ -386,23 +384,24 @@ class ZaarboxPriceService
|
||||
}
|
||||
|
||||
$row = $this->normalizeFeedRow($RPrice);
|
||||
$parts = $this->resolveReferenceBaseProfit($row);
|
||||
|
||||
if (($row['name'] ?? '') === 'TGJU فلز مس') {
|
||||
$copper = ($row['price'] ?? 0) + ($row['profit'] ?? 0);
|
||||
$copper = $parts['price'] + $parts['profit'];
|
||||
}
|
||||
if (($row['name'] ?? '') === 'TGJU دلار') {
|
||||
$dollar = ($row['price'] ?? 0) + ($row['profit'] ?? 0);
|
||||
$dollar = $parts['price'] + $parts['profit'];
|
||||
}
|
||||
|
||||
ProductPriceService::syncFromReference(
|
||||
$product,
|
||||
(int) $row['price'],
|
||||
(int) ($row['profit'] ?? 0)
|
||||
$parts['price'],
|
||||
$parts['profit']
|
||||
);
|
||||
|
||||
$productPrice = (float) ProductPriceService::adjustedTotal(
|
||||
(int) $row['price'],
|
||||
(int) ($row['profit'] ?? 0),
|
||||
$parts['price'],
|
||||
$parts['profit'],
|
||||
ProductPriceService::offsetPercent($product)
|
||||
);
|
||||
|
||||
@@ -477,22 +476,6 @@ class ZaarboxPriceService
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* قیمت نمایشی محصول از یک ردیف فید + offset درصد — بدون نوشتن DB
|
||||
*
|
||||
* @param array<string, mixed> $row
|
||||
*/
|
||||
public function computeAdjustedProductPrice(Product $product, array $row): int
|
||||
{
|
||||
$normalized = $this->normalizeFeedRow($row);
|
||||
|
||||
return ProductPriceService::adjustedTotal(
|
||||
(int) ($normalized['price'] ?? 0),
|
||||
(int) ($normalized['profit'] ?? 0),
|
||||
ProductPriceService::offsetPercent($product)
|
||||
);
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $row */
|
||||
public function normalizeFeedRow(array $row): array
|
||||
{
|
||||
@@ -503,6 +486,55 @@ class ZaarboxPriceService
|
||||
return $row;
|
||||
}
|
||||
|
||||
/**
|
||||
* base/profit مرجع zaarbox — وقتی price صفر است provider قیمت نداده (profit مقدار قدیمی است).
|
||||
*
|
||||
* @param array<string, mixed> $row
|
||||
* @return array{price: int, profit: int}
|
||||
*/
|
||||
public function resolveReferenceBaseProfit(array $row): array
|
||||
{
|
||||
$normalized = $this->normalizeFeedRow($row);
|
||||
$price = (int) round((float) ($normalized['price'] ?? 0));
|
||||
if ($price <= 0) {
|
||||
return ['price' => 0, 'profit' => 0];
|
||||
}
|
||||
|
||||
return [
|
||||
'price' => $price,
|
||||
'profit' => (int) round((float) ($normalized['profit'] ?? 0)),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $row
|
||||
*/
|
||||
public function resolveReferenceProviderTotal(array $row): int
|
||||
{
|
||||
$parts = $this->resolveReferenceBaseProfit($row);
|
||||
|
||||
return $parts['price'] + $parts['profit'];
|
||||
}
|
||||
|
||||
/**
|
||||
* قیمت نمایشی محصول از یک ردیف فید + offset درصد — بدون نوشتن DB
|
||||
*
|
||||
* @param array<string, mixed> $row
|
||||
*/
|
||||
public function computeAdjustedProductPrice(Product $product, array $row): int
|
||||
{
|
||||
$parts = $this->resolveReferenceBaseProfit($row);
|
||||
if ($parts['price'] <= 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return ProductPriceService::adjustedTotal(
|
||||
$parts['price'],
|
||||
$parts['profit'],
|
||||
ProductPriceService::offsetPercent($product)
|
||||
);
|
||||
}
|
||||
|
||||
public function syncProductFromApi(Product $product): bool
|
||||
{
|
||||
if (!Product::hasStoredPriceColumns()) {
|
||||
@@ -524,11 +556,12 @@ class ZaarboxPriceService
|
||||
}
|
||||
|
||||
$row = $this->normalizeFeedRow($RPrice);
|
||||
$parts = $this->resolveReferenceBaseProfit($row);
|
||||
|
||||
ProductPriceService::syncFromReference(
|
||||
$product,
|
||||
(int) $row['price'],
|
||||
(int) ($row['profit'] ?? 0)
|
||||
$parts['price'],
|
||||
$parts['profit']
|
||||
);
|
||||
|
||||
return true;
|
||||
|
||||
Reference in New Issue
Block a user