57 Commits

Author SHA1 Message Date
6fc6ed1fac feat: refactor cart and purchase handling to support polymorphic buyable types and improve code readability 2026-07-16 09:55:38 -03:00
c05206cc51 feat: refactor cart item handling to use mapped buyable types and improve method signatures 2026-07-16 09:19:38 -03:00
480ee70393 feat: refactor cart and bundle handling to support Buyable interface for improved flexibility 2026-07-16 09:19:03 -03:00
ceb1e2b04a feat: implement Stockable interface and methods for Bundle and ProductVariant models 2026-07-16 09:11:37 -03:00
1d56d27350 feat: implement Bundle and BundleItem models, migrations, and polymorphic relationships for cart and purchase items 2026-07-16 09:11:00 -03:00
18c80b075b feat: Update product seeder to include inventory policy and improve code readability 2026-07-16 09:07:05 -03:00
10157d7c63 feat: Implement inventory policy for product variants
- Introduced InventoryPolicy enum to manage tracked and unlimited inventory types.
- Updated ProductVariant model to include inventory_policy and cantidad_vendida attributes.
- Modified addItem and updateItem methods in Cart to check available quantity based on inventory policy.
- Added migration to include inventory_policy and cantidad_vendida in productos_variantes table.
- Enhanced tests to validate inventory behavior for both tracked and unlimited policies.
- Updated various request and resource classes to handle new inventory fields.
2026-07-16 08:36:59 -03:00
716d8e447c feat: add Fecha attribute seeder and integrate FiestaFutbolInfantilProductSeeder 2026-07-15 14:21:19 -03:00
cababe1a43 feat: add ticket fields to Product and ProductVariant models, requests, and resources 2026-07-14 15:19:53 -03:00
0e9f7faaf1 feat: update CatalogController to return JsonResponse instead of AnonymousResourceCollection 2026-07-14 15:04:01 -03:00
13bdb436ed feat: implement FeaturedGroup and FeaturedVariant controllers, models, requests, resources, and routes for managing featured groups and variants 2026-07-14 14:58:28 -03:00
c2efec8906 feat: implement FeaturedVariant and CatalogController for managing featured variants and catalog display 2026-07-14 14:55:48 -03:00
299a462283 feat: implement FeaturedGroup and FeaturedProduct controllers, requests, resources, and routes for managing featured products 2026-07-14 14:21:04 -03:00
38f36a3a23 feat: add hero background image functionality to Tenant model and related requests, resources, and seeder 2026-07-14 13:58:49 -03:00
b4b888adef feat: add FeaturedGroup and FeaturedProduct models with migrations for database structure 2026-07-14 13:30:07 -03:00
3afef63fc7 feat: update MenuSeeder to dynamically fetch menu codes and adjust tenant associations 2026-07-14 12:10:39 -03:00
e325c49a89 feat: enhance tenant resource to include menues and update seeder for new menu routes 2026-07-14 11:44:57 -03:00
9c7d025258 feat: implement Menu management with CRUD operations and database migrations 2026-07-14 11:31:30 -03:00
ba58bf79f8 feat: add 'fiesta_futbol_infantil' tenant with associated images and configurations 2026-07-14 11:25:16 -03:00
2910d3f929 feat: add hero_config and event_config to Tenant model with validation and migration 2026-07-14 11:08:59 -03:00
ca4fea6bcd feat: enhance purchase detail handling to support cart items and improve resource structure 2026-07-08 15:50:40 -03:00
73bf285bad feat: implement profile update functionality with validation and password handling 2026-07-08 12:10:23 -03:00
b273b2866f feat: add status filter to purchase index query for enhanced data retrieval 2026-07-08 11:32:56 -03:00
05a92b7ec3 feat: update purchase query in TelepagosWebhookService to handle multiple statuses and normalize DNI format 2026-07-08 10:05:49 -03:00
f23029e785 feat: enhance integration setup process with error handling and validation 2026-07-08 09:00:42 -03:00
f18fbc8147 feat: rename finalize methods to complete for consistency in purchase processing 2026-07-07 15:36:07 -03:00
c276ccd311 feat: refactor purchase status handling and add finalize endpoint for purchases 2026-07-07 15:33:29 -03:00
786b4eb6a9 feat: add MergeGuestCartMiddleware to tenant route for enhanced cart handling 2026-07-07 12:55:07 -03:00
eca3b01083 feat: update Telepagos webhook and payment intent logic for improved data handling 2026-07-07 11:11:21 -03:00
7b2a741884 feat: add total field to purchases and update related logic for payment processing 2026-07-07 10:16:28 -03:00
362e888e46 feat: update .gitignore to include .env.testing and enhance phpunit.xml with additional environment variables 2026-07-07 09:25:39 -03:00
92458e217e feat: enhance Telepagos webhook handling for transferencia and QR operations with improved purchase matching logic 2026-07-07 08:57:27 -03:00
4edda0bfd8 feat: add default entity value for payment account information in paymentIntent method 2026-07-06 16:53:58 -03:00
2c2cf45f78 feat: remove BankAccount domain and related functionality, including controller, model, requests, routes, and tests 2026-07-06 16:53:45 -03:00
1fcb3129ea feat: enhance Telepagos integration with token refresh handling and refactor CheckoutService to use updateOrCreate for purchases 2026-07-06 16:24:00 -03:00
3703ae9bcf feat: add getTotalAmount method to Cart and refactor Purchase model to utilize it 2026-07-06 15:26:41 -03:00
c19e00987e feat: implement MergeGuestCartMiddleware to merge guest cart with user cart upon authentication 2026-07-06 14:57:19 -03:00
7be2221bb8 feat: update MeController to return user data as UserResource 2026-07-06 14:30:15 -03:00
dc32eb9bee feat: enhance checkout process with cart integration and stock confirmation 2026-07-06 14:06:25 -03:00
6bda3bf013 feat: add payment intent handling in PurchaseController with validation and QR generation 2026-07-06 11:47:04 -03:00
3731cd67fe feat: implement Telepagos webhook handling with request validation and service integration 2026-07-06 09:57:45 -03:00
403caf77f5 feat: add getCashinDetails method to TelepagosIntegrationService and corresponding tests 2026-07-06 09:01:45 -03:00
04b2bb0b2a feat: add QR code generation and response handling to TelepagosIntegrationService with logging for errors 2026-07-06 08:58:14 -03:00
1af5b1d7ed feat: add client method to BaseIntegrationService for pre-configured HTTP client and implement test for client functionality 2026-07-06 08:50:52 -03:00
387e136707 feat: update environment configuration for production and enhance TelepagosIntegrationService with token caching and error handling 2026-07-06 08:48:40 -03:00
9a1e36337d feat: implement BaseIntegrationService and TelepagosIntegrationService with integration handling and header generation 2026-07-06 08:40:32 -03:00
0c28302f84 refactor: remove unused 'payment_status' field from StorePurchaseRequest rules 2026-07-06 08:35:52 -03:00
0cb1c37566 refactor: remove PaymentProviderInterface and TelepagosProvider, simplify CheckoutService and related tests 2026-07-03 16:55:11 -03:00
057e6757dc feat: add customer details fields to Purchase model and request, implement checkout process with cart clearing 2026-07-03 16:48:31 -03:00
6d066beea3 feat: add optional 'dni' and 'telefono' fields to User model and registration process 2026-07-03 16:24:56 -03:00
1d94ff8885 feat: implement checkout service and payment processing integration 2026-07-03 15:37:26 -03:00
ee3be8d550 feat: configure integration secret and update seeder for Telepagos integration 2026-07-03 15:35:31 -03:00
21b8fa5f35 feat: add 'url' field to Integration model and update related requests and seeder 2026-07-03 14:45:05 -03:00
3887a4fcba feat: implement integration management with CRUD operations and routes for tenant integration 2026-07-03 14:44:18 -03:00
0d4c6a4492 feat: implement BankAccount management with CRUD operations and routes for tenant selection 2026-07-03 13:58:21 -03:00
c1b7b12fe1 feat: add endpoint to retrieve selected bank account for a tenant and update routes with authentication 2026-07-03 13:54:31 -03:00
b1e40b3430 feat: implement BankAccount management with CRUD operations and selection for tenants 2026-07-03 13:43:32 -03:00
132 changed files with 6543 additions and 292 deletions

View File

@@ -1,9 +1,10 @@
APP_NAME=Laravel
APP_ENV=local
APP_ENV=production
APP_KEY=
APP_DEBUG=true
APP_DEBUG=false
APP_URL=http://localhost
FRONTEND_URL=http://localhost:4200
INTEGRATION_SECRET=
APP_LOCALE=en
APP_FALLBACK_LOCALE=en

1
.gitignore vendored
View File

@@ -1,6 +1,7 @@
*.log
.DS_Store
.env
.env.testing
.env.backup
.env.production
.phpactor.json

View File

@@ -898,7 +898,7 @@
}
],
"url": {
"raw": "{{base_url}}/api/tenants/{{tenant_codigo}}/product-variants",
"raw": "{{base_url}}/api/tenants/{{tenant_codigo}}/productos/{{producto_id}}/variants",
"host": [
"{{base_url}}"
],
@@ -906,7 +906,9 @@
"api",
"tenants",
"{{tenant_codigo}}",
"product-variants"
"productos",
"{{producto_id}}",
"variants"
]
}
},
@@ -930,10 +932,10 @@
],
"body": {
"mode": "raw",
"raw": "{\n \"producto_id\": {{producto_id}},\n \"slug\": \"remera-basica-blanca-m\",\n \"nombre\": \"Remera Basica Blanca - Talle M\",\n \"stock\": 8,\n \"descripcion\": \"Variante de prueba\",\n \"precio\": 26999,\n \"definitions\": [\n {\n \"products_attribute_id\": {{color_product_attribute_id}},\n \"value\": \"Blanco\"\n },\n {\n \"products_attribute_id\": {{talle_product_attribute_id}},\n \"value\": \"M\"\n }\n ],\n \"images\": []\n}"
"raw": "{\n \"stock\": 8,\n \"definitions\": [\n {\n \"products_attribute_id\": {{color_product_attribute_id}},\n \"value\": \"Blanco\"\n },\n {\n \"products_attribute_id\": {{talle_product_attribute_id}},\n \"value\": \"M\"\n }\n ],\n \"images\": []\n}"
},
"url": {
"raw": "{{base_url}}/api/tenants/{{tenant_codigo}}/product-variants",
"raw": "{{base_url}}/api/tenants/{{tenant_codigo}}/productos/{{producto_id}}/variants",
"host": [
"{{base_url}}"
],
@@ -941,7 +943,9 @@
"api",
"tenants",
"{{tenant_codigo}}",
"product-variants"
"productos",
"{{producto_id}}",
"variants"
]
}
},
@@ -959,7 +963,7 @@
}
],
"url": {
"raw": "{{base_url}}/api/tenants/{{tenant_codigo}}/product-variants/{{product_variant_id}}",
"raw": "{{base_url}}/api/tenants/{{tenant_codigo}}/productos/{{producto_id}}/variants/{{product_variant_id}}",
"host": [
"{{base_url}}"
],
@@ -967,7 +971,9 @@
"api",
"tenants",
"{{tenant_codigo}}",
"product-variants",
"productos",
"{{producto_id}}",
"variants",
"{{product_variant_id}}"
]
}
@@ -992,10 +998,10 @@
],
"body": {
"mode": "raw",
"raw": "{\n \"slug\": \"remera-basica-blanca-m\",\n \"nombre\": \"Remera Basica Blanca - Talle M Updated\",\n \"stock\": 12,\n \"descripcion\": \"Variante actualizada\",\n \"precio\": 27999,\n \"definitions\": [\n {\n \"products_attribute_id\": {{color_product_attribute_id}},\n \"value\": \"Blanco\"\n },\n {\n \"products_attribute_id\": {{talle_product_attribute_id}},\n \"value\": \"M\"\n }\n ],\n \"images\": []\n}"
"raw": "{\n \"stock\": 12,\n \"definitions\": [\n {\n \"products_attribute_id\": {{color_product_attribute_id}},\n \"value\": \"Blanco\"\n },\n {\n \"products_attribute_id\": {{talle_product_attribute_id}},\n \"value\": \"M\"\n }\n ],\n \"images\": []\n}"
},
"url": {
"raw": "{{base_url}}/api/tenants/{{tenant_codigo}}/product-variants/{{product_variant_id}}",
"raw": "{{base_url}}/api/tenants/{{tenant_codigo}}/productos/{{producto_id}}/variants/{{product_variant_id}}",
"host": [
"{{base_url}}"
],
@@ -1003,7 +1009,9 @@
"api",
"tenants",
"{{tenant_codigo}}",
"product-variants",
"productos",
"{{producto_id}}",
"variants",
"{{product_variant_id}}"
]
}
@@ -1022,7 +1030,7 @@
}
],
"url": {
"raw": "{{base_url}}/api/tenants/{{tenant_codigo}}/product-variants/{{product_variant_id}}",
"raw": "{{base_url}}/api/tenants/{{tenant_codigo}}/productos/{{producto_id}}/variants/{{product_variant_id}}",
"host": [
"{{base_url}}"
],
@@ -1030,7 +1038,9 @@
"api",
"tenants",
"{{tenant_codigo}}",
"product-variants",
"productos",
"{{producto_id}}",
"variants",
"{{product_variant_id}}"
]
}
@@ -1357,7 +1367,7 @@
],
"body": {
"mode": "raw",
"raw": "{\n \"status\": \"pending\",\n \"payment_status\": \"pending\",\n \"payment_method\": \"cash\",\n \"items\": [\n {\n \"producto_variante_id\": {{product_variant_id}},\n \"cantidad\": 1\n }\n ]\n}"
"raw": "{\n \"cart_id\": {{cart_id}},\n \"dni\": \"12345678\",\n \"telefono\": \"+54 9 341 555-4321\",\n \"nombre_apellido\": \"Juan Perez\",\n \"email\": \"juan.perez@example.com\"\n}"
},
"url": {
"raw": "{{base_url}}/api/tenants/{{tenant_codigo}}/compras",
@@ -1403,6 +1413,454 @@
}
]
},
{
"name": "Bank Accounts",
"item": [
{
"name": "List Bank Accounts",
"request": {
"method": "GET",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
}
],
"url": {
"raw": "{{base_url}}/api/tenants/{{tenant_codigo}}/bank-accounts",
"host": [
"{{base_url}}"
],
"path": [
"api",
"tenants",
"{{tenant_codigo}}",
"bank-accounts"
]
}
},
"response": []
},
{
"name": "Create Bank Account",
"request": {
"method": "POST",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
},
{
"key": "Content-Type",
"value": "application/json",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"titular\": \"Ada Lovelace\",\n \"entidad\": \"Banco Demo\",\n \"alias\": \"ada.demo.alias\",\n \"cvu\": \"0000003100000000000001\"\n}"
},
"url": {
"raw": "{{base_url}}/api/tenants/{{tenant_codigo}}/bank-accounts",
"host": [
"{{base_url}}"
],
"path": [
"api",
"tenants",
"{{tenant_codigo}}",
"bank-accounts"
]
}
},
"response": []
},
{
"name": "Show Selected Bank Account",
"request": {
"method": "GET",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
}
],
"url": {
"raw": "{{base_url}}/api/tenants/{{tenant_codigo}}/bank-accounts/selected",
"host": [
"{{base_url}}"
],
"path": [
"api",
"tenants",
"{{tenant_codigo}}",
"bank-accounts",
"selected"
]
}
},
"response": []
},
{
"name": "Show Bank Account",
"request": {
"method": "GET",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
}
],
"url": {
"raw": "{{base_url}}/api/tenants/{{tenant_codigo}}/bank-accounts/{{bank_account_id}}",
"host": [
"{{base_url}}"
],
"path": [
"api",
"tenants",
"{{tenant_codigo}}",
"bank-accounts",
"{{bank_account_id}}"
]
}
},
"response": []
},
{
"name": "Update Bank Account",
"request": {
"method": "PATCH",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
},
{
"key": "Content-Type",
"value": "application/json",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"titular\": \"Ada Lovelace Updated\",\n \"entidad\": \"Banco Demo Updated\",\n \"alias\": \"ada.demo.updated\",\n \"cvu\": \"0000003100000000000002\"\n}"
},
"url": {
"raw": "{{base_url}}/api/tenants/{{tenant_codigo}}/bank-accounts/{{bank_account_id}}",
"host": [
"{{base_url}}"
],
"path": [
"api",
"tenants",
"{{tenant_codigo}}",
"bank-accounts",
"{{bank_account_id}}"
]
}
},
"response": []
},
{
"name": "Select Bank Account",
"request": {
"method": "POST",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
}
],
"url": {
"raw": "{{base_url}}/api/tenants/{{tenant_codigo}}/bank-accounts/{{bank_account_id}}/select",
"host": [
"{{base_url}}"
],
"path": [
"api",
"tenants",
"{{tenant_codigo}}",
"bank-accounts",
"{{bank_account_id}}",
"select"
]
}
},
"response": []
},
{
"name": "Delete Bank Account",
"request": {
"method": "DELETE",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
}
],
"url": {
"raw": "{{base_url}}/api/tenants/{{tenant_codigo}}/bank-accounts/{{bank_account_id}}",
"host": [
"{{base_url}}"
],
"path": [
"api",
"tenants",
"{{tenant_codigo}}",
"bank-accounts",
"{{bank_account_id}}"
]
}
},
"response": []
}
]
},
{
"name": "Integrations",
"item": [
{
"name": "List Integrations",
"request": {
"method": "GET",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
}
],
"url": {
"raw": "{{base_url}}/api/integrations",
"host": [
"{{base_url}}"
],
"path": [
"api",
"integrations"
]
}
},
"response": []
},
{
"name": "Create Integration",
"request": {
"method": "POST",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
},
{
"key": "Content-Type",
"value": "application/json",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"integration_code\": \"mercadopago\",\n \"name\": \"Mercado Pago\",\n \"url\": \"https://api.mercadopago.com\",\n \"integration_data_schema\": {\n \"access_token\": \"required|string\",\n \"public_key\": \"nullable|string\"\n }\n}"
},
"url": {
"raw": "{{base_url}}/api/integrations",
"host": [
"{{base_url}}"
],
"path": [
"api",
"integrations"
]
}
},
"response": []
},
{
"name": "Show Integration",
"request": {
"method": "GET",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
}
],
"url": {
"raw": "{{base_url}}/api/integrations/{{integration_id}}",
"host": [
"{{base_url}}"
],
"path": [
"api",
"integrations",
"{{integration_id}}"
]
}
},
"response": []
},
{
"name": "Update Integration",
"request": {
"method": "PUT",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
},
{
"key": "Content-Type",
"value": "application/json",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"integration_code\": \"mercadopago\",\n \"name\": \"Mercado Pago Updated\",\n \"url\": \"https://api.mercadopago.com\",\n \"integration_data_schema\": {\n \"access_token\": \"required|string\",\n \"public_key\": \"nullable|string\"\n }\n}"
},
"url": {
"raw": "{{base_url}}/api/integrations/{{integration_id}}",
"host": [
"{{base_url}}"
],
"path": [
"api",
"integrations",
"{{integration_id}}"
]
}
},
"response": []
},
{
"name": "Delete Integration",
"request": {
"method": "DELETE",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
}
],
"url": {
"raw": "{{base_url}}/api/integrations/{{integration_id}}",
"host": [
"{{base_url}}"
],
"path": [
"api",
"integrations",
"{{integration_id}}"
]
}
},
"response": []
}
]
},
{
"name": "Tenant Integrations",
"item": [
{
"name": "List Tenant Integrations",
"request": {
"method": "GET",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
}
],
"url": {
"raw": "{{base_url}}/api/{{tenant_codigo}}/integrations",
"host": [
"{{base_url}}"
],
"path": [
"api",
"{{tenant_codigo}}",
"integrations"
]
}
},
"response": []
},
{
"name": "Show Tenant Integration",
"request": {
"method": "GET",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
}
],
"url": {
"raw": "{{base_url}}/api/{{tenant_codigo}}/integrations/{{integration_code}}",
"host": [
"{{base_url}}"
],
"path": [
"api",
"{{tenant_codigo}}",
"integrations",
"{{integration_code}}"
]
}
},
"response": []
},
{
"name": "Configure Tenant Integration",
"request": {
"method": "POST",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
},
{
"key": "Content-Type",
"value": "application/json",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"integration_data\": {\n \"access_token\": \"APP_USR-demo-token\",\n \"public_key\": \"APP_PUBLIC-demo-key\"\n }\n}"
},
"url": {
"raw": "{{base_url}}/api/{{tenant_codigo}}/integrations/{{integration_code}}",
"host": [
"{{base_url}}"
],
"path": [
"api",
"{{tenant_codigo}}",
"integrations",
"{{integration_code}}"
]
}
},
"response": []
}
]
},
{
"name": "Storage Test",
"item": [
@@ -1628,6 +2086,21 @@
"key": "compra_id",
"value": "1",
"type": "string"
},
{
"key": "integration_id",
"value": "1",
"type": "string"
},
{
"key": "integration_code",
"value": "mercadopago",
"type": "string"
},
{
"key": "bank_account_id",
"value": "1",
"type": "string"
}
]
}

