Compare commits

..

41 Commits

Author SHA1 Message Date
152d44cd0c Merge branch 'fix/simplify_stock_reservations' of https://gitea.quo.ar/tbianchini/shopit-back into fix/simplify_stock_reservations 2026-08-26 16:23:20 -03:00
cd99a6489b Merge branch 'fix/simplify_stock_reservations' of https://gitea.quo.ar/tbianchini/shopit-back into fix/simplify_stock_reservations 2026-08-26 10:12:44 -03:00
ebcbbb1774 fix(cart): reconcile expired cart mutations 2026-08-26 10:10:35 -03:00
3dd378ed06 docs(stock): describe associated entity expiration 2026-08-26 10:10:35 -03:00
4f705175bd test(stock): cover propagated reservation expiration 2026-08-26 10:10:35 -03:00
82570fe941 refactor(stock): propagate reservation expiration 2026-08-26 10:10:35 -03:00
d2a2b323e0 docs(stock): document terminal reservation recovery 2026-08-26 10:10:22 -03:00
ec67623b7b test(stock): cover terminal reservation lifecycle 2026-08-26 10:10:22 -03:00
f6f138e180 refactor(stock): make expired reservations terminal 2026-08-26 10:10:22 -03:00
d612b7a118 docs(stock): describe unified expiration ownership 2026-08-26 10:10:08 -03:00
49f42d4507 test(stock): cover authoritative reservation expiration 2026-08-26 10:10:00 -03:00
1881cc1d4b refactor(stock): make reservation expiration authoritative 2026-08-26 10:10:00 -03:00
00ec37d8a0 docs(stock): document centralized reservation flow 2026-08-26 10:09:34 -03:00
d9f374c718 test(stock): cover aggregate reservation lifecycle 2026-08-26 10:09:14 -03:00
bbfdf8f342 refactor(stock): centralize reservation aggregate 2026-08-26 10:08:28 -03:00
8a0f29bdae fix(cart): reconcile expired cart mutations 2026-08-26 09:45:39 -03:00
198ed400a9 docs(stock): describe associated entity expiration 2026-08-26 09:45:39 -03:00
23d83166e6 test(stock): cover propagated reservation expiration 2026-08-26 09:45:39 -03:00
cb090402d0 refactor(stock): propagate reservation expiration 2026-08-26 09:45:39 -03:00
c120b6f7c0 docs(stock): document terminal reservation recovery 2026-08-26 09:45:39 -03:00
1106fa28b4 test(stock): cover terminal reservation lifecycle 2026-08-26 09:45:39 -03:00
896fb81bcf refactor(stock): make expired reservations terminal 2026-08-26 09:45:39 -03:00
8545fbc645 docs(stock): describe unified expiration ownership 2026-08-26 09:45:39 -03:00
dd6dcb708a test(stock): cover authoritative reservation expiration 2026-08-26 09:45:38 -03:00
624b246ff5 refactor(stock): make reservation expiration authoritative 2026-08-26 09:45:38 -03:00
007b95b904 docs(stock): document centralized reservation flow 2026-08-26 09:45:38 -03:00
0b3c8c93be test(stock): cover aggregate reservation lifecycle 2026-08-26 09:45:38 -03:00
ede718e448 refactor(stock): centralize reservation aggregate 2026-08-26 09:45:38 -03:00
e63a03601a fix(cart): reconcile expired cart mutations 2026-08-25 16:33:39 -03:00
389373ad8c docs(stock): describe associated entity expiration 2026-08-25 16:10:15 -03:00
ace02a3133 test(stock): cover propagated reservation expiration 2026-08-25 16:10:14 -03:00
d69a6210f6 refactor(stock): propagate reservation expiration 2026-08-25 16:09:52 -03:00
3c0b43fea3 docs(stock): document terminal reservation recovery 2026-08-25 15:58:47 -03:00
9b0008626b test(stock): cover terminal reservation lifecycle 2026-08-25 15:58:47 -03:00
61861e331a refactor(stock): make expired reservations terminal 2026-08-25 15:58:41 -03:00
2cc9d7dd97 docs(stock): describe unified expiration ownership 2026-08-25 15:28:30 -03:00
f982bcead1 test(stock): cover authoritative reservation expiration 2026-08-25 15:28:23 -03:00
7a85e1731d refactor(stock): make reservation expiration authoritative 2026-08-25 15:28:17 -03:00
6db99e775a docs(stock): document centralized reservation flow 2026-08-25 15:05:34 -03:00
e5f7ba3615 test(stock): cover aggregate reservation lifecycle 2026-08-25 15:05:29 -03:00
24bfef431b refactor(stock): centralize reservation aggregate 2026-08-25 15:05:23 -03:00
117 changed files with 390 additions and 6940 deletions

View File

@@ -8,7 +8,6 @@ PURCHASE_CHECKOUT_EXPIRATION_MINUTES=30
PURCHASE_QR_EXPIRATION_MINUTES=15
PURCHASE_TELEPAGOS_EXPIRATION_MINUTES=30
PURCHASE_TRANSFER_EXPIRATION_MINUTES=1440
PURCHASE_TRANSFER_CANDIDATE_AMOUNT_TOLERANCE_PERCENTAGE=5
STOCK_RESERVATION_EXPIRATION_MINUTES=30
FRONTEND_URLS=http://localhost:4200

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 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`.",
"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`.",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
@@ -385,42 +385,6 @@
}
},
"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": []
}
]
},
@@ -608,6 +572,60 @@
}
},
"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": []
}
]
},
@@ -1151,6 +1169,99 @@
},
"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": {
@@ -2103,7 +2214,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 \"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 \"checkout_editing_policy\": \"full\",\n \"website_type_code\": \"shopit\"\n}",
"options": {
"raw": {
"language": "json"
@@ -2169,7 +2280,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}",
"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}",
"options": {
"raw": {
"language": "json"
@@ -2209,7 +2320,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}",
"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}",
"options": {
"raw": {
"language": "json"
@@ -2552,45 +2663,6 @@
},
"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": {
@@ -2666,44 +2738,6 @@
}
},
"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": []
}
]
},
@@ -3024,84 +3058,6 @@
},
"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": {
@@ -3231,84 +3187,6 @@
},
"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": {
@@ -3438,84 +3316,6 @@
},
"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": {
@@ -3645,84 +3445,6 @@
},
"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": {
@@ -4327,45 +4049,6 @@
},
"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": {
@@ -4405,46 +4088,6 @@
},
"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": {
@@ -4958,127 +4601,6 @@
}
]
},
{
"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": [
@@ -5732,11 +5254,6 @@
"value": "http://localhost:8000",
"type": "string"
},
{
"key": "storefront_url",
"value": "http://localhost:4200",
"type": "string"
},
{
"key": "token",
"value": "",

View File

@@ -1,49 +0,0 @@
<?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

@@ -1,38 +0,0 @@
<?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', 'email')->whereNull('deleted_at'),
],
];
}
}

View File

@@ -1,41 +0,0 @@
<?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', 'email')
->whereNull('deleted_at')
->ignore($administratorId),
],
];
}
}

View File

@@ -1,27 +0,0 @@
<?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

@@ -1,99 +0,0 @@
<?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

@@ -1,63 +0,0 @@
# 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

@@ -1,10 +0,0 @@
<?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

@@ -17,8 +17,6 @@ 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,17 +13,16 @@ 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', 'active_email', 'active_google_id'])]
#[Hidden(['password', 'remember_token'])]
class User extends Authenticatable
{
/** @use HasFactory<UserFactory> */
use HasApiTokens, HasFactory, Notifiable, SoftDeletes;
use HasApiTokens, HasFactory, Notifiable;
protected $attributes = [
'rol_codigo' => RoleCode::User->value,

View File

@@ -21,13 +21,7 @@ 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')->whereNull('deleted_at'),
],
'email' => ['required', 'string', 'email', 'max:255', Rule::unique('users', 'email')],
'password' => ['required', 'string', 'confirmed', Password::min(8)->mixedCase()->symbols()],
'dni' => ['nullable', 'string', 'max:255'],
'telefono' => ['nullable', 'string', 'max:255'],

View File

@@ -4,7 +4,6 @@ namespace App\Domains\Auth\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\Password;
class UpdateProfileRequest extends FormRequest
{
@@ -20,13 +19,11 @@ class UpdateProfileRequest extends FormRequest
'email' => [
'required',
'email',
Rule::unique('users', 'email')
->whereNull('deleted_at')
->ignore($this->user()->id),
Rule::unique('users', 'email')->ignore($this->user()->id),
],
'dni' => ['nullable', 'string', 'regex:/^[0-9]{7,8}$/'],
'telefono' => ['nullable', 'string', 'regex:/^\+?[0-9\s\-]+$/'],
'password' => ['nullable', 'string', Password::min(8)->mixedCase()->symbols()],
'password' => ['nullable', 'string', \Illuminate\Validation\Rules\Password::min(8)->mixedCase()->symbols()],
];
}
}

View File

