/
itp_practice
/
itp_backend
Обзор
Документация
Войти
/
itp_practice
/
itp_backend
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
master
app/Models/Cart.php
122 строки
3 KB
vivanenko
fix taps and others structure
27 май 2025, 18:06
27 май 2025, 18:06
8cdc7d9
Код
Авторство
О чём код?
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Factories\HasFactory; /** * @property int $id * @property int $user_id * @property \DateTime $created_at * @property \DateTime $updated_at */ class Cart extends Model { use HasFactory; protected $fillable = [ 'user_id', ]; protected $casts = [ 'user_id' => 'integer', ]; public function user(): BelongsTo { return $this->belongsTo(User::class); } public function items(): HasMany { return $this->hasMany(CartItem::class); } /** * Get cart total amount */ public function getTotalAmount(): float { return $this->items->sum(function (CartItem $item) { return $item->getSubtotal(); }); } /** * Get cart items count */ public function getItemsCount(): int { return $this->items->sum('quantity'); } /** * Check if cart is empty */ public function isEmpty(): bool { return $this->items->isEmpty(); } /** * Clear all items from cart */ public function clear(): bool { return $this->items()->delete() > 0; } /** * Calculate total with quantity discounts */ public function getTotalWithDiscounts(): array { $subtotal = 0; $quantityDiscount = 0; foreach ($this->items as $item) { $itemSubtotal = $item->getSubtotal(); $subtotal += $itemSubtotal; // Apply "Buy 5 get 1 free" discount if ($item->quantity >= 5) { $freeTariffs = intval($item->quantity / 5); $quantityDiscount += $freeTariffs * $item->price; } } return [ 'subtotal' => $subtotal, 'quantity_discount' => $quantityDiscount, 'total' => $subtotal - $quantityDiscount, ]; } /** * Convert cart to order items data */ public function toOrderItemsData(): array { return $this->items->map(function (CartItem $item) { $quantity = $item->quantity; $freeTariffs = $quantity >= 5 ? intval($quantity / 5) : 0; return [ 'sku' => $item->sku, 'itemable_type' => $item->itemable_type, 'itemable_id' => $item->itemable_id, 'price' => $item->price, 'quantity' => $quantity, 'free_quantity' => $freeTariffs, 'tax' => $item->tax, 'shipping' => $item->shipping, 'currency' => $item->currency, 'subtotal' => $item->getSubtotal(), 'discount' => $freeTariffs * $item->price, ]; })->toArray(); } }