Compare commits

...

2 Commits

19 changed files with 336 additions and 121 deletions

View File

@@ -11,9 +11,11 @@ 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\HasMany; use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;
#[Fillable([ #[Fillable([
'tenant_code', 'tenant_code',
'code',
'source_type', 'source_type',
'category_id', 'category_id',
'product_layout', 'product_layout',
@@ -33,6 +35,29 @@ class FeaturedGroup extends Model
'source_type' => FeaturedGroupSource::Manual->value, 'source_type' => FeaturedGroupSource::Manual->value,
]; ];
protected static function booted(): void
{
static::creating(function (FeaturedGroup $featuredGroup): void {
if (filled($featuredGroup->code)) {
return;
}
$baseCode = Str::slug($featuredGroup->group_name) ?: 'group';
$code = $baseCode;
$suffix = 2;
while (static::query()
->where('tenant_code', $featuredGroup->tenant_code)
->where('code', $code)
->exists()) {
$code = "{$baseCode}-{$suffix}";
$suffix++;
}
$featuredGroup->code = $code;
});
}
protected function casts(): array protected function casts(): array
{ {
return [ return [

View File

@@ -15,6 +15,7 @@ class OnTicketFeaturedGroupResource extends JsonResource
{ {
return [ return [
'id' => $this->id, 'id' => $this->id,
'code' => $this->code,
'category_id' => $this->category_id, 'category_id' => $this->category_id,
'category_name' => $this->category->nombre, 'category_name' => $this->category->nombre,
'group_name' => $this->group_name, 'group_name' => $this->group_name,

View File

@@ -20,6 +20,7 @@ class CatalogFeaturedGroupResource extends JsonResource
{ {
return [ return [
'id' => $this->id, 'id' => $this->id,
'code' => $this->code,
'title' => $this->group_name, 'title' => $this->group_name,
'layout' => $this->product_layout->value, 'layout' => $this->product_layout->value,
'group_layout' => $this->group_layout->value, 'group_layout' => $this->group_layout->value,

View File

@@ -6,28 +6,29 @@ use App\Domains\Catalog\Models\StockReservation;
use App\Domains\Catalog\Services\StockReservationService; use App\Domains\Catalog\Services\StockReservationService;
use App\Domains\Purchase\Models\Purchase; use App\Domains\Purchase\Models\Purchase;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException; use Illuminate\Validation\ValidationException;
use Throwable;
class ReleaseCheckoutService class ReleaseCheckoutService
{ {
public function __construct( public function __construct(
private readonly StockReservationService $reservations, private readonly StockReservationService $reservations,
private readonly SourceCartService $sourceCart,
) {} ) {}
public function cancel(Purchase $purchase): Purchase public function cancel(Purchase $purchase): Purchase
{ {
return $this->release($purchase, Purchase::STATUS_CANCELLED, restoreCart: true); return $this->release($purchase, Purchase::STATUS_CANCELLED);
} }
public function cancelWithoutRestoringCart(Purchase $purchase): Purchase public function cancelWithoutRestoringCart(Purchase $purchase): Purchase
{ {
return $this->release($purchase, Purchase::STATUS_CANCELLED, restoreCart: false); return $this->release($purchase, Purchase::STATUS_CANCELLED);
} }
public function expire(Purchase $purchase): Purchase public function expire(Purchase $purchase): Purchase
{ {
return $this->release($purchase, Purchase::STATUS_EXPIRED, restoreCart: true); return $this->release($purchase, Purchase::STATUS_EXPIRED);
} }
public function expireOverdue(): int public function expireOverdue(): int
@@ -40,7 +41,21 @@ class ReleaseCheckoutService
->where('expires_at', '<=', now()) ->where('expires_at', '<=', now())
->orderBy('id') ->orderBy('id')
->eachById(function (Purchase $purchase) use (&$expiredCount): void { ->eachById(function (Purchase $purchase) use (&$expiredCount): void {
$purchase = $this->expire($purchase); try {
$purchase = $this->expire($purchase);
} catch (Throwable $exception) {
Log::channel('commands')->error('Failed to expire overdue purchase.', [
'command' => 'reservations:expire',
'purchase_id' => $purchase->getKey(),
'tenant_codigo' => $purchase->tenant_codigo,
'cart_id' => $purchase->cart_id,
'status' => $purchase->status,
'expires_at' => $purchase->expires_at,
'exception' => $exception,
]);
return;
}
if ($purchase->status === Purchase::STATUS_EXPIRED) { if ($purchase->status === Purchase::STATUS_EXPIRED) {
$expiredCount++; $expiredCount++;
@@ -50,9 +65,9 @@ class ReleaseCheckoutService
return $expiredCount; return $expiredCount;
} }
private function release(Purchase $purchase, string $targetStatus, bool $restoreCart): Purchase private function release(Purchase $purchase, string $targetStatus): Purchase
{ {
return DB::transaction(function () use ($purchase, $targetStatus, $restoreCart): Purchase { return DB::transaction(function () use ($purchase, $targetStatus): Purchase {
$purchase = $this->lockPurchase($purchase); $purchase = $this->lockPurchase($purchase);
if ($purchase->status === Purchase::STATUS_PAID) { if ($purchase->status === Purchase::STATUS_PAID) {
@@ -82,8 +97,7 @@ class ReleaseCheckoutService
]); ]);
} }
$reservationReturnedToCart = $restoreCart && $this->sourceCart->restore($purchase); $this->releaseCartReservations($purchase, $targetStatus);
$this->releaseCartReservations($purchase, $reservationReturnedToCart, $targetStatus);
$purchase->update(['status' => $targetStatus]); $purchase->update(['status' => $targetStatus]);
@@ -93,15 +107,8 @@ class ReleaseCheckoutService
private function releaseCartReservations( private function releaseCartReservations(
Purchase $purchase, Purchase $purchase,
bool $reservationReturnedToCart,
string $targetStatus, string $targetStatus,
): void { ): void {
if ($reservationReturnedToCart) {
$this->reservations->detachFromPurchase($purchase);
return;
}
$cart = $purchase->cart()->withTrashed()->lockForUpdate()->first(); $cart = $purchase->cart()->withTrashed()->lockForUpdate()->first();
if ($cart === null) { if ($cart === null) {
return; return;

View File

@@ -3,65 +3,10 @@
namespace App\Domains\Purchase\Services\Checkout; namespace App\Domains\Purchase\Services\Checkout;
use App\Domains\Cart\Models\Cart; use App\Domains\Cart\Models\Cart;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Services\StockReservationService;
use App\Domains\Purchase\Models\Purchase; use App\Domains\Purchase\Models\Purchase;
class SourceCartService class SourceCartService
{ {
public function __construct(
private readonly StockReservationService $reservations,
) {}
public function restore(Purchase $purchase): bool
{
$sourceCart = $this->findSourceCart($purchase);
if ($sourceCart === null) {
return false;
}
if ($sourceCart->origin === Cart::ORIGIN_DIRECT_CHECKOUT) {
return false;
}
/** @var Cart|null $activeCart */
$activeCart = Cart::query()
->where('tenant_codigo', $purchase->tenant_codigo)
->where('user_id', $purchase->user_id)
->where('status', 'active')
->where('id', '!=', $sourceCart->getKey())
->lockForUpdate()
->first();
if ($activeCart !== null) {
$this->mergeIntoActiveCart($sourceCart, $activeCart);
$sourceCart->update([
'status' => 'converted',
'guest_token' => null,
]);
if (! $sourceCart->trashed()) {
$sourceCart->delete();
}
return true;
}
if ($sourceCart->trashed()) {
$sourceCart->restore();
}
$sourceCart->update([
'status' => 'active',
'user_id' => $purchase->user_id,
'guest_token' => null,
]);
return true;
}
public function syncItemQuantity( public function syncItemQuantity(
Purchase $purchase, Purchase $purchase,
PurchaseItem $purchaseItem, PurchaseItem $purchaseItem,
@@ -171,30 +116,4 @@ class SourceCartService
->lockForUpdate() ->lockForUpdate()
->first(); ->first();
} }
private function mergeIntoActiveCart(Cart $sourceCart, Cart $activeCart): void
{
$sourceItems = $sourceCart->items()->lockForUpdate()->get();
foreach ($sourceItems as $sourceItem) {
/** @var CartItem|null $activeItem */
$activeItem = $activeCart->items()
->where('catalog_item_id', $sourceItem->catalog_item_id)
->where('variant_id', $sourceItem->variant_id)
->lockForUpdate()
->first();
if ($activeItem === null) {
$activeItem = $activeCart->items()->create([
'catalog_item_id' => $sourceItem->catalog_item_id,
'variant_id' => $sourceItem->variant_id,
'cantidad' => $sourceItem->cantidad,
]);
} else {
$activeItem->increment('cantidad', (int) $sourceItem->cantidad);
}
$this->reservations->transfer($sourceItem, $activeItem);
}
}
} }

View File

@@ -19,7 +19,7 @@ Implementa el ciclo de compra y checkout: crea la cabecera de compra desde un ca
- `EditCheckoutService`: modifica los datos del comprador antes del cierre. - `EditCheckoutService`: modifica los datos del comprador antes del cierre.
- `CompleteCheckoutService`: completa, envía a revisión o materializa los `PurchaseItem` al confirmar el pago. - `CompleteCheckoutService`: completa, envía a revisión o materializa los `PurchaseItem` al confirmar el pago.
- `ReleaseCheckoutService`: cancela, vence y procesa vencimientos pendientes. - `ReleaseCheckoutService`: cancela, vence y procesa vencimientos pendientes.
- `SourceCartService`: restaura o finaliza el carrito fuente. - `SourceCartService`: sincroniza o finaliza el carrito de checkout asociado a la compra.
- `CatalogSelectionResolver` y `PurchaseItemSnapshotFactory`: resuelven selecciones y generan snapshots. - `CatalogSelectionResolver` y `PurchaseItemSnapshotFactory`: resuelven selecciones y generan snapshots.
Durante `created` y `pending_payment`, `PurchaseResource` publica las líneas del carrito con `items_source=cart`; una compra materializada publica `items_source=purchase`. Los datos descriptivos y económicos del checkout se resuelven siempre desde el catálogo vigente. Durante `created` y `pending_payment`, `PurchaseResource` publica las líneas del carrito con `items_source=cart`; una compra materializada publica `items_source=purchase`. Los datos descriptivos y económicos del checkout se resuelven siempre desde el catálogo vigente.

View File

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

View File

@@ -51,7 +51,13 @@ class AdminAppSaleService
{ {
return Purchase::query() return Purchase::query()
->where('tenant_codigo', $tenant->codigo) ->where('tenant_codigo', $tenant->codigo)
->with('items') ->with([
'items',
'cart.items.catalogItem',
'cart.items.variant.catalogItem',
'cart.items.variant.eventDates',
'cart.items.variant.eventDate',
])
->findOrFail($saleId); ->findOrFail($saleId);
} }

View File

@@ -27,6 +27,8 @@ use Illuminate\Support\Facades\Schema;
'dominio', 'dominio',
'base_path', 'base_path',
'site_title', 'site_title',
'address',
'phone',
'primary_color', 'primary_color',
'secondary_color', 'secondary_color',
'danger_color', 'danger_color',

View File

@@ -82,6 +82,8 @@ class StoreTenantRequest extends FormRequest
->where('dominio', $this->input('dominio')), ->where('dominio', $this->input('dominio')),
], ],
'site_title' => ['sometimes', 'nullable', 'string', 'max:255'], 'site_title' => ['sometimes', 'nullable', 'string', 'max:255'],
'address' => ['sometimes', 'nullable', 'string', 'max:255'],
'phone' => ['sometimes', 'nullable', 'string', 'max:255'],
'primary_color' => ['required', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'], 'primary_color' => ['required', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
'secondary_color' => ['required', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'], 'secondary_color' => ['required', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
'danger_color' => ['required', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'], 'danger_color' => ['required', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],

View File

@@ -103,6 +103,8 @@ class UpdateTenantRequest extends FormRequest
->ignore($tenant?->id), ->ignore($tenant?->id),
], ],
'site_title' => ['sometimes', 'nullable', 'string', 'max:255'], 'site_title' => ['sometimes', 'nullable', 'string', 'max:255'],
'address' => ['sometimes', 'nullable', 'string', 'max:255'],
'phone' => ['sometimes', 'nullable', 'string', 'max:255'],
'primary_color' => ['nullable', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'], 'primary_color' => ['nullable', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
'secondary_color' => ['nullable', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'], 'secondary_color' => ['nullable', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
'danger_color' => ['nullable', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'], 'danger_color' => ['nullable', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],

View File

@@ -32,6 +32,8 @@ class TenantResource extends JsonResource
'site_title' => $this->site_title 'site_title' => $this->site_title
?? $this->websiteType?->site_title ?? $this->websiteType?->site_title
?? 'ShopitFront', ?? 'ShopitFront',
'address' => $this->address,
'phone' => $this->phone,
'favicon' => ($this->favicon ?? $this->websiteType?->favicon) 'favicon' => ($this->favicon ?? $this->websiteType?->favicon)
?->getTemporaryUrl(1440), ?->getTemporaryUrl(1440),
'primary_color' => $this->primary_color, 'primary_color' => $this->primary_color,

View File

@@ -0,0 +1,29 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('tenants', function (Blueprint $table): void {
$table->string('address')->nullable()->after('site_title');
$table->string('phone')->nullable()->after('address');
});
DB::table('tenants')->update([
'address' => 'Av. San Lorenzo 1542, Rosario',
'phone' => '54 9 (0341) 6658247',
]);
}
public function down(): void
{
Schema::table('tenants', function (Blueprint $table): void {
$table->dropColumn(['address', 'phone']);
});
}
};

View File

@@ -0,0 +1,53 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
return new class extends Migration
{
public function up(): void
{
Schema::table('featured_groups', function (Blueprint $table): void {
$table->string('code')->nullable()->after('tenant_code');
});
$usedCodes = [];
DB::table('featured_groups')
->select(['id', 'tenant_code', 'group_name'])
->orderBy('id')
->get()
->each(function (object $group) use (&$usedCodes): void {
$baseCode = Str::slug($group->group_name) ?: "group-{$group->id}";
$code = $baseCode;
$suffix = 2;
while (isset($usedCodes[$group->tenant_code][$code])) {
$code = "{$baseCode}-{$suffix}";
$suffix++;
}
$usedCodes[$group->tenant_code][$code] = true;
DB::table('featured_groups')
->where('id', $group->id)
->update(['code' => $code]);
});
Schema::table('featured_groups', function (Blueprint $table): void {
$table->string('code')->nullable(false)->change();
$table->unique(['tenant_code', 'code']);
});
}
public function down(): void
{
Schema::table('featured_groups', function (Blueprint $table): void {
$table->dropUnique(['tenant_code', 'code']);
$table->dropColumn('code');
});
}
};

View File

@@ -81,6 +81,7 @@ class OnTicketFeaturedGroupControllerTest extends TestCase
'is_featured' => true, 'is_featured' => true,
]) ])
->assertCreated() ->assertCreated()
->assertJsonPath('data.code', 'food')
->assertJsonPath('data.category_name', 'Food') ->assertJsonPath('data.category_name', 'Food')
->assertJsonPath('data.group_name', 'Food') ->assertJsonPath('data.group_name', 'Food')
->assertJsonPath('data.is_featured', true) ->assertJsonPath('data.is_featured', true)
@@ -96,6 +97,7 @@ class OnTicketFeaturedGroupControllerTest extends TestCase
]); ]);
$this->assertDatabaseHas('featured_groups', [ $this->assertDatabaseHas('featured_groups', [
'tenant_code' => $tenant->codigo, 'tenant_code' => $tenant->codigo,
'code' => 'food',
'source_type' => 'category', 'source_type' => 'category',
'category_id' => $categoryId, 'category_id' => $categoryId,
'product_layout' => 'row', 'product_layout' => 'row',
@@ -130,6 +132,7 @@ class OnTicketFeaturedGroupControllerTest extends TestCase
'is_featured' => true, 'is_featured' => true,
]) ])
->assertOk() ->assertOk()
->assertJsonPath('data.code', 'old-name')
->assertJsonPath('data.category_name', 'New name') ->assertJsonPath('data.category_name', 'New name')
->assertJsonPath('data.group_name', 'New name') ->assertJsonPath('data.group_name', 'New name')
->assertJsonPath('data.is_featured', true) ->assertJsonPath('data.is_featured', true)
@@ -142,6 +145,7 @@ class OnTicketFeaturedGroupControllerTest extends TestCase
]); ]);
$this->assertDatabaseHas('featured_groups', [ $this->assertDatabaseHas('featured_groups', [
'id' => $group->id, 'id' => $group->id,
'code' => 'old-name',
'group_name' => 'New name', 'group_name' => 'New name',
'product_layout' => 'row', 'product_layout' => 'row',
'group_layout' => 'paginated', 'group_layout' => 'paginated',

View File

@@ -412,7 +412,7 @@ class StorePurchaseTest extends TestCase
]); ]);
} }
public function test_it_restores_the_source_cart_when_checkout_is_cancelled(): void public function test_it_releases_and_closes_the_checkout_cart_when_purchase_is_cancelled(): void
{ {
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar'); $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
$user = User::factory()->create(); $user = User::factory()->create();
@@ -430,11 +430,10 @@ class StorePurchaseTest extends TestCase
->assertOk() ->assertOk()
->assertJsonPath('data.status', Purchase::STATUS_CANCELLED); ->assertJsonPath('data.status', Purchase::STATUS_CANCELLED);
$this->assertDatabaseHas('carritos', [ $this->assertSoftDeleted('carritos', [
'id' => $purchase->cart_id, 'id' => $purchase->cart_id,
'user_id' => $user->id, 'user_id' => $user->id,
'status' => 'active', 'status' => 'converted',
'deleted_at' => null,
]); ]);
$this->assertDatabaseHas('carrito_items', [ $this->assertDatabaseHas('carrito_items', [
'cart_id' => $purchase->cart_id, 'cart_id' => $purchase->cart_id,
@@ -444,11 +443,16 @@ class StorePurchaseTest extends TestCase
]); ]);
$this->assertDatabaseHas('inventories', [ $this->assertDatabaseHas('inventories', [
'id' => $variant->inventory_id, 'id' => $variant->inventory_id,
'reserved_stock' => 3, 'reserved_stock' => 0,
]);
$this->assertDatabaseHas('stock_reservations', [
'purchase_id' => $purchase->id,
'quantity' => 0,
'status' => 'released',
]); ]);
} }
public function test_it_merges_the_checkout_cart_when_the_user_created_another_active_cart(): void public function test_it_keeps_a_new_active_cart_separate_when_checkout_is_cancelled(): void
{ {
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar'); $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
$user = User::factory()->create(); $user = User::factory()->create();
@@ -480,11 +484,15 @@ class StorePurchaseTest extends TestCase
'cart_id' => $activeCartId, 'cart_id' => $activeCartId,
'catalog_item_id' => $variant->catalog_item_id, 'catalog_item_id' => $variant->catalog_item_id,
'variant_id' => $variant->id, 'variant_id' => $variant->id,
'cantidad' => 3, 'cantidad' => 1,
]);
$this->assertSoftDeleted('carritos', [
'id' => $purchase->cart_id,
'status' => 'converted',
]); ]);
$this->assertDatabaseHas('inventories', [ $this->assertDatabaseHas('inventories', [
'id' => $variant->inventory_id, 'id' => $variant->inventory_id,
'reserved_stock' => 3, 'reserved_stock' => 1,
]); ]);
} }
@@ -1069,7 +1077,7 @@ class StorePurchaseTest extends TestCase
]); ]);
} }
public function test_it_expires_an_abandoned_purchase_and_restores_its_cart(): void public function test_it_expires_an_abandoned_purchase_and_releases_its_checkout_cart(): void
{ {
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar'); $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
$user = User::factory()->create(); $user = User::factory()->create();
@@ -1095,21 +1103,20 @@ class StorePurchaseTest extends TestCase
]); ]);
$this->assertDatabaseMissing('compra_items', ['compra_id' => $purchase->id]); $this->assertDatabaseMissing('compra_items', ['compra_id' => $purchase->id]);
$this->assertDatabaseHas('stock_reservations', [ $this->assertDatabaseHas('stock_reservations', [
'purchase_id' => null, 'purchase_id' => $purchase->id,
'quantity' => 3, 'quantity' => 0,
'status' => 'active', 'status' => 'expired',
]); ]);
$this->assertDatabaseHas('inventories', [ $this->assertDatabaseHas('inventories', [
'id' => $variant->inventory_id, 'id' => $variant->inventory_id,
'real_stock' => 10, 'real_stock' => 10,
'reserved_stock' => 3, 'reserved_stock' => 0,
'sold_units' => 0, 'sold_units' => 0,
]); ]);
$this->assertDatabaseHas('carritos', [ $this->assertSoftDeleted('carritos', [
'id' => $purchase->cart_id, 'id' => $purchase->cart_id,
'user_id' => $user->id, 'user_id' => $user->id,
'status' => 'active', 'status' => 'converted',
'deleted_at' => null,
]); ]);
$this->artisan('reservations:expire') $this->artisan('reservations:expire')
@@ -1118,6 +1125,43 @@ class StorePurchaseTest extends TestCase
->assertSuccessful(); ->assertSuccessful();
} }
public function test_it_continues_expiring_purchases_after_an_inconsistent_reservation(): void
{
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
$user = User::factory()->create();
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
$inconsistentPurchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 1);
$validPurchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 1);
$inconsistentPurchase->items()->create([
'source_catalog_item_id' => $variant->catalog_item_id,
'source_variant_id' => $variant->id,
'nombre' => 'Inconsistent item',
'slug' => 'inconsistent-item',
'cantidad' => 1,
'precio_unitario' => '50.00',
'discount_total' => '0.00',
'tax_total' => '0.00',
'total' => '50.00',
]);
$this->travel(31)->minutes();
$this->artisan('reservations:expire')
->expectsOutput('Expired purchases: 1')
->expectsOutput('Expired cart items: 0')
->assertSuccessful();
$this->assertDatabaseHas('compras', [
'id' => $inconsistentPurchase->id,
'status' => Purchase::STATUS_CREATED,
]);
$this->assertDatabaseHas('compras', [
'id' => $validPurchase->id,
'status' => Purchase::STATUS_EXPIRED,
]);
}
public function test_purchase_detail_uses_cart_items_for_created_purchase(): void public function test_purchase_detail_uses_cart_items_for_created_purchase(): void
{ {
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar'); $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');

View File

@@ -5,6 +5,7 @@ namespace Tests\Feature\Sale;
use App\Domains\Auth\Models\User; use App\Domains\Auth\Models\User;
use App\Domains\Authorization\Enums\RoleCode; use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Cart\Models\Cart; use App\Domains\Cart\Models\Cart;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Models\CatalogItem; use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Purchase\Events\PurchasePaid; use App\Domains\Purchase\Events\PurchasePaid;
use App\Domains\Purchase\Models\Purchase; use App\Domains\Purchase\Models\Purchase;
@@ -71,6 +72,44 @@ class AdminAppSaleControllerTest extends TestCase
->assertJsonPath('data.total', '40000.00'); ->assertJsonPath('data.total', '40000.00');
} }
public function test_an_adminapp_user_can_read_cart_items_from_an_unconfirmed_sale(): void
{
$tenant = $this->createTenant('acme');
Sanctum::actingAs($this->createAdminAppUser($tenant));
$catalogItem = CatalogItem::query()->create([
'tenant_code' => $tenant->codigo,
'slug' => 'entrada-general',
'nombre' => 'Entrada general',
'descripcion' => 'Acceso general',
'precio' => '12500.00',
]);
$cart = Cart::query()->create([
'tenant_codigo' => $tenant->codigo,
'status' => 'checkout',
]);
$cartItem = CartItem::query()->create([
'cart_id' => $cart->id,
'catalog_item_id' => $catalogItem->id,
'cantidad' => 2,
]);
$purchase = Purchase::query()->create([
'cart_id' => $cart->id,
'tenant_codigo' => $tenant->codigo,
'status' => Purchase::STATUS_PENDING_PAYMENT,
'total' => '25000.00',
]);
$this->getJson("/api/v1/adminapp/tenant/sales/{$purchase->id}")
->assertOk()
->assertJsonPath('data.items.0.id', $cartItem->id)
->assertJsonPath('data.items.0.product', 'Entrada general')
->assertJsonPath('data.items.0.event_dates', [])
->assertJsonPath('data.items.0.quantity', 2)
->assertJsonPath('data.items.0.unit_price', '12500.00')
->assertJsonPath('data.items.0.total', '25000.00');
}
public function test_an_adminapp_user_cannot_read_a_sale_from_another_tenant(): void public function test_an_adminapp_user_cannot_read_a_sale_from_another_tenant(): void
{ {
$tenant = $this->createTenant('acme'); $tenant = $this->createTenant('acme');

View File

@@ -59,6 +59,8 @@ class BootstrapTenantControllerTest extends TestCase
'codigo' => 'acme', 'codigo' => 'acme',
'nombre' => 'Acme', 'nombre' => 'Acme',
'dominio' => 'acme.com', 'dominio' => 'acme.com',
'address' => 'Calle Test 123, Rosario',
'phone' => '+54 341 555 1234',
'primary_color' => '#ff0000', 'primary_color' => '#ff0000',
'secondary_color' => '#00ff00', 'secondary_color' => '#00ff00',
'danger_color' => '#0000ff', 'danger_color' => '#0000ff',
@@ -84,6 +86,8 @@ class BootstrapTenantControllerTest extends TestCase
->assertOk() ->assertOk()
->assertJsonPath('data.codigo', 'acme') ->assertJsonPath('data.codigo', 'acme')
->assertJsonPath('data.dominio', 'acme.com') ->assertJsonPath('data.dominio', 'acme.com')
->assertJsonPath('data.address', 'Calle Test 123, Rosario')
->assertJsonPath('data.phone', '+54 341 555 1234')
->assertJsonPath('data.primary_color', '#ff0000') ->assertJsonPath('data.primary_color', '#ff0000')
->assertJsonPath('data.secondary_color', '#00ff00') ->assertJsonPath('data.secondary_color', '#00ff00')
->assertJsonPath('data.danger_color', '#0000ff') ->assertJsonPath('data.danger_color', '#0000ff')

View File

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