64 lines
1.8 KiB
PHP
64 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Exception;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
|
|
class Reduction extends Model
|
|
{
|
|
public $fillable = [
|
|
'code', 'name', 'value', 'used',
|
|
'desktop_image_available', 'mobile_image_available'
|
|
];
|
|
|
|
public function products()
|
|
{
|
|
return $this->belongsToMany(Products::class, 'reduction_config', 'reduction_id', 'product_id');
|
|
}
|
|
|
|
public function notifiable()
|
|
{
|
|
return $this->morphOne(Notifications::class, 'notifiable');
|
|
}
|
|
|
|
public function ranges()
|
|
{
|
|
return $this->belongsToMany(Range::class, 'reduction_config', 'reduction_id', 'range_id');
|
|
}
|
|
|
|
public static function updateBr()
|
|
{
|
|
// On récupère les réductions depuis MesBR
|
|
/** @var \App\Lib\MesBR */
|
|
$mesBR = app('mesBR');
|
|
$mesBrReduction = $mesBR->getMur();
|
|
|
|
if ($mesBrReduction->status !== 'OK' or !isset($mesBrReduction->coupons)) {
|
|
throw new Exception('Mes BR call failed getMur');
|
|
}
|
|
|
|
$coupons = collect($mesBrReduction->coupons);
|
|
|
|
// get all reductions models
|
|
$dbReduction = Reduction::all();
|
|
|
|
// remove non existent reductions
|
|
foreach ($dbReduction as $dbReduction) {
|
|
if (!($coupon = $coupons->where('code', $dbReduction->code)->first())) {
|
|
$dbReduction->delete();
|
|
} else {
|
|
$dbReduction->fill(\json_decode(\json_encode($coupon), true));
|
|
$dbReduction->saveOrFail();
|
|
$coupons->forget([$coupons->search(function ($i) use ($coupon) {
|
|
return $coupon->code == $i->code;
|
|
})]);
|
|
}
|
|
}
|
|
|
|
// save all new coupons
|
|
foreach ($coupons as $coupon) {
|
|
(new Reduction(\json_decode(\json_encode($coupon), true)))->saveOrFail();
|
|
}
|
|
}
|
|
}
|