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

This commit is contained in:
2026-05-10 22:14:38 +03:00
parent a35d6f7acc
commit 6403f061df
46 changed files with 3082 additions and 2091 deletions
+63 -160
View File
@@ -7,50 +7,45 @@
-include("records.hrl").
%%%===================================================================
%%% cowboy_handler callbacks
%%% cowboy_handler callback
%%%===================================================================
init(Req, _Opts) ->
case cowboy_req:method(Req) of
<<"GET">> -> list_all_events(Req);
_ -> send_error(Req, 405, <<"Method not allowed">>)
_ -> handler_utils:send_error(Req, 405, <<"Method not allowed">>)
end.
%%%===================================================================
%%% Swagger / Trails metadata
%%% Swagger metadata
%%%===================================================================
trails() ->
[
#{
path => <<"/v1/admin/events">>,
method => <<"GET">>,
handler => ?MODULE,
tags => [<<"Events">>],
path => <<"/v1/admin/events">>,
method => <<"GET">>,
description => <<"Search and list events (admin)">>,
parameters => [
#{name => <<"from">>, in => <<"query">>, description => <<"ISO8601 start datetime">>, required => false, schema => #{type => string}},
#{name => <<"to">>, in => <<"query">>, description => <<"ISO8601 end datetime">>, required => false, schema => #{type => string}},
#{name => <<"status">>, in => <<"query">>, description => <<"active, cancelled, completed, or all">>, required => false, schema => #{type => string}},
#{name => <<"calendar_id">>, in => <<"query">>, description => <<"Filter by calendar ID">>, required => false, schema => #{type => string}},
#{name => <<"title">>, in => <<"query">>, description => <<"Exact title match">>, required => false, schema => #{type => string}},
#{name => <<"q">>, in => <<"query">>, description => <<"Substring search in title/description">>, required => false, schema => #{type => string}},
#{name => <<"limit">>, in => <<"query">>, description => <<"Page size (max 200)">>, required => false, schema => #{type => integer}},
#{name => <<"offset">>, in => <<"query">>, description => <<"Offset">>, required => false, schema => #{type => integer}},
#{name => <<"sort">>, in => <<"query">>, description => <<"created_at, start_time, title, status">>, required => false, schema => #{type => string}},
#{name => <<"order">>, in => <<"query">>, description => <<"asc or desc">>, required => false, schema => #{type => string, enum => [<<"asc">>, <<"desc">>]}}
tags => [<<"Events">>],
parameters => [
#{name => <<"from">>, in => <<"query">>, description => <<"ISO8601 start datetime">>, required => false, schema => #{type => string}},
#{name => <<"to">>, in => <<"query">>, description => <<"ISO8601 end datetime">>, required => false, schema => #{type => string}},
#{name => <<"status">>, in => <<"query">>, description => <<"active, cancelled, completed, or all">>, required => false, schema => #{type => string}},
#{name => <<"calendar_id">>, in => <<"query">>, description => <<"Filter by calendar ID">>, required => false, schema => #{type => string}},
#{name => <<"title">>, in => <<"query">>, description => <<"Exact title match">>, required => false, schema => #{type => string}},
#{name => <<"q">>, in => <<"query">>, description => <<"Substring search in title/description">>, required => false, schema => #{type => string}},
#{name => <<"limit">>, in => <<"query">>, description => <<"Page size (max 200)">>, required => false, schema => #{type => integer}},
#{name => <<"offset">>, in => <<"query">>, description => <<"Offset">>, required => false, schema => #{type => integer}},
#{name => <<"sort">>, in => <<"query">>, description => <<"created_at, start_time, title, status">>, required => false, schema => #{type => string}},
#{name => <<"order">>, in => <<"query">>, description => <<"asc or desc">>, required => false, schema => #{type => string, enum => [<<"asc">>, <<"desc">>]}}
],
responses => #{
200 => #{
description => <<"Array of events with Content-Range header">>,
content => #{
<<"application/json">> => #{
schema => #{
type => array,
items => event_schema()
}
}
}
content => #{<<"application/json">> => #{schema => #{
type => array,
items => event_schema()
}}}
},
405 => #{description => <<"Method not allowed">>}
}
@@ -59,28 +54,31 @@ trails() ->
event_schema() ->
#{
type => object,
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">>]},
rating_avg => #{type => number, format => float},
rating_count => #{type => integer},
created_at => #{type => string, format => <<"date-time">>},
updated_at => #{type => string, format => <<"date-time">>}
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">>}
}
}.
@@ -89,131 +87,36 @@ event_schema() ->
%%%===================================================================
list_all_events(Req) ->
case auth_admin(Req) of
case handler_utils:auth_admin(Req) of
{ok, _AdminId, Req1} ->
Params = parse_admin_event_search(Req1),
{ok, Total, Events} = logic_event:search_events(Params),
Json = [event_to_json(E) || E <- Events],
Limit = maps:get(limit, Params, 50),
Json = [handler_utils:event_to_json(E) || E <- Events],
Limit = maps:get(limit, Params, 50),
Offset = maps:get(offset, Params, 0),
RangeEnd = min(Offset + Limit - 1, Total - 1),
Headers = #{
<<"content-type">> => <<"application/json">>,
<<"content-range">> => iolist_to_binary(
io_lib:format("items ~B-~B/~B", [Offset, RangeEnd, Total])),
<<"x-total-count">> => integer_to_binary(Total),
<<"content-type">> => <<"application/json">>,
<<"content-range">> => iolist_to_binary(io_lib:format("items ~B-~B/~B", [Offset, RangeEnd, Total])),
<<"x-total-count">> => integer_to_binary(Total),
<<"access-control-expose-headers">> => <<"Content-Range, X-Total-Count">>
},
send_json(Req1, 200, Json, Headers);
handler_utils:send_json(Req1, 200, Json, Headers);
{error, Code, Msg, Req1} ->
send_error(Req1, Code, Msg)
handler_utils:send_error(Req1, Code, Msg)
end.
parse_admin_event_search(Req) ->
Qs = cowboy_req:parse_qs(Req),
#{
from => parse_datetime_qs(proplists:get_value(<<"from">>, Qs)),
to => parse_datetime_qs(proplists:get_value(<<"to">>, Qs)),
status => proplists:get_value(<<"status">>, Qs, undefined),
from => handler_utils:parse_datetime_qs(proplists:get_value(<<"from">>, Qs)),
to => handler_utils:parse_datetime_qs(proplists:get_value(<<"to">>, Qs)),
status => proplists:get_value(<<"status">>, Qs, undefined),
calendar_id => proplists:get_value(<<"calendar_id">>, Qs, undefined),
title => proplists:get_value(<<"title">>, Qs, undefined),
q => proplists:get_value(<<"q">>, Qs, undefined),
limit => parse_int_qs(proplists:get_value(<<"limit">>, Qs), 50),
offset => parse_int_qs(proplists:get_value(<<"offset">>, Qs), 0),
sort => proplists:get_value(<<"sort">>, Qs, <<"created_at">>),
order => proplists:get_value(<<"order">>, Qs, <<"desc">>)
}.
auth_admin(Req) ->
case handler_auth:authenticate(Req) of
{ok, AdminId, Req1} ->
case admin_utils:is_admin(AdminId) of
true -> {ok, AdminId, Req1};
false -> {error, 403, <<"Admin access required">>, Req1}
end;
{error, Code, Msg, Req1} ->
{error, Code, Msg, Req1}
end.
parse_int_qs(undefined, Default) -> Default;
parse_int_qs(Bin, Default) ->
try binary_to_integer(Bin) catch _:_ -> Default end.
parse_datetime_qs(undefined) -> undefined;
parse_datetime_qs(Bin) ->
case parse_datetime(Bin) of {ok, Dt} -> Dt; _ -> undefined end.
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(list_to_binary(YearStr)),
Month = binary_to_integer(list_to_binary(MonthStr)),
Day = binary_to_integer(list_to_binary(DayStr)),
Hour = binary_to_integer(list_to_binary(HourStr)),
Minute = binary_to_integer(list_to_binary(MinuteStr)),
Second = binary_to_integer(list_to_binary(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 ->
try jsx:decode(Rule, [return_maps]) of
Map when is_map(Map) -> Map;
_ -> null
catch _:_ -> null
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)
}.
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]
)
);
datetime_to_iso8601(undefined) ->
undefined.
send_json(Req, Status, Data, ExtraHeaders) ->
Body = jsx:encode(Data),
Headers = maps:merge(#{<<"content-type">> => <<"application/json">>}, ExtraHeaders),
cowboy_req:reply(Status, Headers, 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, []}.
title => proplists:get_value(<<"title">>, Qs, undefined),
q => proplists:get_value(<<"q">>, Qs, undefined),
limit => handler_utils:parse_int_qs(proplists:get_value(<<"limit">>, Qs), 50),
offset => handler_utils:parse_int_qs(proplists:get_value(<<"offset">>, Qs), 0),
sort => proplists:get_value(<<"sort">>, Qs, <<"created_at">>),
order => proplists:get_value(<<"order">>, Qs, <<"desc">>)
}.