Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 93
0.00% covered (danger)
0.00%
0 / 9
CRAP
0.00% covered (danger)
0.00%
0 / 1
CofraiClientSyncService
0.00% covered (danger)
0.00%
0 / 93
0.00% covered (danger)
0.00%
0 / 9
930
0.00% covered (danger)
0.00%
0 / 1
 runSync
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
6
 syncRegion
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 syncClientIds
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
30
 fetchClientIds
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
 fetchClient
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
30
 upsertClient
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
20
 resolveClientTypeId
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
30
 createNewClient
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
2
 updateExistingClient
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
12
1<?php
2
3namespace App\Services;
4
5use App\Jobs\SyncCofraiClientsForRegion;
6use App\Models\Client;
7use Illuminate\Console\Command;
8use Illuminate\Support\Facades\Log;
9
10/**
11 * FIRE-1077: Cofrai parallel to GestionaClientSyncService.
12 *
13 * Mirrors the G3W client-sync flow 1:1 with two intentional differences:
14 *   - logs go to Log::channel('cofrai') instead of 'g3w'
15 *   - raw API responses are NOT cached (ClientGestionaResponse is
16 *     Gestiona-specific per findings/FIRE-1077_Investigation.md). If
17 *     audit traceability of raw payloads is needed later, mirror the
18 *     ClientGestionaResponse table + model as ClientCofraiResponse and
19 *     wire it in here.
20 */
21class CofraiClientSyncService extends CofraiService
22{
23    public function runSync(string $date, array $regions, Command $command): int
24    {
25        Log::channel('cofrai')->info("cofrai-clients:sync — Dispatching for date {$date}, regions: ".implode(', ', $regions));
26
27        $cronStart = microtime(true);
28        foreach ($regions as $region) {
29            SyncCofraiClientsForRegion::dispatch($date, $region)->onQueue('cofrai');
30            $command->info("Dispatched: {$region}");
31        }
32
33        Log::channel('cofrai')->info('cofrai-clients:sync dispatched', [
34            'regions' => count($regions),
35            'date' => $date,
36            'dispatch_ms' => (int) round((microtime(true) - $cronStart) * 1000),
37        ]);
38
39        return Command::SUCCESS;
40    }
41
42    public function syncRegion(string $date, string $region): array
43    {
44        $clientIds = $this->fetchClientIds($date, $region);
45
46        if (empty($clientIds)) {
47            Log::channel('cofrai')->info("cofrai-clients:sync — No client IDs returned for region {$region}, date {$date}.");
48
49            return ['created' => 0, 'updated' => 0, 'failed' => 0, 'skipped' => 0];
50        }
51
52        $originalCount = count($clientIds);
53        $clientIds = array_unique(array_filter($clientIds));
54
55        Log::channel('cofrai')->info("cofrai-clients:sync — Found {$originalCount} client ID(s) for region {$region}, date {$date} (".count($clientIds).' unique).');
56
57        return $this->syncClientIds($clientIds, $region);
58    }
59
60    public function syncClientIds(array $clientIds, string $region): array
61    {
62        $stats = ['created' => 0, 'updated' => 0, 'failed' => 0, 'skipped' => 0];
63
64        foreach ($clientIds as $clientId) {
65            try {
66                $cofraiData = $this->fetchClient($clientId, $region);
67
68                if (! $cofraiData) {
69                    $stats['skipped']++;
70
71                    continue;
72                }
73
74                $result = $this->upsertClient($cofraiData, $region);
75
76                $result === 'created' ? $stats['created']++ : $stats['updated']++;
77            } catch (\Exception $e) {
78                Log::channel('cofrai')->error("cofrai-clients:sync — Error syncing client ID {$clientId} in region {$region}: ".$e->getMessage());
79                $stats['failed']++;
80            }
81        }
82
83        return $stats;
84    }
85
86    public function fetchClientIds(string $date, string $region): array
87    {
88        $response = $this->request('get', "cliente/fecha/{$date}", $region);
89
90        if (! is_array($response)) {
91            return [];
92        }
93
94        return array_map(fn ($item) => is_array($item) ? ($item['ID'] ?? null) : $item, $response);
95    }
96
97    public function fetchClient(int $id, string $region): ?array
98    {
99        try {
100            $response = $this->request('get', "cliente/{$id}", $region);
101
102            if (is_array($response) && isset($response['cliente'])) {
103                return $response['cliente'];
104            }
105
106            return is_array($response) ? $response : null;
107        } catch (\Exception $e) {
108            Log::channel('cofrai')->warning("cofrai-clients:sync — Could not fetch client {$id} in region {$region}: ".$e->getMessage());
109
110            return null;
111        }
112    }
113
114    public function upsertClient(array $data, string $region): string
115    {
116        $cofraiId = $data['cod_cliente'] ?? $data['ID'] ?? null;
117
118        if (! $cofraiId) {
119            throw new \Exception('Cofrai client data missing cod_cliente/ID field.');
120        }
121
122        if (isset($data['tipo_cliente'])) {
123            Log::channel('cofrai')->info("cofrai-clients:sync — Client {$cofraiId} tipo_cliente: {$data['tipo_cliente']}");
124        }
125
126        // Cofrai shares the same Client table as Gestiona — we look up via
127        // gestiona_client_code because that column is shared. If Cofrai
128        // gets its own dedicated client-code column later, change this lookup.
129        $existing = Client::where('gestiona_client_code', $cofraiId)->first();
130        $clientTypeId = $this->resolveClientTypeId($data);
131
132        if ($existing) {
133            $this->updateExistingClient($existing, $data, $clientTypeId);
134
135            return 'updated';
136        }
137
138        $this->createNewClient($data, $region, $clientTypeId, $cofraiId);
139
140        return 'created';
141    }
142
143    private function resolveClientTypeId(array $data): int
144    {
145        $tipoCliente = $data['tipo_cliente'] ?? null;
146
147        return match ($tipoCliente) {
148            'Administrador' => Client::TYPE_ADMINISTRADOR,
149            'Grandes Cuentas', 'Grandes Clientes' => Client::TYPE_GRAN_CLIENTE,
150            'Facilities' => Client::TYPE_FACILITIES,
151            default => Client::TYPE_GENERAL,
152        };
153    }
154
155    private function createNewClient(array $data, string $region, int $clientTypeId, int $cofraiId): Client
156    {
157        return Client::create([
158            'gestiona_client_code' => $cofraiId,
159            'client_type_id' => $clientTypeId,
160            'company_name' => $data['empresa'] ?? null,
161            'associated_billing_client' => $data['empresa'] ?? null,
162            'fiscal_id' => $data['cliente_cif'] ?? null,
163            'address' => $data['direccion'] ?? null,
164            'postal_code' => $data['codpostal'] ?? null,
165            'city' => $data['poblacion'] ?? null,
166            'province' => $data['provincia'] ?? null,
167            'contact_phone' => $data['telefono'] ?? null,
168            'contact_email' => $data['email_facturacion'] ?? null,
169            'contact_name' => $data['contacto'] ?? null,
170            'payment_method' => $data['forma_pago'] ?? null,
171            'region' => $region,
172        ]);
173    }
174
175    private function updateExistingClient(Client $client, array $data, int $clientTypeId): void
176    {
177        $updateData = [
178            'client_type_id' => $clientTypeId,
179            'associated_billing_client' => $data['empresa'] ?? $client->associated_billing_client,
180            'fiscal_id' => $data['cliente_cif'] ?? $client->fiscal_id,
181            'address' => $data['direccion'] ?? $client->address,
182            'postal_code' => $data['codpostal'] ?? $client->postal_code,
183            'city' => $data['poblacion'] ?? $client->city,
184            'province' => $data['provincia'] ?? $client->province,
185            'contact_phone' => $data['telefono'] ?? $client->contact_phone,
186            'contact_email' => $data['email_facturacion'] ?? $client->contact_email,
187            'contact_name' => $data['contacto'] ?? $client->contact_name,
188            'payment_method' => $data['forma_pago'] ?? $client->payment_method,
189        ];
190
191        if (empty($client->company_name) && ! empty($data['empresa'])) {
192            $updateData['company_name'] = $data['empresa'];
193        }
194
195        $client->update($updateData);
196    }
197}