Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
98.06% covered (success)
98.06%
202 / 206
87.50% covered (warning)
87.50%
21 / 24
CRAP
0.00% covered (danger)
0.00%
0 / 1
ZeusBridge
98.06% covered (success)
98.06%
202 / 206
87.50% covered (warning)
87.50%
21 / 24
75
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 createQuotation
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 updateQuotation
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
1
 getQuotation
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 getFiles
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 downloadFile
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
2
 listQuotations
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
3
 listMasterData
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 shouldReturnZeusResponse
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
4
 resolveRegion
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
8
 shouldForward
92.31% covered (success)
92.31%
12 / 13
0.00% covered (danger)
0.00%
0 / 1
7.02
 isBridgedRegion
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 forwardRead
100.00% covered (success)
100.00%
27 / 27
100.00% covered (success)
100.00%
1 / 1
8
 companyOfQuotation
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 regionFromRequest
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
5
 forward
100.00% covered (success)
100.00%
26 / 26
100.00% covered (success)
100.00%
1 / 1
4
 replayFields
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 replayFiles
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 record
96.88% covered (success)
96.88%
31 / 32
0.00% covered (danger)
0.00%
0 / 1
8
 zeusQuotationId
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
4
 redact
66.67% covered (warning)
66.67%
4 / 6
0.00% covered (danger)
0.00%
0 / 1
4.59
 caller
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 normalize
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 intOrNull
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2
3namespace App\Services;
4
5use App\Models\TblAuthUsers;
6use App\Models\TblCompanies;
7use App\Models\TblFiles;
8use App\Models\TblQuotations;
9use App\Models\TblZeusBridgeLog;
10use Illuminate\Database\Eloquent\Model;
11use Illuminate\Http\Client\Response;
12use Illuminate\Http\Request;
13use Illuminate\Support\Carbon;
14use Illuminate\Support\Facades\Log;
15
16/**
17 * Titan → Zeus bridge: decides whether an incoming operation belongs to a
18 * region that has moved to Zeus and, if so, replays the very same request the
19 * third party sent to Zeus's public API before Titan handles it itself.
20 *
21 * Design notes
22 * ------------
23 * - **Titan stays the single entry point.** Third parties keep calling the same
24 *   Titan URLs with the same credentials and get the same responses. They are
25 *   never told anything, and nothing on their side changes.
26 * - **Titan is just another third party to Zeus.** We speak only Zeus's
27 *   documented API, so once the trial is validated each integration can be
28 *   repointed to Zeus one at a time instead of everything moving at once.
29 * - **Never fatal.** In `mirror` mode a Zeus failure is logged and swallowed:
30 *   Titan writes as it always has and the third party sees the response it
31 *   expects. A Zeus outage must never become a Titan outage.
32 * - **Reversible at any moment.** `ZEUS_BRIDGE_ENABLED=false` returns Titan to
33 *   handling Madrid itself, with nothing lost, because `mirror` mode has been
34 *   keeping Titan's own copy all along.
35 *
36 * @see config/zeus.php for every switch this class reads
37 */
38class ZeusBridge
39{
40    /** Request keys never written to the bridge log. */
41    private const REDACT_KEYS = [
42        'password', 'password_confirmation', 'api_token', 'token',
43        'authorization', 'x-auth-token', 'remember_token',
44    ];
45
46    /** Max response body stored per bridge-log row (chars). */
47    private const MAX_RESPONSE_BODY = 65535;
48
49    public function __construct(private readonly ZeusClient $client) {}
50
51    /**
52     * Bridge `POST /createQuotation`.
53     *
54     * The region comes from the `company_id` the third party already sends.
55     */
56    public function createQuotation(Request $request): ZeusForwardResult
57    {
58        $companyId = $this->intOrNull($request->input('company_id'));
59
60        return $this->forward(
61            $request,
62            '/api/createQuotation',
63            $this->resolveRegion($request, $companyId),
64            $companyId,
65            null,
66        );
67    }
68
69    /**
70     * Bridge `POST /updateQuotation/{id}`.
71     *
72     * Zeus keys `updateQuotation` on the quote's legacy id — the same id Titan
73     * uses — so the path is passed straight through with no id translation.
74     * A partial update need not carry `company_id`, so we fall back to the
75     * region of the company the stored quotation belongs to.
76     */
77    public function updateQuotation(Request $request, int|string $quotationId): ZeusForwardResult
78    {
79        $companyId = $this->intOrNull($request->input('company_id'))
80            ?? $this->intOrNull(TblQuotations::where('id', $quotationId)->value('company_id'));
81
82        return $this->forward(
83            $request,
84            '/api/updateQuotation/'.rawurlencode((string) $quotationId),
85            $this->resolveRegion($request, $companyId),
86            $companyId,
87            (int) $quotationId,
88        );
89    }
90
91    // ── reads ────────────────────────────────────────────────────────
92    //
93    // A read has no second copy to save, so a forwarded read always answers with
94    // Zeus's response. When it fails or is refused, Titan answers it as today —
95    // for a Madrid row that may be stale until the database sync lands, which is
96    // still better than handing the third party an error.
97
98    /** Bridge `GET /getQuotation/{id}` — region from the quote's company. */
99    public function getQuotation(Request $request, int|string $quotationId): ZeusForwardResult
100    {
101        $companyId = $this->companyOfQuotation($quotationId);
102
103        return $this->forwardRead(
104            $request,
105            '/api/getQuotation/'.rawurlencode((string) $quotationId),
106            $this->resolveRegion($request, $companyId),
107            $companyId,
108            (int) $quotationId,
109        );
110    }
111
112    /** Bridge `GET /getFiles/{id}` — the order-detail aggregate for one quote. */
113    public function getFiles(Request $request, int|string $quotationId): ZeusForwardResult
114    {
115        $companyId = $this->companyOfQuotation($quotationId);
116
117        return $this->forwardRead(
118            $request,
119            '/api/getFiles/'.rawurlencode((string) $quotationId),
120            $this->resolveRegion($request, $companyId),
121            $companyId,
122            (int) $quotationId,
123        );
124    }
125
126    /**
127     * Bridge `GET /downloadFile/{id}`.
128     *
129     * The file id is not a quote id, so the region is resolved one hop further
130     * out: file → quotation → company. Zeus emits its own `QuoteFile` pk as
131     * `file_id` in `getFiles`, so a third party that listed the files through
132     * the bridge is already holding Zeus's id and it passes straight through.
133     */
134    public function downloadFile(Request $request, int|string $fileId): ZeusForwardResult
135    {
136        $quotationId = $this->intOrNull(
137            TblFiles::where('file_id', $fileId)->value('quotation_id')
138        );
139        $companyId = $quotationId === null ? null : $this->companyOfQuotation($quotationId);
140
141        return $this->forwardRead(
142            $request,
143            '/api/downloadFile/'.rawurlencode((string) $fileId),
144            $this->resolveRegion($request, $companyId),
145            $companyId,
146            $quotationId,
147        );
148    }
149
150    /**
151     * Bridge `POST /listQuotations` and `POST /listOrdersTable` (both map to
152     * Titan's `list_orders_table`, and Zeus mirrors that aliasing).
153     *
154     * Only forwarded when the body scopes the listing to ONE bridged company.
155     * `company_id` 0/absent means "every company in scope", and that answer
156     * would have to be merged across Titan and Zeus — a single upstream cannot
157     * produce it, so Titan keeps answering those.
158     */
159    public function listQuotations(Request $request, string $zeusPath = '/api/listQuotations'): ZeusForwardResult
160    {
161        $companyId = $this->intOrNull($request->input('company_id'));
162
163        if ($companyId === null || $companyId === 0) {
164            return ZeusForwardResult::skipped(null, ZeusForwardResult::KIND_READ);
165        }
166
167        return $this->forwardRead(
168            $request,
169            $zeusPath,
170            $this->resolveRegion($request, $companyId),
171            $companyId,
172            null,
173            json: true,
174        );
175    }
176
177    /**
178     * Bridge the region-scoped master lists: `listCompanies`, `listSource`,
179     * `listCodigos`.
180     *
181     * These carry no company at all — they ARE the list a caller picks a company
182     * or source from. Their only region signal is the `Region` header, which is
183     * exactly what Titan's own base controller uses to scope them, so that is
184     * what decides here too.
185     */
186    public function listMasterData(Request $request, string $zeusPath): ZeusForwardResult
187    {
188        return $this->forwardRead(
189            $request,
190            $zeusPath,
191            $this->regionFromRequest($request),
192            null,
193            null,
194            get: true,
195        );
196    }
197
198    /**
199     * True when Titan should return Zeus's answer instead of doing the work
200     * itself.
201     *
202     * A **read** returns Zeus's answer whenever it succeeded — there is nothing
203     * to mirror. A **write** only does so in `forward` mode, because `mirror`
204     * deliberately answers with Titan's own response. Either way a failed
205     * forward falls back to Titan, so no operation is dropped on the floor.
206     */
207    public function shouldReturnZeusResponse(ZeusForwardResult $result): bool
208    {
209        if (! $result->forwarded || ! $result->successful()) {
210            return false;
211        }
212
213        return $result->isRead()
214            || strtolower((string) config('zeus.mode', 'mirror')) === 'forward';
215    }
216
217    /**
218     * Resolve which region an operation belongs to.
219     *
220     * The company is authoritative: `tbl_companies.region` for the `company_id`
221     * already present in the request. The explicit `region` field and Titan's
222     * `Region` header are only consulted when the company cannot be resolved —
223     * a header must never be able to misroute another region's write to Zeus.
224     */
225    public function resolveRegion(Request $request, ?int $companyId): ?string
226    {
227        if ($companyId !== null) {
228            $region = TblCompanies::where('company_id', $companyId)->value('region');
229
230            if (is_string($region) && trim($region) !== '') {
231                return trim($region);
232            }
233        }
234
235        foreach ([$request->input('region'), $request->header('Region')] as $candidate) {
236            if (is_string($candidate) && trim($candidate) !== '' && strtolower(trim($candidate)) !== 'all') {
237                return trim(urldecode($candidate));
238            }
239        }
240
241        return null;
242    }
243
244    /**
245     * The full gate. Every condition is a switch someone may need to flip
246     * mid-trial without a deploy.
247     */
248    public function shouldForward(Request $request, ?string $region): bool
249    {
250        // FIRE-1733: writes coming FROM Zeus must never be forwarded back to
251        // Zeus. The Zeus → Titan sync endpoint (see ZeusSyncController) does
252        // not call Quotations::update_quotation, so the bridge is normally not
253        // even reached — but if some future path bridges the two, this guard
254        // stops the loop before any HTTP happens. The `is_from_zeus`
255        // attribute is set by EnsureZeusInboundEnabled.
256        if ($request->attributes->get('is_from_zeus') === true) {
257            return false;
258        }
259
260        if (! config('zeus.enabled')) {
261            return false;
262        }
263
264        if (! $this->isBridgedRegion($region)) {
265            return false;
266        }
267
268        if (! config('zeus.external_consumers_only', true)) {
269            return true;
270        }
271
272        // Only external API consumers (tbl_auth_users) are bridged: Fluency
273        // Labs, Víctor's AI, the chatbot, the landing pages. Titan's own UI
274        // users live on tbl_users and are deliberately left alone.
275        $user = $this->caller($request);
276
277        if (! $user instanceof TblAuthUsers) {
278            return false;
279        }
280
281        $allowlist = (array) config('zeus.consumer_ids', []);
282
283        return $allowlist === [] || in_array((int) $user->id, $allowlist, true);
284    }
285
286    /** Whether this region's operations go to Zeus. */
287    public function isBridgedRegion(?string $region): bool
288    {
289        if ($region === null || trim($region) === '') {
290            return false;
291        }
292
293        $bridged = array_map([$this, 'normalize'], (array) config('zeus.regions', []));
294
295        return in_array($this->normalize($region), $bridged, true);
296    }
297
298    /**
299     * Replay one read to Zeus. Same gate as a write, plus the independent
300     * `forward_reads` switch. Never throws — on any failure the caller falls
301     * back to Titan answering the read itself.
302     *
303     * @param  bool  $json  POST the body as JSON (the listing endpoints)
304     * @param  bool  $get  GET with the query string (the master lists)
305     */
306    private function forwardRead(
307        Request $request,
308        string $zeusPath,
309        ?string $region,
310        ?int $companyId,
311        ?int $quotationId,
312        bool $json = false,
313        bool $get = false,
314    ): ZeusForwardResult {
315        if (! config('zeus.forward_reads', true) || ! $this->shouldForward($request, $region)) {
316            return ZeusForwardResult::skipped($region, ZeusForwardResult::KIND_READ);
317        }
318
319        $fields = $this->replayFields($request);
320        $startedAt = microtime(true);
321
322        try {
323            $response = match (true) {
324                $json => $this->client->postJson($zeusPath, $fields),
325                $get => $this->client->get($zeusPath, $request->query()),
326                default => $this->client->get($zeusPath),
327            };
328
329            $this->record($request, $zeusPath, $region, $companyId, $quotationId, $fields, $startedAt, $response, null);
330
331            if (! $response->successful()) {
332                Log::warning('zeus.bridge.read_rejected', [
333                    'path' => $zeusPath,
334                    'status' => $response->status(),
335                    'quotation_id' => $quotationId,
336                    'company_id' => $companyId,
337                ]);
338            }
339
340            return ZeusForwardResult::sent($region, $response, ZeusForwardResult::KIND_READ);
341        } catch (\Throwable $e) {
342            $this->record($request, $zeusPath, $region, $companyId, $quotationId, $fields, $startedAt, null, $e);
343
344            Log::warning('zeus.bridge.read_failed', [
345                'path' => $zeusPath,
346                'quotation_id' => $quotationId,
347                'company_id' => $companyId,
348                'error' => $e->getMessage(),
349            ]);
350
351            return ZeusForwardResult::failed($region, $e, ZeusForwardResult::KIND_READ);
352        }
353    }
354
355    /** The company a quotation belongs to, or null when Titan doesn't have it. */
356    private function companyOfQuotation(int|string $quotationId): ?int
357    {
358        return $this->intOrNull(
359            TblQuotations::where('id', $quotationId)->value('company_id')
360        );
361    }
362
363    /**
364     * The region a caller asked for on an endpoint that carries no company:
365     * an explicit `region` parameter first (`listCodigos` takes one), then
366     * Titan's `Region` header. "All" and absent both mean "no single region",
367     * which is never bridged.
368     */
369    private function regionFromRequest(Request $request): ?string
370    {
371        foreach ([$request->input('region'), $request->header('Region')] as $candidate) {
372            if (is_string($candidate) && trim($candidate) !== '' && strtolower(trim($candidate)) !== 'all') {
373                return trim(urldecode($candidate));
374            }
375        }
376
377        return null;
378    }
379
380    /**
381     * Replay one request to Zeus. Resolves the gate, sends the same fields and
382     * files the third party sent, logs the outcome, and never throws.
383     */
384    private function forward(
385        Request $request,
386        string $zeusPath,
387        ?string $region,
388        ?int $companyId,
389        ?int $quotationId,
390    ): ZeusForwardResult {
391        if (! $this->shouldForward($request, $region)) {
392            return ZeusForwardResult::skipped($region);
393        }
394
395        $fields = $this->replayFields($request);
396        $files = $this->replayFiles($request);
397        $startedAt = microtime(true);
398
399        try {
400            $response = $this->client->postMultipart($zeusPath, $fields, $files);
401
402            $result = ZeusForwardResult::sent($region, $response);
403
404            $this->record($request, $zeusPath, $region, $companyId, $quotationId, $fields, $startedAt, $response, null);
405
406            if (! $response->successful()) {
407                // Not fatal in mirror mode, but it means Madrid data did not
408                // land in Zeus — it has to be visible in prod logs.
409                Log::warning('zeus.bridge.rejected', [
410                    'path' => $zeusPath,
411                    'status' => $response->status(),
412                    'quotation_id' => $quotationId,
413                    'company_id' => $companyId,
414                    'body' => mb_substr((string) $response->body(), 0, 500),
415                ]);
416            }
417
418            return $result;
419        } catch (\Throwable $e) {
420            $this->record($request, $zeusPath, $region, $companyId, $quotationId, $fields, $startedAt, null, $e);
421
422            Log::warning('zeus.bridge.failed', [
423                'path' => $zeusPath,
424                'quotation_id' => $quotationId,
425                'company_id' => $companyId,
426                'error' => $e->getMessage(),
427            ]);
428
429            return ZeusForwardResult::failed($region, $e);
430        }
431    }
432
433    /**
434     * The scalar fields to replay: everything the third party sent, minus
435     * Laravel plumbing and minus the file fields (attached separately).
436     *
437     * @return array<string, mixed>
438     */
439    private function replayFields(Request $request): array
440    {
441        $strip = array_merge(
442            (array) config('zeus.strip_fields', []),
443            array_keys($request->allFiles()),
444        );
445
446        return array_diff_key($request->all(), array_flip($strip));
447    }
448
449    /**
450     * The uploaded files to replay, under the same field names the third party
451     * used (`files[]`, `internal_files[]`, `coverage_contract_file`).
452     *
453     * @return array<string, mixed>
454     */
455    private function replayFiles(Request $request): array
456    {
457        return $request->allFiles();
458    }
459
460    /**
461     * One row per forward attempt, so a switched-off bridge can be reconciled
462     * and a failed forward replayed. Best-effort: logging must never break the
463     * host request.
464     *
465     * @param  array<string, mixed>  $fields
466     */
467    private function record(
468        Request $request,
469        string $zeusPath,
470        ?string $region,
471        ?int $companyId,
472        ?int $quotationId,
473        array $fields,
474        float $startedAt,
475        ?Response $response,
476        ?\Throwable $error,
477    ): void {
478        try {
479            $user = $this->caller($request);
480
481            TblZeusBridgeLog::create([
482                'auth_user_id' => $user instanceof TblAuthUsers ? (int) $user->id : null,
483                'titan_path' => $request->route()?->uri() ?? $request->path(),
484                'zeus_path' => $zeusPath,
485                'region' => $region,
486                'company_id' => $companyId,
487                'quotation_id' => $quotationId,
488                'zeus_quotation_id' => $this->zeusQuotationId($response),
489                'mode' => strtolower((string) config('zeus.mode', 'mirror')),
490                'status' => match (true) {
491                    $error !== null => TblZeusBridgeLog::STATUS_FAILED,
492                    $response !== null && $response->successful() => TblZeusBridgeLog::STATUS_FORWARDED,
493                    default => TblZeusBridgeLog::STATUS_REJECTED,
494                },
495                'http_status' => $response?->status(),
496                'payload' => json_encode(
497                    $this->redact($fields),
498                    JSON_UNESCAPED_UNICODE | JSON_PARTIAL_OUTPUT_ON_ERROR,
499                ),
500                'file_fields' => json_encode(
501                    array_keys($request->allFiles()),
502                    JSON_UNESCAPED_UNICODE | JSON_PARTIAL_OUTPUT_ON_ERROR,
503                ),
504                'response_body' => $response === null
505                    ? null
506                    : mb_substr((string) $response->body(), 0, self::MAX_RESPONSE_BODY),
507                'error' => $error?->getMessage(),
508                'duration_ms' => (int) round((microtime(true) - $startedAt) * 1000),
509                'created_at' => Carbon::now(),
510                'updated_at' => Carbon::now(),
511            ]);
512        } catch (\Throwable) {
513            // Never break the host request over a log row.
514        }
515    }
516
517    /**
518     * The wire id Zeus answered with, from its `{message, data: {id, ...}}` body.
519     *
520     * On a forwarded create this is the only link back to the Zeus twin: a
521     * Zeus-born quote has `legacy_id = NULL` and a PK in the >= 10,000,000 band,
522     * so Titan's own id will not resolve it. Null for any non-JSON or error body.
523     */
524    private function zeusQuotationId(?Response $response): ?int
525    {
526        if ($response === null || ! $response->successful()) {
527            return null;
528        }
529
530        $id = $response->json('data.id') ?? $response->json('id');
531
532        return is_numeric($id) ? (int) $id : null;
533    }
534
535    /**
536     * @param  array<mixed>  $data
537     * @return array<mixed>
538     */
539    private function redact(array $data): array
540    {
541        foreach ($data as $key => $value) {
542            if (in_array(strtolower((string) $key), self::REDACT_KEYS, true)) {
543                $data[$key] = '[redacted]';
544            } elseif (is_array($value)) {
545                $data[$key] = $this->redact($value);
546            }
547        }
548
549        return $data;
550    }
551
552    /**
553     * The authenticated caller.
554     *
555     * `AuthenticateWithToken` resolves either a Titan-native user (tbl_users) or
556     * an external API consumer (tbl_auth_users) — neither is the framework's
557     * default `App\Models\User` that `Request::user()`'s docblock promises. The
558     * resolver is read directly so the real model type survives.
559     */
560    private function caller(Request $request): ?Model
561    {
562        $user = ($request->getUserResolver())();
563
564        return $user instanceof Model ? $user : null;
565    }
566
567    /** Lowercase + strip accents so "madrid" and "Cataluña" compare reliably. */
568    private function normalize(string $value): string
569    {
570        $ascii = @iconv('UTF-8', 'ASCII//TRANSLIT', $value);
571
572        return strtolower(trim($ascii === false ? $value : $ascii));
573    }
574
575    private function intOrNull(mixed $value): ?int
576    {
577        return is_numeric($value) ? (int) $value : null;
578    }
579}