Skip to content

Commit 603804a

Browse files
Ajuste do preço medio de produto
1 parent 9a13210 commit 603804a

File tree

1 file changed

+19
-9
lines changed

1 file changed

+19
-9
lines changed

app/Models/Product.php

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -27,25 +27,35 @@ public function manufacturer()
2727
{
2828
return $this->belongsTo(Manufacturer::class);
2929
}
30-
public function iventories():HasMany
30+
public function iventories(): HasMany
3131
{
3232
return $this->hasMany(Iventory::class);
3333
}
3434

35-
public function getTotalstockAttribute():int
35+
public function getTotalstockAttribute(): int
3636

3737
{
38-
return $this->iventories->sum('quantity');
38+
return $this->iventories->sum('quantity');
3939
}
4040

41-
public function getAveragePriceAttribute():float
42-
41+
public function getAveragePriceAttribute(): float
4342
{
44-
$inventories = $this->inventories ?? collect();
45-
$weightedSum = $inventories->sum(fn($inventory) => $inventory->unit_price * $inventory->quantity);
46-
$totalQuantity = $this->total_stock;
43+
// Certifique-se de carregar o relacionamento corretamente
44+
$iventories = $this->iventories;
45+
46+
// Verifique se o relacionamento existe e não está vazio
47+
if (!$iventories || $iventories->isEmpty()) {
48+
return 0;
49+
}
50+
51+
// Calcula a soma ponderada (preço unitário * quantidade)
52+
$weightedSum = $iventories->sum(fn($iventory) => $iventory->unit_price * $iventory->quantity);
53+
54+
// Soma das quantidades
55+
$totalQuantity = $iventories->sum('quantity');
4756

48-
return $totalQuantity > 0 ? $weightedSum / $totalQuantity : 0;
57+
// Retorna o preço médio ou 0 se não houver estoque
58+
return $totalQuantity > 0 ? round($weightedSum / $totalQuantity, 2) : 0;
4959
}
5060

5161
public function invetorytransaction()

0 commit comments

Comments
 (0)