51 Commits

Author SHA1 Message Date
bf02d37a33 feat(sales): add Excel exports 2026-08-25 11:37:53 -03:00
78ce263849 feat(notification): update email branding to use website type for welcome and password reset emails 2026-08-25 11:03:06 -03:00
0c8419a5eb feat(notification): implement branding for emails using WebsiteType and update templates 2026-08-25 11:03:06 -03:00
843659583e Merge branch 'homo' of https://gitea.quo.ar/tbianchini/shopit-back into homo 2026-08-25 10:49:07 -03:00
c2921166bd feat(catalog): exclude out-of-stock items and update variant visibility logic 2026-08-25 10:49:05 -03:00
0f67e66b6b feat(category-visibility): add success messages for category visibility updates 2026-08-25 10:47:53 -03:00
725abed06a feat(category-visibility): implement category visibility controller and service with update functionality 2026-08-25 10:47:53 -03:00
743939fc63 feat(category-visibility): add success messages for category visibility updates 2026-08-25 10:47:53 -03:00
eb50e65fef feat(purchase): add filtering for multiple statuses in purchase index and order by status then date 2026-08-25 10:47:53 -03:00
1cf13501d8 feat(category-visibility): implement category visibility controller and service with update functionality 2026-08-25 10:47:53 -03:00
2eeef8d392 feat(catalog): add is_enabled attribute to categories and filter items accordingly 2026-08-25 10:47:53 -03:00
87a4fa6288 feat(catalog): add group_order field to catalog items and update related logic 2026-08-25 10:45:12 -03:00
07d2129410 feat(catalog): exclude out-of-stock items and update variant visibility logic 2026-08-25 09:32:56 -03:00
ceb1d1f1af Merge branch 'homo' of https://gitea.quo.ar/tbianchini/shopit-back into homo 2026-08-24 17:01:55 -03:00
885ab2a6e3 feat(category-visibility): add success messages for category visibility updates 2026-08-24 17:01:46 -03:00
47196a572a feat(category-visibility): implement category visibility controller and service with update functionality 2026-08-24 17:01:46 -03:00
45bba9516d feat(category-visibility): add success messages for category visibility updates 2026-08-24 17:00:48 -03:00
c6da71894e feat(purchase): add filtering for multiple statuses in purchase index and order by status then date 2026-08-24 17:00:48 -03:00
75d3c819d9 feat(category-visibility): implement category visibility controller and service with update functionality 2026-08-24 17:00:48 -03:00
bd6d672df2 feat(catalog): add is_enabled attribute to categories and filter items accordingly 2026-08-24 17:00:48 -03:00
6b06028771 fix(sales): render PDFs in client timezone 2026-08-24 16:42:38 -03:00
0aa423e90e feat(sales): validate PDF timezone parameter 2026-08-24 16:42:38 -03:00
e7bf2f887a Merge branch 'hotfix/change_history_time' 2026-08-24 16:13:19 -03:00
80a02fdc52 feat(sale): add changed_at serialization to SaleModificationResource 2026-08-24 16:12:55 -03:00
4162e2c1cc Merge branch 'homo' of https://gitea.quo.ar/tbianchini/shopit-back into homo 2026-08-24 16:05:15 -03:00
8d01620fa8 feat(sale-modification): add changed_at field serialization to ISO 8601 format 2026-08-24 16:05:10 -03:00
f8b8bab474 feat(category-visibility): add success messages for category visibility updates 2026-08-24 16:05:10 -03:00
53d1415b18 feat(purchase): add filtering for multiple statuses in purchase index and order by status then date 2026-08-24 16:05:10 -03:00
6ff9119086 feat(category-visibility): implement category visibility controller and service with update functionality 2026-08-24 16:05:10 -03:00
24e000b423 feat(catalog): add is_enabled attribute to categories and filter items accordingly 2026-08-24 16:05:10 -03:00
c69ebe5f7c feat(sale-modification): add changed_at field serialization to ISO 8601 format 2026-08-24 15:59:00 -03:00
c3a2da607d Merge branch 'dev' into homo 2026-08-24 12:45:51 -03:00
d1c4acc7ae feat(category-visibility): add success messages for category visibility updates 2026-08-24 12:44:37 -03:00
f8c4cc7428 Merge branch 'dev' into homo 2026-08-24 12:36:57 -03:00
21cfbe2a46 feat(purchase): add filtering for multiple statuses in purchase index and order by status then date 2026-08-24 12:35:20 -03:00
abc060ab25 Merge branch 'homo' of https://gitea.quo.ar/tbianchini/shopit-back into homo 2026-08-24 11:32:09 -03:00
80adbd9ca9 feat(category-visibility): implement category visibility controller and service with update functionality 2026-08-24 11:31:26 -03:00
12c10bbe06 feat(catalog): add is_enabled attribute to categories and filter items accordingly 2026-08-24 10:49:14 -03:00
36eb41a18a feat(invitation): update seat allocation structure and enhance provisioning logic 2026-08-22 14:16:57 +00:00
1dd2366957 feat(catalog): expose product unavailability messages 2026-08-21 16:47:15 -03:00
e8bcaa2026 feat(sales): handle in-review purchases as pending 2026-08-21 16:15:59 -03:00
5548fe8511 feat(purchase): restore in-review transfer lifecycle 2026-08-21 16:15:55 -03:00
dc0fbe06b8 fix(cart): invalidate checkout on mutation 2026-08-21 14:06:11 -03:00
afd69b8393 feat(checkout): track current cart purchase 2026-08-21 14:05:33 -03:00
a34d5cba1a test(sale): require purchase item snapshots 2026-08-21 13:42:30 -03:00
1650176aa0 refactor(checkout): keep source cart active 2026-08-21 13:42:30 -03:00
79e721ae63 refactor(checkout): disable purchase item editing 2026-08-21 11:03:48 -03:00
4e7e42d16e refactor(checkout): materialize purchase item snapshots at start 2026-08-21 11:03:39 -03:00
3a2dc8b7e0 feat(cart): implement restoration and reservation of source cart on expired checkout modification 2026-08-21 10:10:28 -03:00
0510c1aa12 test(checkout): cover source cart restoration 2026-08-21 09:29:23 -03:00
9d870be294 feat(checkout): restore source cart on cancellation 2026-08-21 09:29:23 -03:00
98 changed files with 2785 additions and 1785 deletions

View File

@@ -2,7 +2,6 @@
namespace App\Domains\Cart\Controllers; namespace App\Domains\Cart\Controllers;
use App\Domains\Cart\Models\Cart;
use App\Domains\Cart\Models\CartItem; use App\Domains\Cart\Models\CartItem;
use App\Domains\Cart\Requests\AddCartItemRequest; use App\Domains\Cart\Requests\AddCartItemRequest;
use App\Domains\Cart\Requests\UpdateCartItemQuantityRequest; use App\Domains\Cart\Requests\UpdateCartItemQuantityRequest;
@@ -78,36 +77,6 @@ class CartController extends Controller
]); ]);
} }
public function updateCheckoutItem(
UpdateCartItemQuantityRequest $request,
Tenant $tenant,
Cart $cart,
CartItem $cartItem,
): CartResource {
$updatesVariant = $request->exists('variant_id');
return CartResource::make(
$this->cartService->updateCheckoutItem(
$tenant,
$request,
$cart,
$cartItem->getKey(),
(int) $request->validated('cantidad'),
$updatesVariant
? ($request->validated('variant_id') !== null
? (int) $request->validated('variant_id')
: null)
: $cartItem->variant_id,
$updatesVariant,
),
)->additional([
'code' => $updatesVariant ? 'cart.item_updated' : 'cart.quantity_updated',
'message' => $updatesVariant
? __('api.cart.item_updated')
: __('api.cart.quantity_updated'),
]);
}
public function removeItem(Request $request, Tenant $tenant, CartItem $cartItem): CartResource public function removeItem(Request $request, Tenant $tenant, CartItem $cartItem): CartResource
{ {
return CartResource::make( return CartResource::make(
@@ -117,23 +86,4 @@ class CartController extends Controller
'message' => __('api.cart.item_removed'), 'message' => __('api.cart.item_removed'),
]); ]);
} }
public function removeCheckoutItem(
Request $request,
Tenant $tenant,
Cart $cart,
CartItem $cartItem,
): CartResource {
return CartResource::make(
$this->cartService->removeCheckoutItem(
$tenant,
$request,
$cart,
$cartItem->getKey(),
),
)->additional([
'code' => 'cart.item_removed',
'message' => __('api.cart.item_removed'),
]);
}
} }

View File

@@ -27,6 +27,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
'guest_token', 'guest_token',
'status', 'status',
'origin', 'origin',
'current_purchase_id',
])] ])]
class Cart extends Model class Cart extends Model
{ {
@@ -43,6 +44,7 @@ class Cart extends Model
{ {
return [ return [
'user_id' => 'integer', 'user_id' => 'integer',
'current_purchase_id' => 'integer',
]; ];
} }
@@ -76,6 +78,12 @@ class Cart extends Model
return $this->hasMany(Purchase::class, 'cart_id'); return $this->hasMany(Purchase::class, 'cart_id');
} }
/** @return BelongsTo<Purchase, $this> */
public function currentPurchase(): BelongsTo
{
return $this->belongsTo(Purchase::class, 'current_purchase_id');
}
public function getTotalAmount(): float public function getTotalAmount(): float
{ {
$items = $this->relationLoaded('items') $items = $this->relationLoaded('items')
@@ -98,7 +106,7 @@ class Cart extends Model
} }
return DB::transaction(function () use ($catalogItemId, $variantId, $quantity): CartItem { return DB::transaction(function () use ($catalogItemId, $variantId, $quantity): CartItem {
self::query()->whereKey($this->getKey())->lockForUpdate()->firstOrFail(); $this->invalidateCurrentCheckout();
$selectedItem = $this->resolveScopedItem($catalogItemId, $variantId, true); $selectedItem = $this->resolveScopedItem($catalogItemId, $variantId, true);
$cartQuantity = (int) $this->items() $cartQuantity = (int) $this->items()
->where('catalog_item_id', $catalogItemId) ->where('catalog_item_id', $catalogItemId)
@@ -163,6 +171,8 @@ class Cart extends Model
$updateVariant, $updateVariant,
$excludedPurchaseId, $excludedPurchaseId,
): CartItem { ): CartItem {
$this->invalidateCurrentCheckout();
/** @var CartItem $item */ /** @var CartItem $item */
$item = $this->items() $item = $this->items()
->where('id', $cartItemId) ->where('id', $cartItemId)
@@ -271,6 +281,8 @@ class Cart extends Model
public function removeItem(int $cartItemId): void public function removeItem(int $cartItemId): void
{ {
DB::transaction(function () use ($cartItemId): void { DB::transaction(function () use ($cartItemId): void {
$this->invalidateCurrentCheckout();
/** @var CartItem $item */ /** @var CartItem $item */
$item = $this->items() $item = $this->items()
->where('id', $cartItemId) ->where('id', $cartItemId)
@@ -291,6 +303,58 @@ class Cart extends Model
}); });
} }
private function invalidateCurrentCheckout(): void
{
$candidatePurchaseId = self::query()
->whereKey($this->getKey())
->value('current_purchase_id');
$currentPurchase = $candidatePurchaseId === null
? null
: Purchase::query()->lockForUpdate()->find($candidatePurchaseId);
/** @var self $cart */
$cart = self::query()->lockForUpdate()->findOrFail($this->getKey());
if ($cart->current_purchase_id !== $candidatePurchaseId) {
if ($cart->current_purchase_id !== null) {
throw ValidationException::withMessages([
'cart' => __('api.purchase.checkout_in_progress'),
]);
}
$this->current_purchase_id = null;
return;
}
if ($currentPurchase === null) {
return;
}
if ($currentPurchase->status === Purchase::STATUS_PAID) {
throw ValidationException::withMessages([
'cart' => __('api.cart.editing_disabled'),
]);
}
if (in_array($currentPurchase->status, [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
], true)) {
$currentPurchase->update([
'status' => Purchase::STATUS_SUPERSEDED,
'expires_at' => null,
]);
}
app(StockReservationService::class)->detachFromPurchase($currentPurchase);
self::query()
->whereKey($cart->getKey())
->where('current_purchase_id', $currentPurchase->getKey())
->update(['current_purchase_id' => null]);
$this->current_purchase_id = null;
}
protected function resolveScopedItem( protected function resolveScopedItem(
int $catalogItemId, int $catalogItemId,
?int $variantId, ?int $variantId,

View File

@@ -2,7 +2,6 @@
namespace App\Domains\Cart\Resources; namespace App\Domains\Cart\Resources;
use App\Domains\Cart\Models\Cart;
use App\Domains\Cart\Models\CartItem; use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Enums\InventoryPolicy; use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Catalog\Models\Variant; use App\Domains\Catalog\Models\Variant;
@@ -23,13 +22,9 @@ class CartItemResource extends JsonResource
$selectedItem = $this->selectedItem(); $selectedItem = $this->selectedItem();
$imageUrl = null; $imageUrl = null;
$tenant = $request->route('tenant'); $tenant = $request->route('tenant');
$checkoutCart = $request->route('cart');
$displayImage = ! $tenant instanceof Tenant || $tenant->display_cart_item_images; $displayImage = ! $tenant instanceof Tenant || $tenant->display_cart_item_images;
$includeVariants = $tenant instanceof Tenant $includeVariants = $tenant instanceof Tenant
&& ($checkoutCart instanceof Cart && $tenant->cart_editing_policy->allowsVariantChanges();
? $tenant->checkout_editing_policy
: $tenant->cart_editing_policy)
->allowsVariantChanges();
if ($displayImage && $selectedItem?->relationLoaded('attachments')) { if ($displayImage && $selectedItem?->relationLoaded('attachments')) {
$imageUrl = $selectedItem->attachments->first()?->getTemporaryUrl(1440); $imageUrl = $selectedItem->attachments->first()?->getTemporaryUrl(1440);

View File

@@ -4,14 +4,9 @@ namespace App\Domains\Cart\Services;
use App\Domains\Auth\Models\User; use App\Domains\Auth\Models\User;
use App\Domains\Cart\Models\Cart; use App\Domains\Cart\Models\Cart;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Services\StockReservationService;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Services\PurchaseStateGuard;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException; use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\Cookie; use Symfony\Component\HttpFoundation\Cookie;
@@ -19,11 +14,6 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class CartService class CartService
{ {
public function __construct(
private readonly StockReservationService $reservations,
private readonly PurchaseStateGuard $purchaseState,
) {}
public function show(Tenant $tenant, Request $request): Cart public function show(Tenant $tenant, Request $request): Cart
{ {
$resolvedIdentity = $this->resolveIdentity($request); $resolvedIdentity = $this->resolveIdentity($request);
@@ -89,125 +79,6 @@ class CartService
return $this->loadCart($cart, $tenant); return $this->loadCart($cart, $tenant);
} }
public function updateCheckoutItem(
Tenant $tenant,
Request $request,
Cart $cart,
int $cartItemId,
int $quantity,
?int $variantId,
bool $updateVariant,
): Cart {
$user = $request->user() ?? Auth::guard('sanctum')->user();
if (! $user instanceof User) {
throw new NotFoundHttpException('Checkout cart not found.');
}
return DB::transaction(function () use (
$tenant,
$user,
$cart,
$cartItemId,
$quantity,
$variantId,
$updateVariant,
): Cart {
/** @var Purchase|null $purchase */
$purchase = Purchase::query()
->where('cart_id', $cart->getKey())
->where('tenant_codigo', $tenant->codigo)
->where('user_id', $user->getKey())
->whereDoesntHave('items')
->lockForUpdate()
->first();
if ($purchase === null) {
throw new NotFoundHttpException('Checkout cart not found.');
}
$this->purchaseState->assertNotExpired($purchase);
if (! in_array($purchase->status, [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
], true)) {
throw new NotFoundHttpException('Checkout cart not found.');
}
/** @var Cart|null $checkoutCart */
$checkoutCart = Cart::query()
->whereKey($cart->getKey())
->where('tenant_codigo', $tenant->codigo)
->where('user_id', $user->getKey())
->where('status', 'checkout')
->lockForUpdate()
->first();
if ($checkoutCart === null) {
throw new NotFoundHttpException('Checkout cart not found.');
}
/** @var CartItem|null $cartItem */
$cartItem = $checkoutCart->items()
->whereKey($cartItemId)
->lockForUpdate()
->first();
if ($cartItem === null) {
throw new NotFoundHttpException('Checkout item not found.');
}
$hasChanges = (int) $cartItem->cantidad !== $quantity
|| ($updateVariant && $cartItem->variant_id !== $variantId);
if (! $hasChanges) {
return $this->loadCart($checkoutCart, $tenant, true);
}
if (
(int) $cartItem->cantidad !== $quantity
&& ! $tenant->checkout_editing_policy->allowsQuantityChanges()
) {
throw ValidationException::withMessages([
'cantidad' => __('api.cart.editing_disabled'),
]);
}
if (
$updateVariant
&& $cartItem->variant_id !== $variantId
&& ! $tenant->checkout_editing_policy->allowsVariantChanges()
) {
throw ValidationException::withMessages([
'variant_id' => __('api.cart.variant_change_disabled'),
]);
}
$checkoutCart->updateItem(
$cartItemId,
$quantity,
$variantId,
$updateVariant,
$purchase->getKey(),
);
$purchase->telepagosQr()->delete();
$purchase->update([
'status' => Purchase::STATUS_CREATED,
'payment_method' => null,
'transfer_payer_dni' => null,
'total' => $checkoutCart->getTotalAmount(),
'expires_at' => now()->addMinutes(
max(1, (int) config('purchase.checkout_expiration_minutes', 30)),
),
]);
$this->reservations->syncPurchaseExpiration($purchase);
return $this->loadCart($checkoutCart, $tenant, true);
});
}
public function removeItem(Tenant $tenant, Request $request, int $cartItemId): Cart public function removeItem(Tenant $tenant, Request $request, int $cartItemId): Cart
{ {
if (! $tenant->cart_editing_policy->allowsRemoval()) { if (! $tenant->cart_editing_policy->allowsRemoval()) {
@@ -223,77 +94,6 @@ class CartService
return $this->loadCart($cart, $tenant); return $this->loadCart($cart, $tenant);
} }
public function removeCheckoutItem(
Tenant $tenant,
Request $request,
Cart $cart,
int $cartItemId,
): Cart {
if (! $tenant->checkout_editing_policy->allowsRemoval()) {
throw ValidationException::withMessages([
'cart_item' => __('api.cart.editing_disabled'),
]);
}
$user = $request->user() ?? Auth::guard('sanctum')->user();
if (! $user instanceof User) {
throw new NotFoundHttpException('Checkout cart not found.');
}
return DB::transaction(function () use ($tenant, $user, $cart, $cartItemId): Cart {
/** @var Purchase|null $purchase */
$purchase = Purchase::query()
->where('cart_id', $cart->getKey())
->where('tenant_codigo', $tenant->codigo)
->where('user_id', $user->getKey())
->whereDoesntHave('items')
->lockForUpdate()
->first();
if ($purchase === null) {
throw new NotFoundHttpException('Checkout cart not found.');
}
$this->purchaseState->assertNotExpired($purchase);
if (! in_array($purchase->status, [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
], true)) {
throw new NotFoundHttpException('Checkout cart not found.');
}
/** @var Cart|null $checkoutCart */
$checkoutCart = Cart::query()
->whereKey($cart->getKey())
->where('tenant_codigo', $tenant->codigo)
->where('user_id', $user->getKey())
->where('status', 'checkout')
->lockForUpdate()
->first();
if ($checkoutCart === null) {
throw new NotFoundHttpException('Checkout cart not found.');
}
$checkoutCart->removeItem($cartItemId);
$purchase->telepagosQr()->delete();
$purchase->update([
'status' => Purchase::STATUS_CREATED,
'payment_method' => null,
'transfer_payer_dni' => null,
'total' => $checkoutCart->getTotalAmount(),
'expires_at' => now()->addMinutes(
max(1, (int) config('purchase.checkout_expiration_minutes', 30)),
),
]);
$this->reservations->syncPurchaseExpiration($purchase);
return $this->loadCart($checkoutCart, $tenant, true);
});
}
public function makeGuestTokenCookie(string $guestToken): Cookie public function makeGuestTokenCookie(string $guestToken): Cookie
{ {
$secure = (bool) config('session.secure'); $secure = (bool) config('session.secure');
@@ -327,7 +127,7 @@ class CartService
return $cart; return $cart;
} }
protected function loadCart(Cart $cart, Tenant $tenant, bool $isCheckout = false): Cart protected function loadCart(Cart $cart, Tenant $tenant): Cart
{ {
$relations = [ $relations = [
'items.catalogItem.attachments', 'items.catalogItem.attachments',
@@ -340,11 +140,7 @@ class CartService
'items.variant.eventDate', 'items.variant.eventDate',
]; ];
$editingPolicy = $isCheckout if ($tenant->cart_editing_policy->allowsVariantChanges()) {
? $tenant->checkout_editing_policy
: $tenant->cart_editing_policy;
if ($editingPolicy->allowsVariantChanges()) {
$relations = [ $relations = [
...$relations, ...$relations,
'items.catalogItem.variants' => fn ($query) => $query->orderBy('id'), 'items.catalogItem.variants' => fn ($query) => $query->orderBy('id'),

View File

@@ -10,10 +10,3 @@ Route::prefix('tenants/{tenant:codigo}')
Route::patch('cart/items/{cartItem}', [CartController::class, 'updateItemQuantity']); Route::patch('cart/items/{cartItem}', [CartController::class, 'updateItemQuantity']);
Route::delete('cart/items/{cartItem}', [CartController::class, 'removeItem']); Route::delete('cart/items/{cartItem}', [CartController::class, 'removeItem']);
}); });
Route::prefix('tenants/{tenant:codigo}')
->middleware('auth:sanctum')
->group(function (): void {
Route::patch('checkout-carts/{cart}/items/{cartItem}', [CartController::class, 'updateCheckoutItem'])->withTrashed();
Route::delete('checkout-carts/{cart}/items/{cartItem}', [CartController::class, 'removeCheckoutItem'])->withTrashed();
});

View File

@@ -27,6 +27,7 @@ use Illuminate\Support\Collection;
'type', 'type',
'slug', 'slug',
'nombre', 'nombre',
'group_order',
'descripcion', 'descripcion',
'precio', 'precio',
'inventory_policy', 'inventory_policy',
@@ -47,6 +48,7 @@ class CatalogItem extends Model
'inventory_policy' => InventoryPolicy::Tracked->value, 'inventory_policy' => InventoryPolicy::Tracked->value,
'inventory_subject' => InventorySubject::Product->value, 'inventory_subject' => InventorySubject::Product->value,
'has_tickets' => false, 'has_tickets' => false,
'group_order' => 0,
]; ];
protected function casts(): array protected function casts(): array
@@ -56,6 +58,7 @@ class CatalogItem extends Model
'brand_id' => 'integer', 'brand_id' => 'integer',
'inventory_id' => 'integer', 'inventory_id' => 'integer',
'type' => CatalogItemType::class, 'type' => CatalogItemType::class,
'group_order' => 'integer',
'precio' => 'decimal:2', 'precio' => 'decimal:2',
'inventory_policy' => InventoryPolicy::class, 'inventory_policy' => InventoryPolicy::class,
'inventory_subject' => InventorySubject::class, 'inventory_subject' => InventorySubject::class,
@@ -172,17 +175,29 @@ class CatalogItem extends Model
} }
/** @param Builder<CatalogItem> $query */ /** @param Builder<CatalogItem> $query */
public function scopeWhereVariantsAvailable(Builder $query): Builder public function scopeWhereAvailable(Builder $query): Builder
{ {
return $query->where(function (Builder $query): void { return $query->where(function (Builder $query): void {
$query $query
->whereDoesntHave('variants') ->where('catalog_items.inventory_policy', InventoryPolicy::Unlimited->value)
->orWhere('catalog_items.inventory_policy', InventoryPolicy::Unlimited->value)
->orWhereHas( ->orWhereHas(
'variants.inventory', 'variants.inventory',
fn (Builder $inventoryQuery): Builder => $inventoryQuery fn (Builder $inventoryQuery): Builder => $inventoryQuery
->whereColumn('inventories.real_stock', '>', 'inventories.reserved_stock') ->whereColumn('inventories.real_stock', '>', 'inventories.reserved_stock')
); )
->orWhere(function (Builder $directItemQuery): void {
$directItemQuery
->whereDoesntHave('variants')
->where(function (Builder $inventoryQuery): void {
$inventoryQuery
->whereNull('catalog_items.inventory_id')
->orWhereHas(
'inventory',
fn (Builder $availableInventoryQuery): Builder => $availableInventoryQuery
->whereColumn('inventories.real_stock', '>', 'inventories.reserved_stock')
);
});
});
}); });
} }

View File

@@ -15,6 +15,7 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
'tenant_code', 'tenant_code',
'categoria_id', 'categoria_id',
'nombre', 'nombre',
'is_enabled',
])] ])]
class Category extends Model class Category extends Model
{ {
@@ -22,6 +23,10 @@ class Category extends Model
protected $table = 'categorias'; protected $table = 'categorias';
protected $attributes = [
'is_enabled' => true,
];
/** /**
* @return array<string, string> * @return array<string, string>
*/ */
@@ -29,6 +34,7 @@ class Category extends Model
{ {
return [ return [
'categoria_id' => 'integer', 'categoria_id' => 'integer',
'is_enabled' => 'boolean',
]; ];
} }

View File

@@ -51,6 +51,7 @@ class StoreCatalogItemRequest extends FormRequest
), ),
], ],
'nombre' => ['required', 'string', 'max:255'], 'nombre' => ['required', 'string', 'max:255'],
'group_order' => ['sometimes', 'integer', 'min:0'],
'descripcion' => ['sometimes', 'nullable', 'string'], 'descripcion' => ['sometimes', 'nullable', 'string'],
'precio' => ['required', 'numeric', 'min:0'], 'precio' => ['required', 'numeric', 'min:0'],
'inventory_policy' => [Rule::prohibitedIf($isBundle), 'sometimes', Rule::enum(InventoryPolicy::class)], 'inventory_policy' => [Rule::prohibitedIf($isBundle), 'sometimes', Rule::enum(InventoryPolicy::class)],

View File

@@ -20,7 +20,6 @@ class CatalogFeaturedItemResource extends JsonResource
$catalogItem = $this->resource; $catalogItem = $this->resource;
/** @var FeaturedGroup $featuredGroup */ /** @var FeaturedGroup $featuredGroup */
$featuredGroup = $catalogItem->getRelation('featuredGroup'); $featuredGroup = $catalogItem->getRelation('featuredGroup');
$remainingUserQuota = $catalogItem->getAttribute('remaining_user_quota');
if ($featuredGroup->product_layout === ProductLayout::ColumnWithImage) { if ($featuredGroup->product_layout === ProductLayout::ColumnWithImage) {
return $this->columnWithImageData($catalogItem); return $this->columnWithImageData($catalogItem);
@@ -30,6 +29,9 @@ class CatalogFeaturedItemResource extends JsonResource
return $this->ticketSelectorData($catalogItem); return $this->ticketSelectorData($catalogItem);
} }
$remainingUserQuota = $catalogItem->getAttribute('remaining_user_quota');
$availableStock = $catalogItem->availableStock();
$data = [ $data = [
'id' => $catalogItem->id, 'id' => $catalogItem->id,
'type' => $catalogItem->type->value, 'type' => $catalogItem->type->value,
@@ -37,26 +39,38 @@ class CatalogFeaturedItemResource extends JsonResource
'descripcion' => $catalogItem->descripcion, 'descripcion' => $catalogItem->descripcion,
'precio' => $catalogItem->precio, 'precio' => $catalogItem->precio,
'maximum_addable_quantity' => $this->maximumAddable( 'maximum_addable_quantity' => $this->maximumAddable(
$catalogItem->availableStock(), $availableStock,
$remainingUserQuota,
),
'unavailable_message' => $this->unavailableMessage(
$availableStock,
$remainingUserQuota, $remainingUserQuota,
), ),
'variants' => $catalogItem->visibleVariants() 'variants' => $catalogItem->visibleVariants()
->map(fn (Variant $variant): array => [ ->map(function (Variant $variant) use ($catalogItem, $remainingUserQuota): array {
'id' => $variant->id, $variantStock = $catalogItem->inventory_policy === InventoryPolicy::Unlimited
'event_date_id' => $variant->event_date_id, ? null
'event_date' => $variant->eventDate?->date?->format('Y-m-d'), : $variant->inventory->availableStock();
'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(), return [
'descripcion' => $variant->getDescription(), 'id' => $variant->id,
'precio' => number_format($variant->getPrice(), 2, '.', ''), 'event_date_id' => $variant->event_date_id,
'maximum_addable_quantity' => $this->maximumAddable( 'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
$catalogItem->inventory_policy === InventoryPolicy::Unlimited 'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
? null 'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
: $variant->inventory->availableStock(), 'descripcion' => $variant->getDescription(),
$remainingUserQuota, 'precio' => number_format($variant->getPrice(), 2, '.', ''),
), 'maximum_addable_quantity' => $this->maximumAddable(
'values' => $variant->selectorOptions($catalogItem->itemAttributes), $variantStock,
]) $remainingUserQuota,
),
'unavailable_message' => $this->unavailableMessage(
$variantStock,
$remainingUserQuota,
),
'values' => $variant->selectorOptions($catalogItem->itemAttributes),
];
})
->values(), ->values(),
]; ];
@@ -66,6 +80,9 @@ class CatalogFeaturedItemResource extends JsonResource
/** @return array<string, mixed> */ /** @return array<string, mixed> */
private function ticketSelectorData(CatalogItem $catalogItem): array private function ticketSelectorData(CatalogItem $catalogItem): array
{ {
$availableStock = $catalogItem->availableStock();
$remainingUserQuota = $catalogItem->getAttribute('remaining_user_quota');
return [ return [
'id' => $catalogItem->id, 'id' => $catalogItem->id,
'type' => $catalogItem->type->value, 'type' => $catalogItem->type->value,
@@ -73,25 +90,32 @@ class CatalogFeaturedItemResource extends JsonResource
'descripcion' => $catalogItem->descripcion, 'descripcion' => $catalogItem->descripcion,
'precio' => $catalogItem->precio, 'precio' => $catalogItem->precio,
'image' => $this->firstImageUrl($catalogItem), 'image' => $this->firstImageUrl($catalogItem),
'maximum_addable_quantity' => $this->maximumAddable($availableStock, $remainingUserQuota),
'unavailable_message' => $this->unavailableMessage($availableStock, $remainingUserQuota),
]; ];
} }
/** @return array<string, mixed> */ /** @return array<string, mixed> */
private function columnWithImageData(CatalogItem $catalogItem): array private function columnWithImageData(CatalogItem $catalogItem): array
{ {
$availableStock = $catalogItem->availableStock();
$remainingUserQuota = $catalogItem->getAttribute('remaining_user_quota');
return [ return [
'id' => $catalogItem->id, 'id' => $catalogItem->id,
'type' => $catalogItem->type->value, 'type' => $catalogItem->type->value,
'nombre' => $catalogItem->nombre, 'nombre' => $catalogItem->nombre,
'precio' => $catalogItem->precio, 'precio' => $catalogItem->precio,
'image' => $this->firstImageUrl($catalogItem), 'image' => $this->firstImageUrl($catalogItem),
'maximum_addable_quantity' => $this->maximumAddable($availableStock, $remainingUserQuota),
'unavailable_message' => $this->unavailableMessage($availableStock, $remainingUserQuota),
]; ];
} }
private function firstImageUrl(CatalogItem $catalogItem): ?string private function firstImageUrl(CatalogItem $catalogItem): ?string
{ {
$attachment = $catalogItem->attachments->first() $attachment = $catalogItem->attachments->first()
?? $catalogItem->variants ?? $catalogItem->visibleVariants()
->flatMap(fn (Variant $variant) => $variant->attachments) ->flatMap(fn (Variant $variant) => $variant->attachments)
->first(); ->first();
@@ -103,4 +127,10 @@ class CatalogFeaturedItemResource extends JsonResource
return app(CatalogItemAllowanceService::class) return app(CatalogItemAllowanceService::class)
->maximumAddableQuantity($stock, $remainingUserQuota); ->maximumAddableQuantity($stock, $remainingUserQuota);
} }
private function unavailableMessage(?int $stock, ?int $remainingUserQuota): ?string
{
return app(CatalogItemAllowanceService::class)
->unavailableMessage($stock, $remainingUserQuota);
}
} }

