Repair stats jobs migration

This commit is contained in:
Jérémy Munsch 2021-10-29 17:31:27 +02:00
parent c97b61cc65
commit 41943a6db8
No known key found for this signature in database
GPG key ID: 55196BEE445F6049

View file

@ -0,0 +1,62 @@
<?php
use App\Jobs\SetServiceStats;
use App\Models\ServiceStat;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
class RepairStatsJobs extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$jobIDS = [];
$page = 1;
$perPage = 200;
$total = DB::table('jobs')->count();
$totalPages = ceil($total / $perPage);
do {
$jobs = DB::table('jobs')->paginate($perPage, ['*'], 'page', $page++);
foreach ($jobs as $job) {
$payload = json_decode($job->payload);
if ($payload->displayName === SetServiceStats::class) {
$ref = new ReflectionProperty(SetServiceStats::class, 'service');
$ref->setAccessible(true);
$service = $ref->getValue(unserialize($payload->data->command));
$date = Carbon::parse($job->created_at)->format('Y-m-d');
$serviceStat = ServiceStat::whereDate('date', $date)
->where('service_id', $service->id)->where('brand_id', $service->brand->id)
->firstOrNew();
$serviceStat->date = $date;
if (!$serviceStat->exists) {
$serviceStat->service()->associate($service);
$serviceStat->brand()->associate($service->brand);
}
$serviceStat->nb_calls += 1;
$serviceStat->saveOrFail();
}
}
DB::table('jobs')->whereIn('id', $jobIDS)
->delete();
$jobIDS = [];
} while ($page <= $totalPages);
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}