Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 141
0.00% covered (danger)
0.00%
0 / 5
CRAP
0.00% covered (danger)
0.00%
0 / 1
IfexController
0.00% covered (danger)
0.00%
0 / 141
0.00% covered (danger)
0.00%
0 / 5
756
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
2
 request
0.00% covered (danger)
0.00%
0 / 34
0.00% covered (danger)
0.00%
0 / 1
132
 syncQuotations
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 1
30
 createQuotation
0.00% covered (danger)
0.00%
0 / 46
0.00% covered (danger)
0.00%
0 / 1
30
 updateQuotation
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 1
30
1<?php
2
3namespace App\Http\Controllers;
4
5use App\Http\Controllers\Controller;
6use App\Models\ifex\TblClientes;
7use App\Models\ifex\TblPresupuestos;
8use App\Models\TblIfexLastUpdate;
9use App\Models\TblQuotations;
10use App\Services\PresupuestosService;
11use Carbon\Carbon;
12use Illuminate\Support\Facades\Log;
13use Mockery\Exception;
14
15
16class IfexController extends Controller
17{
18    protected $presupuestosService;
19    protected $statusNormalize;
20
21    public function __construct(PresupuestosService $presupuestosService)
22    {
23        $this->presupuestosService = $presupuestosService;
24
25        $this->statusNormalize = [
26            "Oportunidad" => 1, //Oportunidad => Nuevo
27            "Pendiente" => 11, //Pendiente => Listo para enviar
28            "Pendiente Cliente" => 2, //Pendiente Cliente => Enviado
29            "Aceptado" => 3, //Aceptado => Aceptado
30            "En ejecución" => 12, //En ejecución => En proceso
31            "Rechazado" => 4, //Rechazado => Rechazado
32            "Anulado" => 5, //Anulado => Anulado
33            "Finalizado" => 3 //Finalizado => Aceptado
34        ];
35
36    }
37
38    protected function request($method, $endpoint, array $data = [])
39    {
40        try {
41            //$this->getCredentials($region);
42
43            /*if (!$this->apiUrl) {
44                throw new \Exception('API URL is not defined.');
45            }
46
47            if (!$this->accessToken) {
48                $this->auth($region);
49            }*/
50            $apiUrl = "https://titanapi-h9a2d7bvfqckfzep.spaincentral-01.azurewebsites.net/";
51
52            $url = "{$apiUrl}{$endpoint}";
53            $curl = curl_init();
54
55            curl_setopt_array($curl, [
56                CURLOPT_URL => $url,
57                CURLOPT_RETURNTRANSFER => true,
58                CURLOPT_CUSTOMREQUEST => strtoupper($method),
59                CURLOPT_HTTPHEADER => [
60                    'x-api-key: 9E5reQeWEktx3Cd0uODpjTQTZlEEZjDW' 
61                ],
62            ]);
63
64            if (in_array(strtoupper($method), ['POST', 'PUT', 'PATCH']) && !empty($data)) {
65                if (!is_array($data)) {
66                    throw new \Exception('The $data parameter must be an array.');
67                }
68                curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
69            }
70
71            $response = curl_exec($curl);
72
73            if (curl_errno($curl)) {
74                throw new \Exception('cURL error: ' . curl_error($curl));
75            }
76
77            $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
78            curl_close($curl);
79
80            /*if ($httpCode === 401) {
81                $this->auth($region);
82                return $this->request($method, $endpoint, $region, $data);
83            }*/
84
85            if ($httpCode < 200 || $httpCode >= 300) {
86                Log::channel('ifex')->error('API Response Error: ' . $response);
87
88                $errorResponse = json_decode($response, true);
89                $errorMessage = is_array($errorResponse) && isset($errorResponse['message'])
90                    ? $errorResponse['message']
91                    : 'Request error: ' . $response;
92
93                throw new \Exception($errorMessage);
94            }
95
96            $responseData = json_decode($response, true);
97
98            if (json_last_error() !== JSON_ERROR_NONE) {
99                throw new \Exception('Invalid JSON response: ' . $response);
100            }
101
102            return $responseData;
103        } catch (\Exception $e) {
104            Log::channel('g3w')->error('Error in request: ' . $e->getMessage());
105            throw $e;
106        }
107    }
108
109    public function syncQuotations(){
110        try{
111            $today = Carbon::now()->format('Y-m-d');
112            $requestDate = "presupuestos/creados-editados?fechainicio={$today}&fechafin={$today}";
113
114            $quotationsToSync = json_decode(json_encode($this->request("GET", $requestDate)));
115
116            foreach($quotationsToSync as $quotation){
117                if(TblQuotations::where("internal_quote_id", $quotation->codigo)->exists()){
118                    $this->updateQuotation($quotation);
119                } else {
120                    $this->createQuotation($quotation);
121                }
122
123            }
124
125            TblIfexLastUpdate::where("id", 1)->first()->update(
126                array(
127                    "last_date" => Carbon::now()->format('Y-m-d H:i:s')
128                )
129            );
130
131            return ['success' => true, 'quotations' => $quotationsToSync];
132        }catch (\Exception $e){
133            /** @disregard P1014 */
134            $e->exceptionCode = 'SYNC_QUOTATIONS_IFEX_EXCEPTION'; 
135            report($e);
136            Log::channel('ifex')->error('Error updating quotations: ' . $e->getMessage(), [
137                'exception' => $e
138            ]);
139
140            return response()->json([
141                'success' => false,
142                'message' => 'Failed to update ifex quotations',
143                'error' => $e->getMessage(),
144                'error_code' => $e->getCode() ?: 500
145            ], 500);
146        }
147    }
148
149    public function createQuotation($quotation){
150        //instalaciones 6 25O
151        //correctivos 3 25C
152        //mantenimiento 1 25P
153        $type = null;
154        if (strpos($quotation->codigo, "25O") !== false) {
155            $type = 6;
156        }
157
158        if (strpos($quotation->codigo, "25C") !== false) {
159            $type = 3;
160        }
161
162        if (strpos($quotation->codigo, "25P") !== false) {
163            $type = 1;
164        }
165        if (strpos($quotation->codigo, "G25") !== false) {
166            return;
167        }
168
169        $generateNumber = $this->presupuestosService->generateQuoteId(30);
170
171        $g3wNewId = $generateNumber['id'];
172        $newQuoteId = $generateNumber['number'];
173
174        $ifexArray = array(
175            'internal_quote_id' => $quotation->codigo,
176            'quote_id' => $newQuoteId,
177            'company_id' => 30,
178            'customer_type_id' => 2,
179            'segment_id' => null,
180            'budget_type_id' => $type,
181            'budget_status_id' => $this->statusNormalize[$quotation->estado],
182            'source_id' => 55,
183            'client' => $quotation->clienteNombre?? null,
184            'phone_number' => $quotation->clienteTelefono?? null,
185            'email' => $quotation->clienteMail?? null,
186            'issue_date' => $quotation->fecha?? null,
187            'request_date' => $quotation->fechaAlta?? null,
188            'acceptance_date' => $quotation->fechaAceptacion?? null,
189            'amount' => $quotation->baseImponible?? null,
190            'last_follow_up_date' => null,
191            'commercial' => "Ifex",
192            'created_at' => $quotation->fecha?? null,
193            'created_by' => "Ifex",
194            'has_attachment' => 0,
195            'cost_of_labor' => 0,
196            'total_cost_of_job' => 0,
197            'invoice_margin' => 0,
198            'margin_for_the_company' => 0,
199            'revenue_per_date_per_worked' => 0,
200            'gross_margin' => 100,
201            'labor_percentage' => 0,
202            'sync_import' => 1,
203            'box_work_g3w' => null,
204            'for_add' => 0,
205            'for_approval' => 0,
206        );
207
208        TblQuotations::where('id', $g3wNewId)->update($ifexArray);
209    }
210
211    public function updateQuotation($quotation){
212        $fstQuotation = TblQuotations::where("internal_quote_id", $quotation->codigo)->first();
213
214        //instalaciones 6 25O
215        //correctivos 3 25C
216        //mantenimiento 1 25P
217        $type = null;
218        if (strpos($quotation->codigo, "25O") !== false) {
219            $type = 6;
220        }
221
222        if (strpos($quotation->codigo, "25C") !== false) {
223            $type = 3;
224        }
225
226        if (strpos($quotation->codigo, "25P") !== false) {
227            $type = 1;
228        }
229        if (strpos($quotation->codigo, "G25") !== false) {
230            return;
231        }
232
233        $ifexArray = array(
234            'internal_quote_id' => $quotation->codigo,
235            'budget_type_id' => $type,
236            'budget_status_id' => $this->statusNormalize[$quotation->estado],
237            'client' => $quotation->clienteNombre?? null,
238            'phone_number' => $quotation->clienteTelefono?? null,
239            'email' => $quotation->clienteMail?? null,
240            'issue_date' => $quotation->fecha?? null,
241            'request_date' => $quotation->fechaAlta?? null,
242            'acceptance_date' => $quotation->fechaAceptacion?? null,
243            'amount' => $quotation->baseImponible?? null,
244            'updated_at' => Carbon::now()->format('Y-m-d H:i:s'),
245            'updated_by' => "Ifex"
246        );
247
248        $fstQuotation->update($ifexArray);
249
250    }
251
252}