View File

@@ -42,11 +42,15 @@ class CatalogItemDetailResource extends JsonResource
$selectedVariant === null, $selectedVariant === null,
fn () => $this->maximumAddable($this->availableStock()), fn () => $this->maximumAddable($this->availableStock()),
), ),
'unavailable_message' => $this->when(
$selectedVariant === null,
fn () => $this->unavailableMessage($this->availableStock()),
),
'images' => $this->when( 'images' => $this->when(
$selectedVariant === null, $selectedVariant === null,
fn () => $this->imageUrls($this->attachments), fn () => $this->imageUrls($this->attachments),
), ),
'variants' => $this->visibleVariants() 'variants' => $this->variants
->map(fn (Variant $variant): array => $this->variantData($variant)) ->map(fn (Variant $variant): array => $this->variantData($variant))
->values(), ->values(),
'selected_variant' => $this->when( 'selected_variant' => $this->when(
@@ -159,6 +163,7 @@ class CatalogItemDetailResource extends JsonResource
{ {
$values = $variant->selectionOptions($this->itemAttributes); $values = $variant->selectionOptions($this->itemAttributes);
$eventDates = $variant->selectedEventDates(); $eventDates = $variant->selectedEventDates();
$variantStock = $this->variantStock($variant);
return [ return [
'id' => $variant->id, 'id' => $variant->id,
@@ -168,7 +173,8 @@ class CatalogItemDetailResource extends JsonResource
'event_dates' => $eventDates->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(), 'event_dates' => $eventDates->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
'descripcion' => $variant->getDescription(), 'descripcion' => $variant->getDescription(),
'precio' => number_format($variant->getPrice(), 2, '.', ''), 'precio' => number_format($variant->getPrice(), 2, '.', ''),
'maximum_addable_quantity' => $this->maximumAddable($this->variantStock($variant)), 'maximum_addable_quantity' => $this->maximumAddable($variantStock),
'unavailable_message' => $this->unavailableMessage($variantStock),
'values' => $values, 'values' => $values,
]; ];
} }
@@ -195,4 +201,12 @@ class CatalogItemDetailResource extends JsonResource
$this->getAttribute('remaining_user_quota'), $this->getAttribute('remaining_user_quota'),
); );
} }
private function unavailableMessage(?int $stock): ?string
{
return app(CatalogItemAllowanceService::class)->unavailableMessage(
$stock,
$this->getAttribute('remaining_user_quota'),
);
}
} }

View File

@@ -15,8 +15,10 @@ class CatalogSearchItemResource extends JsonResource
/** @return array<string, mixed> */ /** @return array<string, mixed> */
public function toArray(Request $request): array public function toArray(Request $request): array
{ {
$availableStock = $this->availableStock();
$visibleVariants = $this->visibleVariants();
$attachment = $this->attachments->first() $attachment = $this->attachments->first()
?? $this->variants ?? $visibleVariants
->flatMap(fn (Variant $variant) => $variant->attachments) ->flatMap(fn (Variant $variant) => $variant->attachments)
->first(); ->first();
@@ -27,23 +29,27 @@ class CatalogSearchItemResource extends JsonResource
'descripcion' => $this->descripcion, 'descripcion' => $this->descripcion,
'precio' => $this->precio, 'precio' => $this->precio,
'image' => $attachment?->getTemporaryUrl(1440), 'image' => $attachment?->getTemporaryUrl(1440),
'maximum_addable_quantity' => $this->maximumAddable($this->availableStock()), 'maximum_addable_quantity' => $this->maximumAddable($availableStock),
'variants' => $this->visibleVariants() 'unavailable_message' => $this->unavailableMessage($availableStock),
->map(fn (Variant $variant): array => [ 'variants' => $visibleVariants
'id' => $variant->id, ->map(function (Variant $variant): array {
'event_date_id' => $variant->event_date_id, $variantStock = $this->inventory_policy === InventoryPolicy::Unlimited
'event_date' => $variant->eventDate?->date?->format('Y-m-d'), ? null
'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(), : $variant->inventory?->availableStock();
'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
'descripcion' => $variant->getDescription(), return [
'precio' => number_format($variant->getPrice(), 2, '.', ''), 'id' => $variant->id,
'maximum_addable_quantity' => $this->maximumAddable( 'event_date_id' => $variant->event_date_id,
$this->inventory_policy === InventoryPolicy::Unlimited 'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
? null 'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
: $variant->inventory?->availableStock(), 'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
), 'descripcion' => $variant->getDescription(),
'values' => $variant->selectorOptions($this->itemAttributes), 'precio' => number_format($variant->getPrice(), 2, '.', ''),
]) 'maximum_addable_quantity' => $this->maximumAddable($variantStock),
'unavailable_message' => $this->unavailableMessage($variantStock),
'values' => $variant->selectorOptions($this->itemAttributes),
];
})
->values(), ->values(),
]; ];
} }
@@ -55,4 +61,12 @@ class CatalogSearchItemResource extends JsonResource
$this->getAttribute('remaining_user_quota'), $this->getAttribute('remaining_user_quota'),
); );
} }
private function unavailableMessage(?int $stock): ?string
{
return app(CatalogItemAllowanceService::class)->unavailableMessage(
$stock,
$this->getAttribute('remaining_user_quota'),
);
}
} }

View File

@@ -8,6 +8,10 @@ use Illuminate\Support\Collection;
class CatalogItemAllowanceService class CatalogItemAllowanceService
{ {
private const USER_QUOTA_REACHED_MESSAGE = 'Alcanzaste el cupo máximo permitido para este producto.';
private const OUT_OF_STOCK_MESSAGE = 'Este producto no tiene stock disponible.';
public function __construct( public function __construct(
private readonly UserPurchaseLimitService $purchaseLimits, private readonly UserPurchaseLimitService $purchaseLimits,
) {} ) {}
@@ -37,4 +41,17 @@ class CatalogItemAllowanceService
return min($availableStock, $remainingUserQuota); return min($availableStock, $remainingUserQuota);
} }
public function unavailableMessage(?int $availableStock, ?int $remainingUserQuota): ?string
{
if ($remainingUserQuota !== null && $remainingUserQuota <= 0) {
return self::USER_QUOTA_REACHED_MESSAGE;
}
if ($availableStock !== null && $availableStock <= 0) {
return self::OUT_OF_STOCK_MESSAGE;
}
return null;
}
} }

View File