View File

@@ -2,6 +2,7 @@
namespace App\Domains\Auth\Controllers;
use App\Domains\Auth\Resources\UserResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
@@ -9,6 +10,6 @@ class MeController
{
public function __invoke(Request $request): JsonResponse
{
return response()->json($request->user());
return response()->json(UserResource::make($request->user())->resolve());
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace App\Domains\Auth\Controllers;
use App\Domains\Auth\Requests\UpdateProfileRequest;
use App\Domains\Auth\Resources\UserResource;
use App\Domains\Auth\Services\ProfileService;
use Illuminate\Http\JsonResponse;
class UpdateProfileController
{
public function __invoke(UpdateProfileRequest $request, ProfileService $service): JsonResponse
{
$user = $service->update($request->user(), $request->validated());
return response()->json(UserResource::make($user)->resolve());
}
}

View File

@@ -10,7 +10,7 @@ use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
#[Fillable(['nombre_apellido', 'email', 'password'])]
#[Fillable(['nombre_apellido', 'email', 'password', 'dni', 'telefono'])]
#[Hidden(['password', 'remember_token'])]
class User extends Authenticatable
{

View File

@@ -20,7 +20,9 @@ class RegisterUserRequest extends FormRequest
return [
'nombre_apellido' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', Rule::unique('users', 'email')],
'password' => ['required', 'string', 'confirmed'],
'password' => ['required', 'string', 'confirmed', \Illuminate\Validation\Rules\Password::min(8)->mixedCase()->symbols()],
'dni' => ['nullable', 'string', 'max:255'],
'telefono' => ['nullable', 'string', 'max:255'],
];
}
}

View File

@@ -0,0 +1,29 @@
<?php
namespace App\Domains\Auth\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class UpdateProfileRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'nombre_apellido' => ['required', 'string', 'max:255'],
'email' => [
'required',
'email',
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', \Illuminate\Validation\Rules\Password::min(8)->mixedCase()->symbols()],
];
}
}

View File

@@ -19,6 +19,8 @@ class UserResource extends JsonResource
'id' => $this->id,
'nombre_apellido' => $this->nombre_apellido,
'email' => $this->email,
'dni' => $this->dni,
'telefono' => $this->telefono,
];
}
}

View File

@@ -0,0 +1,41 @@
<?php
namespace App\Domains\Auth\Services;
use App\Domains\Auth\Models\User;
use Illuminate\Support\Facades\Hash;
class ProfileService
{
/**
* Update the given user's profile information.
*
* @param User $user
* @param array $data
* @return User
*/
public function update(User $user, array $data): User
{
// Handle password hashing if a new password is provided
if (!empty($data['password'])) {
$data['password'] = Hash::make($data['password']);
} else {
// Remove password from array if empty so we don't overwrite it with null
unset($data['password']);
}
// Standardize phone number (strip all but numbers and leading '+')
if (!empty($data['telefono'])) {
$data['telefono'] = preg_replace('/[^\+0-9]/', '', $data['telefono']);
}
// DNI is already validated as numbers only, but we can do a quick strip just in case
if (!empty($data['dni'])) {
$data['dni'] = preg_replace('/[^0-9]/', '', $data['dni']);
}
$user->update($data);
return $user;
}
}

View File

@@ -7,7 +7,7 @@ use App\Domains\Auth\Models\User;
class RegisterUserService
{
/**
* @param array{nombre_apellido: string, email: string, password: string} $data
* @param array{nombre_apellido: string, email: string, password: string, dni?: string|null, telefono?: string|null} $data
*/
public function register(array $data): User
{
@@ -15,6 +15,8 @@ class RegisterUserService
'nombre_apellido' => $data['nombre_apellido'],
'email' => $data['email'],
'password' => $data['password'],
'dni' => $data['dni'] ?? null,
'telefono' => $data['telefono'] ?? null,
]);
}
}

View File

@@ -4,9 +4,11 @@ use App\Domains\Auth\Controllers\LoginController;
use App\Domains\Auth\Controllers\LogoutController;
use App\Domains\Auth\Controllers\MeController;
use App\Domains\Auth\Controllers\RegisterController;
use App\Domains\Auth\Controllers\UpdateProfileController;
use Illuminate\Support\Facades\Route;
Route::post('/register', RegisterController::class);
Route::post('/login', LoginController::class);
Route::middleware('auth:sanctum')->post('/logout', LogoutController::class);
Route::middleware('auth:sanctum')->get('/me', MeController::class);
Route::middleware('auth:sanctum')->put('/me', UpdateProfileController::class);

View File

@@ -0,0 +1,126 @@
<?php
namespace App\Domains\Bundle\Models;
use App\Domains\Shared\Contracts\Buyable;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
#[Fillable([
'tenant_codigo',
'nombre',
'descripcion',
'precio',
])]
class Bundle extends Model implements Buyable
{
use HasFactory;
protected $table = 'bundles';
protected $appends = ['stock_tecnico'];
protected function casts(): array
{
return [
'precio' => 'decimal:2',
];
}
/**
* @return BelongsTo<Tenant, $this>
*/
public function tenant(): BelongsTo
{
return $this->belongsTo(Tenant::class, 'tenant_codigo', 'codigo');
}
/**
* @return HasMany<BundleItem, $this>
*/
public function items(): HasMany
{
return $this->hasMany(BundleItem::class, 'bundle_id');
}
public function getPrice(): float
{
return (float) $this->precio;
}
public function getName(): string
{
return $this->nombre ?? 'Bundle';
}
public function availableQuantity(): ?int
{
if ($this->items->isEmpty()) {
return 0;
}
$availableQuantities = [];
foreach ($this->items as $item) {
$variantQuantity = $item->variant?->availableQuantity();
if ($variantQuantity !== null) {
$availableQuantities[] = intdiv($variantQuantity, $item->cantidad);
}
}
return $availableQuantities === [] ? null : min($availableQuantities);
}
public function reserveStock(int $amount): void
{
if ($amount < 0) {
throw new \InvalidArgumentException('El monto a reservar debe ser positivo.');
}
foreach ($this->items as $item) {
$item->variant->reserveStock($amount * $item->cantidad);
}
}
public function decrementReservedStock(int $amount): void
{
if ($amount < 0) {
throw new \InvalidArgumentException('El monto a decrementar debe ser positivo.');
}
foreach ($this->items as $item) {
$item->variant->decrementReservedStock($amount * $item->cantidad);
}
}
public function buy(int $amount): void
{
if ($amount < 0) {
throw new \InvalidArgumentException('El monto a comprar debe ser positivo.');
}
foreach ($this->items as $item) {
$item->variant->buy($amount * $item->cantidad);
}
}
public function validateStock(): void
{
$availableQuantity = $this->availableQuantity();
if ($availableQuantity !== null && $availableQuantity <= 0) {
throw new \InvalidArgumentException('El bundle no tiene stock tecnico disponible.');
}
}
protected function stockTecnico(): Attribute
{
return Attribute::get(fn (): ?int => $this->availableQuantity());
}
}

View File

@@ -0,0 +1,46 @@
<?php
namespace App\Domains\Bundle\Models;
use App\Domains\Catalog\Models\ProductVariant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable([
'bundle_id',
'producto_variante_id',
'cantidad',
])]
class BundleItem extends Model
{
use HasFactory;
protected $table = 'bundle_items';
protected function casts(): array
{
return [
'bundle_id' => 'integer',
'producto_variante_id' => 'integer',
'cantidad' => 'integer',
];
}
/**
* @return BelongsTo<Bundle, $this>
*/
public function bundle(): BelongsTo
{
return $this->belongsTo(Bundle::class, 'bundle_id');
}
/**
* @return BelongsTo<ProductVariant, $this>
*/
public function variant(): BelongsTo
{
return $this->belongsTo(ProductVariant::class, 'producto_variante_id');
}
}

View File

@@ -2,11 +2,11 @@
namespace App\Domains\Cart\Controllers;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Cart\Requests\AddCartItemRequest;
use App\Domains\Cart\Requests\UpdateCartItemQuantityRequest;
use App\Domains\Cart\Resources\CartResource;
use App\Domains\Cart\Services\CartService;
use App\Domains\Catalog\Models\ProductVariant;
use App\Domains\Tenant\Models\Tenant;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
@@ -16,8 +16,7 @@ class CartController extends Controller
{
public function __construct(
protected CartService $cartService,
) {
}
) {}
public function show(Request $request, Tenant $tenant): CartResource
{
@@ -29,7 +28,8 @@ class CartController extends Controller
$result = $this->cartService->addItem(
$tenant,
$request,
(int) $request->validated('product_variant_id'),
$request->mappedBuyableType(),
(int) $request->validated('buyable_id'),
(int) $request->validated('cantidad'),
);
@@ -47,22 +47,22 @@ class CartController extends Controller
public function updateItemQuantity(
UpdateCartItemQuantityRequest $request,
Tenant $tenant,
ProductVariant $productVariant,
CartItem $cartItem,
): CartResource {
return CartResource::make(
$this->cartService->updateItemQuantity(
$tenant,
$request,
$productVariant->getKey(),
$cartItem->getKey(),
(int) $request->validated('cantidad'),
)
)->additional(['message' => 'Cantidad de producto actualizada.']);
}
public function removeItem(Request $request, Tenant $tenant, ProductVariant $productVariant): CartResource
public function removeItem(Request $request, Tenant $tenant, CartItem $cartItem): CartResource
{
return CartResource::make(
$this->cartService->removeItem($tenant, $request, $productVariant->getKey())
$this->cartService->removeItem($tenant, $request, $cartItem->getKey())
)->additional(['message' => 'Producto eliminado del carrito.']);
}
}

View File

@@ -0,0 +1,73 @@
<?php
namespace App\Domains\Cart\Middleware;
use App\Domains\Cart\Models\Cart;
use App\Domains\Tenant\Models\Tenant;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cookie;
use Symfony\Component\HttpFoundation\Response;
class MergeGuestCartMiddleware
{
public function handle(Request $request, Closure $next): Response
{
$guestToken = $request->cookie('guest_token');
// Resolve authenticated user optionally (from default guard or sanctum guard)
$user = $request->user() ?? Auth::guard('sanctum')->user();
$userId = $user?->getKey();
\Illuminate\Support\Facades\Log::info('MergeGuestCartMiddleware processed', [
'user_id' => $userId,
'guest_token' => $guestToken,
]);
if ($user !== null && is_string($guestToken) && $guestToken !== '') {
$tenantParam = $request->route('tenant');
$tenantCodigo = null;
if ($tenantParam instanceof Tenant) {
$tenantCodigo = $tenantParam->codigo;
} elseif (is_string($tenantParam)) {
$tenantCodigo = $tenantParam;
}
if ($tenantCodigo !== null) {
$guestCart = Cart::query()
->where('tenant_codigo', $tenantCodigo)
->where('guest_token', $guestToken)
->first();
if ($guestCart !== null && $guestCart->items()->exists()) {
$userCart = Cart::query()
->where('tenant_codigo', $tenantCodigo)
->where('user_id', $userId)
->first();
if ($userCart !== null) {
$userCart->delete();
}
$guestCart->update([
'user_id' => $userId,
'guest_token' => null,
]);
}
}
}
$response = $next($request);
if ($user !== null && is_string($guestToken) && $guestToken !== '') {
// Remove the cookie from the response since the user is authenticated.
if (method_exists($response, 'withCookie')) {
$response->withCookie(Cookie::forget('guest_token'));
}
}
return $response;
}
}

View File

