ldc-boutique-cnc/app/Models/Shop/Order.php

889 lines
31 KiB
PHP
Raw Normal View History

2020-11-17 13:41:31 +01:00
<?php
2023-03-01 11:02:42 +01:00
namespace App\Models\Shop;
2020-11-17 13:41:31 +01:00
use App\Enums\Order\DeliveryModeEnum;
use App\Enums\Order\DeliveryStatus;
use App\Enums\Order\PaymentModeEnum;
use App\Enums\Order\PaymentStatus;
use App\Enums\Order\TransactionStatus;
use App\Enums\Order\TransactionType;
use App\Enums\Order\ValidationStatus;
use App\Events\OrderIsValidated;
2023-05-19 19:49:41 +02:00
use App\Http\Controllers\Controller;
use App\Lib\Helpers\ToolboxHelper;
2023-03-01 11:02:42 +01:00
use App\Models\Customer\Customer;
use App\Models\Merchandise\Product;
use App\Models\Payment\Transaction;
use App\Notifications\Order\OrderValidationStatusChanged;
use App\Notifications\Order\OrderDeliveryStatusChanged;
use Gloudemans\Shoppingcart\Cart;
2023-05-19 19:49:41 +02:00
use Gloudemans\Shoppingcart\CartItem;
2020-11-17 13:41:31 +01:00
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Session;
2023-05-23 09:32:54 +02:00
use Illuminate\Support\Str;
2022-12-20 16:52:44 +01:00
use Illuminate\Validation\ValidationException;
2022-10-03 17:13:44 +02:00
use Kwaadpepper\Enum\Traits\CastsEnums;
2023-05-23 09:32:54 +02:00
use Mccarlosen\LaravelMpdf\LaravelMpdf;
use Money\Money;
2020-11-17 13:41:31 +01:00
2022-10-03 17:13:44 +02:00
/**
* Order
*
* @property-read string $reference The order unique reference string.
* @property object $basket The order serialized basket.
* @property object $shipped_basket The order serialized basket delivered to customer.
* @property string $email The customer email used for this order.
* @property boolean $mail_sent Has the confirmation mail been sent to the customer.
2022-12-19 16:20:00 +01:00
* @property object $shipping The shipping address info.
* @property object $billing The billing address info.
* @property integer $total_discounted Total discounted on this order in cents.
2023-03-09 15:04:24 +01:00
* @property integer $total_ttc Total payed from the customer in cents.
* @property integer $total_refund Total refunded to the customer.
* @property integer $total_ht Total without taxes in cents.
* @property integer $total_weight Total weight in gramms.
* @property \App\Enums\Order\ValidationStatus $validation_status The order validation status.
* @property \App\Enums\Order\PaymentStatus $payment_status The order payment status.
* @property \App\Enums\Order\DeliveryStatus $delivery_status The order delivery status.
*
2023-05-16 07:43:17 +02:00
* @property-read boolean $can_be_canceled Can the order be canceled ?
2023-03-16 11:43:21 +01:00
* @property-read boolean $can_be_refund Can the order be refund ?
2023-04-25 21:52:27 +02:00
* @property-read boolean $has_warning The order has a warning ?
2022-10-03 17:13:44 +02:00
*
* @package App\Models
*/
class Order extends Model
2020-11-17 13:41:31 +01:00
{
2022-10-03 17:13:44 +02:00
use CastsEnums;
2020-11-17 13:41:31 +01:00
use HasFactory;
2022-12-19 16:20:00 +01:00
/**
* Indicates if the IDs are auto-incrementing.
*
* @var boolean
*/
public $incrementing = false;
/**
* The "type" of the primary key ID.
*
* @var string
*/
protected $keyType = 'uuid';
/**
* The model's attributes.
*
* @var array
*/
protected $attributes = [
'mail_sent' => false,
'shipped_basket' => '{}',
'total_refund' => 0
2022-12-19 16:20:00 +01:00
];
2022-10-03 17:13:44 +02:00
/**
* Map attribute names to enum classes.
*
* @var array
*/
protected $enumCasts = [
'validation_status' => ValidationStatus::class,
'payment_status' => PaymentStatus::class,
'delivery_status' => DeliveryStatus::class
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
2022-12-19 16:20:00 +01:00
'basket' => 'object',
'shipped_basket' => 'object',
2022-12-19 16:20:00 +01:00
'shipping' => 'object',
'billing' => 'object',
'mail_sent' => 'bool'
];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'shipping',
'billing'
];
2022-10-03 17:13:44 +02:00
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted()
{
static::creating(function (self $model) {
// * ASSERTIONS
static::assertValidateStatus($model);
2022-10-03 17:13:44 +02:00
static::assertCancelStatus($model);
2022-12-20 11:32:06 +01:00
$model->setUniqueOrderReference();
2022-10-03 17:13:44 +02:00
});
static::updating(function (self $model) {
2022-12-20 16:52:44 +01:00
static::assertValidateStatus($model);
2022-10-03 17:13:44 +02:00
static::assertCancelStatus($model);
2022-12-20 16:52:44 +01:00
if ($model->validation_status->equals(ValidationStatus::validated())) {
OrderIsValidated::dispatchUnless($model->mail_sent, $model);
}
/** @var \App\Models\Customer\Customer|null */
$customer = $model->customer;
2022-12-20 16:52:44 +01:00
if ($model->validation_status->value !== $model->getOriginal('validation_status')) {
// * Notifiy customer
$notification = new OrderValidationStatusChanged($model);
if ($customer) {
$model->customer->notify($notification);
} else {
// * AnonymousNotifiable with Notification Fake
Notification::route('mail', $model->email)->notifyNow($notification);
}
Session::flash('bo.info', trans('Le client recevra une notification sur l\'état de validation.'));
} //end if
// * Commande est annulée
if (
$model->validation_status->value !== $model->getOriginal('validation_status') and
2023-05-16 07:43:17 +02:00
$model->validation_status->equals(ValidationStatus::canceled())
) {
// * Set le timeslot as soft deleted
$model->timeslot()->delete();
2023-05-16 08:13:10 +02:00
$model->delivery_status = DeliveryStatus::canceled();
// ? La transaction utilisée est inShop ?
$transaction = $model->getTransactionUsedForPayment();
2023-05-19 12:11:38 +02:00
if ($transaction and $transaction->payment_mode->equals(PaymentModeEnum::inShop())) {
2023-05-16 08:13:10 +02:00
// * Set la transaction en annulée.
2023-05-19 19:49:41 +02:00
$transaction->status = TransactionStatus::canceled();
$model->payment_status = PaymentStatus::canceled();
2023-05-16 08:13:10 +02:00
$transaction->saveQuietly();
}
}
// * Empecher la réactivation d'une commande (car le timeslot aura été perdu).
if (
2023-05-16 07:43:17 +02:00
$model->getOriginal('validation_status') === ValidationStatus::canceled()->value and
!$model->validation_status->equals(ValidationStatus::canceled())
) {
throw new \Error('This is not allowed');
2022-12-20 16:52:44 +01:00
}
2023-05-16 08:57:35 +02:00
// * Commande est prête.
if (
$model->delivery_status->equals(DeliveryStatus::ready()) and
!$model->payment_status->equals(PaymentStatus::failed()) and
!$model->payment_status->equals(PaymentStatus::canceled())
) {
// * Notifiy customer
$notification = new OrderDeliveryStatusChanged($model);
if ($customer) {
$model->customer->notify($notification);
} else {
// * AnonymousNotifiable with Notification Fake
Notification::route('mail', $model->email)->notifyNow($notification);
}
Session::flash('bo.info', trans('Le client recevra une notification sur l\'état de livraison.'));
}
2022-10-03 17:13:44 +02:00
});
static::deleting(function () {
throw new \Error('This is not allowed');
});
2022-10-03 17:13:44 +02:00
}
/**
* Get the route key for the model.
*
* @return string
*/
public function getRouteKeyName()
{
return 'reference';
}
2022-10-03 17:13:44 +02:00
// * RELATIONSHIPS
/**
* HasMany transactions relation
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function transactions()
{
return $this->hasMany(Transaction::class);
}
2021-03-27 20:55:16 +01:00
/**
2022-09-03 16:56:16 +02:00
* BelongsToMany products relation
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
2021-03-27 20:55:16 +01:00
*/
2022-08-25 12:26:43 +02:00
public function products()
{
2021-03-27 20:55:16 +01:00
return $this->belongsToMany(Product::class, 'order_lines', 'order_id', 'product_id');
}
2022-09-03 16:56:16 +02:00
/**
* BelongsTo customer relation
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
2022-08-25 12:26:43 +02:00
public function customer()
{
return $this->belongsTo(Customer::class);
2021-03-29 15:10:07 +02:00
}
2022-12-05 15:21:54 +01:00
/**
* BelongsTo DeliveryMode relation
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function deliveryMode()
{
return $this->belongsTo(DeliveryMode::class);
}
2022-09-03 16:56:16 +02:00
/**
* hasOne timeslot relation
*
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
2021-03-29 15:10:07 +02:00
public function timeslot()
{
return $this->hasOne(Timeslot::class);
2020-11-17 13:41:31 +01:00
}
/**
* hasOne timeslot relation
*
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function trashedTimeslot()
{
return $this->timeslot()->withTrashed();
}
2022-12-05 15:21:54 +01:00
// * GETTER
2022-10-03 17:13:44 +02:00
/**
2023-05-16 07:43:17 +02:00
* Getter can_be_canceled
2022-10-03 17:13:44 +02:00
*
* ! Logique modifiée pour refonte only here (sans paiement)
*
* On peut annuler la commande si :
* - la livraison n'a pas encore été initié
* - la commande n'est pas déjà annulée
2022-10-03 17:13:44 +02:00
*
* @return boolean
*/
2023-05-16 08:33:17 +02:00
public function getCanBeCanceledAttribute(): bool
2022-10-03 17:13:44 +02:00
{
// * Si le status de validation n'est pas annulé
2023-05-16 07:43:17 +02:00
return $this->getOriginal('validation_status') !== ValidationStatus::canceled()->value &&
// * Si le statut de livraison n'est pas récupéré
2023-05-16 08:33:17 +02:00
!\in_array($this->getOriginal('delivery_status'), [
DeliveryStatus::recovered()->value,
DeliveryStatus::canceled()->value,
]);
2022-10-03 17:13:44 +02:00
}
2023-03-16 11:43:21 +01:00
/**
* Getter can_be_refund
*
*
* On peut rembourser la commande si le montant déjà remboursé est inférieur au montant payé
*
* @return boolean
*/
public function getCanBeRefundAttribute(): bool
{
return $this->total_ttc > $this->total_refund and
2023-05-19 12:11:38 +02:00
!\in_array($this->getOriginal('payment_status'), [
PaymentStatus::refunded()->value,
PaymentStatus::canceled()->value,
PaymentStatus::failed()->value,
2023-05-16 08:33:17 +02:00
]);
2023-03-16 11:43:21 +01:00
}
2023-04-25 21:52:27 +02:00
/**
* Getter has_warning
*
* Une des transactions de la commande doit être validée avant de continuer.
*
* @return boolean
*/
public function getHasWarningAttribute(): bool
{
return $this->transactions()
->where('needs_validation', true)
->where('type', TransactionType::credit())
->exists();
}
2022-12-05 15:21:54 +01:00
// * SETTER
/**
2023-04-25 21:52:27 +02:00
* Setter reference
2022-12-05 15:21:54 +01:00
*
* @return void
* @throws \RuntimeException This is readonly.
*/
public function setReferenceAttribute(): void
{
throw new \RuntimeException('Reference is readonly');
}
2023-04-25 21:52:27 +02:00
/**
* Setter has_warning
*
* @return void
* @throws \RuntimeException This is readonly.
*/
public function setHasWarningAttribute(): void
{
throw new \RuntimeException('has_warning is readonly');
}
2022-12-05 15:21:54 +01:00
// * METHODS
2023-05-25 13:45:30 +02:00
/**
* Get refunded items
*
* @return \Illuminate\Support\Collection
*/
public function getRefundedItems(): Collection
{
/** @var \Illuminate\Support\Collection<object> */
$orderedItems = clone \collect($this->basket);
// * Collect refunded transaction items.
$unRefundedTransactionItems = $this->getUnrefundedItems();
$unRefundedTransactionsQtys = \collect();
$orderedItems->each(function (object $basktemItem) use (
$unRefundedTransactionItems,
$unRefundedTransactionsQtys
) {
$qty = 0;
if ($unRefundedTransactionItems->has($basktemItem->rowId)) {
$qty = $unRefundedTransactionItems->get($basktemItem->rowId)->qty;
}
$basktemItem->qty -= $qty;
$unRefundedTransactionsQtys->put($basktemItem->rowId, $basktemItem);
});
/** @var \Illuminate\Support\Collection<string,integer> */
$remainingItems = \collect();
$unRefundedTransactionsQtys->each(function (
object $basketItem
) use (
$remainingItems
) {
$qty = $basketItem->qty;
$remainingItems->put(
$basketItem->rowId,
$qty
);
});
$remainingItems = $remainingItems->filter();
return \collect(ToolboxHelper::updateBasketAmounts(
$this->basket,
$remainingItems->toArray()
));
}
2023-04-25 21:52:27 +02:00
/**
2023-05-25 20:04:46 +02:00
* Get unrefunded items (items that are mot part of a validated credit transaction)
2023-04-25 21:52:27 +02:00
*
* @return \Illuminate\Support\Collection<object>
*/
2023-05-25 13:45:30 +02:00
public function getUnrefundedItems(): Collection
2023-05-25 20:04:46 +02:00
{
/** @var \Illuminate\Support\Collection<object> */
$orderedItems = \collect($this->basket);
/** @var \Illuminate\Support\Collection<object> */
$refundedTransactionsItems = $this->transactions()
->where('status', '!=', TransactionStatus::canceled())
->where('type', TransactionType::credit())
->pluck('items')->map(function ($basketItems) {
return (object)\collect($basketItems)
->filter(function (object $basketItem) {
return !\optional($basketItem->options)->virtual;
})->toArray();
});
// * Collect refunded transaction items.
$refundedTransactionsQtys = \collect();
$refundedTransactionsItems->each(function (object $basktemItems) use ($refundedTransactionsQtys) {
\collect($basktemItems)->each(function (object $basktemItem) use ($refundedTransactionsQtys) {
$qty = 0;
if ($refundedTransactionsQtys->has($basktemItem->rowId)) {
$qty = $refundedTransactionsQtys->get($basktemItem->rowId)->qty;
}
$basktemItem->qty += $qty;
$refundedTransactionsQtys->put($basktemItem->rowId, $basktemItem);
});
});
/** @var \Illuminate\Support\Collection<string,integer> */
$remainingItems = \collect();
$orderedItems->each(function (
object $basketItem
) use (
$refundedTransactionsQtys,
$remainingItems
) {
$qty = $basketItem->qty;
if ($refundedTransactionsQtys->contains('id', $basketItem->id)) {
$qty -= $refundedTransactionsQtys->where('id', $basketItem->id)->first()->qty;
}
$remainingItems->put(
$basketItem->rowId,
$qty
);
});
$remainingItems = $remainingItems->filter();
return \collect(ToolboxHelper::updateBasketAmounts(
$orderedItems,
$remainingItems->toArray()
));
}
/**
* Get remaining unrefunded items
*
* @return \Illuminate\Support\Collection<object>
*/
public function getRemainingUnrefundedItems(): Collection
2023-04-25 21:52:27 +02:00
{
/** @var \Illuminate\Support\Collection<object> */
$orderedItems = \collect($this->basket);
/** @var \Illuminate\Support\Collection<object> */
$shippedTransactionsItems = \collect($this->shipped_basket)->filter();
2023-04-25 21:52:27 +02:00
/** @var \Illuminate\Support\Collection<object> */
2023-05-25 13:45:30 +02:00
$refundedTransactionsItems = $this->transactions()
->where('status', '!=', TransactionStatus::canceled())
->where('type', TransactionType::credit())
2023-05-25 20:04:46 +02:00
->pluck('items')->map(function ($basketItems) {
2023-04-25 21:52:27 +02:00
return (object)\collect($basketItems)
->filter(function (object $basketItem) {
return !\optional($basketItem->options)->virtual;
})->toArray();
});
// * Collect shipped transaction items.
$shippedTransactionsQtys = \collect();
$shippedTransactionsItems->each(function (object $basktemItem) use ($shippedTransactionsQtys) {
$qty = 0;
if ($shippedTransactionsQtys->has($basktemItem->rowId)) {
$qty = $shippedTransactionsQtys->get($basktemItem->rowId)->qty;
}
$basktemItem->qty += $qty;
$shippedTransactionsQtys->put($basktemItem->rowId, $basktemItem);
});
2023-04-25 21:52:27 +02:00
// * Collect refunded transaction items.
$refundedTransactionsQtys = \collect();
$refundedTransactionsItems->each(function (object $basktemItems) use ($refundedTransactionsQtys) {
\collect($basktemItems)->each(function (object $basktemItem) use ($refundedTransactionsQtys) {
$qty = 0;
if ($refundedTransactionsQtys->has($basktemItem->rowId)) {
$qty = $refundedTransactionsQtys->get($basktemItem->rowId)->qty;
}
$basktemItem->qty += $qty;
$refundedTransactionsQtys->put($basktemItem->rowId, $basktemItem);
});
});
/** @var \Illuminate\Support\Collection<string,integer> */
$remainingItems = \collect();
$orderedItems->each(function (
object $basketItem
) use (
$shippedTransactionsQtys,
2023-04-25 21:52:27 +02:00
$refundedTransactionsQtys,
$remainingItems
) {
$qty = $basketItem->qty;
if ($shippedTransactionsQtys->contains('id', $basketItem->id)) {
$qty -= $shippedTransactionsQtys->where('id', $basketItem->id)->first()->qty;
}
2023-04-25 21:52:27 +02:00
if ($refundedTransactionsQtys->contains('id', $basketItem->id)) {
$qty -= $refundedTransactionsQtys->where('id', $basketItem->id)->first()->qty;
}
$remainingItems->put(
$basketItem->rowId,
$qty
);
});
$remainingItems = $remainingItems->filter();
return \collect(ToolboxHelper::updateBasketAmounts(
$orderedItems,
$remainingItems->toArray()
));
}
2023-05-19 19:49:41 +02:00
/**
* Get remaining unrefunded items + Refunds from Payment system backend
* ! for final complete refund only.
*
* * Diff between Basket - all credit transactions items
*
* @return \Illuminate\Support\Collection<object>
*/
2023-05-23 09:32:54 +02:00
public function getItemForOrderCancelling(): Collection
2023-05-19 19:49:41 +02:00
{
2023-05-25 20:04:46 +02:00
// * Calculate taxes using items that are not in a refund transaction.
2023-05-25 13:45:30 +02:00
$itemsToRefund = $this->getUnrefundedItems();
$remainingTaxToRefund = \intval($itemsToRefund->sum(function ($basketItem) {
2023-05-23 10:17:42 +02:00
$basketItem = (object)$basketItem;
2023-05-25 13:45:30 +02:00
// * Arrondi a l'entier le plus proche
return round($basketItem->qty * $basketItem->tax);
2023-05-23 10:17:42 +02:00
}));
2023-05-19 19:49:41 +02:00
2023-05-25 20:04:46 +02:00
// * Real remaining amount to refund.
$remainingToRefund = $this->getTotalPayed()->subtract(
$this->getTotalRefunded()
)->getAmount();
2023-05-19 19:49:41 +02:00
// * Créer un dummy product pour représenter la transaction.
$cartItemOptions = \array_merge(Controller::$cartItemOptionsSkel, [
'virtual' => true,
'price_ttc' => $remainingToRefund,
]);
$cartItem = CartItem::fromArray([
'id' => \str_replace('.', '', \uniqid('', true)),
'name' => trans('Remboursement complet'),
'price' => $remainingToRefund,
'weight' => 0,
2023-05-23 10:17:42 +02:00
'options' => $cartItemOptions,
2023-05-19 19:49:41 +02:00
]);
$cartItem->setQuantity(1);
// * Négation du prix
2023-05-23 09:32:54 +02:00
$basketItem = \json_decode($cartItem->toJson());
2023-05-19 19:49:41 +02:00
$basketItem->price = $basketItem->price * -1;
$basketItem->options->price_ttc = $basketItem->options->price_ttc * -1;
$basketItem->subtotal = $basketItem->subtotal * -1;
2023-05-23 10:17:42 +02:00
$basketItem->tax = $remainingTaxToRefund * -1;
2023-05-23 19:08:52 +02:00
$basketItem->subtotal = $basketItem->price;
2023-05-19 19:49:41 +02:00
2023-05-23 09:48:55 +02:00
return collect()->add($basketItem)->values();
2023-05-23 09:32:54 +02:00
}
/**
* Fetch all transaction items
* ! For final bill.
*
* @return \Illuminate\Support\Collection<object>
*/
public function getAllTransactionsItems(): Collection
{
// * Negate all items prices (already refunded)
$orderedItems = \collect(\optional($this->getTransactionUsedForPayment())->items);
2023-05-23 09:32:54 +02:00
/** @var \Illuminate\Support\Collection<object> */
$refundedTransactionsItems = $this->transactions()
->where('type', TransactionType::credit())
2023-05-25 20:04:46 +02:00
->where('status', '!=', TransactionStatus::canceled())
->where('status', '!=', TransactionStatus::failed())
2023-05-23 09:32:54 +02:00
->pluck('items');
$final = \collect($orderedItems);
$refundedTransactionsItems->each(function ($items) use (&$final) {
$final = $final->concat(\collect($items));
});
2023-05-19 19:49:41 +02:00
return $final->values();
}
/**
* Check if the Order is or will be completely refunded using a transaction.
*
* @param \App\Models\Payment\Transaction $transaction
* @return boolean
*/
public function isCompleteRefundWithTransaction(Transaction $transaction): bool
{
$zeroAmount = new Money(0, app('phpMoneyCurrency'));
$lastAmount = clone $zeroAmount;
// * Transactions de remboursement.
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Payment\Transaction> */
2023-05-25 20:04:46 +02:00
$refundTransactions = $this->transactions()
->where('type', TransactionType::credit())
->where('status', '!=', TransactionStatus::canceled())
->where('status', '!=', TransactionStatus::failed())
->where('id', '!=', $transaction->id)
->get(['id', 'amount', 'currency']);
// * Détermination du dernier montant remboursé.
if (
!$refundTransactions->contains(function (Transaction $refundTransaction) use ($transaction) {
return $refundTransaction === $transaction->id;
})
) {
// * La transaction n'est pas enregistrée, le dernier montant remboursé sera notre transaction.
$lastAmount = $transaction->amount;
}
/** @var \Money\Money */
2023-05-25 20:04:46 +02:00
$totalRembourse = $refundTransactions->reduce(function ($previous, Transaction $actual) {
/** @var \Money\Money|null $previous */
/** @var \App\Models\Payment\Transaction $actual */
$out = new Money(0, app('phpMoneyCurrency'));
if ($previous) {
$out = $out->add($previous);
}
if ($actual->type->equals(TransactionType::credit())) {
$out = $out->add($actual->amount);
}
return $out;
}) ?? new Money(0, app('phpMoneyCurrency'));
$totalCommande = (new Money($this->total_ttc, app('phpMoneyCurrency')));
// * Total commande - (total rembousé jusqu'ici + dernier montant a être rembousé).
$resteDevantEtreRembourse = $totalCommande->subtract($totalRembourse->add($lastAmount));
return $resteDevantEtreRembourse->lessThanOrEqual($zeroAmount);
}
/**
* Get the transaction used for payment
*
* @return null|\App\Models\Payment\Transaction
*/
public function getTransactionUsedForPayment(): ?Transaction
{
2023-05-24 17:54:15 +02:00
$query = $this->transactions()->orderBy('created_at', 'DESC');
/** @var \App\Models\Payment\Transaction|null $transaction */
2023-05-24 17:54:15 +02:00
$transaction = (clone $query)->where('type', TransactionType::debit())
->where('status', TransactionStatus::validated())->first();
// If no paid transaction there is, try to fetch an inshop transaction.
if (!$transaction and $this->deliveryMode->mode->equals(DeliveryModeEnum::inShop())) {
2023-05-24 17:54:15 +02:00
$transaction = (clone $query)->where('type', TransactionType::debit())
->where('payment_mode', PaymentModeEnum::inShop())
->where('status', TransactionStatus::pending())
->first();
}
2023-05-19 12:11:38 +02:00
// If no paid transaction there is, try to fetch the last failed or canceled debit transaction.
if (!$transaction and $this->deliveryMode->mode->equals(DeliveryModeEnum::inShop())) {
2023-05-24 17:54:15 +02:00
$transaction = (clone $query)->where('type', TransactionType::debit())
2023-05-19 12:11:38 +02:00
->where('payment_mode', '!=', PaymentModeEnum::inShop())
->whereIn('status', [TransactionStatus::failed(), TransactionStatus::canceled()])
->first();
}
return $transaction;
}
/**
* Total payed by the customer
*
* @return \Money\Money
*/
public function getTotalPayed(): Money
{
2023-05-25 20:04:46 +02:00
return $this->transactions()
->where('status', '!=', TransactionStatus::canceled())
->where('status', '!=', TransactionStatus::failed())
->get()
->reduce(function ($previous, Transaction $actual) {
/** @var \Money\Money|null $previous */
/** @var \App\Models\Payment\Transaction $actual */
$out = new Money(0, app('phpMoneyCurrency'));
if ($previous) {
$out = $out->add($previous);
}
if (
$actual->type->equals(TransactionType::debit()) and
!$actual->payment_mode->equals(PaymentModeEnum::inShop()) and
$actual->status->equals(TransactionStatus::validated())
) {
$out = $out->add($actual->amount);
}
return $out;
}) ?? new Money(0, app('phpMoneyCurrency'));
}
/**
* Total refunded to the customer
*
* @return \Money\Money
*/
public function getTotalRefunded(): Money
{
2023-05-25 20:04:46 +02:00
return $this->transactions()
->where('status', '!=', TransactionStatus::canceled())
->where('status', '!=', TransactionStatus::failed())
->get()->reduce(function ($previous, Transaction $actual) {
/** @var \Money\Money|null $previous */
/** @var \App\Models\Payment\Transaction $actual */
$out = new Money(0, app('phpMoneyCurrency'));
if ($previous) {
$out = $out->add($previous);
}
if ($actual->type->equals(TransactionType::credit())) {
$out = $out->add($actual->amount);
}
return $out;
}) ?? new Money(0, app('phpMoneyCurrency'));
}
2023-05-25 11:11:17 +02:00
/**
* Total ttc
*
* @return \Money\Money
*/
public function getTotalTtc(): Money
{
$totalTax = \intval(\collect(\optional($this->getTransactionUsedForPayment())->items)
->sum('subtotal'));
return new Money($totalTax, app('phpMoneyCurrency'));
}
/**
* Total refunded to the customer
*
* @return \Money\Money
*/
public function getTotalTax(): Money
{
$totalTax = \intval(\collect(\optional($this->getTransactionUsedForPayment())->items)
->sum(function (object $item) {
return $item->tax * $item->qty;
}));
return new Money($totalTax, app('phpMoneyCurrency'));
}
2022-12-20 11:32:06 +01:00
/**
* Setup reference
*
* @return void
*/
public function setUniqueOrderReference()
{
if (!$this->reference) {
$this->setRawAttributes(\array_merge(
$this->attributes,
[
'reference' => ToolboxHelper::getUniqueReference(self::class)
2022-12-20 11:32:06 +01:00
]
));
}
}
2022-10-03 17:13:44 +02:00
/**
2023-05-16 07:43:17 +02:00
* Check if order can be canceled
2022-10-03 17:13:44 +02:00
*
* @param self $model
* @return void
2022-12-20 16:52:44 +01:00
* @throws \Illuminate\Validation\ValidationException If the order is canceled while it cannot be.
2022-10-03 17:13:44 +02:00
*/
public static function assertCancelStatus(self $model)
{
if (
2023-05-16 07:43:17 +02:00
!$model->can_be_canceled and
$model->validation_status->equals(ValidationStatus::canceled())
2022-10-03 17:13:44 +02:00
) {
throw ValidationException::withMessages([
'messages' => "La commande '{$model->id}' ne peut être annulée"
]);
}
if (
2023-05-16 07:43:17 +02:00
$model->validation_status->equals(ValidationStatus::canceled()) and
$model->getTransactionUsedForPayment()->payment_mode->equals(PaymentModeEnum::inShop()) and
!\in_array($model->payment_status, [PaymentStatus::failed(), PaymentStatus::pending()])
) {
throw ValidationException::withMessages([
'messages' =>
"La commande '{$model->id}' ne peut être annulée car le remboursement click and collect n'est pas géré"
2022-12-20 16:52:44 +01:00
]);
}
}
/**
* Check if order can be validated
*
* @param self $model
* @return void
* @throws \Illuminate\Validation\ValidationException If the order is canceled while it cannot be.
*/
public static function assertValidateStatus(self $model)
{
2023-05-16 07:43:17 +02:00
if ($model->getOriginal('validation_status') === ValidationStatus::canceled()->value) {
2022-12-20 16:52:44 +01:00
throw ValidationException::withMessages([
'messages' => "La commande '{$model->id}' ne peut être validée après avoir été annulée"
2022-12-20 16:52:44 +01:00
]);
2022-10-03 17:13:44 +02:00
}
}
/**
* Get updated current session order
*
2023-03-01 11:02:42 +01:00
* @return null|\App\Models\Shop\Order
*/
public static function getCurrentOrder(): ?self
{
2023-03-01 11:02:42 +01:00
/** @var \App\Models\Shop\Order|null $order */
if ($order = Session::get('currentOrder')) {
// * Refresh order if exists in DB.
$order = Order::query()->where('id', $order->id)
->orWhere('reference', $order->reference)
->first() ?? $order;
}
return $order;
}
/**
* Inject the basket items into the order.
*
* @param \Gloudemans\Shoppingcart\Cart $basket
* @return void
* @throws \Illuminate\Validation\ValidationException If a product from the basket is not accessible anymore.
*/
public function assignBasket(Cart $basket): void
{
$this->basket = $basket->content();
$this->total_discounted = \intval($basket->discount());
$this->total_ttc = \intval($basket->total());
$this->total_ht = \intval($this->total_ttc - $basket->tax());
$this->total_weight = \intval($basket->weight());
}
2023-05-23 09:32:54 +02:00
/**
* Generate final Invoice
*
* @param string $title
* @return \Mccarlosen\LaravelMpdf\LaravelMpdf
*/
public function generateInvoice(string $title): LaravelMpdf
{
return ToolboxHelper::generateInvoice(
$this,
$this->created_at,
$title,
Str::ucfirst(\trans('facture')),
$this->getAllTransactionsItems(),
$this->reference
);
}
2020-11-17 13:41:31 +01:00
}