Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
76.92% covered (warning)
76.92%
50 / 65
33.33% covered (danger)
33.33%
2 / 6
CRAP
0.00% covered (danger)
0.00%
0 / 1
QuotationSendRecorder
76.92% covered (warning)
76.92%
50 / 65
33.33% covered (danger)
33.33%
2 / 6
26.42
0.00% covered (danger)
0.00%
0 / 1
 isSentTransition
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 isErpSend
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 neverSent
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 record
80.00% covered (warning)
80.00%
24 / 30
0.00% covered (danger)
0.00%
0 / 1
9.65
 fallbackToIssueDate
100.00% covered (success)
100.00%
24 / 24
100.00% covered (success)
100.00%
1 / 1
4
 norm
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2
3namespace App\Services;
4
5use App\Models\TblBudgetStatus;
6use App\Models\TblQuotations;
7use App\Models\TblQuotationSends;
8use App\Models\TblQuotationsLog;
9use Illuminate\Support\Facades\DB;
10use Illuminate\Support\Facades\Log;
11
12/**
13 * The single place a send of a quotation is recorded.
14 *
15 * Every caller that sends a quotation, or detects that it was sent elsewhere,
16 * calls record(). It writes one tbl_quotation_sends row and moves
17 * tbl_quotations.sent_date forward to that send. sent_date is the LAST send,
18 * never an earlier one, so a backfill that replays history out of order still
19 * ends on the latest send.
20 *
21 * issue_date is deliberately left alone: it stays the ERP's budget date.
22 */
23class QuotationSendRecorder
24{
25    public const TITAN_EMAIL = 'titan_email';
26
27    public const TITAN_WHATSAPP = 'titan_whatsapp';
28
29    public const G3W_STATUS = 'g3w_status';
30
31    public const COFRAI_STATUS = 'cofrai_status';
32
33    public const MANUAL_STATUS = 'manual_status';
34
35    public const IMPORT = 'import';
36
37    public const ACCEPTANCE = 'acceptance';
38
39    /** budget_status_id values that mean "sent". */
40    public const SENT_STATUS_IDS = [2, 17];          // Enviado, Enviado - IA
41
42    public const ACCEPTED_STATUS_ID = 3;
43
44    /**
45     * A status change that is a send: TO a sent status FROM a different one.
46     * Enviado -> Enviado (the sync re-writing the same status) is not a send.
47     */
48    public static function isSentTransition($oldStatusId, $newStatusId): bool
49    {
50        return in_array((int) $newStatusId, self::SENT_STATUS_IDS, true)
51            && ! in_array((int) $oldStatusId, self::SENT_STATUS_IDS, true);
52    }
53
54    /**
55     * An ERP (Gestiona/Cofrai) send: the ERP's OWN status became Enviado.
56     *
57     * Deliberately keyed on the ERP status name (status_by_g3w / status_by_cofrai),
58     * not on Titan's budget_status_id. When Titan moves a quotation away from
59     * Enviado (auto-rejection, an email bounce, an acceptance) while the ERP
60     * still says Enviado, the next sync puts Titan's status back to Enviado.
61     * That is a revert, not a send, and keying on the ERP status tells them
62     * apart. Re-dating an edited budget in the ERP keeps its status Enviado, so
63     * that is not a send either.
64     */
65    public static function isErpSend(?string $oldErpStatus, ?string $newErpStatus): bool
66    {
67        return self::norm($newErpStatus) === 'enviado' && self::norm($oldErpStatus) !== 'enviado';
68    }
69
70    /**
71     * True only when we KNOW the quotation was never sent: no send recorded, no
72     * sent_date, and the log covers its whole life (its creation row is there).
73     * The log starts on 27 Oct 2025; an older quotation may have been sent
74     * before that with no trace, and "unknown" must not become a fabricated send.
75     */
76    public static function neverSent(int $quotationId): bool
77    {
78        if (TblQuotationSends::where('quotation_id', $quotationId)->exists()) {
79            return false;
80        }
81        if (TblQuotations::where('id', $quotationId)->whereNotNull('sent_date')->exists()) {
82            return false;
83        }
84
85        return TblQuotationsLog::where('quotation_id', $quotationId)
86            ->whereIn('category', ['Crear solicitud', 'Creacion presupuesto'])
87            ->exists();
88    }
89
90    /**
91     * @param  string|\DateTimeInterface|null  $at  when it was sent; now when null
92     * @param  mixed  $amount  the amount at that moment; read from the quotation when null
93     */
94    public static function record(int $quotationId, string $channel, ?string $user, $at = null,
95        $amount = null, string $source = 'live', ?string $sourceRef = null, ?string $status = null): ?TblQuotationSends
96    {
97        try {
98            $at = $at ? date('Y-m-d H:i:s', is_string($at) ? strtotime($at) : $at->getTimestamp()) : date('Y-m-d H:i:s');
99            $q = TblQuotations::where('id', $quotationId)->first(['id', 'amount', 'budget_status_id']);
100            if (! $q) {
101                return null;
102            }
103            if ($sourceRef !== null && TblQuotationSends::where('source_ref', $sourceRef)->exists()) {
104                return null;                                     // backfill re-run
105            }
106
107            $amount = $amount ?? $q->amount;
108            $amount = is_numeric($amount) ? round((float) $amount, 2) : null;
109
110            $row = TblQuotationSends::create([
111                'quotation_id' => $quotationId,
112                'sent_at' => $at,
113                'channel' => $channel,
114                'user' => $user !== null ? mb_substr($user, 0, 100) : null,
115                'amount' => $amount,
116                'status' => $status ?? TblBudgetStatus::where('budget_status_id', $q->budget_status_id)->value('name'),
117                'source' => $source,
118                'source_ref' => $sourceRef,
119                'created_at' => date('Y-m-d H:i:s'),
120            ]);
121
122            // Forward only: sent_date is the latest send.
123            TblQuotations::where('id', $quotationId)
124                ->where(function ($w) use ($at): void {
125                    $w->whereNull('sent_date')->orWhere('sent_date', '<', $at);
126                })
127                ->update(['sent_date' => $at]);
128
129            return $row;
130        } catch (\Throwable $e) {
131            // Never let recording a send break the send itself.
132            Log::warning('QuotationSendRecorder: could not record send', [
133                'quotation_id' => $quotationId, 'channel' => $channel, 'error' => $e->getMessage(),
134            ]);
135
136            return null;
137        }
138    }
139
140    /**
141     * "Sent" with no send on record: sent_date = issue_date, and no
142     * tbl_quotation_sends row, since there is no send to record. Typical case:
143     * a budget already Enviado before the log existed whose issue_date was
144     * later changed by hand (FIRE-2034 KO, 14/10: 13 Valencia budgets). The
145     * KPIs already counted these on issue_date via COALESCE, so no figure moves.
146     *
147     * With $oldIssueDate (a single quotation being re-dated), a sent_date that
148     * was this fallback follows the new issue_date. A sent_date from a real
149     * send has a row in tbl_quotation_sends and is never touched.
150     *
151     * @return int quotations updated
152     */
153    public static function fallbackToIssueDate(?int $quotationId = null, ?string $oldIssueDate = null): int
154    {
155        try {
156            // Plain query builder, not the model: TblQuotations' builder audits
157            // every row an update touches, which ran out of memory on the
158            // first run (~6,900 rows). Same approach as the backfill's legacy step.
159            $base = fn () => DB::table('tbl_quotations')
160                ->whereIn('budget_status_id', self::SENT_STATUS_IDS)
161                ->whereNotNull('issue_date')
162                ->whereNull('deleted_at')
163                ->whereNotExists(fn ($q) => $q->from('tbl_quotation_sends as s')->whereColumn('s.quotation_id', 'tbl_quotations.id'))
164                ->when($quotationId, fn ($q) => $q->where('id', $quotationId));
165
166            $updated = 0;
167            // Chunked by id so each UPDATE locks few rows while the syncs run.
168            $base()->whereNull('sent_date')->select('id')->chunkById(2000, function ($rows) use (&$updated): void {
169                $updated += DB::table('tbl_quotations')
170                    ->whereIn('id', $rows->pluck('id'))
171                    ->whereNull('sent_date')
172                    ->update(['sent_date' => DB::raw('issue_date')]);
173            });
174
175            if ($quotationId && $oldIssueDate) {
176                $updated += $base()
177                    ->whereDate('sent_date', date('Y-m-d', strtotime($oldIssueDate)))
178                    ->whereColumn('sent_date', '<>', 'issue_date')
179                    ->update(['sent_date' => DB::raw('issue_date')]);
180            }
181
182            return $updated;
183        } catch (\Throwable $e) {
184            Log::warning('QuotationSendRecorder: issue_date fallback failed', [
185                'quotation_id' => $quotationId, 'error' => $e->getMessage(),
186            ]);
187
188            return 0;
189        }
190    }
191
192    private static function norm(?string $s): string
193    {
194        return mb_strtolower(trim((string) $s));
195    }
196}