Refactor structure

This commit is contained in:
2026-04-23 09:59:53 +03:00
parent 081dcf9588
commit c154ceac39
6 changed files with 1 additions and 1 deletions

View File

@@ -0,0 +1,80 @@
-module(admin_handler_stats).
-include("records.hrl").
-export([init/2]).
-export([count_users/0, count_calendars/0, count_events/0, count_bookings/0,
count_reviews/0, count_reports/0, count_tickets/0, count_subscriptions/0]).
-export([is_admin/1]).
init(Req, Opts) ->
handle(Req, Opts).
handle(Req, _Opts) ->
case cowboy_req:method(Req) of
<<"GET">> -> get_stats(Req);
_ -> send_error(Req, 405, <<"Method not allowed">>)
end.
get_stats(Req) ->
case handler_auth:authenticate(Req) of
{ok, AdminId, Req1} ->
case is_admin(AdminId) of
true ->
Stats = #{
users => count_users(),
calendars => count_calendars(),
events => count_events(),
bookings => count_bookings(),
reviews => count_reviews(),
reports => count_reports(),
tickets => count_tickets(),
subscriptions => count_subscriptions()
},
send_json(Req1, 200, Stats);
false ->
send_error(Req1, 403, <<"Admin access required">>)
end;
{error, Code, Message, Req1} ->
send_error(Req1, Code, Message)
end.
%% Вспомогательные функции
is_admin(UserId) ->
case core_user:get_by_id(UserId) of
{ok, User} -> User#user.role =:= admin;
_ -> false
end.
count_users() ->
length(mnesia:dirty_match_object(#user{_ = '_'})).
count_calendars() ->
length(mnesia:dirty_match_object(#calendar{_ = '_'})).
count_events() ->
length(mnesia:dirty_match_object(#event{is_instance = false, _ = '_'})).
count_bookings() ->
length(mnesia:dirty_match_object(#booking{_ = '_'})).
count_reviews() ->
length(mnesia:dirty_match_object(#review{_ = '_'})).
count_reports() ->
length(mnesia:dirty_match_object(#report{_ = '_'})).
count_tickets() ->
length(mnesia:dirty_match_object(#ticket{_ = '_'})).
count_subscriptions() ->
length(mnesia:dirty_match_object(#subscription{_ = '_'})).
send_json(Req, Status, Data) ->
Body = jsx:encode(Data),
cowboy_req:reply(Status, #{<<"content-type">> => <<"application/json">>}, 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, []}.