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

This commit is contained in:
2026-05-13 23:02:59 +03:00
parent 61bb44ab4a
commit 40806df62a
91 changed files with 6138 additions and 7150 deletions
+105 -29
View File
@@ -1,3 +1,9 @@
%%%-------------------------------------------------------------------
%%% @doc Административный обработчик списка администраторов.
%%% GET – список всех администраторов (только для superadmin).
%%% POST – создать нового администратора (только для superadmin).
%%% @end
%%%-------------------------------------------------------------------
-module(admin_handler_admins).
-behaviour(cowboy_handler).
@@ -6,37 +12,66 @@
-include("records.hrl").
%%% cowboy_handler callback
-spec init(cowboy_req:req(), any()) -> {ok, cowboy_req:req(), any()}.
init(Req, _Opts) ->
case cowboy_req:method(Req) of
<<"GET">> -> list_admins(Req);
_ -> handler_utils:send_error(Req, 405, <<"Method not allowed">>)
<<"GET">> -> list_admins(Req);
<<"POST">> -> create_admin(Req);
_ -> handler_utils:send_error(Req, 405, <<"Method not allowed">>)
end.
%%% Swagger metadata
-spec trails() -> [map()].
trails() ->
[
#{
path => <<"/v1/admin/admins">>,
method => <<"GET">>,
description => <<"List all admins (superadmin only)">>,
tags => [<<"Admins">>],
parameters => [
#{name => <<"role">>, in => <<"query">>, schema => #{type => string}},
#{name => <<"status">>, in => <<"query">>, schema => #{type => string}},
#{name => <<"limit">>, in => <<"query">>, schema => #{type => integer}},
#{name => <<"offset">>, in => <<"query">>, schema => #{type => integer}}
],
responses => #{
200 => #{
description => <<"Array of admins">>,
content => #{<<"application/json">> => #{schema => #{
type => array,
items => admin_schema()
}}}
}
ListGet = #{
path => <<"/v1/admin/admins">>,
method => <<"GET">>,
description => <<"List all admins (superadmin only)">>,
tags => [<<"Admins">>],
parameters => [
#{name => <<"role">>, in => <<"query">>, schema => #{type => string}},
#{name => <<"status">>, in => <<"query">>, schema => #{type => string}},
#{name => <<"limit">>, in => <<"query">>, schema => #{type => integer}},
#{name => <<"offset">>, in => <<"query">>, schema => #{type => integer}}
],
responses => #{
200 => #{
description => <<"Array of admins">>,
content => #{<<"application/json">> => #{schema => #{
type => array,
items => admin_schema()
}}}
}
}
].
},
PostCreate = #{
path => <<"/v1/admin/admins">>,
method => <<"POST">>,
description => <<"Create a new admin (superadmin only)">>,
tags => [<<"Admins">>],
requestBody => #{
required => true,
content => #{<<"application/json">> => #{schema => #{
type => object,
required => [<<"email">>, <<"password">>, <<"role">>],
properties => #{
email => #{type => string, format => <<"email">>},
password => #{type => string},
role => #{type => string, enum => [<<"superadmin">>, <<"admin">>, <<"moderator">>, <<"support">>]}
}
}}}
},
responses => #{
201 => #{description => <<"Admin created">>},
400 => #{description => <<"Invalid fields">>},
403 => #{description => <<"Only superadmin can create admins">>},
409 => #{description => <<"Email already exists">>}
}
},
[ListGet, PostCreate].
-spec admin_schema() -> map().
admin_schema() ->
#{
type => object,
@@ -57,8 +92,12 @@ admin_schema() ->
}
}.
%%% Internal functions
%% @doc GET /v1/admin/admins – список администраторов.
-spec list_admins(cowboy_req:req()) -> {ok, binary(), cowboy_req:req()}.
list_admins(Req) ->
case handler_utils:auth_admin(Req) of
case handler_utils:is_superadmin(Req) of
{ok, _AdminId, Req1} ->
Filters = parse_admin_filters(Req1),
Pagination = handler_utils:parse_pagination_params(Req1),
@@ -70,6 +109,41 @@ list_admins(Req) ->
handler_utils:send_error(Req1, Code, Msg)
end.
%% @doc POST /v1/admin/admins – создание администратора.
-spec create_admin(cowboy_req:req()) -> {ok, binary(), cowboy_req:req()}.
create_admin(Req) ->
case handler_utils:is_superadmin(Req) of
{ok, _AdminId, Req1} ->
{ok, Body, Req2} = cowboy_req:read_body(Req1),
try jsx:decode(Body, [return_maps]) of
#{<<"email">> := Email, <<"password">> := Password, <<"role">> := RoleBin} ->
Role = try binary_to_existing_atom(RoleBin, utf8)
catch error:badarg -> undefined
end,
case Role of
undefined ->
handler_utils:send_error(Req2, 400, <<"Invalid role">>);
_ ->
case logic_admin:create_admin(Email, Password, Role) of
{ok, Admin} ->
handler_utils:send_json(Req2, 201, admin_to_json(Admin));
{error, email_exists} ->
handler_utils:send_error(Req2, 409, <<"Email already exists">>);
{error, invalid_role} ->
handler_utils:send_error(Req2, 400, <<"Invalid role">>);
{error, _} ->
handler_utils:send_error(Req2, 500, <<"Internal server error">>)
end
end;
_ -> handler_utils:send_error(Req2, 400, <<"Missing fields">>)
catch
_:_ -> handler_utils:send_error(Req1, 400, <<"Invalid JSON">>)
end;
{error, Code, Msg, Req1} ->
handler_utils:send_error(Req1, Code, Msg)
end.
-spec parse_admin_filters(cowboy_req:req()) -> map().
parse_admin_filters(Req) ->
Qs = cowboy_req:parse_qs(Req),
#{
@@ -77,23 +151,25 @@ parse_admin_filters(Req) ->
status => proplists:get_value(<<"status">>, Qs)
}.
-spec admin_to_json(#admin{}) -> map().
admin_to_json(Admin) ->
#{
id => Admin#admin.id,
email => Admin#admin.email,
role => Admin#admin.role,
status => Admin#admin.status,
role => atom_to_binary(Admin#admin.role, utf8),
status => atom_to_binary(Admin#admin.status, utf8),
nickname => Admin#admin.nickname,
avatar_url => Admin#admin.avatar_url,
timezone => Admin#admin.timezone,
language => Admin#admin.language,
phone => Admin#admin.phone,
preferences => Admin#admin.preferences,
last_login => handler_utils:parse_datetime(Admin#admin.last_login), % требует доработки – лучше общую функцию
created_at => handler_utils:parse_datetime(Admin#admin.created_at),
updated_at => handler_utils:parse_datetime(Admin#admin.updated_at)
last_login => handler_utils:datetime_to_iso8601(Admin#admin.last_login),
created_at => handler_utils:datetime_to_iso8601(Admin#admin.created_at),
updated_at => handler_utils:datetime_to_iso8601(Admin#admin.updated_at)
}.
-spec pagination_headers(map(), non_neg_integer()) -> map().
pagination_headers(#{limit := Limit, offset := Offset}, Total) ->
RangeEnd = min(Offset + Limit - 1, Total - 1),
#{