Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
0.08% |
1 / 1216 |
|
4.35% |
1 / 23 |
CRAP | |
0.00% |
0 / 1 |
| FacturasService | |
0.08% |
1 / 1216 |
|
4.35% |
1 / 23 |
37350.18 | |
0.00% |
0 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| getInvoices | |
0.00% |
0 / 18 |
|
0.00% |
0 / 1 |
6 | |||
| loopInvoices | |
0.00% |
0 / 212 |
|
0.00% |
0 / 1 |
650 | |||
| loopNextRemindersInvoices | |
0.00% |
0 / 73 |
|
0.00% |
0 / 1 |
90 | |||
| loopNextRemindersClients | |
0.00% |
0 / 148 |
|
0.00% |
0 / 1 |
380 | |||
| sendInvoice | |
0.00% |
0 / 173 |
|
0.00% |
0 / 1 |
930 | |||
| getAllInvoices | |
0.00% |
0 / 15 |
|
0.00% |
0 / 1 |
6 | |||
| getAllInvoicesExceptions | |
0.00% |
0 / 10 |
|
0.00% |
0 / 1 |
2 | |||
| sendCyCInvoices | |
0.00% |
0 / 68 |
|
0.00% |
0 / 1 |
110 | |||
| setAllMonthAdministratorsInvoices | |
0.00% |
0 / 52 |
|
0.00% |
0 / 1 |
182 | |||
| sendAdministratorsInvoices | |
0.00% |
0 / 88 |
|
0.00% |
0 / 1 |
42 | |||
| checkClientHasFreshdeskTask | |
0.00% |
0 / 11 |
|
0.00% |
0 / 1 |
12 | |||
| checkClientHasFreshdeskTaskAll | |
0.00% |
0 / 15 |
|
0.00% |
0 / 1 |
30 | |||
| sendCallCenterInvoices | |
0.00% |
0 / 80 |
|
0.00% |
0 / 1 |
306 | |||
| addToSheets | |
0.00% |
0 / 36 |
|
0.00% |
0 / 1 |
56 | |||
| getGoogleSheetsService | |
0.00% |
0 / 24 |
|
0.00% |
0 / 1 |
56 | |||
| writeToGoogleSheet | |
0.00% |
0 / 17 |
|
0.00% |
0 / 1 |
6 | |||
| handleGoogleAuthCallback | |
0.00% |
0 / 30 |
|
0.00% |
0 / 1 |
42 | |||
| getVencimientosFormateados | |
0.00% |
0 / 6 |
|
0.00% |
0 / 1 |
6 | |||
| listCreditDaysOffered | |
0.00% |
0 / 77 |
|
0.00% |
0 / 1 |
240 | |||
| recordSkip | |
0.00% |
0 / 16 |
|
0.00% |
0 / 1 |
6 | |||
| syncPaymentDateForInvoice | |
0.00% |
0 / 13 |
|
0.00% |
0 / 1 |
30 | |||
| syncPaymentDatesForRegion | |
0.00% |
0 / 33 |
|
0.00% |
0 / 1 |
20 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace App\Services; |
| 4 | |
| 5 | use App\Models\TblCompanies; |
| 6 | use App\Models\TblInvoiceAdministrators; |
| 7 | use App\Models\TblInvoiceReminders; |
| 8 | use App\Models\TblInvoiceRemindersEmailTemplate; |
| 9 | use App\Models\TblInvoiceReminderSkips; |
| 10 | use App\Models\TblInvoicesExceptions; |
| 11 | use App\Models\TblInvoicesNextReminders; |
| 12 | use Carbon\Carbon; |
| 13 | use Google\Client; |
| 14 | use Google\Service\Sheets; |
| 15 | use Google\Service\Sheets\ValueRange; |
| 16 | use Illuminate\Http\Request; |
| 17 | use Illuminate\Support\Facades\Http; |
| 18 | use Illuminate\Support\Facades\Log; |
| 19 | use Mockery\Exception; |
| 20 | use SendGrid\Mail\Attachment; |
| 21 | use SendGrid\Mail\Mail; |
| 22 | |
| 23 | class FacturasService extends GestionaService |
| 24 | { |
| 25 | public function __construct() |
| 26 | { |
| 27 | parent::__construct(); |
| 28 | } |
| 29 | |
| 30 | public function getInvoices($region = 'Cataluña'): array |
| 31 | { |
| 32 | try { |
| 33 | // FIRE-1293 (Berta feedback, 2026-07): run the full flow for every |
| 34 | // Gestiona region so the KPI can display "potential" for regions |
| 35 | // that haven't opted in yet. The active flag now gates only the |
| 36 | // real SendGrid call inside the loops; everything else — skip |
| 37 | // telemetry, would-send counting — happens either way. |
| 38 | $companyActive = TblCompanies::where('region', $region) |
| 39 | ->where('invoice_reminder_active', 1) |
| 40 | ->exists(); |
| 41 | |
| 42 | $today = date('Y-m-d'); |
| 43 | $next10days = date('Y-m-d', strtotime('+10 days')); |
| 44 | $lastWeek = date('Y-m-d', strtotime('-1 week')); |
| 45 | |
| 46 | $counter = 1; |
| 47 | |
| 48 | $nextWeekInvoices = $this->request('get', 'factura/vence/'.$next10days, $region, []); |
| 49 | // $todayInvoices = $this->request('get', 'factura/vence/' . $today, $region, []); |
| 50 | $lastWeekInvoices = $this->request('get', 'factura/vence/'.$lastWeek, $region, []); |
| 51 | |
| 52 | $resultNextWeekInvoices = $this->loopInvoices($nextWeekInvoices, 1, $region, $counter, $next10days, $companyActive); |
| 53 | /*$counter = $resultNextWeekInvoices["counter"] - 1; |
| 54 | if($counter >= 30){ |
| 55 | return ['success' => true]; |
| 56 | }*/ |
| 57 | |
| 58 | // $resultTodayInvoices = $this->loopInvoices($todayInvoices, 2, $region, $counter); |
| 59 | /*$counter = $resultTodayInvoices["counter"] - 1; |
| 60 | if($counter >= 30){ |
| 61 | return ['success' => true]; |
| 62 | }*/ |
| 63 | |
| 64 | $this->loopInvoices($lastWeekInvoices, 3, $region, $counter, $lastWeek, $companyActive); |
| 65 | |
| 66 | $this->loopNextRemindersInvoices($region, $companyActive); |
| 67 | |
| 68 | $this->loopNextRemindersClients($region, $next10days, $lastWeek, $companyActive); |
| 69 | |
| 70 | return ['success' => true]; |
| 71 | } catch (\Exception $e) { |
| 72 | Log::channel('g3w_invoices')->error($e->getMessage()); |
| 73 | Log::error('Trace: '.$e->getTraceAsString()); |
| 74 | |
| 75 | return ['success' => false, 'error' => $e->getMessage()]; |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | public function loopInvoices(array $invoices, $reminder_type, $region, $counter, $date = null, bool $companyActive = true): array |
| 80 | { |
| 81 | $senders = []; |
| 82 | foreach ($invoices['facturas'] as $invoice) { |
| 83 | // Continue if region is Comunidad Valenciana and the invoice starts with M |
| 84 | if ( |
| 85 | $region == 'Comunidad Valenciana' |
| 86 | && str_starts_with((string) $invoice['ID'], 'M') |
| 87 | ) { |
| 88 | $this->recordSkip($region, (string) $invoice['ID'], 'region_filter_cv_m_prefix', null, $reminder_type); |
| 89 | |
| 90 | continue; |
| 91 | } |
| 92 | |
| 93 | // FIRE-1586: same pattern for Aeroextinción — Andalucía region, |
| 94 | // invoice IDs starting with 'C' are Aeroextinción's series and |
| 95 | // must not receive automatic reminders (per Berta). recordSkip |
| 96 | // so the KPI panel surfaces the count under its own bucket. |
| 97 | if ( |
| 98 | $region == 'Andalucía' |
| 99 | && str_starts_with((string) $invoice['ID'], 'C') |
| 100 | ) { |
| 101 | $this->recordSkip($region, (string) $invoice['ID'], 'region_filter_and_c_prefix', null, $reminder_type); |
| 102 | |
| 103 | continue; |
| 104 | } |
| 105 | |
| 106 | // Already scheduled for a future reminder — not a skip, just routed |
| 107 | // to a different cron path (tracked in tbl_invoice_next_reminders). |
| 108 | $existNextReminderInvoice = TblInvoicesNextReminders::where('invoice_number', $invoice['ID']) |
| 109 | ->where('region', $region) |
| 110 | ->exists(); |
| 111 | |
| 112 | if ($existNextReminderInvoice) { |
| 113 | continue; |
| 114 | } |
| 115 | |
| 116 | $dataInvoice = $this->request('get', 'factura/'.$invoice['ID'], $region, []); |
| 117 | |
| 118 | if (! isset($dataInvoice['factura'])) { |
| 119 | $this->recordSkip($region, (string) $invoice['ID'], 'g3w_factura_missing', null, $reminder_type); |
| 120 | |
| 121 | continue; |
| 122 | } |
| 123 | |
| 124 | if ($this->checkClientHasFreshdeskTask($dataInvoice['factura']['cod_cliente'], $region)) { |
| 125 | $this->recordSkip( |
| 126 | $region, |
| 127 | (string) ($dataInvoice['factura']['n_factura'] ?? $invoice['ID']), |
| 128 | 'freshdesk_task_active', |
| 129 | null, |
| 130 | $reminder_type, |
| 131 | (string) ($dataInvoice['factura']['cod_cliente'] ?? null), |
| 132 | ); |
| 133 | |
| 134 | continue; |
| 135 | } |
| 136 | |
| 137 | $cobrada = $dataInvoice['factura']['cobrada']; |
| 138 | $formaPago = $dataInvoice['factura']['forma_pago_factura']; |
| 139 | |
| 140 | // Invoice already paied |
| 141 | // Invoice that the payment method is not "transferencia" |
| 142 | if ( |
| 143 | $cobrada !== 'NO' |
| 144 | || stripos((string) $formaPago, 'tr') === false |
| 145 | ) { |
| 146 | $this->recordSkip( |
| 147 | $region, |
| 148 | (string) ($dataInvoice['factura']['n_factura'] ?? $invoice['ID']), |
| 149 | $cobrada !== 'NO' ? 'already_paid' : 'payment_method_not_transfer', |
| 150 | ['cobrada' => $cobrada, 'forma_pago' => $formaPago], |
| 151 | $reminder_type, |
| 152 | (string) ($dataInvoice['factura']['cod_cliente'] ?? null), |
| 153 | ); |
| 154 | |
| 155 | continue; |
| 156 | } |
| 157 | |
| 158 | $existNextReminderClient = TblInvoicesNextReminders::where('id_client', $dataInvoice['factura']['cod_cliente']) |
| 159 | ->where('region', $region) |
| 160 | ->exists(); |
| 161 | |
| 162 | if ($existNextReminderClient) { |
| 163 | $this->addToSheets($dataInvoice['factura']['cod_cliente'], $dataInvoice['factura']['n_factura'], $region); |
| 164 | |
| 165 | TblInvoicesNextReminders::create([ |
| 166 | 'id_client' => $dataInvoice['factura']['cod_cliente'], |
| 167 | 'region' => $region, |
| 168 | 'invoice_number' => $dataInvoice['factura']['n_factura'], |
| 169 | ]); |
| 170 | |
| 171 | continue; |
| 172 | } |
| 173 | |
| 174 | $dataClient = null; |
| 175 | |
| 176 | if ($dataInvoice['factura']['cod_cliente']) { |
| 177 | $dataClient = $this->request('get', 'cliente/'.$dataInvoice['factura']['cod_cliente'], $region, []); |
| 178 | } |
| 179 | |
| 180 | if ($dataClient['cliente']['tipo_cliente'] == 'Administrador') { |
| 181 | $codService = $dataInvoice['factura']['lineas'][0]['cod_servicio']; |
| 182 | $dataService = $this->request('get', 'servicio/'.$codService, $region, []); |
| 183 | |
| 184 | TblInvoiceAdministrators::create([ |
| 185 | 'invoice_number' => $dataInvoice['factura']['n_factura'], |
| 186 | 'region' => $region, |
| 187 | 'name' => $dataClient['cliente']['empresa'], |
| 188 | 'CIF' => $dataClient['cliente']['cliente_cif'], |
| 189 | 'email' => $dataClient['cliente']['email'], |
| 190 | 'service_name' => $dataService['servicio']['nombre_servicio'], |
| 191 | 'service_addres' => $dataService['servicio']['direccion'], |
| 192 | 'send_date' => $date, |
| 193 | 'expiration_date' => $date, |
| 194 | 'amount' => $dataInvoice['factura']['importe_total_factura'], |
| 195 | ]); |
| 196 | |
| 197 | continue; |
| 198 | } |
| 199 | |
| 200 | $exists = TblInvoicesExceptions::where('cif', $dataClient['cliente']['cliente_cif']) |
| 201 | ->orWhere('name', $dataClient['cliente']['empresa']) |
| 202 | ->orWhere('administrator', $dataClient['cliente']['empresa']) |
| 203 | ->orWhere('id_admin_g3w', $invoice['ID']) |
| 204 | ->orWhere('invoice_number', $dataInvoice['factura']['n_factura']) |
| 205 | ->exists(); |
| 206 | |
| 207 | if ($exists) { |
| 208 | $this->recordSkip( |
| 209 | $region, |
| 210 | (string) ($dataInvoice['factura']['n_factura'] ?? $invoice['ID']), |
| 211 | 'in_exceptions_table', |
| 212 | [ |
| 213 | 'cif' => $dataClient['cliente']['cliente_cif'] ?? null, |
| 214 | 'empresa' => $dataClient['cliente']['empresa'] ?? null, |
| 215 | ], |
| 216 | $reminder_type, |
| 217 | (string) ($dataInvoice['factura']['cod_cliente'] ?? null), |
| 218 | ); |
| 219 | |
| 220 | continue; |
| 221 | } |
| 222 | |
| 223 | $invoice_number = $dataInvoice['factura']['n_factura'] ?? null; |
| 224 | $client_name = $dataClient['cliente']['empresa'] ?? null; |
| 225 | $client_email = $dataClient['cliente']['email'] ?? $dataClient['cliente']['email_facturacion'] ?? null; |
| 226 | $cif = $dataClient['cliente']['cliente_cif'] ?? null; |
| 227 | $issued_date = $dataInvoice['factura']['fecha_emision'] ?? null; |
| 228 | $expiration_date = $date ?? $dataInvoice['factura']['vencimientos'][0]['fecha_vencimiento']; |
| 229 | $amount = $dataInvoice['factura']['importe_total_factura'] ?? null; |
| 230 | $collection_date = null; |
| 231 | $document = $dataInvoice['factura']['documento'] ?? null; |
| 232 | $senders[$cif][] = [ |
| 233 | 'invoice_number' => $invoice_number, |
| 234 | 'client_name' => $client_name, |
| 235 | 'client_email' => $client_email, |
| 236 | 'issued_date' => $issued_date, |
| 237 | 'expiration_date' => $expiration_date, |
| 238 | 'document' => $document, |
| 239 | 'amount' => $amount, |
| 240 | 'reminder_type' => $reminder_type, |
| 241 | 'cif' => $cif, |
| 242 | 'collection_date' => $collection_date, |
| 243 | 'region' => $region, |
| 244 | ]; |
| 245 | |
| 246 | } |
| 247 | |
| 248 | if (config('app.env') === 'production') { |
| 249 | foreach ($senders as $cif => $invoicesGroup) { |
| 250 | |
| 251 | $totalFacturas = count($invoicesGroup); |
| 252 | |
| 253 | if ($totalFacturas === 1) { |
| 254 | // FIRE-1293 (Berta): if the region is inactive we still |
| 255 | // want to count the potential without emailing anyone. |
| 256 | if (! $companyActive) { |
| 257 | $this->recordSkip( |
| 258 | $region, |
| 259 | (string) $invoicesGroup[0]['invoice_number'], |
| 260 | 'region_inactive', |
| 261 | null, |
| 262 | (int) $invoicesGroup[0]['reminder_type'], |
| 263 | null, |
| 264 | (int) ($invoicesGroup[0]['amount'] ?? 0), |
| 265 | ); |
| 266 | $counter++; |
| 267 | |
| 268 | continue; |
| 269 | } |
| 270 | |
| 271 | // FIRE-1293 (Berta): "sent" = every attempt regardless of |
| 272 | // SendGrid outcome. Create the row first so a subsequent |
| 273 | // provider failure still shows up as a sent attempt in |
| 274 | // tbl_invoice_reminders; the sendgrid_send_failed skip |
| 275 | // stays for the "why did it fail" panel. |
| 276 | TblInvoiceReminders::create([ |
| 277 | 'invoice_number' => $invoicesGroup[0]['invoice_number'], |
| 278 | 'client_name' => $invoicesGroup[0]['client_name'], |
| 279 | 'client_email' => $invoicesGroup[0]['client_email'], |
| 280 | 'cif' => $invoicesGroup[0]['cif'], |
| 281 | 'issued_date' => $invoicesGroup[0]['issued_date'], |
| 282 | 'expiration_date' => $invoicesGroup[0]['expiration_date'], |
| 283 | 'amount' => $invoicesGroup[0]['amount'], |
| 284 | 'collection_date' => $invoicesGroup[0]['collection_date'], |
| 285 | 'region' => $invoicesGroup[0]['region'], |
| 286 | 'reminder_type' => $invoicesGroup[0]['reminder_type'], |
| 287 | ]); |
| 288 | |
| 289 | $resultSend = $this->sendInvoice( |
| 290 | $invoicesGroup[0]['invoice_number'], |
| 291 | $invoicesGroup[0]['client_name'], |
| 292 | $invoicesGroup[0]['client_email'], |
| 293 | $invoicesGroup[0]['issued_date'], |
| 294 | $invoicesGroup[0]['expiration_date'], |
| 295 | $invoicesGroup[0]['document'], |
| 296 | $invoicesGroup[0]['amount'], |
| 297 | $invoicesGroup[0]['reminder_type'], |
| 298 | $region); |
| 299 | |
| 300 | if (! $resultSend['success']) { |
| 301 | $this->recordSkip( |
| 302 | $region, |
| 303 | (string) $invoicesGroup[0]['invoice_number'], |
| 304 | 'sendgrid_send_failed', |
| 305 | ['error' => $resultSend['error'] ?? null], |
| 306 | (int) $invoicesGroup[0]['reminder_type'], |
| 307 | null, |
| 308 | (int) ($invoicesGroup[0]['amount'] ?? 0), |
| 309 | ); |
| 310 | } |
| 311 | } else { |
| 312 | $table = "<table style='border-collapse: collapse; width: 100%; font-family: Arial, sans-serif;'> |
| 313 | <tr> |
| 314 | <th style='border: 1px solid #999; padding: 8px; background-color: #f2f2f2; text-align: left;'>Número Factura</th> |
| 315 | <th style='border: 1px solid #999; padding: 8px; background-color: #f2f2f2; text-align: left;'>Nombre cliente de servicio</th> |
| 316 | <th style='border: 1px solid #999; padding: 8px; background-color: #f2f2f2; text-align: left;'>Dirección del servicio</th> |
| 317 | <th style='border: 1px solid #999; padding: 8px; background-color: #f2f2f2; text-align: left;'>Fecha de emisión</th> |
| 318 | <th style='border: 1px solid #999; padding: 8px; background-color: #f2f2f2; text-align: left;'>Fecha de vencimiento</th> |
| 319 | <th style='border: 1px solid #999; padding: 8px; background-color: #f2f2f2; text-align: left;'>Importe</th> |
| 320 | </tr>"; |
| 321 | $documentsBase64 = []; |
| 322 | |
| 323 | foreach ($invoicesGroup as $invoice) { |
| 324 | $invoiceG3W = $this->request('get', 'factura/'.$invoice['invoice_number'], $region, []); |
| 325 | $invoiceData = $invoiceG3W['factura']; |
| 326 | |
| 327 | $codService = $invoiceData['lineas'][0]['cod_servicio']; |
| 328 | $dataService = $this->request('get', 'servicio/'.$codService, $region, []); |
| 329 | $dataService = $dataService['servicio']; |
| 330 | |
| 331 | $invoiceNumber = $invoice['invoice_number']; |
| 332 | $table .= "<tr> |
| 333 | <td class='invoice_number' style='border: 1px solid #999; padding: 8px;'>".$invoiceNumber."</td> |
| 334 | <td class='invoice_service_name' style='border: 1px solid #999; padding: 8px;'>".$dataService['nombre_servicio']."</td> |
| 335 | <td class='invoice_service_addres' style='border: 1px solid #999; padding: 8px;'>".$dataService['direccion']."</td> |
| 336 | <td class='invoice_send_date' style='border: 1px solid #999; padding: 8px;'>".Carbon::now()->format('d-m-Y')."</td> |
| 337 | <td class='invoice_expiration_date' style='border: 1px solid #999; padding: 8px;'>".$invoice['expiration_date']."</td> |
| 338 | <td class='invoice_amount' style='border: 1px solid #999; padding: 8px;'>".$invoice['amount'].' €</td> |
| 339 | </tr>'; |
| 340 | |
| 341 | $documentsBase64[] = [ |
| 342 | 'content' => $invoiceData['documento'], |
| 343 | 'filename' => "Factura_{$invoiceNumber}.pdf", |
| 344 | ]; |
| 345 | } |
| 346 | |
| 347 | $table .= '</table>'; |
| 348 | |
| 349 | // FIRE-1293 (Berta): read-only regions log the potential |
| 350 | // as a skip and don't hit SendGrid. One row per invoice |
| 351 | // in the group so the KPI counts each individually. |
| 352 | if (! $companyActive) { |
| 353 | foreach ($invoicesGroup as $inv) { |
| 354 | $this->recordSkip( |
| 355 | $region, |
| 356 | (string) $inv['invoice_number'], |
| 357 | 'region_inactive', |
| 358 | null, |
| 359 | (int) $inv['reminder_type'], |
| 360 | null, |
| 361 | (int) ($inv['amount'] ?? 0), |
| 362 | ); |
| 363 | } |
| 364 | } else { |
| 365 | $this->sendInvoice( |
| 366 | $invoicesGroup[0]['invoice_number'], |
| 367 | $invoicesGroup[0]['client_name'], |
| 368 | $invoicesGroup[0]['client_email'], |
| 369 | Carbon::now()->format('d-m-Y'), |
| 370 | $invoicesGroup[0]['expiration_date'], |
| 371 | $documentsBase64, |
| 372 | $invoicesGroup[0]['amount'], |
| 373 | $invoicesGroup[0]['reminder_type'] === '1' ? 5 : 6, |
| 374 | $region, |
| 375 | $table |
| 376 | ); |
| 377 | } |
| 378 | |
| 379 | } |
| 380 | |
| 381 | $counter++; |
| 382 | |
| 383 | } |
| 384 | } |
| 385 | |
| 386 | return [ |
| 387 | 'success' => true, |
| 388 | 'counter' => $counter, |
| 389 | ]; |
| 390 | } |
| 391 | |
| 392 | private function loopNextRemindersInvoices($region, bool $companyActive = true): void |
| 393 | { |
| 394 | $nextReminders = TblInvoicesNextReminders::where('region', $region) |
| 395 | ->where('next_reminders', date('Y-m-d')) |
| 396 | ->pluck('invoice_number'); |
| 397 | |
| 398 | foreach ($nextReminders as $nextReminder) { |
| 399 | $dataInvoice = $this->request('get', 'factura/'.$nextReminder, $region, []); |
| 400 | |
| 401 | if ($this->checkClientHasFreshdeskTask($dataInvoice['factura']['cod_cliente'], $region)) { |
| 402 | $this->recordSkip( |
| 403 | $region, |
| 404 | (string) ($dataInvoice['factura']['n_factura'] ?? $nextReminder), |
| 405 | 'freshdesk_task_active', |
| 406 | null, |
| 407 | 2, |
| 408 | (string) ($dataInvoice['factura']['cod_cliente'] ?? null), |
| 409 | ); |
| 410 | |
| 411 | continue; |
| 412 | } |
| 413 | |
| 414 | $cobrada = $dataInvoice['factura']['cobrada']; |
| 415 | $formaPago = $dataInvoice['factura']['forma_pago_factura']; |
| 416 | |
| 417 | // Invoice already paied |
| 418 | // Invoice that the payment method is not "transferencia" |
| 419 | if ( |
| 420 | $cobrada !== 'NO' |
| 421 | || stripos((string) $formaPago, 'tr') === false |
| 422 | ) { |
| 423 | $this->recordSkip( |
| 424 | $region, |
| 425 | (string) ($dataInvoice['factura']['n_factura'] ?? $nextReminder), |
| 426 | $cobrada !== 'NO' ? 'already_paid' : 'payment_method_not_transfer', |
| 427 | ['cobrada' => $cobrada, 'forma_pago' => $formaPago], |
| 428 | 2, |
| 429 | (string) ($dataInvoice['factura']['cod_cliente'] ?? null), |
| 430 | ); |
| 431 | |
| 432 | continue; |
| 433 | } |
| 434 | |
| 435 | $dataClient = $this->request('get', 'cliente/'.$dataInvoice['factura']['cod_cliente'], $region, []); |
| 436 | |
| 437 | $invoice_number = $dataInvoice['factura']['n_factura'] ?? null; |
| 438 | $client_name = $dataClient['cliente']['empresa'] ?? null; |
| 439 | $client_email = $dataClient['cliente']['email'] ?? $dataClient['cliente']['email_facturacion'] ?? null; |
| 440 | $cif = $dataClient['cliente']['cliente_cif'] ?? null; |
| 441 | $issued_date = $dataInvoice['factura']['fecha_emision'] ?? null; |
| 442 | $expiration_date = $this->getVencimientosFormateados($dataInvoice); |
| 443 | $amount = $dataInvoice['factura']['importe_total_factura'] ?? null; |
| 444 | $collection_date = null; |
| 445 | $document = $dataInvoice['factura']['documento'] ?? null; |
| 446 | |
| 447 | // FIRE-1293 (Berta): read-only regions record potential and skip send. |
| 448 | if (! $companyActive) { |
| 449 | $this->recordSkip( |
| 450 | $region, |
| 451 | (string) $invoice_number, |
| 452 | 'region_inactive', |
| 453 | null, |
| 454 | 2, |
| 455 | (string) ($dataInvoice['factura']['cod_cliente'] ?? null), |
| 456 | (int) ($amount ?? 0), |
| 457 | ); |
| 458 | |
| 459 | continue; |
| 460 | } |
| 461 | |
| 462 | // FIRE-1293 (Berta): create sent row first so SendGrid failures |
| 463 | // still count as sent attempts in tbl_invoice_reminders. |
| 464 | TblInvoiceReminders::create([ |
| 465 | 'invoice_number' => $invoice_number, |
| 466 | 'client_name' => $client_name, |
| 467 | 'client_email' => $client_email, |
| 468 | 'cif' => $cif, |
| 469 | 'issued_date' => $issued_date, |
| 470 | 'expiration_date' => $expiration_date, |
| 471 | 'amount' => $amount, |
| 472 | 'collection_date' => $collection_date, |
| 473 | 'region' => $region, |
| 474 | 'reminder_type' => 2, |
| 475 | ]); |
| 476 | |
| 477 | if (config('app.env') === 'production') { |
| 478 | $resultSend = $this->sendInvoice($invoice_number, $client_name, $client_email, $issued_date, $expiration_date, $document, $amount, 2, $region); |
| 479 | |
| 480 | if (! $resultSend['success']) { |
| 481 | $this->recordSkip( |
| 482 | $region, |
| 483 | (string) $invoice_number, |
| 484 | 'sendgrid_send_failed', |
| 485 | ['error' => $resultSend['error'] ?? null], |
| 486 | 2, |
| 487 | (string) ($dataInvoice['factura']['cod_cliente'] ?? null), |
| 488 | (int) ($amount ?? 0), |
| 489 | ); |
| 490 | } |
| 491 | } |
| 492 | } |
| 493 | } |
| 494 | |
| 495 | private function loopNextRemindersClients($region, string $next10days, string $lastWeek, bool $companyActive = true): void |
| 496 | { |
| 497 | $diaNext10 = date('j', strtotime($next10days)); |
| 498 | $diaLastWeek = date('j', strtotime($lastWeek)); |
| 499 | |
| 500 | $nextWeekInvoices = TblInvoicesNextReminders::where('payment_day', $diaNext10)->get()->pluck('invoice_number'); |
| 501 | $lastWeekInvoices = TblInvoicesNextReminders::where('payment_day', $diaLastWeek)->get()->pluck('invoice_number'); |
| 502 | |
| 503 | // type 1 |
| 504 | foreach ($nextWeekInvoices as $reminder) { |
| 505 | if (! $reminder) { |
| 506 | continue; |
| 507 | } |
| 508 | $dataInvoice = $this->request('get', 'factura/'.$reminder, $region, []); |
| 509 | if ($this->checkClientHasFreshdeskTask($dataInvoice['factura']['cod_cliente'], $region)) { |
| 510 | $this->recordSkip( |
| 511 | $region, |
| 512 | (string) ($dataInvoice['factura']['n_factura'] ?? $reminder), |
| 513 | 'freshdesk_task_active', |
| 514 | null, |
| 515 | 1, |
| 516 | (string) ($dataInvoice['factura']['cod_cliente'] ?? null), |
| 517 | ); |
| 518 | |
| 519 | continue; |
| 520 | } |
| 521 | |
| 522 | $cobrada = $dataInvoice['factura']['cobrada']; |
| 523 | $formaPago = $dataInvoice['factura']['forma_pago_factura']; |
| 524 | |
| 525 | // Invoice already paied |
| 526 | // Invoice that the payment method is not "transferencia" |
| 527 | if ( |
| 528 | $cobrada !== 'NO' |
| 529 | || stripos((string) $formaPago, 'tr') === false |
| 530 | ) { |
| 531 | $this->recordSkip( |
| 532 | $region, |
| 533 | (string) ($dataInvoice['factura']['n_factura'] ?? $reminder), |
| 534 | $cobrada !== 'NO' ? 'already_paid' : 'payment_method_not_transfer', |
| 535 | ['cobrada' => $cobrada, 'forma_pago' => $formaPago], |
| 536 | 1, |
| 537 | (string) ($dataInvoice['factura']['cod_cliente'] ?? null), |
| 538 | ); |
| 539 | |
| 540 | continue; |
| 541 | } |
| 542 | |
| 543 | $dataClient = $this->request('get', 'cliente/'.$dataInvoice['factura']['cod_cliente'], $region, []); |
| 544 | |
| 545 | $invoice_number = $dataInvoice['factura']['n_factura'] ?? null; |
| 546 | $client_name = $dataClient['cliente']['empresa'] ?? null; |
| 547 | $client_email = $dataClient['cliente']['email'] ?? $dataClient['cliente']['email_facturacion'] ?? null; |
| 548 | $cif = $dataClient['cliente']['cliente_cif'] ?? null; |
| 549 | $issued_date = $dataInvoice['factura']['fecha_emision'] ?? null; |
| 550 | $expiration_date = $this->getVencimientosFormateados($dataInvoice); |
| 551 | $amount = $dataInvoice['factura']['importe_total_factura'] ?? null; |
| 552 | $collection_date = null; |
| 553 | $document = $dataInvoice['factura']['documento'] ?? null; |
| 554 | |
| 555 | // FIRE-1293 (Berta): read-only regions record potential and skip send. |
| 556 | if (! $companyActive) { |
| 557 | $this->recordSkip( |
| 558 | $region, |
| 559 | (string) $invoice_number, |
| 560 | 'region_inactive', |
| 561 | null, |
| 562 | 1, |
| 563 | (string) ($dataInvoice['factura']['cod_cliente'] ?? null), |
| 564 | (int) ($amount ?? 0), |
| 565 | ); |
| 566 | |
| 567 | continue; |
| 568 | } |
| 569 | |
| 570 | // FIRE-1293 (Berta): create sent row first so SendGrid failures |
| 571 | // still count as sent attempts. |
| 572 | TblInvoiceReminders::create([ |
| 573 | 'invoice_number' => $invoice_number, |
| 574 | 'client_name' => $client_name, |
| 575 | 'client_email' => $client_email, |
| 576 | 'cif' => $cif, |
| 577 | 'issued_date' => $issued_date, |
| 578 | 'expiration_date' => $expiration_date, |
| 579 | 'amount' => $amount, |
| 580 | 'collection_date' => $collection_date, |
| 581 | 'region' => $region, |
| 582 | 'reminder_type' => 1, |
| 583 | ]); |
| 584 | |
| 585 | if (config('app.env') === 'production') { |
| 586 | $resultSend = $this->sendInvoice($invoice_number, $client_name, $client_email, $issued_date, $expiration_date, $document, $amount, 1, $region); |
| 587 | |
| 588 | if (! $resultSend['success']) { |
| 589 | $this->recordSkip( |
| 590 | $region, |
| 591 | (string) $invoice_number, |
| 592 | 'sendgrid_send_failed', |
| 593 | ['error' => $resultSend['error'] ?? null], |
| 594 | 1, |
| 595 | (string) ($dataInvoice['factura']['cod_cliente'] ?? null), |
| 596 | (int) ($amount ?? 0), |
| 597 | ); |
| 598 | } |
| 599 | } |
| 600 | } |
| 601 | |
| 602 | // type 3 |
| 603 | foreach ($lastWeekInvoices as $reminder) { |
| 604 | if (! $reminder) { |
| 605 | continue; |
| 606 | } |
| 607 | $dataInvoice = $this->request('get', 'factura/'.$reminder, $region, []); |
| 608 | if ($this->checkClientHasFreshdeskTask($dataInvoice['factura']['cod_cliente'], $region)) { |
| 609 | $this->recordSkip( |
| 610 | $region, |
| 611 | (string) ($dataInvoice['factura']['n_factura'] ?? $reminder), |
| 612 | 'freshdesk_task_active', |
| 613 | null, |
| 614 | 3, |
| 615 | (string) ($dataInvoice['factura']['cod_cliente'] ?? null), |
| 616 | ); |
| 617 | |
| 618 | continue; |
| 619 | } |
| 620 | |
| 621 | $cobrada = $dataInvoice['factura']['cobrada']; |
| 622 | $formaPago = $dataInvoice['factura']['forma_pago_factura']; |
| 623 | |
| 624 | // Invoice already paied |
| 625 | // Invoice that the payment method is not "transferencia" |
| 626 | if ( |
| 627 | $cobrada !== 'NO' |
| 628 | || stripos((string) $formaPago, 'tr') === false |
| 629 | ) { |
| 630 | $this->recordSkip( |
| 631 | $region, |
| 632 | (string) ($dataInvoice['factura']['n_factura'] ?? $reminder), |
| 633 | $cobrada !== 'NO' ? 'already_paid' : 'payment_method_not_transfer', |
| 634 | ['cobrada' => $cobrada, 'forma_pago' => $formaPago], |
| 635 | 3, |
| 636 | (string) ($dataInvoice['factura']['cod_cliente'] ?? null), |
| 637 | ); |
| 638 | |
| 639 | continue; |
| 640 | } |
| 641 | |
| 642 | $dataClient = $this->request('get', 'cliente/'.$dataInvoice['factura']['cod_cliente'], $region, []); |
| 643 | |
| 644 | $invoice_number = $dataInvoice['factura']['n_factura'] ?? null; |
| 645 | $client_name = $dataClient['cliente']['empresa'] ?? null; |
| 646 | $client_email = $dataClient['cliente']['email'] ?? $dataClient['cliente']['email_facturacion'] ?? null; |
| 647 | $cif = $dataClient['cliente']['cliente_cif'] ?? null; |
| 648 | $issued_date = $dataInvoice['factura']['fecha_emision'] ?? null; |
| 649 | $expiration_date = $this->getVencimientosFormateados($dataInvoice); |
| 650 | $amount = $dataInvoice['factura']['importe_total_factura'] ?? null; |
| 651 | $collection_date = null; |
| 652 | $document = $dataInvoice['factura']['documento'] ?? null; |
| 653 | |
| 654 | // FIRE-1293 (Berta): read-only regions record potential and skip send. |
| 655 | if (! $companyActive) { |
| 656 | $this->recordSkip( |
| 657 | $region, |
| 658 | (string) $invoice_number, |
| 659 | 'region_inactive', |
| 660 | null, |
| 661 | 3, |
| 662 | (string) ($dataInvoice['factura']['cod_cliente'] ?? null), |
| 663 | (int) ($amount ?? 0), |
| 664 | ); |
| 665 | |
| 666 | continue; |
| 667 | } |
| 668 | |
| 669 | // FIRE-1293 (Berta): create sent row first so SendGrid failures |
| 670 | // still count as sent attempts. |
| 671 | TblInvoiceReminders::create([ |
| 672 | 'invoice_number' => $invoice_number, |
| 673 | 'client_name' => $client_name, |
| 674 | 'client_email' => $client_email, |
| 675 | 'cif' => $cif, |
| 676 | 'issued_date' => $issued_date, |
| 677 | 'expiration_date' => $expiration_date, |
| 678 | 'amount' => $amount, |
| 679 | 'collection_date' => $collection_date, |
| 680 | 'region' => $region, |
| 681 | 'reminder_type' => 3, |
| 682 | ]); |
| 683 | |
| 684 | if (config('app.env') === 'production') { |
| 685 | $resultSend = $this->sendInvoice($invoice_number, $client_name, $client_email, $issued_date, $expiration_date, $document, $amount, 3, $region); |
| 686 | |
| 687 | if (! $resultSend['success']) { |
| 688 | $this->recordSkip( |
| 689 | $region, |
| 690 | (string) $invoice_number, |
| 691 | 'sendgrid_send_failed', |
| 692 | ['error' => $resultSend['error'] ?? null], |
| 693 | 3, |
| 694 | (string) ($dataInvoice['factura']['cod_cliente'] ?? null), |
| 695 | (int) ($amount ?? 0), |
| 696 | ); |
| 697 | } |
| 698 | } |
| 699 | } |
| 700 | |
| 701 | } |
| 702 | |
| 703 | public function sendInvoice($invoice_number, $client_name, $client_email, $issued_date, $expiration_date, $document, $amount, $reminder_type, $region, $table = null, $month = null): array |
| 704 | { |
| 705 | if ( |
| 706 | empty($invoice_number) || |
| 707 | empty($client_name) || |
| 708 | empty($client_email) || |
| 709 | empty($issued_date) || |
| 710 | empty($expiration_date) || |
| 711 | empty($document) || |
| 712 | empty($reminder_type) |
| 713 | ) { |
| 714 | Log::channel('g3w_invoices_not_send')->error("$invoice_number => { |
| 715 | 'client_name': $client_name, |
| 716 | 'client_email': $client_email, |
| 717 | 'issued_date': $issued_date, |
| 718 | 'expiration_date': $expiration_date, |
| 719 | 'reminder_type': $reminder_type |
| 720 | }"); |
| 721 | |
| 722 | // FIRE-1293 — record the skip so the KPI surfaces partial-data |
| 723 | // dropouts (commonly: G3W returned an invoice with no document |
| 724 | // or no expiration date). |
| 725 | $missing = array_keys(array_filter([ |
| 726 | 'invoice_number' => empty($invoice_number), |
| 727 | 'client_name' => empty($client_name), |
| 728 | 'client_email' => empty($client_email), |
| 729 | 'issued_date' => empty($issued_date), |
| 730 | 'expiration_date' => empty($expiration_date), |
| 731 | 'document' => empty($document), |
| 732 | 'reminder_type' => empty($reminder_type), |
| 733 | ])); |
| 734 | $this->recordSkip( |
| 735 | $region, |
| 736 | $invoice_number ? (string) $invoice_number : null, |
| 737 | 'missing_mandatory_field', |
| 738 | ['missing' => $missing], |
| 739 | $reminder_type ? (int) $reminder_type : null, |
| 740 | null, |
| 741 | $amount !== null ? (int) $amount : null, |
| 742 | ); |
| 743 | |
| 744 | return ['success' => false, 'message' => 'Campos obligatorios faltantes']; |
| 745 | } |
| 746 | |
| 747 | try { |
| 748 | $emailTemplate = TblInvoiceRemindersEmailTemplate::where('type', $reminder_type)->first(); |
| 749 | |
| 750 | if (! $emailTemplate) { |
| 751 | throw new \Exception('No se encontró la plantilla de correo para este tipo de recordatorio'); |
| 752 | } |
| 753 | |
| 754 | // FIRE-1562: NO separar por '-'. El guion es válido dentro de dominios |
| 755 | // (foo@grupo-fire.es, avc@avc-administraciones.es, etc.). El splitter |
| 756 | // previo lo trataba como separador y aniquilaba emails perfectamente |
| 757 | // válidos → factura clasificada como no_valid_email → falso positivo |
| 758 | // en el panel de "no enviadas". Solo coma, punto-y-coma y whitespace. |
| 759 | $clientEmails = preg_split('/\s*[,;]\s*|\s+/', (string) $client_email, -1, PREG_SPLIT_NO_EMPTY); |
| 760 | $clientEmails = array_map(trim(...), $clientEmails); |
| 761 | $validEmails = []; |
| 762 | $invalidEmails = []; |
| 763 | |
| 764 | foreach ($clientEmails as $email) { |
| 765 | if (filter_var($email, FILTER_VALIDATE_EMAIL)) { |
| 766 | $validEmails[] = $email; |
| 767 | } else { |
| 768 | $invalidEmails[] = $email; |
| 769 | Log::channel('g3w_invoices_not_send')->warning("Email inválido omitido: $email para factura $invoice_number"); |
| 770 | } |
| 771 | } |
| 772 | |
| 773 | // FIRE-1293 — if SOME emails were invalid but at least one valid |
| 774 | // address remains, the reminder will go out. Record a soft skip |
| 775 | // so the KPI's "partial validation failure" panel reflects the |
| 776 | // data-quality issue without conflating it with a true miss. |
| 777 | if (! empty($invalidEmails) && ! empty($validEmails)) { |
| 778 | $this->recordSkip( |
| 779 | $region, |
| 780 | (string) $invoice_number, |
| 781 | 'partial_invalid_emails', |
| 782 | ['invalid_emails' => $invalidEmails, 'valid_count' => count($validEmails)], |
| 783 | (int) $reminder_type, |
| 784 | null, |
| 785 | (int) ($amount ?? 0), |
| 786 | ); |
| 787 | } |
| 788 | |
| 789 | if (empty($validEmails)) { |
| 790 | Log::channel('g3w_invoices_not_send')->error("No hay emails válidos para enviar factura $invoice_number"); |
| 791 | |
| 792 | // FIRE-1293 — persist this skip natively so the KPI dashboard |
| 793 | // captures it without depending on log parsing. Reason code |
| 794 | // matches the historical import (invoices:import-skips-from-log). |
| 795 | $this->recordSkip( |
| 796 | $region, |
| 797 | (string) $invoice_number, |
| 798 | 'no_valid_email', |
| 799 | ['raw_email' => (string) $client_email], |
| 800 | (int) $reminder_type, |
| 801 | null, |
| 802 | (int) ($amount ?? 0), |
| 803 | ); |
| 804 | |
| 805 | return ['success' => false, 'message' => 'No hay direcciones de correo válidas']; |
| 806 | } |
| 807 | |
| 808 | $sendgrid = new \SendGrid(config('services.sendgrid.api_key')); |
| 809 | $successCount = 0; |
| 810 | $failCount = 0; |
| 811 | |
| 812 | foreach ($validEmails as $toEmail) { |
| 813 | try { |
| 814 | $email = new Mail; |
| 815 | |
| 816 | $fromEmail = 'recordatorio.factura@fire.es'; |
| 817 | $fromName = 'Recordatorio Facturas Grupo Fire'; |
| 818 | $email->setFrom($fromEmail, $fromName); |
| 819 | $email->setReplyTo('recordatorio.facturas@fire.es', 'Recordatorio Facturas Grupo Fire'); |
| 820 | |
| 821 | if ($reminder_type != 4) { |
| 822 | $subject = str_replace( |
| 823 | // ['{{invoice_number}}', '{{expiration_date}}', '{{amount}}'], |
| 824 | ['{{invoice_number}}', '{{expiration_date}}'], |
| 825 | [$invoice_number, $expiration_date, $amount], |
| 826 | $emailTemplate->subject |
| 827 | ); |
| 828 | } else { |
| 829 | $subject = str_replace( |
| 830 | // ['{{invoice_number}}', '{{expiration_date}}', '{{amount}}'], |
| 831 | ['{{expiration_date}}'], |
| 832 | [$month], |
| 833 | $emailTemplate->subject |
| 834 | ); |
| 835 | } |
| 836 | |
| 837 | $baseUrl = 'http://aiwf.fire.es/sepa/form/'; |
| 838 | |
| 839 | $params = [ |
| 840 | 'nombre_deudor' => $client_name, |
| 841 | // 'cif_deudor' => $datos['cif'], |
| 842 | // 'direccion_deudor' => urlencode($datos['direccion_deudor']), |
| 843 | // 'codigo_postal' => urlencode($datos['codigo_postal']), |
| 844 | // 'provincia_pais' => urlencode($datos['provincia_pais']), |
| 845 | // 'iban' => $datos['iban'], |
| 846 | // 'swift' => $datos['swift'], |
| 847 | // 'nombre_apoderado' => urlencode($datos['nombre_apoderado']), |
| 848 | // 'nif_apoderado' => $datos['nif_apoderado'], |
| 849 | 'fecha' => $issued_date, |
| 850 | 'email_contacto' => $client_email, |
| 851 | 'region' => $region, |
| 852 | ]; |
| 853 | |
| 854 | $url = $baseUrl.'?'.http_build_query($params); |
| 855 | |
| 856 | Carbon::setLocale('es'); |
| 857 | |
| 858 | if ($reminder_type < 4) { |
| 859 | $body = str_replace( |
| 860 | ['{{invoice_number}}', '{{client_name}}', '{{issued_date}}', '{{expiration_date}}', '{{amount}}', '{{url}}'], |
| 861 | [ |
| 862 | $invoice_number, |
| 863 | $client_name, |
| 864 | Carbon::createFromFormat('Y-m-d', $issued_date)->isoFormat('D [de] MMMM [de] YYYY'), |
| 865 | $expiration_date, |
| 866 | $amount, |
| 867 | $url, |
| 868 | ], |
| 869 | $emailTemplate->html_content |
| 870 | ); |
| 871 | } else { |
| 872 | $body = str_replace( |
| 873 | ['{{invoice_number}}', '{{client_name}}', '{{issued_date}}', '{{expiration_date}}', '{{amount}}', '{{table}}'], |
| 874 | [ |
| 875 | $invoice_number, |
| 876 | $client_name, |
| 877 | Carbon::createFromFormat('Y-m-d', $issued_date)->isoFormat('D [de] MMMM [de] YYYY'), |
| 878 | $expiration_date, |
| 879 | $amount, |
| 880 | $table, |
| 881 | ], |
| 882 | $emailTemplate->html_content |
| 883 | ); |
| 884 | } |
| 885 | |
| 886 | $email->setSubject($subject); |
| 887 | $email->addContent('text/html', $body); |
| 888 | $email->addTo($toEmail, $client_name); |
| 889 | |
| 890 | if (is_array($document)) { |
| 891 | foreach ($document as $doc) { |
| 892 | if (! base64_decode((string) $doc['content'], true)) { |
| 893 | throw new \Exception('El documento no es un base64 válido'); |
| 894 | } |
| 895 | |
| 896 | // Do not set Content-ID on the attachment: with |
| 897 | // disposition=attachment, Gmail treats orphan inline |
| 898 | // parts (Content-ID not referenced in the HTML body) |
| 899 | // as strippable and drops the PDF during delivery. |
| 900 | $attachment = new Attachment; |
| 901 | $attachment->setContent($doc['content']); |
| 902 | $attachment->setType('application/pdf'); |
| 903 | $attachment->setFilename($doc['filename']); |
| 904 | $attachment->setDisposition('attachment'); |
| 905 | $email->addAttachment($attachment); |
| 906 | |
| 907 | } |
| 908 | } |
| 909 | |
| 910 | if (! is_array($document)) { |
| 911 | if (! base64_decode((string) $document, true)) { |
| 912 | throw new \Exception('El documento no es un base64 válido'); |
| 913 | } |
| 914 | |
| 915 | // See the array branch above: no Content-ID on the |
| 916 | // attachment so Gmail does not strip the PDF. |
| 917 | $attachment = new Attachment; |
| 918 | $attachment->setContent($document); |
| 919 | $attachment->setType('application/pdf'); |
| 920 | $attachment->setFilename("Factura_{$invoice_number}.pdf"); |
| 921 | $attachment->setDisposition('attachment'); |
| 922 | $email->addAttachment($attachment); |
| 923 | } |
| 924 | |
| 925 | try { |
| 926 | $response = $sendgrid->send($email); |
| 927 | SendgridLogger::log($email, $response); |
| 928 | } catch (\Throwable $sendException) { |
| 929 | SendgridLogger::logException($email, $sendException); |
| 930 | throw $sendException; |
| 931 | } |
| 932 | |
| 933 | if ($response->statusCode() == 202) { |
| 934 | $successCount++; |
| 935 | Log::channel('g3w_invoices_sent')->info("Factura $invoice_number enviada exitosamente a: $toEmail"); |
| 936 | } else { |
| 937 | $failCount++; |
| 938 | Log::channel('g3w_invoices_not_send')->error("Error enviando a $toEmail: ".$response->body()); |
| 939 | } |
| 940 | |
| 941 | } catch (\Exception $e) { |
| 942 | $failCount++; |
| 943 | Log::channel('g3w_invoices_not_send')->error("Error enviando a $toEmail: ".$e->getMessage()); |
| 944 | |
| 945 | continue; |
| 946 | } |
| 947 | } |
| 948 | |
| 949 | if ($successCount > 0) { |
| 950 | return [ |
| 951 | 'success' => true, |
| 952 | 'message' => "Enviados: $successCount, Fallidos: $failCount", |
| 953 | 'sent_count' => $successCount, |
| 954 | 'failed_count' => $failCount, |
| 955 | ]; |
| 956 | } else { |
| 957 | return [ |
| 958 | 'success' => false, |
| 959 | 'message' => 'Todos los envÃos fallaron', |
| 960 | 'sent_count' => $successCount, |
| 961 | 'failed_count' => $failCount, |
| 962 | ]; |
| 963 | } |
| 964 | |
| 965 | } catch (\Exception $e) { |
| 966 | Log::channel('g3w_invoices_not_send')->error("Error general enviando factura $invoice_number: ".$e->getMessage()); |
| 967 | |
| 968 | return ['success' => false, 'message' => $e->getMessage()]; |
| 969 | } |
| 970 | } |
| 971 | |
| 972 | public function getAllInvoices($region = 'Cataluña') |
| 973 | { |
| 974 | if ($region === 'All') { |
| 975 | $invoices = TblInvoiceReminders::orderBy('id', 'desc') |
| 976 | ->paginate(50); |
| 977 | } else { |
| 978 | $invoices = TblInvoiceReminders::where('region', $region) |
| 979 | ->orderBy('id', 'desc') |
| 980 | ->paginate(50); |
| 981 | } |
| 982 | |
| 983 | return response()->json([ |
| 984 | 'invoices' => $invoices->items(), |
| 985 | 'pagination' => [ |
| 986 | 'total' => $invoices->total(), |
| 987 | 'current_page' => $invoices->currentPage(), |
| 988 | 'per_page' => $invoices->perPage(), |
| 989 | 'last_page' => $invoices->lastPage(), |
| 990 | ], |
| 991 | ]); |
| 992 | } |
| 993 | |
| 994 | public function getAllInvoicesExceptions() |
| 995 | { |
| 996 | $invoices = TblInvoicesExceptions::orderBy('id', 'desc')->paginate(50); |
| 997 | |
| 998 | return response()->json([ |
| 999 | 'invoices' => $invoices->items(), |
| 1000 | 'pagination' => [ |
| 1001 | 'total' => $invoices->total(), |
| 1002 | 'current_page' => $invoices->currentPage(), |
| 1003 | 'per_page' => $invoices->perPage(), |
| 1004 | 'last_page' => $invoices->lastPage(), |
| 1005 | ], |
| 1006 | ]); |
| 1007 | } |
| 1008 | |
| 1009 | public function sendCyCInvoices(?string $region): array |
| 1010 | { |
| 1011 | try { |
| 1012 | if (! $region) { |
| 1013 | throw new Exception('No region provided'); |
| 1014 | } |
| 1015 | |
| 1016 | $fromDay = 45; |
| 1017 | $toDay = 35; |
| 1018 | $today = Carbon::createFromDate(date('Y'), date('m'), date('d')); |
| 1019 | $todayFormatted = Carbon::now()->format('Y-m-d'); |
| 1020 | |
| 1021 | $documentName = $todayFormatted.'.csv'; |
| 1022 | |
| 1023 | $filePath = storage_path('app/public/uploads/CyC/'.$todayFormatted.'/'.$region.'/'.$documentName); |
| 1024 | |
| 1025 | if (! file_exists(dirname($filePath))) { |
| 1026 | mkdir(dirname($filePath), 0777, true); |
| 1027 | } |
| 1028 | |
| 1029 | $file = fopen($filePath, 'w'); |
| 1030 | |
| 1031 | fputcsv($file, [ |
| 1032 | 'Service', |
| 1033 | 'Language', |
| 1034 | 'Cyc Poliza', |
| 1035 | 'SP Tax Idenfication Number', |
| 1036 | 'SP Country', |
| 1037 | 'BP TaxIdentificationNumber', |
| 1038 | 'SP Corporate Name', |
| 1039 | 'BP Country', |
| 1040 | 'Invoice Number', |
| 1041 | 'Invoice Issue Date', |
| 1042 | 'PD Installment Due Date', |
| 1043 | 'PD Payment Means', |
| 1044 | 'Total Amount', |
| 1045 | 'Taxable Base', |
| 1046 | 'Tax Rate', |
| 1047 | 'Tax Amount', |
| 1048 | ], ';', escape: '\\'); |
| 1049 | |
| 1050 | while ($fromDay > $toDay) { |
| 1051 | $date = $today->copy()->subDays($fromDay)->format('Y-m-d'); |
| 1052 | $invoices = $this->request('get', 'factura/vence/'.$date, $region, []); |
| 1053 | foreach ($invoices['facturas'] as $invoice) { |
| 1054 | $invoiceData = $this->request('get', 'factura/'.$invoice['ID'], $region, []); |
| 1055 | $invoiceData = $invoiceData['factura']; |
| 1056 | |
| 1057 | $dataClient = $this->request('get', 'cliente/'.$invoiceData['cod_cliente'], $region, []); |
| 1058 | $invoiceCobrada = $invoiceData['cobrada']; |
| 1059 | $invoiceDocument = $invoiceData['documento']; |
| 1060 | $invoiceNumber = $invoiceData['n_factura']; |
| 1061 | |
| 1062 | if ( |
| 1063 | ! $invoiceDocument || |
| 1064 | $invoiceCobrada !== 'NO') { |
| 1065 | continue; |
| 1066 | } |
| 1067 | |
| 1068 | if ($region === 'Cataluña' && stripos((string) $invoiceNumber, 'R') === false) { |
| 1069 | continue; |
| 1070 | } |
| 1071 | |
| 1072 | fputcsv($file, [ |
| 1073 | 'grabacionFacturas', |
| 1074 | 'ESP', |
| 1075 | '156547', |
| 1076 | 'B67795088', |
| 1077 | 'ESP', |
| 1078 | $dataClient['cliente']['cliente_cif'], |
| 1079 | $dataClient['cliente']['empresa'], |
| 1080 | 'ESP', |
| 1081 | $invoiceNumber, |
| 1082 | $invoiceData['fecha_creacion'], |
| 1083 | $invoiceData['vencimientos'][0]['fecha_vencimiento'], |
| 1084 | $invoiceData['forma_pago_factura'], |
| 1085 | $invoiceData['importe_total_factura'], |
| 1086 | $invoiceData['base_imponible_factura'], |
| 1087 | $invoiceData['iva_factura'] * 100, |
| 1088 | $invoiceData['importe_iva_factura'], |
| 1089 | ], ';', escape: '\\'); |
| 1090 | |
| 1091 | } |
| 1092 | $fromDay--; |
| 1093 | } |
| 1094 | |
| 1095 | fclose($file); |
| 1096 | |
| 1097 | return ['success' => true]; |
| 1098 | } catch (\Exception $e) { |
| 1099 | Log::channel('g3w_invoices')->error($e->getMessage()); |
| 1100 | |
| 1101 | return ['success' => false, 'error' => $e->getMessage()]; |
| 1102 | } |
| 1103 | } |
| 1104 | |
| 1105 | public function setAllMonthAdministratorsInvoices($region): array |
| 1106 | { |
| 1107 | if (! $region) { |
| 1108 | return ['success' => false, 'error' => 'No region provided']; |
| 1109 | } |
| 1110 | |
| 1111 | try { |
| 1112 | $now = Carbon::now(); |
| 1113 | $month = $now->format('m'); |
| 1114 | } catch (\Exception $e) { |
| 1115 | Log::channel('g3w_invoices')->error('Formato de fecha de mes no válido (esperado YYYY-mm)'); |
| 1116 | |
| 1117 | return ['success' => false, 'error' => 'Formato de fecha de mes no válido (esperado YYYY-mm)']; |
| 1118 | } |
| 1119 | |
| 1120 | $invoices = $this->request('get', 'factura/vencemesadministrador/'.$month, $region, []); |
| 1121 | |
| 1122 | foreach ($invoices['facturas'] as $invoice) { |
| 1123 | $invoiceData = $this->request('get', 'factura/'.$invoice['ID'], $region, []); |
| 1124 | $invoiceData = $invoiceData['factura']; |
| 1125 | |
| 1126 | // Continue if region is Comunidad Valenciana and the invoice starts with M |
| 1127 | if ( |
| 1128 | $region == 'Comunidad Valenciana' |
| 1129 | && str_starts_with((string) $invoice['ID'], 'M') |
| 1130 | ) { |
| 1131 | continue; |
| 1132 | } |
| 1133 | |
| 1134 | // FIRE-1586: Aeroextinción (Andalucía / prefix C) — no reminders. |
| 1135 | if ( |
| 1136 | $region == 'Andalucía' |
| 1137 | && str_starts_with((string) $invoice['ID'], 'C') |
| 1138 | ) { |
| 1139 | continue; |
| 1140 | } |
| 1141 | |
| 1142 | $cobrada = $invoiceData['cobrada']; |
| 1143 | $formaPago = $invoiceData['forma_pago_factura']; |
| 1144 | // Invoice already paied |
| 1145 | // Invoice that the payment method is not "transferencia" |
| 1146 | if ( |
| 1147 | $cobrada !== 'NO' |
| 1148 | || stripos((string) $formaPago, 'tr') === false |
| 1149 | ) { |
| 1150 | continue; |
| 1151 | } |
| 1152 | |
| 1153 | $dataClient = []; |
| 1154 | if ($invoice['cod_administrador']) { |
| 1155 | $dataClient = $this->request('get', 'cliente/'.$invoice['cod_administrador'], $region, []); |
| 1156 | $dataClient = $dataClient['cliente']; |
| 1157 | } |
| 1158 | |
| 1159 | if ($invoice['cod_cliente']) { |
| 1160 | $dataClientAdministrado = $this->request('get', 'cliente/'.$invoice['cod_cliente'], $region, []); |
| 1161 | $dataClientAdministrado = $dataClientAdministrado['cliente']; |
| 1162 | if ($dataClientAdministrado['tipo_cliente'] === 'Grandes Cuentas') { |
| 1163 | continue; |
| 1164 | } |
| 1165 | } |
| 1166 | |
| 1167 | /*if ( |
| 1168 | $dataClient["tipo_cliente"] !== "Administrador" |
| 1169 | ){ |
| 1170 | continue; |
| 1171 | }*/ |
| 1172 | |
| 1173 | $codService = $invoiceData['lineas'][0]['cod_servicio']; |
| 1174 | $dataService = $this->request('get', 'servicio/'.$codService, $region, []); |
| 1175 | $dataService = $dataService['servicio']; |
| 1176 | |
| 1177 | TblInvoiceAdministrators::create([ |
| 1178 | 'invoice_number' => $invoiceData['n_factura'], |
| 1179 | 'region' => $region, |
| 1180 | 'name' => $dataClient['empresa'], |
| 1181 | 'CIF' => $dataClient['cliente_cif'], |
| 1182 | 'email' => $dataClient['email'], |
| 1183 | 'service_name' => $dataService['nombre_servicio'], |
| 1184 | 'service_addres' => $dataService['direccion'], |
| 1185 | 'send_date' => Carbon::now('Europe/Madrid')->toDateString(), |
| 1186 | 'expiration_date' => Carbon::parse($invoice['fecha_vencimiento'])->toDateString(), |
| 1187 | 'amount' => $invoiceData['importe_total_factura'], |
| 1188 | 'cod_administrador' => $invoice['cod_administrador'], |
| 1189 | 'cod_cliente' => $invoice['cod_cliente'], |
| 1190 | ]); |
| 1191 | } |
| 1192 | |
| 1193 | return [ |
| 1194 | 'success' => true, |
| 1195 | 'message' => "Proceso completado para el mes $month en la región $region.", |
| 1196 | ]; |
| 1197 | } |
| 1198 | |
| 1199 | /** |
| 1200 | * @return 'No region provided'[]|'Processing complete'[]|bool[] |
| 1201 | */ |
| 1202 | public function sendAdministratorsInvoices($region): array |
| 1203 | { |
| 1204 | if (! $region) { |
| 1205 | return ['success' => false, 'error' => 'No region provided']; |
| 1206 | } |
| 1207 | |
| 1208 | $month = [ |
| 1209 | 1 => 'Enero', |
| 1210 | 2 => 'Febrero', |
| 1211 | 3 => 'Marzo', |
| 1212 | 4 => 'Abril', |
| 1213 | 5 => 'Mayo', |
| 1214 | 6 => 'Junio', |
| 1215 | 7 => 'Julio', |
| 1216 | 8 => 'Agosto', |
| 1217 | 9 => 'Septiembre', |
| 1218 | 10 => 'Octubre', |
| 1219 | 11 => 'Noviembre', |
| 1220 | 12 => 'Diciembre', |
| 1221 | ]; |
| 1222 | |
| 1223 | $startOfMonth = Carbon::now()->startOfMonth()->toDateString(); |
| 1224 | $endOfMonth = Carbon::now()->endOfMonth()->toDateString(); |
| 1225 | |
| 1226 | $currentMonthInvoices = TblInvoiceAdministrators::where('region', $region) |
| 1227 | ->where('paid', 0) |
| 1228 | ->whereBetween('expiration_date', [$startOfMonth, $endOfMonth]) |
| 1229 | ->orderBy('expiration_date', 'asc') |
| 1230 | ->get(); |
| 1231 | |
| 1232 | $invoicesGroupedByAdministrator = $currentMonthInvoices->groupBy('cod_administrador'); |
| 1233 | |
| 1234 | foreach ($invoicesGroupedByAdministrator as $administratorCode => $administratorInvoices) { |
| 1235 | $table = "<table style='border-collapse: collapse; width: 100%; font-family: Arial, sans-serif;'> |
| 1236 | <tr> |
| 1237 | <th style='border: 1px solid #999; padding: 8px; background-color: #f2f2f2; text-align: left;'>Número Factura</th> |
| 1238 | <th style='border: 1px solid #999; padding: 8px; background-color: #f2f2f2; text-align: left;'>Nombre cliente de servicio</th> |
| 1239 | <th style='border: 1px solid #999; padding: 8px; background-color: #f2f2f2; text-align: left;'>Dirección del servicio</th> |
| 1240 | <th style='border: 1px solid #999; padding: 8px; background-color: #f2f2f2; text-align: left;'>Fecha de emisión</th> |
| 1241 | <th style='border: 1px solid #999; padding: 8px; background-color: #f2f2f2; text-align: left;'>Fecha de vencimiento</th> |
| 1242 | <th style='border: 1px solid #999; padding: 8px; background-color: #f2f2f2; text-align: left;'>Importe</th> |
| 1243 | </tr>"; |
| 1244 | |
| 1245 | $documentsBase64 = []; |
| 1246 | |
| 1247 | foreach ($administratorInvoices as $invoice) { |
| 1248 | if ($this->checkClientHasFreshdeskTask($invoice->cod_cliente, $invoice->region)) { |
| 1249 | continue; |
| 1250 | } |
| 1251 | |
| 1252 | $invoiceNumber = $invoice->invoice_number; |
| 1253 | $table .= "<tr> |
| 1254 | <td class='invoice_number' style='border: 1px solid #999; padding: 8px;'>".$invoiceNumber."</td> |
| 1255 | <td class='invoice_service_name' style='border: 1px solid #999; padding: 8px;'>".$invoice->service_name."</td> |
| 1256 | <td class='invoice_service_addres' style='border: 1px solid #999; padding: 8px;'>".$invoice->service_addres."</td> |
| 1257 | <td class='invoice_send_date' style='border: 1px solid #999; padding: 8px;'>".$invoice->send_date."</td> |
| 1258 | <td class='invoice_expiration_date' style='border: 1px solid #999; padding: 8px;'>".$invoice->expiration_date."</td> |
| 1259 | <td class='invoice_amount' style='border: 1px solid #999; padding: 8px;'>".$invoice->amount.' €</td> |
| 1260 | </tr>'; |
| 1261 | |
| 1262 | $invoice = $this->request('get', 'factura/'.$invoiceNumber, $region, []); |
| 1263 | $invoiceData = $invoice['factura']; |
| 1264 | |
| 1265 | $documentsBase64[] = [ |
| 1266 | 'content' => $invoiceData['documento'], |
| 1267 | 'filename' => "Factura_{$invoiceNumber}.pdf", |
| 1268 | ]; |
| 1269 | } |
| 1270 | |
| 1271 | $table .= '</table>'; |
| 1272 | |
| 1273 | if (empty($documentsBase64)) { |
| 1274 | continue; |
| 1275 | } |
| 1276 | |
| 1277 | $monthText = $month[Carbon::now()->format('n')]; |
| 1278 | |
| 1279 | $invoiceSendData = $this->sendInvoice( |
| 1280 | $administratorInvoices->first()->invoice_number, |
| 1281 | $administratorInvoices->first()->name, |
| 1282 | $administratorInvoices->first()->email, |
| 1283 | $administratorInvoices->first()->send_date, |
| 1284 | $administratorInvoices->first()->expiration_date, |
| 1285 | $documentsBase64, |
| 1286 | $administratorInvoices->first()->amount, |
| 1287 | 4, |
| 1288 | $region, |
| 1289 | $table, |
| 1290 | $monthText.' de '.Carbon::now()->format('Y') |
| 1291 | ); |
| 1292 | |
| 1293 | TblInvoiceReminders::create([ |
| 1294 | 'invoice_number' => $administratorInvoices->first()->invoice_number, |
| 1295 | 'client_name' => $administratorInvoices->first()->name, |
| 1296 | 'client_email' => $administratorInvoices->first()->email, |
| 1297 | 'cif' => 'Administradores', |
| 1298 | 'issued_date' => date('Y-m-d'), |
| 1299 | 'expiration_date' => $administratorInvoices->first()->expiration_date, |
| 1300 | 'amount' => $administratorInvoices->first()->amount, |
| 1301 | 'collection_date' => null, |
| 1302 | 'region' => $region, |
| 1303 | 'reminder_type' => 4, |
| 1304 | ]); |
| 1305 | |
| 1306 | TblInvoiceReminders::create([ |
| 1307 | 'invoice_number' => $administratorInvoices->first()->invoice_number, |
| 1308 | 'client_name' => $administratorInvoices->first()->name, |
| 1309 | 'client_email' => $administratorInvoices->first()->email, |
| 1310 | 'cif' => 'Administradores', |
| 1311 | 'issued_date' => date('Y-m-d'), |
| 1312 | 'expiration_date' => $administratorInvoices->first()->expiration_date, |
| 1313 | 'amount' => $administratorInvoices->first()->amount, |
| 1314 | 'collection_date' => null, |
| 1315 | 'region' => $region, |
| 1316 | 'reminder_type' => 4, |
| 1317 | ]); |
| 1318 | |
| 1319 | } |
| 1320 | |
| 1321 | return ['success' => true, 'message' => 'Processing complete']; |
| 1322 | } |
| 1323 | |
| 1324 | private function checkClientHasFreshdeskTask($client, $region): false |
| 1325 | { |
| 1326 | try { |
| 1327 | $response = Http::withBasicAuth('titan_auto', 'n71Mhh8i7FO_h2fF8e4') |
| 1328 | ->post('https://aiwf.ibvgroup.com/webhook/client-lookup', [ |
| 1329 | 'client_id' => $client, |
| 1330 | 'region' => $region, |
| 1331 | ]); |
| 1332 | |
| 1333 | if ($response->successful()) { |
| 1334 | return $response->json('found', false); |
| 1335 | } |
| 1336 | |
| 1337 | return false; |
| 1338 | |
| 1339 | } catch (\Exception $e) { |
| 1340 | Log::error('Error on checkClientHasFreshdeskTask: '.$e->getMessage()); |
| 1341 | |
| 1342 | return false; |
| 1343 | } |
| 1344 | } |
| 1345 | |
| 1346 | public function checkClientHasFreshdeskTaskAll(): array|false |
| 1347 | { |
| 1348 | try { |
| 1349 | $clients = TblInvoiceAdministrators::all(); |
| 1350 | $codClients = []; |
| 1351 | foreach ($clients as $client) { |
| 1352 | $response = Http::withBasicAuth('titan_auto', 'n71Mhh8i7FO_h2fF8e4') |
| 1353 | ->post('https://aiwf.ibvgroup.com/webhook/client-lookup', [ |
| 1354 | 'client_id' => $client->cod_cliente, |
| 1355 | 'region' => $client->region, |
| 1356 | ]); |
| 1357 | $data = $response->json(); |
| 1358 | |
| 1359 | if (isset($data['found']) && $data['found'] === true) { |
| 1360 | $codClients[] = "{$client->cod_cliente} en {$client->region}"; |
| 1361 | } |
| 1362 | } |
| 1363 | |
| 1364 | return $codClients; |
| 1365 | |
| 1366 | } catch (\Exception $e) { |
| 1367 | Log::error('Error on checkClientHasFreshdeskTask: '.$e->getMessage()); |
| 1368 | |
| 1369 | return false; |
| 1370 | } |
| 1371 | } |
| 1372 | |
| 1373 | public function sendCallCenterInvoices() |
| 1374 | { |
| 1375 | $spreadsheetId = '1JxCICtqPtPrE8B_0nVJZYwIZ67Nv5gPYr9rW73Pz1_Q'; |
| 1376 | $sheetName = 'Hoja 1'; |
| 1377 | |
| 1378 | try { |
| 1379 | $googleSheetsService = $this->getGoogleSheetsService(); |
| 1380 | |
| 1381 | $region = [ |
| 1382 | 'G3W Cat' => 'Cataluña', |
| 1383 | 'G3W Mad' => 'Madrid', |
| 1384 | 'G3W Val' => 'Comunidad Valenciana', |
| 1385 | // "G3W Alm"=>"Andalucia", |
| 1386 | ]; |
| 1387 | |
| 1388 | $fromEmail = [ |
| 1389 | 'G3W Cat' => 'fire@fire.es', |
| 1390 | 'G3W Mad' => 'atencion@fire.es', |
| 1391 | 'G3W Val' => 'facturacionval@fire.es', |
| 1392 | // "G3W Alm"=>"documentacion.almeria@fire.es", |
| 1393 | ]; |
| 1394 | |
| 1395 | // A: Entorno, B: ID Factura, C: Email, D: Enviado, E: Fecha EnvÃo |
| 1396 | $range = $sheetName.'!A2:E'; |
| 1397 | $response = $googleSheetsService->spreadsheets_values->get($spreadsheetId, $range); |
| 1398 | $rows = $response->getValues(); |
| 1399 | |
| 1400 | if (empty($rows)) { |
| 1401 | return; |
| 1402 | } |
| 1403 | |
| 1404 | foreach ($rows as $index => $row) { |
| 1405 | $currentRowNumber = $index + 2; |
| 1406 | |
| 1407 | $entorno = $row[0] ?? null; |
| 1408 | $idFactura = $row[1] ?? null; |
| 1409 | $emailToSend = $row[2] ?? null; |
| 1410 | $enviado = $row[3] ?? 'NO'; |
| 1411 | |
| 1412 | if ($idFactura && $emailToSend && strtoupper($enviado) !== 'SI') { |
| 1413 | |
| 1414 | try { |
| 1415 | // --- AQUà LLAMAS A TU LÓGICA DE ENVÃO --- |
| 1416 | if ( |
| 1417 | $region[$entorno] == 'Comunidad Valenciana' |
| 1418 | && str_starts_with((string) $idFactura, 'M') |
| 1419 | ) { |
| 1420 | continue; |
| 1421 | } |
| 1422 | |
| 1423 | // FIRE-1586: Aeroextinción (Andalucía / prefix C). |
| 1424 | if ( |
| 1425 | $region[$entorno] == 'Andalucía' |
| 1426 | && str_starts_with((string) $idFactura, 'C') |
| 1427 | ) { |
| 1428 | continue; |
| 1429 | } |
| 1430 | |
| 1431 | $invoiceData = $this->request('get', 'factura/'.$idFactura, $region[$entorno], []); |
| 1432 | $invoiceData = $invoiceData['factura']; |
| 1433 | |
| 1434 | $cobrada = $invoiceData['cobrada']; |
| 1435 | $formaPago = $invoiceData['forma_pago_factura']; |
| 1436 | // Invoice already paied |
| 1437 | // Invoice that the payment method is not "transferencia" |
| 1438 | if ( |
| 1439 | $cobrada !== 'NO' |
| 1440 | || stripos((string) $formaPago, 'tr') === false |
| 1441 | ) { |
| 1442 | continue; |
| 1443 | } |
| 1444 | |
| 1445 | $html = '<!doctypehtml><html lang=es><meta charset=UTF-8><meta content="width=device-width,initial-scale=1"name=viewport><title>Recordatorio de Pago - Vencimiento en 1 semana</title><style>body{font-family:Arial,sans-serif;font-size:11;line-height:1.6;max-width:600px;margin:0 auto;padding:20px}@media only screen and (max-width:600px){body{padding:15px}}</style><p>Estimado cliente,</p><p>Le contactamos desde <strong>Grupo Fire</strong>, empresa responsable del mantenimiento de sus extintores, en relación con las <strong>facturas pendientes de pago</strong> que se detallan en los documentos adjuntos.</p><p>Tras revisar nuestra contabilidad, hemos comprobado que, a dÃa de hoy, los importes correspondientes aún no han sido abonados. Por ello, le agradecerÃamos que nos indicara si existe alguna incidencia o motivo que haya podido impedir el pago (por ejemplo: cambio de cuenta bancaria, domiciliación no autorizada, disconformidad con la factura, etc.).</p><p>En caso de no existir ninguna incidencia, le agradecerÃamos proceder al abono de los importes pendientes a la mayor brevedad. Puede realizar el pago mediante ingreso o transferencia a la cuenta bancaria que figura en las facturas adjuntas.</p><p>Un cordial saludo,<br><img alt=""src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAUAAAAB9CAYAAADTA7ptAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAO3RFWHRDb21tZW50AHhyOmQ6REFGX1pUUHROLUk6MixqOjU3NDkyNjY0NzQyMDk5MjEyODMsdDoyNDAzMTMxM8+vtAYAAATsaVRYdFhNTDpjb20uYWRvYmUueG1wAAAAAAA8eDp4bXBtZXRhIHhtbG5zOng9J2Fkb2JlOm5zOm1ldGEvJz4KICAgICAgICA8cmRmOlJERiB4bWxuczpyZGY9J2h0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMnPgoKICAgICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0nJwogICAgICAgIHhtbG5zOmRjPSdodHRwOi8vcHVybC5vcmcvZGMvZWxlbW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DUmnKkh64XRg7YAJ6losaeWFHqw6nA3J5KrJfPNaMjdeT3rRH6DZCgIHLojzfhWCom4I5RVwGWV8nTCBBKieAMXvpSVU6MTn4qL+tbEADu3tIfrtb+l7Zyf5X/83YesnmK4T/hiTlK/Uoj28fldKbIvFtdnjJXNRmExyTGLheXa2YNKYmhpSv19HxbKlVFx9NUybDnHsmwqkkqDmWOkFwdcvTvpRZsAyyvjaYOIIcBQYEJxqQ+zx47i2NsL/24v9YC9hSwva3gG9vdgoBGu9CrV6VZkkQBkBFxNlIrIgqmAMEgRoOkNQPZngolqCy+pINzQQzLuEoGY6QWXWE6X0R9GXUUYZ5xfOCAEm8Kd24ByIzw8WVbSrC3u4DftFO7btM+wnrdi2z3BHjyKdnUR9vV7R2VpfRD2VRnI5qJ5MMKOW1MW1mNmzMDMvJJg+HZk+HUlVxBac9U4X8TZigjIBllHG+Yf/B52NO1ZZIPV/AAAAAElFTkSuQmCC" style=width:"height: 45px;"></div>'; |
| 1446 | |
| 1447 | $sendgrid = new \SendGrid(config('services.sendgrid.api_key')); |
| 1448 | |
| 1449 | $successCount = 0; |
| 1450 | $failCount = 0; |
| 1451 | |
| 1452 | $email = new Mail; |
| 1453 | |
| 1454 | // $fromEmail = 'recordatorio.factura@fire.es'; |
| 1455 | $fromName = 'Recordatorio Facturas Grupo Fire'; |
| 1456 | $email->setFrom($fromEmail[$entorno], $fromName); |
| 1457 | $email->setReplyTo($fromEmail[$entorno], 'Recordatorio Facturas Grupo Fire'); |
| 1458 | $email->setSubject('EnvÃo de factura '.$idFactura); |
| 1459 | $email->addContent('text/html', $html); |
| 1460 | $email->addTo($emailToSend); |
| 1461 | |
| 1462 | if (! base64_decode((string) $invoiceData['documento'], true)) { |
| 1463 | throw new \Exception('El documento no es un base64 válido'); |
| 1464 | } |
| 1465 | |
| 1466 | // No Content-ID on the attachment: Gmail strips |
| 1467 | // inline-orphan MIME parts and the PDF never arrives. |
| 1468 | $attachment = new Attachment; |
| 1469 | $attachment->setContent($invoiceData['documento']); |
| 1470 | $attachment->setType('application/pdf'); |
| 1471 | $attachment->setFilename($idFactura); |
| 1472 | $attachment->setDisposition('attachment'); |
| 1473 | $email->addAttachment($attachment); |
| 1474 | |
| 1475 | try { |
| 1476 | $response = $sendgrid->send($email); |
| 1477 | SendgridLogger::log($email, $response); |
| 1478 | } catch (\Throwable $sendException) { |
| 1479 | SendgridLogger::logException($email, $sendException); |
| 1480 | throw $sendException; |
| 1481 | } |
| 1482 | |
| 1483 | if ($response->statusCode() != 202) { |
| 1484 | throw new Exception('Envio fallido'); |
| 1485 | } |
| 1486 | |
| 1487 | // --- AQUà LLAMAS A TU LÓGICA DE ENVÃO --- |
| 1488 | |
| 1489 | // $updateRange = $sheetName . '!D' . $currentRowNumber . ':E' . $currentRowNumber; |
| 1490 | $updateData = [[$entorno, $idFactura, $emailToSend, 'Si', date('Y-m-d H:i:s')]]; |
| 1491 | |
| 1492 | $this->writeToGoogleSheet( |
| 1493 | $googleSheetsService, |
| 1494 | $spreadsheetId, |
| 1495 | $sheetName, |
| 1496 | $updateData, |
| 1497 | $currentRowNumber |
| 1498 | ); |
| 1499 | |
| 1500 | } catch (\Exception $e) { |
| 1501 | continue; |
| 1502 | } |
| 1503 | } |
| 1504 | } |
| 1505 | |
| 1506 | return ['success' => true, 'message' => 'Processing complete']; |
| 1507 | |
| 1508 | } catch (\Exception $e) { |
| 1509 | Log::error('Error en sendCallCenterInvoices: '.$e->getMessage()); |
| 1510 | |
| 1511 | return response()->json(['success' => false, 'message' => $e->getMessage()]); |
| 1512 | } |
| 1513 | } |
| 1514 | |
| 1515 | // Google sheets |
| 1516 | public function addToSheets($codCliente, $invoice, $region, $spreadsheetId = '15Lc9tJnHDOGp33V9RH86mXtIybJBAWWlW4fe7knhDZY') |
| 1517 | { |
| 1518 | $sheetName = 'Hoja 1'; |
| 1519 | $googleSheetsService = null; |
| 1520 | $nextRow = 1; |
| 1521 | |
| 1522 | try { |
| 1523 | $googleSheetsService = $this->getGoogleSheetsService(); |
| 1524 | $range = $sheetName.'!A:A'; |
| 1525 | $response = $googleSheetsService->spreadsheets_values->get($spreadsheetId, $range); |
| 1526 | $values = $response->getValues(); |
| 1527 | $nextRow = $values ? count($values) + 1 : 1; |
| 1528 | |
| 1529 | } catch (\Exception $e) { |
| 1530 | if (str_contains($e->getMessage(), 'Primera configuración requerida')) { |
| 1531 | return [ |
| 1532 | 'success' => false, |
| 1533 | 'message' => $e->getMessage(), |
| 1534 | 'requires_auth' => true, |
| 1535 | ]; |
| 1536 | } |
| 1537 | |
| 1538 | return [ |
| 1539 | 'success' => false, |
| 1540 | 'message' => 'Error de conexión con Google Sheets: '.$e->getMessage(), |
| 1541 | ]; |
| 1542 | } |
| 1543 | |
| 1544 | if ($googleSheetsService && $nextRow === 1) { |
| 1545 | $this->writeToGoogleSheet($googleSheetsService, $spreadsheetId, $sheetName, [ |
| 1546 | ['ID Cliente', 'Número de Factura', 'Fecha de Compromiso de Pago', 'Fecha de Compromiso de Pago + 10 dÃas', 'Region'], |
| 1547 | ], 1); |
| 1548 | $nextRow = 2; |
| 1549 | } |
| 1550 | |
| 1551 | $fechaCompromiso = date('Y-m-d'); |
| 1552 | $fechaCompromisoMas10 = date('Y-m-d', strtotime('+10 days')); |
| 1553 | |
| 1554 | $data = [ |
| 1555 | $codCliente, |
| 1556 | $invoice, |
| 1557 | $fechaCompromiso, |
| 1558 | $fechaCompromisoMas10, |
| 1559 | $region, |
| 1560 | ]; |
| 1561 | |
| 1562 | if ($googleSheetsService) { |
| 1563 | $this->writeToGoogleSheet($googleSheetsService, $spreadsheetId, $sheetName, [$data], $nextRow); |
| 1564 | $nextRow++; |
| 1565 | } |
| 1566 | |
| 1567 | } |
| 1568 | |
| 1569 | private function getGoogleSheetsService(): Sheets |
| 1570 | { |
| 1571 | |
| 1572 | $redirectUrl = ''; |
| 1573 | if (config('app.env') === 'production') { |
| 1574 | $redirectUrl = 'https://fireservicetitan.com/api/google-sheets-callback'; |
| 1575 | } |
| 1576 | |
| 1577 | if (config('app.env') === 'staging') { |
| 1578 | $redirectUrl = 'https://stg.fireservicetitan.com/api/google-sheets-callback'; |
| 1579 | } |
| 1580 | |
| 1581 | if (config('app.env') === 'local') { |
| 1582 | $redirectUrl = 'http://localhost:8000/api/google-sheets-callback'; |
| 1583 | } |
| 1584 | |
| 1585 | $client = new Client; |
| 1586 | $client->setAuthConfig(storage_path('app/credentials.json')); |
| 1587 | $client->addScope(Sheets::SPREADSHEETS); |
| 1588 | $client->setAccessType('offline'); |
| 1589 | $client->setPrompt('select_account consent'); |
| 1590 | $client->setRedirectUri($redirectUrl); |
| 1591 | |
| 1592 | $tokenPath = storage_path('app/token.json'); |
| 1593 | |
| 1594 | if (file_exists($tokenPath)) { |
| 1595 | $accessToken = json_decode(file_get_contents($tokenPath), true); |
| 1596 | $client->setAccessToken($accessToken); |
| 1597 | } |
| 1598 | |
| 1599 | if ($client->isAccessTokenExpired()) { |
| 1600 | if ($client->getRefreshToken()) { |
| 1601 | $newToken = $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken()); |
| 1602 | file_put_contents($tokenPath, json_encode($newToken)); |
| 1603 | } else { |
| 1604 | $authUrl = $client->createAuthUrl(); |
| 1605 | throw new \Exception('Initial setup required. Visit this URL to authorize: '.$authUrl); |
| 1606 | } |
| 1607 | } |
| 1608 | |
| 1609 | return new Sheets($client); |
| 1610 | } |
| 1611 | |
| 1612 | private function writeToGoogleSheet($service, $spreadsheetId, string $sheetName, array $data, int|float $rowNumber) |
| 1613 | { |
| 1614 | try { |
| 1615 | $range = $sheetName.'!A'.$rowNumber.':E'.$rowNumber; |
| 1616 | |
| 1617 | $body = new ValueRange([ |
| 1618 | 'values' => $data, |
| 1619 | ]); |
| 1620 | |
| 1621 | $params = [ |
| 1622 | 'valueInputOption' => 'USER_ENTERED', |
| 1623 | ]; |
| 1624 | |
| 1625 | $result = $service->spreadsheets_values->update( |
| 1626 | $spreadsheetId, |
| 1627 | $range, |
| 1628 | $body, |
| 1629 | $params |
| 1630 | ); |
| 1631 | |
| 1632 | return $result; |
| 1633 | |
| 1634 | } catch (\Exception $e) { |
| 1635 | Log::error('⌠Error escribiendo en Google Sheets: '.$e->getMessage()); |
| 1636 | throw $e; |
| 1637 | } |
| 1638 | } |
| 1639 | |
| 1640 | public function handleGoogleAuthCallback(Request $request) |
| 1641 | { |
| 1642 | try { |
| 1643 | // Verificar que el código existe |
| 1644 | if (! $request->get('code')) { |
| 1645 | Log::error('⌠No code parameter found'); |
| 1646 | |
| 1647 | return response()->json([ |
| 1648 | 'success' => false, |
| 1649 | 'message' => 'No authorization code provided', |
| 1650 | ], 400); |
| 1651 | } |
| 1652 | |
| 1653 | $redirectUrl = ''; |
| 1654 | |
| 1655 | if (config('app.env') === 'production') { |
| 1656 | $redirectUrl = 'https://fireservicetitan.com/api/google-sheets-callback'; |
| 1657 | } |
| 1658 | |
| 1659 | if (config('app.env') === 'staging') { |
| 1660 | $redirectUrl = 'https://stg.fireservicetitan.com/api/google-sheets-callback'; |
| 1661 | } |
| 1662 | |
| 1663 | if (config('app.env') === 'local') { |
| 1664 | $redirectUrl = 'http://localhost:8000/api/google-sheets-callback'; |
| 1665 | } |
| 1666 | |
| 1667 | $client = new Client; |
| 1668 | $client->setAuthConfig(storage_path('app/credentials.json')); |
| 1669 | $client->addScope(Sheets::SPREADSHEETS); |
| 1670 | $client->setRedirectUri($redirectUrl); |
| 1671 | |
| 1672 | $token = $client->fetchAccessTokenWithAuthCode($request->get('code')); |
| 1673 | |
| 1674 | file_put_contents(storage_path('app/token.json'), json_encode($token)); |
| 1675 | |
| 1676 | return response()->json([ |
| 1677 | 'success' => true, |
| 1678 | 'message' => 'Google Sheets authentication complete! You can now run the invoicing function.', |
| 1679 | ]); |
| 1680 | |
| 1681 | } catch (\Exception $e) { |
| 1682 | Log::error('Error on Google sheets callback: '.$e->getMessage()); |
| 1683 | Log::error('Error details: '.$e->getTraceAsString()); |
| 1684 | |
| 1685 | return response()->json([ |
| 1686 | 'success' => false, |
| 1687 | 'message' => 'Error: '.$e->getMessage(), |
| 1688 | ], 400); |
| 1689 | } |
| 1690 | } |
| 1691 | |
| 1692 | private function getVencimientosFormateados(array $dataInvoice): ?string |
| 1693 | { |
| 1694 | $vencimientos = $dataInvoice['factura']['vencimientos'] ?? []; |
| 1695 | |
| 1696 | if (count($vencimientos) === 0) { |
| 1697 | return null; |
| 1698 | } |
| 1699 | |
| 1700 | $fechasFormateadas = array_map(fn (array $vencimiento) => Carbon::createFromFormat('Y-m-d', $vencimiento['fecha_vencimiento']) |
| 1701 | ->isoFormat('D [de] MMMM [de] YYYY'), $vencimientos); |
| 1702 | |
| 1703 | return implode(' ó ', $fechasFormateadas); |
| 1704 | } |
| 1705 | |
| 1706 | public function listCreditDaysOffered($region): array |
| 1707 | { |
| 1708 | try { |
| 1709 | |
| 1710 | ini_set('max_execution_time', 123456); |
| 1711 | $date = now()->subMonth()->toDateString(); |
| 1712 | |
| 1713 | $lastMonthClients = $this->request('get', 'cliente/nuevosconunafactura/'.$date, $region, []); |
| 1714 | |
| 1715 | if (! $lastMonthClients) { |
| 1716 | throw new \Exception('Error al obtener los clientes o la lista está vacía'); |
| 1717 | } |
| 1718 | |
| 1719 | $tempData = []; |
| 1720 | $monthNames = [ |
| 1721 | 1 => 'Enero', 2 => 'Febrero', 3 => 'Marzo', 4 => 'Abril', |
| 1722 | 5 => 'Mayo', 6 => 'Junio', 7 => 'Julio', 8 => 'Agosto', |
| 1723 | 9 => 'Septiembre', 10 => 'Octubre', 11 => 'Noviembre', 12 => 'Diciembre', |
| 1724 | ]; |
| 1725 | |
| 1726 | foreach ($lastMonthClients as $client) { |
| 1727 | $id = $client['ID']; |
| 1728 | $clientInvoiceResponse = $this->request('get', 'factura/cliente/'.$id, $region, []); |
| 1729 | $invoices = $clientInvoiceResponse['facturas'] ?? []; |
| 1730 | |
| 1731 | // 1. Filtro: Si tiene 2 o más facturas, saltamos (queremos 0 o 1) |
| 1732 | if (count($invoices) >= 2) { |
| 1733 | continue; |
| 1734 | } |
| 1735 | |
| 1736 | $clientData = $this->request('get', 'cliente/'.$id, $region, []); |
| 1737 | $clientData = $clientData['cliente']; |
| 1738 | |
| 1739 | // 2. Inicializamos valores por defecto para clientes SIN factura |
| 1740 | $clientValue = 0; |
| 1741 | $creditDays = 0; |
| 1742 | $invoiceData = null; |
| 1743 | |
| 1744 | // 3. Solo si tiene exactamente 1 factura, buscamos sus datos reales |
| 1745 | if (count($invoices) === 1) { |
| 1746 | $invoiceResponse = $this->request('get', 'factura/'.$invoices[0]['numero'], $region, []); |
| 1747 | $invoiceData = $invoiceResponse['factura']; |
| 1748 | |
| 1749 | $clientValue = $invoiceData['base_imponible_factura'] ?? 0; |
| 1750 | |
| 1751 | // Calculamos días de crédito solo si existen las fechas |
| 1752 | if (! empty($invoiceData['fecha_creacion']) && ! empty($invoiceData['fecha_emision'])) { |
| 1753 | $creation = Carbon::parse($invoiceData['fecha_creacion']); |
| 1754 | $send = $invoiceData['vencimientos'][0]['fecha_vencimiento'] |
| 1755 | ?? $invoiceData['fecha_emision']; |
| 1756 | $creditDays = $creation->diffInDays($send); |
| 1757 | } |
| 1758 | } |
| 1759 | |
| 1760 | $date = ($clientData['fecha_alta'] === '0000-00-00' || empty($clientData['fecha_alta'])) |
| 1761 | ? Carbon::now() |
| 1762 | : Carbon::parse($clientData['fecha_alta']); |
| 1763 | |
| 1764 | $year = $date->year; |
| 1765 | $monthNum = $date->month; |
| 1766 | $nameMes = $monthNames[$monthNum]; |
| 1767 | $weekNum = 'Semana '.$date->weekOfMonth; |
| 1768 | |
| 1769 | // Estructura de agrupación (agregamos acumuladores) |
| 1770 | if (! isset($tempData[$year])) { |
| 1771 | $tempData[$year] = []; |
| 1772 | } |
| 1773 | if (! isset($tempData[$year][$monthNum])) { |
| 1774 | $tempData[$year][$monthNum] = [ |
| 1775 | 'month' => $nameMes, |
| 1776 | 'value' => 0, |
| 1777 | 'credit_days' => 0, |
| 1778 | 'weeks' => [], |
| 1779 | ]; |
| 1780 | } |
| 1781 | if (! isset($tempData[$year][$monthNum]['weeks'][$weekNum])) { |
| 1782 | $tempData[$year][$monthNum]['weeks'][$weekNum] = [ |
| 1783 | 'created_at' => $weekNum, |
| 1784 | 'value' => 0, |
| 1785 | 'credit_days' => 0, |
| 1786 | 'clients' => [], |
| 1787 | ]; |
| 1788 | } |
| 1789 | |
| 1790 | // Sumamos a los totales del mes/semana |
| 1791 | $tempData[$year][$monthNum]['value'] += $clientValue; |
| 1792 | $tempData[$year][$monthNum]['weeks'][$weekNum]['value'] += $clientValue; |
| 1793 | |
| 1794 | $tempData[$year][$monthNum]['weeks'][$weekNum]['clients'][] = [ |
| 1795 | 'cif' => $clientData['cliente_cif'], |
| 1796 | 'client_code' => $clientData['cod_cliente'], |
| 1797 | 'client_name' => $clientData['empresa'], |
| 1798 | 'value' => number_format($clientValue, 2, ',', '.').' €', |
| 1799 | 'credit_days' => $creditDays, |
| 1800 | 'payment_days' => $clientData['forma_pago'] ?? 'N/A', |
| 1801 | 'date' => $date->toDateString(), |
| 1802 | 'has_invoice' => count($invoices) === 1, // Flag útil para el frontend |
| 1803 | ]; |
| 1804 | } |
| 1805 | |
| 1806 | // Formateo final |
| 1807 | $finalData = []; |
| 1808 | foreach ($tempData as $year => $months) { |
| 1809 | $yearEntry = ['year' => $year, 'months' => []]; |
| 1810 | foreach ($months as $m) { |
| 1811 | $m['weeks'] = array_values($m['weeks']); |
| 1812 | $m['value'] = number_format($m['value'], 2, ',', '.').' €'; |
| 1813 | $yearEntry['months'][] = $m; |
| 1814 | } |
| 1815 | $finalData[] = $yearEntry; |
| 1816 | } |
| 1817 | |
| 1818 | return ['success' => true, 'data' => $finalData]; |
| 1819 | |
| 1820 | } catch (\Exception $e) { |
| 1821 | return ['success' => false, 'error' => $e->getMessage()]; |
| 1822 | } |
| 1823 | } |
| 1824 | |
| 1825 | /** |
| 1826 | * FIRE-1293 (skip telemetry) — append-only record of a "we considered |
| 1827 | * this invoice and decided NOT to remind it" event. Inserts one row per |
| 1828 | * skip per cron-day so trends and postmortems don't depend on log-file |
| 1829 | * grep. |
| 1830 | * |
| 1831 | * Wrapped in try/catch so a DB error here can never abort the surrounding |
| 1832 | * reminder loop — losing one skip telemetry row is acceptable; losing a |
| 1833 | * reminder send is not. |
| 1834 | * |
| 1835 | * Reason codes are documented inline at each call site. Keep them |
| 1836 | * snake_case and stable — future SQL aggregations key off these strings. |
| 1837 | * |
| 1838 | * @param array<string,mixed>|null $context optional payload (e.g. |
| 1839 | * `['forma_pago' => 'CHEQUE']`) — anything that helps explain |
| 1840 | * a skip after the fact without re-reading G3W |
| 1841 | */ |
| 1842 | private function recordSkip( |
| 1843 | string $region, |
| 1844 | ?string $invoiceNumber, |
| 1845 | string $reason, |
| 1846 | ?array $context = null, |
| 1847 | ?int $reminderType = null, |
| 1848 | ?string $clientCode = null, |
| 1849 | ?int $amount = null, |
| 1850 | ): void { |
| 1851 | try { |
| 1852 | TblInvoiceReminderSkips::create([ |
| 1853 | 'invoice_number' => $invoiceNumber, |
| 1854 | 'region' => $region, |
| 1855 | 'skip_reason' => $reason, |
| 1856 | 'reminder_type' => $reminderType, |
| 1857 | 'client_code' => $clientCode, |
| 1858 | 'amount' => $amount, |
| 1859 | 'context' => $context, |
| 1860 | ]); |
| 1861 | } catch (\Throwable $e) { |
| 1862 | Log::channel('g3w_invoices')->warning('recordSkip failed', [ |
| 1863 | 'region' => $region, |
| 1864 | 'invoice_number' => $invoiceNumber, |
| 1865 | 'reason' => $reason, |
| 1866 | 'error' => $e->getMessage(), |
| 1867 | ]); |
| 1868 | } |
| 1869 | } |
| 1870 | |
| 1871 | /** |
| 1872 | * FIRE-1293 — Read `fecha_cobro` from G3W's `factura/{id}` payload and |
| 1873 | * persist it into `tbl_invoice_reminders.collection_date` for every |
| 1874 | * reminder row sharing the same (invoice_number, region). |
| 1875 | * |
| 1876 | * Spike (findings/FIRE-1293_Investigation.md, Finding 2) confirmed |
| 1877 | * `cobrada='NO'` with empty `fecha_cobro` for unpaid invoices, and |
| 1878 | * `cobrada='SI'` with `fecha_cobro='YYYY-MM-DD'` once paid. We only |
| 1879 | * persist the date when both signals agree. |
| 1880 | * |
| 1881 | * @return string|null the synced YYYY-MM-DD date, or null if the |
| 1882 | * invoice is still unpaid |
| 1883 | */ |
| 1884 | public function syncPaymentDateForInvoice(string $region, string $invoiceNumber): ?string |
| 1885 | { |
| 1886 | $response = $this->request('get', 'factura/'.$invoiceNumber, $region, []); |
| 1887 | $factura = $response['factura'] ?? null; |
| 1888 | |
| 1889 | if (! is_array($factura)) { |
| 1890 | return null; |
| 1891 | } |
| 1892 | |
| 1893 | $cobrada = $factura['cobrada'] ?? 'NO'; |
| 1894 | $fechaCobro = $factura['fecha_cobro'] ?? null; |
| 1895 | |
| 1896 | if ($cobrada === 'NO' || ! is_string($fechaCobro) || $fechaCobro === '') { |
| 1897 | return null; |
| 1898 | } |
| 1899 | |
| 1900 | TblInvoiceReminders::where('invoice_number', $invoiceNumber) |
| 1901 | ->where('region', $region) |
| 1902 | ->whereNull('collection_date') |
| 1903 | ->update(['collection_date' => $fechaCobro]); |
| 1904 | |
| 1905 | return $fechaCobro; |
| 1906 | } |
| 1907 | |
| 1908 | /** |
| 1909 | * FIRE-1293 — For every distinct (invoice_number, region) pair in |
| 1910 | * `tbl_invoice_reminders` that still has a NULL `collection_date` |
| 1911 | * and was first sent within `$daysBack` days, hit G3W once and |
| 1912 | * persist the payment date if the invoice is now paid. |
| 1913 | * |
| 1914 | * Default 90-day window: the KPI's attribution rule is 20 days |
| 1915 | * from first reminder; 90 leaves a generous tail for batched |
| 1916 | * collection runs without polling rows that will never attribute. |
| 1917 | * |
| 1918 | * @return array{checked:int,resolved:int,unpaid:int,errors:int} |
| 1919 | */ |
| 1920 | public function syncPaymentDatesForRegion(string $region, int $daysBack = 90): array |
| 1921 | { |
| 1922 | $checked = 0; |
| 1923 | $resolved = 0; |
| 1924 | $unpaid = 0; |
| 1925 | $errors = 0; |
| 1926 | |
| 1927 | $cutoff = Carbon::now()->subDays($daysBack)->toDateTimeString(); |
| 1928 | |
| 1929 | $invoiceNumbers = TblInvoiceReminders::where('region', $region) |
| 1930 | ->whereNull('collection_date') |
| 1931 | ->whereNotNull('invoice_number') |
| 1932 | ->where('send_datetime', '>=', $cutoff) |
| 1933 | ->distinct() |
| 1934 | ->pluck('invoice_number'); |
| 1935 | |
| 1936 | foreach ($invoiceNumbers as $invoiceNumber) { |
| 1937 | $checked++; |
| 1938 | try { |
| 1939 | $result = $this->syncPaymentDateForInvoice($region, (string) $invoiceNumber); |
| 1940 | if ($result !== null) { |
| 1941 | $resolved++; |
| 1942 | } else { |
| 1943 | $unpaid++; |
| 1944 | } |
| 1945 | } catch (\Throwable $e) { |
| 1946 | $errors++; |
| 1947 | Log::channel('g3w_invoices')->warning('syncPaymentDateForInvoice failed', [ |
| 1948 | 'region' => $region, |
| 1949 | 'invoice_number' => $invoiceNumber, |
| 1950 | 'error' => $e->getMessage(), |
| 1951 | ]); |
| 1952 | } |
| 1953 | } |
| 1954 | |
| 1955 | Log::channel('g3w_invoices')->info('syncPaymentDatesForRegion finished', [ |
| 1956 | 'region' => $region, |
| 1957 | 'days_back' => $daysBack, |
| 1958 | 'checked' => $checked, |
| 1959 | 'resolved' => $resolved, |
| 1960 | 'unpaid' => $unpaid, |
| 1961 | 'errors' => $errors, |
| 1962 | ]); |
| 1963 | |
| 1964 | return compact('checked', 'resolved', 'unpaid', 'errors'); |
| 1965 | } |
| 1966 | } |