@@ -205,6 +205,13 @@ class CatalogService
]); ]);
$visibleVariants = $catalogItem->visibleVariants(); $visibleVariants = $catalogItem->visibleVariants();
if ($catalogItem->type === CatalogItemType::Standard
&& ($catalogItem->inventory_id !== null || $catalogItem->variants->isNotEmpty())
&& ! $catalogItem->isAvailable()) {
throw new NotFoundHttpException('Catalog item is out of stock.');
}
$catalogItem->setRelation('variants', $visibleVariants);
$selectedVariant = $variantId === null $selectedVariant = $variantId === null
? $visibleVariants->first() ? $visibleVariants->first()
: $visibleVariants->firstWhere('id', $variantId); : $visibleVariants->firstWhere('id', $variantId);
@@ -231,7 +238,7 @@ class CatalogService
$paginator = CatalogItem::query() $paginator = CatalogItem::query()
->where('tenant_code', $tenant->codigo) ->where('tenant_code', $tenant->codigo)
->whereVariantsAvailable() ->whereAvailable()
->where(function (Builder $query) use ($containsPattern): void { ->where(function (Builder $query) use ($containsPattern): void {
$query $query
->whereRaw('LOWER(nombre) LIKE ?', [$containsPattern]) ->whereRaw('LOWER(nombre) LIKE ?', [$containsPattern])
@@ -281,7 +288,7 @@ class CatalogService
return CatalogItem::query() return CatalogItem::query()
->where('tenant_code', $tenant->codigo) ->where('tenant_code', $tenant->codigo)
->where('category_id', $category->id) ->where('category_id', $category->id)
->whereVariantsAvailable() ->whereAvailable()
->with([ ->with([
'attachments', 'attachments',
'inventory', 'inventory',

View File

@@ -49,7 +49,16 @@ class FeaturedGroupService
{ {
$query = CatalogItem::query() $query = CatalogItem::query()
->where('catalog_items.tenant_code', $featuredGroup->tenant_code) ->where('catalog_items.tenant_code', $featuredGroup->tenant_code)
->whereVariantsAvailable() ->whereAvailable()
->where(function (Builder $query): void {
$query
->whereDoesntHave('category')
->orWhereHas(
'category',
fn (Builder $categoryQuery): Builder => $categoryQuery
->where('is_enabled', true),
);
})
->with([ ->with([
'inventory', 'inventory',
'attachments', 'attachments',
@@ -73,7 +82,9 @@ class FeaturedGroupService
FeaturedGroupSource::Category => $query FeaturedGroupSource::Category => $query
->where('catalog_items.category_id', $featuredGroup->category_id) ->where('catalog_items.category_id', $featuredGroup->category_id)
->orderBy('catalog_items.id'), ->orderBy('catalog_items.id'),
FeaturedGroupSource::All => $query->orderBy('catalog_items.id'), FeaturedGroupSource::All => $query
->orderBy('catalog_items.group_order')
->orderBy('catalog_items.id'),
}; };
} }

View File

@@ -37,16 +37,24 @@ class StockReservationService
}); });
} }
public function commit(CartItem $cartItem, CatalogItem|Variant $selection): void public function commit(
{ CartItem $cartItem,
DB::transaction(function () use ($cartItem, $selection): void { CatalogItem|Variant $selection,
Purchase $purchase,
): void {
DB::transaction(function () use ($cartItem, $selection, $purchase): void {
$this->ensure($cartItem, $selection); $this->ensure($cartItem, $selection);
$this->inventory->commit($selection, (int) $cartItem->cantidad); $this->inventory->commit($selection, (int) $cartItem->cantidad);
$requirements = $this->inventory->requirementsFor($selection, (int) $cartItem->cantidad); $requirements = $this->inventory->requirementsFor($selection, (int) $cartItem->cantidad);
foreach ($requirements as $inventoryId => $quantity) { foreach ($requirements as $inventoryId => $quantity) {
$reservation = $this->lockReservation($cartItem, $inventoryId); $reservation = $this->lockReservation($cartItem, $inventoryId);
if ($reservation === null || $reservation->status !== StockReservation::STATUS_ACTIVE || $reservation->quantity !== $quantity) { if (
$reservation === null
|| $reservation->status !== StockReservation::STATUS_ACTIVE
|| $reservation->purchase_id !== $purchase->getKey()
|| $reservation->quantity !== $quantity
) {
throw new \InvalidArgumentException('La reserva de stock no coincide con el item del carrito.'); throw new \InvalidArgumentException('La reserva de stock no coincide con el item del carrito.');
} }
@@ -118,6 +126,37 @@ class StockReservationService
]); ]);
} }
public function restore(CartItem $cartItem, CatalogItem|Variant $selection): void
{
DB::transaction(function () use ($cartItem, $selection): void {
$requirements = $this->inventory->requirementsFor(
$selection,
(int) $cartItem->cantidad,
);
$activeReservations = StockReservation::query()
->where('cart_item_id', $cartItem->getKey())
->where('status', StockReservation::STATUS_ACTIVE)
->lockForUpdate()
->get()
->keyBy('inventory_id');
$hasCompleteReservation = collect($requirements)->every(
fn (int $quantity, int $inventoryId): bool => (int) ($activeReservations->get($inventoryId)?->quantity ?? 0) === $quantity,
);
if ($hasCompleteReservation) {
return;
}
if ($activeReservations->isNotEmpty()) {
throw new \InvalidArgumentException('La reserva de stock del carrito es inconsistente.');
}
$this->inventory->reserve($selection, (int) $cartItem->cantidad);
$this->recordIncrease($cartItem, $selection, (int) $cartItem->cantidad);
});
}
public function syncPurchaseExpiration(Purchase $purchase): void public function syncPurchaseExpiration(Purchase $purchase): void
{ {
StockReservation::query() StockReservation::query()

View File

@@ -17,21 +17,25 @@ class InvitationPurchaseProvisioner
private const PAYMENT_METHOD = 'invitation'; private const PAYMENT_METHOD = 'invitation';
/** /**
* @var list<array{sector: string, row: int, seats: int, type: string}> * @var list<array{sector: string, row: int, first_seat: int, last_seat: int, type: string}>
*/ */
private const ALLOCATIONS = [ private const ALLOCATIONS = [
['sector' => 'A', 'row' => 1, 'seats' => 16, 'type' => 'NORMAL'], ['sector' => 'A', 'row' => 1, 'first_seat' => 1, 'last_seat' => 16, 'type' => 'NORMAL'],
['sector' => 'A', 'row' => 3, 'seats' => 14, 'type' => 'NORMAL'], ['sector' => 'A', 'row' => 3, 'first_seat' => 1, 'last_seat' => 14, 'type' => 'NORMAL'],
['sector' => 'C', 'row' => 1, 'seats' => 16, 'type' => 'VIP + LUNCH'], ['sector' => 'C', 'row' => 1, 'first_seat' => 1, 'last_seat' => 16, 'type' => 'VIP + LUNCH'],
['sector' => 'C', 'row' => 3, 'first_seat' => 6, 'last_seat' => 7, 'type' => 'NORMAL'],
]; ];
public function provision(): void /**
* @param list<array{sector: string, row: int, first_seat: int, last_seat: int, type: string}>|null $allocations
*/
public function provision(?array $allocations = null): void
{ {
if (! $this->prerequisitesExist()) { if (! $this->prerequisitesExist()) {
return; return;
} }
DB::transaction(function (): void { DB::transaction(function () use ($allocations): void {
$now = now(); $now = now();
$userId = $this->userId($now); $userId = $this->userId($now);
$purchaseId = $this->purchaseId($userId, $now); $purchaseId = $this->purchaseId($userId, $now);
@@ -44,8 +48,8 @@ class InvitationPurchaseProvisioner
throw new RuntimeException('No se encontró el catálogo de entradas del desfile.'); throw new RuntimeException('No se encontró el catálogo de entradas del desfile.');
} }
foreach (self::ALLOCATIONS as $allocation) { foreach ($allocations ?? self::ALLOCATIONS as $allocation) {
foreach (range(1, $allocation['seats']) as $seat) { foreach (range($allocation['first_seat'], $allocation['last_seat']) as $seat) {
$variant = $this->variant( $variant = $this->variant(
(int) $catalogItem->id, (int) $catalogItem->id,
$allocation['sector'], $allocation['sector'],

View File

@@ -0,0 +1,52 @@
<?php
namespace App\Domains\FiestaFutbolInfantil\Controllers;
use App\Domains\FiestaFutbolInfantil\Enums\FiestaCategory;
use App\Domains\FiestaFutbolInfantil\Requests\UpdateCategoryVisibilityRequest;
use App\Domains\FiestaFutbolInfantil\Services\CategoryVisibilityService;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class CategoryVisibilityController extends Controller
{
public function __construct(private readonly CategoryVisibilityService $visibilityService) {}
public function show(Request $request): JsonResponse
{
$category = $this->category($request);
$tenant = $request->user()->tenant()->firstOrFail();
return response()->json([
'data' => [
'is_enabled' => $this->visibilityService->isEnabled($tenant, $category),
],
]);
}
public function update(UpdateCategoryVisibilityRequest $request): JsonResponse
{
$category = $this->category($request);
$tenant = $request->user()->tenant()->firstOrFail();
$model = $this->visibilityService->update(
$tenant,
$category,
$request->boolean('is_enabled'),
);
return response()->json([
'data' => [
'is_enabled' => $model->is_enabled,
],
'message' => $model->is_enabled
? 'Mostrar en sitio web se activo correctamente'
: 'Mostrar en sitio web se desactivo correctamente',
]);
}
private function category(Request $request): FiestaCategory
{
return FiestaCategory::from((string) $request->route('category'));
}
}

View File

@@ -0,0 +1,21 @@
<?php
namespace App\Domains\FiestaFutbolInfantil\Enums;
enum FiestaCategory: string
{
case Entries = 'entries';
case Foods = 'foods';
case Accommodations = 'accommodations';
case Merchandise = 'merchandise';
public function categoryName(): string
{
return match ($this) {
self::Entries => 'Entradas',
self::Foods => 'Comidas',
self::Accommodations => 'Alojamientos',
self::Merchandise => 'Merchandising',
};
}
}

View File

@@ -0,0 +1,16 @@
<?php
namespace App\Domains\FiestaFutbolInfantil\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UpdateCategoryVisibilityRequest extends FormRequest
{
/** @return array<string, mixed> */
public function rules(): array
{
return [
'is_enabled' => ['required', 'boolean'],
];
}
}

View File

@@ -0,0 +1,29 @@
<?php
namespace App\Domains\FiestaFutbolInfantil\Services;
use App\Domains\Catalog\Models\Category;
use App\Domains\FiestaFutbolInfantil\Enums\FiestaCategory;
use App\Domains\Tenant\Models\Tenant;
class CategoryVisibilityService
{
public function isEnabled(Tenant $tenant, FiestaCategory $category): bool
{
return Category::query()
->where('tenant_code', $tenant->codigo)
->where('nombre', $category->categoryName())
->value('is_enabled') ?? true;
}
public function update(Tenant $tenant, FiestaCategory $category, bool $isEnabled): Category
{
$model = Category::query()->firstOrCreate([
'tenant_code' => $tenant->codigo,
'nombre' => $category->categoryName(),
]);
$model->update(['is_enabled' => $isEnabled]);
return $model;
}
}

View File

@@ -1,6 +1,7 @@
<?php <?php
use App\Domains\FiestaFutbolInfantil\Controllers\AccommodationController; use App\Domains\FiestaFutbolInfantil\Controllers\AccommodationController;
use App\Domains\FiestaFutbolInfantil\Controllers\CategoryVisibilityController;
use App\Domains\FiestaFutbolInfantil\Controllers\EntryController; use App\Domains\FiestaFutbolInfantil\Controllers\EntryController;
use App\Domains\FiestaFutbolInfantil\Controllers\FoodController; use App\Domains\FiestaFutbolInfantil\Controllers\FoodController;
use App\Domains\FiestaFutbolInfantil\Controllers\MerchandiseController; use App\Domains\FiestaFutbolInfantil\Controllers\MerchandiseController;
@@ -9,6 +10,20 @@ use Illuminate\Support\Facades\Route;
Route::prefix('v1/adminapp/tenant') Route::prefix('v1/adminapp/tenant')
->middleware(['auth:sanctum', 'adminapp.tenant']) ->middleware(['auth:sanctum', 'adminapp.tenant'])
->group(function (): void { ->group(function (): void {
$visibilityRoutes = static function (string $endpoint, string $category, string $menuCode): void {
Route::get("{$endpoint}/visibility", [CategoryVisibilityController::class, 'show'])
->defaults('category', $category)
->middleware("tenant.menu:{$menuCode}");
Route::patch("{$endpoint}/visibility", [CategoryVisibilityController::class, 'update'])
->defaults('category', $category)
->middleware("tenant.menu:{$menuCode}");
};
$visibilityRoutes('entries', 'entries', 'adminapp.fiesta-futbol-infantil.entradas');
$visibilityRoutes('foods', 'foods', 'adminapp.fiesta-futbol-infantil.comida');
$visibilityRoutes('accommodations', 'accommodations', 'adminapp.fiesta-futbol-infantil.alojamientos');
$visibilityRoutes('merchandise', 'merchandise', 'adminapp.fiesta-futbol-infantil.merchandising');
Route::get('entries', [EntryController::class, 'index']) Route::get('entries', [EntryController::class, 'index'])
->middleware('tenant.menu:adminapp.fiesta-futbol-infantil.entradas') ->middleware('tenant.menu:adminapp.fiesta-futbol-infantil.entradas')
->name('adminapp.fiesta-futbol-infantil.entries.index'); ->name('adminapp.fiesta-futbol-infantil.entries.index');

View File

@@ -12,10 +12,12 @@ class SaleFormService
$names = [ $names = [
Purchase::STATUS_CREATED => 'Creada', Purchase::STATUS_CREATED => 'Creada',
Purchase::STATUS_PENDING_PAYMENT => 'Esperando pago', Purchase::STATUS_PENDING_PAYMENT => 'Esperando pago',
Purchase::STATUS_IN_REVIEW => 'En revisión',
Purchase::STATUS_PAID => 'Confirmada', Purchase::STATUS_PAID => 'Confirmada',
Purchase::STATUS_CANCELLED => 'Cancelada', Purchase::STATUS_CANCELLED => 'Cancelada',
Purchase::STATUS_REJECTED => 'Rechazada', Purchase::STATUS_REJECTED => 'Rechazada',
Purchase::STATUS_EXPIRED => 'Vencida', Purchase::STATUS_EXPIRED => 'Vencida',
Purchase::STATUS_SUPERSEDED => 'Reemplazada',
]; ];
return [ return [

View File

@@ -3,6 +3,8 @@
namespace App\Domains\Integration\Services; namespace App\Domains\Integration\Services;
use App\Domains\Client\Models\Client; use App\Domains\Client\Models\Client;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Models\WebsiteType;
use Exception; use Exception;
use Illuminate\Contracts\Mail\Factory as MailFactory; use Illuminate\Contracts\Mail\Factory as MailFactory;
use Illuminate\Contracts\Mail\Mailer; use Illuminate\Contracts\Mail\Mailer;
@@ -70,24 +72,31 @@ class MailService extends BaseIntegrationService
return []; return [];
} }
public function send(string|array $recipient, string $subject, string $content): void public function send(
{ string|array $recipient,
string $subject,
string $content,
Tenant|WebsiteType|null $brand = null,
): void {
if (! $this->mailer || ! $this->tenant) { if (! $this->mailer || ! $this->tenant) {
throw new Exception('MailService no está configurado. Llamá a forTenant() o forClient() primero.'); throw new Exception('MailService no está configurado. Llamá a forTenant() o forClient() primero.');
} }
$this->tenant->loadMissing(['headerLogo', 'footerLogo']); $brand ??= $this->tenant;
$branding = $this->brandingFor($brand);
$html = Blade::render( $html = Blade::render(
<<<'BLADE' <<<'BLADE'
<x-mail.branded-layout :tenant="$tenant" :header-logo-url="$headerLogoUrl" :footer-logo-url="$footerLogoUrl"> <x-mail.branded-layout :branding="$branding" :header-logo-url="$headerLogoUrl" :footer-logo-url="$footerLogoUrl">
{!! $content !!} {!! $content !!}
</x-mail.branded-layout> </x-mail.branded-layout>
BLADE, BLADE,
[ [
'tenant' => $this->tenant, 'branding' => $branding,
'headerLogoUrl' => $this->tenant->headerLogo?->getTemporaryUrl(1440), 'headerLogoUrl' => $brand instanceof WebsiteType
'footerLogoUrl' => $this->tenant->footerLogo?->getTemporaryUrl(1440), ? $brand->siteLogo?->getTemporaryUrl(1440)
: $brand->headerLogo?->getTemporaryUrl(1440),
'footerLogoUrl' => $brand->footerLogo?->getTemporaryUrl(1440),
'content' => $content, 'content' => $content,
], ],
); );
@@ -106,6 +115,36 @@ class MailService extends BaseIntegrationService
: (string) config('mail.default'); : (string) config('mail.default');
} }
/** @return array{name: string, primary_color: string, body_color: string, background_color: string, surface_color: string, header_bg_color: string, footer_bg_color: string} */
private function brandingFor(Tenant|WebsiteType $brand): array
{
if ($brand instanceof WebsiteType) {
$brand->loadMissing(['siteLogo', 'footerLogo']);
return [
'name' => $brand->nombre,
'primary_color' => $brand->primary_color ?? '#FF7006',
'body_color' => $brand->body_color ?? '#666666',
'background_color' => $brand->background_color ?? '#f8f8f8',
'surface_color' => $brand->surface_color ?? '#ffffff',
'header_bg_color' => $brand->surface_color ?? '#ffffff',
'footer_bg_color' => $brand->login_header_footer_color ?? '#838383',
];
}
$brand->loadMissing(['headerLogo', 'footerLogo']);
return [
'name' => $brand->nombre,
'primary_color' => $brand->primary_color ?? '#6376f3',
'body_color' => '#334155',
'background_color' => '#f1f5f9',
'surface_color' => '#ffffff',
'header_bg_color' => $brand->header_bg_color ?? '#ffffff',
'footer_bg_color' => $brand->footer_bg_color ?? '#334155',
];
}
public function onSetup(): void public function onSetup(): void
{ {
if (! $this->mailer || ! $this->clientContext) { if (! $this->mailer || ! $this->clientContext) {

View File

@@ -78,6 +78,7 @@ class TelepagosWebhookService
->whereIn('status', [ ->whereIn('status', [
Purchase::STATUS_CREATED, Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT, Purchase::STATUS_PENDING_PAYMENT,
Purchase::STATUS_IN_REVIEW,
]) ])
->where('payment_method', 'transfer') ->where('payment_method', 'transfer')
->where('total', $amount) ->where('total', $amount)

View File

@@ -28,10 +28,21 @@ class TestMail extends Mailable
{ {
$this->tenant->loadMissing(['headerLogo', 'footerLogo']); $this->tenant->loadMissing(['headerLogo', 'footerLogo']);
$branding = [
'name' => $this->tenant->nombre,
'primary_color' => $this->tenant->primary_color ?? '#6376f3',
'body_color' => '#334155',
'background_color' => '#f1f5f9',
'surface_color' => '#ffffff',
'header_bg_color' => $this->tenant->header_bg_color ?? '#ffffff',
'footer_bg_color' => $this->tenant->footer_bg_color ?? '#334155',
];
return new Content( return new Content(
view: 'mail.test', view: 'mail.test',
with: [ with: [
'tenant' => $this->tenant, 'tenant' => $this->tenant,
'branding' => $branding,
'headerLogoUrl' => $this->tenant->headerLogo?->getTemporaryUrl(1440), 'headerLogoUrl' => $this->tenant->headerLogo?->getTemporaryUrl(1440),
'footerLogoUrl' => $this->tenant->footerLogo?->getTemporaryUrl(1440), 'footerLogoUrl' => $this->tenant->footerLogo?->getTemporaryUrl(1440),
], ],

View File

@@ -21,15 +21,17 @@ class NotificationMailService
public function sendWelcome(int $userId, string $tenantCode): void public function sendWelcome(int $userId, string $tenantCode): void
{ {
$tenant = Tenant::query()->where('codigo', $tenantCode)->firstOrFail(); $tenant = Tenant::query()->with('websiteType')->where('codigo', $tenantCode)->firstOrFail();
$user = User::query()->findOrFail($userId); $user = User::query()->findOrFail($userId);
$brand = $tenant->websiteType ?? $tenant;
$this->mailService $this->mailService
->forTenant($tenantCode) ->forTenant($tenantCode)
->send( ->send(
$user->email, $user->email,
"Bienvenido a {$tenant->nombre}", "Bienvenido a {$brand->nombre}",
view('mail.notifications.welcome', compact('tenant', 'user'))->render(), view('mail.notifications.welcome', compact('brand', 'user'))->render(),
$brand,
); );
} }
@@ -75,13 +77,19 @@ class NotificationMailService
$recoveryUrl = $recoveryDomain === null $recoveryUrl = $recoveryDomain === null
? null ? null
: 'https://'.$recoveryDomain.$recoveryBasePath.'/recuperar-contrasena/codigo?'.http_build_query($recoveryQuery); : 'https://'.$recoveryDomain.$recoveryBasePath.'/recuperar-contrasena/codigo?'.http_build_query($recoveryQuery);
$brand = $tenant->websiteType ?? $tenant;
$this->mailService $this->mailService
->forTenant($tenantCode) ->forTenant($tenantCode)
->send( ->send(
$attempt->user->email, $attempt->user->email,
"Código para recuperar tu contraseña - {$tenant->nombre}", "Código para recuperar tu contraseña - {$brand->nombre}",
view('mail.notifications.password-reset', compact('tenant', 'attempt', 'recoveryUrl'))->render(), view('mail.notifications.password-reset', [
'attempt' => $attempt,
'recoveryUrl' => $recoveryUrl,
'brand' => $brand,
])->render(),
$brand,
); );
} }

View File

@@ -23,4 +23,6 @@ No expone rutas HTTP. Consume datos de `Auth`, `Tenant`, `Purchase` y `Ticket`,
- Los listeners reciben identificadores y vuelven a cargar los modelos, evitando transportar entidades obsoletas. - Los listeners reciben identificadores y vuelven a cargar los modelos, evitando transportar entidades obsoletas.
- La recuperación no se envía si el intento dejó de estar pendiente. - La recuperación no se envía si el intento dejó de estar pendiente.
- Los correos de cuenta (bienvenida y recuperación de contraseña) usan la identidad visual del `WebsiteType` asociado al tenant, con fallback al tenant si no tiene uno configurado.
- Los correos transaccionales (pago confirmado y tickets disponibles) usan la identidad visual del tenant/evento de la compra.
- Los handlers deben permanecer idempotentes o tolerantes a reintentos de cola. - Los handlers deben permanecer idempotentes o tolerantes a reintentos de cola.

View File

@@ -4,11 +4,9 @@ namespace App\Domains\Purchase\Controllers;
use App\Domains\Integration\Services\TelepagosIntegrationService; use App\Domains\Integration\Services\TelepagosIntegrationService;
use App\Domains\Purchase\Models\Purchase; use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Purchase\Requests\PaymentIntentRequest; use App\Domains\Purchase\Requests\PaymentIntentRequest;
use App\Domains\Purchase\Requests\StartCheckoutRequest; use App\Domains\Purchase\Requests\StartCheckoutRequest;
use App\Domains\Purchase\Requests\UpdatePurchaseCustomerRequest; use App\Domains\Purchase\Requests\UpdatePurchaseCustomerRequest;
use App\Domains\Purchase\Requests\UpdatePurchaseItemRequest;
use App\Domains\Purchase\Resources\PurchaseResource; use App\Domains\Purchase\Resources\PurchaseResource;
use App\Domains\Purchase\Services\Checkout\PurchaseResponseLoader; use App\Domains\Purchase\Services\Checkout\PurchaseResponseLoader;
use App\Domains\Purchase\Services\CheckoutService; use App\Domains\Purchase\Services\CheckoutService;
@@ -26,13 +24,22 @@ class PurchaseController extends Controller
{ {
public function index(Request $request, Tenant $tenant): JsonResponse public function index(Request $request, Tenant $tenant): JsonResponse
{ {
$statusParam = $request->query('status');
$statuses = is_string($statusParam)
? collect(explode(',', $statusParam))
->map(fn (string $status): string => trim($status))
->filter()
->unique()
->values()
->all()
: [];
return PurchaseResource::collection( return PurchaseResource::collection(
Purchase::query() Purchase::query()
->where('tenant_codigo', $tenant->codigo) ->where('tenant_codigo', $tenant->codigo)
->where('user_id', $request->user()->id) ->where('user_id', $request->user()->id)
->when($request->query('status'), function ($query, $status) { ->when($statuses !== [], fn ($query) => $query->whereIn('status', $statuses))
$query->where('status', $status); ->orderBy('status')
})
->latest() ->latest()
->paginateFromRequest() ->paginateFromRequest()
)->response(); )->response();
@@ -81,53 +88,6 @@ class PurchaseController extends Controller
); );
} }
public function updateItem(
UpdatePurchaseItemRequest $request,
Tenant $tenant,
Purchase $compra,
PurchaseItem $item,
CheckoutService $checkoutService,
): PurchaseResource {
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
return PurchaseResource::make(
$checkoutService->updateItem(
$compra,
$item,
$request->exists('quantity') ? (int) $request->validated('quantity') : null,
$request->exists('variant_id') ? (int) $request->validated('variant_id') : null,
$request->exists('variant_id'),
),
);
}
public function prepareItemEditing(
Request $request,
Tenant $tenant,
Purchase $compra,
CheckoutService $checkoutService,
): PurchaseResource {
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
return PurchaseResource::make(
$checkoutService->prepareItemEditing($compra),
);
}
public function removeItem(
Request $request,
Tenant $tenant,
Purchase $compra,
PurchaseItem $item,
CheckoutService $checkoutService,
): PurchaseResource {
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
return PurchaseResource::make(
$checkoutService->removeItem($compra, $item),
);
}
public function paymentIntent( public function paymentIntent(
PaymentIntentRequest $request, PaymentIntentRequest $request,
Tenant $tenant, Tenant $tenant,
@@ -163,6 +123,8 @@ class PurchaseController extends Controller
return false; return false;
} }
$purchaseState->lockCurrentCart($purchase);
$purchaseUpdate = [ $purchaseUpdate = [
'payment_method' => $method, 'payment_method' => $method,
'status' => Purchase::STATUS_PENDING_PAYMENT, 'status' => Purchase::STATUS_PENDING_PAYMENT,

View File

@@ -39,6 +39,8 @@ class Purchase extends Model
public const STATUS_PENDING_PAYMENT = 'pending_payment'; public const STATUS_PENDING_PAYMENT = 'pending_payment';
public const STATUS_IN_REVIEW = 'in_review';
public const STATUS_PAID = 'paid'; public const STATUS_PAID = 'paid';
public const STATUS_CANCELLED = 'cancelled'; public const STATUS_CANCELLED = 'cancelled';
@@ -47,16 +49,20 @@ class Purchase extends Model
public const STATUS_EXPIRED = 'expired'; public const STATUS_EXPIRED = 'expired';
public const STATUS_SUPERSEDED = 'superseded';
/** @return list<string> */ /** @return list<string> */
public static function statuses(): array public static function statuses(): array
{ {
return [ return [
self::STATUS_CREATED, self::STATUS_CREATED,
self::STATUS_PENDING_PAYMENT, self::STATUS_PENDING_PAYMENT,
self::STATUS_IN_REVIEW,
self::STATUS_PAID, self::STATUS_PAID,
self::STATUS_CANCELLED, self::STATUS_CANCELLED,
self::STATUS_REJECTED, self::STATUS_REJECTED,
self::STATUS_EXPIRED, self::STATUS_EXPIRED,
self::STATUS_SUPERSEDED,
]; ];
} }
@@ -154,12 +160,7 @@ class Purchase extends Model
return (float) $this->getRelation('items')->sum('total'); return (float) $this->getRelation('items')->sum('total');
} }
$itemsTotal = (float) $this->items()->sum('total'); return (float) $this->items()->sum('total');
if ($itemsTotal > 0 || $this->items()->exists()) {
return $itemsTotal;
}
return (float) ($this->cart?->getTotalAmount() ?? $this->total ?? 0);
} }
protected function valueChangeTenantCode(): string protected function valueChangeTenantCode(): string

View File

@@ -1,22 +0,0 @@
<?php
namespace App\Domains\Purchase\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UpdatePurchaseItemRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user() !== null;
}
/** @return array<string, mixed> */
public function rules(): array
{
return [
'quantity' => ['sometimes', 'required_without:variant_id', 'integer', 'min:1', 'max:100'],
'variant_id' => ['sometimes', 'required_without:quantity', 'integer', 'min:1'],
];
}
}

View File

@@ -2,16 +2,12 @@
namespace App\Domains\Purchase\Resources; namespace App\Domains\Purchase\Resources;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Purchase\Models\PurchaseItem; use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Http\Resources\Json\JsonResource;
/** @mixin PurchaseItem|CartItem */ /** @mixin PurchaseItem */
class PurchaseItemResource extends JsonResource class PurchaseItemResource extends JsonResource
{ {
/** @return array<string, mixed> */ /** @return array<string, mixed> */
@@ -20,158 +16,29 @@ class PurchaseItemResource extends JsonResource
$tenant = $request->route('tenant'); $tenant = $request->route('tenant');
$displayImage = ! $tenant instanceof Tenant || $tenant->display_cart_item_images; $displayImage = ! $tenant instanceof Tenant || $tenant->display_cart_item_images;
if ($this->resource instanceof PurchaseItem) {
$imageUrl = $displayImage
? $this->imageAttachment?->getTemporaryUrl(1440)
: null;
$attributes = $this->variant_attributes ?? [];
$catalogItem = $this->relationLoaded('sourceCatalogItem')
? $this->sourceCatalogItem
: null;
$includeVariants = $tenant instanceof Tenant
&& $tenant->checkout_editing_policy->allowsVariantChanges()
&& $catalogItem !== null
&& $catalogItem->relationLoaded('variants');
return [
'id' => $this->id,
'quantity' => (int) $this->cantidad,
'unit_price' => $this->formatMoney($this->precio_unitario),
'line_total' => $this->formatMoney($this->total),
'source_catalog_item_id' => $this->source_catalog_item_id,
'source_variant_id' => $this->source_variant_id,
'item_details' => [
'nombre' => $this->item_nombre,
'descripcion' => $this->descripcion,
'slug' => $this->slug,
'imagen' => $imageUrl,
'attributes' => $attributes,
],
'variants' => $this->when(
$includeVariants,
fn () => $catalogItem
->visibleVariants($this->source_variant_id)
->map(fn (Variant $variant): array => $this->variantData($catalogItem, $variant))
->values(),
),
];
}
$selectedItem = $this->selectedItem();
$catalogItem = $this->catalogItem;
$variant = $this->variant;
$quantity = (int) ($this->cantidad ?? 0);
$unitPrice = $this->resolveUnitPrice($selectedItem);
$lineTotal = $unitPrice * $quantity;
$imageUrl = $displayImage $imageUrl = $displayImage
? $this->resolveImageUrl($selectedItem, $catalogItem) ? $this->imageAttachment?->getTemporaryUrl(1440)
: null; : null;
$includeVariants = $tenant instanceof Tenant
&& $tenant->checkout_editing_policy->allowsVariantChanges()
&& $catalogItem?->relationLoaded('variants');
return [ return [
'id' => $this->id, 'id' => $this->id,
'quantity' => $quantity, 'quantity' => (int) $this->cantidad,
'unit_price' => $this->formatMoney($unitPrice), 'unit_price' => $this->formatMoney($this->precio_unitario),
'line_total' => $this->formatMoney($lineTotal), 'line_total' => $this->formatMoney($this->total),
'source_catalog_item_id' => $this->catalog_item_id, 'source_catalog_item_id' => $this->source_catalog_item_id,
'source_variant_id' => $this->variant_id, 'source_variant_id' => $this->source_variant_id,
'item_details' => $selectedItem === null ? null : [ 'item_details' => [
'nombre' => $selectedItem->getName(), 'nombre' => $this->item_nombre,
'descripcion' => $selectedItem->getDescription(), 'descripcion' => $this->descripcion,
'slug' => $catalogItem?->slug, 'slug' => $this->slug,
'imagen' => $imageUrl, 'imagen' => $imageUrl,
'attributes' => $variant === null ? [] : $this->resolveAttributes($variant), 'attributes' => $this->variant_attributes ?? [],
], ],
'variants' => $this->when(
$includeVariants,
fn () => $catalogItem
->visibleVariants($this->variant_id)
->map(fn (Variant $availableVariant): array => $this->variantData(
$catalogItem,
$availableVariant,
))
->values(),
),
]; ];
} }
private function resolveUnitPrice(CatalogItem|Variant|null $selectedItem): float
{
return (float) ($selectedItem?->getPrice() ?? 0);
}
private function resolveImageUrl(
CatalogItem|Variant|null $selectedItem,
?CatalogItem $catalogItem,
): ?string {
$attachment = $selectedItem?->relationLoaded('attachments')
? $selectedItem->attachments->first()
: null;
if ($attachment === null && $catalogItem?->relationLoaded('attachments')) {
$attachment = $catalogItem->attachments->first();
}
return $attachment?->getTemporaryUrl(1440);
}
/** @return array<int, array{name: string, value: mixed}> */
private function resolveAttributes(Variant $variant): array
{
if (! $variant->relationLoaded('definitions')) {
return [];
}
$attributes = $variant->definitions
->groupBy('item_attribute_id')
->map(function ($definitions): array {
$itemAttribute = $definitions->first()?->itemAttribute;
$values = $definitions->pluck('value')->values();
return [
'name' => (string) ($itemAttribute?->attribute?->nombre ?? ''),
'value' => $itemAttribute?->allow_multi_select
? $values->all()
: $values->first(),
];
})
->filter(fn (array $attribute): bool => $attribute['name'] !== '' || $attribute['value'] !== null)
->values();
$eventDates = $variant->relationLoaded('eventDates')
? $variant->selectedEventDates()
: collect();
if ($eventDates->isNotEmpty()) {
$attributes->prepend([
'name' => 'Fecha',
'value' => $eventDates
->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))
->values()
->all(),
]);
}
return $attributes->all();
}
private function formatMoney(float|int|string|null $amount): string private function formatMoney(float|int|string|null $amount): string
{ {
return number_format((float) ($amount ?? 0), 2, '.', ''); return number_format((float) ($amount ?? 0), 2, '.', '');
} }
/** @return array<string, mixed> */
private function variantData(CatalogItem $catalogItem, Variant $variant): array
{
return [
'id' => $variant->id,
'precio' => $this->formatMoney($variant->precio ?? $catalogItem->precio),
'stock_tecnico' => $catalogItem->inventory_policy === InventoryPolicy::Unlimited
? null
: $variant->inventory->availableStock(),
'values' => $variant->selectorOptions($catalogItem->itemAttributes),
];
}
} }

View File

@@ -2,7 +2,6 @@
namespace App\Domains\Purchase\Resources; namespace App\Domains\Purchase\Resources;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Purchase\Models\Purchase; use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem; use App\Domains\Purchase\Models\PurchaseItem;
use Illuminate\Http\Request; use Illuminate\Http\Request;
@@ -18,28 +17,16 @@ class PurchaseResource extends JsonResource
*/ */
public function toArray(Request $request): array public function toArray(Request $request): array
{ {
$purchaseItems = $this->resource->relationLoaded('items') $items = $this->resource->relationLoaded('items')
? $this->resource->getRelation('items') ? $this->resource->getRelation('items')
: collect(); : collect();
$cartItems = $this->resource->relationLoaded('cart')
&& $this->resource->getRelation('cart')?->relationLoaded('items')
? $this->resource->getRelation('cart')->getRelation('items')
: null;
$usesCartItems = in_array($this->status, [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
], true) && $cartItems !== null;
$items = $usesCartItems ? $cartItems : $purchaseItems;
$itemsSource = $usesCartItems
? 'cart'
: ($purchaseItems->isNotEmpty() ? 'purchase' : null);
$ticketsCount = array_key_exists('tickets_count', $this->resource->getAttributes()) $ticketsCount = array_key_exists('tickets_count', $this->resource->getAttributes())
? (int) $this->resource->getAttribute('tickets_count') ? (int) $this->resource->getAttribute('tickets_count')
: null; : null;
$subtotal = $items->isNotEmpty() $subtotal = $items->isNotEmpty()
? $items->reduce( ? $items->reduce(
fn (float $carry, PurchaseItem|CartItem $item): float => $carry + $this->resolveItemSubtotal($item), fn (float $carry, PurchaseItem $item): float => $carry + $this->resolveItemSubtotal($item),
0.0, 0.0,
) )
: (float) ($this->total ?? 0); : (float) ($this->total ?? 0);
@@ -48,7 +35,7 @@ class PurchaseResource extends JsonResource
? (float) $this->total ? (float) $this->total
: ($items->isNotEmpty() : ($items->isNotEmpty()
? $items->reduce( ? $items->reduce(
fn (float $carry, PurchaseItem|CartItem $item): float => $carry + $this->resolveItemTotal($item), fn (float $carry, PurchaseItem $item): float => $carry + $this->resolveItemTotal($item),
0.0, 0.0,
) )
: (float) ($this->total ?? 0)); : (float) ($this->total ?? 0));
@@ -67,7 +54,7 @@ class PurchaseResource extends JsonResource
'telefono' => $this->telefono, 'telefono' => $this->telefono,
'nombre_apellido' => $this->nombre_apellido, 'nombre_apellido' => $this->nombre_apellido,
'email' => $this->email, 'email' => $this->email,
'items_source' => $itemsSource, 'items_source' => $items->isNotEmpty() ? 'purchase' : null,
'items' => PurchaseItemResource::collection($items), 'items' => PurchaseItemResource::collection($items),
'tickets_count' => $this->when($ticketsCount !== null, $ticketsCount), 'tickets_count' => $this->when($ticketsCount !== null, $ticketsCount),
'has_generated_tickets' => $this->when($ticketsCount !== null, $ticketsCount > 0), 'has_generated_tickets' => $this->when($ticketsCount !== null, $ticketsCount > 0),
@@ -76,21 +63,13 @@ class PurchaseResource extends JsonResource
]; ];
} }
protected function resolveItemSubtotal(PurchaseItem|CartItem $item): float protected function resolveItemSubtotal(PurchaseItem $item): float
{ {
if ($item instanceof CartItem) {
return (float) ($item->selectedItem()?->getPrice() ?? 0) * $item->cantidad;
}
return (float) $item->precio_unitario * $item->cantidad; return (float) $item->precio_unitario * $item->cantidad;
} }
protected function resolveItemTotal(PurchaseItem|CartItem $item): float protected function resolveItemTotal(PurchaseItem $item): float
{ {
if ($item instanceof CartItem) {
return $this->resolveItemSubtotal($item);
}
return (float) ($item->total ?? 0); return (float) ($item->total ?? 0);
} }

View File

@@ -15,7 +15,6 @@ class CompleteCheckoutService
public function __construct( public function __construct(
private readonly StockReservationService $reservations, private readonly StockReservationService $reservations,
private readonly SourceCartService $sourceCart, private readonly SourceCartService $sourceCart,
private readonly PurchaseItemSnapshotFactory $snapshots,
private readonly PurchaseStateGuard $purchaseState, private readonly PurchaseStateGuard $purchaseState,
) {} ) {}
@@ -35,6 +34,8 @@ class CompleteCheckoutService
return $this->loadPurchase($purchase); return $this->loadPurchase($purchase);
} }
$this->purchaseState->lockCurrentCart($purchase);
$purchase->update([ $purchase->update([
'status' => Purchase::STATUS_PENDING_PAYMENT, 'status' => Purchase::STATUS_PENDING_PAYMENT,
'total' => $purchase->calculateCurrentTotalAmount(), 'total' => $purchase->calculateCurrentTotalAmount(),
@@ -54,6 +55,12 @@ class CompleteCheckoutService
return $this->loadPurchase($purchase); return $this->loadPurchase($purchase);
} }
if ($purchase->status === Purchase::STATUS_IN_REVIEW) {
return $this->loadPurchase($purchase);
}
$this->purchaseState->lockCurrentCart($purchase);
if ( if (
$purchase->status !== Purchase::STATUS_PENDING_PAYMENT $purchase->status !== Purchase::STATUS_PENDING_PAYMENT
|| ($purchase->expires_at !== null && $purchase->expires_at->isPast()) || ($purchase->expires_at !== null && $purchase->expires_at->isPast())
@@ -63,7 +70,10 @@ class CompleteCheckoutService
]); ]);
} }
$purchase->update(['expires_at' => null]); $purchase->update([
'status' => Purchase::STATUS_IN_REVIEW,
'expires_at' => null,
]);
$this->reservations->syncPurchaseExpiration($purchase); $this->reservations->syncPurchaseExpiration($purchase);
return $this->loadPurchase($purchase); return $this->loadPurchase($purchase);
@@ -84,25 +94,26 @@ class CompleteCheckoutService
Purchase::STATUS_CANCELLED, Purchase::STATUS_CANCELLED,
Purchase::STATUS_REJECTED, Purchase::STATUS_REJECTED,
Purchase::STATUS_EXPIRED, Purchase::STATUS_EXPIRED,
Purchase::STATUS_SUPERSEDED,
], true)) { ], true)) {
throw ValidationException::withMessages([ throw ValidationException::withMessages([
'purchase' => __('api.purchase.cannot_confirm'), 'purchase' => __('api.purchase.cannot_confirm'),
]); ]);
} }
if ($purchase->items()->exists()) { if (! $purchase->items()->exists()) {
$cart = $purchase->cart()->withTrashed()->lockForUpdate()->first();
if ($cart?->status === 'converted' && $cart->trashed()) {
return;
}
throw ValidationException::withMessages([ throw ValidationException::withMessages([
'items' => __('api.purchase.inconsistent_reservation'), 'items' => __('api.purchase.inconsistent_reservation'),
]); ]);
} }
$cart = $purchase->cart()->lockForUpdate()->first(); $cart = $this->purchaseState->lockCurrentCart($purchase);
if ($cart === null || $cart->status !== 'checkout') {
if ($cart->status === 'converted' && $cart->trashed()) {
return;
}
if (! in_array($cart->status, ['active', 'checkout'], true)) {
throw ValidationException::withMessages([ throw ValidationException::withMessages([
'items' => __('api.purchase.inconsistent_reservation'), 'items' => __('api.purchase.inconsistent_reservation'),
]); ]);
@@ -115,10 +126,32 @@ class CompleteCheckoutService
]); ]);
} }
$snapshotQuantities = $purchase->items()
->lockForUpdate()
->get(['source_catalog_item_id', 'source_variant_id', 'cantidad'])
->groupBy(fn ($item): string => $this->itemKey(
(int) $item->source_catalog_item_id,
$item->source_variant_id === null ? null : (int) $item->source_variant_id,
))
->map(fn (Collection $items): int => (int) $items->sum('cantidad'))
->sortKeys()
->all();
$cartQuantities = $cartItems
->groupBy(fn (CartItem $item): string => $this->itemKey(
(int) $item->catalog_item_id,
$item->variant_id === null ? null : (int) $item->variant_id,
))
->map(fn (Collection $items): int => (int) $items->sum('cantidad'))
->sortKeys()
->all();
if ($snapshotQuantities !== $cartQuantities) {
throw ValidationException::withMessages([
'items' => __('api.purchase.inconsistent_reservation'),
]);
}
$this->loadCartItems($cartItems); $this->loadCartItems($cartItems);
$purchase->items()->createMany(
$this->snapshots->fromCartItems($cartItems),
);
foreach ($cartItems as $cartItem) { foreach ($cartItems as $cartItem) {
$selection = $cartItem->selectedItem(); $selection = $cartItem->selectedItem();
@@ -129,7 +162,7 @@ class CompleteCheckoutService
} }
try { try {
$this->reservations->commit($cartItem, $selection); $this->reservations->commit($cartItem, $selection, $purchase);
} catch (\InvalidArgumentException) { } catch (\InvalidArgumentException) {
throw ValidationException::withMessages([ throw ValidationException::withMessages([
'items' => __('api.purchase.inconsistent_reservation'), 'items' => __('api.purchase.inconsistent_reservation'),
@@ -145,9 +178,11 @@ class CompleteCheckoutService
{ {
return in_array($purchase->status, [ return in_array($purchase->status, [
Purchase::STATUS_PAID, Purchase::STATUS_PAID,
Purchase::STATUS_IN_REVIEW,
Purchase::STATUS_CANCELLED, Purchase::STATUS_CANCELLED,
Purchase::STATUS_REJECTED, Purchase::STATUS_REJECTED,
Purchase::STATUS_EXPIRED, Purchase::STATUS_EXPIRED,
Purchase::STATUS_SUPERSEDED,
], true); ], true);
} }
@@ -159,16 +194,12 @@ class CompleteCheckoutService
private function loadPurchase(Purchase $purchase): Purchase private function loadPurchase(Purchase $purchase): Purchase
{ {
return $purchase->load([ return $purchase->load(['items.imageAttachment']);
'items.imageAttachment', }
'cart.items.catalogItem.inventory',
'cart.items.catalogItem.attachments', private function itemKey(int $catalogItemId, ?int $variantId): string
'cart.items.variant.inventory', {
'cart.items.variant.attachments', return $catalogItemId.':'.($variantId ?? 'none');
'cart.items.variant.definitions.itemAttribute.attribute',
'cart.items.variant.eventDates',
'cart.items.variant.eventDate',
]);
} }
/** @param Collection<int, CartItem> $cartItems */ /** @param Collection<int, CartItem> $cartItems */

View File

@@ -2,24 +2,14 @@
namespace App\Domains\Purchase\Services\Checkout; namespace App\Domains\Purchase\Services\Checkout;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Catalog\Services\CatalogInventoryService;
use App\Domains\Purchase\Models\Purchase; use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Purchase\Services\PurchaseStateGuard; use App\Domains\Purchase\Services\PurchaseStateGuard;
use App\Domains\Purchase\Services\UserPurchaseLimitService;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException; use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class EditCheckoutService class EditCheckoutService
{ {
public function __construct( public function __construct(
private readonly CatalogInventoryService $inventory,
private readonly UserPurchaseLimitService $purchaseLimits,
private readonly CatalogSelectionResolver $selections,
private readonly SourceCartService $sourceCart,
private readonly PurchaseItemSnapshotFactory $snapshots,
private readonly PurchaseResponseLoader $responses, private readonly PurchaseResponseLoader $responses,
private readonly PurchaseStateGuard $purchaseState, private readonly PurchaseStateGuard $purchaseState,
) {} ) {}
@@ -28,295 +18,24 @@ class EditCheckoutService
public function updateCustomer(Purchase $purchase, array $customerData): Purchase public function updateCustomer(Purchase $purchase, array $customerData): Purchase
{ {
return DB::transaction(function () use ($purchase, $customerData): Purchase { return DB::transaction(function () use ($purchase, $customerData): Purchase {
$purchase = $this->lockPurchase($purchase); /** @var Purchase $purchase */
$this->purchaseState->assertNotExpired($purchase); $purchase = Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey());
$this->assertEditable($purchase);
$purchase->update($customerData);
return $this->loadPurchase($purchase);
});
}
public function updateItem(
Purchase $purchase,
PurchaseItem $purchaseItem,
?int $quantity,
?int $variantId,
bool $updateVariant,
): Purchase {
return DB::transaction(function () use (
$purchase,
$purchaseItem,
$quantity,
$variantId,
$updateVariant,
): Purchase {
$purchase = $this->lockPurchase($purchase);
$this->purchaseState->assertNotExpired($purchase); $this->purchaseState->assertNotExpired($purchase);
if ($purchase->status !== Purchase::STATUS_CREATED || $this->hasExpired($purchase)) { if (! in_array($purchase->status, [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
], true)) {
throw ValidationException::withMessages([ throw ValidationException::withMessages([
'purchase' => __('api.purchase.not_editable'), 'purchase' => __('api.purchase.not_editable'),
]); ]);
} }
$purchaseItem = $this->lockPurchaseItem($purchase, $purchaseItem); $this->purchaseState->lockCurrentCart($purchase);
$tenant = $purchase->tenant()->firstOrFail();
$finalQuantity = $quantity ?? (int) $purchaseItem->cantidad;
if ($quantity !== null && ! $tenant->checkout_editing_policy->allowsQuantityChanges()) { $purchase->update($customerData);
throw ValidationException::withMessages([
'quantity' => __('api.cart.editing_disabled'),
]);
}
if ($updateVariant && ! $tenant->checkout_editing_policy->allowsVariantChanges()) { return $this->responses->load($purchase);
throw ValidationException::withMessages([
'variant_id' => __('api.purchase.variant_change_disabled'),
]);
}
if ($updateVariant && $variantId !== $purchaseItem->source_variant_id) {
$this->changeItemVariant(
$purchase,
$purchaseItem,
(int) $variantId,
$finalQuantity,
);
} else {
$difference = $finalQuantity - (int) $purchaseItem->cantidad;
if ($difference !== 0) {
$this->adjustReservation($purchase, $purchaseItem, $finalQuantity, $difference);
$purchaseItem->update([
'cantidad' => $finalQuantity,
'total' => (float) $purchaseItem->precio_unitario * $finalQuantity,
]);
$this->sourceCart->syncItemQuantity($purchase, $purchaseItem, $finalQuantity);
}
}
$purchase->update([
'total' => $purchase->calculateCurrentTotalAmount(),
]);
return $this->loadPurchase($purchase);
}); });
} }
private function changeItemVariant(
Purchase $purchase,
PurchaseItem $sourceItem,
int $variantId,
int $quantity,
): void {
$tenant = $purchase->tenant()->firstOrFail();
$currentSelection = $this->selections->resolvePurchaseItem($tenant, $sourceItem);
$targetSelection = $this->selections->resolve(
$tenant,
(int) $sourceItem->source_catalog_item_id,
$variantId,
'item',
);
if (! $targetSelection instanceof Variant) {
throw ValidationException::withMessages([
'variant_id' => __('api.cart.variant_required'),
]);
}
/** @var PurchaseItem|null $targetItem */
$targetItem = $purchase->items()
->where('source_catalog_item_id', $sourceItem->source_catalog_item_id)
->where('source_variant_id', $targetSelection->id)
->whereKeyNot($sourceItem->getKey())
->lockForUpdate()
->first();
if ($targetItem !== null && $targetItem->reservation_status !== PurchaseItem::RESERVATION_ACTIVE) {
throw ValidationException::withMessages([
'variant_id' => __('api.purchase.item_not_editable'),
]);
}
$otherItemQuantity = (int) $purchase->items()
->where('source_catalog_item_id', $sourceItem->source_catalog_item_id)
->whereKeyNot($sourceItem->getKey())
->sum('cantidad');
$this->purchaseLimits->assertCanPurchase(
$targetSelection->catalogItem,
(int) $purchase->user_id,
$otherItemQuantity + $quantity,
$purchase->getKey(),
'variant_id',
);
try {
$this->inventory->release($currentSelection, (int) $sourceItem->cantidad);
$this->inventory->reserve($targetSelection, $quantity);
} catch (\InvalidArgumentException) {
throw ValidationException::withMessages([
'variant_id' => __('api.purchase.insufficient_stock'),
]);
}
$previousVariantId = $sourceItem->source_variant_id;
$finalQuantity = $quantity;
if ($targetItem !== null) {
$finalQuantity += (int) $targetItem->cantidad;
$targetItem->update($this->snapshots->fromVariant($targetSelection, $finalQuantity));
$sourceItem->delete();
} else {
$sourceItem->update($this->snapshots->fromVariant($targetSelection, $finalQuantity));
}
$this->sourceCart->syncItemSelection(
$purchase,
(int) $sourceItem->source_catalog_item_id,
$previousVariantId,
$targetSelection->id,
$finalQuantity,
);
}
public function prepareItemEditing(Purchase $purchase): Purchase
{
return DB::transaction(function () use ($purchase): Purchase {
$purchase = $this->lockPurchase($purchase);
$this->purchaseState->assertNotExpired($purchase);
$this->assertEditable($purchase);
if (! $purchase->tenant()->firstOrFail()->checkout_editing_policy->allowsModification()) {
throw ValidationException::withMessages([
'purchase' => __('api.cart.editing_disabled'),
]);
}
$purchase->telepagosQr()->delete();
$purchase->update([
'status' => Purchase::STATUS_CREATED,
'payment_method' => null,
'transfer_payer_dni' => null,
'expires_at' => now()->addMinutes(
max(1, (int) config('purchase.checkout_expiration_minutes', 30)),
),
]);
return $this->loadPurchase($purchase);
});
}
public function removeItem(Purchase $purchase, PurchaseItem $purchaseItem): Purchase
{
return DB::transaction(function () use ($purchase, $purchaseItem): Purchase {
$purchase = $this->lockPurchase($purchase);
$this->purchaseState->assertNotExpired($purchase);
$this->assertEditable($purchase);
if (! $purchase->tenant()->firstOrFail()->checkout_editing_policy->allowsRemoval()) {
throw ValidationException::withMessages([
'item' => __('api.cart.editing_disabled'),
]);
}
$purchaseItem = $this->lockPurchaseItem($purchase, $purchaseItem);
$selection = $this->selections->resolvePurchaseItem($purchase->tenant, $purchaseItem);
$this->inventory->release($selection, (int) $purchaseItem->cantidad);
$this->sourceCart->removeItem($purchase, $purchaseItem);
$purchaseItem->delete();
$purchase->update([
'total' => $purchase->calculateCurrentTotalAmount(),
]);
return $this->loadPurchase($purchase);
});
}
private function adjustReservation(
Purchase $purchase,
PurchaseItem $purchaseItem,
int $quantity,
int $difference,
): void {
$selection = $this->selections->resolvePurchaseItem($purchase->tenant, $purchaseItem);
try {
if ($difference > 0) {
$otherItemQuantity = (int) $purchase->items()
->where('source_catalog_item_id', $purchaseItem->source_catalog_item_id)
->whereKeyNot($purchaseItem->getKey())
->sum('cantidad');
$catalogItem = $selection instanceof Variant ? $selection->catalogItem : $selection;
$this->purchaseLimits->assertCanPurchase(
$catalogItem,
(int) $purchase->user_id,
$otherItemQuantity + $quantity,
$purchase->getKey(),
);
$this->inventory->reserve($selection, $difference);
} else {
$this->inventory->release($selection, abs($difference));
}
} catch (\InvalidArgumentException) {
throw ValidationException::withMessages([
'quantity' => __('api.purchase.insufficient_stock'),
]);
}
}
private function lockPurchaseItem(Purchase $purchase, PurchaseItem $item): PurchaseItem
{
/** @var PurchaseItem|null $lockedItem */
$lockedItem = $purchase->items()
->whereKey($item->getKey())
->lockForUpdate()
->first();
if ($lockedItem === null) {
throw new NotFoundHttpException('Purchase item not found.');
}
if ($lockedItem->reservation_status !== PurchaseItem::RESERVATION_ACTIVE) {
throw ValidationException::withMessages([
'item' => __('api.purchase.item_not_editable'),
]);
}
return $lockedItem;
}
private function assertEditable(Purchase $purchase): void
{
if (
! in_array($purchase->status, [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
], true)
|| $this->hasExpired($purchase)
) {
throw ValidationException::withMessages([
'purchase' => __('api.purchase.not_editable'),
]);
}
}
private function hasExpired(Purchase $purchase): bool
{
return $purchase->expires_at !== null && $purchase->expires_at->isPast();
}
private function lockPurchase(Purchase $purchase): Purchase
{
/** @var Purchase */
return Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey());
}
private function loadPurchase(Purchase $purchase): Purchase
{
return $this->responses->load($purchase);
}
} }

View File

@@ -9,35 +9,6 @@ use Illuminate\Support\Collection;
class PurchaseItemSnapshotFactory class PurchaseItemSnapshotFactory
{ {
/** @return array<string, mixed> */
public function fromVariant(Variant $variant, int $quantity): array
{
$variant->loadMissing([
'attachments',
'catalogItem.attachments',
'definitions.itemAttribute.attribute.options',
'eventDates',
'eventDate',
]);
$unitPrice = $variant->getPrice();
return [
'source_variant_id' => $variant->id,
'image_attachment_id' => $variant->attachments->first()?->id
?? $variant->catalogItem->attachments->first()?->id,
'nombre' => $variant->catalogItem->nombre,
'descripcion' => $variant->getDescription(),
'slug' => $variant->catalogItem->slug,
'item_nombre' => $variant->getName(),
'variant_attributes' => $this->snapshotAttributes($variant),
'cantidad' => $quantity,
'precio_unitario' => $unitPrice,
'discount_total' => null,
'tax_total' => null,
'total' => $unitPrice * $quantity,
];
}
/** /**
* @param Collection<int, CartItem> $cartItems * @param Collection<int, CartItem> $cartItems
* @return array<int, array<string, mixed>> * @return array<int, array<string, mixed>>

View File

@@ -8,51 +8,6 @@ class PurchaseResponseLoader
{ {
public function load(Purchase $purchase): Purchase public function load(Purchase $purchase): Purchase
{ {
$purchase->load(['tenant', 'items.imageAttachment']); return $purchase->load(['tenant', 'items.imageAttachment']);
if (
$purchase->cart_id !== null
&& (
in_array($purchase->status, [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
], true)
|| $purchase->items->isEmpty()
)
) {
$purchase->load([
'cart.items.catalogItem.inventory',
'cart.items.catalogItem.attachments',
'cart.items.variant.inventory',
'cart.items.variant.attachments',
'cart.items.variant.catalogItem',
'cart.items.variant.definitions.itemAttribute.attribute',
'cart.items.variant.eventDates',
'cart.items.variant.eventDate',
]);
}
if (! $purchase->tenant->checkout_editing_policy->allowsVariantChanges()) {
return $purchase;
}
$purchase->load([
'items.sourceCatalogItem.itemAttributes.attribute',
'items.sourceCatalogItem.variants' => fn ($query) => $query->orderBy('id'),
'items.sourceCatalogItem.variants.inventory',
'items.sourceCatalogItem.variants.definitions' => fn ($query) => $query->orderBy('id'),
'items.sourceCatalogItem.variants.definitions.itemAttribute.attribute.options',
'items.sourceCatalogItem.variants.eventDates',
'items.sourceCatalogItem.variants.eventDate',
'cart.items.catalogItem.itemAttributes.attribute',
'cart.items.catalogItem.variants' => fn ($query) => $query->orderBy('id'),
'cart.items.catalogItem.variants.inventory',
'cart.items.catalogItem.variants.definitions' => fn ($query) => $query->orderBy('id'),
'cart.items.catalogItem.variants.definitions.itemAttribute.attribute.options',
'cart.items.catalogItem.variants.eventDates',
'cart.items.catalogItem.variants.eventDate',
]);
return $purchase;
} }
} }

View File

@@ -2,10 +2,10 @@
namespace App\Domains\Purchase\Services\Checkout; namespace App\Domains\Purchase\Services\Checkout;
use App\Domains\Cart\Models\Cart;
use App\Domains\Catalog\Models\StockReservation; use App\Domains\Catalog\Models\StockReservation;
use App\Domains\Catalog\Services\StockReservationService; use App\Domains\Catalog\Services\StockReservationService;
use App\Domains\Purchase\Models\Purchase; use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Services\PurchaseStateGuard;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException; use Illuminate\Validation\ValidationException;
@@ -15,8 +15,6 @@ class ReleaseCheckoutService
{ {
public function __construct( public function __construct(
private readonly StockReservationService $reservations, private readonly StockReservationService $reservations,
private readonly SourceCartService $sourceCart,
private readonly PurchaseStateGuard $purchaseState,
) {} ) {}
public function cancel(Purchase $purchase): Purchase public function cancel(Purchase $purchase): Purchase
@@ -24,9 +22,9 @@ class ReleaseCheckoutService
return $this->release($purchase, Purchase::STATUS_CANCELLED); return $this->release($purchase, Purchase::STATUS_CANCELLED);
} }
public function cancelWithoutRestoringCart(Purchase $purchase): Purchase public function cancelFromAdmin(Purchase $purchase): Purchase
{ {
return $this->release($purchase, Purchase::STATUS_CANCELLED); return $this->release($purchase, Purchase::STATUS_CANCELLED, allowInReviewCancellation: true);
} }
public function expire(Purchase $purchase): Purchase public function expire(Purchase $purchase): Purchase
@@ -68,15 +66,18 @@ class ReleaseCheckoutService
return $expiredCount; return $expiredCount;
} }
private function release(Purchase $purchase, string $targetStatus): Purchase private function release(
{ Purchase $purchase,
return DB::transaction(function () use ($purchase, $targetStatus): Purchase { string $targetStatus,
bool $allowInReviewCancellation = false,
): Purchase {
return DB::transaction(function () use (
$purchase,
$targetStatus,
$allowInReviewCancellation,
): Purchase {
$purchase = $this->lockPurchase($purchase); $purchase = $this->lockPurchase($purchase);
if ($targetStatus !== Purchase::STATUS_EXPIRED) {
$this->purchaseState->assertNotExpired($purchase);
}
if ($purchase->status === Purchase::STATUS_PAID) { if ($purchase->status === Purchase::STATUS_PAID) {
if ($targetStatus === Purchase::STATUS_EXPIRED) { if ($targetStatus === Purchase::STATUS_EXPIRED) {
return $this->loadPurchase($purchase); return $this->loadPurchase($purchase);
@@ -87,6 +88,14 @@ class ReleaseCheckoutService
]); ]);
} }
if (
$purchase->status === Purchase::STATUS_IN_REVIEW
&& $targetStatus === Purchase::STATUS_CANCELLED
&& ! $allowInReviewCancellation
) {
return $this->createNewCartWithoutCancelling($purchase);
}
if ($this->isAlreadyReleased($purchase)) { if ($this->isAlreadyReleased($purchase)) {
return $this->loadPurchase($purchase); return $this->loadPurchase($purchase);
} }
@@ -98,13 +107,7 @@ class ReleaseCheckoutService
return $this->loadPurchase($purchase); return $this->loadPurchase($purchase);
} }
if ($purchase->items()->exists()) { $this->releasePurchaseReservations($purchase, $targetStatus);
throw ValidationException::withMessages([
'items' => __('api.purchase.inconsistent_reservation'),
]);
}
$this->releaseCartReservations($purchase, $targetStatus);
$purchase->update(['status' => $targetStatus]); $purchase->update(['status' => $targetStatus]);
@@ -112,15 +115,27 @@ class ReleaseCheckoutService
}); });
} }
private function releaseCartReservations( private function releasePurchaseReservations(Purchase $purchase, string $targetStatus): void
Purchase $purchase, {
string $targetStatus,
): void {
$cart = $purchase->cart()->withTrashed()->lockForUpdate()->first(); $cart = $purchase->cart()->withTrashed()->lockForUpdate()->first();
if ($cart === null) { if ($cart === null) {
return; return;
} }
if ($cart->status === 'active') {
$this->reservations->detachFromPurchase($purchase);
Cart::query()
->whereKey($cart->getKey())
->where('current_purchase_id', $purchase->getKey())
->update(['current_purchase_id' => null]);
return;
}
if ($cart->status !== 'checkout') {
return;
}
$cartItems = $cart->items()->orderBy('id')->lockForUpdate()->get(); $cartItems = $cart->items()->orderBy('id')->lockForUpdate()->get();
$cartItems->load([ $cartItems->load([
'catalogItem.inventory', 'catalogItem.inventory',
@@ -158,12 +173,40 @@ class ReleaseCheckoutService
} }
} }
private function createNewCartWithoutCancelling(Purchase $purchase): Purchase
{
return DB::transaction(function () use ($purchase): Purchase {
$purchase = $this->lockPurchase($purchase);
if ($purchase->status !== Purchase::STATUS_IN_REVIEW || $purchase->user_id === null) {
return $this->loadPurchase($purchase);
}
/** @var Cart|null $sourceCart */
$sourceCart = $purchase->cart()->withTrashed()->lockForUpdate()->first();
if ($sourceCart !== null && ! $sourceCart->trashed() && $sourceCart->status === 'active') {
$sourceCart->update(['status' => 'checkout']);
}
Cart::query()->firstOrCreate([
'tenant_codigo' => $purchase->tenant_codigo,
'user_id' => $purchase->user_id,
'guest_token' => null,
'status' => 'active',
'origin' => Cart::ORIGIN_USER,
]);
return $this->loadPurchase($purchase);
});
}
private function isAlreadyReleased(Purchase $purchase): bool private function isAlreadyReleased(Purchase $purchase): bool
{ {
return in_array($purchase->status, [ return in_array($purchase->status, [
Purchase::STATUS_CANCELLED, Purchase::STATUS_CANCELLED,
Purchase::STATUS_REJECTED, Purchase::STATUS_REJECTED,
Purchase::STATUS_EXPIRED, Purchase::STATUS_EXPIRED,
Purchase::STATUS_SUPERSEDED,
], true); ], true);
} }
@@ -175,15 +218,6 @@ class ReleaseCheckoutService
private function loadPurchase(Purchase $purchase): Purchase private function loadPurchase(Purchase $purchase): Purchase
{ {
return $purchase->load([ return $purchase->load(['items.imageAttachment']);
'items.imageAttachment',
'cart.items.catalogItem.inventory',
'cart.items.catalogItem.attachments',
'cart.items.variant.inventory',
'cart.items.variant.attachments',
'cart.items.variant.definitions.itemAttribute.attribute',
'cart.items.variant.eventDates',
'cart.items.variant.eventDate',
]);
} }
} }

View File

@@ -7,88 +7,6 @@ use App\Domains\Purchase\Models\Purchase;
class SourceCartService class SourceCartService
{ {
public function syncItemQuantity(
Purchase $purchase,
PurchaseItem $purchaseItem,
int $quantity,
): void {
$sourceCart = $this->findSourceCart($purchase);
if ($sourceCart === null) {
return;
}
$sourceCart->items()
->where('catalog_item_id', $purchaseItem->source_catalog_item_id)
->where('variant_id', $purchaseItem->source_variant_id)
->update(['cantidad' => $quantity]);
}
public function syncItemSelection(
Purchase $purchase,
int $catalogItemId,
?int $previousVariantId,
int $newVariantId,
int $finalQuantity,
): void {
$sourceCart = $this->findSourceCart($purchase);
if ($sourceCart === null) {
return;
}
/** @var CartItem|null $previousItem */
$previousItem = $sourceCart->items()
->where('catalog_item_id', $catalogItemId)
->where('variant_id', $previousVariantId)
->lockForUpdate()
->first();
/** @var CartItem|null $targetItem */
$targetItem = $sourceCart->items()
->where('catalog_item_id', $catalogItemId)
->where('variant_id', $newVariantId)
->when($previousItem !== null, fn ($query) => $query->whereKeyNot($previousItem->getKey()))
->lockForUpdate()
->first();
if ($targetItem !== null) {
$targetItem->update(['cantidad' => $finalQuantity]);
$previousItem?->delete();
return;
}
if ($previousItem !== null) {
$previousItem->update([
'variant_id' => $newVariantId,
'cantidad' => $finalQuantity,
]);
return;
}
$sourceCart->items()->create([
'catalog_item_id' => $catalogItemId,
'variant_id' => $newVariantId,
'cantidad' => $finalQuantity,
]);
}
public function removeItem(Purchase $purchase, PurchaseItem $purchaseItem): void
{
$sourceCart = $this->findSourceCart($purchase);
if ($sourceCart === null) {
return;
}
$sourceCart->items()
->where('catalog_item_id', $purchaseItem->source_catalog_item_id)
->where('variant_id', $purchaseItem->source_variant_id)
->delete();
}
public function finalize(Purchase $purchase): void public function finalize(Purchase $purchase): void
{ {
$sourceCart = $this->findSourceCart($purchase); $sourceCart = $this->findSourceCart($purchase);

View File

@@ -26,6 +26,7 @@ class StartCheckoutService
private readonly CatalogSelectionResolver $selections, private readonly CatalogSelectionResolver $selections,
private readonly InsufficientStockMessageBuilder $stockMessages, private readonly InsufficientStockMessageBuilder $stockMessages,
private readonly PurchaseResponseLoader $responses, private readonly PurchaseResponseLoader $responses,
private readonly PurchaseItemSnapshotFactory $snapshots,
) {} ) {}
/** @param array<string, mixed> $purchaseData */ /** @param array<string, mixed> $purchaseData */
@@ -192,6 +193,11 @@ class StartCheckoutService
), ),
$cart->getKey(), $cart->getKey(),
); );
$cart->update(['current_purchase_id' => $purchase->getKey()]);
$cartItems = $cart->items()->orderBy('id')->lockForUpdate()->get();
$this->loadCartItems($cartItems);
$purchase->items()->createMany($this->snapshots->fromCartItems($cartItems));
foreach ($cartItems as $index => $cartItem) { foreach ($cartItems as $index => $cartItem) {
$this->reservations->attachToPurchase( $this->reservations->attachToPurchase(
@@ -259,6 +265,9 @@ class StartCheckoutService
$cart->getTotalAmount(), $cart->getTotalAmount(),
$cart->getKey(), $cart->getKey(),
); );
$cart->update(['current_purchase_id' => $purchase->getKey()]);
$purchase->items()->createMany($this->snapshots->fromCartItems($cartItems));
foreach ($cartItems as $cartItem) { foreach ($cartItems as $cartItem) {
$this->reservations->attachToPurchase( $this->reservations->attachToPurchase(
$cartItem, $cartItem,
@@ -267,21 +276,57 @@ class StartCheckoutService
); );
} }
// The purchase owns the reservation until checkout finishes. The cart is
// retained so it can be restored if the purchase is cancelled or expires.
$cart->update([
'status' => 'checkout',
'guest_token' => null,
]);
return $this->loadPurchase($purchase); return $this->loadPurchase($purchase);
} }
private function resolveCart(Tenant $tenant, int $userId, int $cartId): Cart private function resolveCart(Tenant $tenant, int $userId, int $cartId): Cart
{ {
/** @var Cart|null $candidate */
$candidate = Cart::query()->find($cartId);
$this->assertCartCanCheckout($candidate, $tenant, $userId);
$candidatePurchaseId = $candidate->current_purchase_id;
$currentPurchase = $candidatePurchaseId === null
? null
: Purchase::query()->lockForUpdate()->find($candidatePurchaseId);
/** @var Cart|null $cart */ /** @var Cart|null $cart */
$cart = Cart::query()->lockForUpdate()->find($cartId); $cart = Cart::query()->lockForUpdate()->find($cartId);
$this->assertCartCanCheckout($cart, $tenant, $userId);
if ($cart->current_purchase_id !== $candidatePurchaseId) {
if ($cart->current_purchase_id !== null) {
throw ValidationException::withMessages([
'cart_id' => __('api.purchase.checkout_in_progress'),
]);
}
$currentPurchase = null;
}
if ($currentPurchase?->status === Purchase::STATUS_PAID) {
throw ValidationException::withMessages([
'cart_id' => __('api.purchase.checkout_in_progress'),
]);
}
if ($currentPurchase !== null && in_array($currentPurchase->status, [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
], true)) {
$currentPurchase->update([
'status' => Purchase::STATUS_SUPERSEDED,
'expires_at' => null,
]);
}
return $cart;
}
private function assertCartCanCheckout(?Cart $cart, Tenant $tenant, int $userId): void
{
if ($cart === null || $cart->tenant_codigo !== $tenant->codigo || $cart->user_id !== $userId) { if ($cart === null || $cart->tenant_codigo !== $tenant->codigo || $cart->user_id !== $userId) {
throw new NotFoundHttpException('Cart not found for tenant.'); throw new NotFoundHttpException('Cart not found for tenant.');
} }
@@ -291,8 +336,6 @@ class StartCheckoutService
'cart_id' => __('api.purchase.inactive_cart'), 'cart_id' => __('api.purchase.inactive_cart'),
]); ]);
} }
return $cart;
} }
/** @param Collection<int, CartItem> $cartItems */ /** @param Collection<int, CartItem> $cartItems */

