Skip to content

Commit

Permalink
Add api to extend reservation time
Browse files Browse the repository at this point in the history
  • Loading branch information
starcraft66 committed Jan 24, 2024
1 parent 6853002 commit 0a4cd32
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
57 changes: 57 additions & 0 deletions lib/lanpartyseating/logic/reservation_logic.ex
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,63 @@ defmodule Lanpartyseating.ReservationLogic do
end
end

def extend_reservation(_id, minutes) when minutes <= 0 do
{:error, "Reservations can only be extended by a positive non-zero amount of minutes"}
end

def extend_reservation(id, minutes) do
existing_reservation =
from(r in Reservation,
where: r.station_id == ^id,
where: is_nil(r.deleted_at),
join: s in assoc(r, :station),
preload: [station: s]
)
|> Repo.one()

new_end_date = DateTime.add(existing_reservation.end_date, minutes, :minute)
updated_reservation =
Ecto.Changeset.change(existing_reservation,
end_date: new_end_date
)

reservation = with {:ok, reservation} <- Repo.update(updated_reservation) do
# Terminate the reservation expiration task with the old end date
GenServer.cast(:"expire_reservation_#{reservation.id}", :terminate)

# Start a new reservation expiration task with the new end date
DynamicSupervisor.start_child(
Lanpartyseating.ExpirationTaskSupervisor,
{Lanpartyseating.Tasks.ExpireReservation, {new_end_date, reservation.id}}
)

Endpoint.broadcast!(
"desktop:all",
"extend_reservation",
%{
station_number: reservation.station.station_number,
start_date: reservation.start_date |> DateTime.to_iso8601(),
end_date: reservation.end_date |> DateTime.to_iso8601(),
}
)

{:ok, stations} = StationLogic.get_all_stations()

Phoenix.PubSub.broadcast(
PubSub,
"station_update",
{:stations, stations}
)

reservation
else
{:error, err} ->
{:error, {:reservation_failed, err}}
end

{:ok, reservation}
end

def cancel_reservation(id, reason) do
cancelled =
from(r in Reservation,
Expand Down
13 changes: 13 additions & 0 deletions lib/lanpartyseating_web/live/cancellation_live.ex
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,19 @@ defmodule LanpartyseatingWeb.CancellationLive do
{:noreply, socket}
end

def handle_event(
"extend_reservation",
%{"station_id" => id, "station_number" => _station_number, "minutes_increment" => minutes},
socket
) do
{:ok, _} = ReservationLogic.extend_reservation(
String.to_integer(id),
String.to_integer(minutes)
)

{:noreply, socket}
end

def handle_event(
"cancel_station",
%{"station_id" => id, "station_number" => _station_number, "cancel_reason" => reason},
Expand Down

0 comments on commit 0a4cd32

Please sign in to comment.