@@ -27,25 +27,35 @@ public function manufacturer()
27
27
{
28
28
return $ this ->belongsTo (Manufacturer::class);
29
29
}
30
- public function iventories ():HasMany
30
+ public function iventories (): HasMany
31
31
{
32
32
return $ this ->hasMany (Iventory::class);
33
33
}
34
34
35
- public function getTotalstockAttribute ():int
35
+ public function getTotalstockAttribute (): int
36
36
37
37
{
38
- return $ this ->iventories ->sum ('quantity ' );
38
+ return $ this ->iventories ->sum ('quantity ' );
39
39
}
40
40
41
- public function getAveragePriceAttribute ():float
42
-
41
+ public function getAveragePriceAttribute (): float
43
42
{
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 ' );
47
56
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 ;
49
59
}
50
60
51
61
public function invetorytransaction ()
0 commit comments