Initial commit: Horux Backend API

- API REST para gestion de facturas electronicas mexicanas (CFDI)
- Laravel 9 con autenticacion OAuth 2.0 (Passport)
- Integracion con Syntage, Clerk y Facturama
- 30 modelos Eloquent, 39 controladores
- Documentacion completa en /docs

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
2026-01-18 07:44:29 +00:00
commit 61320b44d8
191 changed files with 22895 additions and 0 deletions

18
.editorconfig Normal file
View File

@@ -0,0 +1,18 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2
[docker-compose.yml]
indent_size = 4

58
.env.example Normal file
View File

@@ -0,0 +1,58 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DISK=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
MEMCACHED_HOST=127.0.0.1
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=mailpit
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_HOST=
PUSHER_PORT=443
PUSHER_SCHEME=https
PUSHER_APP_CLUSTER=mt1
VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
VITE_PUSHER_HOST="${PUSHER_HOST}"
VITE_PUSHER_PORT="${PUSHER_PORT}"
VITE_PUSHER_SCHEME="${PUSHER_SCHEME}"
VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

11
.gitattributes vendored Normal file
View File

@@ -0,0 +1,11 @@
* text=auto
*.blade.php diff=html
*.css diff=css
*.html diff=html
*.md diff=markdown
*.php diff=php
/.github export-ignore
CHANGELOG.md export-ignore
.styleci.yml export-ignore

36
.gitignore vendored Normal file
View File

@@ -0,0 +1,36 @@
/node_modules
/public/build
/public/hot
/public/storage
/storage/*.key
/vendor
.env
.env.backup
.env.production
.phpunit.result.cache
Homestead.json
Homestead.yaml
auth.json
npm-debug.log
yarn-error.log
/.fleet
/.idea
/.vscode
# Database dumps
*.sql
# OS files
.DS_Store
Thumbs.db
# Logs
*.log
storage/logs/*
!storage/logs/.gitkeep
# Cache
bootstrap/cache/*.php
storage/framework/cache/*
storage/framework/sessions/*
storage/framework/views/*

BIN
.rnd Normal file

Binary file not shown.

173
README.md Normal file
View File

@@ -0,0 +1,173 @@
# Horux Backend API
API REST Backend especializada en gestión de facturas electrónicas mexicanas (CFDI).
## Descripcion
Horux es una plataforma de gestión fiscal que permite a los usuarios:
- Gestionar y consultar facturas electrónicas (CFDI) emitidas y recibidas
- Realizar conciliaciones de facturas
- Obtener metricas financieras y analisis de rentabilidad
- Consultar informacion de contribuyentes y riesgos fiscales
- Importar facturas masivamente desde archivos Excel
## Tecnologias
| Tecnologia | Version | Proposito |
|------------|---------|-----------|
| PHP | 8.0.2+ | Lenguaje principal |
| Laravel | 9.19 | Framework backend |
| MySQL | 5.7+ | Base de datos |
| Laravel Passport | 11.0 | Autenticacion OAuth 2.0 |
| Maatwebsite Excel | 3.1 | Importacion de Excel |
| Vite | 4.0 | Build de assets |
## Integraciones Externas
- **Syntage API** - Obtencion de facturas y datos fiscales del SAT
- **Clerk** - Autenticacion social OAuth 2.0
- **Facturama** - Generacion y timbrado de CFDIs
## Estructura del Proyecto
```
Horux_back/
├── app/
│ ├── Console/ # Comandos Artisan
│ ├── Exceptions/ # Manejo de excepciones
│ ├── Http/
│ │ ├── Controllers/ # 39 controladores
│ │ ├── Middleware/ # Middleware personalizado
│ │ └── Kernel.php
│ ├── Imports/ # Importadores Excel
│ ├── Models/ # 30 modelos Eloquent
│ ├── Providers/ # Service Providers
│ └── Services/ # Servicios de negocio
├── bootstrap/ # Inicializacion
├── config/ # Configuracion
├── database/
│ ├── migrations/ # 41 migraciones
│ ├── seeders/ # Seeders
│ └── factories/ # Model factories
├── docs/ # Documentacion
├── public/ # Punto de entrada web
├── resources/ # Vistas y assets
├── routes/
│ ├── api.php # Rutas API (54+ endpoints)
│ └── web.php # Rutas web
├── storage/ # Almacenamiento
├── tests/ # Tests PHPUnit
└── vendor/ # Dependencias
```
## Instalacion Rapida
```bash
# Clonar repositorio
git clone <url-repositorio>
cd Horux_back
# Instalar dependencias PHP
composer install
# Instalar dependencias NPM
npm install
# Configurar entorno
cp .env.example .env
php artisan key:generate
# Configurar base de datos en .env
# DB_DATABASE=horux360bd
# DB_USERNAME=tu_usuario
# DB_PASSWORD=tu_password
# Ejecutar migraciones
php artisan migrate
# Configurar Passport
php artisan passport:install
# Iniciar servidor
php artisan serve
```
## Documentacion
- [Guia de Instalacion](docs/INSTALLATION.md)
- [Documentacion de API](docs/API.md)
- [Modelos y Base de Datos](docs/MODELS.md)
- [Arquitectura](docs/ARCHITECTURE.md)
## Endpoints Principales
### Autenticacion
| Metodo | Endpoint | Descripcion |
|--------|----------|-------------|
| POST | `/api/auth` | Autenticacion con Clerk |
### Facturas
| Metodo | Endpoint | Descripcion |
|--------|----------|-------------|
| GET | `/api/obtener-facturas` | Obtener todas las facturas |
| GET | `/api/facturas-emitidas` | Facturas emitidas |
| GET | `/api/facturas-recibidas` | Facturas recibidas |
| POST | `/api/conciliar-facturas` | Conciliar facturas |
| GET | `/api/descargar-factura` | Descargar CFDI |
### Metricas
| Metodo | Endpoint | Descripcion |
|--------|----------|-------------|
| GET | `/api/obtener-metricas` | Metricas globales |
| GET | `/api/obtener-metricas-mensuales` | Metricas por mes |
| GET | `/api/ivaAFavor` | IVA a favor |
Ver documentacion completa en [docs/API.md](docs/API.md)
## Modelos Principales
- **User** - Usuarios del sistema
- **Rfc** - RFCs asociados a usuarios
- **Invoice** - Facturas electronicas
- **InvoiceLine** - Lineas/conceptos de facturas
- **InvoicePayment** - Pagos de facturas (PPD)
- **Taxpayer** - Informacion de contribuyentes
Ver documentacion completa en [docs/MODELS.md](docs/MODELS.md)
## Requisitos del Sistema
- PHP >= 8.0.2
- Composer >= 2.0
- MySQL >= 5.7 o MariaDB >= 10.3
- Node.js >= 16.0
- NPM >= 8.0
## Variables de Entorno Requeridas
```env
APP_NAME=Horux
APP_ENV=production
APP_KEY=
APP_DEBUG=false
APP_URL=https://tu-dominio.com
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=horux360bd
DB_USERNAME=
DB_PASSWORD=
# Passport OAuth
PASSPORT_CLIENT_ID=
PASSPORT_CLIENT_SECRET=
```
## Licencia
Proyecto propietario - Todos los derechos reservados.
## Contacto
Para soporte tecnico o consultas sobre el proyecto.

32
app/Console/Kernel.php Normal file
View File

@@ -0,0 +1,32 @@
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')->hourly();
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}

View File

@@ -0,0 +1,50 @@
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* A list of exception types with their corresponding custom log levels.
*
* @var array<class-string<\Throwable>, \Psr\Log\LogLevel::*>
*/
protected $levels = [
//
];
/**
* A list of the exception types that are not reported.
*
* @var array<int, class-string<\Throwable>>
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed to the session on validation exceptions.
*
* @var array<int, string>
*/
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->reportable(function (Throwable $e) {
//
});
}
}

View File

@@ -0,0 +1,85 @@
<?php
namespace App\Http\Controllers;
use App\Models\CancellationType;
use Illuminate\Http\Request;
class CancellationTypeController extends Controller
{
/**
* 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\CancellationType $cancellationType
* @return \Illuminate\Http\Response
*/
public function show(CancellationType $cancellationType)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\CancellationType $cancellationType
* @return \Illuminate\Http\Response
*/
public function edit(CancellationType $cancellationType)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\CancellationType $cancellationType
* @return \Illuminate\Http\Response
*/
public function update(Request $request, CancellationType $cancellationType)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\CancellationType $cancellationType
* @return \Illuminate\Http\Response
*/
public function destroy(CancellationType $cancellationType)
{
//
}
}

View File

@@ -0,0 +1,85 @@
<?php
namespace App\Http\Controllers;
use App\Models\Conciliation;
use Illuminate\Http\Request;
class ConciliationController extends Controller
{
/**
* 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\Conciliation $conciliation
* @return \Illuminate\Http\Response
*/
public function show(Conciliation $conciliation)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Conciliation $conciliation
* @return \Illuminate\Http\Response
*/
public function edit(Conciliation $conciliation)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Conciliation $conciliation
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Conciliation $conciliation)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Conciliation $conciliation
* @return \Illuminate\Http\Response
*/
public function destroy(Conciliation $conciliation)
{
//
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}

View File

@@ -0,0 +1,88 @@
<?php
namespace App\Http\Controllers;
use App\Models\Currency;
use Illuminate\Http\Request;
class CurrencyController extends Controller
{
/**
* 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\Currency $currency
* @return \Illuminate\Http\Response
*/
public function get(Currency $currency)
{
//
$currencies = Currency::all();
return($currencies);
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Currency $currency
* @return \Illuminate\Http\Response
*/
public function edit(Currency $currency)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Currency $currency
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Currency $currency)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Currency $currency
* @return \Illuminate\Http\Response
*/
public function destroy(Currency $currency)
{
//
}
}

View File

@@ -0,0 +1,85 @@
<?php
namespace App\Http\Controllers;
use App\Models\Dimension;
use Illuminate\Http\Request;
class DimensionController extends Controller
{
/**
* 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\Dimension $dimension
* @return \Illuminate\Http\Response
*/
public function show(Dimension $dimension)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Dimension $dimension
* @return \Illuminate\Http\Response
*/
public function edit(Dimension $dimension)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Dimension $dimension
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Dimension $dimension)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Dimension $dimension
* @return \Illuminate\Http\Response
*/
public function destroy(Dimension $dimension)
{
//
}
}

View File

@@ -0,0 +1,85 @@
<?php
namespace App\Http\Controllers;
use App\Models\EconomicActivity;
use Illuminate\Http\Request;
class EconomicActivityController extends Controller
{
/**
* 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\EconomicActivity $economicActivity
* @return \Illuminate\Http\Response
*/
public function show(EconomicActivity $economicActivity)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\EconomicActivity $economicActivity
* @return \Illuminate\Http\Response
*/
public function edit(EconomicActivity $economicActivity)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\EconomicActivity $economicActivity
* @return \Illuminate\Http\Response
*/
public function update(Request $request, EconomicActivity $economicActivity)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\EconomicActivity $economicActivity
* @return \Illuminate\Http\Response
*/
public function destroy(EconomicActivity $economicActivity)
{
//
}
}

View File

@@ -0,0 +1,85 @@
<?php
namespace App\Http\Controllers;
use App\Models\Expenditure;
use Illuminate\Http\Request;
class ExpenditureController extends Controller
{
/**
* 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\Expenditure $expenditure
* @return \Illuminate\Http\Response
*/
public function show(Expenditure $expenditure)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Expenditure $expenditure
* @return \Illuminate\Http\Response
*/
public function edit(Expenditure $expenditure)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Expenditure $expenditure
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Expenditure $expenditure)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Expenditure $expenditure
* @return \Illuminate\Http\Response
*/
public function destroy(Expenditure $expenditure)
{
//
}
}

View File

