ldc-mesbr-app/app/Models/Coupon.php

78 lines
2.2 KiB
PHP
Raw Normal View History

2023-09-13 16:48:17 +02:00
<?php
namespace App\Models;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class Coupon extends Model
{
// FIXME : Ajouter les mouvement de quantité, mettre juste une colonne et se servir des logs avec un type pour mouvement ?
2023-11-24 15:35:08 +01:00
// FIXME : Ajouter logs impressions.
2023-09-13 16:48:17 +02:00
use HasFactory;
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'start_diffusion_date' => 'date:Y-m-d',
'end_diffusion_date' => 'date:Y-m-d',
'end_validity_date' => 'date:Y-m-d',
];
2023-11-24 15:35:08 +01:00
/**
* Get campaigns that owns the Coupon
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function campaigns(): BelongsToMany
2023-09-13 16:48:17 +02:00
{
return $this->belongsToMany(Campaign::class);
}
/**
* The "booted" method of the model.
2023-11-24 15:35:08 +01:00
*
* @return void
2023-09-13 16:48:17 +02:00
*/
protected static function booted(): void
{
static::creating(function (Coupon $coupon) {
2023-11-24 15:35:08 +01:00
$coupon->can_be_used = self::checkIfCanBeUsed($coupon);
2023-09-13 16:48:17 +02:00
});
static::updating(function (Coupon $coupon) {
2023-11-24 15:35:08 +01:00
$coupon->can_be_used = self::checkIfCanBeUsed($coupon);
2023-09-13 16:48:17 +02:00
});
}
2023-11-24 15:35:08 +01:00
/**
* Check if coupon can be used taking account multiple factors
*
* @param \App\Models\Coupon $coupon
* @return boolean
*/
public static function checkIfCanBeUsed(Coupon $coupon): bool
2023-09-13 16:48:17 +02:00
{
if (
2023-11-24 15:35:08 +01:00
(
is_null($coupon->start_diffusion_date) or
$coupon->start_diffusion_date->lessThanOrEqualTo(Carbon::now())
) and
(
is_null($coupon->end_diffusion_date) or
$coupon->end_diffusion_date->greaterThanOrEqualTo(Carbon::now())) and
(is_null($coupon->end_validity_date) or
$coupon->end_validity_date->greaterThanOrEqualTo(Carbon::now()->addDays($coupon->validity_period))
)
) {
2023-09-13 16:48:17 +02:00
return true;
}
2023-11-24 15:35:08 +01:00
// FIXME : Ajouter calendrier de diffusion et le prendre en compte dans la condition.
2023-09-13 16:48:17 +02:00
return false;
}
}