Compare commits
17 Commits
feature/ch
...
18c80b075b
| Author | SHA1 | Date | |
|---|---|---|---|
| 18c80b075b | |||
| 10157d7c63 | |||
| 716d8e447c | |||
| 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 [
|
return [
|
||||||
'nombre_apellido' => ['required', 'string', 'max:255'],
|
'nombre_apellido' => ['required', 'string', 'max:255'],
|
||||||
'email' => ['required', 'string', 'email', 'max:255', Rule::unique('users', 'email')],
|
'email' => ['required', 'string', 'email', 'max:255', Rule::unique('users', 'email')],
|
||||||
'password' => ['required', 'string', 'confirmed'],
|
'password' => ['required', 'string', 'confirmed', \Illuminate\Validation\Rules\Password::min(8)->mixedCase()->symbols()],
|
||||||
'dni' => ['nullable', 'string', 'max:255'],
|
'dni' => ['nullable', 'string', 'max:255'],
|
||||||
'telefono' => ['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\LogoutController;
|
||||||
use App\Domains\Auth\Controllers\MeController;
|
use App\Domains\Auth\Controllers\MeController;
|
||||||
use App\Domains\Auth\Controllers\RegisterController;
|
use App\Domains\Auth\Controllers\RegisterController;
|
||||||
|
use App\Domains\Auth\Controllers\UpdateProfileController;
|
||||||
use Illuminate\Support\Facades\Route;
|
use Illuminate\Support\Facades\Route;
|
||||||
|
|
||||||
Route::post('/register', RegisterController::class);
|
Route::post('/register', RegisterController::class);
|
||||||
Route::post('/login', LoginController::class);
|
Route::post('/login', LoginController::class);
|
||||||
Route::middleware('auth:sanctum')->post('/logout', LogoutController::class);
|
Route::middleware('auth:sanctum')->post('/logout', LogoutController::class);
|
||||||
Route::middleware('auth:sanctum')->get('/me', MeController::class);
|
Route::middleware('auth:sanctum')->get('/me', MeController::class);
|
||||||
|
Route::middleware('auth:sanctum')->put('/me', UpdateProfileController::class);
|
||||||
|
|||||||
@@ -82,9 +82,9 @@ class Cart extends Model
|
|||||||
return DB::transaction(function () use ($productVariantId, $quantity): CartItem {
|
return DB::transaction(function () use ($productVariantId, $quantity): CartItem {
|
||||||
$variant = $this->resolveScopedVariant($productVariantId, true);
|
$variant = $this->resolveScopedVariant($productVariantId, true);
|
||||||
|
|
||||||
if ($variant->stock_tecnico < $quantity) {
|
if ($variant->tracksInventory() && $variant->availableQuantity() < $quantity) {
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
'cantidad' => "Stock insuficiente para la variante solicitada. Maximo disponible: {$variant->stock_tecnico}.",
|
'cantidad' => "Stock insuficiente para la variante solicitada. Maximo disponible: {$variant->availableQuantity()}.",
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -104,7 +104,7 @@ class Cart extends Model
|
|||||||
$item->save();
|
$item->save();
|
||||||
}
|
}
|
||||||
|
|
||||||
$variant->incrementReservedStock($quantity);
|
$variant->reserveStock($quantity);
|
||||||
|
|
||||||
return $item->fresh();
|
return $item->fresh();
|
||||||
});
|
});
|
||||||
@@ -128,8 +128,8 @@ class Cart extends Model
|
|||||||
$variant = $this->resolveScopedVariant($productVariantId, true);
|
$variant = $this->resolveScopedVariant($productVariantId, true);
|
||||||
$delta = $quantity - $item->cantidad;
|
$delta = $quantity - $item->cantidad;
|
||||||
|
|
||||||
if ($delta > 0 && $variant->stock_tecnico < $delta) {
|
if ($delta > 0 && $variant->tracksInventory() && $variant->availableQuantity() < $delta) {
|
||||||
$maxAvailable = $variant->stock_tecnico + $item->cantidad;
|
$maxAvailable = $variant->availableQuantity() + $item->cantidad;
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
'cantidad' => "El máximo que se puede agregar es {$maxAvailable}.",
|
'cantidad' => "El máximo que se puede agregar es {$maxAvailable}.",
|
||||||
]);
|
]);
|
||||||
@@ -139,7 +139,7 @@ class Cart extends Model
|
|||||||
$item->save();
|
$item->save();
|
||||||
|
|
||||||
if ($delta > 0) {
|
if ($delta > 0) {
|
||||||
$variant->incrementReservedStock($delta);
|
$variant->reserveStock($delta);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($delta < 0) {
|
if ($delta < 0) {
|
||||||
|
|||||||
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
9
app/Domains/Catalog/Enums/InventoryPolicy.php
Normal file
9
app/Domains/Catalog/Enums/InventoryPolicy.php
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Catalog\Enums;
|
||||||
|
|
||||||
|
enum InventoryPolicy: string
|
||||||
|
{
|
||||||
|
case Tracked = 'tracked';
|
||||||
|
case Unlimited = 'unlimited';
|
||||||
|
}
|
||||||
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');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,21 +3,25 @@
|
|||||||
namespace App\Domains\Catalog\Models;
|
namespace App\Domains\Catalog\Models;
|
||||||
|
|
||||||
use App\Domains\Attachable\Models\Attachment;
|
use App\Domains\Attachable\Models\Attachment;
|
||||||
|
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
|
use Illuminate\Database\Eloquent\Casts\Attribute;
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||||
|
|
||||||
use Illuminate\Database\Eloquent\Casts\Attribute;
|
|
||||||
|
|
||||||
#[Fillable([
|
#[Fillable([
|
||||||
'producto_id',
|
'producto_id',
|
||||||
|
'inventory_policy',
|
||||||
'stock_real',
|
'stock_real',
|
||||||
'stock_reservado',
|
'stock_reservado',
|
||||||
'stock',
|
'stock',
|
||||||
'is_placeholder',
|
'is_placeholder',
|
||||||
|
'has_tickets',
|
||||||
|
'minimum_use_date',
|
||||||
|
'maximum_use_date',
|
||||||
])]
|
])]
|
||||||
class ProductVariant extends Model
|
class ProductVariant extends Model
|
||||||
{
|
{
|
||||||
@@ -27,9 +31,20 @@ class ProductVariant extends Model
|
|||||||
|
|
||||||
protected $appends = ['stock_tecnico'];
|
protected $appends = ['stock_tecnico'];
|
||||||
|
|
||||||
|
protected $attributes = [
|
||||||
|
'inventory_policy' => 'tracked',
|
||||||
|
'stock_real' => 0,
|
||||||
|
'stock_reservado' => 0,
|
||||||
|
'cantidad_vendida' => 0,
|
||||||
|
];
|
||||||
|
|
||||||
protected static function booted(): void
|
protected static function booted(): void
|
||||||
{
|
{
|
||||||
static::saving(function (ProductVariant $variant) {
|
static::saving(function (ProductVariant $variant) {
|
||||||
|
if ($variant->exists && $variant->isDirty('inventory_policy')) {
|
||||||
|
throw new \InvalidArgumentException('La politica de inventario no puede modificarse.');
|
||||||
|
}
|
||||||
|
|
||||||
$variant->validateStock();
|
$variant->validateStock();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -44,34 +59,44 @@ class ProductVariant extends Model
|
|||||||
throw new \InvalidArgumentException('El stock reservado no puede ser negativo.');
|
throw new \InvalidArgumentException('El stock reservado no puede ser negativo.');
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($this->stock_reservado > $this->stock_real) {
|
if ($this->cantidad_vendida < 0) {
|
||||||
|
throw new \InvalidArgumentException('La cantidad vendida no puede ser negativa.');
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->tracksInventory() && $this->stock_reservado > $this->stock_real) {
|
||||||
throw new \InvalidArgumentException('El stock reservado no puede ser mayor que el stock real.');
|
throw new \InvalidArgumentException('El stock reservado no puede ser mayor que el stock real.');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public function incrementRealStock(int $amount): void
|
public function tracksInventory(): bool
|
||||||
|
{
|
||||||
|
return $this->inventory_policy === InventoryPolicy::Tracked;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function availableQuantity(): ?int
|
||||||
|
{
|
||||||
|
if (! $this->tracksInventory()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->stock_real - $this->stock_reservado;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function isAvailableForSale(): bool
|
||||||
|
{
|
||||||
|
return ! $this->tracksInventory() || $this->availableQuantity() > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function reserveStock(int $amount): void
|
||||||
{
|
{
|
||||||
if ($amount < 0) {
|
if ($amount < 0) {
|
||||||
throw new \InvalidArgumentException('El monto a incrementar debe ser positivo.');
|
throw new \InvalidArgumentException('El monto a incrementar debe ser positivo.');
|
||||||
}
|
}
|
||||||
$this->stock_real += $amount;
|
|
||||||
$this->save();
|
|
||||||
}
|
|
||||||
|
|
||||||
public function decrementRealStock(int $amount): void
|
if ($this->tracksInventory() && $this->availableQuantity() < $amount) {
|
||||||
{
|
throw new \InvalidArgumentException('No hay suficiente stock disponible para reservar.');
|
||||||
if ($amount < 0) {
|
|
||||||
throw new \InvalidArgumentException('El monto a decrementar debe ser positivo.');
|
|
||||||
}
|
}
|
||||||
$this->stock_real -= $amount;
|
|
||||||
$this->save();
|
|
||||||
}
|
|
||||||
|
|
||||||
public function incrementReservedStock(int $amount): void
|
|
||||||
{
|
|
||||||
if ($amount < 0) {
|
|
||||||
throw new \InvalidArgumentException('El monto a incrementar debe ser positivo.');
|
|
||||||
}
|
|
||||||
$this->stock_reservado += $amount;
|
$this->stock_reservado += $amount;
|
||||||
$this->save();
|
$this->save();
|
||||||
}
|
}
|
||||||
@@ -85,13 +110,13 @@ class ProductVariant extends Model
|
|||||||
$this->save();
|
$this->save();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function confirmReservedStock(int $amount): void
|
public function buy(int $amount): void
|
||||||
{
|
{
|
||||||
if ($amount < 0) {
|
if ($amount < 0) {
|
||||||
throw new \InvalidArgumentException('El monto a confirmar debe ser positivo.');
|
throw new \InvalidArgumentException('El monto a confirmar debe ser positivo.');
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($this->stock_real < $amount) {
|
if ($this->tracksInventory() && $this->stock_real < $amount) {
|
||||||
throw new \InvalidArgumentException('No hay suficiente stock real para confirmar la reserva.');
|
throw new \InvalidArgumentException('No hay suficiente stock real para confirmar la reserva.');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -99,14 +124,18 @@ class ProductVariant extends Model
|
|||||||
throw new \InvalidArgumentException('No hay suficiente stock reservado para confirmar la reserva.');
|
throw new \InvalidArgumentException('No hay suficiente stock reservado para confirmar la reserva.');
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->stock_real -= $amount;
|
if ($this->tracksInventory()) {
|
||||||
|
$this->stock_real -= $amount;
|
||||||
|
}
|
||||||
|
|
||||||
$this->stock_reservado -= $amount;
|
$this->stock_reservado -= $amount;
|
||||||
|
$this->cantidad_vendida += $amount;
|
||||||
$this->save();
|
$this->save();
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function stockTecnico(): Attribute
|
protected function stockTecnico(): Attribute
|
||||||
{
|
{
|
||||||
return Attribute::get(fn () => $this->stock_real - $this->stock_reservado);
|
return Attribute::get(fn (): ?int => $this->availableQuantity());
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function stock(): Attribute
|
protected function stock(): Attribute
|
||||||
@@ -123,9 +152,14 @@ class ProductVariant extends Model
|
|||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'producto_id' => 'integer',
|
'producto_id' => 'integer',
|
||||||
|
'inventory_policy' => InventoryPolicy::class,
|
||||||
'stock_real' => 'integer',
|
'stock_real' => 'integer',
|
||||||
'stock_reservado' => 'integer',
|
'stock_reservado' => 'integer',
|
||||||
|
'cantidad_vendida' => 'integer',
|
||||||
'is_placeholder' => 'boolean',
|
'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'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
namespace App\Domains\Catalog\Requests;
|
namespace App\Domains\Catalog\Requests;
|
||||||
|
|
||||||
|
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||||
use App\Domains\Shared\Rules\ImageOrBase64Rule;
|
use App\Domains\Shared\Rules\ImageOrBase64Rule;
|
||||||
use Illuminate\Foundation\Http\FormRequest;
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
use Illuminate\Validation\Rule;
|
use Illuminate\Validation\Rule;
|
||||||
@@ -32,6 +33,8 @@ class StoreProductRequest extends FormRequest
|
|||||||
'descripcion' => ['nullable', 'string'],
|
'descripcion' => ['nullable', 'string'],
|
||||||
'precio' => ['required', 'numeric', 'min:0'],
|
'precio' => ['required', 'numeric', 'min:0'],
|
||||||
'stock' => ['sometimes', 'integer', 'min:0'],
|
'stock' => ['sometimes', 'integer', 'min:0'],
|
||||||
|
'inventory_policy' => ['sometimes', Rule::enum(InventoryPolicy::class)],
|
||||||
|
'cantidad_vendida' => ['prohibited'],
|
||||||
'attribute_ids' => ['sometimes', 'array'],
|
'attribute_ids' => ['sometimes', 'array'],
|
||||||
'attribute_ids.*' => [
|
'attribute_ids.*' => [
|
||||||
'required',
|
'required',
|
||||||
@@ -41,7 +44,7 @@ class StoreProductRequest extends FormRequest
|
|||||||
),
|
),
|
||||||
],
|
],
|
||||||
'images' => ['sometimes', 'nullable', 'array'],
|
'images' => ['sometimes', 'nullable', 'array'],
|
||||||
'images.*' => ['required', new ImageOrBase64Rule()],
|
'images.*' => ['required', new ImageOrBase64Rule],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
namespace App\Domains\Catalog\Requests;
|
namespace App\Domains\Catalog\Requests;
|
||||||
|
|
||||||
|
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||||
use App\Domains\Shared\Rules\ImageOrBase64Rule;
|
use App\Domains\Shared\Rules\ImageOrBase64Rule;
|
||||||
use Illuminate\Foundation\Http\FormRequest;
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
use Illuminate\Validation\Rule;
|
use Illuminate\Validation\Rule;
|
||||||
@@ -20,6 +21,8 @@ class StoreProductVariantRequest extends FormRequest
|
|||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'stock' => ['sometimes', 'integer', 'min:0'],
|
'stock' => ['sometimes', 'integer', 'min:0'],
|
||||||
|
'inventory_policy' => ['sometimes', Rule::enum(InventoryPolicy::class)],
|
||||||
|
'cantidad_vendida' => ['prohibited'],
|
||||||
'definitions' => ['sometimes', 'array'],
|
'definitions' => ['sometimes', 'array'],
|
||||||
'definitions.*.products_attribute_id' => [
|
'definitions.*.products_attribute_id' => [
|
||||||
'required',
|
'required',
|
||||||
@@ -31,7 +34,10 @@ class StoreProductVariantRequest extends FormRequest
|
|||||||
],
|
],
|
||||||
'definitions.*.value' => ['nullable', 'string'],
|
'definitions.*.value' => ['nullable', 'string'],
|
||||||
'images' => ['sometimes', 'nullable', 'array'],
|
'images' => ['sometimes', 'nullable', 'array'],
|
||||||
'images.*' => ['required', new ImageOrBase64Rule()],
|
'images.*' => ['required', new ImageOrBase64Rule],
|
||||||
|
'has_tickets' => ['boolean'],
|
||||||
|
'minimum_use_date' => ['nullable', 'date'],
|
||||||
|
'maximum_use_date' => ['nullable', 'date', 'after_or_equal:minimum_use_date'],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
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'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -20,6 +20,8 @@ class UpdateProductVariantRequest extends FormRequest
|
|||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'stock' => ['sometimes', 'integer', 'min:0'],
|
'stock' => ['sometimes', 'integer', 'min:0'],
|
||||||
|
'inventory_policy' => ['prohibited'],
|
||||||
|
'cantidad_vendida' => ['prohibited'],
|
||||||
'definitions' => ['sometimes', 'array'],
|
'definitions' => ['sometimes', 'array'],
|
||||||
'definitions.*.products_attribute_id' => [
|
'definitions.*.products_attribute_id' => [
|
||||||
'required',
|
'required',
|
||||||
@@ -31,7 +33,10 @@ class UpdateProductVariantRequest extends FormRequest
|
|||||||
],
|
],
|
||||||
'definitions.*.value' => ['nullable', 'string'],
|
'definitions.*.value' => ['nullable', 'string'],
|
||||||
'images' => ['sometimes', 'nullable', 'array'],
|
'images' => ['sometimes', 'nullable', 'array'],
|
||||||
'images.*' => ['required', new ImageOrBase64Rule()],
|
'images.*' => ['required', new ImageOrBase64Rule],
|
||||||
|
'has_tickets' => ['boolean'],
|
||||||
|
'minimum_use_date' => ['nullable', 'date'],
|
||||||
|
'maximum_use_date' => ['nullable', 'date', 'after_or_equal:minimum_use_date'],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,
|
'precio' => $this->precio,
|
||||||
'category' => $this->whenLoaded('category', fn () => $this->category?->nombre),
|
'category' => $this->whenLoaded('category', fn () => $this->category?->nombre),
|
||||||
'brand' => $this->whenLoaded('brand', fn () => $this->brand?->nombre),
|
'brand' => $this->whenLoaded('brand', fn () => $this->brand?->nombre),
|
||||||
|
|
||||||
'images' => $this->whenLoaded('attachments', fn () => $this->attachments
|
'images' => $this->whenLoaded('attachments', fn () => $this->attachments
|
||||||
->map(fn ($attachment) => $attachment->getTemporaryUrl(1440))
|
->map(fn ($attachment) => $attachment->getTemporaryUrl(1440))
|
||||||
->values()
|
->values()
|
||||||
@@ -34,7 +35,9 @@ class ProductResource extends JsonResource
|
|||||||
'variants_map' => $this->whenLoaded('variants', fn () => $this->variants
|
'variants_map' => $this->whenLoaded('variants', fn () => $this->variants
|
||||||
->map(fn ($variant) => [
|
->map(fn ($variant) => [
|
||||||
'variant_id' => $variant->id,
|
'variant_id' => $variant->id,
|
||||||
|
'inventory_policy' => $variant->inventory_policy->value,
|
||||||
'cantidad_maxima' => $variant->stock_tecnico,
|
'cantidad_maxima' => $variant->stock_tecnico,
|
||||||
|
'cantidad_vendida' => $variant->cantidad_vendida,
|
||||||
'attributes' => $variant->definitions
|
'attributes' => $variant->definitions
|
||||||
->mapWithKeys(fn ($definition) => [
|
->mapWithKeys(fn ($definition) => [
|
||||||
$definition->productAttribute?->attribute?->codigo => $definition->value,
|
$definition->productAttribute?->attribute?->codigo => $definition->value,
|
||||||
|
|||||||
@@ -18,7 +18,12 @@ class ProductVariantResource extends JsonResource
|
|||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'id' => $this->id,
|
'id' => $this->id,
|
||||||
|
'inventory_policy' => $this->inventory_policy->value,
|
||||||
'cantidad_maxima' => $this->stock_tecnico,
|
'cantidad_maxima' => $this->stock_tecnico,
|
||||||
|
'cantidad_vendida' => $this->cantidad_vendida,
|
||||||
|
'has_tickets' => $this->has_tickets,
|
||||||
|
'minimum_use_date' => $this->minimum_use_date,
|
||||||
|
'maximum_use_date' => $this->maximum_use_date,
|
||||||
'product' => ProductResource::make($this->whenLoaded('product')),
|
'product' => ProductResource::make($this->whenLoaded('product')),
|
||||||
'definitions' => $this->whenLoaded(
|
'definitions' => $this->whenLoaded(
|
||||||
'definitions',
|
'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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
namespace App\Domains\Catalog\Services;
|
namespace App\Domains\Catalog\Services;
|
||||||
|
|
||||||
use App\Domains\Attachable\Services\AttachmentService;
|
use App\Domains\Attachable\Services\AttachmentService;
|
||||||
|
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||||
use App\Domains\Catalog\Models\Attribute;
|
use App\Domains\Catalog\Models\Attribute;
|
||||||
use App\Domains\Catalog\Models\Product;
|
use App\Domains\Catalog\Models\Product;
|
||||||
use App\Domains\Catalog\Models\ProductVariant;
|
use App\Domains\Catalog\Models\ProductVariant;
|
||||||
@@ -28,7 +29,8 @@ class ProductService
|
|||||||
$attributeIds = $data['attribute_ids'] ?? [];
|
$attributeIds = $data['attribute_ids'] ?? [];
|
||||||
$images = $data['images'] ?? [];
|
$images = $data['images'] ?? [];
|
||||||
$stock = $data['stock'] ?? 0;
|
$stock = $data['stock'] ?? 0;
|
||||||
unset($data['attribute_ids'], $data['images'], $data['stock']);
|
$inventoryPolicy = $data['inventory_policy'] ?? InventoryPolicy::Tracked->value;
|
||||||
|
unset($data['attribute_ids'], $data['images'], $data['stock'], $data['inventory_policy']);
|
||||||
|
|
||||||
/** @var Product $product */
|
/** @var Product $product */
|
||||||
$product = Product::query()->create([
|
$product = Product::query()->create([
|
||||||
@@ -45,6 +47,7 @@ class ProductService
|
|||||||
// Create default variant with stock
|
// Create default variant with stock
|
||||||
$this->createVariant($product, [
|
$this->createVariant($product, [
|
||||||
'stock' => $stock,
|
'stock' => $stock,
|
||||||
|
'inventory_policy' => $inventoryPolicy,
|
||||||
'is_placeholder' => true,
|
'is_placeholder' => true,
|
||||||
'definitions' => [],
|
'definitions' => [],
|
||||||
]);
|
]);
|
||||||
@@ -179,6 +182,7 @@ class ProductService
|
|||||||
if ($product->variants()->count() === 0) {
|
if ($product->variants()->count() === 0) {
|
||||||
$product->createVariant([
|
$product->createVariant([
|
||||||
'stock' => 0,
|
'stock' => 0,
|
||||||
|
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||||
'is_placeholder' => true,
|
'is_placeholder' => true,
|
||||||
'definitions' => [],
|
'definitions' => [],
|
||||||
]);
|
]);
|
||||||
@@ -327,13 +331,13 @@ class ProductService
|
|||||||
|
|
||||||
$selectedVariant = $variantId !== null
|
$selectedVariant = $variantId !== null
|
||||||
? $product->variants->firstWhere('id', $variantId)
|
? $product->variants->firstWhere('id', $variantId)
|
||||||
: $product->variants->first(fn (ProductVariant $variant) => $variant->stock_tecnico > 0);
|
: $product->variants->first(fn (ProductVariant $variant) => $variant->isAvailableForSale());
|
||||||
|
|
||||||
if ($variantId !== null && $selectedVariant === null) {
|
if ($variantId !== null && $selectedVariant === null) {
|
||||||
throw new NotFoundHttpException('Product variant not found for product.');
|
throw new NotFoundHttpException('Product variant not found for product.');
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($variantId !== null && $selectedVariant->stock_tecnico <= 0) {
|
if ($variantId !== null && ! $selectedVariant->isAvailableForSale()) {
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
'variant_id' => 'La variante seleccionada no tiene stock.',
|
'variant_id' => 'La variante seleccionada no tiene stock.',
|
||||||
]);
|
]);
|
||||||
|
|||||||
@@ -1,13 +1,17 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
use App\Domains\Catalog\Controllers\BrandController;
|
use App\Domains\Catalog\Controllers\BrandController;
|
||||||
|
use App\Domains\Catalog\Controllers\CatalogController;
|
||||||
use App\Domains\Catalog\Controllers\CategoryController;
|
use App\Domains\Catalog\Controllers\CategoryController;
|
||||||
use App\Domains\Catalog\Controllers\ProductController;
|
use App\Domains\Catalog\Controllers\ProductController;
|
||||||
use App\Domains\Catalog\Controllers\AttributeController;
|
use App\Domains\Catalog\Controllers\AttributeController;
|
||||||
use App\Domains\Catalog\Controllers\ProductVariantController;
|
use App\Domains\Catalog\Controllers\ProductVariantController;
|
||||||
|
use App\Domains\Catalog\Controllers\FeaturedGroupController;
|
||||||
|
use App\Domains\Catalog\Controllers\FeaturedVariantController;
|
||||||
use Illuminate\Support\Facades\Route;
|
use Illuminate\Support\Facades\Route;
|
||||||
|
|
||||||
Route::prefix('tenants/{tenant:codigo}')->group(function (): void {
|
Route::prefix('tenants/{tenant:codigo}')->group(function (): void {
|
||||||
|
Route::get('catalog', [CatalogController::class, 'index']);
|
||||||
Route::apiResource('marcas', BrandController::class)->parameters(['marcas' => 'marca']);
|
Route::apiResource('marcas', BrandController::class)->parameters(['marcas' => 'marca']);
|
||||||
Route::apiResource('categorias', CategoryController::class)->parameters(['categorias' => 'categoria']);
|
Route::apiResource('categorias', CategoryController::class)->parameters(['categorias' => 'categoria']);
|
||||||
Route::apiResource('productos', ProductController::class);
|
Route::apiResource('productos', ProductController::class);
|
||||||
@@ -17,4 +21,11 @@ Route::prefix('tenants/{tenant:codigo}')->group(function (): void {
|
|||||||
'productos' => 'producto',
|
'productos' => 'producto',
|
||||||
'variants' => 'productVariant',
|
'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(
|
return PurchaseResource::collection(
|
||||||
Purchase::query()
|
Purchase::query()
|
||||||
->with(['items.variant.product', 'items.variant.definitions.productAttribute.attribute'])
|
|
||||||
->where('tenant_codigo', $tenant->codigo)
|
->where('tenant_codigo', $tenant->codigo)
|
||||||
->where('user_id', $request->user()->id)
|
->where('user_id', $request->user()->id)
|
||||||
->when($request->query('status'), function ($query, $status) {
|
->when($request->query('status'), function ($query, $status) {
|
||||||
@@ -48,7 +47,7 @@ class PurchaseController extends Controller
|
|||||||
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
|
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
|
||||||
|
|
||||||
return PurchaseResource::make(
|
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 $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',
|
||||||
|
];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,12 +2,13 @@
|
|||||||
|
|
||||||
namespace App\Domains\Purchase\Resources;
|
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\Request;
|
||||||
use Illuminate\Http\Resources\Json\JsonResource;
|
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
|
class PurchaseItemResource extends JsonResource
|
||||||
{
|
{
|
||||||
@@ -18,24 +19,90 @@ class PurchaseItemResource extends JsonResource
|
|||||||
{
|
{
|
||||||
$variant = $this->variant;
|
$variant = $this->variant;
|
||||||
$product = $variant?->product;
|
$product = $variant?->product;
|
||||||
|
$quantity = (int) ($this->cantidad ?? 0);
|
||||||
|
$unitPrice = $this->resolveUnitPrice();
|
||||||
|
$lineTotal = $this->resolveLineTotal($unitPrice, $quantity);
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'id' => $this->id,
|
'id' => $this->id,
|
||||||
'cantidad' => $this->cantidad,
|
'quantity' => $quantity,
|
||||||
'precio_unitario' => $this->formatMoney($this->precio_unitario),
|
'unit_price' => $this->formatMoney($unitPrice),
|
||||||
'total' => $this->formatMoney($this->total),
|
'line_total' => $this->formatMoney($lineTotal),
|
||||||
'product' => $product === null ? null : [
|
'product' => $product === null ? null : [
|
||||||
'id' => $product->id,
|
'id' => $product->id,
|
||||||
'nombre' => $product->nombre,
|
'nombre' => $product->nombre,
|
||||||
'slug' => $product->slug,
|
'slug' => $product->slug,
|
||||||
|
'imagen' => $this->resolveImageUrl(),
|
||||||
],
|
],
|
||||||
'variant' => $variant === null ? null : [
|
'variant' => $variant === null ? null : [
|
||||||
'id' => $variant->id,
|
'id' => $variant->id,
|
||||||
'definitions' => ProductVariantDefinitionResource::collection($variant->definitions),
|
'attributes' => $this->resolveAttributes(),
|
||||||
],
|
],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected function resolveUnitPrice(): float
|
||||||
|
{
|
||||||
|
if ($this->resource instanceof PurchaseItem) {
|
||||||
|
return (float) ($this->precio_unitario ?? 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->resource instanceof CartItem) {
|
||||||
|
return (float) ($this->variant?->product?->precio ?? 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(): ?string
|
||||||
|
{
|
||||||
|
$variant = $this->variant;
|
||||||
|
|
||||||
|
if ($variant === null || ! $variant->relationLoaded('attachments')) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$attachment = $variant->attachments->first();
|
||||||
|
|
||||||
|
if ($attachment === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $attachment->getTemporaryUrl(1440);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, array{name: string, value: mixed}>
|
||||||
|
*/
|
||||||
|
protected function resolveAttributes(): array
|
||||||
|
{
|
||||||
|
$variant = $this->variant;
|
||||||
|
|
||||||
|
if ($variant === null || ! $variant->relationLoaded('definitions')) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $variant->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
|
protected function formatMoney(float|int|string|null $amount): ?string
|
||||||
{
|
{
|
||||||
if ($amount === null) {
|
if ($amount === null) {
|
||||||
|
|||||||
@@ -2,8 +2,11 @@
|
|||||||
|
|
||||||
namespace App\Domains\Purchase\Resources;
|
namespace App\Domains\Purchase\Resources;
|
||||||
|
|
||||||
|
use App\Domains\Cart\Models\CartItem;
|
||||||
|
use App\Domains\Purchase\Models\PurchaseItem;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Http\Resources\Json\JsonResource;
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @mixin \App\Domains\Purchase\Models\Purchase
|
* @mixin \App\Domains\Purchase\Models\Purchase
|
||||||
@@ -15,20 +18,18 @@ class PurchaseResource extends JsonResource
|
|||||||
*/
|
*/
|
||||||
public function toArray(Request $request): array
|
public function toArray(Request $request): array
|
||||||
{
|
{
|
||||||
$items = $this->resource->relationLoaded('items')
|
[$items, $itemsSource] = $this->resolveItems();
|
||||||
? $this->resource->getRelation('items')
|
|
||||||
: collect();
|
|
||||||
|
|
||||||
$subtotal = $items->isNotEmpty()
|
$subtotal = $items->isNotEmpty()
|
||||||
? $items->reduce(
|
? $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,
|
0.0,
|
||||||
)
|
)
|
||||||
: (float) ($this->total ?? 0);
|
: (float) ($this->total ?? 0);
|
||||||
|
|
||||||
$total = $items->isNotEmpty()
|
$total = $items->isNotEmpty()
|
||||||
? $items->reduce(
|
? $items->reduce(
|
||||||
fn (float $carry, $item): float => $carry + (float) $item->total,
|
fn (float $carry, PurchaseItem|CartItem $item): float => $carry + $this->resolveItemTotal($item),
|
||||||
0.0,
|
0.0,
|
||||||
)
|
)
|
||||||
: (float) ($this->total ?? 0);
|
: (float) ($this->total ?? 0);
|
||||||
@@ -38,18 +39,66 @@ class PurchaseResource extends JsonResource
|
|||||||
'cart_id' => $this->cart_id,
|
'cart_id' => $this->cart_id,
|
||||||
'tenant_codigo' => $this->tenant_codigo,
|
'tenant_codigo' => $this->tenant_codigo,
|
||||||
'user_id' => $this->user_id,
|
'user_id' => $this->user_id,
|
||||||
|
'created_at' => $this->created_at,
|
||||||
'status' => $this->status,
|
'status' => $this->status,
|
||||||
'payment_method' => $this->payment_method,
|
'payment_method' => $this->payment_method,
|
||||||
'dni' => $this->dni,
|
'dni' => $this->dni,
|
||||||
'telefono' => $this->telefono,
|
'telefono' => $this->telefono,
|
||||||
'nombre_apellido' => $this->nombre_apellido,
|
'nombre_apellido' => $this->nombre_apellido,
|
||||||
'email' => $this->email,
|
'email' => $this->email,
|
||||||
|
'items_source' => $itemsSource,
|
||||||
'items' => PurchaseItemResource::collection($items),
|
'items' => PurchaseItemResource::collection($items),
|
||||||
'subtotal' => $this->formatMoney($subtotal),
|
'subtotal' => $this->formatMoney($subtotal),
|
||||||
'total' => $this->formatMoney($total),
|
'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
|
protected function formatMoney(float|int|string|null $amount): string
|
||||||
{
|
{
|
||||||
return number_format((float) ($amount ?? 0), 2, '.', '');
|
return number_format((float) ($amount ?? 0), 2, '.', '');
|
||||||
|
|||||||
@@ -97,6 +97,15 @@ class CheckoutService
|
|||||||
public function confirmPurchase(Purchase $purchase): void
|
public function confirmPurchase(Purchase $purchase): void
|
||||||
{
|
{
|
||||||
DB::transaction(function () use ($purchase): void {
|
DB::transaction(function () use ($purchase): void {
|
||||||
|
/** @var Purchase $purchase */
|
||||||
|
$purchase = Purchase::query()
|
||||||
|
->lockForUpdate()
|
||||||
|
->findOrFail($purchase->getKey());
|
||||||
|
|
||||||
|
if ($purchase->items()->exists()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
/** @var Cart|null $cart */
|
/** @var Cart|null $cart */
|
||||||
$cart = $purchase->cart()->lockForUpdate()->first();
|
$cart = $purchase->cart()->lockForUpdate()->first();
|
||||||
|
|
||||||
@@ -114,10 +123,6 @@ class CheckoutService
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($purchase->items()->exists()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
$cartItems->load('variant.product');
|
$cartItems->load('variant.product');
|
||||||
$variants = $this->resolveTenantVariants($purchase->tenant, $cartItems);
|
$variants = $this->resolveTenantVariants($purchase->tenant, $cartItems);
|
||||||
$purchaseItemsPayload = $this->buildPurchaseItemsPayload($cartItems, $variants);
|
$purchaseItemsPayload = $this->buildPurchaseItemsPayload($cartItems, $variants);
|
||||||
@@ -158,7 +163,7 @@ class CheckoutService
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* @param Collection<int, CartItem> $cartItems
|
* @param Collection<int, CartItem> $cartItems
|
||||||
* @return \Illuminate\Support\Collection<int, ProductVariant>
|
* @return Collection<int, ProductVariant>
|
||||||
*/
|
*/
|
||||||
protected function resolveCheckoutCart(Tenant $tenant, int $userId, int $cartId): Cart
|
protected function resolveCheckoutCart(Tenant $tenant, int $userId, int $cartId): Cart
|
||||||
{
|
{
|
||||||
@@ -218,7 +223,7 @@ class CheckoutService
|
|||||||
$quantity = (int) $item->cantidad;
|
$quantity = (int) $item->cantidad;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$variant->confirmReservedStock($quantity);
|
$variant->buy($quantity);
|
||||||
} catch (\InvalidArgumentException $exception) {
|
} catch (\InvalidArgumentException $exception) {
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
'cart_id' => 'The selected cart has inconsistent stock state.',
|
'cart_id' => 'The selected cart has inconsistent stock state.',
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ class BootstrapTenantController extends Controller
|
|||||||
$dominio = $request->validated('dominio');
|
$dominio = $request->validated('dominio');
|
||||||
|
|
||||||
return TenantResource::make(
|
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',
|
'footer_bg_color',
|
||||||
'header_logo_id',
|
'header_logo_id',
|
||||||
'footer_logo_id',
|
'footer_logo_id',
|
||||||
|
'hero_config',
|
||||||
|
'event_config',
|
||||||
])]
|
])]
|
||||||
class Tenant extends Model
|
class Tenant extends Model
|
||||||
{
|
{
|
||||||
@@ -32,6 +34,19 @@ class Tenant extends Model
|
|||||||
return 'codigo';
|
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>
|
* @return BelongsTo<Attachment, $this>
|
||||||
*/
|
*/
|
||||||
@@ -48,9 +63,29 @@ class Tenant extends Model
|
|||||||
return $this->belongsTo(Attachment::class, 'footer_logo_id');
|
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
|
public function productos(): HasMany
|
||||||
{
|
{
|
||||||
return $this->hasMany(Product::class, 'tenant_codigo', 'codigo');
|
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})$/'],
|
'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,
|
'header_logo' => $logoRule,
|
||||||
'footer_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})$/'],
|
'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,
|
'header_logo' => $logoRule,
|
||||||
'footer_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
|
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 [
|
return [
|
||||||
'id' => $this->id,
|
'id' => $this->id,
|
||||||
'codigo' => $this->codigo,
|
'codigo' => $this->codigo,
|
||||||
@@ -29,6 +35,9 @@ class TenantResource extends JsonResource
|
|||||||
// 1 day
|
// 1 day
|
||||||
'header_logo' => $this->headerLogo?->getTemporaryUrl(1440),
|
'header_logo' => $this->headerLogo?->getTemporaryUrl(1440),
|
||||||
'footer_logo' => $this->footerLogo?->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 {
|
return DB::transaction(function () use ($data): Tenant {
|
||||||
$headerLogo = $data['header_logo'] ?? null;
|
$headerLogo = $data['header_logo'] ?? null;
|
||||||
$footerLogo = $data['footer_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;
|
$headerAttachmentId = null;
|
||||||
if ($headerLogo) {
|
if ($headerLogo) {
|
||||||
@@ -52,6 +53,18 @@ class TenantService
|
|||||||
$data['header_logo_id'] = $headerAttachmentId;
|
$data['header_logo_id'] = $headerAttachmentId;
|
||||||
$data['footer_logo_id'] = $footerAttachmentId;
|
$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 */
|
/** @var Tenant $tenant */
|
||||||
$tenant = Tenant::query()->create($data);
|
$tenant = Tenant::query()->create($data);
|
||||||
|
|
||||||
@@ -71,10 +84,14 @@ class TenantService
|
|||||||
return DB::transaction(function () use ($tenant, $data): Tenant {
|
return DB::transaction(function () use ($tenant, $data): Tenant {
|
||||||
$hasHeaderLogoKey = array_key_exists('header_logo', $data);
|
$hasHeaderLogoKey = array_key_exists('header_logo', $data);
|
||||||
$hasFooterLogoKey = array_key_exists('footer_logo', $data);
|
$hasFooterLogoKey = array_key_exists('footer_logo', $data);
|
||||||
|
$hasHeroBgImageKey = array_key_exists('hero_bg_image', $data);
|
||||||
$headerLogo = $data['header_logo'] ?? null;
|
$headerLogo = $data['header_logo'] ?? null;
|
||||||
$footerLogo = $data['footer_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);
|
$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();
|
$tenant->save();
|
||||||
|
|
||||||
return $tenant;
|
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,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('productos_variantes', function (Blueprint $table) {
|
||||||
|
$table->string('inventory_policy')->default('tracked')->after('producto_id');
|
||||||
|
$table->unsignedBigInteger('cantidad_vendida')->default(0)->after('stock_reservado');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reverse the migrations.
|
||||||
|
*/
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('productos_variantes', function (Blueprint $table) {
|
||||||
|
$table->dropColumn(['inventory_policy', 'cantidad_vendida']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -110,6 +110,29 @@ class AttributeSeeder extends Seeder
|
|||||||
],
|
],
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
// Seed Fecha attribute
|
||||||
|
$existingFecha = Attribute::query()
|
||||||
|
->where('tenant_codigo', $tenant->codigo)
|
||||||
|
->where('codigo', 'fecha')
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if ($existingFecha) {
|
||||||
|
Product::deleteAttribute($existingFecha);
|
||||||
|
}
|
||||||
|
|
||||||
|
Product::createAttribute($tenant, [
|
||||||
|
'codigo' => 'fecha',
|
||||||
|
'nombre' => 'Fecha',
|
||||||
|
'type' => FieldType::Select->value,
|
||||||
|
'is_required' => true,
|
||||||
|
'options' => [
|
||||||
|
['value' => '2026-10-09', 'label' => '09/10/2026', 'sort_order' => 1],
|
||||||
|
['value' => '2026-10-10', 'label' => '10/10/2026', 'sort_order' => 2],
|
||||||
|
['value' => '2026-10-11', 'label' => '11/10/2026', 'sort_order' => 3],
|
||||||
|
['value' => '2026-10-12', 'label' => '12/10/2026', 'sort_order' => 4],
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,7 +28,9 @@ class DatabaseSeeder extends Seeder
|
|||||||
CategorySeeder::class,
|
CategorySeeder::class,
|
||||||
BrandSeeder::class,
|
BrandSeeder::class,
|
||||||
ProductCatalogFromImagesSeeder::class,
|
ProductCatalogFromImagesSeeder::class,
|
||||||
|
FiestaFutbolInfantilProductSeeder::class,
|
||||||
TelepagosIntegrationSeeder::class,
|
TelepagosIntegrationSeeder::class,
|
||||||
|
MenuSeeder::class,
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
95
database/seeders/FiestaFutbolInfantilProductSeeder.php
Normal file
95
database/seeders/FiestaFutbolInfantilProductSeeder.php
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Database\Seeders;
|
||||||
|
|
||||||
|
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||||
|
use App\Domains\Catalog\Models\Attribute;
|
||||||
|
use App\Domains\Catalog\Models\Category;
|
||||||
|
use App\Domains\Catalog\Models\Product;
|
||||||
|
use App\Domains\Catalog\Services\ProductService;
|
||||||
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
|
use Illuminate\Database\Seeder;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use RuntimeException;
|
||||||
|
|
||||||
|
class FiestaFutbolInfantilProductSeeder extends Seeder
|
||||||
|
{
|
||||||
|
public function __construct(private readonly ProductService $productService) {}
|
||||||
|
|
||||||
|
public function run(): void
|
||||||
|
{
|
||||||
|
$tenant = Tenant::query()->where('codigo', 'fiesta_futbol_infantil')->first();
|
||||||
|
|
||||||
|
if (! $tenant) {
|
||||||
|
throw new RuntimeException("Tenant 'fiesta_futbol_infantil' no encontrado.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete existing products for this tenant
|
||||||
|
$existingProducts = Product::query()
|
||||||
|
->where('tenant_codigo', $tenant->codigo)
|
||||||
|
->get();
|
||||||
|
|
||||||
|
foreach ($existingProducts as $product) {
|
||||||
|
$this->productService->delete($product);
|
||||||
|
}
|
||||||
|
|
||||||
|
// We need a category, let's just use 'Accesorios' or create an 'Entradas' category
|
||||||
|
$category = Category::firstOrCreate(['nombre' => 'Entradas', 'tenant_code' => null]);
|
||||||
|
|
||||||
|
$dates = ['2026-10-09', '2026-10-10', '2026-10-11', '2026-10-12'];
|
||||||
|
|
||||||
|
// 1. Entrada General
|
||||||
|
$entrada = $this->productService->create($tenant, [
|
||||||
|
'categoria_id' => $category->id,
|
||||||
|
'slug' => 'entrada-general',
|
||||||
|
'nombre' => 'Entrada General',
|
||||||
|
'descripcion' => 'Acceso total al predio. No incluye acceso a estacionamiento. Niños menores de 5 años ingresan gratis.',
|
||||||
|
'precio' => 10000,
|
||||||
|
'stock' => 0,
|
||||||
|
'inventory_policy' => InventoryPolicy::Unlimited->value,
|
||||||
|
'attribute_ids' => [Attribute::where('codigo', 'fecha')->where('tenant_codigo', $tenant->codigo)->first()?->id],
|
||||||
|
]);
|
||||||
|
|
||||||
|
foreach ($dates as $date) {
|
||||||
|
$this->productService->createVariant($entrada, [
|
||||||
|
'stock' => 0,
|
||||||
|
'inventory_policy' => InventoryPolicy::Unlimited->value,
|
||||||
|
'has_tickets' => true,
|
||||||
|
'minimum_use_date' => $date.' 00:00:00',
|
||||||
|
'maximum_use_date' => $date.' 23:59:59',
|
||||||
|
'definitions' => [
|
||||||
|
[
|
||||||
|
'products_attribute_id' => DB::table('products_attributes')
|
||||||
|
->where('product_id', $entrada->id)
|
||||||
|
->first()?->id,
|
||||||
|
'value' => $date,
|
||||||
|
],
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Other products without variants
|
||||||
|
$gastronomiaCategory = Category::firstOrCreate(['nombre' => 'Gastronomía', 'tenant_code' => null]);
|
||||||
|
|
||||||
|
$simpleProducts = [
|
||||||
|
['slug' => 'hamburguesa-papa-frita', 'nombre' => 'Hamburguesa con papa frita', 'precio' => 8000, 'cat' => $gastronomiaCategory->id],
|
||||||
|
['slug' => 'pancho', 'nombre' => 'Pancho', 'precio' => 4000, 'cat' => $gastronomiaCategory->id],
|
||||||
|
['slug' => 'coca-cola-500ml', 'nombre' => 'Coca Cola 500ml', 'precio' => 3000, 'cat' => $gastronomiaCategory->id],
|
||||||
|
['slug' => 'agua-mineral-1l', 'nombre' => 'Agua Mineral 1L', 'precio' => 2500, 'cat' => $gastronomiaCategory->id],
|
||||||
|
['slug' => 'estacionamiento-auto', 'nombre' => 'Estacionamiento Auto', 'precio' => 5000, 'cat' => $category->id],
|
||||||
|
['slug' => 'estacionamiento-moto', 'nombre' => 'Estacionamiento Moto', 'precio' => 2000, 'cat' => $category->id],
|
||||||
|
];
|
||||||
|
|
||||||
|
foreach ($simpleProducts as $p) {
|
||||||
|
$this->productService->create($tenant, [
|
||||||
|
'categoria_id' => $p['cat'],
|
||||||
|
'slug' => $p['slug'],
|
||||||
|
'nombre' => $p['nombre'],
|
||||||
|
'descripcion' => $p['nombre'],
|
||||||
|
'precio' => $p['precio'],
|
||||||
|
'stock' => 0,
|
||||||
|
'inventory_policy' => InventoryPolicy::Unlimited->value,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
namespace Database\Seeders;
|
namespace Database\Seeders;
|
||||||
|
|
||||||
|
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||||
use App\Domains\Catalog\Models\Attribute;
|
use App\Domains\Catalog\Models\Attribute;
|
||||||
use App\Domains\Catalog\Models\Brand;
|
use App\Domains\Catalog\Models\Brand;
|
||||||
use App\Domains\Catalog\Models\Category;
|
use App\Domains\Catalog\Models\Category;
|
||||||
@@ -64,9 +65,7 @@ class ProductCatalogFromImagesSeeder extends Seeder
|
|||||||
'istockphoto-1675347112-2048x2048.jpg',
|
'istockphoto-1675347112-2048x2048.jpg',
|
||||||
];
|
];
|
||||||
|
|
||||||
public function __construct(private readonly ProductService $productService)
|
public function __construct(private readonly ProductService $productService) {}
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Run the database seeds.
|
* Run the database seeds.
|
||||||
@@ -162,9 +161,9 @@ class ProductCatalogFromImagesSeeder extends Seeder
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param array{attribute_codes: array<int, string>, brand_name: string|null, category_name: string, color: string|null, description: string, product_name: string, product_slug: string, type: string} $metadata
|
* @param array{attribute_codes: array<int, string>, brand_name: string|null, category_name: string, color: string|null, description: string, product_name: string, product_slug: string, type: string} $metadata
|
||||||
* @param array{price: int} $pricing
|
* @param array{price: int} $pricing
|
||||||
* @param array<int, array{files: array<int, \SplFileInfo>, group_key: string, metadata: array{attribute_codes: array<int, string>, brand_name: string|null, category_name: string, color: string|null, description: string, product_name: string, product_slug: string, type: string}, stock: int}> $variantGroups
|
* @param array<int, array{files: array<int, \SplFileInfo>, group_key: string, metadata: array{attribute_codes: array<int, string>, brand_name: string|null, category_name: string, color: string|null, description: string, product_name: string, product_slug: string, type: string}, stock: int}> $variantGroups
|
||||||
*/
|
*/
|
||||||
private function seedProduct(Tenant $tenant, array $metadata, array $pricing, array $variantGroups): void
|
private function seedProduct(Tenant $tenant, array $metadata, array $pricing, array $variantGroups): void
|
||||||
{
|
{
|
||||||
@@ -206,6 +205,7 @@ class ProductCatalogFromImagesSeeder extends Seeder
|
|||||||
'nombre' => $metadata['product_name'],
|
'nombre' => $metadata['product_name'],
|
||||||
'descripcion' => $metadata['description'],
|
'descripcion' => $metadata['description'],
|
||||||
'precio' => $pricing['price'],
|
'precio' => $pricing['price'],
|
||||||
|
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||||
'attribute_ids' => array_values($attributeIds->all()),
|
'attribute_ids' => array_values($attributeIds->all()),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -226,9 +226,11 @@ class ProductCatalogFromImagesSeeder extends Seeder
|
|||||||
if ($attributeIds->isEmpty()) {
|
if ($attributeIds->isEmpty()) {
|
||||||
$this->productService->createVariant($product, [
|
$this->productService->createVariant($product, [
|
||||||
'stock' => $variantGroup['stock'],
|
'stock' => $variantGroup['stock'],
|
||||||
|
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||||
'definitions' => [],
|
'definitions' => [],
|
||||||
'images' => $images,
|
'images' => $images,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -280,6 +282,7 @@ class ProductCatalogFromImagesSeeder extends Seeder
|
|||||||
|
|
||||||
$this->productService->createVariant($product, [
|
$this->productService->createVariant($product, [
|
||||||
'stock' => $stock,
|
'stock' => $stock,
|
||||||
|
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||||
'definitions' => $definitions,
|
'definitions' => $definitions,
|
||||||
'images' => $images,
|
'images' => $images,
|
||||||
]);
|
]);
|
||||||
@@ -288,7 +291,7 @@ class ProductCatalogFromImagesSeeder extends Seeder
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param array<int, array{files: array<int, \SplFileInfo>, group_key: string, metadata: array{attribute_codes: array<int, string>, brand_name: string|null, category_name: string, color: string|null, description: string, product_name: string, product_slug: string, type: string}, stock: int}> $variantGroups
|
* @param array<int, array{files: array<int, \SplFileInfo>, group_key: string, metadata: array{attribute_codes: array<int, string>, brand_name: string|null, category_name: string, color: string|null, description: string, product_name: string, product_slug: string, type: string}, stock: int}> $variantGroups
|
||||||
* @return array{attribute_codes: array<int, string>, brand_name: string|null, category_name: string, color: string|null, description: string, product_name: string, product_slug: string, type: string}
|
* @return array{attribute_codes: array<int, string>, brand_name: string|null, category_name: string, color: string|null, description: string, product_name: string, product_slug: string, type: string}
|
||||||
*/
|
*/
|
||||||
private function buildProductMetadata(string $productKey, array $variantGroups): array
|
private function buildProductMetadata(string $productKey, array $variantGroups): array
|
||||||
|
|||||||
@@ -85,5 +85,99 @@ class TenantSeeder extends Seeder
|
|||||||
'header_logo' => $headerLogo,
|
'header_logo' => $headerLogo,
|
||||||
'footer_logo' => $footerLogo,
|
'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/Purchase/routes/api.php';
|
||||||
require __DIR__.'/../app/Domains/Tenant/routes/api.php';
|
require __DIR__.'/../app/Domains/Tenant/routes/api.php';
|
||||||
require __DIR__.'/../app/Domains/Integration/routes/api.php';
|
require __DIR__.'/../app/Domains/Integration/routes/api.php';
|
||||||
|
require __DIR__.'/../app/Domains/Menu/routes/api.php';
|
||||||
|
|
||||||
|
|||||||
@@ -2,14 +2,19 @@
|
|||||||
|
|
||||||
namespace Tests\Feature\Cart;
|
namespace Tests\Feature\Cart;
|
||||||
|
|
||||||
|
use App\Domains\Attachable\Enums\AttachmentType;
|
||||||
|
use App\Domains\Attachable\Models\Attachment;
|
||||||
use App\Domains\Auth\Models\User;
|
use App\Domains\Auth\Models\User;
|
||||||
use App\Domains\Catalog\Models\Product;
|
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||||
use App\Domains\Catalog\Models\Attribute;
|
use App\Domains\Catalog\Models\Attribute;
|
||||||
use App\Domains\Catalog\Models\ProductVariant;
|
use App\Domains\Catalog\Models\Category;
|
||||||
|
use App\Domains\Catalog\Models\Product;
|
||||||
use App\Domains\Catalog\Models\ProductAttribute;
|
use App\Domains\Catalog\Models\ProductAttribute;
|
||||||
|
use App\Domains\Catalog\Models\ProductVariant;
|
||||||
use App\Domains\Catalog\Models\ProductVariantDefinition;
|
use App\Domains\Catalog\Models\ProductVariantDefinition;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
use Tests\TestCase;
|
use Tests\TestCase;
|
||||||
|
|
||||||
class CartControllerTest extends TestCase
|
class CartControllerTest extends TestCase
|
||||||
@@ -29,7 +34,7 @@ class CartControllerTest extends TestCase
|
|||||||
'status' => 'active',
|
'status' => 'active',
|
||||||
'items' => [],
|
'items' => [],
|
||||||
'subtotal' => '0.00',
|
'subtotal' => '0.00',
|
||||||
]
|
],
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -315,18 +320,73 @@ class CartControllerTest extends TestCase
|
|||||||
->assertJsonValidationErrors(['cantidad' => 'El máximo que se puede agregar es 2.']);
|
->assertJsonValidationErrors(['cantidad' => 'El máximo que se puede agregar es 2.']);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function test_unlimited_inventory_can_be_reserved_updated_and_released_without_real_stock(): void
|
||||||
|
{
|
||||||
|
$variant = $this->createVariantForTenant(
|
||||||
|
'acme',
|
||||||
|
0,
|
||||||
|
'10.00',
|
||||||
|
'unlimited',
|
||||||
|
InventoryPolicy::Unlimited,
|
||||||
|
);
|
||||||
|
|
||||||
|
$response = $this->postJson('/api/tenants/acme/cart/items', [
|
||||||
|
'product_variant_id' => $variant->id,
|
||||||
|
'cantidad' => 100,
|
||||||
|
])->assertOk();
|
||||||
|
|
||||||
|
$guestToken = $response->getCookie('guest_token', false)?->getValue();
|
||||||
|
$this->assertDatabaseHas('productos_variantes', [
|
||||||
|
'id' => $variant->id,
|
||||||
|
'stock_real' => 0,
|
||||||
|
'stock_reservado' => 100,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->call(
|
||||||
|
'PATCH',
|
||||||
|
"/api/tenants/acme/cart/items/{$variant->id}",
|
||||||
|
[],
|
||||||
|
['guest_token' => $guestToken],
|
||||||
|
[],
|
||||||
|
['HTTP_Accept' => 'application/json', 'CONTENT_TYPE' => 'application/json'],
|
||||||
|
json_encode(['cantidad' => 150]),
|
||||||
|
)->assertOk();
|
||||||
|
|
||||||
|
$this->assertDatabaseHas('productos_variantes', [
|
||||||
|
'id' => $variant->id,
|
||||||
|
'stock_real' => 0,
|
||||||
|
'stock_reservado' => 150,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->call(
|
||||||
|
'DELETE',
|
||||||
|
"/api/tenants/acme/cart/items/{$variant->id}",
|
||||||
|
[],
|
||||||
|
['guest_token' => $guestToken],
|
||||||
|
[],
|
||||||
|
['HTTP_Accept' => 'application/json'],
|
||||||
|
)->assertOk();
|
||||||
|
|
||||||
|
$this->assertDatabaseHas('productos_variantes', [
|
||||||
|
'id' => $variant->id,
|
||||||
|
'stock_real' => 0,
|
||||||
|
'stock_reservado' => 0,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
protected function createVariantForTenant(
|
protected function createVariantForTenant(
|
||||||
string $tenantCode,
|
string $tenantCode,
|
||||||
int $stock,
|
int $stock,
|
||||||
string $price,
|
string $price,
|
||||||
string $slugPrefix = 'shirt',
|
string $slugPrefix = 'shirt',
|
||||||
|
InventoryPolicy $inventoryPolicy = InventoryPolicy::Tracked,
|
||||||
): ProductVariant {
|
): ProductVariant {
|
||||||
$tenant = Tenant::query()->where('codigo', $tenantCode)->first();
|
$tenant = Tenant::query()->where('codigo', $tenantCode)->first();
|
||||||
if (! $tenant) {
|
if (! $tenant) {
|
||||||
$this->createTenant($tenantCode, ucfirst($tenantCode), "{$tenantCode}.com");
|
$this->createTenant($tenantCode, ucfirst($tenantCode), "{$tenantCode}.com");
|
||||||
}
|
}
|
||||||
|
|
||||||
$category = \App\Domains\Catalog\Models\Category::query()->create([
|
$category = Category::query()->create([
|
||||||
'tenant_code' => $tenantCode,
|
'tenant_code' => $tenantCode,
|
||||||
'nombre' => "{$slugPrefix} category {$tenantCode}",
|
'nombre' => "{$slugPrefix} category {$tenantCode}",
|
||||||
]);
|
]);
|
||||||
@@ -342,6 +402,7 @@ class CartControllerTest extends TestCase
|
|||||||
|
|
||||||
return ProductVariant::query()->create([
|
return ProductVariant::query()->create([
|
||||||
'producto_id' => $product->id,
|
'producto_id' => $product->id,
|
||||||
|
'inventory_policy' => $inventoryPolicy->value,
|
||||||
'slug' => "{$slugPrefix}-variant-".ProductVariant::query()->count(),
|
'slug' => "{$slugPrefix}-variant-".ProductVariant::query()->count(),
|
||||||
'nombre' => ucfirst($slugPrefix).' Variant',
|
'nombre' => ucfirst($slugPrefix).' Variant',
|
||||||
'stock' => $stock,
|
'stock' => $stock,
|
||||||
@@ -352,21 +413,21 @@ class CartControllerTest extends TestCase
|
|||||||
|
|
||||||
protected function createTenant(string $codigo, string $nombre, string $dominio): Tenant
|
protected function createTenant(string $codigo, string $nombre, string $dominio): Tenant
|
||||||
{
|
{
|
||||||
$hdrKey = (string) \Illuminate\Support\Str::uuid();
|
$hdrKey = (string) Str::uuid();
|
||||||
$ftrKey = (string) \Illuminate\Support\Str::uuid();
|
$ftrKey = (string) Str::uuid();
|
||||||
|
|
||||||
$headerAttachment = \App\Domains\Attachable\Models\Attachment::create([
|
$headerAttachment = Attachment::create([
|
||||||
'key' => $hdrKey,
|
'key' => $hdrKey,
|
||||||
'path' => 'tenants/' . $hdrKey . '.png',
|
'path' => 'tenants/'.$hdrKey.'.png',
|
||||||
'filename' => 'logo_header.png',
|
'filename' => 'logo_header.png',
|
||||||
'type' => \App\Domains\Attachable\Enums\AttachmentType::Image,
|
'type' => AttachmentType::Image,
|
||||||
'mime_type' => 'image/png',
|
'mime_type' => 'image/png',
|
||||||
]);
|
]);
|
||||||
$footerAttachment = \App\Domains\Attachable\Models\Attachment::create([
|
$footerAttachment = Attachment::create([
|
||||||
'key' => $ftrKey,
|
'key' => $ftrKey,
|
||||||
'path' => 'tenants/' . $ftrKey . '.png',
|
'path' => 'tenants/'.$ftrKey.'.png',
|
||||||
'filename' => 'logo_footer.png',
|
'filename' => 'logo_footer.png',
|
||||||
'type' => \App\Domains\Attachable\Enums\AttachmentType::Image,
|
'type' => AttachmentType::Image,
|
||||||
'mime_type' => 'image/png',
|
'mime_type' => 'image/png',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ namespace Tests\Feature\Catalog;
|
|||||||
|
|
||||||
use App\Domains\Attachable\Enums\AttachmentType;
|
use App\Domains\Attachable\Enums\AttachmentType;
|
||||||
use App\Domains\Attachable\Models\Attachment;
|
use App\Domains\Attachable\Models\Attachment;
|
||||||
|
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||||
use App\Domains\Catalog\Models\Attribute;
|
use App\Domains\Catalog\Models\Attribute;
|
||||||
use App\Domains\Catalog\Models\Brand;
|
use App\Domains\Catalog\Models\Brand;
|
||||||
use App\Domains\Catalog\Models\Product;
|
use App\Domains\Catalog\Models\Product;
|
||||||
@@ -768,6 +769,67 @@ class ProductControllerTest extends TestCase
|
|||||||
$response->assertJsonValidationErrors(['variant_id']);
|
$response->assertJsonValidationErrors(['variant_id']);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function test_it_creates_an_unlimited_default_variant_and_exposes_inventory_fields(): void
|
||||||
|
{
|
||||||
|
$response = $this->postJson("/api/tenants/{$this->tenant->codigo}/productos", [
|
||||||
|
'categoria_id' => 1,
|
||||||
|
'brand_id' => $this->brand->id,
|
||||||
|
'slug' => 'unlimited-product',
|
||||||
|
'nombre' => 'Unlimited Product',
|
||||||
|
'precio' => 100,
|
||||||
|
'stock' => 0,
|
||||||
|
'inventory_policy' => InventoryPolicy::Unlimited->value,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$response->assertCreated();
|
||||||
|
|
||||||
|
$product = Product::query()->where('slug', 'unlimited-product')->firstOrFail();
|
||||||
|
$variant = $product->variants()->firstOrFail();
|
||||||
|
$this->assertSame(InventoryPolicy::Unlimited, $variant->inventory_policy);
|
||||||
|
|
||||||
|
$this->getJson("/api/tenants/{$this->tenant->codigo}/productos/{$product->id}")
|
||||||
|
->assertOk()
|
||||||
|
->assertJsonPath('data.variant.id', $variant->id)
|
||||||
|
->assertJsonPath('data.variant.inventory_policy', InventoryPolicy::Unlimited->value)
|
||||||
|
->assertJsonPath('data.variant.cantidad_maxima', null)
|
||||||
|
->assertJsonPath('data.variant.cantidad_vendida', 0)
|
||||||
|
->assertJsonPath('data.variants_map.0.inventory_policy', InventoryPolicy::Unlimited->value)
|
||||||
|
->assertJsonPath('data.variants_map.0.cantidad_maxima', null)
|
||||||
|
->assertJsonPath('data.variants_map.0.cantidad_vendida', 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_it_rejects_invalid_or_updated_inventory_policies(): void
|
||||||
|
{
|
||||||
|
$this->postJson("/api/tenants/{$this->tenant->codigo}/productos", [
|
||||||
|
'categoria_id' => 1,
|
||||||
|
'brand_id' => $this->brand->id,
|
||||||
|
'slug' => 'invalid-policy',
|
||||||
|
'nombre' => 'Invalid Policy',
|
||||||
|
'precio' => 100,
|
||||||
|
'inventory_policy' => 'sometimes',
|
||||||
|
])->assertUnprocessable()->assertJsonValidationErrors(['inventory_policy']);
|
||||||
|
|
||||||
|
$product = Product::query()->create([
|
||||||
|
'tenant_codigo' => $this->tenant->codigo,
|
||||||
|
'categoria_id' => 1,
|
||||||
|
'brand_id' => $this->brand->id,
|
||||||
|
'slug' => 'immutable-policy',
|
||||||
|
'nombre' => 'Immutable Policy',
|
||||||
|
'precio' => 100,
|
||||||
|
]);
|
||||||
|
$variant = $product->variants()->create([
|
||||||
|
'stock' => 0,
|
||||||
|
'inventory_policy' => InventoryPolicy::Unlimited->value,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->putJson(
|
||||||
|
"/api/tenants/{$this->tenant->codigo}/productos/{$product->id}/variants/{$variant->id}",
|
||||||
|
['inventory_policy' => InventoryPolicy::Tracked->value],
|
||||||
|
)->assertUnprocessable()->assertJsonValidationErrors(['inventory_policy']);
|
||||||
|
|
||||||
|
$this->assertSame(InventoryPolicy::Unlimited, $variant->fresh()->inventory_policy);
|
||||||
|
}
|
||||||
|
|
||||||
private function createAttachment(string $path): Attachment
|
private function createAttachment(string $path): Attachment
|
||||||
{
|
{
|
||||||
return Attachment::create([
|
return Attachment::create([
|
||||||
|
|||||||
@@ -2,8 +2,12 @@
|
|||||||
|
|
||||||
namespace Tests\Feature\Integration;
|
namespace Tests\Feature\Integration;
|
||||||
|
|
||||||
|
use App\Domains\Attachable\Enums\AttachmentType;
|
||||||
|
use App\Domains\Attachable\Models\Attachment;
|
||||||
use App\Domains\Auth\Models\User;
|
use App\Domains\Auth\Models\User;
|
||||||
use App\Domains\Cart\Models\Cart;
|
use App\Domains\Cart\Models\Cart;
|
||||||
|
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||||
|
use App\Domains\Catalog\Models\Category;
|
||||||
use App\Domains\Catalog\Models\Product;
|
use App\Domains\Catalog\Models\Product;
|
||||||
use App\Domains\Catalog\Models\ProductVariant;
|
use App\Domains\Catalog\Models\ProductVariant;
|
||||||
use App\Domains\Integration\Models\Integration;
|
use App\Domains\Integration\Models\Integration;
|
||||||
@@ -14,6 +18,7 @@ use App\Domains\Tenant\Models\Tenant;
|
|||||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||||
use Illuminate\Support\Facades\Cache;
|
use Illuminate\Support\Facades\Cache;
|
||||||
use Illuminate\Support\Facades\Http;
|
use Illuminate\Support\Facades\Http;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
use Tests\TestCase;
|
use Tests\TestCase;
|
||||||
|
|
||||||
class TelepagosWebhookTest extends TestCase
|
class TelepagosWebhookTest extends TestCase
|
||||||
@@ -24,7 +29,7 @@ class TelepagosWebhookTest extends TestCase
|
|||||||
{
|
{
|
||||||
parent::setUp();
|
parent::setUp();
|
||||||
|
|
||||||
config(['services.integrations.secret' => 'base64:' . base64_encode(random_bytes(32))]);
|
config(['services.integrations.secret' => 'base64:'.base64_encode(random_bytes(32))]);
|
||||||
Cache::flush();
|
Cache::flush();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -113,6 +118,13 @@ class TelepagosWebhookTest extends TestCase
|
|||||||
'total' => 50,
|
'total' => 50,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
$this->assertDatabaseHas('productos_variantes', [
|
||||||
|
'id' => $variant->id,
|
||||||
|
'stock_real' => 9,
|
||||||
|
'stock_reservado' => 2,
|
||||||
|
'cantidad_vendida' => 1,
|
||||||
|
]);
|
||||||
|
|
||||||
$this->assertDatabaseMissing('compra_items', [
|
$this->assertDatabaseMissing('compra_items', [
|
||||||
'compra_id' => $newerPurchase->id,
|
'compra_id' => $newerPurchase->id,
|
||||||
]);
|
]);
|
||||||
@@ -122,6 +134,60 @@ class TelepagosWebhookTest extends TestCase
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function test_transfer_webhook_buys_unlimited_inventory_without_reducing_real_stock(): void
|
||||||
|
{
|
||||||
|
$tenant = $this->createTenant('unlimited', 'Unlimited', 'unlimited.com.ar');
|
||||||
|
$this->configureTelepagosIntegration($tenant);
|
||||||
|
$user = User::factory()->create();
|
||||||
|
$variant = $this->createVariantForTenant(
|
||||||
|
'unlimited',
|
||||||
|
0,
|
||||||
|
'50.00',
|
||||||
|
'service',
|
||||||
|
InventoryPolicy::Unlimited,
|
||||||
|
);
|
||||||
|
$purchase = $this->createPendingTransferPurchase(
|
||||||
|
$tenant,
|
||||||
|
$user->id,
|
||||||
|
$variant->id,
|
||||||
|
3,
|
||||||
|
'87654321',
|
||||||
|
);
|
||||||
|
|
||||||
|
Http::fake([
|
||||||
|
'https://api.telepagos.com.ar/v2/auth/token' => Http::response([
|
||||||
|
'status' => 'ok',
|
||||||
|
'token' => 'test-token',
|
||||||
|
'expires_at' => now()->addHour()->toIso8601String(),
|
||||||
|
]),
|
||||||
|
'https://api.telepagos.com.ar/v2/payment/cashin/7000' => Http::response([
|
||||||
|
'status' => 'ok',
|
||||||
|
'data' => [
|
||||||
|
'amount' => 150,
|
||||||
|
'operation_id' => 1,
|
||||||
|
'transaction_id' => 'tx-unlimited',
|
||||||
|
'buyer' => ['cuit' => '20876543219'],
|
||||||
|
],
|
||||||
|
]),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->postJson('/api/webhooks/telepagos/unlimited', ['id' => '7000'])
|
||||||
|
->assertOk()
|
||||||
|
->assertJsonPath('status', 'success');
|
||||||
|
|
||||||
|
$this->assertDatabaseHas('compras', [
|
||||||
|
'id' => $purchase->id,
|
||||||
|
'status' => Purchase::STATUS_PAID,
|
||||||
|
]);
|
||||||
|
$this->assertDatabaseHas('productos_variantes', [
|
||||||
|
'id' => $variant->id,
|
||||||
|
'inventory_policy' => InventoryPolicy::Unlimited->value,
|
||||||
|
'stock_real' => 0,
|
||||||
|
'stock_reservado' => 0,
|
||||||
|
'cantidad_vendida' => 3,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
private function createPendingTransferPurchase(
|
private function createPendingTransferPurchase(
|
||||||
Tenant $tenant,
|
Tenant $tenant,
|
||||||
int $userId,
|
int $userId,
|
||||||
@@ -184,8 +250,9 @@ class TelepagosWebhookTest extends TestCase
|
|||||||
int $stock,
|
int $stock,
|
||||||
string $price,
|
string $price,
|
||||||
string $slugPrefix = 'shirt',
|
string $slugPrefix = 'shirt',
|
||||||
|
InventoryPolicy $inventoryPolicy = InventoryPolicy::Tracked,
|
||||||
): ProductVariant {
|
): ProductVariant {
|
||||||
$category = \App\Domains\Catalog\Models\Category::query()->create([
|
$category = Category::query()->create([
|
||||||
'tenant_code' => $tenantCode,
|
'tenant_code' => $tenantCode,
|
||||||
'nombre' => "{$slugPrefix} category {$tenantCode}",
|
'nombre' => "{$slugPrefix} category {$tenantCode}",
|
||||||
]);
|
]);
|
||||||
@@ -201,6 +268,7 @@ class TelepagosWebhookTest extends TestCase
|
|||||||
|
|
||||||
return ProductVariant::query()->create([
|
return ProductVariant::query()->create([
|
||||||
'producto_id' => $product->id,
|
'producto_id' => $product->id,
|
||||||
|
'inventory_policy' => $inventoryPolicy->value,
|
||||||
'slug' => "{$slugPrefix}-variant-".ProductVariant::query()->count(),
|
'slug' => "{$slugPrefix}-variant-".ProductVariant::query()->count(),
|
||||||
'nombre' => ucfirst($slugPrefix).' Variant',
|
'nombre' => ucfirst($slugPrefix).' Variant',
|
||||||
'stock' => $stock,
|
'stock' => $stock,
|
||||||
@@ -211,21 +279,21 @@ class TelepagosWebhookTest extends TestCase
|
|||||||
|
|
||||||
private function createTenant(string $codigo, string $nombre, string $dominio): Tenant
|
private function createTenant(string $codigo, string $nombre, string $dominio): Tenant
|
||||||
{
|
{
|
||||||
$hdrKey = (string) \Illuminate\Support\Str::uuid();
|
$hdrKey = (string) Str::uuid();
|
||||||
$ftrKey = (string) \Illuminate\Support\Str::uuid();
|
$ftrKey = (string) Str::uuid();
|
||||||
|
|
||||||
$headerAttachment = \App\Domains\Attachable\Models\Attachment::create([
|
$headerAttachment = Attachment::create([
|
||||||
'key' => $hdrKey,
|
'key' => $hdrKey,
|
||||||
'path' => 'tenants/' . $hdrKey . '.png',
|
'path' => 'tenants/'.$hdrKey.'.png',
|
||||||
'filename' => 'logo_header.png',
|
'filename' => 'logo_header.png',
|
||||||
'type' => \App\Domains\Attachable\Enums\AttachmentType::Image,
|
'type' => AttachmentType::Image,
|
||||||
'mime_type' => 'image/png',
|
'mime_type' => 'image/png',
|
||||||
]);
|
]);
|
||||||
$footerAttachment = \App\Domains\Attachable\Models\Attachment::create([
|
$footerAttachment = Attachment::create([
|
||||||
'key' => $ftrKey,
|
'key' => $ftrKey,
|
||||||
'path' => 'tenants/' . $ftrKey . '.png',
|
'path' => 'tenants/'.$ftrKey.'.png',
|
||||||
'filename' => 'logo_footer.png',
|
'filename' => 'logo_footer.png',
|
||||||
'type' => \App\Domains\Attachable\Enums\AttachmentType::Image,
|
'type' => AttachmentType::Image,
|
||||||
'mime_type' => 'image/png',
|
'mime_type' => 'image/png',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
|||||||
@@ -2,13 +2,19 @@
|
|||||||
|
|
||||||
namespace Tests\Feature\Purchase;
|
namespace Tests\Feature\Purchase;
|
||||||
|
|
||||||
|
use App\Domains\Attachable\Enums\AttachmentType;
|
||||||
|
use App\Domains\Attachable\Models\Attachment;
|
||||||
use App\Domains\Auth\Models\User;
|
use App\Domains\Auth\Models\User;
|
||||||
use App\Domains\Cart\Models\Cart;
|
use App\Domains\Cart\Models\Cart;
|
||||||
|
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||||
|
use App\Domains\Catalog\Models\Category;
|
||||||
use App\Domains\Catalog\Models\Product;
|
use App\Domains\Catalog\Models\Product;
|
||||||
use App\Domains\Catalog\Models\ProductVariant;
|
use App\Domains\Catalog\Models\ProductVariant;
|
||||||
use App\Domains\Purchase\Models\Purchase;
|
use App\Domains\Purchase\Models\Purchase;
|
||||||
|
use App\Domains\Purchase\Services\CheckoutService;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
use Tests\TestCase;
|
use Tests\TestCase;
|
||||||
|
|
||||||
class StorePurchaseTest extends TestCase
|
class StorePurchaseTest extends TestCase
|
||||||
@@ -21,7 +27,7 @@ class StorePurchaseTest extends TestCase
|
|||||||
$user = User::factory()->create([
|
$user = User::factory()->create([
|
||||||
'email' => 'buyer@example.com',
|
'email' => 'buyer@example.com',
|
||||||
]);
|
]);
|
||||||
$category = \App\Domains\Catalog\Models\Category::query()->create([
|
$category = Category::query()->create([
|
||||||
'tenant_code' => 'sonder',
|
'tenant_code' => 'sonder',
|
||||||
'nombre' => 'Test Category',
|
'nombre' => 'Test Category',
|
||||||
]);
|
]);
|
||||||
@@ -76,6 +82,7 @@ class StorePurchaseTest extends TestCase
|
|||||||
$response->assertJsonPath('data.email', 'juan.perez@example.com');
|
$response->assertJsonPath('data.email', 'juan.perez@example.com');
|
||||||
$response->assertJsonPath('data.tenant_codigo', 'sonder');
|
$response->assertJsonPath('data.tenant_codigo', 'sonder');
|
||||||
$response->assertJsonPath('data.status', Purchase::STATUS_CREATED);
|
$response->assertJsonPath('data.status', Purchase::STATUS_CREATED);
|
||||||
|
$response->assertJsonPath('data.items_source', null);
|
||||||
$response->assertJsonPath('data.items', []);
|
$response->assertJsonPath('data.items', []);
|
||||||
$response->assertJsonPath('data.subtotal', '100.00');
|
$response->assertJsonPath('data.subtotal', '100.00');
|
||||||
$response->assertJsonPath('data.total', '100.00');
|
$response->assertJsonPath('data.total', '100.00');
|
||||||
@@ -159,6 +166,157 @@ 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->assertDatabaseHas('productos_variantes', [
|
||||||
|
'id' => $variant->id,
|
||||||
|
'stock_real' => 8,
|
||||||
|
'stock_reservado' => 0,
|
||||||
|
'cantidad_vendida' => 2,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$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
|
public function test_it_rejects_a_cart_from_another_user(): void
|
||||||
{
|
{
|
||||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||||
@@ -255,18 +413,48 @@ class StorePurchaseTest extends TestCase
|
|||||||
->assertJsonValidationErrors(['cart_id']);
|
->assertJsonValidationErrors(['cart_id']);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function test_it_confirms_unlimited_inventory_without_reducing_real_stock_and_is_idempotent(): void
|
||||||
|
{
|
||||||
|
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||||
|
$user = User::factory()->create();
|
||||||
|
$variant = $this->createVariantForTenant(
|
||||||
|
'sonder',
|
||||||
|
0,
|
||||||
|
'50.00',
|
||||||
|
'unlimited',
|
||||||
|
InventoryPolicy::Unlimited,
|
||||||
|
);
|
||||||
|
$purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 25);
|
||||||
|
$purchase->update(['payment_method' => 'transfer']);
|
||||||
|
|
||||||
|
$checkoutService = app(CheckoutService::class);
|
||||||
|
$purchase = $checkoutService->completePurchase($purchase);
|
||||||
|
$checkoutService->confirmPurchase($purchase);
|
||||||
|
$checkoutService->confirmPurchase($purchase);
|
||||||
|
|
||||||
|
$this->assertDatabaseHas('productos_variantes', [
|
||||||
|
'id' => $variant->id,
|
||||||
|
'inventory_policy' => InventoryPolicy::Unlimited->value,
|
||||||
|
'stock_real' => 0,
|
||||||
|
'stock_reservado' => 0,
|
||||||
|
'cantidad_vendida' => 25,
|
||||||
|
]);
|
||||||
|
$this->assertDatabaseCount('compra_items', 1);
|
||||||
|
}
|
||||||
|
|
||||||
protected function createVariantForTenant(
|
protected function createVariantForTenant(
|
||||||
string $tenantCode,
|
string $tenantCode,
|
||||||
int $stock,
|
int $stock,
|
||||||
string $price,
|
string $price,
|
||||||
string $slugPrefix = 'shirt',
|
string $slugPrefix = 'shirt',
|
||||||
|
InventoryPolicy $inventoryPolicy = InventoryPolicy::Tracked,
|
||||||
): ProductVariant {
|
): ProductVariant {
|
||||||
$tenant = Tenant::query()->where('codigo', $tenantCode)->first();
|
$tenant = Tenant::query()->where('codigo', $tenantCode)->first();
|
||||||
if (! $tenant) {
|
if (! $tenant) {
|
||||||
$this->createTenant($tenantCode, ucfirst($tenantCode), "{$tenantCode}.com");
|
$this->createTenant($tenantCode, ucfirst($tenantCode), "{$tenantCode}.com");
|
||||||
}
|
}
|
||||||
|
|
||||||
$category = \App\Domains\Catalog\Models\Category::query()->create([
|
$category = Category::query()->create([
|
||||||
'tenant_code' => $tenantCode,
|
'tenant_code' => $tenantCode,
|
||||||
'nombre' => "{$slugPrefix} category {$tenantCode}",
|
'nombre' => "{$slugPrefix} category {$tenantCode}",
|
||||||
]);
|
]);
|
||||||
@@ -282,6 +470,7 @@ class StorePurchaseTest extends TestCase
|
|||||||
|
|
||||||
return ProductVariant::query()->create([
|
return ProductVariant::query()->create([
|
||||||
'producto_id' => $product->id,
|
'producto_id' => $product->id,
|
||||||
|
'inventory_policy' => $inventoryPolicy->value,
|
||||||
'slug' => "{$slugPrefix}-variant-".ProductVariant::query()->count(),
|
'slug' => "{$slugPrefix}-variant-".ProductVariant::query()->count(),
|
||||||
'nombre' => ucfirst($slugPrefix).' Variant',
|
'nombre' => ucfirst($slugPrefix).' Variant',
|
||||||
'stock' => $stock,
|
'stock' => $stock,
|
||||||
@@ -290,23 +479,47 @@ class StorePurchaseTest extends TestCase
|
|||||||
])->load('product');
|
])->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
|
protected function createTenant(string $codigo, string $nombre, string $dominio): Tenant
|
||||||
{
|
{
|
||||||
$hdrKey = (string) \Illuminate\Support\Str::uuid();
|
$hdrKey = (string) Str::uuid();
|
||||||
$ftrKey = (string) \Illuminate\Support\Str::uuid();
|
$ftrKey = (string) Str::uuid();
|
||||||
|
|
||||||
$headerAttachment = \App\Domains\Attachable\Models\Attachment::create([
|
$headerAttachment = Attachment::create([
|
||||||
'key' => $hdrKey,
|
'key' => $hdrKey,
|
||||||
'path' => 'tenants/' . $hdrKey . '.png',
|
'path' => 'tenants/'.$hdrKey.'.png',
|
||||||
'filename' => 'logo_header.png',
|
'filename' => 'logo_header.png',
|
||||||
'type' => \App\Domains\Attachable\Enums\AttachmentType::Image,
|
'type' => AttachmentType::Image,
|
||||||
'mime_type' => 'image/png',
|
'mime_type' => 'image/png',
|
||||||
]);
|
]);
|
||||||
$footerAttachment = \App\Domains\Attachable\Models\Attachment::create([
|
$footerAttachment = Attachment::create([
|
||||||
'key' => $ftrKey,
|
'key' => $ftrKey,
|
||||||
'path' => 'tenants/' . $ftrKey . '.png',
|
'path' => 'tenants/'.$ftrKey.'.png',
|
||||||
'filename' => 'logo_footer.png',
|
'filename' => 'logo_footer.png',
|
||||||
'type' => \App\Domains\Attachable\Enums\AttachmentType::Image,
|
'type' => AttachmentType::Image,
|
||||||
'mime_type' => 'image/png',
|
'mime_type' => 'image/png',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
|||||||
153
tests/Unit/Catalog/ProductVariantInventoryTest.php
Normal file
153
tests/Unit/Catalog/ProductVariantInventoryTest.php
Normal file
@@ -0,0 +1,153 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Tests\Unit\Catalog;
|
||||||
|
|
||||||
|
use App\Domains\Attachable\Enums\AttachmentType;
|
||||||
|
use App\Domains\Attachable\Models\Attachment;
|
||||||
|
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||||
|
use App\Domains\Catalog\Models\Category;
|
||||||
|
use App\Domains\Catalog\Models\Product;
|
||||||
|
use App\Domains\Catalog\Models\ProductVariant;
|
||||||
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
|
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Tests\TestCase;
|
||||||
|
|
||||||
|
class ProductVariantInventoryTest extends TestCase
|
||||||
|
{
|
||||||
|
use RefreshDatabase;
|
||||||
|
|
||||||
|
private Product $product;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
|
||||||
|
$headerAttachment = $this->createAttachment('header.png');
|
||||||
|
$footerAttachment = $this->createAttachment('footer.png');
|
||||||
|
|
||||||
|
$tenant = Tenant::query()->create([
|
||||||
|
'codigo' => 'inventory-test',
|
||||||
|
'nombre' => 'Inventory Test',
|
||||||
|
'dominio' => 'inventory.test',
|
||||||
|
'primary_color' => '#111111',
|
||||||
|
'secondary_color' => '#222222',
|
||||||
|
'danger_color' => '#333333',
|
||||||
|
'success_color' => '#28a745',
|
||||||
|
'header_bg_color' => '#444444',
|
||||||
|
'footer_bg_color' => '#444444',
|
||||||
|
'header_logo_id' => $headerAttachment->id,
|
||||||
|
'footer_logo_id' => $footerAttachment->id,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$category = Category::query()->create([
|
||||||
|
'tenant_code' => $tenant->codigo,
|
||||||
|
'nombre' => 'Inventory',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->product = Product::query()->create([
|
||||||
|
'tenant_codigo' => $tenant->codigo,
|
||||||
|
'categoria_id' => $category->id,
|
||||||
|
'slug' => 'inventory-product',
|
||||||
|
'nombre' => 'Inventory Product',
|
||||||
|
'precio' => 100,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_it_defaults_to_tracked_inventory_with_no_sales(): void
|
||||||
|
{
|
||||||
|
$variant = $this->createVariant(5);
|
||||||
|
|
||||||
|
$this->assertSame(InventoryPolicy::Tracked, $variant->inventory_policy);
|
||||||
|
$this->assertSame(5, $variant->availableQuantity());
|
||||||
|
$this->assertSame(0, $variant->cantidad_vendida);
|
||||||
|
$this->assertTrue($variant->isAvailableForSale());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_tracked_inventory_cannot_reserve_more_than_available_stock(): void
|
||||||
|
{
|
||||||
|
$variant = $this->createVariant(5);
|
||||||
|
$variant->reserveStock(3);
|
||||||
|
|
||||||
|
$this->assertSame(2, $variant->fresh()->availableQuantity());
|
||||||
|
|
||||||
|
$this->expectException(\InvalidArgumentException::class);
|
||||||
|
$variant->reserveStock(3);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_unlimited_inventory_can_reserve_more_than_real_stock(): void
|
||||||
|
{
|
||||||
|
$variant = $this->createVariant(0, InventoryPolicy::Unlimited);
|
||||||
|
$variant->reserveStock(50);
|
||||||
|
|
||||||
|
$variant->refresh();
|
||||||
|
$this->assertNull($variant->availableQuantity());
|
||||||
|
$this->assertSame(50, $variant->stock_reservado);
|
||||||
|
$this->assertTrue($variant->isAvailableForSale());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_buying_tracked_inventory_consumes_stock_and_records_the_sale(): void
|
||||||
|
{
|
||||||
|
$variant = $this->createVariant(10);
|
||||||
|
$variant->reserveStock(4);
|
||||||
|
$variant->buy(3);
|
||||||
|
|
||||||
|
$variant->refresh();
|
||||||
|
$this->assertSame(7, $variant->stock_real);
|
||||||
|
$this->assertSame(1, $variant->stock_reservado);
|
||||||
|
$this->assertSame(3, $variant->cantidad_vendida);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_buying_unlimited_inventory_preserves_real_stock_and_records_the_sale(): void
|
||||||
|
{
|
||||||
|
$variant = $this->createVariant(0, InventoryPolicy::Unlimited);
|
||||||
|
$variant->reserveStock(4);
|
||||||
|
$variant->buy(3);
|
||||||
|
|
||||||
|
$variant->refresh();
|
||||||
|
$this->assertSame(0, $variant->stock_real);
|
||||||
|
$this->assertSame(1, $variant->stock_reservado);
|
||||||
|
$this->assertSame(3, $variant->cantidad_vendida);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_buy_requires_enough_reserved_stock(): void
|
||||||
|
{
|
||||||
|
$variant = $this->createVariant(10);
|
||||||
|
$variant->reserveStock(1);
|
||||||
|
|
||||||
|
$this->expectException(\InvalidArgumentException::class);
|
||||||
|
$variant->buy(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_inventory_policy_cannot_change_after_creation(): void
|
||||||
|
{
|
||||||
|
$variant = $this->createVariant(10);
|
||||||
|
$variant->inventory_policy = InventoryPolicy::Unlimited;
|
||||||
|
|
||||||
|
$this->expectException(\InvalidArgumentException::class);
|
||||||
|
$this->expectExceptionMessage('La politica de inventario no puede modificarse.');
|
||||||
|
$variant->save();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function createVariant(
|
||||||
|
int $stock,
|
||||||
|
InventoryPolicy $inventoryPolicy = InventoryPolicy::Tracked,
|
||||||
|
): ProductVariant {
|
||||||
|
return ProductVariant::query()->create([
|
||||||
|
'producto_id' => $this->product->id,
|
||||||
|
'stock' => $stock,
|
||||||
|
'inventory_policy' => $inventoryPolicy->value,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function createAttachment(string $filename): Attachment
|
||||||
|
{
|
||||||
|
return Attachment::query()->create([
|
||||||
|
'key' => (string) Str::uuid(),
|
||||||
|
'path' => 'tests/'.$filename,
|
||||||
|
'filename' => $filename,
|
||||||
|
'type' => AttachmentType::Image,
|
||||||
|
'mime_type' => 'image/png',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user