@@ -3,13 +3,16 @@
namespace App\Domains\Cart\Models;
use App\Domains\Auth\Models\User;
use App\Domains\Bundle\Models\Bundle;
use App\Domains\Catalog\Models\ProductVariant;
use App\Domains\Shared\Contracts\Buyable;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
@@ -23,6 +26,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class Cart extends Model
{
use HasFactory;
use SoftDeletes;
protected $table = 'carritos';
@@ -57,7 +61,19 @@ class Cart extends Model
return $this->hasMany(CartItem::class, 'cart_id');
}
public function addItem(int $productVariantId, int $quantity): CartItem
public function getTotalAmount(): float
{
$items = $this->relationLoaded('items')
? $this->getRelation('items')
: $this->items()->with('buyable')->get();
return (float) $items->reduce(
fn (float $carry, $item): float => $carry + ($item->buyable?->getPrice() * $item->cantidad),
0.0,
);
}
public function addItem(string $buyableType, int $buyableId, int $quantity): CartItem
{
if ($quantity <= 0) {
throw ValidationException::withMessages([
@@ -65,24 +81,28 @@ class Cart extends Model
]);
}
return DB::transaction(function () use ($productVariantId, $quantity): CartItem {
$variant = $this->resolveScopedVariant($productVariantId, true);
return DB::transaction(function () use ($buyableType, $buyableId, $quantity): CartItem {
$buyable = $this->resolveScopedBuyable($buyableType, $buyableId, true);
$canonicalType = $buyable::class;
$availableQuantity = $buyable->availableQuantity();
if ($variant->stock_tecnico < $quantity) {
if ($availableQuantity !== null && $availableQuantity < $quantity) {
throw ValidationException::withMessages([
'cantidad' => "Stock insuficiente para la variante solicitada. Maximo disponible: {$variant->stock_tecnico}.",
'cantidad' => "Stock insuficiente para el producto solicitado. Maximo disponible: {$availableQuantity}.",
]);
}
/** @var CartItem|null $item */
$item = $this->items()
->where('producto_variante_id', $variant->getKey())
->where('buyable_type', $canonicalType)
->where('buyable_id', $buyable->getKey())
->lockForUpdate()
->first();
if ($item === null) {
$item = $this->items()->create([
'producto_variante_id' => $variant->getKey(),
'buyable_type' => $canonicalType,
'buyable_id' => $buyable->getKey(),
'cantidad' => $quantity,
]);
} else {
@@ -90,13 +110,13 @@ class Cart extends Model
$item->save();
}
$variant->incrementReservedStock($quantity);
$buyable->reserveStock($quantity);
return $item->fresh();
});
}
public function updateItem(int $productVariantId, int $quantity): CartItem
public function updateItem(int $cartItemId, int $quantity): CartItem
{
if ($quantity <= 0) {
throw ValidationException::withMessages([
@@ -104,18 +124,19 @@ class Cart extends Model
]);
}
return DB::transaction(function () use ($productVariantId, $quantity): CartItem {
return DB::transaction(function () use ($cartItemId, $quantity): CartItem {
/** @var CartItem $item */
$item = $this->items()
->where('producto_variante_id', $productVariantId)
->where('id', $cartItemId)
->lockForUpdate()
->firstOrFail();
$variant = $this->resolveScopedVariant($productVariantId, true);
$buyable = $this->resolveScopedBuyable($item->buyable_type, $item->buyable_id, true);
$delta = $quantity - $item->cantidad;
$availableQuantity = $buyable->availableQuantity();
if ($delta > 0 && $variant->stock_tecnico < $delta) {
$maxAvailable = $variant->stock_tecnico + $item->cantidad;
if ($delta > 0 && $availableQuantity !== null && $availableQuantity < $delta) {
$maxAvailable = $availableQuantity + $item->cantidad;
throw ValidationException::withMessages([
'cantidad' => "El máximo que se puede agregar es {$maxAvailable}.",
]);
@@ -125,49 +146,65 @@ class Cart extends Model
$item->save();
if ($delta > 0) {
$variant->incrementReservedStock($delta);
$buyable->reserveStock($delta);
}
if ($delta < 0) {
$variant->decrementReservedStock(abs($delta));
$buyable->decrementReservedStock(abs($delta));
}
return $item->fresh();
});
}
public function removeItem(int $productVariantId): void
public function removeItem(int $cartItemId): void
{
DB::transaction(function () use ($productVariantId): void {
DB::transaction(function () use ($cartItemId): void {
/** @var CartItem $item */
$item = $this->items()
->where('producto_variante_id', $productVariantId)
->where('id', $cartItemId)
->lockForUpdate()
->firstOrFail();
$variant = $this->resolveScopedVariant($productVariantId, true);
$variant->decrementReservedStock($item->cantidad);
$buyable = $this->resolveScopedBuyable($item->buyable_type, $item->buyable_id, true);
$buyable->decrementReservedStock($item->cantidad);
$item->delete();
});
}
protected function resolveScopedVariant(int $productVariantId, bool $lockForUpdate = false): ProductVariant
protected function resolveScopedBuyable(string $buyableType, int $buyableId, bool $lockForUpdate = false): Buyable
{
$query = ProductVariant::query()
->whereKey($productVariantId)
->whereHas('product', fn ($query) => $query->where('tenant_codigo', $this->tenant_codigo));
$buyableClass = $this->resolveBuyableClass($buyableType);
if ($buyableClass === ProductVariant::class) {
$query = ProductVariant::query()
->whereKey($buyableId)
->whereHas('product', fn ($query) => $query->where('tenant_codigo', $this->tenant_codigo));
} else {
$query = Bundle::query()
->whereKey($buyableId)
->where('tenant_codigo', $this->tenant_codigo);
}
if ($lockForUpdate) {
$query->lockForUpdate();
}
/** @var ProductVariant|null $variant */
$variant = $query->first();
$buyable = $query->first();
if ($variant === null) {
throw new NotFoundHttpException('Product variant not found for tenant.');
if ($buyable === null) {
throw new NotFoundHttpException('Buyable not found for tenant.');
}
return $variant;
return $buyable;
}
protected function resolveBuyableClass(string $buyableType): string
{
return match ($buyableType) {
'variant', ProductVariant::class => ProductVariant::class,
'bundle', Bundle::class => Bundle::class,
default => throw new \InvalidArgumentException('Invalid buyable type'),
};
}
}

View File

@@ -10,7 +10,8 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable([
'cart_id',
'producto_variante_id',
'buyable_id',
'buyable_type',
'cantidad',
])]
class CartItem extends Model
@@ -23,7 +24,8 @@ class CartItem extends Model
{
return [
'cart_id' => 'integer',
'producto_variante_id' => 'integer',
'buyable_id' => 'integer',
'buyable_type' => 'string',
'cantidad' => 'integer',
];
}
@@ -37,10 +39,10 @@ class CartItem extends Model
}
/**
* @return BelongsTo<ProductVariant, $this>
* @return \Illuminate\Database\Eloquent\Relations\MorphTo
*/
public function variant(): BelongsTo
public function buyable()
{
return $this->belongsTo(ProductVariant::class, 'producto_variante_id');
return $this->morphTo();
}
}

View File

@@ -2,7 +2,10 @@
namespace App\Domains\Cart\Requests;
use App\Domains\Bundle\Models\Bundle;
use App\Domains\Catalog\Models\ProductVariant;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class AddCartItemRequest extends FormRequest
{
@@ -17,8 +20,18 @@ class AddCartItemRequest extends FormRequest
public function rules(): array
{
return [
'product_variant_id' => ['required', 'integer'],
'buyable_type' => ['required', 'string', Rule::in(['variant', 'bundle'])],
'buyable_id' => ['required', 'integer'],
'cantidad' => ['required', 'integer', 'min:1'],
];
}
public function mappedBuyableType(): string
{
return match ($this->input('buyable_type')) {
'variant' => ProductVariant::class,
'bundle' => Bundle::class,
default => throw new \InvalidArgumentException('Invalid buyable type'),
};
}
}

View File

@@ -18,6 +18,8 @@ class UpdateCartItemQuantityRequest extends FormRequest
{
return [
'cantidad' => ['required', 'integer', 'min:1'],
'buyable_type' => ['prohibited'],
'buyable_id' => ['prohibited'],
];
}
}

View File

@@ -15,29 +15,15 @@ class CartItemResource extends JsonResource
*/
public function toArray(Request $request): array
{
$variant = $this->variant;
$product = $variant?->product;
$attributesText = '';
if ($variant && $variant->relationLoaded('definitions')) {
$attributesText = $variant->definitions
->map(function ($definition) {
$attrName = $definition->productAttribute?->attribute?->nombre;
$value = $definition->value;
return $attrName ? "{$attrName}: {$value}" : $value;
})
->filter()
->implode(', ');
}
$productName = $product?->nombre;
if ($productName && $attributesText !== '') {
$productName .= " ({$attributesText})";
}
/** @var \App\Domains\Shared\Contracts\Buyable|null $buyable */
$buyable = $this->buyable;
$productName = $buyable?->getName();
$precio = $buyable?->getPrice();
$imageUrl = null;
if ($variant && $variant->relationLoaded('attachments')) {
$firstAttachment = $variant->attachments->first();
if ($this->buyable_type === \App\Domains\Catalog\Models\ProductVariant::class && $buyable && $buyable->relationLoaded('attachments')) {
$firstAttachment = $buyable->attachments->first();
if ($firstAttachment) {
$imageUrl = $firstAttachment->getTemporaryUrl(1440);
}
@@ -46,16 +32,25 @@ class CartItemResource extends JsonResource
return [
'id' => $this->id,
'cantidad' => $this->cantidad,
'precio_unitario' => $this->formatMoney($product?->precio),
'product_id' => $product?->id,
'product_variant_id' => $this->producto_variante_id,
'product' => $product === null ? null : [
'precio_unitario' => $this->formatMoney($precio),
'buyable_type' => $this->mapBuyableTypeToAlias($this->buyable_type),
'buyable_id' => $this->buyable_id,
'product' => $buyable === null ? null : [
'nombre' => $productName,
'imagen' => $imageUrl,
],
];
}
protected function mapBuyableTypeToAlias(?string $type): string
{
return match ($type) {
\App\Domains\Catalog\Models\ProductVariant::class => 'variant',
\App\Domains\Bundle\Models\Bundle::class => 'bundle',
default => 'unknown',
};
}
protected function formatMoney(float|int|string|null $amount): string
{
return number_format((float) ($amount ?? 0), 2, '.', '');

View File

@@ -2,11 +2,12 @@
namespace App\Domains\Cart\Resources;
use App\Domains\Cart\Models\Cart;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/**
* @mixin \App\Domains\Cart\Models\Cart
* @mixin Cart
*/
class CartResource extends JsonResource
{
@@ -20,7 +21,7 @@ class CartResource extends JsonResource
: collect();
$subtotal = $items->reduce(
fn (float $carry, $item): float => $carry + ((float) ($item->variant?->product?->precio ?? 0) * $item->cantidad),
fn (float $carry, $item): float => $carry + ((float) ($item->buyable?->getPrice() ?? 0) * $item->cantidad),
0.0,
);

View File

@@ -2,10 +2,14 @@
namespace App\Domains\Cart\Services;
use App\Domains\Cart\Models\Cart;
use App\Domains\Auth\Models\User;
use App\Domains\Bundle\Models\Bundle;
use App\Domains\Cart\Models\Cart;
use App\Domains\Catalog\Models\ProductVariant;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
@@ -32,12 +36,12 @@ class CartService
/**
* @return array{cart: Cart, guest_token: ?string}
*/
public function addItem(Tenant $tenant, Request $request, int $productVariantId, int $quantity): array
public function addItem(Tenant $tenant, Request $request, string $buyableType, int $buyableId, int $quantity): array
{
$resolvedIdentity = $this->resolveIdentity($request, true);
$identity = $resolvedIdentity['identity'];
$cart = $this->findOrCreateCart($tenant, $identity);
$cart->addItem($productVariantId, $quantity);
$cart->addItem($buyableType, $buyableId, $quantity);
return [
'cart' => $this->loadCart($cart),
@@ -45,20 +49,20 @@ class CartService
];
}
public function updateItemQuantity(Tenant $tenant, Request $request, int $productVariantId, int $quantity): Cart
public function updateItemQuantity(Tenant $tenant, Request $request, int $cartItemId, int $quantity): Cart
{
$identity = $this->requireIdentity($request);
$cart = $this->findCartOrFail($tenant, $identity);
$cart->updateItem($productVariantId, $quantity);
$cart->updateItem($cartItemId, $quantity);
return $this->loadCart($cart);
}
public function removeItem(Tenant $tenant, Request $request, int $productVariantId): Cart
public function removeItem(Tenant $tenant, Request $request, int $cartItemId): Cart
{
$identity = $this->requireIdentity($request);
$cart = $this->findCartOrFail($tenant, $identity);
$cart->removeItem($productVariantId);
$cart->removeItem($cartItemId);
return $this->loadCart($cart);
}
@@ -93,9 +97,16 @@ class CartService
protected function loadCart(Cart $cart): Cart
{
return $cart->fresh()->load([
'items.variant.product',
'items.variant.definitions.productAttribute.attribute',
'items.variant.attachments',
'items.buyable' => function (MorphTo $morphTo): void {
$morphTo->morphWith([
ProductVariant::class => [
'product',
'definitions.productAttribute.attribute',
'attachments',
],
Bundle::class => ['items.variant'],
]);
},
]);
}
@@ -104,7 +115,7 @@ class CartService
*/
protected function resolveIdentity(Request $request, bool $generateGuestToken = false): ?array
{
$user = $request->user();
$user = $request->user() ?? Auth::guard('sanctum')->user();
if ($user instanceof User) {
return [
@@ -201,5 +212,4 @@ class CartService
return Cart::query()->firstOrCreate($attributes, ['status' => 'active']);
}
}

View File

@@ -3,9 +3,11 @@
use App\Domains\Cart\Controllers\CartController;
use Illuminate\Support\Facades\Route;
Route::prefix('tenants/{tenant:codigo}')->group(function (): void {
Route::get('cart', [CartController::class, 'show']);
Route::post('cart/items', [CartController::class, 'addItem']);
Route::patch('cart/items/{productVariant}', [CartController::class, 'updateItemQuantity']);
Route::delete('cart/items/{productVariant}', [CartController::class, 'removeItem']);
});
Route::prefix('tenants/{tenant:codigo}')
->middleware(\App\Domains\Cart\Middleware\MergeGuestCartMiddleware::class)
->group(function (): void {
Route::get('cart', [CartController::class, 'show']);
Route::post('cart/items', [CartController::class, 'addItem']);
Route::patch('cart/items/{cartItem}', [CartController::class, 'updateItemQuantity']);
Route::delete('cart/items/{cartItem}', [CartController::class, 'removeItem']);
});

View File

@@ -0,0 +1,23 @@
<?php
namespace App\Domains\Catalog\Controllers;
use App\Domains\Catalog\Resources\CatalogFeaturedGroupResource;
use App\Domains\Catalog\Models\FeaturedGroup;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Controller;
class CatalogController extends Controller
{
public function index(string $tenant): JsonResponse
{
$featuredGroups = FeaturedGroup::where('tenant_codigo', $tenant)
->with(['featuredVariants' => function ($query) {
$query->orderBy('order');
}, 'featuredVariants.variant.product', 'featuredVariants.variant.attachments', 'featuredVariants.variant.product.attachments'])
->orderBy('group_order')
->get();
return response()->json(CatalogFeaturedGroupResource::collection($featuredGroups)->resolve());
}
}

View File

@@ -0,0 +1,51 @@
<?php
namespace App\Domains\Catalog\Controllers;
use App\Domains\Catalog\Models\FeaturedGroup;
use App\Domains\Catalog\Requests\StoreFeaturedGroupRequest;
use App\Domains\Catalog\Requests\UpdateFeaturedGroupRequest;
use App\Domains\Catalog\Resources\FeaturedGroupResource;
use App\Domains\Catalog\Services\FeaturedGroupService;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Routing\Controller;
use Illuminate\Http\JsonResponse;
class FeaturedGroupController extends Controller
{
public function __construct(
private readonly FeaturedGroupService $featuredGroupService
) {}
public function index(string $tenant): AnonymousResourceCollection
{
$groups = FeaturedGroup::where('tenant_codigo', $tenant)->get();
return FeaturedGroupResource::collection($groups);
}
public function store(StoreFeaturedGroupRequest $request, string $tenant): FeaturedGroupResource
{
$group = $this->featuredGroupService->createGroup($tenant, $request->validated());
return new FeaturedGroupResource($group);
}
public function show(string $tenant, FeaturedGroup $featuredGroup): FeaturedGroupResource
{
abort_if($featuredGroup->tenant_codigo !== $tenant, 404);
return new FeaturedGroupResource($featuredGroup->load('featuredVariants'));
}
public function update(UpdateFeaturedGroupRequest $request, string $tenant, FeaturedGroup $featuredGroup): FeaturedGroupResource
{
abort_if($featuredGroup->tenant_codigo !== $tenant, 404);
$group = $this->featuredGroupService->updateGroup($featuredGroup, $request->validated());
return new FeaturedGroupResource($group);
}
public function destroy(string $tenant, FeaturedGroup $featuredGroup): JsonResponse
{
abort_if($featuredGroup->tenant_codigo !== $tenant, 404);
$this->featuredGroupService->deleteGroup($featuredGroup);
return response()->json(null, 204);
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace App\Domains\Catalog\Controllers;
use App\Domains\Catalog\Models\FeaturedGroup;
use App\Domains\Catalog\Models\FeaturedVariant;
use App\Domains\Catalog\Requests\StoreFeaturedVariantRequest;
use App\Domains\Catalog\Requests\UpdateFeaturedVariantRequest;
use App\Domains\Catalog\Resources\FeaturedVariantResource;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Routing\Controller;
use Illuminate\Http\JsonResponse;
class FeaturedVariantController extends Controller
{
public function index(string $tenant, FeaturedGroup $featuredGroup): AnonymousResourceCollection
{
abort_if($featuredGroup->tenant_codigo !== $tenant, 404);
return FeaturedVariantResource::collection($featuredGroup->featuredVariants);
}
public function store(StoreFeaturedVariantRequest $request, string $tenant, FeaturedGroup $featuredGroup): FeaturedVariantResource
{
abort_if($featuredGroup->tenant_codigo !== $tenant, 404);
$variant = $featuredGroup->featuredVariants()->create($request->validated());
return new FeaturedVariantResource($variant);
}
public function update(UpdateFeaturedVariantRequest $request, string $tenant, FeaturedGroup $featuredGroup, FeaturedVariant $featuredVariant): FeaturedVariantResource
{
abort_if($featuredGroup->tenant_codigo !== $tenant || $featuredVariant->featured_group_id !== $featuredGroup->id, 404);
$featuredVariant->update($request->validated());
return new FeaturedVariantResource($featuredVariant);
}
public function destroy(string $tenant, FeaturedGroup $featuredGroup, FeaturedVariant $featuredVariant): JsonResponse
{
abort_if($featuredGroup->tenant_codigo !== $tenant || $featuredVariant->featured_group_id !== $featuredGroup->id, 404);
$featuredVariant->delete();
return response()->json(null, 204);
}
}

View File

@@ -0,0 +1,9 @@
<?php
namespace App\Domains\Catalog\Enums;
enum InventoryPolicy: string
{
case Tracked = 'tracked';
case Unlimited = 'unlimited';
}

View File

@@ -0,0 +1,21 @@
<?php
namespace App\Domains\Catalog\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class FeaturedGroup extends Model
{
protected $fillable = [
'tenant_codigo',
'group_name',
'product_layout',
'group_order',
];
public function featuredVariants(): HasMany
{
return $this->hasMany(FeaturedVariant::class);
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace App\Domains\Catalog\Models;
use App\Domains\Catalog\Models\ProductVariant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class FeaturedVariant extends Model
{
protected $table = 'featured_variants';
protected $fillable = [
'featured_group_id',
'product_variant_id',
'order',
];
public function featuredGroup(): BelongsTo
{
return $this->belongsTo(FeaturedGroup::class);
}
public function variant(): BelongsTo
{
return $this->belongsTo(ProductVariant::class, 'product_variant_id');
}
}

View File

@@ -3,23 +3,28 @@
namespace App\Domains\Catalog\Models;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Shared\Contracts\Buyable;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Casts\Attribute;
#[Fillable([
'producto_id',
'inventory_policy',
'stock_real',
'stock_reservado',
'stock',
'is_placeholder',
'has_tickets',
'minimum_use_date',
'maximum_use_date',
])]
class ProductVariant extends Model
class ProductVariant extends Model implements Buyable
{
use HasFactory;
@@ -27,9 +32,20 @@ class ProductVariant extends Model
protected $appends = ['stock_tecnico'];
protected $attributes = [
'inventory_policy' => 'tracked',
'stock_real' => 0,
'stock_reservado' => 0,
'cantidad_vendida' => 0,
];
protected static function booted(): void
{
static::saving(function (ProductVariant $variant) {
if ($variant->exists && $variant->isDirty('inventory_policy')) {
throw new \InvalidArgumentException('La politica de inventario no puede modificarse.');
}
$variant->validateStock();
});
}
@@ -44,34 +60,69 @@ class ProductVariant extends Model
throw new \InvalidArgumentException('El stock reservado no puede ser negativo.');
}
if ($this->stock_reservado > $this->stock_real) {
if ($this->cantidad_vendida < 0) {
throw new \InvalidArgumentException('La cantidad vendida no puede ser negativa.');
}
if ($this->tracksInventory() && $this->stock_reservado > $this->stock_real) {
throw new \InvalidArgumentException('El stock reservado no puede ser mayor que el stock real.');
}
}
public function incrementRealStock(int $amount): void
public function tracksInventory(): bool
{
return $this->inventory_policy === InventoryPolicy::Tracked;
}
public function availableQuantity(): ?int
{
if (! $this->tracksInventory()) {
return null;
}
return $this->stock_real - $this->stock_reservado;
}
public function isAvailableForSale(): bool
{
return ! $this->tracksInventory() || $this->availableQuantity() > 0;
}
public function getPrice(): float
{
return (float) ($this->product->precio ?? 0.0);
}
public function getName(): string
{
$name = $this->product?->nombre ?? 'Producto';
if ($this->relationLoaded('definitions') && $this->definitions->isNotEmpty()) {
$definitions = $this->definitions->map(function ($def) {
$attributeName = $def->productAttribute?->attribute?->nombre;
$value = $def->value;
return $attributeName ? "{$attributeName}: {$value}" : $value;
})->filter()->implode(', ');
if ($definitions !== '') {
$name .= " ({$definitions})";
}
}
return $name;
}
public function reserveStock(int $amount): void
{
if ($amount < 0) {
throw new \InvalidArgumentException('El monto a incrementar debe ser positivo.');
}
$this->stock_real += $amount;
$this->save();
}
public function decrementRealStock(int $amount): void
{
if ($amount < 0) {
throw new \InvalidArgumentException('El monto a decrementar debe ser positivo.');
if ($this->tracksInventory() && $this->availableQuantity() < $amount) {
throw new \InvalidArgumentException('No hay suficiente stock disponible para reservar.');
}
$this->stock_real -= $amount;
$this->save();
}
public function incrementReservedStock(int $amount): void
{
if ($amount < 0) {
throw new \InvalidArgumentException('El monto a incrementar debe ser positivo.');
}
$this->stock_reservado += $amount;
$this->save();
}
@@ -85,9 +136,32 @@ class ProductVariant extends Model
$this->save();
}
public function buy(int $amount): void
{
if ($amount < 0) {
throw new \InvalidArgumentException('El monto a confirmar debe ser positivo.');
}
if ($this->tracksInventory() && $this->stock_real < $amount) {
throw new \InvalidArgumentException('No hay suficiente stock real para confirmar la reserva.');
}
if ($this->stock_reservado < $amount) {
throw new \InvalidArgumentException('No hay suficiente stock reservado para confirmar la reserva.');
}
if ($this->tracksInventory()) {
$this->stock_real -= $amount;
}
$this->stock_reservado -= $amount;
$this->cantidad_vendida += $amount;
$this->save();
}
protected function stockTecnico(): Attribute
{
return Attribute::get(fn () => $this->stock_real - $this->stock_reservado);
return Attribute::get(fn (): ?int => $this->availableQuantity());
}
protected function stock(): Attribute
@@ -104,9 +178,14 @@ class ProductVariant extends Model
{
return [
'producto_id' => 'integer',
'inventory_policy' => InventoryPolicy::class,
'stock_real' => 'integer',
'stock_reservado' => 'integer',
'cantidad_vendida' => 'integer',
'is_placeholder' => 'boolean',
'has_tickets' => 'boolean',
'minimum_use_date' => 'datetime',
'maximum_use_date' => 'datetime',
];
}

View File

@@ -0,0 +1,22 @@
<?php
namespace App\Domains\Catalog\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreFeaturedGroupRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'group_name' => ['required', 'string', 'max:255'],
'product_layout' => ['required', 'string', 'in:row,column_with_image,column_with_cart,vertical_with_image,vertical_with_cart'],
'group_order' => ['nullable', 'integer'],
];
}
}

View File

@@ -0,0 +1,21 @@
<?php
namespace App\Domains\Catalog\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreFeaturedVariantRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'product_variant_id' => ['required', 'integer'],
'order' => ['nullable', 'integer'],
];
}
}

View File

@@ -2,6 +2,7 @@
namespace App\Domains\Catalog\Requests;
use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Shared\Rules\ImageOrBase64Rule;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
@@ -32,6 +33,8 @@ class StoreProductRequest extends FormRequest
'descripcion' => ['nullable', 'string'],
'precio' => ['required', 'numeric', 'min:0'],
'stock' => ['sometimes', 'integer', 'min:0'],
'inventory_policy' => ['sometimes', Rule::enum(InventoryPolicy::class)],
'cantidad_vendida' => ['prohibited'],
'attribute_ids' => ['sometimes', 'array'],
'attribute_ids.*' => [
'required',
@@ -41,7 +44,7 @@ class StoreProductRequest extends FormRequest
),
],
'images' => ['sometimes', 'nullable', 'array'],
'images.*' => ['required', new ImageOrBase64Rule()],
'images.*' => ['required', new ImageOrBase64Rule],
];
}
}

View File

@@ -2,6 +2,7 @@
namespace App\Domains\Catalog\Requests;
use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Shared\Rules\ImageOrBase64Rule;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
@@ -20,6 +21,8 @@ class StoreProductVariantRequest extends FormRequest
{
return [
'stock' => ['sometimes', 'integer', 'min:0'],
'inventory_policy' => ['sometimes', Rule::enum(InventoryPolicy::class)],
'cantidad_vendida' => ['prohibited'],
'definitions' => ['sometimes', 'array'],
'definitions.*.products_attribute_id' => [
'required',
@@ -31,7 +34,10 @@ class StoreProductVariantRequest extends FormRequest
],
'definitions.*.value' => ['nullable', 'string'],
'images' => ['sometimes', 'nullable', 'array'],
'images.*' => ['required', new ImageOrBase64Rule()],
'images.*' => ['required', new ImageOrBase64Rule],
'has_tickets' => ['boolean'],
'minimum_use_date' => ['nullable', 'date'],
'maximum_use_date' => ['nullable', 'date', 'after_or_equal:minimum_use_date'],
];
}
}

View File

@@ -0,0 +1,22 @@
<?php
namespace App\Domains\Catalog\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UpdateFeaturedGroupRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'group_name' => ['sometimes', 'string', 'max:255'],
'product_layout' => ['sometimes', 'string', 'in:row,column_with_image,column_with_cart,vertical_with_image,vertical_with_cart'],
'group_order' => ['nullable', 'integer'],
];
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace App\Domains\Catalog\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UpdateFeaturedVariantRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'order' => ['sometimes', 'integer'],
];
}
}

