Compare commits

..

18 Commits

Author SHA1 Message Date
a4b5c2eb19 refactor(auth): remove role-based logic from scanner authentication and permissions 2026-09-04 15:33:01 -03:00
2feca2bed5 docs(auth): explain email identity and role-specific flows 2026-09-04 14:17:42 -03:00
a35ff69140 feat(users): enforce active email uniqueness per role 2026-09-04 14:17:37 -03:00
75152b53a4 fix(auth): isolate password reset flows by application role 2026-09-04 14:17:27 -03:00
99594b17e7 fix(auth): resolve login identities by active email and role 2026-09-04 14:17:19 -03:00
e4db36e650 feat(notification): update welcome email to include tenant URL and call-to-action button 2026-09-04 10:51:00 -03:00
ffa3f10b18 feat(scanner): implement category validation for AdminApp role and update tests 2026-09-04 10:40:46 -03:00
7acef66ee7 feat(notification): enhance password reset emails with custom templates for different scenarios 2026-09-04 10:31:16 -03:00
18f1217daa feat(admin): implement CRUD for administrators with role management and tenant restrictions 2026-09-04 10:28:33 -03:00
ac44e82454 fix(menu): rename 'Staff' to 'Usuarios' in menu seeder and migration 2026-09-04 09:54:56 -03:00
1e7a9b6876 Merge pull request 'homo' (#4) from homo into main
Reviewed-on: https://gitea.quo.ar/tbianchini/shopit-back/pulls/4
2026-09-04 12:01:35 +00:00
deea4fd4af Merge branch 'test/stress' into dev 2026-09-04 08:21:50 -03:00
c4ff695f2e refactor(ticket): simplify tenant validation and update command documentation 2026-09-03 14:30:38 -03:00
703158bd06 feat(ticket): implement LoadTestTicketDatasetService for generating load test datasets
- Added LoadTestTicketDatasetService to prepare disposable scanner tickets and generate a Postman importable dataset.
- Introduced console command `load-test🎟️prepare` for executing the dataset preparation.
- Updated README documentation with usage instructions for the load test command.
- Enhanced Postman collection generation script to include new parameters.
- Created tests for the load test command to ensure proper functionality and validation.
2026-09-03 14:15:23 -03:00
eda2343380 fix(user): update hidden attributes and handle soft-deleted users in registration 2026-09-03 10:31:43 -03:00
0baad641d5 fix(auth): scope email uniqueness to active users 2026-09-03 09:59:21 -03:00
ddb8c3743f fix(staff): preserve scanner history on deletion 2026-09-03 09:58:08 -03:00
900ef6cf98 Merge pull request 'homo' (#3) from homo into main
Reviewed-on: https://gitea.quo.ar/tbianchini/shopit-back/pulls/3
2026-08-31 11:36:04 +00:00
59 changed files with 2434 additions and 266 deletions

View File

@@ -2,7 +2,7 @@
"info": {
"_postman_id": "76fd6fd2-53b9-4d92-8e02-1ddcc6207fa2",
"name": "ShopIt API — Complete",
"description": "Colección canónica generada desde las rutas reales de Laravel. Incluye 122 operaciones HTTP, ejemplos de payload, filtros, archivos y tokens separados para Storefront, Admin App y Scanner.\n\nUso rápido:\n1. Ajustá `base_url` y las credenciales.\n2. Ejecutá el Login de la aplicación correspondiente; el token se guarda automáticamente.\n3. Ajustá los IDs y códigos de las variables de colección.\n\nRegeneración: `php postman/generate-shopit-collection.php`.",
"description": "Colección canónica generada desde las rutas reales de Laravel. Incluye 137 operaciones HTTP, ejemplos de payload, filtros, archivos y tokens separados para Storefront, Admin App y Scanner.\n\nUso rápido:\n1. Ajustá `base_url` y las credenciales.\n2. Ejecutá el Login de la aplicación correspondiente; el token se guarda automáticamente.\n3. Ajustá los IDs y códigos de las variables de colección.\n\nRegeneración: `php postman/generate-shopit-collection.php`.",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
@@ -385,6 +385,42 @@
}
},
"response": []
},
{
"name": "redirect Google Auth",
"request": {
"method": "GET",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
}
],
"description": "Ruta Laravel: `GET /auth/google/redirect`\n\nControlador: `App\\Domains\\Auth\\Controllers\\GoogleAuthController@redirect`",
"url": {
"raw": "{{base_url}}/auth/google/redirect?tenant={{tenant_code}}&return_url={{storefront_url}}",
"host": [
"{{base_url}}"
],
"path": [
"auth",
"google",
"redirect"
],
"query": [
{
"key": "tenant",
"value": "{{tenant_code}}"
},
{
"key": "return_url",
"value": "{{storefront_url}}"
}
]
}
},
"response": []
}
]
},
@@ -572,60 +608,6 @@
}
},
"response": []
},
{
"name": "Update Checkout Cart Item Cart",
"request": {
"method": "PATCH",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
},
{
"key": "Content-Type",
"value": "application/json",
"type": "text"
}
],
"description": "Ruta Laravel: `PATCH /api/tenants/{tenant:codigo}/checkout-carts/{cart}/items/{cartItem}`\n\nControlador: `App\\Domains\\Cart\\Controllers\\CartController@updateCheckoutItem`\n\nRequiere autenticación Sanctum.",
"url": {
"raw": "{{base_url}}/api/tenants/{{tenant_code}}/checkout-carts/{{cart}}/items/{{cart_item_id}}",
"host": [
"{{base_url}}"
],
"path": [
"api",
"tenants",
"{{tenant_code}}",
"checkout-carts",
"{{cart}}",
"items",
"{{cart_item_id}}"
]
},
"body": {
"mode": "raw",
"raw": "{\n \"cantidad\": 2\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "{{token}}",
"type": "string"
}
]
}
},
"response": []
}
]
},
@@ -1169,99 +1151,6 @@
},
"response": []
},
{
"name": "Prepare Item Editing Purchase",
"request": {
"method": "POST",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
}
],
"description": "Ruta Laravel: `POST /api/tenants/{tenant:codigo}/compras/{compra}/edit-items`\n\nControlador: `App\\Domains\\Purchase\\Controllers\\PurchaseController@prepareItemEditing`\n\nRequiere autenticación Sanctum.",
"url": {
"raw": "{{base_url}}/api/tenants/{{tenant_code}}/compras/{{purchase_id}}/edit-items",
"host": [
"{{base_url}}"
],
"path": [
"api",
"tenants",
"{{tenant_code}}",
"compras",
"{{purchase_id}}",
"edit-items"
]
},
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "{{token}}",
"type": "string"
}
]
}
},
"response": []
},
{
"name": "Update Item Purchase",
"request": {
"method": "PATCH",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
},
{
"key": "Content-Type",
"value": "application/json",
"type": "text"
}
],
"description": "Ruta Laravel: `PATCH /api/tenants/{tenant:codigo}/compras/{compra}/items/{item}`\n\nControlador: `App\\Domains\\Purchase\\Controllers\\PurchaseController@updateItem`\n\nRequiere autenticación Sanctum.",
"url": {
"raw": "{{base_url}}/api/tenants/{{tenant_code}}/compras/{{purchase_id}}/items/{{purchase_item_id}}",
"host": [
"{{base_url}}"
],
"path": [
"api",
"tenants",
"{{tenant_code}}",
"compras",
"{{purchase_id}}",
"items",
"{{purchase_item_id}}"
]
},
"body": {
"mode": "raw",
"raw": "{\n \"quantity\": 2,\n \"variant_id\": {{variant_id}}\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "{{token}}",
"type": "string"
}
]
}
},
"response": []
},
{
"name": "Create Payment Intent Purchase",
"request": {
@@ -2214,7 +2103,7 @@
},
"body": {
"mode": "raw",
"raw": "{\n \"client_id\": {{client_id}},\n \"codigo\": \"{{tenant_code}}\",\n \"nombre\": \"Tenant Demo\",\n \"dominio\": \"{{tenant_domain}}\",\n \"site_title\": \"ShopIt Demo\",\n \"primary_color\": \"#111827\",\n \"secondary_color\": \"#2563EB\",\n \"danger_color\": \"#DC2626\",\n \"success_color\": \"#16A34A\",\n \"header_bg_color\": \"#FFFFFF\",\n \"footer_bg_color\": \"#111827\",\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 \"display_categories\": true,\n \"display_seach_bar\": true,\n \"display_cart\": true,\n \"cart_editing_policy\": \"full\",\n \"checkout_editing_policy\": \"full\",\n \"website_type_code\": \"shopit\"\n}",
"raw": "{\n \"client_id\": {{client_id}},\n \"codigo\": \"{{tenant_code}}\",\n \"nombre\": \"Tenant Demo\",\n \"dominio\": \"{{tenant_domain}}\",\n \"site_title\": \"ShopIt Demo\",\n \"primary_color\": \"#111827\",\n \"secondary_color\": \"#2563EB\",\n \"danger_color\": \"#DC2626\",\n \"success_color\": \"#16A34A\",\n \"header_bg_color\": \"#FFFFFF\",\n \"footer_bg_color\": \"#111827\",\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 \"display_categories\": true,\n \"display_seach_bar\": true,\n \"display_cart\": true,\n \"cart_editing_policy\": \"full\",\n \"website_type_code\": \"shopit\"\n}",
"options": {
"raw": {
"language": "json"
@@ -2280,7 +2169,7 @@
},
"body": {
"mode": "raw",
"raw": "{\n \"nombre\": \"Tenant Demo Actualizado\",\n \"site_title\": \"ShopIt Demo\",\n \"primary_color\": \"#111827\",\n \"cart_editing_policy\": \"full\",\n \"checkout_editing_policy\": \"full\"\n}",
"raw": "{\n \"nombre\": \"Tenant Demo Actualizado\",\n \"site_title\": \"ShopIt Demo\",\n \"primary_color\": \"#111827\",\n \"cart_editing_policy\": \"full\"\n}",
"options": {
"raw": {
"language": "json"
@@ -2320,7 +2209,7 @@
},
"body": {
"mode": "raw",
"raw": "{\n \"nombre\": \"Tenant Demo Actualizado\",\n \"site_title\": \"ShopIt Demo\",\n \"primary_color\": \"#111827\",\n \"cart_editing_policy\": \"full\",\n \"checkout_editing_policy\": \"full\"\n}",
"raw": "{\n \"nombre\": \"Tenant Demo Actualizado\",\n \"site_title\": \"ShopIt Demo\",\n \"primary_color\": \"#111827\",\n \"cart_editing_policy\": \"full\"\n}",
"options": {
"raw": {
"language": "json"
@@ -2663,6 +2552,45 @@
},
"response": []
},
{
"name": "Ticket Form",
"request": {
"method": "GET",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
}
],
"description": "Ruta Laravel: `GET /api/v1/adminapp/forms/fiesta-futbol-infantil/ticket`\n\nControlador: `App\\Domains\\Forms\\Controllers\\AdminApp\\TicketFormController`\n\nRequiere autenticación Sanctum.",
"url": {
"raw": "{{base_url}}/api/v1/adminapp/forms/fiesta-futbol-infantil/ticket",
"host": [
"{{base_url}}"
],
"path": [
"api",
"v1",
"adminapp",
"forms",
"fiesta-futbol-infantil",
"ticket"
]
},
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "{{admin_token}}",
"type": "string"
}
]
}
},
"response": []
},
{
"name": "Sale Form",
"request": {
@@ -2738,6 +2666,44 @@
}
},
"response": []
},
{
"name": "Ticket Filter Form",
"request": {
"method": "GET",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
}
],
"description": "Ruta Laravel: `GET /api/v1/adminapp/forms/tickets-filter`\n\nControlador: `App\\Domains\\Forms\\Controllers\\AdminApp\\TicketFilterFormController`\n\nRequiere autenticación Sanctum.",
"url": {
"raw": "{{base_url}}/api/v1/adminapp/forms/tickets-filter",
"host": [
"{{base_url}}"
],
"path": [
"api",
"v1",
"adminapp",
"forms",
"tickets-filter"
]
},
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "{{admin_token}}",
"type": "string"
}
]
}
},
"response": []
}
]
},
@@ -3058,6 +3024,84 @@
},
"response": []
},
{
"name": "Get Category Visibility",
"request": {
"method": "GET",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
}
],
"description": "Ruta Laravel: `GET /api/v1/adminapp/tenant/accommodations/visibility`\n\nControlador: `App\\Domains\\FiestaFutbolInfantil\\Controllers\\CategoryVisibilityController@show`\n\nRequiere autenticación Sanctum.",
"url": {
"raw": "{{base_url}}/api/v1/adminapp/tenant/accommodations/visibility",
"host": [
"{{base_url}}"
],
"path": [
"api",
"v1",
"adminapp",
"tenant",
"accommodations",
"visibility"
]
},
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "{{admin_token}}",
"type": "string"
}
]
}
},
"response": []
},
{
"name": "Update Category Visibility",
"request": {
"method": "PATCH",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
}
],
"description": "Ruta Laravel: `PATCH /api/v1/adminapp/tenant/accommodations/visibility`\n\nControlador: `App\\Domains\\FiestaFutbolInfantil\\Controllers\\CategoryVisibilityController@update`\n\nRequiere autenticación Sanctum.",
"url": {
"raw": "{{base_url}}/api/v1/adminapp/tenant/accommodations/visibility",
"host": [
"{{base_url}}"
],
"path": [
"api",
"v1",
"adminapp",
"tenant",
"accommodations",
"visibility"
]
},
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "{{admin_token}}",
"type": "string"
}
]
}
},
"response": []
},
{
"name": "Delete Accommodation",
"request": {
@@ -3187,6 +3231,84 @@
},
"response": []
},
{
"name": "Get Category Visibility",
"request": {
"method": "GET",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
}
],
"description": "Ruta Laravel: `GET /api/v1/adminapp/tenant/entries/visibility`\n\nControlador: `App\\Domains\\FiestaFutbolInfantil\\Controllers\\CategoryVisibilityController@show`\n\nRequiere autenticación Sanctum.",
"url": {
"raw": "{{base_url}}/api/v1/adminapp/tenant/entries/visibility",
"host": [
"{{base_url}}"
],
"path": [
"api",
"v1",
"adminapp",
"tenant",
"entries",
"visibility"
]
},
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "{{admin_token}}",
"type": "string"
}
]
}
},
"response": []
},
{
"name": "Update Category Visibility",
"request": {
"method": "PATCH",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
}
],
"description": "Ruta Laravel: `PATCH /api/v1/adminapp/tenant/entries/visibility`\n\nControlador: `App\\Domains\\FiestaFutbolInfantil\\Controllers\\CategoryVisibilityController@update`\n\nRequiere autenticación Sanctum.",
"url": {
"raw": "{{base_url}}/api/v1/adminapp/tenant/entries/visibility",
"host": [
"{{base_url}}"
],
"path": [
"api",
"v1",
"adminapp",
"tenant",
"entries",
"visibility"
]
},
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "{{admin_token}}",
"type": "string"
}
]
}
},
"response": []
},
{
"name": "Delete Entry",
"request": {
@@ -3316,6 +3438,84 @@
},
"response": []
},
{
"name": "Get Category Visibility",
"request": {
"method": "GET",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
}
],
"description": "Ruta Laravel: `GET /api/v1/adminapp/tenant/foods/visibility`\n\nControlador: `App\\Domains\\FiestaFutbolInfantil\\Controllers\\CategoryVisibilityController@show`\n\nRequiere autenticación Sanctum.",
"url": {
"raw": "{{base_url}}/api/v1/adminapp/tenant/foods/visibility",
"host": [
"{{base_url}}"
],
"path": [
"api",
"v1",
"adminapp",
"tenant",
"foods",
"visibility"
]
},
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "{{admin_token}}",
"type": "string"
}
]
}
},
"response": []
},
{
"name": "Update Category Visibility",
"request": {
"method": "PATCH",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
}
],
"description": "Ruta Laravel: `PATCH /api/v1/adminapp/tenant/foods/visibility`\n\nControlador: `App\\Domains\\FiestaFutbolInfantil\\Controllers\\CategoryVisibilityController@update`\n\nRequiere autenticación Sanctum.",
"url": {
"raw": "{{base_url}}/api/v1/adminapp/tenant/foods/visibility",
"host": [
"{{base_url}}"
],
"path": [
"api",
"v1",
"adminapp",
"tenant",
"foods",
"visibility"
]
},
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "{{admin_token}}",
"type": "string"
}
]
}
},
"response": []
},
{
"name": "Delete Food",
"request": {
@@ -3445,6 +3645,84 @@
},
"response": []
},
{
"name": "Get Category Visibility",
"request": {
"method": "GET",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
}
],
"description": "Ruta Laravel: `GET /api/v1/adminapp/tenant/merchandise/visibility`\n\nControlador: `App\\Domains\\FiestaFutbolInfantil\\Controllers\\CategoryVisibilityController@show`\n\nRequiere autenticación Sanctum.",
"url": {
"raw": "{{base_url}}/api/v1/adminapp/tenant/merchandise/visibility",
"host": [
"{{base_url}}"
],
"path": [
"api",
"v1",
"adminapp",
"tenant",
"merchandise",
"visibility"
]
},
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "{{admin_token}}",
"type": "string"
}
]
}
},
"response": []
},
{
"name": "Update Category Visibility",
"request": {
"method": "PATCH",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
}
],
"description": "Ruta Laravel: `PATCH /api/v1/adminapp/tenant/merchandise/visibility`\n\nControlador: `App\\Domains\\FiestaFutbolInfantil\\Controllers\\CategoryVisibilityController@update`\n\nRequiere autenticación Sanctum.",
"url": {
"raw": "{{base_url}}/api/v1/adminapp/tenant/merchandise/visibility",
"host": [
"{{base_url}}"
],
"path": [
"api",
"v1",
"adminapp",
"tenant",
"merchandise",
"visibility"
]
},
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "{{admin_token}}",
"type": "string"
}
]
}
},
"response": []
},
{
"name": "Delete Merchandise",
"request": {
@@ -4049,6 +4327,45 @@
},
"response": []
},
{
"name": "download Excel Sale",
"request": {
"method": "GET",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
}
],
"description": "Ruta Laravel: `GET /api/v1/adminapp/tenant/sales/excel`\n\nControlador: `App\\Domains\\Sale\\Controllers\\AdminApp\\SaleController@downloadExcel`\n\nRequiere autenticación Sanctum.",
"url": {
"raw": "{{base_url}}/api/v1/adminapp/tenant/sales/excel",
"host": [
"{{base_url}}"
],
"path": [
"api",
"v1",
"adminapp",
"tenant",
"sales",
"excel"
]
},
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "{{admin_token}}",
"type": "string"
}
]
}
},
"response": []
},
{
"name": "List Modifications Sale",
"request": {
@@ -4088,6 +4405,46 @@
},
"response": []
},
{
"name": "download Modifications Excel Sale",
"request": {
"method": "GET",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
}
],
"description": "Ruta Laravel: `GET /api/v1/adminapp/tenant/sales/modifications/excel`\n\nControlador: `App\\Domains\\Sale\\Controllers\\AdminApp\\SaleController@downloadModificationsExcel`\n\nRequiere autenticación Sanctum.",
"url": {
"raw": "{{base_url}}/api/v1/adminapp/tenant/sales/modifications/excel",
"host": [
"{{base_url}}"
],
"path": [
"api",
"v1",
"adminapp",
"tenant",
"sales",
"modifications",
"excel"
]
},
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "{{admin_token}}",
"type": "string"
}
]
}
},
"response": []
},
{
"name": "Download Modifications PDF Sale",
"request": {
@@ -4601,6 +4958,127 @@
}
]
},
{
"name": "Ticket",
"item": [
{
"name": "List Ticket",
"request": {
"method": "GET",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
}
],
"description": "Ruta Laravel: `GET /api/v1/adminapp/tenant/tickets`\n\nControlador: `App\\Domains\\Ticket\\Controllers\\AdminApp\\TicketController@index`\n\nRequiere autenticación Sanctum.",
"url": {
"raw": "{{base_url}}/api/v1/adminapp/tenant/tickets",
"host": [
"{{base_url}}"
],
"path": [
"api",
"v1",
"adminapp",
"tenant",
"tickets"
]
},
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "{{admin_token}}",
"type": "string"
}
]
}
},
"response": []
},
{
"name": "download Excel Ticket",
"request": {
"method": "GET",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
}
],
"description": "Ruta Laravel: `GET /api/v1/adminapp/tenant/tickets/excel`\n\nControlador: `App\\Domains\\Ticket\\Controllers\\AdminApp\\TicketController@downloadExcel`\n\nRequiere autenticación Sanctum.",
"url": {
"raw": "{{base_url}}/api/v1/adminapp/tenant/tickets/excel",
"host": [
"{{base_url}}"
],
"path": [
"api",
"v1",
"adminapp",
"tenant",
"tickets",
"excel"
]
},
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "{{admin_token}}",
"type": "string"
}
]
}
},
"response": []
},
{
"name": "Download PDF Ticket",
"request": {
"method": "GET",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
}
],
"description": "Ruta Laravel: `GET /api/v1/adminapp/tenant/tickets/pdf`\n\nControlador: `App\\Domains\\Ticket\\Controllers\\AdminApp\\TicketController@downloadPdf`\n\nRequiere autenticación Sanctum.",
"url": {
"raw": "{{base_url}}/api/v1/adminapp/tenant/tickets/pdf",
"host": [
"{{base_url}}"
],
"path": [
"api",
"v1",
"adminapp",
"tenant",
"tickets",
"pdf"
]
},
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "{{admin_token}}",
"type": "string"
}
]
}
},
"response": []
}
]
},
{
"name": "Tenant",
"item": [
@@ -5254,6 +5732,11 @@
"value": "http://localhost:8000",
"type": "string"
},
{
"key": "storefront_url",
"value": "http://localhost:4200",
"type": "string"
},
{
"key": "token",
"value": "",

View File

@@ -0,0 +1,49 @@
<?php
namespace App\Domains\Administrator\Controllers;
use App\Domains\Administrator\Requests\StoreAdministratorRequest;
use App\Domains\Administrator\Requests\UpdateAdministratorRequest;
use App\Domains\Administrator\Resources\AdministratorResource;
use App\Domains\Administrator\Services\AdministratorService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Symfony\Component\HttpFoundation\Response;
class AdminAppAdministratorController extends Controller
{
public function __construct(private readonly AdministratorService $administratorService) {}
public function index(Request $request): AnonymousResourceCollection
{
return AdministratorResource::collection($this->administratorService->list(
$request->user()->tenant()->firstOrFail(),
$request->string('search')->trim()->toString() ?: null,
));
}
public function store(StoreAdministratorRequest $request): AdministratorResource
{
return AdministratorResource::make($this->administratorService->create(
$request->user()->tenant()->firstOrFail(),
$request->validated(),
));
}
public function update(UpdateAdministratorRequest $request, int $administrator): AdministratorResource
{
return AdministratorResource::make($this->administratorService->update(
$request->user()->tenant()->firstOrFail(),
$administrator,
$request->validated(),
));
}
public function destroy(Request $request, int $administrator): Response
{
$this->administratorService->delete($request->user()->tenant()->firstOrFail(), $administrator, $request->user());
return response()->noContent();
}
}

View File

@@ -0,0 +1,38 @@
<?php
namespace App\Domains\Administrator\Requests;
use App\Domains\Authorization\Enums\RoleCode;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class StoreAdministratorRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user()?->rol_codigo === RoleCode::AdminApp->value;
}
protected function prepareForValidation(): void
{
if (is_string($this->input('email'))) {
$this->merge(['email' => mb_strtolower(trim($this->input('email')))]);
}
}
/** @return array<string, mixed> */
public function rules(): array
{
return [
'nombre_apellido' => ['required', 'string', 'max:255'],
'dni' => ['required', 'string', 'max:50'],
'email' => [
'required',
'email',
'max:255',
Rule::unique('users', 'active_email')->where('rol_codigo', RoleCode::AdminApp->value)->whereNull('deleted_at'),
],
];
}
}

