Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix tiered ticketing quality check + SSR token fix #38

Merged
merged 15 commits into from
Jun 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Dockerfile.all-in-one
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ COPY ./docker/all-in-one/nginx/nginx.conf /etc/nginx/nginx.conf
COPY ./docker/all-in-one/supervisor/supervisord.conf /etc/supervisord.conf

COPY ./docker/all-in-one/scripts/startup.sh /startup.sh
RUN chmod +x /startup.sh
RUN dos2unix /startup.sh && chmod +x /startup.sh

EXPOSE 80

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ a quick start, follow these steps:

3. **Start the Docker Containers:**
```bash
docker-compose up -d
docker compose up -d
```
4. **Create an account:**
```bash
Expand Down
4 changes: 2 additions & 2 deletions backend/app/DomainObjects/TicketDomainObject.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ public function getFees(): ?Collection
public function isSoldOut(): bool
{
if (!$this->getTicketPrices() || $this->getTicketPrices()->isEmpty()) {
throw new LogicException('You cannot check if a ticket is sold out without prices.');
return true;
}

return $this->getTicketPrices()->every(fn(TicketPriceDomainObject $price) => $price->isSoldOut());
Expand All @@ -85,7 +85,7 @@ public function isSoldOut(): bool
public function getQuantityAvailable(): int
{
if (!$this->getTicketPrices() || $this->getTicketPrices()->isEmpty()) {
throw new LogicException('You cannot get the quantity available for a ticket without prices.');
return 0;
}

return $this->getTicketPrices()->sum(fn(TicketPriceDomainObject $price) => $price->getQuantityAvailable());
Expand Down
1 change: 1 addition & 0 deletions backend/app/Repository/Eloquent/EventRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ public function getAvailableTicketQuantities(int $eventId): Collection
WHERE orders.event_id = $eventId
AND orders.status = '$reserved'
AND orders.reserved_until > NOW()
AND orders.deleted_at IS NULL
GROUP BY order_items.ticket_id, order_items.ticket_price_id) AS reserved_quantities
ON ticket_prices.id = reserved_quantities.ticket_price_id
WHERE tickets.event_id = $eventId
Expand Down
3 changes: 3 additions & 0 deletions backend/app/Resources/Ticket/TicketResourcePublic.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ public function toArray(Request $request): array
'event_id' => $this->getEventId(),
'is_before_sale_start_date' => $this->isBeforeSaleStartDate(),
'is_after_sale_end_date' => $this->isAfterSaleEndDate(),
$this->mergeWhen($this->getShowQuantityRemaining(), fn () => [
'quantity_available' => $this->getQuantityAvailable(),
]),
'price' => $this->when(
$this->getTicketPrices() && !$this->isTieredType(),
fn() => $this->getPrice(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,21 +168,14 @@ private function validateSingleTicketDetails(EventDomainObject $event, int $tick
private function validateTicketQuantity(int $ticketIndex, array $ticketAndQuantities, TicketDomainObject $ticket): void
{
$totalQuantity = collect($ticketAndQuantities['quantities'])->sum('quantity');
$maxPerOrder = (int)$ticket->getMaxPerOrder() ?: 100; // Placeholder for config value
$maxPerOrder = (int)$ticket->getMaxPerOrder() ?: 100;
$minPerOrder = (int)$ticket->getMinPerOrder() ?: 1;
$ticketQuantityAvailable = $this->ticketRepository->getQuantityRemainingForTicketPrice(
ticketId: $ticket->getId(),
ticketPriceId: $ticketAndQuantities['quantities'][0]['price_id']
);

if ($totalQuantity > $ticketQuantityAvailable) {
throw ValidationException::withMessages([
"tickets.$ticketIndex" => __("The maximum number of tickets available for :ticket is :max", [
'max' => $ticketQuantityAvailable,
'ticket' => $ticket->getTitle(),
]),
]);
}
$this->validateTicketPricesQuantity(
quantities: $ticketAndQuantities['quantities'],
ticket: $ticket,
ticketIndex: $ticketIndex
);

if ($totalQuantity > $maxPerOrder) {
throw ValidationException::withMessages([
Expand Down Expand Up @@ -274,4 +267,40 @@ private function validatePriceIdAndQuantity(int $ticketIndex, array $ticketAndQu
throw ValidationException::withMessages($errors);
}
}

/**
* @throws ValidationException
*/
private function validateTicketPricesQuantity(array $quantities, TicketDomainObject $ticket, int $ticketIndex): void
{
foreach ($quantities as $ticketQuantity) {
$numberAvailable = $this->ticketRepository->getQuantityRemainingForTicketPrice(
ticketId: $ticket->getId(),
ticketPriceId: $ticketQuantity['price_id']
);

$numberAvailable = max(0, $numberAvailable);

/** @var TicketPriceDomainObject $ticketPrice */
$ticketPrice = $ticket->getTicketPrices()
?->first(fn(TicketPriceDomainObject $price) => $price->getId() === $ticketQuantity['price_id']);

if ($ticketQuantity['quantity'] > $numberAvailable) {
if ($numberAvailable === 0) {
throw ValidationException::withMessages([
"tickets.$ticketIndex" => __("The ticket :ticket is sold out", [
'ticket' => $ticket->getTitle() . ($ticketPrice->getLabel() ? ' - ' . $ticketPrice->getLabel() : ''),
]),
]);
}

throw ValidationException::withMessages([
"tickets.$ticketIndex" => __("The maximum number of tickets available for :ticket is :max", [
'max' => $numberAvailable,
'ticket' => $ticket->getTitle() . ($ticketPrice->getLabel() ? ' - ' . $ticketPrice->getLabel() : ''),
]),
]);
}
}
}
}
7 changes: 6 additions & 1 deletion backend/app/Services/Handlers/Order/CreateOrderHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,12 @@ public function handle(
sessionId: $sessionId
);

$orderItems = $this->orderItemProcessingService->process($order, $createOrderPublicDTO->tickets, $event, $promoCode);
$orderItems = $this->orderItemProcessingService->process(
order: $order,
ticketsOrderDetails: $createOrderPublicDTO->tickets,
event: $event,
promoCode: $promoCode,
);

return $this->orderManagementService->updateOrderTotals($order, $orderItems);
});
Expand Down
1 change: 0 additions & 1 deletion docker/all-in-one/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
version: '3.8'
services:
all-in-one:
build:
Expand Down
1 change: 0 additions & 1 deletion docker/backend/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
version: '3.8'
services:
hi-events-backend:
build:
Expand Down
1 change: 0 additions & 1 deletion docker/development/docker-compose.dev.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
version: '3'
services:
backend:
build:
Expand Down
1 change: 0 additions & 1 deletion docker/frontend/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
version: '3.8'
services:
hi-events-frontend:
build:
Expand Down
13 changes: 9 additions & 4 deletions frontend/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,11 +94,16 @@ app.use("*", async (req, res) => {
res.setHeader("Content-Type", "text/html");
return res.status(200).end(html);
} catch (error) {
if (!isProduction) {
vite.ssrFixStacktrace(error);
if (error instanceof Response) {
if (error.status >= 300 && error.status < 400) {
return res.redirect(error.status, error.headers.get("Location") || "/");
} else {
return res.status(error.status).send(await error.text());
}
}
console.log(error.stack);
res.status(500).end(error.stack);

console.error(error);
res.status(500).send("Internal Server Error");
}
});

Expand Down
6 changes: 0 additions & 6 deletions frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import {messages as fr} from "./locales/fr.po";
import {messages as pt} from "./locales/pt.po";
// @ts-ignore
import {messages as es} from "./locales/es.po";
import {setAuthToken} from "./utilites/apiClient.ts";
import {isSsr} from "./utilites/helpers.ts";

declare global {
Expand Down Expand Up @@ -63,7 +62,6 @@ export const App: FC<
PropsWithChildren<{
queryClient: QueryClient;
helmetContext?: any;
token?: string;
}>
> = (props) => {
const [isLoadedOnBrowser, setIsLoadedOnBrowser] = React.useState(false);
Expand All @@ -74,10 +72,6 @@ export const App: FC<
dynamicActivate(getSupportedLocale());
}

if (props.token) {
setAuthToken(props.token);
}

useEffect(() => {
setIsLoadedOnBrowser(!isSsr());
}, [])
Expand Down
6 changes: 0 additions & 6 deletions frontend/src/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,6 @@ export const api = axios.create({
withCredentials: true,
});


const existingToken = typeof window !== "undefined" ? window.localStorage.getItem('token') : undefined;
if (existingToken) {
setAuthToken(existingToken);
}

api.interceptors.response.use(
(response) => {
// Securely update the token on each response
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,17 @@
.questions {
margin-bottom: 20px;

h3 {
margin-bottom: 8px;
}

.noQuestionsAlert {
display: flex;
align-items: center;

svg {
margin-right: 5px;
}
}

.questionCard {
Expand Down
14 changes: 7 additions & 7 deletions frontend/src/components/common/QuestionsTable/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {Alert, Button, Group, Menu, Switch, TextInput, Tooltip} from '@mantine/core';
import {Button, Group, Menu, Switch, TextInput, Tooltip} from '@mantine/core';
import {IdParam, Question} from "../../../types.ts";
import {
IconDotsVertical,
Expand Down Expand Up @@ -297,9 +297,9 @@ export const QuestionsTable = ({questions}: QuestionsTableProp) => {
{orderQuestions
.filter(question => showHiddenQuestions || !question.is_hidden)
.length === 0 && (
<Alert icon={<IconInfoCircle/>} color={'gray'} className={classes.noQuestionsAlert}>
{t`You have no order questions.`}
</Alert>
<Card className={classes.noQuestionsAlert}>
<IconInfoCircle/> {t`You have no order questions.`}
</Card>
)}
</div>
<div className={classes.questions}>
Expand All @@ -312,9 +312,9 @@ export const QuestionsTable = ({questions}: QuestionsTableProp) => {
{ticketQuestions
.filter(question => showHiddenQuestions || !question.is_hidden)
.length === 0 && (
<Alert icon={<IconInfoCircle/>} color={'gray'} className={classes.noQuestionsAlert}>
{t`You have no attendee questions.`}
</Alert>
<Card className={classes.noQuestionsAlert}>
<IconInfoCircle/> {t`You have no attendee questions.`}
</Card>
)}
</div>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,11 @@

.browserChrome {
width: 100%;
background: #f0f0f0;
background: #fff;
border-radius: 5px 5px 0 0;
height: 40px;
display: flex;
border-bottom: 1px solid #dbdbdb;
}

.browserActionButtons {
Expand All @@ -57,7 +58,7 @@
width: 15px;
height: 15px;
border-radius: 50px;
background-color: #fff;
background-color: #eee;
display: inline-block;
margin-right: 4px;
}
Expand All @@ -68,7 +69,7 @@
align-self: center;

div {
background-color: #ffffff63;
background-color: #f8f8f8;
border-radius: 5px;
margin-right: 20%;
font-size: 0.9em;
Expand Down
9 changes: 6 additions & 3 deletions frontend/src/components/forms/PromoCodeForm/index.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import {UseFormReturnType} from "@mantine/form";
import {Alert, MultiSelect, NumberInput, Select, TextInput} from "@mantine/core";
import {IconAlertCircle, IconCurrencyDollar, IconPercentage} from "@tabler/icons-react";
import {IconAlertCircle, IconPercentage} from "@tabler/icons-react";
import {PromoCode, PromoCodeDiscountType} from "../../../types.ts";
import {useGetEvent} from "../../../queries/useGetEvent.ts";
import {useParams} from "react-router-dom";
import {LoadingMask} from "../../common/LoadingMask";
import {t} from "@lingui/macro";
import {InputGroup} from "../../common/InputGroup";
import {getCurrencySymbol} from "../../../utilites/currency.ts";

interface PromoCodeFormProps {
form: UseFormReturnType<PromoCode>,
Expand All @@ -20,7 +21,7 @@ export const PromoCodeForm = ({form}: PromoCodeFormProps) => {
if (form.values.discount_type === 'PERCENTAGE') {
return <IconPercentage/>;
}
return <IconCurrencyDollar/>
return getCurrencySymbol(event?.currency as string);
};

if (!event || !tickets) {
Expand Down Expand Up @@ -55,7 +56,9 @@ export const PromoCodeForm = ({form}: PromoCodeFormProps) => {
]}/>
<NumberInput
disabled={form.values.discount_type === PromoCodeDiscountType.None}
decimalScale={2} min={0} rightSection={<DiscountIcon/>} {...form.getInputProps('discount')}
decimalScale={2} min={0}
leftSection={<DiscountIcon/>}
{...form.getInputProps('discount')}
label={(form.values.discount_type === 'PERCENTAGE' ? t`Discount %` : t`Discount in ${event.currency}`)}
placeholder="0.00"/>
</InputGroup>
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/components/forms/TicketForm/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -296,10 +296,10 @@ export const TicketForm = ({form, ticket}: TicketFormProps) => {
)}

<InputGroup>
<NumberInput {...form.getInputProps('max_per_order')} label={t`Maximum Per Order`}
placeholder="5"/>
<NumberInput {...form.getInputProps('min_per_order')} label={t`Minimum Per Order`}
placeholder="5"/>
<NumberInput {...form.getInputProps('max_per_order')} label={t`Maximum Per Order`}
placeholder="5"/>
</InputGroup>

<InputGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ export const EventDetailsForm = () => {
{...form.getInputProps('currency')}
label={t`Currency`}
placeholder={t`EUR`}
disabled
/>

<Select
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -276,14 +276,19 @@ const SelectTickets = (props: SelectTicketsProps) => {
.map((n) => n.toString());
quantityRange.unshift("0");


return (
<div key={ticket.id} className={'hi-ticket-row'}>
<div className={'hi-title-row'}>
<div className={'hi-ticket-title'}>
<h3>{ticket.title}</h3>
</div>
<div className={'hi-ticket-availability'}>
{(ticket.is_available && !!ticket.quantity_available) && (
<>
<Trans>{ticket?.quantity_available} available</Trans>
</>
)}

{(!ticket.is_available && ticket.type === 'TIERED') && (
<TicketAvailabilityMessage ticket={ticket} event={event}/>
)}
Expand Down
Loading
Loading