@@ -0,0 +1,85 @@
<?php
namespace App\Http\Controllers;
use App\Models\Industry;
use Illuminate\Http\Request;
class IndustryController extends Controller
{
/**
* 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\Industry $industry
* @return \Illuminate\Http\Response
*/
public function show(Industry $industry)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Industry $industry
* @return \Illuminate\Http\Response
*/
public function edit(Industry $industry)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Industry $industry
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Industry $industry)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Industry $industry
* @return \Illuminate\Http\Response
*/
public function destroy(Industry $industry)
{
//
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,287 @@
<?php
namespace App\Http\Controllers;
use App\Models\InvoiceLine;
use App\Models\Invoice;
use App\Models\InvoiceRequest;
use App\Models\User;
use App\Models\Rfc;
use App\Models\InvoiceType;
use App\Models\PaymentType;
use App\Models\Status;
use Carbon\Carbon;
use App\Imports\LineItemsImport;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Client\RequestException;
class InvoiceLineController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
public function obtenerLineasFacturas(Request $request)
{
$start = microtime(true);
set_time_limit(1800);
$user = $request->user();
//$user = User::where('email', strip_tags($request->email))->first();
$rfc = Rfc::where('rfc', strip_tags($request->rfc))->first();
$now = Carbon::now();
$invoice_request = InvoiceRequest::where('rfc_id', $rfc->id)->where('type', 'line')->first();
if ($invoice_request) {
$last_request = new Carbon($invoice_request->requested_at);
$min_days = ($last_request->diff($now)->days > 1) ? true : null;
} else {
$min_days = true;
$invoice_request = new InvoiceRequest();
}
if (in_array($rfc->id, $user->rfcs->pluck('id')->toArray()) && $min_days == true) {
$dataCounter = 1;
$arrayCount = 999;
$header_id = null;
do {
try {
if (isset($header_id) && $dataCounter >= $arrayCount) {
$dataCounter = 1;
// 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/line-items?id[lt]='. $header_id .'&itemsPerPage=1000');
} else {
// 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/line-items?itemsPerPage=1000');
}
// Verificar si la petición fue exitosa
if ($response->successful()) {
// Manejar la respuesta exitosa
$data = $response->json();
$invoiceLines = $data['hydra:member'];
$arrayCount = count($invoiceLines);
foreach ($invoiceLines as $invoiceLine_data) {
// code...
$invoiceLine = $this->setInvoiceLine($invoiceLine_data, $rfc);
$dataCounter++;
if ($dataCounter == 999) {
$header_id = $invoiceLine_data['id'];
}
}
$time = microtime(true) - $start;
} 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);
}
} while ($arrayCount >= 999);
$invoice_request->rfc_id = $rfc->id;
$invoice_request->type = 'line';
$invoice_request->requested_at = Carbon::now();
$invoice_request->save();
return response()->json(['success' => 'Datos almacenados con exito', 'time' => $time]);
} else {
$time = microtime(true) - $start;
return response()->json(['success' => 'Datos almacenados con exito', 'time' => $time]);
}
}
public function importarLineasFacturas(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 LineItemsImport($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);
}
}
public function obtenerFacturasConceptos(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())) {
return response()->json(Invoice::where('rfc_id', $rfc->id)->with('invoiceLines')->get());
}
}
/**
* 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\InvoiceLine $invoiceLine
* @return \Illuminate\Http\Response
*/
public function show(InvoiceLine $invoiceLine)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\InvoiceLine $invoiceLine
* @return \Illuminate\Http\Response
*/
public function edit(InvoiceLine $invoiceLine)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\InvoiceLine $invoiceLine
* @return \Illuminate\Http\Response
*/
public function update(Request $request, InvoiceLine $invoiceLine)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\InvoiceLine $invoiceLine
* @return \Illuminate\Http\Response
*/
public function destroy(InvoiceLine $invoiceLine)
{
//
}
public function setInvoiceLine($invoiceLine_data, $rfc)
{
//
$invoiceLine = InvoiceLine::firstOrNew(['id' => $invoiceLine_data['id']]);
$invoiceLine->rfc_id = $rfc->id;
$invoice = Invoice::where('id', $invoiceLine_data['invoice']['uuid'])->first();
if($invoice) {
$invoiceLine->invoice_id = $invoiceLine_data['invoice']['uuid'];
} else {
$invoiceLine->invoice_id = null;
}
$type = InvoiceType::where('id', $invoiceLine_data['invoice']['type'])->first();
if (!$type) {
$type = new InvoiceType();
$type->id = $invoiceLine_data['invoice']['type'];
$type->save();
}
$invoiceLine->invoice_type_id = $invoiceLine_data['invoice']['type'];
if ($invoiceLine_data['invoice']['paymentType']) {
$payment_method = PaymentType::where('id', strip_tags($invoiceLine_data['invoice']['paymentType']))->first();
if (!$payment_method) {
$payment_method = new PaymentType();
$payment_method->id = $invoiceLine_data['invoice']['paymentType'];
$payment_method->save();
}
}
$invoiceLine->payment_type_id = $invoiceLine_data['invoice']['paymentType'];
if ($invoiceLine_data['invoice']['status']) {
$status = Status::where('description', strip_tags($invoiceLine_data['invoice']['status']))->first();
if (!$status) {
$status = new Status();
$status->description = $invoiceLine_data['invoice']['status'];
$status->save();
}
}
$invoiceLine->status_id = $status->id;
$rfc = Rfc::where('rfc', strip_tags($invoiceLine_data['invoice']['issuer']['rfc']))->first();
if (!$rfc) {
$rfc = new Rfc();
$rfc->rfc = $invoiceLine_data['invoice']['issuer']['rfc'];
$rfc->save();
}
$invoiceLine->issuer_rfc_id = $rfc->id;
$invoiceLine->issuer_name = $invoiceLine_data['invoice']['issuer']['name'];
$rfc = Rfc::where('rfc', strip_tags($invoiceLine_data['invoice']['receiver']['rfc']))->first();
if (!$rfc) {
$rfc = new Rfc();
$rfc->rfc = $invoiceLine_data['invoice']['receiver']['rfc'];
$rfc->save();
}
$invoiceLine->receiver_rfc_id = $rfc->id;
$invoiceLine->receiver_name = $invoiceLine_data['invoice']['receiver']['name'];
$invoiceLine->issued_at = Carbon::createFromFormat('Y-m-d H:i:s', $invoiceLine_data['invoice']['issuedAt']);
$invoiceLine->identification_number = $invoiceLine_data['identificationNumber'];
$invoiceLine->product_identification = $invoiceLine_data['productIdentification'];
$invoiceLine->description = $invoiceLine_data['description'];
$invoiceLine->description = $invoiceLine_data['description'];
$invoiceLine->unit_amount = $invoiceLine_data['unitAmount'];
$invoiceLine->unit_code = $invoiceLine_data['unitCode'];
$invoiceLine->quantity = $invoiceLine_data['quantity'];
$invoiceLine->discount_amount = $invoiceLine_data['discountAmount'];
$invoiceLine->total_amount = $invoiceLine_data['totalAmount'];
$invoiceLine->retained_vat = $invoiceLine_data['retainedTaxes']['valueAddedTax'];
$invoiceLine->retained_income_tax = $invoiceLine_data['retainedTaxes']['incomeTax'];
$invoiceLine->retained_sin_tax = $invoiceLine_data['retainedTaxes']['sinTax'];
$invoiceLine->transferred_vat = $invoiceLine_data['transferredTaxes']['valueAddedTax'];
$invoiceLine->transferred_sin_tax = $invoiceLine_data['transferredTaxes']['sinTax'];
$invoiceLine->save();
return $invoiceLine;
}
}

View File