View File

@@ -0,0 +1,41 @@
<?php
namespace App\Domains\Administrator\Requests;
use App\Domains\Authorization\Enums\RoleCode;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class UpdateAdministratorRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user()?->rol_codigo === RoleCode::AdminApp->value;
}
protected function prepareForValidation(): void
{
if (is_string($this->input('email'))) {
$this->merge(['email' => mb_strtolower(trim($this->input('email')))]);
}
}
/** @return array<string, mixed> */
public function rules(): array
{
$administratorId = (int) $this->route('administrator');
return [
'nombre_apellido' => ['required', 'string', 'max:255'],
'dni' => ['required', 'string', 'max:50'],
'email' => [
'required',
'email',
'max:255',
Rule::unique('users', 'active_email')->where('rol_codigo', RoleCode::AdminApp->value)
->whereNull('deleted_at')
->ignore($administratorId),
],
];
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace App\Domains\Administrator\Resources;
use App\Domains\Auth\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/** @mixin User */
class AdministratorResource extends JsonResource
{
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'nombre_apellido' => $this->nombre_apellido,
'dni' => $this->dni,
'email' => $this->email,
'rol_codigo' => $this->rol_codigo,
'role' => $this->whenLoaded('role', fn () => [
'codigo' => $this->role?->codigo,
'nombre' => $this->role?->nombre,
]),
];
}
}

View File

@@ -0,0 +1,99 @@
<?php
namespace App\Domains\Administrator\Services;
use App\Domains\Auth\Models\ResetPasswordAttempt;
use App\Domains\Auth\Models\User;
use App\Domains\Auth\Services\ResetPasswordAttemptService;
use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class AdministratorService
{
public function __construct(private readonly ResetPasswordAttemptService $resetPasswordAttemptService) {}
/** @return Collection<int, User> */
public function list(Tenant $tenant, ?string $search = null): Collection
{
return $this->query($tenant)->with('role')
->when($search, fn (Builder $query, string $search) => $query->where(function (Builder $query) use ($search): void {
$query->where('nombre_apellido', 'like', "%{$search}%")
->orWhere('dni', 'like', "%{$search}%")
->orWhere('email', 'like', "%{$search}%");
}))
->orderBy('nombre_apellido')->get();
}
/** @param array<string, mixed> $data */
public function create(Tenant $tenant, array $data): User
{
return DB::transaction(function () use ($tenant, $data): User {
$administrator = User::query()->create([
...$this->attributes($data),
'password' => Str::random(64),
'rol_codigo' => RoleCode::AdminApp->value,
'tenant_codigo' => $tenant->codigo,
]);
$this->resetPasswordAttemptService->createForAdminAppEmail(
$administrator->email,
ResetPasswordAttempt::REASON_ADMINISTRATOR_CREATED,
);
return $administrator->load('role');
});
}
/** @param array<string, mixed> $data */
public function update(Tenant $tenant, int $administratorId, array $data): User
{
return DB::transaction(function () use ($tenant, $administratorId, $data): User {
$administrator = $this->query($tenant)->lockForUpdate()->findOrFail($administratorId);
$administrator->update($this->attributes($data));
return $administrator->load('role');
});
}
public function delete(Tenant $tenant, int $administratorId, User $actor): void
{
DB::transaction(function () use ($tenant, $administratorId, $actor): void {
// Serialize deletions for this tenant, including requests already authenticated
// when another administrator removes their account.
Tenant::query()->whereKey($tenant->getKey())->lockForUpdate()->firstOrFail();
$administrator = $this->query($tenant)->lockForUpdate()->findOrFail($administratorId);
if ($administrator->is($actor)) {
throw ValidationException::withMessages(['administrator' => 'No podés eliminar tu propio usuario.']);
}
$activeAdministrators = $this->query($tenant)->lockForUpdate()->get();
if ($activeAdministrators->count() <= 1) {
throw ValidationException::withMessages(['administrator' => 'El tenant debe conservar al menos un administrador.']);
}
abort_unless($activeAdministrators->contains('id', $actor->id), 403);
$administrator->tokens()->delete();
$administrator->delete();
});
}
private function query(Tenant $tenant): Builder
{
return User::query()->where('tenant_codigo', $tenant->codigo)
->where('rol_codigo', RoleCode::AdminApp->value);
}
/** @param array<string, mixed> $data
* @return array<string, mixed>
*/
private function attributes(array $data): array
{
return [
...Arr::only($data, ['nombre_apellido', 'dni']),
'email' => mb_strtolower(trim((string) $data['email'])),
];
}
}

