'integer', 'user_id' => 'integer', 'total' => 'decimal:2', ]; } /** * @return BelongsTo */ public function tenant(): BelongsTo { return $this->belongsTo(Tenant::class, 'tenant_codigo', 'codigo'); } /** * @return BelongsTo */ public function user(): BelongsTo { return $this->belongsTo(User::class); } /** * @return BelongsTo */ public function cart(): BelongsTo { return $this->belongsTo(Cart::class, 'cart_id'); } /** * @return HasMany */ public function items(): HasMany { return $this->hasMany(PurchaseItem::class, 'compra_id'); } /** * @return HasOne */ public function telepagosQr() { return $this->hasOne(TelepagosQr::class, 'compra_id'); } /** * @return HasMany */ public function telepagosPayments(): HasMany { return $this->hasMany(TelepagosPayment::class, 'compra_id'); } public function getTotalAmount(): float { if ($this->total !== null) { return (float) $this->total; } return $this->calculateCurrentTotalAmount(); } public function calculateCurrentTotalAmount(): float { if ($this->relationLoaded('items') && $this->getRelation('items')->isNotEmpty()) { return (float) $this->getRelation('items')->sum('total'); } if ($this->items()->exists()) { return (float) $this->items()->sum('total'); } $cart = $this->relationLoaded('cart') ? $this->getRelation('cart') : $this->cart()->with(['items.catalogItem', 'items.variant'])->first(); if (! $cart) { return 0.0; } return $cart->getTotalAmount(); } public function markAsPendingPayment(): void { $this->update([ 'status' => self::STATUS_PENDING_PAYMENT, ]); } public function markAsPaid(): void { DB::transaction(function (): void { $currentStatus = self::query() ->whereKey($this->getKey()) ->lockForUpdate() ->value('status'); if ($currentStatus === self::STATUS_PAID) { $this->status = self::STATUS_PAID; return; } $this->update([ 'status' => self::STATUS_PAID, ]); PurchasePaid::dispatch($this); }); } }