@@ -0,0 +1,460 @@
<?php
namespace App\Http\Controllers;
use App\Models\InvoicePayment;
use App\Models\User;
use App\Models\Rfc;
use App\Models\Invoice;
use App\Models\InvoiceRequest;
use App\Models\InvoiceType;
use App\Models\PaymentMethod;
use App\Models\Currency;
use App\Models\Usage;
use App\Models\CancellationType;
use App\Models\Taxpayer;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Client\RequestException;
class InvoicePaymentController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
public function obtenerComplementosPago(Request $request)
{
$start = microtime(true);
set_time_limit(900);
$user = $request->user();
//$user = User::where('email', strip_tags($request->email))->first();
$rfc = Rfc::where('rfc', strip_tags($request->rfc))->first();
$now = Carbon::now();
$invoice_request = InvoiceRequest::where('rfc_id', $rfc->id)->where('type', 'payment')->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()) && $min_days == true) {
$dataCounter = 1;
$arrayCount = 999;
$header_id = null;
do {
try {
if (isset($header_id) && $dataCounter >= $arrayCount) {
$dataCounter = 1;
// 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/payments?id[lt]='. $header_id .'&itemsPerPage=1000');
} else {
// 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/payments?itemsPerPage=1000');
}
// Verificar si la petición fue exitosa
if ($response->successful()) {
// Manejar la respuesta exitosa
$data = $response->json();
$invoicePayments = $data['hydra:member'];
$arrayCount = count($invoicePayments);
foreach ($invoicePayments as $invoicePayment_data) {
// code...
$invoicePayment = $this->setInvoicePayment($invoicePayment_data, $rfc);
$dataCounter++;
if ($dataCounter == 999) {
$header_id = $invoicePayment_data['id'];
}
}
$time = microtime(true) - $start;
} 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);
}
} while ($arrayCount >= 999);
$invoice_request->rfc_id = $rfc->id;
$invoice_request->type = 'payment';
$invoice_request->requested_at = Carbon::now();
$invoice_request->save();
return response()->json(['success' => 'Datos almacenados con exito', 'time' => $time]);
} else {
$time = microtime(true) - $start;
return response()->json(['success' => 'Datos almacenados con exito', 'time' => $time]);
}
}
public function ingresoPpd(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) {
$invoicePayments = InvoicePayment::where('rfc_id', $rfc->id)
->whereNull('cancelled_at')
->whereHas('invoice', function($query) use ($rfc, $startDateUTC, $endDateUTC) {
$query->where('issuer_rfc_id', $rfc->id)
//Para Gasto PPD es cuando es receptor
//->where('receiver_rfc_id', $rfc->id);
->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]);
});
})
->get();
} else {
$invoicePayments = InvoicePayment::where('rfc_id', $rfc->id)
->whereNull('cancelled_at')
->whereBetween('date', [$startDateUTC, $endDateUTC])
->whereHas('invoice', function($query) use ($rfc) {
$query->where('issuer_rfc_id', $rfc->id)
//Para Gasto PPD es cuando es receptor
//->where('receiver_rfc_id', $rfc->id);
->whereIn('cancellation_status_id', ['1', '6', '7']);
})
->get();
}
} else {
return response()->json([
'total' => 0,
'amount' => 0,
'transferred_vat' => 0,
'transferred_vat_ppd' => 0,
'retained_vat' => 0,
'retained_vat_ppd' => 0,
'no_natural' => 'No es persona fisica'
]);
}
return response()->json([
'total' => round($invoicePayments->sum('total_in_mxn'), 2),
'transferred_vat' => round($invoicePayments->sum('transferred_vat_in_mxn'), 2),
'retained_vat' => round($invoicePayments->sum('retained_vat_in_mxn'), 2),
'amount' => round($invoicePayments->sum('amount_in_mxn'), 2),
'transferred_vat_ppd' => round($invoicePayments->sum('transferred_vat_ppd'), 2),
'retained_vat_ppd' => round($invoicePayments->sum('retained_vat_ppd'), 2),
'invoicesPpd' => $invoicePayments
]);
}
}
public function gastoPpd(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');
if (in_array($rfc->id, $user->rfcs->pluck('id')->toArray())) {
if ($request->conciliated) {
$invoicePayments = InvoicePayment::where('rfc_id', $rfc->id)
->whereHas('invoice', function($query) use ($rfc, $startDateUTC, $endDateUTC) {
$query->where('receiver_rfc_id', $rfc->id)
->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]);
});
})
->get();
} else {
$invoicePayments = InvoicePayment::where('rfc_id', $rfc->id)
->whereBetween('date', [$startDateUTC, $endDateUTC])
->whereHas('invoice', function($query) use ($rfc) {
$query->where('receiver_rfc_id', $rfc->id)
->whereIn('cancellation_status_id', ['1', '6', '7']);
})
->get();
}
return response()->json([
'total' => round($invoicePayments->sum('total_in_mxn'), 2),
'transferred_vat' => round($invoicePayments->sum('transferred_vat_in_mxn'), 2),
'retained_vat' => round($invoicePayments->sum('retained_vat_in_mxn'), 2),
'amount' => round($invoicePayments->sum('amount_in_mxn'), 2),
'transferred_vat_ppd' => round($invoicePayments->sum('transferred_vat_ppd'), 2),
'retained_vat_ppd' => round($invoicePayments->sum('retained_vat_ppd'), 2),
'retained_income_tax' => round($invoicePayments->sum('retained_income_tax_in_mxn'), 2),
'invoicesPpd' => $invoicePayments,
]);
}
}
public function adquisicionPpd(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');
if (in_array($rfc->id, $user->rfcs->pluck('id')->toArray())) {
if ($request->conciliated) {
$invoicePayments = InvoicePayment::where('rfc_id', $rfc->id)
->whereHas('invoice', function($query) use ($rfc, $startDateUTC, $endDateUTC) {
$query->where('receiver_rfc_id', $rfc->id)
->whereIn('cancellation_status_id', ['1', '6', '7'])
->where('usage_id', 'G01')
->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]);
});
})
->get();
} else {
$invoicePayments = InvoicePayment::where('rfc_id', $rfc->id)
->whereBetween('date', [$startDateUTC, $endDateUTC])
->whereHas('invoice', function($query) use ($rfc) {
$query->where('receiver_rfc_id', $rfc->id)
->whereIn('cancellation_status_id', ['1', '6', '7'])
->where('usage_id', 'G01');
})
->get();
}
return response()->json([
'total' => round($invoicePayments->sum('total_in_mxn'), 2),
'tax' => round($invoicePayments->sum('tax_in_mxn'), 2),
'transferred_vat' => round($invoicePayments->sum('transferred_vat_in_mxn'), 2),
'retained_vat' => round($invoicePayments->sum('retained_vat_in_mxn'), 2),
'amount' => round($invoicePayments->sum('amount_in_mxn'), 2),
'vat_ppd' => round($invoicePayments->sum('vat_ppd'), 2),
'invoicesPpd' => $invoicePayments
]);
}
}
public function ivaIngresoPpd(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) {
$invoicePayments = InvoicePayment::where('rfc_id', $rfc->id)
->whereNull('cancelled_at')
->whereHas('invoice', function($query) use ($rfc, $startDateUTC, $endDateUTC) {
$query->where('issuer_rfc_id', $rfc->id)
//Para Gasto PPD es cuando es receptor
//->where('receiver_rfc_id', $rfc->id);
->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]);
});
})
->get();
} else {
$invoicePayments = InvoicePayment::where('rfc_id', $rfc->id)
->whereNull('cancelled_at')
->whereBetween('date', [$startDateUTC, $endDateUTC])
->whereHas('invoice', function($query) use($rfc) {
$query->where('issuer_rfc_id', $rfc->id)
//Para Gasto PPD es cuando es receptor
//->where('receiver_rfc_id', $rfc->id);
->whereIn('cancellation_status_id', ['1', '6', '7']);
})
->get();
}
return response()->json([
'total' => round($invoicePayments->sum('total_in_mxn'), 2),
'transferred_vat' => round($invoicePayments->sum('transferred_vat_in_mxn'), 2),
'retained_vat' => round($invoicePayments->sum('retained_vat_in_mxn'), 2),
'amount' => round($invoicePayments->sum('amount_in_mxn'), 2),
'transferred_vat_ppd' => round($invoicePayments->sum('transferred_vat_ppd'), 2),
'retained_vat_ppd' => round($invoicePayments->sum('retained_vat_ppd'), 2)
]);
}
}
/**
* 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\InvoicePayment $invoicePayment
* @return \Illuminate\Http\Response
*/
public function show(InvoicePayment $invoicePayment)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\InvoicePayment $invoicePayment
* @return \Illuminate\Http\Response
*/
public function edit(InvoicePayment $invoicePayment)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\InvoicePayment $invoicePayment
* @return \Illuminate\Http\Response
*/
public function update(Request $request, InvoicePayment $invoicePayment)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\InvoicePayment $invoicePayment
* @return \Illuminate\Http\Response
*/
public function destroy(InvoicePayment $invoicePayment)
{
//
}
public function setInvoicePayment($invoicePayment_data, $rfc)
{
//
$invoicePayment = InvoicePayment::firstOrNew(['id' => $invoicePayment_data['id']]);
$invoicePayment->rfc_id = $rfc->id;
$invoicePayment->date = $invoicePayment_data['date'];
$invoice = Invoice::where('id', $invoicePayment_data['invoiceUuid'])->first();
if($invoice) {
$invoicePayment->invoice_id = $invoicePayment_data['invoiceUuid'];
} else {
$invoicePayment->invoice_id = null;
}
if ($invoicePayment_data['paymentMethod']) {
$payment_method = PaymentMethod::where('id', strip_tags($invoicePayment_data['paymentMethod']))->first();
if (!$payment_method) {
$payment_method = new PaymentMethod();
$payment_method->id = $invoicePayment_data['paymentMethod'];
$payment_method->save();
}
}
$invoicePayment->payment_method_id = $invoicePayment_data['paymentMethod'];
if ($invoicePayment_data['currency']) {
$currency = Currency::where('id', strip_tags($invoicePayment_data['currency']))->first();
if (!$currency) {
$currency = new Currency();
$currency->id = $invoicePayment_data['currency'];
$currency->save();
}
}
$invoicePayment->currency_id = $invoicePayment_data['currency'];
$invoicePayment->exchange_rate = $invoicePayment_data['exchangeRate'];
$invoicePayment->installment = $invoicePayment_data['installment'];
$invoicePayment->previous_balance = $invoicePayment_data['previousBalance'];
$invoicePayment->amount = $invoicePayment_data['amount'];
$invoicePayment->outstanding_balance = $invoicePayment_data['outstandingBalance'];
if ($invoicePayment_data['canceledAt']){
$invoicePayment->cancelled_at = Carbon::createFromFormat('Y-m-d H:i:s', $invoicePayment_data['canceledAt']);
}
$invoicePayment->save();
return $invoicePayment;
}
}

View File

@@ -0,0 +1,85 @@
<?php
namespace App\Http\Controllers;
use App\Models\InvoiceRequest;
use Illuminate\Http\Request;
class InvoiceRequestController extends Controller
{
/**
* 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\InvoiceRequest $invoiceRequest
* @return \Illuminate\Http\Response
*/
public function show(InvoiceRequest $invoiceRequest)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\InvoiceRequest $invoiceRequest
* @return \Illuminate\Http\Response
*/
public function edit(InvoiceRequest $invoiceRequest)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\InvoiceRequest $invoiceRequest
* @return \Illuminate\Http\Response
*/
public function update(Request $request, InvoiceRequest $invoiceRequest)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\InvoiceRequest $invoiceRequest
* @return \Illuminate\Http\Response
*/
public function destroy(InvoiceRequest $invoiceRequest)
{
//
}
}

View File

@@ -0,0 +1,88 @@
<?php
namespace App\Http\Controllers;
use App\Models\InvoiceType;
use Illuminate\Http\Request;
class InvoiceTypeController extends Controller
{
/**
* 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\InvoiceType $invoiceType
* @return \Illuminate\Http\Response
*/
public function get(InvoiceType $invoiceType)
{
//
$invoiceTypes = InvoiceType::all();
return($invoiceTypes);
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\InvoiceType $invoiceType
* @return \Illuminate\Http\Response
*/
public function edit(InvoiceType $invoiceType)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\InvoiceType $invoiceType
* @return \Illuminate\Http\Response
*/
public function update(Request $request, InvoiceType $invoiceType)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\InvoiceType $invoiceType
* @return \Illuminate\Http\Response
*/
public function destroy(InvoiceType $invoiceType)
{
//
}
}

View File

@@ -0,0 +1,85 @@
<?php
namespace App\Http\Controllers;
use App\Models\ManagerOTP;
use Illuminate\Http\Request;
class ManagerOTPController extends Controller
{
/**
* 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\ManagerOTP $managerOTP
* @return \Illuminate\Http\Response
*/
public function show(ManagerOTP $managerOTP)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\ManagerOTP $managerOTP
* @return \Illuminate\Http\Response
*/
public function edit(ManagerOTP $managerOTP)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\ManagerOTP $managerOTP
* @return \Illuminate\Http\Response
*/
public function update(Request $request, ManagerOTP $managerOTP)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\ManagerOTP $managerOTP
* @return \Illuminate\Http\Response
*/
public function destroy(ManagerOTP $managerOTP)
{
//
}
}

View File

@@ -0,0 +1,88 @@
<?php
namespace App\Http\Controllers;
use App\Models\PaymentMethod;
use Illuminate\Http\Request;
class PaymentMethodController extends Controller
{
/**
* 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\PaymentMethod $paymentMethod
* @return \Illuminate\Http\Response
*/
public function get(PaymentMethod $paymentMethod)
{
//
$paymentMethods = PaymentMethod::all();
return($paymentMethods);
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\PaymentMethod $paymentMethod
* @return \Illuminate\Http\Response
*/
public function edit(PaymentMethod $paymentMethod)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\PaymentMethod $paymentMethod
* @return \Illuminate\Http\Response
*/
public function update(Request $request, PaymentMethod $paymentMethod)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\PaymentMethod $paymentMethod
* @return \Illuminate\Http\Response
*/
public function destroy(PaymentMethod $paymentMethod)
{
//
}
}

View File

@@ -0,0 +1,88 @@
<?php
namespace App\Http\Controllers;
use App\Models\PaymentType;
use Illuminate\Http\Request;
class PaymentTypeController extends Controller
{
/**
* 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\PaymentType $paymentType
* @return \Illuminate\Http\Response
*/
public function get(PaymentType $paymentType)
{
//
$paymentTypes = PaymentType::all();
return($paymentTypes);
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\PaymentType $paymentType
* @return \Illuminate\Http\Response
*/
public function edit(PaymentType $paymentType)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\PaymentType $paymentType
* @return \Illuminate\Http\Response
*/
public function update(Request $request, PaymentType $paymentType)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\PaymentType $paymentType
* @return \Illuminate\Http\Response
*/
public function destroy(PaymentType $paymentType)
{
//
}
}

View File

@@ -0,0 +1,88 @@
<?php
namespace App\Http\Controllers;
use App\Models\PostalCode;
use Illuminate\Http\Request;
class PostalCodeController extends Controller
{
/**
* 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\PostalCode $postalCode
* @return \Illuminate\Http\Response
*/
public function get(PostalCode $postalCode)
{
//
$postalcodes = PostalCode::all();
return($postalcodes);
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\PostalCode $postalCode
* @return \Illuminate\Http\Response
*/
public function edit(PostalCode $postalCode)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\PostalCode $postalCode
* @return \Illuminate\Http\Response
*/
public function update(Request $request, PostalCode $postalCode)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\PostalCode $postalCode
* @return \Illuminate\Http\Response
*/
public function destroy(PostalCode $postalCode)
{
//
}
}

View File

@@ -0,0 +1,117 @@
<?php
namespace App\Http\Controllers;
use App\Models\ProdServCode;
use App\Imports\ProdServCodesImport;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Http\Request;
class ProdServCodeController extends Controller
{
/**
* 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 importarCodigosProdServ(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
]);
set_time_limit(1000);
//ini_set('memory_limit', '-1');
try {
// Procesar el archivo usando la clase de importación
Excel::import(new ProdServCodesImport(), $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);
}
}
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\ProdServCode $prodServCode
* @return \Illuminate\Http\Response
*/
public function get(ProdServCode $prodServCode)
{
//
$prodservcodes = ProdServCode::all();
return($prodservcodes);
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\ProdServCode $prodServCode
* @return \Illuminate\Http\Response
*/
public function edit(ProdServCode $prodServCode)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\ProdServCode $prodServCode
* @return \Illuminate\Http\Response
*/
public function update(Request $request, ProdServCode $prodServCode)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\ProdServCode $prodServCode
* @return \Illuminate\Http\Response
*/
public function destroy(ProdServCode $prodServCode)
{
//
}
}

View File

@@ -0,0 +1,116 @@
<?php
namespace App\Http\Controllers;
use App\Models\Rfc;
use App\Models\User;
use Illuminate\Http\Request;
class RfcController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Obtiene el RFC del frontend y lo registra en el usuario correspondiente
*
* @return \Illuminate\Http\Response
*/
public function insertarRfc(Request $request)
{
//
$user = $request->user();
$rfc = Rfc::where('rfc', $request->rfc)->firstOrCreate([
'rfc' => $request->rfc
],
);
$user->rfcs()->attach($rfc);
$user->save();
return response()->json([
'success' => true,
'message' => 'RFC agregado con exito'
], 200);
}
public function obtenerRfcs(Request $request)
{
$user = $request->user();
$rfcs = $user->rfcs->pluck('rfc');
return $rfcs;
}
/**
* 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\Rfc $rfc
* @return \Illuminate\Http\Response
*/
public function show(Rfc $rfc)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Rfc $rfc
* @return \Illuminate\Http\Response
*/
public function edit(Rfc $rfc)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Rfc $rfc
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Rfc $rfc)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Rfc $rfc
* @return \Illuminate\Http\Response
*/
public function destroy(Rfc $rfc)
{
//
}
}

View File

@@ -0,0 +1,107 @@
<?php
namespace App\Http\Controllers;
use App\Models\Risk;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Client\RequestException;
class RiskController extends Controller
{
/**
* 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\Risk $risk
* @return \Illuminate\Http\Response
*/
public function show(Risk $risk)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Risk $risk
* @return \Illuminate\Http\Response
*/
public function edit(Risk $risk)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Risk $risk
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Risk $risk)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Risk $risk
* @return \Illuminate\Http\Response
*/
public function destroy(Risk $risk)
{
//
}
public function consultarRisk(Request $request){
$response = Http::withHeaders([
'X-API-Key' => 'b16ec9be960cdf3a8302e92a7aec84d2'
])->get('https://api.syntage.com/insights/'.$request["rfc"].'/risks');
// Verificar si la petición fue exitosa
if ($response->successful()) {
// Manejar la respuesta exitosa
$data = $response->json();
// Filtrar los datos y eliminar claves numéricas
return response()->json([
'data' => $data["data"]
]);
} else {
// Manejar la respuesta fallida
return response()->json(['error' => 'Error al obtener los datos'], $response->status());
}
}
}

View File

@@ -0,0 +1,85 @@
<?php
namespace App\Http\Controllers;
use App\Models\Role;
use Illuminate\Http\Request;
class RoleController extends Controller
{
/**
* 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\Role $role
* @return \Illuminate\Http\Response
*/
public function show(Role $role)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Role $role
* @return \Illuminate\Http\Response
*/
public function edit(Role $role)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Role $role
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Role $role)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Role $role
* @return \Illuminate\Http\Response
*/
public function destroy(Role $role)
{
//
}
}

View File

@@ -0,0 +1,85 @@
<?php
namespace App\Http\Controllers;
use App\Models\SalesRevenue;
use Illuminate\Http\Request;
class SalesRevenueController extends Controller
{
/**
* 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\SalesRevenue $salesRevenue
* @return \Illuminate\Http\Response
*/
public function show(SalesRevenue $salesRevenue)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\SalesRevenue $salesRevenue
* @return \Illuminate\Http\Response
*/
public function edit(SalesRevenue $salesRevenue)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\SalesRevenue $salesRevenue
* @return \Illuminate\Http\Response
*/
public function update(Request $request, SalesRevenue $salesRevenue)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\SalesRevenue $salesRevenue
* @return \Illuminate\Http\Response
*/
public function destroy(SalesRevenue $salesRevenue)
{
//
}
}

View File

@@ -0,0 +1,85 @@
<?php
namespace App\Http\Controllers;
use App\Models\Status;
use Illuminate\Http\Request;
class StatusController extends Controller
{
/**
* 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\Status $status
* @return \Illuminate\Http\Response
*/
public function show(Status $status)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Status $status
* @return \Illuminate\Http\Response
*/
public function edit(Status $status)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Status $status
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Status $status)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Status $status
* @return \Illuminate\Http\Response
*/
public function destroy(Status $status)
{
//
}
}

