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:
592
docs/API.md
Normal file
592
docs/API.md
Normal file
@@ -0,0 +1,592 @@
|
||||
# Documentacion de API - Horux Backend
|
||||
|
||||
Esta documentacion describe todos los endpoints disponibles en la API de Horux.
|
||||
|
||||
## Base URL
|
||||
|
||||
```
|
||||
Produccion: https://horuxfin.com/api
|
||||
Desarrollo: http://localhost:8000/api
|
||||
```
|
||||
|
||||
## Autenticacion
|
||||
|
||||
La API utiliza OAuth 2.0 mediante Laravel Passport. Todos los endpoints protegidos requieren un token Bearer en el header:
|
||||
|
||||
```
|
||||
Authorization: Bearer {access_token}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Endpoints Publicos
|
||||
|
||||
### POST /auth
|
||||
Autenticacion mediante Clerk OAuth.
|
||||
|
||||
**Request Body:**
|
||||
```json
|
||||
{
|
||||
"code": "authorization_code_from_clerk"
|
||||
}
|
||||
```
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"token_type": "Bearer",
|
||||
"expires_in": 31536000,
|
||||
"access_token": "eyJ0...",
|
||||
"refresh_token": "def50..."
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### GET /retenciones
|
||||
Obtener retenciones fiscales.
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"data": [...]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### POST /invoice-endpoint
|
||||
Endpoint para recibir facturas (rate limited).
|
||||
|
||||
**Middleware:** `throttle:custom-origin`
|
||||
|
||||
---
|
||||
|
||||
### GET /obtener-ingresos
|
||||
Obtener ingresos desde Syntage API.
|
||||
|
||||
**Query Parameters:**
|
||||
| Parametro | Tipo | Requerido | Descripcion |
|
||||
|-----------|------|-----------|-------------|
|
||||
| rfc | string | Si | RFC del contribuyente |
|
||||
| year | integer | No | Ano fiscal |
|
||||
|
||||
---
|
||||
|
||||
### POST /obtener-egresos
|
||||
Obtener egresos desde Syntage API.
|
||||
|
||||
**Request Body:**
|
||||
```json
|
||||
{
|
||||
"rfc": "RFC123456789",
|
||||
"year": 2024
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### GET /ivaAFavor
|
||||
Calcular IVA a favor.
|
||||
|
||||
**Query Parameters:**
|
||||
| Parametro | Tipo | Requerido | Descripcion |
|
||||
|-----------|------|-----------|-------------|
|
||||
| rfc | string | Si | RFC del contribuyente |
|
||||
|
||||
---
|
||||
|
||||
### GET /utilidadBrutaVsIndustria
|
||||
Comparar utilidad bruta vs industria.
|
||||
|
||||
---
|
||||
|
||||
### GET /risk
|
||||
Consultar riesgos fiscales del contribuyente.
|
||||
|
||||
---
|
||||
|
||||
### POST /consultarmetrica
|
||||
Consultar metricas almacenadas.
|
||||
|
||||
---
|
||||
|
||||
### POST /insertmetrica
|
||||
Insertar nuevas metricas.
|
||||
|
||||
---
|
||||
|
||||
### POST /consultarcomparativo
|
||||
Consultar comparativo mensual.
|
||||
|
||||
---
|
||||
|
||||
### POST /insertcomparativo
|
||||
Insertar comparativo mensual.
|
||||
|
||||
---
|
||||
|
||||
### POST /usuariosat
|
||||
Registrar usuario SAT.
|
||||
|
||||
---
|
||||
|
||||
## Endpoints Protegidos
|
||||
|
||||
Todos estos endpoints requieren autenticacion (`middleware: auth:api`).
|
||||
|
||||
---
|
||||
|
||||
## Gestion de RFCs
|
||||
|
||||
### POST /insertar-rfc
|
||||
Asociar un RFC al usuario autenticado.
|
||||
|
||||
**Request Body:**
|
||||
```json
|
||||
{
|
||||
"rfc": "RFC123456789",
|
||||
"razon_social": "Empresa SA de CV"
|
||||
}
|
||||
```
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "RFC insertado correctamente",
|
||||
"data": {
|
||||
"id": 1,
|
||||
"rfc": "RFC123456789",
|
||||
"razon_social": "Empresa SA de CV"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### GET /obtener-rfcs
|
||||
Obtener todos los RFCs asociados al usuario.
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": 1,
|
||||
"rfc": "RFC123456789",
|
||||
"razon_social": "Empresa SA de CV"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Catalogos Fiscales
|
||||
|
||||
### GET /tipos-factura
|
||||
Obtener catalogo de tipos de factura.
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{"id": 1, "code": "I", "name": "Ingreso"},
|
||||
{"id": 2, "code": "E", "name": "Egreso"},
|
||||
{"id": 3, "code": "T", "name": "Traslado"},
|
||||
{"id": 4, "code": "N", "name": "Nomina"},
|
||||
{"id": 5, "code": "P", "name": "Pago"}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### GET /uso-factura
|
||||
Obtener catalogo de usos de factura (CFDI).
|
||||
|
||||
---
|
||||
|
||||
### GET /tipos-pago
|
||||
Obtener catalogo de tipos de pago.
|
||||
|
||||
---
|
||||
|
||||
### GET /metodos-pago
|
||||
Obtener catalogo de metodos de pago.
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{"id": 1, "code": "PUE", "name": "Pago en una sola exhibicion"},
|
||||
{"id": 2, "code": "PPD", "name": "Pago en parcialidades o diferido"}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### GET /monedas
|
||||
Obtener catalogo de monedas.
|
||||
|
||||
---
|
||||
|
||||
### GET /regimenes-fiscales
|
||||
Obtener catalogo de regimenes fiscales.
|
||||
|
||||
---
|
||||
|
||||
### GET /codigos-prod-serv
|
||||
Obtener catalogo de codigos de productos/servicios SAT.
|
||||
|
||||
---
|
||||
|
||||
### GET /codigos-unidad
|
||||
Obtener catalogo de codigos de unidad SAT.
|
||||
|
||||
---
|
||||
|
||||
### GET /impuestos
|
||||
Obtener catalogo de impuestos.
|
||||
|
||||
---
|
||||
|
||||
### GET /tasas-impuesto
|
||||
Obtener catalogo de tasas de impuesto.
|
||||
|
||||
---
|
||||
|
||||
## Gestion de Facturas
|
||||
|
||||
### GET /obtener-facturas
|
||||
Obtener todas las facturas del RFC.
|
||||
|
||||
**Query Parameters:**
|
||||
| Parametro | Tipo | Requerido | Descripcion |
|
||||
|-----------|------|-----------|-------------|
|
||||
| rfc | string | Si | RFC del contribuyente |
|
||||
| fecha_inicio | date | No | Fecha inicio (YYYY-MM-DD) |
|
||||
| fecha_fin | date | No | Fecha fin (YYYY-MM-DD) |
|
||||
| tipo | string | No | Tipo de factura (I, E, T, N, P) |
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": 1,
|
||||
"uuid": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
|
||||
"serie": "A",
|
||||
"folio": "123",
|
||||
"fecha": "2024-01-15",
|
||||
"subtotal": 1000.00,
|
||||
"total": 1160.00,
|
||||
"emisor_rfc": "RFC123456789",
|
||||
"emisor_nombre": "Empresa Emisora",
|
||||
"receptor_rfc": "RFC987654321",
|
||||
"receptor_nombre": "Empresa Receptora",
|
||||
"tipo_comprobante": "I",
|
||||
"metodo_pago": "PUE"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### GET /endpoint-facturas
|
||||
Endpoint alternativo para obtener facturas.
|
||||
|
||||
---
|
||||
|
||||
### GET /facturas-emitidas
|
||||
Obtener facturas emitidas por el RFC.
|
||||
|
||||
**Query Parameters:**
|
||||
| Parametro | Tipo | Requerido | Descripcion |
|
||||
|-----------|------|-----------|-------------|
|
||||
| rfc | string | Si | RFC del emisor |
|
||||
| year | integer | No | Ano fiscal |
|
||||
| month | integer | No | Mes (1-12) |
|
||||
|
||||
---
|
||||
|
||||
### GET /facturas-emitidas-conciliadas
|
||||
Obtener facturas emitidas ya conciliadas.
|
||||
|
||||
---
|
||||
|
||||
### GET /facturas-recibidas
|
||||
Obtener facturas recibidas por el RFC.
|
||||
|
||||
---
|
||||
|
||||
### GET /facturas-recibidas-conciliadas
|
||||
Obtener facturas recibidas ya conciliadas.
|
||||
|
||||
---
|
||||
|
||||
### POST /conciliar-facturas
|
||||
Marcar facturas como conciliadas.
|
||||
|
||||
**Request Body:**
|
||||
```json
|
||||
{
|
||||
"invoice_ids": [1, 2, 3],
|
||||
"rfc": "RFC123456789"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### GET /descargar-factura
|
||||
Descargar CFDI en formato XML.
|
||||
|
||||
**Query Parameters:**
|
||||
| Parametro | Tipo | Requerido | Descripcion |
|
||||
|-----------|------|-----------|-------------|
|
||||
| uuid | string | Si | UUID de la factura |
|
||||
|
||||
**Response:** Archivo XML del CFDI.
|
||||
|
||||
---
|
||||
|
||||
## Complementos de Pago
|
||||
|
||||
### GET /obtener-complementos-pago
|
||||
Obtener complementos de pago (facturas PPD).
|
||||
|
||||
**Query Parameters:**
|
||||
| Parametro | Tipo | Requerido | Descripcion |
|
||||
|-----------|------|-----------|-------------|
|
||||
| rfc | string | Si | RFC del contribuyente |
|
||||
|
||||
---
|
||||
|
||||
## Contribuyentes
|
||||
|
||||
### GET /obtener-contribuyente
|
||||
Obtener informacion del contribuyente desde Syntage.
|
||||
|
||||
**Query Parameters:**
|
||||
| Parametro | Tipo | Requerido | Descripcion |
|
||||
|-----------|------|-----------|-------------|
|
||||
| rfc | string | Si | RFC a consultar |
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"rfc": "RFC123456789",
|
||||
"razon_social": "Empresa SA de CV",
|
||||
"regimen_fiscal": "601",
|
||||
"actividades_economicas": [...],
|
||||
"riesgos": [...]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Lineas de Facturas
|
||||
|
||||
### GET /obtener-lineas-facturas
|
||||
Obtener lineas/conceptos de facturas.
|
||||
|
||||
---
|
||||
|
||||
### GET /obtener-facturas-conceptos
|
||||
Obtener facturas con sus conceptos.
|
||||
|
||||
---
|
||||
|
||||
## Calculos Financieros
|
||||
|
||||
### GET /ingreso-tipo-i
|
||||
Calcular ingresos tipo I (facturas de ingreso).
|
||||
|
||||
---
|
||||
|
||||
### GET /gasto-tipo-i
|
||||
Calcular gastos tipo I.
|
||||
|
||||
---
|
||||
|
||||
### GET /ingreso-tipo-e
|
||||
Calcular ingresos tipo E (notas de credito).
|
||||
|
||||
---
|
||||
|
||||
### GET /gasto-tipo-e
|
||||
Calcular gastos tipo E.
|
||||
|
||||
---
|
||||
|
||||
### GET /gasto-tipo-n
|
||||
Calcular gastos tipo N (nomina).
|
||||
|
||||
---
|
||||
|
||||
### GET /ingreso-ppd
|
||||
Calcular ingresos PPD (pagos en parcialidades).
|
||||
|
||||
---
|
||||
|
||||
### GET /gasto-ppd
|
||||
Calcular gastos PPD.
|
||||
|
||||
---
|
||||
|
||||
### GET /adquisicion-pue
|
||||
Calcular adquisiciones PUE.
|
||||
|
||||
---
|
||||
|
||||
### GET /adquisicion-ppd
|
||||
Calcular adquisiciones PPD.
|
||||
|
||||
---
|
||||
|
||||
## Metricas
|
||||
|
||||
### GET /obtener-metricas
|
||||
Obtener metricas globales del RFC.
|
||||
|
||||
**Query Parameters:**
|
||||
| Parametro | Tipo | Requerido | Descripcion |
|
||||
|-----------|------|-----------|-------------|
|
||||
| rfc | string | Si | RFC del contribuyente |
|
||||
| year | integer | No | Ano fiscal |
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"ingresos_totales": 1000000.00,
|
||||
"egresos_totales": 600000.00,
|
||||
"iva_trasladado": 160000.00,
|
||||
"iva_acreditable": 96000.00,
|
||||
"iva_a_favor": 64000.00,
|
||||
"isr_retenido": 50000.00
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### GET /obtener-metricas-mensuales
|
||||
Obtener metricas desglosadas por mes.
|
||||
|
||||
---
|
||||
|
||||
## Importacion Masiva
|
||||
|
||||
### POST /importar-facturas
|
||||
Importar facturas desde archivo Excel.
|
||||
|
||||
**Request:**
|
||||
- Content-Type: `multipart/form-data`
|
||||
- Campo: `file` (archivo .xlsx o .xls)
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "Se importaron 150 facturas correctamente",
|
||||
"imported": 150,
|
||||
"errors": 0
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### POST /importar-lineas-facturas
|
||||
Importar lineas de facturas desde Excel.
|
||||
|
||||
---
|
||||
|
||||
### POST /importar-codigos-prod-serv
|
||||
Importar catalogo de codigos de productos/servicios.
|
||||
|
||||
---
|
||||
|
||||
### POST /importar-codigos-unidad
|
||||
Importar catalogo de codigos de unidad.
|
||||
|
||||
---
|
||||
|
||||
## Codigos de Error
|
||||
|
||||
| Codigo | Descripcion |
|
||||
|--------|-------------|
|
||||
| 200 | Exito |
|
||||
| 201 | Recurso creado |
|
||||
| 400 | Solicitud invalida |
|
||||
| 401 | No autenticado |
|
||||
| 403 | No autorizado |
|
||||
| 404 | Recurso no encontrado |
|
||||
| 422 | Error de validacion |
|
||||
| 429 | Demasiadas solicitudes (rate limit) |
|
||||
| 500 | Error interno del servidor |
|
||||
|
||||
---
|
||||
|
||||
## Rate Limiting
|
||||
|
||||
Algunos endpoints tienen rate limiting configurado:
|
||||
- `/invoice-endpoint`: Limitado por origen (middleware `throttle:custom-origin`)
|
||||
|
||||
---
|
||||
|
||||
## Ejemplos de Uso
|
||||
|
||||
### Autenticacion con cURL
|
||||
|
||||
```bash
|
||||
# 1. Obtener token
|
||||
curl -X POST https://horuxfin.com/api/auth \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"code": "clerk_authorization_code"}'
|
||||
|
||||
# 2. Usar token en peticiones
|
||||
curl -X GET https://horuxfin.com/api/obtener-rfcs \
|
||||
-H "Authorization: Bearer {access_token}"
|
||||
```
|
||||
|
||||
### Obtener facturas con JavaScript
|
||||
|
||||
```javascript
|
||||
const response = await fetch('https://horuxfin.com/api/obtener-facturas?rfc=RFC123456789', {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${accessToken}`,
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
console.log(data);
|
||||
```
|
||||
|
||||
### Importar facturas con PHP
|
||||
|
||||
```php
|
||||
$client = new GuzzleHttp\Client();
|
||||
|
||||
$response = $client->post('https://horuxfin.com/api/importar-facturas', [
|
||||
'headers' => [
|
||||
'Authorization' => 'Bearer ' . $accessToken,
|
||||
],
|
||||
'multipart' => [
|
||||
[
|
||||
'name' => 'file',
|
||||
'contents' => fopen('/path/to/facturas.xlsx', 'r'),
|
||||
'filename' => 'facturas.xlsx'
|
||||
]
|
||||
]
|
||||
]);
|
||||
|
||||
$result = json_decode($response->getBody(), true);
|
||||
```
|
||||
434
docs/ARCHITECTURE.md
Normal file
434
docs/ARCHITECTURE.md
Normal file
@@ -0,0 +1,434 @@
|
||||
# Arquitectura - Horux Backend
|
||||
|
||||
Documentacion de la arquitectura y diseno del sistema Horux.
|
||||
|
||||
## Vision General
|
||||
|
||||
Horux es una API REST que actua como intermediario entre aplicaciones cliente y servicios fiscales mexicanos. La arquitectura sigue el patron MVC de Laravel con una capa de servicios adicional.
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ CLIENTES │
|
||||
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
|
||||
│ │ Web │ │ Mobile │ │ API │ │
|
||||
│ │ App │ │ App │ │ Client │ │
|
||||
│ └────┬────┘ └────┬────┘ └────┬────┘ │
|
||||
└───────┼────────────┼────────────┼───────────────────────────────┘
|
||||
│ │ │
|
||||
└────────────┼────────────┘
|
||||
│ HTTPS
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ HORUX BACKEND (Laravel) │
|
||||
│ ┌─────────────────────────────────────────────────────────┐ │
|
||||
│ │ MIDDLEWARE │ │
|
||||
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │
|
||||
│ │ │ CORS │ │ Auth │ │ Throttle │ │ Custom │ │ │
|
||||
│ │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ │
|
||||
│ └─────────────────────────────────────────────────────────┘ │
|
||||
│ │ │
|
||||
│ ┌─────────────────────────────────────────────────────────┐ │
|
||||
│ │ CONTROLLERS │ │
|
||||
│ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │
|
||||
│ │ │ Invoice │ │ Rfc │ │ Taxpayer │ │ │
|
||||
│ │ │ Controller │ │ Controller │ │ Controller │ │ │
|
||||
│ │ └─────────────┘ └─────────────┘ └─────────────┘ │ │
|
||||
│ └─────────────────────────────────────────────────────────┘ │
|
||||
│ │ │
|
||||
│ ┌─────────────────────────────────────────────────────────┐ │
|
||||
│ │ SERVICES │ │
|
||||
│ │ ┌─────────────────┐ ┌─────────────────────────┐ │ │
|
||||
│ │ │ SocialAccounts │ │ SocialUserResolver │ │ │
|
||||
│ │ │ Service │ │ Service │ │ │
|
||||
│ │ └─────────────────┘ └─────────────────────────┘ │ │
|
||||
│ └─────────────────────────────────────────────────────────┘ │
|
||||
│ │ │
|
||||
│ ┌─────────────────────────────────────────────────────────┐ │
|
||||
│ │ MODELS │ │
|
||||
│ │ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ │ │
|
||||
│ │ │ User │ │ Rfc │ │Invoice │ │Taxpayer│ ... │ │
|
||||
│ │ └────────┘ └────────┘ └────────┘ └────────┘ │ │
|
||||
│ └─────────────────────────────────────────────────────────┘ │
|
||||
│ │ │
|
||||
│ ┌─────────────────────────────────────────────────────────┐ │
|
||||
│ │ DATABASE │ │
|
||||
│ │ ┌──────────────┐ │ │
|
||||
│ │ │ MySQL │ │ │
|
||||
│ │ │ horux360bd │ │ │
|
||||
│ │ └──────────────┘ │ │
|
||||
│ └─────────────────────────────────────────────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
│ HTTP Requests
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ SERVICIOS EXTERNOS │
|
||||
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
|
||||
│ │ Syntage │ │ Clerk │ │ Facturama │ │
|
||||
│ │ API │ │ OAuth │ │ SDK │ │
|
||||
│ └─────────────┘ └─────────────┘ └─────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Capas de la Aplicacion
|
||||
|
||||
### 1. Capa de Routing
|
||||
|
||||
**Ubicacion:** `routes/`
|
||||
|
||||
Define los endpoints de la API y asocia rutas con controladores.
|
||||
|
||||
```php
|
||||
// routes/api.php
|
||||
Route::group(['middleware' => 'auth:api'], function() {
|
||||
Route::get('/obtener-facturas', [InvoiceController::class, 'obtenerFacturas']);
|
||||
});
|
||||
```
|
||||
|
||||
**Grupos de rutas:**
|
||||
- Rutas publicas (sin autenticacion)
|
||||
- Rutas protegidas (requieren `auth:api`)
|
||||
- Rutas con rate limiting (`throttle:custom-origin`)
|
||||
|
||||
---
|
||||
|
||||
### 2. Capa de Middleware
|
||||
|
||||
**Ubicacion:** `app/Http/Middleware/`
|
||||
|
||||
Procesa las solicitudes antes de llegar al controlador.
|
||||
|
||||
| Middleware | Proposito |
|
||||
|------------|-----------|
|
||||
| Authenticate | Verificar token OAuth |
|
||||
| ThrottleEndpoint | Rate limiting personalizado |
|
||||
| Cors | Manejo de CORS |
|
||||
| EncryptCookies | Encriptar cookies |
|
||||
| VerifyCsrfToken | Proteccion CSRF |
|
||||
|
||||
---
|
||||
|
||||
### 3. Capa de Controllers
|
||||
|
||||
**Ubicacion:** `app/Http/Controllers/`
|
||||
|
||||
Manejan la logica de las solicitudes HTTP.
|
||||
|
||||
**Patron utilizado:** Controller con logica de negocio embebida.
|
||||
|
||||
```php
|
||||
class InvoiceController extends Controller
|
||||
{
|
||||
public function obtenerFacturas(Request $request)
|
||||
{
|
||||
// Validacion
|
||||
// Logica de negocio
|
||||
// Llamadas a APIs externas
|
||||
// Persistencia
|
||||
// Respuesta
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Controladores principales:**
|
||||
- `InvoiceController` - Gestion de facturas (1811 lineas)
|
||||
- `InvoicePaymentController` - Pagos de facturas
|
||||
- `TaxpayerController` - Informacion de contribuyentes
|
||||
- `RfcController` - Gestion de RFCs
|
||||
|
||||
---
|
||||
|
||||
### 4. Capa de Services
|
||||
|
||||
**Ubicacion:** `app/Services/`
|
||||
|
||||
Encapsula logica reutilizable.
|
||||
|
||||
```php
|
||||
// app/Services/SocialAccountsService.php
|
||||
class SocialAccountsService
|
||||
{
|
||||
public function findOrCreate($providerUser, $provider)
|
||||
{
|
||||
// Logica para manejar cuentas sociales
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 5. Capa de Models
|
||||
|
||||
**Ubicacion:** `app/Models/`
|
||||
|
||||
Modelos Eloquent que representan las tablas de la base de datos.
|
||||
|
||||
```php
|
||||
class Invoice extends Model
|
||||
{
|
||||
protected $fillable = ['uuid', 'serie', 'folio', ...];
|
||||
|
||||
public function rfc()
|
||||
{
|
||||
return $this->belongsTo(Rfc::class);
|
||||
}
|
||||
|
||||
public function lines()
|
||||
{
|
||||
return $this->hasMany(InvoiceLine::class);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 6. Capa de Imports
|
||||
|
||||
**Ubicacion:** `app/Imports/`
|
||||
|
||||
Maneja la importacion de datos desde archivos Excel.
|
||||
|
||||
```php
|
||||
class InvoicesImport implements ToModel, WithHeadingRow, WithChunkReading
|
||||
{
|
||||
public function model(array $row)
|
||||
{
|
||||
return new Invoice([...]);
|
||||
}
|
||||
|
||||
public function chunkSize(): int
|
||||
{
|
||||
return 1000;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Flujos de Datos
|
||||
|
||||
### Flujo de Autenticacion
|
||||
|
||||
```
|
||||
1. Cliente -> POST /api/auth (code de Clerk)
|
||||
2. Backend -> POST Clerk API (intercambio de codigo)
|
||||
3. Clerk API -> access_token
|
||||
4. Backend -> Crear/buscar usuario
|
||||
5. Backend -> Generar token Passport
|
||||
6. Backend -> Cliente (token Passport)
|
||||
```
|
||||
|
||||
### Flujo de Obtencion de Facturas
|
||||
|
||||
```
|
||||
1. Cliente -> GET /api/obtener-facturas (Bearer token)
|
||||
2. Middleware -> Validar token
|
||||
3. Controller -> Obtener RFC del usuario
|
||||
4. Controller -> GET Syntage API (facturas)
|
||||
5. Controller -> Procesar y guardar en BD
|
||||
6. Controller -> Response JSON al cliente
|
||||
```
|
||||
|
||||
### Flujo de Calculo de Metricas
|
||||
|
||||
```
|
||||
1. Cliente -> GET /api/obtener-metricas
|
||||
2. Controller -> Query facturas desde BD
|
||||
3. Controller -> Calcular:
|
||||
- Ingresos (tipo I)
|
||||
- Egresos (tipo E)
|
||||
- IVA trasladado/retenido
|
||||
- ISR retenido
|
||||
4. Controller -> Response con metricas
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Integraciones Externas
|
||||
|
||||
### Syntage API
|
||||
|
||||
**Proposito:** Obtener datos fiscales del SAT.
|
||||
|
||||
**Endpoints utilizados:**
|
||||
- `/invoices` - Obtener facturas
|
||||
- `/insights` - Metricas financieras
|
||||
- `/taxpayer` - Informacion del contribuyente
|
||||
- `/risks` - Riesgos fiscales
|
||||
|
||||
**Autenticacion:** API Key en header.
|
||||
|
||||
```php
|
||||
$response = Http::withHeaders([
|
||||
'Authorization' => 'Bearer ' . $apiKey
|
||||
])->get('https://api.syntage.com/invoices', $params);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Clerk OAuth
|
||||
|
||||
**Proposito:** Autenticacion de usuarios.
|
||||
|
||||
**Flujo:**
|
||||
1. Usuario se autentica en Clerk (frontend)
|
||||
2. Frontend obtiene authorization code
|
||||
3. Backend intercambia code por access token
|
||||
4. Backend crea sesion local
|
||||
|
||||
---
|
||||
|
||||
### Facturama SDK
|
||||
|
||||
**Proposito:** Generar y timbrar CFDIs.
|
||||
|
||||
```php
|
||||
$facturama = new Facturama(['sandbox' => true]);
|
||||
$cfdi = $facturama->post('Cfdi', $invoiceData);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Patrones de Diseno
|
||||
|
||||
### Repository Pattern (Parcial)
|
||||
|
||||
Aunque no hay repositorios explicitos, los modelos Eloquent actuan como repositories.
|
||||
|
||||
### Service Pattern
|
||||
|
||||
Los servicios encapsulan logica de negocio reutilizable.
|
||||
|
||||
### Strategy Pattern (Imports)
|
||||
|
||||
Los importadores implementan interfaces de Maatwebsite Excel.
|
||||
|
||||
---
|
||||
|
||||
## Seguridad
|
||||
|
||||
### Autenticacion
|
||||
|
||||
- OAuth 2.0 con Laravel Passport
|
||||
- Tokens de acceso con expiracion
|
||||
- Refresh tokens para renovacion
|
||||
|
||||
### Autorizacion
|
||||
|
||||
- Middleware `auth:api` para rutas protegidas
|
||||
- Validacion de pertenencia de RFCs a usuarios
|
||||
|
||||
### Protecciones
|
||||
|
||||
- CORS configurado
|
||||
- Rate limiting con middleware personalizado
|
||||
- Validacion de entrada en controllers
|
||||
- Prepared statements (Eloquent ORM)
|
||||
|
||||
---
|
||||
|
||||
## Escalabilidad
|
||||
|
||||
### Actual
|
||||
|
||||
- Servidor unico
|
||||
- Base de datos MySQL
|
||||
- Cache en archivos
|
||||
|
||||
### Mejoras Recomendadas
|
||||
|
||||
```
|
||||
┌─────────────┐
|
||||
│ Load Balancer│
|
||||
└──────┬──────┘
|
||||
│
|
||||
┌──────┴──────┐
|
||||
│ │
|
||||
▼ ▼
|
||||
┌─────┐ ┌─────┐
|
||||
│App 1│ │App 2│
|
||||
└──┬──┘ └──┬──┘
|
||||
│ │
|
||||
└────┬─────┘
|
||||
│
|
||||
┌────┴────┐
|
||||
│ Redis │ (Cache/Sessions)
|
||||
└────┬────┘
|
||||
│
|
||||
┌────┴────┐
|
||||
│ MySQL │ (Master-Slave)
|
||||
└─────────┘
|
||||
```
|
||||
|
||||
- Redis para cache y sesiones
|
||||
- Queue workers para tareas pesadas
|
||||
- Replica de base de datos
|
||||
|
||||
---
|
||||
|
||||
## Estructura de Directorios Detallada
|
||||
|
||||
```
|
||||
app/
|
||||
├── Console/
|
||||
│ └── Kernel.php # Comandos programados
|
||||
├── Exceptions/
|
||||
│ └── Handler.php # Manejo global de excepciones
|
||||
├── Http/
|
||||
│ ├── Controllers/
|
||||
│ │ ├── Controller.php # Base controller
|
||||
│ │ ├── InvoiceController.php
|
||||
│ │ ├── RfcController.php
|
||||
│ │ └── ...
|
||||
│ ├── Middleware/
|
||||
│ │ ├── Authenticate.php
|
||||
│ │ ├── ThrottleEndpoint.php
|
||||
│ │ └── ...
|
||||
│ └── Kernel.php # Registro de middleware
|
||||
├── Imports/
|
||||
│ ├── InvoicesImport.php
|
||||
│ └── LineItemsImport.php
|
||||
├── Models/
|
||||
│ ├── Invoice.php
|
||||
│ ├── User.php
|
||||
│ └── ...
|
||||
├── Providers/
|
||||
│ ├── AppServiceProvider.php
|
||||
│ ├── AuthServiceProvider.php
|
||||
│ └── ...
|
||||
└── Services/
|
||||
├── SocialAccountsService.php
|
||||
└── SocialUserResolver.php
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Consideraciones de Rendimiento
|
||||
|
||||
### Queries Optimizadas
|
||||
|
||||
```php
|
||||
// Eager loading para evitar N+1
|
||||
$invoices = Invoice::with(['lines', 'payments'])->get();
|
||||
```
|
||||
|
||||
### Importacion en Chunks
|
||||
|
||||
```php
|
||||
// Procesar Excel en lotes de 1000
|
||||
public function chunkSize(): int
|
||||
{
|
||||
return 1000;
|
||||
}
|
||||
```
|
||||
|
||||
### Cache
|
||||
|
||||
```php
|
||||
// Cachear catalogos estaticos
|
||||
$regimes = Cache::remember('tax_regimes', 3600, function() {
|
||||
return TaxRegime::all();
|
||||
});
|
||||
```
|
||||
383
docs/INSTALLATION.md
Normal file
383
docs/INSTALLATION.md
Normal file
@@ -0,0 +1,383 @@
|
||||
# Guia de Instalacion - Horux Backend
|
||||
|
||||
Guia completa para instalar y configurar el proyecto Horux Backend.
|
||||
|
||||
## Requisitos Previos
|
||||
|
||||
### Software Requerido
|
||||
|
||||
| Software | Version Minima | Comando de verificacion |
|
||||
|----------|---------------|------------------------|
|
||||
| PHP | 8.0.2 | `php -v` |
|
||||
| Composer | 2.0 | `composer -V` |
|
||||
| MySQL/MariaDB | 5.7 / 10.3 | `mysql --version` |
|
||||
| Node.js | 16.0 | `node -v` |
|
||||
| NPM | 8.0 | `npm -v` |
|
||||
| Git | 2.0 | `git --version` |
|
||||
|
||||
### Extensiones PHP Requeridas
|
||||
|
||||
```
|
||||
- BCMath
|
||||
- Ctype
|
||||
- cURL
|
||||
- DOM
|
||||
- Fileinfo
|
||||
- JSON
|
||||
- Mbstring
|
||||
- OpenSSL
|
||||
- PDO
|
||||
- PDO_MySQL
|
||||
- Tokenizer
|
||||
- XML
|
||||
```
|
||||
|
||||
Verificar extensiones instaladas:
|
||||
```bash
|
||||
php -m
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Instalacion Paso a Paso
|
||||
|
||||
### 1. Clonar Repositorio
|
||||
|
||||
```bash
|
||||
git clone https://git.consultoria-as.com/tu-usuario/Horux_back.git
|
||||
cd Horux_back
|
||||
```
|
||||
|
||||
### 2. Instalar Dependencias PHP
|
||||
|
||||
```bash
|
||||
composer install
|
||||
```
|
||||
|
||||
Si hay problemas de memoria:
|
||||
```bash
|
||||
COMPOSER_MEMORY_LIMIT=-1 composer install
|
||||
```
|
||||
|
||||
### 3. Instalar Dependencias NPM
|
||||
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
### 4. Configurar Archivo de Entorno
|
||||
|
||||
```bash
|
||||
# Copiar archivo de ejemplo
|
||||
cp .env.example .env
|
||||
|
||||
# Generar clave de aplicacion
|
||||
php artisan key:generate
|
||||
```
|
||||
|
||||
### 5. Editar Configuracion
|
||||
|
||||
Editar el archivo `.env` con los valores apropiados:
|
||||
|
||||
```env
|
||||
# Aplicacion
|
||||
APP_NAME=Horux
|
||||
APP_ENV=local
|
||||
APP_KEY=base64:GENERADA_AUTOMATICAMENTE
|
||||
APP_DEBUG=true
|
||||
APP_URL=http://localhost:8000
|
||||
|
||||
# Base de Datos
|
||||
DB_CONNECTION=mysql
|
||||
DB_HOST=127.0.0.1
|
||||
DB_PORT=3306
|
||||
DB_DATABASE=horux360bd
|
||||
DB_USERNAME=tu_usuario
|
||||
DB_PASSWORD=tu_password
|
||||
|
||||
# Logging
|
||||
LOG_CHANNEL=stack
|
||||
LOG_LEVEL=debug
|
||||
```
|
||||
|
||||
### 6. Crear Base de Datos
|
||||
|
||||
```bash
|
||||
# Conectar a MySQL
|
||||
mysql -u root -p
|
||||
|
||||
# Crear base de datos
|
||||
CREATE DATABASE horux360bd CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
# Crear usuario (opcional)
|
||||
CREATE USER 'horux_user'@'localhost' IDENTIFIED BY 'password_seguro';
|
||||
GRANT ALL PRIVILEGES ON horux360bd.* TO 'horux_user'@'localhost';
|
||||
FLUSH PRIVILEGES;
|
||||
|
||||
# Salir
|
||||
exit
|
||||
```
|
||||
|
||||
### 7. Ejecutar Migraciones
|
||||
|
||||
```bash
|
||||
php artisan migrate
|
||||
```
|
||||
|
||||
O importar el dump existente:
|
||||
```bash
|
||||
mysql -u usuario -p horux360bd < horux360bd.sql
|
||||
```
|
||||
|
||||
### 8. Configurar Laravel Passport
|
||||
|
||||
```bash
|
||||
# Instalar Passport
|
||||
php artisan passport:install
|
||||
|
||||
# Esto generara Client ID y Client Secret
|
||||
# Copiar estos valores al archivo .env o config/app.php
|
||||
```
|
||||
|
||||
Agregar al `.env`:
|
||||
```env
|
||||
PASSPORT_CLIENT_ID=1
|
||||
PASSPORT_CLIENT_SECRET=XXXXXXXXXXXXXXXXXXXXX
|
||||
```
|
||||
|
||||
### 9. Configurar Permisos de Directorios
|
||||
|
||||
```bash
|
||||
# Linux/Mac
|
||||
chmod -R 775 storage
|
||||
chmod -R 775 bootstrap/cache
|
||||
|
||||
# Si hay problemas de permisos
|
||||
sudo chown -R www-data:www-data storage bootstrap/cache
|
||||
```
|
||||
|
||||
### 10. Compilar Assets (Opcional)
|
||||
|
||||
```bash
|
||||
# Desarrollo
|
||||
npm run dev
|
||||
|
||||
# Produccion
|
||||
npm run build
|
||||
```
|
||||
|
||||
### 11. Iniciar Servidor de Desarrollo
|
||||
|
||||
```bash
|
||||
php artisan serve
|
||||
```
|
||||
|
||||
La aplicacion estara disponible en: `http://localhost:8000`
|
||||
|
||||
---
|
||||
|
||||
## Configuracion Avanzada
|
||||
|
||||
### Configurar Clerk (Autenticacion)
|
||||
|
||||
1. Crear cuenta en [Clerk](https://clerk.com)
|
||||
2. Crear aplicacion y obtener credenciales
|
||||
3. Configurar redirect URIs:
|
||||
- Desarrollo: `http://localhost:3000/callback`
|
||||
- Produccion: `https://tu-dominio.com/callback`
|
||||
|
||||
### Configurar Syntage API
|
||||
|
||||
La API key de Syntage se configura en `routes/api.php`. Para produccion, mover a variables de entorno:
|
||||
|
||||
```env
|
||||
SYNTAGE_API_KEY=tu_api_key
|
||||
```
|
||||
|
||||
### Configurar Facturama
|
||||
|
||||
```env
|
||||
FACTURAMA_USER=tu_usuario
|
||||
FACTURAMA_PASSWORD=tu_password
|
||||
FACTURAMA_SANDBOX=true # false para produccion
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Configuracion para Produccion
|
||||
|
||||
### 1. Optimizar Autoloader
|
||||
|
||||
```bash
|
||||
composer install --optimize-autoloader --no-dev
|
||||
```
|
||||
|
||||
### 2. Cachear Configuracion
|
||||
|
||||
```bash
|
||||
php artisan config:cache
|
||||
php artisan route:cache
|
||||
php artisan view:cache
|
||||
```
|
||||
|
||||
### 3. Configurar Variables de Produccion
|
||||
|
||||
```env
|
||||
APP_ENV=production
|
||||
APP_DEBUG=false
|
||||
APP_URL=https://tu-dominio.com
|
||||
|
||||
LOG_LEVEL=error
|
||||
```
|
||||
|
||||
### 4. Configurar HTTPS
|
||||
|
||||
Asegurarse de que el servidor web (Nginx/Apache) tenga SSL configurado.
|
||||
|
||||
### 5. Configurar Cola de Trabajos (Opcional)
|
||||
|
||||
```bash
|
||||
# En .env
|
||||
QUEUE_CONNECTION=database
|
||||
|
||||
# Ejecutar migraciones de cola
|
||||
php artisan queue:table
|
||||
php artisan migrate
|
||||
|
||||
# Iniciar worker
|
||||
php artisan queue:work
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Configuracion de Servidor Web
|
||||
|
||||
### Nginx
|
||||
|
||||
```nginx
|
||||
server {
|
||||
listen 80;
|
||||
server_name tu-dominio.com;
|
||||
root /var/www/Horux_back/public;
|
||||
|
||||
add_header X-Frame-Options "SAMEORIGIN";
|
||||
add_header X-Content-Type-Options "nosniff";
|
||||
|
||||
index index.php;
|
||||
|
||||
charset utf-8;
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ /index.php?$query_string;
|
||||
}
|
||||
|
||||
location = /favicon.ico { access_log off; log_not_found off; }
|
||||
location = /robots.txt { access_log off; log_not_found off; }
|
||||
|
||||
error_page 404 /index.php;
|
||||
|
||||
location ~ \.php$ {
|
||||
fastcgi_pass unix:/var/run/php/php8.0-fpm.sock;
|
||||
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
|
||||
include fastcgi_params;
|
||||
}
|
||||
|
||||
location ~ /\.(?!well-known).* {
|
||||
deny all;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Apache
|
||||
|
||||
Crear archivo `.htaccess` en `/public`:
|
||||
|
||||
```apache
|
||||
<IfModule mod_rewrite.c>
|
||||
<IfModule mod_negotiation.c>
|
||||
Options -MultiViews -Indexes
|
||||
</IfModule>
|
||||
|
||||
RewriteEngine On
|
||||
|
||||
# Handle Authorization Header
|
||||
RewriteCond %{HTTP:Authorization} .
|
||||
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
|
||||
|
||||
# Redirect Trailing Slashes If Not A Folder...
|
||||
RewriteCond %{REQUEST_FILENAME} !-d
|
||||
RewriteCond %{REQUEST_URI} (.+)/$
|
||||
RewriteRule ^ %1 [L,R=301]
|
||||
|
||||
# Send Requests To Front Controller...
|
||||
RewriteCond %{REQUEST_FILENAME} !-d
|
||||
RewriteCond %{REQUEST_FILENAME} !-f
|
||||
RewriteRule ^ index.php [L]
|
||||
</IfModule>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Solucion de Problemas
|
||||
|
||||
### Error: SQLSTATE[HY000] [2002]
|
||||
|
||||
No se puede conectar a MySQL. Verificar:
|
||||
- MySQL esta corriendo: `sudo systemctl status mysql`
|
||||
- Credenciales en `.env` son correctas
|
||||
- Host y puerto son correctos
|
||||
|
||||
### Error: Permission denied
|
||||
|
||||
```bash
|
||||
sudo chown -R $USER:www-data storage bootstrap/cache
|
||||
sudo chmod -R 775 storage bootstrap/cache
|
||||
```
|
||||
|
||||
### Error: Class not found
|
||||
|
||||
```bash
|
||||
composer dump-autoload
|
||||
php artisan clear-compiled
|
||||
```
|
||||
|
||||
### Error: The Mix manifest does not exist
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
# o
|
||||
npm run build
|
||||
```
|
||||
|
||||
### Limpiar Cache
|
||||
|
||||
```bash
|
||||
php artisan cache:clear
|
||||
php artisan config:clear
|
||||
php artisan route:clear
|
||||
php artisan view:clear
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Comandos Utiles
|
||||
|
||||
```bash
|
||||
# Ver rutas disponibles
|
||||
php artisan route:list
|
||||
|
||||
# Ejecutar tests
|
||||
php artisan test
|
||||
|
||||
# Ejecutar tinker (REPL)
|
||||
php artisan tinker
|
||||
|
||||
# Crear nuevo controlador
|
||||
php artisan make:controller NombreController
|
||||
|
||||
# Crear nuevo modelo
|
||||
php artisan make:model Nombre -m
|
||||
|
||||
# Ver logs
|
||||
tail -f storage/logs/laravel.log
|
||||
```
|
||||
447
docs/MODELS.md
Normal file
447
docs/MODELS.md
Normal file
@@ -0,0 +1,447 @@
|
||||
# Modelos y Base de Datos - Horux Backend
|
||||
|
||||
Documentacion de los modelos Eloquent y estructura de la base de datos.
|
||||
|
||||
## Diagrama de Relaciones
|
||||
|
||||
```
|
||||
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
|
||||
│ User │◄─────►│ Rfc │◄─────►│ Invoice │
|
||||
└─────────────┘ M:N └─────────────┘ 1:N └─────────────┘
|
||||
│ │ │
|
||||
│ 1:N │ 1:N │ 1:N
|
||||
▼ ▼ ▼
|
||||
┌─────────────────┐ ┌─────────────┐ ┌─────────────┐
|
||||
│LinkedSocialAcct │ │ Taxpayer │ │ InvoiceLine │
|
||||
└─────────────────┘ └─────────────┘ └─────────────┘
|
||||
│
|
||||
│ M:N
|
||||
▼
|
||||
┌─────────────┐ ┌─────────────────┐
|
||||
│ TaxRegime │ │ InvoicePayment │
|
||||
└─────────────┘ └─────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Modelos Principales
|
||||
|
||||
### User
|
||||
Usuario del sistema.
|
||||
|
||||
**Tabla:** `users`
|
||||
|
||||
| Campo | Tipo | Descripcion |
|
||||
|-------|------|-------------|
|
||||
| id | bigint | ID primario |
|
||||
| name | string | Nombre del usuario |
|
||||
| email | string | Correo electronico |
|
||||
| email_verified_at | timestamp | Fecha verificacion |
|
||||
| password | string | Contrasena hasheada |
|
||||
| remember_token | string | Token de sesion |
|
||||
| created_at | timestamp | Fecha creacion |
|
||||
| updated_at | timestamp | Fecha actualizacion |
|
||||
|
||||
**Relaciones:**
|
||||
- `rfcs()` - BelongsToMany con Rfc
|
||||
- `linkedSocialAccounts()` - HasMany con LinkedSocialAccount
|
||||
|
||||
---
|
||||
|
||||
### Rfc
|
||||
RFC (Registro Federal de Contribuyentes) asociado a usuarios.
|
||||
|
||||
**Tabla:** `rfcs`
|
||||
|
||||
| Campo | Tipo | Descripcion |
|
||||
|-------|------|-------------|
|
||||
| id | bigint | ID primario |
|
||||
| rfc | string(13) | RFC del contribuyente |
|
||||
| razon_social | string | Razon social |
|
||||
| created_at | timestamp | Fecha creacion |
|
||||
| updated_at | timestamp | Fecha actualizacion |
|
||||
|
||||
**Relaciones:**
|
||||
- `users()` - BelongsToMany con User
|
||||
- `invoices()` - HasMany con Invoice
|
||||
- `taxpayers()` - HasMany con Taxpayer
|
||||
|
||||
---
|
||||
|
||||
### Invoice
|
||||
Factura electronica (CFDI).
|
||||
|
||||
**Tabla:** `invoices`
|
||||
|
||||
| Campo | Tipo | Descripcion |
|
||||
|-------|------|-------------|
|
||||
| id | bigint | ID primario |
|
||||
| uuid | string(36) | UUID unico del CFDI |
|
||||
| serie | string | Serie de la factura |
|
||||
| folio | string | Folio de la factura |
|
||||
| fecha | datetime | Fecha de emision |
|
||||
| subtotal | decimal(18,2) | Subtotal |
|
||||
| descuento | decimal(18,2) | Descuento aplicado |
|
||||
| total | decimal(18,2) | Total de la factura |
|
||||
| moneda | string(3) | Codigo de moneda |
|
||||
| tipo_cambio | decimal(10,4) | Tipo de cambio |
|
||||
| emisor_rfc | string(13) | RFC del emisor |
|
||||
| emisor_nombre | string | Nombre del emisor |
|
||||
| receptor_rfc | string(13) | RFC del receptor |
|
||||
| receptor_nombre | string | Nombre del receptor |
|
||||
| tipo_comprobante | string(1) | Tipo (I, E, T, N, P) |
|
||||
| metodo_pago | string(3) | Metodo de pago |
|
||||
| forma_pago | string(2) | Forma de pago |
|
||||
| uso_cfdi | string(4) | Uso del CFDI |
|
||||
| iva_trasladado | decimal(18,2) | IVA trasladado |
|
||||
| iva_retenido | decimal(18,2) | IVA retenido |
|
||||
| isr_retenido | decimal(18,2) | ISR retenido |
|
||||
| rfc_id | bigint | FK a rfcs |
|
||||
| conciliado | boolean | Estado de conciliacion |
|
||||
| created_at | timestamp | Fecha creacion |
|
||||
| updated_at | timestamp | Fecha actualizacion |
|
||||
|
||||
**Relaciones:**
|
||||
- `rfc()` - BelongsTo con Rfc
|
||||
- `lines()` - HasMany con InvoiceLine
|
||||
- `payments()` - HasMany con InvoicePayment
|
||||
- `invoiceType()` - BelongsTo con InvoiceType
|
||||
- `conciliations()` - HasMany con Conciliation
|
||||
|
||||
---
|
||||
|
||||
### InvoiceLine
|
||||
Linea/concepto de una factura.
|
||||
|
||||
**Tabla:** `invoice_lines`
|
||||
|
||||
| Campo | Tipo | Descripcion |
|
||||
|-------|------|-------------|
|
||||
| id | bigint | ID primario |
|
||||
| invoice_id | bigint | FK a invoices |
|
||||
| clave_prod_serv | string(8) | Codigo SAT producto/servicio |
|
||||
| clave_unidad | string(6) | Codigo SAT unidad |
|
||||
| descripcion | text | Descripcion del concepto |
|
||||
| cantidad | decimal(18,6) | Cantidad |
|
||||
| valor_unitario | decimal(18,6) | Valor unitario |
|
||||
| importe | decimal(18,2) | Importe |
|
||||
| descuento | decimal(18,2) | Descuento |
|
||||
| created_at | timestamp | Fecha creacion |
|
||||
| updated_at | timestamp | Fecha actualizacion |
|
||||
|
||||
**Relaciones:**
|
||||
- `invoice()` - BelongsTo con Invoice
|
||||
- `prodServCode()` - BelongsTo con ProdServCode
|
||||
- `unitCode()` - BelongsTo con UnitCode
|
||||
|
||||
---
|
||||
|
||||
### InvoicePayment
|
||||
Pago de factura (complemento de pago PPD).
|
||||
|
||||
**Tabla:** `invoice_payments`
|
||||
|
||||
| Campo | Tipo | Descripcion |
|
||||
|-------|------|-------------|
|
||||
| id | bigint | ID primario |
|
||||
| invoice_id | bigint | FK a invoice (CFDI de pago) |
|
||||
| doc_relacionado_uuid | string(36) | UUID factura pagada |
|
||||
| fecha_pago | datetime | Fecha del pago |
|
||||
| monto | decimal(18,2) | Monto pagado |
|
||||
| num_parcialidad | integer | Numero de parcialidad |
|
||||
| imp_saldo_ant | decimal(18,2) | Saldo anterior |
|
||||
| imp_pagado | decimal(18,2) | Importe pagado |
|
||||
| imp_saldo_insoluto | decimal(18,2) | Saldo insoluto |
|
||||
| created_at | timestamp | Fecha creacion |
|
||||
| updated_at | timestamp | Fecha actualizacion |
|
||||
|
||||
**Relaciones:**
|
||||
- `invoice()` - BelongsTo con Invoice
|
||||
|
||||
---
|
||||
|
||||
### Taxpayer
|
||||
Informacion del contribuyente.
|
||||
|
||||
**Tabla:** `taxpayers`
|
||||
|
||||
| Campo | Tipo | Descripcion |
|
||||
|-------|------|-------------|
|
||||
| id | bigint | ID primario |
|
||||
| rfc_id | bigint | FK a rfcs |
|
||||
| nombre | string | Nombre o razon social |
|
||||
| tipo_persona | string | Fisica o Moral |
|
||||
| situacion | string | Situacion fiscal |
|
||||
| fecha_inicio_operaciones | date | Inicio de operaciones |
|
||||
| created_at | timestamp | Fecha creacion |
|
||||
| updated_at | timestamp | Fecha actualizacion |
|
||||
|
||||
**Relaciones:**
|
||||
- `rfc()` - BelongsTo con Rfc
|
||||
- `taxRegimes()` - BelongsToMany con TaxRegime
|
||||
- `economicActivities()` - BelongsToMany con EconomicActivity
|
||||
- `risks()` - BelongsToMany con Risk
|
||||
|
||||
---
|
||||
|
||||
### LinkedSocialAccount
|
||||
Cuenta social vinculada al usuario.
|
||||
|
||||
**Tabla:** `linked_social_accounts`
|
||||
|
||||
| Campo | Tipo | Descripcion |
|
||||
|-------|------|-------------|
|
||||
| id | bigint | ID primario |
|
||||
| user_id | bigint | FK a users |
|
||||
| provider | string | Proveedor (clerk, google, etc) |
|
||||
| provider_id | string | ID en el proveedor |
|
||||
| created_at | timestamp | Fecha creacion |
|
||||
| updated_at | timestamp | Fecha actualizacion |
|
||||
|
||||
**Relaciones:**
|
||||
- `user()` - BelongsTo con User
|
||||
|
||||
---
|
||||
|
||||
## Modelos de Catalogos
|
||||
|
||||
### InvoiceType
|
||||
Tipos de comprobante fiscal.
|
||||
|
||||
| Codigo | Nombre |
|
||||
|--------|--------|
|
||||
| I | Ingreso |
|
||||
| E | Egreso |
|
||||
| T | Traslado |
|
||||
| N | Nomina |
|
||||
| P | Pago |
|
||||
|
||||
---
|
||||
|
||||
### PaymentMethod
|
||||
Metodos de pago.
|
||||
|
||||
| Codigo | Nombre |
|
||||
|--------|--------|
|
||||
| PUE | Pago en una sola exhibicion |
|
||||
| PPD | Pago en parcialidades o diferido |
|
||||
|
||||
---
|
||||
|
||||
### PaymentType
|
||||
Formas de pago (30+ tipos).
|
||||
|
||||
| Codigo | Nombre |
|
||||
|--------|--------|
|
||||
| 01 | Efectivo |
|
||||
| 02 | Cheque nominativo |
|
||||
| 03 | Transferencia electronica |
|
||||
| 04 | Tarjeta de credito |
|
||||
| ... | ... |
|
||||
|
||||
---
|
||||
|
||||
### Currency
|
||||
Monedas.
|
||||
|
||||
| Codigo | Nombre |
|
||||
|--------|--------|
|
||||
| MXN | Peso Mexicano |
|
||||
| USD | Dolar Americano |
|
||||
| EUR | Euro |
|
||||
| ... | ... |
|
||||
|
||||
---
|
||||
|
||||
### TaxRegime
|
||||
Regimenes fiscales.
|
||||
|
||||
| Codigo | Nombre |
|
||||
|--------|--------|
|
||||
| 601 | General de Ley Personas Morales |
|
||||
| 603 | Personas Morales con Fines no Lucrativos |
|
||||
| 605 | Sueldos y Salarios |
|
||||
| 606 | Arrendamiento |
|
||||
| 612 | Personas Fisicas con Actividades Empresariales |
|
||||
| 621 | Incorporacion Fiscal |
|
||||
| 626 | Regimen Simplificado de Confianza |
|
||||
| ... | ... |
|
||||
|
||||
---
|
||||
|
||||
### Tax
|
||||
Impuestos.
|
||||
|
||||
| Codigo | Nombre |
|
||||
|--------|--------|
|
||||
| 001 | ISR |
|
||||
| 002 | IVA |
|
||||
| 003 | IEPS |
|
||||
|
||||
---
|
||||
|
||||
### TaxRate
|
||||
Tasas de impuestos.
|
||||
|
||||
| Impuesto | Tasa |
|
||||
|----------|------|
|
||||
| IVA | 0.16 (16%) |
|
||||
| IVA | 0.08 (8% frontera) |
|
||||
| IVA | 0.00 (0%) |
|
||||
| ISR | Variable |
|
||||
| IEPS | Variable |
|
||||
|
||||
---
|
||||
|
||||
### Status
|
||||
Estados de factura.
|
||||
|
||||
| Codigo | Nombre |
|
||||
|--------|--------|
|
||||
| 1 | Vigente |
|
||||
| 0 | Cancelado |
|
||||
|
||||
---
|
||||
|
||||
### CancellationType
|
||||
Tipos de cancelacion.
|
||||
|
||||
| Codigo | Nombre |
|
||||
|--------|--------|
|
||||
| 01 | Con relacion |
|
||||
| 02 | Sin relacion |
|
||||
|
||||
---
|
||||
|
||||
### EconomicActivity
|
||||
Actividades economicas.
|
||||
|
||||
---
|
||||
|
||||
### Industry
|
||||
Industrias/sectores.
|
||||
|
||||
---
|
||||
|
||||
### Risk
|
||||
Riesgos fiscales.
|
||||
|
||||
---
|
||||
|
||||
### Dimension
|
||||
Dimensiones de empresa.
|
||||
|
||||
---
|
||||
|
||||
## Modelos de Codigos SAT
|
||||
|
||||
### ProdServCode
|
||||
Catalogo de productos y servicios SAT.
|
||||
|
||||
| Campo | Tipo | Descripcion |
|
||||
|-------|------|-------------|
|
||||
| id | bigint | ID primario |
|
||||
| code | string(8) | Codigo SAT |
|
||||
| description | string | Descripcion |
|
||||
|
||||
---
|
||||
|
||||
### UnitCode
|
||||
Catalogo de unidades SAT.
|
||||
|
||||
| Campo | Tipo | Descripcion |
|
||||
|-------|------|-------------|
|
||||
| id | bigint | ID primario |
|
||||
| code | string(6) | Codigo SAT |
|
||||
| name | string | Nombre de la unidad |
|
||||
|
||||
---
|
||||
|
||||
### PostalCode
|
||||
Codigos postales.
|
||||
|
||||
---
|
||||
|
||||
## Modelos Financieros
|
||||
|
||||
### SalesRevenue
|
||||
Ingresos por ventas.
|
||||
|
||||
---
|
||||
|
||||
### Expenditure
|
||||
Egresos/gastos.
|
||||
|
||||
---
|
||||
|
||||
### Conciliation
|
||||
Conciliaciones de facturas.
|
||||
|
||||
| Campo | Tipo | Descripcion |
|
||||
|-------|------|-------------|
|
||||
| id | bigint | ID primario |
|
||||
| invoice_id | bigint | FK a invoices |
|
||||
| fecha_conciliacion | datetime | Fecha de conciliacion |
|
||||
| usuario_id | bigint | Usuario que concilio |
|
||||
| created_at | timestamp | Fecha creacion |
|
||||
| updated_at | timestamp | Fecha actualizacion |
|
||||
|
||||
---
|
||||
|
||||
## Modelos Auxiliares
|
||||
|
||||
### ManagerOTP
|
||||
Gestion de One-Time Passwords.
|
||||
|
||||
---
|
||||
|
||||
### InvoiceRequest
|
||||
Solicitudes de facturas.
|
||||
|
||||
---
|
||||
|
||||
### Usage
|
||||
Usos de CFDI.
|
||||
|
||||
---
|
||||
|
||||
### Role
|
||||
Roles de usuario.
|
||||
|
||||
---
|
||||
|
||||
## Migraciones
|
||||
|
||||
El proyecto incluye 41 migraciones que crean toda la estructura de base de datos. Para ejecutarlas:
|
||||
|
||||
```bash
|
||||
# Ejecutar todas las migraciones
|
||||
php artisan migrate
|
||||
|
||||
# Revertir migraciones
|
||||
php artisan migrate:rollback
|
||||
|
||||
# Refrescar base de datos (elimina y recrea)
|
||||
php artisan migrate:fresh
|
||||
|
||||
# Ver estado de migraciones
|
||||
php artisan migrate:status
|
||||
```
|
||||
|
||||
## Seeders
|
||||
|
||||
```bash
|
||||
# Ejecutar todos los seeders
|
||||
php artisan db:seed
|
||||
|
||||
# Ejecutar seeder especifico
|
||||
php artisan db:seed --class=InvoiceTypeSeeder
|
||||
```
|
||||
|
||||
## Dump de Base de Datos
|
||||
|
||||
El archivo `horux360bd.sql` contiene un dump completo de la base de datos para importar:
|
||||
|
||||
```bash
|
||||
mysql -u usuario -p horux360bd < horux360bd.sql
|
||||
```
|
||||
Reference in New Issue
Block a user