Compare commits
132 Commits
integratio
...
tenant/des
| Author | SHA1 | Date | |
|---|---|---|---|
| c1bfab471c | |||
| de8da72354 | |||
| 4be94275f1 | |||
| 21b0517e6c | |||
| 7fbdc00c64 | |||
| 58c7a0f580 | |||
| a63aea0463 | |||
| b8251f3b63 | |||
| a919e9366b | |||
| 11dbcb4082 | |||
| ed321d6c6c | |||
| 573d4fe5e6 | |||
| bfdaf1c38b | |||
| 4de08ff2f2 | |||
| a4a4c9afbc | |||
| 630b49cad7 | |||
| e33ebf0af1 | |||
| a2592987f5 | |||
| 329e0b1953 | |||
| 97995ae728 | |||
| 7c7a295625 | |||
| 8359f0831f | |||
| a12b3dd0c8 | |||
| 1b22989252 | |||
| 8e94cf7856 | |||
| 5b089e71b2 | |||
| 45d74e166f | |||
| f50d3d0587 | |||
| 36c1c185ee | |||
| 0fae1ca1d7 | |||
| 1d7c484510 | |||
| cb98652e2f | |||
| 622a3eef86 | |||
| 498b4d9eac | |||
| 7d9489169d | |||
| 3eaa3f8202 | |||
| 254faedf2c | |||
| e0f0fb1a72 | |||
| 02cf3f3773 | |||
| b294e5c46e | |||
| d02b0c5551 | |||
| ee911171be | |||
| e17d1fa15e | |||
| 2a15dc92be | |||
| 3a039a6055 | |||
| 84e45bb964 | |||
| 8aa3a26ee7 | |||
| 1de08c1ca4 | |||
| 3f9bcd84c4 | |||
| 96f26e2e9d | |||
| c4b317d5fc | |||
| 3b2977a330 | |||
| 3b36abd46d | |||
| 12697c2268 | |||
| f4638bc984 | |||
| c3713c62a6 | |||
| 4a51f3afde | |||
| f1df6a5918 | |||
| dbeaf19513 | |||
| dd76d5d951 | |||
| f603a82b5e | |||
| b478c23f3b | |||
| 6858b387c3 | |||
| 893bea1492 | |||
| ec1d80dff2 | |||
| 3968a10f6a | |||
| cf2beb2ff5 | |||
| 484fa204b3 | |||
| 6dd057874a | |||
| 40cbac17c6 | |||
| 45e56c43a6 | |||
| cbb7b1c3a1 | |||
| 6b3a12b624 | |||
| 40a7dece11 | |||
| 5ec65ce3d3 | |||
| b7e1332b8c | |||
| a087a511e0 | |||
| a20b1713d3 | |||
| d56d387933 | |||
| cba32e90e7 | |||
| a674bcfabc | |||
| ace3f136e4 | |||
| 2cc72be850 | |||
| 8e3ee7eff6 | |||
| 27d4f9fac6 | |||
| 9e3163b74f | |||
| b9ad2e589f | |||
| 5416c0fd61 | |||
| 04bf03fc2e | |||
| 7c9ebc6d4d | |||
| 45553dc514 | |||
| 1c870d9cfa | |||
| 8ab94ec61f | |||
| 4eacff86bc | |||
| 5c457db1c9 | |||
| 8dc80411d7 | |||
| e16d91f3f9 | |||
| 89f6dab0c4 | |||
| ff9d7728e8 | |||
| 754aeebe3a | |||
| 5107d858cc | |||
| aa4f3303fc | |||
| 069867522a | |||
| 8a19b0136d | |||
| 8b26a2b63e | |||
| c37b8894e4 | |||
| 7b565e7fa7 | |||
| cb76d1c559 | |||
| 135a3bea3e | |||
| 9e6923e732 | |||
| 18c23a112a | |||
| c1be9ecf7f | |||
| 979ed428a2 | |||
| 7889d747d9 | |||
| f6ce85cbde | |||
| 460eec3c78 | |||
| 2b1ef5f8a9 | |||
| 5ada399adf | |||
| aed818da6e | |||
| 018f3f6c13 | |||
| 217f86f624 | |||
| 25891cefbc | |||
| c66d2019d6 | |||
| 12d496544d | |||
| c31be9c927 | |||
| 67ede1a2b4 | |||
| e778d862ba | |||
| 1438ff66c7 | |||
| 873855c85a | |||
| 855ac13990 | |||
| 87153b7839 | |||
| 528772fc96 |
53
.env.example
53
.env.example
@@ -3,11 +3,15 @@ APP_ENV=production
|
||||
APP_KEY=
|
||||
APP_DEBUG=false
|
||||
APP_URL=http://localhost
|
||||
FRONTEND_URL=http://localhost:4200
|
||||
INTEGRATION_SECRET=
|
||||
|
||||
APP_LOCALE=en
|
||||
APP_FALLBACK_LOCALE=en
|
||||
PURCHASE_CHECKOUT_EXPIRATION_MINUTES=30
|
||||
PURCHASE_QR_EXPIRATION_MINUTES=15
|
||||
PURCHASE_TELEPAGOS_EXPIRATION_MINUTES=30
|
||||
PURCHASE_TRANSFER_EXPIRATION_MINUTES=1440
|
||||
FRONTEND_URLS=http://localhost:4200
|
||||
|
||||
APP_LOCALE=es
|
||||
APP_FALLBACK_LOCALE=es
|
||||
APP_FAKER_LOCALE=en_US
|
||||
|
||||
APP_MAINTENANCE_DRIVER=file
|
||||
@@ -15,27 +19,38 @@ APP_MAINTENANCE_DRIVER=file
|
||||
|
||||
# PHP_CLI_SERVER_WORKERS=4
|
||||
|
||||
GOOGLE_CLIENT_ID=
|
||||
GOOGLE_CLIENT_SECRET=
|
||||
GOOGLE_REDIRECT_URI=http://localhost/auth/google/callback
|
||||
|
||||
|
||||
BCRYPT_ROUNDS=12
|
||||
AUTH_MAX_LOGIN_ATTEMPTS=5
|
||||
AUTH_LOGIN_ATTEMPT_WINDOW_MINUTES=30
|
||||
AUTH_LOGIN_LOCK_MINUTES=15
|
||||
AUTH_LOGIN_RATE_LIMIT_PER_MINUTE=10
|
||||
AUTH_LOGIN_IP_RATE_LIMIT_PER_MINUTE=30
|
||||
|
||||
LOG_CHANNEL=stack
|
||||
LOG_STACK=single
|
||||
LOG_DEPRECATIONS_CHANNEL=null
|
||||
LOG_LEVEL=debug
|
||||
|
||||
DB_CONNECTION=sqlite
|
||||
# DB_HOST=127.0.0.1
|
||||
# DB_PORT=3306
|
||||
# DB_DATABASE=laravel
|
||||
# DB_USERNAME=root
|
||||
# DB_PASSWORD=
|
||||
|
||||
DB_CONNECTION=mysql
|
||||
DB_HOST=127.0.0.1
|
||||
DB_PORT=3306
|
||||
DB_DATABASE=laravel
|
||||
DB_USERNAME=root
|
||||
DB_PASSWORD=
|
||||
INTEGRATION_SECRET=change-me
|
||||
SESSION_DRIVER=database
|
||||
SESSION_LIFETIME=120
|
||||
SESSION_ENCRYPT=false
|
||||
SESSION_PATH=/
|
||||
SESSION_DOMAIN=null
|
||||
|
||||
SANCTUM_STATEFUL_DOMAINS=localhost,127.0.0.1,*.shopit.com.ar
|
||||
SANCTUM_EXPIRATION=720
|
||||
SESSION_SECURE_COOKIE=false
|
||||
|
||||
BROADCAST_CONNECTION=log
|
||||
FILESYSTEM_DISK=local
|
||||
@@ -52,21 +67,19 @@ REDIS_PASSWORD=null
|
||||
REDIS_PORT=6379
|
||||
|
||||
MAIL_MAILER=smtp
|
||||
MAIL_SCHEME=smtp
|
||||
MAIL_HOST=smtp.gmail.com
|
||||
MAIL_PORT=587
|
||||
MAIL_SCHEME=null
|
||||
MAIL_HOST=127.0.0.1
|
||||
MAIL_PORT=2525
|
||||
MAIL_USERNAME=null
|
||||
MAIL_PASSWORD=null
|
||||
MAIL_FROM_ADDRESS="hello@example.com"
|
||||
MAIL_FROM_NAME="${APP_NAME}"
|
||||
|
||||
|
||||
AWS_ENDPOINT=
|
||||
AWS_ACCESS_KEY_ID=
|
||||
AWS_SECRET_ACCESS_KEY=
|
||||
AWS_DEFAULT_REGION=garage
|
||||
AWS_DEFAULT_REGION=us-east-1
|
||||
AWS_BUCKET=
|
||||
AWS_USE_PATH_STYLE_ENDPOINT=
|
||||
AWS_HTTP_VERIFY=
|
||||
|
||||
AWS_USE_PATH_STYLE_ENDPOINT=false
|
||||
AWS_HTTP_VERIFY=true
|
||||
VITE_APP_NAME="${APP_NAME}"
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
"response": []
|
||||
},
|
||||
{
|
||||
"name": "Create Tenant (JSON)",
|
||||
"name": "Create Tenant OnTicket (JSON)",
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"header": [
|
||||
@@ -51,7 +51,7 @@
|
||||
],
|
||||
"body": {
|
||||
"mode": "raw",
|
||||
"raw": "{\n \"codigo\": \"acme\",\n \"nombre\": \"Acme\",\n \"dominio\": \"acme.test\",\n \"primary_color\": \"#111111\",\n \"secondary_color\": \"#222222\",\n \"danger_color\": \"#ff0000\",\n \"header_bg_color\": \"#333333\",\n \"footer_bg_color\": \"#333333\",\n \"header_logo\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==\",\n \"footer_logo\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==\"\n}"
|
||||
"raw": "{\n \"codigo\": \"festival-demo\",\n \"nombre\": \"Festival Demo\",\n \"dominio\": \"festival-demo.test\",\n \"primary_color\": \"#111111\",\n \"secondary_color\": \"#222222\",\n \"danger_color\": \"#ff0000\",\n \"success_color\": \"#00aa55\",\n \"header_bg_color\": \"#333333\",\n \"footer_bg_color\": \"#333333\",\n \"header_logo\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==\",\n \"footer_logo\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==\",\n \"search_product_layout\": \"column_with_image\",\n \"search_group_layout\": \"paginated\",\n \"search_items_per_page\": 12,\n \"website_type_code\": \"onticket\",\n \"extras\": {\n \"heroConfig\": {\n \"title_html\": \"<h1>Festival Demo</h1>\",\n \"description_html\": \"<p>Una experiencia inolvidable</p>\",\n \"button_text\": \"Comprar entradas\",\n \"button_href\": \"/tickets\",\n \"background_image_id\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==\"\n },\n \"eventConfig\": {\n \"title\": \"Festival Demo\",\n \"location\": \"Buenos Aires\",\n \"dates_text\": \"10 y 11 de octubre de 2026\",\n \"dates\": [\n \"2026-10-10\",\n \"2026-10-11\"\n ]\n }\n }\n}"
|
||||
},
|
||||
"url": {
|
||||
"raw": "{{base_url}}/api/tenants",
|
||||
@@ -67,7 +67,7 @@
|
||||
"response": []
|
||||
},
|
||||
{
|
||||
"name": "Create Tenant (Form Data)",
|
||||
"name": "Create Tenant ShopIt (Form Data)",
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"header": [
|
||||
@@ -110,6 +110,11 @@
|
||||
"value": "#ff0000",
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"key": "success_color",
|
||||
"value": "#00aa55",
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"key": "header_bg_color",
|
||||
"value": "#333333",
|
||||
@@ -129,6 +134,32 @@
|
||||
"key": "footer_logo",
|
||||
"type": "file",
|
||||
"src": []
|
||||
},
|
||||
{
|
||||
"key": "search_product_layout",
|
||||
"value": "column_with_image",
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"key": "search_group_layout",
|
||||
"value": "paginated",
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"key": "search_items_per_page",
|
||||
"value": "12",
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"key": "website_type_code",
|
||||
"value": "shopit",
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"key": "extras[carousel][]",
|
||||
"type": "file",
|
||||
"src": [],
|
||||
"description": "Se puede repetir esta key hasta 10 veces. También acepta una imagen base64 o el UUID de un attachment."
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -157,15 +188,18 @@
|
||||
}
|
||||
],
|
||||
"url": {
|
||||
"raw": "{{base_url}}/api/tenants/bootstrap/{{tenant_domain}}",
|
||||
"raw": "{{base_url}}/api/tenants/bootstrap?dominio={{tenant_domain}}&path={{tenant_path}}",
|
||||
"host": [
|
||||
"{{base_url}}"
|
||||
],
|
||||
"path": [
|
||||
"api",
|
||||
"tenants",
|
||||
"bootstrap",
|
||||
"{{tenant_domain}}"
|
||||
"bootstrap"
|
||||
],
|
||||
"query": [
|
||||
{"key": "dominio", "value": "{{tenant_domain}}"},
|
||||
{"key": "path", "value": "{{tenant_path}}"}
|
||||
]
|
||||
}
|
||||
},
|
||||
@@ -1371,6 +1405,11 @@
|
||||
"value": "localhost",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"key": "tenant_path",
|
||||
"value": "/",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"key": "tenant_id",
|
||||
"value": "1",
|
||||
|
||||
@@ -41,15 +41,18 @@
|
||||
}
|
||||
],
|
||||
"url": {
|
||||
"raw": "{{base_url}}/api/tenants/bootstrap/acme.com",
|
||||
"raw": "{{base_url}}/api/tenants/bootstrap?dominio=acme.com&path=/",
|
||||
"host": [
|
||||
"{{base_url}}"
|
||||
],
|
||||
"path": [
|
||||
"api",
|
||||
"tenants",
|
||||
"bootstrap",
|
||||
"acme.com"
|
||||
"bootstrap"
|
||||
],
|
||||
"query": [
|
||||
{"key": "dominio", "value": "acme.com"},
|
||||
{"key": "path", "value": "/"}
|
||||
]
|
||||
}
|
||||
},
|
||||
|
||||
29
app/Domains/Attachable/documentacion/README.md
Normal file
29
app/Domains/Attachable/documentacion/README.md
Normal file
@@ -0,0 +1,29 @@
|
||||
# Dominio Attachable
|
||||
|
||||
## Propósito
|
||||
|
||||
Centraliza el almacenamiento y la metadata de archivos adjuntos. Acepta archivos subidos o contenido Base64, los persiste en S3 y registra su tipo, MIME, extensión, tamaño, nombre original y clave única.
|
||||
|
||||
## Componentes principales
|
||||
|
||||
- `Models/Attachment.php`: representa un adjunto y genera URL temporales de acceso.
|
||||
- `Services/AttachmentService.php`: almacena, copia y elimina archivos, compensando en S3 si falla la escritura en base de datos.
|
||||
- `Enums/AttachmentType.php`: clasifica imágenes, videos, PDF, audio, documentos y otros archivos.
|
||||
- `Exceptions/AttachmentStorageException.php`: expresa fallos propios del almacenamiento.
|
||||
|
||||
## Flujo principal
|
||||
|
||||
1. El consumidor entrega un `UploadedFile` o una cadena Base64 y un directorio.
|
||||
2. El servicio valida el contenido, detecta MIME/extensión y genera una clave UUID.
|
||||
3. El archivo se guarda en el disco `s3`.
|
||||
4. Se crea el registro `Attachment`; ante error se elimina el objeto que había sido subido.
|
||||
|
||||
## API y dependencias
|
||||
|
||||
No expone rutas HTTP propias. Lo consumen otros dominios, especialmente `Catalog` y `Tenant`. Depende de Laravel Storage, Symfony Mime y del modelo `Attachment`.
|
||||
|
||||
## Consideraciones
|
||||
|
||||
- El directorio no puede quedar vacío después de normalizarlo.
|
||||
- La eliminación se considera fallida si S3 no confirma el borrado.
|
||||
- Las URL generadas son temporales; el vencimiento predeterminado es de 10 minutos.
|
||||
42
app/Domains/Auth/Controllers/AdminAppLoginController.php
Normal file
42
app/Domains/Auth/Controllers/AdminAppLoginController.php
Normal file
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Controllers;
|
||||
|
||||
use App\Domains\Auth\Requests\AdminAppLoginRequest;
|
||||
use App\Domains\Auth\Resources\UserResource;
|
||||
use App\Domains\Auth\Services\PasswordLoginService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class AdminAppLoginController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly PasswordLoginService $passwordLoginService,
|
||||
) {}
|
||||
|
||||
public function __invoke(AdminAppLoginRequest $request): JsonResponse
|
||||
{
|
||||
$credentials = $request->validated();
|
||||
$user = $this->passwordLoginService->authenticateAdminApp(
|
||||
$credentials['email'],
|
||||
$credentials['password'],
|
||||
$request->ip(),
|
||||
$request->userAgent(),
|
||||
);
|
||||
|
||||
$expirationMinutes = (int) config('sanctum.expiration');
|
||||
$token = $user->createToken(
|
||||
'adminapp-token',
|
||||
['adminapp'],
|
||||
now()->addMinutes($expirationMinutes),
|
||||
)->plainTextToken;
|
||||
|
||||
return response()->json([
|
||||
'code' => 'auth.login_success',
|
||||
'message' => __('api.auth.login_success'),
|
||||
'token' => $token,
|
||||
'token_type' => 'Bearer',
|
||||
'user' => UserResource::make($user),
|
||||
]);
|
||||
}
|
||||
}
|
||||
26
app/Domains/Auth/Controllers/AdminAppMeController.php
Normal file
26
app/Domains/Auth/Controllers/AdminAppMeController.php
Normal file
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Controllers;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Auth\Resources\AdminAppMeResource;
|
||||
use App\Domains\Auth\Services\AdminAppContextService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class AdminAppMeController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly AdminAppContextService $adminAppContextService,
|
||||
) {}
|
||||
|
||||
public function __invoke(Request $request): AdminAppMeResource
|
||||
{
|
||||
/** @var User $user */
|
||||
$user = $request->user();
|
||||
|
||||
return AdminAppMeResource::make(
|
||||
$this->adminAppContextService->load($user)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Controllers;
|
||||
|
||||
use App\Domains\Auth\Models\ResetPasswordAttempt;
|
||||
use App\Domains\Auth\Requests\AdminAppCreateResetPasswordAttemptRequest;
|
||||
use App\Domains\Auth\Services\ResetPasswordAttemptService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class CreateAdminAppResetPasswordAttemptController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ResetPasswordAttemptService $resetPasswordAttemptService,
|
||||
) {}
|
||||
|
||||
public function __invoke(AdminAppCreateResetPasswordAttemptRequest $request): JsonResponse
|
||||
{
|
||||
$this->resetPasswordAttemptService->createForAdminAppEmail(
|
||||
$request->validated('email'),
|
||||
);
|
||||
|
||||
return response()->json([
|
||||
'code' => 'auth.password_reset_requested',
|
||||
'message' => __('api.auth.password_reset_requested'),
|
||||
'status' => ResetPasswordAttempt::STATUS_PENDING,
|
||||
], 202);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Controllers;
|
||||
|
||||
use App\Domains\Auth\Models\ResetPasswordAttempt;
|
||||
use App\Domains\Auth\Requests\CreateResetPasswordAttemptRequest;
|
||||
use App\Domains\Auth\Services\ResetPasswordAttemptService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class CreateResetPasswordAttemptController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ResetPasswordAttemptService $resetPasswordAttemptService,
|
||||
) {}
|
||||
|
||||
public function __invoke(CreateResetPasswordAttemptRequest $request): JsonResponse
|
||||
{
|
||||
$data = $request->validated();
|
||||
|
||||
$this->resetPasswordAttemptService->createForEmail(
|
||||
$data['email'],
|
||||
$data['tenant_codigo'],
|
||||
);
|
||||
|
||||
return response()->json([
|
||||
'code' => 'auth.password_reset_requested',
|
||||
'message' => __('api.auth.password_reset_requested'),
|
||||
'status' => ResetPasswordAttempt::STATUS_PENDING,
|
||||
], 202);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Controllers;
|
||||
|
||||
use App\Domains\Auth\Models\ResetPasswordAttempt;
|
||||
use App\Domains\Auth\Requests\ScannerCreateResetPasswordAttemptRequest;
|
||||
use App\Domains\Auth\Services\ResetPasswordAttemptService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class CreateScannerResetPasswordAttemptController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ResetPasswordAttemptService $resetPasswordAttemptService,
|
||||
) {}
|
||||
|
||||
public function __invoke(ScannerCreateResetPasswordAttemptRequest $request): JsonResponse
|
||||
{
|
||||
$this->resetPasswordAttemptService->createForScannerEmail(
|
||||
$request->validated('email'),
|
||||
);
|
||||
|
||||
return response()->json([
|
||||
'code' => 'auth.password_reset_requested',
|
||||
'message' => __('api.auth.password_reset_requested'),
|
||||
'status' => ResetPasswordAttempt::STATUS_PENDING,
|
||||
], 202);
|
||||
}
|
||||
}
|
||||
23
app/Domains/Auth/Controllers/GoogleAuthController.php
Normal file
23
app/Domains/Auth/Controllers/GoogleAuthController.php
Normal file
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Controllers;
|
||||
|
||||
use App\Domains\Auth\Services\GoogleAuthService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class GoogleAuthController extends Controller
|
||||
{
|
||||
public function __construct(private readonly GoogleAuthService $googleAuthService) {}
|
||||
|
||||
public function redirect(Request $request): RedirectResponse
|
||||
{
|
||||
return $this->googleAuthService->redirect($request);
|
||||
}
|
||||
|
||||
public function callback(Request $request): RedirectResponse
|
||||
{
|
||||
return $this->googleAuthService->callback($request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Controllers;
|
||||
|
||||
use App\Domains\Auth\Requests\GoogleTokenExchangeRequest;
|
||||
use App\Domains\Auth\Resources\UserResource;
|
||||
use App\Domains\Auth\Services\GoogleAuthService;
|
||||
use App\Domains\Cart\Services\GuestCartMergeService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\Cookie;
|
||||
|
||||
class GoogleTokenExchangeController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly GoogleAuthService $googleAuthService,
|
||||
private readonly GuestCartMergeService $guestCartMergeService,
|
||||
) {}
|
||||
|
||||
public function __invoke(GoogleTokenExchangeRequest $request): JsonResponse
|
||||
{
|
||||
$authentication = $this->googleAuthService->exchange(
|
||||
$request->validated('oauth_code'),
|
||||
$request->validated('tenant_codigo'),
|
||||
);
|
||||
|
||||
$guestTokenCookie = $request->cookie('guest_token');
|
||||
$guestToken = is_string($guestTokenCookie) && $guestTokenCookie !== ''
|
||||
? $guestTokenCookie
|
||||
: null;
|
||||
$this->guestCartMergeService->merge(
|
||||
$authentication['tenant_codigo'],
|
||||
$authentication['user'],
|
||||
$guestToken,
|
||||
);
|
||||
|
||||
$response = response()->json([
|
||||
'code' => 'auth.login_success',
|
||||
'message' => __('api.auth.login_success'),
|
||||
'token' => $authentication['token'],
|
||||
'token_type' => 'Bearer',
|
||||
'user' => UserResource::make($authentication['user']),
|
||||
]);
|
||||
|
||||
if ($guestToken !== null) {
|
||||
$response->withCookie(Cookie::forget('guest_token'));
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
@@ -3,28 +3,30 @@
|
||||
namespace App\Domains\Auth\Controllers;
|
||||
|
||||
use App\Domains\Auth\Requests\LoginUserRequest;
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Auth\Resources\UserResource;
|
||||
use App\Domains\Auth\Services\PasswordLoginService;
|
||||
use App\Domains\Cart\Services\GuestCartMergeService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Illuminate\Support\Facades\Cookie;
|
||||
|
||||
class LoginController extends Controller
|
||||
{
|
||||
/**
|
||||
* @throws ValidationException
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly GuestCartMergeService $guestCartMergeService,
|
||||
private readonly PasswordLoginService $passwordLoginService,
|
||||
) {}
|
||||
|
||||
public function __invoke(LoginUserRequest $request): JsonResponse
|
||||
{
|
||||
$credentials = $request->validated();
|
||||
$user = User::query()->where('email', $credentials['email'])->first();
|
||||
|
||||
if (! $user || ! Hash::check($credentials['password'], $user->password)) {
|
||||
throw ValidationException::withMessages([
|
||||
'email' => 'Email o Contraseña incorrectos.',
|
||||
]);
|
||||
}
|
||||
$user = $this->passwordLoginService->authenticate(
|
||||
$credentials['email'],
|
||||
$credentials['password'],
|
||||
$credentials['tenant_codigo'],
|
||||
$request->ip(),
|
||||
$request->userAgent(),
|
||||
);
|
||||
|
||||
$expirationMinutes = (int) config('sanctum.expiration');
|
||||
$token = $user->createToken(
|
||||
@@ -33,11 +35,28 @@ class LoginController extends Controller
|
||||
now()->addMinutes($expirationMinutes),
|
||||
)->plainTextToken;
|
||||
|
||||
return response()->json([
|
||||
'message' => 'Sesion iniciada correctamente.',
|
||||
$guestTokenCookie = $request->cookie('guest_token');
|
||||
$guestToken = is_string($guestTokenCookie) && $guestTokenCookie !== ''
|
||||
? $guestTokenCookie
|
||||
: null;
|
||||
$this->guestCartMergeService->merge(
|
||||
$credentials['tenant_codigo'],
|
||||
$user,
|
||||
$guestToken,
|
||||
);
|
||||
|
||||
$response = response()->json([
|
||||
'code' => 'auth.login_success',
|
||||
'message' => __('api.auth.login_success'),
|
||||
'token' => $token,
|
||||
'token_type' => 'Bearer',
|
||||
'user' => UserResource::make($user),
|
||||
]);
|
||||
|
||||
if ($guestToken !== null) {
|
||||
$response->withCookie(Cookie::forget('guest_token'));
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,7 +23,8 @@ class LogoutController extends Controller
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'message' => 'Sesion cerrada correctamente.',
|
||||
'code' => 'auth.logout_success',
|
||||
'message' => __('api.auth.logout_success'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,15 +12,17 @@ class RegisterController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
protected RegisterUserService $registerUserService,
|
||||
) {
|
||||
}
|
||||
) {}
|
||||
|
||||
public function __invoke(RegisterUserRequest $request): JsonResponse
|
||||
{
|
||||
$user = $this->registerUserService->register($request->validated());
|
||||
|
||||
return UserResource::make($user)
|
||||
->additional(['message' => 'Usuario registrado correctamente.'])
|
||||
->additional([
|
||||
'code' => 'auth.register_success',
|
||||
'message' => __('api.auth.register_success'),
|
||||
])
|
||||
->response()
|
||||
->setStatusCode(201);
|
||||
}
|
||||
|
||||
41
app/Domains/Auth/Controllers/ResetPasswordController.php
Normal file
41
app/Domains/Auth/Controllers/ResetPasswordController.php
Normal file
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Controllers;
|
||||
|
||||
use App\Domains\Auth\Models\ResetPasswordAttempt;
|
||||
use App\Domains\Auth\Requests\ResetPasswordRequest;
|
||||
use App\Domains\Auth\Services\ResetPasswordAttemptService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class ResetPasswordController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ResetPasswordAttemptService $resetPasswordAttemptService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @throws ValidationException
|
||||
*/
|
||||
public function __invoke(ResetPasswordRequest $request): JsonResponse
|
||||
{
|
||||
$data = $request->validated();
|
||||
|
||||
if (! $this->resetPasswordAttemptService->resetPassword(
|
||||
$data['email'],
|
||||
$data['codigo'],
|
||||
$data['password'],
|
||||
)) {
|
||||
throw ValidationException::withMessages([
|
||||
'codigo' => __('api.auth.password_reset_invalid'),
|
||||
]);
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'code' => 'auth.password_updated',
|
||||
'message' => __('api.auth.password_updated'),
|
||||
'status' => ResetPasswordAttempt::STATUS_USED,
|
||||
]);
|
||||
}
|
||||
}
|
||||
42
app/Domains/Auth/Controllers/ScannerLoginController.php
Normal file
42
app/Domains/Auth/Controllers/ScannerLoginController.php
Normal file
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Controllers;
|
||||
|
||||
use App\Domains\Auth\Requests\ScannerLoginRequest;
|
||||
use App\Domains\Auth\Resources\UserResource;
|
||||
use App\Domains\Auth\Services\PasswordLoginService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class ScannerLoginController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly PasswordLoginService $passwordLoginService,
|
||||
) {}
|
||||
|
||||
public function __invoke(ScannerLoginRequest $request): JsonResponse
|
||||
{
|
||||
$credentials = $request->validated();
|
||||
$user = $this->passwordLoginService->authenticateScanner(
|
||||
$credentials['email'],
|
||||
$credentials['password'],
|
||||
$request->ip(),
|
||||
$request->userAgent(),
|
||||
);
|
||||
|
||||
$expirationMinutes = (int) config('sanctum.expiration');
|
||||
$token = $user->createToken(
|
||||
'scanner-token',
|
||||
['scanner'],
|
||||
now()->addMinutes($expirationMinutes),
|
||||
)->plainTextToken;
|
||||
|
||||
return response()->json([
|
||||
'code' => 'auth.login_success',
|
||||
'message' => __('api.auth.login_success'),
|
||||
'token' => $token,
|
||||
'token_type' => 'Bearer',
|
||||
'user' => UserResource::make($user),
|
||||
]);
|
||||
}
|
||||
}
|
||||
24
app/Domains/Auth/Controllers/ScannerMeController.php
Normal file
24
app/Domains/Auth/Controllers/ScannerMeController.php
Normal file
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Controllers;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Auth\Resources\ScannerMeResource;
|
||||
use App\Domains\Auth\Services\ScannerContextService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class ScannerMeController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ScannerContextService $scannerContextService,
|
||||
) {}
|
||||
|
||||
public function __invoke(Request $request): ScannerMeResource
|
||||
{
|
||||
/** @var User $user */
|
||||
$user = $request->user();
|
||||
|
||||
return ScannerMeResource::make($this->scannerContextService->load($user));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Controllers;
|
||||
|
||||
use App\Domains\Auth\Models\ResetPasswordAttempt;
|
||||
use App\Domains\Auth\Requests\ValidateResetPasswordAttemptRequest;
|
||||
use App\Domains\Auth\Services\ResetPasswordAttemptService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class ValidateResetPasswordAttemptController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ResetPasswordAttemptService $resetPasswordAttemptService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @throws ValidationException
|
||||
*/
|
||||
public function __invoke(ValidateResetPasswordAttemptRequest $request): JsonResponse
|
||||
{
|
||||
$data = $request->validated();
|
||||
|
||||
if (! $this->resetPasswordAttemptService->validateCode(
|
||||
$data['email'],
|
||||
$data['codigo'],
|
||||
)) {
|
||||
throw ValidationException::withMessages([
|
||||
'codigo' => __('api.auth.reset_code_invalid'),
|
||||
]);
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'code' => 'auth.reset_code_valid',
|
||||
'message' => __('api.auth.reset_code_valid'),
|
||||
'status' => ResetPasswordAttempt::STATUS_VALIDATED,
|
||||
]);
|
||||
}
|
||||
}
|
||||
20
app/Domains/Auth/Exceptions/AccountLockedException.php
Normal file
20
app/Domains/Auth/Exceptions/AccountLockedException.php
Normal file
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Exceptions;
|
||||
|
||||
use Carbon\CarbonImmutable;
|
||||
use RuntimeException;
|
||||
|
||||
class AccountLockedException extends RuntimeException
|
||||
{
|
||||
public function __construct(
|
||||
public readonly CarbonImmutable $lockedUntil,
|
||||
) {
|
||||
parent::__construct('The account is temporarily locked.');
|
||||
}
|
||||
|
||||
public function retryAfterSeconds(): int
|
||||
{
|
||||
return max(1, (int) now()->diffInSeconds($this->lockedUntil, false));
|
||||
}
|
||||
}
|
||||
40
app/Domains/Auth/Models/LoginAttempt.php
Normal file
40
app/Domains/Auth/Models/LoginAttempt.php
Normal file
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable([
|
||||
'user_id',
|
||||
'email_fingerprint',
|
||||
'tenant_codigo',
|
||||
'outcome',
|
||||
'ip_address',
|
||||
'user_agent',
|
||||
])]
|
||||
class LoginAttempt extends Model
|
||||
{
|
||||
public const OUTCOME_SUCCESS = 'success';
|
||||
|
||||
public const OUTCOME_INVALID_CREDENTIALS = 'invalid_credentials';
|
||||
|
||||
public const OUTCOME_ACCOUNT_LOCKED = 'account_locked';
|
||||
|
||||
public const UPDATED_AT = null;
|
||||
|
||||
/** @return BelongsTo<User, $this> */
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'user_id' => 'integer',
|
||||
'created_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
}
|
||||
42
app/Domains/Auth/Models/ResetPasswordAttempt.php
Normal file
42
app/Domains/Auth/Models/ResetPasswordAttempt.php
Normal file
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Hidden;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable(['user_id', 'codigo', 'reason', 'status'])]
|
||||
#[Hidden(['codigo'])]
|
||||
class ResetPasswordAttempt extends Model
|
||||
{
|
||||
public const REASON_MANUAL = 'manual';
|
||||
|
||||
public const REASON_ACCOUNT_LOCKED = 'account_locked';
|
||||
|
||||
public const REASON_STAFF_CREATED = 'staff_created';
|
||||
|
||||
public const STATUS_PENDING = 'pending';
|
||||
|
||||
public const STATUS_VALIDATED = 'validated';
|
||||
|
||||
public const STATUS_USED = 'used';
|
||||
|
||||
public const STATUS_EXPIRED = 'expired';
|
||||
|
||||
public $timestamps = false;
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'user_id' => 'integer',
|
||||
];
|
||||
}
|
||||
|
||||
/** @return BelongsTo<User, $this> */
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
}
|
||||
@@ -2,26 +2,86 @@
|
||||
|
||||
namespace App\Domains\Auth\Models;
|
||||
|
||||
use App\Domains\Authorization\Enums\RoleCode;
|
||||
use App\Domains\Authorization\Models\Role;
|
||||
use App\Domains\Catalog\Models\Category;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Database\Factories\UserFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Hidden;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||
use Illuminate\Notifications\Notifiable;
|
||||
use Laravel\Sanctum\HasApiTokens;
|
||||
|
||||
#[Fillable(['nombre_apellido', 'email', 'password', 'dni', 'telefono'])]
|
||||
#[Fillable(['nombre_apellido', 'email', 'password', 'dni', 'telefono', 'google_id', 'rol_codigo', 'tenant_codigo'])]
|
||||
#[Hidden(['password', 'remember_token'])]
|
||||
class User extends Authenticatable
|
||||
{
|
||||
/** @use HasFactory<UserFactory> */
|
||||
use HasApiTokens, HasFactory, Notifiable;
|
||||
|
||||
protected $attributes = [
|
||||
'rol_codigo' => RoleCode::User->value,
|
||||
];
|
||||
|
||||
protected static function newFactory(): UserFactory
|
||||
{
|
||||
return UserFactory::new();
|
||||
}
|
||||
|
||||
/** @return HasMany<ResetPasswordAttempt, $this> */
|
||||
public function resetPasswordAttempts(): HasMany
|
||||
{
|
||||
return $this->hasMany(ResetPasswordAttempt::class);
|
||||
}
|
||||
|
||||
/** @return HasMany<LoginAttempt, $this> */
|
||||
public function loginAttempts(): HasMany
|
||||
{
|
||||
return $this->hasMany(LoginAttempt::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Role, $this>
|
||||
*/
|
||||
public function role(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Role::class, 'rol_codigo', 'codigo');
|
||||
}
|
||||
|
||||
public function hasPermission(string $permissionCode): bool
|
||||
{
|
||||
return $this->role()
|
||||
->whereHas(
|
||||
'permissions',
|
||||
fn ($query) => $query->where('permisos.codigo', $permissionCode)
|
||||
)
|
||||
->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Tenant, $this>
|
||||
*/
|
||||
public function tenant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Tenant::class, 'tenant_codigo', 'codigo');
|
||||
}
|
||||
|
||||
/** @return BelongsToMany<Category, $this> */
|
||||
public function scanCategories(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(
|
||||
Category::class,
|
||||
'category_scanners',
|
||||
'user_id',
|
||||
'categoria_id',
|
||||
)->withTimestamps();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
@@ -30,6 +90,9 @@ class User extends Authenticatable
|
||||
return [
|
||||
'email_verified_at' => 'datetime',
|
||||
'password' => 'hashed',
|
||||
'failed_login_attempts' => 'integer',
|
||||
'last_failed_login_at' => 'datetime',
|
||||
'locked_until' => 'datetime',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class AdminAppCreateResetPasswordAttemptRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
$email = $this->input('email');
|
||||
|
||||
if (is_string($email)) {
|
||||
$this->merge(['email' => Str::lower(trim($email))]);
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'email' => ['required', 'string', 'email', 'max:255'],
|
||||
];
|
||||
}
|
||||
}
|
||||
36
app/Domains/Auth/Requests/AdminAppLoginRequest.php
Normal file
36
app/Domains/Auth/Requests/AdminAppLoginRequest.php
Normal file
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class AdminAppLoginRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
$email = $this->input('email');
|
||||
|
||||
if (is_string($email)) {
|
||||
$this->merge([
|
||||
'email' => Str::lower(trim($email)),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'email' => ['required', 'string', 'email', 'max:255'],
|
||||
'password' => ['required', 'string'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class CreateResetPasswordAttemptRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
$email = $this->input('email');
|
||||
|
||||
if (is_string($email)) {
|
||||
$this->merge([
|
||||
'email' => Str::lower(trim($email)),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'tenant_codigo' => ['required', 'string', Rule::exists('tenants', 'codigo')],
|
||||
'email' => ['required', 'string', 'email', 'max:255'],
|
||||
];
|
||||
}
|
||||
}
|
||||
22
app/Domains/Auth/Requests/GoogleTokenExchangeRequest.php
Normal file
22
app/Domains/Auth/Requests/GoogleTokenExchangeRequest.php
Normal file
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class GoogleTokenExchangeRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string, array<int, string>> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'oauth_code' => ['required', 'uuid'],
|
||||
'tenant_codigo' => ['required', 'string', 'exists:tenants,codigo'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Domains\Auth\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class LoginUserRequest extends FormRequest
|
||||
{
|
||||
@@ -11,6 +12,17 @@ class LoginUserRequest extends FormRequest
|
||||
return true;
|
||||
}
|
||||
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
$email = $this->input('email');
|
||||
|
||||
if (is_string($email)) {
|
||||
$this->merge([
|
||||
'email' => Str::lower(trim($email)),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
@@ -19,6 +31,7 @@ class LoginUserRequest extends FormRequest
|
||||
return [
|
||||
'email' => ['required', 'string', 'email', 'max:255'],
|
||||
'password' => ['required', 'string'],
|
||||
'tenant_codigo' => ['required', 'string', 'exists:tenants,codigo'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace App\Domains\Auth\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\Rules\Password;
|
||||
|
||||
class RegisterUserRequest extends FormRequest
|
||||
{
|
||||
@@ -18,9 +19,10 @@ class RegisterUserRequest extends FormRequest
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'tenant_codigo' => ['nullable', 'string', Rule::exists('tenants', 'codigo')],
|
||||
'nombre_apellido' => ['required', 'string', 'max:255'],
|
||||
'email' => ['required', 'string', 'email', 'max:255', Rule::unique('users', 'email')],
|
||||
'password' => ['required', 'string', 'confirmed', \Illuminate\Validation\Rules\Password::min(8)->mixedCase()->symbols()],
|
||||
'password' => ['required', 'string', 'confirmed', Password::min(8)->mixedCase()->symbols()],
|
||||
'dni' => ['nullable', 'string', 'max:255'],
|
||||
'telefono' => ['nullable', 'string', 'max:255'],
|
||||
];
|
||||
|
||||
43
app/Domains/Auth/Requests/ResetPasswordRequest.php
Normal file
43
app/Domains/Auth/Requests/ResetPasswordRequest.php
Normal file
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rules\Password;
|
||||
|
||||
class ResetPasswordRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
$email = $this->input('email');
|
||||
|
||||
if (is_string($email)) {
|
||||
$this->merge([
|
||||
'email' => Str::lower(trim($email)),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'email' => ['required', 'string', 'email', 'max:255'],
|
||||
'codigo' => ['required', 'string', 'regex:/^\d{4}$/'],
|
||||
'password' => [
|
||||
'required',
|
||||
'string',
|
||||
'confirmed',
|
||||
Password::min(8)->mixedCase()->symbols(),
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class ScannerCreateResetPasswordAttemptRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
$email = $this->input('email');
|
||||
|
||||
if (is_string($email)) {
|
||||
$this->merge(['email' => Str::lower(trim($email))]);
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'email' => ['required', 'string', 'email', 'max:255'],
|
||||
];
|
||||
}
|
||||
}
|
||||
5
app/Domains/Auth/Requests/ScannerLoginRequest.php
Normal file
5
app/Domains/Auth/Requests/ScannerLoginRequest.php
Normal file
@@ -0,0 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Requests;
|
||||
|
||||
class ScannerLoginRequest extends AdminAppLoginRequest {}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class ValidateResetPasswordAttemptRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
$email = $this->input('email');
|
||||
|
||||
if (is_string($email)) {
|
||||
$this->merge([
|
||||
'email' => Str::lower(trim($email)),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'email' => ['required', 'string', 'email', 'max:255'],
|
||||
'codigo' => ['required', 'string', 'regex:/^\d{4}$/'],
|
||||
];
|
||||
}
|
||||
}
|
||||
25
app/Domains/Auth/Resources/AdminAppMeResource.php
Normal file
25
app/Domains/Auth/Resources/AdminAppMeResource.php
Normal file
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Resources;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Tenant\Resources\TenantResource;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/**
|
||||
* @mixin User
|
||||
*/
|
||||
class AdminAppMeResource extends JsonResource
|
||||
{
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'user' => UserResource::make($this->resource),
|
||||
'tenant' => TenantResource::make($this->tenant),
|
||||
];
|
||||
}
|
||||
}
|
||||
21
app/Domains/Auth/Resources/ScannerMeResource.php
Normal file
21
app/Domains/Auth/Resources/ScannerMeResource.php
Normal file
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Resources;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Tenant\Resources\TenantResource;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin User */
|
||||
class ScannerMeResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'user' => UserResource::make($this->resource),
|
||||
'tenant' => TenantResource::make($this->tenant),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,12 @@
|
||||
|
||||
namespace App\Domains\Auth\Resources;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/**
|
||||
* @mixin \App\Domains\Auth\Models\User
|
||||
* @mixin User
|
||||
*/
|
||||
class UserResource extends JsonResource
|
||||
{
|
||||
@@ -21,6 +22,8 @@ class UserResource extends JsonResource
|
||||
'email' => $this->email,
|
||||
'dni' => $this->dni,
|
||||
'telefono' => $this->telefono,
|
||||
'rol_codigo' => $this->rol_codigo,
|
||||
'tenant_codigo' => $this->tenant_codigo,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
26
app/Domains/Auth/Services/AdminAppContextService.php
Normal file
26
app/Domains/Auth/Services/AdminAppContextService.php
Normal file
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Services;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Authorization\Enums\RoleCode;
|
||||
|
||||
class AdminAppContextService
|
||||
{
|
||||
public function load(User $user): User
|
||||
{
|
||||
$tenant = $user->tenant()
|
||||
->with([
|
||||
'menues' => fn ($query) => $query
|
||||
->whereHas(
|
||||
'roles',
|
||||
fn ($query) => $query->where('codigo', RoleCode::AdminApp->value)
|
||||
),
|
||||
])
|
||||
->firstOrFail();
|
||||
|
||||
$user->setRelation('tenant', $tenant);
|
||||
|
||||
return $user;
|
||||
}
|
||||
}
|
||||
173
app/Domains/Auth/Services/GoogleAuthService.php
Normal file
173
app/Domains/Auth/Services/GoogleAuthService.php
Normal file
@@ -0,0 +1,173 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Services;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Notification\Events\UserRegistered;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Tenant\Support\TenantDomainNormalizer;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Laravel\Socialite\Contracts\User as SocialiteUser;
|
||||
use Laravel\Socialite\Facades\Socialite;
|
||||
|
||||
class GoogleAuthService
|
||||
{
|
||||
public function redirect(Request $request): RedirectResponse
|
||||
{
|
||||
$tenantCode = $request->string('tenant')->toString();
|
||||
$returnUrl = $request->string('return_url')->toString();
|
||||
|
||||
$tenant = Tenant::query()->where('codigo', $tenantCode)->first();
|
||||
|
||||
if (! $tenant || ! $this->isTenantReturnUrl($returnUrl, $tenant)) {
|
||||
throw ValidationException::withMessages([
|
||||
'tenant' => __('api.auth.invalid_tenant_or_return_url'),
|
||||
]);
|
||||
}
|
||||
|
||||
$state = (string) Str::uuid();
|
||||
Cache::put("google-oauth-context:{$state}", [
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
'return_url' => rtrim($returnUrl, '/'),
|
||||
], now()->addMinutes(10));
|
||||
|
||||
return Socialite::driver('google')
|
||||
->scopes(['openid', 'profile', 'email'])
|
||||
->stateless()
|
||||
->with(['state' => $state])
|
||||
->redirect();
|
||||
}
|
||||
|
||||
public function callback(Request $request): RedirectResponse
|
||||
{
|
||||
$state = $request->string('state')->toString();
|
||||
|
||||
/** @var array{tenant_codigo?: string, return_url?: string}|null $context */
|
||||
$context = Str::isUuid($state) ? Cache::pull("google-oauth-context:{$state}") : null;
|
||||
|
||||
if (! is_array($context) || ! isset($context['tenant_codigo'], $context['return_url'])) {
|
||||
abort(400, __('api.auth.request_expired'));
|
||||
}
|
||||
|
||||
$tenant = Tenant::query()->where('codigo', $context['tenant_codigo'])->first();
|
||||
|
||||
if (! $tenant || ! $this->isTenantReturnUrl($context['return_url'], $tenant)) {
|
||||
abort(400, __('api.auth.invalid_return_url'));
|
||||
}
|
||||
|
||||
/** @var SocialiteUser $googleUser */
|
||||
$googleUser = Socialite::driver('google')->stateless()->user();
|
||||
$user = $this->resolveUser($googleUser, $tenant);
|
||||
$token = $user->createToken(
|
||||
'google-oauth',
|
||||
['*'],
|
||||
now()->addMinutes((int) config('sanctum.expiration')),
|
||||
)->plainTextToken;
|
||||
|
||||
$exchangeCode = (string) Str::uuid();
|
||||
Cache::put("google-oauth-exchange:{$exchangeCode}", [
|
||||
'user_id' => $user->id,
|
||||
'token' => $token,
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
], now()->addMinutes(5));
|
||||
|
||||
return redirect()->to($context['return_url'].'/login?'.http_build_query([
|
||||
'oauth_code' => $exchangeCode,
|
||||
]));
|
||||
}
|
||||
|
||||
/** @return array{user: User, token: string, tenant_codigo: string} */
|
||||
public function exchange(string $exchangeCode, string $tenantCodigo): array
|
||||
{
|
||||
/** @var array{user_id: int, token: string, tenant_codigo?: string}|null $authentication */
|
||||
$authentication = Cache::pull("google-oauth-exchange:{$exchangeCode}");
|
||||
|
||||
if (! $authentication) {
|
||||
throw ValidationException::withMessages([
|
||||
'oauth_code' => __('api.auth.oauth_code_expired'),
|
||||
]);
|
||||
}
|
||||
|
||||
if (($authentication['tenant_codigo'] ?? null) !== $tenantCodigo) {
|
||||
throw ValidationException::withMessages([
|
||||
'tenant_codigo' => __('api.auth.tenant_mismatch'),
|
||||
]);
|
||||
}
|
||||
|
||||
return [
|
||||
'user' => User::query()->findOrFail($authentication['user_id']),
|
||||
'token' => $authentication['token'],
|
||||
'tenant_codigo' => $tenantCodigo,
|
||||
];
|
||||
}
|
||||
|
||||
private function resolveUser(SocialiteUser $googleUser, Tenant $tenant): User
|
||||
{
|
||||
$googleId = $googleUser->getId();
|
||||
$email = $googleUser->getEmail();
|
||||
|
||||
if (! is_string($googleId) || $googleId === '' || ! is_string($email) || ! filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
||||
throw ValidationException::withMessages([
|
||||
'google' => __('api.auth.google_email_required'),
|
||||
]);
|
||||
}
|
||||
|
||||
$rawUser = $googleUser instanceof \Laravel\Socialite\Two\User ? $googleUser->getRaw() : [];
|
||||
$emailVerified = $rawUser['email_verified'] ?? $rawUser['verified_email'] ?? false;
|
||||
if (! in_array($emailVerified, [true, 'true', 1, '1'], true)) {
|
||||
throw ValidationException::withMessages([
|
||||
'google' => __('api.auth.google_email_unverified'),
|
||||
]);
|
||||
}
|
||||
|
||||
$user = User::query()->where('google_id', $googleId)->first();
|
||||
if ($user) {
|
||||
return $user;
|
||||
}
|
||||
|
||||
$user = User::query()->where('email', $email)->first();
|
||||
if ($user) {
|
||||
$user->forceFill(['google_id' => $googleId])->save();
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
$name = $googleUser->getName();
|
||||
$user = User::query()->create([
|
||||
'nombre_apellido' => is_string($name) && $name !== '' ? $name : $email,
|
||||
'email' => $email,
|
||||
'email_verified_at' => now(),
|
||||
'google_id' => $googleId,
|
||||
'password' => Str::password(64),
|
||||
]);
|
||||
|
||||
UserRegistered::dispatch($user, $tenant->codigo);
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
private function isTenantReturnUrl(string $returnUrl, Tenant $tenant): bool
|
||||
{
|
||||
$parts = parse_url($returnUrl);
|
||||
if (! is_array($parts)
|
||||
|| ! isset($parts['scheme'], $parts['host'])
|
||||
|| isset($parts['user'], $parts['pass'], $parts['query'], $parts['fragment'])
|
||||
|| ($parts['path'] ?? '') !== '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
$scheme = strtolower($parts['scheme']);
|
||||
$host = TenantDomainNormalizer::normalize($parts['host']);
|
||||
$tenantDomain = TenantDomainNormalizer::normalize($tenant->dominio);
|
||||
|
||||
if ($host === null || $tenantDomain === null || $host !== $tenantDomain) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $scheme === 'https' || ($scheme === 'http' && in_array($host, ['localhost', '127.0.0.1'], true));
|
||||
}
|
||||
}
|
||||
311
app/Domains/Auth/Services/PasswordLoginService.php
Normal file
311
app/Domains/Auth/Services/PasswordLoginService.php
Normal file
@@ -0,0 +1,311 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Services;
|
||||
|
||||
use App\Domains\Auth\Exceptions\AccountLockedException;
|
||||
use App\Domains\Auth\Models\LoginAttempt;
|
||||
use App\Domains\Auth\Models\ResetPasswordAttempt;
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Authorization\Enums\PermissionCode;
|
||||
use App\Domains\Authorization\Enums\RoleCode;
|
||||
use App\Domains\Notification\Events\PasswordResetRequested;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class PasswordLoginService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ResetPasswordAttemptService $resetPasswordAttemptService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @throws AccountLockedException
|
||||
* @throws ValidationException
|
||||
*/
|
||||
public function authenticate(
|
||||
string $email,
|
||||
string $password,
|
||||
string $tenantCode,
|
||||
?string $ipAddress,
|
||||
?string $userAgent,
|
||||
): User {
|
||||
return $this->authenticateUser(
|
||||
$email,
|
||||
$password,
|
||||
$tenantCode,
|
||||
$ipAddress,
|
||||
$userAgent,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticate a tenant-bound AdminApp user without requiring the caller
|
||||
* to know their tenant code beforehand.
|
||||
*
|
||||
* @throws AccountLockedException
|
||||
* @throws ValidationException
|
||||
*/
|
||||
public function authenticateAdminApp(
|
||||
string $email,
|
||||
string $password,
|
||||
?string $ipAddress,
|
||||
?string $userAgent,
|
||||
): User {
|
||||
return $this->authenticateUser(
|
||||
$email,
|
||||
$password,
|
||||
null,
|
||||
$ipAddress,
|
||||
$userAgent,
|
||||
RoleCode::AdminApp,
|
||||
true,
|
||||
null,
|
||||
PasswordResetRequested::CHANNEL_ADMINAPP,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticate a tenant-bound user authorized to scan tickets.
|
||||
*
|
||||
* @throws AccountLockedException
|
||||
* @throws ValidationException
|
||||
*/
|
||||
public function authenticateScanner(
|
||||
string $email,
|
||||
string $password,
|
||||
?string $ipAddress,
|
||||
?string $userAgent,
|
||||
): User {
|
||||
return $this->authenticateUser(
|
||||
$email,
|
||||
$password,
|
||||
null,
|
||||
$ipAddress,
|
||||
$userAgent,
|
||||
null,
|
||||
true,
|
||||
PermissionCode::ScanTickets->value,
|
||||
PasswordResetRequested::CHANNEL_SCANNER,
|
||||
);
|
||||
}
|
||||
|
||||
private function authenticateUser(
|
||||
string $email,
|
||||
string $password,
|
||||
?string $tenantCode,
|
||||
?string $ipAddress,
|
||||
?string $userAgent,
|
||||
?RoleCode $requiredRole = RoleCode::User,
|
||||
bool $requiresTenant = false,
|
||||
?string $requiredPermission = null,
|
||||
string $passwordResetChannel = PasswordResetRequested::CHANNEL_STOREFRONT,
|
||||
): User {
|
||||
$normalizedEmail = mb_strtolower(trim($email));
|
||||
$now = CarbonImmutable::now();
|
||||
|
||||
/** @var array{outcome: string, user: User|null, locked_until: CarbonImmutable|null} $result */
|
||||
$result = DB::transaction(function () use (
|
||||
$normalizedEmail,
|
||||
$password,
|
||||
$tenantCode,
|
||||
$ipAddress,
|
||||
$userAgent,
|
||||
$now,
|
||||
$requiredRole,
|
||||
$requiresTenant,
|
||||
$requiredPermission,
|
||||
$passwordResetChannel,
|
||||
): array {
|
||||
$user = User::query()
|
||||
->where('email', $normalizedEmail)
|
||||
->when(
|
||||
$requiredRole !== null,
|
||||
fn ($query) => $query->where('rol_codigo', $requiredRole->value),
|
||||
)
|
||||
->when(
|
||||
$requiredPermission !== null,
|
||||
fn ($query) => $query->whereHas(
|
||||
'role.permissions',
|
||||
fn ($query) => $query->where('permisos.codigo', $requiredPermission)
|
||||
),
|
||||
)
|
||||
->when(
|
||||
$requiresTenant,
|
||||
fn ($query) => $query->whereNotNull('tenant_codigo'),
|
||||
)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
$attemptTenantCode = $tenantCode ?? $user?->tenant_codigo;
|
||||
|
||||
if ($user?->locked_until?->isFuture()) {
|
||||
$this->recordAttempt(
|
||||
$user,
|
||||
$normalizedEmail,
|
||||
$attemptTenantCode,
|
||||
LoginAttempt::OUTCOME_ACCOUNT_LOCKED,
|
||||
$ipAddress,
|
||||
$userAgent,
|
||||
);
|
||||
|
||||
return [
|
||||
'outcome' => LoginAttempt::OUTCOME_ACCOUNT_LOCKED,
|
||||
'user' => $user,
|
||||
'locked_until' => CarbonImmutable::instance($user->locked_until),
|
||||
];
|
||||
}
|
||||
|
||||
if ($user !== null && $user->locked_until !== null) {
|
||||
$user->forceFill([
|
||||
'failed_login_attempts' => 0,
|
||||
'last_failed_login_at' => null,
|
||||
'locked_until' => null,
|
||||
])->save();
|
||||
}
|
||||
|
||||
if ($user === null || ! Hash::check($password, $user->password)) {
|
||||
if ($user !== null && $attemptTenantCode !== null) {
|
||||
$this->registerFailure(
|
||||
$user,
|
||||
$now,
|
||||
$attemptTenantCode,
|
||||
$passwordResetChannel,
|
||||
);
|
||||
}
|
||||
|
||||
$outcome = $user?->locked_until?->isFuture()
|
||||
? LoginAttempt::OUTCOME_ACCOUNT_LOCKED
|
||||
: LoginAttempt::OUTCOME_INVALID_CREDENTIALS;
|
||||
$this->recordAttempt(
|
||||
$user,
|
||||
$normalizedEmail,
|
||||
$attemptTenantCode,
|
||||
$outcome,
|
||||
$ipAddress,
|
||||
$userAgent,
|
||||
);
|
||||
|
||||
return [
|
||||
'outcome' => $outcome,
|
||||
'user' => $user,
|
||||
'locked_until' => $user?->locked_until === null
|
||||
? null
|
||||
: CarbonImmutable::instance($user->locked_until),
|
||||
];
|
||||
}
|
||||
|
||||
$user->forceFill([
|
||||
'failed_login_attempts' => 0,
|
||||
'last_failed_login_at' => null,
|
||||
'locked_until' => null,
|
||||
])->save();
|
||||
|
||||
$this->recordAttempt(
|
||||
$user,
|
||||
$normalizedEmail,
|
||||
$attemptTenantCode,
|
||||
LoginAttempt::OUTCOME_SUCCESS,
|
||||
$ipAddress,
|
||||
$userAgent,
|
||||
);
|
||||
|
||||
return [
|
||||
'outcome' => LoginAttempt::OUTCOME_SUCCESS,
|
||||
'user' => $user,
|
||||
'locked_until' => null,
|
||||
];
|
||||
});
|
||||
|
||||
if ($result['outcome'] === LoginAttempt::OUTCOME_ACCOUNT_LOCKED) {
|
||||
throw new AccountLockedException($result['locked_until']);
|
||||
}
|
||||
|
||||
if ($result['outcome'] === LoginAttempt::OUTCOME_INVALID_CREDENTIALS) {
|
||||
throw ValidationException::withMessages([
|
||||
'email' => __('api.auth.invalid_credentials'),
|
||||
]);
|
||||
}
|
||||
|
||||
return $result['user'];
|
||||
}
|
||||
|
||||
private function registerFailure(
|
||||
User $user,
|
||||
CarbonImmutable $now,
|
||||
string $tenantCode,
|
||||
string $passwordResetChannel,
|
||||
): void {
|
||||
$windowMinutes = max(1, (int) config('login-security.attempt_window_minutes'));
|
||||
$maxAttempts = max(1, (int) config('login-security.max_attempts'));
|
||||
$lockMinutes = max(1, (int) config('login-security.lock_minutes'));
|
||||
|
||||
$withinAttemptWindow = $user->last_failed_login_at !== null
|
||||
&& $user->last_failed_login_at->gte($now->subMinutes($windowMinutes));
|
||||
$attempts = $withinAttemptWindow
|
||||
? $user->failed_login_attempts + 1
|
||||
: 1;
|
||||
|
||||
$previousAttempts = $user->failed_login_attempts;
|
||||
|
||||
$user->forceFill([
|
||||
'failed_login_attempts' => $attempts,
|
||||
'last_failed_login_at' => $now,
|
||||
'locked_until' => $attempts >= $maxAttempts
|
||||
? $now->addMinutes($lockMinutes)
|
||||
: null,
|
||||
])->save();
|
||||
|
||||
if ($attempts >= $maxAttempts && $previousAttempts < $maxAttempts) {
|
||||
try {
|
||||
if ($passwordResetChannel === PasswordResetRequested::CHANNEL_ADMINAPP) {
|
||||
$this->resetPasswordAttemptService->createForAdminAppEmail(
|
||||
$user->email,
|
||||
ResetPasswordAttempt::REASON_ACCOUNT_LOCKED,
|
||||
);
|
||||
} elseif ($passwordResetChannel === PasswordResetRequested::CHANNEL_SCANNER) {
|
||||
$this->resetPasswordAttemptService->createForScannerEmail(
|
||||
$user->email,
|
||||
ResetPasswordAttempt::REASON_ACCOUNT_LOCKED,
|
||||
);
|
||||
} else {
|
||||
$this->resetPasswordAttemptService->createForEmail(
|
||||
$user->email,
|
||||
$tenantCode,
|
||||
ResetPasswordAttempt::REASON_ACCOUNT_LOCKED,
|
||||
);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('Failed to trigger reset password on account lock', [
|
||||
'user_id' => $user->id,
|
||||
'exception' => $e,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function recordAttempt(
|
||||
?User $user,
|
||||
string $normalizedEmail,
|
||||
?string $tenantCode,
|
||||
string $outcome,
|
||||
?string $ipAddress,
|
||||
?string $userAgent,
|
||||
): void {
|
||||
LoginAttempt::query()->create([
|
||||
'user_id' => $user?->getKey(),
|
||||
'email_fingerprint' => hash_hmac(
|
||||
'sha256',
|
||||
$normalizedEmail,
|
||||
(string) config('app.key'),
|
||||
),
|
||||
'tenant_codigo' => $tenantCode,
|
||||
'outcome' => $outcome,
|
||||
'ip_address' => $ipAddress,
|
||||
'user_agent' => $userAgent === null
|
||||
? null
|
||||
: mb_substr($userAgent, 0, 1024),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -3,20 +3,27 @@
|
||||
namespace App\Domains\Auth\Services;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Notification\Events\UserRegistered;
|
||||
|
||||
class RegisterUserService
|
||||
{
|
||||
/**
|
||||
* @param array{nombre_apellido: string, email: string, password: string, dni?: string|null, telefono?: string|null} $data
|
||||
* @param array{tenant_codigo?: string|null, nombre_apellido: string, email: string, password: string, dni?: string|null, telefono?: string|null} $data
|
||||
*/
|
||||
public function register(array $data): User
|
||||
{
|
||||
return User::query()->create([
|
||||
$user = User::query()->create([
|
||||
'nombre_apellido' => $data['nombre_apellido'],
|
||||
'email' => $data['email'],
|
||||
'password' => $data['password'],
|
||||
'dni' => $data['dni'] ?? null,
|
||||
'telefono' => $data['telefono'] ?? null,
|
||||
]);
|
||||
|
||||
if (! empty($data['tenant_codigo'])) {
|
||||
UserRegistered::dispatch($user, $data['tenant_codigo']);
|
||||
}
|
||||
|
||||
return $user;
|
||||
}
|
||||
}
|
||||
|
||||
312
app/Domains/Auth/Services/ResetPasswordAttemptService.php
Normal file
312
app/Domains/Auth/Services/ResetPasswordAttemptService.php
Normal file
@@ -0,0 +1,312 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Services;
|
||||
|
||||
use App\Domains\Auth\Models\ResetPasswordAttempt;
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Authorization\Enums\RoleCode;
|
||||
use App\Domains\Notification\Events\PasswordResetRequested;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Throwable;
|
||||
|
||||
class ResetPasswordAttemptService
|
||||
{
|
||||
public function createForEmail(
|
||||
string $email,
|
||||
string $tenantCode,
|
||||
string $reason = ResetPasswordAttempt::REASON_MANUAL,
|
||||
): void {
|
||||
$emailFingerprint = $this->emailFingerprint($email);
|
||||
|
||||
try {
|
||||
$attemptId = DB::transaction(function () use ($email, $emailFingerprint, $reason): ?int {
|
||||
$user = User::query()
|
||||
->where('email', $email)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
return $this->createAttemptForUser(
|
||||
$user,
|
||||
$reason,
|
||||
$emailFingerprint,
|
||||
'Password reset attempt was not created because the user was not found.',
|
||||
);
|
||||
});
|
||||
} catch (Throwable $exception) {
|
||||
Log::error('Failed to create password reset attempt.', [
|
||||
'email_fingerprint' => $emailFingerprint,
|
||||
'exception' => $exception,
|
||||
]);
|
||||
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
$this->dispatchPasswordResetRequested(
|
||||
$attemptId,
|
||||
$tenantCode,
|
||||
PasswordResetRequested::CHANNEL_STOREFRONT,
|
||||
$emailFingerprint,
|
||||
);
|
||||
}
|
||||
|
||||
public function createForAdminAppEmail(
|
||||
string $email,
|
||||
string $reason = ResetPasswordAttempt::REASON_MANUAL,
|
||||
): void {
|
||||
$emailFingerprint = $this->emailFingerprint($email);
|
||||
|
||||
try {
|
||||
$result = DB::transaction(function () use ($email, $emailFingerprint, $reason): ?array {
|
||||
$user = User::query()
|
||||
->where('email', $email)
|
||||
->where('rol_codigo', RoleCode::AdminApp->value)
|
||||
->whereNotNull('tenant_codigo')
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
$attemptId = $this->createAttemptForUser(
|
||||
$user,
|
||||
$reason,
|
||||
$emailFingerprint,
|
||||
'AdminApp password reset attempt was not created because the user was not found.',
|
||||
);
|
||||
|
||||
if ($user === null || $attemptId === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return [
|
||||
'attempt_id' => $attemptId,
|
||||
'tenant_code' => $user->tenant_codigo,
|
||||
];
|
||||
});
|
||||
} catch (Throwable $exception) {
|
||||
Log::error('Failed to create AdminApp password reset attempt.', [
|
||||
'email_fingerprint' => $emailFingerprint,
|
||||
'exception' => $exception,
|
||||
]);
|
||||
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
$this->dispatchPasswordResetRequested(
|
||||
$result['attempt_id'] ?? null,
|
||||
$result['tenant_code'] ?? null,
|
||||
PasswordResetRequested::CHANNEL_ADMINAPP,
|
||||
$emailFingerprint,
|
||||
);
|
||||
}
|
||||
|
||||
public function createForScannerEmail(
|
||||
string $email,
|
||||
string $reason = ResetPasswordAttempt::REASON_MANUAL,
|
||||
): void {
|
||||
$emailFingerprint = $this->emailFingerprint($email);
|
||||
|
||||
try {
|
||||
$result = DB::transaction(function () use ($email, $emailFingerprint, $reason): ?array {
|
||||
$user = User::query()
|
||||
->where('email', $email)
|
||||
->where('rol_codigo', RoleCode::Scanner->value)
|
||||
->whereNotNull('tenant_codigo')
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
$attemptId = $this->createAttemptForUser(
|
||||
$user,
|
||||
$reason,
|
||||
$emailFingerprint,
|
||||
'Scanner password reset attempt was not created because the user was not found.',
|
||||
);
|
||||
|
||||
if ($user === null || $attemptId === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return [
|
||||
'attempt_id' => $attemptId,
|
||||
'tenant_code' => $user->tenant_codigo,
|
||||
];
|
||||
});
|
||||
} catch (Throwable $exception) {
|
||||
Log::error('Failed to create Scanner password reset attempt.', [
|
||||
'email_fingerprint' => $emailFingerprint,
|
||||
'exception' => $exception,
|
||||
]);
|
||||
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
$this->dispatchPasswordResetRequested(
|
||||
$result['attempt_id'] ?? null,
|
||||
$result['tenant_code'] ?? null,
|
||||
PasswordResetRequested::CHANNEL_SCANNER,
|
||||
$emailFingerprint,
|
||||
);
|
||||
}
|
||||
|
||||
public function validateCode(string $email, string $code): bool
|
||||
{
|
||||
$emailFingerprint = $this->emailFingerprint($email);
|
||||
|
||||
try {
|
||||
return DB::transaction(function () use ($email, $code, $emailFingerprint): bool {
|
||||
$user = User::query()
|
||||
->where('email', $email)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
$attempt = $user?->resetPasswordAttempts()
|
||||
->where('codigo', $code)
|
||||
->where('status', ResetPasswordAttempt::STATUS_PENDING)
|
||||
->latest('id')
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($attempt === null) {
|
||||
Log::warning('Password reset code validation failed: no matching pending attempt.', [
|
||||
'email_fingerprint' => $emailFingerprint,
|
||||
]);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$attempt->update([
|
||||
'status' => ResetPasswordAttempt::STATUS_VALIDATED,
|
||||
]);
|
||||
|
||||
return true;
|
||||
});
|
||||
} catch (Throwable $exception) {
|
||||
Log::error('Failed to validate password reset code.', [
|
||||
'email_fingerprint' => $emailFingerprint,
|
||||
'exception' => $exception,
|
||||
]);
|
||||
|
||||
throw $exception;
|
||||
}
|
||||
}
|
||||
|
||||
public function resetPassword(string $email, string $code, string $password): bool
|
||||
{
|
||||
$emailFingerprint = $this->emailFingerprint($email);
|
||||
|
||||
try {
|
||||
return DB::transaction(function () use ($email, $code, $password, $emailFingerprint): bool {
|
||||
$user = User::query()
|
||||
->where('email', $email)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
$attempt = $user?->resetPasswordAttempts()
|
||||
->where('codigo', $code)
|
||||
->where('status', ResetPasswordAttempt::STATUS_VALIDATED)
|
||||
->latest('id')
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($user === null || $attempt === null) {
|
||||
Log::warning('Password reset failed: no matching validated attempt.', [
|
||||
'email_fingerprint' => $emailFingerprint,
|
||||
]);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$user->password = $password;
|
||||
$user->failed_login_attempts = 0;
|
||||
$user->last_failed_login_at = null;
|
||||
$user->locked_until = null;
|
||||
$user->save();
|
||||
$user->tokens()->delete();
|
||||
|
||||
$user->resetPasswordAttempts()
|
||||
->whereKeyNot($attempt->getKey())
|
||||
->whereIn('status', [
|
||||
ResetPasswordAttempt::STATUS_PENDING,
|
||||
ResetPasswordAttempt::STATUS_VALIDATED,
|
||||
])
|
||||
->update(['status' => ResetPasswordAttempt::STATUS_EXPIRED]);
|
||||
|
||||
$attempt->update([
|
||||
'status' => ResetPasswordAttempt::STATUS_USED,
|
||||
]);
|
||||
|
||||
return true;
|
||||
});
|
||||
} catch (Throwable $exception) {
|
||||
Log::error('Failed to reset user password.', [
|
||||
'email_fingerprint' => $emailFingerprint,
|
||||
'exception' => $exception,
|
||||
]);
|
||||
|
||||
throw $exception;
|
||||
}
|
||||
}
|
||||
|
||||
private function createAttemptForUser(
|
||||
?User $user,
|
||||
string $reason,
|
||||
string $emailFingerprint,
|
||||
string $userNotFoundMessage,
|
||||
): ?int {
|
||||
if ($user === null) {
|
||||
Log::warning($userNotFoundMessage, [
|
||||
'email_fingerprint' => $emailFingerprint,
|
||||
]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
$user->resetPasswordAttempts()
|
||||
->whereIn('status', [
|
||||
ResetPasswordAttempt::STATUS_PENDING,
|
||||
ResetPasswordAttempt::STATUS_VALIDATED,
|
||||
])
|
||||
->update(['status' => ResetPasswordAttempt::STATUS_EXPIRED]);
|
||||
|
||||
$attempt = $user->resetPasswordAttempts()->create([
|
||||
'codigo' => $this->generateCode(),
|
||||
'reason' => $reason,
|
||||
'status' => ResetPasswordAttempt::STATUS_PENDING,
|
||||
]);
|
||||
|
||||
return $attempt->getKey();
|
||||
}
|
||||
|
||||
private function dispatchPasswordResetRequested(
|
||||
?int $attemptId,
|
||||
?string $tenantCode,
|
||||
string $channel,
|
||||
string $emailFingerprint,
|
||||
): void {
|
||||
if ($attemptId === null || $tenantCode === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
PasswordResetRequested::dispatch($attemptId, $tenantCode, $channel);
|
||||
} catch (Throwable $exception) {
|
||||
Log::error('Failed to dispatch password reset email.', [
|
||||
'attempt_id' => $attemptId,
|
||||
'tenant_code' => $tenantCode,
|
||||
'channel' => $channel,
|
||||
'email_fingerprint' => $emailFingerprint,
|
||||
'exception' => $exception,
|
||||
]);
|
||||
|
||||
throw $exception;
|
||||
}
|
||||
}
|
||||
|
||||
private function generateCode(): string
|
||||
{
|
||||
return str_pad((string) random_int(0, 9999), 4, '0', STR_PAD_LEFT);
|
||||
}
|
||||
|
||||
private function emailFingerprint(string $email): string
|
||||
{
|
||||
return substr(hash('sha256', strtolower(trim($email))), 0, 12);
|
||||
}
|
||||
}
|
||||
24
app/Domains/Auth/Services/ScannerContextService.php
Normal file
24
app/Domains/Auth/Services/ScannerContextService.php
Normal file
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Services;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
|
||||
class ScannerContextService
|
||||
{
|
||||
public function load(User $user): User
|
||||
{
|
||||
$tenant = $user->tenant()
|
||||
->with([
|
||||
'menues' => fn ($query) => $query->whereHas(
|
||||
'roles',
|
||||
fn ($query) => $query->where('codigo', $user->rol_codigo)
|
||||
),
|
||||
])
|
||||
->firstOrFail();
|
||||
|
||||
$user->setRelation('tenant', $tenant);
|
||||
|
||||
return $user;
|
||||
}
|
||||
}
|
||||
36
app/Domains/Auth/documentacion/README.md
Normal file
36
app/Domains/Auth/documentacion/README.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# Dominio Auth
|
||||
|
||||
## Propósito
|
||||
|
||||
Gestiona identidad y acceso de usuarios de la tienda y del panel administrativo: registro, inicio y cierre de sesión, perfil, autenticación con Google y recuperación de contraseña.
|
||||
|
||||
## Modelo y servicios
|
||||
|
||||
- `User`: usuario autenticable, asociado a tenant, rol, intentos de acceso y categorías habilitadas para escaneo.
|
||||
- `LoginAttempt` y `ResetPasswordAttempt`: trazabilidad de accesos y recuperación de contraseña.
|
||||
- `PasswordLoginService`: autentica tienda y AdminApp, incluyendo bloqueo por intentos.
|
||||
- `RegisterUserService` y `ProfileService`: alta y edición del usuario.
|
||||
- `ResetPasswordAttemptService`: crea, valida y consume códigos de recuperación.
|
||||
- `GoogleAuthService`: redirección, callback e intercambio de código para Google OAuth.
|
||||
- `AdminAppContextService`: carga el contexto requerido por un usuario administrativo.
|
||||
|
||||
## Endpoints públicos
|
||||
|
||||
- `POST /register`, `POST /login` y `POST /logout`.
|
||||
- `GET /me` y `PUT /me`, protegidos por `auth:sanctum`.
|
||||
- Creación, validación y aplicación de intentos de recuperación bajo `/password`.
|
||||
- `POST /auth/google/exchange` para canjear el código de autenticación.
|
||||
- `POST /v1/adminapp/login` y consulta del usuario administrativo dentro del grupo autenticado de AdminApp.
|
||||
|
||||
## Validación y respuestas
|
||||
|
||||
Los `FormRequest` validan cada operación. `UserResource` y `AdminAppMeResource` definen las representaciones de salida. Los endpoints sensibles aplican `auth:sanctum` y límites de frecuencia.
|
||||
|
||||
## Dependencias y eventos
|
||||
|
||||
Se relaciona con `Tenant` y `Authorization`; el registro y la recuperación disparan flujos atendidos por `Notification`. El carrito invitado puede integrarse al usuario autenticado mediante el dominio `Cart`.
|
||||
|
||||
## Consideraciones
|
||||
|
||||
- La resolución del tenant forma parte de la autenticación y no debe omitirse.
|
||||
- Los cambios en reglas de login deben conservar los límites de intentos y el manejo de `AccountLockedException`.
|
||||
20
app/Domains/Auth/routes/adminapp.php
Normal file
20
app/Domains/Auth/routes/adminapp.php
Normal file
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Auth\Controllers\AdminAppLoginController;
|
||||
use App\Domains\Auth\Controllers\AdminAppMeController;
|
||||
use App\Domains\Auth\Controllers\CreateAdminAppResetPasswordAttemptController;
|
||||
use App\Domains\Auth\Controllers\ResetPasswordController;
|
||||
use App\Domains\Auth\Controllers\ValidateResetPasswordAttemptController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::prefix('v1/adminapp')->group(function (): void {
|
||||
Route::post('login', AdminAppLoginController::class)->middleware('throttle:login');
|
||||
Route::post('password/reset-attempts', CreateAdminAppResetPasswordAttemptController::class)
|
||||
->middleware('throttle:5,1');
|
||||
Route::post('password/reset-attempts/validate', ValidateResetPasswordAttemptController::class)
|
||||
->middleware('throttle:10,1');
|
||||
Route::post('password/reset', ResetPasswordController::class)
|
||||
->middleware('throttle:5,1');
|
||||
Route::middleware(['auth:sanctum', 'adminapp.tenant'])
|
||||
->get('me', AdminAppMeController::class);
|
||||
});
|
||||
@@ -1,14 +1,28 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Auth\Controllers\CreateResetPasswordAttemptController;
|
||||
use App\Domains\Auth\Controllers\GoogleTokenExchangeController;
|
||||
use App\Domains\Auth\Controllers\LoginController;
|
||||
use App\Domains\Auth\Controllers\LogoutController;
|
||||
use App\Domains\Auth\Controllers\MeController;
|
||||
use App\Domains\Auth\Controllers\RegisterController;
|
||||
use App\Domains\Auth\Controllers\ResetPasswordController;
|
||||
use App\Domains\Auth\Controllers\UpdateProfileController;
|
||||
use App\Domains\Auth\Controllers\ValidateResetPasswordAttemptController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::post('/register', RegisterController::class);
|
||||
Route::post('/login', LoginController::class);
|
||||
Route::post('/login', LoginController::class)->middleware('throttle:login');
|
||||
Route::post('/password/reset-attempts', CreateResetPasswordAttemptController::class)
|
||||
->middleware('throttle:5,1');
|
||||
Route::post('/password/reset-attempts/validate', ValidateResetPasswordAttemptController::class)
|
||||
->middleware('throttle:10,1');
|
||||
Route::post('/password/reset', ResetPasswordController::class)
|
||||
->middleware('throttle:5,1');
|
||||
Route::post('/auth/google/exchange', GoogleTokenExchangeController::class);
|
||||
Route::middleware('auth:sanctum')->post('/logout', LogoutController::class);
|
||||
Route::middleware('auth:sanctum')->get('/me', MeController::class);
|
||||
Route::middleware('auth:sanctum')->put('/me', UpdateProfileController::class);
|
||||
|
||||
require __DIR__.'/adminapp.php';
|
||||
require __DIR__.'/scanner.php';
|
||||
|
||||
20
app/Domains/Auth/routes/scanner.php
Normal file
20
app/Domains/Auth/routes/scanner.php
Normal file
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Auth\Controllers\CreateScannerResetPasswordAttemptController;
|
||||
use App\Domains\Auth\Controllers\ResetPasswordController;
|
||||
use App\Domains\Auth\Controllers\ScannerLoginController;
|
||||
use App\Domains\Auth\Controllers\ScannerMeController;
|
||||
use App\Domains\Auth\Controllers\ValidateResetPasswordAttemptController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::prefix('v1/scanner')->group(function (): void {
|
||||
Route::post('login', ScannerLoginController::class)->middleware('throttle:login');
|
||||
Route::post('password/reset-attempts', CreateScannerResetPasswordAttemptController::class)
|
||||
->middleware('throttle:5,1');
|
||||
Route::post('password/reset-attempts/validate', ValidateResetPasswordAttemptController::class)
|
||||
->middleware('throttle:10,1');
|
||||
Route::post('password/reset', ResetPasswordController::class)
|
||||
->middleware('throttle:5,1');
|
||||
Route::middleware(['auth:sanctum', 'scanner.tenant'])
|
||||
->get('me', ScannerMeController::class);
|
||||
});
|
||||
8
app/Domains/Authorization/Enums/PermissionCode.php
Normal file
8
app/Domains/Authorization/Enums/PermissionCode.php
Normal file
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Authorization\Enums;
|
||||
|
||||
enum PermissionCode: string
|
||||
{
|
||||
case ScanTickets = 'tickets.escanear';
|
||||
}
|
||||
11
app/Domains/Authorization/Enums/RoleCode.php
Normal file
11
app/Domains/Authorization/Enums/RoleCode.php
Normal file
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Authorization\Enums;
|
||||
|
||||
enum RoleCode: string
|
||||
{
|
||||
case Admin = 'admin';
|
||||
case AdminApp = 'adminapp';
|
||||
case Scanner = 'scanner';
|
||||
case User = 'user';
|
||||
}
|
||||
32
app/Domains/Authorization/Models/Permission.php
Normal file
32
app/Domains/Authorization/Models/Permission.php
Normal file
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Authorization\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
|
||||
class Permission extends Model
|
||||
{
|
||||
protected $table = 'permisos';
|
||||
|
||||
protected $fillable = [
|
||||
'codigo',
|
||||
'nombre',
|
||||
'descripcion',
|
||||
];
|
||||
|
||||
/**
|
||||
* @return BelongsToMany<Role, $this>
|
||||
*/
|
||||
public function roles(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(
|
||||
Role::class,
|
||||
'roles_permisos',
|
||||
'codigo_permiso',
|
||||
'rol_codigo',
|
||||
'codigo',
|
||||
'codigo'
|
||||
)->withTimestamps();
|
||||
}
|
||||
}
|
||||
59
app/Domains/Authorization/Models/Role.php
Normal file
59
app/Domains/Authorization/Models/Role.php
Normal file
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Authorization\Models;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Menu\Models\Menu;
|
||||
use App\Domains\Menu\Models\MenuRole;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
class Role extends Model
|
||||
{
|
||||
protected $table = 'roles';
|
||||
|
||||
protected $fillable = [
|
||||
'codigo',
|
||||
'nombre',
|
||||
'descripcion',
|
||||
];
|
||||
|
||||
/**
|
||||
* @return BelongsToMany<Permission, $this>
|
||||
*/
|
||||
public function permissions(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(
|
||||
Permission::class,
|
||||
'roles_permisos',
|
||||
'rol_codigo',
|
||||
'codigo_permiso',
|
||||
'codigo',
|
||||
'codigo'
|
||||
)->withTimestamps();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<User, $this>
|
||||
*/
|
||||
public function users(): HasMany
|
||||
{
|
||||
return $this->hasMany(User::class, 'rol_codigo', 'codigo');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsToMany<Menu, $this>
|
||||
*/
|
||||
public function menus(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(
|
||||
Menu::class,
|
||||
'roles_menues',
|
||||
'rol_codigo',
|
||||
'menu_codigo',
|
||||
'codigo',
|
||||
'code'
|
||||
)->using(MenuRole::class);
|
||||
}
|
||||
}
|
||||
32
app/Domains/Authorization/Models/RolePermission.php
Normal file
32
app/Domains/Authorization/Models/RolePermission.php
Normal file
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Authorization\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class RolePermission extends Model
|
||||
{
|
||||
protected $table = 'roles_permisos';
|
||||
|
||||
protected $fillable = [
|
||||
'codigo_permiso',
|
||||
'rol_codigo',
|
||||
];
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Permission, $this>
|
||||
*/
|
||||
public function permission(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Permission::class, 'codigo_permiso', 'codigo');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Role, $this>
|
||||
*/
|
||||
public function role(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Role::class, 'rol_codigo', 'codigo');
|
||||
}
|
||||
}
|
||||
26
app/Domains/Authorization/documentacion/README.md
Normal file
26
app/Domains/Authorization/documentacion/README.md
Normal file
@@ -0,0 +1,26 @@
|
||||
# Dominio Authorization
|
||||
|
||||
## Propósito
|
||||
|
||||
Define el esquema de roles y permisos usado para autorizar funcionalidades de la aplicación.
|
||||
|
||||
## Componentes principales
|
||||
|
||||
- `Enums/RoleCode.php`: códigos de roles conocidos por el sistema.
|
||||
- `Models/Role.php`: rol con relaciones hacia permisos, usuarios y menús.
|
||||
- `Models/Permission.php`: permiso asignable a uno o más roles.
|
||||
- `Models/RolePermission.php`: entidad de asociación entre rol y permiso.
|
||||
|
||||
## API
|
||||
|
||||
No expone controladores ni rutas propias. Su información se consume desde autenticación, menús, políticas y middleware de autorización.
|
||||
|
||||
## Relaciones relevantes
|
||||
|
||||
- `Role` tiene muchos usuarios del dominio `Auth`.
|
||||
- Roles y permisos mantienen una relación muchos-a-muchos.
|
||||
- Los roles determinan los menús disponibles mediante el dominio `Menu`.
|
||||
|
||||
## Consideraciones
|
||||
|
||||
Los códigos definidos en `RoleCode` funcionan como contrato entre datos persistidos y lógica de aplicación. Al agregar un rol o permiso se deben revisar seeds, asociaciones y consumidores.
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Bootstrap\Controllers;
|
||||
|
||||
use App\Domains\Bootstrap\Requests\AdminAppBootstrapRequest;
|
||||
use App\Domains\Bootstrap\Resources\AdminAppBootstrapResource;
|
||||
use App\Domains\Bootstrap\Services\AdminAppBootstrapService;
|
||||
use App\Http\Controllers\Controller;
|
||||
|
||||
class AdminAppBootstrapController extends Controller
|
||||
{
|
||||
public function __construct(protected AdminAppBootstrapService $bootstrapService) {}
|
||||
|
||||
public function __invoke(AdminAppBootstrapRequest $request): AdminAppBootstrapResource
|
||||
{
|
||||
return AdminAppBootstrapResource::make(
|
||||
$this->bootstrapService->get((string) $request->validated('dominio'))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Bootstrap\Controllers;
|
||||
|
||||
use App\Domains\Bootstrap\Requests\ScannerBootstrapRequest;
|
||||
use App\Domains\Bootstrap\Resources\ScannerBootstrapResource;
|
||||
use App\Domains\Bootstrap\Services\ScannerBootstrapService;
|
||||
use App\Http\Controllers\Controller;
|
||||
|
||||
class ScannerBootstrapController extends Controller
|
||||
{
|
||||
public function __construct(protected ScannerBootstrapService $bootstrapService) {}
|
||||
|
||||
public function __invoke(ScannerBootstrapRequest $request): ScannerBootstrapResource
|
||||
{
|
||||
return ScannerBootstrapResource::make(
|
||||
$this->bootstrapService->get((string) $request->validated('dominio'))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Bootstrap\Controllers;
|
||||
|
||||
use App\Domains\Bootstrap\Requests\TenantBootstrapRequest;
|
||||
use App\Domains\Bootstrap\Services\TenantBootstrapService;
|
||||
use App\Domains\Tenant\Resources\TenantResource;
|
||||
use App\Http\Controllers\Controller;
|
||||
|
||||
class TenantBootstrapController extends Controller
|
||||
{
|
||||
public function __construct(protected TenantBootstrapService $bootstrapService) {}
|
||||
|
||||
public function __invoke(TenantBootstrapRequest $request): TenantResource
|
||||
{
|
||||
return TenantResource::make(
|
||||
$this->bootstrapService->get(
|
||||
(string) $request->validated('dominio'),
|
||||
(string) $request->validated('path'),
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Bootstrap\Requests;
|
||||
|
||||
class AdminAppBootstrapRequest extends TenantBootstrapRequest {}
|
||||
@@ -0,0 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Bootstrap\Requests;
|
||||
|
||||
class ScannerBootstrapRequest extends TenantBootstrapRequest {}
|
||||
@@ -1,15 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Tenant\Requests;
|
||||
namespace App\Domains\Bootstrap\Requests;
|
||||
|
||||
use App\Domains\Tenant\Support\TenantDomainNormalizer;
|
||||
use Closure;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class BootstrapTenantRequest extends FormRequest
|
||||
class TenantBootstrapRequest extends FormRequest
|
||||
{
|
||||
protected bool $hasInvalidDomain = false;
|
||||
|
||||
protected bool $hasInvalidPath = false;
|
||||
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
@@ -17,20 +19,23 @@ class BootstrapTenantRequest extends FormRequest
|
||||
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
$rawDomain = $this->route('dominio');
|
||||
$rawDomain = $this->query('dominio', $this->route('dominio'));
|
||||
$rawPath = $this->query('path', '/');
|
||||
$normalizedDomain = TenantDomainNormalizer::normalize($rawDomain);
|
||||
$normalizedPath = TenantDomainNormalizer::normalizePath($rawPath);
|
||||
|
||||
$this->hasInvalidDomain = TenantDomainNormalizer::hasValue($rawDomain)
|
||||
&& $normalizedDomain === null;
|
||||
|
||||
$this->hasInvalidPath = ! is_string($rawPath) || $normalizedPath === null;
|
||||
|
||||
$this->merge([
|
||||
'dominio' => $normalizedDomain,
|
||||
'path' => $normalizedPath,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
/** @return array<string, mixed> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
@@ -45,6 +50,17 @@ class BootstrapTenantRequest extends FormRequest
|
||||
'string',
|
||||
'max:255',
|
||||
],
|
||||
'path' => [
|
||||
'bail',
|
||||
function (string $attribute, mixed $value, Closure $fail): void {
|
||||
if ($this->hasInvalidPath) {
|
||||
$fail("The {$attribute} field must contain a valid URL path.");
|
||||
}
|
||||
},
|
||||
'required',
|
||||
'string',
|
||||
'max:2048',
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Bootstrap\Resources;
|
||||
|
||||
use App\Domains\Tenant\Models\WebsiteType;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin array{website_type: WebsiteType} */
|
||||
class AdminAppBootstrapResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
/** @var WebsiteType $websiteType */
|
||||
$websiteType = $this->resource['website_type'];
|
||||
|
||||
return [
|
||||
'website_type_code' => $websiteType->codigo,
|
||||
'primary_color' => $websiteType->primary_color,
|
||||
'secondary_color' => $websiteType->secondary_color,
|
||||
'danger_color' => $websiteType->danger_color,
|
||||
'success_color' => $websiteType->success_color,
|
||||
'warning_color' => $websiteType->warning_color,
|
||||
'body_color' => $websiteType->body_color,
|
||||
'darker_body_color' => $websiteType->darker_body_color,
|
||||
'surface_color' => $websiteType->surface_color,
|
||||
'background_color' => $websiteType->background_color,
|
||||
'border_color' => $websiteType->border_color,
|
||||
'login_header_footer_color' => $websiteType->login_header_footer_color,
|
||||
'site_logo' => $websiteType->siteLogo?->getTemporaryUrl(1440),
|
||||
'footer_logo' => $websiteType->footerLogo?->getTemporaryUrl(1440),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Bootstrap\Resources;
|
||||
|
||||
class ScannerBootstrapResource extends AdminAppBootstrapResource {}
|
||||
19
app/Domains/Bootstrap/Services/AdminAppBootstrapService.php
Normal file
19
app/Domains/Bootstrap/Services/AdminAppBootstrapService.php
Normal file
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Bootstrap\Services;
|
||||
|
||||
use App\Domains\Tenant\Models\WebsiteType;
|
||||
|
||||
class AdminAppBootstrapService
|
||||
{
|
||||
/** @return array{website_type: WebsiteType} */
|
||||
public function get(string $domain): array
|
||||
{
|
||||
return [
|
||||
'website_type' => WebsiteType::query()
|
||||
->with(['siteLogo', 'footerLogo'])
|
||||
->where('dominio', $domain)
|
||||
->firstOrFail(),
|
||||
];
|
||||
}
|
||||
}
|
||||
19
app/Domains/Bootstrap/Services/ScannerBootstrapService.php
Normal file
19
app/Domains/Bootstrap/Services/ScannerBootstrapService.php
Normal file
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Bootstrap\Services;
|
||||
|
||||
use App\Domains\Tenant\Models\WebsiteType;
|
||||
|
||||
class ScannerBootstrapService
|
||||
{
|
||||
/** @return array{website_type: WebsiteType} */
|
||||
public function get(string $domain): array
|
||||
{
|
||||
return [
|
||||
'website_type' => WebsiteType::query()
|
||||
->with(['siteLogo', 'footerLogo'])
|
||||
->where('scanner_domain', $domain)
|
||||
->firstOrFail(),
|
||||
];
|
||||
}
|
||||
}
|
||||
42
app/Domains/Bootstrap/Services/TenantBootstrapService.php
Normal file
42
app/Domains/Bootstrap/Services/TenantBootstrapService.php
Normal file
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Bootstrap\Services;
|
||||
|
||||
use App\Domains\Authorization\Enums\RoleCode;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Tenant\Services\TenantInformationService;
|
||||
use App\Domains\Tenant\Support\TenantDomainNormalizer;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
|
||||
class TenantBootstrapService
|
||||
{
|
||||
public function __construct(protected TenantInformationService $tenantInformationService) {}
|
||||
|
||||
public function get(string $domain, string $path = '/'): Tenant
|
||||
{
|
||||
$candidateKeys = TenantDomainNormalizer::tenantKeyCandidates($domain, $path);
|
||||
$tenantsByDomain = Tenant::query()
|
||||
->whereIn('dominio', $candidateKeys)
|
||||
->get()
|
||||
->keyBy('dominio');
|
||||
|
||||
$tenant = collect($candidateKeys)
|
||||
->map(fn (string $candidate): ?Tenant => $tenantsByDomain->get($candidate))
|
||||
->first(fn (?Tenant $candidate): bool => $candidate !== null);
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
throw (new ModelNotFoundException)->setModel(Tenant::class);
|
||||
}
|
||||
|
||||
return $this->tenantInformationService->load(
|
||||
$tenant,
|
||||
[
|
||||
'menues' => fn ($query) => $query->whereHas(
|
||||
'roles',
|
||||
fn ($query) => $query->where('codigo', RoleCode::User->value)
|
||||
),
|
||||
'categories' => fn ($query) => $query->orderBy('nombre'),
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
28
app/Domains/Bootstrap/documentacion/README.md
Normal file
28
app/Domains/Bootstrap/documentacion/README.md
Normal file
@@ -0,0 +1,28 @@
|
||||
# Dominio Bootstrap
|
||||
|
||||
## Propósito
|
||||
|
||||
Entrega la configuración inicial que necesitan la tienda y el panel administrativo antes de renderizar su interfaz.
|
||||
|
||||
## Flujos
|
||||
|
||||
- `TenantBootstrapService` resuelve un tenant desde el dominio solicitado y carga su información pública.
|
||||
- `AdminAppBootstrapService` prepara el contexto inicial del panel administrativo para el tenant autenticado.
|
||||
- Los controladores invocables transforman el resultado mediante `TenantResource` o `AdminAppBootstrapResource`.
|
||||
|
||||
## Endpoints
|
||||
|
||||
- `GET /tenants/bootstrap?dominio={hostname}&path={path}`: bootstrap público de la tienda. Resuelve la clave de tenant más específica que sea prefijo completo del path y usa el dominio raíz como fallback.
|
||||
- Endpoint de bootstrap bajo `/v1/adminapp`, protegido por `auth:sanctum` y `adminapp.tenant`.
|
||||
|
||||
## Validación
|
||||
|
||||
`TenantBootstrapRequest` valida y normaliza por separado el hostname y el path recibidos. `AdminAppBootstrapRequest` reutiliza ese contrato para el panel.
|
||||
|
||||
## Dependencias
|
||||
|
||||
Depende principalmente de `Tenant` para resolver y cargar la tienda, y de los dominios que aportan datos al contexto administrativo.
|
||||
|
||||
## Consideraciones
|
||||
|
||||
Este dominio es un agregador de lectura. Debe mantenerse liviano y delegar la obtención de cada dato al dominio propietario.
|
||||
9
app/Domains/Bootstrap/routes/adminapp.php
Normal file
9
app/Domains/Bootstrap/routes/adminapp.php
Normal file
@@ -0,0 +1,9 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Bootstrap\Controllers\AdminAppBootstrapController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::get(
|
||||
'v1/adminapp/bootstrap/{dominio}',
|
||||
AdminAppBootstrapController::class
|
||||
);
|
||||
9
app/Domains/Bootstrap/routes/api.php
Normal file
9
app/Domains/Bootstrap/routes/api.php
Normal file
@@ -0,0 +1,9 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Bootstrap\Controllers\TenantBootstrapController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::get('tenants/bootstrap', TenantBootstrapController::class);
|
||||
|
||||
require __DIR__.'/adminapp.php';
|
||||
require __DIR__.'/scanner.php';
|
||||
9
app/Domains/Bootstrap/routes/scanner.php
Normal file
9
app/Domains/Bootstrap/routes/scanner.php
Normal file
@@ -0,0 +1,9 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Bootstrap\Controllers\ScannerBootstrapController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::get(
|
||||
'v1/scanner/bootstrap/{dominio}',
|
||||
ScannerBootstrapController::class
|
||||
);
|
||||
@@ -36,7 +36,10 @@ class CartController extends Controller
|
||||
);
|
||||
|
||||
$response = CartResource::make($result['cart'])
|
||||
->additional(['message' => 'Producto agregado al carrito.'])
|
||||
->additional([
|
||||
'code' => 'cart.item_added',
|
||||
'message' => __('api.cart.item_added'),
|
||||
])
|
||||
->response();
|
||||
|
||||
if ($result['guest_token'] !== null) {
|
||||
@@ -51,20 +54,36 @@ class CartController extends Controller
|
||||
Tenant $tenant,
|
||||
CartItem $cartItem,
|
||||
): CartResource {
|
||||
$updatesVariant = $request->exists('variant_id');
|
||||
|
||||
return CartResource::make(
|
||||
$this->cartService->updateItemQuantity(
|
||||
$this->cartService->updateItem(
|
||||
$tenant,
|
||||
$request,
|
||||
$cartItem->getKey(),
|
||||
(int) $request->validated('cantidad'),
|
||||
$updatesVariant
|
||||
? ($request->validated('variant_id') !== null
|
||||
? (int) $request->validated('variant_id')
|
||||
: null)
|
||||
: $cartItem->variant_id,
|
||||
$updatesVariant,
|
||||
)
|
||||
)->additional(['message' => 'Cantidad de producto actualizada.']);
|
||||
)->additional([
|
||||
'code' => $updatesVariant ? 'cart.item_updated' : 'cart.quantity_updated',
|
||||
'message' => $updatesVariant
|
||||
? __('api.cart.item_updated')
|
||||
: __('api.cart.quantity_updated'),
|
||||
]);
|
||||
}
|
||||
|
||||
public function removeItem(Request $request, Tenant $tenant, CartItem $cartItem): CartResource
|
||||
{
|
||||
return CartResource::make(
|
||||
$this->cartService->removeItem($tenant, $request, $cartItem->getKey())
|
||||
)->additional(['message' => 'Producto eliminado del carrito.']);
|
||||
)->additional([
|
||||
'code' => 'cart.item_removed',
|
||||
'message' => __('api.cart.item_removed'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Cart\Middleware;
|
||||
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Cookie;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class MergeGuestCartMiddleware
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$guestToken = $request->cookie('guest_token');
|
||||
|
||||
// Resolve authenticated user optionally (from default guard or sanctum guard)
|
||||
$user = $request->user() ?? Auth::guard('sanctum')->user();
|
||||
$userId = $user?->getKey();
|
||||
|
||||
\Illuminate\Support\Facades\Log::info('MergeGuestCartMiddleware processed', [
|
||||
'user_id' => $userId,
|
||||
'guest_token' => $guestToken,
|
||||
]);
|
||||
|
||||
if ($user !== null && is_string($guestToken) && $guestToken !== '') {
|
||||
$tenantParam = $request->route('tenant');
|
||||
$tenantCodigo = null;
|
||||
|
||||
if ($tenantParam instanceof Tenant) {
|
||||
$tenantCodigo = $tenantParam->codigo;
|
||||
} elseif (is_string($tenantParam)) {
|
||||
$tenantCodigo = $tenantParam;
|
||||
}
|
||||
|
||||
if ($tenantCodigo !== null) {
|
||||
$guestCart = Cart::query()
|
||||
->where('tenant_codigo', $tenantCodigo)
|
||||
->where('guest_token', $guestToken)
|
||||
->first();
|
||||
|
||||
if ($guestCart !== null && $guestCart->items()->exists()) {
|
||||
$userCart = Cart::query()
|
||||
->where('tenant_codigo', $tenantCodigo)
|
||||
->where('user_id', $userId)
|
||||
->first();
|
||||
|
||||
if ($userCart !== null) {
|
||||
$userCart->delete();
|
||||
}
|
||||
|
||||
$guestCart->update([
|
||||
'user_id' => $userId,
|
||||
'guest_token' => null,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$response = $next($request);
|
||||
|
||||
if ($user !== null && is_string($guestToken) && $guestToken !== '') {
|
||||
// Remove the cookie from the response since the user is authenticated.
|
||||
if (method_exists($response, 'withCookie')) {
|
||||
$response->withCookie(Cookie::forget('guest_token'));
|
||||
}
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Inventory;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Catalog\Services\CatalogInventoryService;
|
||||
use App\Domains\Purchase\Services\UserPurchaseLimitService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
@@ -79,19 +80,23 @@ class Cart extends Model
|
||||
{
|
||||
if ($quantity <= 0) {
|
||||
throw ValidationException::withMessages([
|
||||
'cantidad' => 'La cantidad debe ser mayor a cero.',
|
||||
'cantidad' => __('api.cart.positive_quantity'),
|
||||
]);
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($catalogItemId, $variantId, $quantity): CartItem {
|
||||
self::query()->whereKey($this->getKey())->lockForUpdate()->firstOrFail();
|
||||
$selectedItem = $this->resolveScopedItem($catalogItemId, $variantId, true);
|
||||
$cartQuantity = (int) $this->items()
|
||||
->where('catalog_item_id', $catalogItemId)
|
||||
->sum('cantidad');
|
||||
$this->assertUserPurchaseLimit($selectedItem, $cartQuantity + $quantity);
|
||||
$inventoryService = app(CatalogInventoryService::class);
|
||||
$availableQuantity = $inventoryService->availableQuantity($selectedItem);
|
||||
|
||||
if ($availableQuantity !== null && $availableQuantity < $quantity) {
|
||||
throw ValidationException::withMessages([
|
||||
'cantidad' => "Stock insuficiente para el producto solicitado. Maximo disponible: {$availableQuantity}.",
|
||||
'cantidad' => __('api.cart.insufficient_stock', ['max' => $availableQuantity]),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -119,34 +124,104 @@ class Cart extends Model
|
||||
});
|
||||
}
|
||||
|
||||
public function updateItem(int $cartItemId, int $quantity): CartItem
|
||||
{
|
||||
public function updateItem(
|
||||
int $cartItemId,
|
||||
int $quantity,
|
||||
?int $variantId = null,
|
||||
bool $updateVariant = false,
|
||||
): CartItem {
|
||||
if ($quantity <= 0) {
|
||||
throw ValidationException::withMessages([
|
||||
'cantidad' => 'La cantidad debe ser mayor a cero.',
|
||||
'cantidad' => __('api.cart.positive_quantity'),
|
||||
]);
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($cartItemId, $quantity): CartItem {
|
||||
return DB::transaction(function () use (
|
||||
$cartItemId,
|
||||
$quantity,
|
||||
$variantId,
|
||||
$updateVariant,
|
||||
): CartItem {
|
||||
/** @var CartItem $item */
|
||||
$item = $this->items()
|
||||
->where('id', $cartItemId)
|
||||
->lockForUpdate()
|
||||
->firstOrFail();
|
||||
|
||||
$selectedItem = $this->resolveScopedItem(
|
||||
$currentSelection = $this->resolveScopedItem(
|
||||
$item->catalog_item_id,
|
||||
$item->variant_id,
|
||||
true,
|
||||
);
|
||||
$inventoryService = app(CatalogInventoryService::class);
|
||||
|
||||
if ($updateVariant && $variantId !== $item->variant_id) {
|
||||
$nextSelection = $this->resolveScopedItem(
|
||||
$item->catalog_item_id,
|
||||
$variantId,
|
||||
true,
|
||||
);
|
||||
$otherVariantsQuantity = (int) $this->items()
|
||||
->where('catalog_item_id', $item->catalog_item_id)
|
||||
->whereKeyNot($item->getKey())
|
||||
->sum('cantidad');
|
||||
$this->assertUserPurchaseLimit(
|
||||
$nextSelection,
|
||||
$otherVariantsQuantity + $quantity,
|
||||
);
|
||||
|
||||
$inventoryService->release($currentSelection, $item->cantidad);
|
||||
$availableQuantity = $inventoryService->availableQuantity($nextSelection);
|
||||
|
||||
if ($availableQuantity !== null && $availableQuantity < $quantity) {
|
||||
throw ValidationException::withMessages([
|
||||
'variant_id' => __('api.cart.insufficient_stock', ['max' => $availableQuantity]),
|
||||
]);
|
||||
}
|
||||
|
||||
$targetItem = $this->items()
|
||||
->where('catalog_item_id', $item->catalog_item_id)
|
||||
->where('variant_id', $variantId)
|
||||
->whereKeyNot($item->getKey())
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
$inventoryService->reserve($nextSelection, $quantity);
|
||||
|
||||
if ($targetItem !== null) {
|
||||
$targetItem->cantidad += $quantity;
|
||||
$targetItem->save();
|
||||
$item->delete();
|
||||
|
||||
return $targetItem->fresh();
|
||||
}
|
||||
|
||||
$item->variant_id = $variantId;
|
||||
$item->cantidad = $quantity;
|
||||
$item->save();
|
||||
|
||||
return $item->fresh();
|
||||
}
|
||||
|
||||
$delta = $quantity - $item->cantidad;
|
||||
$availableQuantity = $inventoryService->availableQuantity($selectedItem);
|
||||
|
||||
if ($delta > 0) {
|
||||
$otherVariantsQuantity = (int) $this->items()
|
||||
->where('catalog_item_id', $item->catalog_item_id)
|
||||
->whereKeyNot($item->getKey())
|
||||
->sum('cantidad');
|
||||
$this->assertUserPurchaseLimit(
|
||||
$currentSelection,
|
||||
$otherVariantsQuantity + $quantity,
|
||||
);
|
||||
}
|
||||
|
||||
$availableQuantity = $inventoryService->availableQuantity($currentSelection);
|
||||
|
||||
if ($delta > 0 && $availableQuantity !== null && $availableQuantity < $delta) {
|
||||
$maxAvailable = $availableQuantity + $item->cantidad;
|
||||
throw ValidationException::withMessages([
|
||||
'cantidad' => "El máximo que se puede agregar es {$maxAvailable}.",
|
||||
'cantidad' => __('api.cart.max_quantity', ['max' => $maxAvailable]),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -154,11 +229,11 @@ class Cart extends Model
|
||||
$item->save();
|
||||
|
||||
if ($delta > 0) {
|
||||
$inventoryService->reserve($selectedItem, $delta);
|
||||
$inventoryService->reserve($currentSelection, $delta);
|
||||
}
|
||||
|
||||
if ($delta < 0) {
|
||||
$inventoryService->release($selectedItem, abs($delta));
|
||||
$inventoryService->release($currentSelection, abs($delta));
|
||||
}
|
||||
|
||||
return $item->fresh();
|
||||
@@ -209,13 +284,13 @@ class Cart extends Model
|
||||
if ($catalogItem->isBundle()) {
|
||||
if ($variantId !== null) {
|
||||
throw ValidationException::withMessages([
|
||||
'variant_id' => 'Un bundle no admite una variante.',
|
||||
'variant_id' => __('api.cart.bundle_variant_forbidden'),
|
||||
]);
|
||||
}
|
||||
|
||||
if (! $catalogItem->bundleComponents()->exists()) {
|
||||
throw ValidationException::withMessages([
|
||||
'catalog_item_id' => 'El bundle no tiene componentes.',
|
||||
'catalog_item_id' => __('api.cart.empty_bundle'),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -225,7 +300,7 @@ class Cart extends Model
|
||||
if ($variantId === null) {
|
||||
if ($catalogItem->inventory_id === null) {
|
||||
throw ValidationException::withMessages([
|
||||
'variant_id' => 'Debe seleccionar una variante para este ítem.',
|
||||
'variant_id' => __('api.cart.variant_required'),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -256,6 +331,26 @@ class Cart extends Model
|
||||
return $variant;
|
||||
}
|
||||
|
||||
private function assertUserPurchaseLimit(
|
||||
CatalogItem|Variant $selectedItem,
|
||||
int $cartQuantity,
|
||||
): void {
|
||||
if ($this->user_id === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$catalogItem = $selectedItem instanceof Variant
|
||||
? $selectedItem->catalogItem
|
||||
: $selectedItem;
|
||||
|
||||
app(UserPurchaseLimitService::class)->assertCanPurchase(
|
||||
$catalogItem,
|
||||
$this->user_id,
|
||||
$cartQuantity,
|
||||
field: 'cantidad',
|
||||
);
|
||||
}
|
||||
|
||||
protected function resolveInventory(int $inventoryId, bool $lockForUpdate): Inventory
|
||||
{
|
||||
$query = Inventory::query()->whereKey($inventoryId);
|
||||
|
||||
@@ -19,7 +19,7 @@ class UpdateCartItemQuantityRequest extends FormRequest
|
||||
return [
|
||||
'cantidad' => ['required', 'integer', 'min:1'],
|
||||
'catalog_item_id' => ['prohibited'],
|
||||
'variant_id' => ['prohibited'],
|
||||
'variant_id' => ['sometimes', 'nullable', 'integer'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
namespace App\Domains\Cart\Resources;
|
||||
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
@@ -36,6 +38,16 @@ class CartItemResource extends JsonResource
|
||||
'product' => $selectedItem === null ? null : [
|
||||
'nombre' => $selectedItem->getName(),
|
||||
'imagen' => $imageUrl,
|
||||
'variants' => $this->catalogItem->visibleVariants($this->variant_id)
|
||||
->map(fn (Variant $variant): array => [
|
||||
'id' => $variant->id,
|
||||
'precio' => $this->formatMoney($variant->getPrice()),
|
||||
'stock_tecnico' => $this->catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
||||
? null
|
||||
: $variant->inventory->availableStock(),
|
||||
'values' => $variant->selectorOptions($this->catalogItem->itemAttributes),
|
||||
])
|
||||
->values(),
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -51,11 +51,17 @@ class CartService
|
||||
];
|
||||
}
|
||||
|
||||
public function updateItemQuantity(Tenant $tenant, Request $request, int $cartItemId, int $quantity): Cart
|
||||
{
|
||||
public function updateItem(
|
||||
Tenant $tenant,
|
||||
Request $request,
|
||||
int $cartItemId,
|
||||
int $quantity,
|
||||
?int $variantId,
|
||||
bool $updateVariant,
|
||||
): Cart {
|
||||
$identity = $this->requireIdentity($request);
|
||||
$cart = $this->findCartOrFail($tenant, $identity);
|
||||
$cart->updateItem($cartItemId, $quantity);
|
||||
$cart->updateItem($cartItemId, $quantity, $variantId, $updateVariant);
|
||||
|
||||
return $this->loadCart($cart);
|
||||
}
|
||||
@@ -76,11 +82,11 @@ class CartService
|
||||
$guestToken,
|
||||
60 * 24 * 180,
|
||||
'/',
|
||||
null,
|
||||
false,
|
||||
config('session.domain'),
|
||||
(bool) config('session.secure'),
|
||||
true,
|
||||
false,
|
||||
'lax',
|
||||
config('session.same_site'),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -101,9 +107,16 @@ class CartService
|
||||
return $cart->fresh()->load([
|
||||
'items.catalogItem.attachments',
|
||||
'items.catalogItem.inventory',
|
||||
'items.catalogItem.itemAttributes.attribute',
|
||||
'items.catalogItem.variants.inventory',
|
||||
'items.catalogItem.variants.definitions.itemAttribute.attribute.options',
|
||||
'items.catalogItem.variants.eventDates',
|
||||
'items.catalogItem.variants.eventDate',
|
||||
'items.variant.attachments',
|
||||
'items.variant.inventory',
|
||||
'items.variant.definitions.itemAttribute.attribute',
|
||||
'items.variant.definitions.itemAttribute.attribute.options',
|
||||
'items.variant.eventDates',
|
||||
'items.variant.eventDate',
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -172,6 +185,7 @@ class CartService
|
||||
{
|
||||
return Cart::query()
|
||||
->where('tenant_codigo', $tenant->codigo)
|
||||
->where('status', 'active')
|
||||
->when(
|
||||
$identity['user_id'] !== null,
|
||||
fn ($query) => $query->where('user_id', $identity['user_id']),
|
||||
@@ -199,7 +213,10 @@ class CartService
|
||||
*/
|
||||
protected function findOrCreateCart(Tenant $tenant, array $identity): Cart
|
||||
{
|
||||
$attributes = ['tenant_codigo' => $tenant->codigo];
|
||||
$attributes = [
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
'status' => 'active',
|
||||
];
|
||||
|
||||
if ($identity['user_id'] !== null) {
|
||||
$attributes['user_id'] = $identity['user_id'];
|
||||
@@ -207,6 +224,6 @@ class CartService
|
||||
$attributes['guest_token'] = $identity['guest_token'];
|
||||
}
|
||||
|
||||
return Cart::query()->firstOrCreate($attributes, ['status' => 'active']);
|
||||
return Cart::query()->firstOrCreate($attributes);
|
||||
}
|
||||
}
|
||||
|
||||
49
app/Domains/Cart/Services/GuestCartMergeService.php
Normal file
49
app/Domains/Cart/Services/GuestCartMergeService.php
Normal file
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Cart\Services;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class GuestCartMergeService
|
||||
{
|
||||
public function merge(string $tenantCodigo, User $user, ?string $guestToken): void
|
||||
{
|
||||
if ($guestToken === null || $guestToken === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
DB::transaction(function () use ($tenantCodigo, $user, $guestToken): void {
|
||||
$guestCart = Cart::query()
|
||||
->where('tenant_codigo', $tenantCodigo)
|
||||
->where('guest_token', $guestToken)
|
||||
->where('status', 'active')
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($guestCart === null || ! $guestCart->items()->exists()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$userCart = Cart::query()
|
||||
->where('tenant_codigo', $tenantCodigo)
|
||||
->where('user_id', $user->getKey())
|
||||
->where('status', 'active')
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($userCart !== null) {
|
||||
$userCart->update([
|
||||
'status' => 'converted',
|
||||
]);
|
||||
$userCart->delete();
|
||||
}
|
||||
|
||||
$guestCart->update([
|
||||
'user_id' => $user->getKey(),
|
||||
'guest_token' => null,
|
||||
]);
|
||||
});
|
||||
}
|
||||
}
|
||||
32
app/Domains/Cart/documentacion/README.md
Normal file
32
app/Domains/Cart/documentacion/README.md
Normal file
@@ -0,0 +1,32 @@
|
||||
# Dominio Cart
|
||||
|
||||
## Propósito
|
||||
|
||||
Gestiona el carrito activo de un tenant tanto para visitantes como para usuarios autenticados.
|
||||
|
||||
## Modelo
|
||||
|
||||
- `Cart`: pertenece a un tenant y opcionalmente a un usuario; calcula el total y permite agregar, actualizar o quitar ítems.
|
||||
- `CartItem`: referencia un `CatalogItem` y, opcionalmente, una `Variant`; expone la selección efectiva.
|
||||
|
||||
## Servicios
|
||||
|
||||
- `CartService`: obtiene el carrito, modifica ítems y administra la cookie del token invitado.
|
||||
- `GuestCartMergeService`: incorpora el carrito invitado al usuario cuando este se autentica.
|
||||
|
||||
## Endpoints
|
||||
|
||||
Bajo `/tenants/{tenant:codigo}`:
|
||||
|
||||
- `GET /cart`.
|
||||
- `POST /cart/items`.
|
||||
- `PATCH /cart/items/{cartItem}`.
|
||||
- `DELETE /cart/items/{cartItem}`.
|
||||
|
||||
## Contratos
|
||||
|
||||
`AddCartItemRequest` y `UpdateCartItemQuantityRequest` validan selección y cantidad. `CartResource` y `CartItemResource` estabilizan la respuesta pública.
|
||||
|
||||
## Dependencias y reglas
|
||||
|
||||
Depende de `Catalog` para productos y variantes, de `Tenant` para aislar datos y de `Auth` cuando existe usuario. Toda operación debe comprobar que carrito e ítem pertenecen al tenant actual.
|
||||
@@ -4,7 +4,6 @@ use App\Domains\Cart\Controllers\CartController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::prefix('tenants/{tenant:codigo}')
|
||||
->middleware(\App\Domains\Cart\Middleware\MergeGuestCartMiddleware::class)
|
||||
->group(function (): void {
|
||||
Route::get('cart', [CartController::class, 'show']);
|
||||
Route::post('cart/items', [CartController::class, 'addItem']);
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Controllers\AdminApp;
|
||||
|
||||
use App\Domains\Catalog\Models\FeaturedGroup;
|
||||
use App\Domains\Catalog\Requests\AdminApp\UpsertOnTicketFeaturedGroupRequest;
|
||||
use App\Domains\Catalog\Resources\AdminApp\OnTicketFeaturedGroupResource;
|
||||
use App\Domains\Catalog\Services\OnTicketFeaturedGroupService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
|
||||
|
||||
class OnTicketFeaturedGroupController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly OnTicketFeaturedGroupService $featuredGroupService,
|
||||
) {}
|
||||
|
||||
public function index(Request $request): AnonymousResourceCollection
|
||||
{
|
||||
return OnTicketFeaturedGroupResource::collection(
|
||||
$this->featuredGroupService->forTenant($this->onTicketTenant($request))
|
||||
);
|
||||
}
|
||||
|
||||
public function store(UpsertOnTicketFeaturedGroupRequest $request): JsonResponse
|
||||
{
|
||||
$featuredGroup = $this->featuredGroupService->create(
|
||||
$this->onTicketTenant($request),
|
||||
$request->validated(),
|
||||
);
|
||||
|
||||
return OnTicketFeaturedGroupResource::make($featuredGroup)
|
||||
->response()
|
||||
->setStatusCode(201);
|
||||
}
|
||||
|
||||
public function update(
|
||||
UpsertOnTicketFeaturedGroupRequest $request,
|
||||
FeaturedGroup $featuredGroup,
|
||||
): OnTicketFeaturedGroupResource {
|
||||
$tenant = $this->onTicketTenant($request);
|
||||
|
||||
abort_unless($featuredGroup->tenant_code === $tenant->codigo, 404);
|
||||
|
||||
return OnTicketFeaturedGroupResource::make(
|
||||
$this->featuredGroupService->update(
|
||||
$tenant,
|
||||
$featuredGroup,
|
||||
$request->validated(),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
private function onTicketTenant(Request $request): Tenant
|
||||
{
|
||||
$tenant = $request->user()->tenant()->firstOrFail();
|
||||
|
||||
abort_unless($tenant->website_type_code === 'onticket', 404);
|
||||
|
||||
return $tenant;
|
||||
}
|
||||
}
|
||||
@@ -2,26 +2,32 @@
|
||||
|
||||
namespace App\Domains\Catalog\Controllers;
|
||||
|
||||
use App\Domains\Cart\Services\CartService;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Category;
|
||||
use App\Domains\Catalog\Models\FeaturedGroup;
|
||||
use App\Domains\Catalog\Requests\CatalogItemDetailRequest;
|
||||
use App\Domains\Catalog\Requests\CatalogVariantOptionsRequest;
|
||||
use App\Domains\Catalog\Requests\CategoryPageRequest;
|
||||
use App\Domains\Catalog\Requests\FeaturedGroupPageRequest;
|
||||
use App\Domains\Catalog\Requests\SearchCatalogItemsRequest;
|
||||
use App\Domains\Catalog\Requests\StoreCatalogItemRequest;
|
||||
use App\Domains\Catalog\Resources\CatalogFeaturedGroupResource;
|
||||
use App\Domains\Catalog\Resources\CatalogFeaturedItemResource;
|
||||
use App\Domains\Catalog\Resources\CatalogItemDetailResource;
|
||||
use App\Domains\Catalog\Resources\CatalogItemResource;
|
||||
use App\Domains\Catalog\Resources\CatalogSearchItemResource;
|
||||
use App\Domains\Catalog\Resources\CatalogVariantOptionsResource;
|
||||
use App\Domains\Catalog\Services\CatalogService;
|
||||
use App\Domains\Catalog\Services\FeaturedGroupService;
|
||||
use App\Domains\Catalog\Services\VariantSelectionService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
|
||||
|
||||
class CatalogController extends Controller
|
||||
{
|
||||
private const ITEMS_PER_PAGE = 12;
|
||||
|
||||
public function index(Tenant $tenant): JsonResponse
|
||||
public function index(Tenant $tenant, FeaturedGroupService $featuredGroupService): JsonResponse
|
||||
{
|
||||
$featuredGroups = FeaturedGroup::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
@@ -31,21 +37,63 @@ class CatalogController extends Controller
|
||||
return response()->json($featuredGroups->map(
|
||||
fn (FeaturedGroup $featuredGroup): array => (new CatalogFeaturedGroupResource(
|
||||
$featuredGroup,
|
||||
$this->featuredItemsResponse($featuredGroup, 1),
|
||||
$featuredGroupService->itemsResponse($featuredGroup, 1),
|
||||
))->resolve()
|
||||
));
|
||||
}
|
||||
|
||||
public function search(
|
||||
SearchCatalogItemsRequest $request,
|
||||
Tenant $tenant,
|
||||
CatalogService $catalogService,
|
||||
): AnonymousResourceCollection {
|
||||
return CatalogSearchItemResource::collection(
|
||||
$catalogService->search(
|
||||
$tenant,
|
||||
$request->validated('q'),
|
||||
$tenant->search_items_per_page,
|
||||
(int) $request->validated('page', 1),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
public function category(
|
||||
CategoryPageRequest $request,
|
||||
Tenant $tenant,
|
||||
Category $category,
|
||||
CatalogService $catalogService,
|
||||
): AnonymousResourceCollection {
|
||||
abort_unless($category->tenant_code === $tenant->codigo, 404);
|
||||
|
||||
return CatalogSearchItemResource::collection(
|
||||
$catalogService->categoryItems(
|
||||
$tenant,
|
||||
$category,
|
||||
$tenant->search_items_per_page,
|
||||
(int) $request->validated('page', 1),
|
||||
)
|
||||
)->additional([
|
||||
'category' => [
|
||||
'id' => $category->id,
|
||||
'nombre' => $category->nombre,
|
||||
'categoria_id' => $category->categoria_id,
|
||||
],
|
||||
'layout' => $tenant->search_product_layout->value,
|
||||
'group_layout' => $tenant->search_group_layout->value,
|
||||
]);
|
||||
}
|
||||
|
||||
public function featuredGroupItems(
|
||||
FeaturedGroupPageRequest $request,
|
||||
Tenant $tenant,
|
||||
FeaturedGroup $featuredGroup,
|
||||
FeaturedGroupService $featuredGroupService,
|
||||
): JsonResponse {
|
||||
abort_unless($featuredGroup->tenant_code === $tenant->codigo, 404);
|
||||
|
||||
$page = (int) $request->validated('page', 1);
|
||||
|
||||
return response()->json($this->featuredItemsResponse($featuredGroup, $page));
|
||||
return response()->json($featuredGroupService->itemsResponse($featuredGroup, $page));
|
||||
}
|
||||
|
||||
public function show(
|
||||
@@ -66,6 +114,35 @@ class CatalogController extends Controller
|
||||
);
|
||||
}
|
||||
|
||||
public function variantOptions(
|
||||
CatalogVariantOptionsRequest $request,
|
||||
Tenant $tenant,
|
||||
CatalogItem $catalogItem,
|
||||
VariantSelectionService $variantSelectionService,
|
||||
CartService $cartService,
|
||||
): CatalogVariantOptionsResource {
|
||||
abort_unless($catalogItem->tenant_code === $tenant->codigo, 404);
|
||||
|
||||
$includedVariantId = null;
|
||||
$cartItemId = $request->validated('cart_item_id');
|
||||
|
||||
if ($cartItemId !== null) {
|
||||
$cartItem = $cartService->show($tenant, $request)
|
||||
->items
|
||||
->firstWhere('id', (int) $cartItemId);
|
||||
abort_unless($cartItem?->catalog_item_id === $catalogItem->id, 404);
|
||||
$includedVariantId = $cartItem->variant_id;
|
||||
}
|
||||
|
||||
return CatalogVariantOptionsResource::make(
|
||||
$variantSelectionService->options(
|
||||
$catalogItem,
|
||||
$request->validated('selected_values', []),
|
||||
$includedVariantId,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
public function store(
|
||||
StoreCatalogItemRequest $request,
|
||||
Tenant $tenant,
|
||||
@@ -80,44 +157,4 @@ class CatalogController extends Controller
|
||||
->response()
|
||||
->setStatusCode(201);
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
private function featuredItemsResponse(FeaturedGroup $featuredGroup, int $page): array
|
||||
{
|
||||
$paginator = $this->paginateFeaturedItems($featuredGroup, $page);
|
||||
|
||||
$paginator->getCollection()->each(
|
||||
fn ($featuredItem) => $featuredItem->setRelation('featuredGroup', $featuredGroup)
|
||||
);
|
||||
|
||||
return CatalogFeaturedItemResource::collection($paginator)
|
||||
->response()
|
||||
->getData(true);
|
||||
}
|
||||
|
||||
private function paginateFeaturedItems(
|
||||
FeaturedGroup $featuredGroup,
|
||||
int $page,
|
||||
): LengthAwarePaginator {
|
||||
$paginator = $featuredGroup->featuredItems()
|
||||
->with([
|
||||
'catalogItem.inventory',
|
||||
'catalogItem.attachments',
|
||||
'catalogItem.variants.inventory',
|
||||
'catalogItem.variants.attachments',
|
||||
'catalogItem.variants.definitions.itemAttribute.attribute',
|
||||
'catalogItem.bundleComponents.catalogItem',
|
||||
'catalogItem.bundleComponents.variant.catalogItem',
|
||||
])
|
||||
->paginate(
|
||||
perPage: self::ITEMS_PER_PAGE,
|
||||
pageName: 'page',
|
||||
page: $page,
|
||||
);
|
||||
|
||||
return $paginator->withPath(route('catalog.featured-groups.items.index', [
|
||||
'tenant' => $featuredGroup->tenant_code,
|
||||
'featuredGroup' => $featuredGroup->id,
|
||||
]));
|
||||
}
|
||||
}
|
||||
|
||||
18
app/Domains/Catalog/Enums/FeaturedGroupSource.php
Normal file
18
app/Domains/Catalog/Enums/FeaturedGroupSource.php
Normal file
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Enums;
|
||||
|
||||
enum FeaturedGroupSource: string
|
||||
{
|
||||
case Manual = 'manual';
|
||||
case Category = 'category';
|
||||
case All = 'all';
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function values(): array
|
||||
{
|
||||
return array_column(self::cases(), 'value');
|
||||
}
|
||||
}
|
||||
20
app/Domains/Catalog/Enums/GroupLayout.php
Normal file
20
app/Domains/Catalog/Enums/GroupLayout.php
Normal file
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Enums;
|
||||
|
||||
enum GroupLayout: string
|
||||
{
|
||||
case Paginated = 'paginated';
|
||||
case Simple = 'simple';
|
||||
case SimpleVertical = 'simple_vertical';
|
||||
case Carousel = 'carousel';
|
||||
case Single = 'single';
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function values(): array
|
||||
{
|
||||
return array_column(self::cases(), 'value');
|
||||
}
|
||||
}
|
||||
16
app/Domains/Catalog/Enums/InventorySubject.php
Normal file
16
app/Domains/Catalog/Enums/InventorySubject.php
Normal file
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Enums;
|
||||
|
||||
enum InventorySubject: string
|
||||
{
|
||||
case Product = 'product';
|
||||
case Seat = 'seat';
|
||||
case Ticket = 'ticket';
|
||||
|
||||
/** @return array<int, string> */
|
||||
public static function values(): array
|
||||
{
|
||||
return array_column(self::cases(), 'value');
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ enum ProductLayout: string
|
||||
case Row = 'row';
|
||||
case ColumnWithImage = 'column_with_image';
|
||||
case ColumnWithCart = 'column_with_cart';
|
||||
case TicketSelector = 'ticket_selector';
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Domains\Catalog\Models;
|
||||
|
||||
use App\Domains\Event\Models\EventDate;
|
||||
use App\Domains\Shared\Enums\FieldType;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
@@ -51,4 +52,14 @@ class Attribute extends Model
|
||||
{
|
||||
return $this->hasMany(AttributeOption::class, 'attribute_id')->orderBy('sort_order');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<EventDate, $this>
|
||||
*/
|
||||
public function eventDates(): HasMany
|
||||
{
|
||||
return $this->hasMany(EventDate::class, 'tenant_code', 'tenant_codigo')
|
||||
->orderBy('date')
|
||||
->orderBy('time_start');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Domains\Catalog\Models;
|
||||
|
||||
use App\Domains\Ticket\Models\ValidityTime;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
@@ -9,6 +10,7 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable([
|
||||
'attribute_id',
|
||||
'validity_time_id',
|
||||
'value',
|
||||
'label',
|
||||
'sort_order',
|
||||
@@ -26,6 +28,7 @@ class AttributeOption extends Model
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'validity_time_id' => 'integer',
|
||||
'sort_order' => 'integer',
|
||||
'metadata' => 'array',
|
||||
];
|
||||
@@ -38,4 +41,10 @@ class AttributeOption extends Model
|
||||
{
|
||||
return $this->belongsTo(Attribute::class, 'attribute_id');
|
||||
}
|
||||
|
||||
/** @return BelongsTo<ValidityTime, $this> */
|
||||
public function validityTime(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ValidityTime::class);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,14 +5,19 @@ namespace App\Domains\Catalog\Models;
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Catalog\Enums\CatalogItemType;
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Enums\InventorySubject;
|
||||
use App\Domains\Catalog\Services\CatalogInventoryService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
#[Fillable([
|
||||
'tenant_code',
|
||||
@@ -25,13 +30,13 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
'descripcion',
|
||||
'precio',
|
||||
'inventory_policy',
|
||||
'inventory_subject',
|
||||
'max_units_per_user',
|
||||
'has_tickets',
|
||||
'maximum_use_date',
|
||||
'minimum_use_date',
|
||||
])]
|
||||
class CatalogItem extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
use HasFactory, SoftDeletes;
|
||||
|
||||
public $timestamps = false;
|
||||
|
||||
@@ -40,6 +45,7 @@ class CatalogItem extends Model
|
||||
protected $attributes = [
|
||||
'type' => CatalogItemType::Standard->value,
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'inventory_subject' => InventorySubject::Product->value,
|
||||
'has_tickets' => false,
|
||||
];
|
||||
|
||||
@@ -52,9 +58,9 @@ class CatalogItem extends Model
|
||||
'type' => CatalogItemType::class,
|
||||
'precio' => 'decimal:2',
|
||||
'inventory_policy' => InventoryPolicy::class,
|
||||
'inventory_subject' => InventorySubject::class,
|
||||
'max_units_per_user' => 'integer',
|
||||
'has_tickets' => 'boolean',
|
||||
'maximum_use_date' => 'datetime',
|
||||
'minimum_use_date' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -100,6 +106,12 @@ class CatalogItem extends Model
|
||||
return $this->hasMany(Variant::class);
|
||||
}
|
||||
|
||||
/** @return HasMany<Ticket, $this> */
|
||||
public function sourceTickets(): HasMany
|
||||
{
|
||||
return $this->hasMany(Ticket::class, 'source_catalog_item_id');
|
||||
}
|
||||
|
||||
/** @return BelongsToMany<Attribute, $this> */
|
||||
public function attributes(): BelongsToMany
|
||||
{
|
||||
@@ -121,6 +133,12 @@ class CatalogItem extends Model
|
||||
|
||||
/** @return BelongsToMany<Attachment, $this> */
|
||||
public function attachments(): BelongsToMany
|
||||
{
|
||||
return $this->allAttachments()->wherePivot('is_enabled', true);
|
||||
}
|
||||
|
||||
/** @return BelongsToMany<Attachment, $this> */
|
||||
public function allAttachments(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(
|
||||
Attachment::class,
|
||||
@@ -128,7 +146,7 @@ class CatalogItem extends Model
|
||||
'catalog_item_id',
|
||||
'attachment_id'
|
||||
)
|
||||
->withPivot('orden')
|
||||
->withPivot(['orden', 'is_enabled'])
|
||||
->wherePivotNull('variant_id')
|
||||
->orderByPivot('orden');
|
||||
}
|
||||
@@ -153,6 +171,31 @@ class CatalogItem extends Model
|
||||
return ($this->availableStock() ?? 0) > 0;
|
||||
}
|
||||
|
||||
/** @param Builder<CatalogItem> $query */
|
||||
public function scopeWhereVariantsAvailable(Builder $query): Builder
|
||||
{
|
||||
return $query->where(function (Builder $query): void {
|
||||
$query
|
||||
->whereDoesntHave('variants')
|
||||
->orWhere('catalog_items.inventory_policy', InventoryPolicy::Unlimited->value)
|
||||
->orWhereHas(
|
||||
'variants.inventory',
|
||||
fn (Builder $inventoryQuery): Builder => $inventoryQuery
|
||||
->whereColumn('inventories.real_stock', '>', 'inventories.reserved_stock')
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/** @return Collection<int, Variant> */
|
||||
public function visibleVariants(?int $includedVariantId = null): Collection
|
||||
{
|
||||
return $this->variants
|
||||
->filter(fn (Variant $variant): bool => ($includedVariantId !== null && $variant->id === $includedVariantId)
|
||||
|| $this->inventory_policy === InventoryPolicy::Unlimited
|
||||
|| ($variant->inventory?->availableStock() ?? 0) > 0)
|
||||
->values();
|
||||
}
|
||||
|
||||
public function getPrice(): float
|
||||
{
|
||||
return (float) $this->precio;
|
||||
@@ -163,6 +206,16 @@ class CatalogItem extends Model
|
||||
return $this->nombre;
|
||||
}
|
||||
|
||||
public function getSelectionLabel(): string
|
||||
{
|
||||
return $this->getName();
|
||||
}
|
||||
|
||||
public function getDescription(): ?string
|
||||
{
|
||||
return $this->descripcion;
|
||||
}
|
||||
|
||||
public function isBundle(): bool
|
||||
{
|
||||
return $this->type === CatalogItemType::Bundle;
|
||||
|
||||
@@ -2,11 +2,13 @@
|
||||
|
||||
namespace App\Domains\Catalog\Models;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
#[Fillable([
|
||||
@@ -64,4 +66,15 @@ class Category extends Model
|
||||
{
|
||||
return $this->hasMany(CatalogItem::class);
|
||||
}
|
||||
|
||||
/** @return BelongsToMany<User, $this> */
|
||||
public function scanners(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(
|
||||
User::class,
|
||||
'category_scanners',
|
||||
'categoria_id',
|
||||
'user_id',
|
||||
)->withTimestamps();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
namespace App\Domains\Catalog\Models;
|
||||
|
||||
use App\Domains\Catalog\Enums\FeaturedGroupSource;
|
||||
use App\Domains\Catalog\Enums\GroupLayout;
|
||||
use App\Domains\Catalog\Enums\ProductLayout;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
@@ -12,7 +14,10 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
#[Fillable([
|
||||
'tenant_code',
|
||||
'source_type',
|
||||
'category_id',
|
||||
'product_layout',
|
||||
'group_layout',
|
||||
'group_name',
|
||||
'group_order',
|
||||
])]
|
||||
@@ -24,10 +29,17 @@ class FeaturedGroup extends Model
|
||||
|
||||
protected $table = 'featured_groups';
|
||||
|
||||
protected $attributes = [
|
||||
'source_type' => FeaturedGroupSource::Manual->value,
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'source_type' => FeaturedGroupSource::class,
|
||||
'category_id' => 'integer',
|
||||
'product_layout' => ProductLayout::class,
|
||||
'group_layout' => GroupLayout::class,
|
||||
'group_order' => 'integer',
|
||||
];
|
||||
}
|
||||
@@ -38,6 +50,12 @@ class FeaturedGroup extends Model
|
||||
return $this->belongsTo(Tenant::class, 'tenant_code', 'codigo');
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Category, $this> */
|
||||
public function category(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Category::class);
|
||||
}
|
||||
|
||||
/** @return HasMany<FeaturedItem, $this> */
|
||||
public function featuredItems(): HasMany
|
||||
{
|
||||
|
||||
@@ -11,6 +11,9 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
#[Fillable([
|
||||
'catalog_item_id',
|
||||
'attribute_id',
|
||||
'allow_multi_select',
|
||||
'sort_order',
|
||||
'show_in_selector',
|
||||
])]
|
||||
class ItemAttribute extends Model
|
||||
{
|
||||
@@ -18,6 +21,21 @@ class ItemAttribute extends Model
|
||||
|
||||
protected $table = 'item_attributes';
|
||||
|
||||
protected $attributes = [
|
||||
'show_in_selector' => true,
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'catalog_item_id' => 'integer',
|
||||
'attribute_id' => 'integer',
|
||||
'allow_multi_select' => 'boolean',
|
||||
'sort_order' => 'integer',
|
||||
'show_in_selector' => 'boolean',
|
||||
];
|
||||
}
|
||||
|
||||
/** @return BelongsTo<CatalogItem, $this> */
|
||||
public function catalogItem(): BelongsTo
|
||||
{
|
||||
|
||||
@@ -3,20 +3,29 @@
|
||||
namespace App\Domains\Catalog\Models;
|
||||
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Event\Models\EventDate;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Lang;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
#[Fillable([
|
||||
'catalog_item_id',
|
||||
'event_date_id',
|
||||
'inventory_id',
|
||||
'descripcion',
|
||||
'precio',
|
||||
])]
|
||||
class Variant extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
use HasFactory, SoftDeletes;
|
||||
|
||||
public $timestamps = false;
|
||||
|
||||
@@ -26,14 +35,39 @@ class Variant extends Model
|
||||
{
|
||||
return [
|
||||
'catalog_item_id' => 'integer',
|
||||
'event_date_id' => 'integer',
|
||||
'inventory_id' => 'integer',
|
||||
'precio' => 'decimal:2',
|
||||
];
|
||||
}
|
||||
|
||||
/** @return BelongsTo<CatalogItem, $this> */
|
||||
public function catalogItem(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(CatalogItem::class);
|
||||
return $this->belongsTo(CatalogItem::class)->withTrashed();
|
||||
}
|
||||
|
||||
/** @return BelongsTo<EventDate, $this> */
|
||||
public function eventDate(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(EventDate::class);
|
||||
}
|
||||
|
||||
/** @return BelongsToMany<EventDate, $this> */
|
||||
public function eventDates(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(
|
||||
EventDate::class,
|
||||
'variant_event_dates',
|
||||
'variant_id',
|
||||
'event_date_id',
|
||||
)->orderBy('date')->orderBy('time_start');
|
||||
}
|
||||
|
||||
/** @return HasMany<Ticket, $this> */
|
||||
public function sourceTickets(): HasMany
|
||||
{
|
||||
return $this->hasMany(Ticket::class, 'source_variant_id');
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Inventory, $this> */
|
||||
@@ -50,6 +84,12 @@ class Variant extends Model
|
||||
|
||||
/** @return BelongsToMany<Attachment, $this> */
|
||||
public function attachments(): BelongsToMany
|
||||
{
|
||||
return $this->allAttachments()->wherePivot('is_enabled', true);
|
||||
}
|
||||
|
||||
/** @return BelongsToMany<Attachment, $this> */
|
||||
public function allAttachments(): BelongsToMany
|
||||
{
|
||||
$relation = $this->belongsToMany(
|
||||
Attachment::class,
|
||||
@@ -57,7 +97,7 @@ class Variant extends Model
|
||||
'variant_id',
|
||||
'attachment_id'
|
||||
)
|
||||
->withPivot('orden')
|
||||
->withPivot(['orden', 'is_enabled'])
|
||||
->orderByPivot('orden');
|
||||
|
||||
if ($this->catalog_item_id !== null) {
|
||||
@@ -69,24 +109,200 @@ class Variant extends Model
|
||||
|
||||
public function getPrice(): float
|
||||
{
|
||||
return $this->catalogItem->getPrice();
|
||||
return (float) ($this->precio ?? $this->catalogItem->precio);
|
||||
}
|
||||
|
||||
public function getDescription(): ?string
|
||||
{
|
||||
return $this->descripcion ?? $this->catalogItem->descripcion;
|
||||
}
|
||||
|
||||
public function getName(): string
|
||||
{
|
||||
$name = $this->catalogItem->nombre;
|
||||
$this->loadMissing('definitions.itemAttribute.attribute');
|
||||
$definitions = $this->definitions
|
||||
->map(function (VariantDefinition $definition): ?string {
|
||||
$attributeName = $definition->itemAttribute?->attribute?->nombre;
|
||||
return $this->catalogItem->nombre;
|
||||
}
|
||||
|
||||
return $attributeName
|
||||
? "{$attributeName}: {$definition->value}"
|
||||
: $definition->value;
|
||||
public function getSelectionLabel(): string
|
||||
{
|
||||
$this->loadMissing([
|
||||
'catalogItem.itemAttributes.attribute.options',
|
||||
'definitions.itemAttribute.attribute.options',
|
||||
'eventDates',
|
||||
'eventDate',
|
||||
]);
|
||||
|
||||
$itemAttributes = $this->catalogItem->itemAttributes;
|
||||
|
||||
$label = $this->selectionOptions($itemAttributes)
|
||||
->map(function (array $option, string $attributeCode) use ($itemAttributes): ?string {
|
||||
$itemAttribute = $itemAttributes->first(
|
||||
fn (ItemAttribute $candidate): bool => $candidate->attribute?->codigo === $attributeCode,
|
||||
);
|
||||
$translationKey = "api.catalog.attribute_labels.{$attributeCode}";
|
||||
$attributeName = Lang::has($translationKey)
|
||||
? __($translationKey)
|
||||
: ($itemAttribute?->attribute?->nombre ?? Str::headline($attributeCode));
|
||||
$selectedOptions = array_is_list($option) ? $option : [$option];
|
||||
$selectedLabels = collect($selectedOptions)
|
||||
->pluck('label')
|
||||
->filter()
|
||||
->implode(', ');
|
||||
|
||||
return $selectedLabels === ''
|
||||
? null
|
||||
: "{$attributeName} {$selectedLabels}";
|
||||
})
|
||||
->filter()
|
||||
->implode(', ');
|
||||
->implode(' · ');
|
||||
|
||||
return $definitions === '' ? $name : "{$name} ({$definitions})";
|
||||
return $label !== '' ? $label : $this->getName();
|
||||
}
|
||||
|
||||
/** @return Collection<string, string|array<int, string>> */
|
||||
public function selectionValues(): Collection
|
||||
{
|
||||
$values = $this->definitions
|
||||
->groupBy('item_attribute_id')
|
||||
->mapWithKeys(function (Collection $definitions): array {
|
||||
$itemAttribute = $definitions->first()?->itemAttribute;
|
||||
$attributeCode = $itemAttribute?->attribute?->codigo;
|
||||
|
||||
if ($attributeCode === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$definitionValues = $definitions->pluck('value')->values();
|
||||
|
||||
return [
|
||||
$attributeCode => $itemAttribute->allow_multi_select
|
||||
? $definitionValues->all()
|
||||
: $definitionValues->first(),
|
||||
];
|
||||
});
|
||||
|
||||
$eventDateIds = $this->selectedEventDates()
|
||||
->pluck('id')
|
||||
->map(fn ($id): string => (string) $id)
|
||||
->values();
|
||||
|
||||
if ($eventDateIds->count() === 1) {
|
||||
$values->put('event_date', $eventDateIds->first());
|
||||
} elseif ($eventDateIds->isNotEmpty()) {
|
||||
$values->put('event_date', $eventDateIds->all());
|
||||
}
|
||||
|
||||
return $values;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<string, array{value: string, label: string}|array<int, array{value: string, label: string}>>
|
||||
*/
|
||||
public function selectionOptions(?Collection $itemAttributes = null): Collection
|
||||
{
|
||||
$options = $this->definitions
|
||||
->groupBy('item_attribute_id')
|
||||
->mapWithKeys(function (Collection $definitions): array {
|
||||
$itemAttribute = $definitions->first()?->itemAttribute;
|
||||
$attribute = $itemAttribute?->attribute;
|
||||
$attributeCode = $attribute?->codigo;
|
||||
|
||||
if ($attributeCode === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$values = $definitions
|
||||
->pluck('value')
|
||||
->values()
|
||||
->map(function (string $value) use ($attribute): array {
|
||||
$attributeOption = $attribute->options->firstWhere('value', $value);
|
||||
|
||||
return [
|
||||
'value' => $value,
|
||||
'label' => $attributeOption?->label ?? $value,
|
||||
];
|
||||
});
|
||||
|
||||
return [
|
||||
$attributeCode => $itemAttribute->allow_multi_select
|
||||
? $values->all()
|
||||
: $values->first(),
|
||||
];
|
||||
});
|
||||
|
||||
$eventDateOptions = $this->selectedEventDates()
|
||||
->map(fn (EventDate $eventDate): array => [
|
||||
'value' => (string) $eventDate->id,
|
||||
'label' => $eventDate->date->format('d/m/Y'),
|
||||
])
|
||||
->values();
|
||||
|
||||
if ($eventDateOptions->count() === 1) {
|
||||
$options->put('event_date', $eventDateOptions->first());
|
||||
} elseif ($eventDateOptions->isNotEmpty()) {
|
||||
$options->put('event_date', $eventDateOptions->all());
|
||||
}
|
||||
|
||||
if ($itemAttributes === null) {
|
||||
$itemAttributes = $this->definitions
|
||||
->map(fn (VariantDefinition $definition) => $definition->itemAttribute)
|
||||
->filter()
|
||||
->unique('id')
|
||||
->values();
|
||||
|
||||
if ($this->catalogItem !== null) {
|
||||
$itemAttributes = $itemAttributes
|
||||
->merge($this->catalogItem->itemAttributes)
|
||||
->unique('id')
|
||||
->values();
|
||||
}
|
||||
}
|
||||
|
||||
$ordering = $itemAttributes->mapWithKeys(function (ItemAttribute $itemAttribute): array {
|
||||
$attribute = $itemAttribute->attribute;
|
||||
|
||||
return $attribute === null
|
||||
? []
|
||||
: [$attribute->codigo => [$itemAttribute->sort_order, mb_strtolower($attribute->nombre)]];
|
||||
});
|
||||
|
||||
return $options->sortKeysUsing(function (string $left, string $right) use ($ordering): int {
|
||||
[$leftOrder, $leftLabel] = $ordering->get($left, [0, mb_strtolower($left)]);
|
||||
[$rightOrder, $rightLabel] = $ordering->get($right, [0, mb_strtolower($right)]);
|
||||
|
||||
return $leftOrder <=> $rightOrder
|
||||
?: $leftLabel <=> $rightLabel
|
||||
?: $left <=> $right;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, ItemAttribute> $itemAttributes
|
||||
* @return Collection<string, array{value: string, label: string}|array<int, array{value: string, label: string}>>
|
||||
*/
|
||||
public function selectorOptions(Collection $itemAttributes): Collection
|
||||
{
|
||||
$visibleAttributeCodes = $itemAttributes
|
||||
->filter(fn (ItemAttribute $itemAttribute): bool => $itemAttribute->show_in_selector)
|
||||
->map(fn (ItemAttribute $itemAttribute): ?string => $itemAttribute->attribute?->codigo)
|
||||
->filter()
|
||||
->values();
|
||||
|
||||
return $this->selectionOptions($itemAttributes)
|
||||
->filter(
|
||||
fn (array $option, string $attributeCode): bool => $visibleAttributeCodes
|
||||
->contains($attributeCode)
|
||||
);
|
||||
}
|
||||
|
||||
/** @return Collection<int, EventDate> */
|
||||
public function selectedEventDates(): Collection
|
||||
{
|
||||
$eventDates = $this->eventDates;
|
||||
|
||||
if ($eventDates->isEmpty() && $this->event_date_id !== null && $this->eventDate !== null) {
|
||||
return collect([$this->eventDate]);
|
||||
}
|
||||
|
||||
return $eventDates;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Requests\AdminApp;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class UpsertOnTicketFeaturedGroupRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'category_name' => ['required', 'string', 'max:255'],
|
||||
'is_featured' => ['required', 'boolean'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class CatalogVariantOptionsRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string, list<string>> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'selected_values' => ['sometimes', 'array'],
|
||||
'selected_values.*' => ['nullable'],
|
||||
'cart_item_id' => ['sometimes', 'nullable', 'integer', 'min:1'],
|
||||
];
|
||||
}
|
||||
}
|
||||
21
app/Domains/Catalog/Requests/CategoryPageRequest.php
Normal file
21
app/Domains/Catalog/Requests/CategoryPageRequest.php
Normal file
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class CategoryPageRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string, list<string>> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'page' => ['sometimes', 'integer', 'min:1'],
|
||||
];
|
||||
}
|
||||
}
|
||||
29
app/Domains/Catalog/Requests/SearchCatalogItemsRequest.php
Normal file
29
app/Domains/Catalog/Requests/SearchCatalogItemsRequest.php
Normal file
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class SearchCatalogItemsRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string, list<string>> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'q' => ['required', 'string', 'min:2', 'max:100'],
|
||||
'page' => ['sometimes', 'integer', 'min:1'],
|
||||
];
|
||||
}
|
||||
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
if ($this->has('q') && is_string($this->input('q'))) {
|
||||
$this->merge(['q' => trim($this->string('q')->toString())]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ namespace App\Domains\Catalog\Requests;
|
||||
|
||||
use App\Domains\Catalog\Enums\CatalogItemType;
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Enums\InventorySubject;
|
||||
use App\Domains\Shared\Rules\ImageOrBase64Rule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
@@ -53,9 +54,9 @@ class StoreCatalogItemRequest extends FormRequest
|
||||
'descripcion' => ['sometimes', 'nullable', 'string'],
|
||||
'precio' => ['required', 'numeric', 'min:0'],
|
||||
'inventory_policy' => [Rule::prohibitedIf($isBundle), 'sometimes', Rule::enum(InventoryPolicy::class)],
|
||||
'inventory_subject' => ['sometimes', Rule::enum(InventorySubject::class)],
|
||||
'max_units_per_user' => ['sometimes', 'nullable', 'integer', 'min:1'],
|
||||
'has_tickets' => [Rule::prohibitedIf($isBundle), 'sometimes', 'boolean'],
|
||||
'minimum_use_date' => [Rule::prohibitedIf($isBundle), 'sometimes', 'nullable', 'date'],
|
||||
'maximum_use_date' => [Rule::prohibitedIf($isBundle), 'sometimes', 'nullable', 'date', 'after_or_equal:minimum_use_date'],
|
||||
'real_stock' => [Rule::prohibitedIf($isBundle), 'sometimes', 'integer', 'min:0'],
|
||||
'inventory_id' => ['prohibited'],
|
||||
'reserved_stock' => ['prohibited'],
|
||||
@@ -69,15 +70,53 @@ class StoreCatalogItemRequest extends FormRequest
|
||||
fn ($query) => $query->where('tenant_codigo', $tenantCode)
|
||||
),
|
||||
],
|
||||
'multi_select_attribute_codes' => [Rule::prohibitedIf($isBundle), 'sometimes', 'array'],
|
||||
'multi_select_attribute_codes.*' => [
|
||||
'required',
|
||||
'string',
|
||||
'distinct',
|
||||
Rule::exists('attribute', 'codigo')->where(
|
||||
fn ($query) => $query->where('tenant_codigo', $tenantCode)
|
||||
),
|
||||
],
|
||||
'hidden_attribute_codes' => [Rule::prohibitedIf($isBundle), 'sometimes', 'array'],
|
||||
'hidden_attribute_codes.*' => [
|
||||
'required',
|
||||
'string',
|
||||
'distinct',
|
||||
Rule::exists('attribute', 'codigo')->where(
|
||||
fn ($query) => $query->where('tenant_codigo', $tenantCode)
|
||||
),
|
||||
],
|
||||
'images' => ['sometimes', 'array'],
|
||||
'images.*' => ['required', new ImageOrBase64Rule],
|
||||
'variants' => [Rule::prohibitedIf($isBundle), 'sometimes', 'array'],
|
||||
'variants.*.real_stock' => ['sometimes', 'integer', 'min:0'],
|
||||
'variants.*.descripcion' => ['sometimes', 'nullable', 'string'],
|
||||
'variants.*.precio' => ['sometimes', 'nullable', 'numeric', 'min:0', 'max:99999999.99'],
|
||||
'variants.*.event_date_id' => [
|
||||
'sometimes',
|
||||
'nullable',
|
||||
'integer',
|
||||
Rule::exists('event_dates', 'id')->where(
|
||||
fn ($query) => $query->where('tenant_code', $tenantCode)
|
||||
),
|
||||
],
|
||||
'variants.*.event_date_ids' => ['sometimes', 'array', 'min:1'],
|
||||
'variants.*.event_date_ids.*' => [
|
||||
'required',
|
||||
'integer',
|
||||
'distinct',
|
||||
Rule::exists('event_dates', 'id')->where(
|
||||
fn ($query) => $query->where('tenant_code', $tenantCode)
|
||||
),
|
||||
],
|
||||
'variants.*.inventory_id' => ['prohibited'],
|
||||
'variants.*.reserved_stock' => ['prohibited'],
|
||||
'variants.*.sold_units' => ['prohibited'],
|
||||
'variants.*.values' => ['sometimes', 'array'],
|
||||
'variants.*.values.*' => ['nullable', 'string'],
|
||||
'variants.*.values.*' => ['nullable'],
|
||||
'variants.*.values.*.*' => ['required', 'string'],
|
||||
'variants.*.images' => ['sometimes', 'array'],
|
||||
'variants.*.images.*' => ['required', new ImageOrBase64Rule],
|
||||
'components' => [
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Resources\AdminApp;
|
||||
|
||||
use App\Domains\Catalog\Enums\ProductLayout;
|
||||
use App\Domains\Catalog\Models\FeaturedGroup;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin FeaturedGroup */
|
||||
class OnTicketFeaturedGroupResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'category_id' => $this->category_id,
|
||||
'category_name' => $this->category->nombre,
|
||||
'group_name' => $this->group_name,
|
||||
'is_featured' => $this->product_layout === ProductLayout::Row,
|
||||
'type' => $this->source_type->value,
|
||||
'product_layout' => $this->product_layout->value,
|
||||
'group_layout' => $this->group_layout->value,
|
||||
'order' => $this->group_order,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -9,8 +9,8 @@ use Illuminate\Http\Resources\Json\JsonResource;
|
||||
/** @mixin FeaturedGroup */
|
||||
class CatalogFeaturedGroupResource extends JsonResource
|
||||
{
|
||||
/** @param array<string, mixed> $itemsPage */
|
||||
public function __construct($resource, private readonly array $itemsPage)
|
||||
/** @param array<array-key, mixed> $items */
|
||||
public function __construct($resource, private readonly array $items)
|
||||
{
|
||||
parent::__construct($resource);
|
||||
}
|
||||
@@ -22,8 +22,9 @@ class CatalogFeaturedGroupResource extends JsonResource
|
||||
'id' => $this->id,
|
||||
'title' => $this->group_name,
|
||||
'layout' => $this->product_layout->value,
|
||||
'group_layout' => $this->group_layout->value,
|
||||
'group_order' => $this->group_order,
|
||||
'items' => $this->itemsPage,
|
||||
'items' => $this->items,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,60 +5,88 @@ namespace App\Domains\Catalog\Resources;
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Enums\ProductLayout;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\FeaturedItem;
|
||||
use App\Domains\Catalog\Models\FeaturedGroup;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin FeaturedItem */
|
||||
/** @mixin CatalogItem */
|
||||
class CatalogFeaturedItemResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$catalogItem = $this->catalogItem;
|
||||
$catalogItem = $this->resource;
|
||||
/** @var FeaturedGroup $featuredGroup */
|
||||
$featuredGroup = $catalogItem->getRelation('featuredGroup');
|
||||
|
||||
if ($this->featuredGroup->product_layout === ProductLayout::ColumnWithImage) {
|
||||
if ($featuredGroup->product_layout === ProductLayout::ColumnWithImage) {
|
||||
return $this->columnWithImageData($catalogItem);
|
||||
}
|
||||
|
||||
return [
|
||||
if ($featuredGroup->product_layout === ProductLayout::TicketSelector) {
|
||||
return $this->ticketSelectorData($catalogItem);
|
||||
}
|
||||
|
||||
$data = [
|
||||
'id' => $catalogItem->id,
|
||||
'type' => $catalogItem->type->value,
|
||||
'nombre' => $catalogItem->nombre,
|
||||
'descripcion' => $catalogItem->descripcion,
|
||||
'precio' => $catalogItem->precio,
|
||||
'stock_tecnico' => $catalogItem->availableStock(),
|
||||
'variants' => $catalogItem->variants
|
||||
'variants' => $catalogItem->visibleVariants()
|
||||
->map(fn (Variant $variant): array => [
|
||||
'id' => $variant->id,
|
||||
'event_date_id' => $variant->event_date_id,
|
||||
'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
|
||||
'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
|
||||
'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
|
||||
'descripcion' => $variant->getDescription(),
|
||||
'precio' => number_format($variant->getPrice(), 2, '.', ''),
|
||||
'stock_tecnico' => $catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
||||
? null
|
||||
: $variant->inventory->availableStock(),
|
||||
'values' => $variant->definitions
|
||||
->mapWithKeys(fn ($definition) => [
|
||||
$definition->itemAttribute?->attribute?->codigo => $definition->value,
|
||||
])
|
||||
->filter(fn ($value, $key): bool => $key !== null),
|
||||
'values' => $variant->selectorOptions($catalogItem->itemAttributes),
|
||||
])
|
||||
->values(),
|
||||
];
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
private function ticketSelectorData(CatalogItem $catalogItem): array
|
||||
{
|
||||
return [
|
||||
'id' => $catalogItem->id,
|
||||
'type' => $catalogItem->type->value,
|
||||
'nombre' => $catalogItem->nombre,
|
||||
'descripcion' => $catalogItem->descripcion,
|
||||
'precio' => $catalogItem->precio,
|
||||
'image' => $this->firstImageUrl($catalogItem),
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
private function columnWithImageData(CatalogItem $catalogItem): array
|
||||
{
|
||||
$attachment = $catalogItem->attachments->first()
|
||||
?? $catalogItem->variants
|
||||
->flatMap(fn (Variant $variant) => $variant->attachments)
|
||||
->first();
|
||||
|
||||
return [
|
||||
'id' => $catalogItem->id,
|
||||
'type' => $catalogItem->type->value,
|
||||
'nombre' => $catalogItem->nombre,
|
||||
'precio' => $catalogItem->precio,
|
||||
'image' => $attachment?->getTemporaryUrl(1440),
|
||||
'image' => $this->firstImageUrl($catalogItem),
|
||||
];
|
||||
}
|
||||
|
||||
private function firstImageUrl(CatalogItem $catalogItem): ?string
|
||||
{
|
||||
$attachment = $catalogItem->attachments->first()
|
||||
?? $catalogItem->variants
|
||||
->flatMap(fn (Variant $variant) => $variant->attachments)
|
||||
->first();
|
||||
|
||||
return $attachment?->getTemporaryUrl(1440);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,8 @@ use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\ItemAttribute;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Shared\Enums\FieldType;
|
||||
use App\Domains\Ticket\Resources\ValidityTimeResource;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
use Illuminate\Support\Collection;
|
||||
@@ -31,12 +33,10 @@ class CatalogItemDetailResource extends JsonResource
|
||||
'category' => $this->category?->nombre,
|
||||
'brand' => $this->brand?->nombre,
|
||||
'inventory_policy' => $this->inventory_policy?->value,
|
||||
'inventory_subject' => $this->inventory_subject->value,
|
||||
'max_units_per_user' => $this->max_units_per_user,
|
||||
'has_tickets' => $this->has_tickets,
|
||||
'minimum_use_date' => $this->minimum_use_date,
|
||||
'maximum_use_date' => $this->maximum_use_date,
|
||||
'attributes' => $this->itemAttributes
|
||||
->map(fn (ItemAttribute $itemAttribute): array => $this->attributeData($itemAttribute))
|
||||
->values(),
|
||||
'attributes' => $this->attributesData(),
|
||||
'stock_tecnico' => $this->when(
|
||||
$selectedVariant === null,
|
||||
fn () => $this->availableStock(),
|
||||
@@ -45,7 +45,7 @@ class CatalogItemDetailResource extends JsonResource
|
||||
$selectedVariant === null,
|
||||
fn () => $this->imageUrls($this->attachments),
|
||||
),
|
||||
'variants' => $this->variants
|
||||
'variants' => $this->visibleVariants()
|
||||
->map(fn (Variant $variant): array => $this->variantData($variant))
|
||||
->values(),
|
||||
'selected_variant' => $this->when(
|
||||
@@ -78,6 +78,45 @@ class CatalogItemDetailResource extends JsonResource
|
||||
private function attributeData(ItemAttribute $itemAttribute): array
|
||||
{
|
||||
$attribute = $itemAttribute->attribute;
|
||||
|
||||
return [
|
||||
'id' => $attribute->id,
|
||||
'codigo' => $attribute->codigo,
|
||||
'nombre' => $attribute->nombre,
|
||||
'sort_order' => $itemAttribute->sort_order,
|
||||
'show_in_selector' => $itemAttribute->show_in_selector,
|
||||
'is_required' => $attribute->is_required,
|
||||
'allow_multi_select' => $itemAttribute->allow_multi_select,
|
||||
'metadata_schema' => $attribute->metadata_schema,
|
||||
'type' => $attribute->type->value,
|
||||
'options' => $attribute->type === FieldType::EventDate
|
||||
? $this->eventDateOptions($itemAttribute)
|
||||
: $this->catalogAttributeOptions($itemAttribute),
|
||||
];
|
||||
}
|
||||
|
||||
/** @return Collection<int, array<string, mixed>> */
|
||||
private function eventDateOptions(ItemAttribute $itemAttribute): Collection
|
||||
{
|
||||
return $itemAttribute->attribute->eventDates
|
||||
->map(fn ($eventDate, int $index): array => [
|
||||
'id' => $eventDate->id,
|
||||
'value' => (string) $eventDate->id,
|
||||
'label' => $eventDate->date->format('d/m/Y'),
|
||||
'sort_order' => $index,
|
||||
'validity_time_id' => $eventDate->validity_time_id,
|
||||
'validity_time' => ValidityTimeResource::make($eventDate->validityTime),
|
||||
'metadata' => [
|
||||
'date' => $eventDate->date->format('Y-m-d'),
|
||||
'time_start' => $eventDate->time_start,
|
||||
'time_end' => $eventDate->time_end,
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
/** @return Collection<int, array<string, mixed>> */
|
||||
private function catalogAttributeOptions(ItemAttribute $itemAttribute): Collection
|
||||
{
|
||||
$availableValues = $this->variants
|
||||
->flatMap->definitions
|
||||
->where('item_attribute_id', $itemAttribute->id)
|
||||
@@ -85,37 +124,50 @@ class CatalogItemDetailResource extends JsonResource
|
||||
->filter()
|
||||
->unique();
|
||||
|
||||
return [
|
||||
'id' => $attribute->id,
|
||||
'codigo' => $attribute->codigo,
|
||||
'nombre' => $attribute->nombre,
|
||||
'is_required' => $attribute->is_required,
|
||||
'metadata_schema' => $attribute->metadata_schema,
|
||||
'type' => $attribute->type->value,
|
||||
'options' => $attribute->options
|
||||
->whereIn('value', $availableValues)
|
||||
->map(fn ($option): array => [
|
||||
'id' => $option->id,
|
||||
'value' => $option->value,
|
||||
'label' => $option->label,
|
||||
'sort_order' => $option->sort_order,
|
||||
'metadata' => $option->metadata,
|
||||
])
|
||||
->values(),
|
||||
];
|
||||
return $itemAttribute->attribute->options
|
||||
->whereIn('value', $availableValues)
|
||||
->map(fn ($option): array => [
|
||||
'id' => $option->id,
|
||||
'value' => $option->value,
|
||||
'label' => $option->label,
|
||||
'sort_order' => $option->sort_order,
|
||||
'validity_time_id' => $option->validity_time_id,
|
||||
'validity_time' => $option->validityTime === null
|
||||
? null
|
||||
: ValidityTimeResource::make($option->validityTime),
|
||||
'metadata' => $option->metadata,
|
||||
])
|
||||
->values();
|
||||
}
|
||||
|
||||
/** @return Collection<int, array<string, mixed>> */
|
||||
private function attributesData(): Collection
|
||||
{
|
||||
return $this->itemAttributes
|
||||
->sort(function (ItemAttribute $left, ItemAttribute $right): int {
|
||||
return $left->sort_order <=> $right->sort_order
|
||||
?: mb_strtolower($left->attribute->nombre) <=> mb_strtolower($right->attribute->nombre);
|
||||
})
|
||||
->map(fn (ItemAttribute $itemAttribute): array => $this->attributeData($itemAttribute))
|
||||
->values();
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
private function variantData(Variant $variant): array
|
||||
{
|
||||
$values = $variant->selectionOptions($this->itemAttributes);
|
||||
$eventDates = $variant->selectedEventDates();
|
||||
|
||||
return [
|
||||
'id' => $variant->id,
|
||||
'event_date_id' => $variant->event_date_id,
|
||||
'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
|
||||
'event_date_ids' => $eventDates->pluck('id')->values(),
|
||||
'event_dates' => $eventDates->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
|
||||
'descripcion' => $variant->getDescription(),
|
||||
'precio' => number_format($variant->getPrice(), 2, '.', ''),
|
||||
'stock_tecnico' => $this->variantStock($variant),
|
||||
'values' => $variant->definitions
|
||||
->mapWithKeys(fn ($definition) => [
|
||||
$definition->itemAttribute?->attribute?->codigo => $definition->value,
|
||||
])
|
||||
->filter(fn ($value, $key): bool => $key !== null),
|
||||
'values' => $values,
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -22,9 +22,9 @@ class CatalogItemResource extends JsonResource
|
||||
'descripcion' => $this->descripcion,
|
||||
'precio' => $this->precio,
|
||||
'inventory_policy' => $this->inventory_policy?->value,
|
||||
'inventory_subject' => $this->inventory_subject->value,
|
||||
'max_units_per_user' => $this->max_units_per_user,
|
||||
'has_tickets' => $this->has_tickets,
|
||||
'minimum_use_date' => $this->minimum_use_date,
|
||||
'maximum_use_date' => $this->maximum_use_date,
|
||||
'real_stock' => $this->whenLoaded('inventory', fn () => $this->inventory?->real_stock),
|
||||
'images' => $this->whenLoaded('attachments', fn () => $this->attachments
|
||||
->map(fn ($attachment) => $attachment->getTemporaryUrl(1440))
|
||||
@@ -32,12 +32,14 @@ class CatalogItemResource extends JsonResource
|
||||
'variants' => $this->whenLoaded('variants', fn () => $this->variants
|
||||
->map(fn ($variant) => [
|
||||
'id' => $variant->id,
|
||||
'event_date_id' => $variant->event_date_id,
|
||||
'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
|
||||
'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
|
||||
'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
|
||||
'descripcion' => $variant->getDescription(),
|
||||
'precio' => number_format($variant->getPrice(), 2, '.', ''),
|
||||
'real_stock' => $variant->inventory?->real_stock,
|
||||
'values' => $variant->definitions
|
||||
->mapWithKeys(fn ($definition) => [
|
||||
$definition->itemAttribute?->attribute?->codigo => $definition->value,
|
||||
])
|
||||
->filter(fn ($value, $key) => $key !== null),
|
||||
'values' => $variant->selectorOptions($this->itemAttributes),
|
||||
'images' => $variant->attachments
|
||||
->map(fn ($attachment) => $attachment->getTemporaryUrl(1440))
|
||||
->values(),
|
||||
|
||||
47
app/Domains/Catalog/Resources/CatalogSearchItemResource.php
Normal file
47
app/Domains/Catalog/Resources/CatalogSearchItemResource.php
Normal file
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Resources;
|
||||
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin CatalogItem */
|
||||
class CatalogSearchItemResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$attachment = $this->attachments->first()
|
||||
?? $this->variants
|
||||
->flatMap(fn (Variant $variant) => $variant->attachments)
|
||||
->first();
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'type' => $this->type->value,
|
||||
'nombre' => $this->nombre,
|
||||
'descripcion' => $this->descripcion,
|
||||
'precio' => $this->precio,
|
||||
'image' => $attachment?->getTemporaryUrl(1440),
|
||||
'stock_tecnico' => $this->availableStock(),
|
||||
'variants' => $this->visibleVariants()
|
||||
->map(fn (Variant $variant): array => [
|
||||
'id' => $variant->id,
|
||||
'event_date_id' => $variant->event_date_id,
|
||||
'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
|
||||
'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
|
||||
'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
|
||||
'descripcion' => $variant->getDescription(),
|
||||
'precio' => number_format($variant->getPrice(), 2, '.', ''),
|
||||
'stock_tecnico' => $this->inventory_policy === InventoryPolicy::Unlimited
|
||||
? null
|
||||
: $variant->inventory?->availableStock(),
|
||||
'values' => $variant->selectorOptions($this->itemAttributes),
|
||||
])
|
||||
->values(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class CatalogVariantOptionsResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return $this->resource;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user