View File

@@ -0,0 +1,88 @@
<?php
namespace App\Http\Controllers;
use App\Models\Tax;
use Illuminate\Http\Request;
class TaxController extends Controller
{
/**
* 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\Tax $tax
* @return \Illuminate\Http\Response
*/
public function get(Tax $tax)
{
//
$taxes = Tax::all();
return($taxes);
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Tax $tax
* @return \Illuminate\Http\Response
*/
public function edit(Tax $tax)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Tax $tax
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Tax $tax)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Tax $tax
* @return \Illuminate\Http\Response
*/
public function destroy(Tax $tax)
{
//
}
}

View File

@@ -0,0 +1,88 @@
<?php
namespace App\Http\Controllers;
use App\Models\TaxRate;
use Illuminate\Http\Request;
class TaxRateController extends Controller
{
/**
* 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\TaxRate $taxRate
* @return \Illuminate\Http\Response
*/
public function get(Request $request)
{
//
$taxRates = TaxRate::where('tax_id', $request->id)->get();
return($taxRates);
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\TaxRate $taxRate
* @return \Illuminate\Http\Response
*/
public function edit(TaxRate $taxRate)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\TaxRate $taxRate
* @return \Illuminate\Http\Response
*/
public function update(Request $request, TaxRate $taxRate)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\TaxRate $taxRate
* @return \Illuminate\Http\Response
*/
public function destroy(TaxRate $taxRate)
{
//
}
}

View File

@@ -0,0 +1,88 @@
<?php
namespace App\Http\Controllers;
use App\Models\TaxRegime;
use Illuminate\Http\Request;
class TaxRegimeController extends Controller
{
/**
* 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\TaxRegime $taxRegime
* @return \Illuminate\Http\Response
*/
public function get(TaxRegime $taxRegime)
{
//
$taxRegimes = TaxRegime::all();
return($taxRegimes);
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\TaxRegime $taxRegime
* @return \Illuminate\Http\Response
*/
public function edit(TaxRegime $taxRegime)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\TaxRegime $taxRegime
* @return \Illuminate\Http\Response
*/
public function update(Request $request, TaxRegime $taxRegime)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\TaxRegime $taxRegime
* @return \Illuminate\Http\Response
*/
public function destroy(TaxRegime $taxRegime)
{
//
}
}

View File

@@ -0,0 +1,312 @@
<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Models\Rfc;
use App\Models\Taxpayer;
use App\Models\EconomicActivity;
use App\Models\TaxRegime;
use App\Models\Risk;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Client\RequestException;
class TaxpayerController extends Controller
{
public function obtenerContribuyente(Request $request)
{
$start = microtime(true);
$user = $request->user();
//$user = User::where('email', strip_tags($request->email))->first();
$rfc = Rfc::where('rfc', strip_tags($request->rfc))->first();
$taxpayer = Taxpayer::where('rfc_id', $rfc->id)->first();
if ($taxpayer) {
$last_request = new Carbon($taxpayer->updated_at);
$now = Carbon::now();
$min_days = ($last_request->diff($now)->days > 7) ? true : null;
} else {
$min_days = true;
}
if (in_array($rfc->id, $user->rfcs->pluck('id')->toArray()) && $min_days == true) {
try {
// 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 .'/summary');
// Verificar si la petición fue exitosa
if ($response->successful()) {
// Manejar la respuesta exitosa
$data = $response->json();
$taxpayer_data = $data;
// code...
$taxpayer = TaxPayer::firstOrNew(['rfc_id' => $rfc->id]);
$taxpayer->name = $taxpayer_data['name'];
$taxpayer->fiscal_address = $taxpayer_data['fiscalAddress'];
$taxpayer->fiscal_address_status = $taxpayer_data['fiscalAddressStatusRaw'];
$taxpayer->save();
$economic_activities = $taxpayer_data['economicActivities'];
foreach ($economic_activities as $economic_activity_data) {
$economic_activity = EconomicActivity::where('description', $economic_activity_data['name'])->first();
if (!$economic_activity) {
$economic_activity = new EconomicActivity();
$economic_activity->description = $economic_activity_data['name'];
$economic_activity->save();
}
$taxpayer->economicActivities()->attach($economic_activity, [
'order' => $economic_activity_data['order'],
'percentage' => $economic_activity_data['percentage'],
'started_at' => $economic_activity_data['startDate'],
'ended_at' => $economic_activity_data['endDate']
]);
$taxpayer->save();
}
$tax_regimes = $taxpayer_data['taxRegimes'];
foreach ($tax_regimes as $tax_regime_data) {
$tax_regime = TaxRegime::where('id', $tax_regime_data['code'])->first();
if (!$tax_regime) {
$tax_regime = new TaxRegime();
$tax_regime->id = $tax_regime_data['code'];
$tax_regime->description = $tax_regime_data['name'];
$tax_regime->save();
}
$taxpayer->taxRegimes()->attach($tax_regime, [
'started_at' => $tax_regime_data['startDate']
]);
$taxpayer->save();
}
$taxpayer->total_employees = $taxpayer_data['totalEmployees'];
$taxpayer->last_year_net_income = $taxpayer_data['lastYearNetIncome'];
$taxpayer->last_year_total_income = $taxpayer_data['lastYearTotalIncome'];
$taxpayer->total_revenue_last_tax_return = $taxpayer_data['totalRevenueLastTaxReturn'];
$taxpayer->total_net_profit_last_tax_return = $taxpayer_data['totalNetProfitLastTaxReturn'];
$taxpayer->last_tax_return_year = $taxpayer_data['lastTaxReturnYear'];
$taxpayer->total_sales_revenue_current_year = $taxpayer_data['totalSalesRevenueCurrentYear'];
$taxpayer->registration_date = Carbon::parse(substr($taxpayer_data['registrationDate'], 0, 21));
$taxpayer->save();
$time = microtime(true) - $start;
return response()->json(Taxpayer::where('rfc_id', $rfc->id)->get());
} 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);
}
} else if (in_array($rfc->id, $user->rfcs->pluck('id')->toArray())) {
return response()->json(Taxpayer::where('rfc_id', $rfc->id)->get());
}
}
public function generarCSD(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())) {
$facturama = new Facturama\Client('pruebas', 'pruebas2011');
$params = [
'Rfc' => $rfc->rfc,
'Certificate' => $request->certificate,
'PrivateKey' => $request->privateKey,
'PrivateKeyPassword' => $request->privateKeyPassword
];
$result = $facturama->post('api-lite/csds', $params );
}
}
//Obtener SalesRevenues/Ingresos y copiarlos a la base de datos
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 utilidadBrutaVsIndustria(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.'/invoices?itemsPerPage=20');
// 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);
}
return $request;
}
/**
* 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\Taxpayer $taxpayer
* @return \Illuminate\Http\Response
*/
public function show(Taxpayer $taxpayer)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Taxpayer $taxpayer
* @return \Illuminate\Http\Response
*/
public function edit(Taxpayer $taxpayer)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Taxpayer $taxpayer
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Taxpayer $taxpayer)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Taxpayer $taxpayer
* @return \Illuminate\Http\Response
*/
public function destroy(Taxpayer $taxpayer)
{
//
}
}

View File