View File

@@ -4,7 +4,6 @@ namespace App\Domains\Purchase\Services;
use App\Domains\Catalog\Services\StockReservationService; use App\Domains\Catalog\Services\StockReservationService;
use App\Domains\Purchase\Models\Purchase; use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Purchase\Services\Checkout\CompleteCheckoutService; use App\Domains\Purchase\Services\Checkout\CompleteCheckoutService;
use App\Domains\Purchase\Services\Checkout\EditCheckoutService; use App\Domains\Purchase\Services\Checkout\EditCheckoutService;
use App\Domains\Purchase\Services\Checkout\ReleaseCheckoutService; use App\Domains\Purchase\Services\Checkout\ReleaseCheckoutService;
@@ -49,32 +48,6 @@ class CheckoutService
return $this->editor->updateCustomer($purchase, $customerData); return $this->editor->updateCustomer($purchase, $customerData);
} }
public function updateItem(
Purchase $purchase,
PurchaseItem $purchaseItem,
?int $quantity,
?int $variantId,
bool $updateVariant,
): Purchase {
return $this->editor->updateItem(
$purchase,
$purchaseItem,
$quantity,
$variantId,
$updateVariant,
);
}
public function prepareItemEditing(Purchase $purchase): Purchase
{
return $this->editor->prepareItemEditing($purchase);
}
public function removeItem(Purchase $purchase, PurchaseItem $purchaseItem): Purchase
{
return $this->editor->removeItem($purchase, $purchaseItem);
}
public function confirmPurchase(Purchase $purchase): void public function confirmPurchase(Purchase $purchase): void
{ {
$this->completer->confirm($purchase); $this->completer->confirm($purchase);
@@ -95,9 +68,9 @@ class CheckoutService
return $this->releaser->cancel($purchase); return $this->releaser->cancel($purchase);
} }
public function cancelPurchaseWithoutRestoringCart(Purchase $purchase): Purchase public function cancelPurchaseFromAdmin(Purchase $purchase): Purchase
{ {
return $this->releaser->cancelWithoutRestoringCart($purchase); return $this->releaser->cancelFromAdmin($purchase);
} }
public function expirePurchase(Purchase $purchase): Purchase public function expirePurchase(Purchase $purchase): Purchase

View File

@@ -2,8 +2,10 @@
namespace App\Domains\Purchase\Services; namespace App\Domains\Purchase\Services;
use App\Domains\Cart\Models\Cart;
use App\Domains\Purchase\Exceptions\PurchaseExpiredException; use App\Domains\Purchase\Exceptions\PurchaseExpiredException;
use App\Domains\Purchase\Models\Purchase; use App\Domains\Purchase\Models\Purchase;
use Illuminate\Validation\ValidationException;
class PurchaseStateGuard class PurchaseStateGuard
{ {
@@ -21,4 +23,18 @@ class PurchaseStateGuard
throw new PurchaseExpiredException; throw new PurchaseExpiredException;
} }
} }
public function lockCurrentCart(Purchase $purchase): Cart
{
/** @var Cart|null $cart */
$cart = $purchase->cart()->withTrashed()->lockForUpdate()->first();
if ($cart === null || $cart->current_purchase_id !== $purchase->getKey()) {
throw ValidationException::withMessages([
'purchase' => __('api.purchase.not_current'),
]);
}
return $cart;
}
} }

View File

@@ -51,6 +51,7 @@ class UserPurchaseLimitService
->whereIn('status', [ ->whereIn('status', [
Purchase::STATUS_CREATED, Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT, Purchase::STATUS_PENDING_PAYMENT,
Purchase::STATUS_IN_REVIEW,
Purchase::STATUS_PAID, Purchase::STATUS_PAID,
]) ])
->when( ->when(
@@ -68,6 +69,7 @@ class UserPurchaseLimitService
->whereIn('status', [ ->whereIn('status', [
Purchase::STATUS_CREATED, Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT, Purchase::STATUS_PENDING_PAYMENT,
Purchase::STATUS_IN_REVIEW,
]) ])
->whereDoesntHave('items') ->whereDoesntHave('items')
->when( ->when(
@@ -86,7 +88,9 @@ class UserPurchaseLimitService
$excludedCartId !== null, $excludedCartId !== null,
fn ($query) => $query->whereKeyNot($excludedCartId), fn ($query) => $query->whereKeyNot($excludedCartId),
)) ))
->whereHas('stockReservations', fn ($query) => $query->where('status', 'active')) ->whereHas('stockReservations', fn ($query) => $query
->where('status', 'active')
->whereNull('purchase_id'))
->sum('cantidad'); ->sum('cantidad');
if ($purchasedQuantity + $checkoutQuantity + $reservedCartQuantity + $requestedQuantity > $limit) { if ($purchasedQuantity + $checkoutQuantity + $reservedCartQuantity + $requestedQuantity > $limit) {
@@ -131,6 +135,7 @@ class UserPurchaseLimitService
->whereIn('status', [ ->whereIn('status', [
Purchase::STATUS_CREATED, Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT, Purchase::STATUS_PENDING_PAYMENT,
Purchase::STATUS_IN_REVIEW,
Purchase::STATUS_PAID, Purchase::STATUS_PAID,
])) ]))
->groupBy('source_catalog_item_id') ->groupBy('source_catalog_item_id')
@@ -141,7 +146,11 @@ class UserPurchaseLimitService
->whereIn('catalog_item_id', $ids) ->whereIn('catalog_item_id', $ids)
->whereHas('cart.purchases', fn ($query) => $query ->whereHas('cart.purchases', fn ($query) => $query
->where('user_id', $userId) ->where('user_id', $userId)
->whereIn('status', [Purchase::STATUS_CREATED, Purchase::STATUS_PENDING_PAYMENT]) ->whereIn('status', [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
Purchase::STATUS_IN_REVIEW,
])
->whereDoesntHave('items')) ->whereDoesntHave('items'))
->groupBy('catalog_item_id') ->groupBy('catalog_item_id')
->pluck('quantity', 'catalog_item_id'); ->pluck('quantity', 'catalog_item_id');
@@ -152,7 +161,9 @@ class UserPurchaseLimitService
->whereHas('cart', fn ($query) => $query ->whereHas('cart', fn ($query) => $query
->where('user_id', $userId) ->where('user_id', $userId)
->where('status', 'active')) ->where('status', 'active'))
->whereHas('stockReservations', fn ($query) => $query->where('status', 'active')) ->whereHas('stockReservations', fn ($query) => $query
->where('status', 'active')
->whereNull('purchase_id'))
->groupBy('catalog_item_id') ->groupBy('catalog_item_id')
->pluck('quantity', 'catalog_item_id'); ->pluck('quantity', 'catalog_item_id');

View File

@@ -6,7 +6,7 @@ Implementa el ciclo de compra y checkout: crea la cabecera de compra desde un ca
## Modelo ## Modelo
- `Purchase`: raíz de la compra; estados `created`, `pending_payment`, `paid`, `cancelled`, `rejected` y `expired`. - `Purchase`: raíz de la compra; estados `created`, `pending_payment`, `in_review`, `paid`, `cancelled`, `rejected` y `expired`.
- `PurchaseItem`: snapshot definitivo del producto o variante, creado recién al confirmar la compra. - `PurchaseItem`: snapshot definitivo del producto o variante, creado recién al confirmar la compra.
- `TelepagosQr` y `TelepagosPayment`: datos del QR e intentos/resultados del proveedor. - `TelepagosQr` y `TelepagosPayment`: datos del QR e intentos/resultados del proveedor.
- `PurchasePaid`: evento emitido una sola vez al pasar a pagada bajo bloqueo transaccional. - `PurchasePaid`: evento emitido una sola vez al pasar a pagada bajo bloqueo transaccional.
@@ -22,7 +22,7 @@ Implementa el ciclo de compra y checkout: crea la cabecera de compra desde un ca
- `SourceCartService`: sincroniza o finaliza el carrito de checkout asociado a la compra. - `SourceCartService`: sincroniza o finaliza el carrito de checkout asociado a la compra.
- `CatalogSelectionResolver` y `PurchaseItemSnapshotFactory`: resuelven selecciones y generan snapshots. - `CatalogSelectionResolver` y `PurchaseItemSnapshotFactory`: resuelven selecciones y generan snapshots.
Durante `created` y `pending_payment`, `PurchaseResource` publica las líneas del carrito con `items_source=cart`; una compra materializada publica `items_source=purchase`. Los datos descriptivos y económicos del checkout se resuelven siempre desde el catálogo vigente. Al informar una transferencia, la compra pasa de `pending_payment` a `in_review` y deja de vencer. Si el comprador abandona el checkout durante la revisión, la compra y sus reservas permanecen intactas y se crea un carrito activo nuevo para que pueda seguir comprando. Adminapp puede confirmar o anular explícitamente la compra en revisión.
Las cantidades y variantes se editan mediante el dominio Cart. El endpoint autenticado `PATCH /checkout-carts/{cart}/items/{cartItem}` valida que el carrito pertenezca al usuario y a una compra editable. Cuando existe un cambio real, invalida atómicamente el intento de pago anterior, recalcula el total y renueva la reserva; Purchase no expone operaciones sobre líneas antes de la confirmación. Las cantidades y variantes se editan mediante el dominio Cart. El endpoint autenticado `PATCH /checkout-carts/{cart}/items/{cartItem}` valida que el carrito pertenezca al usuario y a una compra editable. Cuando existe un cambio real, invalida atómicamente el intento de pago anterior, recalcula el total y renueva la reserva; Purchase no expone operaciones sobre líneas antes de la confirmación.

View File

