Compare commits

...

8 Commits

Author SHA1 Message Date
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
20 changed files with 1311 additions and 163 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

@@ -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

@@ -21,7 +21,13 @@ class RegisterUserRequest extends FormRequest
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', 'email')->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
{
@@ -19,11 +20,13 @@ class UpdateProfileRequest extends FormRequest
'email' => [
'required',
'email',
Rule::unique('users', 'email')->ignore($this->user()->id),
Rule::unique('users', 'email')
->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

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

View File

@@ -23,7 +23,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', 'email')->whereNull('deleted_at'),
],
'category_ids' => $categoryRules,
'category_ids.*' => ['integer', 'distinct', Rule::exists('categorias', 'id')],
];

View File

@@ -28,7 +28,9 @@ class UpdateStaffRequest extends FormRequest
'required',
'email',
'max:255',
Rule::unique('users', 'email')->ignore($staffId),
Rule::unique('users', 'email')
->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

@@ -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

@@ -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

@@ -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

@@ -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

@@ -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,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,
@@ -92,8 +106,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 +166,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 +253,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',
]);
}
}