@@ -343,9 +343,9 @@ class StockReservationService
});
}
public function clearExpirationForReview(Purchase $purchase): void
public function refreshForPurchase(Purchase $purchase, ?Carbon $expiresAt): void
{
DB::transaction(function () use ($purchase): void {
DB::transaction(function () use ($purchase, $expiresAt): void {
/** @var Purchase $purchase */
$purchase = Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey());
if ($purchase->stock_reservation_id === null) {
@@ -363,7 +363,7 @@ class StockReservationService
throw new StockReservationExpiredException;
}
$reservation->update(['expires_at' => null]);
$reservation->update(['expires_at' => $expiresAt]);
});
}

View File

@@ -5,7 +5,6 @@ namespace App\Domains\Desfile\Services;
use DateTimeInterface;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use RuntimeException;
@@ -23,7 +22,7 @@ class InvitationPurchaseProvisioner
private const ALLOCATIONS = [
['sector' => 'A', 'row' => 1, 'first_seat' => 1, 'last_seat' => 16, 'type' => 'NORMAL'],
['sector' => 'A', 'row' => 3, 'first_seat' => 1, 'last_seat' => 14, 'type' => 'NORMAL'],
['sector' => 'C', 'row' => 1, 'first_seat' => 1, 'last_seat' => 17, 'type' => 'VIP + LUNCH'],
['sector' => 'C', 'row' => 1, 'first_seat' => 1, 'last_seat' => 16, 'type' => 'VIP + LUNCH'],
['sector' => 'C', 'row' => 3, 'first_seat' => 6, 'last_seat' => 7, 'type' => 'NORMAL'],
];
@@ -59,7 +58,7 @@ class InvitationPurchaseProvisioner
$allocation['type'],
);
$purchaseItemId = $this->createPurchaseItem(
$this->createPurchaseItem(
$purchaseId,
$catalogItem,
$variant,
@@ -71,7 +70,6 @@ class InvitationPurchaseProvisioner
);
$this->createTicketAndCommitStock(
$purchaseId,
$purchaseItemId,
$userId,
(int) $catalogItem->id,
$variant,
@@ -104,10 +102,7 @@ class InvitationPurchaseProvisioner
private function userId(DateTimeInterface $now): int
{
$user = DB::table('users')
->where('email', self::USER_EMAIL)
->whereNull('deleted_at')
->first();
$user = DB::table('users')->where('email', self::USER_EMAIL)->first();
if ($user !== null) {
if ($user->tenant_codigo !== self::TENANT_CODE) {
@@ -331,13 +326,12 @@ class InvitationPurchaseProvisioner
int $seat,
string $type,
DateTimeInterface $now,
): int {
$existingId = DB::table('compra_items')
): void {
if (DB::table('compra_items')
->where('compra_id', $purchaseId)
->where('source_variant_id', $variant->id)
->value('id');
if ($existingId !== null) {
return (int) $existingId;
->exists()) {
return;
}
$attributes = [
@@ -347,7 +341,7 @@ class InvitationPurchaseProvisioner
['name' => 'Asiento', 'value' => (string) $seat],
];
return DB::table('compra_items')->insertGetId([
DB::table('compra_items')->insert([
'compra_id' => $purchaseId,
'source_catalog_item_id' => $catalogItem->id,
'source_variant_id' => $variant->id,
@@ -373,18 +367,13 @@ class InvitationPurchaseProvisioner
private function createTicketAndCommitStock(
int $purchaseId,
int $purchaseItemId,
int $userId,
int $catalogItemId,
object $variant,
DateTimeInterface $now,
): void {
$purchaseReference = Schema::hasColumn('tickets', 'source_purchase_item_id')
? ['source_purchase_item_id' => $purchaseItemId]
: ['source_purchase_id' => $purchaseId];
if (DB::table('tickets')
->where($purchaseReference)
->where('source_purchase_id', $purchaseId)
->where('source_variant_id', $variant->id)
->exists()) {
return;
@@ -431,7 +420,7 @@ class InvitationPurchaseProvisioner
'ticket' => (string) Str::uuid(),
'name' => null,
'description' => null,
...$purchaseReference,
'source_purchase_id' => $purchaseId,
'source_catalog_item_id' => $catalogItemId,
'source_variant_id' => $variant->id,
'used_at' => null,

View File

@@ -1,20 +0,0 @@
<?php
namespace App\Domains\Forms\Controllers\AdminApp;
use App\Domains\Forms\Resources\TicketFilterFormResource;
use App\Domains\Forms\Services\TicketFilterFormService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class TicketFilterFormController extends Controller
{
public function __construct(private readonly TicketFilterFormService $formService) {}
public function __invoke(Request $request): TicketFilterFormResource
{
$tenant = $request->user('sanctum')->tenant()->firstOrFail();
return TicketFilterFormResource::make($this->formService->get($tenant));
}
}

View File

@@ -1,22 +0,0 @@
<?php
namespace App\Domains\Forms\Controllers\AdminApp;
use App\Domains\Forms\Resources\TicketFormResource;
use App\Domains\Forms\Services\TicketFormService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class TicketFormController extends Controller
{
public function __construct(protected TicketFormService $ticketFormService) {}
public function __invoke(Request $request): TicketFormResource
{
return TicketFormResource::make(
$this->ticketFormService->get(
$request->user('sanctum')->tenant()->firstOrFail()
)
);
}
}

View File

@@ -1,21 +0,0 @@
<?php
namespace App\Domains\Forms\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class TicketFilterFormResource extends JsonResource
{
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
return [
'code' => $this->resource['code'],
'action' => $this->resource['action'],
'method' => $this->resource['method'],
'fields' => $this->resource['fields'],
'columns' => $this->resource['columns'],
];
}
}

View File

@@ -1,18 +0,0 @@
<?php
namespace App\Domains\Forms\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class TicketFormResource extends JsonResource
{
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
return [
'statuses' => $this->resource['statuses'],
'categories' => $this->resource['categories'],
];
}
}

View File

@@ -6,18 +6,27 @@ use App\Domains\Purchase\Models\Purchase;
class SaleFormService
{
/** @return array{statuses: list<array{value: string, label: string, real_statuses: list<string>}>} */
/** @return array{statuses: list<array{code: string, name: string}>} */
public function get(): array
{
$names = [
Purchase::STATUS_CREATED => 'Creada',
Purchase::STATUS_PENDING_PAYMENT => 'Esperando pago',
Purchase::STATUS_IN_REVIEW => 'En revisión',
Purchase::STATUS_PAID => 'Confirmada',
Purchase::STATUS_CANCELLED => 'Cancelada',
Purchase::STATUS_REJECTED => 'Rechazada',
Purchase::STATUS_EXPIRED => 'Vencida',
Purchase::STATUS_SUPERSEDED => 'Reemplazada',
];
return [
'statuses' => array_map(
fn (string $code, array $definition): array => [
'value' => $code,
'label' => $definition['name'],
'real_statuses' => $definition['statuses'],
fn (string $status): array => [
'code' => $status,
'name' => $names[$status],
],
array_keys(Purchase::adminStatuses()),
array_values(Purchase::adminStatuses()),
Purchase::statuses(),
),
];
}

View File

@@ -1,152 +0,0 @@
<?php
namespace App\Domains\Forms\Services;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Models\Ticket;
use App\Domains\Ticket\Services\AdminAppTicketColumnService;
class TicketFilterFormService
{
private const FIESTA_FUTBOL_INFANTIL = 'fiesta_futbol_infantil';
public function __construct(
private readonly TicketFormService $ticketFormService,
private readonly AdminAppTicketColumnService $columnService,
) {}
/** @return array<string, mixed> */
public function get(Tenant $tenant): array
{
$fields = $this->commonFields();
if ($tenant->codigo === self::FIESTA_FUTBOL_INFANTIL) {
$fields = [
...$this->fiestaFutbolInfantilFields($tenant),
...$this->commonFields(includeDate: false),
];
}
return [
'code' => 'tickets_filter',
'action' => '/api/v1/adminapp/tenant/tickets',
'method' => 'GET',
'fields' => $fields,
'columns' => $this->columnService->publicColumns($tenant),
];
}
/** @return list<array<string, mixed>> */
private function fiestaFutbolInfantilFields(Tenant $tenant): array
{
$form = $this->ticketFormService->getForFilters($tenant);
return [
[
'name' => 'category',
'query_param' => 'category',
'label' => 'Categoría',
'type' => 'select',
'required' => false,
'default' => null,
'placeholder' => 'Categoría',
'options' => array_map(
fn (array $category): array => [
'value' => $category['value'],
'label' => $category['label'],
'children' => [
[
'field' => 'product',
'disabled' => $category['products'] === [],
'options' => array_map(
fn (array $product): array => [
'value' => $product['value'],
'label' => $product['label'],
'children' => [
[
'field' => 'type',
'disabled' => $product['types'] === [],
'options' => array_map(
fn (array $type): array => [
'value' => $type['value'],
'label' => $type['label'],
'children' => [[
'field' => 'size',
'disabled' => ($type['sizes'] ?? []) === [],
'options' => $type['sizes'] ?? [],
]],
],
$product['types'],
),
],
],
],
$category['products'],
),
],
[
'field' => 'date',
'disabled' => ! in_array($category['value'], ['comidas', 'comida'], true),
'options' => [],
],
],
],
$form['categories'],
),
],
$this->dependentSelect('product', 'Producto', 'category'),
$this->dependentSelect('type', 'Tipo', 'product'),
$this->dependentSelect('size', 'Talle', 'type'),
[
...$this->dependentSelect('date', 'Fecha', 'category'),
'type' => 'date',
],
];
}
/** @return list<array<string, mixed>> */
private function commonFields(bool $includeDate = true): array
{
return [
...($includeDate ? [[
'name' => 'date',
'query_param' => 'date',
'label' => 'Fecha',
'type' => 'date',
'required' => false,
'default' => null,
]] : []),
[
'name' => 'status',
'query_param' => 'status',
'label' => 'Estado',
'type' => 'select',
'required' => false,
'default' => null,
'placeholder' => 'Estado',
'options' => [
['value' => Ticket::STATUS_ACTIVE, 'label' => 'Activo'],
['value' => Ticket::STATUS_USED, 'label' => 'Usado'],
['value' => Ticket::STATUS_EXPIRED, 'label' => 'Vencido'],
],
],
];
}
/** @return array<string, mixed> */
private function dependentSelect(string $name, string $label, string $dependency): array
{
return [
'name' => $name,
'query_param' => $name,
'label' => $label,
'type' => 'select',
'required' => false,
'default' => null,
'placeholder' => $label,
'depends_on' => $dependency,
'disabled' => true,
'options' => [],
];
}
}

View File

@@ -1,400 +0,0 @@
<?php
namespace App\Domains\Forms\Services;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Models\Ticket;
use Illuminate\Database\Eloquent\Collection;
class TicketFormService
{
private const PRODUCT = 'product';
/**
* @var array<string, array{label: string|null, product: string, type: string|null, order: int}>
*/
private const CATEGORY_PRESENTATIONS = [
'entradas' => [
'label' => null,
'product' => self::PRODUCT,
'type' => null,
'order' => 1,
],
'alojamientos' => [
'label' => 'Camping',
'product' => 'tipo_alojamiento',
'type' => null,
'order' => 2,
],
'camping' => [
'label' => null,
'product' => 'tipo_alojamiento',
'type' => null,
'order' => 2,
],
'comidas' => [
'label' => 'Comida',
'product' => 'event_date',
'type' => 'horario',
'order' => 3,
],
'comida' => [
'label' => null,
'product' => 'event_date',
'type' => 'horario',
'order' => 3,
],
'merchandising' => [
'label' => null,
'product' => self::PRODUCT,
'type' => 'color',
'order' => 4,
],
];
/**
* @var array<string, array{label: string|null, product: string, type: string|null, size: string|null, order: int}>
*/
private const FILTER_CATEGORY_PRESENTATIONS = [
'entradas' => ['label' => null, 'product' => self::PRODUCT, 'type' => null, 'size' => null, 'order' => 1],
'alojamientos' => ['label' => 'Camping', 'product' => 'tipo_alojamiento', 'type' => null, 'size' => null, 'order' => 2],
'camping' => ['label' => null, 'product' => 'tipo_alojamiento', 'type' => null, 'size' => null, 'order' => 2],
'comidas' => ['label' => 'Comida', 'product' => 'horario', 'type' => 'servicio', 'size' => null, 'order' => 3],
'comida' => ['label' => null, 'product' => 'horario', 'type' => 'servicio', 'size' => null, 'order' => 3],
'merchandising' => ['label' => null, 'product' => self::PRODUCT, 'type' => 'color', 'size' => 'talle', 'order' => 4],
];
/**
* @return array{
* statuses: list<array{value: string, label: string}>,
* categories: list<array{
* value: string,
* label: string,
* products: list<array{
* value: string,
* label: string,
* types: list<array{value: string, label: string}>
* }>
* }>
* }
*/
public function get(Tenant $tenant): array
{
$items = CatalogItem::query()
->where('tenant_code', $tenant->codigo)
->where('has_tickets', true)
->whereHas('category')
->with($this->relations())
->orderBy('group_order')
->orderBy('nombre')
->get();
return $this->build($items, self::CATEGORY_PRESENTATIONS);
}
/**
* Return active catalog options plus soft-deleted sources still referenced by
* tickets, so historical tickets never become impossible to filter.
*
* @return array{
* statuses: list<array{value: string, label: string}>,
* categories: list<array{
* value: string,
* label: string,
* products: list<array{
* value: string,
* label: string,
* types: list<array{value: string, label: string}>
* }>
* }>
* }
*/
public function getForFilters(Tenant $tenant): array
{
$historicalVariantIds = Ticket::query()
->where('tenant_code', $tenant->codigo)
->whereNotNull('source_variant_id')
->distinct()
->pluck('source_variant_id')
->map(fn ($id): int => (int) $id)
->all();
$historicalCatalogItemIds = Ticket::query()
->where('tenant_code', $tenant->codigo)
->whereNotNull('source_catalog_item_id')
->distinct()
->pluck('source_catalog_item_id')
->map(fn ($id): int => (int) $id)
->merge(
Variant::withTrashed()
->whereKey($historicalVariantIds)
->pluck('catalog_item_id')
->map(fn ($id): int => (int) $id),
)
->unique()
->values()
->all();
$items = CatalogItem::withTrashed()
->where('tenant_code', $tenant->codigo)
->whereHas('category')
->where(function ($query) use ($historicalCatalogItemIds): void {
$query
->where(function ($activeQuery): void {
$activeQuery
->whereNull('catalog_items.deleted_at')
->where('has_tickets', true);
})
->orWhereIn('catalog_items.id', $historicalCatalogItemIds);
})
->with([
'category',
'itemAttributes.attribute.options',
'variants' => fn ($query) => $query
->withTrashed()
->where(function ($variantQuery) use ($historicalVariantIds): void {
$variantQuery
->whereNull('variantes.deleted_at')
->orWhereIn('variantes.id', $historicalVariantIds);
}),
'variants.definitions.itemAttribute.attribute.options',
'variants.eventDates',
'variants.eventDate',
])
->orderBy('group_order')
->orderBy('nombre')
->get();
return $this->build($items, self::FILTER_CATEGORY_PRESENTATIONS, includeSizes: true);
}
/**
* @param Collection<int, CatalogItem> $items
* @return array{
* statuses: list<array{value: string, label: string}>,
* categories: list<array{
* value: string,
* label: string,
* products: list<array{
* value: string,
* label: string,
* types: list<array{value: string, label: string}>
* }>
* }>
* }
*/
private function build(Collection $items, array $presentations, bool $includeSizes = false): array
{
$categories = [];
foreach ($items as $item) {
$sourceCategory = trim((string) $item->category?->nombre);
$categoryValue = mb_strtolower($sourceCategory);
$presentation = $presentations[$categoryValue] ?? [
'label' => null,
'product' => self::PRODUCT,
'type' => null,
'size' => null,
'order' => PHP_INT_MAX,
];
$categories[$categoryValue] ??= [
'value' => $categoryValue,
'label' => $presentation['label'] ?? $sourceCategory,
'order' => $presentation['order'],
'products' => [],
];
foreach ($this->products(
$item,
$presentation['product'],
$presentation['type'],
$presentation['size'] ?? null,
) as $product) {
$productValue = $product['value'];
$existingProduct = $categories[$categoryValue]['products'][$productValue] ?? [
'value' => $productValue,
'label' => $product['label'],
'types' => [],
'sizes' => [],
];
foreach ($product['types'] as $type) {
$existingProduct['types'][$type['value']] = $type;
}
foreach ($product['sizes'] as $size) {
$existingProduct['sizes'][$size['value']] = $size;
}
$categories[$categoryValue]['products'][$productValue] = $existingProduct;
}
}
uasort($categories, fn (array $left, array $right): int => $left['order'] <=> $right['order']
?: $left['label'] <=> $right['label']);
return [
'statuses' => [
['value' => Ticket::STATUS_ACTIVE, 'label' => 'Activo'],
['value' => Ticket::STATUS_USED, 'label' => 'Usado'],
['value' => Ticket::STATUS_EXPIRED, 'label' => 'Vencido'],
],
'categories' => array_values(array_map(
fn (array $category): array => [
'value' => $category['value'],
'label' => $category['label'],
'products' => array_values(array_map(
fn (array $product): array => [
'value' => $product['value'],
'label' => $product['label'],
'types' => array_values($product['types']),
...($includeSizes ? ['sizes' => array_values($product['sizes'])] : []),
],
$category['products'],
)),
],
$categories,
)),
];
}
/** @return list<string> */
private function relations(): array
{
return [
'category',
'itemAttributes.attribute.options',
'variants.definitions.itemAttribute.attribute.options',
'variants.eventDates',
'variants.eventDate',
];
}
/**
* @return list<array{
* value: string,
* label: string,
* types: list<array{value: string, label: string}>,
* sizes: list<array{value: string, label: string}>
* }>
*/
private function products(CatalogItem $item, string $productCode, ?string $typeCode, ?string $sizeCode): array
{
if ($productCode === self::PRODUCT) {
return [[
'value' => $item->slug,
'label' => $item->nombre,
'types' => $this->types($item, $typeCode, $sizeCode),
'sizes' => $this->types($item, $sizeCode),
]];
}
$products = [];
foreach ($item->variants as $variant) {
foreach ($this->variantOptions($variant, $productCode) as $productOption) {
$productValue = $productOption['value'];
$products[$productValue] ??= [
'value' => $productValue,
'label' => $this->optionLabel($productOption['label'], $productCode),
'types' => [],
'sizes' => [],
];
foreach ($this->variantOptions($variant, $typeCode) as $typeOption) {
$this->mergeTypeOption(
$products[$productValue]['types'],
$typeOption,
$variant,
$sizeCode,
);
}
foreach ($this->variantOptions($variant, $sizeCode) as $sizeOption) {
$products[$productValue]['sizes'][$sizeOption['value']] = $sizeOption;
}
}
}
return array_values(array_map(
fn (array $product): array => [
'value' => $product['value'],
'label' => $product['label'],
'types' => array_values($product['types']),
'sizes' => array_values($product['sizes']),
],
$products,
));
}
/** @return list<array<string, mixed>> */
private function types(CatalogItem $item, ?string $typeCode, ?string $sizeCode = null): array
{
$types = [];
foreach ($item->variants as $variant) {
foreach ($this->variantOptions($variant, $typeCode) as $typeOption) {
$this->mergeTypeOption($types, $typeOption, $variant, $sizeCode);
}
}
return array_values(array_map(function (array $type) use ($sizeCode): array {
if ($sizeCode !== null) {
$type['sizes'] = array_values($type['sizes']);
}
return $type;
}, $types));
}
/**
* @param array<string, array<string, mixed>> $types
* @param array{value: string, label: string} $typeOption
*/
private function mergeTypeOption(
array &$types,
array $typeOption,
Variant $variant,
?string $sizeCode,
): void {
$typeValue = $typeOption['value'];
$types[$typeValue] ??= [
...$typeOption,
...($sizeCode !== null ? ['sizes' => []] : []),
];
foreach ($this->variantOptions($variant, $sizeCode) as $sizeOption) {
$types[$typeValue]['sizes'][$sizeOption['value']] = $sizeOption;
}
}
/** @return list<array{value: string, label: string}> */
private function variantOptions(Variant $variant, ?string $attributeCode): array
{
if ($attributeCode === null) {
return [];
}
$selection = $variant->selectionOptions($variant->catalogItem->itemAttributes)
->get($attributeCode);
if ($selection === null) {
return [];
}
return array_is_list($selection) ? $selection : [$selection];
}
private function optionLabel(string $label, string $attributeCode): string
{
if ($attributeCode !== 'event_date') {
return $label;
}
[$day, $month] = array_pad(explode('/', $label), 2, null);
return $day !== null && $month !== null ? "{$day}/{$month}" : $label;
}
}

View File

@@ -9,7 +9,6 @@ Provee catálogos y opciones auxiliares para construir formularios del panel adm
- `EventFormService`: devuelve redes sociales disponibles y las URL configuradas para el tenant.
- `SaleFormService`: expone los estados admitidos para compras con sus etiquetas de presentación.
- `StaffFormService`: lista categorías raíz que pueden asignarse al personal del tenant.
- `TicketFormService`: expone estados y opciones anidadas de categoría, producto y tipo para los tickets de Fiesta Fútbol Infantil.
Cada servicio tiene un controlador invocable y un `JsonResource` específico. `SocialMediaOptionResource` representa las opciones de redes sociales.
@@ -20,7 +19,6 @@ Bajo `/v1/adminapp/forms`, con `auth:sanctum` y `adminapp.tenant`:
- `GET /event`.
- `GET /sale`.
- `GET /staff`.
- `GET /fiesta-futbol-infantil/ticket`: estados y jerarquía categoría → producto → tipo para filtros de tickets.
- `GET /fiesta-futbol-infantil/merchandise`: opciones de color y talle del tenant para merchandising.
## Dependencias

View File

@@ -5,8 +5,6 @@ use App\Domains\Forms\Controllers\AdminApp\FoodFormController;
use App\Domains\Forms\Controllers\AdminApp\MerchandiseFormController;
use App\Domains\Forms\Controllers\AdminApp\SaleFormController;
use App\Domains\Forms\Controllers\AdminApp\StaffFormController;
use App\Domains\Forms\Controllers\AdminApp\TicketFilterFormController;
use App\Domains\Forms\Controllers\AdminApp\TicketFormController;
use Illuminate\Support\Facades\Route;
Route::prefix('v1/adminapp/forms')
@@ -15,13 +13,6 @@ Route::prefix('v1/adminapp/forms')
Route::get('event', EventFormController::class);
Route::get('sale', SaleFormController::class);
Route::get('staff', StaffFormController::class);
Route::get('tickets-filter', TicketFilterFormController::class)
->middleware('tenant.menu:adminapp.tickets')
->name('adminapp.forms.tickets-filter');
Route::get(
'fiesta-futbol-infantil/ticket',
TicketFormController::class
);
Route::get(
'fiesta-futbol-infantil/merchandise',
MerchandiseFormController::class

View File

@@ -7,10 +7,7 @@ use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\TelepagosPayment;
use App\Domains\Purchase\Models\TelepagosQr;
use App\Domains\Purchase\Services\CheckoutService;
use App\Domains\Purchase\Services\DniDistanceService;
use Exception;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
@@ -18,7 +15,6 @@ class TelepagosWebhookService
{
public function __construct(
private readonly CheckoutService $checkoutService,
private readonly DniDistanceService $dniDistance,
) {}
/**
@@ -45,6 +41,7 @@ class TelepagosWebhookService
$paymentData = [
'compra_id' => null,
'matched_purchase_ids' => null,
'cuit_buyer' => $details['data']['buyer']['cuit'] ?? $details['buyer']['cuit'] ?? null,
'cvu_buyer' => $details['data']['buyer']['cvu'] ?? $details['buyer']['cvu'] ?? null,
'amount' => $amount,
@@ -76,55 +73,24 @@ class TelepagosWebhookService
$dni = substr($cuit, 2, -1);
$tenantCodes = $client->tenants()->pluck('codigo');
$eligiblePurchases = Purchase::query()
->whereIn('tenant_codigo', $tenantCodes)
$purchases = Purchase::whereIn('tenant_codigo', $tenantCodes)
->where('transfer_payer_dni', $dni)
->whereIn('status', [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
Purchase::STATUS_IN_REVIEW,
])
->where('payment_method', 'transfer');
$purchases = (clone $eligiblePurchases)
->where('payment_method', 'transfer')
->where('total', $amount)
->latest()
->get()
->filter(fn (Purchase $purchase): bool => $purchase->transfer_payer_dni !== null
&& $this->dniDistance->distance($dni, $purchase->transfer_payer_dni) === 0)
->values();
->get();
$paymentData['matched_purchase_ids'] = $purchases->pluck('id')->all();
$compra = $purchases->count() === 1 ? $purchases->first() : null;
if (! $compra) {
$candidatePurchases = $this->findTransferCandidates(
$eligiblePurchases,
$dni,
$amount,
);
if ($candidatePurchases->isNotEmpty()) {
$payment = $this->storeTransferCandidates(
$paymentData,
$candidatePurchases,
$dni,
$amount,
);
Log::channel('telepagos')->info('Telepagos webhook: Transfer payment candidates found.', [
'client_code' => $client->code,
'cashin_id' => $cashinId,
'telepagos_payment_id' => $payment->id,
'amount' => $amount,
'candidate_count' => $payment->candidates->count(),
'candidates' => $payment->candidates
->map(fn ($candidate): array => [
'purchase_id' => $candidate->compra_id,
'match_reason' => $candidate->match_reason,
'dni_distance' => $candidate->dni_distance,
'amount_difference' => $candidate->amount_difference,
'confidence' => $candidate->confidence,
])
->all(),
]);
if ($purchases->count() > 1) {
TelepagosPayment::create($paymentData);
}
Log::channel('telepagos')->warning('Telepagos webhook: Expected exactly one matching purchase.', [
@@ -243,91 +209,4 @@ class TelepagosWebhookService
{
return number_format((float) $amount, 2, '.', '');
}
/**
* @param Builder<Purchase> $eligiblePurchases
* @return Collection<int, Purchase>
*/
private function findTransferCandidates(Builder $eligiblePurchases, string $dni, string $amount): Collection
{
$tolerancePercentage = max(
0,
(float) config('purchase.transfer_candidate_amount_tolerance_percentage', 5),
);
$numericAmount = (float) $amount;
$tolerance = $numericAmount * ($tolerancePercentage / 100);
$minimumAmount = $this->normalizeAmount(max(0, $numericAmount - $tolerance));
$maximumAmount = $this->normalizeAmount($numericAmount + $tolerance);
return (clone $eligiblePurchases)
->whereBetween('total', [$minimumAmount, $maximumAmount])
->latest()
->get()
->filter(function (Purchase $purchase) use ($dni, $amount): bool {
if ($purchase->transfer_payer_dni === null) {
return false;
}
$purchaseAmount = $this->normalizeAmount($purchase->total);
$distance = $this->dniDistance->distance(
$dni,
(string) $purchase->transfer_payer_dni,
);
return $distance === 0
|| ($purchaseAmount === $amount && $distance <= 2);
})
->values();
}
/**
* @param array<string, mixed> $paymentData
* @param Collection<int, Purchase> $candidatePurchases
*/
private function storeTransferCandidates(
array $paymentData,
Collection $candidatePurchases,
string $dni,
string $amount,
): TelepagosPayment {
return DB::transaction(function () use ($paymentData, $candidatePurchases, $dni, $amount): TelepagosPayment {
$payment = TelepagosPayment::create($paymentData);
$payment->candidates()->createMany(
$candidatePurchases
->map(function (Purchase $purchase) use ($dni, $amount): array {
$purchaseAmount = $this->normalizeAmount($purchase->total);
$dniDistance = $this->dniDistance->distance(
$dni,
(string) $purchase->transfer_payer_dni,
);
$dniMatches = $dniDistance === 0;
$amountMatches = $purchaseAmount === $amount;
return [
'compra_id' => $purchase->id,
'dni_matches' => $dniMatches,
'dni_distance' => $dniDistance,
'payment_dni' => $dni,
'purchase_dni' => $purchase->transfer_payer_dni,
'amount_matches' => $amountMatches,
'payment_amount' => $amount,
'purchase_amount' => $purchaseAmount,
'amount_difference' => $this->normalizeAmount(
abs((float) $purchaseAmount - (float) $amount),
),
'match_reason' => $amountMatches
? ($dniMatches ? 'ambiguous_exact_match' : 'exact_amount_near_dni')
: 'exact_dni_near_amount',
'confidence' => $amountMatches
? ($dniMatches ? 'exact' : 'medium')
: 'high',
];
})
->all(),
);
return $payment->load('candidates');
});
}
}

View File

@@ -32,14 +32,13 @@ 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', 'tenantUrl'))->render(),
view('mail.notifications.welcome', compact('brand', 'user'))->render(),
$brand,
);
@@ -100,25 +99,12 @@ 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,
"{$subject} - {$brand->nombre}",
view("mail.notifications.{$template}", [
"Código para recuperar tu contraseña - {$brand->nombre}",
view('mail.notifications.password-reset', [
'attempt' => $attempt,
'recoveryUrl' => $recoveryUrl,
'brand' => $brand,
@@ -152,7 +138,8 @@ class NotificationMailService
}
/** @var Collection<int, Ticket> $tickets */
$tickets = $purchase->tickets()
$tickets = Ticket::query()
->where('source_purchase_id', $purchase->getKey())
->where('tenant_code', $purchase->tenant_codigo)
->with(TicketPresentationResolver::RELATIONS)
->get();

View File

@@ -93,6 +93,7 @@ class PurchaseController extends Controller
PaymentIntentRequest $request,
Tenant $tenant,
Purchase $compra,
CheckoutService $checkoutService,
PurchaseStateGuard $purchaseState,
): JsonResponse {
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
@@ -102,6 +103,7 @@ class PurchaseController extends Controller
: null;
$updated = DB::transaction(function () use (
$checkoutService,
$compra,
$method,
$purchaseState,
@@ -140,6 +142,12 @@ class PurchaseController extends Controller
$purchaseUpdate['transfer_payer_dni'] = $transferPayerDni;
}
$purchase->update($purchaseUpdate);
$checkoutService->refreshReservationExpiration(
$purchase,
now()->addMinutes(
max(1, (int) config("purchase.payment_expiration_minutes.{$method}", 30)),
),
);
return true;
});

View File

@@ -14,7 +14,6 @@ use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Facades\DB;
@@ -52,14 +51,6 @@ class Purchase extends Model
public const STATUS_SUPERSEDED = 'superseded';
public const ADMIN_STATUS_INCOMPLETE = 'incomplete';
public const ADMIN_STATUS_AWAITING_PAYMENT = 'awaiting_payment';
public const ADMIN_STATUS_CONFIRMED = 'confirmed';
public const ADMIN_STATUS_CANCELLED = 'cancelled';
/** @return list<string> */
public static function statuses(): array
{
@@ -75,68 +66,6 @@ class Purchase extends Model
];
}
/**
* @return array<string, array{name: string, statuses: list<string>}>
*/
public static function adminStatuses(): array
{
return [
self::ADMIN_STATUS_INCOMPLETE => [
'name' => 'Por completar datos',
'statuses' => [self::STATUS_CREATED],
],
self::ADMIN_STATUS_AWAITING_PAYMENT => [
'name' => 'Esperando pago',
'statuses' => [self::STATUS_PENDING_PAYMENT, self::STATUS_IN_REVIEW],
],
self::ADMIN_STATUS_CONFIRMED => [
'name' => 'Confirmado',
'statuses' => [self::STATUS_PAID],
],
self::ADMIN_STATUS_CANCELLED => [
'name' => 'Anulado',
'statuses' => [
self::STATUS_CANCELLED,
self::STATUS_REJECTED,
self::STATUS_EXPIRED,
self::STATUS_SUPERSEDED,
],
],
];
}
/** @return list<string> */
public static function adminStatusCodes(): array
{
return array_keys(self::adminStatuses());
}
/** @return list<string> */
public static function realStatusesForAdminStatus(string $adminStatus): array
{
return self::adminStatuses()[$adminStatus]['statuses'] ?? [];
}
public static function adminStatusFor(string $realStatus): ?string
{
foreach (self::adminStatuses() as $adminStatus => $definition) {
if (in_array($realStatus, $definition['statuses'], true)) {
return $adminStatus;
}
}
return null;
}
public static function adminStatusNameFor(string $realStatus): ?string
{
$adminStatus = self::adminStatusFor($realStatus);
return $adminStatus === null
? null
: self::adminStatuses()[$adminStatus]['name'];
}
protected $table = 'compras';
/** @var array<int, string> */
@@ -186,15 +115,12 @@ class Purchase extends Model
return $this->hasMany(PurchaseItem::class, 'compra_id');
}
/** @return HasManyThrough<Ticket, PurchaseItem, $this> */
public function tickets(): HasManyThrough
/**
* @return HasMany<Ticket, $this>
*/
public function tickets(): HasMany
{
return $this->hasManyThrough(
Ticket::class,
PurchaseItem::class,
'compra_id',
'source_purchase_item_id',
);
return $this->hasMany(Ticket::class, 'source_purchase_id');
}
/** @return BelongsTo<StockReservation, $this> */
@@ -219,12 +145,6 @@ class Purchase extends Model
return $this->hasMany(TelepagosPayment::class, 'compra_id');
}
/** @return HasMany<TelepagosPaymentCandidate, $this> */
public function telepagosPaymentCandidates(): HasMany
{
return $this->hasMany(TelepagosPaymentCandidate::class, 'compra_id');
}
public function getTotalAmount(): float
{
if ($this->total !== null) {

View File

@@ -5,12 +5,10 @@ namespace App\Domains\Purchase\Models;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Ticket\Models\Ticket;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
#[Fillable([
'compra_id',
@@ -58,12 +56,6 @@ class PurchaseItem extends Model
return $this->belongsTo(Purchase::class, 'compra_id');
}
/** @return HasMany<Ticket, $this> */
public function tickets(): HasMany
{
return $this->hasMany(Ticket::class, 'source_purchase_item_id');
}
/** @return BelongsTo<Attachment, $this> */
public function imageAttachment(): BelongsTo
{

View File

@@ -6,10 +6,10 @@ use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
#[Fillable([
'compra_id',
'matched_purchase_ids',
'cuit_buyer',
'cvu_buyer',
'amount',
@@ -30,6 +30,7 @@ class TelepagosPayment extends Model
{
return [
'compra_id' => 'integer',
'matched_purchase_ids' => 'array',
'amount' => 'decimal:2',
];
}
@@ -41,10 +42,4 @@ class TelepagosPayment extends Model
{
return $this->belongsTo(Purchase::class, 'compra_id');
}
/** @return HasMany<TelepagosPaymentCandidate, $this> */
public function candidates(): HasMany
{
return $this->hasMany(TelepagosPaymentCandidate::class, 'telepagos_payment_id');
}
}

View File

@@ -1,50 +0,0 @@
<?php
namespace App\Domains\Purchase\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable([
'telepagos_payment_id',
'compra_id',
'dni_matches',
'dni_distance',
'payment_dni',
'purchase_dni',
'amount_matches',
'payment_amount',
'purchase_amount',
'amount_difference',
'match_reason',
'confidence',
])]
class TelepagosPaymentCandidate extends Model
{
protected $table = 'telepagos_payment_candidates';
protected function casts(): array
{
return [
'telepagos_payment_id' => 'integer',
'compra_id' => 'integer',
'dni_matches' => 'boolean',
'dni_distance' => 'integer',
'amount_matches' => 'boolean',
'payment_amount' => 'decimal:2',
'purchase_amount' => 'decimal:2',
'amount_difference' => 'decimal:2',
];
}
public function payment(): BelongsTo
{
return $this->belongsTo(TelepagosPayment::class, 'telepagos_payment_id');
}
public function purchase(): BelongsTo
{
return $this->belongsTo(Purchase::class, 'compra_id');
}
}

View File

@@ -4,7 +4,6 @@ namespace App\Domains\Purchase\Resources;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Purchase\Models\TelepagosPaymentCandidate;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
@@ -18,15 +17,12 @@ class PurchaseResource extends JsonResource
*/
public function toArray(Request $request): array
{
$serverTime = now();
$expiresAt = $this->stockReservation?->expires_at;
$items = $this->resource->relationLoaded('items')
? $this->resource->getRelation('items')
: collect();
$ticketsCount = array_key_exists('tickets_count', $this->resource->getAttributes())
? (int) $this->resource->getAttribute('tickets_count')
: null;
$paymentVerification = $this->resolvePaymentVerification();
$subtotal = $items->isNotEmpty()
? $items->reduce(
@@ -52,11 +48,7 @@ class PurchaseResource extends JsonResource
'created_at' => $this->created_at,
'status' => $this->status,
'payment_method' => $this->payment_method,
'expires_at' => $expiresAt,
'expires_in_seconds' => $expiresAt === null
? null
: max(0, $expiresAt->getTimestamp() - $serverTime->getTimestamp()),
'server_time' => $serverTime,
'expires_at' => $this->stockReservation?->expires_at,
'dni' => $this->dni,
'transfer_payer_dni' => $this->transfer_payer_dni,
'telefono' => $this->telefono,
@@ -66,7 +58,6 @@ class PurchaseResource extends JsonResource
'items' => PurchaseItemResource::collection($items),
'tickets_count' => $this->when($ticketsCount !== null, $ticketsCount),
'has_generated_tickets' => $this->when($ticketsCount !== null, $ticketsCount > 0),
'payment_verification' => $this->when($paymentVerification !== null, $paymentVerification),
'subtotal' => $this->formatMoney($subtotal),
'total' => $this->formatMoney($total),
];
@@ -86,75 +77,4 @@ class PurchaseResource extends JsonResource
{
return number_format((float) ($amount ?? 0), 2, '.', '');
}
/** @return array<string, mixed>|null */
private function resolvePaymentVerification(): ?array
{
if (
$this->status !== Purchase::STATUS_IN_REVIEW
|| $this->payment_method !== 'transfer'
|| ! $this->resource->relationLoaded('telepagosPaymentCandidates')
) {
return null;
}
$candidates = $this->resource
->getRelation('telepagosPaymentCandidates')
->sort(fn (TelepagosPaymentCandidate $left, TelepagosPaymentCandidate $right): int => $this->comparePaymentCandidates($left, $right))
->values();
/** @var TelepagosPaymentCandidate|null $primary */
$primary = $candidates->first();
return [
'status' => $primary === null ? 'pending' : 'candidate',
'candidate_count' => $candidates->count(),
'primary' => $primary === null ? null : [
'reason' => $primary->match_reason,
'dni_distance' => $primary->dni_distance,
'payment_amount' => $this->formatMoney($primary->payment_amount),
'purchase_amount' => $this->formatMoney($primary->purchase_amount),
'amount_difference' => $this->formatMoney($primary->amount_difference),
'confidence' => $primary->confidence,
'detected_at' => $primary->payment?->created_at?->toIso8601String(),
],
'reasons' => $candidates
->pluck('match_reason')
->unique()
->values()
->all(),
];
}
private function comparePaymentCandidates(
TelepagosPaymentCandidate $left,
TelepagosPaymentCandidate $right,
): int {
$reasonComparison = $this->paymentCandidateRank($left->match_reason)
<=> $this->paymentCandidateRank($right->match_reason);
if ($reasonComparison !== 0) {
return $reasonComparison;
}
$differenceComparison = (float) $left->amount_difference <=> (float) $right->amount_difference;
if ($differenceComparison !== 0) {
return $differenceComparison;
}
$leftTimestamp = $left->payment?->created_at?->getTimestamp() ?? 0;
$rightTimestamp = $right->payment?->created_at?->getTimestamp() ?? 0;
return ($rightTimestamp <=> $leftTimestamp) ?: ($right->id <=> $left->id);
}
private function paymentCandidateRank(string $reason): int
{
return match ($reason) {
'ambiguous_exact_match' => 0,
'exact_dni_near_amount' => 1,
'exact_amount_near_dni' => 2,
default => 3,
};
}
}

View File

@@ -70,7 +70,7 @@ class CompleteCheckoutService
$purchase->update([
'status' => Purchase::STATUS_IN_REVIEW,
]);
$this->reservations->clearExpirationForReview($purchase);
$this->reservations->refreshForPurchase($purchase, null);
return $this->loadPurchase($purchase);
});

View File

@@ -8,15 +8,6 @@ class PurchaseResponseLoader
{
public function load(Purchase $purchase): Purchase
{
$relations = ['tenant', 'items.imageAttachment', 'stockReservation'];
if (
$purchase->status === Purchase::STATUS_IN_REVIEW
&& $purchase->payment_method === 'transfer'
) {
$relations[] = 'telepagosPaymentCandidates.payment';
}
return $purchase->load($relations);
return $purchase->load(['tenant', 'items.imageAttachment', 'stockReservation']);
}
}

View File

@@ -43,11 +43,6 @@ class ReleaseCheckoutService
): Purchase {
$purchase = $this->lockPurchase($purchase);
if ($purchase->status === Purchase::STATUS_EXPIRED
&& $targetStatus === Purchase::STATUS_CANCELLED) {
return $this->loadPurchase($purchase);
}
if ($purchase->status === Purchase::STATUS_EXPIRED
&& $targetStatus !== Purchase::STATUS_EXPIRED) {
throw new PurchaseExpiredException;
@@ -77,14 +72,6 @@ class ReleaseCheckoutService
$cart = $purchase->cart()->withTrashed()->lockForUpdate()->first();
// Leaving checkout is allowed at the exact instant the reservation
// expires. Finish the expiration while holding the purchase lock so
// the request is idempotent with the scheduled expiration job.
if ($targetStatus === Purchase::STATUS_CANCELLED
&& $this->hasOverdueActiveReservation($purchase)) {
$targetStatus = Purchase::STATUS_EXPIRED;
}
if ($targetStatus === Purchase::STATUS_CANCELLED
&& $cart?->status === 'active'
&& in_array($purchase->status, [

View File

@@ -2,12 +2,14 @@
namespace App\Domains\Purchase\Services;
use App\Domains\Catalog\Services\StockReservationService;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Services\Checkout\CompleteCheckoutService;
use App\Domains\Purchase\Services\Checkout\EditCheckoutService;
use App\Domains\Purchase\Services\Checkout\ReleaseCheckoutService;
use App\Domains\Purchase\Services\Checkout\StartCheckoutService;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
/**
@@ -22,6 +24,7 @@ class CheckoutService
private readonly EditCheckoutService $editor,
private readonly CompleteCheckoutService $completer,
private readonly ReleaseCheckoutService $releaser,
private readonly StockReservationService $reservations,
) {}
/** @param array<string, mixed> $purchaseData */
@@ -75,4 +78,9 @@ class CheckoutService
{
return $this->releaser->expire($purchase);
}
public function refreshReservationExpiration(Purchase $purchase, ?Carbon $expiresAt): void
{
$this->reservations->refreshForPurchase($purchase, $expiresAt);
}
}

View File

@@ -1,82 +0,0 @@
<?php
namespace App\Domains\Purchase\Services;
/**
* Measures likely DNI typing errors using the optimal-string-alignment
* variant of the Damerau-Levenshtein distance.
*
* The returned value is the minimum number of single-character edits needed
* to transform one DNI into the other. Supported edits are insertion,
* deletion, substitution and transposition of two adjacent digits.
*/
class DniDistanceService
{
/**
* Calculate the edit distance between two normalized DNI strings.
*
* Each matrix cell [row][column] stores the minimum edits required to
* transform the first $row digits of $left into the first $column digits
* of $right. The bottom-right cell therefore contains the final distance.
*/
public function distance(string $left, string $right): int
{
$left = $this->normalize($left);
$right = $this->normalize($right);
$leftLength = strlen($left);
$rightLength = strlen($right);
$matrix = [];
// Transforming a prefix into an empty string requires deleting every digit.
for ($row = 0; $row <= $leftLength; $row++) {
$matrix[$row] = [$row];
}
// Transforming an empty string into a prefix requires inserting every digit.
for ($column = 0; $column <= $rightLength; $column++) {
$matrix[0][$column] = $column;
}
for ($row = 1; $row <= $leftLength; $row++) {
for ($column = 1; $column <= $rightLength; $column++) {
$substitutionCost = $left[$row - 1] === $right[$column - 1] ? 0 : 1;
$deletionDistance = $matrix[$row - 1][$column] + 1;
$insertionDistance = $matrix[$row][$column - 1] + 1;
$substitutionDistance = $matrix[$row - 1][$column - 1] + $substitutionCost;
// Keep the cheapest way to align the two prefixes at this position.
$matrix[$row][$column] = min(
$deletionDistance,
$insertionDistance,
$substitutionDistance,
);
// Count two adjacent inverted digits as one edit instead of two substitutions.
if (
$row > 1
&& $column > 1
&& $left[$row - 1] === $right[$column - 2]
&& $left[$row - 2] === $right[$column - 1]
) {
$matrix[$row][$column] = min(
$matrix[$row][$column],
$matrix[$row - 2][$column - 2] + 1,
);
}
}
}
return $matrix[$leftLength][$rightLength];
}
/**
* Keep only digits and left-pad seven-digit DNIs so comparisons preserve
* the leading zero that is present when the DNI is extracted from a CUIT.
*/
public function normalize(string $dni): string
{
$digits = preg_replace('/\D+/', '', $dni) ?? '';
return str_pad($digits, 8, '0', STR_PAD_LEFT);
}
}

View File

@@ -3,7 +3,6 @@
namespace App\Domains\Sale\Controllers\AdminApp;
use App\Domains\Sale\Requests\AdminAppSaleIndexRequest;
use App\Domains\Sale\Requests\AdminAppSaleModificationIndexRequest;
use App\Domains\Sale\Requests\AdminAppSaleModificationPdfRequest;
use App\Domains\Sale\Requests\AdminAppSalePdfRequest;
use App\Domains\Sale\Resources\AdminApp\SaleDetailResource;
@@ -68,13 +67,11 @@ class SaleController extends Controller
return new SaleResource($this->saleService->cancel($tenant, $sale));
}
public function modifications(
AdminAppSaleModificationIndexRequest $request,
): AnonymousResourceCollection {
public function modifications(Request $request): AnonymousResourceCollection
{
return SaleModificationResource::collection(
$this->saleService->modifications(
$request->user()->tenant()->firstOrFail(),
$request->validated(),
$request->user()->tenant()->firstOrFail()
)
);
}
@@ -96,7 +93,7 @@ class SaleController extends Controller
return $this->salePdfService->downloadModifications(
$tenant,
$this->saleService->modificationsForExport($tenant, $request->validated()),
$this->saleService->modificationsForExport($tenant),
$request->validated('timezone'),
);
}
@@ -119,7 +116,7 @@ class SaleController extends Controller
return $this->saleExcelService->downloadModifications(
$tenant,
$this->saleService->modificationsForExport($tenant, $request->validated()),
$this->saleService->modificationsForExport($tenant),
$request->validated('timezone'),
);
}

View File

@@ -20,7 +20,7 @@ class AdminAppSaleIndexRequest extends FormRequest
'q' => ['sometimes', 'nullable', 'string', 'max:255'],
'id' => ['sometimes', 'nullable', 'integer', 'min:1'],
'sale_date' => ['sometimes', 'nullable', 'date_format:Y-m-d'],
'status' => ['sometimes', 'nullable', 'string', Rule::in(Purchase::adminStatusCodes())],
'status' => ['sometimes', 'nullable', 'string', Rule::in(Purchase::statuses())],
'sort_by' => ['sometimes', 'string', 'in:id,date,customer_name,quantity,status,total'],
'sort_direction' => ['sometimes', 'string', 'in:asc,desc'],
'page' => ['sometimes', 'integer', 'min:1'],

View File

@@ -1,16 +0,0 @@
<?php
namespace App\Domains\Sale\Requests;
class AdminAppSaleModificationIndexRequest extends AdminAppSaleIndexRequest
{
/** @return array<string, list<string>> */
public function rules(): array
{
$rules = parent::rules();
unset($rules['sort_by'], $rules['sort_direction']);
return $rules;
}
}

View File

@@ -3,14 +3,19 @@
namespace App\Domains\Sale\Requests;
use App\Domains\Shared\Rules\ValidTimezone;
use Illuminate\Foundation\Http\FormRequest;
class AdminAppSaleModificationPdfRequest extends AdminAppSaleModificationIndexRequest
class AdminAppSaleModificationPdfRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
/** @return array<string, list<string>> */
public function rules(): array
{
return [
...parent::rules(),
'timezone' => ['required', 'string', new ValidTimezone],
];
}

View File

@@ -23,12 +23,6 @@ class SaleModificationResource extends JsonResource
'attribute' => $this->attribute,
'old_value' => $this->old_value,
'new_value' => $this->new_value,
'admin_status' => is_string($this->new_value)
? Purchase::adminStatusFor($this->new_value)
: null,
'status_label' => is_string($this->new_value)
? Purchase::adminStatusNameFor($this->new_value)
: null,
'changed_at' => $this->changed_at->utc()->toIso8601String(),
'date' => $this->changed_at->format('Y-m-d'),
'time' => $this->changed_at->format('H:i:s'),
@@ -37,8 +31,6 @@ class SaleModificationResource extends JsonResource
'id' => $sale->id,
'customer_name' => $sale->nombre_apellido,
'status' => $sale->status,
'admin_status' => Purchase::adminStatusFor($sale->status),
'status_label' => Purchase::adminStatusNameFor($sale->status),
] : null,
'modified_by' => $user ? [
'id' => $user->id,

View File

@@ -20,8 +20,6 @@ class SaleResource extends JsonResource
'customer_name' => $this->nombre_apellido,
'quantity' => (int) ($this->quantity ?? 0),
'status' => $this->status,
'admin_status' => Purchase::adminStatusFor($this->status),
'status_label' => Purchase::adminStatusNameFor($this->status),
'total' => number_format((float) $this->total, 2, '.', ''),
'tickets_count' => $ticketsCount,
'has_generated_tickets' => $ticketsCount > 0,

View File

@@ -201,6 +201,11 @@ class AdminAppSaleExcelService
private function saleStatus(string $status): string
{
return Purchase::adminStatusNameFor($status) ?? $status;
return match ($status) {
Purchase::STATUS_PAID => 'Confirmado',
Purchase::STATUS_CREATED => 'Por completar datos',
Purchase::STATUS_PENDING_PAYMENT, Purchase::STATUS_IN_REVIEW => 'Esperando pago',
default => 'Anulado',
};
}
}

View File

@@ -92,24 +92,18 @@ class AdminAppSaleService
return $this->salesQuery($tenant, $filters)->get();
}
/**
* @param array<string, mixed> $filters
* @return LengthAwarePaginator<ValueChange>
*/
public function modifications(Tenant $tenant, array $filters = []): LengthAwarePaginator
/** @return LengthAwarePaginator<ValueChange> */
public function modifications(Tenant $tenant): LengthAwarePaginator
{
return $this->modificationsQuery($tenant, $filters)
return $this->modificationsQuery($tenant)
->paginateFromRequest()
->withQueryString();
}
/**
* @param array<string, mixed> $filters
* @return Collection<int, ValueChange>
*/
public function modificationsForExport(Tenant $tenant, array $filters = []): Collection
/** @return Collection<int, ValueChange> */
public function modificationsForExport(Tenant $tenant): Collection
{
return $this->modificationsQuery($tenant, $filters)->get();
return $this->modificationsQuery($tenant)->get();
}
/** @param array<string, mixed> $filters */
@@ -132,6 +126,7 @@ class AdminAppSaleService
return Purchase::query()
->where('tenant_codigo', $tenant->codigo)
->where('status', '!=', Purchase::STATUS_SUPERSEDED)
->when($filters['q'] ?? null, function (Builder $query, string $search): void {
$term = trim($search);
@@ -149,10 +144,12 @@ class AdminAppSaleService
)
->when(
$filters['status'] ?? null,
fn (Builder $query, string $status): Builder => $query->whereIn(
'status',
Purchase::realStatusesForAdminStatus($status),
)
fn (Builder $query, string $status): Builder => $status === Purchase::STATUS_PENDING_PAYMENT
? $query->whereIn('status', [
Purchase::STATUS_PENDING_PAYMENT,
Purchase::STATUS_IN_REVIEW,
])
: $query->where('status', $status)
)
->select('compras.*')
->selectRaw(
@@ -165,50 +162,12 @@ class AdminAppSaleService
->when($sortBy !== 'id', fn (Builder $query): Builder => $query->orderByDesc('id'));
}
/**
* @param array<string, mixed> $filters
* @return Builder<ValueChange>
*/
protected function modificationsQuery(Tenant $tenant, array $filters): Builder
/** @return Builder<ValueChange> */
protected function modificationsQuery(Tenant $tenant): Builder
{
return ValueChange::query()
->where('tenant_code', $tenant->codigo)
->where('trackable_type', (new Purchase)->getMorphClass())
->when($filters['q'] ?? null, function (Builder $query, string $search): void {
$term = trim($search);
$query->where(function (Builder $query) use ($term): void {
$query
->where('trackable_id', 'like', "%{$term}%")
->orWhereHasMorph(
'trackable',
[Purchase::class],
function (Builder $sales) use ($term): void {
$sales
->where('nombre_apellido', 'like', "%{$term}%")
->orWhere('created_at', 'like', "%{$term}%");
},
);
});
})
->when(
$filters['id'] ?? null,
fn (Builder $query, int $id): Builder => $query->where('trackable_id', $id)
)
->when(
$filters['sale_date'] ?? null,
fn (Builder $query, string $date): Builder => $query->whereHasMorph(
'trackable',
[Purchase::class],
fn (Builder $sales): Builder => $sales->whereDate('created_at', $date),
)
)
->when(
$filters['status'] ?? null,
fn (Builder $query, string $status): Builder => $query
->where('attribute', 'status')
->whereIn('new_value', Purchase::realStatusesForAdminStatus($status))
)
->with(['trackable', 'user'])
->orderByDesc('changed_at')
->orderByDesc('id');

View File

@@ -9,8 +9,7 @@ Provee consultas administrativas y exportaciones de ventas confirmadas, además
- `AdminAppSaleService`: pagina ventas, calcula totales y obtiene colecciones para exportación; también consulta modificaciones.
- `AdminAppSalePdfService`: genera descargas PDF de ventas y de cambios.
- `AdminAppSaleExcelService`: genera descargas Excel de ventas y de cambios.
- `AdminAppSaleIndexRequest`: valida filtros del listado y la exportación de ventas.
- `AdminAppSaleModificationIndexRequest`: valida los filtros compartidos por el historial y sus exportaciones.
- `AdminAppSaleIndexRequest`: valida filtros del listado y la exportación.
- `SaleResource` y `SaleModificationResource`: representan ventas e historial para AdminApp.
- `SaleController`: entrada HTTP del panel.
@@ -28,5 +27,3 @@ Consume compras de `Purchase`, datos del tenant y entradas de `Logging`. No es d
## Consideraciones
La consulta paginada y la colección de exportación deben aplicar los mismos filtros para evitar diferencias entre pantalla, PDF y Excel.
El historial comparte con ventas los filtros de búsqueda, ID, fecha de venta y estado. En el historial, el estado se evalúa sobre `ValueChange.new_value`: representa el resultado de esa modificación y no el estado actual de la venta.

View File

@@ -23,12 +23,7 @@ class StoreStaffRequest extends FormRequest
return [
'nombre_apellido' => ['required', 'string', 'max:255'],
'dni' => ['required', 'string', 'max:50'],
'email' => [
'required',
'email',
'max:255',
Rule::unique('users', 'email')->whereNull('deleted_at'),
],
'email' => ['required', 'email', 'max:255', 'unique:users,email'],
'category_ids' => $categoryRules,
'category_ids.*' => ['integer', 'distinct', Rule::exists('categorias', 'id')],
];

View File

@@ -28,9 +28,7 @@ class UpdateStaffRequest extends FormRequest
'required',
'email',
'max:255',
Rule::unique('users', 'email')
->whereNull('deleted_at')
->ignore($staffId),
Rule::unique('users', 'email')->ignore($staffId),
],
'category_ids' => $categoryRules,
'category_ids.*' => ['integer', 'distinct', Rule::exists('categorias', 'id')],

View File

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

View File

@@ -1,53 +0,0 @@
<?php
namespace App\Domains\Ticket\Controllers\AdminApp;
use App\Domains\Ticket\Requests\AdminAppTicketExportRequest;
use App\Domains\Ticket\Requests\AdminAppTicketIndexRequest;
use App\Domains\Ticket\Resources\AdminApp\AdminAppTicketCollection;
use App\Domains\Ticket\Services\AdminAppTicketExcelService;
use App\Domains\Ticket\Services\AdminAppTicketPdfService;
use App\Domains\Ticket\Services\AdminAppTicketService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
class TicketController extends Controller
{
public function __construct(
private readonly AdminAppTicketService $ticketService,
private readonly AdminAppTicketPdfService $ticketPdfService,
private readonly AdminAppTicketExcelService $ticketExcelService,
) {}
public function index(AdminAppTicketIndexRequest $request): AdminAppTicketCollection
{
$tenant = $request->user()->tenant()->firstOrFail();
return new AdminAppTicketCollection(
$this->ticketService->search($tenant, $request->validated())
);
}
public function downloadPdf(AdminAppTicketExportRequest $request): Response
{
$tenant = $request->user()->tenant()->firstOrFail();
return $this->ticketPdfService->download(
$tenant,
$this->ticketService->ticketsForExport($tenant, $request->validated()),
$request->validated('timezone'),
);
}
public function downloadExcel(AdminAppTicketExportRequest $request): StreamedResponse
{
$tenant = $request->user()->tenant()->firstOrFail();
return $this->ticketExcelService->download(
$tenant,
$this->ticketService->ticketsForExport($tenant, $request->validated()),
$request->validated('timezone'),
);
}
}

View File

@@ -42,7 +42,7 @@ class GenerateTicketsForPaidPurchase
$user,
$purchaseItem->cantidad,
$purchaseItem->source_variant_id,
$purchaseItem->getKey(),
$purchase->getKey(),
);
}
}

View File

@@ -5,7 +5,7 @@ namespace App\Domains\Ticket\Models;
use App\Domains\Auth\Models\User;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Services\ResolvedTicketValidity;
use App\Domains\Ticket\Services\ResolvedValidityGroup;
@@ -21,7 +21,7 @@ use Illuminate\Support\Collection;
#[Fillable([
'tenant_code',
'ticket',
'source_purchase_item_id',
'source_purchase_id',
'source_catalog_item_id',
'source_variant_id',
'used_at',
@@ -56,7 +56,7 @@ class Ticket extends Model
return [
'source_catalog_item_id' => 'integer',
'source_variant_id' => 'integer',
'source_purchase_item_id' => 'integer',
'source_purchase_id' => 'integer',
'used_at' => 'datetime',
'scanner_user_id' => 'integer',
'user_id' => 'integer',
@@ -78,13 +78,13 @@ class Ticket extends Model
/** @return BelongsTo<User, $this> */
public function scannerUser(): BelongsTo
{
return $this->belongsTo(User::class, 'scanner_user_id')->withTrashed();
return $this->belongsTo(User::class, 'scanner_user_id');
}
/** @return BelongsTo<PurchaseItem, $this> */
public function sourcePurchaseItem(): BelongsTo
/** @return BelongsTo<Purchase, $this> */
public function sourcePurchase(): BelongsTo
{
return $this->belongsTo(PurchaseItem::class, 'source_purchase_item_id');
return $this->belongsTo(Purchase::class, 'source_purchase_id');
}
/** @return BelongsTo<CatalogItem, $this> */

View File

@@ -1,17 +0,0 @@
<?php
namespace App\Domains\Ticket\Requests;
use App\Domains\Shared\Rules\ValidTimezone;
class AdminAppTicketExportRequest extends AdminAppTicketIndexRequest
{
/** @return array<string, mixed> */
public function rules(): array
{
return [
...parent::rules(),
'timezone' => ['required', 'string', new ValidTimezone],
];
}
}

View File

@@ -1,47 +0,0 @@
<?php
namespace App\Domains\Ticket\Requests;
use App\Domains\Ticket\Models\Ticket;
use App\Domains\Ticket\Services\AdminAppTicketColumnService;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class AdminAppTicketIndexRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
/** @return array<string, list<string>> */
public function rules(): array
{
$tenant = $this->user()?->tenant()->first();
$sortableKeys = $tenant === null
? []
: app(AdminAppTicketColumnService::class)->sortableKeys($tenant);
return [
'q' => ['sometimes', 'nullable', 'string', 'max:255'],
'category' => ['sometimes', 'nullable', 'string', 'max:255'],
'product' => ['sometimes', 'nullable', 'string', 'max:255'],
'type' => ['sometimes', 'nullable', 'string', 'max:255'],
'date' => ['sometimes', 'nullable', 'date_format:Y-m-d'],
'size' => ['sometimes', 'nullable', 'string', 'max:255'],
'status' => [
'sometimes',
'nullable',
Rule::in([
Ticket::STATUS_ACTIVE,
Ticket::STATUS_USED,
Ticket::STATUS_EXPIRED,
]),
],
'page' => ['sometimes', 'integer', 'min:1'],
'per_page' => ['sometimes', 'integer', 'min:1', 'max:100'],
'sort_by' => ['sometimes', 'nullable', 'string', Rule::in($sortableKeys)],
'sort_direction' => ['sometimes', 'nullable', 'string', Rule::in(['asc', 'desc'])],
];
}
}

View File

@@ -1,34 +0,0 @@
<?php
namespace App\Domains\Ticket\Resources\AdminApp;
use App\Domains\Ticket\Services\AdminAppTicketResult;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\ResourceCollection;
class AdminAppTicketCollection extends ResourceCollection
{
/** @var class-string<AdminAppTicketResource> */
public $collects = AdminAppTicketResource::class;
private readonly int $scannedTickets;
private readonly int $totalTickets;
public function __construct(AdminAppTicketResult $result)
{
parent::__construct($result->tickets);
$this->scannedTickets = $result->scannedTickets;
$this->totalTickets = $result->totalTickets;
}
/** @return array{scanned_tickets: int, total_tickets: int} */
public function with(Request $request): array
{
return [
'scanned_tickets' => $this->scannedTickets,
'total_tickets' => $this->totalTickets,
];
}
}

View File

@@ -1,25 +0,0 @@
<?php
namespace App\Domains\Ticket\Resources\AdminApp;
use App\Domains\Ticket\Models\Ticket;
use App\Domains\Ticket\Resources\TicketResource;
use App\Domains\Ticket\Services\AdminAppTicketRowService;
use Illuminate\Http\Request;
/** @mixin Ticket */
class AdminAppTicketResource extends TicketResource
{
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
$rowService = app(AdminAppTicketRowService::class);
$details = $rowService->details($this->resource);
return [
...parent::toArray($request),
...$details,
'values' => $rowService->values($this->resource, $details),
];
}
}

View File

@@ -1,103 +0,0 @@
<?php
namespace App\Domains\Ticket\Services;
use App\Domains\Tenant\Models\Tenant;
class AdminAppTicketColumnService
{
private const FIESTA_FUTBOL_INFANTIL = 'fiesta_futbol_infantil';
/** @return list<array{key: string, label: string, type: string, sortable: bool, sort_param: string, width: string, excel_width: int}> */
public function columns(Tenant $tenant): array
{
$keys = $tenant->codigo === self::FIESTA_FUTBOL_INFANTIL
? ['order_number', 'category', 'product', 'type', 'date', 'size', 'amount', 'client', 'id', 'status', 'scanned_by']
: ['order_number', 'product', 'amount', 'client', 'id', 'status', 'scanned_by'];
$columns = array_map(fn (string $key): array => $this->definitions()[$key], $keys);
if ($tenant->codigo === self::FIESTA_FUTBOL_INFANTIL) {
$columns = array_map(function (array $column): array {
if (in_array($column['key'], ['product', 'type', 'date', 'size'], true)) {
$column['sortable'] = false;
}
return $column;
}, $columns);
} else {
$widths = [
'order_number' => '11%',
'product' => '15%',
'amount' => '10%',
'client' => '15%',
'id' => '8%',
'status' => '8%',
'scanned_by' => '11%',
];
$columns = array_map(function (array $column) use ($widths): array {
$column['width'] = $widths[$column['key']];
return $column;
}, $columns);
}
return $columns;
}
/** @return list<array{key: string, label: string, type: string, sortable: bool, sort_param: string, width: string}> */
public function publicColumns(Tenant $tenant): array
{
return array_map(function (array $column): array {
unset($column['excel_width']);
return $column;
}, $this->columns($tenant));
}
/** @return list<string> */
public function sortableKeys(Tenant $tenant): array
{
return array_values(array_map(
fn (array $column): string => $column['sort_param'],
array_filter($this->columns($tenant), fn (array $column): bool => $column['sortable']),
));
}
/** @return array<string, array{key: string, label: string, type: string, sortable: bool, sort_param: string, width: string, excel_width: int}> */
private function definitions(): array
{
return [
'order_number' => $this->column('order_number', 'N° de orden', 'order_number', '10.5%', 14),
'category' => $this->column('category', 'Categoría', 'text', '11%', 18),
'product' => $this->column('product', 'Producto', 'text', '11%', 22),
'type' => $this->column('type', 'Tipo', 'text', '8%', 18),
'date' => $this->column('date', 'Fecha', 'text', '7%', 14),
'size' => $this->column('size', 'Talle', 'text', '6%', 12),
'amount' => $this->column('amount', 'Importe', 'currency', '8%', 15),
'client' => $this->column('client', 'Cliente', 'text', '11%', 30),
'id' => $this->column('id', 'ID', 'text', '6%', 12),
'status' => $this->column('status', 'Estado', 'status', '7%', 13),
'scanned_by' => $this->column('scanned_by', 'Escaneado por', 'text', '8%', 28),
];
}
/** @return array{key: string, label: string, type: string, sortable: bool, sort_param: string, width: string, excel_width: int} */
private function column(
string $key,
string $label,
string $type,
string $width,
int $excelWidth,
): array {
return [
'key' => $key,
'label' => $label,
'type' => $type,
'sortable' => true,
'sort_param' => $key,
'width' => $width,
'excel_width' => $excelWidth,
];
}
}

View File

@@ -1,105 +0,0 @@
<?php
namespace App\Domains\Ticket\Services;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Models\Ticket;
use Carbon\CarbonInterface;
use Illuminate\Support\Collection;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Symfony\Component\HttpFoundation\StreamedResponse;
class AdminAppTicketExcelService
{
public function __construct(
private readonly AdminAppTicketReportService $reportService,
private readonly AdminAppTicketColumnService $columnService,
) {}
/** @param Collection<int, Ticket> $tickets */
public function download(Tenant $tenant, Collection $tickets, string $timeZone): StreamedResponse
{
$generatedAt = now();
$rows = $this->reportService->rows($tickets);
$columns = $this->columnService->columns($tenant);
$spreadsheet = new Spreadsheet;
$spreadsheet->getProperties()
->setCreator('Shopit')
->setTitle('Listado de tickets')
->setSubject($tenant->nombre);
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Tickets');
$sheet->fromArray([array_column($columns, 'label')], null, 'A1');
foreach ($rows as $index => $ticket) {
$row = $index + 2;
foreach ($columns as $columnIndex => $column) {
$coordinate = Coordinate::stringFromColumnIndex($columnIndex + 1).$row;
$value = $ticket[$column['key']] ?? null;
if ($column['type'] === 'currency' && $value !== null) {
$sheet->setCellValue($coordinate, (float) $value);
continue;
}
if ($column['type'] === 'date' && $value instanceof CarbonInterface) {
$sheet->setCellValue(
$coordinate,
Date::dateTimeToExcel($value->copy()->timezone($timeZone)),
);
continue;
}
$sheet->setCellValueExplicit(
$coordinate,
$this->reportService->displayValue($value, $column['type'], $timeZone),
DataType::TYPE_STRING,
);
}
}
$lastRow = max(2, $rows->count() + 1);
$lastColumn = Coordinate::stringFromColumnIndex(count($columns));
foreach ($columns as $columnIndex => $column) {
$letter = Coordinate::stringFromColumnIndex($columnIndex + 1);
if ($column['type'] === 'currency') {
$sheet->getStyle("{$letter}2:{$letter}{$lastRow}")
->getNumberFormat()->setFormatCode('$ #,##0.00');
}
if ($column['type'] === 'date') {
$sheet->getStyle("{$letter}2:{$letter}{$lastRow}")
->getNumberFormat()->setFormatCode('dd/mm/yyyy hh:mm');
}
$sheet->getColumnDimension($letter)->setWidth($column['excel_width']);
}
$sheet->getStyle("A1:{$lastColumn}1")->applyFromArray([
'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
'fill' => [
'fillType' => Fill::FILL_SOLID,
'startColor' => ['rgb' => '26382E'],
],
'alignment' => ['vertical' => Alignment::VERTICAL_CENTER],
]);
$sheet->getRowDimension(1)->setRowHeight(24);
$sheet->freezePane('A2');
$sheet->setAutoFilter("A1:{$lastColumn}{$lastRow}");
$filename = 'tickets_'.$tenant->codigo.'_'
.$generatedAt->copy()->timezone($timeZone)->format('Ymd_His').'.xlsx';
return response()->streamDownload(function () use ($spreadsheet): void {
(new Xlsx($spreadsheet))->save('php://output');
$spreadsheet->disconnectWorksheets();
}, $filename, [
'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
]);
}
}

View File

@@ -1,56 +0,0 @@
<?php
namespace App\Domains\Ticket\Services;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Models\Ticket;
use Barryvdh\DomPDF\Facade\Pdf;
use Barryvdh\DomPDF\PDF as DomPdf;
use Illuminate\Http\Response;
use Illuminate\Support\Collection;
class AdminAppTicketPdfService
{
public function __construct(
private readonly AdminAppTicketReportService $reportService,
private readonly AdminAppTicketColumnService $columnService,
) {}
/** @param Collection<int, Ticket> $tickets */
public function download(Tenant $tenant, Collection $tickets, string $timeZone): Response
{
$generatedAt = now();
$columns = $this->columnService->columns($tenant);
$rows = $this->reportService->rows($tickets);
$pdf = Pdf::loadView('pdf.adminapp.tickets', [
'tenant' => $tenant,
'columns' => $columns,
'tickets' => $this->reportService->displayRows($rows, $columns, $timeZone),
'generatedAt' => $generatedAt,
'timeZone' => $timeZone,
])->setPaper('a3', 'landscape');
$this->addPageNumbers($pdf);
return $pdf->download(
'tickets_'.$tenant->codigo.'_'
.$generatedAt->copy()->timezone($timeZone)->format('Ymd_His').'.pdf'
);
}
private function addPageNumbers(DomPdf $pdf): void
{
$pdf->render();
$domPdf = $pdf->getDomPDF();
$font = $domPdf->getFontMetrics()->getFont('DejaVu Sans');
$domPdf->getCanvas()->page_text(
565,
805,
'Página {PAGE_NUM} de {PAGE_COUNT}',
$font,
7,
[0.48, 0.52, 0.49],
);
}
}

View File

@@ -1,35 +0,0 @@
<?php
namespace App\Domains\Ticket\Services;
use App\Domains\Ticket\Models\Ticket;
use Illuminate\Support\Collection;
class AdminAppTicketReportService
{
public function __construct(private readonly AdminAppTicketRowService $rowService) {}
/**
* @param Collection<int, Ticket> $tickets
* @return Collection<int, array<string, mixed>>
*/
public function rows(Collection $tickets): Collection
{
return $this->rowService->rows($tickets);
}
/**
* @param Collection<int, array<string, mixed>> $rows
* @param list<array<string, mixed>> $columns
* @return Collection<int, array<string, string>>
*/
public function displayRows(Collection $rows, array $columns, string $timeZone): Collection
{
return $this->rowService->displayRows($rows, $columns, $timeZone);
}
public function displayValue(mixed $value, string $type, string $timeZone): string
{
return $this->rowService->displayValue($value, $type, $timeZone);
}
}

View File

@@ -1,16 +0,0 @@
<?php
namespace App\Domains\Ticket\Services;
use App\Domains\Ticket\Models\Ticket;
use Illuminate\Pagination\LengthAwarePaginator;
final readonly class AdminAppTicketResult
{
/** @param LengthAwarePaginator<Ticket> $tickets */
public function __construct(
public LengthAwarePaginator $tickets,
public int $scannedTickets,
public int $totalTickets,
) {}
}

View File

@@ -1,210 +0,0 @@
<?php
namespace App\Domains\Ticket\Services;
use App\Domains\Catalog\Models\ItemAttribute;
use App\Domains\Ticket\Models\Ticket;
use Illuminate\Support\Collection;
class AdminAppTicketRowService
{
private const FIESTA_FUTBOL_INFANTIL = 'fiesta_futbol_infantil';
private const CATEGORY_PRESENTATIONS = [
'alojamientos' => ['category' => 'Camping', 'product' => 'tipo_alojamiento', 'type' => null, 'date' => null, 'size' => null],
'camping' => ['category' => null, 'product' => 'tipo_alojamiento', 'type' => null, 'date' => null, 'size' => null],
'entradas' => ['category' => null, 'product' => 'product', 'type' => null, 'date' => null, 'size' => null],
'comidas' => ['category' => 'Comida', 'product' => 'horario', 'type' => 'servicio', 'date' => 'event_date', 'size' => null],
'comida' => ['category' => null, 'product' => 'horario', 'type' => 'servicio', 'date' => 'event_date', 'size' => null],
'merchandising' => ['category' => null, 'product' => 'product', 'type' => 'color', 'date' => null, 'size' => 'talle'],
];
/** @return array<string, mixed> */
public function details(Ticket $ticket): array
{
$purchaseItem = $ticket->sourcePurchaseItem;
return [
'source_purchase_item_id' => $ticket->source_purchase_item_id,
'order_number' => $purchaseItem?->compra_id,
'product' => $purchaseItem?->item_nombre
?? $ticket->sourceCatalogItem?->nombre
?? $ticket->name,
'amount' => $purchaseItem?->precio_unitario,
'client' => $purchaseItem?->purchase?->nombre_apellido ?? $ticket->user?->nombre_apellido,
'status' => $ticket->status,
'scanned_by' => $ticket->scannerUser?->nombre_apellido,
'variant_properties' => $this->variantProperties($ticket),
];
}
/** @param array<string, mixed>|null $details */
public function values(Ticket $ticket, ?array $details = null): array
{
$details ??= $this->details($ticket);
$presentation = $this->presentation($ticket, $details);
return [
'order_number' => $details['order_number'],
'category' => $presentation['category'],
'product' => $presentation['product'],
'type' => $presentation['type'],
'date' => $presentation['date'],
'size' => $presentation['size'],
'amount' => $details['amount'] === null ? null : (float) $details['amount'],
'client' => $details['client'] ?? 'Sin nombre',
'id' => $ticket->id,
'status' => $details['status'],
'scanned_by' => $details['scanned_by'] ?? '-',
];
}
/**
* @param Collection<int, Ticket> $tickets
* @return Collection<int, array<string, mixed>>
*/
public function rows(Collection $tickets): Collection
{
return $tickets->values()->map(fn (Ticket $ticket): array => $this->values($ticket));
}
/**
* @param Collection<int, array<string, mixed>> $rows
* @param list<array<string, mixed>> $columns
* @return Collection<int, array<string, string>>
*/
public function displayRows(Collection $rows, array $columns, string $timeZone): Collection
{
return $rows->map(fn (array $row): array => collect($columns)
->mapWithKeys(fn (array $column): array => [
$column['key'] => $this->displayValue(
$row[$column['key']] ?? null,
$column['type'],
$timeZone,
),
])
->all());
}
public function displayValue(mixed $value, string $type, string $timeZone): string
{
if ($value === null || $value === '') {
return '-';
}
return match ($type) {
'order_number' => '#'.$value,
'currency' => '$'.number_format((float) $value, 2, ',', '.'),
'status' => match ((string) $value) {
Ticket::STATUS_USED => 'Usado',
Ticket::STATUS_EXPIRED => 'Vencido',
default => 'Activo',
},
default => (string) $value,
};
}
/** @param array<string, mixed> $details */
private function presentation(Ticket $ticket, array $details): array
{
$sourceCategory = trim((string) ($ticket->sourceCatalogItem?->category?->nombre ?? '')) ?: '-';
if ($ticket->tenant_code !== self::FIESTA_FUTBOL_INFANTIL) {
return [
'category' => $sourceCategory,
'product' => (string) ($details['product'] ?: $ticket->name ?: '-'),
'type' => $this->allPropertyLabels($details) ?: '-',
'date' => '-',
'size' => '-',
];
}
$configuration = self::CATEGORY_PRESENTATIONS[mb_strtolower($sourceCategory)] ?? null;
if ($configuration === null) {
return [
'category' => $sourceCategory,
'product' => (string) ($details['product'] ?: $ticket->name ?: '-'),
'type' => $this->allPropertyLabels($details) ?: '-',
'date' => '-',
'size' => '-',
];
}
return [
'category' => $configuration['category'] ?? $sourceCategory,
'product' => $configuration['product'] === 'product'
? (string) ($details['product'] ?: $ticket->name ?: '-')
: ($this->propertyLabels($details, $configuration['product']) ?: '-'),
'type' => $configuration['type'] === null
? '-'
: ($this->propertyLabels($details, $configuration['type']) ?: '-'),
'date' => $configuration['date'] === null
? '-'
: ($this->propertyLabels($details, $configuration['date']) ?: '-'),
'size' => $configuration['size'] === null
? '-'
: ($this->propertyLabels($details, $configuration['size']) ?: '-'),
];
}
/** @param array<string, mixed> $details */
private function propertyLabels(array $details, string $code): string
{
$property = collect($details['variant_properties'] ?? [])->firstWhere('code', $code);
$labels = collect($property['values'] ?? [])->pluck('label')->filter();
if ($code === 'event_date') {
$labels = $labels->map(function (string $label): string {
[$day, $month] = array_pad(explode('/', $label), 2, null);
return $day !== null && $month !== null ? "{$day}/{$month}" : $label;
});
}
return $labels->implode(', ');
}
/** @param array<string, mixed> $details */
private function allPropertyLabels(array $details): string
{
return collect($details['variant_properties'] ?? [])
->flatMap(fn (array $property): array => $property['values'] ?? [])
->pluck('label')
->filter()
->implode(', ');
}
/** @return list<array{code: string, label: string, values: list<array{value: string, label: string}>}> */
private function variantProperties(Ticket $ticket): array
{
$variant = $ticket->sourceVariant;
if ($variant === null) {
return [];
}
$itemAttributes = $variant->definitions
->map(fn ($definition) => $definition->itemAttribute)
->filter()
->merge($variant->catalogItem?->itemAttributes ?? collect())
->unique('id')
->values();
return $variant->selectionOptions($itemAttributes)
->map(function (array $selection, string $attributeCode) use ($itemAttributes): array {
$itemAttribute = $itemAttributes->first(
fn (ItemAttribute $itemAttribute): bool => $itemAttribute->attribute?->codigo
=== $attributeCode,
);
$values = array_is_list($selection) ? $selection : [$selection];
return [
'code' => $attributeCode,
'label' => $itemAttribute?->attribute?->nombre
?? ($attributeCode === 'event_date' ? 'Fecha' : $attributeCode),
'values' => array_values($values),
];
})
->values()
->all();
}
}

View File

@@ -1,404 +0,0 @@
<?php
namespace App\Domains\Ticket\Services;
use App\Domains\Auth\Models\User;
use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Models\Ticket;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
class AdminAppTicketService
{
private const RELATIONS = [
...TicketValidityResolver::RELATIONS,
...TicketPresentationResolver::RELATIONS,
'user',
'scannerUser',
'sourceCatalogItem.category',
'sourcePurchaseItem.purchase',
];
public function __construct(
private readonly AdminAppTicketColumnService $columnService,
private readonly AdminAppTicketRowService $rowService,
) {}
/**
* @param array{q?: string|null, category?: string|null, product?: string|null, type?: string|null, date?: string|null, size?: string|null, status?: string|null, page?: int, per_page?: int, sort_by?: string|null, sort_direction?: string|null} $filters
*/
public function search(Tenant $tenant, array $filters = []): AdminAppTicketResult
{
$query = $this->baseQuery($tenant, $filters);
$countQuery = clone $query;
$databaseSorted = $this->applyDatabaseSort($query, $tenant, $filters);
if (($filters['sort_by'] ?? null) && ! $databaseSorted) {
$matchingTickets = (clone $query)
->with(self::RELATIONS)
->get();
$matchingTickets = $this->sortTickets($matchingTickets, $tenant, $filters);
$tickets = $this->paginate($matchingTickets, $filters);
$scannedTickets = $matchingTickets->whereNotNull('used_at')->count();
} else {
$tickets = (clone $query)
->with(self::RELATIONS)
->when(! $databaseSorted, fn (Builder $query): Builder => $query->orderByDesc('id'))
->paginateFromRequest()
->withQueryString();
$scannedTickets = $countQuery->whereNotNull('used_at')->count();
}
return new AdminAppTicketResult(
tickets: $tickets,
scannedTickets: $scannedTickets,
totalTickets: $tickets->total(),
);
}
/**
* @param array{q?: string|null, category?: string|null, product?: string|null, type?: string|null, date?: string|null, size?: string|null, status?: string|null, sort_by?: string|null, sort_direction?: string|null} $filters
* @return Collection<int, Ticket>
*/
public function ticketsForExport(Tenant $tenant, array $filters = []): Collection
{
$query = $this->baseQuery($tenant, $filters);
$databaseSorted = $this->applyDatabaseSort($query, $tenant, $filters);
$tickets = $query
->with(self::RELATIONS)
->when(! $databaseSorted, fn (Builder $query): Builder => $query->orderByDesc('id'))
->get();
return $databaseSorted ? $tickets : $this->sortTickets($tickets, $tenant, $filters);
}
/**
* @param array{q?: string|null, category?: string|null, product?: string|null, type?: string|null, date?: string|null, size?: string|null, status?: string|null, page?: int, per_page?: int} $filters
* @return Builder<Ticket>
*/
private function baseQuery(Tenant $tenant, array $filters): Builder
{
$search = trim((string) ($filters['q'] ?? ''));
$query = Ticket::query()
->where('tenant_code', $tenant->codigo)
->when($search !== '', function (Builder $query) use ($search): void {
$this->applySearchFilter($query, $search);
})
->when($filters['category'] ?? null, function (Builder $query, string $category): void {
$query->whereHas('sourceCatalogItem.category', fn (Builder $categoryQuery): Builder => $categoryQuery
->whereRaw('LOWER(nombre) = ?', [mb_strtolower(trim($category))]));
})
->when($filters['product'] ?? null, function (Builder $query, string $product) use ($filters): void {
$this->applyProductFilter($query, (string) ($filters['category'] ?? ''), $product);
})
->when($filters['type'] ?? null, function (Builder $query, string $type) use ($filters): void {
$this->applyTypeFilter($query, (string) ($filters['category'] ?? ''), $type);
})
->when($filters['date'] ?? null, function (Builder $query, string $date) use ($tenant): void {
if ($tenant->codigo === 'fiesta_futbol_infantil') {
$this->applyEventDateFilter($query, $date);
return;
}
$query->whereHas('sourcePurchaseItem.purchase', fn (Builder $purchaseQuery): Builder => $purchaseQuery
->whereDate('created_at', $date));
})
->when($filters['size'] ?? null, function (Builder $query, string $size) use ($filters): void {
$this->applySizeFilter($query, (string) ($filters['category'] ?? ''), $size);
});
$this->applyStatusFilter($query, $filters['status'] ?? null);
return $query;
}
/** @param Builder<Ticket> $query */
private function applySearchFilter(Builder $query, string $search): void
{
$containsPattern = '%'.mb_strtolower($search).'%';
$amount = $this->searchAmount($search);
$query->where(function (Builder $searchQuery) use ($search, $containsPattern, $amount): void {
$searchQuery
->where(function (Builder $clientQuery) use ($containsPattern): void {
$clientQuery
->whereHas('sourcePurchaseItem.purchase', fn (Builder $purchaseQuery): Builder => $purchaseQuery
->whereRaw('LOWER(nombre_apellido) LIKE ?', [$containsPattern]))
->orWhere(function (Builder $fallbackClientQuery) use ($containsPattern): void {
$fallbackClientQuery
->where(function (Builder $missingPurchaseClientQuery): void {
$missingPurchaseClientQuery
->whereDoesntHave('sourcePurchaseItem.purchase')
->orWhereHas('sourcePurchaseItem.purchase', fn (Builder $purchaseQuery): Builder => $purchaseQuery
->whereNull('nombre_apellido'));
})
->whereHas('user', fn (Builder $userQuery): Builder => $userQuery
->whereRaw('LOWER(nombre_apellido) LIKE ?', [$containsPattern]));
});
})
->orWhereHas('scannerUser', fn (Builder $scannerQuery): Builder => $scannerQuery
->whereRaw('LOWER(nombre_apellido) LIKE ?', [$containsPattern]));
if (ctype_digit($search)) {
$searchQuery
->orWhere('tickets.id', (int) $search)
->orWhereHas('sourcePurchaseItem', fn (Builder $purchaseItemQuery): Builder => $purchaseItemQuery
->where('compra_id', (int) $search));
}
if ($amount !== null) {
$searchQuery->orWhereHas('sourcePurchaseItem', fn (Builder $purchaseItemQuery): Builder => $purchaseItemQuery
->where('precio_unitario', $amount));
}
});
}
private function searchAmount(string $search): ?string
{
$value = preg_replace('/[\s$]/u', '', trim($search));
if ($value === null || $value === '') {
return null;
}
if (preg_match('/^\d{1,3}(?:\.\d{3})+(?:,\d{1,2})?$/', $value) === 1) {
$value = str_replace(['.', ','], ['', '.'], $value);
} elseif (preg_match('/^\d{1,3}(?:,\d{3})+(?:\.\d{1,2})?$/', $value) === 1) {
$value = str_replace(',', '', $value);
} elseif (preg_match('/^\d+(?:[.,]\d{1,2})?$/', $value) === 1) {
$value = str_replace(',', '.', $value);
} else {
return null;
}
return number_format((float) $value, 2, '.', '');
}
/** @param Builder<Ticket> $query */
private function applyProductFilter(Builder $query, string $category, string $product): void
{
$category = $this->normalizedCategory($category);
if (in_array($category, ['alojamientos', 'camping'], true)) {
$this->whereVariantDefinition($query, 'tipo_alojamiento', $product);
return;
}
if (in_array($category, ['comidas', 'comida'], true)) {
$this->whereVariantDefinition($query, 'horario', $product);
return;
}
$query->whereHas('sourceCatalogItem', fn (Builder $itemQuery): Builder => $itemQuery
->where('slug', $product));
}
/** @param Builder<Ticket> $query */
private function applyTypeFilter(Builder $query, string $category, string $type): void
{
$attribute = match ($this->normalizedCategory($category)) {
'comidas', 'comida' => 'servicio',
'merchandising' => 'color',
default => null,
};
if ($attribute !== null) {
$this->whereVariantDefinition($query, $attribute, $type);
}
}
/** @param Builder<Ticket> $query */
private function applyEventDateFilter(Builder $query, string $date): void
{
$query
->whereHas('sourceCatalogItem.category', fn (Builder $categoryQuery): Builder => $categoryQuery
->whereRaw('LOWER(nombre) IN (?, ?)', ['comidas', 'comida']))
->whereHas('sourceVariant', function (Builder $variantQuery) use ($date): void {
$variantQuery->where(function (Builder $dateQuery) use ($date): void {
$dateQuery
->whereHas('eventDate', fn (Builder $eventDateQuery): Builder => $eventDateQuery
->whereDate('date', $date))
->orWhereHas('eventDates', fn (Builder $eventDateQuery): Builder => $eventDateQuery
->whereDate('date', $date));
});
});
}
/** @param Builder<Ticket> $query */
private function applySizeFilter(Builder $query, string $category, string $size): void
{
if ($this->normalizedCategory($category) === 'merchandising') {
$this->whereVariantDefinition($query, 'talle', $size);
}
}
/** @param Builder<Ticket> $query */
private function whereVariantDefinition(Builder $query, string $attribute, string $value): void
{
$query->whereHas('sourceVariant.definitions', fn (Builder $definitionQuery): Builder => $definitionQuery
->where('value', $value)
->whereHas('itemAttribute.attribute', fn (Builder $attributeQuery): Builder => $attributeQuery
->where('codigo', $attribute)));
}
/** @param Builder<Ticket> $query */
private function applyStatusFilter(Builder $query, ?string $status): void
{
if ($status === null || $status === '') {
return;
}
if ($status === Ticket::STATUS_USED) {
$query->whereNotNull('used_at');
return;
}
$matchingIds = (clone $query)
->whereNull('used_at')
->with(TicketValidityResolver::RELATIONS)
->get()
->filter(fn (Ticket $ticket): bool => $ticket->status === $status)
->pluck('id');
$query->whereIn('tickets.id', $matchingIds);
}
private function normalizedCategory(string $category): string
{
return mb_strtolower(trim($category));
}
/**
* @param Builder<Ticket> $query
* @param array{sort_by?: string|null, sort_direction?: string|null} $filters
*/
private function applyDatabaseSort(Builder $query, Tenant $tenant, array $filters): bool
{
$sortBy = (string) ($filters['sort_by'] ?? '');
if ($sortBy === '') {
return false;
}
$direction = ($filters['sort_direction'] ?? 'asc') === 'desc' ? 'desc' : 'asc';
$sortExpression = match ($sortBy) {
'order_number' => $this->purchaseItemColumnQuery('compra_id'),
'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'
? null
: $this->purchaseItemColumnQuery('item_nombre'),
default => null,
};
if ($sortExpression === null) {
return false;
}
$query->orderBy($sortExpression, $direction)->orderByDesc('tickets.id');
return true;
}
/** @return Builder<PurchaseItem> */
private function purchaseItemColumnQuery(string $column): Builder
{
return PurchaseItem::query()
->select($column)
->whereColumn('compra_items.id', 'tickets.source_purchase_item_id')
->limit(1);
}
/**
* @param Collection<int, Ticket> $tickets
* @param array{sort_by?: string|null, sort_direction?: string|null} $filters
* @return Collection<int, Ticket>
*/
private function sortTickets(Collection $tickets, Tenant $tenant, array $filters): Collection
{
$sortBy = (string) ($filters['sort_by'] ?? '');
if ($sortBy === '') {
return $tickets;
}
$column = collect($this->columnService->columns($tenant))
->firstWhere('sort_param', $sortBy);
if ($column === null) {
return $tickets;
}
$direction = ($filters['sort_direction'] ?? 'asc') === 'desc' ? -1 : 1;
$values = $tickets->mapWithKeys(fn (Ticket $ticket): array => [
$ticket->getKey() => $this->rowService->values($ticket)[$column['key']] ?? null,
]);
return $tickets->sort(function (Ticket $left, Ticket $right) use ($column, $direction, $values): int {
$leftValue = $values->get($left->getKey());
$rightValue = $values->get($right->getKey());
if ($leftValue === null || $leftValue === '') {
return $rightValue === null || $rightValue === '' ? $right->id <=> $left->id : 1;
}
if ($rightValue === null || $rightValue === '') {
return -1;
}
$comparison = $this->compareValues($leftValue, $rightValue, $column['type']);
return $comparison === 0
? $right->id <=> $left->id
: $comparison * $direction;
})->values();
}
private function compareValues(mixed $left, mixed $right, string $type): int
{
if (in_array($type, ['currency', 'order_number'], true)) {
return (float) $left <=> (float) $right;
}
if ($type === 'date') {
$leftTimestamp = $left instanceof \DateTimeInterface ? $left->getTimestamp() : strtotime((string) $left);
$rightTimestamp = $right instanceof \DateTimeInterface ? $right->getTimestamp() : strtotime((string) $right);
return $leftTimestamp <=> $rightTimestamp;
}
if ($type === 'status') {
$left = $this->rowService->displayValue($left, $type, 'UTC');
$right = $this->rowService->displayValue($right, $type, 'UTC');
}
return strnatcasecmp((string) $left, (string) $right);
}
/**
* @param Collection<int, Ticket> $tickets
* @param array{page?: int, per_page?: int} $filters
* @return LengthAwarePaginator<Ticket>
*/
private function paginate(Collection $tickets, array $filters): LengthAwarePaginator
{
$page = (int) ($filters['page'] ?? 1);
$perPage = (int) ($filters['per_page'] ?? 15);
return (new LengthAwarePaginator(
$tickets->forPage($page, $perPage)->values(),
$tickets->count(),
$perPage,
$page,
['path' => request()->url()],
))->withQueryString();
}
}

View File

@@ -1,229 +0,0 @@
<?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

@@ -3,7 +3,6 @@
namespace App\Domains\Ticket\Services;
use App\Domains\Auth\Models\User;
use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Ticket\Models\Ticket;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Pagination\LengthAwarePaginator;
@@ -74,7 +73,7 @@ class ScannerTicketService
->where('tenant_code', $scanner->tenant_codigo)
->where('ticket', $ticketUuid);
if ($this->requiresCategoryValidation($scanner)) {
if ($scanner->tenant()->firstOrFail()->requiresScannerCategoryValidation()) {
$categoryIds = $this->scannerCategoryIds($scanner);
$query->where(function (Builder $query) use ($scanner, $categoryIds): void {
@@ -159,7 +158,7 @@ class ScannerTicketService
private function scannerCanScan(User $scanner, Ticket $ticket): bool
{
if (! $this->requiresCategoryValidation($scanner)) {
if (! $scanner->tenant()->firstOrFail()->requiresScannerCategoryValidation()) {
return true;
}
@@ -170,10 +169,4 @@ class ScannerTicketService
->where('categorias.id', $categoryId)
->exists();
}
private function requiresCategoryValidation(User $scanner): bool
{
return $scanner->rol_codigo !== RoleCode::AdminApp->value
&& $scanner->tenant()->firstOrFail()->requiresScannerCategoryValidation();
}
}

View File

@@ -23,13 +23,13 @@ class TicketGeneratorService
User $user,
int $quantity = 1,
?int $sourceVariantId = null,
?int $sourcePurchaseItemId = null,
?int $sourcePurchaseId = null,
): Collection {
if ($quantity < 1) {
throw TicketGenerationException::invalidQuantity();
}
return DB::transaction(function () use ($catalogItem, $user, $quantity, $sourceVariantId, $sourcePurchaseItemId): Collection {
return DB::transaction(function () use ($catalogItem, $user, $quantity, $sourceVariantId, $sourcePurchaseId): Collection {
$targets = $this->resolveTargets(
$catalogItem,
$quantity,
@@ -37,7 +37,7 @@ class TicketGeneratorService
);
return $targets->map(function (array $target) use (
$sourcePurchaseItemId,
$sourcePurchaseId,
$user,
): Ticket {
$item = $target['catalog_item'];
@@ -45,7 +45,7 @@ class TicketGeneratorService
$ticket = Ticket::query()->create([
'tenant_code' => $item->tenant_code,
'ticket' => (string) Str::uuid(),
'source_purchase_item_id' => $sourcePurchaseItemId,
'source_purchase_id' => $sourcePurchaseId,
'source_catalog_item_id' => $item->getKey(),
'source_variant_id' => $variant?->getKey(),
'used_at' => null,

View File

@@ -6,8 +6,7 @@ Genera, valida, consulta y exporta entradas asociadas a compras pagadas de produ
## Modelo
- `Ticket`: pertenece a tenant y usuario, y conserva referencias al ítem de compra que lo generó, producto,
variante y usuario escáner. La compra se obtiene a través de su ítem.
- `Ticket`: pertenece a tenant y usuario, y conserva referencias a compra, producto, variante y usuario escáner.
- El nombre y la descripción se calculan dinámicamente desde el producto y la variante; los tickets no
persisten una copia de esos textos.
- `ValidityTime`: define ventanas absolutas o relativas de vigencia para fechas de evento y opciones de atributos.
@@ -24,33 +23,6 @@ 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`:
@@ -58,12 +30,6 @@ Bajo `/tenants/{tenant:codigo}`, protegidos por `auth:sanctum`:
- `GET /tickets`.
- `POST /tickets/pdf`.
Bajo `/v1/adminapp/tenant`, protegido por `auth:sanctum`, `adminapp.tenant` y el menú
`adminapp.tickets`:
- `GET /tickets`, paginado y con búsqueda opcional mediante `q`. La respuesta incluye
`scanned_tickets` y `total_tickets` para el tenant autenticado.
`TicketPdfService` genera la descarga y `TicketResource`/`ValidityTimeResource` definen las respuestas.
## Dependencias y reglas

View File

@@ -1,18 +0,0 @@
<?php
use App\Domains\Ticket\Controllers\AdminApp\TicketController;
use Illuminate\Support\Facades\Route;
Route::prefix('v1/adminapp/tenant')
->middleware(['auth:sanctum', 'adminapp.tenant'])
->group(function (): void {
Route::get('tickets', [TicketController::class, 'index'])
->middleware('tenant.menu:adminapp.tickets')
->name('adminapp.tickets.index');
Route::get('tickets/pdf', [TicketController::class, 'downloadPdf'])
->middleware('tenant.menu:adminapp.tickets')
->name('adminapp.tickets.pdf');
Route::get('tickets/excel', [TicketController::class, 'downloadExcel'])
->middleware('tenant.menu:adminapp.tickets')
->name('adminapp.tickets.excel');
});

View File

@@ -11,4 +11,3 @@ Route::prefix('tenants/{tenant:codigo}')
});
require __DIR__.'/scanner.php';
require __DIR__.'/adminapp.php';

View File

@@ -8,9 +8,4 @@ return [
'telepagos' => (int) env('PURCHASE_TELEPAGOS_EXPIRATION_MINUTES', 30),
'transfer' => (int) env('PURCHASE_TRANSFER_EXPIRATION_MINUTES', 1440),
],
'transfer_candidate_amount_tolerance_percentage' => (float) env(
'PURCHASE_TRANSFER_CANDIDATE_AMOUNT_TOLERANCE_PERCENTAGE',
5,
),
];

View File

@@ -1,141 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('telepagos_payment_candidates', function (Blueprint $table) {
$table->id();
$table->foreignId('telepagos_payment_id')
->constrained('telepagos_payments')
->cascadeOnDelete();
$table->foreignId('compra_id')->constrained('compras')->cascadeOnDelete();
$table->boolean('dni_matches');
$table->boolean('amount_matches');
$table->decimal('payment_amount', 10, 2);
$table->decimal('purchase_amount', 10, 2);
$table->decimal('amount_difference', 10, 2);
$table->string('match_reason');
$table->string('confidence');
$table->timestamps();
$table->unique(
['telepagos_payment_id', 'compra_id'],
'telepagos_payment_candidate_unique',
);
});
$this->migrateExistingCandidates();
Schema::table('telepagos_payments', function (Blueprint $table) {
$table->dropColumn('matched_purchase_ids');
});
}
public function down(): void
{
Schema::table('telepagos_payments', function (Blueprint $table) {
$table->json('matched_purchase_ids')->nullable()->after('compra_id');
});
DB::table('telepagos_payments')
->whereNull('compra_id')
->orderBy('id')
->each(function (object $payment): void {
$candidateIds = DB::table('telepagos_payment_candidates')
->where('telepagos_payment_id', $payment->id)
->pluck('compra_id')
->all();
if ($candidateIds !== []) {
DB::table('telepagos_payments')
->where('id', $payment->id)
->update(['matched_purchase_ids' => json_encode($candidateIds)]);
}
});
Schema::dropIfExists('telepagos_payment_candidates');
}
private function migrateExistingCandidates(): void
{
DB::table('telepagos_payments')
->whereNull('compra_id')
->whereNotNull('matched_purchase_ids')
->orderBy('id')
->each(function (object $payment): void {
$candidateIds = json_decode((string) $payment->matched_purchase_ids, true);
if (! is_array($candidateIds)) {
return;
}
$paymentAmount = number_format((float) $payment->amount, 2, '.', '');
$payerDni = $payment->cuit_buyer
? substr((string) $payment->cuit_buyer, 2, -1)
: null;
foreach ($candidateIds as $candidateId) {
$purchase = DB::table('compras')->find($candidateId);
if ($purchase === null) {
continue;
}
$purchaseAmount = number_format((float) $purchase->total, 2, '.', '');
$dniMatches = $payerDni !== null && $purchase->transfer_payer_dni === $payerDni;
$amountMatches = $purchaseAmount === $paymentAmount;
DB::table('telepagos_payment_candidates')->insertOrIgnore([
'telepagos_payment_id' => $payment->id,
'compra_id' => $purchase->id,
'dni_matches' => $dniMatches,
'amount_matches' => $amountMatches,
'payment_amount' => $paymentAmount,
'purchase_amount' => $purchaseAmount,
'amount_difference' => number_format(
abs((float) $purchaseAmount - (float) $paymentAmount),
2,
'.',
'',
),
'match_reason' => $this->matchReason($dniMatches, $amountMatches),
'confidence' => $this->confidence($dniMatches, $amountMatches),
'created_at' => $payment->created_at,
'updated_at' => $payment->updated_at,
]);
}
});
}
private function matchReason(bool $dniMatches, bool $amountMatches): string
{
if ($dniMatches && $amountMatches) {
return 'ambiguous_exact_match';
}
if ($dniMatches) {
return 'exact_dni_near_amount';
}
if ($amountMatches) {
return 'exact_amount_different_dni';
}
return 'legacy_candidate';
}
private function confidence(bool $dniMatches, bool $amountMatches): string
{
if ($dniMatches && $amountMatches) {
return 'exact';
}
return $dniMatches ? 'high' : 'medium';
}
};

View File

@@ -1,61 +0,0 @@
<?php
use App\Domains\Purchase\Services\DniDistanceService;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('telepagos_payment_candidates', function (Blueprint $table) {
$table->unsignedTinyInteger('dni_distance')->nullable()->after('dni_matches');
$table->string('payment_dni', 8)->nullable()->after('dni_distance');
$table->string('purchase_dni', 8)->nullable()->after('payment_dni');
});
$dniDistance = new DniDistanceService;
DB::table('telepagos_payment_candidates as candidate')
->join('telepagos_payments as payment', 'payment.id', '=', 'candidate.telepagos_payment_id')
->join('compras as purchase', 'purchase.id', '=', 'candidate.compra_id')
->select([
'candidate.id',
'candidate.match_reason',
'payment.cuit_buyer',
'purchase.transfer_payer_dni',
])
->orderBy('candidate.id')
->each(function (object $candidate) use ($dniDistance): void {
if ($candidate->cuit_buyer === null || $candidate->transfer_payer_dni === null) {
return;
}
$payerDni = substr((string) $candidate->cuit_buyer, 2, -1);
$distance = $dniDistance->distance($payerDni, (string) $candidate->transfer_payer_dni);
if ($candidate->match_reason === 'exact_amount_different_dni' && $distance > 2) {
DB::table('telepagos_payment_candidates')->where('id', $candidate->id)->delete();
return;
}
DB::table('telepagos_payment_candidates')
->where('id', $candidate->id)
->update([
'dni_distance' => $distance,
'payment_dni' => $payerDni,
'purchase_dni' => $candidate->transfer_payer_dni,
]);
});
}
public function down(): void
{
Schema::table('telepagos_payment_candidates', function (Blueprint $table) {
$table->dropColumn(['dni_distance', 'payment_dni', 'purchase_dni']);
});
}
};

View File

@@ -1,21 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
public function up(): void
{
DB::table('telepagos_payment_candidates')
->where('match_reason', 'exact_amount_different_dni')
->update(['match_reason' => 'exact_amount_near_dni']);
}
public function down(): void
{
DB::table('telepagos_payment_candidates')
->where('match_reason', 'exact_amount_near_dni')
->update(['match_reason' => 'exact_amount_different_dni']);
}
};

View File

@@ -1,82 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
private const MENU_CODE = 'adminapp.tickets';
private const TENANT_CODE = 'fiesta_futbol_infantil';
public function up(): void
{
if (! DB::table('menues')->where('code', 'main.adminapp')->exists()) {
// Reference data is added by seeders on fresh installations.
return;
}
$now = now();
DB::transaction(function () use ($now): void {
DB::table('menues')->updateOrInsert(
['code' => self::MENU_CODE],
[
'label' => 'Tickets',
'parent_menu_code' => 'main.adminapp',
'content_type' => 'dynamic',
'static_content_schema' => null,
'route' => '/admin/tickets',
'created_at' => $now,
'updated_at' => $now,
],
);
DB::table('tenants_menues')
->where('menu_code', self::MENU_CODE)
->where('tenant_code', '!=', self::TENANT_CODE)
->delete();
if (DB::table('tenants')->where('codigo', self::TENANT_CODE)->exists()) {
DB::table('tenants_menues')->updateOrInsert(
[
'tenant_code' => self::TENANT_CODE,
'menu_code' => self::MENU_CODE,
],
[
'static_content' => null,
'created_at' => $now,
'updated_at' => $now,
],
);
}
DB::table('roles')
->whereIn('codigo', ['admin', 'adminapp'])
->pluck('codigo')
->each(function (string $roleCode): void {
DB::table('roles_menues')->updateOrInsert([
'rol_codigo' => $roleCode,
'menu_codigo' => self::MENU_CODE,
]);
});
});
}
public function down(): void
{
DB::transaction(function (): void {
DB::table('tenants_menues')
->where('menu_code', self::MENU_CODE)
->delete();
DB::table('roles_menues')
->where('menu_codigo', self::MENU_CODE)
->delete();
DB::table('menues')
->where('code', self::MENU_CODE)
->delete();
});
}
};

View File

@@ -1,94 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('tickets', function (Blueprint $table): void {
$table->foreignId('source_purchase_item_id')
->nullable()
->after('source_purchase_id')
->constrained('compra_items')
->cascadeOnUpdate()
->nullOnDelete();
});
DB::table('tickets')
->whereNotNull('source_purchase_id')
->whereNull('source_purchase_item_id')
->orderBy('id')
->chunkById(500, function (Collection $tickets): void {
$purchaseIds = $tickets->pluck('source_purchase_id')->unique()->values();
$itemsByPurchase = DB::table('compra_items')
->whereIn('compra_id', $purchaseIds)
->get(['id', 'compra_id', 'source_catalog_item_id', 'source_variant_id'])
->groupBy('compra_id');
$bundleIds = $itemsByPurchase->flatten(1)
->pluck('source_catalog_item_id')
->filter()
->unique()
->values();
$componentsByBundle = DB::table('bundle_components')
->whereIn('bundle_catalog_item_id', $bundleIds)
->get([
'bundle_catalog_item_id',
'component_catalog_item_id',
'component_variant_id',
])
->groupBy('bundle_catalog_item_id');
foreach ($tickets as $ticket) {
$candidates = collect($itemsByPurchase->get($ticket->source_purchase_id, []))
->filter(function (object $item) use ($ticket, $componentsByBundle): bool {
if ($this->sameCatalogTarget($item, $ticket)) {
return true;
}
return collect($componentsByBundle->get($item->source_catalog_item_id, []))
->contains(fn (object $component): bool => $this->sameBundleTarget($component, $ticket));
})
->pluck('id')
->unique()
->values();
if ($candidates->count() === 1) {
DB::table('tickets')->where('id', $ticket->id)->update([
'source_purchase_item_id' => $candidates->sole(),
]);
}
}
});
}
public function down(): void
{
Schema::table('tickets', function (Blueprint $table): void {
$table->dropConstrainedForeignId('source_purchase_item_id');
});
}
private function sameCatalogTarget(object $item, object $ticket): bool
{
return (int) $item->source_catalog_item_id === (int) $ticket->source_catalog_item_id
&& $this->sameNullableId($item->source_variant_id, $ticket->source_variant_id);
}
private function sameBundleTarget(object $component, object $ticket): bool
{
return (int) $component->component_catalog_item_id === (int) $ticket->source_catalog_item_id
&& $this->sameNullableId($component->component_variant_id, $ticket->source_variant_id);
}
private function sameNullableId(mixed $left, mixed $right): bool
{
return $left === null || $right === null
? $left === null && $right === null
: (int) $left === (int) $right;
}
};

View File

@@ -1,73 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
$unresolved = DB::table('tickets')
->whereNotNull('source_purchase_id')
->whereNull('source_purchase_item_id')
->orderBy('id')
->limit(20)
->pluck('id');
if ($unresolved->isNotEmpty()) {
throw new RuntimeException(
'No se puede eliminar tickets.source_purchase_id: hay tickets sin un compra_item inequívoco. '
.'IDs: '.$unresolved->implode(', ')
);
}
$inconsistent = DB::table('tickets')
->join('compra_items', 'compra_items.id', '=', 'tickets.source_purchase_item_id')
->whereNotNull('tickets.source_purchase_id')
->whereColumn('tickets.source_purchase_id', '!=', 'compra_items.compra_id')
->orderBy('tickets.id')
->limit(20)
->pluck('tickets.id');
if ($inconsistent->isNotEmpty()) {
throw new RuntimeException(
'No se puede eliminar tickets.source_purchase_id: hay referencias de compra inconsistentes. '
.'IDs: '.$inconsistent->implode(', ')
);
}
Schema::table('tickets', function (Blueprint $table): void {
$table->dropConstrainedForeignId('source_purchase_id');
});
}
public function down(): void
{
Schema::table('tickets', function (Blueprint $table): void {
$table->foreignId('source_purchase_id')
->nullable()
->after('description')
->constrained('compras')
->cascadeOnUpdate()
->nullOnDelete();
});
DB::table('tickets')
->whereNotNull('source_purchase_item_id')
->orderBy('id')
->chunkById(500, function (Collection $tickets): void {
$purchaseIdsByItem = DB::table('compra_items')
->whereIn('id', $tickets->pluck('source_purchase_item_id'))
->pluck('compra_id', 'id');
foreach ($tickets as $ticket) {
DB::table('tickets')->where('id', $ticket->id)->update([
'source_purchase_id' => $purchaseIdsByItem->get($ticket->source_purchase_item_id),
]);
}
});
}
};

View File

@@ -1,38 +0,0 @@
<?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('tickets', function (Blueprint $table): void {
$table->dropForeign(['source_purchase_item_id']);
});
Schema::table('tickets', function (Blueprint $table): void {
$table->foreign('source_purchase_item_id')
->references('id')
->on('compra_items')
->cascadeOnUpdate()
->restrictOnDelete();
});
}
public function down(): void
{
Schema::table('tickets', function (Blueprint $table): void {
$table->dropForeign(['source_purchase_item_id']);
});
Schema::table('tickets', function (Blueprint $table): void {
$table->foreign('source_purchase_item_id')
->references('id')
->on('compra_items')
->cascadeOnUpdate()
->nullOnDelete();
});
}
};

View File

@@ -1,23 +0,0 @@
<?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

@@ -1,28 +0,0 @@
<?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

@@ -1,28 +0,0 @@
<?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

@@ -1,29 +0,0 @@
<?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

@@ -74,16 +74,10 @@ class MenuSeeder extends Seeder
],
[
'code' => 'adminapp.staff',
'label' => 'Usuarios',
'label' => 'Staff',
'parent_menu_code' => 'main.adminapp',
'route' => '/admin/staff',
],
[
'code' => 'adminapp.tickets',
'label' => 'Tickets',
'parent_menu_code' => 'main.adminapp',
'route' => '/admin/tickets',
],
[
'code' => 'adminapp.fiesta-futbol-infantil.entradas',
'label' => 'Entradas',
@@ -276,7 +270,6 @@ class MenuSeeder extends Seeder
'fiesta_futbol_infantil',
];
$fiestaCategoryMenuCodes = [
'adminapp.tickets',
'adminapp.fiesta-futbol-infantil.entradas',
'adminapp.fiesta-futbol-infantil.alojamientos',
'adminapp.fiesta-futbol-infantil.merchandising',

View File

@@ -18,8 +18,7 @@
</include>
</source>
<php>
<env name="APP_ENV" value="testing" force="true"/>
<env name="DB_DATABASE" value="shopit_test" force="true"/>
<env name="APP_ENV" value="testing"/>
<env name="APP_MAINTENANCE_DRIVER" value="file"/>
<env name="APP_CONFIG_CACHE" value="bootstrap/cache/phpunit-config.php"/>
<env name="APP_EVENTS_CACHE" value="bootstrap/cache/phpunit-events.php"/>

View File

@@ -11,7 +11,7 @@ declare(strict_types=1);
$root = dirname(__DIR__);
chdir($root);
$command = escapeshellarg(PHP_BINARY).' artisan route:list --json';
$command = escapeshellarg(PHP_BINARY).' artisan route:list --path=api --json';
$routeJson = shell_exec($command);
if (! is_string($routeJson) || trim($routeJson) === '') {
@@ -20,11 +20,6 @@ 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==';
@@ -182,10 +177,6 @@ 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']],
@@ -424,7 +415,6 @@ 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

@@ -1,6 +0,0 @@
@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

@@ -1,6 +0,0 @@
@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

@@ -1,24 +0,0 @@
<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,6 +1,45 @@
@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.',
])
<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>

View File

@@ -1,6 +0,0 @@
@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,8 +1,3 @@
<h1 style="margin: 0 0 20px;">¡Bienvenido a {{ $brand->nombre }}!</h1>
<p>Hola {{ $user->nombre_apellido }}, tu cuenta fue creada correctamente.</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>
<p>Ya podés ingresar y comenzar a comprar.</p>

View File

@@ -47,7 +47,11 @@
<td>{{ $sale->created_at?->copy()->timezone($timeZone)->format('d/m/Y H:i') ?? '-' }}</td>
<td>{{ $sale->nombre_apellido ?: 'Sin nombre' }}</td>
<td class="center">{{ (int) ($sale->quantity ?? 0) }}</td>
<td>{{ \App\Domains\Purchase\Models\Purchase::adminStatusNameFor($sale->status) ?? $sale->status }}</td>
<td>{{ match ($sale->status) {
'paid' => 'Confirmado',
'created', 'pending_payment' => 'Esperando pago',
default => 'Anulado',
} }}</td>
<td class="number">${{ number_format((float) $sale->total, 2, ',', '.') }}</td>
<td class="center">{{ (int) ($sale->tickets_count ?? 0) }}</td>
</tr>

View File

@@ -1,57 +0,0 @@
<!doctype html>
<html lang="es">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style>
@page { margin: 28px 34px 58px; }
body { color: #17211b; font-family: DejaVu Sans, sans-serif; font-size: 11px; margin: 0; }
h1 { font-size: 21px; margin: 0 0 3px; }
.subtitle { color: #66736b; margin: 0 0 15px; }
.summary { background: #eef5f1; border-left: 4px solid #198754; margin-bottom: 14px; padding: 8px 11px; }
.summary strong { font-size: 12px; }
table { border-collapse: collapse; width: 100%; }
thead { display: table-header-group; }
tr { page-break-inside: avoid; }
th { background: #26382e; color: #fff; font-size: 11px; letter-spacing: .25px; padding: 6px 5px; text-align: left; text-transform: uppercase; }
td { border-bottom: 1px solid #dfe7e2; overflow-wrap: break-word; padding: 6px 5px; vertical-align: top; }
tbody tr:nth-child(even) { background: #f7f9f8; }
.number { text-align: right; }
.ticket-id { font-size: 11px; word-break: break-all; }
.empty { color: #66736b; padding: 24px; text-align: center; }
</style>
</head>
<body>
<h1>Listado de tickets</h1>
<p class="subtitle">{{ $tenant->nombre }} · Generado el {{ $generatedAt->copy()->timezone($timeZone)->format('d/m/Y H:i') }}</p>
<div class="summary">
Tickets incluidos: <strong>{{ $tickets->count() }}</strong>
&nbsp;&nbsp;·&nbsp;&nbsp;
Escaneados: <strong>{{ $tickets->where('status', 'Usado')->count() }}</strong>
</div>
<table>
<thead>
<tr>
@foreach ($columns as $column)
<th @class(['number' => $column['type'] === 'currency'])>{{ $column['label'] }}</th>
@endforeach
</tr>
</thead>
<tbody>
@forelse ($tickets as $ticket)
<tr>
@foreach ($columns as $column)
<td @class([
'number' => $column['type'] === 'currency',
'ticket-id' => $column['key'] === 'ticket',
])>{{ $ticket[$column['key']] }}</td>
@endforeach
</tr>
@empty
<tr><td class="empty" colspan="{{ count($columns) }}">No hay tickets para los criterios seleccionados.</td></tr>
@endforelse
</tbody>
</table>
</body>
</html>

View File

@@ -16,6 +16,5 @@ 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,11 +3,9 @@
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());
@@ -26,79 +24,6 @@ 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

@@ -1,148 +0,0 @@
<?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_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

@@ -135,36 +135,4 @@ 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,8 +2,6 @@
namespace Tests\Feature\Forms;
use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Auth\Models\User;
use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Purchase\Models\Purchase;
@@ -36,7 +34,12 @@ class AdminAppSaleFormControllerTest extends TestCase
public function test_an_adminapp_user_can_get_the_sale_form(): void
{
$tenant = $this->createTenant('acme');
$tenant = Tenant::query()->create([
'codigo' => 'acme',
'nombre' => 'Acme',
'dominio' => 'acme.test',
'website_type_code' => 'onticket',
]);
Sanctum::actingAs(User::factory()->create([
'rol_codigo' => RoleCode::AdminApp->value,
'tenant_codigo' => $tenant->codigo,
@@ -44,15 +47,13 @@ class AdminAppSaleFormControllerTest extends TestCase
$this->getJson('/api/v1/adminapp/forms/sale')
->assertOk()
->assertJsonCount(count(Purchase::adminStatusCodes()), 'data.statuses')
->assertJsonPath('data.statuses.0.value', Purchase::ADMIN_STATUS_INCOMPLETE)
->assertJsonPath('data.statuses.0.label', 'Por completar datos')
->assertJsonPath('data.statuses.0.real_statuses.0', Purchase::STATUS_CREATED)
->assertJsonPath('data.statuses.1.value', Purchase::ADMIN_STATUS_AWAITING_PAYMENT)
->assertJsonPath('data.statuses.1.real_statuses.0', Purchase::STATUS_PENDING_PAYMENT)
->assertJsonPath('data.statuses.1.real_statuses.1', Purchase::STATUS_IN_REVIEW)
->assertJsonPath('data.statuses.2.value', Purchase::ADMIN_STATUS_CONFIRMED)
->assertJsonPath('data.statuses.3.value', Purchase::ADMIN_STATUS_CANCELLED);
->assertJsonCount(count(Purchase::statuses()), 'data.statuses')
->assertJsonPath('data.statuses.0.code', Purchase::STATUS_CREATED)
->assertJsonPath('data.statuses.0.name', 'Creada')
->assertJsonPath('data.statuses.1.code', Purchase::STATUS_PENDING_PAYMENT)
->assertJsonPath('data.statuses.2.code', Purchase::STATUS_IN_REVIEW)
->assertJsonPath('data.statuses.3.code', Purchase::STATUS_PAID)
->assertJsonPath('data.statuses.6.code', Purchase::STATUS_EXPIRED);
}
public function test_a_customer_cannot_get_the_sale_form(): void
@@ -64,34 +65,4 @@ class AdminAppSaleFormControllerTest extends TestCase
$this->getJson('/api/v1/adminapp/forms/sale')->assertForbidden();
}
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}.test",
'primary_color' => '#000000',
'secondary_color' => '#ffffff',
'danger_color' => '#dc3545',
'header_bg_color' => '#ffffff',
'footer_bg_color' => '#000000',
'header_logo_id' => $headerLogo->id,
'footer_logo_id' => $footerLogo->id,
'website_type_code' => 'onticket',
]);
}
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

@@ -1,357 +0,0 @@
<?php
namespace Tests\Feature\Forms;
use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Auth\Models\User;
use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Services\CatalogService;
use App\Domains\Menu\Models\Menu;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Models\Ticket;
use Database\Seeders\AttributeSeeder;
use Database\Seeders\AuthorizationSeeder;
use Database\Seeders\FiestaFutbolInfantilProductSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Str;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;
class AdminAppTicketFilterFormControllerTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
$this->seed(AuthorizationSeeder::class);
}
public function test_authentication_is_required(): void
{
$this->getJson('/api/v1/adminapp/forms/tickets-filter')->assertUnauthorized();
}
public function test_the_tenant_must_have_the_tickets_menu(): void
{
$tenant = $this->createTenant('tenant_without_tickets');
Sanctum::actingAs($this->createAdminAppUser($tenant));
$this->getJson('/api/v1/adminapp/forms/tickets-filter')->assertNotFound();
}
public function test_it_returns_the_common_ticket_filter_fields_for_other_tenants(): void
{
$tenant = $this->createTenant('another_tenant');
$this->grantTicketsMenu($tenant);
Sanctum::actingAs($this->createAdminAppUser($tenant));
$this->getJson('/api/v1/adminapp/forms/tickets-filter')
->assertOk()
->assertExactJson([
'data' => [
'code' => 'tickets_filter',
'action' => '/api/v1/adminapp/tenant/tickets',
'method' => 'GET',
'columns' => $this->commonColumns(),
'fields' => [
[
'name' => 'date',
'query_param' => 'date',
'label' => 'Fecha',
'type' => 'date',
'required' => false,
'default' => null,
],
[
'name' => 'status',
'query_param' => 'status',
'label' => 'Estado',
'type' => 'select',
'required' => false,
'default' => null,
'placeholder' => 'Estado',
'options' => [
['value' => 'active', 'label' => 'Activo'],
['value' => 'used', 'label' => 'Usado'],
['value' => 'expired', 'label' => 'Vencido'],
],
],
],
],
]);
}
public function test_it_returns_the_complete_nested_form_for_fiesta_futbol_infantil(): void
{
$tenant = $this->createFiestaFutbolInfantilTenant();
$this->grantTicketsMenu($tenant);
$admin = $this->createAdminAppUser($tenant);
Sanctum::actingAs($admin);
$response = $this->getJson('/api/v1/adminapp/forms/tickets-filter')
->assertOk()
->assertJsonPath('data.fields.0.name', 'category')
->assertJsonPath('data.fields.0.query_param', 'category')
->assertJsonPath('data.fields.1.name', 'product')
->assertJsonPath('data.fields.1.query_param', 'product')
->assertJsonPath('data.fields.1.depends_on', 'category')
->assertJsonPath('data.fields.2.name', 'type')
->assertJsonPath('data.fields.2.query_param', 'type')
->assertJsonPath('data.fields.2.depends_on', 'product')
->assertJsonPath('data.fields.3.name', 'size')
->assertJsonPath('data.fields.3.query_param', 'size')
->assertJsonPath('data.fields.3.depends_on', 'type')
->assertJsonPath('data.fields.4.name', 'date')
->assertJsonPath('data.fields.4.query_param', 'date')
->assertJsonPath('data.fields.4.depends_on', 'category')
->assertJsonPath('data.fields.5.name', 'status')
->assertJsonPath('data.fields.5.query_param', 'status')
->assertJsonPath('data.columns.0.key', 'order_number')
->assertJsonPath('data.columns.0.sort_param', 'order_number')
->assertJsonPath('data.columns.1.key', 'category')
->assertJsonPath('data.columns.2.key', 'product')
->assertJsonPath('data.columns.2.sortable', false)
->assertJsonPath('data.columns.3.key', 'type')
->assertJsonPath('data.columns.3.sortable', false)
->assertJsonPath('data.columns.4.key', 'date')
->assertJsonPath('data.columns.4.sortable', false)
->assertJsonPath('data.columns.5.key', 'size')
->assertJsonPath('data.columns.5.sortable', false);
$categories = collect($response->json('data.fields.0.options'));
$this->assertSame(
['Entradas', 'Camping', 'Comida', 'Merchandising'],
$categories->pluck('label')->all(),
);
$entries = $categories->firstWhere('value', 'entradas');
$this->assertSame('Abono', $entries['children'][0]['options'][0]['label']);
$this->assertTrue($entries['children'][0]['options'][0]['children'][0]['disabled']);
$this->assertTrue($entries['children'][1]['disabled']);
$camping = $categories->firstWhere('value', 'alojamientos');
$this->assertSame(
['Carpa', 'Motorhome'],
collect($camping['children'][0]['options'])->pluck('label')->all(),
);
$this->assertTrue($camping['children'][0]['options'][0]['children'][0]['disabled']);
$merchandise = $categories->firstWhere('value', 'merchandising');
$merchandiseProduct = $merchandise['children'][0]['options'][0];
$this->assertSame('Camiseta', $merchandiseProduct['label']);
$this->assertSame(
['Verde', 'Blanco'],
collect($merchandiseProduct['children'][0]['options'])->pluck('label')->all(),
);
$this->assertSame(
['14', 'S', 'M', 'L', 'XL', 'XXL'],
collect($merchandiseProduct['children'][0]['options'][0]['children'][0]['options'])
->pluck('label')
->all(),
);
}
public function test_merchandise_sizes_are_scoped_to_the_selected_product_and_color(): void
{
$tenant = $this->createFiestaFutbolInfantilTenant();
$this->grantTicketsMenu($tenant);
Sanctum::actingAs($this->createAdminAppUser($tenant));
$merchandise = CatalogItem::query()
->where('tenant_code', $tenant->codigo)
->where('slug', 'camiseta')
->with([
'itemAttributes.attribute.options',
'variants.definitions.itemAttribute.attribute.options',
])
->firstOrFail();
$whiteXxl = $merchandise->variants->first(fn ($variant): bool => $variant->selectionValues()->get('color') === 'Blanco'
&& $variant->selectionValues()->get('talle') === 'XXL');
$this->assertNotNull($whiteXxl);
app(CatalogService::class)->deleteVariant($whiteXxl);
$response = $this->getJson('/api/v1/adminapp/forms/tickets-filter')->assertOk();
$merchandiseCategory = collect($response->json('data.fields.0.options'))
->firstWhere('value', 'merchandising');
$product = $merchandiseCategory['children'][0]['options'][0];
$colors = collect($product['children'][0]['options']);
$greenSizes = collect($colors->firstWhere('value', 'Verde')['children'][0]['options'])
->pluck('value');
$whiteSizes = collect($colors->firstWhere('value', 'Blanco')['children'][0]['options'])
->pluck('value');
$this->assertContains('XXL', $greenSizes);
$this->assertNotContains('XXL', $whiteSizes);
}
public function test_a_food_schedule_is_only_returned_when_a_variant_exists_for_the_date(): void
{
$tenant = $this->createFiestaFutbolInfantilTenant();
$this->grantTicketsMenu($tenant);
Sanctum::actingAs($this->createAdminAppUser($tenant));
$food = CatalogItem::query()
->where('tenant_code', $tenant->codigo)
->where('slug', 'comida')
->with([
'itemAttributes.attribute.options',
'variants.definitions.itemAttribute.attribute.options',
'variants.eventDates',
'variants.eventDate',
])
->firstOrFail();
$food->variants
->filter(fn ($variant): bool => $variant->selectionValues()->get('horario') === 'Almuerzo')
->each->delete();
$response = $this->getJson('/api/v1/adminapp/forms/tickets-filter')->assertOk();
$foodCategory = collect($response->json('data.fields.0.options'))->firstWhere('value', 'comidas');
$schedules = collect($foodCategory['children'][0]['options'])->pluck('value');
$this->assertNotContains('Almuerzo', $schedules);
$this->assertContains('Desayuno', $schedules);
$this->assertContains('Cena', $schedules);
}
public function test_a_deleted_food_variant_remains_in_the_filter_when_a_ticket_references_it(): void
{
$tenant = $this->createFiestaFutbolInfantilTenant();
$this->grantTicketsMenu($tenant);
$admin = $this->createAdminAppUser($tenant);
Sanctum::actingAs($admin);
$food = CatalogItem::query()
->where('tenant_code', $tenant->codigo)
->where('slug', 'comida')
->with([
'itemAttributes.attribute.options',
'variants.definitions.itemAttribute.attribute.options',
'variants.eventDates',
'variants.eventDate',
])
->firstOrFail();
$historicalVariant = $food->variants->first(function ($variant): bool {
return $variant->selectedEventDates()->first()?->date->format('d/m') === '12/10'
&& $variant->selectionValues()->get('horario') === 'Cena';
});
$this->assertNotNull($historicalVariant);
$historicalService = $historicalVariant->selectionValues()->get('servicio');
$ticket = Ticket::query()->create([
'tenant_code' => $tenant->codigo,
'ticket' => (string) Str::uuid(),
'user_id' => $admin->id,
'source_catalog_item_id' => $food->id,
'source_variant_id' => $historicalVariant->id,
]);
$catalogService = app(CatalogService::class);
foreach ($food->variants as $variant) {
$catalogService->deleteVariant($variant);
}
$this->assertTrue(CatalogItem::withTrashed()->findOrFail($food->id)->trashed());
$response = $this->getJson('/api/v1/adminapp/forms/tickets-filter')->assertOk();
$foodCategory = collect($response->json('data.fields.0.options'))->firstWhere('value', 'comidas');
$products = collect($foodCategory['children'][0]['options']);
$this->assertCount(1, $products);
$this->assertSame('Cena', $products->first()['label']);
$this->assertSame(
[$historicalService],
collect($products->first()['children'][0]['options'])->pluck('label')->all(),
);
$this->getJson('/api/v1/adminapp/tenant/tickets?'.http_build_query([
'category' => 'comidas',
'product' => $products->first()['value'],
'type' => $historicalService,
'date' => '2026-10-12',
]))
->assertOk()
->assertJsonCount(1, 'data')
->assertJsonPath('data.0.id', $ticket->id)
->assertJsonPath('data.0.values.category', 'Comida')
->assertJsonPath('data.0.values.product', 'Cena')
->assertJsonPath('data.0.values.type', $historicalService)
->assertJsonPath('data.0.values.date', '12/10')
->assertJsonPath('data.0.values.size', '-');
}
private function createFiestaFutbolInfantilTenant(): Tenant
{
$tenant = $this->createTenant('fiesta_futbol_infantil');
$this->seed([AttributeSeeder::class, FiestaFutbolInfantilProductSeeder::class]);
return $tenant->refresh();
}
/** @return list<array<string, mixed>> */
private function commonColumns(): array
{
return [
['key' => 'order_number', 'label' => 'N° de orden', 'type' => 'order_number', 'sortable' => true, 'sort_param' => 'order_number', 'width' => '11%'],
['key' => 'product', 'label' => 'Producto', 'type' => 'text', 'sortable' => true, 'sort_param' => 'product', 'width' => '15%'],
['key' => 'amount', 'label' => 'Importe', 'type' => 'currency', 'sortable' => true, 'sort_param' => 'amount', 'width' => '10%'],
['key' => 'client', 'label' => 'Cliente', 'type' => 'text', 'sortable' => true, 'sort_param' => 'client', 'width' => '15%'],
['key' => 'id', 'label' => 'ID', 'type' => 'text', 'sortable' => true, 'sort_param' => 'id', 'width' => '8%'],
['key' => 'status', 'label' => 'Estado', 'type' => 'status', 'sortable' => true, 'sort_param' => 'status', 'width' => '8%'],
['key' => 'scanned_by', 'label' => 'Escaneado por', 'type' => 'text', 'sortable' => true, 'sort_param' => 'scanned_by', 'width' => '11%'],
];
}
private function createTenant(string $code): Tenant
{
$headerLogo = $this->createAttachment("{$code}-header.png");
$footerLogo = $this->createAttachment("{$code}-footer.png");
return Tenant::query()->create([
'codigo' => $code,
'nombre' => ucfirst($code),
'dominio' => "{$code}.test",
'primary_color' => '#111111',
'secondary_color' => '#222222',
'danger_color' => '#333333',
'success_color' => '#444444',
'header_bg_color' => '#ffffff',
'footer_bg_color' => '#ffffff',
'header_logo_id' => $headerLogo->id,
'footer_logo_id' => $footerLogo->id,
]);
}
private function createAttachment(string $filename): Attachment
{
return Attachment::query()->create([
'path' => "tests/{$filename}",
'filename' => $filename,
'type' => AttachmentType::Image,
'mime_type' => 'image/png',
]);
}
private function createAdminAppUser(Tenant $tenant): User
{
return User::factory()->create([
'rol_codigo' => RoleCode::AdminApp->value,
'tenant_codigo' => $tenant->codigo,
]);
}
private function grantTicketsMenu(Tenant $tenant): void
{
$menu = Menu::query()->create([
'code' => 'adminapp.tickets',
'label' => 'Tickets',
'route' => '/admin/tickets',
]);
$tenant->menues()->attach($menu->code);
}
}

View File

@@ -1,155 +0,0 @@
<?php
namespace Tests\Feature\Forms;
use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Auth\Models\User;
use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Tenant\Models\Tenant;
use Database\Seeders\AttributeSeeder;
use Database\Seeders\AuthorizationSeeder;
use Database\Seeders\FiestaFutbolInfantilProductSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;
class AdminAppTicketFormControllerTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
$this->seed(AuthorizationSeeder::class);
}
public function test_authentication_is_required(): void
{
$this->getJson('/api/v1/adminapp/forms/fiesta-futbol-infantil/ticket')
->assertUnauthorized();
}
public function test_it_returns_nested_ticket_options_using_the_frontend_presentation_mapping(): void
{
$headerLogo = $this->createAttachment('header.png');
$footerLogo = $this->createAttachment('footer.png');
$tenant = Tenant::query()->create([
'codigo' => 'fiesta_futbol_infantil',
'nombre' => 'Fiesta Fútbol Infantil',
'dominio' => 'fiesta-futbol-infantil.test',
'primary_color' => '#00973F',
'secondary_color' => '#A0A0A0',
'danger_color' => '#FF8888',
'success_color' => '#198754',
'header_bg_color' => '#ffffff',
'footer_bg_color' => '#015327',
'header_logo_id' => $headerLogo->id,
'footer_logo_id' => $footerLogo->id,
]);
$this->seed([AttributeSeeder::class, FiestaFutbolInfantilProductSeeder::class]);
Sanctum::actingAs(User::factory()->create([
'rol_codigo' => RoleCode::AdminApp->value,
'tenant_codigo' => $tenant->codigo,
]));
$response = $this->getJson('/api/v1/adminapp/forms/fiesta-futbol-infantil/ticket')
->assertOk()
->assertExactJson([
'data' => [
'statuses' => [
['value' => 'active', 'label' => 'Activo'],
['value' => 'used', 'label' => 'Usado'],
['value' => 'expired', 'label' => 'Vencido'],
],
'categories' => [
[
'value' => 'entradas',
'label' => 'Entradas',
'products' => [[
'value' => 'abono',
'label' => 'Abono',
'types' => [],
]],
],
[
'value' => 'alojamientos',
'label' => 'Camping',
'products' => [
['value' => 'Carpa', 'label' => 'Carpa', 'types' => []],
['value' => 'Motorhome', 'label' => 'Motorhome', 'types' => []],
],
],
[
'value' => 'comidas',
'label' => 'Comida',
'products' => [
[
'value' => (string) $tenant->eventDates[0]->id,
'label' => '09/10',
'types' => [
['value' => 'Desayuno', 'label' => 'Desayuno'],
['value' => 'Almuerzo', 'label' => 'Almuerzo'],
['value' => 'Cena', 'label' => 'Cena'],
],
],
[
'value' => (string) $tenant->eventDates[1]->id,
'label' => '10/10',
'types' => [
['value' => 'Desayuno', 'label' => 'Desayuno'],
['value' => 'Almuerzo', 'label' => 'Almuerzo'],
['value' => 'Cena', 'label' => 'Cena'],
],
],
[
'value' => (string) $tenant->eventDates[2]->id,
'label' => '11/10',
'types' => [
['value' => 'Desayuno', 'label' => 'Desayuno'],
['value' => 'Almuerzo', 'label' => 'Almuerzo'],
['value' => 'Cena', 'label' => 'Cena'],
],
],
[
'value' => (string) $tenant->eventDates[3]->id,
'label' => '12/10',
'types' => [
['value' => 'Desayuno', 'label' => 'Desayuno'],
['value' => 'Almuerzo', 'label' => 'Almuerzo'],
['value' => 'Cena', 'label' => 'Cena'],
],
],
],
],
[
'value' => 'merchandising',
'label' => 'Merchandising',
'products' => [[
'value' => 'camiseta',
'label' => 'Camiseta',
'types' => [
['value' => 'Verde', 'label' => 'Verde'],
['value' => 'Blanco', 'label' => 'Blanco'],
],
]],
],
],
],
]);
$response->assertJsonMissingPath('data.categories.0.products.0.category');
}
private function createAttachment(string $filename): Attachment
{
return Attachment::query()->create([
'path' => "tests/{$filename}",
'filename' => $filename,
'type' => AttachmentType::Image,
'mime_type' => 'image/png',
]);
}
}

View File

@@ -60,9 +60,9 @@ class TelepagosWebhookTest extends TestCase
->assertJsonValidationErrors(['transfer_payer_dni']);
}
public function test_transfer_payment_intent_persists_data_without_extending_checkout_expiration(): void
public function test_transfer_payment_intent_persists_transfer_payer_dni_without_replacing_customer_dni(): void
{
config()->set('purchase.checkout_expiration_minutes', 30);
config()->set('purchase.payment_expiration_minutes.transfer', 60);
$now = now()->startOfSecond();
$this->travelTo($now);
@@ -106,7 +106,7 @@ class TelepagosWebhookTest extends TestCase
$this->assertDatabaseHas('stock_reservations', [
'id' => $purchase->stock_reservation_id,
'status' => 'active',
'expires_at' => $now->copy()->addMinutes(30)->toDateTimeString(),
'expires_at' => $now->copy()->addMinutes(60)->toDateTimeString(),
]);
$this->travelBack();
@@ -341,9 +341,8 @@ class TelepagosWebhookTest extends TestCase
->firstOrFail();
$this->assertEqualsCanonicalizing(
[$firstPurchase->id, $secondPurchase->id, $thirdPurchase->id],
$payment->candidates()->pluck('compra_id')->all(),
$payment->matched_purchase_ids,
);
$this->assertSame(3, $payment->candidates()->where('match_reason', 'ambiguous_exact_match')->count());
$this->assertDatabaseHas('compras', [
'id' => $firstPurchase->id,
'status' => Purchase::STATUS_PENDING_PAYMENT,
@@ -358,183 +357,6 @@ class TelepagosWebhookTest extends TestCase
]);
}
public function test_transfer_webhook_records_near_amount_only_with_exact_dni_or_exact_amount_with_different_dni(): void
{
config(['purchase.transfer_candidate_amount_tolerance_percentage' => 5]);
$tenant = $this->createTenant('candidates', 'Candidates', 'candidates.com.ar');
$this->configureTelepagosIntegration($tenant);
$nearAmountVariant = $this->createVariantForTenant('candidates', 10, '52.00', 'near');
$exactAmountVariant = $this->createVariantForTenant('candidates', 10, '50.00', 'exact');
$distanceTwoExactAmountVariant = $this->createVariantForTenant('candidates', 10, '50.00', 'distance-two');
$farExactAmountVariant = $this->createVariantForTenant('candidates', 10, '50.00', 'far-exact');
$nearAmountDifferentDniVariant = $this->createVariantForTenant('candidates', 10, '51.00', 'near-other-dni');
$outsideRangeVariant = $this->createVariantForTenant('candidates', 10, '100.00', 'outside');
$nearAmountPurchase = $this->createPendingTransferPurchase(
$tenant,
User::factory()->create()->id,
$nearAmountVariant->id,
1,
'12345678',
);
$exactAmountDifferentDniPurchase = $this->createPendingTransferPurchase(
$tenant,
User::factory()->create()->id,
$exactAmountVariant->id,
1,
'12345687',
);
$farExactAmountDifferentDniPurchase = $this->createPendingTransferPurchase(
$tenant,
User::factory()->create()->id,
$farExactAmountVariant->id,
1,
'87654321',
);
$distanceTwoExactAmountPurchase = $this->createPendingTransferPurchase(
$tenant,
User::factory()->create()->id,
$distanceTwoExactAmountVariant->id,
1,
'12345087',
);
$nearAmountDifferentDniPurchase = $this->createPendingTransferPurchase(
$tenant,
User::factory()->create()->id,
$nearAmountDifferentDniVariant->id,
1,
'87654321',
);
$outsideRangePurchase = $this->createPendingTransferPurchase(
$tenant,
User::factory()->create()->id,
$outsideRangeVariant->id,
1,
'12345678',
);
Http::fake([
'https://api.telepagos.com.ar/v2/auth/token' => Http::response([
'status' => 'ok',
'token' => 'test-token',
'expires_at' => now()->addHour()->toIso8601String(),
]),
'https://api.telepagos.com.ar/v2/payment/cashin/candidates' => Http::response([
'status' => 'ok',
'data' => [
'amount' => 50,
'operation_id' => 1,
'transaction_id' => 'tx-candidates',
'buyer' => ['cuit' => '20123456789'],
],
]),
]);
$this->postJson('/api/webhooks/telepagos/candidates', ['id' => 'candidates'])
->assertOk()
->assertJsonPath('status', 'success');
$payment = TelepagosPayment::query()
->where('transaction_id', 'tx-candidates')
->firstOrFail();
$this->assertNull($payment->compra_id);
$this->assertEqualsCanonicalizing([
$nearAmountPurchase->id,
$exactAmountDifferentDniPurchase->id,
$distanceTwoExactAmountPurchase->id,
], $payment->candidates()->pluck('compra_id')->all());
$this->assertDatabaseHas('telepagos_payment_candidates', [
'telepagos_payment_id' => $payment->id,
'compra_id' => $nearAmountPurchase->id,
'dni_matches' => true,
'dni_distance' => 0,
'payment_dni' => '12345678',
'purchase_dni' => '12345678',
'amount_matches' => false,
'payment_amount' => 50,
'purchase_amount' => 52,
'amount_difference' => 2,
'match_reason' => 'exact_dni_near_amount',
'confidence' => 'high',
]);
$this->assertDatabaseHas('telepagos_payment_candidates', [
'telepagos_payment_id' => $payment->id,
'compra_id' => $exactAmountDifferentDniPurchase->id,
'dni_matches' => false,
'dni_distance' => 1,
'payment_dni' => '12345678',
'purchase_dni' => '12345687',
'amount_matches' => true,
'payment_amount' => 50,
'purchase_amount' => 50,
'amount_difference' => 0,
'match_reason' => 'exact_amount_near_dni',
'confidence' => 'medium',
]);
$this->assertDatabaseHas('telepagos_payment_candidates', [
'telepagos_payment_id' => $payment->id,
'compra_id' => $distanceTwoExactAmountPurchase->id,
'dni_matches' => false,
'dni_distance' => 2,
'payment_dni' => '12345678',
'purchase_dni' => '12345087',
'amount_matches' => true,
'match_reason' => 'exact_amount_near_dni',
]);
$this->assertDatabaseMissing('telepagos_payment_candidates', [
'telepagos_payment_id' => $payment->id,
'compra_id' => $farExactAmountDifferentDniPurchase->id,
]);
$this->assertDatabaseMissing('telepagos_payment_candidates', [
'telepagos_payment_id' => $payment->id,
'compra_id' => $nearAmountDifferentDniPurchase->id,
]);
$this->assertDatabaseMissing('telepagos_payment_candidates', [
'telepagos_payment_id' => $payment->id,
'compra_id' => $outsideRangePurchase->id,
]);
$this->assertSame(Purchase::STATUS_PENDING_PAYMENT, $nearAmountPurchase->fresh()->status);
$this->assertSame(Purchase::STATUS_PENDING_PAYMENT, $exactAmountDifferentDniPurchase->fresh()->status);
$higherPriorityPayment = TelepagosPayment::query()->create([
'cuit_buyer' => '20123456789',
'amount' => 52,
'operation_id' => 1,
'transaction_id' => 'tx-primary-candidate',
]);
$higherPriorityPayment->candidates()->create([
'compra_id' => $nearAmountPurchase->id,
'dni_matches' => true,
'dni_distance' => 0,
'payment_dni' => '12345678',
'purchase_dni' => '12345678',
'amount_matches' => true,
'payment_amount' => 52,
'purchase_amount' => 52,
'amount_difference' => 0,
'match_reason' => 'ambiguous_exact_match',
'confidence' => 'exact',
]);
app(CheckoutService::class)->submitForReview($nearAmountPurchase->fresh());
$buyer = User::query()->findOrFail($nearAmountPurchase->user_id);
$this->actingAs($buyer, 'sanctum')
->getJson("/api/tenants/candidates/compras/{$nearAmountPurchase->id}")
->assertOk()
->assertJsonPath('data.status', Purchase::STATUS_IN_REVIEW)
->assertJsonPath('data.payment_verification.status', 'candidate')
->assertJsonPath('data.payment_verification.candidate_count', 2)
->assertJsonPath('data.payment_verification.primary.reason', 'ambiguous_exact_match')
->assertJsonPath('data.payment_verification.primary.amount_difference', '0.00')
->assertJsonPath('data.payment_verification.primary.confidence', 'exact')
->assertJsonPath('data.payment_verification.reasons.0', 'ambiguous_exact_match')
->assertJsonPath('data.payment_verification.reasons.1', 'exact_dni_near_amount');
}
public function test_webhook_confirms_a_purchase_with_tickets_enabled(): void
{
$tenant = $this->createTenant('expired-ticket', 'Expired Ticket', 'expired-ticket.com.ar');

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