View File

@@ -0,0 +1,63 @@
# Administradores de AdminApp
CRUD de usuarios con rol `adminapp`, limitado al tenant del usuario autenticado.
Todos los administradores del tenant pueden gestionar esta sección.
## Endpoints
Base: `/api/v1/adminapp/tenant/administrators`.
Requieren `auth:sanctum` y `adminapp.tenant`.
- `GET /`: listado ordenado por nombre; acepta `search` por nombre, DNI o email.
- `POST /`: alta; responde `201` con `data`.
- `PUT /{administrator}`: actualización de los tres campos; responde `200` con `data`.
- `DELETE /{administrator}`: baja lógica; responde `204`.
Alta y actualización reciben:
```json
{
"nombre_apellido": "Ada Lovelace",
"dni": "12345678",
"email": "ada@example.test"
}
```
Nombre (hasta 255 caracteres), DNI (hasta 50) y email (hasta 255) son obligatorios.
El email se normaliza a minúsculas antes de validar y debe ser único entre
usuarios activos, sin importar su tenant o rol. Se permite reutilizar el email
de un usuario eliminado. Rol y tenant no son editables desde esta API.
Las respuestas incluyen `id`, `nombre_apellido`, `dni`, `email`, `rol_codigo`
y `role` (`codigo`, `nombre`). Nunca incluyen contraseña ni datos de escaneo.
## Alta y acceso
Se genera una contraseña aleatoria y un intento de establecimiento de contraseña
con motivo `administrator_created`, reutilizando `createForAdminAppEmail`.
El evento usa el canal `adminapp`; el listener existente envía el email después
del commit mediante la cola `emails`. Requiere la configuración de correo,
dominio AdminApp y worker existentes. No se envían contraseñas en texto plano.
## Eliminación y aislamiento
Las consultas de usuarios se limitan por tenant y rol `adminapp`. IDs ajenos,
usuarios eliminados y usuarios de otros roles devuelven `404`.
La validación de campos devuelve `422`; falta de autenticación, `401`, y rol
no autorizado, `403`.
No se permite eliminar al propio usuario ni dejar al tenant sin administradores
(`422`, error `administrator`). La eliminación bloquea la fila del tenant dentro
de una transacción para serializar bajas concurrentes. También verifica que el
actor siga activo, revoca tokens y aplica el borrado lógico existente en `users`.
No agrega tablas ni migraciones. No modifica el CRUD de escáneres ni el frontend.
## Verificación
`php artisan test tests/Feature/Administrator/AdministratorControllerTest.php`
Las pruebas cubren CRUD, normalización y unicidad del email, establecimiento de
contraseña, restricciones de rol y tenant, baja lógica, tokens y protecciones de
eliminación. El caso de petición autenticada antes de la baja del actor se simula;
no es una prueba con conexiones concurrentes reales.

View File

@@ -0,0 +1,10 @@
<?php
use App\Domains\Administrator\Controllers\AdminAppAdministratorController;
use Illuminate\Support\Facades\Route;
Route::prefix('v1/adminapp/tenant')
->middleware(['auth:sanctum', 'adminapp.tenant'])
->group(function (): void {
Route::apiResource('administrators', AdminAppAdministratorController::class)->except('show');
});

View File

