Рефакторинг админских обработчиков - пагинация, сортировка, фильтрация. Часть 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
+53 -35
View File
@@ -1,36 +1,44 @@
%%%-------------------------------------------------------------------
%%% @doc Административный обработчик списка пользователей.
%%% GET – список пользователей с пагинацией, фильтрацией и сортировкой.
%%% @end
%%%-------------------------------------------------------------------
-module(admin_handler_users).
-behaviour(cowboy_handler).
-export([init/2]).
-export([trails/0]).
-include("records.hrl").
-spec init(cowboy_req:req(), any()) -> {ok, cowboy_req:req(), any()}.
init(Req, _Opts) ->
case cowboy_req:method(Req) of
<<"GET">> -> list_users(Req);
_ -> handler_utils:send_error(Req, 405, <<"Method not allowed">>)
_ -> handler_utils:send_error(Req, 405, <<"Method not allowed">>)
end.
-spec trails() -> [map()].
trails() ->
[
#{
path => <<"/v1/admin/users">>,
method => <<"GET">>,
path => <<"/v1/admin/users">>,
method => <<"GET">>,
description => <<"List all users (admin)">>,
tags => [<<"Users">>],
parameters => [
#{name => <<"role">>, in => <<"query">>, schema => #{type => string, enum => [<<"user">>, <<"bot">>]}},
tags => [<<"Users">>],
parameters => [
#{name => <<"role">>, in => <<"query">>, schema => #{type => string, enum => [<<"user">>, <<"bot">>]}},
#{name => <<"status">>, in => <<"query">>, schema => #{type => string, enum => [<<"active">>, <<"frozen">>, <<"deleted">>]}},
#{name => <<"q">>, in => <<"query">>, schema => #{type => string}, description => <<"Search by email or nickname">>},
#{name => <<"limit">>, in => <<"query">>, schema => #{type => integer}},
#{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 direction">>},
#{name => <<"limit">>, in => <<"query">>, schema => #{type => integer}},
#{name => <<"offset">>, in => <<"query">>, schema => #{type => integer}}
],
responses => #{
200 => #{
description => <<"Array of users">>,
content => #{<<"application/json">> => #{schema => #{
type => array,
type => array,
items => user_schema()
}}}
}
@@ -38,53 +46,63 @@ trails() ->
}
].
-spec user_schema() -> map().
user_schema() ->
#{
type => object,
type => object,
properties => #{
id => #{type => string},
email => #{type => string, format => <<"email">>},
role => #{type => string, enum => [<<"user">>, <<"bot">>]},
status => #{type => string, enum => [<<"active">>, <<"frozen">>, <<"deleted">>]},
reason => #{type => string, nullable => true},
nickname => #{type => string, nullable => true},
avatar_url => #{type => string, nullable => true},
timezone => #{type => string, nullable => true},
language => #{type => string, nullable => true},
id => #{type => string},
email => #{type => string, format => <<"email">>},
role => #{type => string, enum => [<<"user">>, <<"bot">>]},
status => #{type => string, enum => [<<"active">>, <<"frozen">>, <<"deleted">>]},
reason => #{type => string, nullable => true},
nickname => #{type => string, nullable => true},
avatar_url => #{type => string, nullable => true},
timezone => #{type => string, nullable => true},
language => #{type => string, nullable => true},
social_links => #{type => array, items => #{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">>}
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">>}
}
}.
%%%===================================================================
%%% HTTP-методы
%%%===================================================================
%% @doc GET /v1/admin/users – список пользователей.
-spec list_users(cowboy_req:req()) -> {ok, binary(), cowboy_req:req()}.
list_users(Req) ->
case handler_utils:auth_admin(Req) of
{ok, _AdminId, Req1} ->
Filters = parse_user_filters(Req1),
Pagination = handler_utils:parse_pagination_params(Req1),
{ok, Total, Users} = logic_user:list_users_admin(Filters, Pagination),
% Передаем параметры сортировки в бизнес-логику
PaginationWithSort = Pagination#{
sort => maps:get(sort, Pagination, <<"created_at">>),
order => maps:get(order, Pagination, <<"desc">>)
},
{ok, Total, Users} = logic_user:list_users_admin(Filters, PaginationWithSort),
Json = [handler_utils:user_to_json(U) || U <- Users],
ExtraHeaders = pagination_headers(Pagination, Total),
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)
end.
%%%===================================================================
%%% Вспомогательные функции
%%%===================================================================
%% @private Разбор query-параметров для фильтрации.
-spec parse_user_filters(cowboy_req:req()) -> map().
parse_user_filters(Req) ->
Qs = cowboy_req:parse_qs(Req),
#{
role => proplists:get_value(<<"role">>, Qs),
status => proplists:get_value(<<"status">>, Qs),
q => proplists:get_value(<<"q">>, Qs)
}.
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">>
}.