Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
25.64% covered (danger)
25.64%
20 / 78
50.00% covered (danger)
50.00%
2 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
SendApprovalReminders
25.64% covered (danger)
25.64%
20 / 78
50.00% covered (danger)
50.00%
2 / 4
240.50
0.00% covered (danger)
0.00%
0 / 1
 handle
0.00% covered (danger)
0.00%
0 / 34
0.00% covered (danger)
0.00%
0 / 1
42
 pendingApprovers
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
12
 approverEmails
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 sendReminder
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
20
1<?php
2
3namespace App\Console\Commands;
4
5use App\Services\ResultCache;
6use App\Services\SendgridDispatcher;
7use Carbon\Carbon;
8use Illuminate\Console\Command;
9use Illuminate\Support\Facades\DB;
10use Illuminate\Support\Facades\Log;
11use SendGrid\Mail\Mail;
12
13/**
14 * Approval circuit v2 (SOP §10) — reminders.
15 *
16 * "Recordatorio al aprobador: a los 2 días laborables sin respuesta; solo al
17 * aprobador; se repite cada 2 días laborables hasta que se resuelva."
18 *
19 * Runs daily; the 2-business-day spacing is enforced here (per budget) so a
20 * daily schedule only actually emails when a reminder is due. A budget is
21 * "pending" while `for_approval` is set; whichever approver slot is still open
22 * (technical V1 / financial V2) gets reminded. Resolution (approve / reject /
23 * drops below threshold) clears `for_approval`, ending the reminders.
24 */
25class SendApprovalReminders extends Command
26{
27    protected $signature = 'approvals:reminders {--days=2 : Business-day gap between reminders}';
28
29    protected $description = 'Remind approvers about budgets still pending approval, every N business days.';
30
31    public function handle(): int
32    {
33        $gap = (int) $this->option('days');
34
35        // Candidates: still pending, and an approval request was actually sent.
36        //
37        // A recorded rejection in EITHER slot ends the circuit (SOP §15: an
38        // Operations rejection must never advance the quote to Finance), so it
39        // disqualifies the row here regardless of what `for_approval` still
40        // says. Without this, a budget left flagged by an older rejection —
41        // `pendingApprovers()` only closes the slot that did the rejecting —
42        // kept the OTHER slot open and reminded Finance about a budget
43        // Operations had already killed.
44        $pending = DB::table('tbl_quotations')
45            ->whereNotNull('for_approval')
46            ->where('for_approval', '!=', 0)
47            ->whereNull('rejected_by')
48            ->whereNull('rejected_by_v2')
49            // A cancelled, rejected or duplicate budget needs no approval, even
50            // if its flag was never cleared (same rule as the quotes list).
51            ->where(fn ($q) => $q->whereNull('budget_status_id')->orWhereNotIn('budget_status_id', [4, 7, 18, 20]))
52            ->whereNotNull('approval_requested_at')
53            ->get([
54                'id', 'quote_id', 'company_id', 'amount', 'for_approval', 'approval_type',
55                'approved_by', 'rejected_by', 'approved_by_v2', 'rejected_by_v2',
56                'approval_requested_at', 'approval_last_reminded_at',
57            ]);
58
59        $totalSent = 0;
60
61        foreach ($pending as $q) {
62            $since = $q->approval_last_reminded_at ?? $q->approval_requested_at;
63            if ($since === null) {
64                continue;
65            }
66
67            // Only remind once the business-day gap has elapsed since the last
68            // reminder (or the original request).
69            if (Carbon::parse($since)->diffInWeekdays(Carbon::now()) < $gap) {
70                continue;
71            }
72
73            $recipients = $this->pendingApprovers($q);
74            if (empty($recipients)) {
75                continue;
76            }
77
78            if ($this->sendReminder($q, $recipients)) {
79                DB::table('tbl_quotations')
80                    ->where('id', $q->id)
81                    ->update(['approval_last_reminded_at' => Carbon::now(), 'updated_at' => date('Y-m-d H:i:s')]);
82                $totalSent++;
83            }
84        }
85
86        ResultCache::forgetDomain(['quotations', 'users']);
87        Log::channel('daily')->info("approvals:reminders sent {$totalSent} reminder(s).");
88        $this->info("Sent {$totalSent} reminder(s).");
89
90        return self::SUCCESS;
91    }
92
93    /**
94     * The email addresses of the approver(s) whose slot is still open for this
95     * budget: technical (V1) while its slot is empty on a type 1 or 3 request;
96     * financial (V2) while its slot is empty on a type 2 request, or on a type 3
97     * request once the technical approval is given.
98     *
99     * @return array<int, string>
100     */
101    private function pendingApprovers(object $q): array
102    {
103        $emails = [];
104
105        // Same rule as Quotations::approverActingType(): approval_type is
106        // authoritative (for_approval only flags "pending"). Before, financial-
107        // only quotes (type 2) never reminded Finance, and Finance was reminded
108        // about dual quotes it could not act on yet (dual is sequential:
109        // Operations first, then Finance).
110        $type = $q->approval_type !== null ? (int) $q->approval_type : (int) $q->for_approval;
111        $technicalApproved = ($q->approved_by ?? '') !== '';
112
113        $technicalOpen = ($type === 1 || $type === 3)
114            && ! $technicalApproved
115            && $q->rejected_by === null;
116
117        $financialOpen = (($q->approved_by_v2 ?? '') === '')
118            && $q->rejected_by_v2 === null
119            && ($type === 2 || ($type === 3 && $technicalApproved && $q->rejected_by === null));
120
121        if ($technicalOpen) {
122            $emails = array_merge($emails, $this->approverEmails('tbl_approvers', (int) $q->company_id));
123        }
124        if ($financialOpen) {
125            $emails = array_merge($emails, $this->approverEmails('tbl_approvers_v2', (int) $q->company_id));
126        }
127
128        return array_values(array_unique(array_filter($emails)));
129    }
130
131    /** @return array<int, string> */
132    private function approverEmails(string $table, int $companyId): array
133    {
134        // FIRE-1539: skip inactivated users so approval reminders don't reach
135        // dead inboxes. is_active is nullable-default-1 so NULL rows still pass.
136        return DB::table($table.' as a')
137            ->join('tbl_users as u', 'a.user_id', '=', 'u.id')
138            ->where('a.company_id', $companyId)
139            ->where(fn ($q) => $q->whereNull('u.is_active')->orWhere('u.is_active', 1))
140            ->pluck('u.email')
141            ->all();
142    }
143
144    /**
145     * @param  array<int, string>  $recipients
146     */
147    private function sendReminder(object $q, array $recipients): bool
148    {
149        $amount = number_format((float) $q->amount, 2, ',', '.');
150        $url = config('app.frontend_url')."orders/{$q->id}?company_id={$q->company_id}";
151
152        $email = new Mail;
153        $email->setFrom('fire@fire.es', 'Fire Service Titan');
154        $email->setSubject("Recordatorio: el presupuesto #{$q->quote_id} sigue pendiente de tu aprobación");
155        foreach ($recipients as $to) {
156            $email->addTo($to);
157        }
158
159        $body = '<p>Hola,</p>'
160            ."<p>El presupuesto <b>#{$q->quote_id}</b> por <b>{$amount} €</b> sigue pendiente de tu aprobación.</p>"
161            ."<p><a href=\"{$url}\">Revisar y aprobar</a></p>"
162            .'<p style="font-size:12px;color:#6b7280">La aprobación se realiza dentro del presupuesto, desde este enlace.</p>'
163            .'<p>Fire Service Titan</p>';
164
165        $html = '<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body>'.$body.'</body></html>';
166        $email->addContent('text/html', $html);
167
168        try {
169            // FIRE-1930: gated by the approval_notifications_active flag
170            // of the target company's region. A gated send returns null
171            // and is treated as "not sent" — the caller (handle()) will
172            // NOT bump approval_last_reminded_at, so once the switch is
173            // flipped back on the next cron run re-attempts the same
174            // budgets. That's the desired "cortar al momento" behaviour.
175            $response = SendgridDispatcher::send(
176                $email,
177                SendgridDispatcher::BUCKET_APPROVAL,
178                (int) $q->company_id,
179                'SendApprovalReminders::sendReminder',
180            );
181
182            return $response !== null && $response->statusCode() == 202;
183        } catch (\Throwable $e) {
184            Log::channel('daily')->error("approvals:reminders failed for #{$q->quote_id}: ".$e->getMessage());
185
186            return false;
187        }
188    }
189}