@@ -7,9 +7,6 @@ Route::prefix('tenants/{tenant:codigo}')->middleware('auth:sanctum')->group(func
Route::get('compras', [PurchaseController::class, 'index']); Route::get('compras', [PurchaseController::class, 'index']);
Route::post('compras/start-checkout', [PurchaseController::class, 'startCheckout']); Route::post('compras/start-checkout', [PurchaseController::class, 'startCheckout']);
Route::get('compras/{compra}', [PurchaseController::class, 'show']); Route::get('compras/{compra}', [PurchaseController::class, 'show']);
Route::post('compras/{compra}/edit-items', [PurchaseController::class, 'prepareItemEditing']);
Route::patch('compras/{compra}/items/{item}', [PurchaseController::class, 'updateItem']);
Route::delete('compras/{compra}/items/{item}', [PurchaseController::class, 'removeItem']);
Route::patch('compras/{compra}/customer-data', [PurchaseController::class, 'updateCustomerData']); Route::patch('compras/{compra}/customer-data', [PurchaseController::class, 'updateCustomerData']);
Route::post('compras/{compra}/payment-intent', [PurchaseController::class, 'paymentIntent']); Route::post('compras/{compra}/payment-intent', [PurchaseController::class, 'paymentIntent']);
Route::post('compras/{compra}/complete', [PurchaseController::class, 'complete']); Route::post('compras/{compra}/complete', [PurchaseController::class, 'complete']);

View File

@@ -3,22 +3,27 @@
namespace App\Domains\Sale\Controllers\AdminApp; namespace App\Domains\Sale\Controllers\AdminApp;
use App\Domains\Sale\Requests\AdminAppSaleIndexRequest; use App\Domains\Sale\Requests\AdminAppSaleIndexRequest;
use App\Domains\Sale\Requests\AdminAppSaleModificationPdfRequest;
use App\Domains\Sale\Requests\AdminAppSalePdfRequest;
use App\Domains\Sale\Resources\AdminApp\SaleDetailResource; use App\Domains\Sale\Resources\AdminApp\SaleDetailResource;
use App\Domains\Sale\Resources\AdminApp\SaleModificationResource; use App\Domains\Sale\Resources\AdminApp\SaleModificationResource;
use App\Domains\Sale\Resources\AdminApp\SaleResource; use App\Domains\Sale\Resources\AdminApp\SaleResource;
use App\Domains\Sale\Resources\AdminApp\SaleTicketResource; use App\Domains\Sale\Resources\AdminApp\SaleTicketResource;
use App\Domains\Sale\Services\AdminAppSaleExcelService;
use App\Domains\Sale\Services\AdminAppSalePdfService; use App\Domains\Sale\Services\AdminAppSalePdfService;
use App\Domains\Sale\Services\AdminAppSaleService; use App\Domains\Sale\Services\AdminAppSaleService;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection; use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Http\Response; use Illuminate\Http\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
class SaleController extends Controller class SaleController extends Controller
{ {
public function __construct( public function __construct(
protected AdminAppSaleService $saleService, protected AdminAppSaleService $saleService,
protected AdminAppSalePdfService $salePdfService, protected AdminAppSalePdfService $salePdfService,
protected AdminAppSaleExcelService $saleExcelService,
) {} ) {}
public function index(AdminAppSaleIndexRequest $request): AnonymousResourceCollection public function index(AdminAppSaleIndexRequest $request): AnonymousResourceCollection
@@ -71,23 +76,48 @@ class SaleController extends Controller
); );
} }
public function downloadPdf(AdminAppSaleIndexRequest $request): Response public function downloadPdf(AdminAppSalePdfRequest $request): Response
{ {
$tenant = $request->user()->tenant()->firstOrFail(); $tenant = $request->user()->tenant()->firstOrFail();
return $this->salePdfService->downloadSales( return $this->salePdfService->downloadSales(
$tenant, $tenant,
$this->saleService->salesForExport($tenant, $request->validated()), $this->saleService->salesForExport($tenant, $request->validated()),
$request->validated('timezone'),
); );
} }
public function downloadModificationsPdf(Request $request): Response public function downloadModificationsPdf(AdminAppSaleModificationPdfRequest $request): Response
{ {
$tenant = $request->user()->tenant()->firstOrFail(); $tenant = $request->user()->tenant()->firstOrFail();
return $this->salePdfService->downloadModifications( return $this->salePdfService->downloadModifications(
$tenant, $tenant,
$this->saleService->modificationsForExport($tenant), $this->saleService->modificationsForExport($tenant),
$request->validated('timezone'),
);
}
public function downloadExcel(AdminAppSalePdfRequest $request): StreamedResponse
{
$tenant = $request->user()->tenant()->firstOrFail();
return $this->saleExcelService->downloadSales(
$tenant,
$this->saleService->salesForExport($tenant, $request->validated()),
$request->validated('timezone'),
);
}
public function downloadModificationsExcel(
AdminAppSaleModificationPdfRequest $request,
): StreamedResponse {
$tenant = $request->user()->tenant()->firstOrFail();
return $this->saleExcelService->downloadModifications(
$tenant,
$this->saleService->modificationsForExport($tenant),
$request->validated('timezone'),
); );
} }
} }

View File

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

View File

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

View File