@@ -0,0 +1,117 @@
<?php
namespace App\Http\Controllers;
use App\Models\UnitCode;
use App\Imports\UnitCodesImport;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Http\Request;
class UnitCodeController extends Controller
{
/**
* 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 importarCodigosUnidad(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
]);
set_time_limit(1000);
//ini_set('memory_limit', '-1');
try {
// Procesar el archivo usando la clase de importación
Excel::import(new UnitCodesImport(), $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);
}
}
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\UnitCode $unitCode
* @return \Illuminate\Http\Response
*/
public function get(UnitCode $unitCode)
{
//
$unitcodes = UnitCode::all();
return($unitcodes);
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\UnitCode $unitCode
* @return \Illuminate\Http\Response
*/
public function edit(UnitCode $unitCode)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\UnitCode $unitCode
* @return \Illuminate\Http\Response
*/
public function update(Request $request, UnitCode $unitCode)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\UnitCode $unitCode
* @return \Illuminate\Http\Response
*/
public function destroy(UnitCode $unitCode)
{
//
}
}

View File

@@ -0,0 +1,88 @@
<?php
namespace App\Http\Controllers;
use App\Models\Usage;
use Illuminate\Http\Request;
class UsageController extends Controller
{
/**
* 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\Usage $usage
* @return \Illuminate\Http\Response
*/
public function get(Usage $usage)
{
//
$usages = Usage::all();
return($usages);
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Usage $usage
* @return \Illuminate\Http\Response
*/
public function edit(Usage $usage)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Usage $usage
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Usage $usage)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Usage $usage
* @return \Illuminate\Http\Response
*/
public function destroy(Usage $usage)
{
//
}
}

69
app/Http/Kernel.php Normal file
View File

@@ -0,0 +1,69 @@
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array<int, class-string|string>
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Illuminate\Http\Middleware\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\Cors::class,
];
/**
* The application's route middleware groups.
*
* @var array<string, array<int, class-string|string>>
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array<string, class-string|string>
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \App\Http\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'throttleEndpoint' => \App\Http\Middleware\ThrottleEndpoint::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
}

View File

@@ -0,0 +1,21 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string|null
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class Cors
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, OPTIONS')
->header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With, X-XSRF-TOKEN');
}
}

View File

@@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
class EncryptCookies extends Middleware
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array<int, string>
*/
protected $except = [
//
];
}

View File

@@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance as Middleware;
class PreventRequestsDuringMaintenance extends Middleware
{
/**
* The URIs that should be reachable while maintenance mode is enabled.
*
* @var array<int, string>
*/
protected $except = [
//
];
}

View File

@@ -0,0 +1,32 @@
<?php
namespace App\Http\Middleware;
use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @param string|null ...$guards
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next, ...$guards)
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
}
return $next($request);
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;
class ThrottleEndpoint
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
// Aquí puedes poner el origen de la URL o dominio que deseas
$allowedOrigins = ['https://cx1n8n.ext.consultoria-as.com/', 'http://cx1n8n.ext.consultoria-as.com/'];
// Verificar si el origen de la solicitud es uno de los permitidos
if (in_array($request->header('Origin'), $allowedOrigins)) {
// Si la solicitud proviene de un origen permitido, deshabilitamos el throttle
$request->headers->set('X-RateLimit-Limit', PHP_INT_MAX); // Establece un límite muy alto
$request->headers->set('X-RateLimit-Remaining', 10000); // Establece un límite muy alto
}
return $next($request);
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
class TrimStrings extends Middleware
{
/**
* The names of the attributes that should not be trimmed.
*
* @var array<int, string>
*/
protected $except = [
'current_password',
'password',
'password_confirmation',
];
}

View File

@@ -0,0 +1,20 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustHosts as Middleware;
class TrustHosts extends Middleware
{
/**
* Get the host patterns that should be trusted.
*
* @return array<int, string|null>
*/
public function hosts()
{
return [
$this->allSubdomainsOfApplicationUrl(),
];
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustProxies as Middleware;
use Illuminate\Http\Request;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* @var array<int, string>|string|null
*/
protected $proxies;
/**
* The headers that should be used to detect proxies.
*
* @var int
*/
protected $headers =
Request::HEADER_X_FORWARDED_FOR |
Request::HEADER_X_FORWARDED_HOST |
Request::HEADER_X_FORWARDED_PORT |
Request::HEADER_X_FORWARDED_PROTO |
Request::HEADER_X_FORWARDED_AWS_ELB;
}

View File

@@ -0,0 +1,22 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Routing\Middleware\ValidateSignature as Middleware;
class ValidateSignature extends Middleware
{
/**
* The names of the query string parameters that should be ignored.
*
* @var array<int, string>
*/
protected $except = [
// 'fbclid',
// 'utm_campaign',
// 'utm_content',
// 'utm_medium',
// 'utm_source',
// 'utm_term',
];
}

View File

@@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array<int, string>
*/
protected $except = [
//
];
}

View File

@@ -0,0 +1,158 @@
<?php
namespace App\Imports;
use App\Models\Invoice;
use App\Models\Rfc;
use App\Models\InvoiceType;
use App\Models\PaymentType;
use App\Models\PaymentMethod;
use App\Models\Usage;
use App\Models\Currency;
use App\Models\CancellationType;
use App\Models\Taxpayer;
use App\Models\TaxRegime;
use App\Models\Status;
use Carbon\Carbon;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class InvoicesImport implements ToModel, WithChunkReading, WithHeadingRow, WithStartRow
{
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
protected $rfc;
public function __construct($rfc)
{
$this->rfc = $rfc;
}
/**
* Método para indicar desde qué fila comenzar a leer.
*/
public function startRow(): int
{
return 2; // Si tienes encabezados, comienza en la fila 2
}
public function model(array $row)
{
$rfc = Rfc::where('rfc', $this->rfc)->firstOrCreate([
'rfc' => $this->rfc
]);
$type = InvoiceType::where('id', $this->emptyToNull($row['type']))->firstOrCreate([
'id' => $row['type']
]);
if ($this->emptyToNull($row['usage'])) {
$usage = Usage::where('id', strip_tags($row['usage']))->firstOrCreate([
'id' => $row['usage']
]); }
if ($this->emptyToNull($row['paymenttype'])) {
$payment_type = PaymentType::where('id', strip_tags($row['paymenttype']))->firstOrCreate([
'id' => $row['paymenttype']
]); }
if ($this->emptyToNull($row['paymentmethod'])) {
$payment_method = PaymentMethod::where('id', strip_tags($row['paymentmethod']))->firstOrCreate([
'id' => $row['paymentmethod']
]); }
if ($this->emptyToNull($row['currency'])) {
$currency = Currency::where('id', strip_tags($row['currency']))->firstOrCreate([
'id' => $row['currency']
]); }
if ($this->emptyToNull($row['status'])) {
$status = Status::where('description', strip_tags($row['status']))->firstOrCreate([
'description' => $row['status']
]); }
if ($this->emptyToNull($row['cancellationstatus'])) {
$cancellationType = CancellationType::where('description', strip_tags($row['cancellationstatus']))->firstOrCreate([
'description' => $row['cancellationstatus']
]); }
if ($this->emptyToNull($row['cancellationprocessstatus'])) {
$cancelStatus = Status::where('description', strip_tags($row['cancellationprocessstatus']))->firstOrCreate([
'description' => $row['cancellationprocessstatus']
]); }
$issuerRfc = Rfc::where('rfc', strip_tags($row['issuerrfc']))->first();
if (!$issuerRfc) {
$issuerRfc = new Rfc();
$issuerRfc->rfc = $row['issuerrfc'];
$issuerRfc->save();
}
$receiverRfc = Rfc::where('rfc', strip_tags($row['receiverrfc']))->first();
if (!$receiverRfc) {
$receiverRfc = new Rfc();
$receiverRfc->rfc = $row['receiverrfc'];
$receiverRfc->save();
}
return Invoice::updateOrCreate(
['id' => $row['uuid']],
[
'rfc_id' => $rfc->id,
'version' => $this->emptyToNull($row['version']),
'invoice_type_id' => $this->emptyToNull($row['type']),
'usage_id' => $this->emptyToNull($row['usage']),
'payment_type_id' => $this->emptyToNull($row['paymenttype']),
'payment_method_id' => $this->emptyToNull($row['paymentmethod']),
'zip_code' => $this->emptyToNull($row['placeofissue']),
'currency_id' => $this->emptyToNull($row['currency']),
'exchange_rate' => $this->emptyToNull($row['exchangerate']),
'status_id' => $this->emptyToNull($status->id),
'pac' => $this->emptyToNull($row['pac']),
'issued_at' => Carbon::createFromFormat('Y-m-d H:i:s', $row['issuedat']),
'certified_at' => Carbon::createFromFormat('Y-m-d H:i:s', $row['certifiedat']),
'cancellation_type_id' => $cancellationType->id,
'cancellation_status_id' => $this->emptyToNull($row['cancellationprocessstatus'] ? $cancelStatus->id : null),
'cancelled_at' => $this->emptyToNull($row['canceledat'] ? Carbon::createFromFormat('Y-m-d H:i:s', $row['canceledat']) : null),
'discount' => $this->emptyToNull($row['discount']),
'tax' => $this->emptyToNull($row['tax']),
'subtotal' => $this->emptyToNull($row['subtotal']),
'total' => $this->emptyToNull($row['total']),
'paid_amount' => $this->emptyToNull($row['paidamount']),
'due_amount' => $this->emptyToNull($row['dueamount']),
'fully_paid_at' => $this->emptyToNull($row['fullypaidat'] ? Carbon::createFromFormat('Y-m-d H:i:s', $row['fullypaidat']) : null),
'last_payment_date' => $this->emptyToNull($row['lastpaymentdate'] ? Carbon::createFromFormat('Y-m-d H:i:s', $row['lastpaymentdate']) : null),
'issuer_rfc_id' => $this->emptyToNull($issuerRfc->id),
'issuer_name' => $this->emptyToNull($row['issuername']),
'receiver_rfc_id' => $receiverRfc->id,
'receiver_name' => $this->emptyToNull($row['receivername']),
'is_issuer' => $this->emptyToNull($row['isissuer']),
'is_receiver' => $this->emptyToNull($row['isreceiver']),
'internal_id' => $this->emptyToNull($row['internalidentifier']),
'reference' => $this->emptyToNull($row['reference']),
'credited_amount' => $this->emptyToNull($row['creditedamount'] ? $row['creditedamount'] : null),
'subtotal_credited_amount' => $this->emptyToNull($row['subtotalcreditedamount'] ? $row['subtotalcreditedamount'] : null),
'applied_taxes' => $this->emptyToNull($row['appliedtaxes']),
'total_transferred_taxes' => $this->emptyToNull($row['totaltransferredtaxes']),
'transferred_local_taxes' => $this->emptyToNull($row['transferredlocaltaxes']),
'transferred_vat' => $this->emptyToNull($row['transferredvalueaddedtax']),
'transferred_sin_tax' => $this->emptyToNull($row['transferredsintax']),
'total_retained_taxes' => $this->emptyToNull($row['totalretainedtaxes']),
'retained_local_taxes' => $this->emptyToNull($row['retainedlocaltaxes']),
'retained_vat' => $this->emptyToNull($row['retainedvalueaddedtax']),
'retained_income_tax' => $this->emptyToNull($row['retainedincometax']),
'retained_sin_tax' => $this->emptyToNull($row['retainedsintax'])
]
);
}
private function emptyToNull($value)
{
return $value === '' ? null : $value;
}
/**
* Devuelve el tamaño del chunk (en filas) a leer.
*/
public function chunkSize(): int
{
return 5000; // Ajusta el tamaño según tus necesidades
}
}

View File

