Рефакторинг обработчиков. Часть 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
+212 -166
View File
@@ -1,148 +1,270 @@
%%%-------------------------------------------------------------------
%%% @doc Обработчик маршрута `/v1/calendars/:calendar_id/events`.
%%%
%%% POST – создание нового события (одиночного или повторяющегося).
%%% GET – получение списка событий календаря с возможностью фильтрации
%%% по диапазону дат и разворачиванием повторяющихся событий.
%%% @end
%%%-------------------------------------------------------------------
-module(handler_events).
-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() ->
[
#{ % POST create event
path => <<"/v1/calendars/:calendar_id/events">>,
method => <<"POST">>,
description => <<"Create a new event (single or recurring)">>,
tags => [<<"Events">>],
parameters => [
#{
name => <<"calendar_id">>,
in => <<"path">>,
description => <<"Calendar ID">>,
required => true,
schema => #{type => string}
}
],
requestBody => #{
required => true,
content => #{<<"application/json">> => #{schema => event_create_schema()}}
},
responses => #{
201 => #{description => <<"Event created">>},
400 => #{description => <<"Missing required fields or invalid JSON">>},
403 => #{description => <<"Access denied">>},
404 => #{description => <<"Calendar not found">>}
}
},
#{ % GET list events
path => <<"/v1/calendars/:calendar_id/events">>,
method => <<"GET">>,
description => <<"List events of a calendar with optional date range">>,
tags => [<<"Events">>],
parameters => [
#{
name => <<"calendar_id">>,
in => <<"path">>,
description => <<"Calendar ID">>,
required => true,
schema => #{type => string}
},
#{
name => <<"from">>,
in => <<"query">>,
description => <<"Start datetime (ISO8601)">>,
required => false,
schema => #{type => string, format => <<"date-time">>}
},
#{
name => <<"to">>,
in => <<"query">>,
description => <<"End datetime (ISO8601)">>,
required => false,
schema => #{type => string, format => <<"date-time">>}
}
],
responses => #{
200 => #{
description => <<"Array of events">>,
content => #{<<"application/json">> => #{schema => #{
type => array,
items => event_schema()
}}}
},
403 => #{description => <<"Access denied">>},
404 => #{description => <<"Calendar not found">>}
}
}
].
event_schema() ->
#{
type => object,
properties => #{
id => #{type => string},
calendar_id => #{type => string},
title => #{type => string},
description => #{type => string},
event_type => #{type => string, enum => [<<"single">>, <<"recurring">>]},
start_time => #{type => string, format => <<"date-time">>},
duration => #{type => integer},
recurrence => #{type => object, nullable => true},
master_id => #{type => string, nullable => true},
is_instance => #{type => boolean},
specialist_id => #{type => string, nullable => true},
location => #{type => object, nullable => true},
tags => #{type => array, items => #{type => string}},
capacity => #{type => integer, nullable => true},
online_link => #{type => string, nullable => true},
status => #{type => string, enum => [<<"active">>, <<"cancelled">>, <<"completed">>]},
reason => #{type => string, nullable => true},
rating_avg => #{type => number, format => float},
rating_count => #{type => integer},
attachments => #{type => array, items => #{type => string}, nullable => true},
edit_history => #{type => array, items => #{type => object}, nullable => true},
created_at => #{type => string, format => <<"date-time">>},
updated_at => #{type => string, format => <<"date-time">>}
}
}.
event_create_schema() ->
#{
type => object,
required => [<<"title">>, <<"start_time">>, <<"duration">>],
properties => #{
title => #{type => string},
start_time => #{type => string, format => <<"date-time">>},
duration => #{type => integer, description => <<"Duration in minutes">>},
description => #{type => string},
tags => #{type => array, items => #{type => string}},
capacity => #{type => integer},
online_link => #{type => string},
location => #{
type => object,
properties => #{
address => #{type => string},
lat => #{type => number, format => float},
lon => #{type => number, format => float}
}
},
recurrence => #{type => object, description => <<"Recurrence rule (RFC 5545)">>}
}
}.
%%%===================================================================
%%% HTTP-методы
%%%===================================================================
%% @private
-spec handle(cowboy_req:req(), any()) -> {ok, cowboy_req:req(), any()}.
handle(Req, _Opts) ->
case cowboy_req:method(Req) of
<<"POST">> -> create_event(Req);
<<"GET">> -> list_events(Req);
_ -> send_error(Req, 405, <<"Method not allowed">>)
<<"GET">> -> list_events(Req);
_ -> handler_utils:send_error(Req, 405, <<"Method not allowed">>)
end.
%% POST /v1/calendars/:calendar_id/events - создание события
%% @doc POST /v1/calendars/:calendar_id/events создание события.
-spec create_event(cowboy_req:req()) -> {ok, binary(), cowboy_req:req()}.
create_event(Req) ->
case handler_auth:authenticate(Req) of
case handler_utils:auth_user(Req) of
{ok, UserId, Req1} ->
CalendarId = cowboy_req:binding(calendar_id, Req1),
{ok, Body, Req2} = cowboy_req:read_body(Req1),
try jsx:decode(Body, [return_maps]) of
Decoded when is_map(Decoded) ->
case Decoded of
#{<<"title">> := Title,
<<"start_time">> := StartTimeStr,
<<"duration">> := Duration} ->
case parse_datetime(StartTimeStr) of
#{<<"title">> := Title, <<"start_time">> := StartTimeStr, <<"duration">> := Duration} ->
case handler_utils:parse_datetime(StartTimeStr) of
{ok, StartTime} ->
% Парсим location если есть
Location = parse_location(maps:get(<<"location">>, Decoded, undefined)),
% Проверяем, есть ли правило повторения
case maps:get(<<"recurrence">>, Decoded, undefined) of
undefined ->
% Одиночное событие
case logic_event:create_event(UserId, CalendarId, Title, StartTime, Duration) of
{ok, Event} ->
% Обновляем location и capacity если нужно
update_event_fields(Event#event.id, Location, Decoded),
{ok, UpdatedEvent} = core_event:get_by_id(Event#event.id),
Response = event_to_json(UpdatedEvent),
send_json(Req2, 201, Response);
Response = handler_utils:event_to_json(UpdatedEvent),
handler_utils:send_json(Req2, 201, Response);
{error, access_denied} ->
send_error(Req2, 403, <<"Access denied">>);
handler_utils:send_error(Req2, 403, <<"Access denied">>);
{error, not_found} ->
send_error(Req2, 404, <<"Calendar not found">>);
handler_utils:send_error(Req2, 404, <<"Calendar not found">>);
{error, event_in_past} ->
send_error(Req2, 400, <<"Event cannot be in the past">>);
handler_utils:send_error(Req2, 400, <<"Event cannot be in the past">>);
{error, _} ->
send_error(Req2, 500, <<"Internal server error">>)
handler_utils:send_error(Req2, 500, <<"Internal server error">>)
end;
RRule ->
% Повторяющееся событие
case logic_event:create_recurring_event(UserId, CalendarId, Title, StartTime, Duration, RRule) of
{ok, Event} ->
update_event_fields(Event#event.id, Location, Decoded),
{ok, UpdatedEvent} = core_event:get_by_id(Event#event.id),
Response = event_to_json(UpdatedEvent),
send_json(Req2, 201, Response);
Response = handler_utils:event_to_json(UpdatedEvent),
handler_utils:send_json(Req2, 201, Response);
{error, invalid_rrule} ->
send_error(Req2, 400, <<"Invalid recurrence rule">>);
handler_utils:send_error(Req2, 400, <<"Invalid recurrence rule">>);
{error, access_denied} ->
send_error(Req2, 403, <<"Access denied">>);
handler_utils:send_error(Req2, 403, <<"Access denied">>);
{error, not_found} ->
send_error(Req2, 404, <<"Calendar not found">>);
handler_utils:send_error(Req2, 404, <<"Calendar not found">>);
{error, event_in_past} ->
send_error(Req2, 400, <<"Event cannot be in the past">>);
handler_utils:send_error(Req2, 400, <<"Event cannot be in the past">>);
{error, _} ->
send_error(Req2, 500, <<"Internal server error">>)
handler_utils:send_error(Req2, 500, <<"Internal server error">>)
end
end;
{error, _} ->
send_error(Req2, 400, <<"Invalid start_time format. Use ISO 8601">>)
handler_utils:send_error(Req2, 400, <<"Invalid start_time format. Use ISO 8601">>)
end;
_ ->
send_error(Req2, 400, <<"Missing required fields: title, start_time, duration">>)
handler_utils:send_error(Req2, 400, <<"Missing required fields: title, start_time, duration">>)
end;
_ ->
send_error(Req2, 400, <<"Invalid JSON">>)
handler_utils:send_error(Req2, 400, <<"Invalid JSON">>)
catch
_:_ ->
send_error(Req2, 400, <<"Invalid JSON format">>)
_:_ -> handler_utils:send_error(Req2, 400, <<"Invalid JSON format">>)
end;
{error, Code, Message, Req1} ->
send_error(Req1, Code, Message)
handler_utils:send_error(Req1, Code, Message)
end.
%% GET /v1/calendars/:calendar_id/events - список событий
%% @doc GET /v1/calendars/:calendar_id/events список событий.
-spec list_events(cowboy_req:req()) -> {ok, binary(), cowboy_req:req()}.
list_events(Req) ->
case handler_auth:authenticate(Req) of
case handler_utils:auth_user(Req) of
{ok, UserId, Req1} ->
CalendarId = cowboy_req:binding(calendar_id, Req1),
Qs = cowboy_req:parse_qs(Req1),
From = proplists:get_value(<<"from">>, Qs, undefined),
To = proplists:get_value(<<"to">>, Qs, undefined),
To = proplists:get_value(<<"to">>, Qs, undefined),
case logic_event:list_events(UserId, CalendarId) of
{ok, Events} ->
Response = case {From, To} of
{undefined, undefined} ->
[event_to_json(E) || E <- Events];
[handler_utils:event_to_json(E) || E <- Events];
{FromStr, ToStr} ->
FromDt = parse_datetime_binary(FromStr),
ToDt = parse_datetime_binary(ToStr),
ToDt = parse_datetime_binary(ToStr),
expand_recurring_events(UserId, Events, FromDt, ToDt)
end,
send_json(Req1, 200, Response);
handler_utils:send_json(Req1, 200, Response);
{error, access_denied} ->
send_error(Req1, 403, <<"Access denied">>);
handler_utils:send_error(Req1, 403, <<"Access denied">>);
{error, not_found} ->
send_error(Req1, 404, <<"Calendar not found">>);
handler_utils:send_error(Req1, 404, <<"Calendar not found">>);
{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.
%% Вспомогательные функции
%%%===================================================================
%%% Вспомогательные функции
%%%===================================================================
update_event_fields(EventId, Location, Decoded) ->
Updates = [],
Updates1 = case Location of
undefined -> Updates;
_ -> [{location, Location} | Updates]
end,
Updates2 = case maps:get(<<"capacity">>, Decoded, undefined) of
undefined -> Updates1;
Cap -> [{capacity, Cap} | Updates1]
end,
Updates3 = case maps:get(<<"tags">>, Decoded, undefined) of
undefined -> Updates2;
Tags -> [{tags, Tags} | Updates2]
end,
Updates4 = case maps:get(<<"description">>, Decoded, undefined) of
undefined -> Updates3;
Desc -> [{description, Desc} | Updates3]
end,
Updates5 = case maps:get(<<"online_link">>, Decoded, undefined) of
undefined -> Updates4;
Link -> [{online_link, Link} | Updates4]
end,
if Updates5 /= [] -> core_event:update(EventId, Updates5);
true -> ok
end.
Updates1 = case Location of undefined -> Updates; _ -> [{location, Location} | Updates] end,
Updates2 = case maps:get(<<"capacity">>, Decoded, undefined) of undefined -> Updates1; Cap -> [{capacity, Cap} | Updates1] end,
Updates3 = case maps:get(<<"tags">>, Decoded, undefined) of undefined -> Updates2; Tags -> [{tags, Tags} | Updates2] end,
Updates4 = case maps:get(<<"description">>, Decoded, undefined) of undefined -> Updates3; Desc -> [{description, Desc} | Updates3] end,
Updates5 = case maps:get(<<"online_link">>, Decoded, undefined) of undefined -> Updates4; Link -> [{online_link, Link} | Updates4] end,
if Updates5 /= [] -> core_event:update(EventId, Updates5); true -> ok end.
parse_location(undefined) -> undefined;
parse_location(LocationMap) when is_map(LocationMap) ->
@@ -159,116 +281,40 @@ expand_recurring_events(UserId, Events, From, To) ->
case Event#event.event_type of
single ->
case is_in_range(Event#event.start_time, From, To) of
true -> [event_to_json(Event)];
true -> [handler_utils:event_to_json(Event)];
false -> []
end;
recurring ->
case logic_event:get_occurrences(UserId, Event#event.id, To) of
{ok, Occurrences} ->
lists:filtermap(fun
({virtual, Occ}) ->
case is_in_range(Occ, From, To) of
true -> {true, occurrence_to_json(Event, Occ)};
false -> false
end;
({materialized, Instance}) ->
case is_in_range(Instance#event.start_time, From, To) of
true -> {true, event_to_json(Instance)};
false -> false
end
end, Occurrences);
_ ->
[]
lists:filtermap(
fun({virtual, Occ}) ->
case is_in_range(Occ, From, To) of
true -> {true, occurrence_to_json(Event, Occ)};
false -> false
end;
({materialized, Instance}) ->
case is_in_range(Instance#event.start_time, From, To) of
true -> {true, handler_utils:event_to_json(Instance)};
false -> false
end
end, Occurrences);
_ -> []
end
end
end, Events).
is_in_range(Time, From, To) ->
Time >= From andalso Time =< To.
is_in_range(Time, From, To) -> Time >= From andalso Time =< To.
parse_datetime_binary(Str) ->
{ok, Dt} = parse_datetime(Str),
{ok, Dt} = handler_utils:parse_datetime(Str),
Dt.
parse_datetime(Str) ->
try
[DateStr, TimeStr] = string:split(Str, "T"),
TimeStrNoZ = string:trim(TimeStr, trailing, "Z"),
[YearStr, MonthStr, DayStr] = string:split(DateStr, "-", all),
[HourStr, MinuteStr, SecondStr] = string:split(TimeStrNoZ, ":", all),
Year = binary_to_integer(YearStr),
Month = binary_to_integer(MonthStr),
Day = binary_to_integer(DayStr),
Hour = binary_to_integer(HourStr),
Minute = binary_to_integer(MinuteStr),
Second = binary_to_integer(SecondStr),
{ok, {{Year, Month, Day}, {Hour, Minute, Second}}}
catch
_:_ -> {error, invalid_format}
end.
event_to_json(Event) ->
LocationJson = case Event#event.location of
undefined -> null;
#location{address = Addr, lat = Lat, lon = Lon} ->
#{address => Addr, lat => Lat, lon => Lon}
end,
RecurrenceJson = case Event#event.recurrence_rule of
undefined -> null;
Rule ->
Decoded = jsx:decode(Rule, [return_maps]),
case Decoded of
Map when is_map(Map) -> Map;
{ok, Map} -> Map
end
end,
#{
id => Event#event.id,
calendar_id => Event#event.calendar_id,
title => Event#event.title,
description => Event#event.description,
event_type => Event#event.event_type,
start_time => datetime_to_iso8601(Event#event.start_time),
duration => Event#event.duration,
recurrence => RecurrenceJson,
master_id => Event#event.master_id,
is_instance => Event#event.is_instance,
specialist_id => Event#event.specialist_id,
location => LocationJson,
tags => Event#event.tags,
capacity => Event#event.capacity,
online_link => Event#event.online_link,
status => Event#event.status,
rating_avg => Event#event.rating_avg,
rating_count => Event#event.rating_count,
created_at => datetime_to_iso8601(Event#event.created_at),
updated_at => datetime_to_iso8601(Event#event.updated_at)
}.
occurrence_to_json(Master, Occurrence) ->
#{
master_id => Master#event.id,
start_time => datetime_to_iso8601(Occurrence),
duration => Master#event.duration,
title => Master#event.title,
master_id => Master#event.id,
start_time => handler_utils:datetime_to_iso8601(Occurrence),
duration => Master#event.duration,
title => Master#event.title,
is_virtual => true
}.
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, []}.
}.