Compare commits
18 Commits
feature/ch
...
341cc16ee8
| Author | SHA1 | Date | |
|---|---|---|---|
| 341cc16ee8 | |||
| ab042acf9b | |||
| 562b48b3bd | |||
| 12bcc25b33 | |||
| cababe1a43 | |||
| 0e9f7faaf1 | |||
| 13bdb436ed | |||
| c2efec8906 | |||
| 299a462283 | |||
| 38f36a3a23 | |||
| b4b888adef | |||
| 3afef63fc7 | |||
| e325c49a89 | |||
| 9c7d025258 | |||
| ba58bf79f8 | |||
| 2910d3f929 | |||
| ca4fea6bcd | |||
| 73bf285bad |
18
app/Domains/Auth/Controllers/UpdateProfileController.php
Normal file
18
app/Domains/Auth/Controllers/UpdateProfileController.php
Normal file
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Controllers;
|
||||
|
||||
use App\Domains\Auth\Requests\UpdateProfileRequest;
|
||||
use App\Domains\Auth\Resources\UserResource;
|
||||
use App\Domains\Auth\Services\ProfileService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class UpdateProfileController
|
||||
{
|
||||
public function __invoke(UpdateProfileRequest $request, ProfileService $service): JsonResponse
|
||||
{
|
||||
$user = $service->update($request->user(), $request->validated());
|
||||
|
||||
return response()->json(UserResource::make($user)->resolve());
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,7 @@ class RegisterUserRequest extends FormRequest
|
||||
return [
|
||||
'nombre_apellido' => ['required', 'string', 'max:255'],
|
||||
'email' => ['required', 'string', 'email', 'max:255', Rule::unique('users', 'email')],
|
||||
'password' => ['required', 'string', 'confirmed'],
|
||||
'password' => ['required', 'string', 'confirmed', \Illuminate\Validation\Rules\Password::min(8)->mixedCase()->symbols()],
|
||||
'dni' => ['nullable', 'string', 'max:255'],
|
||||
'telefono' => ['nullable', 'string', 'max:255'],
|
||||
];
|
||||
|
||||
29
app/Domains/Auth/Requests/UpdateProfileRequest.php
Normal file
29
app/Domains/Auth/Requests/UpdateProfileRequest.php
Normal file
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class UpdateProfileRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'nombre_apellido' => ['required', 'string', 'max:255'],
|
||||
'email' => [
|
||||
'required',
|
||||
'email',
|
||||
Rule::unique('users', 'email')->ignore($this->user()->id),
|
||||
],
|
||||
'dni' => ['nullable', 'string', 'regex:/^[0-9]{7,8}$/'],
|
||||
'telefono' => ['nullable', 'string', 'regex:/^\+?[0-9\s\-]+$/'],
|
||||
'password' => ['nullable', 'string', \Illuminate\Validation\Rules\Password::min(8)->mixedCase()->symbols()],
|
||||
];
|
||||
}
|
||||
}
|
||||
41
app/Domains/Auth/Services/ProfileService.php
Normal file
41
app/Domains/Auth/Services/ProfileService.php
Normal file
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Services;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
|
||||
class ProfileService
|
||||
{
|
||||
/**
|
||||
* Update the given user's profile information.
|
||||
*
|
||||
* @param User $user
|
||||
* @param array $data
|
||||
* @return User
|
||||
*/
|
||||
public function update(User $user, array $data): User
|
||||
{
|
||||
// Handle password hashing if a new password is provided
|
||||
if (!empty($data['password'])) {
|
||||
$data['password'] = Hash::make($data['password']);
|
||||
} else {
|
||||
// Remove password from array if empty so we don't overwrite it with null
|
||||
unset($data['password']);
|
||||
}
|
||||
|
||||
// Standardize phone number (strip all but numbers and leading '+')
|
||||
if (!empty($data['telefono'])) {
|
||||
$data['telefono'] = preg_replace('/[^\+0-9]/', '', $data['telefono']);
|
||||
}
|
||||
|
||||
// DNI is already validated as numbers only, but we can do a quick strip just in case
|
||||
if (!empty($data['dni'])) {
|
||||
$data['dni'] = preg_replace('/[^0-9]/', '', $data['dni']);
|
||||
}
|
||||
|
||||
$user->update($data);
|
||||
|
||||
return $user;
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,11 @@ use App\Domains\Auth\Controllers\LoginController;
|
||||
use App\Domains\Auth\Controllers\LogoutController;
|
||||
use App\Domains\Auth\Controllers\MeController;
|
||||
use App\Domains\Auth\Controllers\RegisterController;
|
||||
use App\Domains\Auth\Controllers\UpdateProfileController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::post('/register', RegisterController::class);
|
||||
Route::post('/login', LoginController::class);
|
||||
Route::middleware('auth:sanctum')->post('/logout', LogoutController::class);
|
||||
Route::middleware('auth:sanctum')->get('/me', MeController::class);
|
||||
Route::middleware('auth:sanctum')->put('/me', UpdateProfileController::class);
|
||||
|
||||
145
app/Domains/Bundle/Models/Bundle.php
Normal file
145
app/Domains/Bundle/Models/Bundle.php
Normal file
@@ -0,0 +1,145 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Bundle\Models;
|
||||
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\Casts\Attribute;
|
||||
|
||||
use App\Domains\Shared\Contracts\Buyable;
|
||||
|
||||
#[Fillable([
|
||||
'tenant_codigo',
|
||||
'nombre',
|
||||
'descripcion',
|
||||
'precio',
|
||||
])]
|
||||
class Bundle extends Model implements Buyable
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $table = 'bundles';
|
||||
|
||||
protected $appends = ['stock_tecnico'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'precio' => 'decimal:2',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Tenant, $this>
|
||||
*/
|
||||
public function tenant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Tenant::class, 'tenant_codigo', 'codigo');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<BundleItem, $this>
|
||||
*/
|
||||
public function items(): HasMany
|
||||
{
|
||||
return $this->hasMany(BundleItem::class, 'bundle_id');
|
||||
}
|
||||
|
||||
public function getPrice(): float
|
||||
{
|
||||
return (float) $this->precio;
|
||||
}
|
||||
|
||||
public function getName(): string
|
||||
{
|
||||
return $this->nombre ?? 'Bundle';
|
||||
}
|
||||
|
||||
public function incrementRealStock(int $amount): void
|
||||
{
|
||||
if ($amount < 0) {
|
||||
throw new \InvalidArgumentException('El monto a incrementar debe ser positivo.');
|
||||
}
|
||||
|
||||
foreach ($this->items as $item) {
|
||||
$item->variant->incrementRealStock($amount * $item->cantidad);
|
||||
}
|
||||
}
|
||||
|
||||
public function decrementRealStock(int $amount): void
|
||||
{
|
||||
if ($amount < 0) {
|
||||
throw new \InvalidArgumentException('El monto a decrementar debe ser positivo.');
|
||||
}
|
||||
|
||||
foreach ($this->items as $item) {
|
||||
$item->variant->decrementRealStock($amount * $item->cantidad);
|
||||
}
|
||||
}
|
||||
|
||||
public function incrementReservedStock(int $amount): void
|
||||
{
|
||||
if ($amount < 0) {
|
||||
throw new \InvalidArgumentException('El monto a incrementar debe ser positivo.');
|
||||
}
|
||||
|
||||
foreach ($this->items as $item) {
|
||||
$item->variant->incrementReservedStock($amount * $item->cantidad);
|
||||
}
|
||||
}
|
||||
|
||||
public function decrementReservedStock(int $amount): void
|
||||
{
|
||||
if ($amount < 0) {
|
||||
throw new \InvalidArgumentException('El monto a decrementar debe ser positivo.');
|
||||
}
|
||||
|
||||
foreach ($this->items as $item) {
|
||||
$item->variant->decrementReservedStock($amount * $item->cantidad);
|
||||
}
|
||||
}
|
||||
|
||||
public function confirmReservedStock(int $amount): void
|
||||
{
|
||||
if ($amount < 0) {
|
||||
throw new \InvalidArgumentException('El monto a confirmar debe ser positivo.');
|
||||
}
|
||||
|
||||
foreach ($this->items as $item) {
|
||||
$item->variant->confirmReservedStock($amount * $item->cantidad);
|
||||
}
|
||||
}
|
||||
|
||||
public function validateStock(): void
|
||||
{
|
||||
if ($this->stock_tecnico <= 0) {
|
||||
throw new \InvalidArgumentException('El bundle no tiene stock técnico disponible.');
|
||||
}
|
||||
}
|
||||
|
||||
protected function stockTecnico(): Attribute
|
||||
{
|
||||
return Attribute::get(function () {
|
||||
if ($this->items->isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$minStock = PHP_INT_MAX;
|
||||
foreach ($this->items as $item) {
|
||||
// Ensure variant is loaded
|
||||
if ($item->variant) {
|
||||
$itemStock = floor($item->variant->stock_tecnico / $item->cantidad);
|
||||
if ($itemStock < $minStock) {
|
||||
$minStock = $itemStock;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $minStock === PHP_INT_MAX ? 0 : (int) $minStock;
|
||||
});
|
||||
}
|
||||
}
|
||||
46
app/Domains/Bundle/Models/BundleItem.php
Normal file
46
app/Domains/Bundle/Models/BundleItem.php
Normal file
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Bundle\Models;
|
||||
|
||||
use App\Domains\Catalog\Models\ProductVariant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable([
|
||||
'bundle_id',
|
||||
'producto_variante_id',
|
||||
'cantidad',
|
||||
])]
|
||||
class BundleItem extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $table = 'bundle_items';
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'bundle_id' => 'integer',
|
||||
'producto_variante_id' => 'integer',
|
||||
'cantidad' => 'integer',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Bundle, $this>
|
||||
*/
|
||||
public function bundle(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Bundle::class, 'bundle_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<ProductVariant, $this>
|
||||
*/
|
||||
public function variant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ProductVariant::class, 'producto_variante_id');
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,8 @@ class CartController extends Controller
|
||||
$result = $this->cartService->addItem(
|
||||
$tenant,
|
||||
$request,
|
||||
(int) $request->validated('product_variant_id'),
|
||||
$request->mappedBuyableType(),
|
||||
(int) $request->validated('buyable_id'),
|
||||
(int) $request->validated('cantidad'),
|
||||
);
|
||||
|
||||
@@ -47,22 +48,22 @@ class CartController extends Controller
|
||||
public function updateItemQuantity(
|
||||
UpdateCartItemQuantityRequest $request,
|
||||
Tenant $tenant,
|
||||
ProductVariant $productVariant,
|
||||
\App\Domains\Cart\Models\CartItem $cartItem,
|
||||
): CartResource {
|
||||
return CartResource::make(
|
||||
$this->cartService->updateItemQuantity(
|
||||
$tenant,
|
||||
$request,
|
||||
$productVariant->getKey(),
|
||||
$cartItem->getKey(),
|
||||
(int) $request->validated('cantidad'),
|
||||
)
|
||||
)->additional(['message' => 'Cantidad de producto actualizada.']);
|
||||
}
|
||||
|
||||
public function removeItem(Request $request, Tenant $tenant, ProductVariant $productVariant): CartResource
|
||||
public function removeItem(Request $request, Tenant $tenant, \App\Domains\Cart\Models\CartItem $cartItem): CartResource
|
||||
{
|
||||
return CartResource::make(
|
||||
$this->cartService->removeItem($tenant, $request, $productVariant->getKey())
|
||||
$this->cartService->removeItem($tenant, $request, $cartItem->getKey())
|
||||
)->additional(['message' => 'Producto eliminado del carrito.']);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,15 +63,15 @@ class Cart extends Model
|
||||
{
|
||||
$items = $this->relationLoaded('items')
|
||||
? $this->getRelation('items')
|
||||
: $this->items()->with('variant.product')->get();
|
||||
: $this->items()->with('buyable')->get();
|
||||
|
||||
return (float) $items->reduce(
|
||||
fn (float $carry, $item): float => $carry + ((float) ($item->variant?->product?->precio ?? 0) * $item->cantidad),
|
||||
fn (float $carry, $item): float => $carry + ($item->buyable?->getPrice() * $item->cantidad),
|
||||
0.0,
|
||||
);
|
||||
}
|
||||
|
||||
public function addItem(int $productVariantId, int $quantity): CartItem
|
||||
public function addItem(string $buyableType, int $buyableId, int $quantity): CartItem
|
||||
{
|
||||
if ($quantity <= 0) {
|
||||
throw ValidationException::withMessages([
|
||||
@@ -79,24 +79,26 @@ class Cart extends Model
|
||||
]);
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($productVariantId, $quantity): CartItem {
|
||||
$variant = $this->resolveScopedVariant($productVariantId, true);
|
||||
return DB::transaction(function () use ($buyableType, $buyableId, $quantity): CartItem {
|
||||
$buyable = $this->resolveScopedBuyable($buyableType, $buyableId, true);
|
||||
|
||||
if ($variant->stock_tecnico < $quantity) {
|
||||
if ($buyable->stock_tecnico < $quantity) {
|
||||
throw ValidationException::withMessages([
|
||||
'cantidad' => "Stock insuficiente para la variante solicitada. Maximo disponible: {$variant->stock_tecnico}.",
|
||||
'cantidad' => "Stock insuficiente para la variante/bundle solicitado. Maximo disponible: {$buyable->stock_tecnico}.",
|
||||
]);
|
||||
}
|
||||
|
||||
/** @var CartItem|null $item */
|
||||
$item = $this->items()
|
||||
->where('producto_variante_id', $variant->getKey())
|
||||
->where('buyable_type', $buyableType)
|
||||
->where('buyable_id', $buyable->getKey())
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($item === null) {
|
||||
$item = $this->items()->create([
|
||||
'producto_variante_id' => $variant->getKey(),
|
||||
'buyable_type' => $buyableType,
|
||||
'buyable_id' => $buyable->getKey(),
|
||||
'cantidad' => $quantity,
|
||||
]);
|
||||
} else {
|
||||
@@ -104,13 +106,13 @@ class Cart extends Model
|
||||
$item->save();
|
||||
}
|
||||
|
||||
$variant->incrementReservedStock($quantity);
|
||||
$buyable->incrementReservedStock($quantity);
|
||||
|
||||
return $item->fresh();
|
||||
});
|
||||
}
|
||||
|
||||
public function updateItem(int $productVariantId, int $quantity): CartItem
|
||||
public function updateItem(int $cartItemId, int $quantity): CartItem
|
||||
{
|
||||
if ($quantity <= 0) {
|
||||
throw ValidationException::withMessages([
|
||||
@@ -118,18 +120,18 @@ class Cart extends Model
|
||||
]);
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($productVariantId, $quantity): CartItem {
|
||||
return DB::transaction(function () use ($cartItemId, $quantity): CartItem {
|
||||
/** @var CartItem $item */
|
||||
$item = $this->items()
|
||||
->where('producto_variante_id', $productVariantId)
|
||||
->where('id', $cartItemId)
|
||||
->lockForUpdate()
|
||||
->firstOrFail();
|
||||
|
||||
$variant = $this->resolveScopedVariant($productVariantId, true);
|
||||
$buyable = $this->resolveScopedBuyable($item->buyable_type, $item->buyable_id, true);
|
||||
$delta = $quantity - $item->cantidad;
|
||||
|
||||
if ($delta > 0 && $variant->stock_tecnico < $delta) {
|
||||
$maxAvailable = $variant->stock_tecnico + $item->cantidad;
|
||||
if ($delta > 0 && $buyable->stock_tecnico < $delta) {
|
||||
$maxAvailable = $buyable->stock_tecnico + $item->cantidad;
|
||||
throw ValidationException::withMessages([
|
||||
'cantidad' => "El máximo que se puede agregar es {$maxAvailable}.",
|
||||
]);
|
||||
@@ -139,49 +141,56 @@ class Cart extends Model
|
||||
$item->save();
|
||||
|
||||
if ($delta > 0) {
|
||||
$variant->incrementReservedStock($delta);
|
||||
$buyable->incrementReservedStock($delta);
|
||||
}
|
||||
|
||||
if ($delta < 0) {
|
||||
$variant->decrementReservedStock(abs($delta));
|
||||
$buyable->decrementReservedStock(abs($delta));
|
||||
}
|
||||
|
||||
return $item->fresh();
|
||||
});
|
||||
}
|
||||
|
||||
public function removeItem(int $productVariantId): void
|
||||
public function removeItem(int $cartItemId): void
|
||||
{
|
||||
DB::transaction(function () use ($productVariantId): void {
|
||||
DB::transaction(function () use ($cartItemId): void {
|
||||
/** @var CartItem $item */
|
||||
$item = $this->items()
|
||||
->where('producto_variante_id', $productVariantId)
|
||||
->where('id', $cartItemId)
|
||||
->lockForUpdate()
|
||||
->firstOrFail();
|
||||
|
||||
$variant = $this->resolveScopedVariant($productVariantId, true);
|
||||
$variant->decrementReservedStock($item->cantidad);
|
||||
$buyable = $this->resolveScopedBuyable($item->buyable_type, $item->buyable_id, true);
|
||||
$buyable->decrementReservedStock($item->cantidad);
|
||||
$item->delete();
|
||||
});
|
||||
}
|
||||
|
||||
protected function resolveScopedVariant(int $productVariantId, bool $lockForUpdate = false): ProductVariant
|
||||
protected function resolveScopedBuyable(string $buyableType, int $buyableId, bool $lockForUpdate = false)
|
||||
{
|
||||
$query = ProductVariant::query()
|
||||
->whereKey($productVariantId)
|
||||
->whereHas('product', fn ($query) => $query->where('tenant_codigo', $this->tenant_codigo));
|
||||
if ($buyableType === \App\Domains\Catalog\Models\ProductVariant::class) {
|
||||
$query = \App\Domains\Catalog\Models\ProductVariant::query()
|
||||
->whereKey($buyableId)
|
||||
->whereHas('product', fn ($query) => $query->where('tenant_codigo', $this->tenant_codigo));
|
||||
} elseif ($buyableType === \App\Domains\Bundle\Models\Bundle::class) {
|
||||
$query = \App\Domains\Bundle\Models\Bundle::query()
|
||||
->whereKey($buyableId)
|
||||
->where('tenant_codigo', $this->tenant_codigo);
|
||||
} else {
|
||||
throw new \InvalidArgumentException('Invalid buyable type');
|
||||
}
|
||||
|
||||
if ($lockForUpdate) {
|
||||
$query->lockForUpdate();
|
||||
}
|
||||
|
||||
/** @var ProductVariant|null $variant */
|
||||
$variant = $query->first();
|
||||
$buyable = $query->first();
|
||||
|
||||
if ($variant === null) {
|
||||
throw new NotFoundHttpException('Product variant not found for tenant.');
|
||||
if ($buyable === null) {
|
||||
throw new NotFoundHttpException('Buyable not found for tenant.');
|
||||
}
|
||||
|
||||
return $variant;
|
||||
return $buyable;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,8 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable([
|
||||
'cart_id',
|
||||
'producto_variante_id',
|
||||
'buyable_id',
|
||||
'buyable_type',
|
||||
'cantidad',
|
||||
])]
|
||||
class CartItem extends Model
|
||||
@@ -23,7 +24,8 @@ class CartItem extends Model
|
||||
{
|
||||
return [
|
||||
'cart_id' => 'integer',
|
||||
'producto_variante_id' => 'integer',
|
||||
'buyable_id' => 'integer',
|
||||
'buyable_type' => 'string',
|
||||
'cantidad' => 'integer',
|
||||
];
|
||||
}
|
||||
@@ -37,10 +39,10 @@ class CartItem extends Model
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<ProductVariant, $this>
|
||||
* @return \Illuminate\Database\Eloquent\Relations\MorphTo
|
||||
*/
|
||||
public function variant(): BelongsTo
|
||||
public function buyable()
|
||||
{
|
||||
return $this->belongsTo(ProductVariant::class, 'producto_variante_id');
|
||||
return $this->morphTo();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,8 +17,18 @@ class AddCartItemRequest extends FormRequest
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'product_variant_id' => ['required', 'integer'],
|
||||
'buyable_type' => ['required', 'string', \Illuminate\Validation\Rule::in(['variant', 'bundle'])],
|
||||
'buyable_id' => ['required', 'integer'],
|
||||
'cantidad' => ['required', 'integer', 'min:1'],
|
||||
];
|
||||
}
|
||||
|
||||
public function mappedBuyableType(): string
|
||||
{
|
||||
return match ($this->input('buyable_type')) {
|
||||
'variant' => \App\Domains\Catalog\Models\ProductVariant::class,
|
||||
'bundle' => \App\Domains\Bundle\Models\Bundle::class,
|
||||
default => throw new \InvalidArgumentException('Invalid buyable type'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,29 +15,15 @@ class CartItemResource extends JsonResource
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$variant = $this->variant;
|
||||
$product = $variant?->product;
|
||||
|
||||
$attributesText = '';
|
||||
if ($variant && $variant->relationLoaded('definitions')) {
|
||||
$attributesText = $variant->definitions
|
||||
->map(function ($definition) {
|
||||
$attrName = $definition->productAttribute?->attribute?->nombre;
|
||||
$value = $definition->value;
|
||||
return $attrName ? "{$attrName}: {$value}" : $value;
|
||||
})
|
||||
->filter()
|
||||
->implode(', ');
|
||||
}
|
||||
|
||||
$productName = $product?->nombre;
|
||||
if ($productName && $attributesText !== '') {
|
||||
$productName .= " ({$attributesText})";
|
||||
}
|
||||
|
||||
/** @var \App\Domains\Shared\Contracts\Buyable|null $buyable */
|
||||
$buyable = $this->buyable;
|
||||
|
||||
$productName = $buyable?->getName();
|
||||
$precio = $buyable?->getPrice();
|
||||
|
||||
$imageUrl = null;
|
||||
if ($variant && $variant->relationLoaded('attachments')) {
|
||||
$firstAttachment = $variant->attachments->first();
|
||||
if ($this->buyable_type === \App\Domains\Catalog\Models\ProductVariant::class && $buyable && $buyable->relationLoaded('attachments')) {
|
||||
$firstAttachment = $buyable->attachments->first();
|
||||
if ($firstAttachment) {
|
||||
$imageUrl = $firstAttachment->getTemporaryUrl(1440);
|
||||
}
|
||||
@@ -46,16 +32,25 @@ class CartItemResource extends JsonResource
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'cantidad' => $this->cantidad,
|
||||
'precio_unitario' => $this->formatMoney($product?->precio),
|
||||
'product_id' => $product?->id,
|
||||
'product_variant_id' => $this->producto_variante_id,
|
||||
'product' => $product === null ? null : [
|
||||
'precio_unitario' => $this->formatMoney($precio),
|
||||
'buyable_type' => $this->mapBuyableTypeToAlias($this->buyable_type),
|
||||
'buyable_id' => $this->buyable_id,
|
||||
'product' => $buyable === null ? null : [
|
||||
'nombre' => $productName,
|
||||
'imagen' => $imageUrl,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
protected function mapBuyableTypeToAlias(?string $type): string
|
||||
{
|
||||
return match ($type) {
|
||||
\App\Domains\Catalog\Models\ProductVariant::class => 'variant',
|
||||
\App\Domains\Bundle\Models\Bundle::class => 'bundle',
|
||||
default => 'unknown',
|
||||
};
|
||||
}
|
||||
|
||||
protected function formatMoney(float|int|string|null $amount): string
|
||||
{
|
||||
return number_format((float) ($amount ?? 0), 2, '.', '');
|
||||
|
||||
@@ -32,12 +32,12 @@ class CartService
|
||||
/**
|
||||
* @return array{cart: Cart, guest_token: ?string}
|
||||
*/
|
||||
public function addItem(Tenant $tenant, Request $request, int $productVariantId, int $quantity): array
|
||||
public function addItem(Tenant $tenant, Request $request, string $buyableType, int $buyableId, int $quantity): array
|
||||
{
|
||||
$resolvedIdentity = $this->resolveIdentity($request, true);
|
||||
$identity = $resolvedIdentity['identity'];
|
||||
$cart = $this->findOrCreateCart($tenant, $identity);
|
||||
$cart->addItem($productVariantId, $quantity);
|
||||
$cart->addItem($buyableType, $buyableId, $quantity);
|
||||
|
||||
return [
|
||||
'cart' => $this->loadCart($cart),
|
||||
@@ -45,20 +45,20 @@ class CartService
|
||||
];
|
||||
}
|
||||
|
||||
public function updateItemQuantity(Tenant $tenant, Request $request, int $productVariantId, int $quantity): Cart
|
||||
public function updateItemQuantity(Tenant $tenant, Request $request, int $cartItemId, int $quantity): Cart
|
||||
{
|
||||
$identity = $this->requireIdentity($request);
|
||||
$cart = $this->findCartOrFail($tenant, $identity);
|
||||
$cart->updateItem($productVariantId, $quantity);
|
||||
$cart->updateItem($cartItemId, $quantity);
|
||||
|
||||
return $this->loadCart($cart);
|
||||
}
|
||||
|
||||
public function removeItem(Tenant $tenant, Request $request, int $productVariantId): Cart
|
||||
public function removeItem(Tenant $tenant, Request $request, int $cartItemId): Cart
|
||||
{
|
||||
$identity = $this->requireIdentity($request);
|
||||
$cart = $this->findCartOrFail($tenant, $identity);
|
||||
$cart->removeItem($productVariantId);
|
||||
$cart->removeItem($cartItemId);
|
||||
|
||||
return $this->loadCart($cart);
|
||||
}
|
||||
|
||||
@@ -8,6 +8,6 @@ Route::prefix('tenants/{tenant:codigo}')
|
||||
->group(function (): void {
|
||||
Route::get('cart', [CartController::class, 'show']);
|
||||
Route::post('cart/items', [CartController::class, 'addItem']);
|
||||
Route::patch('cart/items/{productVariant}', [CartController::class, 'updateItemQuantity']);
|
||||
Route::delete('cart/items/{productVariant}', [CartController::class, 'removeItem']);
|
||||
Route::patch('cart/items/{cartItem}', [CartController::class, 'updateItemQuantity']);
|
||||
Route::delete('cart/items/{cartItem}', [CartController::class, 'removeItem']);
|
||||
});
|
||||
|
||||
23
app/Domains/Catalog/Controllers/CatalogController.php
Normal file
23
app/Domains/Catalog/Controllers/CatalogController.php
Normal file
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Controllers;
|
||||
|
||||
use App\Domains\Catalog\Resources\CatalogFeaturedGroupResource;
|
||||
use App\Domains\Catalog\Models\FeaturedGroup;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Routing\Controller;
|
||||
|
||||
class CatalogController extends Controller
|
||||
{
|
||||
public function index(string $tenant): JsonResponse
|
||||
{
|
||||
$featuredGroups = FeaturedGroup::where('tenant_codigo', $tenant)
|
||||
->with(['featuredVariants' => function ($query) {
|
||||
$query->orderBy('order');
|
||||
}, 'featuredVariants.variant.product', 'featuredVariants.variant.attachments', 'featuredVariants.variant.product.attachments'])
|
||||
->orderBy('group_order')
|
||||
->get();
|
||||
|
||||
return response()->json(CatalogFeaturedGroupResource::collection($featuredGroups)->resolve());
|
||||
}
|
||||
}
|
||||
51
app/Domains/Catalog/Controllers/FeaturedGroupController.php
Normal file
51
app/Domains/Catalog/Controllers/FeaturedGroupController.php
Normal file
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Controllers;
|
||||
|
||||
use App\Domains\Catalog\Models\FeaturedGroup;
|
||||
use App\Domains\Catalog\Requests\StoreFeaturedGroupRequest;
|
||||
use App\Domains\Catalog\Requests\UpdateFeaturedGroupRequest;
|
||||
use App\Domains\Catalog\Resources\FeaturedGroupResource;
|
||||
use App\Domains\Catalog\Services\FeaturedGroupService;
|
||||
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
|
||||
use Illuminate\Routing\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class FeaturedGroupController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly FeaturedGroupService $featuredGroupService
|
||||
) {}
|
||||
|
||||
public function index(string $tenant): AnonymousResourceCollection
|
||||
{
|
||||
$groups = FeaturedGroup::where('tenant_codigo', $tenant)->get();
|
||||
return FeaturedGroupResource::collection($groups);
|
||||
}
|
||||
|
||||
public function store(StoreFeaturedGroupRequest $request, string $tenant): FeaturedGroupResource
|
||||
{
|
||||
$group = $this->featuredGroupService->createGroup($tenant, $request->validated());
|
||||
return new FeaturedGroupResource($group);
|
||||
}
|
||||
|
||||
public function show(string $tenant, FeaturedGroup $featuredGroup): FeaturedGroupResource
|
||||
{
|
||||
abort_if($featuredGroup->tenant_codigo !== $tenant, 404);
|
||||
return new FeaturedGroupResource($featuredGroup->load('featuredVariants'));
|
||||
}
|
||||
|
||||
public function update(UpdateFeaturedGroupRequest $request, string $tenant, FeaturedGroup $featuredGroup): FeaturedGroupResource
|
||||
{
|
||||
abort_if($featuredGroup->tenant_codigo !== $tenant, 404);
|
||||
$group = $this->featuredGroupService->updateGroup($featuredGroup, $request->validated());
|
||||
return new FeaturedGroupResource($group);
|
||||
}
|
||||
|
||||
public function destroy(string $tenant, FeaturedGroup $featuredGroup): JsonResponse
|
||||
{
|
||||
abort_if($featuredGroup->tenant_codigo !== $tenant, 404);
|
||||
$this->featuredGroupService->deleteGroup($featuredGroup);
|
||||
return response()->json(null, 204);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Controllers;
|
||||
|
||||
use App\Domains\Catalog\Models\FeaturedGroup;
|
||||
use App\Domains\Catalog\Models\FeaturedVariant;
|
||||
use App\Domains\Catalog\Requests\StoreFeaturedVariantRequest;
|
||||
use App\Domains\Catalog\Requests\UpdateFeaturedVariantRequest;
|
||||
use App\Domains\Catalog\Resources\FeaturedVariantResource;
|
||||
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
|
||||
use Illuminate\Routing\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class FeaturedVariantController extends Controller
|
||||
{
|
||||
public function index(string $tenant, FeaturedGroup $featuredGroup): AnonymousResourceCollection
|
||||
{
|
||||
abort_if($featuredGroup->tenant_codigo !== $tenant, 404);
|
||||
return FeaturedVariantResource::collection($featuredGroup->featuredVariants);
|
||||
}
|
||||
|
||||
public function store(StoreFeaturedVariantRequest $request, string $tenant, FeaturedGroup $featuredGroup): FeaturedVariantResource
|
||||
{
|
||||
abort_if($featuredGroup->tenant_codigo !== $tenant, 404);
|
||||
$variant = $featuredGroup->featuredVariants()->create($request->validated());
|
||||
return new FeaturedVariantResource($variant);
|
||||
}
|
||||
|
||||
public function update(UpdateFeaturedVariantRequest $request, string $tenant, FeaturedGroup $featuredGroup, FeaturedVariant $featuredVariant): FeaturedVariantResource
|
||||
{
|
||||
abort_if($featuredGroup->tenant_codigo !== $tenant || $featuredVariant->featured_group_id !== $featuredGroup->id, 404);
|
||||
$featuredVariant->update($request->validated());
|
||||
return new FeaturedVariantResource($featuredVariant);
|
||||
}
|
||||
|
||||
public function destroy(string $tenant, FeaturedGroup $featuredGroup, FeaturedVariant $featuredVariant): JsonResponse
|
||||
{
|
||||
abort_if($featuredGroup->tenant_codigo !== $tenant || $featuredVariant->featured_group_id !== $featuredGroup->id, 404);
|
||||
$featuredVariant->delete();
|
||||
return response()->json(null, 204);
|
||||
}
|
||||
}
|
||||
21
app/Domains/Catalog/Models/FeaturedGroup.php
Normal file
21
app/Domains/Catalog/Models/FeaturedGroup.php
Normal file
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
class FeaturedGroup extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'tenant_codigo',
|
||||
'group_name',
|
||||
'product_layout',
|
||||
'group_order',
|
||||
];
|
||||
|
||||
public function featuredVariants(): HasMany
|
||||
{
|
||||
return $this->hasMany(FeaturedVariant::class);
|
||||
}
|
||||
}
|
||||
28
app/Domains/Catalog/Models/FeaturedVariant.php
Normal file
28
app/Domains/Catalog/Models/FeaturedVariant.php
Normal file
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Models;
|
||||
|
||||
use App\Domains\Catalog\Models\ProductVariant;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class FeaturedVariant extends Model
|
||||
{
|
||||
protected $table = 'featured_variants';
|
||||
|
||||
protected $fillable = [
|
||||
'featured_group_id',
|
||||
'product_variant_id',
|
||||
'order',
|
||||
];
|
||||
|
||||
public function featuredGroup(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(FeaturedGroup::class);
|
||||
}
|
||||
|
||||
public function variant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ProductVariant::class, 'product_variant_id');
|
||||
}
|
||||
}
|
||||
@@ -12,14 +12,19 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
use Illuminate\Database\Eloquent\Casts\Attribute;
|
||||
|
||||
use App\Domains\Shared\Contracts\Buyable;
|
||||
|
||||
#[Fillable([
|
||||
'producto_id',
|
||||
'stock_real',
|
||||
'stock_reservado',
|
||||
'stock',
|
||||
'is_placeholder',
|
||||
'has_tickets',
|
||||
'minimum_use_date',
|
||||
'maximum_use_date',
|
||||
])]
|
||||
class ProductVariant extends Model
|
||||
class ProductVariant extends Model implements Buyable
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
@@ -49,6 +54,28 @@ class ProductVariant extends Model
|
||||
}
|
||||
}
|
||||
|
||||
public function getPrice(): float
|
||||
{
|
||||
return (float) ($this->product->precio ?? 0.0);
|
||||
}
|
||||
|
||||
public function getName(): string
|
||||
{
|
||||
$name = $this->product->nombre ?? 'Producto';
|
||||
|
||||
if ($this->relationLoaded('definitions') && $this->definitions->isNotEmpty()) {
|
||||
$definitions = $this->definitions->map(function ($def) {
|
||||
return $def->value ?? $def->productAttribute?->attribute?->nombre;
|
||||
})->filter()->implode(', ');
|
||||
|
||||
if ($definitions !== '') {
|
||||
$name .= " ({$definitions})";
|
||||
}
|
||||
}
|
||||
|
||||
return $name;
|
||||
}
|
||||
|
||||
public function incrementRealStock(int $amount): void
|
||||
{
|
||||
if ($amount < 0) {
|
||||
@@ -126,6 +153,9 @@ class ProductVariant extends Model
|
||||
'stock_real' => 'integer',
|
||||
'stock_reservado' => 'integer',
|
||||
'is_placeholder' => 'boolean',
|
||||
'has_tickets' => 'boolean',
|
||||
'minimum_use_date' => 'datetime',
|
||||
'maximum_use_date' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
22
app/Domains/Catalog/Requests/StoreFeaturedGroupRequest.php
Normal file
22
app/Domains/Catalog/Requests/StoreFeaturedGroupRequest.php
Normal file
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class StoreFeaturedGroupRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'group_name' => ['required', 'string', 'max:255'],
|
||||
'product_layout' => ['required', 'string', 'in:row,column_with_image,column_with_cart,vertical_with_image,vertical_with_cart'],
|
||||
'group_order' => ['nullable', 'integer'],
|
||||
];
|
||||
}
|
||||
}
|
||||
21
app/Domains/Catalog/Requests/StoreFeaturedVariantRequest.php
Normal file
21
app/Domains/Catalog/Requests/StoreFeaturedVariantRequest.php
Normal file
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class StoreFeaturedVariantRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'product_variant_id' => ['required', 'integer'],
|
||||
'order' => ['nullable', 'integer'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,9 @@ class StoreProductVariantRequest extends FormRequest
|
||||
'definitions.*.value' => ['nullable', 'string'],
|
||||
'images' => ['sometimes', 'nullable', 'array'],
|
||||
'images.*' => ['required', new ImageOrBase64Rule()],
|
||||
'has_tickets' => ['boolean'],
|
||||
'minimum_use_date' => ['nullable', 'date'],
|
||||
'maximum_use_date' => ['nullable', 'date', 'after_or_equal:minimum_use_date'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
22
app/Domains/Catalog/Requests/UpdateFeaturedGroupRequest.php
Normal file
22
app/Domains/Catalog/Requests/UpdateFeaturedGroupRequest.php
Normal file
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class UpdateFeaturedGroupRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'group_name' => ['sometimes', 'string', 'max:255'],
|
||||
'product_layout' => ['sometimes', 'string', 'in:row,column_with_image,column_with_cart,vertical_with_image,vertical_with_cart'],
|
||||
'group_order' => ['nullable', 'integer'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class UpdateFeaturedVariantRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'order' => ['sometimes', 'integer'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,9 @@ class UpdateProductVariantRequest extends FormRequest
|
||||
'definitions.*.value' => ['nullable', 'string'],
|
||||
'images' => ['sometimes', 'nullable', 'array'],
|
||||
'images.*' => ['required', new ImageOrBase64Rule()],
|
||||
'has_tickets' => ['boolean'],
|
||||
'minimum_use_date' => ['nullable', 'date'],
|
||||
'maximum_use_date' => ['nullable', 'date', 'after_or_equal:minimum_use_date'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
use App\Domains\Catalog\Models\FeaturedVariant;
|
||||
|
||||
class CatalogFeaturedGroupResource extends JsonResource
|
||||
{
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'title' => $this->group_name,
|
||||
'layout' => $this->product_layout,
|
||||
'group_order' => $this->group_order,
|
||||
'items' => $this->whenLoaded('featuredVariants', function () use ($request) {
|
||||
return $this->featuredVariants->map(function (FeaturedVariant $featuredVariant) use ($request) {
|
||||
$variant = $featuredVariant->variant;
|
||||
$variantResource = (new ProductVariantResource($variant))->toArray($request);
|
||||
|
||||
if ($this->product_layout === 'row' || $this->product_layout === 'column_with_cart' || $this->product_layout === 'vertical_with_cart') {
|
||||
// Devuelve el Product Variant Resource completo como pidio el usuario
|
||||
// "Que todo devuelva el product variant resource"
|
||||
return $variantResource;
|
||||
}
|
||||
|
||||
// Para column_with_image o vertical_with_image
|
||||
if ($this->product_layout === 'column_with_image' || $this->product_layout === 'vertical_with_image') {
|
||||
if (isset($variantResource['images']) && count($variantResource['images']) > 0) {
|
||||
$variantResource['images'] = [$variantResource['images'][0]];
|
||||
}
|
||||
return $variantResource;
|
||||
}
|
||||
|
||||
return $variantResource;
|
||||
});
|
||||
}),
|
||||
];
|
||||
}
|
||||
}
|
||||
21
app/Domains/Catalog/Resources/FeaturedGroupResource.php
Normal file
21
app/Domains/Catalog/Resources/FeaturedGroupResource.php
Normal file
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class FeaturedGroupResource extends JsonResource
|
||||
{
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'tenant_codigo' => $this->tenant_codigo,
|
||||
'group_name' => $this->group_name,
|
||||
'product_layout' => $this->product_layout,
|
||||
'group_order' => $this->group_order,
|
||||
'featured_variants' => FeaturedVariantResource::collection($this->whenLoaded('featuredVariants')),
|
||||
];
|
||||
}
|
||||
}
|
||||
19
app/Domains/Catalog/Resources/FeaturedVariantResource.php
Normal file
19
app/Domains/Catalog/Resources/FeaturedVariantResource.php
Normal file
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class FeaturedVariantResource extends JsonResource
|
||||
{
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'featured_group_id' => $this->featured_group_id,
|
||||
'product_variant_id' => $this->product_variant_id,
|
||||
'order' => $this->order,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,7 @@ class ProductResource extends JsonResource
|
||||
'precio' => $this->precio,
|
||||
'category' => $this->whenLoaded('category', fn () => $this->category?->nombre),
|
||||
'brand' => $this->whenLoaded('brand', fn () => $this->brand?->nombre),
|
||||
|
||||
'images' => $this->whenLoaded('attachments', fn () => $this->attachments
|
||||
->map(fn ($attachment) => $attachment->getTemporaryUrl(1440))
|
||||
->values()
|
||||
|
||||
@@ -19,6 +19,9 @@ class ProductVariantResource extends JsonResource
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'cantidad_maxima' => $this->stock_tecnico,
|
||||
'has_tickets' => $this->has_tickets,
|
||||
'minimum_use_date' => $this->minimum_use_date,
|
||||
'maximum_use_date' => $this->maximum_use_date,
|
||||
'product' => ProductResource::make($this->whenLoaded('product')),
|
||||
'definitions' => $this->whenLoaded(
|
||||
'definitions',
|
||||
|
||||
25
app/Domains/Catalog/Services/FeaturedGroupService.php
Normal file
25
app/Domains/Catalog/Services/FeaturedGroupService.php
Normal file
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Services;
|
||||
|
||||
use App\Domains\Catalog\Models\FeaturedGroup;
|
||||
|
||||
class FeaturedGroupService
|
||||
{
|
||||
public function createGroup(string $tenantCodigo, array $data): FeaturedGroup
|
||||
{
|
||||
$data['tenant_codigo'] = $tenantCodigo;
|
||||
return FeaturedGroup::create($data);
|
||||
}
|
||||
|
||||
public function updateGroup(FeaturedGroup $group, array $data): FeaturedGroup
|
||||
{
|
||||
$group->update($data);
|
||||
return $group;
|
||||
}
|
||||
|
||||
public function deleteGroup(FeaturedGroup $group): bool|null
|
||||
{
|
||||
return $group->delete();
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,17 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Catalog\Controllers\BrandController;
|
||||
use App\Domains\Catalog\Controllers\CatalogController;
|
||||
use App\Domains\Catalog\Controllers\CategoryController;
|
||||
use App\Domains\Catalog\Controllers\ProductController;
|
||||
use App\Domains\Catalog\Controllers\AttributeController;
|
||||
use App\Domains\Catalog\Controllers\ProductVariantController;
|
||||
use App\Domains\Catalog\Controllers\FeaturedGroupController;
|
||||
use App\Domains\Catalog\Controllers\FeaturedVariantController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::prefix('tenants/{tenant:codigo}')->group(function (): void {
|
||||
Route::get('catalog', [CatalogController::class, 'index']);
|
||||
Route::apiResource('marcas', BrandController::class)->parameters(['marcas' => 'marca']);
|
||||
Route::apiResource('categorias', CategoryController::class)->parameters(['categorias' => 'categoria']);
|
||||
Route::apiResource('productos', ProductController::class);
|
||||
@@ -17,4 +21,11 @@ Route::prefix('tenants/{tenant:codigo}')->group(function (): void {
|
||||
'productos' => 'producto',
|
||||
'variants' => 'productVariant',
|
||||
]);
|
||||
Route::apiResource('featured-groups', FeaturedGroupController::class);
|
||||
Route::apiResource('featured-groups.variants', FeaturedVariantController::class)
|
||||
->only(['index', 'store', 'update', 'destroy'])
|
||||
->parameters([
|
||||
'featured-groups' => 'featuredGroup',
|
||||
'variants' => 'featuredVariant',
|
||||
]);
|
||||
});
|
||||
|
||||
50
app/Domains/Menu/Controllers/MenuController.php
Normal file
50
app/Domains/Menu/Controllers/MenuController.php
Normal file
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Menu\Controllers;
|
||||
|
||||
use App\Domains\Menu\Models\Menu;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class MenuController extends Controller
|
||||
{
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
$menues = Menu::all();
|
||||
return response()->json($menues);
|
||||
}
|
||||
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'code' => 'required|string|unique:menues,code',
|
||||
'route' => 'required|string',
|
||||
]);
|
||||
|
||||
$menu = Menu::create($validated);
|
||||
return response()->json($menu, 201);
|
||||
}
|
||||
|
||||
public function show(Menu $menu): JsonResponse
|
||||
{
|
||||
return response()->json($menu);
|
||||
}
|
||||
|
||||
public function update(Request $request, Menu $menu): JsonResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'code' => 'sometimes|required|string|unique:menues,code,' . $menu->id,
|
||||
'route' => 'sometimes|required|string',
|
||||
]);
|
||||
|
||||
$menu->update($validated);
|
||||
return response()->json($menu);
|
||||
}
|
||||
|
||||
public function destroy(Menu $menu): JsonResponse
|
||||
{
|
||||
$menu->delete();
|
||||
return response()->json(null, 204);
|
||||
}
|
||||
}
|
||||
32
app/Domains/Menu/Models/Menu.php
Normal file
32
app/Domains/Menu/Models/Menu.php
Normal file
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Menu\Models;
|
||||
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
|
||||
class Menu extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $table = 'menues';
|
||||
|
||||
protected $fillable = [
|
||||
'code',
|
||||
'route',
|
||||
];
|
||||
|
||||
public function tenants(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(
|
||||
Tenant::class,
|
||||
'tenant_menues',
|
||||
'menu_code',
|
||||
'tenant_codigo',
|
||||
'code',
|
||||
'codigo'
|
||||
)->withTimestamps();
|
||||
}
|
||||
}
|
||||
10
app/Domains/Menu/Models/TenantMenu.php
Normal file
10
app/Domains/Menu/Models/TenantMenu.php
Normal file
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Menu\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Relations\Pivot;
|
||||
|
||||
class TenantMenu extends Pivot
|
||||
{
|
||||
protected $table = 'tenant_menues';
|
||||
}
|
||||
6
app/Domains/Menu/routes/api.php
Normal file
6
app/Domains/Menu/routes/api.php
Normal file
@@ -0,0 +1,6 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Menu\Controllers\MenuController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::apiResource('menues', MenuController::class);
|
||||
@@ -19,7 +19,6 @@ class PurchaseController extends Controller
|
||||
{
|
||||
return PurchaseResource::collection(
|
||||
Purchase::query()
|
||||
->with(['items.variant.product', 'items.variant.definitions.productAttribute.attribute'])
|
||||
->where('tenant_codigo', $tenant->codigo)
|
||||
->where('user_id', $request->user()->id)
|
||||
->when($request->query('status'), function ($query, $status) {
|
||||
@@ -48,7 +47,7 @@ class PurchaseController extends Controller
|
||||
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
|
||||
|
||||
return PurchaseResource::make(
|
||||
$compra->loadMissing(['items.variant.product', 'items.variant.definitions.productAttribute.attribute'])
|
||||
$compra->loadMissing($this->purchaseDetailRelations())
|
||||
);
|
||||
}
|
||||
|
||||
@@ -140,4 +139,19 @@ class PurchaseController extends Controller
|
||||
|
||||
return $purchase;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
protected function purchaseDetailRelations(): array
|
||||
{
|
||||
return [
|
||||
'items.variant.product',
|
||||
'items.variant.definitions.productAttribute.attribute',
|
||||
'items.variant.attachments',
|
||||
'cart.items.variant.product',
|
||||
'cart.items.variant.definitions.productAttribute.attribute',
|
||||
'cart.items.variant.attachments',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,8 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable([
|
||||
'compra_id',
|
||||
'producto_variante_id',
|
||||
'buyable_id',
|
||||
'buyable_type',
|
||||
'cantidad',
|
||||
'precio_unitario',
|
||||
'discount_total',
|
||||
@@ -27,7 +28,8 @@ class PurchaseItem extends Model
|
||||
{
|
||||
return [
|
||||
'compra_id' => 'integer',
|
||||
'producto_variante_id' => 'integer',
|
||||
'buyable_id' => 'integer',
|
||||
'buyable_type' => 'string',
|
||||
'cantidad' => 'integer',
|
||||
'precio_unitario' => 'decimal:2',
|
||||
'discount_total' => 'decimal:2',
|
||||
@@ -45,10 +47,10 @@ class PurchaseItem extends Model
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<ProductVariant, $this>
|
||||
* @return \Illuminate\Database\Eloquent\Relations\MorphTo
|
||||
*/
|
||||
public function variant(): BelongsTo
|
||||
public function buyable()
|
||||
{
|
||||
return $this->belongsTo(ProductVariant::class, 'producto_variante_id');
|
||||
return $this->morphTo();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,12 +2,13 @@
|
||||
|
||||
namespace App\Domains\Purchase\Resources;
|
||||
|
||||
use App\Domains\Catalog\Resources\ProductVariantDefinitionResource;
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/**
|
||||
* @mixin \App\Domains\Purchase\Models\PurchaseItem
|
||||
* @mixin \App\Domains\Purchase\Models\PurchaseItem|\App\Domains\Cart\Models\CartItem
|
||||
*/
|
||||
class PurchaseItemResource extends JsonResource
|
||||
{
|
||||
@@ -16,26 +17,101 @@ class PurchaseItemResource extends JsonResource
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$variant = $this->variant;
|
||||
$product = $variant?->product;
|
||||
/** @var \App\Domains\Shared\Contracts\Buyable|null $buyable */
|
||||
$buyable = $this->buyable;
|
||||
$quantity = (int) ($this->cantidad ?? 0);
|
||||
$unitPrice = $this->resolveUnitPrice();
|
||||
$lineTotal = $this->resolveLineTotal($unitPrice, $quantity);
|
||||
|
||||
$imageUrl = null;
|
||||
$attributes = [];
|
||||
if ($this->buyable_type === \App\Domains\Catalog\Models\ProductVariant::class && $buyable) {
|
||||
$imageUrl = $this->resolveImageUrl($buyable);
|
||||
$attributes = $this->resolveAttributes($buyable);
|
||||
}
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'cantidad' => $this->cantidad,
|
||||
'precio_unitario' => $this->formatMoney($this->precio_unitario),
|
||||
'total' => $this->formatMoney($this->total),
|
||||
'product' => $product === null ? null : [
|
||||
'id' => $product->id,
|
||||
'nombre' => $product->nombre,
|
||||
'slug' => $product->slug,
|
||||
],
|
||||
'variant' => $variant === null ? null : [
|
||||
'id' => $variant->id,
|
||||
'definitions' => ProductVariantDefinitionResource::collection($variant->definitions),
|
||||
'quantity' => $quantity,
|
||||
'unit_price' => $this->formatMoney($unitPrice),
|
||||
'line_total' => $this->formatMoney($lineTotal),
|
||||
'buyable_type' => $this->mapBuyableTypeToAlias($this->buyable_type),
|
||||
'buyable_id' => $this->buyable_id,
|
||||
'item_details' => $buyable === null ? null : [
|
||||
'nombre' => $buyable->getName(),
|
||||
'imagen' => $imageUrl,
|
||||
'attributes' => $attributes,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
protected function mapBuyableTypeToAlias(?string $type): string
|
||||
{
|
||||
return match ($type) {
|
||||
\App\Domains\Catalog\Models\ProductVariant::class => 'variant',
|
||||
\App\Domains\Bundle\Models\Bundle::class => 'bundle',
|
||||
default => 'unknown',
|
||||
};
|
||||
}
|
||||
|
||||
protected function resolveUnitPrice(): float
|
||||
{
|
||||
if ($this->resource instanceof PurchaseItem) {
|
||||
return (float) ($this->precio_unitario ?? 0);
|
||||
}
|
||||
|
||||
if ($this->resource instanceof CartItem) {
|
||||
return (float) ($this->buyable?->getPrice() ?? 0);
|
||||
}
|
||||
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
protected function resolveLineTotal(float $unitPrice, int $quantity): float
|
||||
{
|
||||
if ($this->resource instanceof PurchaseItem) {
|
||||
return (float) ($this->total ?? 0);
|
||||
}
|
||||
|
||||
return $unitPrice * $quantity;
|
||||
}
|
||||
|
||||
protected function resolveImageUrl($buyable): ?string
|
||||
{
|
||||
if (! $buyable->relationLoaded('attachments')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$attachment = $buyable->attachments->first();
|
||||
|
||||
if ($attachment === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $attachment->getTemporaryUrl(1440);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, array{name: string, value: mixed}>
|
||||
*/
|
||||
protected function resolveAttributes($buyable): array
|
||||
{
|
||||
if (! $buyable->relationLoaded('definitions')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $buyable->definitions
|
||||
->map(function ($definition): array {
|
||||
return [
|
||||
'name' => (string) ($definition->productAttribute?->attribute?->nombre ?? ''),
|
||||
'value' => $definition->value,
|
||||
];
|
||||
})
|
||||
->filter(fn (array $attribute): bool => $attribute['name'] !== '' || $attribute['value'] !== null)
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
protected function formatMoney(float|int|string|null $amount): ?string
|
||||
{
|
||||
if ($amount === null) {
|
||||
|
||||
@@ -2,8 +2,11 @@
|
||||
|
||||
namespace App\Domains\Purchase\Resources;
|
||||
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* @mixin \App\Domains\Purchase\Models\Purchase
|
||||
@@ -15,20 +18,18 @@ class PurchaseResource extends JsonResource
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$items = $this->resource->relationLoaded('items')
|
||||
? $this->resource->getRelation('items')
|
||||
: collect();
|
||||
[$items, $itemsSource] = $this->resolveItems();
|
||||
|
||||
$subtotal = $items->isNotEmpty()
|
||||
? $items->reduce(
|
||||
fn (float $carry, $item): float => $carry + ((float) $item->precio_unitario * $item->cantidad),
|
||||
fn (float $carry, PurchaseItem|CartItem $item): float => $carry + $this->resolveItemSubtotal($item),
|
||||
0.0,
|
||||
)
|
||||
: (float) ($this->total ?? 0);
|
||||
|
||||
$total = $items->isNotEmpty()
|
||||
? $items->reduce(
|
||||
fn (float $carry, $item): float => $carry + (float) $item->total,
|
||||
fn (float $carry, PurchaseItem|CartItem $item): float => $carry + $this->resolveItemTotal($item),
|
||||
0.0,
|
||||
)
|
||||
: (float) ($this->total ?? 0);
|
||||
@@ -38,18 +39,66 @@ class PurchaseResource extends JsonResource
|
||||
'cart_id' => $this->cart_id,
|
||||
'tenant_codigo' => $this->tenant_codigo,
|
||||
'user_id' => $this->user_id,
|
||||
'created_at' => $this->created_at,
|
||||
'status' => $this->status,
|
||||
'payment_method' => $this->payment_method,
|
||||
'dni' => $this->dni,
|
||||
'telefono' => $this->telefono,
|
||||
'nombre_apellido' => $this->nombre_apellido,
|
||||
'email' => $this->email,
|
||||
'items_source' => $itemsSource,
|
||||
'items' => PurchaseItemResource::collection($items),
|
||||
'subtotal' => $this->formatMoney($subtotal),
|
||||
'total' => $this->formatMoney($total),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0: Collection<int, PurchaseItem|CartItem>, 1: string|null}
|
||||
*/
|
||||
protected function resolveItems(): array
|
||||
{
|
||||
if (! $this->resource->relationLoaded('items')) {
|
||||
return [collect(), null];
|
||||
}
|
||||
|
||||
$purchaseItems = $this->resource->getRelation('items');
|
||||
|
||||
if ($purchaseItems->isNotEmpty()) {
|
||||
return [$purchaseItems, 'purchase'];
|
||||
}
|
||||
|
||||
if (! $this->resource->relationLoaded('cart')) {
|
||||
return [collect(), null];
|
||||
}
|
||||
|
||||
$cart = $this->resource->getRelation('cart');
|
||||
|
||||
if ($cart === null || ! $cart->relationLoaded('items')) {
|
||||
return [collect(), null];
|
||||
}
|
||||
|
||||
return [$cart->getRelation('items'), 'cart'];
|
||||
}
|
||||
|
||||
protected function resolveItemSubtotal(PurchaseItem|CartItem $item): float
|
||||
{
|
||||
if ($item instanceof PurchaseItem) {
|
||||
return (float) $item->precio_unitario * $item->cantidad;
|
||||
}
|
||||
|
||||
return (float) ($item->variant?->product?->precio ?? 0) * $item->cantidad;
|
||||
}
|
||||
|
||||
protected function resolveItemTotal(PurchaseItem|CartItem $item): float
|
||||
{
|
||||
if ($item instanceof PurchaseItem) {
|
||||
return (float) ($item->total ?? 0);
|
||||
}
|
||||
|
||||
return $this->resolveItemSubtotal($item);
|
||||
}
|
||||
|
||||
protected function formatMoney(float|int|string|null $amount): string
|
||||
{
|
||||
return number_format((float) ($amount ?? 0), 2, '.', '');
|
||||
|
||||
@@ -29,7 +29,7 @@ class CheckoutService
|
||||
]);
|
||||
}
|
||||
|
||||
$cartItems->load('variant.product');
|
||||
$cartItems->load('buyable');
|
||||
$cart->setRelation('items', $cartItems);
|
||||
$totalAmount = $cart->getTotalAmount();
|
||||
|
||||
@@ -63,7 +63,7 @@ class CheckoutService
|
||||
$purchase->save();
|
||||
}
|
||||
|
||||
return $purchase->load(['items.variant.product', 'items.variant.definitions.productAttribute.attribute']);
|
||||
return $purchase->load(['items.buyable']);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -82,7 +82,7 @@ class CheckoutService
|
||||
}
|
||||
|
||||
if (in_array($purchase->status, [Purchase::STATUS_PAID, Purchase::STATUS_CANCELLED, Purchase::STATUS_REJECTED], true)) {
|
||||
return $purchase->load(['items.variant.product', 'items.variant.definitions.productAttribute.attribute']);
|
||||
return $purchase->load(['items.buyable']);
|
||||
}
|
||||
|
||||
$purchase->update([
|
||||
@@ -90,7 +90,7 @@ class CheckoutService
|
||||
'total' => $purchase->calculateCurrentTotalAmount(),
|
||||
]);
|
||||
|
||||
return $purchase->load(['items.variant.product', 'items.variant.definitions.productAttribute.attribute']);
|
||||
return $purchase->load(['items.buyable']);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -118,42 +118,36 @@ class CheckoutService
|
||||
return;
|
||||
}
|
||||
|
||||
$cartItems->load('variant.product');
|
||||
$variants = $this->resolveTenantVariants($purchase->tenant, $cartItems);
|
||||
$purchaseItemsPayload = $this->buildPurchaseItemsPayload($cartItems, $variants);
|
||||
$cartItems->load('buyable');
|
||||
$this->verifyTenantBuyables($purchase->tenant, $cartItems);
|
||||
$purchaseItemsPayload = $this->buildPurchaseItemsPayload($cartItems);
|
||||
|
||||
$purchase->items()->createMany($purchaseItemsPayload);
|
||||
$this->completeCartConversion($cart, $cartItems, $variants);
|
||||
$this->completeCartConversion($cart, $cartItems);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, ProductVariant>
|
||||
*/
|
||||
protected function resolveTenantVariants(Tenant $tenant, Collection $cartItems): Collection
|
||||
protected function verifyTenantBuyables(Tenant $tenant, Collection $cartItems): void
|
||||
{
|
||||
$variantIds = $cartItems
|
||||
->pluck('producto_variante_id')
|
||||
->map(static fn (mixed $id): int => (int) $id)
|
||||
->unique()
|
||||
->values();
|
||||
|
||||
/** @var Collection<int, ProductVariant> $variants */
|
||||
$variants = ProductVariant::query()
|
||||
->with('product')
|
||||
->whereIn('id', $variantIds)
|
||||
->whereHas('product', fn ($query) => $query->where('tenant_codigo', $tenant->codigo))
|
||||
->lockForUpdate()
|
||||
->get()
|
||||
->keyBy('id');
|
||||
|
||||
if ($variants->count() !== $variantIds->count()) {
|
||||
throw ValidationException::withMessages([
|
||||
'cart_id' => 'One or more product variants do not belong to the tenant.',
|
||||
]);
|
||||
foreach ($cartItems as $item) {
|
||||
$buyable = $item->buyable;
|
||||
if ($buyable === null) {
|
||||
throw ValidationException::withMessages([
|
||||
'cart_id' => 'One or more buyables could not be loaded.',
|
||||
]);
|
||||
}
|
||||
|
||||
// Check tenant relation depending on type
|
||||
if ($item->buyable_type === \App\Domains\Catalog\Models\ProductVariant::class && $buyable->product->tenant_codigo !== $tenant->codigo) {
|
||||
throw ValidationException::withMessages([
|
||||
'cart_id' => 'One or more product variants do not belong to the tenant.',
|
||||
]);
|
||||
} elseif ($item->buyable_type === \App\Domains\Bundle\Models\Bundle::class && $buyable->tenant_codigo !== $tenant->codigo) {
|
||||
throw ValidationException::withMessages([
|
||||
'cart_id' => 'One or more bundles do not belong to the tenant.',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
return $variants;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -182,20 +176,19 @@ class CheckoutService
|
||||
|
||||
/**
|
||||
* @param Collection<int, CartItem> $cartItems
|
||||
* @param Collection<int, ProductVariant> $variants
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
protected function buildPurchaseItemsPayload(Collection $cartItems, Collection $variants): array
|
||||
protected function buildPurchaseItemsPayload(Collection $cartItems): array
|
||||
{
|
||||
return $cartItems
|
||||
->map(function (CartItem $item) use ($variants): array {
|
||||
/** @var ProductVariant $variant */
|
||||
$variant = $variants->get((int) $item['producto_variante_id']);
|
||||
->map(function (CartItem $item): array {
|
||||
$buyable = $item->buyable;
|
||||
$quantity = (int) $item['cantidad'];
|
||||
$unitPrice = (float) ($variant->product?->precio ?? 0);
|
||||
$unitPrice = $buyable?->getPrice() ?? 0;
|
||||
|
||||
return [
|
||||
'producto_variante_id' => $variant->getKey(),
|
||||
'buyable_type' => $item->buyable_type,
|
||||
'buyable_id' => $item->buyable_id,
|
||||
'cantidad' => $quantity,
|
||||
'precio_unitario' => $unitPrice,
|
||||
'discount_total' => null,
|
||||
@@ -208,17 +201,15 @@ class CheckoutService
|
||||
|
||||
/**
|
||||
* @param Collection<int, CartItem> $cartItems
|
||||
* @param Collection<int, ProductVariant> $variants
|
||||
*/
|
||||
protected function completeCartConversion(Cart $cart, Collection $cartItems, Collection $variants): void
|
||||
protected function completeCartConversion(Cart $cart, Collection $cartItems): void
|
||||
{
|
||||
foreach ($cartItems as $item) {
|
||||
/** @var ProductVariant $variant */
|
||||
$variant = $variants->get((int) $item->producto_variante_id);
|
||||
$buyable = $item->buyable;
|
||||
$quantity = (int) $item->cantidad;
|
||||
|
||||
try {
|
||||
$variant->confirmReservedStock($quantity);
|
||||
$buyable->confirmReservedStock($quantity);
|
||||
} catch (\InvalidArgumentException $exception) {
|
||||
throw ValidationException::withMessages([
|
||||
'cart_id' => 'The selected cart has inconsistent stock state.',
|
||||
|
||||
18
app/Domains/Shared/Contracts/Buyable.php
Normal file
18
app/Domains/Shared/Contracts/Buyable.php
Normal file
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Shared\Contracts;
|
||||
|
||||
interface Buyable
|
||||
{
|
||||
public function getPrice(): float;
|
||||
public function getName(): string;
|
||||
|
||||
public function incrementRealStock(int $amount): void;
|
||||
public function decrementRealStock(int $amount): void;
|
||||
|
||||
public function incrementReservedStock(int $amount): void;
|
||||
public function decrementReservedStock(int $amount): void;
|
||||
public function confirmReservedStock(int $amount): void;
|
||||
|
||||
public function validateStock(): void;
|
||||
}
|
||||
@@ -15,7 +15,7 @@ class BootstrapTenantController extends Controller
|
||||
$dominio = $request->validated('dominio');
|
||||
|
||||
return TenantResource::make(
|
||||
Tenant::query()->with(['headerLogo', 'footerLogo'])->where('dominio', $dominio)->firstOrFail()
|
||||
Tenant::query()->with(['headerLogo', 'footerLogo', 'menues'])->where('dominio', $dominio)->firstOrFail()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,8 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
'footer_bg_color',
|
||||
'header_logo_id',
|
||||
'footer_logo_id',
|
||||
'hero_config',
|
||||
'event_config',
|
||||
])]
|
||||
class Tenant extends Model
|
||||
{
|
||||
@@ -32,6 +34,19 @@ class Tenant extends Model
|
||||
return 'codigo';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'hero_config' => 'array',
|
||||
'event_config' => 'array',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Attachment, $this>
|
||||
*/
|
||||
@@ -48,9 +63,29 @@ class Tenant extends Model
|
||||
return $this->belongsTo(Attachment::class, 'footer_logo_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Attachment, $this>
|
||||
*/
|
||||
public function heroBgImage(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Attachment::class, 'hero_bg_image_id');
|
||||
}
|
||||
|
||||
public function productos(): HasMany
|
||||
{
|
||||
return $this->hasMany(Product::class, 'tenant_codigo', 'codigo');
|
||||
}
|
||||
|
||||
public function menues(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(
|
||||
\App\Domains\Menu\Models\Menu::class,
|
||||
'tenant_menues',
|
||||
'tenant_codigo',
|
||||
'menu_code',
|
||||
'codigo',
|
||||
'code'
|
||||
)->withTimestamps();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -61,6 +61,17 @@ class StoreTenantRequest extends FormRequest
|
||||
'footer_bg_color' => ['required', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
|
||||
'header_logo' => $logoRule,
|
||||
'footer_logo' => $logoRule,
|
||||
'hero_bg_image' => ['nullable', new ImageOrBase64Rule()],
|
||||
'hero_config' => ['nullable', 'array'],
|
||||
'hero_config.title_html' => ['nullable', 'string'],
|
||||
'hero_config.description_html' => ['nullable', 'string'],
|
||||
'hero_config.button_text' => ['nullable', 'string'],
|
||||
'hero_config.button_href' => ['nullable', 'string'],
|
||||
'event_config' => ['nullable', 'array'],
|
||||
'event_config.title' => ['nullable', 'string'],
|
||||
'event_config.location' => ['nullable', 'string'],
|
||||
'event_config.dates' => ['nullable', 'array'],
|
||||
'event_config.dates.*' => ['required', 'string'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,6 +72,17 @@ class UpdateTenantRequest extends FormRequest
|
||||
'footer_bg_color' => ['nullable', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
|
||||
'header_logo' => $logoRule,
|
||||
'footer_logo' => $logoRule,
|
||||
'hero_bg_image' => ['nullable', new ImageOrBase64Rule()],
|
||||
'hero_config' => ['nullable', 'array'],
|
||||
'hero_config.title_html' => ['nullable', 'string'],
|
||||
'hero_config.description_html' => ['nullable', 'string'],
|
||||
'hero_config.button_text' => ['nullable', 'string'],
|
||||
'hero_config.button_href' => ['nullable', 'string'],
|
||||
'event_config' => ['nullable', 'array'],
|
||||
'event_config.title' => ['nullable', 'string'],
|
||||
'event_config.location' => ['nullable', 'string'],
|
||||
'event_config.dates' => ['nullable', 'array'],
|
||||
'event_config.dates.*' => ['required', 'string'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,12 @@ class TenantResource extends JsonResource
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$heroConfig = $this->hero_config;
|
||||
if (is_array($heroConfig)) {
|
||||
$heroConfig['background_image'] = $this->heroBgImage?->getTemporaryUrl(1440);
|
||||
unset($heroConfig['background_image_id']);
|
||||
}
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'codigo' => $this->codigo,
|
||||
@@ -29,6 +35,9 @@ class TenantResource extends JsonResource
|
||||
// 1 day
|
||||
'header_logo' => $this->headerLogo?->getTemporaryUrl(1440),
|
||||
'footer_logo' => $this->footerLogo?->getTemporaryUrl(1440 ),
|
||||
'hero_config' => $heroConfig,
|
||||
'event_config' => $this->event_config,
|
||||
'menues' => $this->whenLoaded('menues'),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,8 +24,9 @@ class TenantService
|
||||
return DB::transaction(function () use ($data): Tenant {
|
||||
$headerLogo = $data['header_logo'] ?? null;
|
||||
$footerLogo = $data['footer_logo'] ?? null;
|
||||
$heroBgImage = $data['hero_bg_image'] ?? null;
|
||||
|
||||
unset($data['header_logo'], $data['footer_logo']);
|
||||
unset($data['header_logo'], $data['footer_logo'], $data['hero_bg_image']);
|
||||
|
||||
$headerAttachmentId = null;
|
||||
if ($headerLogo) {
|
||||
@@ -52,6 +53,18 @@ class TenantService
|
||||
$data['header_logo_id'] = $headerAttachmentId;
|
||||
$data['footer_logo_id'] = $footerAttachmentId;
|
||||
|
||||
if ($heroBgImage) {
|
||||
$attachment = Str::isUuid($heroBgImage)
|
||||
? \App\Domains\Attachable\Models\Attachment::query()->where('key', $heroBgImage)->first()
|
||||
: $this->attachmentService->store($heroBgImage, 'tenants');
|
||||
|
||||
if ($attachment) {
|
||||
$heroConfig = $data['hero_config'] ?? [];
|
||||
$heroConfig['background_image_id'] = $attachment->id;
|
||||
$data['hero_config'] = $heroConfig;
|
||||
}
|
||||
}
|
||||
|
||||
/** @var Tenant $tenant */
|
||||
$tenant = Tenant::query()->create($data);
|
||||
|
||||
@@ -71,10 +84,14 @@ class TenantService
|
||||
return DB::transaction(function () use ($tenant, $data): Tenant {
|
||||
$hasHeaderLogoKey = array_key_exists('header_logo', $data);
|
||||
$hasFooterLogoKey = array_key_exists('footer_logo', $data);
|
||||
$hasHeroBgImageKey = array_key_exists('hero_bg_image', $data);
|
||||
$headerLogo = $data['header_logo'] ?? null;
|
||||
$footerLogo = $data['footer_logo'] ?? null;
|
||||
$heroBgImage = $data['hero_bg_image'] ?? null;
|
||||
|
||||
unset($data['header_logo'], $data['footer_logo']);
|
||||
unset($data['header_logo'], $data['footer_logo'], $data['hero_bg_image']);
|
||||
|
||||
$oldHeroBgId = $tenant->hero_bg_image_id;
|
||||
|
||||
$tenant->fill($data);
|
||||
|
||||
@@ -110,6 +127,28 @@ class TenantService
|
||||
}
|
||||
}
|
||||
|
||||
$currentHeroConfig = $tenant->hero_config ?? [];
|
||||
if ($hasHeroBgImageKey) {
|
||||
if ($heroBgImage) {
|
||||
$attachment = Str::isUuid($heroBgImage)
|
||||
? \App\Domains\Attachable\Models\Attachment::query()->where('key', $heroBgImage)->first()
|
||||
: $this->attachmentService->store($heroBgImage, 'tenants');
|
||||
|
||||
if ($attachment) {
|
||||
$currentHeroConfig['background_image_id'] = $attachment->id;
|
||||
} else {
|
||||
unset($currentHeroConfig['background_image_id']);
|
||||
}
|
||||
} else {
|
||||
unset($currentHeroConfig['background_image_id']);
|
||||
}
|
||||
} else {
|
||||
if ($oldHeroBgId) {
|
||||
$currentHeroConfig['background_image_id'] = $oldHeroBgId;
|
||||
}
|
||||
}
|
||||
$tenant->hero_config = empty($currentHeroConfig) ? null : $currentHeroConfig;
|
||||
|
||||
$tenant->save();
|
||||
|
||||
return $tenant;
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('tenants', function (Blueprint $table) {
|
||||
$table->json('hero_config')->nullable();
|
||||
$table->json('event_config')->nullable();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('tenants', function (Blueprint $table) {
|
||||
$table->dropColumn(['hero_config', 'event_config']);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('tenants', function (Blueprint $table) {
|
||||
$table->unsignedBigInteger('hero_bg_image_id')
|
||||
->virtualAs('hero_config->>"$.background_image_id"')
|
||||
->nullable()
|
||||
->after('footer_bg_color');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('tenants', function (Blueprint $table) {
|
||||
$table->dropColumn('hero_bg_image_id');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('menues', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('code')->unique();
|
||||
$table->string('route');
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('menues');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('tenant_menues', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('tenant_codigo');
|
||||
$table->string('menu_code');
|
||||
$table->timestamps();
|
||||
|
||||
$table->foreign('tenant_codigo')->references('codigo')->on('tenants')->onDelete('cascade');
|
||||
$table->foreign('menu_code')->references('code')->on('menues')->onDelete('cascade');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('tenant_menues');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('featured_groups', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('tenant_codigo');
|
||||
$table->string('group_name');
|
||||
$table->enum('product_layout', ['row', 'column_with_image', 'column_with_cart']);
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('featured_groups');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('featured_products', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('featured_group_id')->constrained('featured_groups')->onDelete('cascade');
|
||||
$table->unsignedBigInteger('product_id');
|
||||
$table->integer('order')->default(0);
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('featured_products');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('featured_groups', function (Blueprint $table) {
|
||||
$table->integer('group_order')->default(0)->after('product_layout');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('featured_groups', function (Blueprint $table) {
|
||||
$table->dropColumn('group_order');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
if (Schema::hasTable('featured_products')) {
|
||||
Schema::rename('featured_products', 'featured_variants');
|
||||
}
|
||||
|
||||
if (Schema::hasColumn('featured_variants', 'product_id')) {
|
||||
Schema::table('featured_variants', function (Blueprint $table) {
|
||||
$table->renameColumn('product_id', 'product_variant_id');
|
||||
});
|
||||
}
|
||||
|
||||
Schema::table('featured_variants', function (Blueprint $table) {
|
||||
$table->foreign('product_variant_id')->references('id')->on('productos_variantes')->onDelete('cascade');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('featured_variants', function (Blueprint $table) {
|
||||
//
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('productos', function (Blueprint $table) {
|
||||
$table->boolean('has_tickets')->default(false);
|
||||
$table->dateTime('minimum_use_date')->nullable();
|
||||
$table->dateTime('maximum_use_date')->nullable();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('productos', function (Blueprint $table) {
|
||||
$table->dropColumn(['has_tickets', 'minimum_use_date', 'maximum_use_date']);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('productos', function (Blueprint $table) {
|
||||
$table->dropColumn(['has_tickets', 'minimum_use_date', 'maximum_use_date']);
|
||||
});
|
||||
|
||||
Schema::table('productos_variantes', function (Blueprint $table) {
|
||||
$table->boolean('has_tickets')->default(false);
|
||||
$table->dateTime('minimum_use_date')->nullable();
|
||||
$table->dateTime('maximum_use_date')->nullable();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('productos', function (Blueprint $table) {
|
||||
$table->boolean('has_tickets')->default(false);
|
||||
$table->dateTime('minimum_use_date')->nullable();
|
||||
$table->dateTime('maximum_use_date')->nullable();
|
||||
});
|
||||
|
||||
Schema::table('productos_variantes', function (Blueprint $table) {
|
||||
$table->dropColumn(['has_tickets', 'minimum_use_date', 'maximum_use_date']);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('bundles', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('tenant_codigo', 10);
|
||||
$table->string('nombre');
|
||||
$table->text('descripcion')->nullable();
|
||||
$table->decimal('precio', 10, 2);
|
||||
$table->timestamps();
|
||||
|
||||
$table->foreign('tenant_codigo')->references('codigo')->on('tenants')->onDelete('cascade');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('bundles');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('bundle_items', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('bundle_id')->constrained('bundles')->onDelete('cascade');
|
||||
$table->foreignId('producto_variante_id')->constrained('productos_variantes')->onDelete('cascade');
|
||||
$table->integer('cantidad');
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('bundle_items');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('carrito_items', function (Blueprint $table) {
|
||||
$table->string('buyable_type')->nullable();
|
||||
$table->unsignedBigInteger('buyable_id')->nullable();
|
||||
});
|
||||
|
||||
// Copy existing data
|
||||
\Illuminate\Support\Facades\DB::table('carrito_items')->update([
|
||||
'buyable_type' => 'App\Domains\Catalog\Models\ProductVariant',
|
||||
'buyable_id' => \Illuminate\Support\Facades\DB::raw('producto_variante_id'),
|
||||
]);
|
||||
|
||||
Schema::table('carrito_items', function (Blueprint $table) {
|
||||
$table->dropForeign(['producto_variante_id']);
|
||||
$table->dropColumn('producto_variante_id');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('carrito_items', function (Blueprint $table) {
|
||||
$table->foreignId('producto_variante_id')->nullable()->constrained('productos_variantes')->onDelete('cascade');
|
||||
});
|
||||
|
||||
\Illuminate\Support\Facades\DB::table('carrito_items')->update([
|
||||
'producto_variante_id' => \Illuminate\Support\Facades\DB::raw('buyable_id'),
|
||||
]);
|
||||
|
||||
Schema::table('carrito_items', function (Blueprint $table) {
|
||||
$table->dropColumn(['buyable_type', 'buyable_id']);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('compra_items', function (Blueprint $table) {
|
||||
$table->string('buyable_type')->nullable();
|
||||
$table->unsignedBigInteger('buyable_id')->nullable();
|
||||
});
|
||||
|
||||
// Copy existing data
|
||||
\Illuminate\Support\Facades\DB::table('compra_items')->update([
|
||||
'buyable_type' => 'App\Domains\Catalog\Models\ProductVariant',
|
||||
'buyable_id' => \Illuminate\Support\Facades\DB::raw('producto_variante_id'),
|
||||
]);
|
||||
|
||||
Schema::table('compra_items', function (Blueprint $table) {
|
||||
$table->dropForeign(['producto_variante_id']);
|
||||
$table->dropColumn('producto_variante_id');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('compra_items', function (Blueprint $table) {
|
||||
$table->foreignId('producto_variante_id')->nullable()->constrained('productos_variantes')->onDelete('cascade');
|
||||
});
|
||||
|
||||
\Illuminate\Support\Facades\DB::table('compra_items')->update([
|
||||
'producto_variante_id' => \Illuminate\Support\Facades\DB::raw('buyable_id'),
|
||||
]);
|
||||
|
||||
Schema::table('compra_items', function (Blueprint $table) {
|
||||
$table->dropColumn(['buyable_type', 'buyable_id']);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -29,6 +29,7 @@ class DatabaseSeeder extends Seeder
|
||||
BrandSeeder::class,
|
||||
ProductCatalogFromImagesSeeder::class,
|
||||
TelepagosIntegrationSeeder::class,
|
||||
MenuSeeder::class,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
48
database/seeders/MenuSeeder.php
Normal file
48
database/seeders/MenuSeeder.php
Normal file
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace Database\Seeders;
|
||||
|
||||
use Illuminate\Database\Seeder;
|
||||
use App\Domains\Menu\Models\Menu;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
|
||||
class MenuSeeder extends Seeder
|
||||
{
|
||||
/**
|
||||
* Run the database seeds.
|
||||
*/
|
||||
public function run(): void
|
||||
{
|
||||
$menus = [
|
||||
['code' => 'index', 'route' => '/'],
|
||||
['code' => 'product.detail', 'route' => '/product/:id'],
|
||||
['code' => 'checkout', 'route' => '/checkout'],
|
||||
['code' => 'profile', 'route' => '/profile'],
|
||||
['code' => 'purchases', 'route' => '/purchases'],
|
||||
['code' => 'tickets', 'route' => '/tickets'],
|
||||
];
|
||||
|
||||
foreach ($menus as $menuData) {
|
||||
Menu::firstOrCreate(['code' => $menuData['code']], $menuData);
|
||||
}
|
||||
|
||||
$tenants = Tenant::all();
|
||||
|
||||
$allMenus = Menu::pluck('code')->toArray();
|
||||
|
||||
foreach ($tenants as $tenant) {
|
||||
$menuCodes = $allMenus;
|
||||
|
||||
if ($tenant->codigo === 'sonder') {
|
||||
// Sonder NO tiene tickets
|
||||
$menuCodes = array_diff($menuCodes, ['tickets']);
|
||||
} else {
|
||||
// Los demás NO tienen product.detail
|
||||
$menuCodes = array_diff($menuCodes, ['product.detail']);
|
||||
}
|
||||
|
||||
// Usar sync para asociar los menues al tenant
|
||||
$tenant->menues()->sync($menuCodes);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -85,5 +85,99 @@ class TenantSeeder extends Seeder
|
||||
'header_logo' => $headerLogo,
|
||||
'footer_logo' => $footerLogo,
|
||||
]);
|
||||
|
||||
// Check if tenant 'fiesta_futbol_infantil' already exists
|
||||
$existingFiesta = Tenant::query()->where('codigo', 'fiesta_futbol_infantil')->first();
|
||||
if ($existingFiesta) {
|
||||
$attachmentService = app(\App\Domains\Attachable\Services\AttachmentService::class);
|
||||
if ($existingFiesta->headerLogo) {
|
||||
try {
|
||||
$attachmentService->delete($existingFiesta->headerLogo);
|
||||
} catch (\Throwable $e) {}
|
||||
}
|
||||
if ($existingFiesta->footerLogo && $existingFiesta->footer_logo_id !== $existingFiesta->header_logo_id) {
|
||||
try {
|
||||
$attachmentService->delete($existingFiesta->footerLogo);
|
||||
} catch (\Throwable $e) {}
|
||||
}
|
||||
if ($existingFiesta->heroBgImage) {
|
||||
try {
|
||||
$attachmentService->delete($existingFiesta->heroBgImage);
|
||||
} catch (\Throwable $e) {}
|
||||
}
|
||||
$existingFiesta->delete();
|
||||
}
|
||||
|
||||
$fiestaDomain = 'fiesta-futbol-infantil.localhost';
|
||||
$existingFiestaDomain = Tenant::query()->where('dominio', $fiestaDomain)->first();
|
||||
if ($existingFiestaDomain) {
|
||||
$existingFiestaDomain->delete();
|
||||
}
|
||||
|
||||
$fiestaHeaderImagePath = public_path('images/futbol_infantil_header.png');
|
||||
$fiestaFooterImagePath = public_path('images/futbol_infantil_footer.png');
|
||||
$fiestaHeroBgImagePath = public_path('images/futbol_infantil_hero.jpg');
|
||||
|
||||
if (! file_exists($fiestaHeaderImagePath)) {
|
||||
throw new \RuntimeException("Image not found at path: {$fiestaHeaderImagePath}");
|
||||
}
|
||||
|
||||
if (! file_exists($fiestaFooterImagePath)) {
|
||||
throw new \RuntimeException("Image not found at path: {$fiestaFooterImagePath}");
|
||||
}
|
||||
|
||||
if (! file_exists($fiestaHeroBgImagePath)) {
|
||||
throw new \RuntimeException("Image not found at path: {$fiestaHeroBgImagePath}");
|
||||
}
|
||||
|
||||
$fiestaHeaderLogo = new UploadedFile(
|
||||
$fiestaHeaderImagePath,
|
||||
'futbol_infantil_header.png',
|
||||
'image/png',
|
||||
null,
|
||||
true
|
||||
);
|
||||
|
||||
$fiestaFooterLogo = new UploadedFile(
|
||||
$fiestaFooterImagePath,
|
||||
'futbol_infantil_footer.png',
|
||||
'image/png',
|
||||
null,
|
||||
true
|
||||
);
|
||||
|
||||
$fiestaHeroBgImage = new UploadedFile(
|
||||
$fiestaHeroBgImagePath,
|
||||
'futbol_infantil_hero.jpg',
|
||||
'image/jpeg',
|
||||
null,
|
||||
true
|
||||
);
|
||||
|
||||
$this->tenantService->create([
|
||||
'codigo' => 'fiesta_futbol_infantil',
|
||||
'nombre' => 'Fiesta Fútbol Infantil',
|
||||
'dominio' => $fiestaDomain,
|
||||
'primary_color' => '#00973F',
|
||||
'secondary_color' => '#A0A0A0',
|
||||
'danger_color' => '#FF8888',
|
||||
'success_color' => '#198754',
|
||||
'header_bg_color' => '#015327',
|
||||
'footer_bg_color' => '#015327',
|
||||
'header_logo' => $fiestaHeaderLogo,
|
||||
'footer_logo' => $fiestaFooterLogo,
|
||||
'hero_bg_image' => $fiestaHeroBgImage,
|
||||
'hero_config' => [
|
||||
'title_html' => '<strong>ASEGURÁ TU LUGAR</strong>',
|
||||
'description_html' => '<strong>Comprá tu entrada oficial en segundos</strong> de forma 100% segura. Preparate para vivir la experiencia completa.',
|
||||
'button_text' => 'Quiero mi entrada',
|
||||
'button_href' => null,
|
||||
],
|
||||
'event_config' => [
|
||||
'title' => 'FIESTA NACIONAL DEL FÚTBOL INFANTIL',
|
||||
'location' => 'Sunchales, Santa Fe',
|
||||
'dates' => ['2026-10-09', '2026-10-10', '2026-10-11', '2026-10-12'],
|
||||
],
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
BIN
public/images/futbol_infantil_footer.png
Normal file
BIN
public/images/futbol_infantil_footer.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 14 KiB |
BIN
public/images/futbol_infantil_header.png
Normal file
BIN
public/images/futbol_infantil_header.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 27 KiB |
BIN
public/images/futbol_infantil_hero.jpg
Normal file
BIN
public/images/futbol_infantil_hero.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 58 KiB |
@@ -10,3 +10,5 @@ require __DIR__.'/../app/Domains/StorageTest/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Purchase/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Tenant/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Integration/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Menu/routes/api.php';
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Catalog\Models\Product;
|
||||
use App\Domains\Catalog\Models\ProductVariant;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Services\CheckoutService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
@@ -76,6 +77,7 @@ class StorePurchaseTest extends TestCase
|
||||
$response->assertJsonPath('data.email', 'juan.perez@example.com');
|
||||
$response->assertJsonPath('data.tenant_codigo', 'sonder');
|
||||
$response->assertJsonPath('data.status', Purchase::STATUS_CREATED);
|
||||
$response->assertJsonPath('data.items_source', null);
|
||||
$response->assertJsonPath('data.items', []);
|
||||
$response->assertJsonPath('data.subtotal', '100.00');
|
||||
$response->assertJsonPath('data.total', '100.00');
|
||||
@@ -159,6 +161,150 @@ class StorePurchaseTest extends TestCase
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_purchase_detail_uses_cart_items_for_created_purchase(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$user = User::factory()->create([
|
||||
'email' => 'buyer@example.com',
|
||||
]);
|
||||
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->getJson("/api/tenants/sonder/compras/{$purchase->id}")
|
||||
->assertOk()
|
||||
->assertJsonPath('data.status', Purchase::STATUS_CREATED)
|
||||
->assertJsonPath('data.items_source', 'cart')
|
||||
->assertJsonCount(1, 'data.items')
|
||||
->assertJsonPath('data.items.0.quantity', 2)
|
||||
->assertJsonPath('data.items.0.unit_price', '50.00')
|
||||
->assertJsonPath('data.items.0.line_total', '100.00')
|
||||
->assertJsonPath('data.items.0.product.id', $variant->product->id)
|
||||
->assertJsonPath('data.items.0.product.nombre', $variant->product->nombre)
|
||||
->assertJsonPath('data.items.0.product.slug', $variant->product->slug)
|
||||
->assertJsonPath('data.items.0.product.imagen', null)
|
||||
->assertJsonPath('data.items.0.variant.id', $variant->id)
|
||||
->assertJsonPath('data.items.0.variant.attributes', [])
|
||||
->assertJsonPath('data.subtotal', '100.00')
|
||||
->assertJsonPath('data.total', '100.00');
|
||||
}
|
||||
|
||||
public function test_purchase_detail_uses_cart_items_for_pending_payment_purchase(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$user = User::factory()->create([
|
||||
'email' => 'buyer@example.com',
|
||||
]);
|
||||
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);
|
||||
|
||||
$purchase->update([
|
||||
'payment_method' => 'transfer',
|
||||
]);
|
||||
|
||||
app(CheckoutService::class)->completePurchase($purchase);
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->getJson("/api/tenants/sonder/compras/{$purchase->id}")
|
||||
->assertOk()
|
||||
->assertJsonPath('data.status', Purchase::STATUS_PENDING_PAYMENT)
|
||||
->assertJsonPath('data.items_source', 'cart')
|
||||
->assertJsonCount(1, 'data.items')
|
||||
->assertJsonPath('data.items.0.quantity', 2)
|
||||
->assertJsonPath('data.items.0.unit_price', '50.00')
|
||||
->assertJsonPath('data.items.0.line_total', '100.00')
|
||||
->assertJsonPath('data.items.0.product.imagen', null)
|
||||
->assertJsonPath('data.items.0.variant.attributes', [])
|
||||
->assertJsonPath('data.subtotal', '100.00')
|
||||
->assertJsonPath('data.total', '100.00');
|
||||
}
|
||||
|
||||
public function test_purchase_detail_uses_purchase_items_for_paid_purchase_even_without_cart(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$user = User::factory()->create([
|
||||
'email' => 'buyer@example.com',
|
||||
]);
|
||||
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);
|
||||
|
||||
$purchase->update([
|
||||
'payment_method' => 'transfer',
|
||||
]);
|
||||
|
||||
$checkoutService = app(CheckoutService::class);
|
||||
$purchase = $checkoutService->completePurchase($purchase);
|
||||
$checkoutService->confirmPurchase($purchase);
|
||||
$purchase->refresh()->markAsPaid();
|
||||
|
||||
$this->assertSoftDeleted('carritos', [
|
||||
'id' => $purchase->cart_id,
|
||||
]);
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->getJson("/api/tenants/sonder/compras/{$purchase->id}")
|
||||
->assertOk()
|
||||
->assertJsonPath('data.status', Purchase::STATUS_PAID)
|
||||
->assertJsonPath('data.items_source', 'purchase')
|
||||
->assertJsonCount(1, 'data.items')
|
||||
->assertJsonPath('data.items.0.quantity', 2)
|
||||
->assertJsonPath('data.items.0.unit_price', '50.00')
|
||||
->assertJsonPath('data.items.0.line_total', '100.00')
|
||||
->assertJsonPath('data.items.0.product.id', $variant->product->id)
|
||||
->assertJsonPath('data.items.0.product.imagen', null)
|
||||
->assertJsonPath('data.items.0.variant.id', $variant->id)
|
||||
->assertJsonPath('data.items.0.variant.attributes', [])
|
||||
->assertJsonPath('data.subtotal', '100.00')
|
||||
->assertJsonPath('data.total', '100.00');
|
||||
}
|
||||
|
||||
public function test_purchase_detail_prefers_purchase_items_when_both_sources_exist(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$user = User::factory()->create([
|
||||
'email' => 'buyer@example.com',
|
||||
]);
|
||||
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);
|
||||
|
||||
$purchase->items()->create([
|
||||
'producto_variante_id' => $variant->id,
|
||||
'cantidad' => 1,
|
||||
'precio_unitario' => '50.00',
|
||||
'discount_total' => null,
|
||||
'tax_total' => null,
|
||||
'total' => '50.00',
|
||||
]);
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->getJson("/api/tenants/sonder/compras/{$purchase->id}")
|
||||
->assertOk()
|
||||
->assertJsonPath('data.items_source', 'purchase')
|
||||
->assertJsonCount(1, 'data.items')
|
||||
->assertJsonPath('data.items.0.quantity', 1)
|
||||
->assertJsonPath('data.items.0.line_total', '50.00')
|
||||
->assertJsonPath('data.subtotal', '50.00')
|
||||
->assertJsonPath('data.total', '50.00');
|
||||
}
|
||||
|
||||
public function test_purchase_index_returns_empty_items_without_loaded_relations(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$user = User::factory()->create([
|
||||
'email' => 'buyer@example.com',
|
||||
]);
|
||||
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$this->createCheckoutPurchase($user, 'sonder', $variant, 2);
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->getJson('/api/tenants/sonder/compras?status=created')
|
||||
->assertOk()
|
||||
->assertJsonCount(1, 'data')
|
||||
->assertJsonPath('data.0.items_source', null)
|
||||
->assertJsonPath('data.0.items', [])
|
||||
->assertJsonPath('data.0.total', '100.00');
|
||||
}
|
||||
|
||||
public function test_it_rejects_a_cart_from_another_user(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
@@ -290,6 +436,30 @@ class StorePurchaseTest extends TestCase
|
||||
])->load('product');
|
||||
}
|
||||
|
||||
protected function createCheckoutPurchase(
|
||||
User $user,
|
||||
string $tenantCode,
|
||||
ProductVariant $variant,
|
||||
int $quantity,
|
||||
): Purchase {
|
||||
$tenant = Tenant::query()->where('codigo', $tenantCode)->firstOrFail();
|
||||
$cart = Cart::query()->create([
|
||||
'tenant_codigo' => $tenantCode,
|
||||
'user_id' => $user->id,
|
||||
'status' => 'active',
|
||||
]);
|
||||
|
||||
$cart->addItem($variant->id, $quantity);
|
||||
|
||||
return app(CheckoutService::class)->startCheckout($tenant, $user->id, [
|
||||
'cart_id' => $cart->id,
|
||||
'dni' => '987654321',
|
||||
'telefono' => '+54 9 341 555-4321',
|
||||
'nombre_apellido' => 'Juan Perez',
|
||||
'email' => 'juan.perez@example.com',
|
||||
]);
|
||||
}
|
||||
|
||||
protected function createTenant(string $codigo, string $nombre, string $dominio): Tenant
|
||||
{
|
||||
$hdrKey = (string) \Illuminate\Support\Str::uuid();
|
||||
|
||||
Reference in New Issue
Block a user