@@ -0,0 +1,124 @@
<?php
namespace App\Imports;
use App\Models\InvoiceLine;
use App\Models\Invoice;
use App\Models\Rfc;
use App\Models\InvoiceType;
use App\Models\PaymentType;
use App\Models\PaymentMethod;
use App\Models\Usage;
use App\Models\Currency;
use App\Models\CancellationType;
use App\Models\Taxpayer;
use App\Models\TaxRegime;
use App\Models\Status;
use Carbon\Carbon;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class LineItemsImport implements ToModel, WithChunkReading, WithHeadingRow, WithStartRow
{
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
protected $rfc;
public function __construct($rfc)
{
$this->rfc = $rfc;
}
/**
* Método para indicar desde qué fila comenzar a leer.
*/
public function startRow(): int
{
return 2; // Si tienes encabezados, comienza en la fila 2
}
public function model(array $row)
{
$rfc = Rfc::where('rfc', $this->rfc)->firstOrCreate([
'rfc' => $this->rfc
]);
$invoice = Invoice::where('id', strip_tags($row['invoice_uuid']))->firstOrCreate([
'id' => $row['invoice_uuid']
]);
$type = InvoiceType::where('id', strip_tags($row['invoice_type']))->firstOrCreate([
'id' => $row['invoice_type']
]);
if ($this->emptyToNull($row['paymentType'])) {
$paymentType = PaymentType::where('id', strip_tags($row['paymentType']))->firstOrCreate([
'id' => $row['paymentType']
]);
}
if ($this->emptyToNull($row['invoice_status'])) {
$status = Status::where('description', strip_tags($row['status']))->firstOrCreatet([
'description' => $row['status']
]);
}
$issuerRfc = Rfc::where('rfc', strip_tags($row['issuer_rfc']))->firstOrCreate([
'rfc' => $row['issuer_rfc']
]);
$receiverRfc = Rfc::where('rfc', strip_tags($row['receiver_rfc']))->firstOrCreate([
'rfc' => $row['receiver_rfc']
]);
return InvoiceLine::updateOrCreate(
['id' => $invoiceLine_data['id']],
[
'rfc_id' => $rfc->id,
'invoice_id' => $invoice->id,
'invoice_type_id' => $type->id,
'payment_type_id' => $paymentType->id,
'status_id' => $status->id,
'issuer_rfc_id' => $issuerRfc->id,
'issuer_name' => $this->emptyToNull($row['issuername']),
'receiver_rfc_id' => $receiverRfc->id,
'receiver_name' => $this->emptyToNull($row['receivername']),
'issued_at' => Carbon::createFromFormat('Y-m-d H:i:s', $row['issuedAt']);
'identification_number' => $row['identificationNumber'];
'product_identification' => $row['productIdentification'];
'description' => $row['description'];
'unit_amount' => $row['unitAmount'];
'unit_code' => $row['unitCode'];
'quantity' => $row['quantity'];
'discount_amount' => $row['discountAmount'];
'total_amount' => $row['totalAmount'];
'retained_vat' => $row['rrowvalueAddedTax'];
'retained_income_tax' => $row['retainedTaxes']['incomeTax'];
'retained_sin_tax' => $row['retainedTaxes']['sinTax'];
'transferred_vat' => $row['transferredTaxes']['valueAddedTax'];
'transferred_sin_tax' => $row['transferredTaxes']['sinTax'];
]
);
}
private function emptyToNull($value)
{
return $value === '' ? null : $value;
}
/**
* Devuelve el tamaño del chunk (en filas) a leer.
*/
public function chunkSize(): int
{
return 5000; // Ajusta el tamaño según tus necesidades
}
}

View File

@@ -0,0 +1,44 @@
<?php
namespace App\Imports;
use App\Models\ProdServCode;
use Carbon\Carbon;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class ProdServCodesImport implements ToModel, WithChunkReading, WithHeadingRow, WithStartRow
{
/**
* Método para indicar desde qué fila comenzar a leer.
*/
public function startRow(): int
{
return 2; // Si tienes encabezados, comienza en la fila 2
}
public function model(array $row)
{
return ProdServCode::updateOrCreate(
['id' => $row['id']],
['description' => $this->emptyToNull($row['description'])]
);
}
private function emptyToNull($value)
{
return $value === '' ? null : $value;
}
/**
* Devuelve el tamaño del chunk (en filas) a leer.
*/
public function chunkSize(): int
{
return 5000; // Ajusta el tamaño según tus necesidades
}
}

View File

@@ -0,0 +1,44 @@
<?php
namespace App\Imports;
use App\Models\UnitCode;
use Carbon\Carbon;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class UnitCodesImport implements ToModel, WithChunkReading, WithHeadingRow, WithStartRow
{
/**
* Método para indicar desde qué fila comenzar a leer.
*/
public function startRow(): int
{
return 2; // Si tienes encabezados, comienza en la fila 2
}
public function model(array $row)
{
return UnitCode::updateOrCreate(
['id' => $row['id']],
['description' => $this->emptyToNull($row['description'])]
);
}
private function emptyToNull($value)
{
return $value === '' ? null : $value;
}
/**
* Devuelve el tamaño del chunk (en filas) a leer.
*/
public function chunkSize(): int
{
return 5000; // Ajusta el tamaño según tus necesidades
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Model;
class CancellationType extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'description',
];
public function invoices(): HasMany
{
return $this->hasMany(Invoice::class);
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Conciliation extends Model
{
use HasFactory;
protected $fillable = [
'invoice_id',
'rfc_id',
'payment_description',
'payment_at',
'is_conciliated',
'conciliated_at'
];
public function invoice(): BelongsTo
{
return $this->belongsTo(Invoice::class);
}
public function rfc(): BelongsTo
{
return $this->belongsTo(Rfc::class);
}
}

35
app/Models/Currency.php Normal file
View File

@@ -0,0 +1,35 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Currency extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'id',
'description'
];
public $incrementing = false;
protected $keyType = 'string';
public function invoices(): HasMany
{
return $this->hasMany(Invoice::class);
}
public function invoicePayments(): HasMany
{
return $this->hasMany(InvoicePayment::class);
}
}

22
app/Models/Dimension.php Normal file
View File

@@ -0,0 +1,22 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Model;
class Dimension extends Model
{
use HasFactory;
public function salesRevenues(): HasMany
{
return $this->hasMany(SalesRevenue::class);
}
public function expenditures(): HasMany
{
return $this->hasMany(Expenditure::class);
}
}

View File

@@ -0,0 +1,17 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Model;
class EconomicActivity extends Model
{
use HasFactory;
public function taxPayers(): BelongsToMany
{
return $this->belongsToMany(TaxPayers::class);
}
}

View File

@@ -0,0 +1,22 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Model;
class Expenditure extends Model
{
use HasFactory;
public function taxpayer(): BelongsTo
{
return $this->belongsTo(Taxpayer::class);
}
public function dimension(): BelongsTo
{
return $this->belongsTo(Dimension::class);
}
}

11
app/Models/Industry.php Normal file
View File

@@ -0,0 +1,11 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Industry extends Model
{
use HasFactory;
}

230
app/Models/Invoice.php Normal file
View File

@@ -0,0 +1,230 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Model;
class Invoice extends Model
{
use HasFactory;
protected $fillable = [
'id',
'api_id',
'rfc_id',
'version',
'invoice_type_id',
'usage_id',
'payment_type_id',
'payment_method_id',
'zip_code',
'currency_id',
'exchange_rate',
'status_id',
'pac',
'issued_at',
'certified_at',
'cancellation_status_id',
'cancellation_type_id',
'cancelled_at',
'discount',
'tax',
'subtotal',
'total',
'paid_amount',
'due_amount',
'fully_paid_at',
'last_payment_date',
'issuer_rfc_id',
'issuer_name',
'receiver_rfc_id',
'receiver_name',
'is_issuer',
'is_receiver',
'internal_id',
'reference',
'credited_amount',
'subtotal_credited_amount',
'applied_taxes',
'total_transferred_taxes',
'transferred_local_taxes',
'transferred_vat',
'transferred_sin_tax',
'total_retained_taxes',
'retained_local_taxes',
'retained_vat',
'retained_income_tax',
'retained_sin_tax',
'is_conciliated',
];
public function invoiceType(): BelongsTo
{
return $this->belongsTo(InvoiceType::class);
}
public function rfc(): BelongsTo
{
return $this->belongsTo(Rfc::class);
}
public function usage(): BelongsTo
{
return $this->belongsTo(Usage::class);
}
public function paymentType(): BelongsTo
{
return $this->belongsTo(PaymentType::class);
}
public function paymentMethod(): BelongsTo
{
return $this->belongsTo(PaymentMethod::class);
}
public function currency(): BelongsTo
{
return $this->belongsTo(Currency::class);
}
public function status(): BelongsTo
{
return $this->belongsTo(Status::class);
}
public function cancellationType(): BelongsTo
{
return $this->belongsTo(CancellationType::class);
}
public function cancellationStatus(): BelongsTo
{
return $this->belongsTo(Status::class);
}
public function issuerRfc(): BelongsTo
{
return $this->belongsTo(Rfc::class);
}
public function receiverRfc(): BelongsTo
{
return $this->belongsTo(Rfc::class);
}
public function invoiceLines(): HasMany
{
return $this->hasMany(InvoiceLine::class);
}
public function conciliations(): HasMany
{
return $this->hasMany(Conciliation::class);
}
public function invoicePayments(): HasMany
{
return $this->hasMany(InvoicePayment::class);
}
public function getRfcAttribute()
{
return $this->rfc()->first()->rfc;
}
public function getStatusAttribute()
{
return $this->status()->first()->description;
}
public function getCancellationTypeAttribute()
{
return $this->cancellationType()->first()->description;
}
public function getCancellationStatusAttribute()
{
return $this->cancellationStatus()->first()->description;
}
public function getIssuerRfcAttribute()
{
return $this->issuerRfc()->first()->rfc;
}
public function getReceiverRfcAttribute()
{
return $this->receiverRfc()->first()->rfc;
}
public function getTotalInMxnAttribute()
{
if ($this->exchange_rate) {
$totalMXN = $this->total * $this->exchange_rate;
} else {
$totalMXN = $this->total;
}
return $totalMXN;
}
public function getTaxInMxnAttribute()
{
if ($this->exchange_rate) {
$taxMXN = $this->tax * $this->exchange_rate;
} else {
$taxMXN = $this->tax;
}
return $taxMXN;
}
public function getTransferredVatInMxnAttribute()
{
if ($this->exchange_rate) {
$transferredVatMXN = $this->transferred_vat * $this->exchange_rate;
} else {
$transferredVatMXN = $this->transferred_vat;
}
return $transferredVatMXN;
}
public function getTransferredSinTaxInMxnAttribute()
{
if ($this->exchange_rate) {
$transferredSinMXN = $this->transferred_sin_tax * $this->exchange_rate;
} else {
$transferredSinMXN = $this->transferred_sin_tax;
}
return $transferredSinMXN;
}
public function getRetainedVatInMxnAttribute()
{
if ($this->exchange_rate) {
$retainedVatMXN = $this->retained_vat * $this->exchange_rate;
} else {
$retainedVatMXN = $this->retained_vat;
}
return $retainedVatMXN;
}
public function getRetainedIncomeTaxInMxnAttribute()
{
if ($this->exchange_rate) {
$retainedIncomeTaxMXN = $this->retained_income_tax * $this->exchange_rate;
} else {
$retainedIncomeTaxMXN = $this->retained_income_tax;
}
return $retainedIncomeTaxMXN;
}
protected $keyType = 'string';
protected $hidden = ['rfc_id', 'status_id', 'cancellation_type_id', 'cancellation_status_id', 'issuer_rfc_id', 'receiver_rfc_id'];
protected $appends = ['rfc', 'status', 'cancellation_type', 'cancellation_status', 'issuer_rfc', 'receiver_rfc', 'total_in_mxn',
'tax_in_mxn', 'transferred_vat_in_mxn', 'transferred_sin_tax_in_mxn', 'retained_vat_in_mxn', 'retained_income_tax_in_mxn'];
}

View File

@@ -0,0 +1,62 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Model;
class InvoiceLine extends Model
{
use HasFactory;
protected $fillable = [
'id'
];
public function invoice(): BelongsTo
{
return $this->belongsTo(Invoice::class);
}
public function rfc(): BelongsTo
{
return $this->belongsTo(Rfc::class);
}
public function invoiceType(): BelongsTo
{
return $this->belongsTo(InvoiceType::class);
}
public function paymentType(): BelongsTo
{
return $this->belongsTo(PaymentType::class);
}
public function issuerRfc(): BelongsTo
{
return $this->belongsTo(Rfc::class);
}
public function receiverRfc(): BelongsTo
{
return $this->belongsTo(Rfc::class);
}
public function getIssuerRfcAttribute()
{
return $this->issuerRfc()->first()->rfc;
}
public function getReceiverRfcAttribute()
{
return $this->receiverRfc()->first()->rfc;
}
protected $keyType = 'string';
protected $hidden = ['issuer_rfc_id', 'receiver_rfc_id'];
protected $appends = ['issuer_rfc', 'receiver_rfc'];
}

View File

