invoicePaymentController = $invoicePaymentController; } public function ingresos(Request $request) { try { $postdate = Carbon::parse($request->date)->addMonth()->format('Y-m'); // Realizar una petición GET con encabezados $response = Http::withHeaders([ 'accept' => 'application/ld+json', 'X-API-Key' => 'b16ec9be960cdf3a8302e92a7aec84d2' ])->get('https://api.syntage.com/insights/'. $request->rfc .'/sales-revenue?options[from]='.$request->date.'-01T06%3A00%3A00&options[to]='.$postdate.'-01T05%3A59%3A59&options[periodicity]=monthly&options[type]=total'); // Verificar si la petición fue exitosa if ($response->successful()) { // Manejar la respuesta exitosa $egresos = $this->egresos($request); $data = $response->json(); // Filtrar los datos y eliminar claves numéricas $filteredData = array_values(collect($data['data']) ->where('date', $request->date) ->all()); $filteredEgresos = array_values(collect($egresos['data']) ->where('date', $request->date) ->all()); return response()->json([ 'ingresos' => $filteredData, 'egresos' => $filteredEgresos, 'datos' => $data ]); } else { // Manejar la respuesta fallida return response()->json(['error' => 'Error al obtener los datos'], $response->status()); } } catch (RequestException $e) { // Manejar excepciones específicas de solicitudes HTTP return response()->json(['error' => 'Excepción al obtener los datos: ' . $e->getMessage()], 500); } catch (\Exception $e) { // Manejar otras excepciones return response()->json(['error' => 'Error inesperado: ' . $e->getMessage()], 500); } } public function egresos(Request $request) { try { $postdate = Carbon::parse($request->date)->addMonth()->format('Y-m'); // Realizar una petición GET con encabezados $response = Http::withHeaders([ 'accept' => 'application/ld+json', 'X-API-Key' => 'b16ec9be960cdf3a8302e92a7aec84d2' ])->get('https://api.syntage.com/insights/'. $request->rfc .'/expenditures?options[from]='.$request->date.'-01T06%3A00%3A00&options[to]='.$postdate.'-01T05%3A59%3A59&options[periodicity]=monthly&options[type]=total'); // Verificar si la petición fue exitosa if ($response->successful()) { // Manejar la respuesta exitosa $data = $response->json(); return $data; } else { // Manejar la respuesta fallida return response()->json(['error' => 'Error al obtener los datos'], $response->status()); } } catch (RequestException $e) { // Manejar excepciones específicas de solicitudes HTTP return response()->json(['error' => 'Excepción al obtener los datos: ' . $e->getMessage()], 500); } catch (\Exception $e) { // Manejar otras excepciones return response()->json(['error' => 'Error inesperado: ' . $e->getMessage()], 500); } } public function ivaAFavor(Request $request) { try { $postdate = Carbon::parse($request->date)->addMonth()->format('Y-m'); // Realizar una petición GET con encabezados $response = Http::withHeaders([ 'accept' => 'application/ld+json', 'X-API-Key' => 'b16ec9be960cdf3a8302e92a7aec84d2' ])->get('https://api.syntage.com/taxpayers/'.$request->rfc.'/invoices?options[from]='.$request->date.'-01T06%3A00%3A00&options[to]='.$postdate.'-01T05%3A59%3A59&options[periodicity]=monthly&options[type]=total'); // Verificar si la petición fue exitosa if ($response->successful()) { // Manejar la respuesta exitosa $data = $response->json(); $fecha = $request->date; $filteredData = array_values(collect($data['hydra:member']) ->where('paymentType', "PUE") ->where("cancellationProcessStatus", null) //->where("isReceiver", true) ->filter(function ($item) use ($fecha) { // Escape any special characters in the user-provided date $escapedFecha = preg_quote($fecha, '/'); return preg_match("/^$escapedFecha/", $item['issuedAt']); }) ->all()); $totalIvaAFavor = 0; $totalIvaAPagar = 0; foreach ($filteredData as $invoice) { // Check if the invoice is received by the user (isReceiver) if ($invoice['isReceiver']) { // Access the transferredTaxes object $transferredTaxes = $invoice['transferredTaxes']; // Check if transferredTaxes exists if (isset($transferredTaxes) && is_array($transferredTaxes)) { // Extract the valueAddedTax amount $ivaValue = array_key_exists('valueAddedTax', $transferredTaxes) ? $transferredTaxes['valueAddedTax'] : 0; // Add the IVA value to the total $totalIvaAFavor += $ivaValue; } // Access the retainedTaxes object $retainedTaxes = $invoice['retainedTaxes']; // Check if retainedTaxes exists if (isset($retainedTaxes) && is_array($retainedTaxes)) { // Extract the valueAddedTax amount $retainedIvaValue = array_key_exists('valueAddedTax', $retainedTaxes) ? $retainedTaxes['valueAddedTax'] : 0; // Add the retained IVA value to the total $totalIvaAFavor += $retainedIvaValue; } } else { $transferredTaxes = $invoice['transferredTaxes']; // Check if transferredTaxes exists if (isset($transferredTaxes) && is_array($transferredTaxes)) { // Extract the valueAddedTax amount $ivaValue = array_key_exists('valueAddedTax', $transferredTaxes) ? $transferredTaxes['valueAddedTax'] : 0; // Add the IVA value to the total $totalIvaAPagar += $ivaValue; } } } /* $filteredData = array_values(collect($filteredData) ->where("issuedAt", "~/^2024-08/") ->all()); */ return [ 'total_iva_a_favor' => $totalIvaAFavor, 'total_iva_a_pagar' => $totalIvaAPagar, 'datos_filtrados' => $filteredData // Include the filtered data if needed ]; } else { // Manejar la respuesta fallida return response()->json(['error' => 'Error al obtener los datos'], $response->status()); } } catch (RequestException $e) { // Manejar excepciones específicas de solicitudes HTTP return response()->json(['error' => 'Excepción al obtener los datos: ' . $e->getMessage()], 500); } catch (\Exception $e) { // Manejar otras excepciones return response()->json(['error' => 'Error inesperado: ' . $e->getMessage()], 500); } } public function retenciones(Request $request) { try { // Realizar una petición GET con encabezados $response = Http::withHeaders([ 'accept' => 'application/ld+json', 'X-API-Key' => 'b16ec9be960cdf3a8302e92a7aec84d2' ])->get('https://api.syntage.com/taxpayers/'.$request->rfc.'/tax-retentions'); // Verificar si la petición fue exitosa if ($response->successful()) { // Manejar la respuesta exitosa return $response->json(); } else { // Manejar la respuesta fallida return response()->json(['error' => 'Error al obtener los datos'], $response->status()); } } catch (RequestException $e) { // Manejar excepciones específicas de solicitudes HTTP return response()->json(['error' => 'Excepción al obtener los datos: ' . $e->getMessage()], 500); } catch (\Exception $e) { // Manejar otras excepciones return response()->json(['error' => 'Error inesperado: ' . $e->getMessage()], 500); } } public function obtenerFacturas(Request $request) { $start = microtime(true); set_time_limit(1000); $user = $request->user(); //$user = User::where('email', strip_tags($request->email))->first(); $rfc = Rfc::where('rfc', strip_tags($request->rfc))->first(); $now = Carbon::now(); $maxPast = Carbon::now()->subYears(3); $first_time = false; $invoice_request = InvoiceRequest::where('rfc_id', $rfc->id)->where('type', 'invoice')->first(); if ($invoice_request) { $last_request = new Carbon($invoice_request->requested_at); $min_days = ($last_request->diff($now)->days > 1) ? true : null; } else { $first_time = true; $min_days = true; $invoice_request = new InvoiceRequest(); } if (in_array($rfc->id, $user->rfcs->pluck('id')->toArray()) && $first_time == true) { $currentMontly = $maxPast; $monthlyMaxPeriods = 36; $startMonthly = 0; while ($startMonthly <= $monthlyMaxPeriods) { if ($currentMontly->lt(Carbon::parse($now)->addMonth())) { $postMontly = Carbon::parse($currentMontly)->addMonth()->format('Y-m'); try { // Realizar una petición GET con encabezados $response = Http::withHeaders([ 'accept' => 'application/ld+json', 'X-API-Key' => 'b16ec9be960cdf3a8302e92a7aec84d2' ])->get('https://api.syntage.com/taxpayers/'. $request->rfc .'/invoices?issuedAt[before]='. $postMontly .'-01T06%3A00%3A00&issuedAt[after]='. $currentMontly->format('Y-m') .'-01T05%3A59%3A59'); // Verificar si la petición fue exitosa if ($response->successful()) { // Manejar la respuesta exitosa $data = $response->json(); $invoices = $data['hydra:member']; foreach ($invoices as $invoice_data) { // code... $invoice = Invoice::where('id', $invoice_data['uuid'])->first(); $status = Status::where('description', strip_tags($invoice_data['cancellationProcessStatus']))->first(); if (!$invoice) { $invoiceCreate = $this->setInvoice($invoice_data, $rfc); } else if ($invoice->paid_amount != $invoice_data['paidAmount'] || $invoice->due_amount != $invoice_data['dueAmount'] || $invoice->fully_paid_at != $invoice_data['fullyPaidAt'] || $invoice->last_payment_date != $invoice_data['lastPaymentDate']) { $invoiceCreate = $this->setInvoice($invoice_data, $rfc); } else if ($status) { if ($invoice->cancellation_status_id != $status->id) { $invoiceCreate = $this->setInvoice($invoice_data, $rfc); } } } } else { // Manejar la respuesta fallida return response()->json(['error' => 'Error al obtener los datos'], $response->status()); } } catch (RequestException $e) { // Manejar excepciones específicas de solicitudes HTTP return response()->json(['error' => 'Excepción al obtener los datos: ' . $e->getMessage()], 500); } catch (\Exception $e) { // Manejar otras excepciones return response()->json(['error' => 'Error inesperado: ' . $e->getMessage()], 500); } } $currentMontly = Carbon::parse($currentMontly)->addMonth(); $startMonthly++; } $invoice_request->rfc_id = $rfc->id; $invoice_request->type = 'invoice'; $invoice_request->requested_at = Carbon::now(); $invoice_request->save(); $time = microtime(true) - $start; return response()->json(Invoice::where('rfc_id', $rfc->id)->get()); } else { if (in_array($rfc->id, $user->rfcs->pluck('id')->toArray()) && $min_days == true) { $maxPast = Carbon::now()->subYears(1); $currentMontly = $maxPast; $monthlyMaxPeriods = 12; $startMonthly = 0; while ($startMonthly <= $monthlyMaxPeriods) { if ($currentMontly->lt(Carbon::parse($now)->addMonth())) { $postMontly = Carbon::parse($currentMontly)->addMonth()->format('Y-m'); try { // Realizar una petición GET con encabezados $response = Http::withHeaders([ 'accept' => 'application/ld+json', 'X-API-Key' => 'b16ec9be960cdf3a8302e92a7aec84d2' ])->get('https://api.syntage.com/taxpayers/'. $request->rfc .'/invoices?issuedAt[before]='. $postMontly .'-01T06%3A00%3A00&issuedAt[after]='. $currentMontly->format('Y-m') .'-01T05%3A59%3A59'); // Verificar si la petición fue exitosa if ($response->successful()) { // Manejar la respuesta exitosa $data = $response->json(); $invoices = $data['hydra:member']; foreach ($invoices as $invoice_data) { // code... $invoice = Invoice::where('id', $invoice_data['uuid'])->first(); $status = Status::where('description', strip_tags($invoice_data['cancellationProcessStatus']))->first(); if (!$invoice) { $invoiceCreate = $this->setInvoice($invoice_data, $rfc); } else if ($invoice->paid_amount != $invoice_data['paidAmount'] || $invoice->due_amount != $invoice_data['dueAmount'] || $invoice->fully_paid_at != $invoice_data['fullyPaidAt'] || $invoice->last_payment_date != $invoice_data['lastPaymentDate']) { $invoiceCreate = $this->setInvoice($invoice_data, $rfc); } else if ($status) { if ($invoice->cancellation_status_id != $status->id) { $invoiceCreate = $this->setInvoice($invoice_data, $rfc); } } } } else { // Manejar la respuesta fallida return response()->json(['error' => 'Error al obtener los datos'], $response->status()); } } catch (RequestException $e) { // Manejar excepciones específicas de solicitudes HTTP return response()->json(['error' => 'Excepción al obtener los datos: ' . $e->getMessage()], 500); } catch (\Exception $e) { // Manejar otras excepciones return response()->json(['error' => 'Error inesperado: ' . $e->getMessage()], 500); } } $currentMontly = Carbon::parse($currentMontly)->addMonth(); $startMonthly++; } $invoice_request->rfc_id = $rfc->id; $invoice_request->type = 'invoice'; $invoice_request->requested_at = Carbon::now(); $invoice_request->save(); $time = microtime(true) - $start; return response()->json(Invoice::where('rfc_id', $rfc->id)->get()); } else if (in_array($rfc->id, $user->rfcs->pluck('id')->toArray())) { return response()->json(Invoice::where('rfc_id', $rfc->id)->get()); } } } public function endpointObtenerFacturas(Request $request) { $user = $request->user(); $invoiceType = $request->type; $initialDateCST = Carbon::createFromFormat('Y-m-d H:i:s', $request->initialDate, 'CST'); $finalDateCST = Carbon::createFromFormat('Y-m-d H:i:s', $request->finalDate, 'CST'); $startDateUTC = $initialDateCST->copy()->firstOfMonth()->setTimezone('UTC'); $endDateUTC = $finalDateCST->copy()->endOfMonth()->setTimezone('UTC'); /** * RFCs opcionales */ $issuerRfc = null; $receiverRfc = null; if ($request->issuerRfc) { $issuerRfc = Rfc::where('rfc', strip_tags($request->issuerRfc))->first(); } if ($request->receiverRfc) { $receiverRfc = Rfc::where('rfc', strip_tags($request->receiverRfc))->first(); } /** * Validar que al menos uno venga en el request */ if (!$issuerRfc && !$receiverRfc) { return response()->json([ 'error' => 'Debe seleccionar un RFC emisor o receptor' ], 422); } $userRfcIds = $user->rfcs->pluck('id')->toArray(); /** * Query base */ $query = Invoice::where('invoice_type_id', $invoiceType) ->whereBetween('issued_at', [$startDateUTC, $endDateUTC]); /** * Aplicar filtro según el RFC enviado y autorizado */ if ($issuerRfc && in_array($issuerRfc->id, $userRfcIds)) { $query->where('issuer_rfc_id', $issuerRfc->id); } elseif ($receiverRfc && in_array($receiverRfc->id, $userRfcIds)) { $query->where('receiver_rfc_id', $receiverRfc->id); } else { return response()->json(['error' => 'No autorizado'], 403); } return response()->json($query->get()); } public function facturasEmitidas(Request $request) { $user = $request->user(); //$user = User::where('email', strip_tags($request->email))->first(); $rfc = Rfc::where('rfc', strip_tags($request->rfc))->first(); $initialDateCST = Carbon::createFromFormat('Y-m-d H:i:s', $request->initialDate, 'CST'); $finalDateCST = Carbon::createFromFormat('Y-m-d H:i:s', $request->finalDate, 'CST'); // Definir inicio y fin en CST (Central Standard Time) $startDateCST = $initialDateCST->copy()->firstOfMonth(); $endDateCST = $finalDateCST->copy()->endOfMonth(); // Convertir las fechas a UTC $startDateUTC = $startDateCST->copy()->setTimezone('UTC'); $endDateUTC = $endDateCST->copy()->setTimezone('UTC'); if (in_array($rfc->id, $user->rfcs->pluck('id')->toArray())) { $invoices = Invoice::where('issuer_rfc_id', $rfc->id) ->whereBetween('issued_at',[$startDateUTC, $endDateUTC]) ->orderBy('issued_at', 'asc') ->with(['conciliations' => function($query) use ($rfc) { $query->where('rfc_id', $rfc->id); } ]) ->get(); return response()->json($invoices); } } public function facturasRecibidas(Request $request) { $user = $request->user(); //$user = User::where('email', strip_tags($request->email))->first(); $rfc = Rfc::where('rfc', strip_tags($request->rfc))->first(); $initialDateCST = Carbon::createFromFormat('Y-m-d H:i:s', $request->initialDate, 'CST'); $finalDateCST = Carbon::createFromFormat('Y-m-d H:i:s', $request->finalDate, 'CST'); // Definir inicio y fin en CST (Central Standard Time) $startDateCST = $initialDateCST->copy()->firstOfMonth(); $endDateCST = $finalDateCST->copy()->endOfMonth(); // Convertir las fechas a UTC $startDateUTC = $startDateCST->copy()->setTimezone('UTC'); $endDateUTC = $endDateCST->copy()->setTimezone('UTC'); if (in_array($rfc->id, $user->rfcs->pluck('id')->toArray())) { $invoices = Invoice::where('receiver_rfc_id', $rfc->id) ->whereBetween('issued_at',[$startDateUTC, $endDateUTC]) ->orderBy('issued_at', 'asc') ->with(['conciliations' => function($query) use ($rfc) { $query->where('rfc_id', $rfc->id); }])->get(); return response()->json($invoices); } } public function facturasEmitidasConciliadas(Request $request) { $user = $request->user(); //$user = User::where('email', strip_tags($request->email))->first(); $rfc = Rfc::where('rfc', strip_tags($request->rfc))->first(); $initialDateCST = Carbon::createFromFormat('Y-m-d H:i:s', $request->initialDate, 'CST'); $finalDateCST = Carbon::createFromFormat('Y-m-d H:i:s', $request->finalDate, 'CST'); // Definir inicio y fin en CST (Central Standard Time) $startDateCST = $initialDateCST->copy()->firstOfMonth(); $endDateCST = $finalDateCST->copy()->endOfMonth(); // Convertir las fechas a UTC $startDateUTC = $startDateCST->copy()->setTimezone('UTC'); $endDateUTC = $endDateCST->copy()->setTimezone('UTC'); if (in_array($rfc->id, $user->rfcs->pluck('id')->toArray())) { $invoices = Invoice::where('issuer_rfc_id', $rfc->id) ->orderBy('issued_at', 'asc') ->whereHas('conciliations', function($query) use ($rfc, $startDateUTC, $endDateUTC) { $query->where('rfc_id', $rfc->id) ->whereBetween('conciliated_at', [$startDateUTC, $endDateUTC]); })->get(); return response()->json($invoices->sum('total_in_mxn')); } } public function facturasRecibidasConciliadas(Request $request) { $user = $request->user(); //$user = User::where('email', strip_tags($request->email))->first(); $rfc = Rfc::where('rfc', strip_tags($request->rfc))->first(); $initialDateCST = Carbon::createFromFormat('Y-m-d H:i:s', $request->initialDate, 'CST'); $finalDateCST = Carbon::createFromFormat('Y-m-d H:i:s', $request->finalDate, 'CST'); // Definir inicio y fin en CST (Central Standard Time) $startDateCST = $initialDateCST->copy()->firstOfMonth(); $endDateCST = $finalDateCST->copy()->endOfMonth(); // Convertir las fechas a UTC $startDateUTC = $startDateCST->copy()->setTimezone('UTC'); $endDateUTC = $endDateCST->copy()->setTimezone('UTC'); if (in_array($rfc->id, $user->rfcs->pluck('id')->toArray())) { $invoices = Invoice::where('receiver_rfc_id', $rfc->id) ->orderBy('issued_at', 'asc') ->whereHas('conciliations', function($query) use ($rfc, $startDateUTC, $endDateUTC) { $query->where('rfc_id', $rfc->id) ->whereBetween('conciliated_at', [$startDateUTC, $endDateUTC]); })->get(); return response()->json($invoices->sum('total_in_mxn')); } } public function conciliarFacturas(Request $request) { $user = $request->user(); //$user = User::where('email', strip_tags($request->email))->first(); $rfc = Rfc::where('rfc', strip_tags($request->rfc))->first(); if (in_array($rfc->id, $user->rfcs->pluck('id')->toArray())) { //Logica para conciliar facturas $invoices = $request->items; foreach($invoices as $invoice) { //El array que viene del front solo tiene el ID y //el boolean de conciliacion de cada invoice $conciliation = Conciliation::firstOrNew(['invoice_id' => $invoice["id"]]); $conciliation->rfc_id = $rfc->id; if($invoice["formaPago"]) { $conciliation->payment_description = $invoice["formaPago"]; } if($invoice["fechaPago"]) { $conciliation->payment_at = Carbon::createFromFormat('Y-m-d', $invoice["fechaPago"], 'UTC'); } $conciliation->is_conciliated = $invoice["conciliado"]; if($invoice["conciliado"] == true){ if($invoice["fechaConciliacion"]){ $conciliation->conciliated_at = Carbon::createFromFormat('Y-m-d', $invoice["fechaConciliacion"], 'UTC'); } else { $conciliation->conciliated_at = Carbon::now(); } } $conciliation->save(); } } return response()->json([ 'success' => 'Datos almacenados con exito' ]); } public function descargarFactura(Request $request) { $user = $request->user(); //$user = User::where('email', strip_tags($request->email))->first(); $rfc = Rfc::where('rfc', strip_tags($request->rfc))->first(); $invoice = Invoice::where('id', $request->id); if (in_array($rfc->id, $user->rfcs->pluck('id')->toArray())) { //Logica para conciliar facturas if ($invoice->issuer_rfc_id = $rfc->id || $invoice->receiver_rfc_id = $rfc->id) { if ($request->type == "pdf") { $type = "application/pdf"; } else { $type = "text/xml"; } $response = Http::withHeaders([ 'accept' => $type, 'X-API-Key' => 'b16ec9be960cdf3a8302e92a7aec84d2' ])->get('https://api.syntage.com/invoices/'. $request->id .'/cfdi'); if ($response->successful()) { // Manejar la respuesta exitosa return $response; } else { // Manejar la respuesta fallida return $response; //return response()->json(['error' => 'Error al obtener los datos'], $response->status()); } } } } public function emitirFactura(Request $request) { $user = $request->user(); //$user = User::where('email', strip_tags($request->email))->first(); $rfc = Rfc::where('rfc', strip_tags($request->issuerRfc))->first(); if (in_array($rfc->id, $user->rfcs->pluck('id')->toArray())) { //Logica para emitir facturas $issuer = Taxpayer::where('rfc_id', $rfc->id)->first(); $issuerZipCode = Invoice::where('issuer_rfc_id', $rfc->id)->first(); $facturama = new Facturama\Client('pruebas', 'pruebas2011'); $params = [ //"Serie"=>"A", //"NameId"=> "1", //"Folio"=> "999", "CfdiType"=> $request->cfdiType, "Currency"=> $request->currency, "PaymentForm"=> $request->paymentForm, "PaymentMethod"=> $request->paymentMethod, //"Exportation"=> "01", "Date"=> Carbon::now(), "ExpeditionPlace"=> $issuerZipCode->zip_code, //"OrderNumber"=> "TEST-001", //"PaymentAccountNumber"=> "6789", //"PaymentConditions"=> "Condiciones", "Issuer" => [ "Rfc"=> $issuer->rfc, "Name"=> $issuer->name, "FiscalRegime"=> $request->fiscalRegime, "TaxZipCode"=> $issuerZipCode->zip_code ], "Receiver" => [ "Rfc"=> $request->receiver->rfc, "CfdiUse"=> $request->CfdiUse, "Name"=> $request->receiver->name, "FiscalRegime"=> $request->receiver->fiscalRegime, "TaxZipCode" => $request->receiver->taxZipCode, /*"Address"=> [ "Street" => "Guadalcazar del receptor", "ExteriorNumber" => "300", "InteriorNumber" => "A", "Neighborhood"=> "Las lomas", "ZipCode" => "32040", "Municipality" => "San Luis Potosi", "State" => "San Luis Potosi", "Country" => "México" ]*/ ], 'Items' => $request->items //"LogoUrl"=> "https://www.ejemplos.co/wp-content/uploads/2015/11/Logo-Chanel.jpg", //"Observations"=> "Este es un ejemplo de observaciones", //"PaymentBankName"=> "BBVA" ]; $response = $facturama->post('api-lite/3/cfdis', $params); if ($response->successful()) { // Manejar la respuesta exitosa return $response; } else { // Manejar la respuesta fallida return $response; //return response()->json(['error' => 'Error al obtener los datos'], $response->status()); } } } /** * Escribe los Invoices en la base de datos * * @return \Illuminate\Http\Response */ public function setInvoice($invoice_data, $rfc) { // $invoice = Invoice::firstOrNew(['id' => $invoice_data['uuid']]); $invoice->api_id = $invoice_data['id']; $invoice->rfc_id = $rfc->id; $invoice->version = $invoice_data['version']; $type = InvoiceType::where('id', $invoice_data['type'])->first(); if (!$type) { $type = new InvoiceType(); $type->id = $invoice_data['type']; $type->save(); } $invoice->invoice_type_id = $invoice_data['type']; if ($invoice_data['usage']) { $usage = Usage::where('id', strip_tags($invoice_data['usage']))->first(); if (!$usage) { $usage = new Usage(); $usage->id = $invoice_data['usage']; $usage->save(); } } $invoice->usage_id = $invoice_data['usage']; if ($invoice_data['paymentType']) { $payment_type = PaymentType::where('id', strip_tags($invoice_data['paymentType']))->first(); if (!$payment_type) { $payment_type = new PaymentType(); $payment_type->id = $invoice_data['paymentType']; $payment_type->save(); } } $invoice->payment_type_id = $invoice_data['paymentType']; if ($invoice_data['paymentMethod']) { $payment_method = PaymentMethod::where('id', strip_tags($invoice_data['paymentMethod']))->first(); if (!$payment_method) { $payment_method = new PaymentMethod(); $payment_method->id = $invoice_data['paymentMethod']; $payment_method->save(); } } $invoice->payment_method_id = $invoice_data['paymentMethod']; $invoice->zip_code = $invoice_data['placeOfIssue']; if (!empty($invoice_data['currency'])) { $currency = Currency::where('id', strip_tags($invoice_data['currency']))->first(); if (!$currency) { $currency = new Currency(); $currency->id = $invoice_data['currency']; $currency->save(); } $invoice->currency_id = $invoice_data['currency']; } else { $invoice->currency_id = null; } $invoice->exchange_rate = $invoice_data['exchangeRate']; if ($invoice_data['status']) { $status = Status::where('description', strip_tags($invoice_data['status']))->first(); if (!$status) { $status = new Status(); $status->description = $invoice_data['status']; $status->save(); } } $invoice->status_id = $status->id; $invoice->pac = $invoice_data['pac']; $invoice->issued_at = Carbon::createFromFormat('Y-m-d H:i:s', $invoice_data['issuedAt']); $invoice->certified_at = Carbon::createFromFormat('Y-m-d H:i:s', $invoice_data['certifiedAt']); $cancellationType = CancellationType::where('description', strip_tags($invoice_data['cancellationStatus']))->first(); if (!$cancellationType) { $cancellationType = new CancellationType(); $cancellationType->description = $invoice_data['cancellationStatus']; $cancellationType->save(); } $invoice->cancellation_type_id = $cancellationType->id; if ($invoice_data['cancellationProcessStatus']) { $status = Status::where('description', strip_tags($invoice_data['cancellationProcessStatus']))->first(); if (!$status) { $status = new Status(); $status->description = $invoice_data['cancellationProcessStatus']; $status->save(); } } $invoice->cancellation_status_id = $status->id; if ($invoice_data['canceledAt']){ $invoice->cancelled_at = Carbon::createFromFormat('Y-m-d H:i:s', $invoice_data['canceledAt']); } $invoice->discount = $invoice_data['discount']; $invoice->tax = $invoice_data['tax']; $invoice->subtotal = $invoice_data['subtotal']; $invoice->total = $invoice_data['total']; $invoice->paid_amount = $invoice_data['paidAmount']; $invoice->due_amount = $invoice_data['dueAmount']; if ($invoice_data['fullyPaidAt']){ $invoice->fully_paid_at = Carbon::createFromFormat('Y-m-d H:i:s', $invoice_data['fullyPaidAt']); } if ($invoice_data['lastPaymentDate']){ $invoice->last_payment_date = Carbon::createFromFormat('Y-m-d H:i:s', $invoice_data['lastPaymentDate']); } $rfc = Rfc::where('rfc', strip_tags($invoice_data['issuer']['rfc']))->first(); if (!$rfc) { $rfc = new Rfc(); $rfc->rfc = $invoice_data['issuer']['rfc']; $rfc->save(); } $invoice->issuer_rfc_id = $rfc->id; $invoice->issuer_name = $invoice_data['issuer']['name']; $rfc = Rfc::where('rfc', strip_tags($invoice_data['receiver']['rfc']))->first(); if (!$rfc) { $rfc = new Rfc(); $rfc->rfc = $invoice_data['receiver']['rfc']; $rfc->save(); } $invoice->receiver_rfc_id = $rfc->id; $invoice->receiver_name = $invoice_data['receiver']['name']; $invoice->is_issuer = $invoice_data['isIssuer']; $invoice->is_receiver = $invoice_data['isReceiver']; $invoice->internal_id = $invoice_data['internalIdentifier']; $invoice->reference = $invoice_data['reference']; if ($invoice_data['creditedAmount']){ $invoice->credited_amount = $invoice_data['creditedAmount']; } if ($invoice_data['subtotalCreditedAmount']){ $invoice->subtotal_credited_amount = $invoice_data['subtotalCreditedAmount']; } $invoice->applied_taxes = $invoice_data['appliedTaxes']; $invoice->total_transferred_taxes = $invoice_data['transferredTaxes']['total']; $invoice->transferred_local_taxes = $invoice_data['transferredTaxes']['localTaxes']; $invoice->transferred_vat = $invoice_data['transferredTaxes']['valueAddedTax']; $invoice->transferred_sin_tax = $invoice_data['transferredTaxes']['sinTax']; $invoice->total_retained_taxes = $invoice_data['retainedTaxes']['total']; $invoice->retained_local_taxes = $invoice_data['retainedTaxes']['localTaxes']; $invoice->retained_vat = $invoice_data['retainedTaxes']['valueAddedTax']; $invoice->retained_income_tax = $invoice_data['retainedTaxes']['incomeTax']; $invoice->retained_sin_tax = $invoice_data['retainedTaxes']['sinTax']; $invoice->save(); } public function invoiceEndpoint(Request $request) { // $invoice_data = $request['data']['object']; $invoice = Invoice::firstOrNew(['id' => $invoice_data['uuid']]); $invoice->api_id = $invoice_data['id']; $rfc = Rfc::firstOrCreate( ['rfc' => $request['taxpayer']['id']] ); $invoice->rfc_id = $rfc->id; $invoice->version = $invoice_data['version']; $type = InvoiceType::where('id', $invoice_data['type'])->first(); if (!$type) { $type = new InvoiceType(); $type->id = $invoice_data['type']; $type->save(); } $invoice->invoice_type_id = $invoice_data['type']; if ($invoice_data['usage']) { $usage = Usage::where('id', strip_tags($invoice_data['usage']))->first(); if (!$usage) { $usage = new Usage(); $usage->id = $invoice_data['usage']; $usage->save(); } } $invoice->usage_id = $invoice_data['usage']; if ($invoice_data['paymentType']) { $payment_type = PaymentType::where('id', strip_tags($invoice_data['paymentType']))->first(); if (!$payment_type) { $payment_type = new PaymentType(); $payment_type->id = $invoice_data['paymentType']; $payment_type->save(); } } $invoice->payment_type_id = $invoice_data['paymentType']; if ($invoice_data['paymentMethod']) { $payment_method = PaymentMethod::where('id', strip_tags($invoice_data['paymentMethod']))->first(); if (!$payment_method) { $payment_method = new PaymentMethod(); $payment_method->id = $invoice_data['paymentMethod']; $payment_method->save(); } } $invoice->payment_method_id = $invoice_data['paymentMethod']; $invoice->zip_code = $invoice_data['placeOfIssue']; if ($invoice_data['currency']) { $currency = Currency::where('id', strip_tags($invoice_data['currency']))->first(); if (!$currency) { $currency = new Currency(); $currency->id = $invoice_data['currency']; $currency->save(); } } $invoice->currency_id = $invoice_data['currency']; $invoice->exchange_rate = $invoice_data['exchangeRate']; if ($invoice_data['status']) { $status = Status::where('description', strip_tags($invoice_data['status']))->first(); if (!$status) { $status = new Status(); $status->description = $invoice_data['status']; $status->save(); } } $invoice->status_id = $status->id; $invoice->pac = $invoice_data['pac']; $invoice->issued_at = Carbon::createFromFormat('Y-m-d H:i:s', $invoice_data['issuedAt']); $invoice->certified_at = Carbon::createFromFormat('Y-m-d H:i:s', $invoice_data['certifiedAt']); $cancellationType = CancellationType::where('description', strip_tags($invoice_data['cancellationStatus']))->first(); if (!$cancellationType) { $cancellationType = new CancellationType(); $cancellationType->description = $invoice_data['cancellationStatus']; $cancellationType->save(); } $invoice->cancellation_type_id = $cancellationType->id; if ($invoice_data['cancellationProcessStatus']) { $status = Status::where('description', strip_tags($invoice_data['cancellationProcessStatus']))->first(); if (!$status) { $status = new Status(); $status->description = $invoice_data['cancellationProcessStatus']; $status->save(); } } $invoice->cancellation_status_id = $status->id; if ($invoice_data['canceledAt']){ $invoice->cancelled_at = Carbon::createFromFormat('Y-m-d H:i:s', $invoice_data['canceledAt']); } $invoice->discount = $invoice_data['discount']; $invoice->tax = $invoice_data['tax']; $invoice->subtotal = $invoice_data['subtotal']; $invoice->total = $invoice_data['total']; $invoice->paid_amount = $invoice_data['paidAmount']; $invoice->due_amount = $invoice_data['dueAmount']; if ($invoice_data['fullyPaidAt']){ $invoice->fully_paid_at = Carbon::createFromFormat('Y-m-d H:i:s', $invoice_data['fullyPaidAt']); } if ($invoice_data['lastPaymentDate']){ $invoice->last_payment_date = Carbon::createFromFormat('Y-m-d H:i:s', $invoice_data['lastPaymentDate']); } $rfc = Rfc::where('rfc', strip_tags($invoice_data['issuer']['rfc']))->first(); if (!$rfc) { $rfc = new Rfc(); $rfc->rfc = $invoice_data['issuer']['rfc']; $rfc->save(); } $invoice->issuer_rfc_id = $rfc->id; $invoice->issuer_name = $invoice_data['issuer']['name']; $rfc = Rfc::where('rfc', strip_tags($invoice_data['receiver']['rfc']))->first(); if (!$rfc) { $rfc = new Rfc(); $rfc->rfc = $invoice_data['receiver']['rfc']; $rfc->save(); } $invoice->receiver_rfc_id = $rfc->id; $invoice->receiver_name = $invoice_data['receiver']['name']; $invoice->is_issuer = $invoice_data['isIssuer']; $invoice->is_receiver = $invoice_data['isReceiver']; $invoice->internal_id = $invoice_data['internalIdentifier']; $invoice->reference = $invoice_data['reference']; if ($invoice_data['creditedAmount']){ $invoice->credited_amount = $invoice_data['creditedAmount']; } if ($invoice_data['subtotalCreditedAmount']){ $invoice->subtotal_credited_amount = $invoice_data['subtotalCreditedAmount']; } $invoice->applied_taxes = $invoice_data['appliedTaxes']; $invoice->total_transferred_taxes = $invoice_data['transferredTaxes']['total']; $invoice->transferred_local_taxes = $invoice_data['transferredTaxes']['localTaxes']; $invoice->transferred_vat = $invoice_data['transferredTaxes']['valueAddedTax']; $invoice->transferred_sin_tax = $invoice_data['transferredTaxes']['sinTax']; $invoice->total_retained_taxes = $invoice_data['retainedTaxes']['total']; $invoice->retained_local_taxes = $invoice_data['retainedTaxes']['localTaxes']; $invoice->retained_vat = $invoice_data['retainedTaxes']['valueAddedTax']; $invoice->retained_income_tax = $invoice_data['retainedTaxes']['incomeTax']; $invoice->retained_sin_tax = $invoice_data['retainedTaxes']['sinTax']; $invoice->save(); } public function importarFacturas(Request $request) { // Validar que se ha subido un archivo y que es un Excel $request->validate([ 'file' => 'required|mimes:xlsx,xls,csv|max:20480', // Limitar el tamaño del archivo a 10MB 'rfc' => 'required|string', // Validación para el parámetro adicional ]); $rfc = $request->rfc; set_time_limit(1000); //ini_set('memory_limit', '-1'); try { // Procesar el archivo usando la clase de importación Excel::import(new InvoicesImport($rfc), $request->file('file')); return response()->json([ 'success' => true, 'message' => 'Excel importado correctamente' ], 200); } catch (\Exception $e) { // Manejar errores durante la importación return response()->json([ 'success' => false, 'message' => 'Error al importar el archivo: ' . $e->getMessage() ], 500); } } /** * Metricas basadas en las facturas * * @return \Illuminate\Http\Response */ public function ingresoTipoI(Request $request) { $start = microtime(true); set_time_limit(1000); $user = $request->user(); //$user = User::where('email', strip_tags($request->email))->first(); $rfc = Rfc::where('rfc', strip_tags($request->rfc))->first(); $dateCST = Carbon::createFromFormat('Y-m-d H:i:s', $request->date, 'CST'); // Definir inicio y fin en CST (Central Standard Time) $startDateCST = $dateCST->copy()->firstOfMonth(); $endDateCST = $dateCST->copy()->endOfMonth(); // Convertir las fechas a UTC $startDateUTC = $startDateCST->copy()->setTimezone('UTC'); $endDateUTC = $endDateCST->copy()->setTimezone('UTC'); $taxpayer = Taxpayer::where('rfc_id', $rfc->id)->first(); $naturalPerson = ['612', '621', '626']; if (in_array($rfc->id, $user->rfcs->pluck('id')->toArray())) { if(count(array_intersect($naturalPerson, $taxpayer->taxRegimes->pluck('id')->toArray())) > 0) { if ($request->conciliated) { $invoices = Invoice::where('issuer_rfc_id', $rfc->id) ->where('invoice_type_id', 'I') ->whereIn('cancellation_status_id', ['1', '6', '7']) ->where('payment_type_id', 'PUE') ->whereHas('conciliations', function($query) use ($rfc, $startDateUTC, $endDateUTC) { $query->where('rfc_id', $rfc->id); $query->where('is_conciliated', true); $query->whereBetween('conciliated_at', [$startDateUTC, $endDateUTC]); }) ->whereDoesntHave('invoiceLines', function($query) { $query->whereIn('product_identification', [84121603, 84121600]); }) ->get(); } else { $invoices = Invoice::where('issuer_rfc_id', $rfc->id) ->where('invoice_type_id', 'I') ->whereIn('cancellation_status_id', ['1', '6', '7']) ->where('payment_type_id', 'PUE') ->whereBetween('issued_at', [$startDateUTC, $endDateUTC]) ->whereDoesntHave('invoiceLines', function($query) { $query->whereIn('product_identification', [84121603, 84121600]); }) ->get(); } } else if ($request->conciliated) { $invoices = Invoice::where('issuer_rfc_id', $rfc->id) ->where('invoice_type_id', 'I') ->whereIn('cancellation_status_id', ['1', '6', '7']) ->whereHas('conciliations', function($query) use ($rfc, $startDateUTC, $endDateUTC) { $query->where('rfc_id', $rfc->id); $query->where('is_conciliated', true); $query->whereBetween('conciliated_at', [$startDateUTC, $endDateUTC]); }) ->whereDoesntHave('invoiceLines', function($query) { $query->whereIn('product_identification', [84121603, 84121600]); }) ->get(); } else { $invoices = Invoice::where('issuer_rfc_id', $rfc->id) ->where('invoice_type_id', 'I') ->whereIn('cancellation_status_id', ['1', '6', '7']) ->whereBetween('issued_at', [$startDateUTC, $endDateUTC]) ->whereDoesntHave('invoiceLines', function($query) { $query->whereIn('product_identification', [84121603, 84121600]); }) ->get(); } return response()->json([ 'total' => round($invoices->sum('total_in_mxn'), 2), 'transferred_vat' => round($invoices->sum('transferred_vat_in_mxn'), 2), 'transferred_sin_tax' => round($invoices->sum('transferred_sin_tax_in_mxn'), 2), 'retained_vat' => round($invoices->sum('retained_vat_in_mxn'), 2), 'start_date' => $startDateUTC, 'end_date' => $endDateUTC, 'invoicesI' => $invoices ]); } } public function gastoTipoI(Request $request) { $start = microtime(true); set_time_limit(1000); $user = $request->user(); //$user = User::where('email', strip_tags($request->email))->first(); $rfc = Rfc::where('rfc', strip_tags($request->rfc))->first(); $dateCST = Carbon::createFromFormat('Y-m-d H:i:s', $request->date, 'CST'); // Definir inicio y fin en CST (Central Standard Time) $startDateCST = $dateCST->copy()->firstOfMonth(); $endDateCST = $dateCST->copy()->endOfMonth(); // Convertir las fechas a UTC $startDateUTC = $startDateCST->copy()->setTimezone('UTC'); $endDateUTC = $endDateCST->copy()->setTimezone('UTC'); $taxpayer = Taxpayer::where('rfc_id', $rfc->id)->first(); $naturalPerson = ['612', '621', '626']; if (in_array($rfc->id, $user->rfcs->pluck('id')->toArray())) { if ($request->conciliated) { $invoices = Invoice::where('receiver_rfc_id', $rfc->id) ->where('invoice_type_id', 'I') ->whereIn('cancellation_status_id', ['1', '6', '7']) ->where('payment_type_id', 'PUE') ->whereHas('conciliations', function($query) use ($rfc, $startDateUTC, $endDateUTC) { $query->where('rfc_id', $rfc->id); $query->where('is_conciliated', true); $query->whereBetween('conciliated_at', [$startDateUTC, $endDateUTC]); }) ->whereDoesntHave('invoiceLines', function($query) { $query->whereIn('product_identification', [84121603, 84121600]); }) ->get(); } else { $invoices = Invoice::where('receiver_rfc_id', $rfc->id) ->where('invoice_type_id', 'I') ->whereIn('cancellation_status_id', ['1', '6', '7']) ->where('payment_type_id', 'PUE') ->whereBetween('issued_at', [$startDateUTC, $endDateUTC]) ->whereDoesntHave('invoiceLines', function($query) { $query->whereIn('product_identification', [84121603, 84121600]); }) ->get(); } return response()->json([ 'total' => round($invoices->sum('total_in_mxn'), 2), 'tax' => round($invoices->sum('tax_in_mxn'), 2), 'transferred_vat' => round($invoices->sum('transferred_vat_in_mxn'), 2), 'transferred_sin_tax' => round($invoices->sum('transferred_sin_tax_in_mxn'), 2), 'retained_vat' => round($invoices->sum('retained_vat_in_mxn'), 2), 'retained_income_tax' => round($invoices->sum('retained_income_tax_in_mxn'), 2), 'invoicesI' => $invoices ]); } } public function ingresoTipoE(Request $request) { $start = microtime(true); set_time_limit(1000); $user = $request->user(); //$user = User::where('email', strip_tags($request->email))->first(); $rfc = Rfc::where('rfc', strip_tags($request->rfc))->first(); $dateCST = Carbon::createFromFormat('Y-m-d H:i:s', $request->date, 'CST'); // Definir inicio y fin en CST (Central Standard Time) $startDateCST = $dateCST->copy()->firstOfMonth(); $endDateCST = $dateCST->copy()->endOfMonth(); // Convertir las fechas a UTC $startDateUTC = $startDateCST->copy()->setTimezone('UTC'); $endDateUTC = $endDateCST->copy()->setTimezone('UTC'); $taxpayer = Taxpayer::where('rfc_id', $rfc->id)->first(); $naturalPerson = ['612', '621', '626']; if (in_array($rfc->id, $user->rfcs->pluck('id')->toArray())) { if(count(array_intersect($naturalPerson, $taxpayer->taxRegimes->pluck('id')->toArray())) > 0) { if ($request->conciliated) { $invoices = Invoice::where('issuer_rfc_id', $rfc->id) ->where('invoice_type_id', 'E') ->whereIn('cancellation_status_id', ['1', '6', '7']) ->where('payment_type_id', 'PUE') ->whereHas('conciliations', function($query) use ($rfc, $startDateUTC, $endDateUTC) { $query->where('rfc_id', $rfc->id); $query->where('is_conciliated', true); $query->whereBetween('conciliated_at', [$startDateUTC, $endDateUTC]); }) ->whereDoesntHave('invoiceLines', function($query) { $query->whereIn('product_identification', [84121603, 84121600]); }) ->get(); } else { $invoices = Invoice::where('issuer_rfc_id', $rfc->id) ->where('invoice_type_id', 'E') ->whereIn('cancellation_status_id', ['1', '6', '7']) ->where('payment_type_id', 'PUE') ->whereBetween('issued_at', [$startDateUTC, $endDateUTC]) ->whereDoesntHave('invoiceLines', function($query) { $query->whereIn('product_identification', [84121603, 84121600]); }) ->get(); } } else if ($request->conciliated) { $invoices = Invoice::where('issuer_rfc_id', $rfc->id) ->where('invoice_type_id', 'E') ->whereIn('cancellation_status_id', ['1', '6', '7']) ->whereHas('conciliations', function($query) use ($rfc, $startDateUTC, $endDateUTC) { $query->where('rfc_id', $rfc->id); $query->where('is_conciliated', true); $query->whereBetween('conciliated_at', [$startDateUTC, $endDateUTC]); }) ->whereDoesntHave('invoiceLines', function($query) { $query->whereIn('product_identification', [84121603, 84121600]); }) ->get(); } else { $invoices = Invoice::where('issuer_rfc_id', $rfc->id) ->where('invoice_type_id', 'E') ->whereIn('cancellation_status_id', ['1', '6', '7']) ->whereBetween('issued_at', [$startDateUTC, $endDateUTC]) ->whereDoesntHave('invoiceLines', function($query) { $query->whereIn('product_identification', [84121603, 84121600]); }) ->get(); } return response()->json([ 'total' => round($invoices->sum('total_in_mxn'), 2), 'transferred_vat' => round($invoices->sum('transferred_vat_in_mxn'), 2), 'transferred_sin_tax' => round($invoices->sum('transferred_sin_tax_in_mxn'), 2), 'retained_vat' => round($invoices->sum('retained_vat_in_mxn'), 2), 'invoicesE' => $invoices ]); } } public function gastoTipoE(Request $request) { $start = microtime(true); set_time_limit(1000); $user = $request->user(); //$user = User::where('email', strip_tags($request->email))->first(); $rfc = Rfc::where('rfc', strip_tags($request->rfc))->first(); $dateCST = Carbon::createFromFormat('Y-m-d H:i:s', $request->date, 'CST'); // Definir inicio y fin en CST (Central Standard Time) $startDateCST = $dateCST->copy()->firstOfMonth(); $endDateCST = $dateCST->copy()->endOfMonth(); // Convertir las fechas a UTC $startDateUTC = $startDateCST->copy()->setTimezone('UTC'); $endDateUTC = $endDateCST->copy()->setTimezone('UTC'); $taxpayer = Taxpayer::where('rfc_id', $rfc->id)->first(); $naturalPerson = ['612', '621', '626']; if (in_array($rfc->id, $user->rfcs->pluck('id')->toArray())) { if ($request->conciliated) { $invoices = Invoice::where('receiver_rfc_id', $rfc->id) ->where('invoice_type_id', 'E') ->whereIn('cancellation_status_id', ['1', '6', '7']) ->where('payment_type_id', 'PUE') ->whereHas('conciliations', function($query) use ($rfc, $startDateUTC, $endDateUTC) { $query->where('rfc_id', $rfc->id); $query->where('is_conciliated', true); $query->whereBetween('conciliated_at', [$startDateUTC, $endDateUTC]); }) ->whereDoesntHave('invoiceLines', function($query) { $query->whereIn('product_identification', [84121603, 84121600]); }) ->get(); } else { $invoices = Invoice::where('receiver_rfc_id', $rfc->id) ->where('invoice_type_id', 'E') ->whereIn('cancellation_status_id', ['1', '6', '7']) ->where('payment_type_id', 'PUE') ->whereBetween('issued_at', [$startDateUTC, $endDateUTC]) ->whereDoesntHave('invoiceLines', function($query) { $query->whereIn('product_identification', [84121603, 84121600]); }) ->get(); } return response()->json([ 'total' => round($invoices->sum('total_in_mxn'), 2), 'tax' => round($invoices->sum('tax_in_mxn'), 2), 'transferred_vat' => round($invoices->sum('transferred_vat_in_mxn'), 2), 'transferred_sin_tax' => round($invoices->sum('transferred_sin_tax_in_mxn'), 2), 'retained_vat' => round($invoices->sum('retained_vat_in_mxn'), 2), 'retained_income_tax' => round($invoices->sum('retained_income_tax_in_mxn'), 2), 'invoicesE' => $invoices ]); } } public function gastoTipoN(Request $request) { $start = microtime(true); set_time_limit(1000); $user = $request->user(); //$user = User::where('email', strip_tags($request->email))->first(); $rfc = Rfc::where('rfc', strip_tags($request->rfc))->first(); $dateCST = Carbon::createFromFormat('Y-m-d H:i:s', $request->date, 'CST'); // Definir inicio y fin en CST (Central Standard Time) $startDateCST = $dateCST->copy()->firstOfMonth(); $endDateCST = $dateCST->copy()->endOfMonth(); // Convertir las fechas a UTC $startDateUTC = $startDateCST->copy()->setTimezone('UTC'); $endDateUTC = $endDateCST->copy()->setTimezone('UTC'); $taxpayer = Taxpayer::where('rfc_id', $rfc->id)->first(); $naturalPerson = ['612', '621', '626']; if (in_array($rfc->id, $user->rfcs->pluck('id')->toArray())) { if ($request->conciliated) { $invoices = Invoice::where('issuer_rfc_id', $rfc->id) ->where('invoice_type_id', 'N') ->whereIn('cancellation_status_id', ['1', '6', '7']) ->where('payment_type_id', 'PUE') ->whereHas('conciliations', function($query) use ($rfc, $startDateUTC, $endDateUTC) { $query->where('rfc_id', $rfc->id); $query->where('is_conciliated', true); $query->whereBetween('conciliated_at', [$startDateUTC, $endDateUTC]); }) ->whereDoesntHave('invoiceLines', function($query) { $query->where('product_identification', 84121603); }) ->get(); } else { $invoices = Invoice::where('issuer_rfc_id', $rfc->id) ->where('invoice_type_id', 'N') ->whereIn('cancellation_status_id', ['1', '6', '7']) ->where('payment_type_id', 'PUE') ->whereBetween('issued_at', [$startDateUTC, $endDateUTC]) ->whereDoesntHave('invoiceLines', function($query) { $query->where('product_identification', 84121603); }) ->get(); } return response()->json([ 'total' => round($invoices->sum('total_in_mxn'), 2), 'transferred_vat' => round($invoices->sum('transferred_vat_in_mxn'), 2), 'retained_vat' => round($invoices->sum('retained_vat_in_mxn'), 2), 'retained_income_tax' => round($invoices->sum('retained_income_tax_in_mxn'), 2), 'invoicesN' => $invoices ]); } } public function adquisicionPue(Request $request) { $start = microtime(true); set_time_limit(1000); $user = $request->user(); //$user = User::where('email', strip_tags($request->email))->first(); $rfc = Rfc::where('rfc', strip_tags($request->rfc))->first(); $dateCST = Carbon::createFromFormat('Y-m-d H:i:s', $request->date, 'CST'); // Definir inicio y fin en CST (Central Standard Time) $startDateCST = $dateCST->copy()->firstOfMonth(); $endDateCST = $dateCST->copy()->endOfMonth(); // Convertir las fechas a UTC $startDateUTC = $startDateCST->copy()->setTimezone('UTC'); $endDateUTC = $endDateCST->copy()->setTimezone('UTC'); $taxpayer = Taxpayer::where('rfc_id', $rfc->id)->first(); $naturalPerson = ['612', '621', '626']; if (in_array($rfc->id, $user->rfcs->pluck('id')->toArray())) { if ($request->conciliated) { $invoices = Invoice::where('receiver_rfc_id', $rfc->id) ->where('invoice_type_id', 'I') ->where('usage_id', 'G01') ->where('payment_type_id', 'PUE') ->whereHas('conciliations', function($query) use ($rfc, $startDateUTC, $endDateUTC) { $query->where('rfc_id', $rfc->id); $query->where('is_conciliated', true); $query->whereBetween('conciliated_at', [$startDateUTC, $endDateUTC]); }) ->whereDoesntHave('invoiceLines', function($query) { $query->where('product_identification', 84121603); }) ->get(); } else { $invoices = Invoice::where('receiver_rfc_id', $rfc->id) ->where('invoice_type_id', 'I') ->where('usage_id', 'G01') ->where('payment_type_id', 'PUE') ->whereBetween('issued_at', [$startDateUTC, $endDateUTC]) ->whereDoesntHave('invoiceLines', function($query) { $query->where('product_identification', 84121603); }) ->get(); } return response()->json([ 'total' => round($invoices->sum('total_in_mxn'), 2), 'tax' => round($invoices->sum('tax_in_mxn'), 2), 'invoicesAPue' => $invoices ]); } } public function ivaIngresoTipoI(Request $request) { $start = microtime(true); set_time_limit(1000); $user = $request->user(); //$user = User::where('email', strip_tags($request->email))->first(); $rfc = Rfc::where('rfc', strip_tags($request->rfc))->first(); $dateCST = Carbon::createFromFormat('Y-m-d H:i:s', $request->date, 'CST'); // Definir inicio y fin en CST (Central Standard Time) $startDateCST = $dateCST->copy()->firstOfMonth(); $endDateCST = $dateCST->copy()->endOfMonth(); // Convertir las fechas a UTC $startDateUTC = $startDateCST->copy()->setTimezone('UTC'); $endDateUTC = $endDateCST->copy()->setTimezone('UTC'); $taxpayer = Taxpayer::where('rfc_id', $rfc->id)->first(); $naturalPerson = ['612', '621', '626']; if (in_array($rfc->id, $user->rfcs->pluck('id')->toArray())) { if ($request->conciliated) { $invoices = Invoice::where('issuer_rfc_id', $rfc->id) ->where('invoice_type_id', 'I') ->whereIn('cancellation_status_id', ['1', '6', '7']) ->where('payment_type_id', 'PUE') ->whereHas('conciliations', function($query) use ($rfc, $startDateUTC, $endDateUTC) { $query->where('rfc_id', $rfc->id); $query->where('is_conciliated', true); $query->whereBetween('conciliated_at', [$startDateUTC, $endDateUTC]); }) ->whereDoesntHave('invoiceLines', function($query) { $query->where('product_identification', 84121603); }) ->get(); } else { $invoices = Invoice::where('issuer_rfc_id', $rfc->id) ->where('invoice_type_id', 'I') ->whereIn('cancellation_status_id', ['1', '6', '7']) ->where('payment_type_id', 'PUE') ->whereBetween('issued_at', [$startDateUTC, $endDateUTC]) ->whereDoesntHave('invoiceLines', function($query) { $query->where('product_identification', 84121603); }) ->get(); } return response()->json([ 'total' => round($invoices->sum('total_in_mxn'), 2), 'transferred_vat' => round($invoices->sum('transferred_vat_in_mxn'), 2), 'retained_vat' => round($invoices->sum('retained_vat_in_mxn'), 2), 'start_date' => $startDateUTC, 'end_date' => $endDateUTC, 'invoicesIiva' => $invoices ]); } } public function ivaIngresoTipoE(Request $request) { $start = microtime(true); set_time_limit(1000); $user = $request->user(); //$user = User::where('email', strip_tags($request->email))->first(); $rfc = Rfc::where('rfc', strip_tags($request->rfc))->first(); $dateCST = Carbon::createFromFormat('Y-m-d H:i:s', $request->date, 'CST'); // Definir inicio y fin en CST (Central Standard Time) $startDateCST = $dateCST->copy()->firstOfMonth(); $endDateCST = $dateCST->copy()->endOfMonth(); // Convertir las fechas a UTC $startDateUTC = $startDateCST->copy()->setTimezone('UTC'); $endDateUTC = $endDateCST->copy()->setTimezone('UTC'); $taxpayer = Taxpayer::where('rfc_id', $rfc->id)->first(); $naturalPerson = ['612', '621', '626']; if (in_array($rfc->id, $user->rfcs->pluck('id')->toArray())) { if ($request->conciliated) { $invoices = Invoice::where('issuer_rfc_id', $rfc->id) ->where('invoice_type_id', 'E') ->whereIn('cancellation_status_id', ['1', '6', '7']) ->where('payment_type_id', 'PUE') ->whereHas('conciliations', function($query) use ($rfc, $startDateUTC, $endDateUTC) { $query->where('rfc_id', $rfc->id); $query->where('is_conciliated', true); $query->whereBetween('conciliated_at', [$startDateUTC, $endDateUTC]); }) ->whereDoesntHave('invoiceLines', function($query) { $query->where('product_identification', 84121603); }) ->get(); } else { $invoices = Invoice::where('issuer_rfc_id', $rfc->id) ->where('invoice_type_id', 'E') ->whereIn('cancellation_status_id', ['1', '6', '7']) ->where('payment_type_id', 'PUE') ->whereBetween('issued_at', [$startDateUTC, $endDateUTC]) ->whereDoesntHave('invoiceLines', function($query) { $query->where('product_identification', 84121603); }) ->get(); } return response()->json([ 'total' => round($invoices->sum('total_in_mxn'), 2), 'transferred_vat' => round($invoices->sum('transferred_vat_in_mxn'), 2), 'retained_vat' => round($invoices->sum('retained_vat_in_mxn'), 2), 'invoicesEiva' => $invoices ]); } } public function ivaGastoTipoI(Request $request) { $start = microtime(true); set_time_limit(1000); $user = $request->user(); //$user = User::where('email', strip_tags($request->email))->first(); $rfc = Rfc::where('rfc', strip_tags($request->rfc))->first(); $dateCST = Carbon::createFromFormat('Y-m-d H:i:s', $request->date, 'CST'); // Definir inicio y fin en CST (Central Standard Time) $startDateCST = $dateCST->copy()->firstOfMonth(); $endDateCST = $dateCST->copy()->endOfMonth(); // Convertir las fechas a UTC $startDateUTC = $startDateCST->copy()->setTimezone('UTC'); $endDateUTC = $endDateCST->copy()->setTimezone('UTC'); $taxpayer = Taxpayer::where('rfc_id', $rfc->id)->first(); $naturalPerson = ['612', '621', '626']; if (in_array($rfc->id, $user->rfcs->pluck('id')->toArray())) { if ($request->conciliated) { $invoices = Invoice::where('receiver_rfc_id', $rfc->id) ->where('invoice_type_id', 'I') ->whereIn('cancellation_status_id', ['1', '6', '7']) ->where('payment_type_id', 'PUE') ->whereHas('conciliations', function($query) use ($rfc, $startDateUTC, $endDateUTC) { $query->where('rfc_id', $rfc->id); $query->where('is_conciliated', true); $query->whereBetween('conciliated_at', [$startDateUTC, $endDateUTC]); }) ->whereDoesntHave('invoiceLines', function($query) { $query->where('product_identification', 84121603) ->orWhere('product_identification', 93161608); }) ->get(); } else { $invoices = Invoice::where('receiver_rfc_id', $rfc->id) ->where('invoice_type_id', 'I') ->whereIn('cancellation_status_id', ['1', '6', '7']) ->where('payment_type_id', 'PUE') ->whereBetween('issued_at', [$startDateUTC, $endDateUTC]) ->whereDoesntHave('invoiceLines', function($query) { $query->where('product_identification', 84121603) ->orWhere('product_identification', 93161608); }) ->get(); } return response()->json([ 'total' => round($invoices->sum('total_in_mxn'), 2), 'tax' => round($invoices->sum('tax_in_mxn'), 2), 'transferred_vat' => round($invoices->sum('transferred_vat_in_mxn'), 2), 'retained_vat' => round($invoices->sum('retained_vat_in_mxn'), 2), 'invoicesI' => $invoices ]); } } public function ivaGastoTipoE(Request $request) { $start = microtime(true); set_time_limit(1000); $user = $request->user(); //$user = User::where('email', strip_tags($request->email))->first(); $rfc = Rfc::where('rfc', strip_tags($request->rfc))->first(); $dateCST = Carbon::createFromFormat('Y-m-d H:i:s', $request->date, 'CST'); // Definir inicio y fin en CST (Central Standard Time) $startDateCST = $dateCST->copy()->firstOfMonth(); $endDateCST = $dateCST->copy()->endOfMonth(); // Convertir las fechas a UTC $startDateUTC = $startDateCST->copy()->setTimezone('UTC'); $endDateUTC = $endDateCST->copy()->setTimezone('UTC'); $taxpayer = Taxpayer::where('rfc_id', $rfc->id)->first(); $naturalPerson = ['612', '621', '626']; if (in_array($rfc->id, $user->rfcs->pluck('id')->toArray())) { if ($request->conciliated) { $invoices = Invoice::where('receiver_rfc_id', $rfc->id) ->where('invoice_type_id', 'E') ->whereIn('cancellation_status_id', ['1', '6', '7']) ->where('payment_type_id', 'PUE') ->whereHas('conciliations', function($query) use ($rfc, $startDateUTC, $endDateUTC) { $query->where('rfc_id', $rfc->id); $query->where('is_conciliated', true); $query->whereBetween('conciliated_at', [$startDateUTC, $endDateUTC]); }) ->whereDoesntHave('invoiceLines', function($query) { $query->where('product_identification', 84121603) ->orWhere('product_identification', 93161608); }) ->get(); } else { $invoices = Invoice::where('receiver_rfc_id', $rfc->id) ->where('invoice_type_id', 'E') ->whereIn('cancellation_status_id', ['1', '6', '7']) ->where('payment_type_id', 'PUE') ->whereBetween('issued_at', [$startDateUTC, $endDateUTC]) ->whereDoesntHave('invoiceLines', function($query) { $query->where('product_identification', 84121603) ->orWhere('product_identification', 93161608); }) ->get(); } return response()->json([ 'total' => round($invoices->sum('total_in_mxn'), 2), 'tax' => round($invoices->sum('tax_in_mxn'), 2), 'transferred_vat' => round($invoices->sum('transferred_vat_in_mxn'), 2), 'retained_vat' => round($invoices->sum('retained_vat_in_mxn'), 2), 'invoicesE' => $invoices ]); } } public function obtenerMetricas(Request $request) { $user = $request->user(); //$user = User::where('email', strip_tags($request->email))->first(); $rfc = Rfc::where('rfc', strip_tags($request->rfc))->first(); if (in_array($rfc->id, $user->rfcs->pluck('id')->toArray())) { $ingresoI = $this->ingresoTipoI($request)->getOriginalContent(); $ingresoE = $this->ingresoTipoE($request)->getOriginalContent(); $ingresoPpd = $this->invoicePaymentController->ingresoPpd($request)->getOriginalContent(); $gastoI = $this->gastoTipoI($request)->getOriginalContent(); $gastoE = $this->gastoTipoE($request)->getOriginalContent(); $gastoN = $this->gastoTipoN($request)->getOriginalContent(); $gastoPpd = $this->invoicePaymentController->gastoPpd($request)->getOriginalContent(); $ivaIngresoI = $this->ivaIngresoTipoI($request)->getOriginalContent(); $ivaIngresoE = $this->ivaIngresoTipoE($request)->getOriginalContent(); $ivaIngresoPpd = $this->invoicePaymentController->ivaIngresoPpd($request)->getOriginalContent(); $ivaGastoI = $this->ivaGastoTipoI($request)->getOriginalContent(); $ivaGastoE = $this->ivaGastoTipoE($request)->getOriginalContent(); $adquisicionPue = $this->adquisicionPue($request)->getOriginalContent(); $adquisicionPpd = $this->invoicePaymentController->adquisicionPpd($request)->getOriginalContent(); $ingresoIsr = $ingresoI['total'] - $ingresoI['transferred_vat'] + $ingresoI['retained_vat'] - $ingresoI['transferred_sin_tax'] - $ingresoE['total'] + $ingresoE['transferred_vat'] + $ingresoE['transferred_sin_tax'] + $ingresoPpd['amount'] - $ingresoPpd['transferred_vat_ppd']; $gastoIsr = $gastoI['total'] - $gastoI['transferred_vat'] + $gastoI['retained_vat'] - $gastoI['transferred_sin_tax'] - $gastoE['total'] + $gastoE['transferred_vat'] + $gastoE['transferred_sin_tax'] + $gastoN['total'] + $gastoPpd['amount'] - $gastoPpd['transferred_vat_ppd']; $ingresoIva = $ivaIngresoI['total'] - $ivaIngresoI['transferred_vat'] +$ivaIngresoI['retained_vat'] - $ivaIngresoE['total'] + $ivaIngresoE['transferred_vat'] + $ivaIngresoPpd['amount'] - $ivaIngresoPpd['transferred_vat_ppd']; $gastoIva = $ivaGastoI['total'] - $ivaGastoI['tax'] - $ivaGastoE['total'] + $ivaGastoE['tax'] + $gastoPpd['amount'] - $gastoPpd['transferred_vat_ppd']; $ivaFavor = $gastoI['transferred_vat'] - $gastoE['transferred_vat'] + $gastoPpd['transferred_vat_ppd']; $ivaContra = $ivaIngresoI['transferred_vat'] - $ivaIngresoE['transferred_vat'] + $ivaIngresoPpd['transferred_vat_ppd']; $ivaRetenido = $ivaGastoI['retained_vat'] - $ivaGastoE['retained_vat'] + $ivaIngresoPpd['retained_vat_ppd'] + $gastoPpd['retained_vat_ppd']; $isrRetenido = $gastoI['retained_income_tax'] - $gastoE['retained_income_tax'] + $gastoPpd['retained_income_tax']; $utilidadAntesImpuestos = $ingresoIsr - $gastoIsr; $adquisicionMercancia = ($adquisicionPue['total'] - $adquisicionPue['tax']) + ($adquisicionPpd['total'] - $adquisicionPpd['tax']); return response()->json([ "ingresoISR" => round($ingresoIsr, 2), "gastoISR" => round($gastoIsr, 2), "utilidadAntesImpuestos" => round($utilidadAntesImpuestos, 2), "ingresoIVA" => round($ingresoIva, 2), "gastoIVA" => round($gastoIva, 2), "ivaFavor" => round($ivaFavor, 2), "ivaContra" => round($ivaContra, 2), "ivaRetenido" => round($ivaRetenido, 2), "isrRetenido" => round($isrRetenido, 2), "adquisicionMercancia" => round($adquisicionMercancia, 2), "ivaIngresoI" => $ivaIngresoI, "ivaIngresoE" => $ivaIngresoE, 'ivaIngresoPpd' => $ivaIngresoPpd, "ivaGastoI" => $ivaGastoI, "ingresoI" => $ingresoI, "ingresoE" => $ingresoE, "ingresoPpd" => $ingresoPpd, "gastoI" => $gastoI, "gastoE" => $gastoE, "gastoN" => $gastoN, "gastoPpd" => $gastoPpd, "adquisicionPue" => $adquisicionPue, "adquisicionPpd" => $adquisicionPpd ]); } } public function obtenerMetricasMensuales(Request $request) { $user = $request->user(); //$user = User::where('email', strip_tags($request->email))->first(); $startDate = Carbon::parse($request->startDate); // Fecha de inicio (ejemplo: 1 enero 2025) $endDate = Carbon::parse($request->endDate); // Fecha de fin (ejemplo: 31 diciembre 2025) // Array donde guardaremos los totales por mes $monthlyTotals = []; // Iteramos desde el inicio del rango hasta el final $currentDate = $startDate->copy(); $i = 0; while ($currentDate->lessThanOrEqualTo($endDate)) { // Obtenemos el inicio del mes actual $monthStart = $currentDate->startOfMonth(); $requestData = clone $request; $requestData->merge([ 'rfc' => $request->rfc, // Usamos el valor de id_tienda del Request original 'date' => Carbon::createFromFormat('Y-m-d H:i:s', $currentDate), // Usamos la fecha actual, o la que se necesite ]); // Llamamos a la función getTotalMonto para ese mes $totalMonto = $this->obtenerMetricas($requestData)->getOriginalContent(); $totalMonto["date"] = $monthStart->format('Y-m'); // Guardamos el resultado en el array, usando el formato 'Y-m' como índice $monthlyTotals[$i] = $totalMonto; // Avanzamos al siguiente mes $currentDate->addMonth(); $i++; } return $monthlyTotals; } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param \App\Models\Invoice $invoice * @return \Illuminate\Http\Response */ public function show(Invoice $invoice) { // } /** * Show the form for editing the specified resource. * * @param \App\Models\Invoice $invoice * @return \Illuminate\Http\Response */ public function edit(Invoice $invoice) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Models\Invoice $invoice * @return \Illuminate\Http\Response */ public function update(Request $request, Invoice $invoice) { // } /** * Remove the specified resource from storage. * * @param \App\Models\Invoice $invoice * @return \Illuminate\Http\Response */ public function destroy(Invoice $invoice) { // } }