View File

@@ -20,6 +20,8 @@ class UpdateProductVariantRequest extends FormRequest
{
return [
'stock' => ['sometimes', 'integer', 'min:0'],
'inventory_policy' => ['prohibited'],
'cantidad_vendida' => ['prohibited'],
'definitions' => ['sometimes', 'array'],
'definitions.*.products_attribute_id' => [
'required',
@@ -31,7 +33,10 @@ class UpdateProductVariantRequest extends FormRequest
],
'definitions.*.value' => ['nullable', 'string'],
'images' => ['sometimes', 'nullable', 'array'],
'images.*' => ['required', new ImageOrBase64Rule()],
'images.*' => ['required', new ImageOrBase64Rule],
'has_tickets' => ['boolean'],
'minimum_use_date' => ['nullable', 'date'],
'maximum_use_date' => ['nullable', 'date', 'after_or_equal:minimum_use_date'],
];
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace App\Domains\Catalog\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use App\Domains\Catalog\Models\FeaturedVariant;
class CatalogFeaturedGroupResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'title' => $this->group_name,
'layout' => $this->product_layout,
'group_order' => $this->group_order,
'items' => $this->whenLoaded('featuredVariants', function () use ($request) {
return $this->featuredVariants->map(function (FeaturedVariant $featuredVariant) use ($request) {
$variant = $featuredVariant->variant;
$variantResource = (new ProductVariantResource($variant))->toArray($request);
if ($this->product_layout === 'row' || $this->product_layout === 'column_with_cart' || $this->product_layout === 'vertical_with_cart') {
// Devuelve el Product Variant Resource completo como pidio el usuario
// "Que todo devuelva el product variant resource"
return $variantResource;
}
// Para column_with_image o vertical_with_image
if ($this->product_layout === 'column_with_image' || $this->product_layout === 'vertical_with_image') {
if (isset($variantResource['images']) && count($variantResource['images']) > 0) {
$variantResource['images'] = [$variantResource['images'][0]];
}
return $variantResource;
}
return $variantResource;
});
}),
];
}
}

View File

@@ -0,0 +1,21 @@
<?php
namespace App\Domains\Catalog\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class FeaturedGroupResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'tenant_codigo' => $this->tenant_codigo,
'group_name' => $this->group_name,
'product_layout' => $this->product_layout,
'group_order' => $this->group_order,
'featured_variants' => FeaturedVariantResource::collection($this->whenLoaded('featuredVariants')),
];
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace App\Domains\Catalog\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class FeaturedVariantResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'featured_group_id' => $this->featured_group_id,
'product_variant_id' => $this->product_variant_id,
'order' => $this->order,
];
}
}

View File

