92 lines
3.4 KiB
PHP
92 lines
3.4 KiB
PHP
<?php
|
|
|
|
namespace App\Jobs;
|
|
|
|
use App\Models\ArchiveCampaign;
|
|
use App\Models\ArchiveCoupon;
|
|
use App\Models\ArchiveStat;
|
|
use App\Models\Statistique;
|
|
use Illuminate\Bus\Queueable;
|
|
use Illuminate\Contracts\Queue\ShouldQueue;
|
|
use Illuminate\Foundation\Bus\Dispatchable;
|
|
use Illuminate\Queue\InteractsWithQueue;
|
|
use Illuminate\Queue\SerializesModels;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\Log;
|
|
|
|
class ArchiveStatsJob implements ShouldQueue
|
|
{
|
|
use Dispatchable;
|
|
use InteractsWithQueue;
|
|
use Queueable;
|
|
use SerializesModels;
|
|
|
|
/**
|
|
* Execute the job.
|
|
*
|
|
* @return void
|
|
*/
|
|
public function handle(): void
|
|
{
|
|
try {
|
|
DB::transaction(function () {
|
|
Statistique::query()
|
|
->where('date', '<', now())
|
|
->each(function (Statistique $stat) {
|
|
$archiveCampaign = ArchiveCampaign::query()->where('campaign_id', $stat->stat_campId)->first();
|
|
$archiveCoupon = ArchiveCoupon::query()->where('coupon_code', $stat->stat_couponId)->first();
|
|
if (!is_null($archiveCampaign) && !is_null($archiveCoupon)) {
|
|
$options = [
|
|
['date', $stat->date],
|
|
['archive_coupon_id', $archiveCoupon->getKey()],
|
|
['archive_campaign_id', $archiveCampaign->getKey()],
|
|
];
|
|
$archiveStat = ArchiveStat::query()->where($options)->first();
|
|
if (!is_null($archiveStat)) {
|
|
$newQuantity = $archiveStat->quantity + $stat->stat_couponPrinted;
|
|
$archiveStat->quantity = $newQuantity;
|
|
$archiveStat->saveOrFail();
|
|
} else {
|
|
$this->createArchiveStat($stat, $archiveCampaign->getKey(), $archiveCoupon->getKey());
|
|
}
|
|
} else {
|
|
$this->createArchiveStat($stat);
|
|
}
|
|
});
|
|
Statistique::query()
|
|
->where('date', '<', now())
|
|
->delete();
|
|
});
|
|
} catch (\Exception $e) {
|
|
Log::error(
|
|
sprintf(
|
|
"ArchiveStatsJob failed - Code : %s - %s",
|
|
$e->getCode(),
|
|
$e->getMessage(),
|
|
)
|
|
);
|
|
\report($e);
|
|
} //end try
|
|
}
|
|
|
|
/**
|
|
* Create a new archive statistique.
|
|
*
|
|
* @param \App\Models\Statistique $stat
|
|
* @param integer|null $archiveCampaignKey
|
|
* @param integer|null $archiveCouponKey
|
|
* @return void
|
|
*/
|
|
private function createArchiveStat(
|
|
Statistique $stat,
|
|
?int $archiveCampaignKey = null,
|
|
?int $archiveCouponKey = null
|
|
): void {
|
|
$newArchiveStat = new ArchiveStat();
|
|
$newArchiveStat->quantity = $stat->stat_couponPrinted;
|
|
$newArchiveStat->date = $stat->date;
|
|
$newArchiveStat->archive_coupon_id = $archiveCouponKey ?? $stat->stat_couponId;
|
|
$newArchiveStat->archive_campaign_id = $archiveCampaignKey ?? $stat->stat_campId;
|
|
$newArchiveStat->saveOrFail();
|
|
}
|
|
}
|