Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 243
0.00% covered (danger)
0.00%
0 / 10
CRAP
0.00% covered (danger)
0.00%
0 / 1
ZeusSyncService
0.00% covered (danger)
0.00%
0 / 243
0.00% covered (danger)
0.00%
0 / 10
9900
0.00% covered (danger)
0.00%
0 / 1
 upsert
0.00% covered (danger)
0.00%
0 / 47
0.00% covered (danger)
0.00%
0 / 1
132
 delete
0.00% covered (danger)
0.00%
0 / 31
0.00% covered (danger)
0.00%
0 / 1
72
 uploadFiles
0.00% covered (danger)
0.00%
0 / 76
0.00% covered (danger)
0.00%
0 / 1
462
 log
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
12
 validate
0.00% covered (danger)
0.00%
0 / 41
0.00% covered (danger)
0.00%
0 / 1
1122
 pickFields
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 reject
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 intOrNull
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
56
 parseDateTime
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
20
 pkFor
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
72
1<?php
2
3namespace App\Services;
4
5use App\Models\TblBudgetStatus;
6use App\Models\TblBudgetTypes;
7use App\Models\TblCompanies;
8use App\Models\TblCustomerTypes;
9use App\Models\TblFiles;
10use App\Models\TblQuotations;
11use App\Models\TblSegments;
12use App\Models\TblSources;
13use App\Models\TblZeusInboundLog;
14use Illuminate\Http\UploadedFile;
15use Illuminate\Support\Carbon;
16use Illuminate\Support\Facades\DB;
17use Illuminate\Support\Facades\Storage;
18
19/**
20 * Zeus → Titan sync (FIRE-1733).
21 *
22 * Receives a payload Zeus emitted for a create/update/delete event and writes
23 * to `tbl_quotations` with strict PATCH semantics. Deliberately runs NONE of
24 * Titan's usual workflows (approval matrix, emails, notifications,
25 * `addUpdateLog`, cache invalidation, outbound bridge) — Zeus already ran its
26 * own equivalents on the Madrid side, and running Titan's on top would
27 * duplicate emails and produce divergent approval decisions.
28 *
29 * PATCH semantics:
30 *   - field present in payload → write.
31 *   - field absent            → leave the DB value untouched.
32 *   - field present with null → clear the DB value.
33 * This lets Zeus emit partial diffs without needing to re-declare the full row.
34 */
35class ZeusSyncService
36{
37    /**
38     * Whitelist of tbl_quotations columns Zeus is allowed to write. Anything
39     * outside this list is silently ignored: prevents Zeus (or a
40     * misconfiguration on the Zeus side) from touching Titan-only fields such
41     * as G3W sync markers or audit columns.
42     */
43    private const WRITABLE_FIELDS = [
44        'company_id',
45        'budget_type_id',
46        'customer_type_id',
47        'budget_status_id',
48        'source_id',
49        'codigo_id',
50        'segment_id',
51        'amount',
52        'invoice_margin',
53        'revenue_per_date_per_worked',
54        'budget_margin_enabled',
55        'requires_technical_office',
56        'cost_of_labor',
57        'estimated_cost_of_materials',
58        'commission_pct',
59        // Column names must match tbl_quotations exactly — pickFields() writes them
60        // straight as columns. The short forms below were dead (no such columns).
61        'people_assigned_to_the_job',
62        'duration_of_job_in_days',
63        'total_cost_of_job',
64        'margin_for_the_company',
65        'margin_on_invoice_per_day_per_worker',
66        'gross_margin',
67        'labor_percentage',
68        'client',
69        'email',
70        'phone_number',
71        'internal_quote_id',
72        'quote_id',
73        'order_number',
74        'commercial',
75        'created_by',
76        'issue_date',
77        'request_date',
78        'acceptance_date',
79        'sent_date',
80        'accepted_by',
81        'accepted_at',
82        'for_approval',
83        'approval_type',
84        'approved_by',
85        'approved_at',
86        'approved_by_v2',
87        'approved_at_v2',
88        'rejected_by',
89        'rejected_at',
90        'rejected_by_v2',
91        'rejected_at_v2',
92        'importe_avisado',
93        'approval_requested_at',
94        'approval_last_reminded_at',
95        'last_follow_up_date',
96        'likehood',
97        'reason_for_not_following_up_id',
98        'last_follow_up_comment',
99        'box_work_g3w',
100        'visit_date',
101        'send_channel',
102        'direccion_postal',
103        'reason_for_rejection_id',
104        'reason_for_rejection',
105    ];
106
107    /**
108     * Allowed values for the `send_channel` column (Zeus's SendChannel enum).
109     */
110    private const SEND_CHANNEL_VALUES = ['email', 'correo', 'whatsapp'];
111
112    /**
113     * Allowed values for the `likehood` ENUM column. Mirrors the enum defined on
114     * tbl_quotations — a value outside this set is rejected (422) rather than
115     * hitting a DB truncation error on write.
116     */
117    private const LIKEHOOD_VALUES = [
118        'Bajo',
119        'Media Bajo',
120        'Media',
121        'Medio Alto',
122        'Alto',
123    ];
124
125    /**
126     * Result codes returned to the controller. Each maps 1:1 to a
127     * TblZeusInboundLog::ACTION_* constant so the audit trail and the HTTP
128     * response are always in sync.
129     */
130    public const RESULT_CREATED = 'created';
131
132    public const RESULT_UPDATED = 'updated';
133
134    public const RESULT_DELETED = 'deleted';
135
136    public const RESULT_SKIPPED_STALE = 'skipped_stale';
137
138    public const RESULT_SKIPPED_NOT_FOUND = 'skipped_not_found';
139
140    public const RESULT_REJECTED = 'rejected';
141
142    public const RESULT_FILES_UPLOADED = 'files_uploaded';
143
144    /**
145     * Upsert one quote from Zeus. Idempotent by `zeus_id`.
146     *
147     * @param  array<string, mixed>  $payload
148     * @return array{result: string, titan_id: ?int, zeus_id: ?int, errors: array<string, array<int, string>>}
149     */
150    public function upsert(array $payload): array
151    {
152        $zeusId = $this->intOrNull($payload['zeus_id'] ?? null);
153        if ($zeusId === null || $zeusId <= 0) {
154            return $this->reject($zeusId, ['zeus_id' => ['The zeus_id field is required and must be a positive integer.']]);
155        }
156
157        $errors = $this->validate($payload);
158        if ($errors !== []) {
159            return $this->reject($zeusId, $errors);
160        }
161
162        $zeusUpdatedAt = $this->parseDateTime($payload['zeus_updated_at'] ?? null);
163
164        // Match order: (1) zeus_id — the definitive key once bound;
165        // (2) titan_id (== our own PK) — for quotes Zeus imported from Titan the
166        //     first time and hasn't stamped `zeus_id` on us yet; matching here
167        //     lets us backfill `zeus_id` onto the correct pre-existing row.
168        // (3) neither → treat as create.
169        $existing = TblQuotations::where('zeus_id', $zeusId)->first();
170
171        if ($existing === null) {
172            $titanId = $this->intOrNull($payload['titan_id'] ?? null);
173            if ($titanId !== null && $titanId > 0) {
174                $existing = TblQuotations::where('id', $titanId)->first();
175            }
176        }
177
178        if ($existing === null) {
179            // Create path: fill Zeus-writable fields + stamp zeus_id +
180            // synced_from_zeus_at, then INSERT. NO workflow side effects.
181            // Timestamps are stored as UTC-normalised naive DATETIME strings
182            // so the stale-write comparison reads back consistently regardless
183            // of Laravel's app timezone.
184            $syncedAt = ($zeusUpdatedAt ?? Carbon::now())->copy()->utc();
185            $insert = $this->pickFields($payload);
186            $insert['zeus_id'] = $zeusId;
187            $insert['synced_from_zeus_at'] = $syncedAt->format('Y-m-d H:i:s');
188            $insert['created_at'] = $syncedAt->format('Y-m-d H:i:s');
189            $insert['updated_at'] = date('Y-m-d H:i:s'); // Titan write time, app tz — same as every other writer (DWH change cursor)
190
191            $newId = DB::table('tbl_quotations')->insertGetId($insert);
192
193            return [
194                'result' => self::RESULT_CREATED,
195                'titan_id' => (int) $newId,
196                'zeus_id' => $zeusId,
197                'errors' => [],
198            ];
199        }
200
201        // Stale-write guard: Zeus events can arrive out of order. If the row
202        // was already synced at a newer timestamp than the incoming payload
203        // claims, drop this one instead of rewinding state. Compare on the
204        // UNIX timestamp so DB timezone (naive DATETIME, interpreted as UTC —
205        // see the write path below) and payload timezone (ISO 8601 with `Z`)
206        // cannot skew the answer.
207        if ($zeusUpdatedAt !== null && $existing->synced_from_zeus_at !== null) {
208            $currentSyncedAt = Carbon::parse((string) $existing->synced_from_zeus_at, 'UTC');
209            if ($zeusUpdatedAt->getTimestamp() < $currentSyncedAt->getTimestamp()) {
210                return [
211                    'result' => self::RESULT_SKIPPED_STALE,
212                    'titan_id' => (int) $existing->id,
213                    'zeus_id' => $zeusId,
214                    'errors' => [],
215                ];
216            }
217        }
218
219        $syncedAt = ($zeusUpdatedAt ?? Carbon::now())->copy()->utc();
220        $update = $this->pickFields($payload);
221        $update['zeus_id'] = $zeusId; // idempotent; noop if it already matches
222        $update['synced_from_zeus_at'] = $syncedAt->format('Y-m-d H:i:s');
223        $update['updated_at'] = date('Y-m-d H:i:s'); // Titan write time, app tz — same as every other writer (DWH change cursor)
224
225        DB::table('tbl_quotations')->where('id', $existing->id)->update($update);
226
227        return [
228            'result' => self::RESULT_UPDATED,
229            'titan_id' => (int) $existing->id,
230            'zeus_id' => $zeusId,
231            'errors' => [],
232        ];
233    }
234
235    /**
236     * Soft-delete one quote, resolved by `titan_id` (our own PK). Sets
237     * `deleted_at` to Zeus's timestamp so a later out-of-order upsert can be
238     * compared against it. When `titan_id` is absent or matches no row we return
239     * `skipped_not_found` — a quote Zeus never synced simply doesn't exist here,
240     * and a retry stays idempotent.
241     *
242     * @param  array<string, mixed>  $payload
243     * @return array{result: string, titan_id: ?int, errors: array<string, array<int, string>>}
244     */
245    public function delete(array $payload): array
246    {
247        $titanId = $this->intOrNull($payload['titan_id'] ?? null);
248        $existing = $titanId !== null && $titanId > 0
249            ? TblQuotations::where('id', $titanId)->first()
250            : null;
251
252        if ($existing === null) {
253            return [
254                'result' => self::RESULT_SKIPPED_NOT_FOUND,
255                'titan_id' => null,
256                'errors' => [],
257            ];
258        }
259
260        $zeusDeletedAt = ($this->parseDateTime($payload['zeus_deleted_at'] ?? null) ?? Carbon::now())->copy()->utc();
261        $utc = $zeusDeletedAt->format('Y-m-d H:i:s');
262
263        $update = [
264            // `for_add = 2` is Titan's own "deleted" marker: the quotations
265            // listing filters `WHERE for_add = 0`, so this is what actually hides
266            // the row in Titan's UI. `deleted_at` is the Zeus soft-delete audit
267            // column (no native query reads it), kept so the row survives as backup
268            // — we intentionally do NOT replicate Titan's hard-delete + archive.
269            'for_add' => 2,
270            'deleted_at' => $utc,
271            'synced_from_zeus_at' => $utc,
272            'updated_at' => date('Y-m-d H:i:s'), // Titan write time, app tz (DWH change cursor)
273        ];
274
275        // Retain the deletion reason Zeus captured. reason_id is a FK to
276        // tbl_reasons — guard on existence so an unmapped id can't fail the whole
277        // delete; the soft-delete itself matters more than the reason.
278        $reasonId = $this->intOrNull($payload['reason_id'] ?? null);
279        if ($reasonId !== null && $reasonId > 0 && DB::table('tbl_reasons')->where('reason_id', $reasonId)->exists()) {
280            $update['reason_id'] = $reasonId;
281        }
282        if (array_key_exists('reason_for_deletion', $payload)) {
283            $update['reason_for_deletion'] = (string) ($payload['reason_for_deletion'] ?? '');
284        }
285
286        DB::table('tbl_quotations')
287            ->where('id', $existing->id)
288            ->update($update);
289
290        return [
291            'result' => self::RESULT_DELETED,
292            'titan_id' => (int) $existing->id,
293            'errors' => [],
294        ];
295    }
296
297    /**
298     * FIRE-1733 comment 27842: attach one or more files to an existing quote.
299     *
300     * Resolution order for the target row mirrors upsert(): `zeus_id` first
301     * (canonical), fall back to `titan_id`. If neither identifies a row we
302     * return `skipped_not_found` — same idempotent semantics as delete().
303     *
304     * Storage matches Titan's own flow (Quotations::save at :211): files land
305     * on `uploads/{timestamp}_{original}` on S3, and each one gets a row in
306     * `tbl_files` scoped by `quotation_id`. `has_attachment` is recomputed
307     * from `tbl_files` afterwards — the service never trusts a payload flag
308     * for it.
309     *
310     * Titan's usual side effects (email dispatch, `addUpdateLog`, cache
311     * flush) are intentionally NOT triggered — same policy as upsert()/delete().
312     *
313     * @param  array<string, mixed>  $payload
314     * @param  array<int, UploadedFile>  $files
315     * @return array{result: string, titan_id: ?int, zeus_id: ?int, uploaded: int, errors: array<string, array<int, string>>}
316     */
317    public function uploadFiles(array $payload, array $files): array
318    {
319        $zeusId = $this->intOrNull($payload['zeus_id'] ?? null);
320        $titanId = $this->intOrNull($payload['titan_id'] ?? null);
321
322        if (($zeusId === null || $zeusId <= 0) && ($titanId === null || $titanId <= 0)) {
323            return [
324                'result' => self::RESULT_REJECTED,
325                'titan_id' => null,
326                'zeus_id' => $zeusId,
327                'uploaded' => 0,
328                'errors' => ['identity' => ['Either zeus_id or titan_id must be provided.']],
329            ];
330        }
331        if ($files === []) {
332            return [
333                'result' => self::RESULT_REJECTED,
334                'titan_id' => $titanId,
335                'zeus_id' => $zeusId,
336                'uploaded' => 0,
337                'errors' => ['files' => ['At least one file must be attached (multipart key `files[]`).']],
338            ];
339        }
340
341        $existing = null;
342        if ($zeusId !== null && $zeusId > 0) {
343            $existing = TblQuotations::where('zeus_id', $zeusId)->first();
344        }
345        if ($existing === null && $titanId !== null && $titanId > 0) {
346            $existing = TblQuotations::where('id', $titanId)->first();
347        }
348
349        if ($existing === null) {
350            return [
351                'result' => self::RESULT_SKIPPED_NOT_FOUND,
352                'titan_id' => $titanId,
353                'zeus_id' => $zeusId,
354                'uploaded' => 0,
355                'errors' => [],
356            ];
357        }
358
359        $uploadedBy = is_string($payload['uploaded_by'] ?? null) && $payload['uploaded_by'] !== ''
360            ? (string) $payload['uploaded_by']
361            : 'Zeus Bot';
362
363        // Per-file flags, aligned by index with files[] (Zeus sends is_internal[],
364        // is_coverage_contract[], is_signed[] in the same order). "1" => set, anything
365        // else/absent => NULL. is_internal in particular MUST stay NULL for client files
366        // (Titan's client tab queries `is_internal IS NULL`; a 0 would hide the file from
367        // both the client and internal tabs).
368        $isInternal = (array) ($payload['is_internal'] ?? []);
369        $isCoverageContract = (array) ($payload['is_coverage_contract'] ?? []);
370        $isSigned = (array) ($payload['is_signed'] ?? []);
371        $flag = static fn (array $vals, int $i): ?int => (isset($vals[$i]) && (string) $vals[$i] === '1') ? 1 : null;
372
373        $uploaded = 0;
374        foreach ($files as $i => $file) {
375            if (! $file instanceof UploadedFile || ! $file->isValid()) {
376                continue;
377            }
378            $filename = time().'_'.$file->getClientOriginalName();
379
380            Storage::disk('s3')->putFileAs(
381                'uploads',
382                $file,
383                $filename,
384                ['ContentType' => $file->getMimeType()],
385            );
386
387            TblFiles::create([
388                'quotation_id' => $existing->id,
389                'quote_id' => $existing->quote_id,
390                'original_name' => $file->getClientOriginalName(),
391                'filename' => $filename,
392                'file_size' => $file->getSize(),
393                'mime_type' => $file->getMimeType(),
394                'uploaded_by' => $uploadedBy,
395                'uploaded_at' => Carbon::now(),
396                'is_internal' => $flag($isInternal, $i),
397                'is_coverage_contract' => $flag($isCoverageContract, $i),
398                'is_signed' => $flag($isSigned, $i),
399            ]);
400
401            $uploaded++;
402        }
403
404        // Recompute has_attachment from tbl_files — never trust the input.
405        $fileCount = (int) DB::table('tbl_files')
406            ->where('quotation_id', $existing->id)
407            ->count();
408
409        DB::table('tbl_quotations')
410            ->where('id', $existing->id)
411            ->update(['has_attachment' => $fileCount > 0 ? 1 : 0, 'updated_at' => date('Y-m-d H:i:s')]);
412
413        return [
414            'result' => self::RESULT_FILES_UPLOADED,
415            'titan_id' => (int) $existing->id,
416            'zeus_id' => $existing->zeus_id !== null ? (int) $existing->zeus_id : $zeusId,
417            'uploaded' => $uploaded,
418            'errors' => [],
419        ];
420    }
421
422    /**
423     * Write one audit row summarising what happened. The full payload is
424     * recorded by AuthenticateWithToken in tbl_api_consumer_endpoints only when
425     * services.api_consumer_log.enabled is on; this table stores just the
426     * outcome for fast reconciliation queries.
427     */
428    public function log(
429        ?int $authUserId,
430        string $endpoint,
431        ?int $zeusId,
432        ?int $quotationId,
433        string $action,
434        ?int $httpStatus,
435        ?string $rawPayload,
436        ?string $zeusUpdatedAt,
437        ?string $error,
438        ?int $durationMs,
439    ): void {
440        try {
441            TblZeusInboundLog::create([
442                'auth_user_id' => $authUserId,
443                'endpoint' => $endpoint,
444                'zeus_id' => $zeusId,
445                'quotation_id' => $quotationId,
446                'action' => $action,
447                'http_status' => $httpStatus,
448                'payload_hash' => $rawPayload === null ? null : hash('sha256', $rawPayload),
449                'zeus_updated_at' => $zeusUpdatedAt,
450                'error' => $error,
451                'duration_ms' => $durationMs,
452                'created_at' => Carbon::now(),
453            ]);
454        } catch (\Throwable) {
455            // Audit is best-effort; a logging failure must not break the sync.
456        }
457    }
458
459    /**
460     * Basic FK / type / range validation. Runs before any DB write. Absent
461     * fields are OK (PATCH semantics): only fields that are PRESENT and
462     * malformed are rejected.
463     *
464     * @param  array<string, mixed>  $payload
465     * @return array<string, array<int, string>>
466     */
467    private function validate(array $payload): array
468    {
469        $errors = [];
470
471        if (array_key_exists('company_id', $payload)) {
472            $companyId = $this->intOrNull($payload['company_id']);
473            if ($companyId === null) {
474                $errors['company_id'] = ['The company_id must be an integer.'];
475            } else {
476                $allowedRegions = (array) config('zeus.inbound_regions', []);
477                if ($allowedRegions !== [] && ! in_array($companyId, $allowedRegions, true)) {
478                    $errors['company_id'] = ['The company_id '.$companyId.' is not in the Zeus inbound allowlist.'];
479                } elseif (! TblCompanies::where('company_id', $companyId)->exists()) {
480                    $errors['company_id'] = ['The company_id '.$companyId.' does not exist.'];
481                }
482            }
483        }
484
485        foreach (['budget_type_id' => TblBudgetTypes::class, 'customer_type_id' => TblCustomerTypes::class, 'budget_status_id' => TblBudgetStatus::class, 'source_id' => TblSources::class, 'segment_id' => TblSegments::class] as $field => $model) {
486            if (! array_key_exists($field, $payload) || $payload[$field] === null) {
487                continue;
488            }
489            $id = $this->intOrNull($payload[$field]);
490            if ($id === null || ! $model::where($this->pkFor($field), $id)->exists()) {
491                $errors[$field] = ['The '.$field.' '.($id ?? 'null').' does not exist.'];
492            }
493        }
494
495        $numericFields = [
496            'amount', 'invoice_margin', 'revenue_per_date_per_worked', 'cost_of_labor',
497            'estimated_cost_of_materials', 'commission_pct', 'people_assigned_to_the_job',
498            'duration_of_job_in_days', 'total_cost_of_job', 'margin_for_the_company',
499            'margin_on_invoice_per_day_per_worker', 'gross_margin', 'labor_percentage',
500        ];
501        foreach ($numericFields as $numeric) {
502            if (array_key_exists($numeric, $payload) && $payload[$numeric] !== null && ! is_numeric($payload[$numeric])) {
503                $errors[$numeric] = ['The '.$numeric.' must be numeric.'];
504            }
505        }
506
507        foreach (['issue_date', 'request_date', 'acceptance_date', 'visit_date', 'sent_date', 'accepted_at', 'approved_at', 'approved_at_v2', 'rejected_at', 'rejected_at_v2', 'approval_requested_at', 'approval_last_reminded_at', 'last_follow_up_date', 'zeus_updated_at'] as $dt) {
508            if (array_key_exists($dt, $payload) && $payload[$dt] !== null && $this->parseDateTime($payload[$dt]) === null) {
509                $errors[$dt] = ['The '.$dt.' must be a valid ISO 8601 date/time.'];
510            }
511        }
512
513        if (array_key_exists('likehood', $payload) && $payload['likehood'] !== null && ! in_array($payload['likehood'], self::LIKEHOOD_VALUES, true)) {
514            $errors['likehood'] = ['The likehood must be one of: '.implode(', ', self::LIKEHOOD_VALUES).'.'];
515        }
516
517        if (array_key_exists('reason_for_not_following_up_id', $payload) && $payload['reason_for_not_following_up_id'] !== null) {
518            $rnfId = $this->intOrNull($payload['reason_for_not_following_up_id']);
519            if ($rnfId === null || ! DB::table('tbl_reason_for_not_following_up')->where('reason_for_not_following_up_id', $rnfId)->exists()) {
520                $errors['reason_for_not_following_up_id'] = ['The reason_for_not_following_up_id '.($rnfId ?? 'null').' does not exist.'];
521            }
522        }
523
524        if (array_key_exists('reason_for_rejection_id', $payload) && $payload['reason_for_rejection_id'] !== null) {
525            $rfrId = $this->intOrNull($payload['reason_for_rejection_id']);
526            if ($rfrId === null || ! DB::table('tbl_reason_for_rejection')->where('reason_for_rejection_id', $rfrId)->exists()) {
527                $errors['reason_for_rejection_id'] = ['The reason_for_rejection_id '.($rfrId ?? 'null').' does not exist.'];
528            }
529        }
530
531        if (array_key_exists('send_channel', $payload) && $payload['send_channel'] !== null && ! in_array($payload['send_channel'], self::SEND_CHANNEL_VALUES, true)) {
532            $errors['send_channel'] = ['The send_channel must be one of: '.implode(', ', self::SEND_CHANNEL_VALUES).'.'];
533        }
534
535        return $errors;
536    }
537
538    /**
539     * Filter the payload down to the columns Zeus is allowed to write.
540     * Null values are preserved so the caller can explicitly clear a field.
541     *
542     * @param  array<string, mixed>  $payload
543     * @return array<string, mixed>
544     */
545    private function pickFields(array $payload): array
546    {
547        $picked = [];
548        foreach (self::WRITABLE_FIELDS as $field) {
549            if (array_key_exists($field, $payload)) {
550                $picked[$field] = $payload[$field];
551            }
552        }
553
554        return $picked;
555    }
556
557    private function reject(?int $zeusId, array $errors): array
558    {
559        return [
560            'result' => self::RESULT_REJECTED,
561            'titan_id' => null,
562            'zeus_id' => $zeusId,
563            'errors' => $errors,
564        ];
565    }
566
567    private function intOrNull(mixed $value): ?int
568    {
569        if ($value === null || $value === '') {
570            return null;
571        }
572        if (is_int($value)) {
573            return $value;
574        }
575        if (is_string($value) && ctype_digit(ltrim($value, '-'))) {
576            return (int) $value;
577        }
578        if (is_numeric($value)) {
579            return (int) $value;
580        }
581
582        return null;
583    }
584
585    private function parseDateTime(mixed $value): ?Carbon
586    {
587        if ($value === null || $value === '') {
588            return null;
589        }
590        try {
591            return Carbon::parse((string) $value);
592        } catch (\Throwable) {
593            return null;
594        }
595    }
596
597    /** Reference-table PK column name — not every catalog uses `id`. */
598    private function pkFor(string $field): string
599    {
600        return match ($field) {
601            'company_id' => 'company_id',
602            'budget_type_id' => 'budget_type_id',
603            'customer_type_id' => 'customer_type_id',
604            'budget_status_id' => 'budget_status_id',
605            'source_id' => 'source_id',
606            'segment_id' => 'segment_id',
607            default => 'id',
608        };
609    }
610}