Add tests for ticket validity and event date formatting
- Create TicketValiditySchemaTest to verify database schema for ticket validity. - Update CatalogModelsTest to include tests for event date attributes and selection options. - Introduce EventDateTextFormatterTest for formatting event dates in Spanish. - Refactor EventModelsTest to include validity time relationships. - Add SaleDetailResourceTest to ensure correct serialization of purchase items. - Enhance TicketTest with validity time checks and status management. - Implement ValidityTimeResourceTest to validate resource output for different validity types. - Add ValidityTimeTest to verify casting and validity checks for validity time types.
This commit is contained in:
62
app/Domains/Purchase/Services/UserPurchaseLimitService.php
Normal file
62
app/Domains/Purchase/Services/UserPurchaseLimitService.php
Normal file
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Purchase\Services;
|
||||
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class UserPurchaseLimitService
|
||||
{
|
||||
public function assertCanPurchase(
|
||||
CatalogItem $catalogItem,
|
||||
int $userId,
|
||||
int $requestedQuantity,
|
||||
?int $excludedPurchaseId = null,
|
||||
string $field = 'quantity',
|
||||
): void {
|
||||
DB::transaction(function () use (
|
||||
$catalogItem,
|
||||
$userId,
|
||||
$requestedQuantity,
|
||||
$excludedPurchaseId,
|
||||
$field,
|
||||
): void {
|
||||
/** @var CatalogItem $catalogItem */
|
||||
$catalogItem = CatalogItem::query()
|
||||
->whereKey($catalogItem->getKey())
|
||||
->lockForUpdate()
|
||||
->firstOrFail();
|
||||
$limit = $catalogItem->max_units_per_user;
|
||||
|
||||
if ($limit === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$purchasedQuantity = (int) PurchaseItem::query()
|
||||
->where('source_catalog_item_id', $catalogItem->getKey())
|
||||
->whereHas('purchase', function ($query) use ($userId, $excludedPurchaseId): void {
|
||||
$query
|
||||
->where('user_id', $userId)
|
||||
->whereIn('status', [
|
||||
Purchase::STATUS_CREATED,
|
||||
Purchase::STATUS_PENDING_PAYMENT,
|
||||
Purchase::STATUS_PAID,
|
||||
])
|
||||
->when(
|
||||
$excludedPurchaseId !== null,
|
||||
fn ($query) => $query->whereKeyNot($excludedPurchaseId),
|
||||
);
|
||||
})
|
||||
->sum('cantidad');
|
||||
|
||||
if ($purchasedQuantity + $requestedQuantity > $limit) {
|
||||
throw ValidationException::withMessages([
|
||||
$field => __('api.purchase_limit.exceeded', ['max' => $limit]),
|
||||
]);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user