Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
56.16% covered (warning)
56.16%
41 / 73
25.00% covered (danger)
25.00%
1 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
QuotationSendHistory
56.16% covered (warning)
56.16%
41 / 73
25.00% covered (danger)
25.00%
1 / 4
215.57
0.00% covered (danger)
0.00%
0 / 1
 arrivedSent
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
3
 sends
62.50% covered (warning)
62.50%
35 / 56
0.00% covered (danger)
0.00%
0 / 1
90.43
 isRevert
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
30
 amountAt
50.00% covered (danger)
50.00%
4 / 8
0.00% covered (danger)
0.00%
0 / 1
6.00
1<?php
2
3namespace App\Services;
4
5/**
6 * Rebuilds one quotation's sends from its tbl_quotations_log rows. Pure: no
7 * database access, so every rule below is unit-tested
8 * (tests/Unit/QuotationSendHistoryTest.php). The backfill command feeds it.
9 *
10 * The rules mirror what the live code paths record from now on:
11 *
12 *   - 'send_email_to_client' log row      -> a Titan send (email / WhatsApp)
13 *   - status TO Enviado / Enviado - IA FROM a different status:
14 *       by a person                       -> manual_status
15 *       by the sync (user G3W, or System,
16 *       which the sync logged as before
17 *       March 2026)                       -> g3w_status, UNLESS it is a revert
18 *   - imported with the budget already Enviado (G3W 'Creacion presupuesto' and
19 *     the first known status is Enviado) -> import, at the import time
20 *   - never sent, then Aceptado           -> acceptance, at that change
21 *
22 * A REVERT is the sync putting Enviado back after Titan (not Gestiona) moved
23 * the quotation away from it: an auto-rejection, an email bounce, a manual
24 * acceptance while Gestiona still says Enviado. Gestiona did not change, so it
25 * is not a send. Two shapes in the log:
26 *   1. the previous status row moved it FROM Enviado TO the status the sync now
27 *      reverts, made by someone other than the sync;
28 *   2. the previous status row left it IN Enviado, so the status the sync now
29 *      reverts was set without a log entry (the auto-rejection cron writes none).
30 * Going forward the sync keys on status_by_g3w instead (see
31 * QuotationSendRecorder::isErpSend), which sees this directly; the log has no
32 * status_by_g3w history, hence these rules for the past.
33 */
34class QuotationSendHistory
35{
36    public const SENT = ['Enviado', 'Enviado - IA'];
37
38    public const SYNC_USERS = ['G3W', 'System'];
39
40    /**
41     * @param  array<int,array{id:int,created_at:string,user:?string,field:?string,old_value:?string,new_value:?string,category:?string}>  $rows
42     *                                                                                                                                            this quotation's log rows, any order
43     * @param  string|null  $sendChannel  tbl_quotations.send_channel, to tell a WhatsApp send from an email one
44     * @param  mixed  $currentAmount  tbl_quotations.amount now
45     * @return array<int,array{sent_at:string,channel:string,user:?string,amount:?float,status:string,source_ref:string}>
46     */
47    /**
48     * A quotation whose status never changed after import arrived sent when
49     * it is Enviado now, or "Correo erroneo" while Gestiona says Enviado (the
50     * sync wrote 22 at import because of the email, FIRE-864).
51     */
52    private static function arrivedSent(?string $currentStatus, ?string $currentStatusByG3w): bool
53    {
54        return in_array($currentStatus, self::SENT, true)
55            || ($currentStatus === 'Correo erroneo' && $currentStatusByG3w === 'Enviado');
56    }
57
58    public static function sends(int $quotationId, array $rows, ?string $sendChannel, $currentAmount,
59        ?string $currentStatus = null, ?string $currentStatusByG3w = null): array
60    {
61        usort($rows, fn ($a, $b) => [$a['created_at'], $a['id']] <=> [$b['created_at'], $b['id']]);
62
63        $status = array_values(array_filter($rows, fn ($r) => $r['field'] === 'budget_status_id'));
64        $amounts = array_values(array_filter($rows, fn ($r) => $r['field'] === 'amount'));
65        $out = [];
66        $add = function (array $r, string $channel, string $statusAfter, string $ref) use (&$out, $amounts, $currentAmount): void {
67            $out[] = [
68                'sent_at' => $r['created_at'],
69                'channel' => $channel,
70                'user' => $r['user'],
71                'amount' => self::amountAt($r['created_at'], $r['id'], $amounts, $currentAmount),
72                'status' => $statusAfter,
73                'source_ref' => $ref,
74            ];
75        };
76
77        // Import already Enviado. The first status row's old_value is the status
78        // the quotation arrived with, unless a Titan send (which sets Enviado
79        // without a status log row) came before that row.
80        $creation = null;
81        foreach ($rows as $r) {
82            if ($r['category'] === 'Creacion presupuesto' && in_array($r['user'], self::SYNC_USERS, true)) {
83                $creation = $r;
84                break;
85            }
86        }
87        if ($creation) {
88            $firstStatus = $status[0] ?? null;
89            $titanBefore = false;
90            foreach ($rows as $r) {
91                if ($firstStatus && [$r['created_at'], $r['id']] >= [$firstStatus['created_at'], $firstStatus['id']]) {
92                    break;
93                }
94                if ($r['field'] === 'send_email_to_client') {
95                    $titanBefore = true;
96                    break;
97                }
98            }
99            if ($firstStatus && ! $titanBefore && in_array($firstStatus['old_value'], self::SENT, true)) {
100                $add($creation, QuotationSendRecorder::IMPORT, 'Enviado', 'import:'.$quotationId);
101            } elseif (! $firstStatus && ! $titanBefore && self::arrivedSent($currentStatus, $currentStatusByG3w)) {
102                // No status row at all: the status never changed after import,
103                // so the status it has now is the one it arrived with. Without
104                // this, every budget imported already Enviado that stayed there
105                // (most of them) had no send and dropped out of "issued".
106                $add($creation, QuotationSendRecorder::IMPORT, 'Enviado', 'import:'.$quotationId);
107            } elseif (! $firstStatus && ! $titanBefore && $currentStatus === 'Aceptado') {
108                // Imported already accepted and never changed: no send on record,
109                // so the acceptance (at import) is the send.
110                $add($creation, QuotationSendRecorder::ACCEPTANCE, 'Aceptado', 'import:'.$quotationId);
111            }
112        }
113
114        $wholeLife = (bool) array_filter($rows, fn ($r) => in_array($r['category'], ['Crear solicitud', 'Creacion presupuesto'], true));
115
116        $prev = null;
117        foreach ($rows as $r) {
118            if ($r['field'] === 'send_email_to_client') {
119                $channel = $sendChannel === 'whatsapp' ? QuotationSendRecorder::TITAN_WHATSAPP : QuotationSendRecorder::TITAN_EMAIL;
120                $add($r, $channel, 'Enviado', 'log:'.$r['id']);
121
122                continue;
123            }
124            if ($r['field'] !== 'budget_status_id') {
125                continue;
126            }
127            $toSent = in_array($r['new_value'], self::SENT, true) && ! in_array($r['old_value'], self::SENT, true);
128            if ($toSent) {
129                if (in_array($r['user'], self::SYNC_USERS, true)) {
130                    if (! self::isRevert($r, $prev)) {
131                        $add($r, QuotationSendRecorder::G3W_STATUS, (string) $r['new_value'], 'log:'.$r['id']);
132                    }
133                } else {
134                    $add($r, QuotationSendRecorder::MANUAL_STATUS, (string) $r['new_value'], 'log:'.$r['id']);
135                }
136            } elseif ($r['user'] === 'G3W' && $r['new_value'] === 'Correo erroneo'
137                && ! in_array($r['old_value'], array_merge(self::SENT, ['Correo erroneo']), true)) {
138                // Gestiona moved to Enviado but the client's email is invalid, so
139                // the sync wrote 22 instead (PresupuestosService, FIRE-864). It is
140                // still Gestiona's send. Only user 'G3W': the older 'System' label
141                // is shared with syncManualBudgetEmailStatus, which sets 22 on
142                // manual quotes that were never sent.
143                $add($r, QuotationSendRecorder::G3W_STATUS, 'Correo erroneo', 'log:'.$r['id']);
144            } elseif ($r['new_value'] === 'Aceptado' && $r['old_value'] !== 'Aceptado' && ! $out && $wholeLife) {
145                // Only when the log covers the quotation's whole life: the log
146                // starts on 27 Oct 2025, and an older quotation may well have been
147                // sent before that with no trace here. Unknown is left unsent.
148
149                $add($r, QuotationSendRecorder::ACCEPTANCE, 'Aceptado', 'log:'.$r['id']);
150            }
151            $prev = $r;
152        }
153
154        return $out;
155    }
156
157    public static function isRevert(array $row, ?array $prev): bool
158    {
159        if ($prev === null) {
160            return false;
161        }
162        // Shape 2: the quotation was Enviado and left it without a log row.
163        if (in_array($prev['new_value'], self::SENT, true)) {
164            return true;
165        }
166
167        // Shape 1: someone other than the sync moved it from Enviado to X; the sync puts it back.
168        return $prev['new_value'] === $row['old_value']
169            && in_array($prev['old_value'], self::SENT, true)
170            && ! in_array($prev['user'], self::SYNC_USERS, true);
171    }
172
173    /**
174     * The amount at a moment: the value set by the latest amount change at or
175     * before it; before any change, the first change's old value; with no
176     * changes at all, the amount today.
177     */
178    public static function amountAt(string $at, int $id, array $amounts, $currentAmount): ?float
179    {
180        $value = null;
181        foreach ($amounts as $a) {
182            if ([$a['created_at'], $a['id']] <= [$at, $id]) {
183                $value = $a['new_value'];
184            } else {
185                $value = $value ?? $a['old_value'];
186                break;
187            }
188        }
189        $value = $value ?? $currentAmount;
190
191        return is_numeric($value) ? round((float) $value, 2) : null;
192    }
193}