@@ -0,0 +1,162 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Model;
class InvoicePayment extends Model
{
use HasFactory;
protected $fillable = [
'id',
'cancelled_at'
];
public function invoice(): BelongsTo
{
return $this->belongsTo(Invoice::class);
}
public function rfc(): BelongsTo
{
return $this->belongsTo(Rfc::class);
}
public function paymentMethod(): BelongsTo
{
return $this->belongsTo(PaymentMethod::class);
}
public function currency(): BelongsTo
{
return $this->belongsTo(Currency::class);
}
public function getIssuerRfcAttribute()
{
return $this->invoice()->first()->issuer_rfc;
}
public function getReceiverRfcAttribute()
{
return $this->invoice()->first()->receiver_rfc;
}
public function getTotalInMxnAttribute()
{
if ($this->invoice()->first()->exchange_rate) {
$totalMXN = $this->invoice()->first()->total * $this->invoice()->first()->exchange_rate;
} else {
$totalMXN = $this->invoice()->first()->total;
}
return $totalMXN;
}
public function getAmountInMxnAttribute()
{
if ($this->exchange_rate) {
$amountMXN = abs($this->amount * $this->exchange_rate);
} else {
$amountMXN = abs($this->amount);
}
return $amountMXN;
}
public function getTransferredVatInMxnAttribute()
{
if ($this->invoice()->first()->exchange_rate) {
$transferredVatMXN = $this->invoice()->first()->transferred_vat * $this->invoice()->first()->exchange_rate;
} else {
$transferredVatMXN = $this->invoice()->first()->transferred_vat;
}
return $transferredVatMXN;
}
public function getRetainedVatInMxnAttribute()
{
if ($this->invoice()->first()->exchange_rate) {
$retainedVatMXN = $this->invoice()->first()->retained_vat * $this->invoice()->first()->exchange_rate;
} else {
$retainedVatMXN = $this->invoice()->first()->retained_vat;
}
return $retainedVatMXN;
}
public function getRetainedIncomeTaxInMxnAttribute()
{
if ($this->invoice()->first()->exchange_rate) {
$retainedIncomeTaxMXN = $this->invoice()->first()->retained_income_tax * $this->invoice()->first()->exchange_rate;
} else {
$retainedIncomeTaxMXN = $this->invoice()->first()->retained_income_tax;
}
return $retainedIncomeTaxMXN;
}
public function getTransferredVatPercentageAttribute()
{
$totalMXN = $this->getTotalInMxnAttribute();
$transferredVatMXN = $this->getTransferredVatInMxnAttribute();
$retainedVatMXN = $this->getRetainedVatInMxnAttribute();
$transferredVatPercentage = round(100*(($transferredVatMXN)/($totalMXN - $transferredVatMXN)));
return $transferredVatPercentage;
}
public function getTransferredVatPpdAttribute()
{
$transferredVatPercentage = $this->getTransferredVatPercentageAttribute();
if ($this->exchange_rate) {
$transferredVatPPD = round((abs($this->amount*$this->exchange_rate)/(1+($transferredVatPercentage*0.01)))*($transferredVatPercentage*0.01), 2);
} else {
$transferredVatPPD = round((abs($this->amount)/(1+($transferredVatPercentage*0.01)))*($transferredVatPercentage*0.01), 2);
}
return $transferredVatPPD;
}
public function getRetainedVatPercentageAttribute()
{
$totalMXN = $this->getTotalInMxnAttribute();
$transferredVatMXN = $this->getTransferredVatInMxnAttribute();
$retainedVatMXN = $this->getRetainedVatInMxnAttribute();
$retainedVatPercentage = round(100*(($retainedVatMXN)/($totalMXN - $transferredVatMXN)));
return $retainedVatPercentage;
}
public function getRetainedVatPpdAttribute()
{
$retainedVatPercentage = $this->getRetainedVatPercentageAttribute();
$transferredVatPercentage = $this->getTransferredVatPercentageAttribute();
if ($this->exchange_rate) {
$retainedVatPPD = round((abs($this->amount*$this->exchange_rate)/(1+($transferredVatPercentage*0.01)))*($retainedVatPercentage*0.01), 2);
} else {
$retainedVatPPD = round((abs($this->amount)/(1+($transferredVatPercentage*0.01)))*($retainedVatPercentage*0.01), 2);
}
return $retainedVatPPD;
}
public function getAbsAmountAttribute()
{
$absAmount = abs($this->amount);
return $absAmount;
}
protected $appends = [
'issuer_rfc', 'receiver_rfc', 'total_in_mxn',
'transferred_vat_in_mxn', 'retained_vat_in_mxn',
'retained_income_tax_in_mxn',
'transferred_vat_percentage', 'transferred_vat_ppd',
'retained_vat_percentage', 'retained_vat_ppd',
'abs_amount', 'amount_in_mxn'
];
}

View File

@@ -0,0 +1,17 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Model;
class InvoiceRequest extends Model
{
use HasFactory;
public function rfcs(): BelongsTo
{
return $this->belongsTo(Rfc::class);
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Model;
class InvoiceType extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'id',
'description'
];
protected $keyType = 'string';
public function invoices(): HasMany
{
return $this->hasMany(Invoice::class);
}
public function invoiceLines(): HasMany
{
return $this->hasMany(InvoiceLine::class);
}
}

View File

@@ -0,0 +1,21 @@
<?php
namespace App\Models;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class LinkedSocialAccount extends Model
{
use HasFactory;
protected $fillable = [
'provider_name',
'provider_id',
];
public function user()
{
return $this->belongsTo(User::class);
}
}

22
app/Models/ManagerOTP.php Normal file
View File

@@ -0,0 +1,22 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Model;
class ManagerOTP extends Model
{
use HasFactory;
public function users(): HasMany
{
return $this->belongsTo(User::class);
}
public function rfcs(): BelongsTo
{
return $this->belongsTo(Rfc::class);
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Model;
class PaymentMethod extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'id',
'description'
];
protected $keyType = 'string';
public function invoices(): HasMany
{
return $this->hasMany(Invoice::class);
}
public function invoicePayments(): HasMany
{
return $this->hasMany(InvoicePayment::class);
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Model;
class PaymentType extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'id',
'description'
];
protected $keyType = 'string';
public function invoices(): HasMany
{
return $this->hasMany(Invoice::class);
}
public function invoiceLines(): HasMany
{
return $this->hasMany(InvoiceLine::class);
}
}

22
app/Models/PostalCode.php Normal file
View File

@@ -0,0 +1,22 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class PostalCode extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'id',
'description'
];
}

View File

@@ -0,0 +1,22 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class ProdServCode extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'id',
'description'
];
}

62
app/Models/Rfc.php Normal file
View File

@@ -0,0 +1,62 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Model;
class Rfc extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'rfc',
];
public function users(): BelongsToMany
{
return $this->belongsToMany(User::class);
}
public function managerOTP(): HasMany
{
return $this->hasMany(ManagerOTP::class);
}
public function invoices(): HasMany
{
return $this->hasMany(Invoice::class);
}
public function invoiceLines(): HasMany
{
return $this->hasMany(InvoiceLine::class);
}
public function invoicePayments(): HasMany
{
return $this->hasMany(InvoiceLine::class);
}
public function invoiceRequest(): HasMany
{
return $this->hasMany(InvoiceRequest::class);
}
public function taxpayers(): HasMany
{
return $this->hasMany(Taxpayer::class);
}
public function conciliations(): HasMany
{
return $this->hasMany(Conciliation::class);
}
}

17
app/Models/Risk.php Normal file
View File

@@ -0,0 +1,17 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Model;
class Risk extends Model
{
use HasFactory;
public function taxPayers(): BelongsToMany
{
return $this->belongsToMany(TaxPayers::class);
}
}

27
app/Models/Role.php Normal file
View File

@@ -0,0 +1,27 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Role extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'description',
];
public function users(): HasMany
{
return $this->hasMany(User::class);
}
}

View File

@@ -0,0 +1,22 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Model;
class SalesRevenue extends Model
{
use HasFactory;
public function taxpayer(): BelongsTo
{
return $this->belongsTo(Taxpayer::class);
}
public function dimension(): BelongsTo
{
return $this->belongsTo(Dimension::class);
}
}

33
app/Models/Status.php Normal file
View File

@@ -0,0 +1,33 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Model;
class Status extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'id',
'description'
];
public function invoices(): HasMany
{
return $this->hasMany(Invoice::class);
}
public function invoiceLines(): HasMany
{
return $this->hasMany(InvoiceLine::class);
}
}

23
app/Models/Tax.php Normal file
View File

@@ -0,0 +1,23 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Tax extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'id',
'description'
];
protected $keyType = 'string';
}

23
app/Models/TaxRate.php Normal file
View File

@@ -0,0 +1,23 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class TaxRate extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'id',
'tax_id',
'description'
];
}

17
app/Models/TaxRegime.php Normal file
View File

@@ -0,0 +1,17 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Model;
class TaxRegime extends Model
{
use HasFactory;
public function taxPayers(): BelongsToMany
{
return $this->belongsToMany(TaxPayers::class);
}
}

48
app/Models/Taxpayer.php Normal file
View File

@@ -0,0 +1,48 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Model;
class Taxpayer extends Model
{
use HasFactory;
protected $fillable = [
'rfc_id'
];
public function rfc(): BelongsTo
{
return $this->belongsTo(Rfc::class);
}
public function economicActivities(): BelongsToMany
{
return $this->belongsToMany(EconomicActivity::class);
}
public function taxRegimes(): BelongsToMany
{
return $this->belongsToMany(TaxRegime::class);
}
public function risks(): BelongsToMany
{
return $this->belongsToMany(Risks::class);
}
public function salesRevenues(): HasMany
{
return $this->hasMany(SalesRevenue::class);
}
public function expenditures(): HasMany
{
return $this->hasMany(Expenditure::class);
}
}

23
app/Models/UnitCode.php Normal file
View File

@@ -0,0 +1,23 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class UnitCode extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'id',
'description'
];
protected $keyType = 'string';
}

23
app/Models/Usage.php Normal file
View File

@@ -0,0 +1,23 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Usage extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'id',
'description'
];
protected $keyType = 'string';
}

70
app/Models/User.php Normal file
View File

@@ -0,0 +1,70 @@
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use App\Models\LinkedSocialAccount;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable, HasApiTokens;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
'role_id'
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function linkedSocialAccounts()
{
return $this->hasMany(LinkedSocialAccount::class);
}
public function role(): BelongsTo
{
return $this->belongsTo(Role::class);
}
public function rfcs(): BelongsToMany
{
return $this->belongsToMany(Rfc::class);
}
public function managerOTPs(): HasMany
{
return $this->hasMany(ManagerOTP::class);
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Event;
use App\Services\SocialUserResolver;
use Coderello\SocialGrant\Resolvers\SocialUserResolverInterface;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
Event::listen(function (\SocialiteProviders\Manager\SocialiteWasCalled $event) {
$event->extendSocialite('clerk', \SocialiteProviders\Clerk\Provider::class);
});
}
/**
* All of the container bindings that should be registered.
*
* @var array
*/
public $bindings = [
SocialUserResolverInterface::class => SocialUserResolver::class,
];
}

View File

@@ -0,0 +1,30 @@
<?php
namespace App\Providers;
// use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The model to policy mappings for the application.
*
* @var array<class-string, class-string>
*/
protected $policies = [
// 'App\Models\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
//
}
}

View File

@@ -0,0 +1,21 @@
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Broadcast::routes();
require base_path('routes/channels.php');
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace App\Providers;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
class EventServiceProvider extends ServiceProvider
{
/**
* The event to listener mappings for the application.
*
* @var array<class-string, array<int, class-string>>
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
//
}
/**
* Determine if events and listeners should be automatically discovered.
*
* @return bool
*/
public function shouldDiscoverEvents()
{
return false;
}
}

View File

