Рефакторинг обработчиков. Часть 2 #21

This commit is contained in:
2026-05-11 21:51:45 +03:00
parent 6403f061df
commit 61bb44ab4a
31 changed files with 8391 additions and 1480 deletions
+82 -34
View File
@@ -1,57 +1,105 @@
%%%-------------------------------------------------------------------
%%% @doc Обработчик бронирований текущего пользователя (клиентский API).
%%% GET – возвращает список всех бронирований, сделанных пользователем.
%%% @end
%%%-------------------------------------------------------------------
-module(handler_user_bookings).
-include("records.hrl").
-behaviour(cowboy_handler).
-export([init/2]).
-export([trails/0]).
-include("records.hrl").
%%% cowboy_handler callback
-spec init(cowboy_req:req(), any()) -> {ok, cowboy_req:req(), any()}.
init(Req, Opts) ->
handle(Req, Opts).
%%% Swagger metadata
-spec trails() -> [map()].
trails() ->
[
#{
path => <<"/v1/user/bookings">>,
method => <<"GET">>,
description => <<"List bookings of the current user">>,
tags => [<<"Bookings">>],
responses => #{
200 => #{
description => <<"Array of bookings">>,
content => #{<<"application/json">> => #{schema => #{
type => array,
items => booking_schema()
}}}
},
401 => #{description => <<"Unauthorized">>}
}
}
].
booking_schema() ->
#{
type => object,
properties => #{
id => #{type => string},
event_id => #{type => string},
user_id => #{type => string},
status => #{type => string, enum => [<<"pending">>, <<"confirmed">>, <<"cancelled">>]},
notes => #{type => string, nullable => true},
reminder_sent => #{type => boolean},
confirmed_at => #{type => string, format => <<"date-time">>, nullable => true},
created_at => #{type => string, format => <<"date-time">>},
updated_at => #{type => string, format => <<"date-time">>}
}
}.
%%%===================================================================
%%% HTTP-методы
%%%===================================================================
%% @private
-spec handle(cowboy_req:req(), any()) -> {ok, cowboy_req:req(), any()}.
handle(Req, _Opts) ->
case cowboy_req:method(Req) of
<<"GET">> -> list_user_bookings(Req);
_ -> send_error(Req, 405, <<"Method not allowed">>)
<<"GET">> -> list_user_bookings(Req);
_ -> handler_utils:send_error(Req, 405, <<"Method not allowed">>)
end.
%% GET /v1/user/bookings - список бронирований текущего пользователя
%% @doc GET /v1/user/bookings список бронирований текущего пользователя.
-spec list_user_bookings(cowboy_req:req()) -> {ok, binary(), cowboy_req:req()}.
list_user_bookings(Req) ->
case handler_auth:authenticate(Req) of
case handler_utils:auth_user(Req) of
{ok, UserId, Req1} ->
case logic_booking:list_user_bookings(UserId) of
{ok, Bookings} ->
Response = [booking_to_json(B) || B <- Bookings],
send_json(Req1, 200, Response);
handler_utils:send_json(Req1, 200, Response);
{error, _} ->
send_error(Req1, 500, <<"Internal server error">>)
handler_utils:send_error(Req1, 500, <<"Internal server error">>)
end;
{error, Code, Message, Req1} ->
send_error(Req1, Code, Message)
handler_utils:send_error(Req1, Code, Message)
end.
%% Вспомогательные функции
%%%===================================================================
%%% Внутренние функции
%%%===================================================================
%% @private Формирует JSON-представление записи #booking{}.
-spec booking_to_json(#booking{}) -> map().
booking_to_json(Booking) ->
#{
id => Booking#booking.id,
event_id => Booking#booking.event_id,
user_id => Booking#booking.user_id,
status => Booking#booking.status,
confirmed_at => case Booking#booking.confirmed_at of
undefined -> null;
Dt -> datetime_to_iso8601(Dt)
end,
created_at => datetime_to_iso8601(Booking#booking.created_at),
updated_at => datetime_to_iso8601(Booking#booking.updated_at)
}.
datetime_to_iso8601({{Year, Month, Day}, {Hour, Minute, Second}}) ->
iolist_to_binary(io_lib:format("~4..0B-~2..0B-~2..0BT~2..0B:~2..0B:~2..0BZ",
[Year, Month, Day, Hour, Minute, Second])).
send_json(Req, Status, Data) ->
Body = jsx:encode(Data),
cowboy_req:reply(Status, #{<<"content-type">> => <<"application/json">>}, Body, Req),
{ok, Body, []}.
send_error(Req, Status, Message) ->
Body = jsx:encode(#{error => Message}),
cowboy_req:reply(Status, #{<<"content-type">> => <<"application/json">>}, Body, Req),
{ok, Body, []}.
id => Booking#booking.id,
event_id => Booking#booking.event_id,
user_id => Booking#booking.user_id,
status => Booking#booking.status,
notes => Booking#booking.notes,
reminder_sent => Booking#booking.reminder_sent,
confirmed_at => case Booking#booking.confirmed_at of
undefined -> null;
Dt -> handler_utils:datetime_to_iso8601(Dt)
end,
created_at => handler_utils:datetime_to_iso8601(Booking#booking.created_at),
updated_at => handler_utils:datetime_to_iso8601(Booking#booking.updated_at)
}.