Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
49 / 49
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
QuotationsSync
100.00% covered (success)
100.00%
49 / 49
100.00% covered (success)
100.00%
2 / 2
8
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 handle
100.00% covered (success)
100.00%
48 / 48
100.00% covered (success)
100.00%
1 / 1
7
1<?php
2
3namespace App\Console\Commands;
4
5use App\Jobs\SyncG3WRegion;
6use App\Services\PresupuestosService;
7use Illuminate\Console\Command;
8use Illuminate\Support\Facades\Log;
9
10class QuotationsSync extends Command
11{
12    /**
13     * The name and signature of the console command.
14     *
15     * @var string
16     */
17    protected $signature = 'quotations:sync {date?} {name?} {region?}';
18
19    /**
20     * Default G3W regions synced when no region argument is supplied.
21     * Single source of truth — kept here (not inlined in handle()) so callers
22     * and tests can reference the canonical list instead of duplicating it.
23     *
24     * @var list<string>
25     */
26    public const DEFAULT_REGIONS = ['Cataluña', 'Madrid', 'Comunidad Valenciana', 'Andalucía', 'Baleares', 'Castellón', 'Aragón'];
27
28    /**
29     * The console command description.
30     *
31     * @var string
32     */
33    protected $description = 'Synchronizes budgets for the specified date';
34
35    /**
36     * @var PresupuestosService
37     */
38    protected $presupuestoService;
39
40    /**
41     * Create a new command instance.
42     */
43    public function __construct(private readonly PresupuestosService $presupuestosService)
44    {
45        parent::__construct();
46    }
47
48    /**
49     * Execute the console command.
50     */
51    public function handle(): int
52    {
53        $date = $this->argument('date') ?? date('Y-m-d');
54        $name = $this->argument('name') ?? 'System';
55        $regions = $this->argument('region') ? explode(',', $this->argument('region')) : self::DEFAULT_REGIONS;
56
57        $cronStart = microtime(true);
58
59        // FIRE-1151: dispatch one job per region.
60        // - Under QUEUE_CONNECTION=sync (today), jobs run inline: same shape
61        //   and timing as the old foreach.
62        // - Under QUEUE_CONNECTION=redis + a worker (after FIRE-1147 ops setup),
63        //   jobs run in parallel on the 'g3w' queue. Per-region wall-time is
64        //   still logged from inside the job (SyncG3WRegion::handle) so we
65        //   can see each region's duration in either mode.
66        //
67        // Each dispatch is isolated. Under QUEUE_CONNECTION=sync the job runs
68        // INLINE and re-throws, so before this try/catch a single failing
69        // region aborted the whole loop: with Cataluña first in
70        // DEFAULT_REGIONS, one bad region silently stopped the other five from
71        // ever being attempted, on every run. One region failing must degrade
72        // the sync, not stop it.
73        $dispatched = [];
74        $disabled = [];
75        $failed = [];
76
77        foreach ($regions as $region) {
78            try {
79                SyncG3WRegion::dispatch($date, $name, $region)->onQueue('g3w');
80                $dispatched[] = $region;
81            } catch (\Throwable $e) {
82                // Throwable, not Exception, so PHP Errors (TypeError etc.)
83                // surface here instead of bubbling out — same reasoning as
84                // IfexQuotationsSync.
85                //
86                // A region with g3W_active off throws by design
87                // (PresupuestosService::syncByDate), and that fires every 5
88                // minutes. Reporting it would drown Sentry, so it is logged at
89                // warning rather than error and is not reported. It is NOT
90                // downgraded to info: a missing or renamed company row for the
91                // region raises the identical message, so this line has to stay
92                // visible in prod, where LOG_LEVEL is warning.
93                if (str_contains($e->getMessage(), 'debe estar desactivada')) {
94                    $disabled[] = $region;
95
96                    Log::channel('g3w')->warning('quotations:sync region not active', [
97                        'region' => $region,
98                        'date' => $date,
99                        'note' => 'g3W_active off, or no company row resolves for this region',
100                    ]);
101
102                    continue;
103                }
104
105                $failed[$region] = $e->getMessage();
106
107                Log::channel('g3w')->error('quotations:sync region failed', [
108                    'region' => $region,
109                    'date' => $date,
110                    'error' => $e->getMessage(),
111                ]);
112
113                // Route through the exception handler so Sentry sees it. The
114                // absence of this is why the sync could stop for days without
115                // anyone noticing.
116                report($e);
117            }
118        }
119
120        // One line carrying the state of every region, so a single grep answers
121        // "which regions ran today" instead of inferring it from what is absent.
122        Log::channel('g3w')->info('quotations:sync dispatched', [
123            'regions' => count($regions),
124            'dispatched' => $dispatched,
125            'disabled' => $disabled,
126            'failed' => array_keys($failed),
127            'date' => $date,
128            'dispatch_ms' => (int) round((microtime(true) - $cronStart) * 1000),
129        ]);
130
131        if ($failed !== []) {
132            $this->error(sprintf(
133                'quotations:sync completed with %d of %d region(s) failing: %s',
134                count($failed),
135                count($regions),
136                implode(', ', array_keys($failed)),
137            ));
138
139            return Command::FAILURE;
140        }
141
142        $this->info(sprintf(
143            'quotations:sync dispatched %d region(s)%s.',
144            count($dispatched),
145            $disabled === [] ? '' : ', skipped '.count($disabled).' inactive',
146        ));
147
148        return Command::SUCCESS;
149    }
150}