Files
EventHubBack/src/handlers/admin/admin_handler_users.erl
T
2026-05-28 21:55:34 +03:00

116 lines
4.9 KiB
Erlang

%%%-------------------------------------------------------------------
%%% @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">>)
end.
-spec trails() -> [map()].
trails() ->
[
#{
path => <<"/v1/admin/users">>,
method => <<"GET">>,
description => <<"List all users (admin)">>,
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 => <<"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,
items => user_schema()
}}}
}
}
}
].
-spec user_schema() -> map().
user_schema() ->
#{
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},
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">>}
}
}.
%%%===================================================================
%%% 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),
% Передаем параметры сортировки в бизнес-логику
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 = 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),
RoleBin = proplists:get_value(<<"role">>, Qs),
StatusBin = proplists:get_value(<<"status">>, Qs),
#{
role => convert_to_atom(RoleBin),
status => convert_to_atom(StatusBin),
q => proplists:get_value(<<"q">>, Qs)
}.
convert_to_atom(undefined) -> undefined;
convert_to_atom(Bin) when is_binary(Bin) ->
try binary_to_existing_atom(Bin, utf8)
catch error:badarg -> Bin
end.