@@ -0,0 +1,65 @@
<?php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* The path to the "home" route for your application.
*
* Typically, users are redirected here after authentication.
*
* @var string
*/
public const HOME = '/home';
/**
* Define your route model bindings, pattern filters, and other route configuration.
*
* @return void
*/
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
Route::middleware('api')
->prefix('api')
->group(base_path('routes/api.php'));
Route::middleware('web')
->group(base_path('routes/web.php'));
});
}
/**
* Configure the rate limiters for the application.
*
* @return void
*/
protected function configureRateLimiting()
{
RateLimiter::for('custom-origin', function ($request) {
// Aquí decides qué origen permitir sin límite
$allowedOrigins = ['https://cx1n8n.ext.consultoria-as.com/', 'http://cx1n8n.ext.consultoria-as.com/'];
$origin = $request->header('origin') ?? $request->header('referer');
if (in_array($origin, $allowedOrigins)) {
// No limitar
return Limit::none();
}
return Limit::perMinute(200)->by($request->ip());
});
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace App\Services;
use App\Models\User;
use App\Models\LinkedSocialAccount;
use Laravel\Socialite\Two\User as ProviderUser;
use Illuminate\Support\Facades\File;
class SocialAccountsService
{
/**
* Find or create user instance by provider user instance and provider name.
*
* @param ProviderUser $providerUser
* @param string $provider
*
* @return User
*/
public function findOrCreate(ProviderUser $providerUser, string $provider): User
{
$linkedSocialAccount = LinkedSocialAccount::where('provider_name', $provider)
->where('provider_id', $providerUser->getId())
->first();
if ($linkedSocialAccount) {
return $linkedSocialAccount->user;
} else {
$user = null;
if ($email = $providerUser->getEmail()) {
$user = User::where('email', $email)->first();
}
if (! $user) {
$user = User::create([
'name' => $providerUser->getName(),
'email' => $providerUser->getEmail(),
//'rfc' = $providerUser->public_metadata->rfc,
'social_id' => $providerUser->getId() . '_' . $provider
]);
$user->save();
}
$user->linkedSocialAccounts()->create([
'provider_id' => $providerUser->getId(),
'provider_name' => $provider
]);
return $user;
}
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace App\Services;
use Exception;
use Coderello\SocialGrant\Resolvers\SocialUserResolverInterface;
use Illuminate\Contracts\Auth\Authenticatable;
use Laravel\Socialite\Facades\Socialite;
use Laravel\Socialite\Two\User as ProviderUser;
class SocialUserResolver implements SocialUserResolverInterface
{
/**
* Resolve user by provider credentials.
*
* @param string $provider
* @param string $accessToken
*
* @return Authenticatable|null
*/
public function resolveUserByProviderCredentials(string $provider, string $accessToken): ?Authenticatable
{
$providerUser = null;
try {
$providerUser = Socialite::driver($provider)->scopes(['profile email public_metadata'])->userFromToken($accessToken);
} catch (Exception $exception) {}
if ($providerUser) {
return (new SocialAccountsService())->findOrCreate($providerUser, $provider);
}
return null;
}
}

53
artisan Normal file
View File

@@ -0,0 +1,53 @@
#!/usr/bin/env php
<?php
define('LARAVEL_START', microtime(true));
/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any of our classes manually. It's great to relax.
|
*/
require __DIR__.'/vendor/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';
/*
|--------------------------------------------------------------------------
| Run The Artisan Application
|--------------------------------------------------------------------------
|
| When we run the console application, the current CLI command will be
| executed in this console and the response sent back to a terminal
| or another output device for the developers. Here goes nothing!
|
*/
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$status = $kernel->handle(
$input = new Symfony\Component\Console\Input\ArgvInput,
new Symfony\Component\Console\Output\ConsoleOutput
);
/*
|--------------------------------------------------------------------------
| Shutdown The Application
|--------------------------------------------------------------------------
|
| Once Artisan has finished running, we will fire off the shutdown events
| so that any final work may be done by the application before we shut
| down the process. This is the last thing to happen to the request.
|
*/
$kernel->terminate($input, $status);
exit($status);

55
bootstrap/app.php Normal file
View File

@@ -0,0 +1,55 @@
<?php
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| The first thing we will do is create a new Laravel application instance
| which serves as the "glue" for all the components of Laravel, and is
| the IoC container for the system binding all of the various parts.
|
*/
$app = new Illuminate\Foundation\Application(
$_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);
/*
|--------------------------------------------------------------------------
| Bind Important Interfaces
|--------------------------------------------------------------------------
|
| Next, we need to bind some important interfaces into the container so
| we will be able to resolve them when needed. The kernels serve the
| incoming requests to this application from both the web and CLI.
|
*/
$app->singleton(
Illuminate\Contracts\Http\Kernel::class,
App\Http\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
App\Console\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
/*
|--------------------------------------------------------------------------
| Return The Application
|--------------------------------------------------------------------------
|
| This script returns the application instance. The instance is given to
| the calling script so we can separate the building of the instances
| from the actual running of the application and sending responses.
|
*/
return $app;

2
bootstrap/cache/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
*
!.gitignore

68
composer.json Normal file
View File

@@ -0,0 +1,68 @@
{
"name": "laravel/laravel",
"type": "project",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"require": {
"php": "^8.0.2",
"facturama/facturama-php-sdk": "^2.0",
"guzzlehttp/guzzle": "^7.2",
"laravel/framework": "^9.19",
"laravel/socialite": "^5.15",
"laravel/tinker": "^2.7",
"maatwebsite/excel": "^3.1",
"socialiteproviders/clerk": "^5.0"
},
"require-dev": {
"fakerphp/faker": "^1.9.1",
"laravel/pint": "^1.0",
"laravel/sail": "^1.0.1",
"mockery/mockery": "^1.4.4",
"nunomaduro/collision": "^6.1",
"phpunit/phpunit": "^9.5.10",
"spatie/laravel-ignition": "^1.0"
},
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"scripts": {
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"@php artisan package:discover --ansi"
],
"post-update-cmd": [
"@php artisan vendor:publish --tag=laravel-assets --ansi --force"
],
"post-root-package-install": [
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"@php artisan key:generate --ansi"
]
},
"extra": {
"laravel": {
"dont-discover": []
}
},
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true,
"allow-plugins": {
"pestphp/pest-plugin": true
}
},
"minimum-stability": "stable",
"prefer-stable": true
}

9236
composer.lock generated Normal file

File diff suppressed because it is too large Load Diff

221
config/app.php Normal file
View File

@@ -0,0 +1,221 @@
<?php
use Illuminate\Support\Facades\Facade;
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application. This value is used when the
| framework needs to place the application's name in a notification or
| any other location as required by the application or its packages.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => (bool) env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/
'url' => env('APP_URL', 'http://localhost'),
'asset_url' => env('ASSET_URL'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => 'en',
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => 'en',
/*
|--------------------------------------------------------------------------
| Faker Locale
|--------------------------------------------------------------------------
|
| This locale will be used by the Faker PHP library when generating fake
| data for your database seeds. For example, this will be used to get
| localized telephone numbers, street address information and more.
|
*/
'faker_locale' => 'en_US',
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/
'key' => env('APP_KEY'),
'cipher' => 'AES-256-CBC',
'client_id' => env('CLIENT_ID'),
'client_secret' => env('CLIENT_SECRET'),
/*
|--------------------------------------------------------------------------
| Maintenance Mode Driver
|--------------------------------------------------------------------------
|
| These configuration options determine the driver used to determine and
| manage Laravel's "maintenance mode" status. The "cache" driver will
| allow maintenance mode to be controlled across multiple machines.
|
| Supported drivers: "file", "cache"
|
*/
'maintenance' => [
'driver' => 'file',
// 'store' => 'redis',
],
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/
'providers' => [
/*
* Laravel Framework Service Providers...
*/
Illuminate\Auth\AuthServiceProvider::class,
Illuminate\Broadcasting\BroadcastServiceProvider::class,
Illuminate\Bus\BusServiceProvider::class,
Illuminate\Cache\CacheServiceProvider::class,
Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
Illuminate\Cookie\CookieServiceProvider::class,
Illuminate\Database\DatabaseServiceProvider::class,
Illuminate\Encryption\EncryptionServiceProvider::class,
Illuminate\Filesystem\FilesystemServiceProvider::class,
Illuminate\Foundation\Providers\FoundationServiceProvider::class,
Illuminate\Hashing\HashServiceProvider::class,
Illuminate\Mail\MailServiceProvider::class,
Illuminate\Notifications\NotificationServiceProvider::class,
Illuminate\Pagination\PaginationServiceProvider::class,
Illuminate\Pipeline\PipelineServiceProvider::class,
Illuminate\Queue\QueueServiceProvider::class,
Illuminate\Redis\RedisServiceProvider::class,
Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
Illuminate\Session\SessionServiceProvider::class,
Illuminate\Translation\TranslationServiceProvider::class,
Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\View\ViewServiceProvider::class,
/*
* Package Service Providers...
*/
Maatwebsite\Excel\ExcelServiceProvider::class,
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
],
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => Facade::defaultAliases()->merge([
// 'ExampleClass' => App\Example\ExampleClass::class,
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
])->toArray(),
];

115
config/auth.php Normal file
View File

@@ -0,0 +1,115 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that each reset token will be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the amount of seconds before a password confirmation
| times out and the user is prompted to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => 10800,
];

70
config/broadcasting.php Normal file
View File

@@ -0,0 +1,70 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Broadcaster
|--------------------------------------------------------------------------
|
| This option controls the default broadcaster that will be used by the
| framework when an event needs to be broadcast. You may set this to
| any of the connections defined in the "connections" array below.
|
| Supported: "pusher", "ably", "redis", "log", "null"
|
*/
'default' => env('BROADCAST_DRIVER', 'null'),
/*
|--------------------------------------------------------------------------
| Broadcast Connections
|--------------------------------------------------------------------------
|
| Here you may define all of the broadcast connections that will be used
| to broadcast events to other systems or over websockets. Samples of
| each available type of connection are provided inside this array.
|
*/
'connections' => [
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'host' => env('PUSHER_HOST') ?: 'api-'.env('PUSHER_APP_CLUSTER', 'mt1').'.pusher.com',
'port' => env('PUSHER_PORT', 443),
'scheme' => env('PUSHER_SCHEME', 'https'),
'encrypted' => true,
'useTLS' => env('PUSHER_SCHEME', 'https') === 'https',
],
'client_options' => [
// Guzzle client options: https://docs.guzzlephp.org/en/stable/request-options.html
],
],
'ably' => [
'driver' => 'ably',
'key' => env('ABLY_KEY'),
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
],
'log' => [
'driver' => 'log',
],
'null' => [
'driver' => 'null',
],
],
];

110
config/cache.php Normal file
View File

@@ -0,0 +1,110 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Cache Store
|--------------------------------------------------------------------------
|
| This option controls the default cache connection that gets used while
| using this caching library. This connection is used when another is
| not explicitly specified when executing a given caching function.
|
*/
'default' => env('CACHE_DRIVER', 'file'),
/*
|--------------------------------------------------------------------------
| Cache Stores
|--------------------------------------------------------------------------
|
| Here you may define all of the cache "stores" for your application as
| well as their drivers. You may even define multiple stores for the
| same cache driver to group types of items stored in your caches.
|
| Supported drivers: "apc", "array", "database", "file",
| "memcached", "redis", "dynamodb", "octane", "null"
|
*/
'stores' => [
'apc' => [
'driver' => 'apc',
],
'array' => [
'driver' => 'array',
'serialize' => false,
],
'database' => [
'driver' => 'database',
'table' => 'cache',
'connection' => null,
'lock_connection' => null,
],
'file' => [
'driver' => 'file',
'path' => storage_path('framework/cache/data'),
],
'memcached' => [
'driver' => 'memcached',
'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
'sasl' => [
env('MEMCACHED_USERNAME'),
env('MEMCACHED_PASSWORD'),
],
'options' => [
// Memcached::OPT_CONNECT_TIMEOUT => 2000,
],
'servers' => [
[
'host' => env('MEMCACHED_HOST', '127.0.0.1'),
'port' => env('MEMCACHED_PORT', 11211),
'weight' => 100,
],
],
],
'redis' => [
'driver' => 'redis',
'connection' => 'cache',
'lock_connection' => 'default',
],
'dynamodb' => [
'driver' => 'dynamodb',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
'endpoint' => env('DYNAMODB_ENDPOINT'),
],
'octane' => [
'driver' => 'octane',
],
],
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing the APC, database, memcached, Redis, or DynamoDB cache
| stores there might be other applications using the same cache. For
| that reason, you may prefix every cache key to avoid collisions.
|
*/
'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_cache_'),
];

34
config/cors.php Normal file
View File

@@ -0,0 +1,34 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
];

Some files were not shown because too many files have changed in this diff Show More