Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
2.22% covered (danger)
2.22%
4 / 180
0.00% covered (danger)
0.00%
0 / 17
CRAP
0.00% covered (danger)
0.00%
0 / 1
CofraiService
2.22% covered (danger)
2.22%
4 / 180
0.00% covered (danger)
0.00%
0 / 17
4263.33
0.00% covered (danger)
0.00%
0 / 1
 __construct
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
2.03
 getCredentials
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
42
 encrypt
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 decrypt
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 auth
0.00% covered (danger)
0.00%
0 / 34
0.00% covered (danger)
0.00%
0 / 1
72
 request
0.00% covered (danger)
0.00%
0 / 44
0.00% covered (danger)
0.00%
0 / 1
210
 updateApiCredentials
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
56
 getApiDetails
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 getLastUpdate
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 getSyncStatus
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 setSyncStatus
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 getCofraiActive
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 updateCofraiActive
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 getBudgetsByDay
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getAllBudgetsWithDates
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
30
 checkDeleted
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
20
 checkDeletedBatch
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
56
1<?php
2
3namespace App\Services;
4
5use App\Models\TblCofraiCredentials;
6use App\Models\TblCofraiLastUpdate;
7use App\Models\TblCompanies;
8use Illuminate\Http\JsonResponse;
9use Illuminate\Support\Facades\Log;
10
11class CofraiService
12{
13    protected $apiUrl;
14
15    protected $user;
16
17    protected $password;
18
19    protected $accessToken;
20
21    protected $region;
22
23    protected $credentials;
24
25    protected $appUser;
26
27    protected $encryptKey;
28
29    protected $cipher;
30
31    public function __construct()
32    {
33        $this->encryptKey = env('ENCRYPT_KEY');
34        if (! $this->encryptKey) {
35            throw new \Exception('Encryption key not set in environment variables');
36        }
37
38        $this->cipher = 'AES-256-CBC';
39
40        $this->appUser = @getallheaders()['Name'] ?? 'System';
41    }
42
43    public function getCredentials($region)
44    {
45
46        if ($region === 'Catalunya') {
47            $region = 'Cataluña';
48        }
49
50        $this->credentials = TblCofraiCredentials::where('region', $region)->first();
51
52        if (! $this->credentials) {
53            TblCofraiCredentials::create([
54                'region' => $region,
55            ]);
56            $this->credentials = TblCofraiCredentials::where('region', $region)->first();
57        }
58
59        $this->user = $this->credentials->user ? $this->decrypt($this->credentials->user) : null;
60        $this->password = $this->credentials->password ? $this->decrypt($this->credentials->password) : null;
61        $this->apiUrl = $this->credentials->url ? $this->decrypt($this->credentials->url) : null;
62    }
63
64    /**
65     * @return false|string
66     */
67    private function encrypt($data)
68    {
69        $iv = substr(hash('sha256', $this->encryptKey), 0, 16);
70
71        return openssl_encrypt($data, $this->cipher, $this->encryptKey, 0, $iv);
72    }
73
74    /**
75     * @return false|string
76     */
77    private function decrypt($encryptedData)
78    {
79        $iv = substr(hash('sha256', $this->encryptKey), 0, 16);
80
81        return openssl_decrypt($encryptedData, $this->cipher, $this->encryptKey, 0, $iv);
82    }
83
84    /**
85     * @return void
86     *
87     * @throws \Exception
88     */
89    protected function auth($region)
90    {
91        try {
92            $this->getCredentials($region);
93            if (! $this->apiUrl || ! $this->user || ! $this->password) {
94                throw new \Exception('Incomplete credentials: URL, user, or password missing.');
95            }
96
97            $url = "{$this->apiUrl}auth/login";
98
99            $curl = curl_init();
100            curl_setopt_array($curl, [
101                CURLOPT_URL => $url,
102                CURLOPT_RETURNTRANSFER => true,
103                CURLOPT_POST => true,
104                CURLOPT_USERAGENT => 'Titan/1.0',
105                CURLOPT_POSTFIELDS => json_encode([
106                    'email' => $this->user,
107                    'password' => $this->password,
108                    'device_name' => 'FST',
109                ]),
110                CURLOPT_HTTPHEADER => [
111                    'Accept: application/json',
112                    'Content-Type: application/json',
113                ],
114            ]);
115            // Cofrai sits behind CloudFront which 403s any request with an
116            // empty or PHP-default User-Agent ("Request blocked" WAF rule).
117            // Hoppscotch / browsers work because they send a real UA; we have
118            // to do the same.
119
120            $response = curl_exec($curl);
121
122            if (curl_errno($curl)) {
123                throw new \Exception('cURL error: '.curl_error($curl));
124            }
125
126            $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
127            curl_close($curl);
128
129            if ($httpCode !== 200) {
130                throw new \Exception('Authentication error: '.$response);
131            }
132
133            $responseData = json_decode($response, true);
134            $this->accessToken = $responseData['token'] ?? null;
135
136            if (! $this->accessToken) {
137                throw new \Exception('No access token returned.');
138            }
139        } catch (\Exception $e) {
140            Log::channel('cofrai')->error('Error in auth: '.$e->getMessage());
141            throw new \Exception('Authentication failed: '.$e->getMessage());
142        }
143    }
144
145    /**
146     * @return mixed
147     *
148     * @throws \Exception
149     */
150    protected function request($method, $endpoint, $region, array $data = [])
151    {
152        try {
153            $this->getCredentials($region);
154
155            if (! $this->apiUrl) {
156                throw new \Exception('API URL is not defined.');
157            }
158
159            if (! $this->accessToken) {
160                $this->auth($region);
161            }
162
163            $url = "{$this->apiUrl}{$endpoint}";
164            $curl = curl_init();
165
166            // CURLOPT_USERAGENT: bypass CloudFront WAF — see auth() above.
167            curl_setopt_array($curl, [
168                CURLOPT_URL => $url,
169                CURLOPT_RETURNTRANSFER => true,
170                CURLOPT_CUSTOMREQUEST => strtoupper($method),
171                CURLOPT_USERAGENT => 'Titan/1.0',
172                CURLOPT_HTTPHEADER => [
173                    'Authorization: Bearer '.$this->accessToken,
174                    'Accept: application/json',
175                    'Content-Type: application/json',
176                ],
177            ]);
178
179            if (in_array(strtoupper($method), ['POST', 'PUT', 'PATCH']) && ! empty($data)) {
180                if (! is_array($data)) {
181                    throw new \Exception('The $data parameter must be an array.');
182                }
183                curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
184            }
185
186            $response = curl_exec($curl);
187
188            if (curl_errno($curl)) {
189                throw new \Exception('cURL error: '.curl_error($curl));
190            }
191
192            $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
193            curl_close($curl);
194
195            if ($httpCode === 401) {
196                $this->auth($region);
197
198                return $this->request($method, $endpoint, $region, $data);
199            }
200
201            if ($httpCode < 200 || $httpCode >= 300) {
202                Log::channel('cofrai')->error('API Response Error: '.$response);
203
204                $errorResponse = json_decode($response, true);
205                $errorMessage = is_array($errorResponse) && isset($errorResponse['message'])
206                    ? $errorResponse['message']
207                    : 'Request error: '.$response;
208
209                throw new \Exception($errorMessage);
210            }
211
212            $responseData = json_decode($response, true);
213
214            if (json_last_error() !== JSON_ERROR_NONE) {
215                throw new \Exception('Invalid JSON response: '.$response);
216            }
217
218            return $responseData;
219        } catch (\Exception $e) {
220            Log::channel('cofrai')->error('Error in request: '.$e->getMessage());
221            throw $e;
222        }
223    }
224
225    /**
226     * @return true
227     *
228     * @throws \Exception
229     */
230    public function updateApiCredentials($params, $region = null)
231    {
232        try {
233            $this->getCredentials($region);
234
235            $updateData = [];
236            if (isset($params['url'])) {
237                if (substr($params['url'], -1) !== '/') {
238                    $params['url'] .= '/';
239                }
240                $updateData['url'] = $this->encrypt($params['url']);
241            }
242
243            if (isset($params['user'])) {
244                $updateData['user'] = $this->encrypt($params['user']);
245            }
246
247            if (isset($params['password'])) {
248                $updateData['password'] = $this->encrypt($params['password']);
249            }
250
251            $updateData['user_id'] = $params['user_id'] ?? null;
252
253            if (empty($updateData)) {
254                throw new \Exception('No data provided to update.');
255            }
256
257            TblCofraiCredentials::where('region', $region)->update($updateData);
258
259            return true;
260        } catch (\Exception $e) {
261            Log::channel('cofrai')->error('Error updating credentials for region '.$this->region.': '.$e->getMessage());
262            throw $e;
263        }
264    }
265
266    /**
267     * @return JsonResponse
268     */
269    public function getApiDetails($region = null)
270    {
271        $this->getCredentials($region);
272        if (! $this->credentials) {
273            return response()->json(['message' => 'No credentials found'], 404);
274        }
275
276        return response()->json([
277            'url' => $this->decrypt($this->credentials->url),
278            'user' => $this->decrypt($this->credentials->user),
279        ]);
280    }
281
282    /**
283     * @return JsonResponse
284     */
285    public function getLastUpdate($region)
286    {
287        $lastUpdate = TblCofraiLastUpdate::where('region', $region)->first();
288
289        if (! $lastUpdate) {
290            return response()->json(['message' => 'No last update found'], 404);
291        }
292
293        return response()->json([
294            'lastUpdate' => $lastUpdate->updated_at->format('Y-m-d H:i:s'),
295            'updatingNow' => $lastUpdate->updatingNow,
296        ]);
297    }
298
299    public function getSyncStatus($region)
300    {
301        if ($region === "'Catalunya'") {
302            $region = 'Cataluña';
303        }
304
305        return TblCofraiLastUpdate::where('region', $region)->first()->updatingNow ?? 0;
306
307    }
308
309    public function setSyncStatus($status, $region)
310    {
311        if ($region === 'Catalunya' || $region === "'Catalunya'") {
312            $region = 'Cataluña';
313        }
314
315        // Mirror of the G3W setSyncStatus fix (GestionaService): the row is
316        // only seeded for the regions that have run a sync before. Use
317        // firstOrCreate so any new region (e.g. Comunidad Valenciana on first
318        // sync-by-ids) auto-provisions instead of fataling on null assignment.
319        $record = TblCofraiLastUpdate::firstOrCreate(
320            ['region' => $region],
321            ['cofrai_id' => 0, 'updatingNow' => 0, 'updated_at' => now()],
322        );
323
324        $record->updatingNow = $status;
325        $record->save();
326    }
327
328    public function getCofraiActive($region)
329    {
330        return TblCompanies::where('region', $region)->first()->cofrai_active ?? 0;
331    }
332
333    public function updateCofraiActive($active, $region)
334    {
335        $record = TblCompanies::where('region', $region)->first();
336
337        $record->cofrai_active = $active;
338        $record->save();
339    }
340
341    public function getBudgetsByDay($date, $region)
342    {
343        // FIRE-1077: Cofrai's API does NOT have a date-filtered budget
344        // endpoint (Gestiona does, at `presupuesto?fecha=X`). This method
345        // exists for parity with GestionaService but Cofrai callers should
346        // use getAllBudgetsWithDates() instead — it returns the full list
347        // in one call and the caller filters locally.
348        return $this->getAllBudgetsWithDates($region);
349    }
350
351    /**
352     * FIRE-1077: Cofrai-friendly "all budgets, with their date" endpoint.
353     * Paginated fetch returning [{id, date}, ...]. Callers that need
354     * per-day buckets group locally (cheaper than N API calls).
355     *
356     * Cofrai's `/model/sync` defaults to per_page=50 and supports up to 300
357     * (per the OpenAPI spec). Without explicit pagination params the call
358     * silently truncates at 50 records — this loop walks all pages and
359     * terminates when the last partial page comes back (< per_page rows).
360     * SimplePaginate-style responses don't expose `last_page`.
361     *
362     * Returns the same shape callers already expect: {data: [{id, date}, ...]}.
363     */
364    public function getAllBudgetsWithDates($region)
365    {
366        $perPage = 300;
367        $page = 1;
368        $all = [];
369
370        do {
371            $batch = $this->request(
372                'get',
373                "model/sync?model=budget&fields=id,date&per_page={$perPage}&page={$page}",
374                $region,
375                []
376            );
377
378            if (is_string($batch)) {
379                $batch = json_decode($batch, true);
380            }
381
382            if (! is_array($batch) || empty($batch['data']) || ! is_array($batch['data'])) {
383                break;
384            }
385
386            $all = array_merge($all, $batch['data']);
387            $count = count($batch['data']);
388            $page++;
389        } while ($count === $perPage);
390
391        return ['data' => $all];
392    }
393
394    /**
395     * FIRE-1077: mirror of GestionaService::checkDeleted. Returns true when
396     * Cofrai's API can't find the given id. Cofrai's "not found" semantics:
397     * `model/sync?model=budget&ids={id}` returns empty `data` array.
398     *
399     * For monitor pages that need to check many IDs, prefer
400     * checkDeletedBatch() — it's a single round-trip vs N.
401     */
402    public function checkDeleted($id, $region): bool
403    {
404        try {
405            $response = $this->request('get', "model/sync?model=budget&ids={$id}&fields=id", $region, []);
406
407            $data = is_array($response) ? ($response['data'] ?? null) : null;
408
409            return empty($data);
410        } catch (\Exception $e) {
411            if (str_contains($e->getMessage(), 'No se ha encontrado el presupuesto')) {
412                return true;
413            }
414
415            return false;
416        }
417    }
418
419    /**
420     * FIRE-1077: efficient bulk version of checkDeleted. Given a list of
421     * Cofrai budget IDs, returns the subset that are NO LONGER in Cofrai
422     * (i.e. "deleted upstream"). Uses one fetch of the full budget list,
423     * then a local set-difference.
424     */
425    public function checkDeletedBatch(array $ids, $region): array
426    {
427        if (empty($ids)) {
428            return [];
429        }
430
431        $response = $this->getAllBudgetsWithDates($region);
432        $remoteIds = [];
433        if (is_array($response) && isset($response['data']) && is_array($response['data'])) {
434            foreach ($response['data'] as $b) {
435                if (isset($b['id'])) {
436                    $remoteIds[(string) $b['id']] = true;
437                }
438            }
439        }
440
441        return array_values(array_filter($ids, fn ($id) => ! isset($remoteIds[(string) $id])));
442    }
443}