@@ -26,6 +26,7 @@ class ProductResource extends JsonResource
'precio' => $this->precio,
'category' => $this->whenLoaded('category', fn () => $this->category?->nombre),
'brand' => $this->whenLoaded('brand', fn () => $this->brand?->nombre),
'images' => $this->whenLoaded('attachments', fn () => $this->attachments
->map(fn ($attachment) => $attachment->getTemporaryUrl(1440))
->values()
@@ -34,7 +35,9 @@ class ProductResource extends JsonResource
'variants_map' => $this->whenLoaded('variants', fn () => $this->variants
->map(fn ($variant) => [
'variant_id' => $variant->id,
'inventory_policy' => $variant->inventory_policy->value,
'cantidad_maxima' => $variant->stock_tecnico,
'cantidad_vendida' => $variant->cantidad_vendida,
'attributes' => $variant->definitions
->mapWithKeys(fn ($definition) => [
$definition->productAttribute?->attribute?->codigo => $definition->value,

View File

@@ -18,7 +18,12 @@ class ProductVariantResource extends JsonResource
{
return [
'id' => $this->id,
'inventory_policy' => $this->inventory_policy->value,
'cantidad_maxima' => $this->stock_tecnico,
'cantidad_vendida' => $this->cantidad_vendida,
'has_tickets' => $this->has_tickets,
'minimum_use_date' => $this->minimum_use_date,
'maximum_use_date' => $this->maximum_use_date,
'product' => ProductResource::make($this->whenLoaded('product')),
'definitions' => $this->whenLoaded(
'definitions',

View File

@@ -0,0 +1,25 @@
<?php
namespace App\Domains\Catalog\Services;
use App\Domains\Catalog\Models\FeaturedGroup;
class FeaturedGroupService
{
public function createGroup(string $tenantCodigo, array $data): FeaturedGroup
{
$data['tenant_codigo'] = $tenantCodigo;
return FeaturedGroup::create($data);
}
public function updateGroup(FeaturedGroup $group, array $data): FeaturedGroup
{
$group->update($data);
return $group;
}
public function deleteGroup(FeaturedGroup $group): bool|null
{
return $group->delete();
}
}

View File

@@ -3,6 +3,7 @@
namespace App\Domains\Catalog\Services;
use App\Domains\Attachable\Services\AttachmentService;
use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Catalog\Models\Attribute;
use App\Domains\Catalog\Models\Product;
use App\Domains\Catalog\Models\ProductVariant;
@@ -28,7 +29,8 @@ class ProductService
$attributeIds = $data['attribute_ids'] ?? [];
$images = $data['images'] ?? [];
$stock = $data['stock'] ?? 0;
unset($data['attribute_ids'], $data['images'], $data['stock']);
$inventoryPolicy = $data['inventory_policy'] ?? InventoryPolicy::Tracked->value;
unset($data['attribute_ids'], $data['images'], $data['stock'], $data['inventory_policy']);
/** @var Product $product */
$product = Product::query()->create([
@@ -45,6 +47,7 @@ class ProductService
// Create default variant with stock
$this->createVariant($product, [
'stock' => $stock,
'inventory_policy' => $inventoryPolicy,
'is_placeholder' => true,
'definitions' => [],
]);
@@ -179,6 +182,7 @@ class ProductService
if ($product->variants()->count() === 0) {
$product->createVariant([
'stock' => 0,
'inventory_policy' => InventoryPolicy::Tracked->value,
'is_placeholder' => true,
'definitions' => [],
]);
@@ -327,13 +331,13 @@ class ProductService
$selectedVariant = $variantId !== null
? $product->variants->firstWhere('id', $variantId)
: $product->variants->first(fn (ProductVariant $variant) => $variant->stock_tecnico > 0);
: $product->variants->first(fn (ProductVariant $variant) => $variant->isAvailableForSale());
if ($variantId !== null && $selectedVariant === null) {
throw new NotFoundHttpException('Product variant not found for product.');
}
if ($variantId !== null && $selectedVariant->stock_tecnico <= 0) {
if ($variantId !== null && ! $selectedVariant->isAvailableForSale()) {
throw ValidationException::withMessages([
'variant_id' => 'La variante seleccionada no tiene stock.',
]);

View File

@@ -1,13 +1,17 @@
<?php
use App\Domains\Catalog\Controllers\BrandController;
use App\Domains\Catalog\Controllers\CatalogController;
use App\Domains\Catalog\Controllers\CategoryController;
use App\Domains\Catalog\Controllers\ProductController;
use App\Domains\Catalog\Controllers\AttributeController;
use App\Domains\Catalog\Controllers\ProductVariantController;
use App\Domains\Catalog\Controllers\FeaturedGroupController;
use App\Domains\Catalog\Controllers\FeaturedVariantController;
use Illuminate\Support\Facades\Route;
Route::prefix('tenants/{tenant:codigo}')->group(function (): void {
Route::get('catalog', [CatalogController::class, 'index']);
Route::apiResource('marcas', BrandController::class)->parameters(['marcas' => 'marca']);
Route::apiResource('categorias', CategoryController::class)->parameters(['categorias' => 'categoria']);
Route::apiResource('productos', ProductController::class);
@@ -17,4 +21,11 @@ Route::prefix('tenants/{tenant:codigo}')->group(function (): void {
'productos' => 'producto',
'variants' => 'productVariant',
]);
Route::apiResource('featured-groups', FeaturedGroupController::class);
Route::apiResource('featured-groups.variants', FeaturedVariantController::class)
->only(['index', 'store', 'update', 'destroy'])
->parameters([
'featured-groups' => 'featuredGroup',
'variants' => 'featuredVariant',
]);
});

View File

@@ -0,0 +1,66 @@
<?php
namespace App\Domains\Integration\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Encryption\Encrypter;
use Exception;
class EncryptedIntegrationData implements CastsAttributes
{
protected function getEncrypter(): Encrypter
{
$secret = config('services.integrations.secret');
if (empty($secret)) {
throw new Exception('The integrations secret is not configured.');
}
// Laravel encrypter requires a key of exact length. Typically 32 bytes for AES-256-CBC.
// If the secret is base64 encoded like the APP_KEY:
if (str_starts_with($secret, 'base64:')) {
$key = base64_decode(substr($secret, 7));
} else {
// Otherwise, we hash it to ensure 32 bytes for AES-256-CBC.
$key = hash('sha256', $secret, true);
}
return new Encrypter($key, config('app.cipher', 'AES-256-CBC'));
}
/**
* Cast the given value.
*
* @param array<string, mixed> $attributes
*/
public function get(Model $model, string $key, mixed $value, array $attributes): mixed
{
if ($value === null) {
return null;
}
try {
$decrypted = $this->getEncrypter()->decryptString($value);
return json_decode($decrypted, true);
} catch (Exception $e) {
// Return null or throw depending on how strict we want to be.
return null;
}
}
/**
* Prepare the given value for storage.
*
* @param array<string, mixed> $attributes
*/
public function set(Model $model, string $key, mixed $value, array $attributes): mixed
{
if ($value === null) {
return null;
}
$json = json_encode($value);
return $this->getEncrypter()->encryptString($json);
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace App\Domains\Integration\Controllers;
use App\Domains\Integration\Models\Integration;
use App\Domains\Integration\Requests\StoreIntegrationRequest;
use App\Domains\Integration\Requests\UpdateIntegrationRequest;
use Illuminate\Routing\Controller;
class IntegrationController extends Controller
{
public function index()
{
return response()->json(Integration::all());
}
public function store(StoreIntegrationRequest $request)
{
$integration = Integration::create($request->validated());
return response()->json($integration, 201);
}
public function show(Integration $integration)
{
return response()->json($integration);
}
public function update(UpdateIntegrationRequest $request, Integration $integration)
{
$integration->update($request->validated());
return response()->json($integration->fresh());
}
public function destroy(Integration $integration)
{
$integration->delete();
return response()->noContent();
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace App\Domains\Integration\Controllers;
use App\Domains\Integration\Requests\TelepagosWebhookRequest;
use App\Domains\Integration\Services\TelepagosWebhookService;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class TelepagosWebhookController extends Controller
{
/**
* Handle the incoming Telepagos webhook.
*
* @param TelepagosWebhookRequest $request
* @param string $tenantCodigo
* @param TelepagosWebhookService $service
* @return JsonResponse
*/
public function handle(TelepagosWebhookRequest $request, string $tenantCodigo, TelepagosWebhookService $service): JsonResponse
{
try {
$cashinId = $request->validated('id');
$service->handleWebhook($tenantCodigo, $cashinId);
return response()->json(['status' => 'success']);
} catch (\Exception $e) {
return response()->json(['status' => 'error', 'message' => $e->getMessage()], 500);
}
}
}

View File

@@ -0,0 +1,53 @@
<?php
namespace App\Domains\Integration\Controllers;
use App\Domains\Integration\Models\Integration;
use App\Domains\Integration\Requests\StoreTenantIntegrationRequest;
use App\Domains\Integration\Services\TenantIntegrationService;
use Illuminate\Routing\Controller;
class TenantIntegrationController extends Controller
{
protected TenantIntegrationService $tenantIntegrationService;
public function __construct(TenantIntegrationService $tenantIntegrationService)
{
$this->tenantIntegrationService = $tenantIntegrationService;
}
public function index(string $tenantCode)
{
return response()->json($this->tenantIntegrationService->getAllForTenant($tenantCode));
}
public function show(string $tenantCode, string $integrationCode)
{
$integration = $this->tenantIntegrationService->getTenantIntegration($tenantCode, $integrationCode);
if (!$integration) {
return response()->json(['message' => 'Integration not configured for this tenant'], 404);
}
return response()->json($integration);
}
public function store(StoreTenantIntegrationRequest $request, string $tenantCode, string $integrationCode)
{
$integration = Integration::where('integration_code', $integrationCode)->firstOrFail();
try {
$tenantIntegration = $this->tenantIntegrationService->updateOrCreateIntegration(
$tenantCode,
$integration,
$request->input('integration_data', [])
);
return response()->json($tenantIntegration);
} catch (\Exception $e) {
return response()->json([
'message' => 'Error validando la configuración: ' . $e->getMessage()
], 400);
}
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace App\Domains\Integration\Models;
use Illuminate\Database\Eloquent\Model;
class Integration extends Model
{
protected $table = 'integrations';
protected $fillable = [
'integration_code',
'name',
'url',
'integration_data_schema',
];
protected $casts = [
'integration_data_schema' => 'array',
];
public function tenantIntegrations()
{
return $this->hasMany(TenantIntegration::class, 'integration_code', 'integration_code');
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace App\Domains\Integration\Models;
use App\Domains\Integration\Casts\EncryptedIntegrationData;
use Illuminate\Database\Eloquent\Model;
class TenantIntegration extends Model
{
protected $table = 'tenant_integration';
protected $fillable = [
'integration_code',
'tenant_code',
'integration_data',
];
protected $casts = [
'integration_data' => EncryptedIntegrationData::class,
];
public function integration()
{
return $this->belongsTo(Integration::class, 'integration_code', 'integration_code');
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace App\Domains\Integration\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreIntegrationRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'integration_code' => ['required', 'string', 'unique:integrations,integration_code'],
'name' => ['required', 'string', 'max:255'],
'url' => ['nullable', 'url', 'max:255'],
'integration_data_schema' => ['nullable', 'array'],
];
}
}

View File

@@ -0,0 +1,43 @@
<?php
namespace App\Domains\Integration\Requests;
use App\Domains\Integration\Models\Integration;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\ValidationException;
class StoreTenantIntegrationRequest extends FormRequest
{
protected ?Integration $integrationModel = null;
public function authorize(): bool
{
return true;
}
protected function prepareForValidation()
{
$integrationCode = $this->route('integration_code');
$this->integrationModel = Integration::where('integration_code', $integrationCode)->first();
if (!$this->integrationModel) {
throw ValidationException::withMessages([
'integration_code' => 'Integration not found.'
]);
}
}
public function rules(): array
{
$rules = [];
// Dynamic validation rules based on the integration data schema
if ($this->integrationModel && $this->integrationModel->integration_data_schema) {
foreach ($this->integrationModel->integration_data_schema as $field => $rule) {
$rules['integration_data.' . $field] = $rule;
}
}
return $rules;
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace App\Domains\Integration\Requests;
use Illuminate\Foundation\Http\FormRequest;
class TelepagosWebhookRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array|string>
*/
public function rules(): array
{
return [
'id' => ['required', 'string'],
];
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace App\Domains\Integration\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UpdateIntegrationRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
$integration = $this->route('integration');
return [
'name' => ['sometimes', 'required', 'string', 'max:255'],
'url' => ['nullable', 'url', 'max:255'],
'integration_data_schema' => ['nullable', 'array'],
// the code shouldn't ideally be updatable, but if it is:
'integration_code' => ['sometimes', 'required', 'string', 'unique:integrations,integration_code,' . ($integration->id ?? '')],
];
}
}

View File

@@ -0,0 +1,167 @@
<?php
namespace App\Domains\Integration\Services;
use App\Domains\Integration\Models\Integration;
use App\Domains\Integration\Models\TenantIntegration;
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Client\PendingRequest;
use Exception;
abstract class BaseIntegrationService
{
/**
* The unique code of the integration.
*
* @var string
*/
protected string $integrationCode;
/**
* The current tenant code.
*
* @var string
*/
protected string $tenantCode;
/**
* The integration model instance.
*
* @var Integration|null
*/
protected ?Integration $integration = null;
/**
* The tenant-specific integration model instance.
*
* @var TenantIntegration|null
*/
protected ?TenantIntegration $tenantIntegration = null;
/**
* Set the integration code.
*
* @param string $integrationCode
* @return $this
*/
public function setIntegrationCode(string $integrationCode): self
{
$this->integrationCode = $integrationCode;
return $this;
}
/**
* Get the integration code.
*
* @return string
*/
public function getIntegrationCode(): string
{
return $this->integrationCode;
}
/**
* Set the tenant code and load the integration models.
*
* @param string $tenantCode
* @return $this
* @throws Exception
*/
public function forTenant(string $tenantCode): self
{
$this->tenantCode = $tenantCode;
$this->loadIntegration();
return $this;
}
/**
* Load the Integration and TenantIntegration models.
*
* @throws Exception
*/
protected function loadIntegration(): void
{
if (empty($this->integrationCode)) {
throw new Exception("Integration code is not set.");
}
$this->integration = Integration::where('integration_code', $this->integrationCode)->first();
if (!$this->integration) {
throw new Exception("Integration with code '{$this->integrationCode}' not found.");
}
$this->tenantIntegration = TenantIntegration::where('tenant_code', $this->tenantCode)
->where('integration_code', $this->integrationCode)
->first();
if (!$this->tenantIntegration) {
throw new Exception("Tenant '{$this->tenantCode}' does not have integration '{$this->integrationCode}' configured.");
}
}
/**
* Build the request URL.
*
* @param string $path
* @return string
* @throws Exception
*/
public function getUrl(string $path = ''): string
{
if (!$this->integration) {
throw new Exception("Integration is not loaded. Call forTenant() first.");
}
$baseUrl = rtrim($this->integration->url, '/');
$path = ltrim($path, '/');
return $path !== '' ? "{$baseUrl}/{$path}" : $baseUrl;
}
/**
* Get integration setting by key from tenant's integration data.
*
* @param string $key
* @param mixed $default
* @return mixed
*/
protected function getIntegrationSetting(string $key, mixed $default = null): mixed
{
if (!$this->tenantIntegration || !$this->tenantIntegration->integration_data) {
return $default;
}
return $this->tenantIntegration->integration_data[$key] ?? $default;
}
/**
* Get a pre-configured HTTP client builder.
*
* @return PendingRequest
* @throws Exception
*/
public function client(): PendingRequest
{
return Http::baseUrl($this->getUrl())
->withHeaders($this->getHeaders());
}
/**
* Get the headers for the integration.
*
* @return array
*/
abstract public function getHeaders(): array;
/**
* Hook called after the integration is configured for the tenant.
* Can be used to validate credentials or perform initial setups.
* Throw an Exception on failure.
*
* @return void
*/
public function onSetup(): void
{
// Override in child classes if needed
}
}

View File

@@ -0,0 +1,228 @@
<?php
namespace App\Domains\Integration\Services;
use Exception;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;
class TelepagosIntegrationService extends BaseIntegrationService
{
/**
* TelepagosIntegrationService constructor.
*
* @param string $integrationCode
*/
public function __construct(string $integrationCode = 'telepagos')
{
// Force homologation code if not in production and using default
if ($integrationCode === 'telepagos' && !app()->environment('production')) {
$integrationCode = 'telepagos_homo';
}
$this->integrationCode = $integrationCode;
}
/**
* Get the headers for Telepagos integration.
*
* @return array
* @throws Exception
*/
public function getHeaders(): array
{
return [
'Authorization' => 'Bearer ' . $this->getToken(),
'Content-Type' => 'application/json',
'Accept' => 'application/json',
];
}
/**
* Get a valid token, either from cache or by performing a login.
*
* @return string
* @throws Exception
*/
public function getToken(): string
{
if (!$this->tenantIntegration) {
throw new Exception("Tenant integration is not loaded. Call forTenant() first.");
}
$cacheKey = "integration_token:{$this->tenantCode}:{$this->integrationCode}";
$token = Cache::get($cacheKey);
if ($token) {
return $token;
}
return $this->login();
}
/**
* Authenticate with Telepagos and cache the returned token.
*
* @return string
* @throws Exception
*/
public function login(): string
{
$username = $this->getIntegrationSetting('username');
$password = $this->getIntegrationSetting('password');
if (empty($username) || empty($password)) {
throw new Exception("Missing username or password in Telepagos integration settings.");
}
$url = $this->getUrl('/v2/auth/token');
$response = Http::post($url, [
'username' => $username,
'password' => $password,
]);
$data = $this->handleResponse($response, 'authentication', [
'username' => $username,
]);
$token = $data['token'] ?? null;
$expiresAtStr = $data['expires_at'] ?? null;
if (!$token || !$expiresAtStr) {
throw new Exception("Telepagos authentication response is missing token or expires_at.");
}
$expiresAt = Carbon::parse($expiresAtStr);
// Calculate TTL and subtract a buffer of 60 seconds
$ttlSeconds = max(1, $expiresAt->diffInSeconds(now()) - 60);
$cacheKey = "integration_token:{$this->tenantCode}:{$this->integrationCode}";
Cache::put($cacheKey, $token, $ttlSeconds);
return $token;
}
/**
* Send a request to Telepagos, handling 401 Unauthorized for token refresh.
*
* @param string $method
* @param string $endpoint
* @param array $data
* @return \Illuminate\Http\Client\Response
*/
protected function sendRequest(string $method, string $endpoint, array $data = []): \Illuminate\Http\Client\Response
{
$response = $this->client()->$method($endpoint, $data);
if ($response->status() === 401) {
Log::info("Telepagos 401 Unauthorized. Refreshing token and retrying...");
$this->clearToken();
$response = $this->client()->$method($endpoint, $data);
}
return $response;
}
/**
* Generate a QR code for cash-in.
*
* @param float $amount
* @param string $concept
* @param string $description
* @return array
* @throws Exception
*/
public function generateQr(float $amount, string $concept, string $description): array
{
$payload = [
'amount' => $amount,
'concept' => $concept,
'description' => $description,
];
$response = $this->sendRequest('post', '/v2/payment/cashin/qr/generate', $payload);
return $this->handleResponse($response, 'QR generation', $payload);
}
/**
* Get the details of a cash-in payment.
*
* @param int $cashinId
* @return array
* @throws Exception
*/
public function getCashinDetails(string $cashinId): array
{
$response = $this->sendRequest('get', "/v2/payment/cashin/{$cashinId}");
return $this->handleResponse($response, 'get cash-in details', [
'cashin_id' => $cashinId,
]);
}
/**
* Get the account info.
*
* @return array
* @throws Exception
*/
public function getAccountInfo(): array
{
$response = $this->sendRequest('get', '/v2/account/info');
return $this->handleResponse($response, 'get account info');
}
/**
* Handle the Telepagos API response, logging any failures and throwing Exceptions.
*
* @param \Illuminate\Http\Client\Response $response
* @param string $actionDescription
* @param array $context
* @return array
* @throws Exception
*/
protected function handleResponse(\Illuminate\Http\Client\Response $response, string $actionDescription, array $context = []): array
{
if ($response->failed() || $response->json('status') !== 'ok') {
$errorMessage = $response->json('message') ?? $response->body();
Log::error("Telepagos {$actionDescription} failed: {$errorMessage}", array_merge([
'response_status' => $response->status(),
'response_body' => $response->json() ?? $response->body(),
], $context));
throw new Exception("Telepagos {$actionDescription} failed: {$errorMessage}");
}
return $response->json() ?? [];
}
/**
* Clear the cached token.
*
* @return void
*/
public function clearToken(): void
{
$cacheKey = "integration_token:{$this->tenantCode}:{$this->integrationCode}";
Cache::forget($cacheKey);
}
/**
* Perform initial setup validation for Telepagos.
*
* @return void
* @throws Exception
*/
public function onSetup(): void
{
// Realiza un login de prueba para validar que las credenciales son correctas.
$this->login();
}
}

View File

@@ -0,0 +1,134 @@
<?php
namespace App\Domains\Integration\Services;
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\Tenant\Models\Tenant;
use Exception;
use Illuminate\Support\Facades\Log;
class TelepagosWebhookService
{
public function __construct(
private readonly CheckoutService $checkoutService,
) {}
/**
* Handle the Telepagos webhook notification.
*
* @param string $tenantCodigo
* @param string $cashinId
* @return void
* @throws Exception
*/
public function handleWebhook(string $tenantCodigo, string $cashinId): void
{
$tenant = Tenant::where('codigo', $tenantCodigo)->firstOrFail();
$telepagosService = new TelepagosIntegrationService();
$telepagosService->forTenant($tenant->codigo);
try {
$details = $telepagosService->getCashinDetails($cashinId);
$qrOrderId = $details['data']['qr_order_id'] ?? $details['qr_order_id'] ?? null;
$amount = $this->normalizeAmount($details['data']['amount'] ?? $details['amount'] ?? 0);
$operationId = $details['data']['operation_id'] ?? $details['operation_id'] ?? null;
$transferenciaOperationIds = [1, 3, 11];
$qrOperationIds = [31, 37, 47];
$compra = null;
if (in_array((int) $operationId, $transferenciaOperationIds, true)) {
$cuit = $details['data']['buyer']['cuit'] ?? $details['buyer']['cuit'] ?? null;
if (! $cuit) {
Log::warning("Telepagos webhook: CUIT not found for Transferencia cashin {$cashinId}");
return;
}
$dni = substr($cuit, 2, -1);
$compra = Purchase::where('tenant_codigo', $tenantCodigo)
->whereRaw("REPLACE(dni, '.', '') = ?", [$dni])
->whereIn('status', [Purchase::STATUS_CREATED, Purchase::STATUS_PENDING_PAYMENT])
->where('payment_method', 'transfer')
->where('total', $amount)
->latest()
->first();
if (! $compra) {
Log::warning("Telepagos webhook: No matching purchase found for DNI {$dni} and amount {$amount} for cashin {$cashinId}");
return;
}
} elseif (in_array((int) $operationId, $qrOperationIds, true)) {
if (! $qrOrderId) {
Log::warning("Telepagos webhook: qr_order_id not found for QR cashin {$cashinId}");
return;
}
$telepagosQr = TelepagosQr::where('qr_order_id', $qrOrderId)->first();
if (! $telepagosQr) {
Log::warning("Telepagos webhook: QR {$qrOrderId} not found in database for cashin {$cashinId}");
return;
}
$compra = $telepagosQr->compra;
if (! $compra) {
Log::warning("Telepagos webhook: Purchase not found for QR {$qrOrderId}");
return;
}
if ($compra->status !== Purchase::STATUS_PENDING_PAYMENT) {
Log::warning("Telepagos webhook: Purchase {$compra->id} is not awaiting payment confirmation");
return;
}
$totalAmount = $this->normalizeAmount($compra->getTotalAmount());
if ($amount !== $totalAmount) {
Log::warning("Telepagos webhook: Amount mismatch. Cashin amount: {$amount}, Purchase amount: {$totalAmount}");
return;
}
} else {
Log::warning("Telepagos webhook: Unknown operation_id {$operationId} for cashin {$cashinId}");
return;
}
$paymentData = [
'compra_id' => $compra->id,
'cuit_buyer' => $details['data']['buyer']['cuit'] ?? $details['buyer']['cuit'] ?? null,
'cvu_buyer' => $details['data']['buyer']['cvu'] ?? $details['buyer']['cvu'] ?? null,
'amount' => $amount,
'concept' => $details['data']['concept'] ?? $details['concept'] ?? null,
'operation' => $details['data']['operation'] ?? $details['operation'] ?? null,
'operation_id' => $details['data']['operation_id'] ?? $details['operation_id'] ?? null,
'transaction_id' => $details['data']['transaction_id'] ?? $details['transaction_id'] ?? null,
'qr_order_id' => $qrOrderId,
'link_id' => $details['data']['link_id'] ?? $details['link_id'] ?? null,
];
\Illuminate\Support\Facades\DB::transaction(function () use ($compra, $paymentData) {
TelepagosPayment::create($paymentData);
$this->checkoutService->confirmPurchase($compra);
$compra->markAsPaid();
});
Log::info("Telepagos webhook: Successfully processed cashin {$cashinId} for purchase {$compra->id}");
} catch (Exception $e) {
Log::error("Telepagos webhook error: " . $e->getMessage());
throw $e;
}
}
protected function normalizeAmount(mixed $amount): string
{
return number_format((float) $amount, 2, '.', '');
}
}

View File

@@ -0,0 +1,57 @@
<?php
namespace App\Domains\Integration\Services;
use App\Domains\Integration\Models\Integration;
use App\Domains\Integration\Models\TenantIntegration;
use Illuminate\Support\Facades\DB;
class TenantIntegrationService
{
public function getTenantIntegration(string $tenantCode, string $integrationCode): ?TenantIntegration
{
return TenantIntegration::where('tenant_code', $tenantCode)
->where('integration_code', $integrationCode)
->first();
}
public function getAllForTenant(string $tenantCode)
{
return TenantIntegration::with('integration')
->where('tenant_code', $tenantCode)
->get();
}
public function updateOrCreateIntegration(string $tenantCode, Integration $integration, array $data): TenantIntegration
{
return DB::transaction(function () use ($tenantCode, $integration, $data) {
$tenantIntegration = TenantIntegration::updateOrCreate(
[
'tenant_code' => $tenantCode,
'integration_code' => $integration->integration_code,
],
[
'integration_data' => $data,
]
);
$service = $this->resolveService($integration->integration_code);
if ($service) {
$service->forTenant($tenantCode)->onSetup();
}
return $tenantIntegration;
});
}
protected function resolveService(string $integrationCode): ?BaseIntegrationService
{
switch ($integrationCode) {
case 'telepagos':
case 'telepagos_homo':
return new TelepagosIntegrationService($integrationCode);
default:
return null;
}
}
}

View File

@@ -0,0 +1,21 @@
<?php
use App\Domains\Integration\Controllers\IntegrationController;
use App\Domains\Integration\Controllers\TenantIntegrationController;
use Illuminate\Support\Facades\Route;
Route::group(['prefix' => 'integrations'], function () {
Route::get('/', [IntegrationController::class, 'index']);
Route::post('/', [IntegrationController::class, 'store']);
Route::get('/{integration}', [IntegrationController::class, 'show']);
Route::put('/{integration}', [IntegrationController::class, 'update']);
Route::delete('/{integration}', [IntegrationController::class, 'destroy']);
});
Route::group(['prefix' => '{tenant_code}/integrations'], function () {
Route::get('/', [TenantIntegrationController::class, 'index']);
Route::get('/{integration_code}', [TenantIntegrationController::class, 'show']);
Route::post('/{integration_code}', [TenantIntegrationController::class, 'store']);
});
Route::post('webhooks/telepagos/{tenant_codigo}', [\App\Domains\Integration\Controllers\TelepagosWebhookController::class, 'handle']);

View File

@@ -0,0 +1,50 @@
<?php
namespace App\Domains\Menu\Controllers;
use App\Domains\Menu\Models\Menu;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
class MenuController extends Controller
{
public function index(): JsonResponse
{
$menues = Menu::all();
return response()->json($menues);
}
public function store(Request $request): JsonResponse
{
$validated = $request->validate([
'code' => 'required|string|unique:menues,code',
'route' => 'required|string',
]);
$menu = Menu::create($validated);
return response()->json($menu, 201);
}
public function show(Menu $menu): JsonResponse
{
return response()->json($menu);
}
public function update(Request $request, Menu $menu): JsonResponse
{
$validated = $request->validate([
'code' => 'sometimes|required|string|unique:menues,code,' . $menu->id,
'route' => 'sometimes|required|string',
]);
$menu->update($validated);
return response()->json($menu);
}
public function destroy(Menu $menu): JsonResponse
{
$menu->delete();
return response()->json(null, 204);
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace App\Domains\Menu\Models;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class Menu extends Model
{
use HasFactory;
protected $table = 'menues';
protected $fillable = [
'code',
'route',
];
public function tenants(): BelongsToMany
{
return $this->belongsToMany(
Tenant::class,
'tenant_menues',
'menu_code',
'tenant_codigo',
'code',
'codigo'
)->withTimestamps();
}
}

View File

@@ -0,0 +1,10 @@
<?php
namespace App\Domains\Menu\Models;
use Illuminate\Database\Eloquent\Relations\Pivot;
class TenantMenu extends Pivot
{
protected $table = 'tenant_menues';
}

View File

@@ -0,0 +1,6 @@
<?php
use App\Domains\Menu\Controllers\MenuController;
use Illuminate\Support\Facades\Route;
Route::apiResource('menues', MenuController::class);

View File

@@ -2,16 +2,21 @@
namespace App\Domains\Purchase\Controllers;
use App\Domains\Bundle\Models\Bundle;
use App\Domains\Catalog\Models\ProductVariant;
use App\Domains\Integration\Services\TelepagosIntegrationService;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Requests\PaymentIntentRequest;
use App\Domains\Purchase\Requests\StorePurchaseRequest;
use App\Domains\Purchase\Resources\PurchaseResource;
use App\Domains\Purchase\Services\CheckoutService;
use App\Domains\Tenant\Models\Tenant;
use App\Http\Controllers\Controller;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class PurchaseController extends Controller
@@ -20,36 +25,25 @@ class PurchaseController extends Controller
{
return PurchaseResource::collection(
Purchase::query()
->with(['items.variant.product', 'items.variant.definitions.productAttribute.attribute'])
->where('tenant_codigo', $tenant->codigo)
->where('user_id', $request->user()->id)
->when($request->query('status'), function ($query, $status) {
$query->where('status', $status);
})
->latest()
->paginateFromRequest()
)->response();
}
public function store(StorePurchaseRequest $request, Tenant $tenant): JsonResponse
public function store(StorePurchaseRequest $request, Tenant $tenant, CheckoutService $checkoutService): JsonResponse
{
$data = $request->validated();
$items = $data['items'];
unset($data['items']);
$variants = $this->resolveTenantVariants($tenant, $items);
$purchaseItems = $this->buildPurchaseItemsPayload($items, $variants);
$purchase = DB::transaction(function () use ($request, $tenant, $data, $purchaseItems): Purchase {
/** @var Purchase $purchase */
$purchase = Purchase::query()->create([
...$data,
'tenant_codigo' => $tenant->codigo,
'user_id' => $request->user()->id,
]);
$purchase->items()->createMany($purchaseItems);
return $purchase->load(['items.variant.product', 'items.variant.definitions.productAttribute.attribute']);
});
$purchase = $checkoutService->startCheckout(
$tenant,
$request->user()->id,
$data
);
return PurchaseResource::make($purchase)->response()->setStatusCode(201);
}
@@ -58,64 +52,94 @@ class PurchaseController extends Controller
{
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
return PurchaseResource::make(
$compra->loadMissing(['items.variant.product', 'items.variant.definitions.productAttribute.attribute'])
);
$compra->loadMissing(['items', 'cart.items']);
$this->loadBuyables($compra->items);
if ($compra->cart !== null) {
$this->loadBuyables($compra->cart->items);
}
return PurchaseResource::make($compra);
}
/**
* @param array<int, array<string, mixed>> $items
* @return \Illuminate\Support\Collection<int, ProductVariant>
*/
protected function resolveTenantVariants(Tenant $tenant, array $items)
public function paymentIntent(PaymentIntentRequest $request, Tenant $tenant, Purchase $compra): JsonResponse
{
$variantIds = collect($items)
->pluck('producto_variante_id')
->filter()
->map(static fn (mixed $id): int => (int) $id)
->unique()
->values();
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
$method = $request->validated('method');
$totalAmount = $compra->calculateCurrentTotalAmount();
$variants = ProductVariant::query()
->with('product')
->whereIn('id', $variantIds)
->whereHas('product', fn ($query) => $query->where('tenant_codigo', $tenant->codigo))
->get()
->keyBy('id');
$compra->update([
'payment_method' => $method,
'total' => $totalAmount,
]);
if ($variants->count() !== $variantIds->count()) {
throw ValidationException::withMessages([
'items' => 'One or more product variants do not belong to the tenant.',
if ($method === 'transfer') {
$telepagosService = new TelepagosIntegrationService;
$telepagosService->forTenant($tenant->codigo);
try {
$accountInfo = $telepagosService->getAccountInfo();
return response()->json([
'payment_method' => 'transfer',
'transfer_data' => [
'titular' => $accountInfo['holder'] ?? null,
'cvu' => $accountInfo['cvu'] ?? null,
'alias' => $accountInfo['alias'] ?? null,
'cuit' => $accountInfo['cuit'] ?? null,
'entidad' => $accountInfo['entity'] ?? 'Telepagos S.A.',
],
]);
} catch (\Exception $e) {
return response()->json([
'message' => 'Error getting account info: '.$e->getMessage(),
], 500);
}
}
if ($method === 'qr') {
$telepagosService = new TelepagosIntegrationService;
$telepagosService->forTenant($tenant->codigo);
try {
Log::info("Generating QR for purchase ID: {$compra->id}, amount: {$totalAmount}");
$qrResponse = $telepagosService->generateQr(
$totalAmount,
'Compra',
"Compra #{$compra->id}"
);
$telepagosQr = $compra->telepagosQr()->create([
'qr_order_id' => (string) ($qrResponse['qr_order_id'] ?? ''),
'qr_code' => $qrResponse['qr_code'] ?? '',
]);
} catch (\Exception $e) {
return response()->json([
'message' => 'Error generating QR: '.$e->getMessage(),
], 500);
}
return response()->json([
'payment_method' => 'qr',
'qr_data' => [
'qr_code' => $telepagosQr->qr_code,
'qr_order_id' => $telepagosQr->qr_order_id,
],
]);
}
return $variants;
return response()->json([
'message' => 'Invalid payment method.',
], 400);
}
/**
* @param array<int, array<string, mixed>> $items
* @param \Illuminate\Support\Collection<int, ProductVariant> $variants
* @return array<int, array<string, mixed>>
*/
protected function buildPurchaseItemsPayload(array $items, $variants): array
public function complete(Request $request, Tenant $tenant, Purchase $compra, CheckoutService $checkoutService): PurchaseResource
{
return collect($items)
->map(function (array $item) use ($variants): array {
/** @var ProductVariant $variant */
$variant = $variants->get((int) $item['producto_variante_id']);
$quantity = (int) $item['cantidad'];
$unitPrice = (float) ($variant->product?->precio ?? 0);
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
return [
'producto_variante_id' => $variant->getKey(),
'cantidad' => $quantity,
'precio_unitario' => $unitPrice,
'discount_total' => null,
'tax_total' => null,
'total' => $unitPrice * $quantity,
];
})
->all();
return PurchaseResource::make(
$checkoutService->completePurchase($compra)
);
}
protected function resolveScopedPurchase(Tenant $tenant, int $userId, Purchase $purchase): Purchase
@@ -126,4 +150,23 @@ class PurchaseController extends Controller
return $purchase;
}
/**
* @return list<string>
*/
protected function loadBuyables(Collection $items): void
{
$items->load([
'buyable' => function (MorphTo $morphTo): void {
$morphTo->morphWith([
ProductVariant::class => [
'product',
'definitions.productAttribute.attribute',
'attachments',
],
Bundle::class => ['items.variant'],
]);
},
]);
}
}

View File

@@ -3,30 +3,49 @@
namespace App\Domains\Purchase\Models;
use App\Domains\Auth\Models\User;
use App\Domains\Cart\Models\Cart;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
#[Fillable([
'cart_id',
'tenant_codigo',
'user_id',
'status',
'payment_status',
'payment_method',
'total',
'dni',
'telefono',
'nombre_apellido',
'email',
])]
class Purchase extends Model
{
use HasFactory;
public const STATUS_CREATED = 'created';
public const STATUS_PENDING_PAYMENT = 'pending_payment';
public const STATUS_PAID = 'paid';
public const STATUS_CANCELLED = 'cancelled';
public const STATUS_REJECTED = 'rejected';
protected $table = 'compras';
protected function casts(): array
{
return [
'cart_id' => 'integer',
'user_id' => 'integer',
'total' => 'decimal:2',
];
}
@@ -46,6 +65,14 @@ class Purchase extends Model
return $this->belongsTo(User::class);
}
/**
* @return BelongsTo<Cart, $this>
*/
public function cart(): BelongsTo
{
return $this->belongsTo(Cart::class, 'cart_id');
}
/**
* @return HasMany<PurchaseItem, $this>
*/
@@ -53,4 +80,64 @@ class Purchase extends Model
{
return $this->hasMany(PurchaseItem::class, 'compra_id');
}
/**
* @return HasOne<TelepagosQr, $this>
*/
public function telepagosQr()
{
return $this->hasOne(TelepagosQr::class, 'compra_id');
}
/**
* @return HasMany<TelepagosPayment, $this>
*/
public function telepagosPayments(): HasMany
{
return $this->hasMany(TelepagosPayment::class, 'compra_id');
}
public function getTotalAmount(): float
{
if ($this->total !== null) {
return (float) $this->total;
}
return $this->calculateCurrentTotalAmount();
}
public function calculateCurrentTotalAmount(): float
{
if ($this->relationLoaded('items') && $this->getRelation('items')->isNotEmpty()) {
return (float) $this->getRelation('items')->sum('total');
}
if ($this->items()->exists()) {
return (float) $this->items()->sum('total');
}
$cart = $this->relationLoaded('cart')
? $this->getRelation('cart')
: $this->cart()->with('items.buyable')->first();
if (! $cart) {
return 0.0;
}
return $cart->getTotalAmount();
}
public function markAsPendingPayment(): void
{
$this->update([
'status' => self::STATUS_PENDING_PAYMENT,
]);
}
public function markAsPaid(): void
{
$this->update([
'status' => self::STATUS_PAID,
]);
}
}

View File

@@ -10,7 +10,8 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable([
'compra_id',
'producto_variante_id',
'buyable_id',
'buyable_type',
'cantidad',
'precio_unitario',
'discount_total',
@@ -27,7 +28,8 @@ class PurchaseItem extends Model
{
return [
'compra_id' => 'integer',
'producto_variante_id' => 'integer',
'buyable_id' => 'integer',
'buyable_type' => 'string',
'cantidad' => 'integer',
'precio_unitario' => 'decimal:2',
'discount_total' => 'decimal:2',
@@ -45,10 +47,10 @@ class PurchaseItem extends Model
}
/**
* @return BelongsTo<ProductVariant, $this>
* @return \Illuminate\Database\Eloquent\Relations\MorphTo
*/
public function variant(): BelongsTo
public function buyable()
{
return $this->belongsTo(ProductVariant::class, 'producto_variante_id');
return $this->morphTo();
}
}

View File

@@ -0,0 +1,43 @@
<?php
namespace App\Domains\Purchase\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable([
'compra_id',
'cuit_buyer',
'cvu_buyer',
'amount',
'concept',
'operation',
'operation_id',
'transaction_id',
'qr_order_id',
'link_id',
])]
class TelepagosPayment extends Model
{
use HasFactory;
protected $table = 'telepagos_payments';
protected function casts(): array
{
return [
'compra_id' => 'integer',
'amount' => 'decimal:2',
];
}
/**
* @return BelongsTo<Purchase, $this>
*/
public function compra(): BelongsTo
{
return $this->belongsTo(Purchase::class, 'compra_id');
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace App\Domains\Purchase\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable([
'compra_id',
'qr_order_id',
'qr_code',
])]
class TelepagosQr extends Model
{
use HasFactory;
protected $table = 'telepagos_qr';
protected function casts(): array
{
return [
'compra_id' => 'integer',
];
}
/**
* @return BelongsTo<Purchase, $this>
*/
public function compra(): BelongsTo
{
return $this->belongsTo(Purchase::class, 'compra_id');
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace App\Domains\Purchase\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class PaymentIntentRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user() !== null;
}
/**
* @return array<string, mixed>
*/
public function rules(): array
{
return [
'method' => ['required', 'string', Rule::in(['qr', 'transfer'])],
];
}
}

View File

@@ -3,7 +3,6 @@
namespace App\Domains\Purchase\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class StorePurchaseRequest extends FormRequest
{
@@ -18,12 +17,11 @@ class StorePurchaseRequest extends FormRequest
public function rules(): array
{
return [
'status' => ['sometimes', 'string', Rule::in(['pending', 'paid', 'cancelled'])],
'payment_status' => ['sometimes', 'string', Rule::in(['pending', 'approved', 'rejected'])],
'payment_method' => ['nullable', 'string', 'max:255'],
'items' => ['required', 'array', 'min:1'],
'items.*.producto_variante_id' => ['required', 'integer', 'exists:productos_variantes,id'],
'items.*.cantidad' => ['required', 'integer', 'min:1'],
'cart_id' => ['required', 'integer', 'exists:carritos,id'],
'dni' => ['required', 'string'],
'telefono' => ['required', 'string'],
'nombre_apellido' => ['required', 'string'],
'email' => ['required', 'string', 'email'],
];
}
}

View File

@@ -2,12 +2,16 @@
namespace App\Domains\Purchase\Resources;
use App\Domains\Catalog\Resources\ProductVariantDefinitionResource;
use App\Domains\Bundle\Models\Bundle;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Models\ProductVariant;
use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Shared\Contracts\Buyable;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/**
* @mixin \App\Domains\Purchase\Models\PurchaseItem
* @mixin PurchaseItem|CartItem
*/
class PurchaseItemResource extends JsonResource
{
@@ -16,26 +20,112 @@ class PurchaseItemResource extends JsonResource
*/
public function toArray(Request $request): array
{
$variant = $this->variant;
$product = $variant?->product;
/** @var Buyable|null $buyable */
$buyable = $this->buyable;
$quantity = (int) ($this->cantidad ?? 0);
$unitPrice = $this->resolveUnitPrice();
$lineTotal = $this->resolveLineTotal($unitPrice, $quantity);
$variant = $buyable instanceof ProductVariant ? $buyable : null;
$imageUrl = null;
$attributes = [];
if ($this->buyable_type === ProductVariant::class && $buyable) {
$imageUrl = $this->resolveImageUrl($buyable);
$attributes = $this->resolveAttributes($buyable);
}
return [
'id' => $this->id,
'cantidad' => $this->cantidad,
'precio_unitario' => $this->formatMoney($this->precio_unitario),
'total' => $this->formatMoney($this->total),
'product' => $product === null ? null : [
'id' => $product->id,
'nombre' => $product->nombre,
'slug' => $product->slug,
'quantity' => $quantity,
'unit_price' => $this->formatMoney($unitPrice),
'line_total' => $this->formatMoney($lineTotal),
'buyable_type' => $this->mapBuyableTypeToAlias($this->buyable_type),
'buyable_id' => $this->buyable_id,
'product' => $variant === null ? null : [
'id' => $variant->product?->id,
'nombre' => $variant->product?->nombre,
'slug' => $variant->product?->slug,
'imagen' => $imageUrl,
],
'variant' => $variant === null ? null : [
'id' => $variant->id,
'definitions' => ProductVariantDefinitionResource::collection($variant->definitions),
'attributes' => $attributes,
],
'item_details' => $buyable === null ? null : [
'nombre' => $buyable->getName(),
'imagen' => $imageUrl,
'attributes' => $attributes,
],
];
}
protected function mapBuyableTypeToAlias(?string $type): string
{
return match ($type) {
ProductVariant::class => 'variant',
Bundle::class => 'bundle',
default => 'unknown',
};
}
protected function resolveUnitPrice(): float
{
if ($this->resource instanceof PurchaseItem) {
return (float) ($this->precio_unitario ?? 0);
}
if ($this->resource instanceof CartItem) {
return (float) ($this->buyable?->getPrice() ?? 0);
}
return 0.0;
}
protected function resolveLineTotal(float $unitPrice, int $quantity): float
{
if ($this->resource instanceof PurchaseItem) {
return (float) ($this->total ?? 0);
}
return $unitPrice * $quantity;
}
protected function resolveImageUrl($buyable): ?string
{
if (! $buyable->relationLoaded('attachments')) {
return null;
}
$attachment = $buyable->attachments->first();
if ($attachment === null) {
return null;
}
return $attachment->getTemporaryUrl(1440);
}
/**
* @return array<int, array{name: string, value: mixed}>
*/
protected function resolveAttributes($buyable): array
{
if (! $buyable->relationLoaded('definitions')) {
return [];
}
return $buyable->definitions
->map(function ($definition): array {
return [
'name' => (string) ($definition->productAttribute?->attribute?->nombre ?? ''),
'value' => $definition->value,
];
})
->filter(fn (array $attribute): bool => $attribute['name'] !== '' || $attribute['value'] !== null)
->values()
->all();
}
protected function formatMoney(float|int|string|null $amount): ?string
{
if ($amount === null) {

View File

@@ -2,11 +2,15 @@
namespace App\Domains\Purchase\Resources;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Collection;
/**
* @mixin \App\Domains\Purchase\Models\Purchase
* @mixin Purchase
*/
class PurchaseResource extends JsonResource
{
@@ -15,33 +19,87 @@ class PurchaseResource extends JsonResource
*/
public function toArray(Request $request): array
{
$items = $this->resource->relationLoaded('items')
? $this->resource->getRelation('items')
: collect();
[$items, $itemsSource] = $this->resolveItems();
$subtotal = $items->reduce(
fn (float $carry, $item): float => $carry + ((float) $item->precio_unitario * $item->cantidad),
0.0,
);
$subtotal = $items->isNotEmpty()
? $items->reduce(
fn (float $carry, PurchaseItem|CartItem $item): float => $carry + $this->resolveItemSubtotal($item),
0.0,
)
: (float) ($this->total ?? 0);
$total = $items->reduce(
fn (float $carry, $item): float => $carry + (float) $item->total,
0.0,
);
$total = $items->isNotEmpty()
? $items->reduce(
fn (float $carry, PurchaseItem|CartItem $item): float => $carry + $this->resolveItemTotal($item),
0.0,
)
: (float) ($this->total ?? 0);
return [
'id' => $this->id,
'cart_id' => $this->cart_id,
'tenant_codigo' => $this->tenant_codigo,
'user_id' => $this->user_id,
'created_at' => $this->created_at,
'status' => $this->status,
'payment_status' => $this->payment_status,
'payment_method' => $this->payment_method,
'dni' => $this->dni,
'telefono' => $this->telefono,
'nombre_apellido' => $this->nombre_apellido,
'email' => $this->email,
'items_source' => $itemsSource,
'items' => PurchaseItemResource::collection($items),
'subtotal' => $this->formatMoney($subtotal),
'total' => $this->formatMoney($total),
];
}
/**
* @return array{0: Collection<int, PurchaseItem|CartItem>, 1: string|null}
*/
protected function resolveItems(): array
{
if (! $this->resource->relationLoaded('items')) {
return [collect(), null];
}
$purchaseItems = $this->resource->getRelation('items');
if ($purchaseItems->isNotEmpty()) {
return [$purchaseItems, 'purchase'];
}
if (! $this->resource->relationLoaded('cart')) {
return [collect(), null];
}
$cart = $this->resource->getRelation('cart');
if ($cart === null || ! $cart->relationLoaded('items')) {
return [collect(), null];
}
return [$cart->getRelation('items'), 'cart'];
}
protected function resolveItemSubtotal(PurchaseItem|CartItem $item): float
{
if ($item instanceof PurchaseItem) {
return (float) $item->precio_unitario * $item->cantidad;
}
return (float) ($item->buyable?->getPrice() ?? 0) * $item->cantidad;
}
protected function resolveItemTotal(PurchaseItem|CartItem $item): float
{
if ($item instanceof PurchaseItem) {
return (float) ($item->total ?? 0);
}
return $this->resolveItemSubtotal($item);
}
protected function formatMoney(float|int|string|null $amount): string
{
return number_format((float) ($amount ?? 0), 2, '.', '');

View File

@@ -0,0 +1,233 @@
<?php
namespace App\Domains\Purchase\Services;
use App\Domains\Cart\Models\Cart;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Bundle\Models\Bundle;
use App\Domains\Catalog\Models\ProductVariant;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class CheckoutService
{
public function startCheckout(Tenant $tenant, int $userId, array $purchaseData): Purchase
{
$cartId = (int) $purchaseData['cart_id'];
unset($purchaseData['cart_id']);
return DB::transaction(function () use ($tenant, $userId, $purchaseData, $cartId): Purchase {
$cart = $this->resolveCheckoutCart($tenant, $userId, $cartId);
$cartItems = $cart->items()->lockForUpdate()->get();
if ($cartItems->isEmpty()) {
throw ValidationException::withMessages([
'cart_id' => 'The selected cart does not contain items.',
]);
}
$cartItems->load('buyable');
$cart->setRelation('items', $cartItems);
$totalAmount = $cart->getTotalAmount();
/** @var Purchase|null $purchase */
$purchase = Purchase::query()
->where('cart_id', $cart->getKey())
->where('tenant_codigo', $tenant->codigo)
->where('user_id', $userId)
->whereIn('status', [Purchase::STATUS_CREATED, Purchase::STATUS_PENDING_PAYMENT])
->latest('id')
->first();
if ($purchase === null) {
/** @var Purchase $purchase */
$purchase = Purchase::query()->create([
...$purchaseData,
'cart_id' => $cart->getKey(),
'tenant_codigo' => $tenant->codigo,
'user_id' => $userId,
'status' => Purchase::STATUS_CREATED,
'payment_method' => null,
'total' => $totalAmount,
]);
} else {
$purchase->fill([
...$purchaseData,
'status' => Purchase::STATUS_CREATED,
'payment_method' => null,
'total' => $totalAmount,
]);
$purchase->save();
}
return $purchase->load(['items.buyable']);
});
}
public function completePurchase(Purchase $purchase): Purchase
{
return DB::transaction(function () use ($purchase): Purchase {
/** @var Purchase $purchase */
$purchase = Purchase::query()
->lockForUpdate()
->findOrFail($purchase->getKey());
if ($purchase->payment_method === null) {
throw ValidationException::withMessages([
'payment_method' => 'The purchase payment method must be selected before finalizing.',
]);
}
if (in_array($purchase->status, [Purchase::STATUS_PAID, Purchase::STATUS_CANCELLED, Purchase::STATUS_REJECTED], true)) {
return $purchase->load(['items.buyable']);
}
$purchase->update([
'status' => Purchase::STATUS_PENDING_PAYMENT,
'total' => $purchase->calculateCurrentTotalAmount(),
]);
return $purchase->load(['items.buyable']);
});
}
public function confirmPurchase(Purchase $purchase): void
{
DB::transaction(function () use ($purchase): void {
/** @var Purchase $purchase */
$purchase = Purchase::query()
->lockForUpdate()
->findOrFail($purchase->getKey());
if ($purchase->items()->exists()) {
return;
}
/** @var Cart|null $cart */
$cart = $purchase->cart()->lockForUpdate()->first();
if ($cart === null) {
throw ValidationException::withMessages([
'cart_id' => 'The purchase cart is no longer available.',
]);
}
$cartItems = $cart->items()->lockForUpdate()->get();
if ($cartItems->isEmpty()) {
throw ValidationException::withMessages([
'cart_id' => 'The purchase cart does not contain items.',
]);
}
$cartItems->load('buyable');
$this->verifyTenantBuyables($purchase->tenant, $cartItems);
$purchaseItemsPayload = $this->buildPurchaseItemsPayload($cartItems);
$purchase->items()->createMany($purchaseItemsPayload);
$this->completeCartConversion($cart, $cartItems);
});
}
protected function verifyTenantBuyables(Tenant $tenant, Collection $cartItems): void
{
foreach ($cartItems as $item) {
$buyable = $item->buyable;
if ($buyable === null) {
throw ValidationException::withMessages([
'cart_id' => 'One or more buyables could not be loaded.',
]);
}
if ($item->buyable_type === ProductVariant::class && $buyable->product->tenant_codigo !== $tenant->codigo) {
throw ValidationException::withMessages([
'cart_id' => 'One or more product variants do not belong to the tenant.',
]);
}
if ($item->buyable_type === Bundle::class && $buyable->tenant_codigo !== $tenant->codigo) {
throw ValidationException::withMessages([
'cart_id' => 'One or more bundles do not belong to the tenant.',
]);
}
}
}
/**
* @param Collection<int, CartItem> $cartItems
* @return Collection<int, ProductVariant>
*/
protected function resolveCheckoutCart(Tenant $tenant, int $userId, int $cartId): Cart
{
/** @var Cart|null $cart */
$cart = Cart::query()
->lockForUpdate()
->find($cartId);
if ($cart === null || $cart->tenant_codigo !== $tenant->codigo || $cart->user_id !== $userId) {
throw new NotFoundHttpException('Cart not found for tenant.');
}
if ($cart->status !== 'active') {
throw ValidationException::withMessages([
'cart_id' => 'The selected cart is no longer active.',
]);
}
return $cart;
}
/**
* @param Collection<int, CartItem> $cartItems
* @return array<int, array<string, mixed>>
*/
protected function buildPurchaseItemsPayload(Collection $cartItems): array
{
return $cartItems
->map(function (CartItem $item): array {
$buyable = $item->buyable;
$quantity = (int) $item['cantidad'];
$unitPrice = $buyable?->getPrice() ?? 0;
return [
'buyable_type' => $item->buyable_type,
'buyable_id' => $item->buyable_id,
'cantidad' => $quantity,
'precio_unitario' => $unitPrice,
'discount_total' => null,
'tax_total' => null,
'total' => $unitPrice * $quantity,
];
})
->all();
}
/**
* @param Collection<int, CartItem> $cartItems
*/
protected function completeCartConversion(Cart $cart, Collection $cartItems): void
{
foreach ($cartItems as $item) {
$buyable = $item->buyable;
$quantity = (int) $item->cantidad;
try {
$buyable->buy($quantity);
} catch (\InvalidArgumentException $exception) {
throw ValidationException::withMessages([
'cart_id' => 'The selected cart has inconsistent stock state.',
]);
}
}
$cart->status = 'converted';
$cart->user_id = null;
$cart->guest_token = null;
$cart->save();
$cart->delete();
}
}

View File

@@ -3,6 +3,8 @@
use App\Domains\Purchase\Controllers\PurchaseController;
use Illuminate\Support\Facades\Route;
Route::prefix('tenants/{tenant:codigo}')->middleware('auth:sanctum')->group(function (): void {
Route::prefix('tenants/{tenant:codigo}')->middleware(['auth:sanctum', \App\Domains\Cart\Middleware\MergeGuestCartMiddleware::class])->group(function (): void {
Route::apiResource('compras', PurchaseController::class)->only(['index', 'store', 'show']);
Route::post('compras/{compra}/payment-intent', [PurchaseController::class, 'paymentIntent']);
Route::post('compras/{compra}/complete', [PurchaseController::class, 'complete']);
});

View File

@@ -0,0 +1,20 @@
<?php
namespace App\Domains\Shared\Contracts;
interface Buyable
{
public function getPrice(): float;
public function getName(): string;
public function availableQuantity(): ?int;
public function reserveStock(int $amount): void;
public function decrementReservedStock(int $amount): void;
public function buy(int $amount): void;
public function validateStock(): void;
}

View File

@@ -15,7 +15,7 @@ class BootstrapTenantController extends Controller
$dominio = $request->validated('dominio');
return TenantResource::make(
Tenant::query()->with(['headerLogo', 'footerLogo'])->where('dominio', $dominio)->firstOrFail()
Tenant::query()->with(['headerLogo', 'footerLogo', 'menues'])->where('dominio', $dominio)->firstOrFail()
);
}
}

View File

@@ -22,6 +22,8 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
'footer_bg_color',
'header_logo_id',
'footer_logo_id',
'hero_config',
'event_config',
])]
class Tenant extends Model
{
@@ -32,6 +34,19 @@ class Tenant extends Model
return 'codigo';
}
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'hero_config' => 'array',
'event_config' => 'array',
];
}
/**
* @return BelongsTo<Attachment, $this>
*/
@@ -49,11 +64,28 @@ class Tenant extends Model
}
/**
* @return HasMany<Product, $this>
* @return BelongsTo<Attachment, $this>
*/
public function heroBgImage(): BelongsTo
{
return $this->belongsTo(Attachment::class, 'hero_bg_image_id');
}
public function productos(): HasMany
{
return $this->hasMany(Product::class, 'tenant_codigo', 'codigo');
}
public function menues(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
{
return $this->belongsToMany(
\App\Domains\Menu\Models\Menu::class,
'tenant_menues',
'tenant_codigo',
'menu_code',
'codigo',
'code'
)->withTimestamps();
}
}

View File

@@ -61,6 +61,17 @@ class StoreTenantRequest extends FormRequest
'footer_bg_color' => ['required', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
'header_logo' => $logoRule,
'footer_logo' => $logoRule,
'hero_bg_image' => ['nullable', new ImageOrBase64Rule()],
'hero_config' => ['nullable', 'array'],
'hero_config.title_html' => ['nullable', 'string'],
'hero_config.description_html' => ['nullable', 'string'],
'hero_config.button_text' => ['nullable', 'string'],
'hero_config.button_href' => ['nullable', 'string'],
'event_config' => ['nullable', 'array'],
'event_config.title' => ['nullable', 'string'],
'event_config.location' => ['nullable', 'string'],
'event_config.dates' => ['nullable', 'array'],
'event_config.dates.*' => ['required', 'string'],
];
}
}

View File

@@ -72,6 +72,17 @@ class UpdateTenantRequest extends FormRequest
'footer_bg_color' => ['nullable', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
'header_logo' => $logoRule,
'footer_logo' => $logoRule,
'hero_bg_image' => ['nullable', new ImageOrBase64Rule()],
'hero_config' => ['nullable', 'array'],
'hero_config.title_html' => ['nullable', 'string'],
'hero_config.description_html' => ['nullable', 'string'],
'hero_config.button_text' => ['nullable', 'string'],
'hero_config.button_href' => ['nullable', 'string'],
'event_config' => ['nullable', 'array'],
'event_config.title' => ['nullable', 'string'],
'event_config.location' => ['nullable', 'string'],
'event_config.dates' => ['nullable', 'array'],
'event_config.dates.*' => ['required', 'string'],
];
}
}

View File

@@ -15,6 +15,12 @@ class TenantResource extends JsonResource
*/
public function toArray(Request $request): array
{
$heroConfig = $this->hero_config;
if (is_array($heroConfig)) {
$heroConfig['background_image'] = $this->heroBgImage?->getTemporaryUrl(1440);
unset($heroConfig['background_image_id']);
}
return [
'id' => $this->id,
'codigo' => $this->codigo,
@@ -29,6 +35,9 @@ class TenantResource extends JsonResource
// 1 day
'header_logo' => $this->headerLogo?->getTemporaryUrl(1440),
'footer_logo' => $this->footerLogo?->getTemporaryUrl(1440 ),
'hero_config' => $heroConfig,
'event_config' => $this->event_config,
'menues' => $this->whenLoaded('menues'),
];
}
}

View File

@@ -24,8 +24,9 @@ class TenantService
return DB::transaction(function () use ($data): Tenant {
$headerLogo = $data['header_logo'] ?? null;
$footerLogo = $data['footer_logo'] ?? null;
$heroBgImage = $data['hero_bg_image'] ?? null;
unset($data['header_logo'], $data['footer_logo']);
unset($data['header_logo'], $data['footer_logo'], $data['hero_bg_image']);
$headerAttachmentId = null;
if ($headerLogo) {
@@ -52,6 +53,18 @@ class TenantService
$data['header_logo_id'] = $headerAttachmentId;
$data['footer_logo_id'] = $footerAttachmentId;
if ($heroBgImage) {
$attachment = Str::isUuid($heroBgImage)
? \App\Domains\Attachable\Models\Attachment::query()->where('key', $heroBgImage)->first()
: $this->attachmentService->store($heroBgImage, 'tenants');
if ($attachment) {
$heroConfig = $data['hero_config'] ?? [];
$heroConfig['background_image_id'] = $attachment->id;
$data['hero_config'] = $heroConfig;
}
}
/** @var Tenant $tenant */
$tenant = Tenant::query()->create($data);
@@ -71,10 +84,14 @@ class TenantService
return DB::transaction(function () use ($tenant, $data): Tenant {
$hasHeaderLogoKey = array_key_exists('header_logo', $data);
$hasFooterLogoKey = array_key_exists('footer_logo', $data);
$hasHeroBgImageKey = array_key_exists('hero_bg_image', $data);
$headerLogo = $data['header_logo'] ?? null;
$footerLogo = $data['footer_logo'] ?? null;
$heroBgImage = $data['hero_bg_image'] ?? null;
unset($data['header_logo'], $data['footer_logo']);
unset($data['header_logo'], $data['footer_logo'], $data['hero_bg_image']);
$oldHeroBgId = $tenant->hero_bg_image_id;
$tenant->fill($data);
@@ -110,6 +127,28 @@ class TenantService
}
}
$currentHeroConfig = $tenant->hero_config ?? [];
if ($hasHeroBgImageKey) {
if ($heroBgImage) {
$attachment = Str::isUuid($heroBgImage)
? \App\Domains\Attachable\Models\Attachment::query()->where('key', $heroBgImage)->first()
: $this->attachmentService->store($heroBgImage, 'tenants');
if ($attachment) {
$currentHeroConfig['background_image_id'] = $attachment->id;
} else {
unset($currentHeroConfig['background_image_id']);
}
} else {
unset($currentHeroConfig['background_image_id']);
}
} else {
if ($oldHeroBgId) {
$currentHeroConfig['background_image_id'] = $oldHeroBgId;
}
}
$tenant->hero_config = empty($currentHeroConfig) ? null : $currentHeroConfig;
$tenant->save();
return $tenant;

View File

@@ -35,4 +35,8 @@ return [
],
],
'integrations' => [
'secret' => env('INTEGRATION_SECRET'),
],
];

View File

@@ -0,0 +1,31 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('integrations', function (Blueprint $table) {
$table->id();
$table->string('integration_code')->unique();
$table->string('name');
$table->string('url')->nullable();
$table->json('integration_data_schema')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('integrations');
}
};

View File

@@ -0,0 +1,36 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('tenant_integration', function (Blueprint $table) {
$table->id();
$table->string('integration_code');
$table->string('tenant_code');
$table->longText('integration_data')->nullable(); // Stored as longText because it's encrypted JSON
$table->timestamps();
// Foreign keys
$table->foreign('integration_code')->references('integration_code')->on('integrations')->onDelete('cascade');
$table->foreign('tenant_code')->references('codigo')->on('tenants')->onDelete('cascade');
$table->unique(['integration_code', 'tenant_code']);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('tenant_integration');
}
};

View File

@@ -0,0 +1,38 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('bank_accounts', function (Blueprint $table) {
$table->id();
$table->string('tenant_code');
$table->string('titular');
$table->string('entidad');
$table->string('alias');
$table->string('cvu');
$table->timestamps();
$table->foreign('tenant_code')
->references('codigo')
->on('tenants')
->cascadeOnUpdate()
->cascadeOnDelete();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('bank_accounts');
}
};

View File

@@ -0,0 +1,34 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('tenants', function (Blueprint $table) {
$table->unsignedBigInteger('selected_bank_account_id')->nullable()->after('footer_logo_id');
$table->foreign('selected_bank_account_id')
->references('id')
->on('bank_accounts')
->nullOnDelete();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('tenants', function (Blueprint $table) {
$table->dropForeign(['selected_bank_account_id']);
$table->dropColumn('selected_bank_account_id');
});
}
};

View File

@@ -0,0 +1,29 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
$table->string('dni')->nullable()->after('email');
$table->string('telefono')->nullable()->after('dni');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn(['dni', 'telefono']);
});
}
};

View File

@@ -0,0 +1,31 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('compras', function (Blueprint $table) {
$table->string('dni')->nullable()->after('payment_method');
$table->string('telefono')->nullable()->after('dni');
$table->string('nombre_apellido')->nullable()->after('telefono');
$table->string('email')->nullable()->after('nombre_apellido');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('compras', function (Blueprint $table) {
$table->dropColumn(['dni', 'telefono', 'nombre_apellido', 'email']);
});
}
};

View File

@@ -0,0 +1,37 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('telepagos_payments', function (Blueprint $table) {
$table->id();
$table->foreignId('compra_id')->constrained('compras')->onDelete('cascade');
$table->string('cuit_buyer')->nullable();
$table->string('cvu_buyer')->nullable();
$table->decimal('amount', 10, 2);
$table->string('concept')->nullable();
$table->string('operation')->nullable();
$table->string('operation_id')->nullable();
$table->string('transaction_id')->nullable();
$table->string('qr_order_id')->nullable();
$table->string('link_id')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('telepagos_payments');
}
};

View File

@@ -0,0 +1,30 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('telepagos_qr', function (Blueprint $table) {
$table->id();
$table->foreignId('compra_id')->constrained('compras')->onDelete('cascade');
$table->string('qr_order_id');
$table->text('qr_code');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('telepagos_qr');
}
};

View File

@@ -0,0 +1,33 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('compras', function (Blueprint $table) {
$table->foreignId('cart_id')
->nullable()
->after('user_id')
->constrained('carritos')
->cascadeOnUpdate()
->nullOnDelete();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('compras', function (Blueprint $table) {
$table->dropConstrainedForeignId('cart_id');
});
}
};

View File

@@ -0,0 +1,28 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('carritos', function (Blueprint $table) {
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('carritos', function (Blueprint $table) {
$table->dropSoftDeletes();
});
}
};

View File

@@ -0,0 +1,44 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('tenants', function (Blueprint $table) {
$table->dropForeign(['selected_bank_account_id']);
$table->dropColumn('selected_bank_account_id');
});
Schema::dropIfExists('bank_accounts');
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::create('bank_accounts', function (Blueprint $table) {
$table->id();
$table->string('tenant_code');
$table->string('titular');
$table->string('entidad');
$table->string('alias');
$table->string('cvu');
$table->timestamps();
$table->foreign('tenant_code')->references('codigo')->on('tenants')->onDelete('cascade');
});
Schema::table('tenants', function (Blueprint $table) {
$table->unsignedBigInteger('selected_bank_account_id')->nullable();
$table->foreign('selected_bank_account_id')->references('id')->on('bank_accounts')->onDelete('set null');
});
}
};

View File

@@ -0,0 +1,59 @@
<?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
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('compras', function (Blueprint $table) {
$table->decimal('total', 10, 2)->default(0)->after('payment_method');
});
DB::table('compras')
->orderBy('id')
->chunkById(100, function ($compras): void {
foreach ($compras as $compra) {
$itemsQuery = DB::table('compra_items')
->where('compra_id', $compra->id);
$hasItems = $itemsQuery->exists();
$itemsTotal = $itemsQuery->sum('total');
$total = (float) $itemsTotal;
if (! $hasItems && $compra->cart_id !== null) {
$cartTotal = DB::table('carrito_items as carrito_item')
->join('productos_variantes as variante', 'variante.id', '=', 'carrito_item.producto_variante_id')
->join('productos as producto', 'producto.id', '=', 'variante.producto_id')
->where('carrito_item.cart_id', $compra->cart_id)
->selectRaw('COALESCE(SUM(producto.precio * carrito_item.cantidad), 0) as total')
->value('total');
$total = (float) ($cartTotal ?? 0);
}
DB::table('compras')
->where('id', $compra->id)
->update([
'total' => number_format($total, 2, '.', ''),
]);
}
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('compras', function (Blueprint $table) {
$table->dropColumn('total');
});
}
};

View File

@@ -0,0 +1,83 @@
<?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
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('compras', function (Blueprint $table) {
$table->string('status')->default('created')->change();
});
if (Schema::hasColumn('compras', 'payment_status')) {
DB::table('compras')
->where('payment_status', 'approved')
->update(['status' => 'paid']);
DB::table('compras')
->where('payment_status', 'rejected')
->where('status', '!=', 'cancelled')
->update(['status' => 'rejected']);
}
DB::table('compras')
->where('status', 'pending')
->whereNull('payment_method')
->update(['status' => 'created']);
DB::table('compras')
->where('status', 'pending')
->whereNotNull('payment_method')
->update(['status' => 'pending_payment']);
if (Schema::hasColumn('compras', 'payment_status')) {
Schema::table('compras', function (Blueprint $table) {
$table->dropColumn('payment_status');
});
}
}
/**
* Reverse the migrations.
*/
public function down(): void
{
if (! Schema::hasColumn('compras', 'payment_status')) {
Schema::table('compras', function (Blueprint $table) {
$table->string('payment_status')->default('pending')->after('status');
});
}
DB::table('compras')
->where('status', 'paid')
->update([
'status' => 'paid',
'payment_status' => 'approved',
]);
DB::table('compras')
->where('status', 'rejected')
->update([
'status' => 'pending',
'payment_status' => 'rejected',
]);
DB::table('compras')
->whereIn('status', ['created', 'pending_payment'])
->update([
'status' => 'pending',
'payment_status' => 'pending',
]);
Schema::table('compras', function (Blueprint $table) {
$table->string('status')->default('pending')->change();
});
}
};

View File

@@ -0,0 +1,29 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('tenants', function (Blueprint $table) {
$table->json('hero_config')->nullable();
$table->json('event_config')->nullable();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('tenants', function (Blueprint $table) {
$table->dropColumn(['hero_config', 'event_config']);
});
}
};

View File

@@ -0,0 +1,31 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('tenants', function (Blueprint $table) {
$table->unsignedBigInteger('hero_bg_image_id')
->virtualAs('hero_config->>"$.background_image_id"')
->nullable()
->after('footer_bg_color');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('tenants', function (Blueprint $table) {
$table->dropColumn('hero_bg_image_id');
});
}
};

View File

@@ -0,0 +1,29 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('menues', function (Blueprint $table) {
$table->id();
$table->string('code')->unique();
$table->string('route');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('menues');
}
};

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