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

349 lines
11 KiB
PHP
Raw Normal View History

2020-11-17 13:41:31 +01:00
<?php
namespace App\Models;
use App\Enums\Order\DeliveryStatus;
use App\Enums\Order\PaymentStatus;
use App\Enums\Order\ValidationStatus;
use App\Notifications\Order\OrderValidationStatusChanged;
use App\Notifications\Order\OrderDeliveryStatusChanged;
use Gloudemans\Shoppingcart\Cart;
2020-11-17 13:41:31 +01:00
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
2022-12-19 16:20:00 +01:00
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Session;
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;
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 array $basket The order serialized basket.
* @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.
* @property integer $total_ttc Total payed fro mthe customer in cents.
* @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.
*
* @property-read boolean $can_be_cancelled Can the order be cancelled ?
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
/**
* The primary key for the model.
*
* @var string
*/
protected $primaryKey = 'uuid';
/**
* 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
];
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',
'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);
static::assertDeliveryStatusCanBeChanged($model);
2022-12-20 16:52:44 +01:00
if ($model->validation_status->value !== $model->getOriginal('validation_status')) {
// * Notifiy customer
$model->customer->notify(new OrderValidationStatusChanged($model));
Session::flash('info', trans('Le client recevra une notification sur l\'état de validation.'));
}
if (
$model->delivery_status->equals(DeliveryStatus::ready()) and
$model->delivery_status->value !== $model->getOriginal('delivery_status')
) {
// * Notifiy customer
$model->customer->notify(new OrderDeliveryStatusChanged($model));
Session::flash('info', trans('Le client recevra une notification sur \'état de livraison.'));
2022-12-20 16:52:44 +01:00
}
2022-10-03 17:13:44 +02:00
});
}
// * RELATIONSHIPS
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
}
2022-12-05 15:21:54 +01:00
// * GETTER
2022-10-03 17:13:44 +02:00
/**
* Getter can_be_cancelled
*
* ! Logique modifiée pour refonte only here (sans paiement)
*
2022-10-03 17:13:44 +02:00
* On peut annuler la commande si le client
* n'as pas payé et que la livraison n'a pas
* encore été initié, et la commande n'est pas
* déjà annulée.
*
* @return boolean
*/
public function getCanBeCancelledAttribute(): bool
{
// * Si le status de validation n'est pas annulé
return $this->getOriginal('validation_status') !== ValidationStatus::cancelled()->value and
// * Si le status de paiement n'est pas payé
2022-12-20 16:52:44 +01:00
!($this->getOriginal('payment_status') === PaymentStatus::payed()->value) and
// * Si le statut de livraison n'est pas récupéré
!($this->getOriginal('delivery_status') === DeliveryStatus::recovered()->value);
2022-10-03 17:13:44 +02:00
}
2022-12-05 15:21:54 +01:00
// * SETTER
/**
* Getter reference
*
* @return void
* @throws \RuntimeException This is readonly.
*/
public function setReferenceAttribute(): void
{
throw new \RuntimeException('Reference is readonly');
}
// * METHODS
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' => self::getUniqueOrderReference()
]
));
}
}
2022-12-19 16:20:00 +01:00
/**
* Generate an unique order reference
*
* @param integer $recursiveIncrement Used for interanl only.
* @return string
*/
private static function getUniqueOrderReference(int $recursiveIncrement = 0): string
{
$counter = Order::whereDate('created_at', Carbon::today())->count() + 1 + $recursiveIncrement;
$reference = Carbon::now()->isoFormat('YYYYMMDD') . str_pad($counter, 4, "0", STR_PAD_LEFT);
if (self::query()->where('reference', $reference)->exists()) {
// * Recursive counter to determinate reference unicity.
return self::getUniqueOrderReference($counter + 1);
}
return $reference;
}
2022-10-03 17:13:44 +02:00
/**
* Check if order can be cancelled
*
* @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 (
!$model->can_be_cancelled and
$model->validation_status->equals(ValidationStatus::cancelled())
) {
2022-12-20 16:52:44 +01:00
throw ValidationException::withMessages([
'messages' => "La commande '{$model->uuid}' ne peut être annulée"
]);
}
}
/**
* 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)
{
if ($model->getOriginal('validation_status') === ValidationStatus::cancelled()->value) {
throw ValidationException::withMessages([
'messages' => "La commande '{$model->uuid}' ne peut être validée après avoir été annulée"
]);
2022-10-03 17:13:44 +02:00
}
}
/**
* Check if delivery status can be changed.
*
* @param self $model
* @return void
* @throws \Illuminate\Validation\ValidationException If the order is canceled while it cannot be.
*/
public static function assertDeliveryStatusCanBeChanged(self $model)
{
$deliveryStatusHasChanged = $model->getOriginal('delivery_status') !== $model->delivery_status->value;
if ($deliveryStatusHasChanged and !$model->validation_status->equals(ValidationStatus::validated())) {
throw ValidationException::withMessages([
'messages' =>
// phpcs:ignore Generic.Files.LineLength.TooLong
"L'état de livraison de la commande ne peut être modifié car la commande '{$model->uuid}' n'est pas validée"
]);
}
if ($model->getOriginal('validation_status') === ValidationStatus::cancelled()->value) {
throw ValidationException::withMessages([
'messages' =>
"L'état de livraison de la commande ne peut être modifié car la commande '{$model->uuid}' est annulée"
]);
}
}
/**
* Get updated current session order
*
* @return null|\App\Models\Order
*/
public static function getCurrentOrder(): ?self
{
/** @var \App\Models\Order|null $order */
if ($order = Session::get('currentOrder')) {
// * Refresh order if exists in DB.
2022-12-19 16:20:00 +01:00
$order = Order::where('uuid', $order->uuid)
->orWhere('reference', $order->ref)
->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());
}
2020-11-17 13:41:31 +01:00
}