@@ -2,12 +2,10 @@
namespace App\Domains\Sale\Resources\AdminApp; namespace App\Domains\Sale\Resources\AdminApp;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Purchase\Models\Purchase; use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem; use App\Domains\Purchase\Models\PurchaseItem;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Collection;
/** @mixin Purchase */ /** @mixin Purchase */
class SaleDetailResource extends JsonResource class SaleDetailResource extends JsonResource
@@ -15,44 +13,23 @@ class SaleDetailResource extends JsonResource
/** @return array<string, mixed> */ /** @return array<string, mixed> */
public function toArray(Request $request): array public function toArray(Request $request): array
{ {
$items = $this->saleItems();
return [ return [
'id' => $this->id, 'id' => $this->id,
'items' => $items->map(fn (PurchaseItem|CartItem $item): array => [ 'items' => $this->items->map(fn (PurchaseItem $item): array => [
'id' => $item->id, 'id' => $item->id,
'product' => $item instanceof PurchaseItem 'product' => $item->item_nombre,
? $item->item_nombre
: $item->selectedItem()?->getName(),
'event_dates' => $this->eventDates($item), 'event_dates' => $this->eventDates($item),
'quantity' => (int) $item->cantidad, 'quantity' => (int) $item->cantidad,
'unit_price' => $this->formatMoney($this->unitPrice($item)), 'unit_price' => $this->formatMoney($item->precio_unitario),
'total' => $this->formatMoney($this->lineTotal($item)), 'total' => $this->formatMoney($item->total),
])->values(), ])->values(),
'total' => $this->formatMoney($this->total), 'total' => $this->formatMoney($this->total),
]; ];
} }
/** @return Collection<int, PurchaseItem|CartItem> */
private function saleItems(): Collection
{
if ($this->items->isNotEmpty()) {
return $this->items;
}
return $this->cart?->items ?? collect();
}
/** @return list<string> */ /** @return list<string> */
private function eventDates(PurchaseItem|CartItem $item): array private function eventDates(PurchaseItem $item): array
{ {
if ($item instanceof CartItem) {
return $item->variant?->selectedEventDates()
->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))
->values()
->all() ?? [];
}
return collect($item->variant_attributes ?? []) return collect($item->variant_attributes ?? [])
->filter(fn (mixed $attribute): bool => is_array($attribute) ->filter(fn (mixed $attribute): bool => is_array($attribute)
&& mb_strtolower(trim((string) ($attribute['name'] ?? ''))) === 'fecha') && mb_strtolower(trim((string) ($attribute['name'] ?? ''))) === 'fecha')
@@ -66,20 +43,6 @@ class SaleDetailResource extends JsonResource
->all(); ->all();
} }
private function unitPrice(PurchaseItem|CartItem $item): float|int|string|null
{
return $item instanceof PurchaseItem
? $item->precio_unitario
: $item->selectedItem()?->getPrice();
}
private function lineTotal(PurchaseItem|CartItem $item): float|int|string|null
{
return $item instanceof PurchaseItem
? $item->total
: ($item->selectedItem()?->getPrice() ?? 0) * $item->cantidad;
}
private function formatMoney(float|int|string|null $amount): string private function formatMoney(float|int|string|null $amount): string
{ {
return number_format((float) ($amount ?? 0), 2, '.', ''); return number_format((float) ($amount ?? 0), 2, '.', '');

View File

@@ -23,6 +23,7 @@ class SaleModificationResource extends JsonResource
'attribute' => $this->attribute, 'attribute' => $this->attribute,
'old_value' => $this->old_value, 'old_value' => $this->old_value,
'new_value' => $this->new_value, 'new_value' => $this->new_value,
'changed_at' => $this->changed_at->utc()->toIso8601String(),
'date' => $this->changed_at->format('Y-m-d'), 'date' => $this->changed_at->format('Y-m-d'),
'time' => $this->changed_at->format('H:i:s'), 'time' => $this->changed_at->format('H:i:s'),
'actor_type' => $this->actor_type->value, 'actor_type' => $this->actor_type->value,

View File

@@ -0,0 +1,211 @@
<?php
namespace App\Domains\Sale\Services;
use App\Domains\Logging\Models\ValueChange;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Support\Collection;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Symfony\Component\HttpFoundation\StreamedResponse;
class AdminAppSaleExcelService
{
/** @param Collection<int, Purchase> $sales */
public function downloadSales(Tenant $tenant, Collection $sales, string $timeZone): StreamedResponse
{
$generatedAt = now();
$spreadsheet = $this->spreadsheet($tenant, 'Historial de ventas');
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Ventas');
$sheet->fromArray([
'ID',
'Fecha',
'Cliente',
'Cantidad',
'Estado',
'Importe',
'Tickets',
], null, 'A1');
foreach ($sales->values() as $index => $sale) {
$row = $index + 2;
$sheet->setCellValueExplicit("A{$row}", '#'.$sale->id, DataType::TYPE_STRING);
if ($sale->created_at) {
$sheet->setCellValue(
"B{$row}",
Date::dateTimeToExcel($sale->created_at->copy()->timezone($timeZone)),
);
}
$sheet->setCellValueExplicit(
"C{$row}",
$sale->nombre_apellido ?: 'Sin nombre',
DataType::TYPE_STRING,
);
$sheet->setCellValue("D{$row}", (int) ($sale->quantity ?? 0));
$sheet->setCellValue("E{$row}", $this->saleStatus($sale->status));
$sheet->setCellValue("F{$row}", (float) $sale->total);
$sheet->setCellValue("G{$row}", (int) ($sale->tickets_count ?? 0));
}
$lastRow = max(2, $sales->count() + 1);
$sheet->getStyle("B2:B{$lastRow}")->getNumberFormat()->setFormatCode('dd/mm/yyyy hh:mm');
$sheet->getStyle("F2:F{$lastRow}")->getNumberFormat()->setFormatCode('$ #,##0.00');
$this->formatSheet($spreadsheet, 'A1:G1', "A1:G{$lastRow}", [
'A' => 13,
'B' => 20,
'C' => 32,
'D' => 12,
'E' => 22,
'F' => 16,
'G' => 12,
]);
return $this->download(
$spreadsheet,
'ventas_'.$tenant->codigo.'_'
.$generatedAt->copy()->timezone($timeZone)->format('Ymd_His').'.xlsx',
);
}
/** @param Collection<int, ValueChange> $modifications */
public function downloadModifications(
Tenant $tenant,
Collection $modifications,
string $timeZone,
): StreamedResponse {
$generatedAt = now();
$spreadsheet = $this->spreadsheet($tenant, 'Historial de modificaciones de ventas');
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Modificaciones');
$sheet->fromArray([
'Fecha',
'Hora',
'Venta',
'Cliente',
'Campo',
'Valor anterior',
'Valor nuevo',
'Modificado por',
], null, 'A1');
foreach ($modifications->values() as $index => $modification) {
$row = $index + 2;
$changedAt = $modification->changed_at->copy()->timezone($timeZone);
$sale = $modification->trackable;
$sheet->setCellValue("A{$row}", Date::dateTimeToExcel($changedAt));
$sheet->setCellValue("B{$row}", Date::dateTimeToExcel($changedAt));
$sheet->setCellValueExplicit(
"C{$row}",
'#'.$modification->trackable_id,
DataType::TYPE_STRING,
);
$sheet->setCellValueExplicit(
"D{$row}",
$sale?->nombre_apellido ?: 'Sin nombre',
DataType::TYPE_STRING,
);
$sheet->setCellValueExplicit(
"E{$row}",
$modification->attribute,
DataType::TYPE_STRING,
);
$sheet->setCellValueExplicit(
"F{$row}",
$modification->old_value ?? '-',
DataType::TYPE_STRING,
);
$sheet->setCellValueExplicit(
"G{$row}",
$modification->new_value ?? '-',
DataType::TYPE_STRING,
);
$sheet->setCellValueExplicit(
"H{$row}",
$modification->user?->nombre_apellido ?? 'Sistema',
DataType::TYPE_STRING,
);
}
$lastRow = max(2, $modifications->count() + 1);
$sheet->getStyle("A2:A{$lastRow}")->getNumberFormat()->setFormatCode('dd/mm/yyyy');
$sheet->getStyle("B2:B{$lastRow}")->getNumberFormat()->setFormatCode('hh:mm:ss');
$this->formatSheet($spreadsheet, 'A1:H1', "A1:H{$lastRow}", [
'A' => 14,
'B' => 12,
'C' => 13,
'D' => 32,
'E' => 20,
'F' => 24,
'G' => 24,
'H' => 28,
]);
return $this->download(
$spreadsheet,
'historial_modificaciones_'.$tenant->codigo.'_'
.$generatedAt->copy()->timezone($timeZone)->format('Ymd_His').'.xlsx',
);
}
private function spreadsheet(Tenant $tenant, string $title): Spreadsheet
{
$spreadsheet = new Spreadsheet;
$spreadsheet->getProperties()
->setCreator('Shopit')
->setTitle($title)
->setSubject($tenant->nombre);
return $spreadsheet;
}
/** @param array<string, int> $widths */
private function formatSheet(
Spreadsheet $spreadsheet,
string $headerRange,
string $filterRange,
array $widths,
): void {
$sheet = $spreadsheet->getActiveSheet();
$sheet->getStyle($headerRange)->applyFromArray([
'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
'fill' => [
'fillType' => Fill::FILL_SOLID,
'startColor' => ['rgb' => '26382E'],
],
'alignment' => ['vertical' => Alignment::VERTICAL_CENTER],
]);
$sheet->getRowDimension(1)->setRowHeight(24);
$sheet->freezePane('A2');
$sheet->setAutoFilter($filterRange);
foreach ($widths as $column => $width) {
$sheet->getColumnDimension($column)->setWidth($width);
}
}
private function download(Spreadsheet $spreadsheet, string $filename): StreamedResponse
{
return response()->streamDownload(function () use ($spreadsheet): void {
(new Xlsx($spreadsheet))->save('php://output');
$spreadsheet->disconnectWorksheets();
}, $filename, [
'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
]);
}
private function saleStatus(string $status): string
{
return match ($status) {
Purchase::STATUS_PAID => 'Confirmado',
Purchase::STATUS_CREATED => 'Por completar datos',
Purchase::STATUS_PENDING_PAYMENT, Purchase::STATUS_IN_REVIEW => 'Esperando pago',
default => 'Anulado',
};
}
}

View File

@@ -13,12 +13,14 @@ use Illuminate\Support\Collection;
class AdminAppSalePdfService class AdminAppSalePdfService
{ {
/** @param Collection<int, Purchase> $sales */ /** @param Collection<int, Purchase> $sales */
public function downloadSales(Tenant $tenant, Collection $sales): Response public function downloadSales(Tenant $tenant, Collection $sales, string $timeZone): Response
{ {
$generatedAt = now();
$pdf = Pdf::loadView('pdf.adminapp.sales', [ $pdf = Pdf::loadView('pdf.adminapp.sales', [
'tenant' => $tenant, 'tenant' => $tenant,
'sales' => $sales, 'sales' => $sales,
'generatedAt' => now(), 'generatedAt' => $generatedAt,
'timeZone' => $timeZone,
'confirmedSalesTotal' => number_format( 'confirmedSalesTotal' => number_format(
(float) $sales->where('status', Purchase::STATUS_PAID)->sum('total'), (float) $sales->where('status', Purchase::STATUS_PAID)->sum('total'),
2, 2,
@@ -30,23 +32,30 @@ class AdminAppSalePdfService
$this->addPageNumbers($pdf); $this->addPageNumbers($pdf);
return $pdf->download( return $pdf->download(
'ventas_'.$tenant->codigo.'_'.now()->format('Ymd_His').'.pdf' 'ventas_'.$tenant->codigo.'_'
.$generatedAt->copy()->timezone($timeZone)->format('Ymd_His').'.pdf'
); );
} }
/** @param Collection<int, ValueChange> $modifications */ /** @param Collection<int, ValueChange> $modifications */
public function downloadModifications(Tenant $tenant, Collection $modifications): Response public function downloadModifications(
{ Tenant $tenant,
Collection $modifications,
string $timeZone,
): Response {
$generatedAt = now();
$pdf = Pdf::loadView('pdf.adminapp.sale-modifications', [ $pdf = Pdf::loadView('pdf.adminapp.sale-modifications', [
'tenant' => $tenant, 'tenant' => $tenant,
'modifications' => $modifications, 'modifications' => $modifications,
'generatedAt' => now(), 'generatedAt' => $generatedAt,
'timeZone' => $timeZone,
])->setPaper('a4', 'landscape'); ])->setPaper('a4', 'landscape');
$this->addPageNumbers($pdf); $this->addPageNumbers($pdf);
return $pdf->download( return $pdf->download(
'historial_modificaciones_'.$tenant->codigo.'_'.now()->format('Ymd_His').'.pdf' 'historial_modificaciones_'.$tenant->codigo.'_'
.$generatedAt->copy()->timezone($timeZone)->format('Ymd_His').'.pdf'
); );
} }

View File

@@ -51,14 +51,7 @@ class AdminAppSaleService
{ {
return Purchase::query() return Purchase::query()
->where('tenant_codigo', $tenant->codigo) ->where('tenant_codigo', $tenant->codigo)
->with([ ->with('items')
'items',
'cart' => fn ($query) => $query->withTrashed(),
'cart.items.catalogItem',
'cart.items.variant.catalogItem',
'cart.items.variant.eventDates',
'cart.items.variant.eventDate',
])
->findOrFail($saleId); ->findOrFail($saleId);
} }
@@ -86,7 +79,7 @@ class AdminAppSaleService
$sale = $this->findForTenant($tenant, $saleId); $sale = $this->findForTenant($tenant, $saleId);
return $this->saleForResponse( return $this->saleForResponse(
$this->checkoutService->cancelPurchaseWithoutRestoringCart($sale) $this->checkoutService->cancelPurchaseFromAdmin($sale)
); );
} }
@@ -133,6 +126,7 @@ class AdminAppSaleService
return Purchase::query() return Purchase::query()
->where('tenant_codigo', $tenant->codigo) ->where('tenant_codigo', $tenant->codigo)
->where('status', '!=', Purchase::STATUS_SUPERSEDED)
->when($filters['q'] ?? null, function (Builder $query, string $search): void { ->when($filters['q'] ?? null, function (Builder $query, string $search): void {
$term = trim($search); $term = trim($search);
@@ -150,19 +144,18 @@ class AdminAppSaleService
) )
->when( ->when(
$filters['status'] ?? null, $filters['status'] ?? null,
fn (Builder $query, string $status): Builder => $query->where('status', $status) fn (Builder $query, string $status): Builder => $status === Purchase::STATUS_PENDING_PAYMENT
? $query->whereIn('status', [
Purchase::STATUS_PENDING_PAYMENT,
Purchase::STATUS_IN_REVIEW,
])
: $query->where('status', $status)
) )
->select('compras.*') ->select('compras.*')
->selectRaw( ->selectRaw(
'CASE WHEN compras.status IN (?, ?) ' '(SELECT COALESCE(SUM(purchase_items.cantidad), 0) '
.'THEN (SELECT COALESCE(SUM(cart_items.cantidad), 0) FROM carrito_items AS cart_items ' .'FROM compra_items AS purchase_items '
.'WHERE cart_items.cart_id = compras.cart_id) ' .'WHERE purchase_items.compra_id = compras.id) AS quantity',
.'ELSE (SELECT COALESCE(SUM(purchase_items.cantidad), 0) FROM compra_items AS purchase_items '
.'WHERE purchase_items.compra_id = compras.id) END AS quantity',
[
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
],
) )
->withCount('tickets') ->withCount('tickets')
->orderBy($sortColumns[$sortBy], $sortDirection) ->orderBy($sortColumns[$sortBy], $sortDirection)
@@ -199,16 +192,11 @@ class AdminAppSaleService
protected function quantityExpression(): string protected function quantityExpression(): string
{ {
// El fallback se resuelve en SQL para poder ordenar por cantidad antes de paginar;
// los ítems consolidados de la compra tienen prioridad sobre los del carrito de origen.
return <<<'SQL' return <<<'SQL'
COALESCE( COALESCE(
(SELECT SUM(compra_items.cantidad) (SELECT SUM(compra_items.cantidad)
FROM compra_items FROM compra_items
WHERE compra_items.compra_id = compras.id), WHERE compra_items.compra_id = compras.id),
(SELECT SUM(carrito_items.cantidad)
FROM carrito_items
WHERE carrito_items.cart_id = compras.cart_id),
0 0
) AS quantity ) AS quantity
SQL; SQL;

View File

@@ -8,6 +8,7 @@ Provee consultas administrativas y exportaciones de ventas confirmadas, además
- `AdminAppSaleService`: pagina ventas, calcula totales y obtiene colecciones para exportación; también consulta modificaciones. - `AdminAppSaleService`: pagina ventas, calcula totales y obtiene colecciones para exportación; también consulta modificaciones.
- `AdminAppSalePdfService`: genera descargas PDF de ventas y de cambios. - `AdminAppSalePdfService`: genera descargas PDF de ventas y de cambios.
- `AdminAppSaleExcelService`: genera descargas Excel de ventas y de cambios.
- `AdminAppSaleIndexRequest`: valida filtros del listado y la exportación. - `AdminAppSaleIndexRequest`: valida filtros del listado y la exportación.
- `SaleResource` y `SaleModificationResource`: representan ventas e historial para AdminApp. - `SaleResource` y `SaleModificationResource`: representan ventas e historial para AdminApp.
- `SaleController`: entrada HTTP del panel. - `SaleController`: entrada HTTP del panel.
@@ -16,8 +17,8 @@ Provee consultas administrativas y exportaciones de ventas confirmadas, además
Bajo `/v1/adminapp/tenant`, protegidos por `auth:sanctum` y `adminapp.tenant`: Bajo `/v1/adminapp/tenant`, protegidos por `auth:sanctum` y `adminapp.tenant`:
- `GET /sales` y `GET /sales/pdf`. - `GET /sales`, `GET /sales/pdf` y `GET /sales/excel`.
- `GET /sales/modifications` y `GET /sales/modifications/pdf`. - `GET /sales/modifications`, `GET /sales/modifications/pdf` y `GET /sales/modifications/excel`.
## Dependencias ## Dependencias
@@ -25,4 +26,4 @@ Consume compras de `Purchase`, datos del tenant y entradas de `Logging`. No es d
## Consideraciones ## Consideraciones
La consulta paginada y la colección de exportación deben aplicar los mismos filtros para evitar diferencias entre pantalla y PDF. La consulta paginada y la colección de exportación deben aplicar los mismos filtros para evitar diferencias entre pantalla, PDF y Excel.

View File

@@ -8,8 +8,10 @@ Route::prefix('v1/adminapp/tenant')
->group(function (): void { ->group(function (): void {
Route::get('sales', [SaleController::class, 'index']); Route::get('sales', [SaleController::class, 'index']);
Route::get('sales/pdf', [SaleController::class, 'downloadPdf']); Route::get('sales/pdf', [SaleController::class, 'downloadPdf']);
Route::get('sales/excel', [SaleController::class, 'downloadExcel']);
Route::get('sales/modifications', [SaleController::class, 'modifications']); Route::get('sales/modifications', [SaleController::class, 'modifications']);
Route::get('sales/modifications/pdf', [SaleController::class, 'downloadModificationsPdf']); Route::get('sales/modifications/pdf', [SaleController::class, 'downloadModificationsPdf']);
Route::get('sales/modifications/excel', [SaleController::class, 'downloadModificationsExcel']);
Route::post('sales/{sale}/confirm', [SaleController::class, 'confirm'])->whereNumber('sale'); Route::post('sales/{sale}/confirm', [SaleController::class, 'confirm'])->whereNumber('sale');
Route::post('sales/{sale}/cancel', [SaleController::class, 'cancel'])->whereNumber('sale'); Route::post('sales/{sale}/cancel', [SaleController::class, 'cancel'])->whereNumber('sale');
Route::get('sales/{sale}/tickets', [SaleController::class, 'tickets'])->whereNumber('sale'); Route::get('sales/{sale}/tickets', [SaleController::class, 'tickets'])->whereNumber('sale');

View File

@@ -0,0 +1,24 @@
<?php
namespace App\Domains\Shared\Rules;
use Closure;
use DateTimeZone;
use Exception;
use Illuminate\Contracts\Validation\ValidationRule;
class ValidTimezone implements ValidationRule
{
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (! is_string($value)) {
return;
}
try {
new DateTimeZone($value);
} catch (Exception) {
$fail(__('validation.timezone'));
}
}
}

View File

@@ -111,7 +111,10 @@ class StoreTenantRequest extends FormRequest
'display_seach_bar' => ['sometimes', 'boolean'], 'display_seach_bar' => ['sometimes', 'boolean'],
'display_cart' => ['sometimes', 'boolean'], 'display_cart' => ['sometimes', 'boolean'],
'cart_editing_policy' => ['sometimes', Rule::enum(CartEditingPolicy::class)], 'cart_editing_policy' => ['sometimes', Rule::enum(CartEditingPolicy::class)],
'checkout_editing_policy' => ['sometimes', Rule::enum(CartEditingPolicy::class)], 'checkout_editing_policy' => [
'sometimes',
Rule::in([CartEditingPolicy::Disabled->value]),
],
'display_cart_item_images' => ['sometimes', 'boolean'], 'display_cart_item_images' => ['sometimes', 'boolean'],
'scanner_category_validation_enabled' => ['sometimes', 'boolean'], 'scanner_category_validation_enabled' => ['sometimes', 'boolean'],
'website_type_code' => [ 'website_type_code' => [

View File

@@ -132,7 +132,10 @@ class UpdateTenantRequest extends FormRequest
'display_seach_bar' => ['sometimes', 'boolean'], 'display_seach_bar' => ['sometimes', 'boolean'],
'display_cart' => ['sometimes', 'boolean'], 'display_cart' => ['sometimes', 'boolean'],
'cart_editing_policy' => ['sometimes', Rule::enum(CartEditingPolicy::class)], 'cart_editing_policy' => ['sometimes', Rule::enum(CartEditingPolicy::class)],
'checkout_editing_policy' => ['sometimes', Rule::enum(CartEditingPolicy::class)], 'checkout_editing_policy' => [
'sometimes',
Rule::in([CartEditingPolicy::Disabled->value]),
],
'display_cart_item_images' => ['sometimes', 'boolean'], 'display_cart_item_images' => ['sometimes', 'boolean'],
'scanner_category_validation_enabled' => ['sometimes', 'boolean'], 'scanner_category_validation_enabled' => ['sometimes', 'boolean'],
]; ];

View File

@@ -6,15 +6,16 @@
"keywords": ["laravel", "framework"], "keywords": ["laravel", "framework"],
"license": "MIT", "license": "MIT",
"require": { "require": {
"ext-gd": "*",
"php": "^8.3", "php": "^8.3",
"ext-gd": "*",
"barryvdh/laravel-dompdf": "^3.1", "barryvdh/laravel-dompdf": "^3.1",
"endroid/qr-code": "^6.1", "endroid/qr-code": "^6.1",
"laravel/framework": "^13.8", "laravel/framework": "^13.8",
"laravel/sanctum": "^4.3", "laravel/sanctum": "^4.3",
"laravel/socialite": "^5.29", "laravel/socialite": "^5.29",
"laravel/tinker": "^3.0", "laravel/tinker": "^3.0",
"league/flysystem-aws-s3-v3": "^3.0" "league/flysystem-aws-s3-v3": "^3.0",
"phpoffice/phpspreadsheet": "^5.9"
}, },
"require-dev": { "require-dev": {
"fakerphp/faker": "^1.23", "fakerphp/faker": "^1.23",

376
composer.lock generated
View File

@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "ce185c60c617846be30ae694f0cf6e9c", "content-hash": "a593ab47d99b233f75851dbb7ea50479",
"packages": [ "packages": [
{ {
"name": "aws/aws-crt-php", "name": "aws/aws-crt-php",
@@ -417,6 +417,82 @@
], ],
"time": "2024-02-09T16:56:22+00:00" "time": "2024-02-09T16:56:22+00:00"
}, },
{
"name": "composer/pcre",
"version": "3.4.0",
"source": {
"type": "git",
"url": "https://github.com/composer/pcre.git",
"reference": "d5a341b3fb61f3001970940afb1d332968a183ed"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/composer/pcre/zipball/d5a341b3fb61f3001970940afb1d332968a183ed",
"reference": "d5a341b3fb61f3001970940afb1d332968a183ed",
"shasum": ""
},
"require": {
"php": "^7.4 || ^8.0"
},
"conflict": {
"phpstan/phpstan": "<2.2.2"
},
"require-dev": {
"phpstan/phpstan": "^2",
"phpstan/phpstan-deprecation-rules": "^2",
"phpstan/phpstan-strict-rules": "^2",
"phpunit/phpunit": "^9"
},
"type": "library",
"extra": {
"phpstan": {
"includes": [
"extension.neon"
]
},
"branch-alias": {
"dev-main": "3.x-dev"
}
},
"autoload": {
"psr-4": {
"Composer\\Pcre\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Jordi Boggiano",
"email": "j.boggiano@seld.be",
"homepage": "http://seld.be"
}
],
"description": "PCRE wrapping library that offers type-safe preg_* replacements.",
"keywords": [
"PCRE",
"preg",
"regex",
"regular expression"
],
"support": {
"issues": "https://github.com/composer/pcre/issues",
"source": "https://github.com/composer/pcre/tree/3.4.0"
},
"funding": [
{
"url": "https://packagist.com",
"type": "custom"
},
{
"url": "https://github.com/composer",
"type": "github"
}
],
"time": "2026-06-07T11:47:49+00:00"
},
{ {
"name": "dasprid/enum", "name": "dasprid/enum",
"version": "1.0.7", "version": "1.0.7",
@@ -2924,6 +3000,191 @@
], ],
"time": "2026-03-08T20:05:35+00:00" "time": "2026-03-08T20:05:35+00:00"
}, },
{
"name": "maennchen/zipstream-php",
"version": "3.2.2",
"source": {
"type": "git",
"url": "https://github.com/maennchen/ZipStream-PHP.git",
"reference": "77bebeb4c6c340bb3c11c843b2cffd8bbfde4d5e"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/maennchen/ZipStream-PHP/zipball/77bebeb4c6c340bb3c11c843b2cffd8bbfde4d5e",
"reference": "77bebeb4c6c340bb3c11c843b2cffd8bbfde4d5e",
"shasum": ""
},
"require": {
"ext-mbstring": "*",
"ext-zlib": "*",
"php-64bit": "^8.3"
},
"require-dev": {
"brianium/paratest": "^7.7",
"ext-zip": "*",
"friendsofphp/php-cs-fixer": "^3.86",
"guzzlehttp/guzzle": "^7.5",
"mikey179/vfsstream": "^1.6",
"php-coveralls/php-coveralls": "^2.5",
"phpunit/phpunit": "^12.0",
"vimeo/psalm": "^6.0"
},
"suggest": {
"guzzlehttp/psr7": "^2.4",
"psr/http-message": "^2.0"
},
"type": "library",
"autoload": {
"psr-4": {
"ZipStream\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Paul Duncan",
"email": "pabs@pablotron.org"
},
{
"name": "Jonatan Männchen",
"email": "jonatan@maennchen.ch"
},
{
"name": "Jesse Donat",
"email": "donatj@gmail.com"
},
{
"name": "András Kolesár",
"email": "kolesar@kolesar.hu"
}
],
"description": "ZipStream is a library for dynamically streaming dynamic zip files from PHP without writing to the disk at all on the server.",
"keywords": [
"stream",
"zip"
],
"support": {
"issues": "https://github.com/maennchen/ZipStream-PHP/issues",
"source": "https://github.com/maennchen/ZipStream-PHP/tree/3.2.2"
},
"funding": [
{
"url": "https://github.com/maennchen",
"type": "github"
}
],
"time": "2026-04-11T18:38:28+00:00"
},
{
"name": "markbaker/complex",
"version": "3.0.2",
"source": {
"type": "git",
"url": "https://github.com/MarkBaker/PHPComplex.git",
"reference": "95c56caa1cf5c766ad6d65b6344b807c1e8405b9"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/MarkBaker/PHPComplex/zipball/95c56caa1cf5c766ad6d65b6344b807c1e8405b9",
"reference": "95c56caa1cf5c766ad6d65b6344b807c1e8405b9",
"shasum": ""
},
"require": {
"php": "^7.2 || ^8.0"
},
"require-dev": {
"dealerdirect/phpcodesniffer-composer-installer": "dev-master",
"phpcompatibility/php-compatibility": "^9.3",
"phpunit/phpunit": "^7.0 || ^8.0 || ^9.0",
"squizlabs/php_codesniffer": "^3.7"
},
"type": "library",
"autoload": {
"psr-4": {
"Complex\\": "classes/src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Mark Baker",
"email": "mark@lange.demon.co.uk"
}
],
"description": "PHP Class for working with complex numbers",
"homepage": "https://github.com/MarkBaker/PHPComplex",
"keywords": [
"complex",
"mathematics"
],
"support": {
"issues": "https://github.com/MarkBaker/PHPComplex/issues",
"source": "https://github.com/MarkBaker/PHPComplex/tree/3.0.2"
},
"time": "2022-12-06T16:21:08+00:00"
},
{
"name": "markbaker/matrix",
"version": "3.0.1",
"source": {
"type": "git",
"url": "https://github.com/MarkBaker/PHPMatrix.git",
"reference": "728434227fe21be27ff6d86621a1b13107a2562c"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/MarkBaker/PHPMatrix/zipball/728434227fe21be27ff6d86621a1b13107a2562c",
"reference": "728434227fe21be27ff6d86621a1b13107a2562c",
"shasum": ""
},
"require": {
"php": "^7.1 || ^8.0"
},
"require-dev": {
"dealerdirect/phpcodesniffer-composer-installer": "dev-master",
"phpcompatibility/php-compatibility": "^9.3",
"phpdocumentor/phpdocumentor": "2.*",
"phploc/phploc": "^4.0",
"phpmd/phpmd": "2.*",
"phpunit/phpunit": "^7.0 || ^8.0 || ^9.0",
"sebastian/phpcpd": "^4.0",
"squizlabs/php_codesniffer": "^3.7"
},
"type": "library",
"autoload": {
"psr-4": {
"Matrix\\": "classes/src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Mark Baker",
"email": "mark@demon-angel.eu"
}
],
"description": "PHP Class for working with matrices",
"homepage": "https://github.com/MarkBaker/PHPMatrix",
"keywords": [
"mathematics",
"matrix",
"vector"
],
"support": {
"issues": "https://github.com/MarkBaker/PHPMatrix/issues",
"source": "https://github.com/MarkBaker/PHPMatrix/tree/3.0.1"
},
"time": "2022-12-02T22:17:43+00:00"
},
{ {
"name": "masterminds/html5", "name": "masterminds/html5",
"version": "2.10.1", "version": "2.10.1",
@@ -3686,6 +3947,115 @@
}, },
"time": "2020-10-15T08:29:30+00:00" "time": "2020-10-15T08:29:30+00:00"
}, },
{
"name": "phpoffice/phpspreadsheet",
"version": "5.9.0",
"source": {
"type": "git",
"url": "https://github.com/PHPOffice/PhpSpreadsheet.git",
"reference": "05e99ebf61238a70227b4d9cc02d0030d34f6339"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/PHPOffice/PhpSpreadsheet/zipball/05e99ebf61238a70227b4d9cc02d0030d34f6339",
"reference": "05e99ebf61238a70227b4d9cc02d0030d34f6339",
"shasum": ""
},
"require": {
"composer/pcre": "^1||^2||^3",
"ext-ctype": "*",
"ext-dom": "*",
"ext-fileinfo": "*",
"ext-filter": "*",
"ext-gd": "*",
"ext-iconv": "*",
"ext-libxml": "*",
"ext-mbstring": "*",
"ext-simplexml": "*",
"ext-xml": "*",
"ext-xmlreader": "*",
"ext-xmlwriter": "*",
"ext-zip": "*",
"ext-zlib": "*",
"maennchen/zipstream-php": "^2.1 || ^3.0",
"markbaker/complex": "^3.0",
"markbaker/matrix": "^3.0",
"php": "^8.2",
"psr/simple-cache": "^1.0 || ^2.0 || ^3.0"
},
"require-dev": {
"dealerdirect/phpcodesniffer-composer-installer": "dev-main",
"dompdf/dompdf": "^2.0 || ^3.0",
"ext-intl": "*",
"friendsofphp/php-cs-fixer": "^3.2",
"mitoteam/jpgraph": "^10.5",
"mpdf/mpdf": "^8.1.1",
"phpcompatibility/php-compatibility": "^9.3",
"phpstan/phpstan": "^1.1 || ^2.0",
"phpstan/phpstan-deprecation-rules": "^1.0 || ^2.0",
"phpstan/phpstan-phpunit": "^1.0 || ^2.0",
"phpunit/phpunit": "^10.5 || ^11.0",
"squizlabs/php_codesniffer": "^3.7",
"tecnickcom/tcpdf": "^6.5"
},
"suggest": {
"dompdf/dompdf": "Option for rendering PDF with PDF Writer",
"ext-intl": "PHP Internationalization Functions, required for NumberFormat Wizard and StringHelper::setLocale()",
"mitoteam/jpgraph": "Option for rendering charts, or including charts with PDF or HTML Writers",
"mpdf/mpdf": "Option for rendering PDF with PDF Writer",
"tecnickcom/tcpdf": "Option for rendering PDF with PDF Writer"
},
"type": "library",
"autoload": {
"psr-4": {
"PhpOffice\\PhpSpreadsheet\\": "src/PhpSpreadsheet"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Maarten Balliauw",
"homepage": "https://blog.maartenballiauw.be"
},
{
"name": "Mark Baker",
"homepage": "https://markbakeruk.net"
},
{
"name": "Franck Lefevre",
"homepage": "https://rootslabs.net"
},
{
"name": "Erik Tilt"
},
{
"name": "Adrien Crivelli"
},
{
"name": "Owen Leibman"
}
],
"description": "PHPSpreadsheet - Read, Create and Write Spreadsheet documents in PHP - Spreadsheet engine",
"homepage": "https://github.com/PHPOffice/PhpSpreadsheet",
"keywords": [
"OpenXML",
"excel",
"gnumeric",
"ods",
"php",
"spreadsheet",
"xls",
"xlsx"
],
"support": {
"issues": "https://github.com/PHPOffice/PhpSpreadsheet/issues",
"source": "https://github.com/PHPOffice/PhpSpreadsheet/tree/5.9.0"
},
"time": "2026-07-12T19:17:39+00:00"
},
{ {
"name": "phpoption/phpoption", "name": "phpoption/phpoption",
"version": "1.9.5", "version": "1.9.5",
@@ -9838,8 +10208,8 @@
"prefer-stable": true, "prefer-stable": true,
"prefer-lowest": false, "prefer-lowest": false,
"platform": { "platform": {
"ext-gd": "*", "php": "^8.3",
"php": "^8.3" "ext-gd": "*"
}, },
"platform-dev": {}, "platform-dev": {},
"plugin-api-version": "2.9.0" "plugin-api-version": "2.9.0"

View File

@@ -0,0 +1,20 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
public function up(): void
{
DB::table('tenants')->update([
'checkout_editing_policy' => 'disabled',
]);
}
public function down(): void
{
// Checkout editing stays disabled because previous tenant values cannot
// be reconstructed after normalization.
}
};

View File

@@ -0,0 +1,46 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('carritos', function (Blueprint $table): void {
$table->foreignId('current_purchase_id')
->nullable()
->after('origin')
->constrained('compras')
->nullOnDelete();
$table->unique('current_purchase_id', 'carts_current_purchase_unique');
});
DB::table('carritos')
->select('id')
->orderBy('id')
->each(function (object $cart): void {
$purchaseId = DB::table('compras')
->where('cart_id', $cart->id)
->whereIn('status', ['created', 'pending_payment'])
->latest('id')
->value('id');
if ($purchaseId !== null) {
DB::table('carritos')
->where('id', $cart->id)
->update(['current_purchase_id' => $purchaseId]);
}
});
}
public function down(): void
{
Schema::table('carritos', function (Blueprint $table): void {
$table->dropUnique('carts_current_purchase_unique');
$table->dropConstrainedForeignId('current_purchase_id');
});
}
};

View File

@@ -0,0 +1,25 @@
<?php
use App\Domains\Desfile\Services\InvitationPurchaseProvisioner;
use Illuminate\Database\Migrations\Migration;
return new class extends Migration
{
public function up(): void
{
app(InvitationPurchaseProvisioner::class)->provision([
[
'sector' => 'C',
'row' => 3,
'first_seat' => 6,
'last_seat' => 7,
'type' => 'NORMAL',
],
]);
}
public function down(): void
{
// Intentionally irreversible: issued invitation tickets may already be used.
}
};

View File

@@ -0,0 +1,22 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('categorias', function (Blueprint $table): void {
$table->boolean('is_enabled')->default(true)->after('nombre');
});
}
public function down(): void
{
Schema::table('categorias', function (Blueprint $table): void {
$table->dropColumn('is_enabled');
});
}
};

View File

@@ -0,0 +1,53 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('catalog_items', function (Blueprint $table): void {
$table->unsignedInteger('group_order')->default(0)->after('nombre');
});
$footballOrder = [
1 => [
'slugs' => ['camiseta', 'camiseta-oficial-fnfi'],
'names' => ['Camiseta', 'CAMISETA OFICIAL FNFI'],
],
2 => [
'slugs' => ['alojamiento', 'camping'],
'names' => ['Alojamiento', 'CAMPING'],
],
3 => [
'slugs' => ['abono'],
'names' => ['Abono', 'ABONO'],
],
4 => [
'slugs' => ['comida'],
'names' => ['Comida', 'COMIDA'],
],
];
foreach ($footballOrder as $order => $identifiers) {
DB::table('catalog_items')
->where('tenant_code', 'fiesta_futbol_infantil')
->where(function ($query) use ($identifiers): void {
$query
->whereIn('slug', $identifiers['slugs'])
->orWhereIn('nombre', $identifiers['names']);
})
->update(['group_order' => $order]);
}
}
public function down(): void
{
Schema::table('catalog_items', function (Blueprint $table): void {
$table->dropColumn('group_order');
});
}
};

View File

@@ -78,6 +78,7 @@ class FiestaFutbolInfantilProductSeeder extends Seeder
$this->createProduct($tenant, [ $this->createProduct($tenant, [
'slug' => 'camiseta', 'slug' => 'camiseta',
'nombre' => 'Camiseta', 'nombre' => 'Camiseta',
'group_order' => 1,
'category_id' => $categories['merchandising']->id, 'category_id' => $categories['merchandising']->id,
'precio' => 18000, 'precio' => 18000,
'attribute_codes' => ['color', 'talle'], 'attribute_codes' => ['color', 'talle'],
@@ -92,6 +93,7 @@ class FiestaFutbolInfantilProductSeeder extends Seeder
$this->createProduct($tenant, [ $this->createProduct($tenant, [
'slug' => 'alojamiento', 'slug' => 'alojamiento',
'nombre' => 'Alojamiento', 'nombre' => 'Alojamiento',
'group_order' => 2,
'category_id' => $categories['alojamientos']->id, 'category_id' => $categories['alojamientos']->id,
'precio' => 35000, 'precio' => 35000,
'attribute_codes' => ['tipo_alojamiento'], 'attribute_codes' => ['tipo_alojamiento'],
@@ -104,6 +106,7 @@ class FiestaFutbolInfantilProductSeeder extends Seeder
$this->createProduct($tenant, [ $this->createProduct($tenant, [
'slug' => 'comida', 'slug' => 'comida',
'nombre' => 'Comida', 'nombre' => 'Comida',
'group_order' => 4,
'category_id' => $categories['comidas']->id, 'category_id' => $categories['comidas']->id,
'precio' => 4000, 'precio' => 4000,
'attribute_codes' => ['event_date', 'horario', 'servicio'], 'attribute_codes' => ['event_date', 'horario', 'servicio'],
@@ -126,6 +129,7 @@ class FiestaFutbolInfantilProductSeeder extends Seeder
$this->createProduct($tenant, [ $this->createProduct($tenant, [
'slug' => 'abono', 'slug' => 'abono',
'nombre' => 'Abono', 'nombre' => 'Abono',
'group_order' => 3,
'category_id' => $categories['entradas']->id, 'category_id' => $categories['entradas']->id,
'precio' => 40000, 'precio' => 40000,
'has_tickets' => true, 'has_tickets' => true,

View File

@@ -42,8 +42,9 @@ return [
'payment_method_required' => 'The purchase payment method must be selected before finalizing.', 'payment_method_required' => 'The purchase payment method must be selected before finalizing.',
'not_editable' => 'The purchase is no longer editable.', 'not_editable' => 'The purchase is no longer editable.',
'insufficient_stock' => 'There is not enough stock available.', 'insufficient_stock' => 'There is not enough stock available.',
'cannot_confirm' => 'A cancelled, rejected, or expired purchase cannot be confirmed.', 'cannot_confirm' => 'A cancelled, rejected, expired, or superseded purchase cannot be confirmed.',
'inconsistent_reservation' => 'The purchase has an inconsistent stock reservation.', 'inconsistent_reservation' => 'The purchase has an inconsistent stock reservation.',
'not_current' => 'The purchase is no longer the cart\'s current checkout.',
'paid_cannot_cancel' => 'A paid purchase cannot be cancelled.', 'paid_cannot_cancel' => 'A paid purchase cannot be cancelled.',
'stock' => [ 'stock' => [
'seat_unavailable' => 'Seat :selection is no longer available.', 'seat_unavailable' => 'Seat :selection is no longer available.',
@@ -55,6 +56,7 @@ return [
'catalog_item_missing' => 'One or more catalog items could not be loaded.', 'catalog_item_missing' => 'One or more catalog items could not be loaded.',
'catalog_item_wrong_tenant' => 'One or more catalog items do not belong to the tenant.', 'catalog_item_wrong_tenant' => 'One or more catalog items do not belong to the tenant.',
'inactive_cart' => 'The selected cart is no longer active.', 'inactive_cart' => 'The selected cart is no longer active.',
'checkout_in_progress' => 'The cart already has a purchase in progress.',
'not_available_for_payment' => 'The purchase is no longer available for payment.', 'not_available_for_payment' => 'The purchase is no longer available for payment.',
'not_available_for_review' => 'The purchase is no longer available for review.', 'not_available_for_review' => 'The purchase is no longer available for review.',
], ],

View File

@@ -37,6 +37,7 @@ return [
'required_with' => 'The :attribute field is required when :values is present.', 'required_with' => 'The :attribute field is required when :values is present.',
'required_without' => 'The :attribute field is required when :values is not present.', 'required_without' => 'The :attribute field is required when :values is not present.',
'string' => 'The :attribute must be a string.', 'string' => 'The :attribute must be a string.',
'timezone' => 'The timezone sent by the browser is invalid.',
'unique' => 'The :attribute has already been taken.', 'unique' => 'The :attribute has already been taken.',
'url' => 'The :attribute must be a valid URL.', 'url' => 'The :attribute must be a valid URL.',
'uuid' => 'The :attribute must be a valid UUID.', 'uuid' => 'The :attribute must be a valid UUID.',
@@ -52,6 +53,7 @@ return [
'password_confirmation' => 'password confirmation', 'password_confirmation' => 'password confirmation',
'telefono' => 'phone number', 'telefono' => 'phone number',
'tenant_codigo' => 'tenant', 'tenant_codigo' => 'tenant',
'timezone' => 'timezone',
'variant_id' => 'variant', 'variant_id' => 'variant',
], ],
]; ];

View File

@@ -42,8 +42,9 @@ return [
'payment_method_required' => 'Debes seleccionar el método de pago antes de finalizar la compra.', 'payment_method_required' => 'Debes seleccionar el método de pago antes de finalizar la compra.',
'not_editable' => 'La compra ya no se puede modificar.', 'not_editable' => 'La compra ya no se puede modificar.',
'insufficient_stock' => 'No hay suficiente stock disponible.', 'insufficient_stock' => 'No hay suficiente stock disponible.',
'cannot_confirm' => 'Una compra cancelada, rechazada o vencida no se puede confirmar.', 'cannot_confirm' => 'Una compra cancelada, rechazada, vencida o reemplazada no se puede confirmar.',
'inconsistent_reservation' => 'La compra tiene una reserva de stock inconsistente.', 'inconsistent_reservation' => 'La compra tiene una reserva de stock inconsistente.',
'not_current' => 'La compra ya no es el checkout actual del carrito.',
'paid_cannot_cancel' => 'Una compra pagada no se puede cancelar.', 'paid_cannot_cancel' => 'Una compra pagada no se puede cancelar.',
'stock' => [ 'stock' => [
'seat_unavailable' => 'El asiento :selection ya no está disponible.', 'seat_unavailable' => 'El asiento :selection ya no está disponible.',
@@ -55,6 +56,7 @@ return [
'catalog_item_missing' => 'No se pudieron cargar uno o más productos del catálogo.', 'catalog_item_missing' => 'No se pudieron cargar uno o más productos del catálogo.',
'catalog_item_wrong_tenant' => 'Uno o más productos no pertenecen al tenant.', 'catalog_item_wrong_tenant' => 'Uno o más productos no pertenecen al tenant.',
'inactive_cart' => 'El carrito seleccionado ya no está activo.', 'inactive_cart' => 'El carrito seleccionado ya no está activo.',
'checkout_in_progress' => 'El carrito ya tiene una compra en curso.',
'not_available_for_payment' => 'La compra ya no está disponible para el pago.', 'not_available_for_payment' => 'La compra ya no está disponible para el pago.',
'not_available_for_review' => "La compra ya no est\u{00E1} disponible para revisi\u{00F3}n.", 'not_available_for_review' => "La compra ya no est\u{00E1} disponible para revisi\u{00F3}n.",
], ],

View File

@@ -37,6 +37,7 @@ return [
'required_with' => 'El campo :attribute es obligatorio cuando :values está presente.', 'required_with' => 'El campo :attribute es obligatorio cuando :values está presente.',
'required_without' => 'El campo :attribute es obligatorio cuando :values no está presente.', 'required_without' => 'El campo :attribute es obligatorio cuando :values no está presente.',
'string' => ':Attribute debe ser texto.', 'string' => ':Attribute debe ser texto.',
'timezone' => 'La zona horaria enviada por el navegador no es válida.',
'unique' => 'El :attribute ya está en uso.', 'unique' => 'El :attribute ya está en uso.',
'url' => ':Attribute debe ser una URL válida.', 'url' => ':Attribute debe ser una URL válida.',
'uuid' => ':Attribute debe ser un UUID válido.', 'uuid' => ':Attribute debe ser un UUID válido.',
@@ -52,6 +53,7 @@ return [
'password_confirmation' => 'confirmación de contraseña', 'password_confirmation' => 'confirmación de contraseña',
'telefono' => 'teléfono', 'telefono' => 'teléfono',
'tenant_codigo' => 'tenant', 'tenant_codigo' => 'tenant',
'timezone' => 'zona horaria',
'variant_id' => 'variante', 'variant_id' => 'variante',
], ],
]; ];

View File

@@ -1,4 +1,4 @@
@props(['tenant', 'headerLogoUrl' => null, 'footerLogoUrl' => null]) @props(['branding', 'headerLogoUrl' => null, 'footerLogoUrl' => null])
<!DOCTYPE html> <!DOCTYPE html>
<html lang="es"> <html lang="es">
@@ -6,7 +6,7 @@
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="color-scheme" content="light"> <meta name="color-scheme" content="light">
<title>{{ $tenant->nombre }}</title> <title>{{ $branding['name'] }}</title>
<style> <style>
@media only screen and (max-width: 620px) { @media only screen and (max-width: 620px) {
.mail-container { width: 100% !important; } .mail-container { width: 100% !important; }
@@ -14,17 +14,17 @@
} }
</style> </style>
</head> </head>
<body style="margin: 0; padding: 0; background-color: #f1f5f9; color: #334155; font-family: Arial, Helvetica, sans-serif;"> <body style="margin: 0; padding: 0; background-color: {{ $branding['background_color'] }}; color: {{ $branding['body_color'] }}; font-family: Arial, Helvetica, sans-serif;">
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="background-color: #f1f5f9;"> <table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="background-color: {{ $branding['background_color'] }};">
<tr> <tr>
<td align="center" style="padding: 32px 12px;"> <td align="center" style="padding: 32px 12px;">
<table role="presentation" width="600" cellspacing="0" cellpadding="0" border="0" class="mail-container" style="width: 600px; max-width: 600px; background-color: #ffffff; border-top: 4px solid {{ $tenant->primary_color }}; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(15, 23, 42, 0.08);"> <table role="presentation" width="600" cellspacing="0" cellpadding="0" border="0" class="mail-container" style="width: 600px; max-width: 600px; background-color: {{ $branding['surface_color'] }}; border-top: 4px solid {{ $branding['primary_color'] }}; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(15, 23, 42, 0.08);">
<tr> <tr>
<td align="center" bgcolor="{{ $tenant->header_bg_color }}" style="padding: 24px 32px; background-color: {{ $tenant->header_bg_color }};"> <td align="center" bgcolor="{{ $branding['header_bg_color'] }}" style="padding: 24px 32px; background-color: {{ $branding['header_bg_color'] }};">
@if ($headerLogoUrl) @if ($headerLogoUrl)
<img src="{{ $headerLogoUrl }}" alt="{{ $tenant->nombre }}" width="180" style="display: block; width: auto; max-width: 180px; max-height: 64px; border: 0;"> <img src="{{ $headerLogoUrl }}" alt="{{ $branding['name'] }}" width="180" style="display: block; width: auto; max-width: 180px; max-height: 64px; border: 0;">
@else @else
<span style="color: {{ $tenant->primary_color }}; font-size: 24px; font-weight: 700; line-height: 1.2;">{{ $tenant->nombre }}</span> <span style="color: {{ $branding['primary_color'] }}; font-size: 24px; font-weight: 700; line-height: 1.2;">{{ $branding['name'] }}</span>
@endif @endif
</td> </td>
</tr> </tr>
@@ -34,11 +34,11 @@
</td> </td>
</tr> </tr>
<tr> <tr>
<td align="center" bgcolor="{{ $tenant->footer_bg_color }}" style="padding: 24px 32px; background-color: {{ $tenant->footer_bg_color }}; color: #ffffff; font-size: 12px; line-height: 1.5;"> <td align="center" bgcolor="{{ $branding['footer_bg_color'] }}" style="padding: 24px 32px; background-color: {{ $branding['footer_bg_color'] }}; color: #ffffff; font-size: 12px; line-height: 1.5;">
@if ($footerLogoUrl) @if ($footerLogoUrl)
<img src="{{ $footerLogoUrl }}" alt="{{ $tenant->nombre }}" width="140" style="display: block; width: auto; max-width: 140px; max-height: 48px; margin: 0 auto 16px; border: 0;"> <img src="{{ $footerLogoUrl }}" alt="{{ $branding['name'] }}" width="140" style="display: block; width: auto; max-width: 140px; max-height: 48px; margin: 0 auto 16px; border: 0;">
@endif @endif
{{ $footer ?? 'Este correo fue enviado por '.$tenant->nombre.'.' }} {{ $footer ?? 'Este correo fue enviado por '.$branding['name'].'.' }}
</td> </td>
</tr> </tr>
</table> </table>

View File

@@ -1,10 +1,10 @@
<h1 style="margin: 0 0 20px; color: {{ $tenant->primary_color }};"> <h1 style="margin: 0 0 20px; color: {{ $brand->primary_color }};">
Recuperá tu contraseña Recuperá tu contraseña
</h1> </h1>
@if($attempt->reason === \App\Domains\Auth\Models\ResetPasswordAttempt::REASON_STAFF_CREATED) @if($attempt->reason === \App\Domains\Auth\Models\ResetPasswordAttempt::REASON_STAFF_CREATED)
<p> <p>
Hola {{ $attempt->user->nombre_apellido }}, creamos tu cuenta de scanner en {{ $tenant->nombre }}. Utilizá este código para crear tu contraseña y comenzar a usarla. Hola {{ $attempt->user->nombre_apellido }}, creamos tu cuenta de scanner en {{ $brand->nombre }}. Utilizá este código para crear tu contraseña y comenzar a usarla.
</p> </p>
@elseif($attempt->reason === \App\Domains\Auth\Models\ResetPasswordAttempt::REASON_ACCOUNT_LOCKED) @elseif($attempt->reason === \App\Domains\Auth\Models\ResetPasswordAttempt::REASON_ACCOUNT_LOCKED)
<p> <p>
@@ -17,10 +17,10 @@
</p> </p>
@endif @endif
<p>Ingresá este código en {{ $tenant->nombre }}:</p> <p>Ingresá este código en {{ $brand->nombre }}:</p>
<div style="margin: 28px 0; padding: 20px; border: 2px solid {{ $tenant->primary_color }}; border-radius: 8px; text-align: center;"> <div style="margin: 28px 0; padding: 20px; border: 2px solid {{ $brand->primary_color }}; border-radius: 8px; text-align: center;">
<span style="color: {{ $tenant->primary_color }}; font-size: 36px; font-weight: 700; letter-spacing: 12px;"> <span style="color: {{ $brand->primary_color }}; font-size: 36px; font-weight: 700; letter-spacing: 12px;">
{{ $attempt->codigo }} {{ $attempt->codigo }}
</span> </span>
</div> </div>
@@ -28,7 +28,7 @@
@if($recoveryUrl) @if($recoveryUrl)
<div style="text-align: center; margin-bottom: 28px;"> <div style="text-align: center; margin-bottom: 28px;">
<a href="{{ $recoveryUrl }}" <a href="{{ $recoveryUrl }}"
style="display: inline-block; padding: 12px 24px; background-color: {{ $tenant->primary_color }}; color: #ffffff; text-decoration: none; border-radius: 6px; font-weight: bold;"> style="display: inline-block; padding: 12px 24px; background-color: {{ $brand->primary_color }}; color: #ffffff; text-decoration: none; border-radius: 6px; font-weight: bold;">
{{ $attempt->reason === \App\Domains\Auth\Models\ResetPasswordAttempt::REASON_STAFF_CREATED ? 'Crear mi contraseña' : 'Ingresar código ahora' }} {{ $attempt->reason === \App\Domains\Auth\Models\ResetPasswordAttempt::REASON_STAFF_CREATED ? 'Crear mi contraseña' : 'Ingresar código ahora' }}
</a> </a>
</div> </div>

View File

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

View File

@@ -1,4 +1,4 @@
<x-mail.branded-layout :tenant="$tenant" :header-logo-url="$headerLogoUrl" :footer-logo-url="$footerLogoUrl"> <x-mail.branded-layout :branding="$branding" :header-logo-url="$headerLogoUrl" :footer-logo-url="$footerLogoUrl">
<h1 style="margin: 0 0 20px; color: {{ $tenant->primary_color }}; font-size: 26px; line-height: 1.3;"> <h1 style="margin: 0 0 20px; color: {{ $tenant->primary_color }}; font-size: 26px; line-height: 1.3;">
Prueba de correo de Shopit Prueba de correo de Shopit
</h1> </h1>

View File

@@ -25,7 +25,7 @@
</head> </head>
<body> <body>
<h1>Historial de modificaciones de ventas</h1> <h1>Historial de modificaciones de ventas</h1>
<p class="subtitle">{{ $tenant->nombre }} · Generado el {{ $generatedAt->format('d/m/Y H:i') }}</p> <p class="subtitle">{{ $tenant->nombre }} · Generado el {{ $generatedAt->copy()->timezone($timeZone)->format('d/m/Y H:i') }}</p>
<table> <table>
<thead> <thead>
@@ -44,8 +44,8 @@
@forelse ($modifications as $modification) @forelse ($modifications as $modification)
@php($sale = $modification->trackable) @php($sale = $modification->trackable)
<tr> <tr>
<td>{{ $modification->changed_at->format('d/m/Y') }}</td> <td>{{ $modification->changed_at->copy()->timezone($timeZone)->format('d/m/Y') }}</td>
<td>{{ $modification->changed_at->format('H:i:s') }}</td> <td>{{ $modification->changed_at->copy()->timezone($timeZone)->format('H:i:s') }}</td>
<td>#{{ $modification->trackable_id }}</td> <td>#{{ $modification->trackable_id }}</td>
<td>{{ $sale?->nombre_apellido ?: 'Sin nombre' }}</td> <td>{{ $sale?->nombre_apellido ?: 'Sin nombre' }}</td>
<td>{{ $modification->attribute }}</td> <td>{{ $modification->attribute }}</td>

View File

@@ -22,7 +22,7 @@
</head> </head>
<body> <body>
<h1>Historial de ventas</h1> <h1>Historial de ventas</h1>
<p class="subtitle">{{ $tenant->nombre }} · Generado el {{ $generatedAt->format('d/m/Y H:i') }}</p> <p class="subtitle">{{ $tenant->nombre }} · Generado el {{ $generatedAt->copy()->timezone($timeZone)->format('d/m/Y H:i') }}</p>
<div class="summary"> <div class="summary">
Total de ventas confirmadas en este reporte: <strong>${{ number_format((float) $confirmedSalesTotal, 2, ',', '.') }}</strong> Total de ventas confirmadas en este reporte: <strong>${{ number_format((float) $confirmedSalesTotal, 2, ',', '.') }}</strong>
@@ -44,7 +44,7 @@
@forelse ($sales as $sale) @forelse ($sales as $sale)
<tr> <tr>
<td>#{{ $sale->id }}</td> <td>#{{ $sale->id }}</td>
<td>{{ $sale->created_at?->format('d/m/Y H:i') ?? '-' }}</td> <td>{{ $sale->created_at?->copy()->timezone($timeZone)->format('d/m/Y H:i') ?? '-' }}</td>
<td>{{ $sale->nombre_apellido ?: 'Sin nombre' }}</td> <td>{{ $sale->nombre_apellido ?: 'Sin nombre' }}</td>
<td class="center">{{ (int) ($sale->quantity ?? 0) }}</td> <td class="center">{{ (int) ($sale->quantity ?? 0) }}</td>
<td>{{ match ($sale->status) { <td>{{ match ($sale->status) {

View File

@@ -76,11 +76,15 @@ class CatalogControllerTest extends TestCase
->assertJsonCount(2, '0.items.0.variants') ->assertJsonCount(2, '0.items.0.variants')
->assertJsonPath('0.items.0.variants.0.maximum_addable_quantity', 4) ->assertJsonPath('0.items.0.variants.0.maximum_addable_quantity', 4)
->assertJsonPath('0.items.0.variants.1.maximum_addable_quantity', 3) ->assertJsonPath('0.items.0.variants.1.maximum_addable_quantity', 3)
->assertJsonMissing(['id' => $unavailableVariant->id])
->assertJsonPath('1.title', 'Row') ->assertJsonPath('1.title', 'Row')
->assertJsonPath('1.items.data.0.maximum_addable_quantity', 8) ->assertJsonPath('1.items.data.0.maximum_addable_quantity', 8)
->assertJsonMissingPath('1.items.data.0.stock_tecnico') ->assertJsonMissingPath('1.items.data.0.stock_tecnico')
->assertJsonCount(0, '1.items.data.0.variants'); ->assertJsonCount(0, '1.items.data.0.variants');
$this->assertNotContains(
$unavailableVariant->id,
collect($response->json('0.items.0.variants'))->pluck('id')->all(),
);
} }
public function test_maximum_addable_quantity_shares_the_authenticated_user_quota_between_variants(): void public function test_maximum_addable_quantity_shares_the_authenticated_user_quota_between_variants(): void
@@ -94,7 +98,7 @@ class CatalogControllerTest extends TestCase
); );
$user = User::factory()->create(); $user = User::factory()->create();
$item = $this->createItem($tenant, 'Limited variants'); $item = $this->createItem($tenant, 'Limited variants');
$item->update(['max_units_per_user' => 5]); $item->update(['max_units_per_user' => 3]);
$firstVariant = $item->variants()->create([ $firstVariant = $item->variants()->create([
'inventory_id' => Inventory::query()->create(['real_stock' => 10])->id, 'inventory_id' => Inventory::query()->create(['real_stock' => 10])->id,
]); ]);
@@ -114,13 +118,21 @@ class CatalogControllerTest extends TestCase
$this->actingAs($user, 'sanctum') $this->actingAs($user, 'sanctum')
->getJson("/api/tenants/{$tenant->codigo}/catalog") ->getJson("/api/tenants/{$tenant->codigo}/catalog")
->assertOk() ->assertOk()
->assertJsonPath('0.items.0.variants.0.maximum_addable_quantity', 2) ->assertJsonPath('0.items.0.variants.0.maximum_addable_quantity', 0)
->assertJsonPath('0.items.0.variants.1.maximum_addable_quantity', 2) ->assertJsonPath('0.items.0.variants.1.maximum_addable_quantity', 0)
->assertJsonPath(
'0.items.0.variants.0.unavailable_message',
'Alcanzaste el cupo máximo permitido para este producto.',
)
->assertJsonPath(
'0.items.0.variants.1.unavailable_message',
'Alcanzaste el cupo máximo permitido para este producto.',
)
->assertJsonMissingPath('0.items.0.variants.0.stock_tecnico') ->assertJsonMissingPath('0.items.0.variants.0.stock_tecnico')
->assertJsonMissingPath('0.items.0.variants.1.stock_tecnico'); ->assertJsonMissingPath('0.items.0.variants.1.stock_tecnico');
} }
public function test_it_excludes_items_when_all_of_their_variants_are_out_of_stock(): void public function test_it_excludes_out_of_stock_items(): void
{ {
$tenant = $this->createTenant('catalog-available-variants'); $tenant = $this->createTenant('catalog-available-variants');
$group = $this->createGroup( $group = $this->createGroup(
@@ -150,6 +162,7 @@ class CatalogControllerTest extends TestCase
->assertOk() ->assertOk()
->assertJsonCount(1, '0.items') ->assertJsonCount(1, '0.items')
->assertJsonPath('0.items.0.nombre', 'Available') ->assertJsonPath('0.items.0.nombre', 'Available')
->assertJsonPath('0.items.0.unavailable_message', null)
->assertJsonMissing(['nombre' => 'Unavailable']); ->assertJsonMissing(['nombre' => 'Unavailable']);
} }
@@ -335,8 +348,10 @@ class CatalogControllerTest extends TestCase
]); ]);
$food = $this->createItem($tenant, 'Hamburger'); $food = $this->createItem($tenant, 'Hamburger');
$food->update(['group_order' => 2]);
$food->category()->associate($category)->save(); $food->category()->associate($category)->save();
$this->createItem($tenant, 'Parking'); $parking = $this->createItem($tenant, 'Parking');
$parking->update(['group_order' => 1]);
$this->getJson("/api/tenants/{$tenant->codigo}/catalog") $this->getJson("/api/tenants/{$tenant->codigo}/catalog")
->assertOk() ->assertOk()
@@ -345,9 +360,59 @@ class CatalogControllerTest extends TestCase
->assertJsonPath('0.items.0.nombre', 'Hamburger') ->assertJsonPath('0.items.0.nombre', 'Hamburger')
->assertJsonPath('1.title', 'All products') ->assertJsonPath('1.title', 'All products')
->assertJsonCount(2, '1.items.data') ->assertJsonCount(2, '1.items.data')
->assertJsonPath('1.items.data.0.nombre', 'Parking')
->assertJsonPath('1.items.data.1.nombre', 'Hamburger')
->assertJsonMissingPath('1.items.data.0.group_order')
->assertJsonPath('1.items.meta.total', 2); ->assertJsonPath('1.items.meta.total', 2);
} }
public function test_index_excludes_items_from_disabled_categories(): void
{
$tenant = $this->createTenant('catalog-disabled-category');
$group = $this->createGroup(
$tenant,
ProductLayout::Row,
'All products',
groupLayout: GroupLayout::Simple,
);
$enabledCategory = Category::query()->create([
'tenant_code' => $tenant->codigo,
'nombre' => 'Enabled',
]);
$disabledCategory = Category::query()->create([
'tenant_code' => $tenant->codigo,
'nombre' => 'Disabled',
'is_enabled' => false,
]);
$enabledItem = $this->createItem($tenant, 'Enabled item');
$enabledItem->category()->associate($enabledCategory)->save();
$disabledItem = $this->createItem($tenant, 'Disabled item');
$disabledItem->category()->associate($disabledCategory)->save();
$uncategorizedItem = $this->createItem($tenant, 'Uncategorized item');
foreach ([$enabledItem, $disabledItem, $uncategorizedItem] as $order => $item) {
$group->featuredItems()->create([
'catalog_item_id' => $item->id,
'order' => $order,
]);
}
$this->getJson("/api/tenants/{$tenant->codigo}/catalog")
->assertOk()
->assertJsonCount(2, '0.items')
->assertJsonPath('0.items.0.nombre', 'Enabled item')
->assertJsonPath('0.items.1.nombre', 'Uncategorized item')
->assertJsonMissing(['nombre' => 'Disabled item']);
$this->getJson(
"/api/tenants/{$tenant->codigo}/catalog/featured-groups/{$group->id}/items"
)
->assertOk()
->assertJsonCount(2)
->assertJsonMissing(['nombre' => 'Disabled item']);
}
private function createGroup( private function createGroup(
Tenant $tenant, Tenant $tenant,
ProductLayout $layout, ProductLayout $layout,

View File

@@ -31,6 +31,7 @@ class CatalogItemControllerTest extends TestCase
$response = $this->postJson("/api/tenants/{$tenant->codigo}/catalog-items", [ $response = $this->postJson("/api/tenants/{$tenant->codigo}/catalog-items", [
'slug' => 'shirt', 'slug' => 'shirt',
'nombre' => 'Shirt', 'nombre' => 'Shirt',
'group_order' => 7,
'precio' => 100, 'precio' => 100,
'max_units_per_user' => 4, 'max_units_per_user' => 4,
'attribute_codes' => [$attribute->codigo], 'attribute_codes' => [$attribute->codigo],
@@ -47,6 +48,7 @@ class CatalogItemControllerTest extends TestCase
$response $response
->assertCreated() ->assertCreated()
->assertJsonPath('data.nombre', 'Shirt') ->assertJsonPath('data.nombre', 'Shirt')
->assertJsonMissingPath('data.group_order')
->assertJsonPath('data.max_units_per_user', 4) ->assertJsonPath('data.max_units_per_user', 4)
->assertJsonCount(2, 'data.images') ->assertJsonCount(2, 'data.images')
->assertJsonCount(1, 'data.variants') ->assertJsonCount(1, 'data.variants')
@@ -57,6 +59,7 @@ class CatalogItemControllerTest extends TestCase
$this->assertSame([0, 1], $item->attachments()->get()->pluck('pivot.orden')->all()); $this->assertSame([0, 1], $item->attachments()->get()->pluck('pivot.orden')->all());
$this->assertSame(4, $item->max_units_per_user); $this->assertSame(4, $item->max_units_per_user);
$this->assertSame(7, $item->group_order);
$this->assertSame([0], $variant->attachments()->get()->pluck('pivot.orden')->all()); $this->assertSame([0], $variant->attachments()->get()->pluck('pivot.orden')->all());
$this->assertDatabaseHas('catalog_items_attachments', [ $this->assertDatabaseHas('catalog_items_attachments', [
'catalog_item_id' => $item->id, 'catalog_item_id' => $item->id,

View File

@@ -48,7 +48,7 @@ class CatalogItemDetailControllerTest extends TestCase
$this->assertStringContainsString($itemImage->path, $response->json('data.images.0')); $this->assertStringContainsString($itemImage->path, $response->json('data.images.0'));
} }
public function test_it_filters_unavailable_variants_and_selects_the_first_available_one(): void public function test_it_omits_unavailable_variants_and_selects_the_first_available_one(): void
{ {
Storage::fake('s3'); Storage::fake('s3');
$tenant = $this->createTenant('detail-default'); $tenant = $this->createTenant('detail-default');
@@ -78,6 +78,10 @@ class CatalogItemDetailControllerTest extends TestCase
$response $response
->assertJsonMissingPath('data.stock_tecnico') ->assertJsonMissingPath('data.stock_tecnico')
->assertJsonMissingPath('data.images'); ->assertJsonMissingPath('data.images');
$this->assertNotContains(
$firstVariant->id,
collect($response->json('data.variants'))->pluck('id')->all(),
);
$this->assertStringContainsString($secondImage->path, $response->json('data.selected_variant.images.0')); $this->assertStringContainsString($secondImage->path, $response->json('data.selected_variant.images.0'));
$this->assertStringNotContainsString($firstImage->path, $response->json('data.selected_variant.images.0')); $this->assertStringNotContainsString($firstImage->path, $response->json('data.selected_variant.images.0'));
$this->assertStringNotContainsString($itemImage->path, $response->json('data.selected_variant.images.0')); $this->assertStringNotContainsString($itemImage->path, $response->json('data.selected_variant.images.0'));
@@ -87,6 +91,19 @@ class CatalogItemDetailControllerTest extends TestCase
)->assertNotFound(); )->assertNotFound();
} }
public function test_it_does_not_return_an_out_of_stock_item(): void
{
$tenant = $this->createTenant('detail-out-of-stock');
$inventory = Inventory::query()->create([
'real_stock' => 5,
'reserved_stock' => 5,
]);
$item = $this->createItem($tenant, 'Sold out item', $inventory);
$this->getJson("/api/tenants/{$tenant->codigo}/catalog-items/{$item->id}")
->assertNotFound();
}
public function test_it_selects_the_requested_variant_and_lists_variant_values_and_stock(): void public function test_it_selects_the_requested_variant_and_lists_variant_values_and_stock(): void
{ {
Storage::fake('s3'); Storage::fake('s3');

View File

@@ -5,6 +5,7 @@ namespace Tests\Feature\Catalog;
use App\Domains\Attachable\Enums\AttachmentType; use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment; use App\Domains\Attachable\Models\Attachment;
use App\Domains\Catalog\Models\CatalogItem; use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Category;
use App\Domains\Catalog\Models\Inventory; use App\Domains\Catalog\Models\Inventory;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\RefreshDatabase;
@@ -15,6 +16,21 @@ class CatalogSchemaTest extends TestCase
{ {
use RefreshDatabase; use RefreshDatabase;
public function test_categories_are_enabled_by_default(): void
{
$this->assertTrue(Schema::hasColumn('categorias', 'is_enabled'));
$category = Category::query()->create([
'nombre' => 'Enabled category',
]);
$this->assertTrue($category->is_enabled);
$this->assertDatabaseHas('categorias', [
'id' => $category->id,
'is_enabled' => true,
]);
}
public function test_legacy_product_tables_are_replaced_by_catalog_tables(): void public function test_legacy_product_tables_are_replaced_by_catalog_tables(): void
{ {
$this->assertFalse(Schema::hasTable('productos')); $this->assertFalse(Schema::hasTable('productos'));

View File

@@ -62,6 +62,24 @@ class CatalogSearchTest extends TestCase
$this->createCatalogItem($tenant, "Running {$number}"); $this->createCatalogItem($tenant, "Running {$number}");
} }
$exactMatch = $this->createCatalogItem($tenant, 'Running'); $exactMatch = $this->createCatalogItem($tenant, 'Running');
$outOfStock = CatalogItem::query()->create([
'tenant_code' => $tenant->codigo,
'slug' => 'running-sold-out',
'nombre' => 'Running sold out',
'descripcion' => 'Running sold out description',
'precio' => 100,
]);
$outOfStock->variants()->create([
'inventory_id' => Inventory::query()->create(['real_stock' => 0])->id,
]);
CatalogItem::query()->create([
'tenant_code' => $tenant->codigo,
'inventory_id' => Inventory::query()->create(['real_stock' => 2, 'reserved_stock' => 2])->id,
'slug' => 'running-direct-sold-out',
'nombre' => 'Running direct sold out',
'descripcion' => 'Running direct sold out description',
'precio' => 100,
]);
$this->createCatalogItem($tenant, 'Unrelated'); $this->createCatalogItem($tenant, 'Unrelated');
$this->createCatalogItem($otherTenant, 'Running foreign'); $this->createCatalogItem($otherTenant, 'Running foreign');
@@ -76,6 +94,8 @@ class CatalogSearchTest extends TestCase
->assertJsonPath('meta.total', 6) ->assertJsonPath('meta.total', 6)
->assertJsonCount(4, 'data') ->assertJsonCount(4, 'data')
->assertJsonPath('data.0.id', $exactMatch->id) ->assertJsonPath('data.0.id', $exactMatch->id)
->assertJsonMissing(['nombre' => 'Running sold out'])
->assertJsonMissing(['nombre' => 'Running direct sold out'])
->assertJsonMissing(['nombre' => 'Running foreign']) ->assertJsonMissing(['nombre' => 'Running foreign'])
->assertJsonMissing(['nombre' => 'Unrelated']); ->assertJsonMissing(['nombre' => 'Unrelated']);
} }

View File

@@ -29,6 +29,17 @@ class CategoryDetailTest extends TestCase
$this->createCatalogItem($tenant, $category, 'Remera C'); $this->createCatalogItem($tenant, $category, 'Remera C');
$firstItem = $this->createCatalogItem($tenant, $category, 'Remera A'); $firstItem = $this->createCatalogItem($tenant, $category, 'Remera A');
$secondItem = $this->createCatalogItem($tenant, $category, 'Remera B'); $secondItem = $this->createCatalogItem($tenant, $category, 'Remera B');
$outOfStock = CatalogItem::query()->create([
'tenant_code' => $tenant->codigo,
'category_id' => $category->id,
'slug' => 'remera-agotada',
'nombre' => 'Remera agotada',
'descripcion' => 'Sin stock',
'precio' => 100,
]);
$outOfStock->variants()->create([
'inventory_id' => Inventory::query()->create(['real_stock' => 0])->id,
]);
$this->createCatalogItem($tenant, $otherCategory, 'Pantalón'); $this->createCatalogItem($tenant, $otherCategory, 'Pantalón');
$this->getJson("/api/tenants/{$tenant->codigo}/categories/{$category->id}") $this->getJson("/api/tenants/{$tenant->codigo}/categories/{$category->id}")
@@ -44,6 +55,7 @@ class CategoryDetailTest extends TestCase
->assertJsonCount(2, 'data') ->assertJsonCount(2, 'data')
->assertJsonPath('data.0.id', $firstItem->id) ->assertJsonPath('data.0.id', $firstItem->id)
->assertJsonPath('data.1.id', $secondItem->id) ->assertJsonPath('data.1.id', $secondItem->id)
->assertJsonMissing(['nombre' => 'Remera agotada'])
->assertJsonMissing(['nombre' => 'Pantalón']); ->assertJsonMissing(['nombre' => 'Pantalón']);
} }

View File

@@ -38,6 +38,59 @@ class EntryControllerTest extends TestCase
->assertUnauthorized(); ->assertUnauthorized();
} }
public function test_category_visibility_can_be_read_and_updated_for_every_fiesta_menu(): void
{
$tenant = $this->createFiestaTenant();
$categories = [
'entries' => ['Entradas', 'adminapp.fiesta-futbol-infantil.entradas'],
'foods' => ['Comidas', 'adminapp.fiesta-futbol-infantil.comida'],
'accommodations' => ['Alojamientos', 'adminapp.fiesta-futbol-infantil.alojamientos'],
'merchandise' => ['Merchandising', 'adminapp.fiesta-futbol-infantil.merchandising'],
];
foreach ($categories as [$label, $menuCode]) {
$menu = Menu::query()->firstOrCreate(
['code' => $menuCode],
['label' => $label, 'route' => '/admin'],
);
$tenant->menues()->syncWithoutDetaching([$menu->code]);
}
Sanctum::actingAs($this->createAdminAppUser($tenant));
foreach ($categories as $endpoint => [$categoryName]) {
$this->getJson("/api/v1/adminapp/tenant/{$endpoint}/visibility")
->assertOk()
->assertJsonPath('data.is_enabled', true);
$this->patchJson("/api/v1/adminapp/tenant/{$endpoint}/visibility", [
'is_enabled' => false,
])
->assertOk()
->assertJsonPath('data.is_enabled', false)
->assertJsonPath(
'message',
'Mostrar en sitio web se desactivo correctamente',
);
$this->patchJson("/api/v1/adminapp/tenant/{$endpoint}/visibility", [
'is_enabled' => true,
])
->assertOk()
->assertJsonPath('data.is_enabled', true)
->assertJsonPath(
'message',
'Mostrar en sitio web se activo correctamente',
);
$this->assertDatabaseHas('categorias', [
'tenant_code' => $tenant->codigo,
'nombre' => $categoryName,
'is_enabled' => true,
]);
}
}
public function test_it_creates_multiple_entries_with_dates_and_tracked_inventory(): void public function test_it_creates_multiple_entries_with_dates_and_tracked_inventory(): void
{ {
$tenant = $this->createFiestaTenant(); $tenant = $this->createFiestaTenant();

View File

@@ -51,8 +51,9 @@ class AdminAppSaleFormControllerTest extends TestCase
->assertJsonPath('data.statuses.0.code', Purchase::STATUS_CREATED) ->assertJsonPath('data.statuses.0.code', Purchase::STATUS_CREATED)
->assertJsonPath('data.statuses.0.name', 'Creada') ->assertJsonPath('data.statuses.0.name', 'Creada')
->assertJsonPath('data.statuses.1.code', Purchase::STATUS_PENDING_PAYMENT) ->assertJsonPath('data.statuses.1.code', Purchase::STATUS_PENDING_PAYMENT)
->assertJsonPath('data.statuses.2.code', Purchase::STATUS_PAID) ->assertJsonPath('data.statuses.2.code', Purchase::STATUS_IN_REVIEW)
->assertJsonPath('data.statuses.5.code', Purchase::STATUS_EXPIRED); ->assertJsonPath('data.statuses.3.code', Purchase::STATUS_PAID)
->assertJsonPath('data.statuses.6.code', Purchase::STATUS_EXPIRED);
} }
public function test_a_customer_cannot_get_the_sale_form(): void public function test_a_customer_cannot_get_the_sale_form(): void

View File

@@ -194,8 +194,9 @@ class TelepagosWebhookTest extends TestCase
'sold_units' => 1, 'sold_units' => 1,
]); ]);
$this->assertDatabaseMissing('compra_items', [ $this->assertDatabaseHas('compra_items', [
'compra_id' => $newerPurchase->id, 'compra_id' => $newerPurchase->id,
'cantidad' => 2,
]); ]);
$this->assertDatabaseHas('stock_reservations', [ $this->assertDatabaseHas('stock_reservations', [
'purchase_id' => $newerPurchase->id, 'purchase_id' => $newerPurchase->id,

View File

@@ -71,19 +71,24 @@ class NotificationMailServiceTest extends TestCase
public function test_it_sends_a_branded_welcome_email(): void public function test_it_sends_a_branded_welcome_email(): void
{ {
$this->useWebsiteTypeBranding();
app(NotificationMailService::class)->sendWelcome($this->user->id, $this->tenant->codigo); app(NotificationMailService::class)->sendWelcome($this->user->id, $this->tenant->codigo);
Mail::assertSent(Mailable::class, function (Mailable $mail): bool { Mail::assertSent(Mailable::class, function (Mailable $mail): bool {
$mail->assertTo('ada@example.com'); $mail->assertTo('ada@example.com');
$mail->assertHasSubject('Bienvenido a Mail Tenant'); $mail->assertHasSubject('Bienvenido a OnTicket');
return str_contains($mail->render(), 'Ada Lovelace') return str_contains($mail->render(), 'Ada Lovelace')
&& str_contains($mail->render(), 'Mail Tenant'); && str_contains($mail->render(), 'OnTicket')
&& ! str_contains($mail->render(), 'Mail Tenant')
&& str_contains($mail->render(), 'border-top: 4px solid #ff7006');
}); });
} }
public function test_it_sends_a_branded_password_reset_email(): void public function test_it_sends_a_branded_password_reset_email(): void
{ {
$this->useWebsiteTypeBranding();
$attempt = $this->user->resetPasswordAttempts()->create([ $attempt = $this->user->resetPasswordAttempts()->create([
'codigo' => '0123', 'codigo' => '0123',
]); ]);
@@ -95,13 +100,15 @@ class NotificationMailServiceTest extends TestCase
Mail::assertSent(Mailable::class, function (Mailable $mail): bool { Mail::assertSent(Mailable::class, function (Mailable $mail): bool {
$mail->assertTo('ada@example.com'); $mail->assertTo('ada@example.com');
$mail->assertHasSubject('Código para recuperar tu contraseña - Mail Tenant'); $mail->assertHasSubject('Código para recuperar tu contraseña - OnTicket');
$rendered = $mail->render(); $rendered = $mail->render();
return str_contains($rendered, '0123') return str_contains($rendered, '0123')
&& str_contains($rendered, 'Ada Lovelace') && str_contains($rendered, 'Ada Lovelace')
&& str_contains($rendered, 'Mail Tenant') && str_contains($rendered, 'OnTicket')
&& str_contains($rendered, '#112233'); && ! str_contains($rendered, 'Mail Tenant')
&& str_contains($rendered, '#ff7006')
&& ! str_contains($rendered, 'border: 2px solid #112233');
}); });
} }
@@ -137,6 +144,7 @@ class NotificationMailServiceTest extends TestCase
public function test_it_sends_purchase_and_ticket_emails_to_the_purchase_recipient(): void public function test_it_sends_purchase_and_ticket_emails_to_the_purchase_recipient(): void
{ {
$this->useWebsiteTypeBranding();
$purchase = Purchase::query()->create([ $purchase = Purchase::query()->create([
'tenant_codigo' => $this->tenant->codigo, 'tenant_codigo' => $this->tenant->codigo,
'user_id' => $this->user->id, 'user_id' => $this->user->id,
@@ -180,13 +188,34 @@ class NotificationMailServiceTest extends TestCase
$mail->assertTo('checkout@example.com'); $mail->assertTo('checkout@example.com');
return $mail->subject === "Pago confirmado - Compra #{$purchase->id}" return $mail->subject === "Pago confirmado - Compra #{$purchase->id}"
&& str_contains($mail->render(), 'Total pagado'); && str_contains($mail->render(), 'Total pagado')
&& str_contains($mail->render(), 'border-top: 4px solid #112233')
&& ! str_contains($mail->render(), 'border-top: 4px solid #ff7006');
}); });
Mail::assertSent(Mailable::class, function (Mailable $mail): bool { Mail::assertSent(Mailable::class, function (Mailable $mail): bool {
$mail->assertTo('checkout@example.com'); $mail->assertTo('checkout@example.com');
return $mail->subject === 'Tus tickets ya están disponibles' return $mail->subject === 'Tus tickets ya están disponibles'
&& str_contains($mail->render(), 'Entrada general'); && str_contains($mail->render(), 'Entrada general')
&& str_contains($mail->render(), 'border-top: 4px solid #112233')
&& ! str_contains($mail->render(), 'border-top: 4px solid #ff7006');
}); });
} }
private function useWebsiteTypeBranding(): void
{
$websiteType = WebsiteType::query()->create([
'codigo' => 'onticket',
'nombre' => 'OnTicket',
'dominio' => 'onticket.local',
'primary_color' => '#ff7006',
'body_color' => '#666666',
'background_color' => '#f8f8f8',
'surface_color' => '#ffffff',
'login_header_footer_color' => '#838383',
]);
$this->tenant->update(['website_type_code' => $websiteType->codigo]);
$this->tenant->unsetRelation('websiteType');
}
} }

File diff suppressed because it is too large Load Diff

View File

@@ -7,9 +7,12 @@ use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Cart\Models\Cart; use App\Domains\Cart\Models\Cart;
use App\Domains\Cart\Models\CartItem; use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Models\CatalogItem; use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Inventory;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Purchase\Events\PurchasePaid; use App\Domains\Purchase\Events\PurchasePaid;
use App\Domains\Purchase\Models\Purchase; use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem; use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Purchase\Services\CheckoutService;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Models\WebsiteType; use App\Domains\Tenant\Models\WebsiteType;
use App\Domains\Ticket\Models\Ticket; use App\Domains\Ticket\Models\Ticket;
@@ -31,7 +34,7 @@ class AdminAppSaleControllerTest extends TestCase
WebsiteType::query()->create(['codigo' => 'onticket', 'nombre' => 'OnTicket']); WebsiteType::query()->create(['codigo' => 'onticket', 'nombre' => 'OnTicket']);
} }
public function test_sales_list_uses_cart_quantity_for_created_and_pending_payment_sales(): void public function test_sales_list_uses_purchase_item_snapshots_for_every_status(): void
{ {
$tenant = $this->createTenant('acme'); $tenant = $this->createTenant('acme');
Sanctum::actingAs($this->createAdminAppUser($tenant)); Sanctum::actingAs($this->createAdminAppUser($tenant));
@@ -62,9 +65,9 @@ class AdminAppSaleControllerTest extends TestCase
'compra_id' => $createdPurchase->id, 'compra_id' => $createdPurchase->id,
'source_catalog_item_id' => $catalogItem->id, 'source_catalog_item_id' => $catalogItem->id,
'item_nombre' => $catalogItem->nombre, 'item_nombre' => $catalogItem->nombre,
'cantidad' => 1, 'cantidad' => 3,
'precio_unitario' => '10000.00', 'precio_unitario' => '10000.00',
'total' => '10000.00', 'total' => '30000.00',
]); ]);
$pendingCart = Cart::query()->create([ $pendingCart = Cart::query()->create([
@@ -82,6 +85,14 @@ class AdminAppSaleControllerTest extends TestCase
'status' => Purchase::STATUS_PENDING_PAYMENT, 'status' => Purchase::STATUS_PENDING_PAYMENT,
'total' => '40000.00', 'total' => '40000.00',
]); ]);
PurchaseItem::query()->create([
'compra_id' => $pendingPurchase->id,
'source_catalog_item_id' => $catalogItem->id,
'item_nombre' => $catalogItem->nombre,
'cantidad' => 4,
'precio_unitario' => '10000.00',
'total' => '40000.00',
]);
$paidPurchase = Purchase::query()->create([ $paidPurchase = Purchase::query()->create([
'tenant_codigo' => $tenant->codigo, 'tenant_codigo' => $tenant->codigo,
@@ -97,6 +108,20 @@ class AdminAppSaleControllerTest extends TestCase
'total' => '20000.00', 'total' => '20000.00',
]); ]);
$supersededPurchase = Purchase::query()->create([
'tenant_codigo' => $tenant->codigo,
'status' => Purchase::STATUS_SUPERSEDED,
'total' => '50000.00',
]);
PurchaseItem::query()->create([
'compra_id' => $supersededPurchase->id,
'source_catalog_item_id' => $catalogItem->id,
'item_nombre' => $catalogItem->nombre,
'cantidad' => 5,
'precio_unitario' => '10000.00',
'total' => '50000.00',
]);
$this->getJson('/api/v1/adminapp/tenant/sales?sort_by=id&sort_direction=asc') $this->getJson('/api/v1/adminapp/tenant/sales?sort_by=id&sort_direction=asc')
->assertOk() ->assertOk()
->assertJsonCount(3, 'data') ->assertJsonCount(3, 'data')
@@ -106,6 +131,10 @@ class AdminAppSaleControllerTest extends TestCase
->assertJsonPath('data.1.quantity', 4) ->assertJsonPath('data.1.quantity', 4)
->assertJsonPath('data.2.id', $paidPurchase->id) ->assertJsonPath('data.2.id', $paidPurchase->id)
->assertJsonPath('data.2.quantity', 2); ->assertJsonPath('data.2.quantity', 2);
$this->getJson('/api/v1/adminapp/tenant/sales?status='.Purchase::STATUS_SUPERSEDED)
->assertOk()
->assertJsonCount(0, 'data');
} }
public function test_authentication_is_required_to_read_a_sale_detail(): void public function test_authentication_is_required_to_read_a_sale_detail(): void
@@ -113,6 +142,31 @@ class AdminAppSaleControllerTest extends TestCase
$this->getJson('/api/v1/adminapp/tenant/sales/1')->assertUnauthorized(); $this->getJson('/api/v1/adminapp/tenant/sales/1')->assertUnauthorized();
} }
public function test_pending_payment_filter_also_returns_purchases_in_review(): void
{
$tenant = $this->createTenant('acme');
Sanctum::actingAs($this->createAdminAppUser($tenant));
$pendingPurchase = Purchase::query()->create([
'tenant_codigo' => $tenant->codigo,
'status' => Purchase::STATUS_PENDING_PAYMENT,
]);
$reviewPurchase = Purchase::query()->create([
'tenant_codigo' => $tenant->codigo,
'status' => Purchase::STATUS_IN_REVIEW,
]);
Purchase::query()->create([
'tenant_codigo' => $tenant->codigo,
'status' => Purchase::STATUS_PAID,
]);
$this->getJson('/api/v1/adminapp/tenant/sales?status=pending_payment&sort_by=id&sort_direction=asc')
->assertOk()
->assertJsonCount(2, 'data')
->assertJsonPath('data.0.id', $pendingPurchase->id)
->assertJsonPath('data.1.id', $reviewPurchase->id);
}
public function test_an_adminapp_user_can_read_a_sale_detail_from_its_tenant(): void public function test_an_adminapp_user_can_read_a_sale_detail_from_its_tenant(): void
{ {
$tenant = $this->createTenant('acme'); $tenant = $this->createTenant('acme');
@@ -149,7 +203,7 @@ class AdminAppSaleControllerTest extends TestCase
->assertJsonPath('data.total', '40000.00'); ->assertJsonPath('data.total', '40000.00');
} }
public function test_an_adminapp_user_can_read_cart_items_from_an_unconfirmed_sale(): void public function test_an_adminapp_user_can_read_purchase_item_snapshots_from_an_unconfirmed_sale(): void
{ {
$tenant = $this->createTenant('acme'); $tenant = $this->createTenant('acme');
Sanctum::actingAs($this->createAdminAppUser($tenant)); Sanctum::actingAs($this->createAdminAppUser($tenant));
@@ -176,10 +230,18 @@ class AdminAppSaleControllerTest extends TestCase
'status' => Purchase::STATUS_PENDING_PAYMENT, 'status' => Purchase::STATUS_PENDING_PAYMENT,
'total' => '25000.00', 'total' => '25000.00',
]); ]);
$purchaseItem = PurchaseItem::query()->create([
'compra_id' => $purchase->id,
'source_catalog_item_id' => $catalogItem->id,
'item_nombre' => $catalogItem->nombre,
'cantidad' => 2,
'precio_unitario' => '12500.00',
'total' => '25000.00',
]);
$this->getJson("/api/v1/adminapp/tenant/sales/{$purchase->id}") $this->getJson("/api/v1/adminapp/tenant/sales/{$purchase->id}")
->assertOk() ->assertOk()
->assertJsonPath('data.items.0.id', $cartItem->id) ->assertJsonPath('data.items.0.id', $purchaseItem->id)
->assertJsonPath('data.items.0.product', 'Entrada general') ->assertJsonPath('data.items.0.product', 'Entrada general')
->assertJsonPath('data.items.0.event_dates', []) ->assertJsonPath('data.items.0.event_dates', [])
->assertJsonPath('data.items.0.quantity', 2) ->assertJsonPath('data.items.0.quantity', 2)
@@ -187,7 +249,7 @@ class AdminAppSaleControllerTest extends TestCase
->assertJsonPath('data.items.0.total', '25000.00'); ->assertJsonPath('data.items.0.total', '25000.00');
} }
public function test_sales_list_uses_cart_quantity_until_purchase_items_exist(): void public function test_sales_list_quantity_always_comes_from_purchase_items(): void
{ {
$tenant = $this->createTenant('acme'); $tenant = $this->createTenant('acme');
Sanctum::actingAs($this->createAdminAppUser($tenant)); Sanctum::actingAs($this->createAdminAppUser($tenant));
@@ -214,13 +276,7 @@ class AdminAppSaleControllerTest extends TestCase
'status' => Purchase::STATUS_PENDING_PAYMENT, 'status' => Purchase::STATUS_PENDING_PAYMENT,
'total' => '37500.00', 'total' => '37500.00',
]); ]);
$purchaseItem = PurchaseItem::query()->create([
$this->getJson('/api/v1/adminapp/tenant/sales')
->assertOk()
->assertJsonPath('data.0.id', $purchase->id)
->assertJsonPath('data.0.quantity', 3);
PurchaseItem::query()->create([
'compra_id' => $purchase->id, 'compra_id' => $purchase->id,
'source_catalog_item_id' => $catalogItem->id, 'source_catalog_item_id' => $catalogItem->id,
'nombre' => 'Entrada general', 'nombre' => 'Entrada general',
@@ -232,7 +288,17 @@ class AdminAppSaleControllerTest extends TestCase
$this->getJson('/api/v1/adminapp/tenant/sales') $this->getJson('/api/v1/adminapp/tenant/sales')
->assertOk() ->assertOk()
->assertJsonPath('data.0.id', $purchase->id)
->assertJsonPath('data.0.quantity', 2); ->assertJsonPath('data.0.quantity', 2);
$purchaseItem->update([
'cantidad' => 4,
'total' => '50000.00',
]);
$this->getJson('/api/v1/adminapp/tenant/sales')
->assertOk()
->assertJsonPath('data.0.quantity', 4);
} }
public function test_an_adminapp_user_cannot_read_a_sale_from_another_tenant(): void public function test_an_adminapp_user_cannot_read_a_sale_from_another_tenant(): void
@@ -329,11 +395,25 @@ class AdminAppSaleControllerTest extends TestCase
$admin = $this->createAdminAppUser($tenant); $admin = $this->createAdminAppUser($tenant);
Sanctum::actingAs($admin); Sanctum::actingAs($admin);
$purchase = Purchase::query()->create([ $inventory = Inventory::query()->create(['real_stock' => 10]);
'tenant_codigo' => $tenant->codigo, $catalogItem = CatalogItem::query()->create([
'status' => Purchase::STATUS_PENDING_PAYMENT, 'tenant_code' => $tenant->codigo,
'total' => '10000.00', 'slug' => 'confirmable-item',
'nombre' => 'Confirmable item',
'precio' => '10000.00',
]); ]);
$variant = Variant::query()->create([
'catalog_item_id' => $catalogItem->id,
'inventory_id' => $inventory->id,
]);
$purchase = app(CheckoutService::class)->startCheckout($tenant, $admin->id, [
'direct_items' => [[
'catalog_item_id' => $catalogItem->id,
'variant_id' => $variant->id,
'cantidad' => 1,
]],
]);
$purchase->update(['status' => Purchase::STATUS_PENDING_PAYMENT]);
$this->postJson("/api/v1/adminapp/tenant/sales/{$purchase->id}/confirm") $this->postJson("/api/v1/adminapp/tenant/sales/{$purchase->id}/confirm")
->assertOk() ->assertOk()
@@ -385,6 +465,14 @@ class AdminAppSaleControllerTest extends TestCase
'status' => Purchase::STATUS_PENDING_PAYMENT, 'status' => Purchase::STATUS_PENDING_PAYMENT,
'total' => '10000.00', 'total' => '10000.00',
]); ]);
PurchaseItem::query()->create([
'compra_id' => $purchase->id,
'source_catalog_item_id' => $catalogItem->id,
'item_nombre' => $catalogItem->nombre,
'cantidad' => 2,
'precio_unitario' => '10000.00',
'total' => '20000.00',
]);
$this->postJson("/api/v1/adminapp/tenant/sales/{$purchase->id}/cancel") $this->postJson("/api/v1/adminapp/tenant/sales/{$purchase->id}/cancel")
->assertOk() ->assertOk()
@@ -401,6 +489,43 @@ class AdminAppSaleControllerTest extends TestCase
->assertJsonPath('data.items.0.quantity', 2); ->assertJsonPath('data.items.0.quantity', 2);
} }
public function test_adminapp_can_cancel_a_purchase_in_review(): void
{
$tenant = $this->createTenant('acme');
$admin = $this->createAdminAppUser($tenant);
Sanctum::actingAs($admin);
$inventory = Inventory::query()->create(['real_stock' => 10]);
$catalogItem = CatalogItem::query()->create([
'tenant_code' => $tenant->codigo,
'slug' => 'review-item',
'nombre' => 'Review item',
'precio' => '10000.00',
]);
$variant = Variant::query()->create([
'catalog_item_id' => $catalogItem->id,
'inventory_id' => $inventory->id,
]);
$purchase = app(CheckoutService::class)->startCheckout($tenant, $admin->id, [
'direct_items' => [[
'catalog_item_id' => $catalogItem->id,
'variant_id' => $variant->id,
'cantidad' => 2,
]],
]);
$purchase->update(['status' => Purchase::STATUS_IN_REVIEW]);
$sourceCartId = $purchase->cart_id;
$this->postJson("/api/v1/adminapp/tenant/sales/{$purchase->id}/cancel")
->assertOk()
->assertJsonPath('data.status', Purchase::STATUS_CANCELLED);
$this->assertSoftDeleted('carritos', ['id' => $sourceCartId]);
$this->assertDatabaseHas('stock_reservations', [
'purchase_id' => $purchase->id,
'status' => 'released',
]);
}
public function test_an_adminapp_user_cannot_change_a_sale_from_another_tenant(): void public function test_an_adminapp_user_cannot_change_a_sale_from_another_tenant(): void
{ {
$tenant = $this->createTenant('acme'); $tenant = $this->createTenant('acme');

View File

@@ -288,19 +288,19 @@ class DesfilePuraTendenciaSeederTest extends TestCase
$items = DB::table('compra_items')->where('compra_id', $purchase->id); $items = DB::table('compra_items')->where('compra_id', $purchase->id);
$this->assertSame(46, (clone $items)->count()); $this->assertSame(48, (clone $items)->count());
$this->assertSame(46, (clone $items) $this->assertSame(48, (clone $items)
->where('precio_unitario', 0) ->where('precio_unitario', 0)
->where('discount_total', 0) ->where('discount_total', 0)
->where('tax_total', 0) ->where('tax_total', 0)
->where('total', 0) ->where('total', 0)
->count()); ->count());
$this->assertSame(46, DB::table('tickets') $this->assertSame(48, DB::table('tickets')
->where('source_purchase_id', $purchase->id) ->where('source_purchase_id', $purchase->id)
->where('user_id', $user->id) ->where('user_id', $user->id)
->where('source_catalog_item_id', $catalogItemId) ->where('source_catalog_item_id', $catalogItemId)
->count()); ->count());
$this->assertSame(46, DB::table('stock_reservations') $this->assertSame(48, DB::table('stock_reservations')
->where('purchase_id', $purchase->id) ->where('purchase_id', $purchase->id)
->where('status', 'committed') ->where('status', 'committed')
->count()); ->count());
@@ -309,6 +309,7 @@ class DesfilePuraTendenciaSeederTest extends TestCase
['sector' => 'A', 'fila' => '1', 'tipo' => 'NORMAL', 'count' => 16], ['sector' => 'A', 'fila' => '1', 'tipo' => 'NORMAL', 'count' => 16],
['sector' => 'A', 'fila' => '3', 'tipo' => 'NORMAL', 'count' => 14], ['sector' => 'A', 'fila' => '3', 'tipo' => 'NORMAL', 'count' => 14],
['sector' => 'C', 'fila' => '1', 'tipo' => 'VIP + LUNCH', 'count' => 16], ['sector' => 'C', 'fila' => '1', 'tipo' => 'VIP + LUNCH', 'count' => 16],
['sector' => 'C', 'fila' => '3', 'tipo' => 'NORMAL', 'count' => 2, 'seats' => ['6', '7']],
] as $allocation) { ] as $allocation) {
$allocatedVariants = DB::table('variantes') $allocatedVariants = DB::table('variantes')
->where('catalog_item_id', $catalogItemId) ->where('catalog_item_id', $catalogItemId)
@@ -326,6 +327,20 @@ class DesfilePuraTendenciaSeederTest extends TestCase
} }
$this->assertSame($allocation['count'], $allocatedVariants->count()); $this->assertSame($allocation['count'], $allocatedVariants->count());
if (isset($allocation['seats'])) {
$seatValues = DB::table('variant_values')
->join('item_attributes', 'item_attributes.id', '=', 'variant_values.item_attribute_id')
->join('attribute', 'attribute.id', '=', 'item_attributes.attribute_id')
->whereIn('variant_values.variant_id', (clone $allocatedVariants)->pluck('id'))
->where('attribute.codigo', 'asiento')
->pluck('variant_values.value')
->sort()
->values()
->all();
$this->assertSame($allocation['seats'], $seatValues);
}
} }
} }

