Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
72.37% covered (warning)
72.37%
55 / 76
0.00% covered (danger)
0.00%
0 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
Kernel
72.37% covered (warning)
72.37%
55 / 76
0.00% covered (danger)
0.00%
0 / 3
9.35
0.00% covered (danger)
0.00%
0 / 1
 schedule
85.94% covered (warning)
85.94%
55 / 64
0.00% covered (danger)
0.00%
0 / 1
3.03
 commands
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 isWorkingDayOfMonth
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
20
1<?php
2
3namespace App\Console;
4
5use Carbon\Carbon;
6use Illuminate\Console\Scheduling\Schedule;
7use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
8
9class Kernel extends ConsoleKernel
10{
11    /**
12     * Define the application's command schedule.
13     *
14     * @return void
15     */
16    protected function schedule(Schedule $schedule)
17    {
18        // FIRE-1025 / FIRE-977 follow-up: every command below uses
19        // `withoutOverlapping($timeoutMinutes)` so a long-running invocation
20        // never piles a second instance on top of itself. See
21        // routes/console.php for the same protection (mirrored intentionally
22        // — the system cron on master currently dispatches individual artisan
23        // commands directly, but Laravel's scheduler also reads this file
24        // when it's re-enabled).
25
26        // $schedule->command('inspire')->hourly();
27        $schedule->command('presupuestos:sincronizar')->dailyAt('03:00')->withoutOverlapping(60);
28
29        // FIRE-1279 follow-up: the G3W sync above only reclassifies imported
30        // budgets. This sweeps manually-created ("non-gestiona") budgets and
31        // moves bad-email ones into status 22 (Correo erroneo) — and back to
32        // 11 once fixed — so they surface correctly in "Emails con error".
33        // Independent of G3W (no region / g3w_active guard), so it runs even
34        // when the G3W integration is disabled. 05:00 is a free slot after
35        // the 03:00 sync window.
36        $schedule->command('presupuestos:sincronizar-manuales')->dailyAt('05:00')->withoutOverlapping(30);
37        $schedule->command('quotations:sync')
38            ->everyFiveMinutes()
39            ->weekdays() // from monday to friday
40            ->withoutOverlapping(15);
41
42        $schedule->command('ifex-quotations:sync')
43            ->everyFiveMinutes()
44            ->weekdays() // from monday to friday
45            ->withoutOverlapping(15);
46
47        $schedule->command('quotations:sync')
48            ->dailyAt('22:00')
49            ->weekends() // saturday and sunday
50            ->withoutOverlapping(60);
51
52        $schedule->command('quotations:sync-work')->weeklyOn(6, '03:00')->withoutOverlapping(120);
53
54        $schedule->command('update:commercial-numbers')
55            ->everyMinute()
56            ->when(function () {
57                return now()->minute % 3 == 0;
58            })
59            ->withoutOverlapping(5);
60
61        $schedule->command('invoices:send-reminder')->dailyAt('08:00')->withoutOverlapping(60);
62
63        // Approval circuit v2 (SOP §10) — remind approvers of still-pending
64        // budgets. Runs daily; the command enforces the 2-business-day spacing
65        // per budget, so a daily run only actually emails when a reminder is due.
66        $schedule->command('approvals:reminders')->dailyAt('08:30')->withoutOverlapping(30);
67
68        // FIRE-1293 — daily G3W payment-date sync into tbl_invoice_reminders.
69        // Runs at 10:00 so the 08:00 send-reminder cron (withoutOverlapping=60)
70        // has reliably finished. Shares the 'g3w' rate-limit bucket with the
71        // send-reminder job — both target factura/{id}.
72        $schedule->command('invoices:sync-payment-dates')->dailyAt('10:00')->withoutOverlapping(60);
73
74        $schedule->command('invoices:call-center')->dailyAt('18:00')->withoutOverlapping(60);
75
76        $schedule->command('quotations:sync-missing')->dailyAt('06:01')->withoutOverlapping(60);
77
78        // FIRE-977 schedule lives in routes/console.php (Laravel 11+ convention)
79
80        $schedule->command('clear:email-processing')->everyTenMinutes()->withoutOverlapping(15);
81
82        // FIRE-864 — backfill stuck "processed" emails from SendGrid Activity
83        // API. Runs hourly so the cleanup Jorge asked for happens continuously
84        // instead of only when the webhook delivers events. Limit of 200 rows
85        // keeps the API usage bounded.
86        $schedule->command('email:backfill-status --limit=200')->hourly()->withoutOverlapping(50);
87
88        // Berta's audit follow-up: pre-fix `finance:import-drive` and
89        // `finance:send-report --type=weekly` BOTH ran Saturday 04:00, so
90        // they raced. The weekly email frequently went out with stale
91        // data because the Drive import hadn't finished (or its results
92        // weren't yet visible to the report query). Move the import to
93        // Friday 04:00 so the data is settled by Saturday, and the report
94        // sends Saturday 06:00 with margin.
95        $schedule->command('finance:import-drive')->weeklyOn(5, '04:00')->withoutOverlapping(60);
96
97        // Weekly finance report — every Saturday at 06:00 (madrugada) — shows MTD.
98        // The 2h gap vs the Friday import gives time for any slow imports
99        // to land and for the operator to spot-check overnight if needed.
100        $schedule->command('finance:send-report --type=weekly')->weeklyOn(6, '06:00')->withoutOverlapping(60);
101
102        // Monthly finance report — on working day +5 of each month (closed previous month + YTD)
103        $schedule->command('finance:send-report --type=monthly')
104            ->dailyAt('06:00')
105            ->when(fn () => $this->isWorkingDayOfMonth(5))
106            ->withoutOverlapping(60);
107
108        // FIRE-1025 follow-up to FIRE-1001: once-daily janitor for legacy
109        // `acceptance_date = '0000-00-00 00:00:00'` rows. Replaces the 5
110        // in-line sweepers in PresupuestosService.php that were issuing
111        // the same UPDATE at the end of every G3W sync iteration and
112        // deadlocking on `idx_acceptance_date` under concurrency.
113        $schedule->command('quotations:cleanup-zero-dates')->dailyAt('04:30')->withoutOverlapping(30);
114
115        // Disk-full incident 2026-09-28: prune log files no channel rotates.
116        $schedule->command('logs:prune')->dailyAt('03:15')->withoutOverlapping(30);
117
118        // Retention for the external-API request log: keep 15 days, deleted
119        // in 10k-row batches so the middleware's INSERTs aren't blocked.
120        $schedule->command('api-consumer-endpoints:purge')->dailyAt('02:15')->withoutOverlapping(60);
121
122        // FIRE-982: Cofrai sync chain mirrors the G3W cadence so the
123        // second ERP integration has the same observability and safety
124        // posture. Pre-fix these schedules were missing entirely — Cofrai
125        // imports were only ever triggered manually via the UI.
126        $schedule->command('cofrai-quotations:sync')
127            ->everyFiveMinutes()
128            ->weekdays()
129            ->withoutOverlapping(15);
130
131        $schedule->command('cofrai-quotations:sync')
132            ->dailyAt('22:00')
133            ->weekends()
134            ->withoutOverlapping(60);
135
136        $schedule->command('cofrai-quotations:sync-work')->weeklyOn(6, '03:00')->withoutOverlapping(120);
137
138        $schedule->command('cofrai-quotations:retry-failed')->dailyAt('01:00')->withoutOverlapping(30);
139
140        $schedule->command('cofrai-quotations:retry-failed')
141            ->cron('5-59/5 1-5 * * *')
142            ->withoutOverlapping(30);
143
144        // FIRE-1077: Cofrai parallel to quotations:sync-missing.
145        // Offset 1h from G3W's 06:01 to avoid contention.
146        $schedule->command('cofrai-quotations:sync-missing')->dailyAt('07:01')->withoutOverlapping(60);
147
148        $schedule->command('administrators-invoices:sync')
149            ->dailyAt('11:00')
150            ->withoutOverlapping(60)
151            ->when(function () {
152                $today = Carbon::today();
153
154                if ($today->isWeekend()) {
155                    return false;
156                }
157
158                $firstDayOfMonth = Carbon::parse($today->year.'-'.$today->month.'-01');
159
160                $firstWorkDayOfMonth = $firstDayOfMonth;
161                while ($firstWorkDayOfMonth->isWeekend()) {
162                    $firstWorkDayOfMonth->addDay();
163                }
164
165                return $today->toDateString() === $firstWorkDayOfMonth->toDateString();
166            });
167    }
168
169    /**
170     * Register the commands for the application.
171     *
172     * @return void
173     */
174    protected function commands()
175    {
176        $this->load(__DIR__.'/Commands');
177
178        require base_path('routes/console.php');
179    }
180
181    /**
182     * True if today is the Nth working day (Mon-Fri) of the current month.
183     * Used for scheduling the monthly finance report on "WD+5".
184     */
185    private function isWorkingDayOfMonth(int $n): bool
186    {
187        $today = Carbon::today();
188        if ($today->isWeekend()) {
189            return false;
190        }
191        $current = $today->copy()->startOfMonth();
192        $workingDays = 0;
193        while ($current->lte($today)) {
194            if (! $current->isWeekend()) {
195                $workingDays++;
196            }
197            $current->addDay();
198        }
199
200        return $workingDays === $n;
201    }
202}