@@ -5,6 +5,7 @@ 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\Domains\Authorization\Enums\RoleCode;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Validation\ValidationException;
@@ -26,6 +27,7 @@ class ResetPasswordController extends Controller
$data['email'],
$data['codigo'],
$data['password'],
RoleCode::from($request->route('reset_role', RoleCode::User->value)),
)) {
throw ValidationException::withMessages([
'codigo' => __('api.auth.password_reset_invalid'),

View File

@@ -5,6 +5,7 @@ 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\Domains\Authorization\Enums\RoleCode;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Validation\ValidationException;
@@ -25,6 +26,7 @@ class ValidateResetPasswordAttemptController extends Controller
$result = $this->resetPasswordAttemptService->validateCode(
$data['email'],
$data['codigo'],
RoleCode::from($request->route('reset_role', RoleCode::User->value)),
);
if ($result === ResetPasswordAttemptService::CODE_EXPIRED) {

View File

@@ -17,6 +17,8 @@ class ResetPasswordAttempt extends Model
public const REASON_STAFF_CREATED = 'staff_created';
public const REASON_ADMINISTRATOR_CREATED = 'administrator_created';
public const STATUS_PENDING = 'pending';
public const STATUS_VALIDATED = 'validated';

View File

@@ -13,16 +13,17 @@ 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\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
#[Fillable(['nombre_apellido', 'email', 'password', 'dni', 'telefono', 'google_id', 'rol_codigo', 'tenant_codigo'])]
#[Hidden(['password', 'remember_token'])]
#[Hidden(['password', 'remember_token', 'active_email', 'active_google_id'])]
class User extends Authenticatable
{
/** @use HasFactory<UserFactory> */
use HasApiTokens, HasFactory, Notifiable;
use HasApiTokens, HasFactory, Notifiable, SoftDeletes;
protected $attributes = [
'rol_codigo' => RoleCode::User->value,

View File

@@ -2,6 +2,7 @@
namespace App\Domains\Auth\Requests;
use App\Domains\Authorization\Enums\RoleCode;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\Password;
@@ -13,15 +14,26 @@ class RegisterUserRequest extends FormRequest
return true;
}
/**
* @return array<string, mixed>
*/
protected function prepareForValidation(): void
{
if (is_string($this->input('email'))) {
$this->merge(['email' => mb_strtolower(trim($this->input('email')))]);
}
}
/** @return array<string, mixed> */
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')],
'email' => [
'required',
'string',
'email',
'max:255',
Rule::unique('users', 'active_email')->where('rol_codigo', RoleCode::User->value)->whereNull('deleted_at'),
],
'password' => ['required', 'string', 'confirmed', Password::min(8)->mixedCase()->symbols()],
'dni' => ['nullable', 'string', 'max:255'],
'telefono' => ['nullable', 'string', 'max:255'],

View File

@@ -4,6 +4,7 @@ namespace App\Domains\Auth\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\Password;
class UpdateProfileRequest extends FormRequest
{
@@ -12,6 +13,13 @@ class UpdateProfileRequest extends FormRequest
return true;
}
protected function prepareForValidation(): void
{
if (is_string($this->input('email'))) {
$this->merge(['email' => mb_strtolower(trim($this->input('email')))]);
}
}
public function rules(): array
{
return [
@@ -19,11 +27,13 @@ class UpdateProfileRequest extends FormRequest
'email' => [
'required',
'email',
Rule::unique('users', 'email')->ignore($this->user()->id),
Rule::unique('users', 'active_email')->where('rol_codigo', $this->user()->rol_codigo)
->whereNull('deleted_at')
->ignore($this->user()->id),
],
'dni' => ['nullable', 'string', 'regex:/^[0-9]{7,8}$/'],
'telefono' => ['nullable', 'string', 'regex:/^\+?[0-9\s\-]+$/'],
'password' => ['nullable', 'string', \Illuminate\Validation\Rules\Password::min(8)->mixedCase()->symbols()],
'password' => ['nullable', 'string', Password::min(8)->mixedCase()->symbols()],
];
}
}

View File

@@ -11,7 +11,7 @@ class AdminCredentialVerifier
public function verify(string $email, string $password): bool
{
$admin = User::query()
->where('email', mb_strtolower(trim($email)))
->where('active_email', mb_strtolower(trim($email)))
->where('rol_codigo', RoleCode::Admin->value)
->first();

View File

@@ -3,6 +3,7 @@
namespace App\Domains\Auth\Services;
use App\Domains\Auth\Models\User;
use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Notification\Events\UserRegistered;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Support\TenantDomainNormalizer;
@@ -124,12 +125,12 @@ class GoogleAuthService
]);
}
$user = User::query()->where('google_id', $googleId)->first();
$user = User::query()->where('rol_codigo', RoleCode::User->value)->where('google_id', $googleId)->first();
if ($user) {
return $user;
}
$user = User::query()->where('email', $email)->first();
$user = User::query()->where('rol_codigo', RoleCode::User->value)->where('active_email', mb_strtolower(trim($email)))->first();
if ($user) {
$user->forceFill(['google_id' => $googleId])->save();

View File

@@ -85,7 +85,7 @@ class PasswordLoginService
null,
$ipAddress,
$userAgent,
null,
RoleCode::Scanner,
true,
PermissionCode::ScanTickets->value,
PasswordResetRequested::CHANNEL_SCANNER,
@@ -120,7 +120,7 @@ class PasswordLoginService
$passwordResetChannel,
): array {
$user = User::query()
->where('email', $normalizedEmail)
->where('active_email', $normalizedEmail)
->when(
$requiredRole !== null,
fn ($query) => $query->where('rol_codigo', $requiredRole->value),

View File

@@ -28,7 +28,8 @@ class ResetPasswordAttemptService
try {
$attemptId = DB::transaction(function () use ($email, $emailFingerprint, $reason): ?int {
$user = User::query()
->where('email', $email)
->where('active_email', mb_strtolower(trim($email)))
->where('rol_codigo', RoleCode::User->value)
->lockForUpdate()
->first();
@@ -65,7 +66,7 @@ class ResetPasswordAttemptService
try {
$result = DB::transaction(function () use ($email, $emailFingerprint, $reason): ?array {
$user = User::query()
->where('email', $email)
->where('active_email', mb_strtolower(trim($email)))
->where('rol_codigo', RoleCode::AdminApp->value)
->whereNotNull('tenant_codigo')
->lockForUpdate()
@@ -113,7 +114,7 @@ class ResetPasswordAttemptService
try {
$result = DB::transaction(function () use ($email, $emailFingerprint, $reason): ?array {
$user = User::query()
->where('email', $email)
->where('active_email', mb_strtolower(trim($email)))
->where('rol_codigo', RoleCode::Scanner->value)
->whereNotNull('tenant_codigo')
->lockForUpdate()
@@ -152,14 +153,15 @@ class ResetPasswordAttemptService
);
}
public function validateCode(string $email, string $code): string
public function validateCode(string $email, string $code, RoleCode $role = RoleCode::User): string
{
$emailFingerprint = $this->emailFingerprint($email);
try {
return DB::transaction(function () use ($email, $code, $emailFingerprint): string {
return DB::transaction(function () use ($email, $code, $emailFingerprint, $role): string {
$user = User::query()
->where('email', $email)
->where('active_email', mb_strtolower(trim($email)))
->where('rol_codigo', $role->value)
->lockForUpdate()
->first();
@@ -207,14 +209,15 @@ class ResetPasswordAttemptService
}
}
public function resetPassword(string $email, string $code, string $password): bool
public function resetPassword(string $email, string $code, string $password, RoleCode $role = RoleCode::User): bool
{
$emailFingerprint = $this->emailFingerprint($email);
try {
return DB::transaction(function () use ($email, $code, $password, $emailFingerprint): bool {
return DB::transaction(function () use ($email, $code, $password, $emailFingerprint, $role): bool {
$user = User::query()
->where('email', $email)
->where('active_email', mb_strtolower(trim($email)))
->where('rol_codigo', $role->value)
->lockForUpdate()
->first();

View File

@@ -12,8 +12,10 @@ Route::prefix('v1/adminapp')->group(function (): void {
Route::post('password/reset-attempts', CreateAdminAppResetPasswordAttemptController::class)
->middleware('throttle:5,1');
Route::post('password/reset-attempts/validate', ValidateResetPasswordAttemptController::class)
->defaults('reset_role', 'adminapp')
->middleware('throttle:10,1');
Route::post('password/reset', ResetPasswordController::class)
->defaults('reset_role', 'adminapp')
->middleware('throttle:5,1');
Route::middleware(['auth:sanctum', 'adminapp.tenant'])
->get('me', AdminAppMeController::class);

View File

@@ -12,8 +12,10 @@ Route::prefix('v1/scanner')->group(function (): void {
Route::post('password/reset-attempts', CreateScannerResetPasswordAttemptController::class)
->middleware('throttle:5,1');
Route::post('password/reset-attempts/validate', ValidateResetPasswordAttemptController::class)
->defaults('reset_role', 'scanner')
->middleware('throttle:10,1');
Route::post('password/reset', ResetPasswordController::class)
->defaults('reset_role', 'scanner')
->middleware('throttle:5,1');
Route::middleware(['auth:sanctum', 'scanner.tenant'])
->get('me', ScannerMeController::class);

View File

@@ -104,7 +104,11 @@ class InvitationPurchaseProvisioner
private function userId(DateTimeInterface $now): int
{
$user = DB::table('users')->where('email', self::USER_EMAIL)->first();
$user = DB::table('users')
->where('active_email', self::USER_EMAIL)
->where('rol_codigo', 'user')
->whereNull('deleted_at')
->first();
if ($user !== null) {
if ($user->tenant_codigo !== self::TENANT_CODE) {

View File

@@ -32,13 +32,14 @@ class NotificationMailService
$tenant = Tenant::query()->with('websiteType')->where('codigo', $tenantCode)->firstOrFail();
$user = User::query()->findOrFail($userId);
$brand = $tenant->websiteType ?? $tenant;
$tenantUrl = 'https://'.$tenant->dominio.$tenant->base_path;
$this->mailService
->forTenant($tenantCode)
->send(
$user->email,
"Bienvenido a {$brand->nombre}",
view('mail.notifications.welcome', compact('brand', 'user'))->render(),
view('mail.notifications.welcome', compact('brand', 'user', 'tenantUrl'))->render(),
$brand,
);
@@ -99,12 +100,25 @@ class NotificationMailService
: 'https://'.$recoveryDomain.$recoveryBasePath.'/recuperar-contrasena/codigo?'.http_build_query($recoveryQuery);
$brand = $tenant->websiteType ?? $tenant;
[$subject, $template] = match ($attempt->reason) {
ResetPasswordAttempt::REASON_STAFF_CREATED => [
'Tu cuenta de escáner está lista', 'scanner-created',
],
ResetPasswordAttempt::REASON_ADMINISTRATOR_CREATED => [
'Tu cuenta de administrador está lista', 'administrator-created',
],
ResetPasswordAttempt::REASON_ACCOUNT_LOCKED => [
'Desbloqueá tu cuenta', 'account-locked',
],
default => ['Código para recuperar tu contraseña', 'password-reset'],
};
$this->mailService
->forTenant($tenantCode)
->send(
$attempt->user->email,
"Código para recuperar tu contraseña - {$brand->nombre}",
view('mail.notifications.password-reset', [
"{$subject} - {$brand->nombre}",
view("mail.notifications.{$template}", [
'attempt' => $attempt,
'recoveryUrl' => $recoveryUrl,
'brand' => $brand,

View File

@@ -2,6 +2,7 @@
namespace App\Domains\Staff\Requests;
use App\Domains\Authorization\Enums\RoleCode;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
@@ -12,6 +13,13 @@ class StoreStaffRequest extends FormRequest
return true;
}
protected function prepareForValidation(): void
{
if (is_string($this->input('email'))) {
$this->merge(['email' => mb_strtolower(trim($this->input('email')))]);
}
}
/** @return array<string, mixed> */
public function rules(): array
{
@@ -23,7 +31,12 @@ class StoreStaffRequest extends FormRequest
return [
'nombre_apellido' => ['required', 'string', 'max:255'],
'dni' => ['required', 'string', 'max:50'],
'email' => ['required', 'email', 'max:255', 'unique:users,email'],
'email' => [
'required',
'email',
'max:255',
Rule::unique('users', 'active_email')->where('rol_codigo', RoleCode::Scanner->value)->whereNull('deleted_at'),
],
'category_ids' => $categoryRules,
'category_ids.*' => ['integer', 'distinct', Rule::exists('categorias', 'id')],
];

View File

@@ -2,6 +2,7 @@
namespace App\Domains\Staff\Requests;
use App\Domains\Authorization\Enums\RoleCode;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
@@ -12,6 +13,13 @@ class UpdateStaffRequest extends FormRequest
return true;
}
protected function prepareForValidation(): void
{
if (is_string($this->input('email'))) {
$this->merge(['email' => mb_strtolower(trim($this->input('email')))]);
}
}
/** @return array<string, mixed> */
public function rules(): array
{
@@ -28,7 +36,9 @@ class UpdateStaffRequest extends FormRequest
'required',
'email',
'max:255',
Rule::unique('users', 'email')->ignore($staffId),
Rule::unique('users', 'active_email')->where('rol_codigo', RoleCode::Scanner->value)
->whereNull('deleted_at')
->ignore($staffId),
],
'category_ids' => $categoryRules,
'category_ids.*' => ['integer', 'distinct', Rule::exists('categorias', 'id')],

View File

@@ -94,7 +94,12 @@ class StaffService
public function delete(Tenant $tenant, int $staffId): void
{
$this->find($tenant, $staffId)->delete();
$staff = $this->find($tenant, $staffId);
DB::transaction(function () use ($staff): void {
$staff->tokens()->delete();
$staff->delete();
});
}
public function find(Tenant $tenant, int $staffId): User

View File

@@ -78,7 +78,7 @@ class Ticket extends Model
/** @return BelongsTo<User, $this> */
public function scannerUser(): BelongsTo
{
return $this->belongsTo(User::class, 'scanner_user_id');
return $this->belongsTo(User::class, 'scanner_user_id')->withTrashed();
}
/** @return BelongsTo<PurchaseItem, $this> */

View File

@@ -293,6 +293,7 @@ class AdminAppTicketService
'id' => 'tickets.id',
'amount' => $this->purchaseItemColumnQuery('precio_unitario'),
'scanned_by' => User::query()
->withTrashed()
->select('nombre_apellido')
->whereColumn('users.id', 'tickets.scanner_user_id'),
'product' => $tenant->codigo === 'fiesta_futbol_infantil'

View File

@@ -0,0 +1,229 @@
<?php
namespace App\Domains\Ticket\Services;
use App\Domains\Auth\Models\User;
use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Catalog\Enums\CatalogItemType;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use InvalidArgumentException;
class LoadTestTicketDatasetService
{
public function __construct(
private readonly TicketGeneratorService $ticketGenerator,
private readonly TicketValidityResolver $validityResolver,
) {}
/**
* @return array{
* run_id: string,
* tenant_code: string,
* catalog_item_id: int,
* variant_id: int|null,
* tickets: int,
* scanners: int,
* owners: int,
* rows: array<int, array{scanner_token: string, ticket_uuid: string, expected_status: int}>
* }
*/
public function prepare(
string $tenantCode,
int $ticketCount,
int $scannerCount,
int $ownerCount,
?int $catalogItemId = null,
?int $variantId = null,
?string $runId = null,
): array {
$this->validateInput($tenantCode, $ticketCount, $scannerCount, $ownerCount);
$tenant = Tenant::query()->where('codigo', $tenantCode)->firstOrFail();
$catalogItem = $this->resolveCatalogItem($tenant, $catalogItemId);
$variant = $this->resolveVariant($catalogItem, $variantId);
$runId ??= now()->format('Ymd-His').'-'.Str::lower(Str::random(6));
if (preg_match('/\A[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}\z/', $runId) !== 1) {
throw new InvalidArgumentException('run_id contiene caracteres inválidos o es demasiado largo.');
}
if ($variant !== null && ! $this->validityResolver->resolveVariant($variant)->isValid()) {
throw new InvalidArgumentException(
'La variante seleccionada no tiene una vigencia activa y resoluble.'
);
}
$scanners = $this->scanners($tenant, $catalogItem, $scannerCount);
$owners = $this->owners($tenant, $ownerCount);
$tokens = $scanners->map(function (User $scanner): string {
$scanner->tokens()->where('name', 'load-test-scanner')->delete();
return $scanner->createToken(
'load-test-scanner',
['scanner'],
now()->addMinutes((int) config('sanctum.expiration', 720)),
)->plainTextToken;
})->values();
$rows = [];
$remaining = $ticketCount;
$ownerIndex = 0;
$scannerIndex = 0;
$batchSize = min(500, max(1, (int) ceil($ticketCount / $ownerCount)));
while ($remaining > 0) {
$quantity = min($batchSize, $remaining);
$owner = $owners[$ownerIndex % $owners->count()];
$tickets = $this->ticketGenerator->generate(
$catalogItem,
$owner,
$quantity,
$variant?->getKey(),
);
foreach ($tickets as $ticket) {
if (! $ticket->is_valid) {
throw new InvalidArgumentException(
'La configuración seleccionada genera tickets que no están vigentes.'
);
}
$rows[] = [
'scanner_token' => $tokens[$scannerIndex % $tokens->count()],
'ticket_uuid' => $ticket->ticket,
'expected_status' => 200,
];
$scannerIndex++;
}
$remaining -= $quantity;
$ownerIndex++;
}
return [
'run_id' => $runId,
'tenant_code' => $tenant->codigo,
'catalog_item_id' => $catalogItem->getKey(),
'variant_id' => $variant?->getKey(),
'tickets' => count($rows),
'scanners' => $scanners->count(),
'owners' => $owners->count(),
'rows' => $rows,
];
}
private function validateInput(
string $tenantCode,
int $ticketCount,
int $scannerCount,
int $ownerCount,
): void {
foreach ([
'tickets' => [$ticketCount, 100_000],
'scanners' => [$scannerCount, 10_000],
'owners' => [$ownerCount, 100_000],
] as $name => [$value, $maximum]) {
if ($value < 1 || $value > $maximum) {
throw new InvalidArgumentException("{$name} debe estar entre 1 y {$maximum}.");
}
}
if ($scannerCount > $ticketCount || $ownerCount > $ticketCount) {
throw new InvalidArgumentException(
'La cantidad de scanners y propietarios no puede superar la cantidad de tickets.'
);
}
}
private function resolveCatalogItem(Tenant $tenant, ?int $catalogItemId): CatalogItem
{
$query = $tenant->catalogItems()
->where('has_tickets', true)
->where('type', CatalogItemType::Standard->value);
if ($catalogItemId !== null) {
$query->whereKey($catalogItemId);
}
$catalogItem = $query->first();
if ($catalogItem === null) {
throw new InvalidArgumentException(
'No se encontró un producto estándar con tickets habilitados para el tenant.'
);
}
if ($tenant->requiresScannerCategoryValidation() && $catalogItem->category_id === null) {
throw new InvalidArgumentException(
'El producto debe tener una categoría para autorizar a los scanners.'
);
}
return $catalogItem;
}
private function resolveVariant(CatalogItem $catalogItem, ?int $variantId): ?Variant
{
if ($variantId === null) {
return null;
}
$variant = $catalogItem->variants()->whereKey($variantId)->first();
if ($variant === null) {
throw new InvalidArgumentException('La variante no pertenece al producto seleccionado.');
}
return $variant;
}
/** @return Collection<int, User> */
private function scanners(Tenant $tenant, CatalogItem $catalogItem, int $count): Collection
{
return Collection::times($count, function (int $number) use ($tenant, $catalogItem): User {
$scanner = User::query()->updateOrCreate(
['email' => $this->email($tenant, 'scanner', $number)],
[
'nombre_apellido' => "Load test scanner {$number}",
'password' => Str::password(32),
'rol_codigo' => RoleCode::Scanner->value,
'tenant_codigo' => $tenant->codigo,
],
);
if ($tenant->requiresScannerCategoryValidation()) {
$scanner->scanCategories()->syncWithoutDetaching([$catalogItem->category_id]);
}
return $scanner;
});
}
/** @return Collection<int, User> */
private function owners(Tenant $tenant, int $count): Collection
{
return Collection::times($count, function (int $number) use ($tenant): User {
$owner = User::query()->updateOrCreate(
['email' => $this->email($tenant, 'owner', $number)],
[
'nombre_apellido' => "Load test owner {$number}",
'password' => Str::password(32),
'rol_codigo' => RoleCode::User->value,
'tenant_codigo' => $tenant->codigo,
],
);
return $owner;
});
}
private function email(Tenant $tenant, string $kind, int $number): string
{
$tenantSlug = Str::lower(preg_replace('/[^a-z0-9]+/i', '-', $tenant->codigo));
return "loadtest+{$tenantSlug}.{$kind}.{$number}@shopit.test";
}
}

View File

@@ -73,7 +73,7 @@ class ScannerTicketService
->where('tenant_code', $scanner->tenant_codigo)
->where('ticket', $ticketUuid);
if ($scanner->tenant()->firstOrFail()->requiresScannerCategoryValidation()) {
if ($this->requiresCategoryValidation($scanner)) {
$categoryIds = $this->scannerCategoryIds($scanner);
$query->where(function (Builder $query) use ($scanner, $categoryIds): void {
@@ -158,7 +158,7 @@ class ScannerTicketService
private function scannerCanScan(User $scanner, Ticket $ticket): bool
{
if (! $scanner->tenant()->firstOrFail()->requiresScannerCategoryValidation()) {
if (! $this->requiresCategoryValidation($scanner)) {
return true;
}
@@ -169,4 +169,9 @@ class ScannerTicketService
->where('categorias.id', $categoryId)
->exists();
}
private function requiresCategoryValidation(User $scanner): bool
{
return $scanner->tenant()->firstOrFail()->requiresScannerCategoryValidation();
}
}

View File

@@ -24,6 +24,33 @@ vigente, vencido o usado, y resuelve sus fechas efectivas de inicio y fin sin pe
3. `TicketGeneratorService` crea los tickets requeridos según ítems, cantidades y vigencia.
4. `Notification` envía la confirmación de compra después de la generación y adjunta los tickets cuando existen.
## Datos descartables para pruebas de carga
En ambientes `local`, `testing`, `staging`, `homo` u `homologation`, el comando siguiente crea tickets
válidos, identidades scanner con tokens Sanctum y un dataset JSON importable por Postman:
```bash
php artisan load-test:tickets:prepare loadtest-evento \
--tickets=40000 \
--scanners=100 \
--owners=1000 \
--catalog-item=123 \
--run=evento-001
```
El tenant debe existir y se recomienda que sea exclusivo para carga. Si no se indica `--catalog-item`,
se usa el primer producto estándar del tenant con tickets habilitados. `--variant`
es opcional; al indicarlo, su configuración de vigencia debe estar activa y ser resoluble. Sin variante,
los tickets tienen vigencia irrestricta.
El archivo se escribe por defecto en `storage/app/private/load-tests/` y contiene tokens secretos, por
lo que no debe versionarse. Para limpiar el tenant después de la ejecución:
```bash
php artisan tenants:reset-transactions loadtest-evento --dry-run
php artisan tenants:reset-transactions loadtest-evento
```
## Endpoints
Bajo `/tenants/{tenant:codigo}`, protegidos por `auth:sanctum`:

View File

@@ -3,6 +3,7 @@
namespace App\Http\Middleware;
use App\Domains\Authorization\Enums\PermissionCode;
use App\Domains\Authorization\Enums\RoleCode;
use Closure;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\Request;
@@ -19,6 +20,7 @@ class EnsureScannerTenant
if (
! $user
|| $user->rol_codigo !== RoleCode::Scanner->value
|| ! $user->tenant_codigo
|| ! $user->hasPermission(PermissionCode::ScanTickets->value)
) {

View File

@@ -0,0 +1,23 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('users', function (Blueprint $table): void {
$table->softDeletes();
});
}
public function down(): void
{
Schema::table('users', function (Blueprint $table): void {
$table->dropSoftDeletes();
});
}
};

View File

@@ -0,0 +1,28 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('users', function (Blueprint $table): void {
$table->dropUnique(['email']);
$table->string('active_email')
->nullable()
->storedAs('CASE WHEN `deleted_at` IS NULL THEN LOWER(`email`) ELSE NULL END');
$table->unique('active_email');
});
}
public function down(): void
{
Schema::table('users', function (Blueprint $table): void {
$table->dropUnique(['active_email']);
$table->dropColumn('active_email');
$table->unique('email');
});
}
};

View File

@@ -0,0 +1,28 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('users', function (Blueprint $table): void {
$table->dropUnique(['google_id']);
$table->string('active_google_id')
->nullable()
->storedAs('CASE WHEN `deleted_at` IS NULL THEN `google_id` ELSE NULL END');
$table->unique('active_google_id');
});
}
public function down(): void
{
Schema::table('users', function (Blueprint $table): void {
$table->dropUnique(['active_google_id']);
$table->dropColumn('active_google_id');
$table->unique('google_id');
});
}
};

View File

@@ -0,0 +1,29 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
private const MENU_CODE = 'adminapp.staff';
public function up(): void
{
DB::table('menues')
->where('code', self::MENU_CODE)
->update([
'label' => 'Usuarios',
'updated_at' => now(),
]);
}
public function down(): void
{
DB::table('menues')
->where('code', self::MENU_CODE)
->update([
'label' => 'Staff',
'updated_at' => now(),
]);
}
};

View File

@@ -0,0 +1,24 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('users', function (Blueprint $table): void {
$table->unique(['active_email', 'rol_codigo']);
$table->dropUnique(['active_email']);
});
}
public function down(): void
{
Schema::table('users', function (Blueprint $table): void {
$table->unique('active_email');
$table->dropUnique(['active_email', 'rol_codigo']);
});
}
};

View File

@@ -0,0 +1,42 @@
<?php
use App\Domains\Authorization\Enums\PermissionCode;
use App\Domains\Authorization\Enums\RoleCode;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
public function up(): void
{
DB::table('roles_permisos')
->where('rol_codigo', RoleCode::AdminApp->value)
->where('codigo_permiso', PermissionCode::ScanTickets->value)
->delete();
}
public function down(): void
{
$roleExists = DB::table('roles')
->where('codigo', RoleCode::AdminApp->value)
->exists();
$permissionExists = DB::table('permisos')
->where('codigo', PermissionCode::ScanTickets->value)
->exists();
if (! $roleExists || ! $permissionExists) {
return;
}
DB::table('roles_permisos')->updateOrInsert(
[
'rol_codigo' => RoleCode::AdminApp->value,
'codigo_permiso' => PermissionCode::ScanTickets->value,
],
[
'created_at' => now(),
'updated_at' => now(),
],
);
}
};

View File

@@ -120,7 +120,7 @@ class AuthorizationSeeder extends Seeder
RoleCode::AdminApp->value => [
'nombre' => 'Administrador de la aplicación',
'descripcion' => 'Accede a los menús administrativos de la aplicación.',
'permisos' => [PermissionCode::ScanTickets->value],
'permisos' => [],
],
RoleCode::Scanner->value => [
'nombre' => 'Scanner',

View File

@@ -74,7 +74,7 @@ class MenuSeeder extends Seeder
],
[
'code' => 'adminapp.staff',
'label' => 'Staff',
'label' => 'Usuarios',
'parent_menu_code' => 'main.adminapp',
'route' => '/admin/staff',
],

31
docs/email-identity.md Normal file
View File

@@ -0,0 +1,31 @@
# Identidad por email y rol
Cada cuenta activa se identifica por `LOWER(email)` + `rol_codigo`, globalmente,
sin incluir el tenant. Un mismo correo puede tener una cuenta `user`, otra
`adminapp`, otra `scanner` y otra `admin`. Dos cuentas activas del mismo rol
no pueden compartir correo, incluso si pertenecen a distintos tenants.
La base lo garantiza con el índice único `(active_email, rol_codigo)`.
`active_email` es una columna generada: vale `LOWER(email)` cuando `deleted_at`
es NULL y NULL para cuentas eliminadas. El soft delete libera el correo para
ese rol; registrarlo nuevamente crea una cuenta independiente.
Registro, perfil, administradores y staff validan el correo normalizado contra
el rol de destino. Cambiar de rol o restaurar una cuenta también queda sujeto
al índice único de la base.
Login y recuperación seleccionan la identidad de la aplicación:
- Tienda y Google: `user`.
- AdminApp: `adminapp`.
- Scanner: `scanner`. Sólo las identidades con ese rol pueden autenticarse y
consumir los endpoints del scanner.
- Verificación administrativa de plataforma: `admin`.
Los endpoints de validación de código y cambio de contraseña toman el rol de
la ruta, nunca del cuerpo enviado por el cliente. Los intentos y cambios de
contraseña pertenecen a una cuenta concreta, aunque otra comparta su email.
Aplicar `php artisan migrate` antes de habilitar correos compartidos por rol.
Para revertir esta migración hay que resolver primero los correos compartidos
entre cuentas activas: el índice global anterior no los admite.

View File

@@ -11,7 +11,7 @@ declare(strict_types=1);
$root = dirname(__DIR__);
chdir($root);
$command = escapeshellarg(PHP_BINARY).' artisan route:list --path=api --json';
$command = escapeshellarg(PHP_BINARY).' artisan route:list --json';
$routeJson = shell_exec($command);
if (! is_string($routeJson) || trim($routeJson) === '') {
@@ -20,6 +20,11 @@ if (! is_string($routeJson) || trim($routeJson) === '') {
}
$routes = json_decode($routeJson, true, flags: JSON_THROW_ON_ERROR);
$routes = array_values(array_filter(
$routes,
fn (array $route): bool => str_starts_with($route['uri'], 'api/')
|| $route['uri'] === 'auth/google/redirect',
));
const TINY_PNG = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==';
@@ -177,6 +182,10 @@ function bodyFor(string $method, string $uri): ?array
function queryFor(string $uri): array
{
return match ($uri) {
'auth/google/redirect' => [
['key' => 'tenant', 'value' => '{{tenant_code}}'],
['key' => 'return_url', 'value' => '{{storefront_url}}'],
],
'api/tenants/bootstrap' => [['key' => 'dominio', 'value' => '{{tenant_domain}}'], ['key' => 'path', 'value' => '/']],
'api/v1/adminapp/bootstrap/{dominio}', 'api/v1/scanner/bootstrap/{dominio}' => [['key' => 'path', 'value' => '/']],
'api/tenants/{tenant:codigo}/catalog-items' => [['key' => 'q', 'value' => 'demo'], ['key' => 'page', 'value' => '1']],
@@ -415,6 +424,7 @@ foreach ($tree as $section => $folders) {
$variables = [
'base_url' => 'http://localhost:8000',
'storefront_url' => 'http://localhost:4200',
'token' => '', 'admin_token' => '', 'scanner_token' => '',
'user_email' => 'usuario@example.com', 'user_password' => 'Password!123',
'admin_email' => 'admin@example.com', 'admin_password' => 'Password!123',

View File

@@ -0,0 +1,6 @@
@include('mail.notifications.partials.password-action', [
'title' => 'Desbloqueá tu cuenta',
'description' => 'registramos varios intentos fallidos de inicio de sesión en tu cuenta. Por seguridad, bloqueamos el acceso temporalmente. Utilizá este código para cambiar tu contraseña y desbloquearla.',
'buttonLabel' => 'Ingresar código ahora',
'footer' => 'Si no fuiste vos, por favor desestimá y borrá este correo. Tu cuenta seguirá protegida.',
])

View File

@@ -0,0 +1,6 @@
@include('mail.notifications.partials.password-action', [
'title' => 'Tu cuenta de administrador está lista',
'description' => 'creamos tu cuenta de administrador en '.$brand->nombre.'. Creá tu contraseña con este código para ingresar al panel de administración.',
'buttonLabel' => 'Crear mi contraseña',
'footer' => 'Si no esperabas recibir una cuenta de administrador, podés ignorar este mensaje.',
])

View File

@@ -0,0 +1,24 @@
<h1 style="margin: 0 0 20px; color: {{ $brand->primary_color }};">
{{ $title }}
</h1>
<p>Hola {{ $attempt->user->nombre_apellido }}, {{ $description }}</p>
<p>Ingresá este código en {{ $brand->nombre }}:</p>
<div style="margin: 28px 0; padding: 20px; border: 2px solid {{ $brand->primary_color }}; border-radius: 8px; text-align: center;">
<span style="color: {{ $brand->primary_color }}; font-size: 36px; font-weight: 700; letter-spacing: 12px;">
{{ $attempt->codigo }}
</span>
</div>
@if($recoveryUrl)
<div style="text-align: center; margin-bottom: 28px;">
<a href="{{ $recoveryUrl }}"
style="display: inline-block; padding: 12px 24px; background-color: {{ $brand->primary_color }}; color: #ffffff; text-decoration: none; border-radius: 6px; font-weight: bold;">
{{ $buttonLabel }}
</a>
</div>
@endif
<p style="color: #64748b; font-size: 14px;">{{ $footer }}</p>

View File

@@ -1,45 +1,6 @@
<h1 style="margin: 0 0 20px; color: {{ $brand->primary_color }};">
Recuperá tu contraseña
</h1>
@if($attempt->reason === \App\Domains\Auth\Models\ResetPasswordAttempt::REASON_STAFF_CREATED)
<p>
Hola {{ $attempt->user->nombre_apellido }}, creamos tu cuenta de scanner en {{ $brand->nombre }}. Utilizá este código para crear tu contraseña y comenzar a usarla.
</p>
@elseif($attempt->reason === \App\Domains\Auth\Models\ResetPasswordAttempt::REASON_ACCOUNT_LOCKED)
<p>
Hola {{ $attempt->user->nombre_apellido }}, registramos varios intentos fallidos de inicio de sesión en tu cuenta. Por seguridad, hemos bloqueado el acceso temporalmente. Puedes utilizar este código para cambiar tu contraseña y desbloquearla inmediatamente.
</p>
@else
<p>
Hola {{ $attempt->user->nombre_apellido }}, recibimos una solicitud para restablecer
la contraseña de tu cuenta.
</p>
@endif
<p>Ingresá este código en {{ $brand->nombre }}:</p>
<div style="margin: 28px 0; padding: 20px; border: 2px solid {{ $brand->primary_color }}; border-radius: 8px; text-align: center;">
<span style="color: {{ $brand->primary_color }}; font-size: 36px; font-weight: 700; letter-spacing: 12px;">
{{ $attempt->codigo }}
</span>
</div>
@if($recoveryUrl)
<div style="text-align: center; margin-bottom: 28px;">
<a href="{{ $recoveryUrl }}"
style="display: inline-block; padding: 12px 24px; background-color: {{ $brand->primary_color }}; color: #ffffff; text-decoration: none; border-radius: 6px; font-weight: bold;">
{{ $attempt->reason === \App\Domains\Auth\Models\ResetPasswordAttempt::REASON_STAFF_CREATED ? 'Crear mi contraseña' : 'Ingresar código ahora' }}
</a>
</div>
@endif
<p style="color: #64748b; font-size: 14px;">
@if($attempt->reason === \App\Domains\Auth\Models\ResetPasswordAttempt::REASON_ACCOUNT_LOCKED)
Si no fuiste vos, por favor desestimá y borrá este correo. Tu cuenta seguirá protegida.
@elseif($attempt->reason === \App\Domains\Auth\Models\ResetPasswordAttempt::REASON_STAFF_CREATED)
Si no esperabas recibir una cuenta de scanner, podés ignorar este mensaje.
@else
Si no solicitaste recuperar tu contraseña, podés ignorar este mensaje.
@endif
</p>
@include('mail.notifications.partials.password-action', [
'title' => 'Recuperá tu contraseña',
'description' => 'recibimos una solicitud para restablecer la contraseña de tu cuenta.',
'buttonLabel' => 'Ingresar código ahora',
'footer' => 'Si no solicitaste recuperar tu contraseña, podés ignorar este mensaje.',
])

View File

@@ -0,0 +1,6 @@
@include('mail.notifications.partials.password-action', [
'title' => 'Tu cuenta de escáner está lista',
'description' => 'creamos tu cuenta de escáner en '.$brand->nombre.'. Creá tu contraseña con este código para ingresar y comenzar a escanear entradas.',
'buttonLabel' => 'Crear mi contraseña',
'footer' => 'Si no esperabas recibir una cuenta de escáner, podés ignorar este mensaje.',
])

View File

@@ -1,3 +1,8 @@
<h1 style="margin: 0 0 20px;">¡Bienvenido a {{ $brand->nombre }}!</h1>
<p>Hola {{ $user->nombre_apellido }}, tu cuenta fue creada correctamente.</p>
<p>Ya podés ingresar y comenzar a comprar.</p>
<div style="text-align: center; margin-bottom: 28px;">
<a href="{{ $tenantUrl }}"
style="display: inline-block; padding: 12px 24px; background-color: {{ $brand->primary_color }}; color: #ffffff; text-decoration: none; border-radius: 6px; font-weight: bold;">
Encendé tu experiencia
</a>
</div>

View File

@@ -16,5 +16,6 @@ require __DIR__.'/../app/Domains/Ticket/routes/api.php';
require __DIR__.'/../app/Domains/Event/routes/api.php';
require __DIR__.'/../app/Domains/Forms/routes/api.php';
require __DIR__.'/../app/Domains/Staff/routes/api.php';
require __DIR__.'/../app/Domains/Administrator/routes/api.php';
require __DIR__.'/../app/Domains/FiestaFutbolInfantil/routes/api.php';
require __DIR__.'/../app/Domains/Desfile/routes/api.php';

View File

@@ -3,9 +3,11 @@
use App\Domains\Auth\Services\AdminCredentialVerifier;
use App\Domains\Catalog\Services\ExpireStockReservationsService;
use App\Domains\Purchase\Services\TenantTransactionResetService;
use App\Domains\Ticket\Services\LoadTestTicketDatasetService;
use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Schedule;
use Illuminate\Support\Facades\Storage;
Artisan::command('inspire', function () {
$this->comment(Inspiring::quote());
@@ -24,6 +26,79 @@ Schedule::command('reservations:expire')
->everyMinute()
->withoutOverlapping();
Artisan::command(
'load-test:tickets:prepare
{tenant : Código del tenant que recibirá los datos de carga}
{--tickets=1000 : Cantidad de tickets válidos}
{--scanners=10 : Cantidad de identidades scanner}
{--owners=100 : Cantidad de propietarios de tickets}
{--catalog-item= : Producto estándar con tickets habilitados}
{--variant= : Variante opcional que define la vigencia}
{--run= : Identificador opcional de la ejecución}
{--output= : Ruta relativa dentro del disco local}',
function (LoadTestTicketDatasetService $datasetService): int {
if (! app()->environment(['local', 'testing', 'staging', 'homo', 'homologation'])) {
$this->error('Este comando sólo puede ejecutarse en local u homologación.');
return self::FAILURE;
}
$requestedOutput = filled($this->option('output'))
? ltrim((string) $this->option('output'), '/\\')
: null;
if ($requestedOutput !== null
&& ($requestedOutput === '' || str_contains(str_replace('\\', '/', $requestedOutput), '../'))) {
$this->error('La ruta de salida debe permanecer dentro del disco local.');
return self::FAILURE;
}
try {
$dataset = $datasetService->prepare(
(string) $this->argument('tenant'),
(int) $this->option('tickets'),
(int) $this->option('scanners'),
(int) $this->option('owners'),
filled($this->option('catalog-item')) ? (int) $this->option('catalog-item') : null,
filled($this->option('variant')) ? (int) $this->option('variant') : null,
filled($this->option('run')) ? (string) $this->option('run') : null,
);
} catch (Throwable $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
$relativePath = $requestedOutput !== null
? $requestedOutput
: "load-tests/{$dataset['run_id']}.postman.json";
$payload = json_encode($dataset['rows'], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
if (! is_string($payload) || ! Storage::disk('local')->put($relativePath, $payload.PHP_EOL)) {
$this->error('No se pudo escribir el dataset.');
return self::FAILURE;
}
$this->info('Dataset de carga generado.');
$this->table(['Dato', 'Valor'], [
['run_id', $dataset['run_id']],
['tenant', $dataset['tenant_code']],
['catalog_item_id', $dataset['catalog_item_id']],
['variant_id', $dataset['variant_id'] ?? 'sin variante (vigencia irrestricta)'],
['tickets', $dataset['tickets']],
['scanners', $dataset['scanners']],
['owners', $dataset['owners']],
['archivo', Storage::disk('local')->path($relativePath)],
]);
$this->warn('El archivo contiene tokens secretos. No lo subas al repositorio.');
$this->comment("Limpieza: php artisan tenants:reset-transactions {$dataset['tenant_code']}");
return self::SUCCESS;
},
)->purpose('Prepare disposable scanner tickets and a Postman performance dataset');
Artisan::command(
'tenants:reset-transactions
{tenant : Código del tenant que se limpiará}

View File

@@ -0,0 +1,159 @@
<?php
namespace Tests\Feature\Administrator;
use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
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 App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Models\WebsiteType;
use Database\Seeders\AuthorizationSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Event;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;
class AdministratorControllerTest extends TestCase
{
use RefreshDatabase;
private Tenant $tenant;
private User $admin;
protected function setUp(): void
{
parent::setUp();
Event::fake([PasswordResetRequested::class]);
$this->seed(AuthorizationSeeder::class);
WebsiteType::query()->create(['codigo' => 'onticket', 'nombre' => 'OnTicket']);
$headerLogo = $this->createAttachment('header.png');
$footerLogo = $this->createAttachment('footer.png');
$this->tenant = Tenant::query()->create([
'codigo' => 'acme',
'nombre' => 'Acme',
'dominio' => 'acme.test',
'website_type_code' => 'onticket',
'primary_color' => '#111111',
'secondary_color' => '#222222',
'danger_color' => '#cc0000',
'success_color' => '#008800',
'header_bg_color' => '#ffffff',
'footer_bg_color' => '#ffffff',
'header_logo_id' => $headerLogo->id,
'footer_logo_id' => $footerLogo->id,
]);
$this->admin = User::factory()->create([
'rol_codigo' => RoleCode::AdminApp->value,
'tenant_codigo' => $this->tenant->codigo,
]);
}
private const URL = '/api/v1/adminapp/tenant/administrators';
private function payload(): array
{
return ['nombre_apellido' => 'Ada Lovelace', 'dni' => '12345678', 'email' => 'ada@example.test'];
}
public function test_email_can_be_shared_with_customers_and_scanners(): void
{
Sanctum::actingAs($this->admin);
foreach (['user', 'scanner'] as $role) {
User::factory()->create(['email' => 'ada@example.test', 'rol_codigo' => $role]);
}
$response = $this->postJson(self::URL, $this->payload())->assertCreated();
$this->putJson(self::URL.'/'.$response->json('data.id'), $this->payload())->assertOk();
$this->postJson(self::URL, $this->payload())->assertUnprocessable()->assertJsonValidationErrors('email');
}
public function test_crud_and_password_setup_and_token_revocation(): void
{
Sanctum::actingAs($this->admin);
$response = $this->postJson(self::URL, [...$this->payload(), 'email' => ' ADA@example.test ', 'rol_codigo' => 'admin', 'tenant_codigo' => 'other'])
->assertCreated()->assertJsonPath('data.email', 'ada@example.test')
->assertJsonPath('data.rol_codigo', 'adminapp')->assertJsonMissingPath('data.password');
$id = $response->json('data.id');
$this->assertDatabaseHas('users', ['id' => $id, 'tenant_codigo' => $this->tenant->codigo, 'rol_codigo' => 'adminapp']);
$this->assertDatabaseHas('reset_password_attempts', ['user_id' => $id, 'reason' => ResetPasswordAttempt::REASON_ADMINISTRATOR_CREATED, 'status' => ResetPasswordAttempt::STATUS_PENDING]);
Event::assertDispatched(PasswordResetRequested::class, fn ($event) => $event->channel === PasswordResetRequested::CHANNEL_ADMINAPP && $event->tenantCode === $this->tenant->codigo);
$this->getJson(self::URL.'?search=Ada')->assertOk()->assertJsonCount(1, 'data');
$this->putJson(self::URL."/{$id}", [...$this->payload(), 'nombre_apellido' => 'Ada Byron', 'rol_codigo' => 'scanner'])
->assertOk()->assertJsonPath('data.nombre_apellido', 'Ada Byron')->assertJsonPath('data.rol_codigo', 'adminapp');
$token = User::findOrFail($id)->createToken('adminapp')->accessToken;
$this->deleteJson(self::URL."/{$id}")->assertNoContent();
$this->assertSoftDeleted('users', ['id' => $id]);
$this->assertDatabaseMissing('personal_access_tokens', ['id' => $token->id]);
$this->getJson(self::URL.'?search=Ada')->assertOk()->assertJsonCount(0, 'data');
$this->postJson(self::URL, $this->payload())->assertCreated();
}
public function test_validation_and_case_insensitive_active_email_uniqueness(): void
{
Sanctum::actingAs($this->admin);
$this->postJson(self::URL, [])->assertUnprocessable()->assertJsonValidationErrors(['nombre_apellido', 'dni', 'email']);
$this->postJson(self::URL, [...$this->payload(), 'email' => 'invalid'])->assertUnprocessable()->assertJsonValidationErrors('email');
$this->postJson(self::URL, [...$this->payload(), 'email' => strtoupper($this->admin->email)])->assertUnprocessable()->assertJsonValidationErrors('email');
$target = User::factory()->create(['rol_codigo' => 'adminapp', 'tenant_codigo' => $this->tenant->codigo]);
$this->putJson(self::URL."/{$target->id}", [...$this->payload(), 'email' => strtoupper($this->admin->email)])->assertUnprocessable()->assertJsonValidationErrors('email');
}
public function test_other_tenants_and_roles_are_excluded(): void
{
Sanctum::actingAs($this->admin);
$otherTenant = $this->tenant->replicate();
$otherTenant->codigo = 'other';
$otherTenant->dominio = 'other.test';
$otherTenant->save();
$targets = [
User::factory()->create(['rol_codigo' => 'adminapp', 'tenant_codigo' => $otherTenant->codigo]),
User::factory()->create(['rol_codigo' => 'scanner', 'tenant_codigo' => $this->tenant->codigo]),
User::factory()->create(['rol_codigo' => 'admin', 'tenant_codigo' => $this->tenant->codigo]),
];
$this->getJson(self::URL)->assertOk()->assertJsonCount(1, 'data')->assertJsonPath('data.0.id', $this->admin->id);
foreach ($targets as $target) {
$this->putJson(self::URL."/{$target->id}", $this->payload())->assertNotFound();
$this->deleteJson(self::URL."/{$target->id}")->assertNotFound();
$this->assertNotSoftDeleted($target);
}
}
public function test_cannot_delete_self_even_with_another_administrator(): void
{
Sanctum::actingAs($this->admin);
$this->deleteJson(self::URL."/{$this->admin->id}")->assertUnprocessable()->assertJsonValidationErrors('administrator');
User::factory()->create(['rol_codigo' => 'adminapp', 'tenant_codigo' => $this->tenant->codigo]);
$this->deleteJson(self::URL."/{$this->admin->id}")->assertUnprocessable();
$this->assertNotSoftDeleted($this->admin);
}
public function test_in_flight_request_from_deleted_actor_cannot_remove_last_administrator(): void
{
$remaining = User::factory()->create(['rol_codigo' => 'adminapp', 'tenant_codigo' => $this->tenant->codigo]);
$this->admin->delete();
Sanctum::actingAs($this->admin);
$this->deleteJson(self::URL."/{$remaining->id}")->assertUnprocessable()->assertJsonValidationErrors('administrator');
$this->assertNotSoftDeleted($remaining);
}
public function test_authentication_and_role_are_required_for_all_operations(): void
{
$this->getJson(self::URL)->assertUnauthorized();
foreach (['user', 'scanner', 'admin'] as $role) {
Sanctum::actingAs(User::factory()->create(['rol_codigo' => $role, 'tenant_codigo' => $this->tenant->codigo]));
$this->getJson(self::URL)->assertForbidden();
$this->postJson(self::URL, $this->payload())->assertForbidden();
$this->putJson(self::URL."/{$this->admin->id}", $this->payload())->assertForbidden();
$this->deleteJson(self::URL."/{$this->admin->id}")->assertForbidden();
}
}
private function createAttachment(string $filename): Attachment
{
return Attachment::query()->create(['path' => "test/{$filename}", 'filename' => $filename, 'type' => AttachmentType::Image, 'mime_type' => 'image/png']);
}
}

View File

@@ -0,0 +1,133 @@
<?php
namespace Tests\Feature\Auth;
use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
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 App\Domains\Tenant\Models\Tenant;
use Database\Seeders\AuthorizationSeeder;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Routing\Middleware\ThrottleRequests;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Hash;
use Tests\TestCase;
class EmailUniquenessPerRoleTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
$this->withoutMiddleware(ThrottleRequests::class);
$this->seed(AuthorizationSeeder::class);
Event::fake([PasswordResetRequested::class]);
}
public function test_database_allows_different_roles_and_reuse_after_soft_delete(): void
{
foreach (RoleCode::cases() as $role) {
User::factory()->create(['email' => 'Shared@example.com', 'rol_codigo' => $role->value]);
}
$user = User::where('rol_codigo', 'user')->sole();
$user->delete();
$replacement = User::factory()->create(['email' => 'shared@example.com']);
$this->assertNotSame($user->id, $replacement->id);
$this->assertSame(4, User::where('active_email', 'shared@example.com')->count());
}
public function test_database_rejects_same_role_case_insensitively_across_tenants(): void
{
foreach (['one', 'two'] as $code) {
$this->createTenant($code);
}
User::factory()->create(['email' => 'Shared@example.com', 'tenant_codigo' => 'one']);
$this->expectException(UniqueConstraintViolationException::class);
User::factory()->create(['email' => 'shared@example.com', 'tenant_codigo' => 'two']);
}
public function test_role_change_cannot_create_a_duplicate_active_identity(): void
{
User::factory()->create(['email' => 'shared@example.com']);
$admin = User::factory()->create(['email' => 'shared@example.com', 'rol_codigo' => 'adminapp']);
$this->expectException(UniqueConstraintViolationException::class);
$admin->update(['rol_codigo' => 'user']);
}
public function test_registration_accepts_another_role_but_rejects_same_role(): void
{
User::factory()->create(['email' => 'SHARED@example.com', 'rol_codigo' => 'adminapp']);
$payload = ['nombre_apellido' => 'Shared', 'email' => ' Shared@Example.com ',
'password' => 'Secret!123', 'password_confirmation' => 'Secret!123'];
$this->postJson('/api/register', $payload)->assertCreated()->assertJsonPath('data.email', 'shared@example.com');
$this->postJson('/api/register', $payload)->assertUnprocessable()->assertJsonValidationErrors('email');
}
public function test_login_and_password_reset_select_the_role_from_each_application(): void
{
$tenant = $this->createTenant('acme');
$users = [];
// Create staff first so an email-only lookup would select the wrong account.
foreach (['adminapp', 'scanner', 'user'] as $role) {
$users[$role] = User::factory()->create([
'email' => 'Shared@example.com', 'rol_codigo' => $role,
'tenant_codigo' => $tenant->codigo, 'password' => 'Old!'.$role,
]);
}
foreach (['user' => '/api', 'adminapp' => '/api/v1/adminapp', 'scanner' => '/api/v1/scanner'] as $role => $base) {
$this->postJson($base.'/login', [
'email' => 'SHARED@example.com', 'password' => 'Old!'.$role, 'tenant_codigo' => 'acme',
])->assertOk()->assertJsonPath('user.id', $users[$role]->id);
$this->postJson($base.'/password/reset-attempts', [
'email' => 'shared@example.com', 'tenant_codigo' => 'acme',
])->assertAccepted();
}
// Identical codes across roles must still only change the intended account.
ResetPasswordAttempt::query()->update(['codigo' => '1234']);
foreach (['user' => '/api', 'adminapp' => '/api/v1/adminapp', 'scanner' => '/api/v1/scanner'] as $role => $base) {
$this->postJson($base.'/password/reset-attempts/validate', [
'email' => 'shared@example.com', 'codigo' => '1234',
])->assertOk();
$this->postJson($base.'/password/reset', [
'email' => 'shared@example.com', 'codigo' => '1234',
'password' => 'New!'.$role, 'password_confirmation' => 'New!'.$role,
])->assertOk();
$this->assertTrue(Hash::check('New!'.$role, $users[$role]->fresh()->password));
}
}
private function createTenant(string $code): Tenant
{
$headerLogo = $this->createAttachment("{$code}-header");
$footerLogo = $this->createAttachment("{$code}-footer");
return Tenant::query()->create([
'codigo' => $code,
'nombre' => ucfirst($code),
'dominio' => "{$code}.local",
'primary_color' => '#000000',
'secondary_color' => '#000000',
'danger_color' => '#000000',
'success_color' => '#000000',
'header_bg_color' => '#000000',
'footer_bg_color' => '#000000',
'header_logo_id' => $headerLogo->id,
'footer_logo_id' => $footerLogo->id,
]);
}
private function createAttachment(string $name): Attachment
{
return Attachment::query()->create([
'path' => "test/{$name}.png",
'filename' => "{$name}.png",
'type' => AttachmentType::Image,
'mime_type' => 'image/png',
]);
}
}

View File

@@ -135,4 +135,36 @@ class RegisterControllerTest extends TestCase
'password',
]);
}
public function test_it_can_reuse_the_email_of_a_soft_deleted_user(): void
{
$deletedUser = User::factory()->create([
'email' => 'reused@example.com',
]);
$deletedUser->delete();
$response = $this->postJson('/api/register', [
'nombre_apellido' => 'New Account',
'email' => 'reused@example.com',
'password' => 'Secret!123',
'password_confirmation' => 'Secret!123',
])->assertCreated();
$newUserId = $response->json('data.id');
$this->assertNotSame($deletedUser->id, $newUserId);
$this->assertSame(
2,
User::withTrashed()->where('email', 'reused@example.com')->count(),
);
$this->assertDatabaseHas('users', [
'id' => $deletedUser->id,
'active_email' => null,
]);
$this->assertDatabaseHas('users', [
'id' => $newUserId,
'active_email' => 'reused@example.com',
'deleted_at' => null,
]);
}
}

View File

@@ -2,6 +2,7 @@
namespace Tests\Feature\Auth;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Auth\Models\LoginAttempt;
use App\Domains\Auth\Models\ResetPasswordAttempt;
use App\Domains\Auth\Models\User;
@@ -14,6 +15,7 @@ use App\Domains\Tenant\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Tests\TestCase;
class ScannerLoginControllerTest extends TestCase
@@ -23,19 +25,15 @@ class ScannerLoginControllerTest extends TestCase
public function test_it_logs_in_a_tenant_bound_user_with_scan_permission(): void
{
$role = Role::query()->create([
'codigo' => RoleCode::AdminApp->value,
'nombre' => 'Operador',
'codigo' => RoleCode::Scanner->value,
'nombre' => 'Scanner',
]);
$permission = Permission::query()->create([
'codigo' => PermissionCode::ScanTickets->value,
'nombre' => 'Escanear tickets',
]);
$role->permissions()->attach($permission->codigo);
$tenant = Tenant::query()->create([
'codigo' => 'acme',
'nombre' => 'Acme',
'dominio' => 'acme.test',
]);
$tenant = $this->createTenant();
$user = User::factory()->create([
'email' => 'scanner@example.com',
'password' => Hash::make('secret123'),
@@ -51,23 +49,85 @@ class ScannerLoginControllerTest extends TestCase
$response
->assertOk()
->assertJsonPath('user.id', $user->id)
->assertJsonPath('user.rol_codigo', RoleCode::AdminApp->value)
->assertJsonPath('user.rol_codigo', RoleCode::Scanner->value)
->assertJsonPath('token_type', 'Bearer');
$this->assertSame(['scanner'], $user->tokens()->sole()->abilities);
}
public function test_it_rejects_adminapp_credentials_even_when_the_role_has_scan_permission(): void
{
$role = Role::query()->create([
'codigo' => RoleCode::AdminApp->value,
'nombre' => 'Administrador',
]);
$permission = Permission::query()->create([
'codigo' => PermissionCode::ScanTickets->value,
'nombre' => 'Escanear tickets',
]);
$role->permissions()->attach($permission->codigo);
$tenant = $this->createTenant();
$adminApp = User::factory()->create([
'email' => 'shared@example.com',
'password' => Hash::make('admin-password'),
'rol_codigo' => $role->codigo,
'tenant_codigo' => $tenant->codigo,
]);
$this->postJson('/api/v1/scanner/login', [
'email' => $adminApp->email,
'password' => 'admin-password',
'rol_codigo' => RoleCode::AdminApp->value,
])->assertUnprocessable()->assertJsonValidationErrors(['email']);
$this->assertDatabaseCount('personal_access_tokens', 0);
}
public function test_shared_email_authenticates_the_scanner_identity_only(): void
{
$scannerRole = Role::query()->create([
'codigo' => RoleCode::Scanner->value,
'nombre' => 'Scanner',
]);
$adminAppRole = Role::query()->create([
'codigo' => RoleCode::AdminApp->value,
'nombre' => 'Administrador',
]);
$permission = Permission::query()->create([
'codigo' => PermissionCode::ScanTickets->value,
'nombre' => 'Escanear tickets',
]);
$scannerRole->permissions()->attach($permission->codigo);
$tenant = $this->createTenant();
User::factory()->create([
'email' => 'shared@example.com',
'password' => Hash::make('admin-password'),
'rol_codigo' => $adminAppRole->codigo,
'tenant_codigo' => $tenant->codigo,
]);
$scanner = User::factory()->create([
'email' => 'shared@example.com',
'password' => Hash::make('scanner-password'),
'rol_codigo' => $scannerRole->codigo,
'tenant_codigo' => $tenant->codigo,
]);
$this->postJson('/api/v1/scanner/login', [
'email' => 'shared@example.com',
'password' => 'scanner-password',
])
->assertOk()
->assertJsonPath('user.id', $scanner->id)
->assertJsonPath('user.rol_codigo', RoleCode::Scanner->value);
}
public function test_it_rejects_a_user_without_scan_permission(): void
{
$role = Role::query()->create([
'codigo' => RoleCode::Scanner->value,
'nombre' => 'Scanner sin permiso',
]);
$tenant = Tenant::query()->create([
'codigo' => 'acme',
'nombre' => 'Acme',
'dominio' => 'acme.test',
]);
$tenant = $this->createTenant();
$user = User::factory()->create([
'email' => 'customer@example.com',
'password' => Hash::make('secret123'),
@@ -92,11 +152,7 @@ class ScannerLoginControllerTest extends TestCase
'nombre' => 'Escanear tickets',
]);
$role->permissions()->attach($permission->codigo);
$tenant = Tenant::query()->create([
'codigo' => 'acme',
'nombre' => 'Acme',
'dominio' => 'acme.test',
]);
$tenant = $this->createTenant();
$user = User::factory()->create([
'email' => 'scanner@example.com',
'password' => Hash::make('correct-password'),
@@ -134,11 +190,7 @@ class ScannerLoginControllerTest extends TestCase
'nombre' => 'Escanear tickets',
]);
$role->permissions()->attach($permission->codigo);
$tenant = Tenant::query()->create([
'codigo' => 'acme',
'nombre' => 'Acme',
'dominio' => 'acme.test',
]);
$tenant = $this->createTenant();
$user = User::factory()->create([
'email' => 'scanner@example.com',
'password' => Hash::make('correct-password'),
@@ -163,4 +215,30 @@ class ScannerLoginControllerTest extends TestCase
&& $event->channel === PasswordResetRequested::CHANNEL_SCANNER,
);
}
private function createTenant(): Tenant
{
$logo = Attachment::query()->create([
'key' => (string) Str::uuid(),
'path' => 'tests/scanner-login-logo.png',
'filename' => 'scanner-login-logo.png',
'type' => 'image',
'mime_type' => 'image/png',
'extension' => 'png',
'size' => 1,
]);
return Tenant::query()->create([
'codigo' => 'acme',
'nombre' => 'Acme',
'dominio' => 'acme.test',
'primary_color' => '#000000',
'secondary_color' => '#000000',
'danger_color' => '#000000',
'header_bg_color' => '#000000',
'footer_bg_color' => '#000000',
'header_logo_id' => $logo->id,
'footer_logo_id' => $logo->id,
]);
}
}

View File

@@ -2,6 +2,7 @@
namespace Tests\Feature\Auth;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Auth\Models\User;
use App\Domains\Authorization\Enums\PermissionCode;
use App\Domains\Authorization\Enums\RoleCode;
@@ -10,6 +11,7 @@ use App\Domains\Authorization\Models\Role;
use App\Domains\Menu\Models\Menu;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Str;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;
@@ -28,11 +30,7 @@ class ScannerMeControllerTest extends TestCase
'nombre' => 'Escanear tickets',
]);
$scannerRole->permissions()->attach($permission->codigo);
$tenant = Tenant::query()->create([
'codigo' => 'acme',
'nombre' => 'Acme',
'dominio' => 'acme.test',
]);
$tenant = $this->createTenant();
$home = Menu::query()->create([
'code' => 'scanner.inicio',
'label' => 'Inicio',
@@ -65,4 +63,51 @@ class ScannerMeControllerTest extends TestCase
->assertJsonCount(2, 'data.tenant.menues')
->assertJsonMissing(['code' => $foreign->code]);
}
public function test_it_rejects_an_adminapp_user_even_with_scan_permission(): void
{
$adminAppRole = Role::query()->create([
'codigo' => RoleCode::AdminApp->value,
'nombre' => 'Administrador',
]);
$permission = Permission::query()->create([
'codigo' => PermissionCode::ScanTickets->value,
'nombre' => 'Escanear tickets',
]);
$adminAppRole->permissions()->attach($permission->codigo);
$tenant = $this->createTenant();
$adminApp = User::factory()->create([
'rol_codigo' => $adminAppRole->codigo,
'tenant_codigo' => $tenant->codigo,
]);
Sanctum::actingAs($adminApp);
$this->getJson('/api/v1/scanner/me')->assertForbidden();
}
private function createTenant(): Tenant
{
$logo = Attachment::query()->create([
'key' => (string) Str::uuid(),
'path' => 'tests/scanner-me-logo.png',
'filename' => 'scanner-me-logo.png',
'type' => 'image',
'mime_type' => 'image/png',
'extension' => 'png',
'size' => 1,
]);
return Tenant::query()->create([
'codigo' => 'acme',
'nombre' => 'Acme',
'dominio' => 'acme.test',
'primary_color' => '#000000',
'secondary_color' => '#000000',
'danger_color' => '#000000',
'header_bg_color' => '#000000',
'footer_bg_color' => '#000000',
'header_logo_id' => $logo->id,
'footer_logo_id' => $logo->id,
]);
}
}

View File

@@ -4,6 +4,7 @@ namespace Tests\Feature\Notification;
use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Auth\Models\ResetPasswordAttempt;
use App\Domains\Auth\Models\User;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Integration\Models\Integration;
@@ -133,15 +134,64 @@ class NotificationMailServiceTest extends TestCase
);
Mail::assertSent(Mailable::class, function (Mailable $mail): bool {
$mail->assertHasSubject('Tu cuenta de escáner está lista - Scanner Mail');
$rendered = $mail->render();
return str_contains($rendered, 'https://scanner.mail.local/recuperar-contrasena/codigo')
&& str_contains($rendered, 'Tu cuenta de escáner está lista')
&& str_contains($rendered, 'comenzar a escanear entradas')
&& ! str_contains($rendered, 'Recuperá tu contraseña')
&& str_contains($rendered, 'email=ada%40example.com')
&& str_contains($rendered, 'code=0123')
&& str_contains($rendered, 'Crear mi');
});
}
public function test_administrator_creation_has_custom_copy_and_the_existing_code_and_link(): void
{
$websiteType = WebsiteType::query()->create([
'codigo' => 'admin-mail', 'nombre' => 'Admin Mail',
'dominio' => 'admin.mail.local', 'scanner_domain' => 'scanner.mail.local',
]);
$this->tenant->update(['website_type_code' => $websiteType->codigo]);
$attempt = $this->user->resetPasswordAttempts()->create([
'codigo' => '0456', 'reason' => ResetPasswordAttempt::REASON_ADMINISTRATOR_CREATED,
]);
app(NotificationMailService::class)->sendPasswordResetCode($attempt->id, $this->tenant->codigo, PasswordResetRequested::CHANNEL_ADMINAPP);
Mail::assertSent(Mailable::class, function (Mailable $mail): bool {
$mail->assertHasSubject('Tu cuenta de administrador está lista - Admin Mail');
$html = $mail->render();
return str_contains($html, 'Tu cuenta de administrador está lista')
&& str_contains($html, 'ingresar al panel de administración')
&& str_contains($html, '0456')
&& str_contains($html, 'Crear mi contraseña')
&& str_contains($html, 'https://admin.mail.local/recuperar-contrasena/codigo?email=ada%40example.com')
&& ! str_contains($html, 'scanner.mail.local')
&& ! str_contains($html, 'administrator_created')
&& ! str_contains($html, 'Recuperá tu contraseña');
});
}
public function test_locked_account_has_its_own_copy_and_the_shared_code_action(): void
{
$attempt = $this->user->resetPasswordAttempts()->create([
'codigo' => '0789', 'reason' => ResetPasswordAttempt::REASON_ACCOUNT_LOCKED,
]);
app(NotificationMailService::class)->sendPasswordResetCode($attempt->id, $this->tenant->codigo);
Mail::assertSent(Mailable::class, function (Mailable $mail): bool {
$mail->assertHasSubject('Desbloqueá tu cuenta - Mail Tenant');
$html = $mail->render();
return str_contains($html, 'Desbloqueá tu cuenta')
&& str_contains($html, 'bloqueamos el acceso temporalmente')
&& str_contains($html, '0789')
&& str_contains($html, 'Ingresar código ahora')
&& str_contains($html, 'https://mail.local/recuperar-contrasena/codigo')
&& ! str_contains($html, 'account_locked');
});
}
public function test_it_sends_one_purchase_confirmation_with_generated_tickets_attached(): void
{
$this->useWebsiteTypeBranding();

View File

@@ -27,7 +27,7 @@ class AuthorizationSeederTest extends TestCase
],
Role::query()->orderBy('codigo')->pluck('codigo')->all()
);
$this->assertCount(22, Permission::query()->get());
$this->assertCount(23, Permission::query()->get());
}
public function test_it_assigns_the_expected_permissions_to_each_role(): void
@@ -39,7 +39,7 @@ class AuthorizationSeederTest extends TestCase
$scanner = Role::query()->where('codigo', RoleCode::Scanner->value)->firstOrFail();
$user = Role::query()->where('codigo', RoleCode::User->value)->firstOrFail();
$this->assertCount(22, $admin->permissions);
$this->assertCount(23, $admin->permissions);
$this->assertCount(0, $appAdmin->permissions);
$this->assertSame(
[PermissionCode::ScanTickets->value],
@@ -54,7 +54,7 @@ class AuthorizationSeederTest extends TestCase
$this->seed(AuthorizationSeeder::class);
$this->assertCount(4, Role::query()->get());
$this->assertCount(22, Permission::query()->get());
$this->assertDatabaseCount('roles_permisos', 23);
$this->assertCount(23, Permission::query()->get());
$this->assertDatabaseCount('roles_permisos', 24);
}
}

View File

@@ -2,6 +2,8 @@
namespace Tests\Feature\Staff;
use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Auth\Models\ResetPasswordAttempt;
use App\Domains\Auth\Models\User;
use App\Domains\Authorization\Enums\RoleCode;
@@ -9,9 +11,11 @@ use App\Domains\Catalog\Models\Category;
use App\Domains\Notification\Events\PasswordResetRequested;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Models\WebsiteType;
use App\Domains\Ticket\Models\Ticket;
use Database\Seeders\AuthorizationSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Str;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;
@@ -30,11 +34,21 @@ class StaffControllerTest extends TestCase
Event::fake([PasswordResetRequested::class]);
$this->seed(AuthorizationSeeder::class);
WebsiteType::query()->create(['codigo' => 'onticket', 'nombre' => 'OnTicket']);
$headerLogo = $this->createAttachment('header.png');
$footerLogo = $this->createAttachment('footer.png');
$this->tenant = Tenant::query()->create([
'codigo' => 'acme',
'nombre' => 'Acme',
'dominio' => 'acme.test',
'website_type_code' => 'onticket',
'primary_color' => '#111111',
'secondary_color' => '#222222',
'danger_color' => '#cc0000',
'success_color' => '#008800',
'header_bg_color' => '#ffffff',
'footer_bg_color' => '#ffffff',
'header_logo_id' => $headerLogo->id,
'footer_logo_id' => $footerLogo->id,
]);
$this->admin = User::factory()->create([
'rol_codigo' => RoleCode::AdminApp->value,
@@ -42,6 +56,17 @@ class StaffControllerTest extends TestCase
]);
}
public function test_staff_email_can_be_shared_with_adminapp_and_customers(): void
{
Sanctum::actingAs($this->admin);
User::factory()->create(['email' => $this->admin->email]);
$payload = ['nombre_apellido' => 'Shared', 'dni' => '12345678',
'email' => strtoupper($this->admin->email), 'category_ids' => [$this->createCategory('Tickets')->id]];
$response = $this->postJson('/api/v1/adminapp/tenant/staff', $payload)->assertSuccessful();
$this->putJson('/api/v1/adminapp/tenant/staff/'.$response->json('data.id'), $payload)->assertOk();
$this->postJson('/api/v1/adminapp/tenant/staff', $payload)->assertUnprocessable()->assertJsonValidationErrors('email');
}
public function test_adminapp_can_create_update_list_and_delete_staff_with_categories(): void
{
Sanctum::actingAs($this->admin);
@@ -92,8 +117,56 @@ class StaffControllerTest extends TestCase
'categoria_id' => $firstCategory->id,
]);
$ticket = Ticket::query()->create([
'tenant_code' => $this->tenant->codigo,
'ticket' => (string) Str::uuid(),
'user_id' => $this->admin->id,
'used_at' => now(),
'scanner_user_id' => $staffId,
]);
$accessTokenId = User::query()
->findOrFail($staffId)
->createToken('scanner', ['scanner'])
->accessToken
->getKey();
$this->deleteJson("/api/v1/adminapp/tenant/staff/{$staffId}")->assertNoContent();
$this->assertDatabaseMissing('users', ['id' => $staffId]);
$this->assertSoftDeleted('users', ['id' => $staffId]);
$this->assertDatabaseHas('users', [
'id' => $staffId,
'email' => 'ada@example.test',
'active_email' => null,
]);
$this->assertDatabaseMissing('personal_access_tokens', ['id' => $accessTokenId]);
$this->assertDatabaseHas('category_scanners', [
'user_id' => $staffId,
'categoria_id' => $secondCategory->id,
]);
$this->assertSame($staffId, $ticket->fresh()->scanner_user_id);
$this->assertSame('Ada Byron', $ticket->fresh()->scannerUser?->nombre_apellido);
$this->getJson('/api/v1/adminapp/tenant/staff')
->assertOk()
->assertJsonCount(0, 'data');
$replacementResponse = $this->postJson('/api/v1/adminapp/tenant/staff', [
'nombre_apellido' => 'Nueva Ada',
'dni' => '11223344',
'email' => 'ADA@example.test',
'category_ids' => [$firstCategory->id],
])->assertSuccessful()
->assertJsonPath('data.email', 'ada@example.test');
$replacementStaffId = $replacementResponse->json('data.id');
$this->assertNotSame($staffId, $replacementStaffId);
$this->assertSame('Ada Byron', $ticket->fresh()->scannerUser?->nombre_apellido);
$this->assertDatabaseHas('users', [
'id' => $replacementStaffId,
'email' => 'ada@example.test',
'active_email' => 'ada@example.test',
'deleted_at' => null,
]);
}
public function test_admin_cannot_assign_another_tenants_category(): void
@@ -104,6 +177,14 @@ class StaffControllerTest extends TestCase
'nombre' => 'Other',
'dominio' => 'other.test',
'website_type_code' => 'onticket',
'primary_color' => '#111111',
'secondary_color' => '#222222',
'danger_color' => '#cc0000',
'success_color' => '#008800',
'header_bg_color' => '#ffffff',
'footer_bg_color' => '#ffffff',
'header_logo_id' => $this->tenant->header_logo_id,
'footer_logo_id' => $this->tenant->footer_logo_id,
]);
$foreignCategory = Category::query()->create([
'tenant_code' => $otherTenant->codigo,
@@ -183,6 +264,16 @@ class StaffControllerTest extends TestCase
$this->getJson('/api/v1/adminapp/tenant/staff')->assertForbidden();
}
private function createAttachment(string $filename): Attachment
{
return Attachment::query()->create([
'path' => "test/{$filename}",
'filename' => $filename,
'type' => AttachmentType::Image,
'mime_type' => 'image/png',
]);
}
private function createCategory(string $name): Category
{
return Category::query()->create([

View File

@@ -0,0 +1,107 @@
<?php
namespace Tests\Feature\Ticket;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Category;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Models\WebsiteType;
use App\Domains\Ticket\Models\Ticket;
use Database\Seeders\AuthorizationSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Tests\TestCase;
class PrepareLoadTestTicketsCommandTest extends TestCase
{
use RefreshDatabase;
public function test_it_generates_a_postman_dataset_that_can_scan_the_tickets(): void
{
Storage::fake('local');
$this->seed(AuthorizationSeeder::class);
WebsiteType::query()->create(['codigo' => 'onticket', 'nombre' => 'OnTicket']);
$tenant = $this->createTenant('acme');
$category = Category::query()->create([
'tenant_code' => $tenant->codigo,
'nombre' => 'Entradas de carga',
]);
$catalogItem = CatalogItem::query()->create([
'tenant_code' => $tenant->codigo,
'category_id' => $category->id,
'slug' => 'entrada-load-test',
'nombre' => 'Entrada load test',
'descripcion' => 'Ticket descartable',
'precio' => 100,
'has_tickets' => true,
]);
$exitCode = Artisan::call('load-test:tickets:prepare', [
'tenant' => $tenant->codigo,
'--tickets' => 4,
'--scanners' => 2,
'--owners' => 2,
'--catalog-item' => $catalogItem->id,
'--run' => 'test-run',
'--output' => 'load-tests/test-run.postman.json',
]);
$this->assertSame(0, $exitCode, Artisan::output());
Storage::disk('local')->assertExists('load-tests/test-run.postman.json');
$rows = json_decode(
Storage::disk('local')->get('load-tests/test-run.postman.json'),
true,
flags: JSON_THROW_ON_ERROR,
);
$this->assertCount(4, $rows);
$this->assertCount(4, collect($rows)->pluck('ticket_uuid')->unique());
$this->assertCount(2, collect($rows)->pluck('scanner_token')->unique());
$this->assertSame([200], collect($rows)->pluck('expected_status')->unique()->values()->all());
$this->assertDatabaseCount('tickets', 4);
$this->assertCount(2, Ticket::query()->distinct()->pluck('user_id'));
$this->assertDatabaseCount('category_scanners', 2);
$first = $rows[0];
$this->withToken($first['scanner_token'])
->postJson("/api/v1/scanner/tickets/{$first['ticket_uuid']}/scan")
->assertOk()
->assertJsonPath('data.ticket', $first['ticket_uuid']);
$this->assertNotNull(
Ticket::query()->where('ticket', $first['ticket_uuid'])->firstOrFail()->used_at
);
}
private function createTenant(string $code): Tenant
{
$logo = Attachment::query()->create([
'key' => (string) Str::uuid(),
'path' => "tests/{$code}-logo.png",
'filename' => "{$code}-logo.png",
'type' => 'image',
'mime_type' => 'image/png',
'extension' => 'png',
'size' => 1,
]);
return Tenant::query()->create([
'codigo' => $code,
'nombre' => ucfirst($code),
'dominio' => "{$code}.test",
'primary_color' => '#ff7006',
'secondary_color' => '#777777',
'danger_color' => '#e04a4a',
'success_color' => '#81bc73',
'header_bg_color' => '#313131',
'footer_bg_color' => '#313131',
'header_logo_id' => $logo->id,
'footer_logo_id' => $logo->id,
'website_type_code' => 'onticket',
]);
}
}

View File

@@ -4,6 +4,7 @@ namespace Tests\Feature\Ticket;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Auth\Models\User;
use App\Domains\Authorization\Enums\PermissionCode;
use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Category;
@@ -52,7 +53,7 @@ class ScannerTicketControllerTest extends TestCase
$this->getJson('/api/v1/scanner/tickets')->assertUnauthorized();
Sanctum::actingAs(User::factory()->create([
'rol_codigo' => RoleCode::AdminApp->value,
'rol_codigo' => RoleCode::User->value,
'tenant_codigo' => $this->tenant->codigo,
]));
@@ -300,6 +301,22 @@ class ScannerTicketControllerTest extends TestCase
->assertNotFound();
}
public function test_adminapp_cannot_access_scanner_routes_even_with_scan_permission(): void
{
$admin = User::factory()->create([
'rol_codigo' => RoleCode::AdminApp->value,
'tenant_codigo' => $this->tenant->codigo,
]);
$admin->role()->firstOrFail()->permissions()->attach(PermissionCode::ScanTickets->value);
$ticket = $this->createTicket((string) Str::uuid());
Sanctum::actingAs($admin);
$this->getJson('/api/v1/scanner/tickets')->assertForbidden();
$this->getJson("/api/v1/scanner/tickets/{$ticket->ticket}")->assertForbidden();
$this->postJson("/api/v1/scanner/tickets/{$ticket->ticket}/scan")->assertForbidden();
$this->assertNull($ticket->fresh()->used_at);
}
/** @param array<string, mixed> $attributes */
private function createTicket(
string $uuid,