120 lines
2.8 KiB
PHP
120 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace App\Domains\Purchase\Models;
|
|
|
|
use App\Domains\Auth\Models\User;
|
|
use App\Domains\Cart\Models\Cart;
|
|
use App\Domains\Tenant\Models\Tenant;
|
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
|
use Illuminate\Support\Collection;
|
|
|
|
#[Fillable([
|
|
'cart_id',
|
|
'tenant_codigo',
|
|
'user_id',
|
|
'status',
|
|
'payment_status',
|
|
'payment_method',
|
|
'dni',
|
|
'telefono',
|
|
'nombre_apellido',
|
|
'email',
|
|
])]
|
|
class Purchase extends Model
|
|
{
|
|
use HasFactory;
|
|
|
|
protected $table = 'compras';
|
|
|
|
protected function casts(): array
|
|
{
|
|
return [
|
|
'cart_id' => 'integer',
|
|
'user_id' => 'integer',
|
|
];
|
|
}
|
|
|
|
/**
|
|
* @return BelongsTo<Tenant, $this>
|
|
*/
|
|
public function tenant(): BelongsTo
|
|
{
|
|
return $this->belongsTo(Tenant::class, 'tenant_codigo', 'codigo');
|
|
}
|
|
|
|
/**
|
|
* @return BelongsTo<User, $this>
|
|
*/
|
|
public function user(): BelongsTo
|
|
{
|
|
return $this->belongsTo(User::class);
|
|
}
|
|
|
|
/**
|
|
* @return BelongsTo<Cart, $this>
|
|
*/
|
|
public function cart(): BelongsTo
|
|
{
|
|
return $this->belongsTo(Cart::class, 'cart_id')->withTrashed();
|
|
}
|
|
|
|
/**
|
|
* @return HasMany<PurchaseItem, $this>
|
|
*/
|
|
public function items(): HasMany
|
|
{
|
|
return $this->hasMany(PurchaseItem::class, 'compra_id');
|
|
}
|
|
|
|
/**
|
|
* @return \Illuminate\Database\Eloquent\Relations\HasOne<TelepagosQr, $this>
|
|
*/
|
|
public function telepagosQr()
|
|
{
|
|
return $this->hasOne(TelepagosQr::class, 'compra_id');
|
|
}
|
|
|
|
/**
|
|
* @return HasMany<TelepagosPayment, $this>
|
|
*/
|
|
public function telepagosPayments(): HasMany
|
|
{
|
|
return $this->hasMany(TelepagosPayment::class, 'compra_id');
|
|
}
|
|
|
|
public function getTotalAmount(): float
|
|
{
|
|
if ($this->items()->exists()) {
|
|
return (float) $this->items()->sum('total');
|
|
}
|
|
|
|
$cart = $this->relationLoaded('cart') ? $this->getRelation('cart') : $this->cart;
|
|
|
|
if ($cart === null) {
|
|
return 0.0;
|
|
}
|
|
|
|
/** @var Collection<int, mixed> $items */
|
|
$items = $cart->relationLoaded('items')
|
|
? $cart->getRelation('items')
|
|
: $cart->items()->with('variant.product')->get();
|
|
|
|
return $items->reduce(
|
|
static fn (float $carry, $item): float => $carry + ((float) ($item->variant?->product?->precio ?? 0) * (int) $item->cantidad),
|
|
0.0,
|
|
);
|
|
}
|
|
|
|
public function finalize(): void
|
|
{
|
|
$this->update([
|
|
'status' => 'pagado', // Or the equivalent final status in your system
|
|
'payment_status' => 'paid',
|
|
]);
|
|
}
|
|
}
|