82 lines
2.3 KiB
PHP
82 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Models\Campagne;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
|
use Illuminate\Support\Str;
|
|
|
|
class Basket extends Model
|
|
{
|
|
use HasFactory;
|
|
|
|
protected $fillable = [
|
|
'campagne_id'
|
|
];
|
|
|
|
/**
|
|
* Customer model relation
|
|
* @return BelongsTo
|
|
*/
|
|
public function customer()
|
|
{
|
|
return $this->belongsTo(Customers::class, 'customer_id', 'id');
|
|
}
|
|
|
|
/**
|
|
* Campagne model relation
|
|
* @return BelongsTo
|
|
*/
|
|
public function campagne()
|
|
{
|
|
return $this->belongsTo(Campagne::class, 'campagne_id', 'camp_id');
|
|
}
|
|
|
|
/**
|
|
* BasketContent model relation
|
|
* @return HasMany
|
|
*/
|
|
public function contents()
|
|
{
|
|
return $this->hasMany(BasketContent::class);
|
|
}
|
|
|
|
public static function updateContent(Campagne $campagne, array $coupons, Customers $customer)
|
|
{
|
|
$basket = self::where(['campagne_id' => $campagne->camp_id, 'customer_id' => $customer->id])->first();
|
|
|
|
if (!$basket) {
|
|
$basket = new Basket();
|
|
$basket->uuid = (string) Str::uuid();
|
|
$basket->campagne()->associate($campagne);
|
|
$basket->customer()->associate($customer);
|
|
$basket->save();
|
|
}
|
|
|
|
foreach ($coupons as $couponId => $quantity) {
|
|
$associatedCoupon = $campagne->coupons()->where('coupon_id', $couponId)->first();
|
|
|
|
if ($associatedCoupon) {
|
|
$basketContent = BasketContent::where(['basket_id' => $basket->id, 'coupon_id' => $associatedCoupon->coupon_id])->first();
|
|
if ($basketContent) {
|
|
$basketContent->quantity += $quantity;
|
|
$basketContent->save();
|
|
} else {
|
|
if ($quantity > 0) {
|
|
$newBasketContent = new BasketContent();
|
|
$newBasketContent->basket_id = $basket->id;
|
|
$newBasketContent->coupon_id = $associatedCoupon->coupon_id;
|
|
$newBasketContent->quantity = $quantity;
|
|
$newBasketContent->save();
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
return $basket;
|
|
}
|
|
}
|