Рефакторинг админских обработчиков - пагинация, сортировка, фильтрация. Часть 1

This commit is contained in:
2026-05-26 13:04:31 +03:00
parent 01dbc6d6cb
commit ed5b275efb
24 changed files with 1009 additions and 1126 deletions
+46 -61
View File
@@ -6,7 +6,6 @@
%%%-------------------------------------------------------------------
-module(admin_handler_admins).
-behaviour(cowboy_handler).
-export([init/2]).
-export([trails/0]).
@@ -18,20 +17,23 @@ init(Req, _Opts) ->
case cowboy_req:method(Req) of
<<"GET">> -> list_admins(Req);
<<"POST">> -> create_admin(Req);
_ -> handler_utils:send_error(Req, 405, <<"Method not allowed">>)
_ -> handler_utils:send_error(Req, 405, <<"Method not allowed">>)
end.
%%% Swagger metadata
-spec trails() -> [map()].
trails() ->
ListGet = #{
path => <<"/v1/admin/admins">>,
method => <<"GET">>,
path => <<"/v1/admin/admins">>,
method => <<"GET">>,
description => <<"List all admins (superadmin only)">>,
tags => [<<"Admins">>],
parameters => [
tags => [<<"Admins">>],
parameters => [
#{name => <<"role">>, in => <<"query">>, schema => #{type => string}},
#{name => <<"status">>, in => <<"query">>, schema => #{type => string}},
#{name => <<"q">>, in => <<"query">>, schema => #{type => string}, description => <<"Search by email or nickname">>},
#{name => <<"sort">>, in => <<"query">>, schema => #{type => string, enum => [<<"email">>, <<"role">>, <<"created_at">>]}, description => <<"Sort field">>},
#{name => <<"order">>, in => <<"query">>, schema => #{type => string, enum => [<<"asc">>, <<"desc">>]}, description => <<"Sort order">>},
#{name => <<"limit">>, in => <<"query">>, schema => #{type => integer}},
#{name => <<"offset">>, in => <<"query">>, schema => #{type => integer}}
],
@@ -39,22 +41,22 @@ trails() ->
200 => #{
description => <<"Array of admins">>,
content => #{<<"application/json">> => #{schema => #{
type => array,
type => array,
items => admin_schema()
}}}
}
}
},
PostCreate = #{
path => <<"/v1/admin/admins">>,
method => <<"POST">>,
path => <<"/v1/admin/admins">>,
method => <<"POST">>,
description => <<"Create a new admin (superadmin only)">>,
tags => [<<"Admins">>],
tags => [<<"Admins">>],
requestBody => #{
required => true,
content => #{<<"application/json">> => #{schema => #{
type => object,
required => [<<"email">>, <<"password">>, <<"role">>],
content => #{<<"application/json">> => #{schema => #{
type => object,
required => [<<"email">>, <<"password">>, <<"role">>],
properties => #{
email => #{type => string, format => <<"email">>},
password => #{type => string},
@@ -74,25 +76,27 @@ trails() ->
-spec admin_schema() -> map().
admin_schema() ->
#{
type => object,
type => object,
properties => #{
id => #{type => string},
email => #{type => string, format => <<"email">>},
role => #{type => string, enum => [<<"superadmin">>, <<"admin">>, <<"moderator">>, <<"support">>]},
status => #{type => string, enum => [<<"active">>, <<"blocked">>]},
nickname => #{type => string, nullable => true},
avatar_url => #{type => string, nullable => true},
timezone => #{type => string, nullable => true},
language => #{type => string, nullable => true},
phone => #{type => string, nullable => true},
preferences => #{type => object, nullable => true},
last_login => #{type => string, format => <<"date-time">>},
created_at => #{type => string, format => <<"date-time">>},
updated_at => #{type => string, format => <<"date-time">>}
id => #{type => string},
email => #{type => string, format => <<"email">>},
role => #{type => string, enum => [<<"superadmin">>, <<"admin">>, <<"moderator">>, <<"support">>]},
status => #{type => string, enum => [<<"active">>, <<"blocked">>]},
nickname => #{type => string, nullable => true},
avatar_url => #{type => string, nullable => true},
timezone => #{type => string, nullable => true},
language => #{type => string, nullable => true},
phone => #{type => string, nullable => true},
preferences => #{type => object, nullable => true},
last_login => #{type => string, format => <<"date-time">>},
created_at => #{type => string, format => <<"date-time">>},
updated_at => #{type => string, format => <<"date-time">>}
}
}.
%%% Internal functions
%%%===================================================================
%%% HTTP-методы
%%%===================================================================
%% @doc GET /v1/admin/admins – список администраторов.
-spec list_admins(cowboy_req:req()) -> {ok, binary(), cowboy_req:req()}.
@@ -102,8 +106,8 @@ list_admins(Req) ->
Filters = parse_admin_filters(Req1),
Pagination = handler_utils:parse_pagination_params(Req1),
{ok, Total, Admins} = logic_admin:list_admins(Filters, Pagination),
Json = [admin_to_json(A) || A <- Admins],
ExtraHeaders = pagination_headers(Pagination, Total),
Json = [handler_utils:admin_to_json(A) || A <- Admins],
ExtraHeaders = handler_utils:pagination_headers(Pagination, Total),
handler_utils:send_json(Req1, 200, Json, ExtraHeaders);
{error, Code, Msg, Req1} ->
handler_utils:send_error(Req1, Code, Msg)
@@ -113,7 +117,7 @@ list_admins(Req) ->
-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, SuperAdminId, Req1} ->
{ok, Body, Req2} = cowboy_req:read_body(Req1),
try jsx:decode(Body, [return_maps]) of
#{<<"email">> := Email, <<"password">> := Password, <<"role">> := RoleBin} ->
@@ -126,7 +130,8 @@ create_admin(Req) ->
_ ->
case logic_admin:create_admin(Email, Password, Role) of
{ok, Admin} ->
handler_utils:send_json(Req2, 201, admin_to_json(Admin));
admin_utils:log_admin_action(SuperAdminId, <<"create_admin">>, <<"admin">>, Email, Req2),
handler_utils:send_json(Req2, 201, handler_utils:admin_to_json(Admin));
{error, email_exists} ->
handler_utils:send_error(Req2, 409, <<"Email already exists">>);
{error, invalid_role} ->
@@ -135,7 +140,8 @@ create_admin(Req) ->
handler_utils:send_error(Req2, 500, <<"Internal server error">>)
end
end;
_ -> handler_utils:send_error(Req2, 400, <<"Missing fields">>)
_ ->
handler_utils:send_error(Req2, 400, <<"Missing fields">>)
catch
_:_ -> handler_utils:send_error(Req1, 400, <<"Invalid JSON">>)
end;
@@ -143,37 +149,16 @@ create_admin(Req) ->
handler_utils:send_error(Req1, Code, Msg)
end.
%%%===================================================================
%%% Вспомогательные функции
%%%===================================================================
%% @private Разбор query-параметров для фильтрации.
-spec parse_admin_filters(cowboy_req:req()) -> map().
parse_admin_filters(Req) ->
Qs = cowboy_req:parse_qs(Req),
#{
role => proplists:get_value(<<"role">>, Qs),
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 => 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: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),
#{
<<"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">>
status => proplists:get_value(<<"status">>, Qs),
q => proplists:get_value(<<"q">>, Qs)
}.