'date:Y-m-d', 'end_diffusion_date' => 'date:Y-m-d', 'end_validity_date' => 'date:Y-m-d', ]; /** * Get campaigns that owns the Coupon * * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function campaigns(): BelongsToMany { return $this->belongsToMany(Campaign::class); } /** * The "booted" method of the model. * * @return void */ protected static function booted(): void { static::creating(function (Coupon $coupon) { $coupon->can_be_used = self::checkIfCanBeUsed($coupon); }); static::updating(function (Coupon $coupon) { $coupon->can_be_used = self::checkIfCanBeUsed($coupon); }); } /** * Check if coupon can be used taking account multiple factors * * @param \App\Models\Coupon $coupon * @return boolean */ public static function checkIfCanBeUsed(Coupon $coupon): bool { if ( ( 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)) ) ) { return true; } // FIXME : Ajouter calendrier de diffusion et le prendre en compte dans la condition. return false; } }