102 lines
2.5 KiB
PHP
102 lines
2.5 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Console\Commands;
|
|
|
|
use App\Enums\SyncStatus;
|
|
use Illuminate\Console\Command;
|
|
use App\Enums\WbEndpoint;
|
|
use App\Models\SyncState;
|
|
use Illuminate\Support\Carbon;
|
|
use Illuminate\Support\Facades\Artisan;
|
|
|
|
final class SyncAllCommand extends Command
|
|
{
|
|
/**
|
|
* The name and signature of the console command.
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $signature = 'sync:all';
|
|
|
|
/**
|
|
* The console command description.
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $description = 'Command description';
|
|
|
|
/**
|
|
* Execute the console command.
|
|
*/
|
|
public function handle(): int
|
|
{
|
|
$this->syncEndpoint(WbEndpoint::ORDERS, 'sync:orders');
|
|
$this->syncEndpoint(WbEndpoint::SALES, 'sync:sales');
|
|
$this->syncEndpoint(WbEndpoint::INCOMES, 'sync:incomes');
|
|
|
|
$this->syncStocks();
|
|
|
|
return self::SUCCESS;
|
|
}
|
|
|
|
private function syncEndpoint(WbEndpoint $endpoint, string $command): void
|
|
{
|
|
$yesterday = Carbon::yesterday();
|
|
|
|
$lastSuccess = SyncState::query()
|
|
->where('entity', $endpoint->name)
|
|
->where('status', SyncStatus::SUCCESS)
|
|
->orderByDesc('date_to')
|
|
->first();
|
|
|
|
if (!$lastSuccess) {
|
|
$dateFrom = Carbon::now()->subYears(2);
|
|
$dateTo = $yesterday;
|
|
} else {
|
|
$dateFrom = Carbon::parse($lastSuccess->date_to);
|
|
$dateTo = $dateFrom->copy()->addDay();
|
|
|
|
if ($dateTo->gt($yesterday)) {
|
|
$dateTo = $yesterday->copy();
|
|
}
|
|
}
|
|
|
|
if ($dateFrom->gte($yesterday)) {
|
|
$this->info("$endpoint->name already up-to-date");
|
|
return;
|
|
}
|
|
|
|
$this->info("Syncing $endpoint->name from {$dateFrom->toDateString()} to {$dateTo->toDateString()}");
|
|
|
|
Artisan::call($command, [
|
|
'--dateFrom' => $dateFrom->toDateString(),
|
|
'--dateTo' => $dateTo->toDateString(),
|
|
]);
|
|
}
|
|
|
|
|
|
private function syncStocks(): void
|
|
{
|
|
$today = Carbon::today()->toDateString();
|
|
|
|
$lastSuccess = SyncState::query()
|
|
->where('entity', WbEndpoint::STOCKS->name)
|
|
->where('status', SyncStatus::SUCCESS)
|
|
->where('date_from', $today)
|
|
->first();
|
|
|
|
if ($lastSuccess) {
|
|
$this->info("STOCKS already synced for today");
|
|
return;
|
|
}
|
|
|
|
$this->info("Syncing STOCKS for today");
|
|
|
|
Artisan::call('sync:stocks', [
|
|
'--date' => $today,
|
|
]);
|
|
}
|
|
}
|