Compare commits
91 Commits
bbe3cf82f5
...
feature/ti
| Author | SHA1 | Date | |
|---|---|---|---|
| c2233389d0 | |||
| 334ffe92e7 | |||
| a19ace3115 | |||
| acc0a68736 | |||
| dcf105c316 | |||
| f74bf41931 | |||
| 34217be630 | |||
| ee906d2d2e | |||
| 836aa1afd7 | |||
| 6896646c54 | |||
| 5e541f7cd0 | |||
| 80b8707771 | |||
| 58b15f3026 | |||
| 2e9355c85c | |||
| fa1e11a69f | |||
| 6a00d8d09c | |||
| fbfcb5cf63 | |||
| adce4ab59e | |||
| 5250d1a818 | |||
| 457eba68a9 | |||
| 52b0b339d6 | |||
| 9175df1d7f | |||
| 38341b2bda | |||
| 34a0a14404 | |||
| af516ce9e3 | |||
| dca35e7b0c | |||
| df853de843 | |||
| 4ba464bf85 | |||
| 208e929262 | |||
| ffe47d903e | |||
| 24983439b1 | |||
| d179a0f74e | |||
| 636e39e98e | |||
| bda94d02af | |||
| bfb16ef60e | |||
| 1b6303237a | |||
| 9da92c880a | |||
| 63012838a4 | |||
| 27544a23be | |||
| a71c80248c | |||
| 1ca8fb20af | |||
| ba167559a6 | |||
| 495515b1f3 | |||
| 781e282f16 | |||
| 7fb4c9674a | |||
| 0d85c3df19 | |||
| a93b260043 | |||
| c209e716e3 | |||
| 71c914a389 | |||
| 705b1247f5 | |||
| b1f42775d6 | |||
| 0f6f39cce7 | |||
| 1ec7ab3e35 | |||
| ba0e2dd00c | |||
| c792e7d306 | |||
| 6ee3f22e41 | |||
| d4ec34db1a | |||
| 351178d9da | |||
| b617285148 | |||
| 9bca41bfa5 | |||
| 5601285369 | |||
| 6fb60c9a73 | |||
| c3f1c320a4 | |||
| 899bf12457 | |||
| a460743ae0 | |||
| a4d7b1b789 | |||
| 10655b8c07 | |||
| adc7b21ab8 | |||
| ba1355448a | |||
| 1c76e56f2d | |||
| daa74845b7 | |||
| 05944cec9c | |||
| c820741e5f | |||
| adc4cc9595 | |||
| c67dfcc1a1 | |||
| f61b7e4dee | |||
| e53fa949cf | |||
| c51e24311f | |||
| a650de79c1 | |||
| 8f4fc39858 | |||
| 09554b9f80 | |||
| 0d2198a3db | |||
| 52732da960 | |||
| 1f7bb35f63 | |||
| 22c6631652 | |||
| 6c5d49bf45 | |||
| 2596b5df18 | |||
| 733064c0dc | |||
| 99808c1053 | |||
| e2ad78b1fb | |||
| 414df97e9d |
@@ -8,6 +8,7 @@ PURCHASE_CHECKOUT_EXPIRATION_MINUTES=30
|
|||||||
PURCHASE_QR_EXPIRATION_MINUTES=15
|
PURCHASE_QR_EXPIRATION_MINUTES=15
|
||||||
PURCHASE_TELEPAGOS_EXPIRATION_MINUTES=30
|
PURCHASE_TELEPAGOS_EXPIRATION_MINUTES=30
|
||||||
PURCHASE_TRANSFER_EXPIRATION_MINUTES=1440
|
PURCHASE_TRANSFER_EXPIRATION_MINUTES=1440
|
||||||
|
PURCHASE_TRANSFER_CANDIDATE_AMOUNT_TOLERANCE_PERCENTAGE=5
|
||||||
STOCK_RESERVATION_EXPIRATION_MINUTES=30
|
STOCK_RESERVATION_EXPIRATION_MINUTES=30
|
||||||
FRONTEND_URLS=http://localhost:4200
|
FRONTEND_URLS=http://localhost:4200
|
||||||
|
|
||||||
@@ -31,6 +32,7 @@ AUTH_LOGIN_ATTEMPT_WINDOW_MINUTES=30
|
|||||||
AUTH_LOGIN_LOCK_MINUTES=15
|
AUTH_LOGIN_LOCK_MINUTES=15
|
||||||
AUTH_LOGIN_RATE_LIMIT_PER_MINUTE=10
|
AUTH_LOGIN_RATE_LIMIT_PER_MINUTE=10
|
||||||
AUTH_LOGIN_IP_RATE_LIMIT_PER_MINUTE=30
|
AUTH_LOGIN_IP_RATE_LIMIT_PER_MINUTE=30
|
||||||
|
AUTH_PASSWORD_RESET_EXPIRATION_MINUTES=60
|
||||||
|
|
||||||
LOG_CHANNEL=daily
|
LOG_CHANNEL=daily
|
||||||
LOG_STACK=single
|
LOG_STACK=single
|
||||||
|
|||||||
@@ -22,10 +22,18 @@ class ValidateResetPasswordAttemptController extends Controller
|
|||||||
{
|
{
|
||||||
$data = $request->validated();
|
$data = $request->validated();
|
||||||
|
|
||||||
if (! $this->resetPasswordAttemptService->validateCode(
|
$result = $this->resetPasswordAttemptService->validateCode(
|
||||||
$data['email'],
|
$data['email'],
|
||||||
$data['codigo'],
|
$data['codigo'],
|
||||||
)) {
|
);
|
||||||
|
|
||||||
|
if ($result === ResetPasswordAttemptService::CODE_EXPIRED) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'codigo' => __('api.auth.reset_code_expired'),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($result !== ResetPasswordAttemptService::CODE_VALID) {
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
'codigo' => __('api.auth.reset_code_invalid'),
|
'codigo' => __('api.auth.reset_code_invalid'),
|
||||||
]);
|
]);
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ use Illuminate\Database\Eloquent\Attributes\Hidden;
|
|||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
|
||||||
#[Fillable(['user_id', 'codigo', 'reason', 'status'])]
|
#[Fillable(['user_id', 'codigo', 'reason', 'status', 'expires_at'])]
|
||||||
#[Hidden(['codigo'])]
|
#[Hidden(['codigo'])]
|
||||||
class ResetPasswordAttempt extends Model
|
class ResetPasswordAttempt extends Model
|
||||||
{
|
{
|
||||||
@@ -31,6 +31,7 @@ class ResetPasswordAttempt extends Model
|
|||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'user_id' => 'integer',
|
'user_id' => 'integer',
|
||||||
|
'expires_at' => 'datetime',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -12,6 +12,12 @@ use Throwable;
|
|||||||
|
|
||||||
class ResetPasswordAttemptService
|
class ResetPasswordAttemptService
|
||||||
{
|
{
|
||||||
|
public const CODE_VALID = 'valid';
|
||||||
|
|
||||||
|
public const CODE_INVALID = 'invalid';
|
||||||
|
|
||||||
|
public const CODE_EXPIRED = 'expired';
|
||||||
|
|
||||||
public function createForEmail(
|
public function createForEmail(
|
||||||
string $email,
|
string $email,
|
||||||
string $tenantCode,
|
string $tenantCode,
|
||||||
@@ -146,12 +152,12 @@ class ResetPasswordAttemptService
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function validateCode(string $email, string $code): bool
|
public function validateCode(string $email, string $code): string
|
||||||
{
|
{
|
||||||
$emailFingerprint = $this->emailFingerprint($email);
|
$emailFingerprint = $this->emailFingerprint($email);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return DB::transaction(function () use ($email, $code, $emailFingerprint): bool {
|
return DB::transaction(function () use ($email, $code, $emailFingerprint): string {
|
||||||
$user = User::query()
|
$user = User::query()
|
||||||
->where('email', $email)
|
->where('email', $email)
|
||||||
->lockForUpdate()
|
->lockForUpdate()
|
||||||
@@ -169,14 +175,27 @@ class ResetPasswordAttemptService
|
|||||||
'email_fingerprint' => $emailFingerprint,
|
'email_fingerprint' => $emailFingerprint,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return false;
|
return self::CODE_INVALID;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($attempt->expires_at?->isPast()) {
|
||||||
|
$attempt->update([
|
||||||
|
'status' => ResetPasswordAttempt::STATUS_EXPIRED,
|
||||||
|
]);
|
||||||
|
|
||||||
|
Log::info('Password reset code validation failed: attempt expired.', [
|
||||||
|
'email_fingerprint' => $emailFingerprint,
|
||||||
|
'attempt_id' => $attempt->getKey(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return self::CODE_EXPIRED;
|
||||||
}
|
}
|
||||||
|
|
||||||
$attempt->update([
|
$attempt->update([
|
||||||
'status' => ResetPasswordAttempt::STATUS_VALIDATED,
|
'status' => ResetPasswordAttempt::STATUS_VALIDATED,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return true;
|
return self::CODE_VALID;
|
||||||
});
|
});
|
||||||
} catch (Throwable $exception) {
|
} catch (Throwable $exception) {
|
||||||
Log::error('Failed to validate password reset code.', [
|
Log::error('Failed to validate password reset code.', [
|
||||||
@@ -214,6 +233,19 @@ class ResetPasswordAttemptService
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if ($attempt->expires_at?->isPast()) {
|
||||||
|
$attempt->update([
|
||||||
|
'status' => ResetPasswordAttempt::STATUS_EXPIRED,
|
||||||
|
]);
|
||||||
|
|
||||||
|
Log::info('Password reset failed: attempt expired.', [
|
||||||
|
'email_fingerprint' => $emailFingerprint,
|
||||||
|
'attempt_id' => $attempt->getKey(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
$user->password = $password;
|
$user->password = $password;
|
||||||
$user->failed_login_attempts = 0;
|
$user->failed_login_attempts = 0;
|
||||||
$user->last_failed_login_at = null;
|
$user->last_failed_login_at = null;
|
||||||
@@ -270,6 +302,7 @@ class ResetPasswordAttemptService
|
|||||||
'codigo' => $this->generateCode(),
|
'codigo' => $this->generateCode(),
|
||||||
'reason' => $reason,
|
'reason' => $reason,
|
||||||
'status' => ResetPasswordAttempt::STATUS_PENDING,
|
'status' => ResetPasswordAttempt::STATUS_PENDING,
|
||||||
|
'expires_at' => now()->addMinutes((int) config('auth.passwords.users.expire')),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return $attempt->getKey();
|
return $attempt->getKey();
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ namespace App\Domains\Cart\Models;
|
|||||||
use App\Domains\Auth\Models\User;
|
use App\Domains\Auth\Models\User;
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Catalog\Models\CatalogItem;
|
||||||
use App\Domains\Catalog\Models\Inventory;
|
use App\Domains\Catalog\Models\Inventory;
|
||||||
|
use App\Domains\Catalog\Models\StockReservation;
|
||||||
use App\Domains\Catalog\Models\Variant;
|
use App\Domains\Catalog\Models\Variant;
|
||||||
use App\Domains\Catalog\Services\CatalogInventoryService;
|
use App\Domains\Catalog\Services\CatalogInventoryService;
|
||||||
use App\Domains\Catalog\Services\StockReservationService;
|
use App\Domains\Catalog\Services\StockReservationService;
|
||||||
@@ -28,6 +29,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
|||||||
'status',
|
'status',
|
||||||
'origin',
|
'origin',
|
||||||
'current_purchase_id',
|
'current_purchase_id',
|
||||||
|
'current_stock_reservation_id',
|
||||||
])]
|
])]
|
||||||
class Cart extends Model
|
class Cart extends Model
|
||||||
{
|
{
|
||||||
@@ -36,6 +38,16 @@ class Cart extends Model
|
|||||||
|
|
||||||
protected $table = 'carritos';
|
protected $table = 'carritos';
|
||||||
|
|
||||||
|
public const STATUS_ACTIVE = 'active';
|
||||||
|
|
||||||
|
public const STATUS_CHECKOUT = 'checkout';
|
||||||
|
|
||||||
|
public const STATUS_CONVERTED = 'converted';
|
||||||
|
|
||||||
|
public const STATUS_EXPIRED = 'expired';
|
||||||
|
|
||||||
|
public const STATUS_ABANDONED = 'abandoned';
|
||||||
|
|
||||||
public const ORIGIN_USER = 'user';
|
public const ORIGIN_USER = 'user';
|
||||||
|
|
||||||
public const ORIGIN_DIRECT_CHECKOUT = 'direct_checkout';
|
public const ORIGIN_DIRECT_CHECKOUT = 'direct_checkout';
|
||||||
@@ -45,6 +57,7 @@ class Cart extends Model
|
|||||||
return [
|
return [
|
||||||
'user_id' => 'integer',
|
'user_id' => 'integer',
|
||||||
'current_purchase_id' => 'integer',
|
'current_purchase_id' => 'integer',
|
||||||
|
'current_stock_reservation_id' => 'integer',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -84,6 +97,15 @@ class Cart extends Model
|
|||||||
return $this->belongsTo(Purchase::class, 'current_purchase_id');
|
return $this->belongsTo(Purchase::class, 'current_purchase_id');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @return BelongsTo<StockReservation, $this> */
|
||||||
|
public function currentStockReservation(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(
|
||||||
|
StockReservation::class,
|
||||||
|
'current_stock_reservation_id',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
public function getTotalAmount(): float
|
public function getTotalAmount(): float
|
||||||
{
|
{
|
||||||
$items = $this->relationLoaded('items')
|
$items = $this->relationLoaded('items')
|
||||||
@@ -107,6 +129,7 @@ class Cart extends Model
|
|||||||
|
|
||||||
return DB::transaction(function () use ($catalogItemId, $variantId, $quantity): CartItem {
|
return DB::transaction(function () use ($catalogItemId, $variantId, $quantity): CartItem {
|
||||||
$this->invalidateCurrentCheckout();
|
$this->invalidateCurrentCheckout();
|
||||||
|
app(StockReservationService::class)->assertCartReservationUsable($this);
|
||||||
$selectedItem = $this->resolveScopedItem($catalogItemId, $variantId, true);
|
$selectedItem = $this->resolveScopedItem($catalogItemId, $variantId, true);
|
||||||
$cartQuantity = (int) $this->items()
|
$cartQuantity = (int) $this->items()
|
||||||
->where('catalog_item_id', $catalogItemId)
|
->where('catalog_item_id', $catalogItemId)
|
||||||
@@ -140,12 +163,11 @@ class Cart extends Model
|
|||||||
'cantidad' => $quantity,
|
'cantidad' => $quantity,
|
||||||
]);
|
]);
|
||||||
} else {
|
} else {
|
||||||
app(StockReservationService::class)->ensure($item, $selectedItem);
|
|
||||||
$item->cantidad += $quantity;
|
$item->cantidad += $quantity;
|
||||||
$item->save();
|
$item->save();
|
||||||
}
|
}
|
||||||
|
|
||||||
app(StockReservationService::class)->reserve($item, $selectedItem, $quantity);
|
app(StockReservationService::class)->syncCart($this);
|
||||||
|
|
||||||
return $item->fresh();
|
return $item->fresh();
|
||||||
});
|
});
|
||||||
@@ -172,6 +194,7 @@ class Cart extends Model
|
|||||||
$excludedPurchaseId,
|
$excludedPurchaseId,
|
||||||
): CartItem {
|
): CartItem {
|
||||||
$this->invalidateCurrentCheckout();
|
$this->invalidateCurrentCheckout();
|
||||||
|
app(StockReservationService::class)->assertCartReservationUsable($this);
|
||||||
|
|
||||||
/** @var CartItem $item */
|
/** @var CartItem $item */
|
||||||
$item = $this->items()
|
$item = $this->items()
|
||||||
@@ -205,7 +228,6 @@ class Cart extends Model
|
|||||||
$nextAvailableQuantity,
|
$nextAvailableQuantity,
|
||||||
);
|
);
|
||||||
|
|
||||||
app(StockReservationService::class)->release($item, $currentSelection, $item->cantidad);
|
|
||||||
$availableQuantity = $inventoryService->availableQuantity($nextSelection);
|
$availableQuantity = $inventoryService->availableQuantity($nextSelection);
|
||||||
|
|
||||||
if ($availableQuantity !== null && $availableQuantity < $quantity) {
|
if ($availableQuantity !== null && $availableQuantity < $quantity) {
|
||||||
@@ -222,11 +244,10 @@ class Cart extends Model
|
|||||||
->first();
|
->first();
|
||||||
|
|
||||||
if ($targetItem !== null) {
|
if ($targetItem !== null) {
|
||||||
app(StockReservationService::class)->ensure($targetItem, $nextSelection);
|
|
||||||
$targetItem->cantidad += $quantity;
|
$targetItem->cantidad += $quantity;
|
||||||
$targetItem->save();
|
$targetItem->save();
|
||||||
app(StockReservationService::class)->reserve($targetItem, $nextSelection, $quantity);
|
|
||||||
$item->delete();
|
$item->delete();
|
||||||
|
app(StockReservationService::class)->syncCart($this);
|
||||||
|
|
||||||
return $targetItem->fresh();
|
return $targetItem->fresh();
|
||||||
}
|
}
|
||||||
@@ -234,7 +255,7 @@ class Cart extends Model
|
|||||||
$item->variant_id = $variantId;
|
$item->variant_id = $variantId;
|
||||||
$item->cantidad = $quantity;
|
$item->cantidad = $quantity;
|
||||||
$item->save();
|
$item->save();
|
||||||
app(StockReservationService::class)->reserve($item, $nextSelection, $quantity);
|
app(StockReservationService::class)->syncCart($this);
|
||||||
|
|
||||||
return $item->fresh();
|
return $item->fresh();
|
||||||
}
|
}
|
||||||
@@ -263,16 +284,9 @@ class Cart extends Model
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($delta > 0) {
|
|
||||||
app(StockReservationService::class)->reserve($item, $currentSelection, $delta);
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($delta < 0) {
|
|
||||||
app(StockReservationService::class)->release($item, $currentSelection, abs($delta));
|
|
||||||
}
|
|
||||||
|
|
||||||
$item->cantidad = $quantity;
|
$item->cantidad = $quantity;
|
||||||
$item->save();
|
$item->save();
|
||||||
|
app(StockReservationService::class)->syncCart($this);
|
||||||
|
|
||||||
return $item->fresh();
|
return $item->fresh();
|
||||||
});
|
});
|
||||||
@@ -282,6 +296,7 @@ class Cart extends Model
|
|||||||
{
|
{
|
||||||
DB::transaction(function () use ($cartItemId): void {
|
DB::transaction(function () use ($cartItemId): void {
|
||||||
$this->invalidateCurrentCheckout();
|
$this->invalidateCurrentCheckout();
|
||||||
|
app(StockReservationService::class)->assertCartReservationUsable($this);
|
||||||
|
|
||||||
/** @var CartItem $item */
|
/** @var CartItem $item */
|
||||||
$item = $this->items()
|
$item = $this->items()
|
||||||
@@ -289,17 +304,8 @@ class Cart extends Model
|
|||||||
->lockForUpdate()
|
->lockForUpdate()
|
||||||
->firstOrFail();
|
->firstOrFail();
|
||||||
|
|
||||||
$selectedItem = $this->resolveScopedItem(
|
|
||||||
$item->catalog_item_id,
|
|
||||||
$item->variant_id,
|
|
||||||
true,
|
|
||||||
);
|
|
||||||
app(StockReservationService::class)->release(
|
|
||||||
$item,
|
|
||||||
$selectedItem,
|
|
||||||
$item->cantidad,
|
|
||||||
);
|
|
||||||
$item->delete();
|
$item->delete();
|
||||||
|
app(StockReservationService::class)->syncCart($this);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -341,13 +347,20 @@ class Cart extends Model
|
|||||||
Purchase::STATUS_CREATED,
|
Purchase::STATUS_CREATED,
|
||||||
Purchase::STATUS_PENDING_PAYMENT,
|
Purchase::STATUS_PENDING_PAYMENT,
|
||||||
], true)) {
|
], true)) {
|
||||||
|
app(StockReservationService::class)->returnToCart($currentPurchase, $cart);
|
||||||
$currentPurchase->update([
|
$currentPurchase->update([
|
||||||
'status' => Purchase::STATUS_SUPERSEDED,
|
'status' => Purchase::STATUS_SUPERSEDED,
|
||||||
'expires_at' => null,
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
$this->current_purchase_id = null;
|
||||||
|
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
app(StockReservationService::class)->detachFromPurchase($currentPurchase);
|
app(StockReservationService::class)->releaseForPurchase(
|
||||||
|
$currentPurchase,
|
||||||
|
reason: StockReservationService::REASON_PURCHASE_SUPERSEDED,
|
||||||
|
);
|
||||||
self::query()
|
self::query()
|
||||||
->whereKey($cart->getKey())
|
->whereKey($cart->getKey())
|
||||||
->where('current_purchase_id', $currentPurchase->getKey())
|
->where('current_purchase_id', $currentPurchase->getKey())
|
||||||
|
|||||||
@@ -3,13 +3,11 @@
|
|||||||
namespace App\Domains\Cart\Models;
|
namespace App\Domains\Cart\Models;
|
||||||
|
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Catalog\Models\CatalogItem;
|
||||||
use App\Domains\Catalog\Models\StockReservation;
|
|
||||||
use App\Domains\Catalog\Models\Variant;
|
use App\Domains\Catalog\Models\Variant;
|
||||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
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\HasMany;
|
|
||||||
|
|
||||||
#[Fillable([
|
#[Fillable([
|
||||||
'cart_id',
|
'cart_id',
|
||||||
@@ -57,10 +55,4 @@ class CartItem extends Model
|
|||||||
{
|
{
|
||||||
return $this->variant ?? $this->catalogItem;
|
return $this->variant ?? $this->catalogItem;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return HasMany<StockReservation, $this> */
|
|
||||||
public function stockReservations(): HasMany
|
|
||||||
{
|
|
||||||
return $this->hasMany(StockReservation::class);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,9 +4,12 @@ namespace App\Domains\Cart\Services;
|
|||||||
|
|
||||||
use App\Domains\Auth\Models\User;
|
use App\Domains\Auth\Models\User;
|
||||||
use App\Domains\Cart\Models\Cart;
|
use App\Domains\Cart\Models\Cart;
|
||||||
|
use App\Domains\Catalog\Exceptions\StockReservationExpiredException;
|
||||||
|
use App\Domains\Catalog\Services\ExpireStockReservationsService;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Facades\Auth;
|
use Illuminate\Support\Facades\Auth;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\Str;
|
use Illuminate\Support\Str;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
use Symfony\Component\HttpFoundation\Cookie;
|
use Symfony\Component\HttpFoundation\Cookie;
|
||||||
@@ -22,7 +25,7 @@ class CartService
|
|||||||
return $this->makeEmptyCart($tenant);
|
return $this->makeEmptyCart($tenant);
|
||||||
}
|
}
|
||||||
|
|
||||||
$cart = $this->findCart($tenant, $resolvedIdentity['identity']);
|
$cart = $this->resolveCart($tenant, $resolvedIdentity['identity']);
|
||||||
|
|
||||||
if ($cart === null) {
|
if ($cart === null) {
|
||||||
return $this->makeEmptyCart($tenant);
|
return $this->makeEmptyCart($tenant);
|
||||||
@@ -119,7 +122,7 @@ class CartService
|
|||||||
{
|
{
|
||||||
$cart = new Cart([
|
$cart = new Cart([
|
||||||
'tenant_codigo' => $tenant->codigo,
|
'tenant_codigo' => $tenant->codigo,
|
||||||
'status' => 'active',
|
'status' => Cart::STATUS_ACTIVE,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$cart->setRelation('items', collect());
|
$cart->setRelation('items', collect());
|
||||||
@@ -220,12 +223,14 @@ class CartService
|
|||||||
{
|
{
|
||||||
return Cart::query()
|
return Cart::query()
|
||||||
->where('tenant_codigo', $tenant->codigo)
|
->where('tenant_codigo', $tenant->codigo)
|
||||||
->where('status', 'active')
|
->where('origin', Cart::ORIGIN_USER)
|
||||||
|
->whereIn('status', [Cart::STATUS_ACTIVE, Cart::STATUS_EXPIRED])
|
||||||
->when(
|
->when(
|
||||||
$identity['user_id'] !== null,
|
$identity['user_id'] !== null,
|
||||||
fn ($query) => $query->where('user_id', $identity['user_id']),
|
fn ($query) => $query->where('user_id', $identity['user_id']),
|
||||||
fn ($query) => $query->where('guest_token', $identity['guest_token']),
|
fn ($query) => $query->where('guest_token', $identity['guest_token']),
|
||||||
)
|
)
|
||||||
|
->orderByRaw('CASE WHEN status = ? THEN 0 ELSE 1 END', [Cart::STATUS_ACTIVE])
|
||||||
->first();
|
->first();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -234,7 +239,7 @@ class CartService
|
|||||||
*/
|
*/
|
||||||
protected function findCartOrFail(Tenant $tenant, array $identity): Cart
|
protected function findCartOrFail(Tenant $tenant, array $identity): Cart
|
||||||
{
|
{
|
||||||
$cart = $this->findCart($tenant, $identity);
|
$cart = $this->resolveCart($tenant, $identity, replaceExpired: false);
|
||||||
|
|
||||||
if ($cart === null) {
|
if ($cart === null) {
|
||||||
throw new NotFoundHttpException('Cart not found.');
|
throw new NotFoundHttpException('Cart not found.');
|
||||||
@@ -247,10 +252,73 @@ class CartService
|
|||||||
* @param array{user_id: ?int, guest_token: ?string} $identity
|
* @param array{user_id: ?int, guest_token: ?string} $identity
|
||||||
*/
|
*/
|
||||||
protected function findOrCreateCart(Tenant $tenant, array $identity): Cart
|
protected function findOrCreateCart(Tenant $tenant, array $identity): Cart
|
||||||
|
{
|
||||||
|
return $this->resolveCart($tenant, $identity)
|
||||||
|
?? $this->createCart($tenant, $identity);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array{user_id: ?int, guest_token: ?string} $identity
|
||||||
|
*/
|
||||||
|
protected function resolveCart(
|
||||||
|
Tenant $tenant,
|
||||||
|
array $identity,
|
||||||
|
bool $replaceExpired = true,
|
||||||
|
): ?Cart {
|
||||||
|
$cart = $this->findCart($tenant, $identity);
|
||||||
|
|
||||||
|
if ($cart?->status === Cart::STATUS_ACTIVE
|
||||||
|
&& $cart->current_stock_reservation_id !== null
|
||||||
|
&& app(ExpireStockReservationsService::class)
|
||||||
|
->expireIfOverdue($cart->current_stock_reservation_id)) {
|
||||||
|
$cart = $this->findCart($tenant, $identity);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($cart?->status === Cart::STATUS_EXPIRED) {
|
||||||
|
if (! $replaceExpired) {
|
||||||
|
throw new StockReservationExpiredException;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->replaceExpiredCart($cart, $tenant, $identity);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($cart !== null) {
|
||||||
|
return $cart;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array{user_id: ?int, guest_token: ?string} $identity
|
||||||
|
*/
|
||||||
|
protected function replaceExpiredCart(Cart $expiredCart, Tenant $tenant, array $identity): Cart
|
||||||
|
{
|
||||||
|
return DB::transaction(function () use ($expiredCart, $tenant, $identity): Cart {
|
||||||
|
/** @var Cart|null $lockedCart */
|
||||||
|
$lockedCart = Cart::query()->lockForUpdate()->find($expiredCart->getKey());
|
||||||
|
|
||||||
|
if ($lockedCart?->status === Cart::STATUS_EXPIRED) {
|
||||||
|
$lockedCart->update([
|
||||||
|
'status' => Cart::STATUS_ABANDONED,
|
||||||
|
'current_purchase_id' => null,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->findCart($tenant, $identity)
|
||||||
|
?? $this->createCart($tenant, $identity);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array{user_id: ?int, guest_token: ?string} $identity
|
||||||
|
*/
|
||||||
|
protected function createCart(Tenant $tenant, array $identity): Cart
|
||||||
{
|
{
|
||||||
$attributes = [
|
$attributes = [
|
||||||
'tenant_codigo' => $tenant->codigo,
|
'tenant_codigo' => $tenant->codigo,
|
||||||
'status' => 'active',
|
'status' => Cart::STATUS_ACTIVE,
|
||||||
|
'origin' => Cart::ORIGIN_USER,
|
||||||
];
|
];
|
||||||
|
|
||||||
if ($identity['user_id'] !== null) {
|
if ($identity['user_id'] !== null) {
|
||||||
|
|||||||
@@ -1,123 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Domains\Cart\Services;
|
|
||||||
|
|
||||||
use App\Domains\Cart\Models\Cart;
|
|
||||||
use App\Domains\Cart\Models\CartItem;
|
|
||||||
use App\Domains\Catalog\Models\Inventory;
|
|
||||||
use App\Domains\Catalog\Models\StockReservation;
|
|
||||||
use Illuminate\Support\Facades\DB;
|
|
||||||
|
|
||||||
class ExpireCartReservationsService
|
|
||||||
{
|
|
||||||
public function expireOverdue(): int
|
|
||||||
{
|
|
||||||
$expiredItems = 0;
|
|
||||||
$lastCartItemId = 0;
|
|
||||||
|
|
||||||
do {
|
|
||||||
$cartItemIds = StockReservation::query()
|
|
||||||
->where('status', StockReservation::STATUS_ACTIVE)
|
|
||||||
->whereNull('purchase_id')
|
|
||||||
->whereNotNull('cart_item_id')
|
|
||||||
->whereNotNull('expires_at')
|
|
||||||
->where('expires_at', '<=', now())
|
|
||||||
->where('cart_item_id', '>', $lastCartItemId)
|
|
||||||
->whereHas('cartItem.cart', fn ($query) => $query->where('status', 'active'))
|
|
||||||
->select('cart_item_id')
|
|
||||||
->distinct()
|
|
||||||
->orderBy('cart_item_id')
|
|
||||||
->limit(500)
|
|
||||||
->pluck('cart_item_id');
|
|
||||||
|
|
||||||
foreach ($cartItemIds as $cartItemId) {
|
|
||||||
$lastCartItemId = (int) $cartItemId;
|
|
||||||
|
|
||||||
if ($this->expireCartItem($lastCartItemId)) {
|
|
||||||
$expiredItems++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} while ($cartItemIds->count() === 500);
|
|
||||||
|
|
||||||
return $expiredItems;
|
|
||||||
}
|
|
||||||
|
|
||||||
private function expireCartItem(int $cartItemId): bool
|
|
||||||
{
|
|
||||||
/** @var CartItem|null $candidate */
|
|
||||||
$candidate = CartItem::query()->select(['id', 'cart_id'])->find($cartItemId);
|
|
||||||
if ($candidate === null) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return DB::transaction(function () use ($candidate, $cartItemId): bool {
|
|
||||||
/** @var Cart|null $cart */
|
|
||||||
$cart = Cart::query()
|
|
||||||
->whereKey($candidate->cart_id)
|
|
||||||
->where('status', 'active')
|
|
||||||
->lockForUpdate()
|
|
||||||
->first();
|
|
||||||
|
|
||||||
if ($cart === null) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @var CartItem|null $cartItem */
|
|
||||||
$cartItem = $cart->items()
|
|
||||||
->whereKey($cartItemId)
|
|
||||||
->lockForUpdate()
|
|
||||||
->first();
|
|
||||||
|
|
||||||
if ($cartItem === null) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
$reservations = StockReservation::query()
|
|
||||||
->where('cart_item_id', $cartItem->getKey())
|
|
||||||
->where('status', StockReservation::STATUS_ACTIVE)
|
|
||||||
->orderBy('inventory_id')
|
|
||||||
->lockForUpdate()
|
|
||||||
->get();
|
|
||||||
|
|
||||||
if (
|
|
||||||
$reservations->isEmpty()
|
|
||||||
|| $reservations->contains(
|
|
||||||
fn (StockReservation $reservation): bool => $reservation->purchase_id !== null
|
|
||||||
|| $reservation->expires_at === null
|
|
||||||
|| $reservation->expires_at->isFuture(),
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
$inventories = Inventory::query()
|
|
||||||
->whereKey($reservations->pluck('inventory_id'))
|
|
||||||
->orderBy('id')
|
|
||||||
->lockForUpdate()
|
|
||||||
->get()
|
|
||||||
->keyBy('id');
|
|
||||||
|
|
||||||
foreach ($reservations as $reservation) {
|
|
||||||
$inventory = $inventories->get($reservation->inventory_id)
|
|
||||||
?? throw new \InvalidArgumentException('No se encontro el inventario reservado.');
|
|
||||||
|
|
||||||
$inventory->release((int) $reservation->quantity);
|
|
||||||
$reservation->update([
|
|
||||||
'quantity' => 0,
|
|
||||||
'status' => StockReservation::STATUS_EXPIRED,
|
|
||||||
'expires_at' => null,
|
|
||||||
'released_at' => now(),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
$cartItem->delete();
|
|
||||||
|
|
||||||
if (! $cart->items()->exists()) {
|
|
||||||
$cart->update(['status' => 'expired']);
|
|
||||||
$cart->delete();
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -6,13 +6,12 @@ Gestiona el carrito activo de un tenant tanto para visitantes como para usuarios
|
|||||||
|
|
||||||
## Modelo
|
## Modelo
|
||||||
|
|
||||||
- `Cart`: pertenece a un tenant y opcionalmente a un usuario; calcula el total y permite agregar, actualizar o quitar ítems.
|
- `Cart`: pertenece a un tenant y opcionalmente a un usuario; calcula el total, permite agregar, actualizar o quitar ítems y apunta a su reserva de stock vigente mediante `current_stock_reservation_id`.
|
||||||
- `CartItem`: referencia un `CatalogItem` y, opcionalmente, una `Variant`; sólo persiste la selección y cantidad, y expone siempre los datos vigentes del catálogo.
|
- `CartItem`: referencia un `CatalogItem` y, opcionalmente, una `Variant`; sólo persiste la selección y cantidad, y expone siempre los datos vigentes del catálogo.
|
||||||
|
|
||||||
## Servicios
|
## Servicios
|
||||||
|
|
||||||
- `CartService`: obtiene el carrito, modifica ítems y administra la cookie del token invitado.
|
- `CartService`: obtiene el carrito, modifica ítems y administra la cookie del token invitado.
|
||||||
- `ExpireCartReservationsService`: libera las reservas vencidas de carritos activos y elimina los carritos que quedan vacíos.
|
|
||||||
- `GuestCartMergeService`: incorpora el carrito invitado al usuario cuando este se autentica.
|
- `GuestCartMergeService`: incorpora el carrito invitado al usuario cuando este se autentica.
|
||||||
|
|
||||||
## Endpoints
|
## Endpoints
|
||||||
@@ -34,4 +33,6 @@ Depende de `Catalog` para productos y variantes, de `Tenant` para aislar datos y
|
|||||||
|
|
||||||
Un carrito puede pasar a `checkout`. Las compras directas usan un carrito técnico con `origin=direct_checkout`; los carritos normales conservan `origin=user` y pueden restaurarse al cancelar o vencer la compra.
|
Un carrito puede pasar a `checkout`. Las compras directas usan un carrito técnico con `origin=direct_checkout`; los carritos normales conservan `origin=user` y pueden restaurarse al cancelar o vencer la compra.
|
||||||
|
|
||||||
El comando unificado `php artisan reservations:expire` procesa primero las compras vencidas y luego las reservas activas sin compra cuyo `expires_at` haya vencido. Se ejecuta cada minuto mediante el scheduler, conserva la fila de reserva con estado `expired`, elimina el ítem abandonado y elimina lógicamente el carrito cuando queda vacío. Cada intento registra sus resultados o su error en el log diario `storage/logs/commands/commands-AAAA-MM-DD.log`.
|
Cada edición sincroniza una única reserva para el carrito completo. Si varios ítems o bundles consumen el mismo inventario, se persiste una sola línea con la cantidad agregada. Al editar durante checkout, la compra anterior queda `superseded`, se desvincula y el carrito conserva la misma reserva activa con sus líneas actualizadas.
|
||||||
|
|
||||||
|
El comando unificado `php artisan reservations:expire` recorre una sola vez las reservas activas cuyo `expires_at` haya vencido. Cuando pertenecen a un carrito, conserva la reserva y sus líneas como historial, libera el stock como conjunto y cambia el carrito asociado a `expired` sin eliminar sus ítems. Al volver a resolver ese carrito desde la API, el anterior pasa automáticamente a `abandoned` y se crea uno activo y vacío para la misma identidad. El cliente nunca necesita reiniciarlo explícitamente. La API también materializa este vencimiento al acceder al carrito aunque el comando programado todavía no haya corrido.
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Catalog\Exceptions;
|
||||||
|
|
||||||
|
use RuntimeException;
|
||||||
|
|
||||||
|
class StockReservationExpiredException extends RuntimeException
|
||||||
|
{
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
parent::__construct(__('api.cart.reservation_expired'));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -48,10 +48,10 @@ class Inventory extends Model
|
|||||||
return $this->hasOne(Variant::class);
|
return $this->hasOne(Variant::class);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return HasMany<StockReservation, $this> */
|
/** @return HasMany<StockReservationLine, $this> */
|
||||||
public function stockReservations(): HasMany
|
public function stockReservationLines(): HasMany
|
||||||
{
|
{
|
||||||
return $this->hasMany(StockReservation::class);
|
return $this->hasMany(StockReservationLine::class);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function availableStock(): int
|
public function availableStock(): int
|
||||||
|
|||||||
@@ -2,21 +2,20 @@
|
|||||||
|
|
||||||
namespace App\Domains\Catalog\Models;
|
namespace App\Domains\Catalog\Models;
|
||||||
|
|
||||||
use App\Domains\Cart\Models\CartItem;
|
use App\Domains\Cart\Models\Cart;
|
||||||
use App\Domains\Purchase\Models\Purchase;
|
use App\Domains\Purchase\Models\Purchase;
|
||||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||||
|
|
||||||
#[Fillable([
|
#[Fillable([
|
||||||
'inventory_id',
|
|
||||||
'cart_item_id',
|
|
||||||
'purchase_id',
|
|
||||||
'quantity',
|
|
||||||
'status',
|
'status',
|
||||||
'expires_at',
|
'expires_at',
|
||||||
'committed_at',
|
'committed_at',
|
||||||
'released_at',
|
'released_at',
|
||||||
|
'expired_at',
|
||||||
|
'release_reason',
|
||||||
])]
|
])]
|
||||||
class StockReservation extends Model
|
class StockReservation extends Model
|
||||||
{
|
{
|
||||||
@@ -31,31 +30,28 @@ class StockReservation extends Model
|
|||||||
protected function casts(): array
|
protected function casts(): array
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'inventory_id' => 'integer',
|
|
||||||
'cart_item_id' => 'integer',
|
|
||||||
'purchase_id' => 'integer',
|
|
||||||
'quantity' => 'integer',
|
|
||||||
'expires_at' => 'datetime',
|
'expires_at' => 'datetime',
|
||||||
'committed_at' => 'datetime',
|
'committed_at' => 'datetime',
|
||||||
'released_at' => 'datetime',
|
'released_at' => 'datetime',
|
||||||
|
'expired_at' => 'datetime',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return BelongsTo<Inventory, $this> */
|
/** @return HasMany<StockReservationLine, $this> */
|
||||||
public function inventory(): BelongsTo
|
public function lines(): HasMany
|
||||||
{
|
{
|
||||||
return $this->belongsTo(Inventory::class);
|
return $this->hasMany(StockReservationLine::class);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return BelongsTo<CartItem, $this> */
|
/** @return HasOne<Cart, $this> */
|
||||||
public function cartItem(): BelongsTo
|
public function currentCart(): HasOne
|
||||||
{
|
{
|
||||||
return $this->belongsTo(CartItem::class);
|
return $this->hasOne(Cart::class, 'current_stock_reservation_id');
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return BelongsTo<Purchase, $this> */
|
/** @return HasOne<Purchase, $this> */
|
||||||
public function purchase(): BelongsTo
|
public function purchase(): HasOne
|
||||||
{
|
{
|
||||||
return $this->belongsTo(Purchase::class);
|
return $this->hasOne(Purchase::class);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
38
app/Domains/Catalog/Models/StockReservationLine.php
Normal file
38
app/Domains/Catalog/Models/StockReservationLine.php
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Catalog\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
|
||||||
|
#[Fillable([
|
||||||
|
'stock_reservation_id',
|
||||||
|
'inventory_id',
|
||||||
|
'quantity',
|
||||||
|
'tracks_inventory',
|
||||||
|
])]
|
||||||
|
class StockReservationLine extends Model
|
||||||
|
{
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'stock_reservation_id' => 'integer',
|
||||||
|
'inventory_id' => 'integer',
|
||||||
|
'quantity' => 'integer',
|
||||||
|
'tracks_inventory' => 'boolean',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return BelongsTo<StockReservation, $this> */
|
||||||
|
public function reservation(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(StockReservation::class, 'stock_reservation_id');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return BelongsTo<Inventory, $this> */
|
||||||
|
public function inventory(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Inventory::class);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -25,6 +25,24 @@ class CatalogInventoryService
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, array{quantity: int, tracks_inventory: bool}>
|
||||||
|
*/
|
||||||
|
public function detailedRequirementsFor(CatalogItem|Variant $selection, int $quantity = 1): array
|
||||||
|
{
|
||||||
|
if ($quantity <= 0) {
|
||||||
|
throw new \InvalidArgumentException('La cantidad debe ser mayor a cero.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return array_map(
|
||||||
|
fn (array $requirement): array => [
|
||||||
|
...$requirement,
|
||||||
|
'quantity' => $requirement['quantity'] * $quantity,
|
||||||
|
],
|
||||||
|
$this->inventoryRequirements($selection),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
public function availableQuantity(CatalogItem|Variant $selection): ?int
|
public function availableQuantity(CatalogItem|Variant $selection): ?int
|
||||||
{
|
{
|
||||||
if ($selection instanceof CatalogItem
|
if ($selection instanceof CatalogItem
|
||||||
|
|||||||
@@ -2,50 +2,184 @@
|
|||||||
|
|
||||||
namespace App\Domains\Catalog\Services;
|
namespace App\Domains\Catalog\Services;
|
||||||
|
|
||||||
use App\Domains\Cart\Services\ExpireCartReservationsService;
|
use App\Domains\Cart\Models\Cart;
|
||||||
use App\Domains\Purchase\Services\CheckoutService;
|
use App\Domains\Catalog\Models\StockReservation;
|
||||||
|
use App\Domains\Purchase\Models\Purchase;
|
||||||
|
use App\Domains\Purchase\Services\Checkout\ReleaseCheckoutService;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\Facades\Log;
|
use Illuminate\Support\Facades\Log;
|
||||||
|
use RuntimeException;
|
||||||
use Throwable;
|
use Throwable;
|
||||||
|
|
||||||
class ExpireStockReservationsService
|
class ExpireStockReservationsService
|
||||||
{
|
{
|
||||||
|
private const BATCH_SIZE = 500;
|
||||||
|
|
||||||
public function __construct(
|
public function __construct(
|
||||||
private readonly CheckoutService $checkout,
|
private readonly ReleaseCheckoutService $purchases,
|
||||||
private readonly ExpireCartReservationsService $carts,
|
private readonly StockReservationService $reservations,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return array{purchases: int, cart_items: int}
|
* @return array{purchases: int, cart_reservations: int, orphan_reservations: int, failed: int}
|
||||||
*/
|
*/
|
||||||
public function expireOverdue(): array
|
public function expireOverdue(): array
|
||||||
{
|
{
|
||||||
$expiredPurchases = null;
|
$summary = [
|
||||||
$expiredCartItems = null;
|
'purchases' => 0,
|
||||||
|
'cart_reservations' => 0,
|
||||||
|
'orphan_reservations' => 0,
|
||||||
|
'failed' => 0,
|
||||||
|
];
|
||||||
|
$lastReservationId = 0;
|
||||||
|
|
||||||
|
do {
|
||||||
|
$reservationIds = StockReservation::query()
|
||||||
|
->where('status', StockReservation::STATUS_ACTIVE)
|
||||||
|
->whereNotNull('expires_at')
|
||||||
|
->where('expires_at', '<=', now())
|
||||||
|
->where('id', '>', $lastReservationId)
|
||||||
|
->orderBy('id')
|
||||||
|
->limit(self::BATCH_SIZE)
|
||||||
|
->pluck('id');
|
||||||
|
|
||||||
|
foreach ($reservationIds as $reservationId) {
|
||||||
|
$lastReservationId = (int) $reservationId;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$expiredPurchases = $this->checkout->expireOverduePurchases();
|
$owner = $this->expireReservation($lastReservationId);
|
||||||
$expiredCartItems = $this->carts->expireOverdue();
|
if ($owner !== null) {
|
||||||
|
$summary[$owner]++;
|
||||||
|
}
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
$summary['failed']++;
|
||||||
|
Log::channel('commands')->error('Failed to expire overdue stock reservation.', [
|
||||||
|
'command' => 'reservations:expire',
|
||||||
|
'stock_reservation_id' => $lastReservationId,
|
||||||
|
'exception' => $exception,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} while ($reservationIds->count() === self::BATCH_SIZE);
|
||||||
|
|
||||||
Log::channel('commands')->info('Stock reservation cleanup completed.', [
|
Log::channel('commands')->info('Stock reservation cleanup completed.', [
|
||||||
'command' => 'reservations:expire',
|
'command' => 'reservations:expire',
|
||||||
'expired_purchases' => $expiredPurchases,
|
'expired_purchases' => $summary['purchases'],
|
||||||
'expired_cart_items' => $expiredCartItems,
|
'expired_cart_reservations' => $summary['cart_reservations'],
|
||||||
'total_expired' => $expiredPurchases + $expiredCartItems,
|
'expired_orphan_reservations' => $summary['orphan_reservations'],
|
||||||
|
'failed_reservations' => $summary['failed'],
|
||||||
|
'total_expired' => $summary['purchases']
|
||||||
|
+ $summary['cart_reservations']
|
||||||
|
+ $summary['orphan_reservations'],
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return [
|
return $summary;
|
||||||
'purchases' => $expiredPurchases,
|
}
|
||||||
'cart_items' => $expiredCartItems,
|
|
||||||
];
|
|
||||||
} catch (Throwable $exception) {
|
|
||||||
Log::channel('commands')->error('Stock reservation cleanup failed.', [
|
|
||||||
'command' => 'reservations:expire',
|
|
||||||
'expired_purchases' => $expiredPurchases,
|
|
||||||
'expired_cart_items' => $expiredCartItems,
|
|
||||||
'exception' => $exception,
|
|
||||||
]);
|
|
||||||
|
|
||||||
throw $exception;
|
public function expireIfOverdue(int $reservationId): bool
|
||||||
}
|
{
|
||||||
|
/** @var StockReservation|null $reservation */
|
||||||
|
$reservation = StockReservation::query()->find($reservationId);
|
||||||
|
if ($reservation?->status === StockReservation::STATUS_EXPIRED) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (! $this->isOverdue($reservation)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->expireReservation($reservationId) !== null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return 'purchases'|'cart_reservations'|'orphan_reservations'|null */
|
||||||
|
private function expireReservation(int $reservationId): ?string
|
||||||
|
{
|
||||||
|
$purchaseId = Purchase::query()
|
||||||
|
->where('stock_reservation_id', $reservationId)
|
||||||
|
->value('id');
|
||||||
|
if ($purchaseId !== null) {
|
||||||
|
return $this->expirePurchase((int) $purchaseId);
|
||||||
|
}
|
||||||
|
|
||||||
|
$cartId = Cart::query()
|
||||||
|
->where('current_stock_reservation_id', $reservationId)
|
||||||
|
->where('status', 'active')
|
||||||
|
->value('id');
|
||||||
|
if ($cartId !== null) {
|
||||||
|
return $this->expireCart((int) $cartId, $reservationId);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->expireOrphan($reservationId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return 'purchases'|null */
|
||||||
|
private function expirePurchase(int $purchaseId): ?string
|
||||||
|
{
|
||||||
|
/** @var Purchase|null $purchase */
|
||||||
|
$purchase = Purchase::query()->find($purchaseId);
|
||||||
|
if ($purchase === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$purchase = $this->purchases->expire($purchase);
|
||||||
|
if ($purchase->status === Purchase::STATUS_EXPIRED) {
|
||||||
|
return 'purchases';
|
||||||
|
}
|
||||||
|
|
||||||
|
$reservation = $purchase->stockReservation;
|
||||||
|
if ($this->isOverdue($reservation)) {
|
||||||
|
throw new RuntimeException('An overdue active reservation belongs to a purchase that cannot expire.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return 'cart_reservations'|null */
|
||||||
|
private function expireCart(int $cartId, int $reservationId): ?string
|
||||||
|
{
|
||||||
|
return DB::transaction(function () use ($cartId, $reservationId): ?string {
|
||||||
|
/** @var Cart|null $cart */
|
||||||
|
$cart = Cart::query()
|
||||||
|
->whereKey($cartId)
|
||||||
|
->where('current_stock_reservation_id', $reservationId)
|
||||||
|
->where('status', Cart::STATUS_ACTIVE)
|
||||||
|
->lockForUpdate()
|
||||||
|
->first();
|
||||||
|
if ($cart === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @var StockReservation|null $reservation */
|
||||||
|
$reservation = StockReservation::query()->lockForUpdate()->find($reservationId);
|
||||||
|
if (! $this->isOverdue($reservation)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->reservations->expire($reservation);
|
||||||
|
$cart->update(['status' => Cart::STATUS_EXPIRED]);
|
||||||
|
|
||||||
|
return 'cart_reservations';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return 'orphan_reservations'|null */
|
||||||
|
private function expireOrphan(int $reservationId): ?string
|
||||||
|
{
|
||||||
|
/** @var StockReservation|null $reservation */
|
||||||
|
$reservation = StockReservation::query()->find($reservationId);
|
||||||
|
if (! $this->isOverdue($reservation)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->reservations->expire($reservation);
|
||||||
|
|
||||||
|
return 'orphan_reservations';
|
||||||
|
}
|
||||||
|
|
||||||
|
private function isOverdue(?StockReservation $reservation): bool
|
||||||
|
{
|
||||||
|
return $reservation !== null
|
||||||
|
&& $reservation->status === StockReservation::STATUS_ACTIVE
|
||||||
|
&& $reservation->expires_at !== null
|
||||||
|
&& ! $reservation->expires_at->isFuture();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,262 +2,486 @@
|
|||||||
|
|
||||||
namespace App\Domains\Catalog\Services;
|
namespace App\Domains\Catalog\Services;
|
||||||
|
|
||||||
|
use App\Domains\Cart\Models\Cart;
|
||||||
use App\Domains\Cart\Models\CartItem;
|
use App\Domains\Cart\Models\CartItem;
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Catalog\Exceptions\StockReservationExpiredException;
|
||||||
|
use App\Domains\Catalog\Models\Inventory;
|
||||||
use App\Domains\Catalog\Models\StockReservation;
|
use App\Domains\Catalog\Models\StockReservation;
|
||||||
use App\Domains\Catalog\Models\Variant;
|
use App\Domains\Catalog\Models\StockReservationLine;
|
||||||
use App\Domains\Purchase\Models\Purchase;
|
use App\Domains\Purchase\Models\Purchase;
|
||||||
use Illuminate\Support\Carbon;
|
use Illuminate\Support\Carbon;
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
class StockReservationService
|
class StockReservationService
|
||||||
{
|
{
|
||||||
|
public const REASON_CART_EMPTY = 'cart_empty';
|
||||||
|
|
||||||
|
public const REASON_CART_CHANGED = 'cart_changed';
|
||||||
|
|
||||||
|
public const REASON_PURCHASE_SUPERSEDED = 'purchase_superseded';
|
||||||
|
|
||||||
|
public const REASON_PURCHASE_CANCELLED = 'purchase_cancelled';
|
||||||
|
|
||||||
|
public const REASON_PAYMENT_REJECTED = 'payment_rejected';
|
||||||
|
|
||||||
|
public const REASON_MANUAL_RELEASE = 'manual_release';
|
||||||
|
|
||||||
public function __construct(
|
public function __construct(
|
||||||
private readonly CatalogInventoryService $inventory,
|
private readonly CatalogInventoryService $inventory,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public function reserve(CartItem $cartItem, CatalogItem|Variant $selection, int $quantity): void
|
public function syncCart(Cart $cart): ?StockReservation
|
||||||
{
|
{
|
||||||
DB::transaction(function () use ($cartItem, $selection, $quantity): void {
|
return DB::transaction(function () use ($cart): ?StockReservation {
|
||||||
$this->inventory->reserve($selection, $quantity);
|
/** @var Cart $lockedCart */
|
||||||
$this->recordIncrease($cartItem, $selection, $quantity);
|
$lockedCart = Cart::query()->lockForUpdate()->findOrFail($cart->getKey());
|
||||||
|
$items = $lockedCart->items()->orderBy('id')->lockForUpdate()->get();
|
||||||
|
$this->loadSelections($items);
|
||||||
|
$requirements = $this->requirementsForItems($items);
|
||||||
|
|
||||||
|
$reservation = $lockedCart->current_stock_reservation_id === null
|
||||||
|
? null
|
||||||
|
: StockReservation::query()->lockForUpdate()->find($lockedCart->current_stock_reservation_id);
|
||||||
|
|
||||||
|
if ($reservation !== null) {
|
||||||
|
$this->assertUsableCartReservation($reservation);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($requirements === []) {
|
||||||
|
if ($reservation !== null && $reservation->status === StockReservation::STATUS_ACTIVE) {
|
||||||
|
$this->finalizeLocked(
|
||||||
|
$reservation,
|
||||||
|
StockReservation::STATUS_RELEASED,
|
||||||
|
self::REASON_CART_EMPTY,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
$lockedCart->update(['current_stock_reservation_id' => null]);
|
||||||
|
$cart->current_stock_reservation_id = null;
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($reservation === null) {
|
||||||
|
$reservation = StockReservation::query()->create([
|
||||||
|
'status' => StockReservation::STATUS_ACTIVE,
|
||||||
|
'expires_at' => $this->expiration(),
|
||||||
|
]);
|
||||||
|
$lockedCart->update(['current_stock_reservation_id' => $reservation->getKey()]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Purchase::query()->where('stock_reservation_id', $reservation->getKey())->exists()) {
|
||||||
|
throw new \InvalidArgumentException('La reserva vinculada a una compra no se puede modificar.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$currentLines = StockReservationLine::query()
|
||||||
|
->where('stock_reservation_id', $reservation->getKey())
|
||||||
|
->orderBy('inventory_id')
|
||||||
|
->lockForUpdate()
|
||||||
|
->get()
|
||||||
|
->keyBy('inventory_id');
|
||||||
|
$inventoryIds = collect(array_keys($requirements))
|
||||||
|
->merge($currentLines->keys())
|
||||||
|
->map(fn ($id): int => (int) $id)
|
||||||
|
->unique()
|
||||||
|
->sort()
|
||||||
|
->values();
|
||||||
|
$inventories = Inventory::query()
|
||||||
|
->whereKey($inventoryIds)
|
||||||
|
->orderBy('id')
|
||||||
|
->lockForUpdate()
|
||||||
|
->get()
|
||||||
|
->keyBy('id');
|
||||||
|
|
||||||
|
foreach ($inventoryIds as $inventoryId) {
|
||||||
|
$inventory = $inventories->get($inventoryId)
|
||||||
|
?? throw new \InvalidArgumentException('No se encontró el inventario requerido.');
|
||||||
|
$previous = (int) ($currentLines->get($inventoryId)?->quantity ?? 0);
|
||||||
|
$required = (int) ($requirements[$inventoryId]['quantity'] ?? 0);
|
||||||
|
$delta = $required - $previous;
|
||||||
|
|
||||||
|
if ($delta > 0
|
||||||
|
&& $requirements[$inventoryId]['tracks_inventory']
|
||||||
|
&& $inventory->availableStock() < $delta) {
|
||||||
|
throw new \InvalidArgumentException('No hay suficiente stock disponible para reservar el carrito.');
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($delta < 0 && $inventory->reserved_stock < abs($delta)) {
|
||||||
|
throw new \InvalidArgumentException('La reserva de stock del carrito es inconsistente.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($inventoryIds as $inventoryId) {
|
||||||
|
/** @var Inventory $inventory */
|
||||||
|
$inventory = $inventories->get($inventoryId);
|
||||||
|
$line = $currentLines->get($inventoryId);
|
||||||
|
$previous = (int) ($line?->quantity ?? 0);
|
||||||
|
$required = (int) ($requirements[$inventoryId]['quantity'] ?? 0);
|
||||||
|
$delta = $required - $previous;
|
||||||
|
|
||||||
|
if ($delta > 0) {
|
||||||
|
$inventory->reserve($delta, $requirements[$inventoryId]['tracks_inventory']);
|
||||||
|
} elseif ($delta < 0) {
|
||||||
|
$inventory->release(abs($delta));
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($required === 0) {
|
||||||
|
$line?->delete();
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
StockReservationLine::query()->updateOrCreate(
|
||||||
|
[
|
||||||
|
'stock_reservation_id' => $reservation->getKey(),
|
||||||
|
'inventory_id' => $inventoryId,
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'quantity' => $required,
|
||||||
|
'tracks_inventory' => $requirements[$inventoryId]['tracks_inventory'],
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
$reservation->update([
|
||||||
|
'expires_at' => $this->expiration(),
|
||||||
|
'release_reason' => null,
|
||||||
|
]);
|
||||||
|
$cart->current_stock_reservation_id = $reservation->getKey();
|
||||||
|
|
||||||
|
return $reservation->fresh('lines');
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public function release(
|
public function attachToPurchase(
|
||||||
CartItem $cartItem,
|
Cart $cart,
|
||||||
CatalogItem|Variant $selection,
|
|
||||||
int $quantity,
|
|
||||||
string $releasedStatus = StockReservation::STATUS_RELEASED,
|
|
||||||
): void {
|
|
||||||
DB::transaction(function () use ($cartItem, $selection, $quantity, $releasedStatus): void {
|
|
||||||
$this->ensure($cartItem, $selection);
|
|
||||||
$this->inventory->release($selection, $quantity);
|
|
||||||
$this->recordDecrease($cartItem, $selection, $quantity, $releasedStatus);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
public function commit(
|
|
||||||
CartItem $cartItem,
|
|
||||||
CatalogItem|Variant $selection,
|
|
||||||
Purchase $purchase,
|
Purchase $purchase,
|
||||||
): void {
|
Carbon $expiresAt,
|
||||||
DB::transaction(function () use ($cartItem, $selection, $purchase): void {
|
): StockReservation {
|
||||||
$this->ensure($cartItem, $selection);
|
return DB::transaction(function () use ($cart, $purchase, $expiresAt): StockReservation {
|
||||||
$this->inventory->commit($selection, (int) $cartItem->cantidad);
|
/** @var Cart $lockedCart */
|
||||||
|
$lockedCart = Cart::query()->lockForUpdate()->findOrFail($cart->getKey());
|
||||||
|
/** @var Purchase $lockedPurchase */
|
||||||
|
$lockedPurchase = Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey());
|
||||||
|
|
||||||
$requirements = $this->inventory->requirementsFor($selection, (int) $cartItem->cantidad);
|
if ($lockedCart->current_stock_reservation_id === null) {
|
||||||
foreach ($requirements as $inventoryId => $quantity) {
|
throw new \InvalidArgumentException('El carrito no tiene una reserva de stock activa.');
|
||||||
$reservation = $this->lockReservation($cartItem, $inventoryId);
|
}
|
||||||
if (
|
|
||||||
$reservation === null
|
/** @var StockReservation $reservation */
|
||||||
|| $reservation->status !== StockReservation::STATUS_ACTIVE
|
$reservation = StockReservation::query()->lockForUpdate()->findOrFail($lockedCart->current_stock_reservation_id);
|
||||||
|| $reservation->purchase_id !== $purchase->getKey()
|
$this->assertUsableCartReservation($reservation);
|
||||||
|| $reservation->quantity !== $quantity
|
|
||||||
) {
|
$linkedPurchase = Purchase::query()
|
||||||
throw new \InvalidArgumentException('La reserva de stock no coincide con el item del carrito.');
|
->where('stock_reservation_id', $reservation->getKey())
|
||||||
|
->whereKeyNot($lockedPurchase->getKey())
|
||||||
|
->exists();
|
||||||
|
if ($linkedPurchase) {
|
||||||
|
throw new \InvalidArgumentException('La reserva de stock ya pertenece a otra compra.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$lockedPurchase->update(['stock_reservation_id' => $reservation->getKey()]);
|
||||||
|
$reservation->update(['expires_at' => $expiresAt]);
|
||||||
|
$purchase->stock_reservation_id = $reservation->getKey();
|
||||||
|
$cart->current_stock_reservation_id = $reservation->getKey();
|
||||||
|
|
||||||
|
return $reservation->fresh('lines');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function commit(Purchase $purchase): void
|
||||||
|
{
|
||||||
|
DB::transaction(function () use ($purchase): void {
|
||||||
|
/** @var Purchase $purchase */
|
||||||
|
$purchase = Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey());
|
||||||
|
if ($purchase->stock_reservation_id === null) {
|
||||||
|
throw new \InvalidArgumentException('La compra no tiene una reserva de stock.');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @var StockReservation $reservation */
|
||||||
|
$reservation = StockReservation::query()->lockForUpdate()->findOrFail($purchase->stock_reservation_id);
|
||||||
|
if ($reservation->status === StockReservation::STATUS_COMMITTED) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ($reservation->status !== StockReservation::STATUS_ACTIVE) {
|
||||||
|
throw new \InvalidArgumentException('La reserva de stock no está activa.');
|
||||||
|
}
|
||||||
|
if ($reservation->expires_at !== null && ! $reservation->expires_at->isFuture()) {
|
||||||
|
throw new StockReservationExpiredException;
|
||||||
|
}
|
||||||
|
|
||||||
|
$lines = $this->lockLines($reservation);
|
||||||
|
if ($lines->isEmpty()) {
|
||||||
|
throw new \InvalidArgumentException('La reserva de stock no tiene inventarios.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$inventories = $this->lockInventories($lines);
|
||||||
|
foreach ($lines as $line) {
|
||||||
|
$inventory = $inventories->get($line->inventory_id)
|
||||||
|
?? throw new \InvalidArgumentException('No se encontró el inventario reservado.');
|
||||||
|
if ($inventory->reserved_stock < $line->quantity
|
||||||
|
|| ($line->tracks_inventory && $inventory->real_stock < $line->quantity)) {
|
||||||
|
throw new \InvalidArgumentException('La reserva de stock no alcanza para confirmar la compra.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($lines as $line) {
|
||||||
|
$inventories->get($line->inventory_id)->buy(
|
||||||
|
(int) $line->quantity,
|
||||||
|
(bool) $line->tracks_inventory,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
$reservation->update([
|
$reservation->update([
|
||||||
'status' => StockReservation::STATUS_COMMITTED,
|
'status' => StockReservation::STATUS_COMMITTED,
|
||||||
'committed_at' => now(),
|
|
||||||
'expires_at' => null,
|
'expires_at' => null,
|
||||||
]);
|
'committed_at' => now(),
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
public function ensure(CartItem $cartItem, CatalogItem|Variant $selection): void
|
|
||||||
{
|
|
||||||
$requirements = $this->inventory->requirementsFor($selection, (int) $cartItem->cantidad);
|
|
||||||
|
|
||||||
foreach ($requirements as $inventoryId => $quantity) {
|
|
||||||
$reservation = $this->lockReservation($cartItem, $inventoryId);
|
|
||||||
|
|
||||||
if ($reservation === null) {
|
|
||||||
StockReservation::query()->create([
|
|
||||||
'inventory_id' => $inventoryId,
|
|
||||||
'cart_item_id' => $cartItem->getKey(),
|
|
||||||
'quantity' => $quantity,
|
|
||||||
'status' => StockReservation::STATUS_ACTIVE,
|
|
||||||
'expires_at' => $this->expiration(),
|
|
||||||
]);
|
|
||||||
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($reservation->status !== StockReservation::STATUS_ACTIVE || $reservation->quantity !== $quantity) {
|
|
||||||
$reservation->update([
|
|
||||||
'quantity' => $quantity,
|
|
||||||
'status' => StockReservation::STATUS_ACTIVE,
|
|
||||||
'committed_at' => null,
|
|
||||||
'released_at' => null,
|
'released_at' => null,
|
||||||
'expires_at' => $this->expiration(),
|
'expired_at' => null,
|
||||||
]);
|
'release_reason' => null,
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public function attachToPurchase(
|
|
||||||
CartItem $cartItem,
|
|
||||||
CatalogItem|Variant $selection,
|
|
||||||
Purchase $purchase,
|
|
||||||
): void {
|
|
||||||
DB::transaction(function () use ($cartItem, $selection, $purchase): void {
|
|
||||||
$this->ensure($cartItem, $selection);
|
|
||||||
StockReservation::query()
|
|
||||||
->where('cart_item_id', $cartItem->getKey())
|
|
||||||
->where('status', StockReservation::STATUS_ACTIVE)
|
|
||||||
->update([
|
|
||||||
'purchase_id' => $purchase->getKey(),
|
|
||||||
'expires_at' => $purchase->expires_at,
|
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public function detachFromPurchase(Purchase $purchase): void
|
public function releaseForPurchase(
|
||||||
{
|
Purchase $purchase,
|
||||||
StockReservation::query()
|
string $status = StockReservation::STATUS_RELEASED,
|
||||||
->where('purchase_id', $purchase->getKey())
|
?string $reason = null,
|
||||||
->where('status', StockReservation::STATUS_ACTIVE)
|
): void {
|
||||||
->update([
|
DB::transaction(function () use ($purchase, $status, $reason): void {
|
||||||
'purchase_id' => null,
|
/** @var Purchase $purchase */
|
||||||
'expires_at' => $this->expiration(),
|
$purchase = Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey());
|
||||||
]);
|
if ($purchase->stock_reservation_id === null) {
|
||||||
}
|
|
||||||
|
|
||||||
public function restore(CartItem $cartItem, CatalogItem|Variant $selection): void
|
|
||||||
{
|
|
||||||
DB::transaction(function () use ($cartItem, $selection): void {
|
|
||||||
$requirements = $this->inventory->requirementsFor(
|
|
||||||
$selection,
|
|
||||||
(int) $cartItem->cantidad,
|
|
||||||
);
|
|
||||||
$activeReservations = StockReservation::query()
|
|
||||||
->where('cart_item_id', $cartItem->getKey())
|
|
||||||
->where('status', StockReservation::STATUS_ACTIVE)
|
|
||||||
->lockForUpdate()
|
|
||||||
->get()
|
|
||||||
->keyBy('inventory_id');
|
|
||||||
|
|
||||||
$hasCompleteReservation = collect($requirements)->every(
|
|
||||||
fn (int $quantity, int $inventoryId): bool => (int) ($activeReservations->get($inventoryId)?->quantity ?? 0) === $quantity,
|
|
||||||
);
|
|
||||||
|
|
||||||
if ($hasCompleteReservation) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($activeReservations->isNotEmpty()) {
|
/** @var StockReservation|null $reservation */
|
||||||
throw new \InvalidArgumentException('La reserva de stock del carrito es inconsistente.');
|
$reservation = StockReservation::query()->lockForUpdate()->find($purchase->stock_reservation_id);
|
||||||
|
if ($reservation !== null) {
|
||||||
|
$this->finalizeLocked($reservation, $status, $reason);
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->inventory->reserve($selection, (int) $cartItem->cantidad);
|
|
||||||
$this->recordIncrease($cartItem, $selection, (int) $cartItem->cantidad);
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public function syncPurchaseExpiration(Purchase $purchase): void
|
public function returnToCart(Purchase $purchase, Cart $cart): StockReservation
|
||||||
{
|
{
|
||||||
StockReservation::query()
|
return DB::transaction(function () use ($purchase, $cart): StockReservation {
|
||||||
->where('purchase_id', $purchase->getKey())
|
/** @var Purchase $purchase */
|
||||||
->where('status', StockReservation::STATUS_ACTIVE)
|
$purchase = Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey());
|
||||||
->update(['expires_at' => $purchase->expires_at]);
|
/** @var Cart $cart */
|
||||||
|
$cart = Cart::query()->lockForUpdate()->findOrFail($cart->getKey());
|
||||||
|
|
||||||
|
if ($purchase->stock_reservation_id === null
|
||||||
|
|| $cart->current_stock_reservation_id !== $purchase->stock_reservation_id) {
|
||||||
|
throw new \InvalidArgumentException('La compra y el carrito no comparten la reserva activa.');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function transfer(CartItem $source, CartItem $target): void
|
/** @var StockReservation $reservation */
|
||||||
|
$reservation = StockReservation::query()
|
||||||
|
->lockForUpdate()
|
||||||
|
->findOrFail($purchase->stock_reservation_id);
|
||||||
|
$this->assertUsableCartReservation($reservation);
|
||||||
|
|
||||||
|
$purchase->update(['stock_reservation_id' => null]);
|
||||||
|
$cart->update(['current_purchase_id' => null]);
|
||||||
|
$reservation->update(['expires_at' => $this->expiration()]);
|
||||||
|
|
||||||
|
return $reservation->fresh('lines');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function assertCartReservationUsable(Cart $cart): void
|
||||||
{
|
{
|
||||||
DB::transaction(function () use ($source, $target): void {
|
DB::transaction(function () use ($cart): void {
|
||||||
$sourceReservations = StockReservation::query()
|
/** @var Cart $cart */
|
||||||
->where('cart_item_id', $source->getKey())
|
$cart = Cart::query()->lockForUpdate()->findOrFail($cart->getKey());
|
||||||
->where('status', StockReservation::STATUS_ACTIVE)
|
if ($cart->current_stock_reservation_id === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @var StockReservation $reservation */
|
||||||
|
$reservation = StockReservation::query()
|
||||||
|
->lockForUpdate()
|
||||||
|
->findOrFail($cart->current_stock_reservation_id);
|
||||||
|
$this->assertUsableCartReservation($reservation);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function releaseCurrentCartReservation(
|
||||||
|
Cart $cart,
|
||||||
|
string $reason = self::REASON_CART_CHANGED,
|
||||||
|
): void {
|
||||||
|
DB::transaction(function () use ($cart, $reason): void {
|
||||||
|
/** @var Cart $cart */
|
||||||
|
$cart = Cart::query()->lockForUpdate()->findOrFail($cart->getKey());
|
||||||
|
if ($cart->current_stock_reservation_id === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @var StockReservation|null $reservation */
|
||||||
|
$reservation = StockReservation::query()->lockForUpdate()->find($cart->current_stock_reservation_id);
|
||||||
|
if ($reservation !== null) {
|
||||||
|
$this->finalizeLocked($reservation, StockReservation::STATUS_RELEASED, $reason);
|
||||||
|
}
|
||||||
|
$cart->update(['current_stock_reservation_id' => null]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function expire(StockReservation $reservation): void
|
||||||
|
{
|
||||||
|
DB::transaction(function () use ($reservation): void {
|
||||||
|
/** @var StockReservation $reservation */
|
||||||
|
$reservation = StockReservation::query()->lockForUpdate()->findOrFail($reservation->getKey());
|
||||||
|
if ($reservation->status !== StockReservation::STATUS_ACTIVE
|
||||||
|
|| $reservation->expires_at === null
|
||||||
|
|| $reservation->expires_at->isFuture()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->finalizeLocked($reservation, StockReservation::STATUS_EXPIRED, null);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function clearExpirationForReview(Purchase $purchase): void
|
||||||
|
{
|
||||||
|
DB::transaction(function () use ($purchase): void {
|
||||||
|
/** @var Purchase $purchase */
|
||||||
|
$purchase = Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey());
|
||||||
|
if ($purchase->stock_reservation_id === null) {
|
||||||
|
throw new \InvalidArgumentException('La compra no tiene una reserva de stock.');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @var StockReservation $reservation */
|
||||||
|
$reservation = StockReservation::query()
|
||||||
|
->lockForUpdate()
|
||||||
|
->findOrFail($purchase->stock_reservation_id);
|
||||||
|
if ($reservation->status !== StockReservation::STATUS_ACTIVE) {
|
||||||
|
throw new \InvalidArgumentException('La reserva de stock no está activa.');
|
||||||
|
}
|
||||||
|
if ($reservation->expires_at !== null && ! $reservation->expires_at->isFuture()) {
|
||||||
|
throw new StockReservationExpiredException;
|
||||||
|
}
|
||||||
|
|
||||||
|
$reservation->update(['expires_at' => null]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param Collection<int, CartItem> $items
|
||||||
|
* @return array<int, array{quantity: int, tracks_inventory: bool}>
|
||||||
|
*/
|
||||||
|
private function requirementsForItems(Collection $items): array
|
||||||
|
{
|
||||||
|
$requirements = [];
|
||||||
|
foreach ($items as $item) {
|
||||||
|
$selection = $item->selectedItem();
|
||||||
|
if ($selection === null) {
|
||||||
|
throw new \InvalidArgumentException('El carrito contiene un item de catálogo inexistente.');
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($this->inventory->detailedRequirementsFor($selection, (int) $item->cantidad) as $inventoryId => $requirement) {
|
||||||
|
if (isset($requirements[$inventoryId])) {
|
||||||
|
$requirements[$inventoryId]['quantity'] += $requirement['quantity'];
|
||||||
|
$requirements[$inventoryId]['tracks_inventory'] =
|
||||||
|
$requirements[$inventoryId]['tracks_inventory'] || $requirement['tracks_inventory'];
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$requirements[$inventoryId] = $requirement;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ksort($requirements);
|
||||||
|
|
||||||
|
return $requirements;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param Collection<int, CartItem> $items */
|
||||||
|
private function loadSelections(Collection $items): void
|
||||||
|
{
|
||||||
|
$items->load([
|
||||||
|
'catalogItem.inventory',
|
||||||
|
'catalogItem.bundleComponents.catalogItem.inventory',
|
||||||
|
'catalogItem.bundleComponents.variant.inventory',
|
||||||
|
'catalogItem.bundleComponents.variant.catalogItem',
|
||||||
|
'variant.inventory',
|
||||||
|
'variant.catalogItem',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return Collection<int, StockReservationLine> */
|
||||||
|
private function lockLines(StockReservation $reservation): Collection
|
||||||
|
{
|
||||||
|
return StockReservationLine::query()
|
||||||
|
->where('stock_reservation_id', $reservation->getKey())
|
||||||
->orderBy('inventory_id')
|
->orderBy('inventory_id')
|
||||||
->lockForUpdate()
|
->lockForUpdate()
|
||||||
->get();
|
->get();
|
||||||
|
|
||||||
foreach ($sourceReservations as $sourceReservation) {
|
|
||||||
$targetReservation = $this->lockReservation($target, (int) $sourceReservation->inventory_id);
|
|
||||||
|
|
||||||
if ($targetReservation === null) {
|
|
||||||
$sourceItemQuantity = (int) $source->cantidad;
|
|
||||||
$targetItemQuantity = (int) $target->fresh()->cantidad;
|
|
||||||
$perItemQuantity = intdiv((int) $sourceReservation->quantity, $sourceItemQuantity);
|
|
||||||
$sourceReservation->update([
|
|
||||||
'cart_item_id' => $target->getKey(),
|
|
||||||
'purchase_id' => null,
|
|
||||||
'quantity' => $perItemQuantity * $targetItemQuantity,
|
|
||||||
'expires_at' => $this->expiration(),
|
|
||||||
]);
|
|
||||||
|
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$targetReservation->update([
|
/**
|
||||||
'quantity' => $targetReservation->quantity + $sourceReservation->quantity,
|
* @param Collection<int, StockReservationLine> $lines
|
||||||
'status' => StockReservation::STATUS_ACTIVE,
|
* @return Collection<int, Inventory>
|
||||||
'expires_at' => $this->expiration(),
|
*/
|
||||||
]);
|
private function lockInventories(Collection $lines): Collection
|
||||||
$sourceReservation->delete();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private function recordIncrease(CartItem $cartItem, CatalogItem|Variant $selection, int $quantity): void
|
|
||||||
{
|
{
|
||||||
foreach ($this->inventory->requirementsFor($selection, $quantity) as $inventoryId => $requiredQuantity) {
|
return Inventory::query()
|
||||||
$reservation = $this->lockReservation($cartItem, $inventoryId);
|
->whereKey($lines->pluck('inventory_id'))
|
||||||
|
->orderBy('id')
|
||||||
if ($reservation === null) {
|
|
||||||
StockReservation::query()->create([
|
|
||||||
'inventory_id' => $inventoryId,
|
|
||||||
'cart_item_id' => $cartItem->getKey(),
|
|
||||||
'quantity' => $requiredQuantity,
|
|
||||||
'status' => StockReservation::STATUS_ACTIVE,
|
|
||||||
'expires_at' => $this->expiration(),
|
|
||||||
]);
|
|
||||||
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
$reservation->update([
|
|
||||||
'quantity' => ($reservation->status === StockReservation::STATUS_ACTIVE ? $reservation->quantity : 0) + $requiredQuantity,
|
|
||||||
'status' => StockReservation::STATUS_ACTIVE,
|
|
||||||
'committed_at' => null,
|
|
||||||
'released_at' => null,
|
|
||||||
'expires_at' => $this->expiration(),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private function recordDecrease(
|
|
||||||
CartItem $cartItem,
|
|
||||||
CatalogItem|Variant $selection,
|
|
||||||
int $quantity,
|
|
||||||
string $releasedStatus,
|
|
||||||
): void {
|
|
||||||
foreach ($this->inventory->requirementsFor($selection, $quantity) as $inventoryId => $requiredQuantity) {
|
|
||||||
$reservation = $this->lockReservation($cartItem, $inventoryId);
|
|
||||||
if ($reservation === null || $reservation->status !== StockReservation::STATUS_ACTIVE || $reservation->quantity < $requiredQuantity) {
|
|
||||||
throw new \InvalidArgumentException('La reserva de stock no alcanza para liberar la cantidad solicitada.');
|
|
||||||
}
|
|
||||||
|
|
||||||
$remaining = $reservation->quantity - $requiredQuantity;
|
|
||||||
$reservation->update([
|
|
||||||
'quantity' => $remaining,
|
|
||||||
'status' => $remaining === 0 ? $releasedStatus : StockReservation::STATUS_ACTIVE,
|
|
||||||
'released_at' => $remaining === 0 ? now() : null,
|
|
||||||
'expires_at' => $remaining === 0 ? null : $reservation->expires_at,
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private function lockReservation(CartItem $cartItem, int $inventoryId): ?StockReservation
|
|
||||||
{
|
|
||||||
return StockReservation::query()
|
|
||||||
->where('cart_item_id', $cartItem->getKey())
|
|
||||||
->where('inventory_id', $inventoryId)
|
|
||||||
->lockForUpdate()
|
->lockForUpdate()
|
||||||
->first();
|
->get()
|
||||||
|
->keyBy('id');
|
||||||
|
}
|
||||||
|
|
||||||
|
private function finalizeLocked(
|
||||||
|
StockReservation $reservation,
|
||||||
|
string $status,
|
||||||
|
?string $reason,
|
||||||
|
): void {
|
||||||
|
if ($reservation->status !== StockReservation::STATUS_ACTIVE) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (! in_array($status, [StockReservation::STATUS_RELEASED, StockReservation::STATUS_EXPIRED], true)) {
|
||||||
|
throw new \InvalidArgumentException('El estado final de la reserva no es válido.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$lines = $this->lockLines($reservation);
|
||||||
|
$inventories = $this->lockInventories($lines);
|
||||||
|
foreach ($lines as $line) {
|
||||||
|
$inventory = $inventories->get($line->inventory_id)
|
||||||
|
?? throw new \InvalidArgumentException('No se encontró el inventario reservado.');
|
||||||
|
$inventory->release((int) $line->quantity);
|
||||||
|
}
|
||||||
|
|
||||||
|
$now = now();
|
||||||
|
$reservation->update([
|
||||||
|
'status' => $status,
|
||||||
|
'expires_at' => null,
|
||||||
|
'released_at' => $status === StockReservation::STATUS_RELEASED ? $now : null,
|
||||||
|
'expired_at' => $status === StockReservation::STATUS_EXPIRED ? $now : null,
|
||||||
|
'release_reason' => $status === StockReservation::STATUS_RELEASED ? $reason : null,
|
||||||
|
]);
|
||||||
|
|
||||||
|
if ($status === StockReservation::STATUS_RELEASED) {
|
||||||
|
Cart::query()
|
||||||
|
->where('current_stock_reservation_id', $reservation->getKey())
|
||||||
|
->update(['current_stock_reservation_id' => null]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function assertUsableCartReservation(StockReservation $reservation): void
|
||||||
|
{
|
||||||
|
if ($reservation->status === StockReservation::STATUS_EXPIRED
|
||||||
|
|| ($reservation->expires_at !== null && ! $reservation->expires_at->isFuture())) {
|
||||||
|
throw new StockReservationExpiredException;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($reservation->status !== StockReservation::STATUS_ACTIVE
|
||||||
|
|| $reservation->expires_at === null) {
|
||||||
|
throw new \InvalidArgumentException('La reserva de stock no está disponible para operar el carrito.');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private function expiration(): Carbon
|
private function expiration(): Carbon
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ Modela y publica la oferta comercial del tenant: productos, variantes, categorí
|
|||||||
- `CatalogItem` es la raíz del producto y se relaciona con tenant, categoría, marca, inventario, variantes, atributos, adjuntos y grupos destacados.
|
- `CatalogItem` es la raíz del producto y se relaciona con tenant, categoría, marca, inventario, variantes, atributos, adjuntos y grupos destacados.
|
||||||
- `Variant`, `ItemAttribute`, `Attribute`, `AttributeOption` y `VariantDefinition` describen opciones comercializables.
|
- `Variant`, `ItemAttribute`, `Attribute`, `AttributeOption` y `VariantDefinition` describen opciones comercializables.
|
||||||
- `Inventory` administra stock disponible, reservado y comprado.
|
- `Inventory` administra stock disponible, reservado y comprado.
|
||||||
- `StockReservation` atribuye cada unidad reservada a un ítem de carrito y, durante checkout, a una compra, con estados `active`, `committed`, `released` y `expired`.
|
- `StockReservation` representa la reserva completa de un carrito o checkout, con estados `active`, `committed`, `released` y `expired`. Su `expires_at` es el único reloj del bloqueo. Al expirar, también pasan a `expired` la compra pagable y el carrito asociados dentro de la misma transacción. Sus estados terminales nunca se reactivan ni se reemplazan implícitamente. Sus `StockReservationLine` agregan la cantidad requerida por inventario, incluso cuando varios ítems o bundles consumen el mismo stock.
|
||||||
- `Category` soporta jerarquía y categorías globales o propias del tenant.
|
- `Category` soporta jerarquía y categorías globales o propias del tenant.
|
||||||
- `FeaturedGroup` y `FeaturedItem` organizan secciones destacadas.
|
- `FeaturedGroup` y `FeaturedItem` organizan secciones destacadas.
|
||||||
- `BundleComponent` representa los componentes de un paquete.
|
- `BundleComponent` representa los componentes de un paquete.
|
||||||
@@ -18,7 +18,8 @@ Modela y publica la oferta comercial del tenant: productos, variantes, categorí
|
|||||||
|
|
||||||
- `CatalogService`: alta, búsqueda, detalle, listado por categoría y eliminación.
|
- `CatalogService`: alta, búsqueda, detalle, listado por categoría y eliminación.
|
||||||
- `CatalogInventoryService`: consulta, reserva, libera y confirma inventario.
|
- `CatalogInventoryService`: consulta, reserva, libera y confirma inventario.
|
||||||
- `StockReservationService`: mantiene el ledger de reservas sincronizado con `Inventory.reserved_stock`.
|
- `StockReservationService`: sincroniza el carrito como conjunto, bloquea todos sus inventarios en orden estable y mantiene el ledger agregado consistente con `Inventory.reserved_stock`.
|
||||||
|
- `ExpireStockReservationsService`: detecta en un único recorrido reservas vencidas de compras, carritos y huérfanas, y delega los efectos comerciales sin mezclar esas reglas con la liberación física del inventario.
|
||||||
- `FeaturedGroupService`: pagina los ítems destacados para la tienda.
|
- `FeaturedGroupService`: pagina los ítems destacados para la tienda.
|
||||||
- `OnTicketFeaturedGroupService`: administra grupos destacados del panel para sitios de tickets.
|
- `OnTicketFeaturedGroupService`: administra grupos destacados del panel para sitios de tickets.
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ namespace App\Domains\Desfile\Services;
|
|||||||
use DateTimeInterface;
|
use DateTimeInterface;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\Facades\Hash;
|
use Illuminate\Support\Facades\Hash;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
use Illuminate\Support\Str;
|
use Illuminate\Support\Str;
|
||||||
use RuntimeException;
|
use RuntimeException;
|
||||||
|
|
||||||
@@ -22,7 +23,7 @@ class InvitationPurchaseProvisioner
|
|||||||
private const ALLOCATIONS = [
|
private const ALLOCATIONS = [
|
||||||
['sector' => 'A', 'row' => 1, 'first_seat' => 1, 'last_seat' => 16, 'type' => 'NORMAL'],
|
['sector' => 'A', 'row' => 1, 'first_seat' => 1, 'last_seat' => 16, 'type' => 'NORMAL'],
|
||||||
['sector' => 'A', 'row' => 3, 'first_seat' => 1, 'last_seat' => 14, 'type' => 'NORMAL'],
|
['sector' => 'A', 'row' => 3, 'first_seat' => 1, 'last_seat' => 14, 'type' => 'NORMAL'],
|
||||||
['sector' => 'C', 'row' => 1, 'first_seat' => 1, 'last_seat' => 16, 'type' => 'VIP + LUNCH'],
|
['sector' => 'C', 'row' => 1, 'first_seat' => 1, 'last_seat' => 17, 'type' => 'VIP + LUNCH'],
|
||||||
['sector' => 'C', 'row' => 3, 'first_seat' => 6, 'last_seat' => 7, 'type' => 'NORMAL'],
|
['sector' => 'C', 'row' => 3, 'first_seat' => 6, 'last_seat' => 7, 'type' => 'NORMAL'],
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -58,7 +59,7 @@ class InvitationPurchaseProvisioner
|
|||||||
$allocation['type'],
|
$allocation['type'],
|
||||||
);
|
);
|
||||||
|
|
||||||
$this->createPurchaseItem(
|
$purchaseItemId = $this->createPurchaseItem(
|
||||||
$purchaseId,
|
$purchaseId,
|
||||||
$catalogItem,
|
$catalogItem,
|
||||||
$variant,
|
$variant,
|
||||||
@@ -70,6 +71,7 @@ class InvitationPurchaseProvisioner
|
|||||||
);
|
);
|
||||||
$this->createTicketAndCommitStock(
|
$this->createTicketAndCommitStock(
|
||||||
$purchaseId,
|
$purchaseId,
|
||||||
|
$purchaseItemId,
|
||||||
$userId,
|
$userId,
|
||||||
(int) $catalogItem->id,
|
(int) $catalogItem->id,
|
||||||
$variant,
|
$variant,
|
||||||
@@ -144,7 +146,6 @@ class InvitationPurchaseProvisioner
|
|||||||
if ($purchaseId !== null) {
|
if ($purchaseId !== null) {
|
||||||
DB::table('compras')->where('id', $purchaseId)->update([
|
DB::table('compras')->where('id', $purchaseId)->update([
|
||||||
'status' => 'paid',
|
'status' => 'paid',
|
||||||
'expires_at' => null,
|
|
||||||
'total' => 0,
|
'total' => 0,
|
||||||
'updated_at' => $now,
|
'updated_at' => $now,
|
||||||
]);
|
]);
|
||||||
@@ -158,7 +159,6 @@ class InvitationPurchaseProvisioner
|
|||||||
'cart_id' => null,
|
'cart_id' => null,
|
||||||
'status' => 'paid',
|
'status' => 'paid',
|
||||||
'payment_method' => self::PAYMENT_METHOD,
|
'payment_method' => self::PAYMENT_METHOD,
|
||||||
'expires_at' => null,
|
|
||||||
'total' => 0,
|
'total' => 0,
|
||||||
'dni' => null,
|
'dni' => null,
|
||||||
'transfer_payer_dni' => null,
|
'transfer_payer_dni' => null,
|
||||||
@@ -328,12 +328,13 @@ class InvitationPurchaseProvisioner
|
|||||||
int $seat,
|
int $seat,
|
||||||
string $type,
|
string $type,
|
||||||
DateTimeInterface $now,
|
DateTimeInterface $now,
|
||||||
): void {
|
): int {
|
||||||
if (DB::table('compra_items')
|
$existingId = DB::table('compra_items')
|
||||||
->where('compra_id', $purchaseId)
|
->where('compra_id', $purchaseId)
|
||||||
->where('source_variant_id', $variant->id)
|
->where('source_variant_id', $variant->id)
|
||||||
->exists()) {
|
->value('id');
|
||||||
return;
|
if ($existingId !== null) {
|
||||||
|
return (int) $existingId;
|
||||||
}
|
}
|
||||||
|
|
||||||
$attributes = [
|
$attributes = [
|
||||||
@@ -343,7 +344,7 @@ class InvitationPurchaseProvisioner
|
|||||||
['name' => 'Asiento', 'value' => (string) $seat],
|
['name' => 'Asiento', 'value' => (string) $seat],
|
||||||
];
|
];
|
||||||
|
|
||||||
DB::table('compra_items')->insert([
|
return DB::table('compra_items')->insertGetId([
|
||||||
'compra_id' => $purchaseId,
|
'compra_id' => $purchaseId,
|
||||||
'source_catalog_item_id' => $catalogItem->id,
|
'source_catalog_item_id' => $catalogItem->id,
|
||||||
'source_variant_id' => $variant->id,
|
'source_variant_id' => $variant->id,
|
||||||
@@ -369,13 +370,18 @@ class InvitationPurchaseProvisioner
|
|||||||
|
|
||||||
private function createTicketAndCommitStock(
|
private function createTicketAndCommitStock(
|
||||||
int $purchaseId,
|
int $purchaseId,
|
||||||
|
int $purchaseItemId,
|
||||||
int $userId,
|
int $userId,
|
||||||
int $catalogItemId,
|
int $catalogItemId,
|
||||||
object $variant,
|
object $variant,
|
||||||
DateTimeInterface $now,
|
DateTimeInterface $now,
|
||||||
): void {
|
): void {
|
||||||
|
$purchaseReference = Schema::hasColumn('tickets', 'source_purchase_item_id')
|
||||||
|
? ['source_purchase_item_id' => $purchaseItemId]
|
||||||
|
: ['source_purchase_id' => $purchaseId];
|
||||||
|
|
||||||
if (DB::table('tickets')
|
if (DB::table('tickets')
|
||||||
->where('source_purchase_id', $purchaseId)
|
->where($purchaseReference)
|
||||||
->where('source_variant_id', $variant->id)
|
->where('source_variant_id', $variant->id)
|
||||||
->exists()) {
|
->exists()) {
|
||||||
return;
|
return;
|
||||||
@@ -392,15 +398,27 @@ class InvitationPurchaseProvisioner
|
|||||||
'sold_units' => $inventory->sold_units + 1,
|
'sold_units' => $inventory->sold_units + 1,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
DB::table('stock_reservations')->insert([
|
$reservationId = DB::table('compras')->where('id', $purchaseId)->value('stock_reservation_id');
|
||||||
'inventory_id' => $inventory->id,
|
if ($reservationId === null) {
|
||||||
'cart_item_id' => null,
|
$reservationId = DB::table('stock_reservations')->insertGetId([
|
||||||
'purchase_id' => $purchaseId,
|
|
||||||
'quantity' => 1,
|
|
||||||
'status' => 'committed',
|
'status' => 'committed',
|
||||||
'expires_at' => null,
|
|
||||||
'committed_at' => $now,
|
'committed_at' => $now,
|
||||||
'released_at' => null,
|
'released_at' => null,
|
||||||
|
'expired_at' => null,
|
||||||
|
'release_reason' => null,
|
||||||
|
'created_at' => $now,
|
||||||
|
'updated_at' => $now,
|
||||||
|
]);
|
||||||
|
DB::table('compras')->where('id', $purchaseId)->update([
|
||||||
|
'stock_reservation_id' => $reservationId,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
DB::table('stock_reservation_lines')->insert([
|
||||||
|
'stock_reservation_id' => $reservationId,
|
||||||
|
'inventory_id' => $inventory->id,
|
||||||
|
'quantity' => 1,
|
||||||
|
'tracks_inventory' => true,
|
||||||
'created_at' => $now,
|
'created_at' => $now,
|
||||||
'updated_at' => $now,
|
'updated_at' => $now,
|
||||||
]);
|
]);
|
||||||
@@ -410,7 +428,7 @@ class InvitationPurchaseProvisioner
|
|||||||
'ticket' => (string) Str::uuid(),
|
'ticket' => (string) Str::uuid(),
|
||||||
'name' => null,
|
'name' => null,
|
||||||
'description' => null,
|
'description' => null,
|
||||||
'source_purchase_id' => $purchaseId,
|
...$purchaseReference,
|
||||||
'source_catalog_item_id' => $catalogItemId,
|
'source_catalog_item_id' => $catalogItemId,
|
||||||
'source_variant_id' => $variant->id,
|
'source_variant_id' => $variant->id,
|
||||||
'used_at' => null,
|
'used_at' => null,
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Forms\Controllers\AdminApp;
|
||||||
|
|
||||||
|
use App\Domains\Forms\Resources\TicketFilterFormResource;
|
||||||
|
use App\Domains\Forms\Services\TicketFilterFormService;
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
|
||||||
|
class TicketFilterFormController extends Controller
|
||||||
|
{
|
||||||
|
public function __construct(private readonly TicketFilterFormService $formService) {}
|
||||||
|
|
||||||
|
public function __invoke(Request $request): TicketFilterFormResource
|
||||||
|
{
|
||||||
|
$tenant = $request->user('sanctum')->tenant()->firstOrFail();
|
||||||
|
|
||||||
|
return TicketFilterFormResource::make($this->formService->get($tenant));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Forms\Controllers\AdminApp;
|
||||||
|
|
||||||
|
use App\Domains\Forms\Resources\TicketFormResource;
|
||||||
|
use App\Domains\Forms\Services\TicketFormService;
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
|
||||||
|
class TicketFormController extends Controller
|
||||||
|
{
|
||||||
|
public function __construct(protected TicketFormService $ticketFormService) {}
|
||||||
|
|
||||||
|
public function __invoke(Request $request): TicketFormResource
|
||||||
|
{
|
||||||
|
return TicketFormResource::make(
|
||||||
|
$this->ticketFormService->get(
|
||||||
|
$request->user('sanctum')->tenant()->firstOrFail()
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
21
app/Domains/Forms/Resources/TicketFilterFormResource.php
Normal file
21
app/Domains/Forms/Resources/TicketFilterFormResource.php
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Forms\Resources;
|
||||||
|
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
|
class TicketFilterFormResource extends JsonResource
|
||||||
|
{
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
public function toArray(Request $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'code' => $this->resource['code'],
|
||||||
|
'action' => $this->resource['action'],
|
||||||
|
'method' => $this->resource['method'],
|
||||||
|
'fields' => $this->resource['fields'],
|
||||||
|
'columns' => $this->resource['columns'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
18
app/Domains/Forms/Resources/TicketFormResource.php
Normal file
18
app/Domains/Forms/Resources/TicketFormResource.php
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Forms\Resources;
|
||||||
|
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
|
class TicketFormResource extends JsonResource
|
||||||
|
{
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
public function toArray(Request $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'statuses' => $this->resource['statuses'],
|
||||||
|
'categories' => $this->resource['categories'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,27 +6,18 @@ use App\Domains\Purchase\Models\Purchase;
|
|||||||
|
|
||||||
class SaleFormService
|
class SaleFormService
|
||||||
{
|
{
|
||||||
/** @return array{statuses: list<array{code: string, name: string}>} */
|
/** @return array{statuses: list<array{value: string, label: string, real_statuses: list<string>}>} */
|
||||||
public function get(): array
|
public function get(): array
|
||||||
{
|
{
|
||||||
$names = [
|
|
||||||
Purchase::STATUS_CREATED => 'Creada',
|
|
||||||
Purchase::STATUS_PENDING_PAYMENT => 'Esperando pago',
|
|
||||||
Purchase::STATUS_IN_REVIEW => 'En revisión',
|
|
||||||
Purchase::STATUS_PAID => 'Confirmada',
|
|
||||||
Purchase::STATUS_CANCELLED => 'Cancelada',
|
|
||||||
Purchase::STATUS_REJECTED => 'Rechazada',
|
|
||||||
Purchase::STATUS_EXPIRED => 'Vencida',
|
|
||||||
Purchase::STATUS_SUPERSEDED => 'Reemplazada',
|
|
||||||
];
|
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'statuses' => array_map(
|
'statuses' => array_map(
|
||||||
fn (string $status): array => [
|
fn (string $code, array $definition): array => [
|
||||||
'code' => $status,
|
'value' => $code,
|
||||||
'name' => $names[$status],
|
'label' => $definition['name'],
|
||||||
|
'real_statuses' => $definition['statuses'],
|
||||||
],
|
],
|
||||||
Purchase::statuses(),
|
array_keys(Purchase::adminStatuses()),
|
||||||
|
array_values(Purchase::adminStatuses()),
|
||||||
),
|
),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
152
app/Domains/Forms/Services/TicketFilterFormService.php
Normal file
152
app/Domains/Forms/Services/TicketFilterFormService.php
Normal file
@@ -0,0 +1,152 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Forms\Services;
|
||||||
|
|
||||||
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
|
use App\Domains\Ticket\Models\Ticket;
|
||||||
|
use App\Domains\Ticket\Services\AdminAppTicketColumnService;
|
||||||
|
|
||||||
|
class TicketFilterFormService
|
||||||
|
{
|
||||||
|
private const FIESTA_FUTBOL_INFANTIL = 'fiesta_futbol_infantil';
|
||||||
|
|
||||||
|
public function __construct(
|
||||||
|
private readonly TicketFormService $ticketFormService,
|
||||||
|
private readonly AdminAppTicketColumnService $columnService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
public function get(Tenant $tenant): array
|
||||||
|
{
|
||||||
|
$fields = $this->commonFields();
|
||||||
|
|
||||||
|
if ($tenant->codigo === self::FIESTA_FUTBOL_INFANTIL) {
|
||||||
|
$fields = [
|
||||||
|
...$this->fiestaFutbolInfantilFields($tenant),
|
||||||
|
...$this->commonFields(includeDate: false),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'code' => 'tickets_filter',
|
||||||
|
'action' => '/api/v1/adminapp/tenant/tickets',
|
||||||
|
'method' => 'GET',
|
||||||
|
'fields' => $fields,
|
||||||
|
'columns' => $this->columnService->publicColumns($tenant),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return list<array<string, mixed>> */
|
||||||
|
private function fiestaFutbolInfantilFields(Tenant $tenant): array
|
||||||
|
{
|
||||||
|
$form = $this->ticketFormService->getForFilters($tenant);
|
||||||
|
|
||||||
|
return [
|
||||||
|
[
|
||||||
|
'name' => 'category',
|
||||||
|
'query_param' => 'category',
|
||||||
|
'label' => 'Categoría',
|
||||||
|
'type' => 'select',
|
||||||
|
'required' => false,
|
||||||
|
'default' => null,
|
||||||
|
'placeholder' => 'Categoría',
|
||||||
|
'options' => array_map(
|
||||||
|
fn (array $category): array => [
|
||||||
|
'value' => $category['value'],
|
||||||
|
'label' => $category['label'],
|
||||||
|
'children' => [
|
||||||
|
[
|
||||||
|
'field' => 'product',
|
||||||
|
'disabled' => $category['products'] === [],
|
||||||
|
'options' => array_map(
|
||||||
|
fn (array $product): array => [
|
||||||
|
'value' => $product['value'],
|
||||||
|
'label' => $product['label'],
|
||||||
|
'children' => [
|
||||||
|
[
|
||||||
|
'field' => 'type',
|
||||||
|
'disabled' => $product['types'] === [],
|
||||||
|
'options' => array_map(
|
||||||
|
fn (array $type): array => [
|
||||||
|
'value' => $type['value'],
|
||||||
|
'label' => $type['label'],
|
||||||
|
'children' => [[
|
||||||
|
'field' => 'size',
|
||||||
|
'disabled' => ($type['sizes'] ?? []) === [],
|
||||||
|
'options' => $type['sizes'] ?? [],
|
||||||
|
]],
|
||||||
|
],
|
||||||
|
$product['types'],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
],
|
||||||
|
$category['products'],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'field' => 'date',
|
||||||
|
'disabled' => ! in_array($category['value'], ['comidas', 'comida'], true),
|
||||||
|
'options' => [],
|
||||||
|
],
|
||||||
|
],
|
||||||
|
],
|
||||||
|
$form['categories'],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
$this->dependentSelect('product', 'Producto', 'category'),
|
||||||
|
$this->dependentSelect('type', 'Tipo', 'product'),
|
||||||
|
$this->dependentSelect('size', 'Talle', 'type'),
|
||||||
|
[
|
||||||
|
...$this->dependentSelect('date', 'Fecha', 'category'),
|
||||||
|
'type' => 'date',
|
||||||
|
],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return list<array<string, mixed>> */
|
||||||
|
private function commonFields(bool $includeDate = true): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
...($includeDate ? [[
|
||||||
|
'name' => 'date',
|
||||||
|
'query_param' => 'date',
|
||||||
|
'label' => 'Fecha',
|
||||||
|
'type' => 'date',
|
||||||
|
'required' => false,
|
||||||
|
'default' => null,
|
||||||
|
]] : []),
|
||||||
|
[
|
||||||
|
'name' => 'status',
|
||||||
|
'query_param' => 'status',
|
||||||
|
'label' => 'Estado',
|
||||||
|
'type' => 'select',
|
||||||
|
'required' => false,
|
||||||
|
'default' => null,
|
||||||
|
'placeholder' => 'Estado',
|
||||||
|
'options' => [
|
||||||
|
['value' => Ticket::STATUS_ACTIVE, 'label' => 'Activo'],
|
||||||
|
['value' => Ticket::STATUS_USED, 'label' => 'Usado'],
|
||||||
|
['value' => Ticket::STATUS_EXPIRED, 'label' => 'Vencido'],
|
||||||
|
],
|
||||||
|
],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
private function dependentSelect(string $name, string $label, string $dependency): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'name' => $name,
|
||||||
|
'query_param' => $name,
|
||||||
|
'label' => $label,
|
||||||
|
'type' => 'select',
|
||||||
|
'required' => false,
|
||||||
|
'default' => null,
|
||||||
|
'placeholder' => $label,
|
||||||
|
'depends_on' => $dependency,
|
||||||
|
'disabled' => true,
|
||||||
|
'options' => [],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
400
app/Domains/Forms/Services/TicketFormService.php
Normal file
400
app/Domains/Forms/Services/TicketFormService.php
Normal file
@@ -0,0 +1,400 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Forms\Services;
|
||||||
|
|
||||||
|
use App\Domains\Catalog\Models\CatalogItem;
|
||||||
|
use App\Domains\Catalog\Models\Variant;
|
||||||
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
|
use App\Domains\Ticket\Models\Ticket;
|
||||||
|
use Illuminate\Database\Eloquent\Collection;
|
||||||
|
|
||||||
|
class TicketFormService
|
||||||
|
{
|
||||||
|
private const PRODUCT = 'product';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var array<string, array{label: string|null, product: string, type: string|null, order: int}>
|
||||||
|
*/
|
||||||
|
private const CATEGORY_PRESENTATIONS = [
|
||||||
|
'entradas' => [
|
||||||
|
'label' => null,
|
||||||
|
'product' => self::PRODUCT,
|
||||||
|
'type' => null,
|
||||||
|
'order' => 1,
|
||||||
|
],
|
||||||
|
'alojamientos' => [
|
||||||
|
'label' => 'Camping',
|
||||||
|
'product' => 'tipo_alojamiento',
|
||||||
|
'type' => null,
|
||||||
|
'order' => 2,
|
||||||
|
],
|
||||||
|
'camping' => [
|
||||||
|
'label' => null,
|
||||||
|
'product' => 'tipo_alojamiento',
|
||||||
|
'type' => null,
|
||||||
|
'order' => 2,
|
||||||
|
],
|
||||||
|
'comidas' => [
|
||||||
|
'label' => 'Comida',
|
||||||
|
'product' => 'event_date',
|
||||||
|
'type' => 'horario',
|
||||||
|
'order' => 3,
|
||||||
|
],
|
||||||
|
'comida' => [
|
||||||
|
'label' => null,
|
||||||
|
'product' => 'event_date',
|
||||||
|
'type' => 'horario',
|
||||||
|
'order' => 3,
|
||||||
|
],
|
||||||
|
'merchandising' => [
|
||||||
|
'label' => null,
|
||||||
|
'product' => self::PRODUCT,
|
||||||
|
'type' => 'color',
|
||||||
|
'order' => 4,
|
||||||
|
],
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var array<string, array{label: string|null, product: string, type: string|null, size: string|null, order: int}>
|
||||||
|
*/
|
||||||
|
private const FILTER_CATEGORY_PRESENTATIONS = [
|
||||||
|
'entradas' => ['label' => null, 'product' => self::PRODUCT, 'type' => null, 'size' => null, 'order' => 1],
|
||||||
|
'alojamientos' => ['label' => 'Camping', 'product' => 'tipo_alojamiento', 'type' => null, 'size' => null, 'order' => 2],
|
||||||
|
'camping' => ['label' => null, 'product' => 'tipo_alojamiento', 'type' => null, 'size' => null, 'order' => 2],
|
||||||
|
'comidas' => ['label' => 'Comida', 'product' => 'horario', 'type' => 'servicio', 'size' => null, 'order' => 3],
|
||||||
|
'comida' => ['label' => null, 'product' => 'horario', 'type' => 'servicio', 'size' => null, 'order' => 3],
|
||||||
|
'merchandising' => ['label' => null, 'product' => self::PRODUCT, 'type' => 'color', 'size' => 'talle', 'order' => 4],
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array{
|
||||||
|
* statuses: list<array{value: string, label: string}>,
|
||||||
|
* categories: list<array{
|
||||||
|
* value: string,
|
||||||
|
* label: string,
|
||||||
|
* products: list<array{
|
||||||
|
* value: string,
|
||||||
|
* label: string,
|
||||||
|
* types: list<array{value: string, label: string}>
|
||||||
|
* }>
|
||||||
|
* }>
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
public function get(Tenant $tenant): array
|
||||||
|
{
|
||||||
|
$items = CatalogItem::query()
|
||||||
|
->where('tenant_code', $tenant->codigo)
|
||||||
|
->where('has_tickets', true)
|
||||||
|
->whereHas('category')
|
||||||
|
->with($this->relations())
|
||||||
|
->orderBy('group_order')
|
||||||
|
->orderBy('nombre')
|
||||||
|
->get();
|
||||||
|
|
||||||
|
return $this->build($items, self::CATEGORY_PRESENTATIONS);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return active catalog options plus soft-deleted sources still referenced by
|
||||||
|
* tickets, so historical tickets never become impossible to filter.
|
||||||
|
*
|
||||||
|
* @return array{
|
||||||
|
* statuses: list<array{value: string, label: string}>,
|
||||||
|
* categories: list<array{
|
||||||
|
* value: string,
|
||||||
|
* label: string,
|
||||||
|
* products: list<array{
|
||||||
|
* value: string,
|
||||||
|
* label: string,
|
||||||
|
* types: list<array{value: string, label: string}>
|
||||||
|
* }>
|
||||||
|
* }>
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
public function getForFilters(Tenant $tenant): array
|
||||||
|
{
|
||||||
|
$historicalVariantIds = Ticket::query()
|
||||||
|
->where('tenant_code', $tenant->codigo)
|
||||||
|
->whereNotNull('source_variant_id')
|
||||||
|
->distinct()
|
||||||
|
->pluck('source_variant_id')
|
||||||
|
->map(fn ($id): int => (int) $id)
|
||||||
|
->all();
|
||||||
|
$historicalCatalogItemIds = Ticket::query()
|
||||||
|
->where('tenant_code', $tenant->codigo)
|
||||||
|
->whereNotNull('source_catalog_item_id')
|
||||||
|
->distinct()
|
||||||
|
->pluck('source_catalog_item_id')
|
||||||
|
->map(fn ($id): int => (int) $id)
|
||||||
|
->merge(
|
||||||
|
Variant::withTrashed()
|
||||||
|
->whereKey($historicalVariantIds)
|
||||||
|
->pluck('catalog_item_id')
|
||||||
|
->map(fn ($id): int => (int) $id),
|
||||||
|
)
|
||||||
|
->unique()
|
||||||
|
->values()
|
||||||
|
->all();
|
||||||
|
|
||||||
|
$items = CatalogItem::withTrashed()
|
||||||
|
->where('tenant_code', $tenant->codigo)
|
||||||
|
->whereHas('category')
|
||||||
|
->where(function ($query) use ($historicalCatalogItemIds): void {
|
||||||
|
$query
|
||||||
|
->where(function ($activeQuery): void {
|
||||||
|
$activeQuery
|
||||||
|
->whereNull('catalog_items.deleted_at')
|
||||||
|
->where('has_tickets', true);
|
||||||
|
})
|
||||||
|
->orWhereIn('catalog_items.id', $historicalCatalogItemIds);
|
||||||
|
})
|
||||||
|
->with([
|
||||||
|
'category',
|
||||||
|
'itemAttributes.attribute.options',
|
||||||
|
'variants' => fn ($query) => $query
|
||||||
|
->withTrashed()
|
||||||
|
->where(function ($variantQuery) use ($historicalVariantIds): void {
|
||||||
|
$variantQuery
|
||||||
|
->whereNull('variantes.deleted_at')
|
||||||
|
->orWhereIn('variantes.id', $historicalVariantIds);
|
||||||
|
}),
|
||||||
|
'variants.definitions.itemAttribute.attribute.options',
|
||||||
|
'variants.eventDates',
|
||||||
|
'variants.eventDate',
|
||||||
|
])
|
||||||
|
->orderBy('group_order')
|
||||||
|
->orderBy('nombre')
|
||||||
|
->get();
|
||||||
|
|
||||||
|
return $this->build($items, self::FILTER_CATEGORY_PRESENTATIONS, includeSizes: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param Collection<int, CatalogItem> $items
|
||||||
|
* @return array{
|
||||||
|
* statuses: list<array{value: string, label: string}>,
|
||||||
|
* categories: list<array{
|
||||||
|
* value: string,
|
||||||
|
* label: string,
|
||||||
|
* products: list<array{
|
||||||
|
* value: string,
|
||||||
|
* label: string,
|
||||||
|
* types: list<array{value: string, label: string}>
|
||||||
|
* }>
|
||||||
|
* }>
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
private function build(Collection $items, array $presentations, bool $includeSizes = false): array
|
||||||
|
{
|
||||||
|
$categories = [];
|
||||||
|
|
||||||
|
foreach ($items as $item) {
|
||||||
|
$sourceCategory = trim((string) $item->category?->nombre);
|
||||||
|
$categoryValue = mb_strtolower($sourceCategory);
|
||||||
|
$presentation = $presentations[$categoryValue] ?? [
|
||||||
|
'label' => null,
|
||||||
|
'product' => self::PRODUCT,
|
||||||
|
'type' => null,
|
||||||
|
'size' => null,
|
||||||
|
'order' => PHP_INT_MAX,
|
||||||
|
];
|
||||||
|
|
||||||
|
$categories[$categoryValue] ??= [
|
||||||
|
'value' => $categoryValue,
|
||||||
|
'label' => $presentation['label'] ?? $sourceCategory,
|
||||||
|
'order' => $presentation['order'],
|
||||||
|
'products' => [],
|
||||||
|
];
|
||||||
|
|
||||||
|
foreach ($this->products(
|
||||||
|
$item,
|
||||||
|
$presentation['product'],
|
||||||
|
$presentation['type'],
|
||||||
|
$presentation['size'] ?? null,
|
||||||
|
) as $product) {
|
||||||
|
$productValue = $product['value'];
|
||||||
|
$existingProduct = $categories[$categoryValue]['products'][$productValue] ?? [
|
||||||
|
'value' => $productValue,
|
||||||
|
'label' => $product['label'],
|
||||||
|
'types' => [],
|
||||||
|
'sizes' => [],
|
||||||
|
];
|
||||||
|
|
||||||
|
foreach ($product['types'] as $type) {
|
||||||
|
$existingProduct['types'][$type['value']] = $type;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($product['sizes'] as $size) {
|
||||||
|
$existingProduct['sizes'][$size['value']] = $size;
|
||||||
|
}
|
||||||
|
|
||||||
|
$categories[$categoryValue]['products'][$productValue] = $existingProduct;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
uasort($categories, fn (array $left, array $right): int => $left['order'] <=> $right['order']
|
||||||
|
?: $left['label'] <=> $right['label']);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'statuses' => [
|
||||||
|
['value' => Ticket::STATUS_ACTIVE, 'label' => 'Activo'],
|
||||||
|
['value' => Ticket::STATUS_USED, 'label' => 'Usado'],
|
||||||
|
['value' => Ticket::STATUS_EXPIRED, 'label' => 'Vencido'],
|
||||||
|
],
|
||||||
|
'categories' => array_values(array_map(
|
||||||
|
fn (array $category): array => [
|
||||||
|
'value' => $category['value'],
|
||||||
|
'label' => $category['label'],
|
||||||
|
'products' => array_values(array_map(
|
||||||
|
fn (array $product): array => [
|
||||||
|
'value' => $product['value'],
|
||||||
|
'label' => $product['label'],
|
||||||
|
'types' => array_values($product['types']),
|
||||||
|
...($includeSizes ? ['sizes' => array_values($product['sizes'])] : []),
|
||||||
|
],
|
||||||
|
$category['products'],
|
||||||
|
)),
|
||||||
|
],
|
||||||
|
$categories,
|
||||||
|
)),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return list<string> */
|
||||||
|
private function relations(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'category',
|
||||||
|
'itemAttributes.attribute.options',
|
||||||
|
'variants.definitions.itemAttribute.attribute.options',
|
||||||
|
'variants.eventDates',
|
||||||
|
'variants.eventDate',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return list<array{
|
||||||
|
* value: string,
|
||||||
|
* label: string,
|
||||||
|
* types: list<array{value: string, label: string}>,
|
||||||
|
* sizes: list<array{value: string, label: string}>
|
||||||
|
* }>
|
||||||
|
*/
|
||||||
|
private function products(CatalogItem $item, string $productCode, ?string $typeCode, ?string $sizeCode): array
|
||||||
|
{
|
||||||
|
if ($productCode === self::PRODUCT) {
|
||||||
|
return [[
|
||||||
|
'value' => $item->slug,
|
||||||
|
'label' => $item->nombre,
|
||||||
|
'types' => $this->types($item, $typeCode, $sizeCode),
|
||||||
|
'sizes' => $this->types($item, $sizeCode),
|
||||||
|
]];
|
||||||
|
}
|
||||||
|
|
||||||
|
$products = [];
|
||||||
|
|
||||||
|
foreach ($item->variants as $variant) {
|
||||||
|
foreach ($this->variantOptions($variant, $productCode) as $productOption) {
|
||||||
|
$productValue = $productOption['value'];
|
||||||
|
$products[$productValue] ??= [
|
||||||
|
'value' => $productValue,
|
||||||
|
'label' => $this->optionLabel($productOption['label'], $productCode),
|
||||||
|
'types' => [],
|
||||||
|
'sizes' => [],
|
||||||
|
];
|
||||||
|
|
||||||
|
foreach ($this->variantOptions($variant, $typeCode) as $typeOption) {
|
||||||
|
$this->mergeTypeOption(
|
||||||
|
$products[$productValue]['types'],
|
||||||
|
$typeOption,
|
||||||
|
$variant,
|
||||||
|
$sizeCode,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($this->variantOptions($variant, $sizeCode) as $sizeOption) {
|
||||||
|
$products[$productValue]['sizes'][$sizeOption['value']] = $sizeOption;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return array_values(array_map(
|
||||||
|
fn (array $product): array => [
|
||||||
|
'value' => $product['value'],
|
||||||
|
'label' => $product['label'],
|
||||||
|
'types' => array_values($product['types']),
|
||||||
|
'sizes' => array_values($product['sizes']),
|
||||||
|
],
|
||||||
|
$products,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return list<array<string, mixed>> */
|
||||||
|
private function types(CatalogItem $item, ?string $typeCode, ?string $sizeCode = null): array
|
||||||
|
{
|
||||||
|
$types = [];
|
||||||
|
|
||||||
|
foreach ($item->variants as $variant) {
|
||||||
|
foreach ($this->variantOptions($variant, $typeCode) as $typeOption) {
|
||||||
|
$this->mergeTypeOption($types, $typeOption, $variant, $sizeCode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return array_values(array_map(function (array $type) use ($sizeCode): array {
|
||||||
|
if ($sizeCode !== null) {
|
||||||
|
$type['sizes'] = array_values($type['sizes']);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $type;
|
||||||
|
}, $types));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, array<string, mixed>> $types
|
||||||
|
* @param array{value: string, label: string} $typeOption
|
||||||
|
*/
|
||||||
|
private function mergeTypeOption(
|
||||||
|
array &$types,
|
||||||
|
array $typeOption,
|
||||||
|
Variant $variant,
|
||||||
|
?string $sizeCode,
|
||||||
|
): void {
|
||||||
|
$typeValue = $typeOption['value'];
|
||||||
|
$types[$typeValue] ??= [
|
||||||
|
...$typeOption,
|
||||||
|
...($sizeCode !== null ? ['sizes' => []] : []),
|
||||||
|
];
|
||||||
|
|
||||||
|
foreach ($this->variantOptions($variant, $sizeCode) as $sizeOption) {
|
||||||
|
$types[$typeValue]['sizes'][$sizeOption['value']] = $sizeOption;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return list<array{value: string, label: string}> */
|
||||||
|
private function variantOptions(Variant $variant, ?string $attributeCode): array
|
||||||
|
{
|
||||||
|
if ($attributeCode === null) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
$selection = $variant->selectionOptions($variant->catalogItem->itemAttributes)
|
||||||
|
->get($attributeCode);
|
||||||
|
|
||||||
|
if ($selection === null) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return array_is_list($selection) ? $selection : [$selection];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function optionLabel(string $label, string $attributeCode): string
|
||||||
|
{
|
||||||
|
if ($attributeCode !== 'event_date') {
|
||||||
|
return $label;
|
||||||
|
}
|
||||||
|
|
||||||
|
[$day, $month] = array_pad(explode('/', $label), 2, null);
|
||||||
|
|
||||||
|
return $day !== null && $month !== null ? "{$day}/{$month}" : $label;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,6 +9,7 @@ Provee catálogos y opciones auxiliares para construir formularios del panel adm
|
|||||||
- `EventFormService`: devuelve redes sociales disponibles y las URL configuradas para el tenant.
|
- `EventFormService`: devuelve redes sociales disponibles y las URL configuradas para el tenant.
|
||||||
- `SaleFormService`: expone los estados admitidos para compras con sus etiquetas de presentación.
|
- `SaleFormService`: expone los estados admitidos para compras con sus etiquetas de presentación.
|
||||||
- `StaffFormService`: lista categorías raíz que pueden asignarse al personal del tenant.
|
- `StaffFormService`: lista categorías raíz que pueden asignarse al personal del tenant.
|
||||||
|
- `TicketFormService`: expone estados y opciones anidadas de categoría, producto y tipo para los tickets de Fiesta Fútbol Infantil.
|
||||||
|
|
||||||
Cada servicio tiene un controlador invocable y un `JsonResource` específico. `SocialMediaOptionResource` representa las opciones de redes sociales.
|
Cada servicio tiene un controlador invocable y un `JsonResource` específico. `SocialMediaOptionResource` representa las opciones de redes sociales.
|
||||||
|
|
||||||
@@ -19,6 +20,7 @@ Bajo `/v1/adminapp/forms`, con `auth:sanctum` y `adminapp.tenant`:
|
|||||||
- `GET /event`.
|
- `GET /event`.
|
||||||
- `GET /sale`.
|
- `GET /sale`.
|
||||||
- `GET /staff`.
|
- `GET /staff`.
|
||||||
|
- `GET /fiesta-futbol-infantil/ticket`: estados y jerarquía categoría → producto → tipo para filtros de tickets.
|
||||||
- `GET /fiesta-futbol-infantil/merchandise`: opciones de color y talle del tenant para merchandising.
|
- `GET /fiesta-futbol-infantil/merchandise`: opciones de color y talle del tenant para merchandising.
|
||||||
|
|
||||||
## Dependencias
|
## Dependencias
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ use App\Domains\Forms\Controllers\AdminApp\FoodFormController;
|
|||||||
use App\Domains\Forms\Controllers\AdminApp\MerchandiseFormController;
|
use App\Domains\Forms\Controllers\AdminApp\MerchandiseFormController;
|
||||||
use App\Domains\Forms\Controllers\AdminApp\SaleFormController;
|
use App\Domains\Forms\Controllers\AdminApp\SaleFormController;
|
||||||
use App\Domains\Forms\Controllers\AdminApp\StaffFormController;
|
use App\Domains\Forms\Controllers\AdminApp\StaffFormController;
|
||||||
|
use App\Domains\Forms\Controllers\AdminApp\TicketFilterFormController;
|
||||||
|
use App\Domains\Forms\Controllers\AdminApp\TicketFormController;
|
||||||
use Illuminate\Support\Facades\Route;
|
use Illuminate\Support\Facades\Route;
|
||||||
|
|
||||||
Route::prefix('v1/adminapp/forms')
|
Route::prefix('v1/adminapp/forms')
|
||||||
@@ -13,6 +15,13 @@ Route::prefix('v1/adminapp/forms')
|
|||||||
Route::get('event', EventFormController::class);
|
Route::get('event', EventFormController::class);
|
||||||
Route::get('sale', SaleFormController::class);
|
Route::get('sale', SaleFormController::class);
|
||||||
Route::get('staff', StaffFormController::class);
|
Route::get('staff', StaffFormController::class);
|
||||||
|
Route::get('tickets-filter', TicketFilterFormController::class)
|
||||||
|
->middleware('tenant.menu:adminapp.tickets')
|
||||||
|
->name('adminapp.forms.tickets-filter');
|
||||||
|
Route::get(
|
||||||
|
'fiesta-futbol-infantil/ticket',
|
||||||
|
TicketFormController::class
|
||||||
|
);
|
||||||
Route::get(
|
Route::get(
|
||||||
'fiesta-futbol-infantil/merchandise',
|
'fiesta-futbol-infantil/merchandise',
|
||||||
MerchandiseFormController::class
|
MerchandiseFormController::class
|
||||||
|
|||||||
@@ -7,7 +7,10 @@ use App\Domains\Purchase\Models\Purchase;
|
|||||||
use App\Domains\Purchase\Models\TelepagosPayment;
|
use App\Domains\Purchase\Models\TelepagosPayment;
|
||||||
use App\Domains\Purchase\Models\TelepagosQr;
|
use App\Domains\Purchase\Models\TelepagosQr;
|
||||||
use App\Domains\Purchase\Services\CheckoutService;
|
use App\Domains\Purchase\Services\CheckoutService;
|
||||||
|
use App\Domains\Purchase\Services\DniDistanceService;
|
||||||
use Exception;
|
use Exception;
|
||||||
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
|
use Illuminate\Database\Eloquent\Collection;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\Facades\Log;
|
use Illuminate\Support\Facades\Log;
|
||||||
|
|
||||||
@@ -15,6 +18,7 @@ class TelepagosWebhookService
|
|||||||
{
|
{
|
||||||
public function __construct(
|
public function __construct(
|
||||||
private readonly CheckoutService $checkoutService,
|
private readonly CheckoutService $checkoutService,
|
||||||
|
private readonly DniDistanceService $dniDistance,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -41,7 +45,6 @@ class TelepagosWebhookService
|
|||||||
|
|
||||||
$paymentData = [
|
$paymentData = [
|
||||||
'compra_id' => null,
|
'compra_id' => null,
|
||||||
'matched_purchase_ids' => null,
|
|
||||||
'cuit_buyer' => $details['data']['buyer']['cuit'] ?? $details['buyer']['cuit'] ?? null,
|
'cuit_buyer' => $details['data']['buyer']['cuit'] ?? $details['buyer']['cuit'] ?? null,
|
||||||
'cvu_buyer' => $details['data']['buyer']['cvu'] ?? $details['buyer']['cvu'] ?? null,
|
'cvu_buyer' => $details['data']['buyer']['cvu'] ?? $details['buyer']['cvu'] ?? null,
|
||||||
'amount' => $amount,
|
'amount' => $amount,
|
||||||
@@ -73,24 +76,55 @@ class TelepagosWebhookService
|
|||||||
$dni = substr($cuit, 2, -1);
|
$dni = substr($cuit, 2, -1);
|
||||||
|
|
||||||
$tenantCodes = $client->tenants()->pluck('codigo');
|
$tenantCodes = $client->tenants()->pluck('codigo');
|
||||||
$purchases = Purchase::whereIn('tenant_codigo', $tenantCodes)
|
$eligiblePurchases = Purchase::query()
|
||||||
->where('transfer_payer_dni', $dni)
|
->whereIn('tenant_codigo', $tenantCodes)
|
||||||
->whereIn('status', [
|
->whereIn('status', [
|
||||||
Purchase::STATUS_CREATED,
|
Purchase::STATUS_CREATED,
|
||||||
Purchase::STATUS_PENDING_PAYMENT,
|
Purchase::STATUS_PENDING_PAYMENT,
|
||||||
Purchase::STATUS_IN_REVIEW,
|
Purchase::STATUS_IN_REVIEW,
|
||||||
])
|
])
|
||||||
->where('payment_method', 'transfer')
|
->where('payment_method', 'transfer');
|
||||||
|
|
||||||
|
$purchases = (clone $eligiblePurchases)
|
||||||
->where('total', $amount)
|
->where('total', $amount)
|
||||||
->latest()
|
->latest()
|
||||||
->get();
|
->get()
|
||||||
|
->filter(fn (Purchase $purchase): bool => $purchase->transfer_payer_dni !== null
|
||||||
|
&& $this->dniDistance->distance($dni, $purchase->transfer_payer_dni) === 0)
|
||||||
|
->values();
|
||||||
|
|
||||||
$paymentData['matched_purchase_ids'] = $purchases->pluck('id')->all();
|
|
||||||
$compra = $purchases->count() === 1 ? $purchases->first() : null;
|
$compra = $purchases->count() === 1 ? $purchases->first() : null;
|
||||||
|
|
||||||
if (! $compra) {
|
if (! $compra) {
|
||||||
if ($purchases->count() > 1) {
|
$candidatePurchases = $this->findTransferCandidates(
|
||||||
TelepagosPayment::create($paymentData);
|
$eligiblePurchases,
|
||||||
|
$dni,
|
||||||
|
$amount,
|
||||||
|
);
|
||||||
|
if ($candidatePurchases->isNotEmpty()) {
|
||||||
|
$payment = $this->storeTransferCandidates(
|
||||||
|
$paymentData,
|
||||||
|
$candidatePurchases,
|
||||||
|
$dni,
|
||||||
|
$amount,
|
||||||
|
);
|
||||||
|
|
||||||
|
Log::channel('telepagos')->info('Telepagos webhook: Transfer payment candidates found.', [
|
||||||
|
'client_code' => $client->code,
|
||||||
|
'cashin_id' => $cashinId,
|
||||||
|
'telepagos_payment_id' => $payment->id,
|
||||||
|
'amount' => $amount,
|
||||||
|
'candidate_count' => $payment->candidates->count(),
|
||||||
|
'candidates' => $payment->candidates
|
||||||
|
->map(fn ($candidate): array => [
|
||||||
|
'purchase_id' => $candidate->compra_id,
|
||||||
|
'match_reason' => $candidate->match_reason,
|
||||||
|
'dni_distance' => $candidate->dni_distance,
|
||||||
|
'amount_difference' => $candidate->amount_difference,
|
||||||
|
'confidence' => $candidate->confidence,
|
||||||
|
])
|
||||||
|
->all(),
|
||||||
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
Log::channel('telepagos')->warning('Telepagos webhook: Expected exactly one matching purchase.', [
|
Log::channel('telepagos')->warning('Telepagos webhook: Expected exactly one matching purchase.', [
|
||||||
@@ -209,4 +243,91 @@ class TelepagosWebhookService
|
|||||||
{
|
{
|
||||||
return number_format((float) $amount, 2, '.', '');
|
return number_format((float) $amount, 2, '.', '');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param Builder<Purchase> $eligiblePurchases
|
||||||
|
* @return Collection<int, Purchase>
|
||||||
|
*/
|
||||||
|
private function findTransferCandidates(Builder $eligiblePurchases, string $dni, string $amount): Collection
|
||||||
|
{
|
||||||
|
$tolerancePercentage = max(
|
||||||
|
0,
|
||||||
|
(float) config('purchase.transfer_candidate_amount_tolerance_percentage', 5),
|
||||||
|
);
|
||||||
|
$numericAmount = (float) $amount;
|
||||||
|
$tolerance = $numericAmount * ($tolerancePercentage / 100);
|
||||||
|
$minimumAmount = $this->normalizeAmount(max(0, $numericAmount - $tolerance));
|
||||||
|
$maximumAmount = $this->normalizeAmount($numericAmount + $tolerance);
|
||||||
|
|
||||||
|
return (clone $eligiblePurchases)
|
||||||
|
->whereBetween('total', [$minimumAmount, $maximumAmount])
|
||||||
|
->latest()
|
||||||
|
->get()
|
||||||
|
->filter(function (Purchase $purchase) use ($dni, $amount): bool {
|
||||||
|
if ($purchase->transfer_payer_dni === null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$purchaseAmount = $this->normalizeAmount($purchase->total);
|
||||||
|
$distance = $this->dniDistance->distance(
|
||||||
|
$dni,
|
||||||
|
(string) $purchase->transfer_payer_dni,
|
||||||
|
);
|
||||||
|
|
||||||
|
return $distance === 0
|
||||||
|
|| ($purchaseAmount === $amount && $distance <= 2);
|
||||||
|
})
|
||||||
|
->values();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $paymentData
|
||||||
|
* @param Collection<int, Purchase> $candidatePurchases
|
||||||
|
*/
|
||||||
|
private function storeTransferCandidates(
|
||||||
|
array $paymentData,
|
||||||
|
Collection $candidatePurchases,
|
||||||
|
string $dni,
|
||||||
|
string $amount,
|
||||||
|
): TelepagosPayment {
|
||||||
|
return DB::transaction(function () use ($paymentData, $candidatePurchases, $dni, $amount): TelepagosPayment {
|
||||||
|
$payment = TelepagosPayment::create($paymentData);
|
||||||
|
|
||||||
|
$payment->candidates()->createMany(
|
||||||
|
$candidatePurchases
|
||||||
|
->map(function (Purchase $purchase) use ($dni, $amount): array {
|
||||||
|
$purchaseAmount = $this->normalizeAmount($purchase->total);
|
||||||
|
$dniDistance = $this->dniDistance->distance(
|
||||||
|
$dni,
|
||||||
|
(string) $purchase->transfer_payer_dni,
|
||||||
|
);
|
||||||
|
$dniMatches = $dniDistance === 0;
|
||||||
|
$amountMatches = $purchaseAmount === $amount;
|
||||||
|
|
||||||
|
return [
|
||||||
|
'compra_id' => $purchase->id,
|
||||||
|
'dni_matches' => $dniMatches,
|
||||||
|
'dni_distance' => $dniDistance,
|
||||||
|
'payment_dni' => $dni,
|
||||||
|
'purchase_dni' => $purchase->transfer_payer_dni,
|
||||||
|
'amount_matches' => $amountMatches,
|
||||||
|
'payment_amount' => $amount,
|
||||||
|
'purchase_amount' => $purchaseAmount,
|
||||||
|
'amount_difference' => $this->normalizeAmount(
|
||||||
|
abs((float) $purchaseAmount - (float) $amount),
|
||||||
|
),
|
||||||
|
'match_reason' => $amountMatches
|
||||||
|
? ($dniMatches ? 'ambiguous_exact_match' : 'exact_amount_near_dni')
|
||||||
|
: 'exact_dni_near_amount',
|
||||||
|
'confidence' => $amountMatches
|
||||||
|
? ($dniMatches ? 'exact' : 'medium')
|
||||||
|
: 'high',
|
||||||
|
];
|
||||||
|
})
|
||||||
|
->all(),
|
||||||
|
);
|
||||||
|
|
||||||
|
return $payment->load('candidates');
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -138,8 +138,7 @@ class NotificationMailService
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** @var Collection<int, Ticket> $tickets */
|
/** @var Collection<int, Ticket> $tickets */
|
||||||
$tickets = Ticket::query()
|
$tickets = $purchase->tickets()
|
||||||
->where('source_purchase_id', $purchase->getKey())
|
|
||||||
->where('tenant_code', $purchase->tenant_codigo)
|
->where('tenant_code', $purchase->tenant_codigo)
|
||||||
->with(TicketPresentationResolver::RELATIONS)
|
->with(TicketPresentationResolver::RELATIONS)
|
||||||
->get();
|
->get();
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ class PurchaseController extends Controller
|
|||||||
|
|
||||||
return PurchaseResource::collection(
|
return PurchaseResource::collection(
|
||||||
Purchase::query()
|
Purchase::query()
|
||||||
|
->with('stockReservation')
|
||||||
->where('tenant_codigo', $tenant->codigo)
|
->where('tenant_codigo', $tenant->codigo)
|
||||||
->where('user_id', $request->user()->id)
|
->where('user_id', $request->user()->id)
|
||||||
->when($statuses !== [], fn ($query) => $query->whereIn('status', $statuses))
|
->when($statuses !== [], fn ($query) => $query->whereIn('status', $statuses))
|
||||||
@@ -92,7 +93,6 @@ class PurchaseController extends Controller
|
|||||||
PaymentIntentRequest $request,
|
PaymentIntentRequest $request,
|
||||||
Tenant $tenant,
|
Tenant $tenant,
|
||||||
Purchase $compra,
|
Purchase $compra,
|
||||||
CheckoutService $checkoutService,
|
|
||||||
PurchaseStateGuard $purchaseState,
|
PurchaseStateGuard $purchaseState,
|
||||||
): JsonResponse {
|
): JsonResponse {
|
||||||
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
|
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
|
||||||
@@ -101,7 +101,12 @@ class PurchaseController extends Controller
|
|||||||
? preg_replace('/\D+/', '', (string) $request->validated('transfer_payer_dni'))
|
? preg_replace('/\D+/', '', (string) $request->validated('transfer_payer_dni'))
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
$updated = DB::transaction(function () use ($compra, $method, $purchaseState, $transferPayerDni): bool {
|
$updated = DB::transaction(function () use (
|
||||||
|
$compra,
|
||||||
|
$method,
|
||||||
|
$purchaseState,
|
||||||
|
$transferPayerDni,
|
||||||
|
): bool {
|
||||||
/** @var Purchase|null $purchase */
|
/** @var Purchase|null $purchase */
|
||||||
$purchase = Purchase::query()
|
$purchase = Purchase::query()
|
||||||
->whereKey($compra->getKey())
|
->whereKey($compra->getKey())
|
||||||
@@ -128,9 +133,6 @@ class PurchaseController extends Controller
|
|||||||
$purchaseUpdate = [
|
$purchaseUpdate = [
|
||||||
'payment_method' => $method,
|
'payment_method' => $method,
|
||||||
'status' => Purchase::STATUS_PENDING_PAYMENT,
|
'status' => Purchase::STATUS_PENDING_PAYMENT,
|
||||||
'expires_at' => now()->addMinutes(
|
|
||||||
max(1, (int) config("purchase.payment_expiration_minutes.{$method}", 30))
|
|
||||||
),
|
|
||||||
'total' => $purchase->calculateCurrentTotalAmount(),
|
'total' => $purchase->calculateCurrentTotalAmount(),
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -150,7 +152,6 @@ class PurchaseController extends Controller
|
|||||||
|
|
||||||
$compra->refresh();
|
$compra->refresh();
|
||||||
$totalAmount = (float) $compra->total;
|
$totalAmount = (float) $compra->total;
|
||||||
$checkoutService->syncReservationExpiration($compra);
|
|
||||||
|
|
||||||
if ($method === 'transfer') {
|
if ($method === 'transfer') {
|
||||||
$telepagosService = new TelepagosIntegrationService;
|
$telepagosService = new TelepagosIntegrationService;
|
||||||
|
|||||||
@@ -14,16 +14,17 @@ 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\Database\Eloquent\Relations\HasManyThrough;
|
||||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
#[Fillable([
|
#[Fillable([
|
||||||
'cart_id',
|
'cart_id',
|
||||||
|
'stock_reservation_id',
|
||||||
'tenant_codigo',
|
'tenant_codigo',
|
||||||
'user_id',
|
'user_id',
|
||||||
'status',
|
'status',
|
||||||
'payment_method',
|
'payment_method',
|
||||||
'expires_at',
|
|
||||||
'total',
|
'total',
|
||||||
'dni',
|
'dni',
|
||||||
'transfer_payer_dni',
|
'transfer_payer_dni',
|
||||||
@@ -51,6 +52,14 @@ class Purchase extends Model
|
|||||||
|
|
||||||
public const STATUS_SUPERSEDED = 'superseded';
|
public const STATUS_SUPERSEDED = 'superseded';
|
||||||
|
|
||||||
|
public const ADMIN_STATUS_INCOMPLETE = 'incomplete';
|
||||||
|
|
||||||
|
public const ADMIN_STATUS_AWAITING_PAYMENT = 'awaiting_payment';
|
||||||
|
|
||||||
|
public const ADMIN_STATUS_CONFIRMED = 'confirmed';
|
||||||
|
|
||||||
|
public const ADMIN_STATUS_CANCELLED = 'cancelled';
|
||||||
|
|
||||||
/** @return list<string> */
|
/** @return list<string> */
|
||||||
public static function statuses(): array
|
public static function statuses(): array
|
||||||
{
|
{
|
||||||
@@ -66,6 +75,68 @@ class Purchase extends Model
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, array{name: string, statuses: list<string>}>
|
||||||
|
*/
|
||||||
|
public static function adminStatuses(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
self::ADMIN_STATUS_INCOMPLETE => [
|
||||||
|
'name' => 'Por completar datos',
|
||||||
|
'statuses' => [self::STATUS_CREATED],
|
||||||
|
],
|
||||||
|
self::ADMIN_STATUS_AWAITING_PAYMENT => [
|
||||||
|
'name' => 'Esperando pago',
|
||||||
|
'statuses' => [self::STATUS_PENDING_PAYMENT, self::STATUS_IN_REVIEW],
|
||||||
|
],
|
||||||
|
self::ADMIN_STATUS_CONFIRMED => [
|
||||||
|
'name' => 'Confirmado',
|
||||||
|
'statuses' => [self::STATUS_PAID],
|
||||||
|
],
|
||||||
|
self::ADMIN_STATUS_CANCELLED => [
|
||||||
|
'name' => 'Anulado',
|
||||||
|
'statuses' => [
|
||||||
|
self::STATUS_CANCELLED,
|
||||||
|
self::STATUS_REJECTED,
|
||||||
|
self::STATUS_EXPIRED,
|
||||||
|
self::STATUS_SUPERSEDED,
|
||||||
|
],
|
||||||
|
],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return list<string> */
|
||||||
|
public static function adminStatusCodes(): array
|
||||||
|
{
|
||||||
|
return array_keys(self::adminStatuses());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return list<string> */
|
||||||
|
public static function realStatusesForAdminStatus(string $adminStatus): array
|
||||||
|
{
|
||||||
|
return self::adminStatuses()[$adminStatus]['statuses'] ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function adminStatusFor(string $realStatus): ?string
|
||||||
|
{
|
||||||
|
foreach (self::adminStatuses() as $adminStatus => $definition) {
|
||||||
|
if (in_array($realStatus, $definition['statuses'], true)) {
|
||||||
|
return $adminStatus;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function adminStatusNameFor(string $realStatus): ?string
|
||||||
|
{
|
||||||
|
$adminStatus = self::adminStatusFor($realStatus);
|
||||||
|
|
||||||
|
return $adminStatus === null
|
||||||
|
? null
|
||||||
|
: self::adminStatuses()[$adminStatus]['name'];
|
||||||
|
}
|
||||||
|
|
||||||
protected $table = 'compras';
|
protected $table = 'compras';
|
||||||
|
|
||||||
/** @var array<int, string> */
|
/** @var array<int, string> */
|
||||||
@@ -77,8 +148,8 @@ class Purchase extends Model
|
|||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'cart_id' => 'integer',
|
'cart_id' => 'integer',
|
||||||
|
'stock_reservation_id' => 'integer',
|
||||||
'user_id' => 'integer',
|
'user_id' => 'integer',
|
||||||
'expires_at' => 'datetime',
|
|
||||||
'total' => 'decimal:2',
|
'total' => 'decimal:2',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
@@ -115,18 +186,21 @@ class Purchase extends Model
|
|||||||
return $this->hasMany(PurchaseItem::class, 'compra_id');
|
return $this->hasMany(PurchaseItem::class, 'compra_id');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** @return HasManyThrough<Ticket, PurchaseItem, $this> */
|
||||||
* @return HasMany<Ticket, $this>
|
public function tickets(): HasManyThrough
|
||||||
*/
|
|
||||||
public function tickets(): HasMany
|
|
||||||
{
|
{
|
||||||
return $this->hasMany(Ticket::class, 'source_purchase_id');
|
return $this->hasManyThrough(
|
||||||
|
Ticket::class,
|
||||||
|
PurchaseItem::class,
|
||||||
|
'compra_id',
|
||||||
|
'source_purchase_item_id',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return HasMany<StockReservation, $this> */
|
/** @return BelongsTo<StockReservation, $this> */
|
||||||
public function stockReservations(): HasMany
|
public function stockReservation(): BelongsTo
|
||||||
{
|
{
|
||||||
return $this->hasMany(StockReservation::class);
|
return $this->belongsTo(StockReservation::class);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -145,6 +219,12 @@ class Purchase extends Model
|
|||||||
return $this->hasMany(TelepagosPayment::class, 'compra_id');
|
return $this->hasMany(TelepagosPayment::class, 'compra_id');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @return HasMany<TelepagosPaymentCandidate, $this> */
|
||||||
|
public function telepagosPaymentCandidates(): HasMany
|
||||||
|
{
|
||||||
|
return $this->hasMany(TelepagosPaymentCandidate::class, 'compra_id');
|
||||||
|
}
|
||||||
|
|
||||||
public function getTotalAmount(): float
|
public function getTotalAmount(): float
|
||||||
{
|
{
|
||||||
if ($this->total !== null) {
|
if ($this->total !== null) {
|
||||||
|
|||||||
@@ -5,10 +5,12 @@ namespace App\Domains\Purchase\Models;
|
|||||||
use App\Domains\Attachable\Models\Attachment;
|
use App\Domains\Attachable\Models\Attachment;
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Catalog\Models\CatalogItem;
|
||||||
use App\Domains\Catalog\Models\Variant;
|
use App\Domains\Catalog\Models\Variant;
|
||||||
|
use App\Domains\Ticket\Models\Ticket;
|
||||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
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\HasMany;
|
||||||
|
|
||||||
#[Fillable([
|
#[Fillable([
|
||||||
'compra_id',
|
'compra_id',
|
||||||
@@ -56,6 +58,12 @@ class PurchaseItem extends Model
|
|||||||
return $this->belongsTo(Purchase::class, 'compra_id');
|
return $this->belongsTo(Purchase::class, 'compra_id');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @return HasMany<Ticket, $this> */
|
||||||
|
public function tickets(): HasMany
|
||||||
|
{
|
||||||
|
return $this->hasMany(Ticket::class, 'source_purchase_item_id');
|
||||||
|
}
|
||||||
|
|
||||||
/** @return BelongsTo<Attachment, $this> */
|
/** @return BelongsTo<Attachment, $this> */
|
||||||
public function imageAttachment(): BelongsTo
|
public function imageAttachment(): BelongsTo
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -6,10 +6,10 @@ use Illuminate\Database\Eloquent\Attributes\Fillable;
|
|||||||
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\HasMany;
|
||||||
|
|
||||||
#[Fillable([
|
#[Fillable([
|
||||||
'compra_id',
|
'compra_id',
|
||||||
'matched_purchase_ids',
|
|
||||||
'cuit_buyer',
|
'cuit_buyer',
|
||||||
'cvu_buyer',
|
'cvu_buyer',
|
||||||
'amount',
|
'amount',
|
||||||
@@ -30,7 +30,6 @@ class TelepagosPayment extends Model
|
|||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'compra_id' => 'integer',
|
'compra_id' => 'integer',
|
||||||
'matched_purchase_ids' => 'array',
|
|
||||||
'amount' => 'decimal:2',
|
'amount' => 'decimal:2',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
@@ -42,4 +41,10 @@ class TelepagosPayment extends Model
|
|||||||
{
|
{
|
||||||
return $this->belongsTo(Purchase::class, 'compra_id');
|
return $this->belongsTo(Purchase::class, 'compra_id');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @return HasMany<TelepagosPaymentCandidate, $this> */
|
||||||
|
public function candidates(): HasMany
|
||||||
|
{
|
||||||
|
return $this->hasMany(TelepagosPaymentCandidate::class, 'telepagos_payment_id');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
50
app/Domains/Purchase/Models/TelepagosPaymentCandidate.php
Normal file
50
app/Domains/Purchase/Models/TelepagosPaymentCandidate.php
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Purchase\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
|
||||||
|
#[Fillable([
|
||||||
|
'telepagos_payment_id',
|
||||||
|
'compra_id',
|
||||||
|
'dni_matches',
|
||||||
|
'dni_distance',
|
||||||
|
'payment_dni',
|
||||||
|
'purchase_dni',
|
||||||
|
'amount_matches',
|
||||||
|
'payment_amount',
|
||||||
|
'purchase_amount',
|
||||||
|
'amount_difference',
|
||||||
|
'match_reason',
|
||||||
|
'confidence',
|
||||||
|
])]
|
||||||
|
class TelepagosPaymentCandidate extends Model
|
||||||
|
{
|
||||||
|
protected $table = 'telepagos_payment_candidates';
|
||||||
|
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'telepagos_payment_id' => 'integer',
|
||||||
|
'compra_id' => 'integer',
|
||||||
|
'dni_matches' => 'boolean',
|
||||||
|
'dni_distance' => 'integer',
|
||||||
|
'amount_matches' => 'boolean',
|
||||||
|
'payment_amount' => 'decimal:2',
|
||||||
|
'purchase_amount' => 'decimal:2',
|
||||||
|
'amount_difference' => 'decimal:2',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function payment(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(TelepagosPayment::class, 'telepagos_payment_id');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function purchase(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Purchase::class, 'compra_id');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ namespace App\Domains\Purchase\Resources;
|
|||||||
|
|
||||||
use App\Domains\Purchase\Models\Purchase;
|
use App\Domains\Purchase\Models\Purchase;
|
||||||
use App\Domains\Purchase\Models\PurchaseItem;
|
use App\Domains\Purchase\Models\PurchaseItem;
|
||||||
|
use App\Domains\Purchase\Models\TelepagosPaymentCandidate;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Http\Resources\Json\JsonResource;
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
@@ -17,12 +18,15 @@ class PurchaseResource extends JsonResource
|
|||||||
*/
|
*/
|
||||||
public function toArray(Request $request): array
|
public function toArray(Request $request): array
|
||||||
{
|
{
|
||||||
|
$serverTime = now();
|
||||||
|
$expiresAt = $this->stockReservation?->expires_at;
|
||||||
$items = $this->resource->relationLoaded('items')
|
$items = $this->resource->relationLoaded('items')
|
||||||
? $this->resource->getRelation('items')
|
? $this->resource->getRelation('items')
|
||||||
: collect();
|
: collect();
|
||||||
$ticketsCount = array_key_exists('tickets_count', $this->resource->getAttributes())
|
$ticketsCount = array_key_exists('tickets_count', $this->resource->getAttributes())
|
||||||
? (int) $this->resource->getAttribute('tickets_count')
|
? (int) $this->resource->getAttribute('tickets_count')
|
||||||
: null;
|
: null;
|
||||||
|
$paymentVerification = $this->resolvePaymentVerification();
|
||||||
|
|
||||||
$subtotal = $items->isNotEmpty()
|
$subtotal = $items->isNotEmpty()
|
||||||
? $items->reduce(
|
? $items->reduce(
|
||||||
@@ -48,7 +52,11 @@ class PurchaseResource extends JsonResource
|
|||||||
'created_at' => $this->created_at,
|
'created_at' => $this->created_at,
|
||||||
'status' => $this->status,
|
'status' => $this->status,
|
||||||
'payment_method' => $this->payment_method,
|
'payment_method' => $this->payment_method,
|
||||||
'expires_at' => $this->expires_at,
|
'expires_at' => $expiresAt,
|
||||||
|
'expires_in_seconds' => $expiresAt === null
|
||||||
|
? null
|
||||||
|
: max(0, $expiresAt->getTimestamp() - $serverTime->getTimestamp()),
|
||||||
|
'server_time' => $serverTime,
|
||||||
'dni' => $this->dni,
|
'dni' => $this->dni,
|
||||||
'transfer_payer_dni' => $this->transfer_payer_dni,
|
'transfer_payer_dni' => $this->transfer_payer_dni,
|
||||||
'telefono' => $this->telefono,
|
'telefono' => $this->telefono,
|
||||||
@@ -58,6 +66,7 @@ class PurchaseResource extends JsonResource
|
|||||||
'items' => PurchaseItemResource::collection($items),
|
'items' => PurchaseItemResource::collection($items),
|
||||||
'tickets_count' => $this->when($ticketsCount !== null, $ticketsCount),
|
'tickets_count' => $this->when($ticketsCount !== null, $ticketsCount),
|
||||||
'has_generated_tickets' => $this->when($ticketsCount !== null, $ticketsCount > 0),
|
'has_generated_tickets' => $this->when($ticketsCount !== null, $ticketsCount > 0),
|
||||||
|
'payment_verification' => $this->when($paymentVerification !== null, $paymentVerification),
|
||||||
'subtotal' => $this->formatMoney($subtotal),
|
'subtotal' => $this->formatMoney($subtotal),
|
||||||
'total' => $this->formatMoney($total),
|
'total' => $this->formatMoney($total),
|
||||||
];
|
];
|
||||||
@@ -77,4 +86,75 @@ class PurchaseResource extends JsonResource
|
|||||||
{
|
{
|
||||||
return number_format((float) ($amount ?? 0), 2, '.', '');
|
return number_format((float) ($amount ?? 0), 2, '.', '');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @return array<string, mixed>|null */
|
||||||
|
private function resolvePaymentVerification(): ?array
|
||||||
|
{
|
||||||
|
if (
|
||||||
|
$this->status !== Purchase::STATUS_IN_REVIEW
|
||||||
|
|| $this->payment_method !== 'transfer'
|
||||||
|
|| ! $this->resource->relationLoaded('telepagosPaymentCandidates')
|
||||||
|
) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$candidates = $this->resource
|
||||||
|
->getRelation('telepagosPaymentCandidates')
|
||||||
|
->sort(fn (TelepagosPaymentCandidate $left, TelepagosPaymentCandidate $right): int => $this->comparePaymentCandidates($left, $right))
|
||||||
|
->values();
|
||||||
|
/** @var TelepagosPaymentCandidate|null $primary */
|
||||||
|
$primary = $candidates->first();
|
||||||
|
|
||||||
|
return [
|
||||||
|
'status' => $primary === null ? 'pending' : 'candidate',
|
||||||
|
'candidate_count' => $candidates->count(),
|
||||||
|
'primary' => $primary === null ? null : [
|
||||||
|
'reason' => $primary->match_reason,
|
||||||
|
'dni_distance' => $primary->dni_distance,
|
||||||
|
'payment_amount' => $this->formatMoney($primary->payment_amount),
|
||||||
|
'purchase_amount' => $this->formatMoney($primary->purchase_amount),
|
||||||
|
'amount_difference' => $this->formatMoney($primary->amount_difference),
|
||||||
|
'confidence' => $primary->confidence,
|
||||||
|
'detected_at' => $primary->payment?->created_at?->toIso8601String(),
|
||||||
|
],
|
||||||
|
'reasons' => $candidates
|
||||||
|
->pluck('match_reason')
|
||||||
|
->unique()
|
||||||
|
->values()
|
||||||
|
->all(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function comparePaymentCandidates(
|
||||||
|
TelepagosPaymentCandidate $left,
|
||||||
|
TelepagosPaymentCandidate $right,
|
||||||
|
): int {
|
||||||
|
$reasonComparison = $this->paymentCandidateRank($left->match_reason)
|
||||||
|
<=> $this->paymentCandidateRank($right->match_reason);
|
||||||
|
|
||||||
|
if ($reasonComparison !== 0) {
|
||||||
|
return $reasonComparison;
|
||||||
|
}
|
||||||
|
|
||||||
|
$differenceComparison = (float) $left->amount_difference <=> (float) $right->amount_difference;
|
||||||
|
|
||||||
|
if ($differenceComparison !== 0) {
|
||||||
|
return $differenceComparison;
|
||||||
|
}
|
||||||
|
|
||||||
|
$leftTimestamp = $left->payment?->created_at?->getTimestamp() ?? 0;
|
||||||
|
$rightTimestamp = $right->payment?->created_at?->getTimestamp() ?? 0;
|
||||||
|
|
||||||
|
return ($rightTimestamp <=> $leftTimestamp) ?: ($right->id <=> $left->id);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function paymentCandidateRank(string $reason): int
|
||||||
|
{
|
||||||
|
return match ($reason) {
|
||||||
|
'ambiguous_exact_match' => 0,
|
||||||
|
'exact_dni_near_amount' => 1,
|
||||||
|
'exact_amount_near_dni' => 2,
|
||||||
|
default => 3,
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -61,10 +61,7 @@ class CompleteCheckoutService
|
|||||||
|
|
||||||
$this->purchaseState->lockCurrentCart($purchase);
|
$this->purchaseState->lockCurrentCart($purchase);
|
||||||
|
|
||||||
if (
|
if ($purchase->status !== Purchase::STATUS_PENDING_PAYMENT) {
|
||||||
$purchase->status !== Purchase::STATUS_PENDING_PAYMENT
|
|
||||||
|| ($purchase->expires_at !== null && $purchase->expires_at->isPast())
|
|
||||||
) {
|
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
'purchase' => __('api.purchase.not_available_for_review'),
|
'purchase' => __('api.purchase.not_available_for_review'),
|
||||||
]);
|
]);
|
||||||
@@ -72,9 +69,8 @@ class CompleteCheckoutService
|
|||||||
|
|
||||||
$purchase->update([
|
$purchase->update([
|
||||||
'status' => Purchase::STATUS_IN_REVIEW,
|
'status' => Purchase::STATUS_IN_REVIEW,
|
||||||
'expires_at' => null,
|
|
||||||
]);
|
]);
|
||||||
$this->reservations->syncPurchaseExpiration($purchase);
|
$this->reservations->clearExpirationForReview($purchase);
|
||||||
|
|
||||||
return $this->loadPurchase($purchase);
|
return $this->loadPurchase($purchase);
|
||||||
});
|
});
|
||||||
@@ -161,14 +157,15 @@ class CompleteCheckoutService
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$this->reservations->commit($cartItem, $selection, $purchase);
|
$this->reservations->commit($purchase);
|
||||||
} catch (\InvalidArgumentException) {
|
} catch (\InvalidArgumentException) {
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
'items' => __('api.purchase.inconsistent_reservation'),
|
'items' => __('api.purchase.inconsistent_reservation'),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
$this->sourceCart->finalize($purchase);
|
$this->sourceCart->finalize($purchase);
|
||||||
});
|
});
|
||||||
@@ -194,7 +191,7 @@ class CompleteCheckoutService
|
|||||||
|
|
||||||
private function loadPurchase(Purchase $purchase): Purchase
|
private function loadPurchase(Purchase $purchase): Purchase
|
||||||
{
|
{
|
||||||
return $purchase->load(['items.imageAttachment']);
|
return $purchase->load(['items.imageAttachment', 'stockReservation']);
|
||||||
}
|
}
|
||||||
|
|
||||||
private function itemKey(int $catalogItemId, ?int $variantId): string
|
private function itemKey(int $catalogItemId, ?int $variantId): string
|
||||||
|
|||||||
@@ -8,6 +8,15 @@ class PurchaseResponseLoader
|
|||||||
{
|
{
|
||||||
public function load(Purchase $purchase): Purchase
|
public function load(Purchase $purchase): Purchase
|
||||||
{
|
{
|
||||||
return $purchase->load(['tenant', 'items.imageAttachment']);
|
$relations = ['tenant', 'items.imageAttachment', 'stockReservation'];
|
||||||
|
|
||||||
|
if (
|
||||||
|
$purchase->status === Purchase::STATUS_IN_REVIEW
|
||||||
|
&& $purchase->payment_method === 'transfer'
|
||||||
|
) {
|
||||||
|
$relations[] = 'telepagosPaymentCandidates.payment';
|
||||||
|
}
|
||||||
|
|
||||||
|
return $purchase->load($relations);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,11 +5,10 @@ namespace App\Domains\Purchase\Services\Checkout;
|
|||||||
use App\Domains\Cart\Models\Cart;
|
use App\Domains\Cart\Models\Cart;
|
||||||
use App\Domains\Catalog\Models\StockReservation;
|
use App\Domains\Catalog\Models\StockReservation;
|
||||||
use App\Domains\Catalog\Services\StockReservationService;
|
use App\Domains\Catalog\Services\StockReservationService;
|
||||||
|
use App\Domains\Purchase\Exceptions\PurchaseExpiredException;
|
||||||
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
|
||||||
{
|
{
|
||||||
@@ -32,40 +31,6 @@ class ReleaseCheckoutService
|
|||||||
return $this->release($purchase, Purchase::STATUS_EXPIRED);
|
return $this->release($purchase, Purchase::STATUS_EXPIRED);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function expireOverdue(): int
|
|
||||||
{
|
|
||||||
$expiredCount = 0;
|
|
||||||
|
|
||||||
Purchase::query()
|
|
||||||
->whereIn('status', [Purchase::STATUS_CREATED, Purchase::STATUS_PENDING_PAYMENT])
|
|
||||||
->whereNotNull('expires_at')
|
|
||||||
->where('expires_at', '<=', now())
|
|
||||||
->orderBy('id')
|
|
||||||
->eachById(function (Purchase $purchase) use (&$expiredCount): void {
|
|
||||||
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) {
|
|
||||||
$expiredCount++;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return $expiredCount;
|
|
||||||
}
|
|
||||||
|
|
||||||
private function release(
|
private function release(
|
||||||
Purchase $purchase,
|
Purchase $purchase,
|
||||||
string $targetStatus,
|
string $targetStatus,
|
||||||
@@ -78,6 +43,16 @@ class ReleaseCheckoutService
|
|||||||
): Purchase {
|
): Purchase {
|
||||||
$purchase = $this->lockPurchase($purchase);
|
$purchase = $this->lockPurchase($purchase);
|
||||||
|
|
||||||
|
if ($purchase->status === Purchase::STATUS_EXPIRED
|
||||||
|
&& $targetStatus === Purchase::STATUS_CANCELLED) {
|
||||||
|
return $this->loadPurchase($purchase);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($purchase->status === Purchase::STATUS_EXPIRED
|
||||||
|
&& $targetStatus !== Purchase::STATUS_EXPIRED) {
|
||||||
|
throw new PurchaseExpiredException;
|
||||||
|
}
|
||||||
|
|
||||||
if ($purchase->status === Purchase::STATUS_PAID) {
|
if ($purchase->status === Purchase::STATUS_PAID) {
|
||||||
if ($targetStatus === Purchase::STATUS_EXPIRED) {
|
if ($targetStatus === Purchase::STATUS_EXPIRED) {
|
||||||
return $this->loadPurchase($purchase);
|
return $this->loadPurchase($purchase);
|
||||||
@@ -100,14 +75,39 @@ class ReleaseCheckoutService
|
|||||||
return $this->loadPurchase($purchase);
|
return $this->loadPurchase($purchase);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$cart = $purchase->cart()->withTrashed()->lockForUpdate()->first();
|
||||||
|
|
||||||
|
// Leaving checkout is allowed at the exact instant the reservation
|
||||||
|
// expires. Finish the expiration while holding the purchase lock so
|
||||||
|
// the request is idempotent with the scheduled expiration job.
|
||||||
|
if ($targetStatus === Purchase::STATUS_CANCELLED
|
||||||
|
&& $this->hasOverdueActiveReservation($purchase)) {
|
||||||
|
$targetStatus = Purchase::STATUS_EXPIRED;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($targetStatus === Purchase::STATUS_CANCELLED
|
||||||
|
&& $cart?->status === 'active'
|
||||||
|
&& in_array($purchase->status, [
|
||||||
|
Purchase::STATUS_CREATED,
|
||||||
|
Purchase::STATUS_PENDING_PAYMENT,
|
||||||
|
], true)) {
|
||||||
|
$this->reservations->returnToCart($purchase, $cart);
|
||||||
|
$purchase->update(['status' => Purchase::STATUS_CANCELLED]);
|
||||||
|
|
||||||
|
return $this->loadPurchase($purchase);
|
||||||
|
}
|
||||||
|
|
||||||
if (
|
if (
|
||||||
$targetStatus === Purchase::STATUS_EXPIRED
|
$targetStatus === Purchase::STATUS_EXPIRED
|
||||||
&& ($purchase->expires_at === null || $purchase->expires_at->isFuture())
|
&& (! in_array($purchase->status, [
|
||||||
|
Purchase::STATUS_CREATED,
|
||||||
|
Purchase::STATUS_PENDING_PAYMENT,
|
||||||
|
], true) || ! $this->hasOverdueActiveReservation($purchase))
|
||||||
) {
|
) {
|
||||||
return $this->loadPurchase($purchase);
|
return $this->loadPurchase($purchase);
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->releasePurchaseReservations($purchase, $targetStatus);
|
$this->releasePurchaseReservations($purchase, $targetStatus, $cart);
|
||||||
|
|
||||||
$purchase->update(['status' => $targetStatus]);
|
$purchase->update(['status' => $targetStatus]);
|
||||||
|
|
||||||
@@ -115,60 +115,67 @@ class ReleaseCheckoutService
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private function releasePurchaseReservations(Purchase $purchase, string $targetStatus): void
|
private function releasePurchaseReservations(
|
||||||
{
|
Purchase $purchase,
|
||||||
$cart = $purchase->cart()->withTrashed()->lockForUpdate()->first();
|
string $targetStatus,
|
||||||
if ($cart === null) {
|
?Cart $cart,
|
||||||
return;
|
): void {
|
||||||
}
|
|
||||||
|
|
||||||
if ($cart->status === 'active') {
|
|
||||||
$this->reservations->detachFromPurchase($purchase);
|
|
||||||
Cart::query()
|
|
||||||
->whereKey($cart->getKey())
|
|
||||||
->where('current_purchase_id', $purchase->getKey())
|
|
||||||
->update(['current_purchase_id' => null]);
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($cart->status !== 'checkout') {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
$cartItems = $cart->items()->orderBy('id')->lockForUpdate()->get();
|
|
||||||
$cartItems->load([
|
|
||||||
'catalogItem.inventory',
|
|
||||||
'catalogItem.bundleComponents.catalogItem.inventory',
|
|
||||||
'catalogItem.bundleComponents.variant.inventory',
|
|
||||||
'variant.inventory',
|
|
||||||
'variant.catalogItem',
|
|
||||||
]);
|
|
||||||
|
|
||||||
foreach ($cartItems as $cartItem) {
|
|
||||||
$selection = $cartItem->selectedItem();
|
|
||||||
if ($selection === null) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$this->reservations->release(
|
$this->reservations->releaseForPurchase(
|
||||||
$cartItem,
|
$purchase,
|
||||||
$selection,
|
|
||||||
(int) $cartItem->cantidad,
|
|
||||||
$targetStatus === Purchase::STATUS_EXPIRED
|
$targetStatus === Purchase::STATUS_EXPIRED
|
||||||
? StockReservation::STATUS_EXPIRED
|
? StockReservation::STATUS_EXPIRED
|
||||||
: StockReservation::STATUS_RELEASED,
|
: StockReservation::STATUS_RELEASED,
|
||||||
|
$targetStatus === Purchase::STATUS_CANCELLED
|
||||||
|
? StockReservationService::REASON_PURCHASE_CANCELLED
|
||||||
|
: ($targetStatus === Purchase::STATUS_REJECTED
|
||||||
|
? StockReservationService::REASON_PAYMENT_REJECTED
|
||||||
|
: null),
|
||||||
);
|
);
|
||||||
} catch (\InvalidArgumentException) {
|
} catch (\InvalidArgumentException) {
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
'items' => __('api.purchase.inconsistent_reservation'),
|
'items' => __('api.purchase.inconsistent_reservation'),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if ($cart === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($targetStatus === Purchase::STATUS_EXPIRED
|
||||||
|
&& in_array($cart->status, [Cart::STATUS_ACTIVE, Cart::STATUS_CHECKOUT], true)) {
|
||||||
|
Cart::query()
|
||||||
|
->whereKey($cart->getKey())
|
||||||
|
->where('current_purchase_id', $purchase->getKey())
|
||||||
|
->where('current_stock_reservation_id', $purchase->stock_reservation_id)
|
||||||
|
->update([
|
||||||
|
'status' => Cart::STATUS_EXPIRED,
|
||||||
|
'current_purchase_id' => null,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($cart->status === Cart::STATUS_ACTIVE) {
|
||||||
|
$cartUpdate = [
|
||||||
|
'current_purchase_id' => null,
|
||||||
|
'current_stock_reservation_id' => null,
|
||||||
|
];
|
||||||
|
|
||||||
|
Cart::query()
|
||||||
|
->whereKey($cart->getKey())
|
||||||
|
->where('current_purchase_id', $purchase->getKey())
|
||||||
|
->update($cartUpdate);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($cart->status !== Cart::STATUS_CHECKOUT) {
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (! $cart->trashed()) {
|
if (! $cart->trashed()) {
|
||||||
$cart->update(['status' => 'converted']);
|
$cart->update(['status' => Cart::STATUS_CONVERTED]);
|
||||||
$cart->delete();
|
$cart->delete();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -218,6 +225,17 @@ class ReleaseCheckoutService
|
|||||||
|
|
||||||
private function loadPurchase(Purchase $purchase): Purchase
|
private function loadPurchase(Purchase $purchase): Purchase
|
||||||
{
|
{
|
||||||
return $purchase->load(['items.imageAttachment']);
|
return $purchase->load(['items.imageAttachment', 'stockReservation']);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function hasOverdueActiveReservation(Purchase $purchase): bool
|
||||||
|
{
|
||||||
|
/** @var StockReservation|null $reservation */
|
||||||
|
$reservation = $purchase->stockReservation()->lockForUpdate()->first();
|
||||||
|
|
||||||
|
return $reservation !== null
|
||||||
|
&& $reservation->status === StockReservation::STATUS_ACTIVE
|
||||||
|
&& $reservation->expires_at !== null
|
||||||
|
&& ! $reservation->expires_at->isFuture();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ 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\Cart\Models\CartItem;
|
||||||
|
use App\Domains\Catalog\Exceptions\StockReservationExpiredException;
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Catalog\Models\CatalogItem;
|
||||||
use App\Domains\Catalog\Models\Variant;
|
use App\Domains\Catalog\Models\Variant;
|
||||||
use App\Domains\Catalog\Services\CatalogInventoryService;
|
use App\Domains\Catalog\Services\CatalogInventoryService;
|
||||||
@@ -12,6 +13,7 @@ use App\Domains\Purchase\Exceptions\InsufficientStockException;
|
|||||||
use App\Domains\Purchase\Models\Purchase;
|
use App\Domains\Purchase\Models\Purchase;
|
||||||
use App\Domains\Purchase\Services\UserPurchaseLimitService;
|
use App\Domains\Purchase\Services\UserPurchaseLimitService;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
|
use Illuminate\Support\Carbon;
|
||||||
use Illuminate\Support\Collection;
|
use Illuminate\Support\Collection;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
@@ -169,21 +171,31 @@ class StartCheckoutService
|
|||||||
'cantidad' => $line['quantity'],
|
'cantidad' => $line['quantity'],
|
||||||
]);
|
]);
|
||||||
|
|
||||||
try {
|
|
||||||
$this->reservations->reserve($cartItem, $line['selection'], $line['quantity']);
|
|
||||||
} catch (\InvalidArgumentException) {
|
|
||||||
$availableQuantity = $this->inventory->availableQuantity($line['selection']) ?? 0;
|
|
||||||
|
|
||||||
throw new InsufficientStockException([
|
|
||||||
$this->unavailableItem($line, $availableQuantity),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
$cartItem->setRelation('catalogItem', $line['catalog_item']);
|
$cartItem->setRelation('catalogItem', $line['catalog_item']);
|
||||||
$cartItem->setRelation('variant', $line['selection'] instanceof Variant ? $line['selection'] : null);
|
$cartItem->setRelation('variant', $line['selection'] instanceof Variant ? $line['selection'] : null);
|
||||||
$cartItems->push($cartItem);
|
$cartItems->push($cartItem);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$this->reservations->syncCart($cart);
|
||||||
|
} catch (\InvalidArgumentException) {
|
||||||
|
$unavailable = $resolvedLines
|
||||||
|
->map(function (array $line): ?array {
|
||||||
|
$availableQuantity = $this->inventory->availableQuantity($line['selection']);
|
||||||
|
|
||||||
|
return $availableQuantity !== null && $availableQuantity < $line['quantity']
|
||||||
|
? $this->unavailableItem($line, $availableQuantity)
|
||||||
|
: null;
|
||||||
|
})
|
||||||
|
->filter()
|
||||||
|
->values()
|
||||||
|
->all();
|
||||||
|
|
||||||
|
throw new InsufficientStockException($unavailable !== [] ? $unavailable : [
|
||||||
|
$this->unavailableItem($resolvedLines->first(), 0),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
$purchase = $this->createPurchase(
|
$purchase = $this->createPurchase(
|
||||||
$tenant,
|
$tenant,
|
||||||
$userId,
|
$userId,
|
||||||
@@ -194,19 +206,12 @@ class StartCheckoutService
|
|||||||
$cart->getKey(),
|
$cart->getKey(),
|
||||||
);
|
);
|
||||||
$cart->update(['current_purchase_id' => $purchase->getKey()]);
|
$cart->update(['current_purchase_id' => $purchase->getKey()]);
|
||||||
|
$this->reservations->attachToPurchase($cart, $purchase, $this->checkoutExpiration());
|
||||||
|
|
||||||
$cartItems = $cart->items()->orderBy('id')->lockForUpdate()->get();
|
$cartItems = $cart->items()->orderBy('id')->lockForUpdate()->get();
|
||||||
$this->loadCartItems($cartItems);
|
$this->loadCartItems($cartItems);
|
||||||
$purchase->items()->createMany($this->snapshots->fromCartItems($cartItems));
|
$purchase->items()->createMany($this->snapshots->fromCartItems($cartItems));
|
||||||
|
|
||||||
foreach ($cartItems as $index => $cartItem) {
|
|
||||||
$this->reservations->attachToPurchase(
|
|
||||||
$cartItem,
|
|
||||||
$resolvedLines->get($index)['selection'],
|
|
||||||
$purchase,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return $this->loadPurchase($purchase);
|
return $this->loadPurchase($purchase);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -257,6 +262,7 @@ class StartCheckoutService
|
|||||||
$this->verifyTenantItems($tenant, $cartItems);
|
$this->verifyTenantItems($tenant, $cartItems);
|
||||||
$this->assertCartPurchaseLimits($tenant, $userId, $cartItems, $cart->getKey());
|
$this->assertCartPurchaseLimits($tenant, $userId, $cartItems, $cart->getKey());
|
||||||
$cart->setRelation('items', $cartItems);
|
$cart->setRelation('items', $cartItems);
|
||||||
|
$this->reservations->syncCart($cart);
|
||||||
|
|
||||||
$purchase = $this->createPurchase(
|
$purchase = $this->createPurchase(
|
||||||
$tenant,
|
$tenant,
|
||||||
@@ -266,16 +272,9 @@ class StartCheckoutService
|
|||||||
$cart->getKey(),
|
$cart->getKey(),
|
||||||
);
|
);
|
||||||
$cart->update(['current_purchase_id' => $purchase->getKey()]);
|
$cart->update(['current_purchase_id' => $purchase->getKey()]);
|
||||||
|
$this->reservations->attachToPurchase($cart, $purchase, $this->checkoutExpiration());
|
||||||
$purchase->items()->createMany($this->snapshots->fromCartItems($cartItems));
|
$purchase->items()->createMany($this->snapshots->fromCartItems($cartItems));
|
||||||
|
|
||||||
foreach ($cartItems as $cartItem) {
|
|
||||||
$this->reservations->attachToPurchase(
|
|
||||||
$cartItem,
|
|
||||||
$cartItem->selectedItem(),
|
|
||||||
$purchase,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return $this->loadPurchase($purchase);
|
return $this->loadPurchase($purchase);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -316,9 +315,9 @@ class StartCheckoutService
|
|||||||
Purchase::STATUS_CREATED,
|
Purchase::STATUS_CREATED,
|
||||||
Purchase::STATUS_PENDING_PAYMENT,
|
Purchase::STATUS_PENDING_PAYMENT,
|
||||||
], true)) {
|
], true)) {
|
||||||
|
$this->reservations->returnToCart($currentPurchase, $cart);
|
||||||
$currentPurchase->update([
|
$currentPurchase->update([
|
||||||
'status' => Purchase::STATUS_SUPERSEDED,
|
'status' => Purchase::STATUS_SUPERSEDED,
|
||||||
'expires_at' => null,
|
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -331,7 +330,11 @@ class StartCheckoutService
|
|||||||
throw new NotFoundHttpException('Cart not found for tenant.');
|
throw new NotFoundHttpException('Cart not found for tenant.');
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($cart->status !== 'active') {
|
if ($cart->status === Cart::STATUS_EXPIRED) {
|
||||||
|
throw new StockReservationExpiredException;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($cart->status !== Cart::STATUS_ACTIVE) {
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
'cart_id' => __('api.purchase.inactive_cart'),
|
'cart_id' => __('api.purchase.inactive_cart'),
|
||||||
]);
|
]);
|
||||||
@@ -405,13 +408,17 @@ class StartCheckoutService
|
|||||||
'user_id' => $userId,
|
'user_id' => $userId,
|
||||||
'status' => Purchase::STATUS_CREATED,
|
'status' => Purchase::STATUS_CREATED,
|
||||||
'payment_method' => null,
|
'payment_method' => null,
|
||||||
'expires_at' => now()->addMinutes(
|
|
||||||
max(1, (int) config('purchase.checkout_expiration_minutes', 30)),
|
|
||||||
),
|
|
||||||
'total' => $total,
|
'total' => $total,
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function checkoutExpiration(): Carbon
|
||||||
|
{
|
||||||
|
return now()->addMinutes(
|
||||||
|
max(1, (int) config('purchase.checkout_expiration_minutes', 30)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/** @param Collection<int, CartItem> $cartItems */
|
/** @param Collection<int, CartItem> $cartItems */
|
||||||
private function loadCartItems(Collection $cartItems): void
|
private function loadCartItems(Collection $cartItems): void
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -2,7 +2,6 @@
|
|||||||
|
|
||||||
namespace App\Domains\Purchase\Services;
|
namespace App\Domains\Purchase\Services;
|
||||||
|
|
||||||
use App\Domains\Catalog\Services\StockReservationService;
|
|
||||||
use App\Domains\Purchase\Models\Purchase;
|
use App\Domains\Purchase\Models\Purchase;
|
||||||
use App\Domains\Purchase\Services\Checkout\CompleteCheckoutService;
|
use App\Domains\Purchase\Services\Checkout\CompleteCheckoutService;
|
||||||
use App\Domains\Purchase\Services\Checkout\EditCheckoutService;
|
use App\Domains\Purchase\Services\Checkout\EditCheckoutService;
|
||||||
@@ -23,7 +22,6 @@ class CheckoutService
|
|||||||
private readonly EditCheckoutService $editor,
|
private readonly EditCheckoutService $editor,
|
||||||
private readonly CompleteCheckoutService $completer,
|
private readonly CompleteCheckoutService $completer,
|
||||||
private readonly ReleaseCheckoutService $releaser,
|
private readonly ReleaseCheckoutService $releaser,
|
||||||
private readonly StockReservationService $reservations,
|
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
/** @param array<string, mixed> $purchaseData */
|
/** @param array<string, mixed> $purchaseData */
|
||||||
@@ -77,14 +75,4 @@ class CheckoutService
|
|||||||
{
|
{
|
||||||
return $this->releaser->expire($purchase);
|
return $this->releaser->expire($purchase);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function expireOverduePurchases(): int
|
|
||||||
{
|
|
||||||
return $this->releaser->expireOverdue();
|
|
||||||
}
|
|
||||||
|
|
||||||
public function syncReservationExpiration(Purchase $purchase): void
|
|
||||||
{
|
|
||||||
$this->reservations->syncPurchaseExpiration($purchase);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
82
app/Domains/Purchase/Services/DniDistanceService.php
Normal file
82
app/Domains/Purchase/Services/DniDistanceService.php
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Purchase\Services;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Measures likely DNI typing errors using the optimal-string-alignment
|
||||||
|
* variant of the Damerau-Levenshtein distance.
|
||||||
|
*
|
||||||
|
* The returned value is the minimum number of single-character edits needed
|
||||||
|
* to transform one DNI into the other. Supported edits are insertion,
|
||||||
|
* deletion, substitution and transposition of two adjacent digits.
|
||||||
|
*/
|
||||||
|
class DniDistanceService
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Calculate the edit distance between two normalized DNI strings.
|
||||||
|
*
|
||||||
|
* Each matrix cell [row][column] stores the minimum edits required to
|
||||||
|
* transform the first $row digits of $left into the first $column digits
|
||||||
|
* of $right. The bottom-right cell therefore contains the final distance.
|
||||||
|
*/
|
||||||
|
public function distance(string $left, string $right): int
|
||||||
|
{
|
||||||
|
$left = $this->normalize($left);
|
||||||
|
$right = $this->normalize($right);
|
||||||
|
$leftLength = strlen($left);
|
||||||
|
$rightLength = strlen($right);
|
||||||
|
$matrix = [];
|
||||||
|
|
||||||
|
// Transforming a prefix into an empty string requires deleting every digit.
|
||||||
|
for ($row = 0; $row <= $leftLength; $row++) {
|
||||||
|
$matrix[$row] = [$row];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Transforming an empty string into a prefix requires inserting every digit.
|
||||||
|
for ($column = 0; $column <= $rightLength; $column++) {
|
||||||
|
$matrix[0][$column] = $column;
|
||||||
|
}
|
||||||
|
|
||||||
|
for ($row = 1; $row <= $leftLength; $row++) {
|
||||||
|
for ($column = 1; $column <= $rightLength; $column++) {
|
||||||
|
$substitutionCost = $left[$row - 1] === $right[$column - 1] ? 0 : 1;
|
||||||
|
$deletionDistance = $matrix[$row - 1][$column] + 1;
|
||||||
|
$insertionDistance = $matrix[$row][$column - 1] + 1;
|
||||||
|
$substitutionDistance = $matrix[$row - 1][$column - 1] + $substitutionCost;
|
||||||
|
|
||||||
|
// Keep the cheapest way to align the two prefixes at this position.
|
||||||
|
$matrix[$row][$column] = min(
|
||||||
|
$deletionDistance,
|
||||||
|
$insertionDistance,
|
||||||
|
$substitutionDistance,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Count two adjacent inverted digits as one edit instead of two substitutions.
|
||||||
|
if (
|
||||||
|
$row > 1
|
||||||
|
&& $column > 1
|
||||||
|
&& $left[$row - 1] === $right[$column - 2]
|
||||||
|
&& $left[$row - 2] === $right[$column - 1]
|
||||||
|
) {
|
||||||
|
$matrix[$row][$column] = min(
|
||||||
|
$matrix[$row][$column],
|
||||||
|
$matrix[$row - 2][$column - 2] + 1,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $matrix[$leftLength][$rightLength];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keep only digits and left-pad seven-digit DNIs so comparisons preserve
|
||||||
|
* the leading zero that is present when the DNI is extracted from a CUIT.
|
||||||
|
*/
|
||||||
|
public function normalize(string $dni): string
|
||||||
|
{
|
||||||
|
$digits = preg_replace('/\D+/', '', $dni) ?? '';
|
||||||
|
|
||||||
|
return str_pad($digits, 8, '0', STR_PAD_LEFT);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
namespace App\Domains\Purchase\Services;
|
namespace App\Domains\Purchase\Services;
|
||||||
|
|
||||||
use App\Domains\Cart\Models\Cart;
|
use App\Domains\Cart\Models\Cart;
|
||||||
|
use App\Domains\Catalog\Models\StockReservation;
|
||||||
use App\Domains\Purchase\Exceptions\PurchaseExpiredException;
|
use App\Domains\Purchase\Exceptions\PurchaseExpiredException;
|
||||||
use App\Domains\Purchase\Models\Purchase;
|
use App\Domains\Purchase\Models\Purchase;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
@@ -11,15 +12,32 @@ class PurchaseStateGuard
|
|||||||
{
|
{
|
||||||
public function assertNotExpired(Purchase $purchase): void
|
public function assertNotExpired(Purchase $purchase): void
|
||||||
{
|
{
|
||||||
$hasExpiredStatus = $purchase->status === Purchase::STATUS_EXPIRED;
|
if ($purchase->status === Purchase::STATUS_EXPIRED) {
|
||||||
$hasExpiredByTime = in_array($purchase->status, [
|
throw new PurchaseExpiredException;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! in_array($purchase->status, [
|
||||||
Purchase::STATUS_CREATED,
|
Purchase::STATUS_CREATED,
|
||||||
Purchase::STATUS_PENDING_PAYMENT,
|
Purchase::STATUS_PENDING_PAYMENT,
|
||||||
], true)
|
], true)) {
|
||||||
&& $purchase->expires_at !== null
|
return;
|
||||||
&& $purchase->expires_at->isPast();
|
}
|
||||||
|
|
||||||
if ($hasExpiredStatus || $hasExpiredByTime) {
|
/** @var StockReservation|null $reservation */
|
||||||
|
$reservation = $purchase->relationLoaded('stockReservation')
|
||||||
|
? $purchase->getRelation('stockReservation')
|
||||||
|
: ($purchase->exists
|
||||||
|
? $purchase->stockReservation()->first()
|
||||||
|
: null);
|
||||||
|
|
||||||
|
if ($reservation !== null && (
|
||||||
|
$reservation->status === StockReservation::STATUS_EXPIRED
|
||||||
|
|| (
|
||||||
|
$reservation->status === StockReservation::STATUS_ACTIVE
|
||||||
|
&& $reservation->expires_at !== null
|
||||||
|
&& ! $reservation->expires_at->isFuture()
|
||||||
|
)
|
||||||
|
)) {
|
||||||
throw new PurchaseExpiredException;
|
throw new PurchaseExpiredException;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -135,11 +135,25 @@ class TenantTransactionResetService
|
|||||||
*/
|
*/
|
||||||
private function reservationQuery(array $scope): Builder
|
private function reservationQuery(array $scope): Builder
|
||||||
{
|
{
|
||||||
|
$reservationIds = DB::table('carritos')
|
||||||
|
->whereIn('id', $scope['cart_ids'])
|
||||||
|
->whereNotNull('current_stock_reservation_id')
|
||||||
|
->pluck('current_stock_reservation_id')
|
||||||
|
->merge(
|
||||||
|
DB::table('compras')
|
||||||
|
->whereIn('id', $scope['purchase_ids'])
|
||||||
|
->whereNotNull('stock_reservation_id')
|
||||||
|
->pluck('stock_reservation_id'),
|
||||||
|
)
|
||||||
|
->merge(
|
||||||
|
DB::table('stock_reservation_lines')
|
||||||
|
->whereIn('inventory_id', $scope['inventory_ids'])
|
||||||
|
->pluck('stock_reservation_id'),
|
||||||
|
)
|
||||||
|
->unique()
|
||||||
|
->values();
|
||||||
|
|
||||||
return DB::table('stock_reservations')
|
return DB::table('stock_reservations')
|
||||||
->where(function (Builder $query) use ($scope): void {
|
->whereIn('id', $reservationIds);
|
||||||
$query->whereIn('inventory_id', $scope['inventory_ids'])
|
|
||||||
->orWhereIn('purchase_id', $scope['purchase_ids'])
|
|
||||||
->orWhereIn('cart_item_id', $scope['cart_item_ids']);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -88,9 +88,9 @@ class UserPurchaseLimitService
|
|||||||
$excludedCartId !== null,
|
$excludedCartId !== null,
|
||||||
fn ($query) => $query->whereKeyNot($excludedCartId),
|
fn ($query) => $query->whereKeyNot($excludedCartId),
|
||||||
))
|
))
|
||||||
->whereHas('stockReservations', fn ($query) => $query
|
->whereHas('cart.currentStockReservation', fn ($query) => $query
|
||||||
->where('status', 'active')
|
->where('status', 'active')
|
||||||
->whereNull('purchase_id'))
|
->whereDoesntHave('purchase'))
|
||||||
->sum('cantidad');
|
->sum('cantidad');
|
||||||
|
|
||||||
if ($purchasedQuantity + $checkoutQuantity + $reservedCartQuantity + $requestedQuantity > $limit) {
|
if ($purchasedQuantity + $checkoutQuantity + $reservedCartQuantity + $requestedQuantity > $limit) {
|
||||||
@@ -161,9 +161,9 @@ class UserPurchaseLimitService
|
|||||||
->whereHas('cart', fn ($query) => $query
|
->whereHas('cart', fn ($query) => $query
|
||||||
->where('user_id', $userId)
|
->where('user_id', $userId)
|
||||||
->where('status', 'active'))
|
->where('status', 'active'))
|
||||||
->whereHas('stockReservations', fn ($query) => $query
|
->whereHas('cart.currentStockReservation', fn ($query) => $query
|
||||||
->where('status', 'active')
|
->where('status', 'active')
|
||||||
->whereNull('purchase_id'))
|
->whereDoesntHave('purchase'))
|
||||||
->groupBy('catalog_item_id')
|
->groupBy('catalog_item_id')
|
||||||
->pluck('quantity', 'catalog_item_id');
|
->pluck('quantity', 'catalog_item_id');
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ Implementa el ciclo de compra y checkout: crea la cabecera de compra desde un ca
|
|||||||
|
|
||||||
## Modelo
|
## Modelo
|
||||||
|
|
||||||
- `Purchase`: raíz de la compra; estados `created`, `pending_payment`, `in_review`, `paid`, `cancelled`, `rejected` y `expired`.
|
- `Purchase`: raíz de la compra; estados `created`, `pending_payment`, `in_review`, `paid`, `cancelled`, `rejected` y `expired`, y referencia la reserva que respaldó ese intento de checkout. No guarda un vencimiento propio: expira como consecuencia del vencimiento de su reserva.
|
||||||
- `PurchaseItem`: snapshot definitivo del producto o variante, creado recién al confirmar la compra.
|
- `PurchaseItem`: snapshot definitivo del producto o variante, creado recién al confirmar la compra.
|
||||||
- `TelepagosQr` y `TelepagosPayment`: datos del QR e intentos/resultados del proveedor.
|
- `TelepagosQr` y `TelepagosPayment`: datos del QR e intentos/resultados del proveedor.
|
||||||
- `PurchasePaid`: evento emitido una sola vez al pasar a pagada bajo bloqueo transaccional.
|
- `PurchasePaid`: evento emitido una sola vez al pasar a pagada bajo bloqueo transaccional.
|
||||||
@@ -15,16 +15,16 @@ Implementa el ciclo de compra y checkout: crea la cabecera de compra desde un ca
|
|||||||
|
|
||||||
`CheckoutService` es la fachada estable. Delega en:
|
`CheckoutService` es la fachada estable. Delega en:
|
||||||
|
|
||||||
- `StartCheckoutService`: inicia la compra desde el carrito o crea un carrito técnico para compra directa, sin crear todavía `PurchaseItem`.
|
- `StartCheckoutService`: inicia la compra desde el carrito o crea un carrito técnico para compra directa, refresca el vencimiento de la reserva agregada y crea los snapshots `PurchaseItem`.
|
||||||
- `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 o vence una compra y aplica sus efectos comerciales; el scanner unificado del dominio Catalog detecta las reservas pendientes de vencimiento.
|
||||||
- `SourceCartService`: sincroniza o finaliza el carrito de checkout asociado a la compra.
|
- `SourceCartService`: sincroniza o finaliza el carrito de checkout asociado a la compra.
|
||||||
- `CatalogSelectionResolver` y `PurchaseItemSnapshotFactory`: resuelven selecciones y generan snapshots.
|
- `CatalogSelectionResolver` y `PurchaseItemSnapshotFactory`: resuelven selecciones y generan snapshots.
|
||||||
|
|
||||||
Al informar una transferencia, la compra pasa de `pending_payment` a `in_review` y deja de vencer. Si el comprador abandona el checkout durante la revisión, la compra y sus reservas permanecen intactas y se crea un carrito activo nuevo para que pueda seguir comprando. Adminapp puede confirmar o anular explícitamente la compra en revisión.
|
Al iniciar checkout o elegir un medio de pago se refresca directamente `StockReservation.expires_at`, que es la única fuente de verdad y se expone como `expires_at` en la respuesta pública de la compra. El refresco sólo se permite mientras la reserva siga vigente; una fecha vencida bloquea todas las mutaciones aun antes de que corra el scheduler. Al materializar la expiración, la compra pagable, su carrito y la reserva pasan a `expired` dentro de la misma transacción. Al cancelar o reemplazar una compra recuperable, ésta se desvincula y el carrito conserva la misma reserva activa. Al informar una transferencia, la compra pasa de `pending_payment` a `in_review` y ese vencimiento se limpia. Si el comprador abandona el checkout durante la revisión, la compra y sus reservas permanecen intactas y se crea un carrito activo nuevo para que pueda seguir comprando. Adminapp puede confirmar o anular explícitamente la compra en revisión.
|
||||||
|
|
||||||
Las cantidades y variantes se editan mediante el dominio Cart. El endpoint autenticado `PATCH /checkout-carts/{cart}/items/{cartItem}` valida que el carrito pertenezca al usuario y a una compra editable. Cuando existe un cambio real, invalida atómicamente el intento de pago anterior, recalcula el total y renueva la reserva; Purchase no expone operaciones sobre líneas antes de la confirmación.
|
Las cantidades y variantes se editan mediante el dominio Cart. El endpoint autenticado `PATCH /checkout-carts/{cart}/items/{cartItem}` valida que el carrito pertenezca al usuario y a una compra editable. Cuando existe un cambio real, invalida atómicamente el intento de pago anterior, devuelve la misma reserva activa al carrito y sincroniza sus líneas con el contenido actualizado; Purchase no expone operaciones sobre líneas antes de la confirmación.
|
||||||
|
|
||||||
`UserPurchaseLimitService` controla límites de compra y `CheckoutService` conserva el punto de entrada para controladores e integraciones.
|
`UserPurchaseLimitService` controla límites de compra y `CheckoutService` conserva el punto de entrada para controladores e integraciones.
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
namespace App\Domains\Sale\Controllers\AdminApp;
|
namespace App\Domains\Sale\Controllers\AdminApp;
|
||||||
|
|
||||||
use App\Domains\Sale\Requests\AdminAppSaleIndexRequest;
|
use App\Domains\Sale\Requests\AdminAppSaleIndexRequest;
|
||||||
|
use App\Domains\Sale\Requests\AdminAppSaleModificationIndexRequest;
|
||||||
use App\Domains\Sale\Requests\AdminAppSaleModificationPdfRequest;
|
use App\Domains\Sale\Requests\AdminAppSaleModificationPdfRequest;
|
||||||
use App\Domains\Sale\Requests\AdminAppSalePdfRequest;
|
use App\Domains\Sale\Requests\AdminAppSalePdfRequest;
|
||||||
use App\Domains\Sale\Resources\AdminApp\SaleDetailResource;
|
use App\Domains\Sale\Resources\AdminApp\SaleDetailResource;
|
||||||
@@ -67,11 +68,13 @@ class SaleController extends Controller
|
|||||||
return new SaleResource($this->saleService->cancel($tenant, $sale));
|
return new SaleResource($this->saleService->cancel($tenant, $sale));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function modifications(Request $request): AnonymousResourceCollection
|
public function modifications(
|
||||||
{
|
AdminAppSaleModificationIndexRequest $request,
|
||||||
|
): AnonymousResourceCollection {
|
||||||
return SaleModificationResource::collection(
|
return SaleModificationResource::collection(
|
||||||
$this->saleService->modifications(
|
$this->saleService->modifications(
|
||||||
$request->user()->tenant()->firstOrFail()
|
$request->user()->tenant()->firstOrFail(),
|
||||||
|
$request->validated(),
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -93,7 +96,7 @@ class SaleController extends Controller
|
|||||||
|
|
||||||
return $this->salePdfService->downloadModifications(
|
return $this->salePdfService->downloadModifications(
|
||||||
$tenant,
|
$tenant,
|
||||||
$this->saleService->modificationsForExport($tenant),
|
$this->saleService->modificationsForExport($tenant, $request->validated()),
|
||||||
$request->validated('timezone'),
|
$request->validated('timezone'),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -116,7 +119,7 @@ class SaleController extends Controller
|
|||||||
|
|
||||||
return $this->saleExcelService->downloadModifications(
|
return $this->saleExcelService->downloadModifications(
|
||||||
$tenant,
|
$tenant,
|
||||||
$this->saleService->modificationsForExport($tenant),
|
$this->saleService->modificationsForExport($tenant, $request->validated()),
|
||||||
$request->validated('timezone'),
|
$request->validated('timezone'),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ class AdminAppSaleIndexRequest extends FormRequest
|
|||||||
'q' => ['sometimes', 'nullable', 'string', 'max:255'],
|
'q' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||||
'id' => ['sometimes', 'nullable', 'integer', 'min:1'],
|
'id' => ['sometimes', 'nullable', 'integer', 'min:1'],
|
||||||
'sale_date' => ['sometimes', 'nullable', 'date_format:Y-m-d'],
|
'sale_date' => ['sometimes', 'nullable', 'date_format:Y-m-d'],
|
||||||
'status' => ['sometimes', 'nullable', 'string', Rule::in(Purchase::statuses())],
|
'status' => ['sometimes', 'nullable', 'string', Rule::in(Purchase::adminStatusCodes())],
|
||||||
'sort_by' => ['sometimes', 'string', 'in:id,date,customer_name,quantity,status,total'],
|
'sort_by' => ['sometimes', 'string', 'in:id,date,customer_name,quantity,status,total'],
|
||||||
'sort_direction' => ['sometimes', 'string', 'in:asc,desc'],
|
'sort_direction' => ['sometimes', 'string', 'in:asc,desc'],
|
||||||
'page' => ['sometimes', 'integer', 'min:1'],
|
'page' => ['sometimes', 'integer', 'min:1'],
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Sale\Requests;
|
||||||
|
|
||||||
|
class AdminAppSaleModificationIndexRequest extends AdminAppSaleIndexRequest
|
||||||
|
{
|
||||||
|
/** @return array<string, list<string>> */
|
||||||
|
public function rules(): array
|
||||||
|
{
|
||||||
|
$rules = parent::rules();
|
||||||
|
|
||||||
|
unset($rules['sort_by'], $rules['sort_direction']);
|
||||||
|
|
||||||
|
return $rules;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,19 +3,14 @@
|
|||||||
namespace App\Domains\Sale\Requests;
|
namespace App\Domains\Sale\Requests;
|
||||||
|
|
||||||
use App\Domains\Shared\Rules\ValidTimezone;
|
use App\Domains\Shared\Rules\ValidTimezone;
|
||||||
use Illuminate\Foundation\Http\FormRequest;
|
|
||||||
|
|
||||||
class AdminAppSaleModificationPdfRequest extends FormRequest
|
class AdminAppSaleModificationPdfRequest extends AdminAppSaleModificationIndexRequest
|
||||||
{
|
{
|
||||||
public function authorize(): bool
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return array<string, list<string>> */
|
/** @return array<string, list<string>> */
|
||||||
public function rules(): array
|
public function rules(): array
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
|
...parent::rules(),
|
||||||
'timezone' => ['required', 'string', new ValidTimezone],
|
'timezone' => ['required', 'string', new ValidTimezone],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,6 +23,12 @@ class SaleModificationResource extends JsonResource
|
|||||||
'attribute' => $this->attribute,
|
'attribute' => $this->attribute,
|
||||||
'old_value' => $this->old_value,
|
'old_value' => $this->old_value,
|
||||||
'new_value' => $this->new_value,
|
'new_value' => $this->new_value,
|
||||||
|
'admin_status' => is_string($this->new_value)
|
||||||
|
? Purchase::adminStatusFor($this->new_value)
|
||||||
|
: null,
|
||||||
|
'status_label' => is_string($this->new_value)
|
||||||
|
? Purchase::adminStatusNameFor($this->new_value)
|
||||||
|
: null,
|
||||||
'changed_at' => $this->changed_at->utc()->toIso8601String(),
|
'changed_at' => $this->changed_at->utc()->toIso8601String(),
|
||||||
'date' => $this->changed_at->format('Y-m-d'),
|
'date' => $this->changed_at->format('Y-m-d'),
|
||||||
'time' => $this->changed_at->format('H:i:s'),
|
'time' => $this->changed_at->format('H:i:s'),
|
||||||
@@ -31,6 +37,8 @@ class SaleModificationResource extends JsonResource
|
|||||||
'id' => $sale->id,
|
'id' => $sale->id,
|
||||||
'customer_name' => $sale->nombre_apellido,
|
'customer_name' => $sale->nombre_apellido,
|
||||||
'status' => $sale->status,
|
'status' => $sale->status,
|
||||||
|
'admin_status' => Purchase::adminStatusFor($sale->status),
|
||||||
|
'status_label' => Purchase::adminStatusNameFor($sale->status),
|
||||||
] : null,
|
] : null,
|
||||||
'modified_by' => $user ? [
|
'modified_by' => $user ? [
|
||||||
'id' => $user->id,
|
'id' => $user->id,
|
||||||
|
|||||||
@@ -20,6 +20,8 @@ class SaleResource extends JsonResource
|
|||||||
'customer_name' => $this->nombre_apellido,
|
'customer_name' => $this->nombre_apellido,
|
||||||
'quantity' => (int) ($this->quantity ?? 0),
|
'quantity' => (int) ($this->quantity ?? 0),
|
||||||
'status' => $this->status,
|
'status' => $this->status,
|
||||||
|
'admin_status' => Purchase::adminStatusFor($this->status),
|
||||||
|
'status_label' => Purchase::adminStatusNameFor($this->status),
|
||||||
'total' => number_format((float) $this->total, 2, '.', ''),
|
'total' => number_format((float) $this->total, 2, '.', ''),
|
||||||
'tickets_count' => $ticketsCount,
|
'tickets_count' => $ticketsCount,
|
||||||
'has_generated_tickets' => $ticketsCount > 0,
|
'has_generated_tickets' => $ticketsCount > 0,
|
||||||
|
|||||||
@@ -201,11 +201,6 @@ class AdminAppSaleExcelService
|
|||||||
|
|
||||||
private function saleStatus(string $status): string
|
private function saleStatus(string $status): string
|
||||||
{
|
{
|
||||||
return match ($status) {
|
return Purchase::adminStatusNameFor($status) ?? $status;
|
||||||
Purchase::STATUS_PAID => 'Confirmado',
|
|
||||||
Purchase::STATUS_CREATED => 'Por completar datos',
|
|
||||||
Purchase::STATUS_PENDING_PAYMENT, Purchase::STATUS_IN_REVIEW => 'Esperando pago',
|
|
||||||
default => 'Anulado',
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -92,18 +92,24 @@ class AdminAppSaleService
|
|||||||
return $this->salesQuery($tenant, $filters)->get();
|
return $this->salesQuery($tenant, $filters)->get();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return LengthAwarePaginator<ValueChange> */
|
/**
|
||||||
public function modifications(Tenant $tenant): LengthAwarePaginator
|
* @param array<string, mixed> $filters
|
||||||
|
* @return LengthAwarePaginator<ValueChange>
|
||||||
|
*/
|
||||||
|
public function modifications(Tenant $tenant, array $filters = []): LengthAwarePaginator
|
||||||
{
|
{
|
||||||
return $this->modificationsQuery($tenant)
|
return $this->modificationsQuery($tenant, $filters)
|
||||||
->paginateFromRequest()
|
->paginateFromRequest()
|
||||||
->withQueryString();
|
->withQueryString();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return Collection<int, ValueChange> */
|
/**
|
||||||
public function modificationsForExport(Tenant $tenant): Collection
|
* @param array<string, mixed> $filters
|
||||||
|
* @return Collection<int, ValueChange>
|
||||||
|
*/
|
||||||
|
public function modificationsForExport(Tenant $tenant, array $filters = []): Collection
|
||||||
{
|
{
|
||||||
return $this->modificationsQuery($tenant)->get();
|
return $this->modificationsQuery($tenant, $filters)->get();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @param array<string, mixed> $filters */
|
/** @param array<string, mixed> $filters */
|
||||||
@@ -126,7 +132,6 @@ class AdminAppSaleService
|
|||||||
|
|
||||||
return Purchase::query()
|
return Purchase::query()
|
||||||
->where('tenant_codigo', $tenant->codigo)
|
->where('tenant_codigo', $tenant->codigo)
|
||||||
->where('status', '!=', Purchase::STATUS_SUPERSEDED)
|
|
||||||
->when($filters['q'] ?? null, function (Builder $query, string $search): void {
|
->when($filters['q'] ?? null, function (Builder $query, string $search): void {
|
||||||
$term = trim($search);
|
$term = trim($search);
|
||||||
|
|
||||||
@@ -144,12 +149,10 @@ class AdminAppSaleService
|
|||||||
)
|
)
|
||||||
->when(
|
->when(
|
||||||
$filters['status'] ?? null,
|
$filters['status'] ?? null,
|
||||||
fn (Builder $query, string $status): Builder => $status === Purchase::STATUS_PENDING_PAYMENT
|
fn (Builder $query, string $status): Builder => $query->whereIn(
|
||||||
? $query->whereIn('status', [
|
'status',
|
||||||
Purchase::STATUS_PENDING_PAYMENT,
|
Purchase::realStatusesForAdminStatus($status),
|
||||||
Purchase::STATUS_IN_REVIEW,
|
)
|
||||||
])
|
|
||||||
: $query->where('status', $status)
|
|
||||||
)
|
)
|
||||||
->select('compras.*')
|
->select('compras.*')
|
||||||
->selectRaw(
|
->selectRaw(
|
||||||
@@ -162,12 +165,50 @@ class AdminAppSaleService
|
|||||||
->when($sortBy !== 'id', fn (Builder $query): Builder => $query->orderByDesc('id'));
|
->when($sortBy !== 'id', fn (Builder $query): Builder => $query->orderByDesc('id'));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return Builder<ValueChange> */
|
/**
|
||||||
protected function modificationsQuery(Tenant $tenant): Builder
|
* @param array<string, mixed> $filters
|
||||||
|
* @return Builder<ValueChange>
|
||||||
|
*/
|
||||||
|
protected function modificationsQuery(Tenant $tenant, array $filters): Builder
|
||||||
{
|
{
|
||||||
return ValueChange::query()
|
return ValueChange::query()
|
||||||
->where('tenant_code', $tenant->codigo)
|
->where('tenant_code', $tenant->codigo)
|
||||||
->where('trackable_type', (new Purchase)->getMorphClass())
|
->where('trackable_type', (new Purchase)->getMorphClass())
|
||||||
|
->when($filters['q'] ?? null, function (Builder $query, string $search): void {
|
||||||
|
$term = trim($search);
|
||||||
|
|
||||||
|
$query->where(function (Builder $query) use ($term): void {
|
||||||
|
$query
|
||||||
|
->where('trackable_id', 'like', "%{$term}%")
|
||||||
|
->orWhereHasMorph(
|
||||||
|
'trackable',
|
||||||
|
[Purchase::class],
|
||||||
|
function (Builder $sales) use ($term): void {
|
||||||
|
$sales
|
||||||
|
->where('nombre_apellido', 'like', "%{$term}%")
|
||||||
|
->orWhere('created_at', 'like', "%{$term}%");
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
->when(
|
||||||
|
$filters['id'] ?? null,
|
||||||
|
fn (Builder $query, int $id): Builder => $query->where('trackable_id', $id)
|
||||||
|
)
|
||||||
|
->when(
|
||||||
|
$filters['sale_date'] ?? null,
|
||||||
|
fn (Builder $query, string $date): Builder => $query->whereHasMorph(
|
||||||
|
'trackable',
|
||||||
|
[Purchase::class],
|
||||||
|
fn (Builder $sales): Builder => $sales->whereDate('created_at', $date),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
->when(
|
||||||
|
$filters['status'] ?? null,
|
||||||
|
fn (Builder $query, string $status): Builder => $query
|
||||||
|
->where('attribute', 'status')
|
||||||
|
->whereIn('new_value', Purchase::realStatusesForAdminStatus($status))
|
||||||
|
)
|
||||||
->with(['trackable', 'user'])
|
->with(['trackable', 'user'])
|
||||||
->orderByDesc('changed_at')
|
->orderByDesc('changed_at')
|
||||||
->orderByDesc('id');
|
->orderByDesc('id');
|
||||||
|
|||||||
@@ -9,7 +9,8 @@ Provee consultas administrativas y exportaciones de ventas confirmadas, además
|
|||||||
- `AdminAppSaleService`: pagina ventas, calcula totales y obtiene colecciones para exportación; también consulta modificaciones.
|
- `AdminAppSaleService`: pagina ventas, calcula totales y obtiene colecciones para exportación; también consulta modificaciones.
|
||||||
- `AdminAppSalePdfService`: genera descargas PDF de ventas y de cambios.
|
- `AdminAppSalePdfService`: genera descargas PDF de ventas y de cambios.
|
||||||
- `AdminAppSaleExcelService`: genera descargas Excel de ventas y de cambios.
|
- `AdminAppSaleExcelService`: genera descargas Excel de ventas y de cambios.
|
||||||
- `AdminAppSaleIndexRequest`: valida filtros del listado y la exportación.
|
- `AdminAppSaleIndexRequest`: valida filtros del listado y la exportación de ventas.
|
||||||
|
- `AdminAppSaleModificationIndexRequest`: valida los filtros compartidos por el historial y sus exportaciones.
|
||||||
- `SaleResource` y `SaleModificationResource`: representan ventas e historial para AdminApp.
|
- `SaleResource` y `SaleModificationResource`: representan ventas e historial para AdminApp.
|
||||||
- `SaleController`: entrada HTTP del panel.
|
- `SaleController`: entrada HTTP del panel.
|
||||||
|
|
||||||
@@ -27,3 +28,5 @@ Consume compras de `Purchase`, datos del tenant y entradas de `Logging`. No es d
|
|||||||
## Consideraciones
|
## Consideraciones
|
||||||
|
|
||||||
La consulta paginada y la colección de exportación deben aplicar los mismos filtros para evitar diferencias entre pantalla, PDF y Excel.
|
La consulta paginada y la colección de exportación deben aplicar los mismos filtros para evitar diferencias entre pantalla, PDF y Excel.
|
||||||
|
|
||||||
|
El historial comparte con ventas los filtros de búsqueda, ID, fecha de venta y estado. En el historial, el estado se evalúa sobre `ValueChange.new_value`: representa el resultado de esa modificación y no el estado actual de la venta.
|
||||||
|
|||||||
53
app/Domains/Ticket/Controllers/AdminApp/TicketController.php
Normal file
53
app/Domains/Ticket/Controllers/AdminApp/TicketController.php
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Ticket\Controllers\AdminApp;
|
||||||
|
|
||||||
|
use App\Domains\Ticket\Requests\AdminAppTicketExportRequest;
|
||||||
|
use App\Domains\Ticket\Requests\AdminAppTicketIndexRequest;
|
||||||
|
use App\Domains\Ticket\Resources\AdminApp\AdminAppTicketCollection;
|
||||||
|
use App\Domains\Ticket\Services\AdminAppTicketExcelService;
|
||||||
|
use App\Domains\Ticket\Services\AdminAppTicketPdfService;
|
||||||
|
use App\Domains\Ticket\Services\AdminAppTicketService;
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
use Illuminate\Http\Response;
|
||||||
|
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||||
|
|
||||||
|
class TicketController extends Controller
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly AdminAppTicketService $ticketService,
|
||||||
|
private readonly AdminAppTicketPdfService $ticketPdfService,
|
||||||
|
private readonly AdminAppTicketExcelService $ticketExcelService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function index(AdminAppTicketIndexRequest $request): AdminAppTicketCollection
|
||||||
|
{
|
||||||
|
$tenant = $request->user()->tenant()->firstOrFail();
|
||||||
|
|
||||||
|
return new AdminAppTicketCollection(
|
||||||
|
$this->ticketService->search($tenant, $request->validated())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function downloadPdf(AdminAppTicketExportRequest $request): Response
|
||||||
|
{
|
||||||
|
$tenant = $request->user()->tenant()->firstOrFail();
|
||||||
|
|
||||||
|
return $this->ticketPdfService->download(
|
||||||
|
$tenant,
|
||||||
|
$this->ticketService->ticketsForExport($tenant, $request->validated()),
|
||||||
|
$request->validated('timezone'),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function downloadExcel(AdminAppTicketExportRequest $request): StreamedResponse
|
||||||
|
{
|
||||||
|
$tenant = $request->user()->tenant()->firstOrFail();
|
||||||
|
|
||||||
|
return $this->ticketExcelService->download(
|
||||||
|
$tenant,
|
||||||
|
$this->ticketService->ticketsForExport($tenant, $request->validated()),
|
||||||
|
$request->validated('timezone'),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -42,7 +42,7 @@ class GenerateTicketsForPaidPurchase
|
|||||||
$user,
|
$user,
|
||||||
$purchaseItem->cantidad,
|
$purchaseItem->cantidad,
|
||||||
$purchaseItem->source_variant_id,
|
$purchaseItem->source_variant_id,
|
||||||
$purchase->getKey(),
|
$purchaseItem->getKey(),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ namespace App\Domains\Ticket\Models;
|
|||||||
use App\Domains\Auth\Models\User;
|
use App\Domains\Auth\Models\User;
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Catalog\Models\CatalogItem;
|
||||||
use App\Domains\Catalog\Models\Variant;
|
use App\Domains\Catalog\Models\Variant;
|
||||||
use App\Domains\Purchase\Models\Purchase;
|
use App\Domains\Purchase\Models\PurchaseItem;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
use App\Domains\Ticket\Services\ResolvedTicketValidity;
|
use App\Domains\Ticket\Services\ResolvedTicketValidity;
|
||||||
use App\Domains\Ticket\Services\ResolvedValidityGroup;
|
use App\Domains\Ticket\Services\ResolvedValidityGroup;
|
||||||
@@ -21,7 +21,7 @@ use Illuminate\Support\Collection;
|
|||||||
#[Fillable([
|
#[Fillable([
|
||||||
'tenant_code',
|
'tenant_code',
|
||||||
'ticket',
|
'ticket',
|
||||||
'source_purchase_id',
|
'source_purchase_item_id',
|
||||||
'source_catalog_item_id',
|
'source_catalog_item_id',
|
||||||
'source_variant_id',
|
'source_variant_id',
|
||||||
'used_at',
|
'used_at',
|
||||||
@@ -56,7 +56,7 @@ class Ticket extends Model
|
|||||||
return [
|
return [
|
||||||
'source_catalog_item_id' => 'integer',
|
'source_catalog_item_id' => 'integer',
|
||||||
'source_variant_id' => 'integer',
|
'source_variant_id' => 'integer',
|
||||||
'source_purchase_id' => 'integer',
|
'source_purchase_item_id' => 'integer',
|
||||||
'used_at' => 'datetime',
|
'used_at' => 'datetime',
|
||||||
'scanner_user_id' => 'integer',
|
'scanner_user_id' => 'integer',
|
||||||
'user_id' => 'integer',
|
'user_id' => 'integer',
|
||||||
@@ -81,10 +81,10 @@ class Ticket extends Model
|
|||||||
return $this->belongsTo(User::class, 'scanner_user_id');
|
return $this->belongsTo(User::class, 'scanner_user_id');
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return BelongsTo<Purchase, $this> */
|
/** @return BelongsTo<PurchaseItem, $this> */
|
||||||
public function sourcePurchase(): BelongsTo
|
public function sourcePurchaseItem(): BelongsTo
|
||||||
{
|
{
|
||||||
return $this->belongsTo(Purchase::class, 'source_purchase_id');
|
return $this->belongsTo(PurchaseItem::class, 'source_purchase_item_id');
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return BelongsTo<CatalogItem, $this> */
|
/** @return BelongsTo<CatalogItem, $this> */
|
||||||
|
|||||||
17
app/Domains/Ticket/Requests/AdminAppTicketExportRequest.php
Normal file
17
app/Domains/Ticket/Requests/AdminAppTicketExportRequest.php
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Ticket\Requests;
|
||||||
|
|
||||||
|
use App\Domains\Shared\Rules\ValidTimezone;
|
||||||
|
|
||||||
|
class AdminAppTicketExportRequest extends AdminAppTicketIndexRequest
|
||||||
|
{
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
public function rules(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
...parent::rules(),
|
||||||
|
'timezone' => ['required', 'string', new ValidTimezone],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
47
app/Domains/Ticket/Requests/AdminAppTicketIndexRequest.php
Normal file
47
app/Domains/Ticket/Requests/AdminAppTicketIndexRequest.php
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Ticket\Requests;
|
||||||
|
|
||||||
|
use App\Domains\Ticket\Models\Ticket;
|
||||||
|
use App\Domains\Ticket\Services\AdminAppTicketColumnService;
|
||||||
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
|
|
||||||
|
class AdminAppTicketIndexRequest extends FormRequest
|
||||||
|
{
|
||||||
|
public function authorize(): bool
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string, list<string>> */
|
||||||
|
public function rules(): array
|
||||||
|
{
|
||||||
|
$tenant = $this->user()?->tenant()->first();
|
||||||
|
$sortableKeys = $tenant === null
|
||||||
|
? []
|
||||||
|
: app(AdminAppTicketColumnService::class)->sortableKeys($tenant);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'q' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||||
|
'category' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||||
|
'product' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||||
|
'type' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||||
|
'date' => ['sometimes', 'nullable', 'date_format:Y-m-d'],
|
||||||
|
'size' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||||
|
'status' => [
|
||||||
|
'sometimes',
|
||||||
|
'nullable',
|
||||||
|
Rule::in([
|
||||||
|
Ticket::STATUS_ACTIVE,
|
||||||
|
Ticket::STATUS_USED,
|
||||||
|
Ticket::STATUS_EXPIRED,
|
||||||
|
]),
|
||||||
|
],
|
||||||
|
'page' => ['sometimes', 'integer', 'min:1'],
|
||||||
|
'per_page' => ['sometimes', 'integer', 'min:1', 'max:100'],
|
||||||
|
'sort_by' => ['sometimes', 'nullable', 'string', Rule::in($sortableKeys)],
|
||||||
|
'sort_direction' => ['sometimes', 'nullable', 'string', Rule::in(['asc', 'desc'])],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Ticket\Resources\AdminApp;
|
||||||
|
|
||||||
|
use App\Domains\Ticket\Services\AdminAppTicketResult;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\Resources\Json\ResourceCollection;
|
||||||
|
|
||||||
|
class AdminAppTicketCollection extends ResourceCollection
|
||||||
|
{
|
||||||
|
/** @var class-string<AdminAppTicketResource> */
|
||||||
|
public $collects = AdminAppTicketResource::class;
|
||||||
|
|
||||||
|
private readonly int $scannedTickets;
|
||||||
|
|
||||||
|
private readonly int $totalTickets;
|
||||||
|
|
||||||
|
public function __construct(AdminAppTicketResult $result)
|
||||||
|
{
|
||||||
|
parent::__construct($result->tickets);
|
||||||
|
|
||||||
|
$this->scannedTickets = $result->scannedTickets;
|
||||||
|
$this->totalTickets = $result->totalTickets;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array{scanned_tickets: int, total_tickets: int} */
|
||||||
|
public function with(Request $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'scanned_tickets' => $this->scannedTickets,
|
||||||
|
'total_tickets' => $this->totalTickets,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Ticket\Resources\AdminApp;
|
||||||
|
|
||||||
|
use App\Domains\Ticket\Models\Ticket;
|
||||||
|
use App\Domains\Ticket\Resources\TicketResource;
|
||||||
|
use App\Domains\Ticket\Services\AdminAppTicketRowService;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
|
||||||
|
/** @mixin Ticket */
|
||||||
|
class AdminAppTicketResource extends TicketResource
|
||||||
|
{
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
public function toArray(Request $request): array
|
||||||
|
{
|
||||||
|
$rowService = app(AdminAppTicketRowService::class);
|
||||||
|
$details = $rowService->details($this->resource);
|
||||||
|
|
||||||
|
return [
|
||||||
|
...parent::toArray($request),
|
||||||
|
...$details,
|
||||||
|
'values' => $rowService->values($this->resource, $details),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
103
app/Domains/Ticket/Services/AdminAppTicketColumnService.php
Normal file
103
app/Domains/Ticket/Services/AdminAppTicketColumnService.php
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Ticket\Services;
|
||||||
|
|
||||||
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
|
|
||||||
|
class AdminAppTicketColumnService
|
||||||
|
{
|
||||||
|
private const FIESTA_FUTBOL_INFANTIL = 'fiesta_futbol_infantil';
|
||||||
|
|
||||||
|
/** @return list<array{key: string, label: string, type: string, sortable: bool, sort_param: string, width: string, excel_width: int}> */
|
||||||
|
public function columns(Tenant $tenant): array
|
||||||
|
{
|
||||||
|
$keys = $tenant->codigo === self::FIESTA_FUTBOL_INFANTIL
|
||||||
|
? ['order_number', 'category', 'product', 'type', 'date', 'size', 'amount', 'client', 'id', 'status', 'scanned_by']
|
||||||
|
: ['order_number', 'product', 'amount', 'client', 'id', 'status', 'scanned_by'];
|
||||||
|
|
||||||
|
$columns = array_map(fn (string $key): array => $this->definitions()[$key], $keys);
|
||||||
|
|
||||||
|
if ($tenant->codigo === self::FIESTA_FUTBOL_INFANTIL) {
|
||||||
|
$columns = array_map(function (array $column): array {
|
||||||
|
if (in_array($column['key'], ['product', 'type', 'date', 'size'], true)) {
|
||||||
|
$column['sortable'] = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $column;
|
||||||
|
}, $columns);
|
||||||
|
} else {
|
||||||
|
$widths = [
|
||||||
|
'order_number' => '11%',
|
||||||
|
'product' => '15%',
|
||||||
|
'amount' => '10%',
|
||||||
|
'client' => '15%',
|
||||||
|
'id' => '8%',
|
||||||
|
'status' => '8%',
|
||||||
|
'scanned_by' => '11%',
|
||||||
|
];
|
||||||
|
$columns = array_map(function (array $column) use ($widths): array {
|
||||||
|
$column['width'] = $widths[$column['key']];
|
||||||
|
|
||||||
|
return $column;
|
||||||
|
}, $columns);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $columns;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return list<array{key: string, label: string, type: string, sortable: bool, sort_param: string, width: string}> */
|
||||||
|
public function publicColumns(Tenant $tenant): array
|
||||||
|
{
|
||||||
|
return array_map(function (array $column): array {
|
||||||
|
unset($column['excel_width']);
|
||||||
|
|
||||||
|
return $column;
|
||||||
|
}, $this->columns($tenant));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return list<string> */
|
||||||
|
public function sortableKeys(Tenant $tenant): array
|
||||||
|
{
|
||||||
|
return array_values(array_map(
|
||||||
|
fn (array $column): string => $column['sort_param'],
|
||||||
|
array_filter($this->columns($tenant), fn (array $column): bool => $column['sortable']),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string, array{key: string, label: string, type: string, sortable: bool, sort_param: string, width: string, excel_width: int}> */
|
||||||
|
private function definitions(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'order_number' => $this->column('order_number', 'N° de orden', 'order_number', '10.5%', 14),
|
||||||
|
'category' => $this->column('category', 'Categoría', 'text', '11%', 18),
|
||||||
|
'product' => $this->column('product', 'Producto', 'text', '11%', 22),
|
||||||
|
'type' => $this->column('type', 'Tipo', 'text', '8%', 18),
|
||||||
|
'date' => $this->column('date', 'Fecha', 'text', '7%', 14),
|
||||||
|
'size' => $this->column('size', 'Talle', 'text', '6%', 12),
|
||||||
|
'amount' => $this->column('amount', 'Importe', 'currency', '8%', 15),
|
||||||
|
'client' => $this->column('client', 'Cliente', 'text', '11%', 30),
|
||||||
|
'id' => $this->column('id', 'ID', 'text', '6%', 12),
|
||||||
|
'status' => $this->column('status', 'Estado', 'status', '7%', 13),
|
||||||
|
'scanned_by' => $this->column('scanned_by', 'Escaneado por', 'text', '8%', 28),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array{key: string, label: string, type: string, sortable: bool, sort_param: string, width: string, excel_width: int} */
|
||||||
|
private function column(
|
||||||
|
string $key,
|
||||||
|
string $label,
|
||||||
|
string $type,
|
||||||
|
string $width,
|
||||||
|
int $excelWidth,
|
||||||
|
): array {
|
||||||
|
return [
|
||||||
|
'key' => $key,
|
||||||
|
'label' => $label,
|
||||||
|
'type' => $type,
|
||||||
|
'sortable' => true,
|
||||||
|
'sort_param' => $key,
|
||||||
|
'width' => $width,
|
||||||
|
'excel_width' => $excelWidth,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
105
app/Domains/Ticket/Services/AdminAppTicketExcelService.php
Normal file
105
app/Domains/Ticket/Services/AdminAppTicketExcelService.php
Normal file
@@ -0,0 +1,105 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Ticket\Services;
|
||||||
|
|
||||||
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
|
use App\Domains\Ticket\Models\Ticket;
|
||||||
|
use Carbon\CarbonInterface;
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
|
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
|
||||||
|
use PhpOffice\PhpSpreadsheet\Cell\DataType;
|
||||||
|
use PhpOffice\PhpSpreadsheet\Shared\Date;
|
||||||
|
use PhpOffice\PhpSpreadsheet\Spreadsheet;
|
||||||
|
use PhpOffice\PhpSpreadsheet\Style\Alignment;
|
||||||
|
use PhpOffice\PhpSpreadsheet\Style\Fill;
|
||||||
|
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
|
||||||
|
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||||
|
|
||||||
|
class AdminAppTicketExcelService
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly AdminAppTicketReportService $reportService,
|
||||||
|
private readonly AdminAppTicketColumnService $columnService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/** @param Collection<int, Ticket> $tickets */
|
||||||
|
public function download(Tenant $tenant, Collection $tickets, string $timeZone): StreamedResponse
|
||||||
|
{
|
||||||
|
$generatedAt = now();
|
||||||
|
$rows = $this->reportService->rows($tickets);
|
||||||
|
$columns = $this->columnService->columns($tenant);
|
||||||
|
$spreadsheet = new Spreadsheet;
|
||||||
|
$spreadsheet->getProperties()
|
||||||
|
->setCreator('Shopit')
|
||||||
|
->setTitle('Listado de tickets')
|
||||||
|
->setSubject($tenant->nombre);
|
||||||
|
$sheet = $spreadsheet->getActiveSheet();
|
||||||
|
$sheet->setTitle('Tickets');
|
||||||
|
$sheet->fromArray([array_column($columns, 'label')], null, 'A1');
|
||||||
|
|
||||||
|
foreach ($rows as $index => $ticket) {
|
||||||
|
$row = $index + 2;
|
||||||
|
foreach ($columns as $columnIndex => $column) {
|
||||||
|
$coordinate = Coordinate::stringFromColumnIndex($columnIndex + 1).$row;
|
||||||
|
$value = $ticket[$column['key']] ?? null;
|
||||||
|
|
||||||
|
if ($column['type'] === 'currency' && $value !== null) {
|
||||||
|
$sheet->setCellValue($coordinate, (float) $value);
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($column['type'] === 'date' && $value instanceof CarbonInterface) {
|
||||||
|
$sheet->setCellValue(
|
||||||
|
$coordinate,
|
||||||
|
Date::dateTimeToExcel($value->copy()->timezone($timeZone)),
|
||||||
|
);
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$sheet->setCellValueExplicit(
|
||||||
|
$coordinate,
|
||||||
|
$this->reportService->displayValue($value, $column['type'], $timeZone),
|
||||||
|
DataType::TYPE_STRING,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$lastRow = max(2, $rows->count() + 1);
|
||||||
|
$lastColumn = Coordinate::stringFromColumnIndex(count($columns));
|
||||||
|
foreach ($columns as $columnIndex => $column) {
|
||||||
|
$letter = Coordinate::stringFromColumnIndex($columnIndex + 1);
|
||||||
|
if ($column['type'] === 'currency') {
|
||||||
|
$sheet->getStyle("{$letter}2:{$letter}{$lastRow}")
|
||||||
|
->getNumberFormat()->setFormatCode('$ #,##0.00');
|
||||||
|
}
|
||||||
|
if ($column['type'] === 'date') {
|
||||||
|
$sheet->getStyle("{$letter}2:{$letter}{$lastRow}")
|
||||||
|
->getNumberFormat()->setFormatCode('dd/mm/yyyy hh:mm');
|
||||||
|
}
|
||||||
|
$sheet->getColumnDimension($letter)->setWidth($column['excel_width']);
|
||||||
|
}
|
||||||
|
$sheet->getStyle("A1:{$lastColumn}1")->applyFromArray([
|
||||||
|
'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
|
||||||
|
'fill' => [
|
||||||
|
'fillType' => Fill::FILL_SOLID,
|
||||||
|
'startColor' => ['rgb' => '26382E'],
|
||||||
|
],
|
||||||
|
'alignment' => ['vertical' => Alignment::VERTICAL_CENTER],
|
||||||
|
]);
|
||||||
|
$sheet->getRowDimension(1)->setRowHeight(24);
|
||||||
|
$sheet->freezePane('A2');
|
||||||
|
$sheet->setAutoFilter("A1:{$lastColumn}{$lastRow}");
|
||||||
|
|
||||||
|
$filename = 'tickets_'.$tenant->codigo.'_'
|
||||||
|
.$generatedAt->copy()->timezone($timeZone)->format('Ymd_His').'.xlsx';
|
||||||
|
|
||||||
|
return response()->streamDownload(function () use ($spreadsheet): void {
|
||||||
|
(new Xlsx($spreadsheet))->save('php://output');
|
||||||
|
$spreadsheet->disconnectWorksheets();
|
||||||
|
}, $filename, [
|
||||||
|
'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
56
app/Domains/Ticket/Services/AdminAppTicketPdfService.php
Normal file
56
app/Domains/Ticket/Services/AdminAppTicketPdfService.php
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Ticket\Services;
|
||||||
|
|
||||||
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
|
use App\Domains\Ticket\Models\Ticket;
|
||||||
|
use Barryvdh\DomPDF\Facade\Pdf;
|
||||||
|
use Barryvdh\DomPDF\PDF as DomPdf;
|
||||||
|
use Illuminate\Http\Response;
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
|
|
||||||
|
class AdminAppTicketPdfService
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly AdminAppTicketReportService $reportService,
|
||||||
|
private readonly AdminAppTicketColumnService $columnService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/** @param Collection<int, Ticket> $tickets */
|
||||||
|
public function download(Tenant $tenant, Collection $tickets, string $timeZone): Response
|
||||||
|
{
|
||||||
|
$generatedAt = now();
|
||||||
|
$columns = $this->columnService->columns($tenant);
|
||||||
|
$rows = $this->reportService->rows($tickets);
|
||||||
|
$pdf = Pdf::loadView('pdf.adminapp.tickets', [
|
||||||
|
'tenant' => $tenant,
|
||||||
|
'columns' => $columns,
|
||||||
|
'tickets' => $this->reportService->displayRows($rows, $columns, $timeZone),
|
||||||
|
'generatedAt' => $generatedAt,
|
||||||
|
'timeZone' => $timeZone,
|
||||||
|
])->setPaper('a3', 'landscape');
|
||||||
|
|
||||||
|
$this->addPageNumbers($pdf);
|
||||||
|
|
||||||
|
return $pdf->download(
|
||||||
|
'tickets_'.$tenant->codigo.'_'
|
||||||
|
.$generatedAt->copy()->timezone($timeZone)->format('Ymd_His').'.pdf'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function addPageNumbers(DomPdf $pdf): void
|
||||||
|
{
|
||||||
|
$pdf->render();
|
||||||
|
$domPdf = $pdf->getDomPDF();
|
||||||
|
$font = $domPdf->getFontMetrics()->getFont('DejaVu Sans');
|
||||||
|
|
||||||
|
$domPdf->getCanvas()->page_text(
|
||||||
|
565,
|
||||||
|
805,
|
||||||
|
'Página {PAGE_NUM} de {PAGE_COUNT}',
|
||||||
|
$font,
|
||||||
|
7,
|
||||||
|
[0.48, 0.52, 0.49],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
35
app/Domains/Ticket/Services/AdminAppTicketReportService.php
Normal file
35
app/Domains/Ticket/Services/AdminAppTicketReportService.php
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Ticket\Services;
|
||||||
|
|
||||||
|
use App\Domains\Ticket\Models\Ticket;
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
|
|
||||||
|
class AdminAppTicketReportService
|
||||||
|
{
|
||||||
|
public function __construct(private readonly AdminAppTicketRowService $rowService) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param Collection<int, Ticket> $tickets
|
||||||
|
* @return Collection<int, array<string, mixed>>
|
||||||
|
*/
|
||||||
|
public function rows(Collection $tickets): Collection
|
||||||
|
{
|
||||||
|
return $this->rowService->rows($tickets);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param Collection<int, array<string, mixed>> $rows
|
||||||
|
* @param list<array<string, mixed>> $columns
|
||||||
|
* @return Collection<int, array<string, string>>
|
||||||
|
*/
|
||||||
|
public function displayRows(Collection $rows, array $columns, string $timeZone): Collection
|
||||||
|
{
|
||||||
|
return $this->rowService->displayRows($rows, $columns, $timeZone);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function displayValue(mixed $value, string $type, string $timeZone): string
|
||||||
|
{
|
||||||
|
return $this->rowService->displayValue($value, $type, $timeZone);
|
||||||
|
}
|
||||||
|
}
|
||||||
16
app/Domains/Ticket/Services/AdminAppTicketResult.php
Normal file
16
app/Domains/Ticket/Services/AdminAppTicketResult.php
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Ticket\Services;
|
||||||
|
|
||||||
|
use App\Domains\Ticket\Models\Ticket;
|
||||||
|
use Illuminate\Pagination\LengthAwarePaginator;
|
||||||
|
|
||||||
|
final readonly class AdminAppTicketResult
|
||||||
|
{
|
||||||
|
/** @param LengthAwarePaginator<Ticket> $tickets */
|
||||||
|
public function __construct(
|
||||||
|
public LengthAwarePaginator $tickets,
|
||||||
|
public int $scannedTickets,
|
||||||
|
public int $totalTickets,
|
||||||
|
) {}
|
||||||
|
}
|
||||||
210
app/Domains/Ticket/Services/AdminAppTicketRowService.php
Normal file
210
app/Domains/Ticket/Services/AdminAppTicketRowService.php
Normal file
@@ -0,0 +1,210 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Ticket\Services;
|
||||||
|
|
||||||
|
use App\Domains\Catalog\Models\ItemAttribute;
|
||||||
|
use App\Domains\Ticket\Models\Ticket;
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
|
|
||||||
|
class AdminAppTicketRowService
|
||||||
|
{
|
||||||
|
private const FIESTA_FUTBOL_INFANTIL = 'fiesta_futbol_infantil';
|
||||||
|
|
||||||
|
private const CATEGORY_PRESENTATIONS = [
|
||||||
|
'alojamientos' => ['category' => 'Camping', 'product' => 'tipo_alojamiento', 'type' => null, 'date' => null, 'size' => null],
|
||||||
|
'camping' => ['category' => null, 'product' => 'tipo_alojamiento', 'type' => null, 'date' => null, 'size' => null],
|
||||||
|
'entradas' => ['category' => null, 'product' => 'product', 'type' => null, 'date' => null, 'size' => null],
|
||||||
|
'comidas' => ['category' => 'Comida', 'product' => 'horario', 'type' => 'servicio', 'date' => 'event_date', 'size' => null],
|
||||||
|
'comida' => ['category' => null, 'product' => 'horario', 'type' => 'servicio', 'date' => 'event_date', 'size' => null],
|
||||||
|
'merchandising' => ['category' => null, 'product' => 'product', 'type' => 'color', 'date' => null, 'size' => 'talle'],
|
||||||
|
];
|
||||||
|
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
public function details(Ticket $ticket): array
|
||||||
|
{
|
||||||
|
$purchaseItem = $ticket->sourcePurchaseItem;
|
||||||
|
|
||||||
|
return [
|
||||||
|
'source_purchase_item_id' => $ticket->source_purchase_item_id,
|
||||||
|
'order_number' => $purchaseItem?->compra_id,
|
||||||
|
'product' => $purchaseItem?->item_nombre
|
||||||
|
?? $ticket->sourceCatalogItem?->nombre
|
||||||
|
?? $ticket->name,
|
||||||
|
'amount' => $purchaseItem?->precio_unitario,
|
||||||
|
'client' => $purchaseItem?->purchase?->nombre_apellido ?? $ticket->user?->nombre_apellido,
|
||||||
|
'status' => $ticket->status,
|
||||||
|
'scanned_by' => $ticket->scannerUser?->nombre_apellido,
|
||||||
|
'variant_properties' => $this->variantProperties($ticket),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string, mixed>|null $details */
|
||||||
|
public function values(Ticket $ticket, ?array $details = null): array
|
||||||
|
{
|
||||||
|
$details ??= $this->details($ticket);
|
||||||
|
$presentation = $this->presentation($ticket, $details);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'order_number' => $details['order_number'],
|
||||||
|
'category' => $presentation['category'],
|
||||||
|
'product' => $presentation['product'],
|
||||||
|
'type' => $presentation['type'],
|
||||||
|
'date' => $presentation['date'],
|
||||||
|
'size' => $presentation['size'],
|
||||||
|
'amount' => $details['amount'] === null ? null : (float) $details['amount'],
|
||||||
|
'client' => $details['client'] ?? 'Sin nombre',
|
||||||
|
'id' => $ticket->id,
|
||||||
|
'status' => $details['status'],
|
||||||
|
'scanned_by' => $details['scanned_by'] ?? '-',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param Collection<int, Ticket> $tickets
|
||||||
|
* @return Collection<int, array<string, mixed>>
|
||||||
|
*/
|
||||||
|
public function rows(Collection $tickets): Collection
|
||||||
|
{
|
||||||
|
return $tickets->values()->map(fn (Ticket $ticket): array => $this->values($ticket));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param Collection<int, array<string, mixed>> $rows
|
||||||
|
* @param list<array<string, mixed>> $columns
|
||||||
|
* @return Collection<int, array<string, string>>
|
||||||
|
*/
|
||||||
|
public function displayRows(Collection $rows, array $columns, string $timeZone): Collection
|
||||||
|
{
|
||||||
|
return $rows->map(fn (array $row): array => collect($columns)
|
||||||
|
->mapWithKeys(fn (array $column): array => [
|
||||||
|
$column['key'] => $this->displayValue(
|
||||||
|
$row[$column['key']] ?? null,
|
||||||
|
$column['type'],
|
||||||
|
$timeZone,
|
||||||
|
),
|
||||||
|
])
|
||||||
|
->all());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function displayValue(mixed $value, string $type, string $timeZone): string
|
||||||
|
{
|
||||||
|
if ($value === null || $value === '') {
|
||||||
|
return '-';
|
||||||
|
}
|
||||||
|
|
||||||
|
return match ($type) {
|
||||||
|
'order_number' => '#'.$value,
|
||||||
|
'currency' => '$'.number_format((float) $value, 2, ',', '.'),
|
||||||
|
'status' => match ((string) $value) {
|
||||||
|
Ticket::STATUS_USED => 'Usado',
|
||||||
|
Ticket::STATUS_EXPIRED => 'Vencido',
|
||||||
|
default => 'Activo',
|
||||||
|
},
|
||||||
|
default => (string) $value,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string, mixed> $details */
|
||||||
|
private function presentation(Ticket $ticket, array $details): array
|
||||||
|
{
|
||||||
|
$sourceCategory = trim((string) ($ticket->sourceCatalogItem?->category?->nombre ?? '')) ?: '-';
|
||||||
|
|
||||||
|
if ($ticket->tenant_code !== self::FIESTA_FUTBOL_INFANTIL) {
|
||||||
|
return [
|
||||||
|
'category' => $sourceCategory,
|
||||||
|
'product' => (string) ($details['product'] ?: $ticket->name ?: '-'),
|
||||||
|
'type' => $this->allPropertyLabels($details) ?: '-',
|
||||||
|
'date' => '-',
|
||||||
|
'size' => '-',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
$configuration = self::CATEGORY_PRESENTATIONS[mb_strtolower($sourceCategory)] ?? null;
|
||||||
|
if ($configuration === null) {
|
||||||
|
return [
|
||||||
|
'category' => $sourceCategory,
|
||||||
|
'product' => (string) ($details['product'] ?: $ticket->name ?: '-'),
|
||||||
|
'type' => $this->allPropertyLabels($details) ?: '-',
|
||||||
|
'date' => '-',
|
||||||
|
'size' => '-',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'category' => $configuration['category'] ?? $sourceCategory,
|
||||||
|
'product' => $configuration['product'] === 'product'
|
||||||
|
? (string) ($details['product'] ?: $ticket->name ?: '-')
|
||||||
|
: ($this->propertyLabels($details, $configuration['product']) ?: '-'),
|
||||||
|
'type' => $configuration['type'] === null
|
||||||
|
? '-'
|
||||||
|
: ($this->propertyLabels($details, $configuration['type']) ?: '-'),
|
||||||
|
'date' => $configuration['date'] === null
|
||||||
|
? '-'
|
||||||
|
: ($this->propertyLabels($details, $configuration['date']) ?: '-'),
|
||||||
|
'size' => $configuration['size'] === null
|
||||||
|
? '-'
|
||||||
|
: ($this->propertyLabels($details, $configuration['size']) ?: '-'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string, mixed> $details */
|
||||||
|
private function propertyLabels(array $details, string $code): string
|
||||||
|
{
|
||||||
|
$property = collect($details['variant_properties'] ?? [])->firstWhere('code', $code);
|
||||||
|
$labels = collect($property['values'] ?? [])->pluck('label')->filter();
|
||||||
|
|
||||||
|
if ($code === 'event_date') {
|
||||||
|
$labels = $labels->map(function (string $label): string {
|
||||||
|
[$day, $month] = array_pad(explode('/', $label), 2, null);
|
||||||
|
|
||||||
|
return $day !== null && $month !== null ? "{$day}/{$month}" : $label;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return $labels->implode(', ');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string, mixed> $details */
|
||||||
|
private function allPropertyLabels(array $details): string
|
||||||
|
{
|
||||||
|
return collect($details['variant_properties'] ?? [])
|
||||||
|
->flatMap(fn (array $property): array => $property['values'] ?? [])
|
||||||
|
->pluck('label')
|
||||||
|
->filter()
|
||||||
|
->implode(', ');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return list<array{code: string, label: string, values: list<array{value: string, label: string}>}> */
|
||||||
|
private function variantProperties(Ticket $ticket): array
|
||||||
|
{
|
||||||
|
$variant = $ticket->sourceVariant;
|
||||||
|
if ($variant === null) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
$itemAttributes = $variant->definitions
|
||||||
|
->map(fn ($definition) => $definition->itemAttribute)
|
||||||
|
->filter()
|
||||||
|
->merge($variant->catalogItem?->itemAttributes ?? collect())
|
||||||
|
->unique('id')
|
||||||
|
->values();
|
||||||
|
|
||||||
|
return $variant->selectionOptions($itemAttributes)
|
||||||
|
->map(function (array $selection, string $attributeCode) use ($itemAttributes): array {
|
||||||
|
$itemAttribute = $itemAttributes->first(
|
||||||
|
fn (ItemAttribute $itemAttribute): bool => $itemAttribute->attribute?->codigo
|
||||||
|
=== $attributeCode,
|
||||||
|
);
|
||||||
|
$values = array_is_list($selection) ? $selection : [$selection];
|
||||||
|
|
||||||
|
return [
|
||||||
|
'code' => $attributeCode,
|
||||||
|
'label' => $itemAttribute?->attribute?->nombre
|
||||||
|
?? ($attributeCode === 'event_date' ? 'Fecha' : $attributeCode),
|
||||||
|
'values' => array_values($values),
|
||||||
|
];
|
||||||
|
})
|
||||||
|
->values()
|
||||||
|
->all();
|
||||||
|
}
|
||||||
|
}
|
||||||
403
app/Domains/Ticket/Services/AdminAppTicketService.php
Normal file
403
app/Domains/Ticket/Services/AdminAppTicketService.php
Normal file
@@ -0,0 +1,403 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Ticket\Services;
|
||||||
|
|
||||||
|
use App\Domains\Auth\Models\User;
|
||||||
|
use App\Domains\Purchase\Models\PurchaseItem;
|
||||||
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
|
use App\Domains\Ticket\Models\Ticket;
|
||||||
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
|
use Illuminate\Pagination\LengthAwarePaginator;
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
|
|
||||||
|
class AdminAppTicketService
|
||||||
|
{
|
||||||
|
private const RELATIONS = [
|
||||||
|
...TicketValidityResolver::RELATIONS,
|
||||||
|
...TicketPresentationResolver::RELATIONS,
|
||||||
|
'user',
|
||||||
|
'scannerUser',
|
||||||
|
'sourceCatalogItem.category',
|
||||||
|
'sourcePurchaseItem.purchase',
|
||||||
|
];
|
||||||
|
|
||||||
|
public function __construct(
|
||||||
|
private readonly AdminAppTicketColumnService $columnService,
|
||||||
|
private readonly AdminAppTicketRowService $rowService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array{q?: string|null, category?: string|null, product?: string|null, type?: string|null, date?: string|null, size?: string|null, status?: string|null, page?: int, per_page?: int, sort_by?: string|null, sort_direction?: string|null} $filters
|
||||||
|
*/
|
||||||
|
public function search(Tenant $tenant, array $filters = []): AdminAppTicketResult
|
||||||
|
{
|
||||||
|
$query = $this->baseQuery($tenant, $filters);
|
||||||
|
$countQuery = clone $query;
|
||||||
|
|
||||||
|
$databaseSorted = $this->applyDatabaseSort($query, $tenant, $filters);
|
||||||
|
|
||||||
|
if (($filters['sort_by'] ?? null) && ! $databaseSorted) {
|
||||||
|
$matchingTickets = (clone $query)
|
||||||
|
->with(self::RELATIONS)
|
||||||
|
->get();
|
||||||
|
$matchingTickets = $this->sortTickets($matchingTickets, $tenant, $filters);
|
||||||
|
$tickets = $this->paginate($matchingTickets, $filters);
|
||||||
|
$scannedTickets = $matchingTickets->whereNotNull('used_at')->count();
|
||||||
|
} else {
|
||||||
|
$tickets = (clone $query)
|
||||||
|
->with(self::RELATIONS)
|
||||||
|
->when(! $databaseSorted, fn (Builder $query): Builder => $query->orderByDesc('id'))
|
||||||
|
->paginateFromRequest()
|
||||||
|
->withQueryString();
|
||||||
|
$scannedTickets = $countQuery->whereNotNull('used_at')->count();
|
||||||
|
}
|
||||||
|
|
||||||
|
return new AdminAppTicketResult(
|
||||||
|
tickets: $tickets,
|
||||||
|
scannedTickets: $scannedTickets,
|
||||||
|
totalTickets: $tickets->total(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array{q?: string|null, category?: string|null, product?: string|null, type?: string|null, date?: string|null, size?: string|null, status?: string|null, sort_by?: string|null, sort_direction?: string|null} $filters
|
||||||
|
* @return Collection<int, Ticket>
|
||||||
|
*/
|
||||||
|
public function ticketsForExport(Tenant $tenant, array $filters = []): Collection
|
||||||
|
{
|
||||||
|
$query = $this->baseQuery($tenant, $filters);
|
||||||
|
$databaseSorted = $this->applyDatabaseSort($query, $tenant, $filters);
|
||||||
|
$tickets = $query
|
||||||
|
->with(self::RELATIONS)
|
||||||
|
->when(! $databaseSorted, fn (Builder $query): Builder => $query->orderByDesc('id'))
|
||||||
|
->get();
|
||||||
|
|
||||||
|
return $databaseSorted ? $tickets : $this->sortTickets($tickets, $tenant, $filters);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array{q?: string|null, category?: string|null, product?: string|null, type?: string|null, date?: string|null, size?: string|null, status?: string|null, page?: int, per_page?: int} $filters
|
||||||
|
* @return Builder<Ticket>
|
||||||
|
*/
|
||||||
|
private function baseQuery(Tenant $tenant, array $filters): Builder
|
||||||
|
{
|
||||||
|
$search = trim((string) ($filters['q'] ?? ''));
|
||||||
|
|
||||||
|
$query = Ticket::query()
|
||||||
|
->where('tenant_code', $tenant->codigo)
|
||||||
|
->when($search !== '', function (Builder $query) use ($search): void {
|
||||||
|
$this->applySearchFilter($query, $search);
|
||||||
|
})
|
||||||
|
->when($filters['category'] ?? null, function (Builder $query, string $category): void {
|
||||||
|
$query->whereHas('sourceCatalogItem.category', fn (Builder $categoryQuery): Builder => $categoryQuery
|
||||||
|
->whereRaw('LOWER(nombre) = ?', [mb_strtolower(trim($category))]));
|
||||||
|
})
|
||||||
|
->when($filters['product'] ?? null, function (Builder $query, string $product) use ($filters): void {
|
||||||
|
$this->applyProductFilter($query, (string) ($filters['category'] ?? ''), $product);
|
||||||
|
})
|
||||||
|
->when($filters['type'] ?? null, function (Builder $query, string $type) use ($filters): void {
|
||||||
|
$this->applyTypeFilter($query, (string) ($filters['category'] ?? ''), $type);
|
||||||
|
})
|
||||||
|
->when($filters['date'] ?? null, function (Builder $query, string $date) use ($tenant): void {
|
||||||
|
if ($tenant->codigo === 'fiesta_futbol_infantil') {
|
||||||
|
$this->applyEventDateFilter($query, $date);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$query->whereHas('sourcePurchaseItem.purchase', fn (Builder $purchaseQuery): Builder => $purchaseQuery
|
||||||
|
->whereDate('created_at', $date));
|
||||||
|
})
|
||||||
|
->when($filters['size'] ?? null, function (Builder $query, string $size) use ($filters): void {
|
||||||
|
$this->applySizeFilter($query, (string) ($filters['category'] ?? ''), $size);
|
||||||
|
});
|
||||||
|
|
||||||
|
$this->applyStatusFilter($query, $filters['status'] ?? null);
|
||||||
|
|
||||||
|
return $query;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param Builder<Ticket> $query */
|
||||||
|
private function applySearchFilter(Builder $query, string $search): void
|
||||||
|
{
|
||||||
|
$containsPattern = '%'.mb_strtolower($search).'%';
|
||||||
|
$amount = $this->searchAmount($search);
|
||||||
|
|
||||||
|
$query->where(function (Builder $searchQuery) use ($search, $containsPattern, $amount): void {
|
||||||
|
$searchQuery
|
||||||
|
->where(function (Builder $clientQuery) use ($containsPattern): void {
|
||||||
|
$clientQuery
|
||||||
|
->whereHas('sourcePurchaseItem.purchase', fn (Builder $purchaseQuery): Builder => $purchaseQuery
|
||||||
|
->whereRaw('LOWER(nombre_apellido) LIKE ?', [$containsPattern]))
|
||||||
|
->orWhere(function (Builder $fallbackClientQuery) use ($containsPattern): void {
|
||||||
|
$fallbackClientQuery
|
||||||
|
->where(function (Builder $missingPurchaseClientQuery): void {
|
||||||
|
$missingPurchaseClientQuery
|
||||||
|
->whereDoesntHave('sourcePurchaseItem.purchase')
|
||||||
|
->orWhereHas('sourcePurchaseItem.purchase', fn (Builder $purchaseQuery): Builder => $purchaseQuery
|
||||||
|
->whereNull('nombre_apellido'));
|
||||||
|
})
|
||||||
|
->whereHas('user', fn (Builder $userQuery): Builder => $userQuery
|
||||||
|
->whereRaw('LOWER(nombre_apellido) LIKE ?', [$containsPattern]));
|
||||||
|
});
|
||||||
|
})
|
||||||
|
->orWhereHas('scannerUser', fn (Builder $scannerQuery): Builder => $scannerQuery
|
||||||
|
->whereRaw('LOWER(nombre_apellido) LIKE ?', [$containsPattern]));
|
||||||
|
|
||||||
|
if (ctype_digit($search)) {
|
||||||
|
$searchQuery
|
||||||
|
->orWhere('tickets.id', (int) $search)
|
||||||
|
->orWhereHas('sourcePurchaseItem', fn (Builder $purchaseItemQuery): Builder => $purchaseItemQuery
|
||||||
|
->where('compra_id', (int) $search));
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($amount !== null) {
|
||||||
|
$searchQuery->orWhereHas('sourcePurchaseItem', fn (Builder $purchaseItemQuery): Builder => $purchaseItemQuery
|
||||||
|
->where('precio_unitario', $amount));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function searchAmount(string $search): ?string
|
||||||
|
{
|
||||||
|
$value = preg_replace('/[\s$]/u', '', trim($search));
|
||||||
|
if ($value === null || $value === '') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (preg_match('/^\d{1,3}(?:\.\d{3})+(?:,\d{1,2})?$/', $value) === 1) {
|
||||||
|
$value = str_replace(['.', ','], ['', '.'], $value);
|
||||||
|
} elseif (preg_match('/^\d{1,3}(?:,\d{3})+(?:\.\d{1,2})?$/', $value) === 1) {
|
||||||
|
$value = str_replace(',', '', $value);
|
||||||
|
} elseif (preg_match('/^\d+(?:[.,]\d{1,2})?$/', $value) === 1) {
|
||||||
|
$value = str_replace(',', '.', $value);
|
||||||
|
} else {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return number_format((float) $value, 2, '.', '');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param Builder<Ticket> $query */
|
||||||
|
private function applyProductFilter(Builder $query, string $category, string $product): void
|
||||||
|
{
|
||||||
|
$category = $this->normalizedCategory($category);
|
||||||
|
|
||||||
|
if (in_array($category, ['alojamientos', 'camping'], true)) {
|
||||||
|
$this->whereVariantDefinition($query, 'tipo_alojamiento', $product);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (in_array($category, ['comidas', 'comida'], true)) {
|
||||||
|
$this->whereVariantDefinition($query, 'horario', $product);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$query->whereHas('sourceCatalogItem', fn (Builder $itemQuery): Builder => $itemQuery
|
||||||
|
->where('slug', $product));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param Builder<Ticket> $query */
|
||||||
|
private function applyTypeFilter(Builder $query, string $category, string $type): void
|
||||||
|
{
|
||||||
|
$attribute = match ($this->normalizedCategory($category)) {
|
||||||
|
'comidas', 'comida' => 'servicio',
|
||||||
|
'merchandising' => 'color',
|
||||||
|
default => null,
|
||||||
|
};
|
||||||
|
|
||||||
|
if ($attribute !== null) {
|
||||||
|
$this->whereVariantDefinition($query, $attribute, $type);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param Builder<Ticket> $query */
|
||||||
|
private function applyEventDateFilter(Builder $query, string $date): void
|
||||||
|
{
|
||||||
|
$query
|
||||||
|
->whereHas('sourceCatalogItem.category', fn (Builder $categoryQuery): Builder => $categoryQuery
|
||||||
|
->whereRaw('LOWER(nombre) IN (?, ?)', ['comidas', 'comida']))
|
||||||
|
->whereHas('sourceVariant', function (Builder $variantQuery) use ($date): void {
|
||||||
|
$variantQuery->where(function (Builder $dateQuery) use ($date): void {
|
||||||
|
$dateQuery
|
||||||
|
->whereHas('eventDate', fn (Builder $eventDateQuery): Builder => $eventDateQuery
|
||||||
|
->whereDate('date', $date))
|
||||||
|
->orWhereHas('eventDates', fn (Builder $eventDateQuery): Builder => $eventDateQuery
|
||||||
|
->whereDate('date', $date));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param Builder<Ticket> $query */
|
||||||
|
private function applySizeFilter(Builder $query, string $category, string $size): void
|
||||||
|
{
|
||||||
|
if ($this->normalizedCategory($category) === 'merchandising') {
|
||||||
|
$this->whereVariantDefinition($query, 'talle', $size);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param Builder<Ticket> $query */
|
||||||
|
private function whereVariantDefinition(Builder $query, string $attribute, string $value): void
|
||||||
|
{
|
||||||
|
$query->whereHas('sourceVariant.definitions', fn (Builder $definitionQuery): Builder => $definitionQuery
|
||||||
|
->where('value', $value)
|
||||||
|
->whereHas('itemAttribute.attribute', fn (Builder $attributeQuery): Builder => $attributeQuery
|
||||||
|
->where('codigo', $attribute)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param Builder<Ticket> $query */
|
||||||
|
private function applyStatusFilter(Builder $query, ?string $status): void
|
||||||
|
{
|
||||||
|
if ($status === null || $status === '') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($status === Ticket::STATUS_USED) {
|
||||||
|
$query->whereNotNull('used_at');
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$matchingIds = (clone $query)
|
||||||
|
->whereNull('used_at')
|
||||||
|
->with(TicketValidityResolver::RELATIONS)
|
||||||
|
->get()
|
||||||
|
->filter(fn (Ticket $ticket): bool => $ticket->status === $status)
|
||||||
|
->pluck('id');
|
||||||
|
|
||||||
|
$query->whereIn('tickets.id', $matchingIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function normalizedCategory(string $category): string
|
||||||
|
{
|
||||||
|
return mb_strtolower(trim($category));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param Builder<Ticket> $query
|
||||||
|
* @param array{sort_by?: string|null, sort_direction?: string|null} $filters
|
||||||
|
*/
|
||||||
|
private function applyDatabaseSort(Builder $query, Tenant $tenant, array $filters): bool
|
||||||
|
{
|
||||||
|
$sortBy = (string) ($filters['sort_by'] ?? '');
|
||||||
|
if ($sortBy === '') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$direction = ($filters['sort_direction'] ?? 'asc') === 'desc' ? 'desc' : 'asc';
|
||||||
|
|
||||||
|
$sortExpression = match ($sortBy) {
|
||||||
|
'order_number' => $this->purchaseItemColumnQuery('compra_id'),
|
||||||
|
'id' => 'tickets.id',
|
||||||
|
'amount' => $this->purchaseItemColumnQuery('precio_unitario'),
|
||||||
|
'scanned_by' => User::query()
|
||||||
|
->select('nombre_apellido')
|
||||||
|
->whereColumn('users.id', 'tickets.scanner_user_id'),
|
||||||
|
'product' => $tenant->codigo === 'fiesta_futbol_infantil'
|
||||||
|
? null
|
||||||
|
: $this->purchaseItemColumnQuery('item_nombre'),
|
||||||
|
default => null,
|
||||||
|
};
|
||||||
|
|
||||||
|
if ($sortExpression === null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$query->orderBy($sortExpression, $direction)->orderByDesc('tickets.id');
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return Builder<PurchaseItem> */
|
||||||
|
private function purchaseItemColumnQuery(string $column): Builder
|
||||||
|
{
|
||||||
|
return PurchaseItem::query()
|
||||||
|
->select($column)
|
||||||
|
->whereColumn('compra_items.id', 'tickets.source_purchase_item_id')
|
||||||
|
->limit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param Collection<int, Ticket> $tickets
|
||||||
|
* @param array{sort_by?: string|null, sort_direction?: string|null} $filters
|
||||||
|
* @return Collection<int, Ticket>
|
||||||
|
*/
|
||||||
|
private function sortTickets(Collection $tickets, Tenant $tenant, array $filters): Collection
|
||||||
|
{
|
||||||
|
$sortBy = (string) ($filters['sort_by'] ?? '');
|
||||||
|
if ($sortBy === '') {
|
||||||
|
return $tickets;
|
||||||
|
}
|
||||||
|
|
||||||
|
$column = collect($this->columnService->columns($tenant))
|
||||||
|
->firstWhere('sort_param', $sortBy);
|
||||||
|
if ($column === null) {
|
||||||
|
return $tickets;
|
||||||
|
}
|
||||||
|
|
||||||
|
$direction = ($filters['sort_direction'] ?? 'asc') === 'desc' ? -1 : 1;
|
||||||
|
$values = $tickets->mapWithKeys(fn (Ticket $ticket): array => [
|
||||||
|
$ticket->getKey() => $this->rowService->values($ticket)[$column['key']] ?? null,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return $tickets->sort(function (Ticket $left, Ticket $right) use ($column, $direction, $values): int {
|
||||||
|
$leftValue = $values->get($left->getKey());
|
||||||
|
$rightValue = $values->get($right->getKey());
|
||||||
|
|
||||||
|
if ($leftValue === null || $leftValue === '') {
|
||||||
|
return $rightValue === null || $rightValue === '' ? $right->id <=> $left->id : 1;
|
||||||
|
}
|
||||||
|
if ($rightValue === null || $rightValue === '') {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
$comparison = $this->compareValues($leftValue, $rightValue, $column['type']);
|
||||||
|
|
||||||
|
return $comparison === 0
|
||||||
|
? $right->id <=> $left->id
|
||||||
|
: $comparison * $direction;
|
||||||
|
})->values();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function compareValues(mixed $left, mixed $right, string $type): int
|
||||||
|
{
|
||||||
|
if (in_array($type, ['currency', 'order_number'], true)) {
|
||||||
|
return (float) $left <=> (float) $right;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($type === 'date') {
|
||||||
|
$leftTimestamp = $left instanceof \DateTimeInterface ? $left->getTimestamp() : strtotime((string) $left);
|
||||||
|
$rightTimestamp = $right instanceof \DateTimeInterface ? $right->getTimestamp() : strtotime((string) $right);
|
||||||
|
|
||||||
|
return $leftTimestamp <=> $rightTimestamp;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($type === 'status') {
|
||||||
|
$left = $this->rowService->displayValue($left, $type, 'UTC');
|
||||||
|
$right = $this->rowService->displayValue($right, $type, 'UTC');
|
||||||
|
}
|
||||||
|
|
||||||
|
return strnatcasecmp((string) $left, (string) $right);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param Collection<int, Ticket> $tickets
|
||||||
|
* @param array{page?: int, per_page?: int} $filters
|
||||||
|
* @return LengthAwarePaginator<Ticket>
|
||||||
|
*/
|
||||||
|
private function paginate(Collection $tickets, array $filters): LengthAwarePaginator
|
||||||
|
{
|
||||||
|
$page = (int) ($filters['page'] ?? 1);
|
||||||
|
$perPage = (int) ($filters['per_page'] ?? 15);
|
||||||
|
|
||||||
|
return (new LengthAwarePaginator(
|
||||||
|
$tickets->forPage($page, $perPage)->values(),
|
||||||
|
$tickets->count(),
|
||||||
|
$perPage,
|
||||||
|
$page,
|
||||||
|
['path' => request()->url()],
|
||||||
|
))->withQueryString();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -23,13 +23,13 @@ class TicketGeneratorService
|
|||||||
User $user,
|
User $user,
|
||||||
int $quantity = 1,
|
int $quantity = 1,
|
||||||
?int $sourceVariantId = null,
|
?int $sourceVariantId = null,
|
||||||
?int $sourcePurchaseId = null,
|
?int $sourcePurchaseItemId = null,
|
||||||
): Collection {
|
): Collection {
|
||||||
if ($quantity < 1) {
|
if ($quantity < 1) {
|
||||||
throw TicketGenerationException::invalidQuantity();
|
throw TicketGenerationException::invalidQuantity();
|
||||||
}
|
}
|
||||||
|
|
||||||
return DB::transaction(function () use ($catalogItem, $user, $quantity, $sourceVariantId, $sourcePurchaseId): Collection {
|
return DB::transaction(function () use ($catalogItem, $user, $quantity, $sourceVariantId, $sourcePurchaseItemId): Collection {
|
||||||
$targets = $this->resolveTargets(
|
$targets = $this->resolveTargets(
|
||||||
$catalogItem,
|
$catalogItem,
|
||||||
$quantity,
|
$quantity,
|
||||||
@@ -37,7 +37,7 @@ class TicketGeneratorService
|
|||||||
);
|
);
|
||||||
|
|
||||||
return $targets->map(function (array $target) use (
|
return $targets->map(function (array $target) use (
|
||||||
$sourcePurchaseId,
|
$sourcePurchaseItemId,
|
||||||
$user,
|
$user,
|
||||||
): Ticket {
|
): Ticket {
|
||||||
$item = $target['catalog_item'];
|
$item = $target['catalog_item'];
|
||||||
@@ -45,7 +45,7 @@ class TicketGeneratorService
|
|||||||
$ticket = Ticket::query()->create([
|
$ticket = Ticket::query()->create([
|
||||||
'tenant_code' => $item->tenant_code,
|
'tenant_code' => $item->tenant_code,
|
||||||
'ticket' => (string) Str::uuid(),
|
'ticket' => (string) Str::uuid(),
|
||||||
'source_purchase_id' => $sourcePurchaseId,
|
'source_purchase_item_id' => $sourcePurchaseItemId,
|
||||||
'source_catalog_item_id' => $item->getKey(),
|
'source_catalog_item_id' => $item->getKey(),
|
||||||
'source_variant_id' => $variant?->getKey(),
|
'source_variant_id' => $variant?->getKey(),
|
||||||
'used_at' => null,
|
'used_at' => null,
|
||||||
|
|||||||
@@ -6,7 +6,8 @@ Genera, valida, consulta y exporta entradas asociadas a compras pagadas de produ
|
|||||||
|
|
||||||
## Modelo
|
## Modelo
|
||||||
|
|
||||||
- `Ticket`: pertenece a tenant y usuario, y conserva referencias a compra, producto, variante y usuario escáner.
|
- `Ticket`: pertenece a tenant y usuario, y conserva referencias al ítem de compra que lo generó, producto,
|
||||||
|
variante y usuario escáner. La compra se obtiene a través de su ítem.
|
||||||
- El nombre y la descripción se calculan dinámicamente desde el producto y la variante; los tickets no
|
- El nombre y la descripción se calculan dinámicamente desde el producto y la variante; los tickets no
|
||||||
persisten una copia de esos textos.
|
persisten una copia de esos textos.
|
||||||
- `ValidityTime`: define ventanas absolutas o relativas de vigencia para fechas de evento y opciones de atributos.
|
- `ValidityTime`: define ventanas absolutas o relativas de vigencia para fechas de evento y opciones de atributos.
|
||||||
@@ -30,6 +31,12 @@ Bajo `/tenants/{tenant:codigo}`, protegidos por `auth:sanctum`:
|
|||||||
- `GET /tickets`.
|
- `GET /tickets`.
|
||||||
- `POST /tickets/pdf`.
|
- `POST /tickets/pdf`.
|
||||||
|
|
||||||
|
Bajo `/v1/adminapp/tenant`, protegido por `auth:sanctum`, `adminapp.tenant` y el menú
|
||||||
|
`adminapp.tickets`:
|
||||||
|
|
||||||
|
- `GET /tickets`, paginado y con búsqueda opcional mediante `q`. La respuesta incluye
|
||||||
|
`scanned_tickets` y `total_tickets` para el tenant autenticado.
|
||||||
|
|
||||||
`TicketPdfService` genera la descarga y `TicketResource`/`ValidityTimeResource` definen las respuestas.
|
`TicketPdfService` genera la descarga y `TicketResource`/`ValidityTimeResource` definen las respuestas.
|
||||||
|
|
||||||
## Dependencias y reglas
|
## Dependencias y reglas
|
||||||
|
|||||||
18
app/Domains/Ticket/routes/adminapp.php
Normal file
18
app/Domains/Ticket/routes/adminapp.php
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Domains\Ticket\Controllers\AdminApp\TicketController;
|
||||||
|
use Illuminate\Support\Facades\Route;
|
||||||
|
|
||||||
|
Route::prefix('v1/adminapp/tenant')
|
||||||
|
->middleware(['auth:sanctum', 'adminapp.tenant'])
|
||||||
|
->group(function (): void {
|
||||||
|
Route::get('tickets', [TicketController::class, 'index'])
|
||||||
|
->middleware('tenant.menu:adminapp.tickets')
|
||||||
|
->name('adminapp.tickets.index');
|
||||||
|
Route::get('tickets/pdf', [TicketController::class, 'downloadPdf'])
|
||||||
|
->middleware('tenant.menu:adminapp.tickets')
|
||||||
|
->name('adminapp.tickets.pdf');
|
||||||
|
Route::get('tickets/excel', [TicketController::class, 'downloadExcel'])
|
||||||
|
->middleware('tenant.menu:adminapp.tickets')
|
||||||
|
->name('adminapp.tickets.excel');
|
||||||
|
});
|
||||||
@@ -11,3 +11,4 @@ Route::prefix('tenants/{tenant:codigo}')
|
|||||||
});
|
});
|
||||||
|
|
||||||
require __DIR__.'/scanner.php';
|
require __DIR__.'/scanner.php';
|
||||||
|
require __DIR__.'/adminapp.php';
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
use App\Domains\Auth\Exceptions\AccountLockedException;
|
use App\Domains\Auth\Exceptions\AccountLockedException;
|
||||||
|
use App\Domains\Catalog\Exceptions\StockReservationExpiredException;
|
||||||
use App\Domains\Purchase\Exceptions\InsufficientStockException;
|
use App\Domains\Purchase\Exceptions\InsufficientStockException;
|
||||||
use App\Domains\Purchase\Exceptions\PurchaseExpiredException;
|
use App\Domains\Purchase\Exceptions\PurchaseExpiredException;
|
||||||
use App\Domains\Purchase\Exceptions\PurchaseLimitExceededException;
|
use App\Domains\Purchase\Exceptions\PurchaseLimitExceededException;
|
||||||
@@ -113,6 +114,16 @@ return Application::configure(basePath: dirname(__DIR__))
|
|||||||
'message' => $exception->getMessage(),
|
'message' => $exception->getMessage(),
|
||||||
], 422);
|
], 422);
|
||||||
});
|
});
|
||||||
|
$exceptions->render(function (StockReservationExpiredException $exception, Request $request) {
|
||||||
|
if (! $request->is('api/*')) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'code' => 'stock_reservation.expired',
|
||||||
|
'message' => $exception->getMessage(),
|
||||||
|
], 422);
|
||||||
|
});
|
||||||
$exceptions->render(function (ModelNotFoundException $exception, Request $request) {
|
$exceptions->render(function (ModelNotFoundException $exception, Request $request) {
|
||||||
if (! $request->is('api/*')) {
|
if (! $request->is('api/*')) {
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
@@ -96,7 +96,7 @@ return [
|
|||||||
'users' => [
|
'users' => [
|
||||||
'provider' => 'users',
|
'provider' => 'users',
|
||||||
'table' => env('AUTH_PASSWORD_RESET_TOKEN_TABLE', 'password_reset_tokens'),
|
'table' => env('AUTH_PASSWORD_RESET_TOKEN_TABLE', 'password_reset_tokens'),
|
||||||
'expire' => 60,
|
'expire' => (int) env('AUTH_PASSWORD_RESET_EXPIRATION_MINUTES', 60),
|
||||||
'throttle' => 60,
|
'throttle' => 60,
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -8,4 +8,9 @@ return [
|
|||||||
'telepagos' => (int) env('PURCHASE_TELEPAGOS_EXPIRATION_MINUTES', 30),
|
'telepagos' => (int) env('PURCHASE_TELEPAGOS_EXPIRATION_MINUTES', 30),
|
||||||
'transfer' => (int) env('PURCHASE_TRANSFER_EXPIRATION_MINUTES', 1440),
|
'transfer' => (int) env('PURCHASE_TRANSFER_EXPIRATION_MINUTES', 1440),
|
||||||
],
|
],
|
||||||
|
|
||||||
|
'transfer_candidate_amount_tolerance_percentage' => (float) env(
|
||||||
|
'PURCHASE_TRANSFER_CANDIDATE_AMOUNT_TOLERANCE_PERCENTAGE',
|
||||||
|
5,
|
||||||
|
),
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Domains\Auth\Models\ResetPasswordAttempt;
|
||||||
|
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('reset_password_attempts', function (Blueprint $table): void {
|
||||||
|
$table->timestamp('expires_at')->nullable()->after('status');
|
||||||
|
});
|
||||||
|
|
||||||
|
// Attempts created before this migration did not have an expiration instant.
|
||||||
|
DB::table('reset_password_attempts')
|
||||||
|
->whereIn('status', [
|
||||||
|
ResetPasswordAttempt::STATUS_PENDING,
|
||||||
|
ResetPasswordAttempt::STATUS_VALIDATED,
|
||||||
|
])
|
||||||
|
->update(['status' => ResetPasswordAttempt::STATUS_EXPIRED]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('reset_password_attempts', function (Blueprint $table): void {
|
||||||
|
$table->dropColumn('expires_at');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
<?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::rename('stock_reservations', 'stock_reservation_lines');
|
||||||
|
|
||||||
|
Schema::create('stock_reservations', function (Blueprint $table): void {
|
||||||
|
$table->id();
|
||||||
|
$table->string('status')->default('active');
|
||||||
|
$table->dateTime('expires_at')->nullable();
|
||||||
|
$table->dateTime('committed_at')->nullable();
|
||||||
|
$table->dateTime('released_at')->nullable();
|
||||||
|
$table->dateTime('expired_at')->nullable();
|
||||||
|
$table->string('release_reason')->nullable();
|
||||||
|
$table->timestamps();
|
||||||
|
|
||||||
|
$table->index(['status', 'expires_at']);
|
||||||
|
});
|
||||||
|
|
||||||
|
Schema::table('stock_reservation_lines', function (Blueprint $table): void {
|
||||||
|
$table->foreignId('stock_reservation_id')->nullable()->after('id');
|
||||||
|
$table->boolean('tracks_inventory')->default(true)->after('quantity');
|
||||||
|
});
|
||||||
|
|
||||||
|
Schema::table('carritos', function (Blueprint $table): void {
|
||||||
|
$table->foreignId('current_stock_reservation_id')->nullable()->after('current_purchase_id');
|
||||||
|
});
|
||||||
|
|
||||||
|
Schema::table('compras', function (Blueprint $table): void {
|
||||||
|
$table->foreignId('stock_reservation_id')->nullable()->after('cart_id');
|
||||||
|
});
|
||||||
|
|
||||||
|
$cartIdsByItem = DB::table('carrito_items')->pluck('cart_id', 'id');
|
||||||
|
$unlimitedInventoryIds = DB::table('catalog_items')
|
||||||
|
->where('inventory_policy', 'unlimited')
|
||||||
|
->whereNotNull('inventory_id')
|
||||||
|
->pluck('inventory_id')
|
||||||
|
->merge(
|
||||||
|
DB::table('variantes')
|
||||||
|
->join('catalog_items', 'catalog_items.id', '=', 'variantes.catalog_item_id')
|
||||||
|
->where('catalog_items.inventory_policy', 'unlimited')
|
||||||
|
->pluck('variantes.inventory_id'),
|
||||||
|
)
|
||||||
|
->map(fn ($id): int => (int) $id)
|
||||||
|
->unique();
|
||||||
|
$legacyRows = DB::table('stock_reservation_lines')->orderBy('id')->get();
|
||||||
|
$groups = $legacyRows->groupBy(function (object $row) use ($cartIdsByItem): string {
|
||||||
|
if ($row->purchase_id !== null) {
|
||||||
|
return 'purchase:'.$row->purchase_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
$cartId = $row->cart_item_id === null ? null : $cartIdsByItem->get($row->cart_item_id);
|
||||||
|
|
||||||
|
return $cartId === null ? 'legacy:'.$row->id : 'cart:'.$cartId;
|
||||||
|
});
|
||||||
|
|
||||||
|
foreach ($groups as $key => $rows) {
|
||||||
|
$statuses = $rows->pluck('status');
|
||||||
|
$status = $statuses->contains('active')
|
||||||
|
? 'active'
|
||||||
|
: ($statuses->contains('committed')
|
||||||
|
? 'committed'
|
||||||
|
: ($statuses->contains('expired') ? 'expired' : 'released'));
|
||||||
|
$first = $rows->first();
|
||||||
|
$reservationId = DB::table('stock_reservations')->insertGetId([
|
||||||
|
'status' => $status,
|
||||||
|
'expires_at' => $status === 'active' ? $rows->pluck('expires_at')->filter()->max() : null,
|
||||||
|
'committed_at' => $status === 'committed' ? $rows->pluck('committed_at')->filter()->max() : null,
|
||||||
|
'released_at' => $status === 'released' ? $rows->pluck('released_at')->filter()->max() : null,
|
||||||
|
'expired_at' => $status === 'expired' ? $rows->pluck('released_at')->filter()->max() : null,
|
||||||
|
'release_reason' => null,
|
||||||
|
'created_at' => $first->created_at,
|
||||||
|
'updated_at' => $rows->pluck('updated_at')->filter()->max() ?? $first->updated_at,
|
||||||
|
]);
|
||||||
|
|
||||||
|
foreach ($rows->groupBy('inventory_id') as $inventoryRows) {
|
||||||
|
$line = $inventoryRows->first();
|
||||||
|
DB::table('stock_reservation_lines')->where('id', $line->id)->update([
|
||||||
|
'stock_reservation_id' => $reservationId,
|
||||||
|
'quantity' => $inventoryRows->sum('quantity'),
|
||||||
|
'tracks_inventory' => ! $unlimitedInventoryIds->contains((int) $line->inventory_id),
|
||||||
|
]);
|
||||||
|
DB::table('stock_reservation_lines')
|
||||||
|
->whereIn('id', $inventoryRows->pluck('id')->skip(1))
|
||||||
|
->delete();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (str_starts_with($key, 'purchase:')) {
|
||||||
|
$purchaseId = (int) substr($key, strlen('purchase:'));
|
||||||
|
DB::table('compras')->where('id', $purchaseId)->update([
|
||||||
|
'stock_reservation_id' => $reservationId,
|
||||||
|
]);
|
||||||
|
$cartId = DB::table('compras')->where('id', $purchaseId)->value('cart_id');
|
||||||
|
$isCurrent = $cartId !== null
|
||||||
|
&& (int) DB::table('carritos')->where('id', $cartId)->value('current_purchase_id') === $purchaseId;
|
||||||
|
|
||||||
|
if ($status === 'active' && $isCurrent) {
|
||||||
|
DB::table('carritos')->where('id', $cartId)->update([
|
||||||
|
'current_stock_reservation_id' => $reservationId,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
} elseif (str_starts_with($key, 'cart:') && $status === 'active') {
|
||||||
|
DB::table('carritos')->where('id', (int) substr($key, strlen('cart:')))->update([
|
||||||
|
'current_stock_reservation_id' => $reservationId,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (DB::getDriverName() !== 'sqlite') {
|
||||||
|
Schema::table('stock_reservation_lines', function (Blueprint $table): void {
|
||||||
|
$table->dropForeign('stock_reservations_cart_item_id_foreign');
|
||||||
|
$table->dropForeign('stock_reservations_purchase_id_foreign');
|
||||||
|
$table->dropUnique('stock_reservations_cart_item_id_inventory_id_unique');
|
||||||
|
$table->dropIndex('stock_reservations_purchase_id_status_index');
|
||||||
|
$table->dropIndex('stock_reservations_status_expires_at_index');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Schema::table('stock_reservation_lines', function (Blueprint $table): void {
|
||||||
|
$table->unsignedBigInteger('stock_reservation_id')->nullable(false)->change();
|
||||||
|
$table->dropColumn([
|
||||||
|
'cart_item_id',
|
||||||
|
'purchase_id',
|
||||||
|
'status',
|
||||||
|
'expires_at',
|
||||||
|
'committed_at',
|
||||||
|
'released_at',
|
||||||
|
]);
|
||||||
|
$table->foreign('stock_reservation_id', 'reservation_lines_reservation_fk')
|
||||||
|
->references('id')
|
||||||
|
->on('stock_reservations')
|
||||||
|
->cascadeOnDelete();
|
||||||
|
$table->unique(
|
||||||
|
['stock_reservation_id', 'inventory_id'],
|
||||||
|
'reservation_lines_reservation_inventory_unique',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
Schema::table('carritos', function (Blueprint $table): void {
|
||||||
|
$table->foreign('current_stock_reservation_id', 'carts_current_stock_reservation_fk')
|
||||||
|
->references('id')
|
||||||
|
->on('stock_reservations')
|
||||||
|
->nullOnDelete();
|
||||||
|
$table->unique('current_stock_reservation_id', 'carts_current_stock_reservation_unique');
|
||||||
|
});
|
||||||
|
|
||||||
|
Schema::table('compras', function (Blueprint $table): void {
|
||||||
|
$table->foreign('stock_reservation_id', 'purchases_stock_reservation_fk')
|
||||||
|
->references('id')
|
||||||
|
->on('stock_reservations')
|
||||||
|
->nullOnDelete();
|
||||||
|
$table->unique('stock_reservation_id', 'purchases_stock_reservation_unique');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('compras', function (Blueprint $table): void {
|
||||||
|
$table->dropUnique('purchases_stock_reservation_unique');
|
||||||
|
$table->dropForeign('purchases_stock_reservation_fk');
|
||||||
|
$table->dropColumn('stock_reservation_id');
|
||||||
|
});
|
||||||
|
|
||||||
|
Schema::table('carritos', function (Blueprint $table): void {
|
||||||
|
$table->dropUnique('carts_current_stock_reservation_unique');
|
||||||
|
$table->dropForeign('carts_current_stock_reservation_fk');
|
||||||
|
$table->dropColumn('current_stock_reservation_id');
|
||||||
|
});
|
||||||
|
|
||||||
|
Schema::dropIfExists('stock_reservation_lines');
|
||||||
|
Schema::dropIfExists('stock_reservations');
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
<?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
|
||||||
|
{
|
||||||
|
DB::table('compras')
|
||||||
|
->whereNotNull('stock_reservation_id')
|
||||||
|
->orderBy('id')
|
||||||
|
->chunkById(500, function ($purchases): void {
|
||||||
|
foreach ($purchases as $purchase) {
|
||||||
|
DB::table('stock_reservations')
|
||||||
|
->where('id', $purchase->stock_reservation_id)
|
||||||
|
->where('status', 'active')
|
||||||
|
->update(['expires_at' => $purchase->expires_at]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Schema::table('compras', function (Blueprint $table): void {
|
||||||
|
$table->dropIndex(['expires_at']);
|
||||||
|
$table->dropColumn('expires_at');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('compras', function (Blueprint $table): void {
|
||||||
|
$table->timestamp('expires_at')->nullable()->index()->after('payment_method');
|
||||||
|
});
|
||||||
|
|
||||||
|
DB::table('compras')
|
||||||
|
->whereNotNull('stock_reservation_id')
|
||||||
|
->orderBy('id')
|
||||||
|
->chunkById(500, function ($purchases): void {
|
||||||
|
foreach ($purchases as $purchase) {
|
||||||
|
DB::table('compras')
|
||||||
|
->where('id', $purchase->id)
|
||||||
|
->update([
|
||||||
|
'expires_at' => DB::table('stock_reservations')
|
||||||
|
->where('id', $purchase->stock_reservation_id)
|
||||||
|
->value('expires_at'),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
$expiredReservationIds = fn ($query) => $query
|
||||||
|
->select('id')
|
||||||
|
->from('stock_reservations')
|
||||||
|
->where('status', 'expired');
|
||||||
|
|
||||||
|
DB::table('compras')
|
||||||
|
->whereIn('status', ['created', 'pending_payment'])
|
||||||
|
->whereIn('stock_reservation_id', $expiredReservationIds)
|
||||||
|
->update(['status' => 'expired']);
|
||||||
|
|
||||||
|
DB::table('carritos')
|
||||||
|
->whereIn('status', ['active', 'checkout'])
|
||||||
|
->whereIn('current_stock_reservation_id', $expiredReservationIds)
|
||||||
|
->update(['status' => 'expired']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
// Terminal business states cannot be reversed without inventing their prior state.
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
<?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::create('telepagos_payment_candidates', function (Blueprint $table) {
|
||||||
|
$table->id();
|
||||||
|
$table->foreignId('telepagos_payment_id')
|
||||||
|
->constrained('telepagos_payments')
|
||||||
|
->cascadeOnDelete();
|
||||||
|
$table->foreignId('compra_id')->constrained('compras')->cascadeOnDelete();
|
||||||
|
$table->boolean('dni_matches');
|
||||||
|
$table->boolean('amount_matches');
|
||||||
|
$table->decimal('payment_amount', 10, 2);
|
||||||
|
$table->decimal('purchase_amount', 10, 2);
|
||||||
|
$table->decimal('amount_difference', 10, 2);
|
||||||
|
$table->string('match_reason');
|
||||||
|
$table->string('confidence');
|
||||||
|
$table->timestamps();
|
||||||
|
|
||||||
|
$table->unique(
|
||||||
|
['telepagos_payment_id', 'compra_id'],
|
||||||
|
'telepagos_payment_candidate_unique',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
$this->migrateExistingCandidates();
|
||||||
|
|
||||||
|
Schema::table('telepagos_payments', function (Blueprint $table) {
|
||||||
|
$table->dropColumn('matched_purchase_ids');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('telepagos_payments', function (Blueprint $table) {
|
||||||
|
$table->json('matched_purchase_ids')->nullable()->after('compra_id');
|
||||||
|
});
|
||||||
|
|
||||||
|
DB::table('telepagos_payments')
|
||||||
|
->whereNull('compra_id')
|
||||||
|
->orderBy('id')
|
||||||
|
->each(function (object $payment): void {
|
||||||
|
$candidateIds = DB::table('telepagos_payment_candidates')
|
||||||
|
->where('telepagos_payment_id', $payment->id)
|
||||||
|
->pluck('compra_id')
|
||||||
|
->all();
|
||||||
|
|
||||||
|
if ($candidateIds !== []) {
|
||||||
|
DB::table('telepagos_payments')
|
||||||
|
->where('id', $payment->id)
|
||||||
|
->update(['matched_purchase_ids' => json_encode($candidateIds)]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Schema::dropIfExists('telepagos_payment_candidates');
|
||||||
|
}
|
||||||
|
|
||||||
|
private function migrateExistingCandidates(): void
|
||||||
|
{
|
||||||
|
DB::table('telepagos_payments')
|
||||||
|
->whereNull('compra_id')
|
||||||
|
->whereNotNull('matched_purchase_ids')
|
||||||
|
->orderBy('id')
|
||||||
|
->each(function (object $payment): void {
|
||||||
|
$candidateIds = json_decode((string) $payment->matched_purchase_ids, true);
|
||||||
|
|
||||||
|
if (! is_array($candidateIds)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$paymentAmount = number_format((float) $payment->amount, 2, '.', '');
|
||||||
|
$payerDni = $payment->cuit_buyer
|
||||||
|
? substr((string) $payment->cuit_buyer, 2, -1)
|
||||||
|
: null;
|
||||||
|
|
||||||
|
foreach ($candidateIds as $candidateId) {
|
||||||
|
$purchase = DB::table('compras')->find($candidateId);
|
||||||
|
|
||||||
|
if ($purchase === null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$purchaseAmount = number_format((float) $purchase->total, 2, '.', '');
|
||||||
|
$dniMatches = $payerDni !== null && $purchase->transfer_payer_dni === $payerDni;
|
||||||
|
$amountMatches = $purchaseAmount === $paymentAmount;
|
||||||
|
|
||||||
|
DB::table('telepagos_payment_candidates')->insertOrIgnore([
|
||||||
|
'telepagos_payment_id' => $payment->id,
|
||||||
|
'compra_id' => $purchase->id,
|
||||||
|
'dni_matches' => $dniMatches,
|
||||||
|
'amount_matches' => $amountMatches,
|
||||||
|
'payment_amount' => $paymentAmount,
|
||||||
|
'purchase_amount' => $purchaseAmount,
|
||||||
|
'amount_difference' => number_format(
|
||||||
|
abs((float) $purchaseAmount - (float) $paymentAmount),
|
||||||
|
2,
|
||||||
|
'.',
|
||||||
|
'',
|
||||||
|
),
|
||||||
|
'match_reason' => $this->matchReason($dniMatches, $amountMatches),
|
||||||
|
'confidence' => $this->confidence($dniMatches, $amountMatches),
|
||||||
|
'created_at' => $payment->created_at,
|
||||||
|
'updated_at' => $payment->updated_at,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function matchReason(bool $dniMatches, bool $amountMatches): string
|
||||||
|
{
|
||||||
|
if ($dniMatches && $amountMatches) {
|
||||||
|
return 'ambiguous_exact_match';
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($dniMatches) {
|
||||||
|
return 'exact_dni_near_amount';
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($amountMatches) {
|
||||||
|
return 'exact_amount_different_dni';
|
||||||
|
}
|
||||||
|
|
||||||
|
return 'legacy_candidate';
|
||||||
|
}
|
||||||
|
|
||||||
|
private function confidence(bool $dniMatches, bool $amountMatches): string
|
||||||
|
{
|
||||||
|
if ($dniMatches && $amountMatches) {
|
||||||
|
return 'exact';
|
||||||
|
}
|
||||||
|
|
||||||
|
return $dniMatches ? 'high' : 'medium';
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Domains\Purchase\Services\DniDistanceService;
|
||||||
|
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('telepagos_payment_candidates', function (Blueprint $table) {
|
||||||
|
$table->unsignedTinyInteger('dni_distance')->nullable()->after('dni_matches');
|
||||||
|
$table->string('payment_dni', 8)->nullable()->after('dni_distance');
|
||||||
|
$table->string('purchase_dni', 8)->nullable()->after('payment_dni');
|
||||||
|
});
|
||||||
|
|
||||||
|
$dniDistance = new DniDistanceService;
|
||||||
|
|
||||||
|
DB::table('telepagos_payment_candidates as candidate')
|
||||||
|
->join('telepagos_payments as payment', 'payment.id', '=', 'candidate.telepagos_payment_id')
|
||||||
|
->join('compras as purchase', 'purchase.id', '=', 'candidate.compra_id')
|
||||||
|
->select([
|
||||||
|
'candidate.id',
|
||||||
|
'candidate.match_reason',
|
||||||
|
'payment.cuit_buyer',
|
||||||
|
'purchase.transfer_payer_dni',
|
||||||
|
])
|
||||||
|
->orderBy('candidate.id')
|
||||||
|
->each(function (object $candidate) use ($dniDistance): void {
|
||||||
|
if ($candidate->cuit_buyer === null || $candidate->transfer_payer_dni === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$payerDni = substr((string) $candidate->cuit_buyer, 2, -1);
|
||||||
|
$distance = $dniDistance->distance($payerDni, (string) $candidate->transfer_payer_dni);
|
||||||
|
|
||||||
|
if ($candidate->match_reason === 'exact_amount_different_dni' && $distance > 2) {
|
||||||
|
DB::table('telepagos_payment_candidates')->where('id', $candidate->id)->delete();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
DB::table('telepagos_payment_candidates')
|
||||||
|
->where('id', $candidate->id)
|
||||||
|
->update([
|
||||||
|
'dni_distance' => $distance,
|
||||||
|
'payment_dni' => $payerDni,
|
||||||
|
'purchase_dni' => $candidate->transfer_payer_dni,
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('telepagos_payment_candidates', function (Blueprint $table) {
|
||||||
|
$table->dropColumn(['dni_distance', 'payment_dni', 'purchase_dni']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
DB::table('telepagos_payment_candidates')
|
||||||
|
->where('match_reason', 'exact_amount_different_dni')
|
||||||
|
->update(['match_reason' => 'exact_amount_near_dni']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
DB::table('telepagos_payment_candidates')
|
||||||
|
->where('match_reason', 'exact_amount_near_dni')
|
||||||
|
->update(['match_reason' => 'exact_amount_different_dni']);
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
private const MENU_CODE = 'adminapp.tickets';
|
||||||
|
|
||||||
|
private const TENANT_CODE = 'fiesta_futbol_infantil';
|
||||||
|
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
if (! DB::table('menues')->where('code', 'main.adminapp')->exists()) {
|
||||||
|
// Reference data is added by seeders on fresh installations.
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$now = now();
|
||||||
|
|
||||||
|
DB::transaction(function () use ($now): void {
|
||||||
|
DB::table('menues')->updateOrInsert(
|
||||||
|
['code' => self::MENU_CODE],
|
||||||
|
[
|
||||||
|
'label' => 'Tickets',
|
||||||
|
'parent_menu_code' => 'main.adminapp',
|
||||||
|
'content_type' => 'dynamic',
|
||||||
|
'static_content_schema' => null,
|
||||||
|
'route' => '/admin/tickets',
|
||||||
|
'created_at' => $now,
|
||||||
|
'updated_at' => $now,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
DB::table('tenants_menues')
|
||||||
|
->where('menu_code', self::MENU_CODE)
|
||||||
|
->where('tenant_code', '!=', self::TENANT_CODE)
|
||||||
|
->delete();
|
||||||
|
|
||||||
|
if (DB::table('tenants')->where('codigo', self::TENANT_CODE)->exists()) {
|
||||||
|
DB::table('tenants_menues')->updateOrInsert(
|
||||||
|
[
|
||||||
|
'tenant_code' => self::TENANT_CODE,
|
||||||
|
'menu_code' => self::MENU_CODE,
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'static_content' => null,
|
||||||
|
'created_at' => $now,
|
||||||
|
'updated_at' => $now,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
DB::table('roles')
|
||||||
|
->whereIn('codigo', ['admin', 'adminapp'])
|
||||||
|
->pluck('codigo')
|
||||||
|
->each(function (string $roleCode): void {
|
||||||
|
DB::table('roles_menues')->updateOrInsert([
|
||||||
|
'rol_codigo' => $roleCode,
|
||||||
|
'menu_codigo' => self::MENU_CODE,
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
DB::transaction(function (): void {
|
||||||
|
DB::table('tenants_menues')
|
||||||
|
->where('menu_code', self::MENU_CODE)
|
||||||
|
->delete();
|
||||||
|
|
||||||
|
DB::table('roles_menues')
|
||||||
|
->where('menu_codigo', self::MENU_CODE)
|
||||||
|
->delete();
|
||||||
|
|
||||||
|
DB::table('menues')
|
||||||
|
->where('code', self::MENU_CODE)
|
||||||
|
->delete();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::table('tickets', function (Blueprint $table): void {
|
||||||
|
$table->foreignId('source_purchase_item_id')
|
||||||
|
->nullable()
|
||||||
|
->after('source_purchase_id')
|
||||||
|
->constrained('compra_items')
|
||||||
|
->cascadeOnUpdate()
|
||||||
|
->nullOnDelete();
|
||||||
|
});
|
||||||
|
|
||||||
|
DB::table('tickets')
|
||||||
|
->whereNotNull('source_purchase_id')
|
||||||
|
->whereNull('source_purchase_item_id')
|
||||||
|
->orderBy('id')
|
||||||
|
->chunkById(500, function (Collection $tickets): void {
|
||||||
|
$purchaseIds = $tickets->pluck('source_purchase_id')->unique()->values();
|
||||||
|
$itemsByPurchase = DB::table('compra_items')
|
||||||
|
->whereIn('compra_id', $purchaseIds)
|
||||||
|
->get(['id', 'compra_id', 'source_catalog_item_id', 'source_variant_id'])
|
||||||
|
->groupBy('compra_id');
|
||||||
|
$bundleIds = $itemsByPurchase->flatten(1)
|
||||||
|
->pluck('source_catalog_item_id')
|
||||||
|
->filter()
|
||||||
|
->unique()
|
||||||
|
->values();
|
||||||
|
$componentsByBundle = DB::table('bundle_components')
|
||||||
|
->whereIn('bundle_catalog_item_id', $bundleIds)
|
||||||
|
->get([
|
||||||
|
'bundle_catalog_item_id',
|
||||||
|
'component_catalog_item_id',
|
||||||
|
'component_variant_id',
|
||||||
|
])
|
||||||
|
->groupBy('bundle_catalog_item_id');
|
||||||
|
|
||||||
|
foreach ($tickets as $ticket) {
|
||||||
|
$candidates = collect($itemsByPurchase->get($ticket->source_purchase_id, []))
|
||||||
|
->filter(function (object $item) use ($ticket, $componentsByBundle): bool {
|
||||||
|
if ($this->sameCatalogTarget($item, $ticket)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return collect($componentsByBundle->get($item->source_catalog_item_id, []))
|
||||||
|
->contains(fn (object $component): bool => $this->sameBundleTarget($component, $ticket));
|
||||||
|
})
|
||||||
|
->pluck('id')
|
||||||
|
->unique()
|
||||||
|
->values();
|
||||||
|
|
||||||
|
if ($candidates->count() === 1) {
|
||||||
|
DB::table('tickets')->where('id', $ticket->id)->update([
|
||||||
|
'source_purchase_item_id' => $candidates->sole(),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('tickets', function (Blueprint $table): void {
|
||||||
|
$table->dropConstrainedForeignId('source_purchase_item_id');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function sameCatalogTarget(object $item, object $ticket): bool
|
||||||
|
{
|
||||||
|
return (int) $item->source_catalog_item_id === (int) $ticket->source_catalog_item_id
|
||||||
|
&& $this->sameNullableId($item->source_variant_id, $ticket->source_variant_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function sameBundleTarget(object $component, object $ticket): bool
|
||||||
|
{
|
||||||
|
return (int) $component->component_catalog_item_id === (int) $ticket->source_catalog_item_id
|
||||||
|
&& $this->sameNullableId($component->component_variant_id, $ticket->source_variant_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function sameNullableId(mixed $left, mixed $right): bool
|
||||||
|
{
|
||||||
|
return $left === null || $right === null
|
||||||
|
? $left === null && $right === null
|
||||||
|
: (int) $left === (int) $right;
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
$unresolved = DB::table('tickets')
|
||||||
|
->whereNotNull('source_purchase_id')
|
||||||
|
->whereNull('source_purchase_item_id')
|
||||||
|
->orderBy('id')
|
||||||
|
->limit(20)
|
||||||
|
->pluck('id');
|
||||||
|
|
||||||
|
if ($unresolved->isNotEmpty()) {
|
||||||
|
throw new RuntimeException(
|
||||||
|
'No se puede eliminar tickets.source_purchase_id: hay tickets sin un compra_item inequívoco. '
|
||||||
|
.'IDs: '.$unresolved->implode(', ')
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
$inconsistent = DB::table('tickets')
|
||||||
|
->join('compra_items', 'compra_items.id', '=', 'tickets.source_purchase_item_id')
|
||||||
|
->whereNotNull('tickets.source_purchase_id')
|
||||||
|
->whereColumn('tickets.source_purchase_id', '!=', 'compra_items.compra_id')
|
||||||
|
->orderBy('tickets.id')
|
||||||
|
->limit(20)
|
||||||
|
->pluck('tickets.id');
|
||||||
|
|
||||||
|
if ($inconsistent->isNotEmpty()) {
|
||||||
|
throw new RuntimeException(
|
||||||
|
'No se puede eliminar tickets.source_purchase_id: hay referencias de compra inconsistentes. '
|
||||||
|
.'IDs: '.$inconsistent->implode(', ')
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Schema::table('tickets', function (Blueprint $table): void {
|
||||||
|
$table->dropConstrainedForeignId('source_purchase_id');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('tickets', function (Blueprint $table): void {
|
||||||
|
$table->foreignId('source_purchase_id')
|
||||||
|
->nullable()
|
||||||
|
->after('description')
|
||||||
|
->constrained('compras')
|
||||||
|
->cascadeOnUpdate()
|
||||||
|
->nullOnDelete();
|
||||||
|
});
|
||||||
|
|
||||||
|
DB::table('tickets')
|
||||||
|
->whereNotNull('source_purchase_item_id')
|
||||||
|
->orderBy('id')
|
||||||
|
->chunkById(500, function (Collection $tickets): void {
|
||||||
|
$purchaseIdsByItem = DB::table('compra_items')
|
||||||
|
->whereIn('id', $tickets->pluck('source_purchase_item_id'))
|
||||||
|
->pluck('compra_id', 'id');
|
||||||
|
|
||||||
|
foreach ($tickets as $ticket) {
|
||||||
|
DB::table('tickets')->where('id', $ticket->id)->update([
|
||||||
|
'source_purchase_id' => $purchaseIdsByItem->get($ticket->source_purchase_item_id),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -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
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::table('tickets', function (Blueprint $table): void {
|
||||||
|
$table->dropForeign(['source_purchase_item_id']);
|
||||||
|
});
|
||||||
|
|
||||||
|
Schema::table('tickets', function (Blueprint $table): void {
|
||||||
|
$table->foreign('source_purchase_item_id')
|
||||||
|
->references('id')
|
||||||
|
->on('compra_items')
|
||||||
|
->cascadeOnUpdate()
|
||||||
|
->restrictOnDelete();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('tickets', function (Blueprint $table): void {
|
||||||
|
$table->dropForeign(['source_purchase_item_id']);
|
||||||
|
});
|
||||||
|
|
||||||
|
Schema::table('tickets', function (Blueprint $table): void {
|
||||||
|
$table->foreign('source_purchase_item_id')
|
||||||
|
->references('id')
|
||||||
|
->on('compra_items')
|
||||||
|
->cascadeOnUpdate()
|
||||||
|
->nullOnDelete();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -78,6 +78,12 @@ class MenuSeeder extends Seeder
|
|||||||
'parent_menu_code' => 'main.adminapp',
|
'parent_menu_code' => 'main.adminapp',
|
||||||
'route' => '/admin/staff',
|
'route' => '/admin/staff',
|
||||||
],
|
],
|
||||||
|
[
|
||||||
|
'code' => 'adminapp.tickets',
|
||||||
|
'label' => 'Tickets',
|
||||||
|
'parent_menu_code' => 'main.adminapp',
|
||||||
|
'route' => '/admin/tickets',
|
||||||
|
],
|
||||||
[
|
[
|
||||||
'code' => 'adminapp.fiesta-futbol-infantil.entradas',
|
'code' => 'adminapp.fiesta-futbol-infantil.entradas',
|
||||||
'label' => 'Entradas',
|
'label' => 'Entradas',
|
||||||
@@ -270,6 +276,7 @@ class MenuSeeder extends Seeder
|
|||||||
'fiesta_futbol_infantil',
|
'fiesta_futbol_infantil',
|
||||||
];
|
];
|
||||||
$fiestaCategoryMenuCodes = [
|
$fiestaCategoryMenuCodes = [
|
||||||
|
'adminapp.tickets',
|
||||||
'adminapp.fiesta-futbol-infantil.entradas',
|
'adminapp.fiesta-futbol-infantil.entradas',
|
||||||
'adminapp.fiesta-futbol-infantil.alojamientos',
|
'adminapp.fiesta-futbol-infantil.alojamientos',
|
||||||
'adminapp.fiesta-futbol-infantil.merchandising',
|
'adminapp.fiesta-futbol-infantil.merchandising',
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ return [
|
|||||||
'password_reset_invalid' => 'The password recovery request is invalid or has already been used.',
|
'password_reset_invalid' => 'The password recovery request is invalid or has already been used.',
|
||||||
'password_updated' => 'Password updated successfully.',
|
'password_updated' => 'Password updated successfully.',
|
||||||
'reset_code_invalid' => 'The code you entered is invalid.',
|
'reset_code_invalid' => 'The code you entered is invalid.',
|
||||||
|
'reset_code_expired' => 'The password recovery code expired. Request a new one.',
|
||||||
'reset_code_valid' => 'Code validated successfully.',
|
'reset_code_valid' => 'Code validated successfully.',
|
||||||
'invalid_tenant_or_return_url' => 'The tenant or return URL is invalid.',
|
'invalid_tenant_or_return_url' => 'The tenant or return URL is invalid.',
|
||||||
'request_expired' => 'The authentication request expired. Please try again.',
|
'request_expired' => 'The authentication request expired. Please try again.',
|
||||||
@@ -34,6 +35,7 @@ return [
|
|||||||
'bundle_variant_forbidden' => 'A bundle cannot have a variant.',
|
'bundle_variant_forbidden' => 'A bundle cannot have a variant.',
|
||||||
'empty_bundle' => 'The bundle has no components.',
|
'empty_bundle' => 'The bundle has no components.',
|
||||||
'variant_required' => 'You must select a variant for this item.',
|
'variant_required' => 'You must select a variant for this item.',
|
||||||
|
'reservation_expired' => 'The stock reservation has expired. Use the active cart to continue.',
|
||||||
],
|
],
|
||||||
'purchase' => [
|
'purchase' => [
|
||||||
'expired' => 'The purchase has expired. Please start a new purchase.',
|
'expired' => 'The purchase has expired. Please start a new purchase.',
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ return [
|
|||||||
'password_reset_invalid' => 'La solicitud de recuperación es inválida o ya fue utilizada.',
|
'password_reset_invalid' => 'La solicitud de recuperación es inválida o ya fue utilizada.',
|
||||||
'password_updated' => 'Contraseña modificada correctamente.',
|
'password_updated' => 'Contraseña modificada correctamente.',
|
||||||
'reset_code_invalid' => 'El código ingresado es inválido.',
|
'reset_code_invalid' => 'El código ingresado es inválido.',
|
||||||
|
'reset_code_expired' => 'El código de recuperación expiró. Solicitá uno nuevo.',
|
||||||
'reset_code_valid' => 'Código validado correctamente.',
|
'reset_code_valid' => 'Código validado correctamente.',
|
||||||
'invalid_tenant_or_return_url' => 'El tenant o la URL de retorno no son válidos.',
|
'invalid_tenant_or_return_url' => 'El tenant o la URL de retorno no son válidos.',
|
||||||
'request_expired' => 'La solicitud de autenticación expiró. Intenta nuevamente.',
|
'request_expired' => 'La solicitud de autenticación expiró. Intenta nuevamente.',
|
||||||
@@ -34,6 +35,7 @@ return [
|
|||||||
'bundle_variant_forbidden' => 'Un bundle no admite una variante.',
|
'bundle_variant_forbidden' => 'Un bundle no admite una variante.',
|
||||||
'empty_bundle' => 'El bundle no tiene componentes.',
|
'empty_bundle' => 'El bundle no tiene componentes.',
|
||||||
'variant_required' => 'Debe seleccionar una variante para este ítem.',
|
'variant_required' => 'Debe seleccionar una variante para este ítem.',
|
||||||
|
'reservation_expired' => 'La reserva de stock venció. Usá el carrito activo para continuar.',
|
||||||
],
|
],
|
||||||
'purchase' => [
|
'purchase' => [
|
||||||
'expired' => "La compra venci\u{00F3}. Inici\u{00E1} una nueva compra.",
|
'expired' => "La compra venci\u{00F3}. Inici\u{00E1} una nueva compra.",
|
||||||
|
|||||||
@@ -18,7 +18,8 @@
|
|||||||
</include>
|
</include>
|
||||||
</source>
|
</source>
|
||||||
<php>
|
<php>
|
||||||
<env name="APP_ENV" value="testing"/>
|
<env name="APP_ENV" value="testing" force="true"/>
|
||||||
|
<env name="DB_DATABASE" value="shopit_test" force="true"/>
|
||||||
<env name="APP_MAINTENANCE_DRIVER" value="file"/>
|
<env name="APP_MAINTENANCE_DRIVER" value="file"/>
|
||||||
<env name="APP_CONFIG_CACHE" value="bootstrap/cache/phpunit-config.php"/>
|
<env name="APP_CONFIG_CACHE" value="bootstrap/cache/phpunit-config.php"/>
|
||||||
<env name="APP_EVENTS_CACHE" value="bootstrap/cache/phpunit-events.php"/>
|
<env name="APP_EVENTS_CACHE" value="bootstrap/cache/phpunit-events.php"/>
|
||||||
|
|||||||
@@ -47,11 +47,7 @@
|
|||||||
<td>{{ $sale->created_at?->copy()->timezone($timeZone)->format('d/m/Y H:i') ?? '-' }}</td>
|
<td>{{ $sale->created_at?->copy()->timezone($timeZone)->format('d/m/Y H:i') ?? '-' }}</td>
|
||||||
<td>{{ $sale->nombre_apellido ?: 'Sin nombre' }}</td>
|
<td>{{ $sale->nombre_apellido ?: 'Sin nombre' }}</td>
|
||||||
<td class="center">{{ (int) ($sale->quantity ?? 0) }}</td>
|
<td class="center">{{ (int) ($sale->quantity ?? 0) }}</td>
|
||||||
<td>{{ match ($sale->status) {
|
<td>{{ \App\Domains\Purchase\Models\Purchase::adminStatusNameFor($sale->status) ?? $sale->status }}</td>
|
||||||
'paid' => 'Confirmado',
|
|
||||||
'created', 'pending_payment' => 'Esperando pago',
|
|
||||||
default => 'Anulado',
|
|
||||||
} }}</td>
|
|
||||||
<td class="number">${{ number_format((float) $sale->total, 2, ',', '.') }}</td>
|
<td class="number">${{ number_format((float) $sale->total, 2, ',', '.') }}</td>
|
||||||
<td class="center">{{ (int) ($sale->tickets_count ?? 0) }}</td>
|
<td class="center">{{ (int) ($sale->tickets_count ?? 0) }}</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
|||||||
57
resources/views/pdf/adminapp/tickets.blade.php
Normal file
57
resources/views/pdf/adminapp/tickets.blade.php
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="es">
|
||||||
|
<head>
|
||||||
|
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
|
||||||
|
<style>
|
||||||
|
@page { margin: 28px 34px 58px; }
|
||||||
|
body { color: #17211b; font-family: DejaVu Sans, sans-serif; font-size: 11px; margin: 0; }
|
||||||
|
h1 { font-size: 21px; margin: 0 0 3px; }
|
||||||
|
.subtitle { color: #66736b; margin: 0 0 15px; }
|
||||||
|
.summary { background: #eef5f1; border-left: 4px solid #198754; margin-bottom: 14px; padding: 8px 11px; }
|
||||||
|
.summary strong { font-size: 12px; }
|
||||||
|
table { border-collapse: collapse; width: 100%; }
|
||||||
|
thead { display: table-header-group; }
|
||||||
|
tr { page-break-inside: avoid; }
|
||||||
|
th { background: #26382e; color: #fff; font-size: 11px; letter-spacing: .25px; padding: 6px 5px; text-align: left; text-transform: uppercase; }
|
||||||
|
td { border-bottom: 1px solid #dfe7e2; overflow-wrap: break-word; padding: 6px 5px; vertical-align: top; }
|
||||||
|
tbody tr:nth-child(even) { background: #f7f9f8; }
|
||||||
|
.number { text-align: right; }
|
||||||
|
.ticket-id { font-size: 11px; word-break: break-all; }
|
||||||
|
.empty { color: #66736b; padding: 24px; text-align: center; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>Listado de tickets</h1>
|
||||||
|
<p class="subtitle">{{ $tenant->nombre }} · Generado el {{ $generatedAt->copy()->timezone($timeZone)->format('d/m/Y H:i') }}</p>
|
||||||
|
|
||||||
|
<div class="summary">
|
||||||
|
Tickets incluidos: <strong>{{ $tickets->count() }}</strong>
|
||||||
|
·
|
||||||
|
Escaneados: <strong>{{ $tickets->where('status', 'Usado')->count() }}</strong>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
@foreach ($columns as $column)
|
||||||
|
<th @class(['number' => $column['type'] === 'currency'])>{{ $column['label'] }}</th>
|
||||||
|
@endforeach
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
@forelse ($tickets as $ticket)
|
||||||
|
<tr>
|
||||||
|
@foreach ($columns as $column)
|
||||||
|
<td @class([
|
||||||
|
'number' => $column['type'] === 'currency',
|
||||||
|
'ticket-id' => $column['key'] === 'ticket',
|
||||||
|
])>{{ $ticket[$column['key']] }}</td>
|
||||||
|
@endforeach
|
||||||
|
</tr>
|
||||||
|
@empty
|
||||||
|
<tr><td class="empty" colspan="{{ count($columns) }}">No hay tickets para los criterios seleccionados.</td></tr>
|
||||||
|
@endforelse
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -15,7 +15,9 @@ Artisan::command('reservations:expire', function (): void {
|
|||||||
$expired = app(ExpireStockReservationsService::class)->expireOverdue();
|
$expired = app(ExpireStockReservationsService::class)->expireOverdue();
|
||||||
|
|
||||||
$this->info("Expired purchases: {$expired['purchases']}");
|
$this->info("Expired purchases: {$expired['purchases']}");
|
||||||
$this->info("Expired cart items: {$expired['cart_items']}");
|
$this->info("Expired cart reservations: {$expired['cart_reservations']}");
|
||||||
|
$this->info("Expired orphan reservations: {$expired['orphan_reservations']}");
|
||||||
|
$this->info("Failed reservations: {$expired['failed']}");
|
||||||
})->purpose('Release expired stock reservations from purchases and abandoned carts');
|
})->purpose('Release expired stock reservations from purchases and abandoned carts');
|
||||||
|
|
||||||
Schedule::command('reservations:expire')
|
Schedule::command('reservations:expire')
|
||||||
|
|||||||
@@ -69,6 +69,10 @@ class CreateResetPasswordAttemptControllerTest extends TestCase
|
|||||||
$this->assertTrue($attempt->user->is($user));
|
$this->assertTrue($attempt->user->is($user));
|
||||||
$this->assertMatchesRegularExpression('/^\d{4}$/', $attempt->codigo);
|
$this->assertMatchesRegularExpression('/^\d{4}$/', $attempt->codigo);
|
||||||
$this->assertSame(ResetPasswordAttempt::STATUS_PENDING, $attempt->status);
|
$this->assertSame(ResetPasswordAttempt::STATUS_PENDING, $attempt->status);
|
||||||
|
$this->assertTrue($attempt->expires_at->between(
|
||||||
|
now()->addMinutes(59),
|
||||||
|
now()->addMinutes(60),
|
||||||
|
));
|
||||||
Event::assertDispatched(
|
Event::assertDispatched(
|
||||||
PasswordResetRequested::class,
|
PasswordResetRequested::class,
|
||||||
fn (PasswordResetRequested $event): bool => $event->attemptId === $attempt->id
|
fn (PasswordResetRequested $event): bool => $event->attemptId === $attempt->id
|
||||||
|
|||||||
@@ -18,7 +18,9 @@ class ResetPasswordAttemptTest extends TestCase
|
|||||||
'id',
|
'id',
|
||||||
'user_id',
|
'user_id',
|
||||||
'codigo',
|
'codigo',
|
||||||
|
'reason',
|
||||||
'status',
|
'status',
|
||||||
|
'expires_at',
|
||||||
], Schema::getColumnListing('reset_password_attempts'));
|
], Schema::getColumnListing('reset_password_attempts'));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -28,12 +30,14 @@ class ResetPasswordAttemptTest extends TestCase
|
|||||||
|
|
||||||
$attempt = $user->resetPasswordAttempts()->create([
|
$attempt = $user->resetPasswordAttempts()->create([
|
||||||
'codigo' => '123456',
|
'codigo' => '123456',
|
||||||
|
'expires_at' => now()->addHour(),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$this->assertSame(ResetPasswordAttempt::STATUS_PENDING, $attempt->status);
|
$this->assertSame(ResetPasswordAttempt::STATUS_PENDING, $attempt->status);
|
||||||
$this->assertTrue($attempt->user->is($user));
|
$this->assertTrue($attempt->user->is($user));
|
||||||
$this->assertTrue($user->resetPasswordAttempts->contains($attempt));
|
$this->assertTrue($user->resetPasswordAttempts->contains($attempt));
|
||||||
$this->assertFalse($attempt->usesTimestamps());
|
$this->assertFalse($attempt->usesTimestamps());
|
||||||
|
$this->assertTrue($attempt->expires_at->isFuture());
|
||||||
$this->assertArrayNotHasKey('codigo', $attempt->toArray());
|
$this->assertArrayNotHasKey('codigo', $attempt->toArray());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -99,6 +99,30 @@ class ResetPasswordControllerTest extends TestCase
|
|||||||
$this->assertSame(ResetPasswordAttempt::STATUS_USED, $attempt->fresh()->status);
|
$this->assertSame(ResetPasswordAttempt::STATUS_USED, $attempt->fresh()->status);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function test_an_expired_validated_attempt_cannot_reset_the_password(): void
|
||||||
|
{
|
||||||
|
$user = User::factory()->create([
|
||||||
|
'email' => 'ada@example.com',
|
||||||
|
'password' => 'OldSecret!123',
|
||||||
|
]);
|
||||||
|
$attempt = $user->resetPasswordAttempts()->create([
|
||||||
|
'codigo' => '1234',
|
||||||
|
'status' => ResetPasswordAttempt::STATUS_VALIDATED,
|
||||||
|
'expires_at' => now()->subSecond(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->postJson('/api/password/reset', [
|
||||||
|
'email' => 'ada@example.com',
|
||||||
|
'codigo' => '1234',
|
||||||
|
'password' => 'NewSecret!456',
|
||||||
|
'password_confirmation' => 'NewSecret!456',
|
||||||
|
])->assertUnprocessable()
|
||||||
|
->assertJsonValidationErrors('codigo');
|
||||||
|
|
||||||
|
$this->assertTrue(Hash::check('OldSecret!123', $user->fresh()->password));
|
||||||
|
$this->assertSame(ResetPasswordAttempt::STATUS_EXPIRED, $attempt->fresh()->status);
|
||||||
|
}
|
||||||
|
|
||||||
public function test_it_validates_password_confirmation_and_strength(): void
|
public function test_it_validates_password_confirmation_and_strength(): void
|
||||||
{
|
{
|
||||||
$this->postJson('/api/password/reset', [
|
$this->postJson('/api/password/reset', [
|
||||||
|
|||||||
@@ -49,6 +49,27 @@ class ValidateResetPasswordAttemptControllerTest extends TestCase
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function test_it_expires_an_attempt_and_returns_the_expired_code_message(): void
|
||||||
|
{
|
||||||
|
$user = User::factory()->create(['email' => 'ada@example.com']);
|
||||||
|
$attempt = $user->resetPasswordAttempts()->create([
|
||||||
|
'codigo' => '1234',
|
||||||
|
'expires_at' => now()->subSecond(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->postJson('/api/password/reset-attempts/validate', [
|
||||||
|
'email' => 'ada@example.com',
|
||||||
|
'codigo' => '1234',
|
||||||
|
])->assertUnprocessable()
|
||||||
|
->assertJsonValidationErrors('codigo')
|
||||||
|
->assertJsonPath('errors.codigo.0', __('api.auth.reset_code_expired'));
|
||||||
|
|
||||||
|
$this->assertSame(
|
||||||
|
ResetPasswordAttempt::STATUS_EXPIRED,
|
||||||
|
$attempt->fresh()->status,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
public function test_it_rejects_an_expired_or_already_validated_attempt(): void
|
public function test_it_rejects_an_expired_or_already_validated_attempt(): void
|
||||||
{
|
{
|
||||||
$user = User::factory()->create(['email' => 'ada@example.com']);
|
$user = User::factory()->create(['email' => 'ada@example.com']);
|
||||||
|
|||||||
@@ -5,10 +5,12 @@ namespace Tests\Feature\Cart;
|
|||||||
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\Auth\Models\User;
|
use App\Domains\Auth\Models\User;
|
||||||
|
use App\Domains\Cart\Models\Cart;
|
||||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Catalog\Models\CatalogItem;
|
||||||
use App\Domains\Catalog\Models\Inventory;
|
use App\Domains\Catalog\Models\Inventory;
|
||||||
use App\Domains\Catalog\Models\Variant;
|
use App\Domains\Catalog\Models\Variant;
|
||||||
|
use App\Domains\Catalog\Services\CatalogService;
|
||||||
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\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
@@ -28,6 +30,81 @@ class CartControllerTest extends TestCase
|
|||||||
]));
|
]));
|
||||||
$this->assertFalse(Schema::hasColumn('carrito_items', 'buyable_type'));
|
$this->assertFalse(Schema::hasColumn('carrito_items', 'buyable_type'));
|
||||||
$this->assertFalse(Schema::hasColumn('carrito_items', 'buyable_id'));
|
$this->assertFalse(Schema::hasColumn('carrito_items', 'buyable_id'));
|
||||||
|
$this->assertTrue(Schema::hasColumns('stock_reservations', [
|
||||||
|
'status',
|
||||||
|
'expires_at',
|
||||||
|
'committed_at',
|
||||||
|
'released_at',
|
||||||
|
'expired_at',
|
||||||
|
'release_reason',
|
||||||
|
]));
|
||||||
|
$this->assertFalse(Schema::hasColumn('stock_reservations', 'quantity'));
|
||||||
|
$this->assertTrue(Schema::hasColumns('stock_reservation_lines', [
|
||||||
|
'stock_reservation_id',
|
||||||
|
'inventory_id',
|
||||||
|
'quantity',
|
||||||
|
'tracks_inventory',
|
||||||
|
]));
|
||||||
|
$this->assertTrue(Schema::hasColumn('carritos', 'current_stock_reservation_id'));
|
||||||
|
$this->assertTrue(Schema::hasColumn('compras', 'stock_reservation_id'));
|
||||||
|
$this->assertFalse(Schema::hasColumn('compras', 'expires_at'));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_it_aggregates_shared_inventory_into_one_cart_reservation_line(): void
|
||||||
|
{
|
||||||
|
$tenant = $this->createTenant('acme');
|
||||||
|
$firstItem = $this->createDirectItem($tenant, 10, '10.00');
|
||||||
|
$secondItem = app(CatalogService::class)->create([
|
||||||
|
'tenant_code' => $tenant->codigo,
|
||||||
|
'type' => 'bundle',
|
||||||
|
'slug' => 'second-shared-item',
|
||||||
|
'nombre' => 'Second shared item',
|
||||||
|
'precio' => '20.00',
|
||||||
|
'components' => [[
|
||||||
|
'catalog_item_id' => $firstItem->id,
|
||||||
|
'quantity' => 1,
|
||||||
|
]],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$firstResponse = $this->postJson('/api/tenants/acme/cart/items', [
|
||||||
|
'catalog_item_id' => $firstItem->id,
|
||||||
|
'cantidad' => 2,
|
||||||
|
])->assertOk();
|
||||||
|
$guestToken = $firstResponse->getCookie('guest_token', false)?->getValue();
|
||||||
|
|
||||||
|
$this->call(
|
||||||
|
'POST',
|
||||||
|
'/api/tenants/acme/cart/items',
|
||||||
|
[],
|
||||||
|
['guest_token' => $guestToken],
|
||||||
|
[],
|
||||||
|
['HTTP_Accept' => 'application/json', 'CONTENT_TYPE' => 'application/json'],
|
||||||
|
json_encode([
|
||||||
|
'catalog_item_id' => $secondItem->id,
|
||||||
|
'cantidad' => 3,
|
||||||
|
]),
|
||||||
|
)->assertOk();
|
||||||
|
|
||||||
|
$reservationId = (int) $firstResponse->json('data.id');
|
||||||
|
$reservationId = (int) Cart::query()
|
||||||
|
->findOrFail($reservationId)
|
||||||
|
->current_stock_reservation_id;
|
||||||
|
|
||||||
|
$this->assertDatabaseCount('stock_reservations', 1);
|
||||||
|
$this->assertDatabaseHas('stock_reservations', [
|
||||||
|
'id' => $reservationId,
|
||||||
|
'status' => 'active',
|
||||||
|
]);
|
||||||
|
$this->assertDatabaseHas('stock_reservation_lines', [
|
||||||
|
'stock_reservation_id' => $reservationId,
|
||||||
|
'inventory_id' => $firstItem->inventory_id,
|
||||||
|
'quantity' => 5,
|
||||||
|
]);
|
||||||
|
$this->assertDatabaseCount('stock_reservation_lines', 1);
|
||||||
|
$this->assertDatabaseHas('inventories', [
|
||||||
|
'id' => $firstItem->inventory_id,
|
||||||
|
'reserved_stock' => 5,
|
||||||
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_it_adds_a_catalog_item_without_a_variant(): void
|
public function test_it_adds_a_catalog_item_without_a_variant(): void
|
||||||
@@ -74,9 +151,11 @@ class CartControllerTest extends TestCase
|
|||||||
'id' => $item->inventory_id,
|
'id' => $item->inventory_id,
|
||||||
'reserved_stock' => 2,
|
'reserved_stock' => 2,
|
||||||
]);
|
]);
|
||||||
$this->assertDatabaseHas('stock_reservations', [
|
$this->assertDatabaseHas('stock_reservation_lines', [
|
||||||
'inventory_id' => $item->inventory_id,
|
'inventory_id' => $item->inventory_id,
|
||||||
'quantity' => 2,
|
'quantity' => 2,
|
||||||
|
]);
|
||||||
|
$this->assertDatabaseHas('stock_reservations', [
|
||||||
'status' => 'active',
|
'status' => 'active',
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
@@ -96,38 +175,44 @@ class CartControllerTest extends TestCase
|
|||||||
])->assertOk();
|
])->assertOk();
|
||||||
|
|
||||||
$this->assertDatabaseHas('stock_reservations', [
|
$this->assertDatabaseHas('stock_reservations', [
|
||||||
'inventory_id' => $item->inventory_id,
|
|
||||||
'quantity' => 2,
|
|
||||||
'status' => 'active',
|
'status' => 'active',
|
||||||
'expires_at' => $now->copy()->addMinutes(45)->toDateTimeString(),
|
'expires_at' => $now->copy()->addMinutes(45)->toDateTimeString(),
|
||||||
]);
|
]);
|
||||||
|
$this->assertDatabaseHas('stock_reservation_lines', [
|
||||||
|
'inventory_id' => $item->inventory_id,
|
||||||
|
'quantity' => 2,
|
||||||
|
]);
|
||||||
|
|
||||||
$this->travelBack();
|
$this->travelBack();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_it_expires_abandoned_cart_reservations_and_removes_empty_carts(): void
|
public function test_it_expires_a_cart_reservation_and_automatically_replaces_the_cart(): void
|
||||||
{
|
{
|
||||||
config()->set('catalog.stock_reservation_expiration_minutes', 30);
|
config()->set('catalog.stock_reservation_expiration_minutes', 30);
|
||||||
$tenant = $this->createTenant('acme');
|
$tenant = $this->createTenant('acme');
|
||||||
|
$user = User::factory()->create();
|
||||||
$item = $this->createDirectItem($tenant, 10, '49.90');
|
$item = $this->createDirectItem($tenant, 10, '49.90');
|
||||||
|
|
||||||
$response = $this->postJson('/api/tenants/acme/cart/items', [
|
$response = $this->actingAs($user, 'sanctum')
|
||||||
|
->postJson('/api/tenants/acme/cart/items', [
|
||||||
'catalog_item_id' => $item->id,
|
'catalog_item_id' => $item->id,
|
||||||
'cantidad' => 2,
|
'cantidad' => 2,
|
||||||
])->assertOk();
|
])->assertOk();
|
||||||
$cartId = $response->json('data.id');
|
$cartId = $response->json('data.id');
|
||||||
$cartItemId = $response->json('data.items.0.id');
|
$cartItemId = $response->json('data.items.0.id');
|
||||||
|
$cart = Cart::query()->findOrFail($cartId);
|
||||||
|
$reservationId = $cart->current_stock_reservation_id;
|
||||||
|
|
||||||
$this->artisan('reservations:expire')
|
$this->artisan('reservations:expire')
|
||||||
->expectsOutput('Expired purchases: 0')
|
->expectsOutput('Expired purchases: 0')
|
||||||
->expectsOutput('Expired cart items: 0')
|
->expectsOutput('Expired cart reservations: 0')
|
||||||
->assertSuccessful();
|
->assertSuccessful();
|
||||||
|
|
||||||
$this->travel(31)->minutes();
|
$this->travel(31)->minutes();
|
||||||
|
|
||||||
$this->artisan('reservations:expire')
|
$this->artisan('reservations:expire')
|
||||||
->expectsOutput('Expired purchases: 0')
|
->expectsOutput('Expired purchases: 0')
|
||||||
->expectsOutput('Expired cart items: 1')
|
->expectsOutput('Expired cart reservations: 1')
|
||||||
->assertSuccessful();
|
->assertSuccessful();
|
||||||
|
|
||||||
$this->assertDatabaseHas('inventories', [
|
$this->assertDatabaseHas('inventories', [
|
||||||
@@ -135,28 +220,141 @@ class CartControllerTest extends TestCase
|
|||||||
'real_stock' => 10,
|
'real_stock' => 10,
|
||||||
'reserved_stock' => 0,
|
'reserved_stock' => 0,
|
||||||
]);
|
]);
|
||||||
$this->assertDatabaseMissing('carrito_items', ['id' => $cartItemId]);
|
$this->assertDatabaseHas('carrito_items', ['id' => $cartItemId]);
|
||||||
$this->assertSoftDeleted('carritos', [
|
$this->assertDatabaseHas('carritos', [
|
||||||
'id' => $cartId,
|
'id' => $cartId,
|
||||||
'status' => 'expired',
|
'status' => Cart::STATUS_EXPIRED,
|
||||||
|
'current_stock_reservation_id' => $reservationId,
|
||||||
|
'deleted_at' => null,
|
||||||
]);
|
]);
|
||||||
$this->assertDatabaseHas('stock_reservations', [
|
$this->assertDatabaseHas('stock_reservations', [
|
||||||
'inventory_id' => $item->inventory_id,
|
'id' => $reservationId,
|
||||||
'cart_item_id' => null,
|
|
||||||
'purchase_id' => null,
|
|
||||||
'quantity' => 0,
|
|
||||||
'status' => 'expired',
|
'status' => 'expired',
|
||||||
'expires_at' => null,
|
'expires_at' => null,
|
||||||
]);
|
]);
|
||||||
|
$this->assertDatabaseHas('stock_reservation_lines', [
|
||||||
|
'inventory_id' => $item->inventory_id,
|
||||||
|
'quantity' => 2,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$currentCart = $this->getJson('/api/tenants/acme/cart')
|
||||||
|
->assertOk()
|
||||||
|
->assertJsonPath('data.status', Cart::STATUS_ACTIVE)
|
||||||
|
->assertJsonPath('data.items', [])
|
||||||
|
->assertJsonMissingPath('data.stock_reservation')
|
||||||
|
->assertJsonMissingPath('data.current_stock_reservation_id');
|
||||||
|
$newCartId = $currentCart->json('data.id');
|
||||||
|
|
||||||
|
$this->assertNotSame($cartId, $newCartId);
|
||||||
|
$this->assertDatabaseHas('carritos', [
|
||||||
|
'id' => $cartId,
|
||||||
|
'status' => Cart::STATUS_ABANDONED,
|
||||||
|
'current_stock_reservation_id' => $reservationId,
|
||||||
|
]);
|
||||||
|
$this->assertDatabaseHas('carritos', [
|
||||||
|
'id' => $newCartId,
|
||||||
|
'status' => Cart::STATUS_ACTIVE,
|
||||||
|
'current_stock_reservation_id' => null,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->postJson('/api/tenants/acme/cart/items', [
|
||||||
|
'catalog_item_id' => $item->id,
|
||||||
|
'cantidad' => 1,
|
||||||
|
])
|
||||||
|
->assertOk()
|
||||||
|
->assertJsonPath('data.id', $newCartId)
|
||||||
|
->assertJsonPath('data.items.0.cantidad', 1);
|
||||||
|
|
||||||
$this->artisan('reservations:expire')
|
$this->artisan('reservations:expire')
|
||||||
->expectsOutput('Expired purchases: 0')
|
->expectsOutput('Expired purchases: 0')
|
||||||
->expectsOutput('Expired cart items: 0')
|
->expectsOutput('Expired cart reservations: 0')
|
||||||
->assertSuccessful();
|
->assertSuccessful();
|
||||||
|
|
||||||
$this->travelBack();
|
$this->travelBack();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function test_it_replaces_an_overdue_cart_before_the_expiration_job_runs(): void
|
||||||
|
{
|
||||||
|
config()->set('catalog.stock_reservation_expiration_minutes', 30);
|
||||||
|
$tenant = $this->createTenant('acme');
|
||||||
|
$user = User::factory()->create();
|
||||||
|
$item = $this->createDirectItem($tenant, 10, '49.90');
|
||||||
|
|
||||||
|
$original = $this->actingAs($user, 'sanctum')
|
||||||
|
->postJson('/api/tenants/acme/cart/items', [
|
||||||
|
'catalog_item_id' => $item->id,
|
||||||
|
'cantidad' => 2,
|
||||||
|
])->assertOk();
|
||||||
|
$originalCartId = $original->json('data.id');
|
||||||
|
|
||||||
|
$this->travel(31)->minutes();
|
||||||
|
|
||||||
|
$replacement = $this->postJson('/api/tenants/acme/cart/items', [
|
||||||
|
'catalog_item_id' => $item->id,
|
||||||
|
'cantidad' => 1,
|
||||||
|
])
|
||||||
|
->assertOk()
|
||||||
|
->assertJsonPath('data.status', Cart::STATUS_ACTIVE)
|
||||||
|
->assertJsonPath('data.items.0.cantidad', 1);
|
||||||
|
|
||||||
|
$this->assertNotSame($originalCartId, $replacement->json('data.id'));
|
||||||
|
$this->assertDatabaseHas('carritos', [
|
||||||
|
'id' => $originalCartId,
|
||||||
|
'status' => Cart::STATUS_ABANDONED,
|
||||||
|
]);
|
||||||
|
$this->assertDatabaseHas('inventories', [
|
||||||
|
'id' => $item->inventory_id,
|
||||||
|
'reserved_stock' => 1,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->travelBack();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_expired_cart_mutations_return_the_expiration_error_instead_of_not_found(): void
|
||||||
|
{
|
||||||
|
config()->set('catalog.stock_reservation_expiration_minutes', 30);
|
||||||
|
$tenant = $this->createTenant('acme');
|
||||||
|
$user = User::factory()->create();
|
||||||
|
[$item, $firstVariant] = $this->createVariantItem($tenant, 10, '49.90');
|
||||||
|
$secondInventory = Inventory::query()->create(['real_stock' => 10]);
|
||||||
|
$secondVariant = $item->variants()->create(['inventory_id' => $secondInventory->id]);
|
||||||
|
|
||||||
|
$cartItemId = $this->actingAs($user, 'sanctum')
|
||||||
|
->postJson('/api/tenants/acme/cart/items', [
|
||||||
|
'catalog_item_id' => $item->id,
|
||||||
|
'variant_id' => $firstVariant->id,
|
||||||
|
'cantidad' => 2,
|
||||||
|
])
|
||||||
|
->assertOk()
|
||||||
|
->json('data.items.0.id');
|
||||||
|
|
||||||
|
$this->travel(31)->minutes();
|
||||||
|
|
||||||
|
$expectedError = [
|
||||||
|
'code' => 'stock_reservation.expired',
|
||||||
|
'message' => __('api.cart.reservation_expired'),
|
||||||
|
];
|
||||||
|
|
||||||
|
$this->patchJson("/api/tenants/acme/cart/items/{$cartItemId}", [
|
||||||
|
'cantidad' => 3,
|
||||||
|
])
|
||||||
|
->assertUnprocessable()
|
||||||
|
->assertExactJson($expectedError);
|
||||||
|
|
||||||
|
$this->patchJson("/api/tenants/acme/cart/items/{$cartItemId}", [
|
||||||
|
'cantidad' => 2,
|
||||||
|
'variant_id' => $secondVariant->id,
|
||||||
|
])
|
||||||
|
->assertUnprocessable()
|
||||||
|
->assertExactJson($expectedError);
|
||||||
|
|
||||||
|
$this->deleteJson("/api/tenants/acme/cart/items/{$cartItemId}")
|
||||||
|
->assertUnprocessable()
|
||||||
|
->assertExactJson($expectedError);
|
||||||
|
|
||||||
|
$this->travelBack();
|
||||||
|
}
|
||||||
|
|
||||||
public function test_it_filters_item_images_when_the_tenant_disables_them(): void
|
public function test_it_filters_item_images_when_the_tenant_disables_them(): void
|
||||||
{
|
{
|
||||||
$tenant = $this->createTenant('acme');
|
$tenant = $this->createTenant('acme');
|
||||||
@@ -212,10 +410,11 @@ class CartControllerTest extends TestCase
|
|||||||
'id' => $variant->inventory_id,
|
'id' => $variant->inventory_id,
|
||||||
'reserved_stock' => 5,
|
'reserved_stock' => 5,
|
||||||
]);
|
]);
|
||||||
$this->assertDatabaseHas('stock_reservations', [
|
$this->assertDatabaseHas('stock_reservation_lines', [
|
||||||
'cart_item_id' => $response->json('data.items.0.id'),
|
|
||||||
'inventory_id' => $variant->inventory_id,
|
'inventory_id' => $variant->inventory_id,
|
||||||
'quantity' => 5,
|
'quantity' => 5,
|
||||||
|
]);
|
||||||
|
$this->assertDatabaseHas('stock_reservations', [
|
||||||
'status' => 'active',
|
'status' => 'active',
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
@@ -229,6 +428,7 @@ class CartControllerTest extends TestCase
|
|||||||
$this->createPurchaseItem($tenant, $user, $item, 1);
|
$this->createPurchaseItem($tenant, $user, $item, 1);
|
||||||
|
|
||||||
$this->actingAs($user, 'sanctum')
|
$this->actingAs($user, 'sanctum')
|
||||||
|
->withHeader('Accept-Language', 'es')
|
||||||
->postJson('/api/tenants/acme/cart/items', [
|
->postJson('/api/tenants/acme/cart/items', [
|
||||||
'catalog_item_id' => $item->id,
|
'catalog_item_id' => $item->id,
|
||||||
'cantidad' => 2,
|
'cantidad' => 2,
|
||||||
@@ -237,6 +437,7 @@ class CartControllerTest extends TestCase
|
|||||||
->assertJsonPath('data.items.0.cantidad', 2);
|
->assertJsonPath('data.items.0.cantidad', 2);
|
||||||
|
|
||||||
$this->actingAs($user, 'sanctum')
|
$this->actingAs($user, 'sanctum')
|
||||||
|
->withHeader('Accept-Language', 'es')
|
||||||
->postJson('/api/tenants/acme/cart/items', [
|
->postJson('/api/tenants/acme/cart/items', [
|
||||||
'catalog_item_id' => $item->id,
|
'catalog_item_id' => $item->id,
|
||||||
'cantidad' => 2,
|
'cantidad' => 2,
|
||||||
@@ -381,10 +582,12 @@ class CartControllerTest extends TestCase
|
|||||||
'reserved_stock' => 0,
|
'reserved_stock' => 0,
|
||||||
]);
|
]);
|
||||||
$this->assertDatabaseHas('stock_reservations', [
|
$this->assertDatabaseHas('stock_reservations', [
|
||||||
'cart_item_id' => null,
|
|
||||||
'inventory_id' => $variant->inventory_id,
|
|
||||||
'quantity' => 0,
|
|
||||||
'status' => 'released',
|
'status' => 'released',
|
||||||
|
'release_reason' => 'cart_empty',
|
||||||
|
]);
|
||||||
|
$this->assertDatabaseHas('stock_reservation_lines', [
|
||||||
|
'inventory_id' => $variant->inventory_id,
|
||||||
|
'quantity' => 5,
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
namespace Tests\Feature\Forms;
|
namespace Tests\Feature\Forms;
|
||||||
|
|
||||||
|
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\Authorization\Enums\RoleCode;
|
use App\Domains\Authorization\Enums\RoleCode;
|
||||||
use App\Domains\Purchase\Models\Purchase;
|
use App\Domains\Purchase\Models\Purchase;
|
||||||
@@ -34,12 +36,7 @@ class AdminAppSaleFormControllerTest extends TestCase
|
|||||||
|
|
||||||
public function test_an_adminapp_user_can_get_the_sale_form(): void
|
public function test_an_adminapp_user_can_get_the_sale_form(): void
|
||||||
{
|
{
|
||||||
$tenant = Tenant::query()->create([
|
$tenant = $this->createTenant('acme');
|
||||||
'codigo' => 'acme',
|
|
||||||
'nombre' => 'Acme',
|
|
||||||
'dominio' => 'acme.test',
|
|
||||||
'website_type_code' => 'onticket',
|
|
||||||
]);
|
|
||||||
Sanctum::actingAs(User::factory()->create([
|
Sanctum::actingAs(User::factory()->create([
|
||||||
'rol_codigo' => RoleCode::AdminApp->value,
|
'rol_codigo' => RoleCode::AdminApp->value,
|
||||||
'tenant_codigo' => $tenant->codigo,
|
'tenant_codigo' => $tenant->codigo,
|
||||||
@@ -47,13 +44,15 @@ class AdminAppSaleFormControllerTest extends TestCase
|
|||||||
|
|
||||||
$this->getJson('/api/v1/adminapp/forms/sale')
|
$this->getJson('/api/v1/adminapp/forms/sale')
|
||||||
->assertOk()
|
->assertOk()
|
||||||
->assertJsonCount(count(Purchase::statuses()), 'data.statuses')
|
->assertJsonCount(count(Purchase::adminStatusCodes()), 'data.statuses')
|
||||||
->assertJsonPath('data.statuses.0.code', Purchase::STATUS_CREATED)
|
->assertJsonPath('data.statuses.0.value', Purchase::ADMIN_STATUS_INCOMPLETE)
|
||||||
->assertJsonPath('data.statuses.0.name', 'Creada')
|
->assertJsonPath('data.statuses.0.label', 'Por completar datos')
|
||||||
->assertJsonPath('data.statuses.1.code', Purchase::STATUS_PENDING_PAYMENT)
|
->assertJsonPath('data.statuses.0.real_statuses.0', Purchase::STATUS_CREATED)
|
||||||
->assertJsonPath('data.statuses.2.code', Purchase::STATUS_IN_REVIEW)
|
->assertJsonPath('data.statuses.1.value', Purchase::ADMIN_STATUS_AWAITING_PAYMENT)
|
||||||
->assertJsonPath('data.statuses.3.code', Purchase::STATUS_PAID)
|
->assertJsonPath('data.statuses.1.real_statuses.0', Purchase::STATUS_PENDING_PAYMENT)
|
||||||
->assertJsonPath('data.statuses.6.code', Purchase::STATUS_EXPIRED);
|
->assertJsonPath('data.statuses.1.real_statuses.1', Purchase::STATUS_IN_REVIEW)
|
||||||
|
->assertJsonPath('data.statuses.2.value', Purchase::ADMIN_STATUS_CONFIRMED)
|
||||||
|
->assertJsonPath('data.statuses.3.value', Purchase::ADMIN_STATUS_CANCELLED);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_a_customer_cannot_get_the_sale_form(): void
|
public function test_a_customer_cannot_get_the_sale_form(): void
|
||||||
@@ -65,4 +64,34 @@ class AdminAppSaleFormControllerTest extends TestCase
|
|||||||
|
|
||||||
$this->getJson('/api/v1/adminapp/forms/sale')->assertForbidden();
|
$this->getJson('/api/v1/adminapp/forms/sale')->assertForbidden();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function createTenant(string $code): Tenant
|
||||||
|
{
|
||||||
|
$headerLogo = $this->createAttachment("{$code}-header");
|
||||||
|
$footerLogo = $this->createAttachment("{$code}-footer");
|
||||||
|
|
||||||
|
return Tenant::query()->create([
|
||||||
|
'codigo' => $code,
|
||||||
|
'nombre' => ucfirst($code),
|
||||||
|
'dominio' => "{$code}.test",
|
||||||
|
'primary_color' => '#000000',
|
||||||
|
'secondary_color' => '#ffffff',
|
||||||
|
'danger_color' => '#dc3545',
|
||||||
|
'header_bg_color' => '#ffffff',
|
||||||
|
'footer_bg_color' => '#000000',
|
||||||
|
'header_logo_id' => $headerLogo->id,
|
||||||
|
'footer_logo_id' => $footerLogo->id,
|
||||||
|
'website_type_code' => 'onticket',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function createAttachment(string $name): Attachment
|
||||||
|
{
|
||||||
|
return Attachment::query()->create([
|
||||||
|
'path' => "test/{$name}.png",
|
||||||
|
'filename' => "{$name}.png",
|
||||||
|
'type' => AttachmentType::Image,
|
||||||
|
'mime_type' => 'image/png',
|
||||||
|
]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
357
tests/Feature/Forms/AdminAppTicketFilterFormControllerTest.php
Normal file
357
tests/Feature/Forms/AdminAppTicketFilterFormControllerTest.php
Normal file
@@ -0,0 +1,357 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Tests\Feature\Forms;
|
||||||
|
|
||||||
|
use App\Domains\Attachable\Enums\AttachmentType;
|
||||||
|
use App\Domains\Attachable\Models\Attachment;
|
||||||
|
use App\Domains\Auth\Models\User;
|
||||||
|
use App\Domains\Authorization\Enums\RoleCode;
|
||||||
|
use App\Domains\Catalog\Models\CatalogItem;
|
||||||
|
use App\Domains\Catalog\Services\CatalogService;
|
||||||
|
use App\Domains\Menu\Models\Menu;
|
||||||
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
|
use App\Domains\Ticket\Models\Ticket;
|
||||||
|
use Database\Seeders\AttributeSeeder;
|
||||||
|
use Database\Seeders\AuthorizationSeeder;
|
||||||
|
use Database\Seeders\FiestaFutbolInfantilProductSeeder;
|
||||||
|
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Laravel\Sanctum\Sanctum;
|
||||||
|
use Tests\TestCase;
|
||||||
|
|
||||||
|
class AdminAppTicketFilterFormControllerTest extends TestCase
|
||||||
|
{
|
||||||
|
use RefreshDatabase;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
|
||||||
|
$this->seed(AuthorizationSeeder::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_authentication_is_required(): void
|
||||||
|
{
|
||||||
|
$this->getJson('/api/v1/adminapp/forms/tickets-filter')->assertUnauthorized();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_the_tenant_must_have_the_tickets_menu(): void
|
||||||
|
{
|
||||||
|
$tenant = $this->createTenant('tenant_without_tickets');
|
||||||
|
Sanctum::actingAs($this->createAdminAppUser($tenant));
|
||||||
|
|
||||||
|
$this->getJson('/api/v1/adminapp/forms/tickets-filter')->assertNotFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_it_returns_the_common_ticket_filter_fields_for_other_tenants(): void
|
||||||
|
{
|
||||||
|
$tenant = $this->createTenant('another_tenant');
|
||||||
|
$this->grantTicketsMenu($tenant);
|
||||||
|
Sanctum::actingAs($this->createAdminAppUser($tenant));
|
||||||
|
|
||||||
|
$this->getJson('/api/v1/adminapp/forms/tickets-filter')
|
||||||
|
->assertOk()
|
||||||
|
->assertExactJson([
|
||||||
|
'data' => [
|
||||||
|
'code' => 'tickets_filter',
|
||||||
|
'action' => '/api/v1/adminapp/tenant/tickets',
|
||||||
|
'method' => 'GET',
|
||||||
|
'columns' => $this->commonColumns(),
|
||||||
|
'fields' => [
|
||||||
|
[
|
||||||
|
'name' => 'date',
|
||||||
|
'query_param' => 'date',
|
||||||
|
'label' => 'Fecha',
|
||||||
|
'type' => 'date',
|
||||||
|
'required' => false,
|
||||||
|
'default' => null,
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'name' => 'status',
|
||||||
|
'query_param' => 'status',
|
||||||
|
'label' => 'Estado',
|
||||||
|
'type' => 'select',
|
||||||
|
'required' => false,
|
||||||
|
'default' => null,
|
||||||
|
'placeholder' => 'Estado',
|
||||||
|
'options' => [
|
||||||
|
['value' => 'active', 'label' => 'Activo'],
|
||||||
|
['value' => 'used', 'label' => 'Usado'],
|
||||||
|
['value' => 'expired', 'label' => 'Vencido'],
|
||||||
|
],
|
||||||
|
],
|
||||||
|
],
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_it_returns_the_complete_nested_form_for_fiesta_futbol_infantil(): void
|
||||||
|
{
|
||||||
|
$tenant = $this->createFiestaFutbolInfantilTenant();
|
||||||
|
$this->grantTicketsMenu($tenant);
|
||||||
|
$admin = $this->createAdminAppUser($tenant);
|
||||||
|
Sanctum::actingAs($admin);
|
||||||
|
|
||||||
|
$response = $this->getJson('/api/v1/adminapp/forms/tickets-filter')
|
||||||
|
->assertOk()
|
||||||
|
->assertJsonPath('data.fields.0.name', 'category')
|
||||||
|
->assertJsonPath('data.fields.0.query_param', 'category')
|
||||||
|
->assertJsonPath('data.fields.1.name', 'product')
|
||||||
|
->assertJsonPath('data.fields.1.query_param', 'product')
|
||||||
|
->assertJsonPath('data.fields.1.depends_on', 'category')
|
||||||
|
->assertJsonPath('data.fields.2.name', 'type')
|
||||||
|
->assertJsonPath('data.fields.2.query_param', 'type')
|
||||||
|
->assertJsonPath('data.fields.2.depends_on', 'product')
|
||||||
|
->assertJsonPath('data.fields.3.name', 'size')
|
||||||
|
->assertJsonPath('data.fields.3.query_param', 'size')
|
||||||
|
->assertJsonPath('data.fields.3.depends_on', 'type')
|
||||||
|
->assertJsonPath('data.fields.4.name', 'date')
|
||||||
|
->assertJsonPath('data.fields.4.query_param', 'date')
|
||||||
|
->assertJsonPath('data.fields.4.depends_on', 'category')
|
||||||
|
->assertJsonPath('data.fields.5.name', 'status')
|
||||||
|
->assertJsonPath('data.fields.5.query_param', 'status')
|
||||||
|
->assertJsonPath('data.columns.0.key', 'order_number')
|
||||||
|
->assertJsonPath('data.columns.0.sort_param', 'order_number')
|
||||||
|
->assertJsonPath('data.columns.1.key', 'category')
|
||||||
|
->assertJsonPath('data.columns.2.key', 'product')
|
||||||
|
->assertJsonPath('data.columns.2.sortable', false)
|
||||||
|
->assertJsonPath('data.columns.3.key', 'type')
|
||||||
|
->assertJsonPath('data.columns.3.sortable', false)
|
||||||
|
->assertJsonPath('data.columns.4.key', 'date')
|
||||||
|
->assertJsonPath('data.columns.4.sortable', false)
|
||||||
|
->assertJsonPath('data.columns.5.key', 'size')
|
||||||
|
->assertJsonPath('data.columns.5.sortable', false);
|
||||||
|
|
||||||
|
$categories = collect($response->json('data.fields.0.options'));
|
||||||
|
$this->assertSame(
|
||||||
|
['Entradas', 'Camping', 'Comida', 'Merchandising'],
|
||||||
|
$categories->pluck('label')->all(),
|
||||||
|
);
|
||||||
|
|
||||||
|
$entries = $categories->firstWhere('value', 'entradas');
|
||||||
|
$this->assertSame('Abono', $entries['children'][0]['options'][0]['label']);
|
||||||
|
$this->assertTrue($entries['children'][0]['options'][0]['children'][0]['disabled']);
|
||||||
|
$this->assertTrue($entries['children'][1]['disabled']);
|
||||||
|
|
||||||
|
$camping = $categories->firstWhere('value', 'alojamientos');
|
||||||
|
$this->assertSame(
|
||||||
|
['Carpa', 'Motorhome'],
|
||||||
|
collect($camping['children'][0]['options'])->pluck('label')->all(),
|
||||||
|
);
|
||||||
|
$this->assertTrue($camping['children'][0]['options'][0]['children'][0]['disabled']);
|
||||||
|
|
||||||
|
$merchandise = $categories->firstWhere('value', 'merchandising');
|
||||||
|
$merchandiseProduct = $merchandise['children'][0]['options'][0];
|
||||||
|
$this->assertSame('Camiseta', $merchandiseProduct['label']);
|
||||||
|
$this->assertSame(
|
||||||
|
['Verde', 'Blanco'],
|
||||||
|
collect($merchandiseProduct['children'][0]['options'])->pluck('label')->all(),
|
||||||
|
);
|
||||||
|
$this->assertSame(
|
||||||
|
['14', 'S', 'M', 'L', 'XL', 'XXL'],
|
||||||
|
collect($merchandiseProduct['children'][0]['options'][0]['children'][0]['options'])
|
||||||
|
->pluck('label')
|
||||||
|
->all(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_merchandise_sizes_are_scoped_to_the_selected_product_and_color(): void
|
||||||
|
{
|
||||||
|
$tenant = $this->createFiestaFutbolInfantilTenant();
|
||||||
|
$this->grantTicketsMenu($tenant);
|
||||||
|
Sanctum::actingAs($this->createAdminAppUser($tenant));
|
||||||
|
|
||||||
|
$merchandise = CatalogItem::query()
|
||||||
|
->where('tenant_code', $tenant->codigo)
|
||||||
|
->where('slug', 'camiseta')
|
||||||
|
->with([
|
||||||
|
'itemAttributes.attribute.options',
|
||||||
|
'variants.definitions.itemAttribute.attribute.options',
|
||||||
|
])
|
||||||
|
->firstOrFail();
|
||||||
|
$whiteXxl = $merchandise->variants->first(fn ($variant): bool => $variant->selectionValues()->get('color') === 'Blanco'
|
||||||
|
&& $variant->selectionValues()->get('talle') === 'XXL');
|
||||||
|
$this->assertNotNull($whiteXxl);
|
||||||
|
app(CatalogService::class)->deleteVariant($whiteXxl);
|
||||||
|
|
||||||
|
$response = $this->getJson('/api/v1/adminapp/forms/tickets-filter')->assertOk();
|
||||||
|
$merchandiseCategory = collect($response->json('data.fields.0.options'))
|
||||||
|
->firstWhere('value', 'merchandising');
|
||||||
|
$product = $merchandiseCategory['children'][0]['options'][0];
|
||||||
|
$colors = collect($product['children'][0]['options']);
|
||||||
|
$greenSizes = collect($colors->firstWhere('value', 'Verde')['children'][0]['options'])
|
||||||
|
->pluck('value');
|
||||||
|
$whiteSizes = collect($colors->firstWhere('value', 'Blanco')['children'][0]['options'])
|
||||||
|
->pluck('value');
|
||||||
|
|
||||||
|
$this->assertContains('XXL', $greenSizes);
|
||||||
|
$this->assertNotContains('XXL', $whiteSizes);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_a_food_schedule_is_only_returned_when_a_variant_exists_for_the_date(): void
|
||||||
|
{
|
||||||
|
$tenant = $this->createFiestaFutbolInfantilTenant();
|
||||||
|
$this->grantTicketsMenu($tenant);
|
||||||
|
Sanctum::actingAs($this->createAdminAppUser($tenant));
|
||||||
|
|
||||||
|
$food = CatalogItem::query()
|
||||||
|
->where('tenant_code', $tenant->codigo)
|
||||||
|
->where('slug', 'comida')
|
||||||
|
->with([
|
||||||
|
'itemAttributes.attribute.options',
|
||||||
|
'variants.definitions.itemAttribute.attribute.options',
|
||||||
|
'variants.eventDates',
|
||||||
|
'variants.eventDate',
|
||||||
|
])
|
||||||
|
->firstOrFail();
|
||||||
|
|
||||||
|
$food->variants
|
||||||
|
->filter(fn ($variant): bool => $variant->selectionValues()->get('horario') === 'Almuerzo')
|
||||||
|
->each->delete();
|
||||||
|
|
||||||
|
$response = $this->getJson('/api/v1/adminapp/forms/tickets-filter')->assertOk();
|
||||||
|
$foodCategory = collect($response->json('data.fields.0.options'))->firstWhere('value', 'comidas');
|
||||||
|
$schedules = collect($foodCategory['children'][0]['options'])->pluck('value');
|
||||||
|
|
||||||
|
$this->assertNotContains('Almuerzo', $schedules);
|
||||||
|
$this->assertContains('Desayuno', $schedules);
|
||||||
|
$this->assertContains('Cena', $schedules);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_a_deleted_food_variant_remains_in_the_filter_when_a_ticket_references_it(): void
|
||||||
|
{
|
||||||
|
$tenant = $this->createFiestaFutbolInfantilTenant();
|
||||||
|
$this->grantTicketsMenu($tenant);
|
||||||
|
$admin = $this->createAdminAppUser($tenant);
|
||||||
|
Sanctum::actingAs($admin);
|
||||||
|
|
||||||
|
$food = CatalogItem::query()
|
||||||
|
->where('tenant_code', $tenant->codigo)
|
||||||
|
->where('slug', 'comida')
|
||||||
|
->with([
|
||||||
|
'itemAttributes.attribute.options',
|
||||||
|
'variants.definitions.itemAttribute.attribute.options',
|
||||||
|
'variants.eventDates',
|
||||||
|
'variants.eventDate',
|
||||||
|
])
|
||||||
|
->firstOrFail();
|
||||||
|
$historicalVariant = $food->variants->first(function ($variant): bool {
|
||||||
|
return $variant->selectedEventDates()->first()?->date->format('d/m') === '12/10'
|
||||||
|
&& $variant->selectionValues()->get('horario') === 'Cena';
|
||||||
|
});
|
||||||
|
$this->assertNotNull($historicalVariant);
|
||||||
|
$historicalService = $historicalVariant->selectionValues()->get('servicio');
|
||||||
|
|
||||||
|
$ticket = Ticket::query()->create([
|
||||||
|
'tenant_code' => $tenant->codigo,
|
||||||
|
'ticket' => (string) Str::uuid(),
|
||||||
|
'user_id' => $admin->id,
|
||||||
|
'source_catalog_item_id' => $food->id,
|
||||||
|
'source_variant_id' => $historicalVariant->id,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$catalogService = app(CatalogService::class);
|
||||||
|
foreach ($food->variants as $variant) {
|
||||||
|
$catalogService->deleteVariant($variant);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->assertTrue(CatalogItem::withTrashed()->findOrFail($food->id)->trashed());
|
||||||
|
|
||||||
|
$response = $this->getJson('/api/v1/adminapp/forms/tickets-filter')->assertOk();
|
||||||
|
$foodCategory = collect($response->json('data.fields.0.options'))->firstWhere('value', 'comidas');
|
||||||
|
$products = collect($foodCategory['children'][0]['options']);
|
||||||
|
|
||||||
|
$this->assertCount(1, $products);
|
||||||
|
$this->assertSame('Cena', $products->first()['label']);
|
||||||
|
$this->assertSame(
|
||||||
|
[$historicalService],
|
||||||
|
collect($products->first()['children'][0]['options'])->pluck('label')->all(),
|
||||||
|
);
|
||||||
|
|
||||||
|
$this->getJson('/api/v1/adminapp/tenant/tickets?'.http_build_query([
|
||||||
|
'category' => 'comidas',
|
||||||
|
'product' => $products->first()['value'],
|
||||||
|
'type' => $historicalService,
|
||||||
|
'date' => '2026-10-12',
|
||||||
|
]))
|
||||||
|
->assertOk()
|
||||||
|
->assertJsonCount(1, 'data')
|
||||||
|
->assertJsonPath('data.0.id', $ticket->id)
|
||||||
|
->assertJsonPath('data.0.values.category', 'Comida')
|
||||||
|
->assertJsonPath('data.0.values.product', 'Cena')
|
||||||
|
->assertJsonPath('data.0.values.type', $historicalService)
|
||||||
|
->assertJsonPath('data.0.values.date', '12/10')
|
||||||
|
->assertJsonPath('data.0.values.size', '-');
|
||||||
|
}
|
||||||
|
|
||||||
|
private function createFiestaFutbolInfantilTenant(): Tenant
|
||||||
|
{
|
||||||
|
$tenant = $this->createTenant('fiesta_futbol_infantil');
|
||||||
|
$this->seed([AttributeSeeder::class, FiestaFutbolInfantilProductSeeder::class]);
|
||||||
|
|
||||||
|
return $tenant->refresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return list<array<string, mixed>> */
|
||||||
|
private function commonColumns(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
['key' => 'order_number', 'label' => 'N° de orden', 'type' => 'order_number', 'sortable' => true, 'sort_param' => 'order_number', 'width' => '11%'],
|
||||||
|
['key' => 'product', 'label' => 'Producto', 'type' => 'text', 'sortable' => true, 'sort_param' => 'product', 'width' => '15%'],
|
||||||
|
['key' => 'amount', 'label' => 'Importe', 'type' => 'currency', 'sortable' => true, 'sort_param' => 'amount', 'width' => '10%'],
|
||||||
|
['key' => 'client', 'label' => 'Cliente', 'type' => 'text', 'sortable' => true, 'sort_param' => 'client', 'width' => '15%'],
|
||||||
|
['key' => 'id', 'label' => 'ID', 'type' => 'text', 'sortable' => true, 'sort_param' => 'id', 'width' => '8%'],
|
||||||
|
['key' => 'status', 'label' => 'Estado', 'type' => 'status', 'sortable' => true, 'sort_param' => 'status', 'width' => '8%'],
|
||||||
|
['key' => 'scanned_by', 'label' => 'Escaneado por', 'type' => 'text', 'sortable' => true, 'sort_param' => 'scanned_by', 'width' => '11%'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function createTenant(string $code): Tenant
|
||||||
|
{
|
||||||
|
$headerLogo = $this->createAttachment("{$code}-header.png");
|
||||||
|
$footerLogo = $this->createAttachment("{$code}-footer.png");
|
||||||
|
|
||||||
|
return Tenant::query()->create([
|
||||||
|
'codigo' => $code,
|
||||||
|
'nombre' => ucfirst($code),
|
||||||
|
'dominio' => "{$code}.test",
|
||||||
|
'primary_color' => '#111111',
|
||||||
|
'secondary_color' => '#222222',
|
||||||
|
'danger_color' => '#333333',
|
||||||
|
'success_color' => '#444444',
|
||||||
|
'header_bg_color' => '#ffffff',
|
||||||
|
'footer_bg_color' => '#ffffff',
|
||||||
|
'header_logo_id' => $headerLogo->id,
|
||||||
|
'footer_logo_id' => $footerLogo->id,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function createAttachment(string $filename): Attachment
|
||||||
|
{
|
||||||
|
return Attachment::query()->create([
|
||||||
|
'path' => "tests/{$filename}",
|
||||||
|
'filename' => $filename,
|
||||||
|
'type' => AttachmentType::Image,
|
||||||
|
'mime_type' => 'image/png',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function createAdminAppUser(Tenant $tenant): User
|
||||||
|
{
|
||||||
|
return User::factory()->create([
|
||||||
|
'rol_codigo' => RoleCode::AdminApp->value,
|
||||||
|
'tenant_codigo' => $tenant->codigo,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function grantTicketsMenu(Tenant $tenant): void
|
||||||
|
{
|
||||||
|
$menu = Menu::query()->create([
|
||||||
|
'code' => 'adminapp.tickets',
|
||||||
|
'label' => 'Tickets',
|
||||||
|
'route' => '/admin/tickets',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$tenant->menues()->attach($menu->code);
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user