View File

@@ -70,6 +70,14 @@ class FiestaFutbolInfantilProductSeederTest extends TestCase
['abono', 'alojamiento', 'camiseta', 'comida'], ['abono', 'alojamiento', 'camiseta', 'comida'],
CatalogItem::query()->where('tenant_code', $tenant->codigo)->orderBy('slug')->pluck('slug')->all(), CatalogItem::query()->where('tenant_code', $tenant->codigo)->orderBy('slug')->pluck('slug')->all(),
); );
$this->assertSame(
['camiseta', 'alojamiento', 'abono', 'comida'],
CatalogItem::query()
->where('tenant_code', $tenant->codigo)
->orderBy('group_order')
->pluck('slug')
->all(),
);
$this->assertTrue( $this->assertTrue(
CatalogItem::query() CatalogItem::query()
->where('tenant_code', $tenant->codigo) ->where('tenant_code', $tenant->codigo)

View File

@@ -76,7 +76,7 @@ class BootstrapTenantControllerTest extends TestCase
'display_seach_bar' => false, 'display_seach_bar' => false,
'display_cart' => false, 'display_cart' => false,
'cart_editing_policy' => 'disabled', 'cart_editing_policy' => 'disabled',
'checkout_editing_policy' => 'quantity_and_remove', 'checkout_editing_policy' => 'disabled',
'display_cart_item_images' => false, 'display_cart_item_images' => false,
]); ]);
@@ -101,10 +101,10 @@ class BootstrapTenantControllerTest extends TestCase
->assertJsonPath('data.cart_editing_policy.allow_delete', false) ->assertJsonPath('data.cart_editing_policy.allow_delete', false)
->assertJsonPath('data.cart_editing_policy.allow_update_quantity', false) ->assertJsonPath('data.cart_editing_policy.allow_update_quantity', false)
->assertJsonPath('data.cart_editing_policy.allow_update_variant', false) ->assertJsonPath('data.cart_editing_policy.allow_update_variant', false)
->assertJsonPath('data.checkout_editing_policy.code', 'quantity_and_remove') ->assertJsonPath('data.checkout_editing_policy.code', 'disabled')
->assertJsonPath('data.checkout_editing_policy.allow_modify', true) ->assertJsonPath('data.checkout_editing_policy.allow_modify', false)
->assertJsonPath('data.checkout_editing_policy.allow_delete', true) ->assertJsonPath('data.checkout_editing_policy.allow_delete', false)
->assertJsonPath('data.checkout_editing_policy.allow_update_quantity', true) ->assertJsonPath('data.checkout_editing_policy.allow_update_quantity', false)
->assertJsonPath('data.checkout_editing_policy.allow_update_variant', false) ->assertJsonPath('data.checkout_editing_policy.allow_update_variant', false)
->assertJsonPath('data.display_cart_item_images', false) ->assertJsonPath('data.display_cart_item_images', false)
->assertJsonPath('data.header_bg_color', '#ffffff')->assertJsonPath('data.footer_bg_color', '#ffffff'); ->assertJsonPath('data.header_bg_color', '#ffffff')->assertJsonPath('data.footer_bg_color', '#ffffff');

