Open-source event management and ticket selling platform — perfect for concerts, conferences, and everything in between 🎟️ If you find this project helpful, please consider giving us a star ⭐️
PHP attendize-alternativedoor-managementevent-check-inevent-managementevent-registrationevent-ticketingeventbrite-alternativeeventslaravelopen-sourcephpreactself-hostedsell-ticketssell-tickets-onlineticket-sellingticketing-systemtickettailor-alternativetito-alternative
Enforce promo code usage limit at order reservation (#1233)
Dave Earleyb551d55a31b2
diff --git a/backend/app/Http/Actions/PromoCodes/GetPromoCodePublic.php b/backend/app/Http/Actions/PromoCodes/GetPromoCodePublic.phpindex 7d97aee3c..f29d6e165 100644--- a/backend/app/Http/Actions/PromoCodes/GetPromoCodePublic.php+++ b/backend/app/Http/Actions/PromoCodes/GetPromoCodePublic.php@@ -5,16 +5,17 @@ namespace HiEvents\Http\Actions\PromoCodes;use HiEvents\DomainObjects\Generated\PromoCodeDomainObjectAbstract;use HiEvents\Http\Actions\BaseAction;use HiEvents\Repository\Interfaces\PromoCodeRepositoryInterface;+use HiEvents\Services\Domain\PromoCode\PromoCodeUsageValidationService;use Illuminate\Http\JsonResponse;use Illuminate\Http\Request;class GetPromoCodePublic extends BaseAction{- private PromoCodeRepositoryInterface $promoCodeRepository;-- public function __construct(PromoCodeRepositoryInterface $promoCodeRepository)+ public function __construct(+ private readonly PromoCodeRepositoryInterface $promoCodeRepository,+ private readonly PromoCodeUsageValidationService $promoCodeUsageValidationService,+ ){- $this->promoCodeRepository = $promoCodeRepository;}public function __invoke(int $eventId, string $promoCode, Request $request): JsonResponse@@ -26,7 +27,7 @@ class GetPromoCodePublic extends BaseAction]);return $this->jsonResponse([- 'valid' => $promoCode !== null && $promoCode->isValid(),+ 'valid' => $this->promoCodeUsageValidationService->isPromoCodeUsable($promoCode),]);}}diff --git a/backend/app/Repository/Eloquent/OrderRepository.php b/backend/app/Repository/Eloquent/OrderRepository.phpindex f33c2629e..3130d9adb 100644--- a/backend/app/Repository/Eloquent/OrderRepository.php+++ b/backend/app/Repository/Eloquent/OrderRepository.php@@ -185,6 +185,26 @@ class OrderRepository extends BaseRepository implements OrderRepositoryInterfacereturn $count;}+ public function countActivePromoCodeUsage(int $promoCodeId): int+ {+ $count = $this->model+ ->where('promo_code_id', $promoCodeId)+ ->where(static function (Builder $query) {+ $query->whereIn('status', [+ OrderStatus::COMPLETED->name,+ OrderStatus::AWAITING_OFFLINE_PAYMENT->name,+ ])->orWhere(static function (Builder $reserved) {+ $reserved->where('status', OrderStatus::RESERVED->name)+ ->where('reserved_until', '>', now());+ });+ })+ ->count();++ $this->resetModel();++ return $count;+ }+public function getAllOrdersForAdmin(?string $search = null,int $perPage = 20,diff --git a/backend/app/Repository/Interfaces/OrderRepositoryInterface.php b/backend/app/Repository/Interfaces/OrderRepositoryInterface.phpindex 58cf2c7a8..0f6de621d 100644--- a/backend/app/Repository/Interfaces/OrderRepositoryInterface.php+++ b/backend/app/Repository/Interfaces/OrderRepositoryInterface.php@@ -31,6 +31,8 @@ interface OrderRepositoryInterface extends RepositoryInterfacepublic function countOrdersAssociatedWithProducts(int $eventId, array $productIds, array $orderStatuses): int;+ public function countActivePromoCodeUsage(int $promoCodeId): int;+public function getAllOrdersForAdmin(?string $search = null,int $perPage = 20,diff --git a/backend/app/Services/Application/Handlers/Order/CreateOrderHandler.php b/backend/app/Services/Application/Handlers/Order/CreateOrderHandler.phpindex 5278ef224..9ae7d2fce 100644--- a/backend/app/Services/Application/Handlers/Order/CreateOrderHandler.php+++ b/backend/app/Services/Application/Handlers/Order/CreateOrderHandler.php@@ -19,6 +19,7 @@ use HiEvents\Repository\Interfaces\PromoCodeRepositoryInterface;use HiEvents\Services\Application\Handlers\Order\DTO\CreateOrderPublicDTO;use HiEvents\Services\Domain\Order\OrderItemProcessingService;use HiEvents\Services\Domain\Order\OrderManagementService;+use HiEvents\Services\Domain\PromoCode\PromoCodeUsageValidationService;use HiEvents\Services\Domain\Product\AvailableProductQuantitiesFetchService;use Illuminate\Database\DatabaseManager;use Illuminate\Validation\UnauthorizedException;@@ -30,6 +31,7 @@ class CreateOrderHandlerpublic function __construct(private readonly EventRepositoryInterface $eventRepository,private readonly PromoCodeRepositoryInterface $promoCodeRepository,+ private readonly PromoCodeUsageValidationService $promoCodeUsageValidationService,private readonly AffiliateRepositoryInterface $affiliateRepository,private readonly OrderManagementService $orderManagementService,private readonly OrderItemProcessingService $orderItemProcessingService,@@ -57,13 +59,14 @@ class CreateOrderHandler$this->validateEventStatus($event, $createOrderPublicDTO);- $promoCode = $this->getPromoCode($createOrderPublicDTO, $eventId);- $affiliate = $this->getAffiliate($createOrderPublicDTO, $eventId);-+ // Remove the session's stale reservations before promo usage is counted in getPromoCode()if ($deleteExistingOrdersForSession) {$this->orderManagementService->deleteExistingOrders($eventId, $createOrderPublicDTO->session_identifier);}+ $promoCode = $this->getPromoCode($createOrderPublicDTO, $eventId);+ $affiliate = $this->getAffiliate($createOrderPublicDTO, $eventId);+$this->validateProductAvailability($eventId, $createOrderPublicDTO);$order = $this->orderManagementService->createNewOrder(@@ -98,11 +101,11 @@ class CreateOrderHandlerPromoCodeDomainObjectAbstract::EVENT_ID => $eventId,]);- if ($promoCode?->isValid()) {- return $promoCode;+ if (!$this->promoCodeUsageValidationService->isPromoCodeUsable($promoCode)) {+ return null;}- return null;+ return $promoCode;}private function getAffiliate(CreateOrderPublicDTO $createOrderPublicDTO, int $eventId): ?AffiliateDomainObjectdiff --git a/backend/app/Services/Domain/PromoCode/PromoCodeUsageValidationService.php b/backend/app/Services/Domain/PromoCode/PromoCodeUsageValidationService.phpnew file mode 100644index 000000000..f62ac2776--- /dev/null+++ b/backend/app/Services/Domain/PromoCode/PromoCodeUsageValidationService.php@@ -0,0 +1,35 @@+<?php++namespace HiEvents\Services\Domain\PromoCode;++use HiEvents\DomainObjects\PromoCodeDomainObject;+use HiEvents\Repository\Interfaces\OrderRepositoryInterface;++class PromoCodeUsageValidationService+{+ public function __construct(+ private readonly OrderRepositoryInterface $orderRepository,+ )+ {+ }++ /**+ * Usage is derived from a live count of orders currently holding the code+ * (completed, awaiting offline payment, or unexpired reservations), because the+ * persisted order_usage_count counter is only updated asynchronously after completion.+ */+ public function isPromoCodeUsable(?PromoCodeDomainObject $promoCode): bool+ {+ if (!$promoCode?->isValid()) {+ return false;+ }++ $maxAllowedUsages = $promoCode->getMaxAllowedUsages();++ if ($maxAllowedUsages === null) {+ return true;+ }++ return $this->orderRepository->countActivePromoCodeUsage($promoCode->getId()) < $maxAllowedUsages;+ }+}diff --git a/backend/tests/Unit/Services/Application/Handlers/Order/CreateOrderHandlerPromoCodeTest.php b/backend/tests/Unit/Services/Application/Handlers/Order/CreateOrderHandlerPromoCodeTest.phpnew file mode 100644index 000000000..c63e57216--- /dev/null+++ b/backend/tests/Unit/Services/Application/Handlers/Order/CreateOrderHandlerPromoCodeTest.php@@ -0,0 +1,122 @@+<?php++namespace Tests\Unit\Services\Application\Handlers\Order;++use HiEvents\DomainObjects\EventDomainObject;+use HiEvents\DomainObjects\EventSettingDomainObject;+use HiEvents\DomainObjects\OrderDomainObject;+use HiEvents\DomainObjects\PromoCodeDomainObject;+use HiEvents\Repository\Interfaces\AffiliateRepositoryInterface;+use HiEvents\Repository\Interfaces\EventRepositoryInterface;+use HiEvents\Repository\Interfaces\PromoCodeRepositoryInterface;+use HiEvents\Services\Application\Handlers\Order\CreateOrderHandler;+use HiEvents\Services\Application\Handlers\Order\DTO\CreateOrderPublicDTO;+use HiEvents\Services\Domain\Order\OrderItemProcessingService;+use HiEvents\Services\Domain\Order\OrderManagementService;+use HiEvents\Services\Domain\Product\AvailableProductQuantitiesFetchService;+use HiEvents\Services\Domain\Product\DTO\AvailableProductQuantitiesResponseDTO;+use HiEvents\Services\Domain\PromoCode\PromoCodeUsageValidationService;+use Illuminate\Database\DatabaseManager;+use Mockery;+use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;+use Tests\TestCase;++class CreateOrderHandlerPromoCodeTest extends TestCase+{+ use MockeryPHPUnitIntegration;++ private const EVENT_ID = 1;+ private const PROMO_CODE_ID = 5;++ public function testPromoCodeIsDroppedWhenNotUsable(): void+ {+ $captured = $this->runHandler(isUsable: false);++ $this->assertNull($captured);+ }++ public function testPromoCodeIsAppliedWhenUsable(): void+ {+ $captured = $this->runHandler(isUsable: true);++ $this->assertInstanceOf(PromoCodeDomainObject::class, $captured);+ $this->assertSame(self::PROMO_CODE_ID, $captured->getId());+ }++ private function runHandler(bool $isUsable): mixed+ {+ $promoCode = (new PromoCodeDomainObject())+ ->setId(self::PROMO_CODE_ID)+ ->setCode('save50');++ $eventSettings = Mockery::mock(EventSettingDomainObject::class);+ $eventSettings->shouldReceive('getOrderTimeoutInMinutes')->andReturn(15);++ $event = Mockery::mock(EventDomainObject::class);+ $event->shouldReceive('getEventSettings')->andReturn($eventSettings);+ $event->shouldReceive('getCurrency')->andReturn('USD');++ $eventRepository = Mockery::mock(EventRepositoryInterface::class);+ $eventRepository->shouldReceive('loadRelation')->andReturnSelf();+ $eventRepository->shouldReceive('findById')->with(self::EVENT_ID)->andReturn($event);++ $promoCodeRepository = Mockery::mock(PromoCodeRepositoryInterface::class);+ $promoCodeRepository->shouldReceive('findFirstWhere')->andReturn($promoCode);++ $usageValidationService = Mockery::mock(PromoCodeUsageValidationService::class);+ $usageValidationService->shouldReceive('isPromoCodeUsable')->with($promoCode)->andReturn($isUsable);++ $affiliateRepository = Mockery::mock(AffiliateRepositoryInterface::class);++ $orderManagementService = Mockery::mock(OrderManagementService::class);+ $orderManagementService->shouldReceive('deleteExistingOrders');++ $captured = false;+ $order = Mockery::mock(OrderDomainObject::class);+ $orderManagementService+ ->shouldReceive('createNewOrder')+ ->andReturnUsing(function ($eventId, $event, $timeOut, $locale, $promo, $affiliate, $sessionId) use (&$captured, $order) {+ $captured = $promo;+ return $order;+ });+ $orderManagementService->shouldReceive('updateOrderTotals')->andReturn($order);++ $orderItemProcessingService = Mockery::mock(OrderItemProcessingService::class);+ $orderItemProcessingService->shouldReceive('process')->andReturn(collect());++ $availabilityService = Mockery::mock(AvailableProductQuantitiesFetchService::class);+ $availabilityService->shouldReceive('getAvailableProductQuantities')+ ->andReturn(new AvailableProductQuantitiesResponseDTO(+ productQuantities: collect(),+ capacities: collect(),+ ));++ $databaseManager = Mockery::mock(DatabaseManager::class);+ $databaseManager->shouldReceive('statement')->andReturn(true);+ $databaseManager->shouldReceive('transaction')->andReturnUsing(fn($callback) => $callback());++ $handler = new CreateOrderHandler(+ $eventRepository,+ $promoCodeRepository,+ $usageValidationService,+ $affiliateRepository,+ $orderManagementService,+ $orderItemProcessingService,+ $availabilityService,+ $databaseManager,+ );++ $dto = new CreateOrderPublicDTO(+ products: collect(),+ is_user_authenticated: true,+ session_identifier: 'sess-123',+ order_locale: 'en',+ promo_code: 'save50',+ affiliate_code: null,+ );++ $handler->handle(self::EVENT_ID, $dto);++ return $captured;+ }+}diff --git a/backend/tests/Unit/Services/Application/Handlers/Order/CreateOrderHandlerTest.php b/backend/tests/Unit/Services/Application/Handlers/Order/CreateOrderHandlerTest.phpindex 21a06aeb0..8bc15306c 100644--- a/backend/tests/Unit/Services/Application/Handlers/Order/CreateOrderHandlerTest.php+++ b/backend/tests/Unit/Services/Application/Handlers/Order/CreateOrderHandlerTest.php@@ -10,6 +10,7 @@ use HiEvents\DomainObjects\Status\EventStatus;use HiEvents\Repository\Interfaces\AffiliateRepositoryInterface;use HiEvents\Repository\Interfaces\EventRepositoryInterface;use HiEvents\Repository\Interfaces\PromoCodeRepositoryInterface;+use HiEvents\Services\Domain\PromoCode\PromoCodeUsageValidationService;use HiEvents\Services\Application\Handlers\Order\CreateOrderHandler;use HiEvents\Services\Application\Handlers\Order\DTO\CreateOrderPublicDTO;use HiEvents\Services\Application\Handlers\Order\DTO\ProductOrderDetailsDTO;@@ -29,6 +30,7 @@ class CreateOrderHandlerTest extends TestCase{private EventRepositoryInterface|MockInterface $eventRepository;private PromoCodeRepositoryInterface|MockInterface $promoCodeRepository;+ private PromoCodeUsageValidationService|MockInterface $promoCodeUsageValidationService;private AffiliateRepositoryInterface|MockInterface $affiliateRepository;private OrderManagementService|MockInterface $orderManagementService;private OrderItemProcessingService|MockInterface $orderItemProcessingService;@@ -42,6 +44,7 @@ class CreateOrderHandlerTest extends TestCase$this->eventRepository = Mockery::mock(EventRepositoryInterface::class);$this->promoCodeRepository = Mockery::mock(PromoCodeRepositoryInterface::class);+ $this->promoCodeUsageValidationService = Mockery::mock(PromoCodeUsageValidationService::class);$this->affiliateRepository = Mockery::mock(AffiliateRepositoryInterface::class);$this->orderManagementService = Mockery::mock(OrderManagementService::class);$this->orderItemProcessingService = Mockery::mock(OrderItemProcessingService::class);@@ -54,6 +57,7 @@ class CreateOrderHandlerTest extends TestCase$this->handler = new CreateOrderHandler($this->eventRepository,$this->promoCodeRepository,+ $this->promoCodeUsageValidationService,$this->affiliateRepository,$this->orderManagementService,$this->orderItemProcessingService,diff --git a/backend/tests/Unit/Services/Domain/PromoCode/PromoCodeUsageValidationServiceTest.php b/backend/tests/Unit/Services/Domain/PromoCode/PromoCodeUsageValidationServiceTest.phpnew file mode 100644index 000000000..bf6df6a68--- /dev/null+++ b/backend/tests/Unit/Services/Domain/PromoCode/PromoCodeUsageValidationServiceTest.php@@ -0,0 +1,88 @@+<?php++namespace Tests\Unit\Services\Domain\PromoCode;++use HiEvents\DomainObjects\PromoCodeDomainObject;+use HiEvents\Repository\Interfaces\OrderRepositoryInterface;+use HiEvents\Services\Domain\PromoCode\PromoCodeUsageValidationService;+use Carbon\Carbon;+use Mockery;+use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;+use Tests\TestCase;++class PromoCodeUsageValidationServiceTest extends TestCase+{+ use MockeryPHPUnitIntegration;++ private const PROMO_CODE_ID = 5;++ public function testNullPromoCodeIsNotUsable(): void+ {+ $service = new PromoCodeUsageValidationService(Mockery::mock(OrderRepositoryInterface::class));++ $this->assertFalse($service->isPromoCodeUsable(null));+ }++ public function testExpiredPromoCodeIsNotUsable(): void+ {+ $promoCode = (new PromoCodeDomainObject())+ ->setId(self::PROMO_CODE_ID)+ ->setExpiryDate(Carbon::now()->subDay()->toDateTimeString());++ $orderRepository = Mockery::mock(OrderRepositoryInterface::class);+ $orderRepository->shouldNotReceive('countActivePromoCodeUsage');++ $service = new PromoCodeUsageValidationService($orderRepository);++ $this->assertFalse($service->isPromoCodeUsable($promoCode));+ }++ public function testPromoCodeWithNoUsageLimitIsUsable(): void+ {+ $promoCode = (new PromoCodeDomainObject())+ ->setId(self::PROMO_CODE_ID)+ ->setMaxAllowedUsages(null);++ $orderRepository = Mockery::mock(OrderRepositoryInterface::class);+ $orderRepository->shouldNotReceive('countActivePromoCodeUsage');++ $service = new PromoCodeUsageValidationService($orderRepository);++ $this->assertTrue($service->isPromoCodeUsable($promoCode));+ }++ public function testPromoCodeIsUsableWhenLiveCountIsUnderLimit(): void+ {+ $promoCode = (new PromoCodeDomainObject())+ ->setId(self::PROMO_CODE_ID)+ ->setMaxAllowedUsages(2)+ ->setOrderUsageCount(0);++ $orderRepository = Mockery::mock(OrderRepositoryInterface::class);+ $orderRepository->shouldReceive('countActivePromoCodeUsage')+ ->with(self::PROMO_CODE_ID)+ ->andReturn(1);++ $service = new PromoCodeUsageValidationService($orderRepository);++ $this->assertTrue($service->isPromoCodeUsable($promoCode));+ }++ public function testPromoCodeIsNotUsableWhenLiveCountReachesLimit(): void+ {+ // Stale order_usage_count is 0 (passes isValid), but the live count has reached the limit.+ $promoCode = (new PromoCodeDomainObject())+ ->setId(self::PROMO_CODE_ID)+ ->setMaxAllowedUsages(1)+ ->setOrderUsageCount(0);++ $orderRepository = Mockery::mock(OrderRepositoryInterface::class);+ $orderRepository->shouldReceive('countActivePromoCodeUsage')+ ->with(self::PROMO_CODE_ID)+ ->andReturn(1);++ $service = new PromoCodeUsageValidationService($orderRepository);++ $this->assertFalse($service->isPromoCodeUsable($promoCode));+ }+}