View File

@@ -0,0 +1,43 @@
<?php
namespace Tests\Unit\Catalog;
use App\Domains\Catalog\Services\CatalogItemAllowanceService;
use ReflectionClass;
use Tests\TestCase;
class CatalogItemAllowanceServiceTest extends TestCase
{
private CatalogItemAllowanceService $service;
protected function setUp(): void
{
parent::setUp();
$this->service = (new ReflectionClass(CatalogItemAllowanceService::class))
->newInstanceWithoutConstructor();
}
public function test_it_returns_the_user_quota_message_with_priority_over_stock(): void
{
$this->assertSame(
'Alcanzaste el cupo máximo permitido para este producto.',
$this->service->unavailableMessage(0, 0),
);
}
public function test_it_returns_the_out_of_stock_message(): void
{
$this->assertSame(
'Este producto no tiene stock disponible.',
$this->service->unavailableMessage(0, null),
);
}
public function test_it_returns_no_message_when_the_item_is_available(): void
{
$this->assertNull($this->service->unavailableMessage(1, null));
$this->assertNull($this->service->unavailableMessage(null, 1));
$this->assertNull($this->service->unavailableMessage(null, null));
}
}

View File

@@ -83,11 +83,13 @@ class CatalogModelsTest extends TestCase
public function test_catalog_item_is_the_catalog_root(): void public function test_catalog_item_is_the_catalog_root(): void
{ {
$item = new CatalogItem; $item = new CatalogItem;
$this->assertSame(0, $item->group_order);
$item->setRawAttributes([ $item->setRawAttributes([
'category_id' => '10', 'category_id' => '10',
'brand_id' => '20', 'brand_id' => '20',
'inventory_id' => '30', 'inventory_id' => '30',
'type' => CatalogItemType::Standard->value, 'type' => CatalogItemType::Standard->value,
'group_order' => '4',
'precio' => '12.50', 'precio' => '12.50',
'inventory_policy' => InventoryPolicy::Tracked->value, 'inventory_policy' => InventoryPolicy::Tracked->value,
'inventory_subject' => InventorySubject::Seat->value, 'inventory_subject' => InventorySubject::Seat->value,
@@ -100,6 +102,7 @@ class CatalogModelsTest extends TestCase
$this->assertSame(20, $item->brand_id); $this->assertSame(20, $item->brand_id);
$this->assertSame(30, $item->inventory_id); $this->assertSame(30, $item->inventory_id);
$this->assertSame(CatalogItemType::Standard, $item->type); $this->assertSame(CatalogItemType::Standard, $item->type);
$this->assertSame(4, $item->group_order);
$this->assertSame('12.50', $item->precio); $this->assertSame('12.50', $item->precio);
$this->assertSame(InventoryPolicy::Tracked, $item->inventory_policy); $this->assertSame(InventoryPolicy::Tracked, $item->inventory_policy);
$this->assertSame(InventorySubject::Seat, $item->inventory_subject); $this->assertSame(InventorySubject::Seat, $item->inventory_subject);

View File

@@ -16,10 +16,12 @@ class SaleFormServiceTest extends TestCase
$this->assertSame([ $this->assertSame([
'Creada', 'Creada',
'Esperando pago', 'Esperando pago',
'En revisión',
'Confirmada', 'Confirmada',
'Cancelada', 'Cancelada',
'Rechazada', 'Rechazada',
'Vencida', 'Vencida',
'Reemplazada',
], array_column($form['statuses'], 'name')); ], array_column($form['statuses'], 'name'));
} }
} }

View File

@@ -0,0 +1,146 @@
<?php
namespace Tests\Unit\Sale;
use App\Domains\Auth\Models\User;
use App\Domains\Logging\Models\ValueChange;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Sale\Services\AdminAppSaleExcelService;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Support\Carbon;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Tests\TestCase;
class AdminAppSaleExcelServiceTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
Carbon::setTestNow(Carbon::parse('2026-08-24 17:53:00', 'UTC'));
}
protected function tearDown(): void
{
Carbon::setTestNow();
parent::tearDown();
}
public function test_it_downloads_filtered_sales_as_an_excel_file(): void
{
$response = app(AdminAppSaleExcelService::class)->downloadSales(
$this->tenant(),
collect([$this->sale()]),
'America/La_Paz',
);
$this->assertExcelResponse(
$response,
'ventas_acme_20260824_135300.xlsx',
function (string $path): void {
$sheet = IOFactory::load($path)->getActiveSheet();
$this->assertSame('Ventas', $sheet->getTitle());
$this->assertSame('Cliente Test', $sheet->getCell('C2')->getValue());
$this->assertSame('Confirmado', $sheet->getCell('E2')->getValue());
$this->assertSame(25000.0, $sheet->getCell('F2')->getValue());
},
);
}
public function test_it_downloads_the_modification_history_as_an_excel_file(): void
{
$sale = $this->sale();
$admin = (new User)->forceFill([
'id' => 10,
'nombre_apellido' => 'Admin Test',
'email' => 'admin@example.test',
]);
$modification = (new ValueChange)->forceFill([
'id' => 1,
'trackable_id' => $sale->id,
'attribute' => 'status',
'old_value' => Purchase::STATUS_PENDING_PAYMENT,
'new_value' => Purchase::STATUS_PAID,
'changed_at' => now(),
'actor_type' => 'user',
]);
$modification->setRelation('trackable', $sale);
$modification->setRelation('user', $admin);
$response = app(AdminAppSaleExcelService::class)->downloadModifications(
$this->tenant(),
collect([$modification]),
'America/La_Paz',
);
$this->assertExcelResponse(
$response,
'historial_modificaciones_acme_20260824_135300.xlsx',
function (string $path): void {
$sheet = IOFactory::load($path)->getActiveSheet();
$this->assertSame('Modificaciones', $sheet->getTitle());
$this->assertSame('#15', $sheet->getCell('C2')->getValue());
$this->assertSame('pending_payment', $sheet->getCell('F2')->getValue());
$this->assertSame('paid', $sheet->getCell('G2')->getValue());
$this->assertSame('Admin Test', $sheet->getCell('H2')->getValue());
},
);
}
/** @param callable(string): void $assertSpreadsheet */
private function assertExcelResponse(
StreamedResponse $response,
string $filename,
callable $assertSpreadsheet,
): void {
$this->assertSame(
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
$response->headers->get('content-type'),
);
$this->assertStringContainsString(
"attachment; filename={$filename}",
(string) $response->headers->get('content-disposition'),
);
ob_start();
($response->getCallback())();
$contents = ob_get_clean();
$this->assertIsString($contents);
$this->assertStringStartsWith('PK', $contents);
$path = tempnam(sys_get_temp_dir(), 'shopit_excel_');
$this->assertNotFalse($path);
try {
file_put_contents($path, $contents);
$assertSpreadsheet($path);
} finally {
@unlink($path);
}
}
private function tenant(): Tenant
{
return (new Tenant)->forceFill([
'codigo' => 'acme',
'nombre' => 'Acme Eventos',
]);
}
private function sale(): Purchase
{
return (new Purchase)->forceFill([
'id' => 15,
'created_at' => now(),
'nombre_apellido' => 'Cliente Test',
'quantity' => 2,
'status' => Purchase::STATUS_PAID,
'total' => '25000.00',
'tickets_count' => 2,
]);
}
}

View File

@@ -0,0 +1,55 @@
<?php
namespace Tests\Unit\Sale;
use App\Domains\Sale\Requests\AdminAppSaleModificationPdfRequest;
use App\Domains\Sale\Requests\AdminAppSalePdfRequest;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Validator;
use Tests\TestCase;
class AdminAppSalePdfRequestTest extends TestCase
{
public function test_pdf_requests_accept_php_timezone_identifiers_including_browser_aliases(): void
{
$requests = [
new AdminAppSalePdfRequest,
new AdminAppSaleModificationPdfRequest,
];
foreach ($requests as $request) {
$this->assertTrue(Validator::make([
'timezone' => 'America/Argentina/Buenos_Aires',
], $request->rules())->passes());
$this->assertTrue(Validator::make([
'timezone' => 'America/Buenos_Aires',
], $request->rules())->passes());
$this->assertFalse(Validator::make([
'timezone' => 'Invalid/Timezone',
], $request->rules())->passes());
$this->assertFalse(Validator::make([], $request->rules())->passes());
}
}
public function test_invalid_timezone_message_uses_the_application_locale(): void
{
$request = new AdminAppSalePdfRequest;
App::setLocale('es');
$spanishValidator = Validator::make(['timezone' => 'Invalid/Timezone'], $request->rules());
$this->assertSame(
'La zona horaria enviada por el navegador no es válida.',
$spanishValidator->errors()->first('timezone'),
);
App::setLocale('en');
$englishValidator = Validator::make(['timezone' => 'Invalid/Timezone'], $request->rules());
$this->assertSame(
'The timezone sent by the browser is invalid.',
$englishValidator->errors()->first('timezone'),
);
}
}

View File

@@ -8,6 +8,7 @@ use App\Domains\Purchase\Models\Purchase;
use App\Domains\Sale\Services\AdminAppSalePdfService; use App\Domains\Sale\Services\AdminAppSalePdfService;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use Barryvdh\DomPDF\ServiceProvider; use Barryvdh\DomPDF\ServiceProvider;
use Illuminate\Support\Carbon;
use Tests\TestCase; use Tests\TestCase;
class AdminAppSalePdfServiceTest extends TestCase class AdminAppSalePdfServiceTest extends TestCase
@@ -17,6 +18,14 @@ class AdminAppSalePdfServiceTest extends TestCase
parent::setUp(); parent::setUp();
$this->app->register(ServiceProvider::class); $this->app->register(ServiceProvider::class);
Carbon::setTestNow(Carbon::parse('2026-08-24 17:53:00', 'UTC'));
}
protected function tearDown(): void
{
Carbon::setTestNow();
parent::tearDown();
} }
public function test_it_downloads_the_sales_report_as_a_pdf(): void public function test_it_downloads_the_sales_report_as_a_pdf(): void
@@ -24,11 +33,12 @@ class AdminAppSalePdfServiceTest extends TestCase
$response = app(AdminAppSalePdfService::class)->downloadSales( $response = app(AdminAppSalePdfService::class)->downloadSales(
$this->tenant(), $this->tenant(),
collect([$this->sale()]), collect([$this->sale()]),
'America/La_Paz',
); );
$this->assertSame('application/pdf', $response->headers->get('content-type')); $this->assertSame('application/pdf', $response->headers->get('content-type'));
$this->assertStringContainsString( $this->assertStringContainsString(
'attachment; filename=ventas_acme_', 'attachment; filename=ventas_acme_20260824_135300.pdf',
(string) $response->headers->get('content-disposition'), (string) $response->headers->get('content-disposition'),
); );
$this->assertStringStartsWith('%PDF', $response->getContent()); $this->assertStringStartsWith('%PDF', $response->getContent());
@@ -57,16 +67,52 @@ class AdminAppSalePdfServiceTest extends TestCase
$response = app(AdminAppSalePdfService::class)->downloadModifications( $response = app(AdminAppSalePdfService::class)->downloadModifications(
$this->tenant(), $this->tenant(),
collect([$modification]), collect([$modification]),
'America/La_Paz',
); );
$this->assertSame('application/pdf', $response->headers->get('content-type')); $this->assertSame('application/pdf', $response->headers->get('content-type'));
$this->assertStringContainsString( $this->assertStringContainsString(
'attachment; filename=historial_modificaciones_acme_', 'attachment; filename=historial_modificaciones_acme_20260824_135300.pdf',
(string) $response->headers->get('content-disposition'), (string) $response->headers->get('content-disposition'),
); );
$this->assertStringStartsWith('%PDF', $response->getContent()); $this->assertStringStartsWith('%PDF', $response->getContent());
} }
public function test_it_renders_pdf_dates_in_the_requested_timezone(): void
{
$sale = $this->sale();
$modification = (new ValueChange)->forceFill([
'id' => 1,
'trackable_id' => $sale->id,
'attribute' => 'status',
'old_value' => Purchase::STATUS_PENDING_PAYMENT,
'new_value' => Purchase::STATUS_PAID,
'changed_at' => now(),
'actor_type' => 'system',
]);
$modification->setRelation('trackable', $sale);
$modification->setRelation('user', null);
$salesHtml = view('pdf.adminapp.sales', [
'tenant' => $this->tenant(),
'sales' => collect([$sale]),
'generatedAt' => now(),
'timeZone' => 'America/La_Paz',
'confirmedSalesTotal' => '25000.00',
])->render();
$modificationsHtml = view('pdf.adminapp.sale-modifications', [
'tenant' => $this->tenant(),
'modifications' => collect([$modification]),
'generatedAt' => now(),
'timeZone' => 'America/La_Paz',
])->render();
$this->assertStringContainsString('Generado el 24/08/2026 13:53', $salesHtml);
$this->assertStringContainsString('24/08/2026 13:53', $salesHtml);
$this->assertStringContainsString('Generado el 24/08/2026 13:53', $modificationsHtml);
$this->assertStringContainsString('13:53:00', $modificationsHtml);
}
private function tenant(): Tenant private function tenant(): Tenant
{ {
return (new Tenant)->forceFill([ return (new Tenant)->forceFill([

View File

@@ -2,9 +2,6 @@
namespace Tests\Unit\Sale; namespace Tests\Unit\Sale;
use App\Domains\Cart\Models\Cart;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Purchase\Models\Purchase; use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem; use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Sale\Resources\AdminApp\SaleDetailResource; use App\Domains\Sale\Resources\AdminApp\SaleDetailResource;
@@ -42,38 +39,16 @@ class SaleDetailResourceTest extends TestCase
$this->assertSame('30000.00', $data['total']); $this->assertSame('30000.00', $data['total']);
} }
public function test_it_uses_the_associated_cart_items_when_the_purchase_has_no_items(): void public function test_it_does_not_fall_back_to_cart_items_when_the_purchase_has_no_items(): void
{ {
$catalogItem = (new CatalogItem)->forceFill([
'id' => 21,
'nombre' => 'Entrada general',
'precio' => '12500.00',
]);
$cartItem = (new CartItem)->forceFill([
'id' => 34,
'catalog_item_id' => $catalogItem->id,
'cantidad' => 2,
]);
$cartItem->setRelation('catalogItem', $catalogItem);
$cartItem->setRelation('variant', null);
$cart = new Cart;
$cart->setRelation('items', collect([$cartItem]));
$purchase = (new Purchase)->forceFill([ $purchase = (new Purchase)->forceFill([
'id' => 16, 'id' => 16,
'total' => '25000.00', 'total' => '25000.00',
]); ]);
$purchase->setRelation('items', collect()); $purchase->setRelation('items', collect());
$purchase->setRelation('cart', $cart);
$data = (new SaleDetailResource($purchase))->resolve(Request::create('/')); $data = (new SaleDetailResource($purchase))->resolve(Request::create('/'));
$this->assertSame(34, $data['items'][0]['id']); $this->assertCount(0, $data['items']);
$this->assertSame('Entrada general', $data['items'][0]['product']);
$this->assertSame([], $data['items'][0]['event_dates']);
$this->assertSame(2, $data['items'][0]['quantity']);
$this->assertSame('12500.00', $data['items'][0]['unit_price']);
$this->assertSame('25000.00', $data['items'][0]['total']);
} }
} }

View File

@@ -0,0 +1,33 @@
<?php
namespace Tests\Unit\Sale;
use App\Domains\Logging\Models\ValueChange;
use App\Domains\Sale\Resources\AdminApp\SaleModificationResource;
use Carbon\CarbonImmutable;
use Illuminate\Http\Request;
use Tests\TestCase;
class SaleModificationResourceTest extends TestCase
{
public function test_it_serializes_the_change_instant_as_utc_iso_8601(): void
{
$modification = (new ValueChange)->forceFill([
'id' => 1,
'trackable_id' => 33,
'attribute' => 'status',
'old_value' => 'pending_payment',
'new_value' => 'cancelled',
'changed_at' => CarbonImmutable::parse('2026-08-24 17:53:00', 'UTC'),
'actor_type' => 'system',
]);
$modification->setRelation('trackable', null);
$modification->setRelation('user', null);
$data = (new SaleModificationResource($modification))->resolve(Request::create('/'));
$this->assertSame('2026-08-24T17:53:00+00:00', $data['changed_at']);
$this->assertSame('2026-08-24', $data['date']);
$this->assertSame('17:53:00', $data['time']);
}
}