Рефакторинг обработчиков. Часть 1 #21
This commit is contained in:
@@ -1,109 +1,135 @@
|
||||
%%%-------------------------------------------------------------------
|
||||
%%% @doc Административный обработчик списка жалоб.
|
||||
%%% GET – список с пагинацией, фильтрацией и сортировкой.
|
||||
%%% @end
|
||||
%%%-------------------------------------------------------------------
|
||||
-module(admin_handler_reports).
|
||||
-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_reports(Req);
|
||||
<<"PUT">> -> update_report(Req);
|
||||
_ -> send_error(Req, 405, <<"Method not allowed">>)
|
||||
_ -> handler_utils:send_error(Req, 405, <<"Method not allowed">>)
|
||||
end.
|
||||
|
||||
list_reports(Req) ->
|
||||
case auth_admin(Req) of
|
||||
{ok, AdminId, Req1} ->
|
||||
case admin_utils:is_admin(AdminId) of
|
||||
true ->
|
||||
{ok, Reports} = core_report:list_all(),
|
||||
send_json(Req1, 200, [report_to_json(R) || R <- Reports]);
|
||||
false ->
|
||||
send_error(Req1, 403, <<"Admin access required">>)
|
||||
end;
|
||||
{error, Code, Message, Req1} ->
|
||||
send_error(Req1, Code, Message)
|
||||
end.
|
||||
-spec trails() -> [map()].
|
||||
trails() ->
|
||||
[
|
||||
#{
|
||||
path => <<"/v1/admin/reports">>,
|
||||
method => <<"GET">>,
|
||||
description => <<"List all reports (admin)">>,
|
||||
tags => [<<"Reports">>],
|
||||
parameters => [
|
||||
#{name => <<"status">>, in => <<"query">>, schema => #{type => string, enum => [<<"pending">>, <<"reviewed">>, <<"dismissed">>]}, description => <<"Filter by status">>},
|
||||
#{name => <<"target_type">>, in => <<"query">>, schema => #{type => string, enum => [<<"calendar">>, <<"event">>, <<"review">>]}, description => <<"Filter by target type">>},
|
||||
#{name => <<"q">>, in => <<"query">>, schema => #{type => string}, description => <<"Search in reason">>},
|
||||
#{name => <<"limit">>, in => <<"query">>, schema => #{type => integer}, description => <<"Page size">>},
|
||||
#{name => <<"offset">>, in => <<"query">>, schema => #{type => integer}, description => <<"Offset">>}
|
||||
],
|
||||
responses => #{
|
||||
200 => #{
|
||||
description => <<"Array of reports">>,
|
||||
content => #{<<"application/json">> => #{schema => #{
|
||||
type => array,
|
||||
items => report_schema()
|
||||
}}}
|
||||
}
|
||||
}
|
||||
}
|
||||
].
|
||||
|
||||
update_report(Req) ->
|
||||
case auth_admin(Req) of
|
||||
{ok, AdminId, Req1} ->
|
||||
case admin_utils:is_admin(AdminId) of
|
||||
true ->
|
||||
ReportId = cowboy_req:binding(id, Req1),
|
||||
{ok, Body, Req2} = cowboy_req:read_body(Req1),
|
||||
try jsx:decode(Body, [return_maps]) of
|
||||
#{<<"status">> := NewStatus, <<"reason">> := Reason} ->
|
||||
StatusAtom = binary_to_atom(NewStatus, utf8),
|
||||
case core_report:update_status(ReportId, StatusAtom, AdminId) of
|
||||
{ok, Report} ->
|
||||
log_audit(AdminId, <<"update_report_status">>, <<"report">>, ReportId, Reason),
|
||||
send_json(Req2, 200, report_to_json(Report));
|
||||
{error, not_found} ->
|
||||
send_error(Req2, 404, <<"Report not found">>);
|
||||
{error, _} ->
|
||||
send_error(Req2, 500, <<"Internal server error">>)
|
||||
end;
|
||||
_ ->
|
||||
send_error(Req2, 400, <<"Missing status or reason">>)
|
||||
catch
|
||||
_:_ -> send_error(Req2, 400, <<"Invalid JSON">>)
|
||||
end;
|
||||
false ->
|
||||
send_error(Req1, 403, <<"Admin access required">>)
|
||||
end;
|
||||
{error, Code, Message, Req1} ->
|
||||
send_error(Req1, Code, Message)
|
||||
end.
|
||||
|
||||
auth_admin(Req) ->
|
||||
case handler_auth:authenticate(Req) of
|
||||
{ok, AdminId, Req1} ->
|
||||
case admin_utils:is_admin(AdminId) of
|
||||
true -> {ok, AdminId, Req1};
|
||||
false -> {error, 403, <<"Admin access required">>, Req1}
|
||||
end;
|
||||
{error, Code, Message, Req1} ->
|
||||
{error, Code, Message, Req1}
|
||||
end.
|
||||
|
||||
log_audit(AdminId, Action, EntityType, EntityId, Reason) ->
|
||||
case core_admin:get_by_id(AdminId) of
|
||||
{ok, Admin} ->
|
||||
core_admin_audit:log(AdminId, Admin#admin.email, Admin#admin.role,
|
||||
Action, EntityType, EntityId,
|
||||
<<"127.0.0.1">>, Reason);
|
||||
_ -> ok
|
||||
end.
|
||||
|
||||
report_to_json(R) ->
|
||||
report_schema() ->
|
||||
#{
|
||||
id => R#report.id,
|
||||
reporter_id => R#report.reporter_id,
|
||||
target_type => R#report.target_type,
|
||||
target_id => R#report.target_id,
|
||||
reason => R#report.reason,
|
||||
status => R#report.status,
|
||||
created_at => datetime_to_iso8601(R#report.created_at),
|
||||
resolved_at => datetime_to_iso8601(R#report.resolved_at)
|
||||
type => object,
|
||||
properties => #{
|
||||
id => #{type => string},
|
||||
reporter_id => #{type => string},
|
||||
target_type => #{type => string, enum => [<<"calendar">>, <<"event">>, <<"review">>]},
|
||||
target_id => #{type => string},
|
||||
reason => #{type => string},
|
||||
status => #{type => string, enum => [<<"pending">>, <<"reviewed">>, <<"dismissed">>]},
|
||||
created_at => #{type => string, format => <<"date-time">>},
|
||||
resolved_at => #{type => string, format => <<"date-time">>, nullable => true},
|
||||
resolved_by => #{type => string, nullable => true}
|
||||
}
|
||||
}.
|
||||
|
||||
datetime_to_iso8601({{Year, Month, Day}, {Hour, Minute, Second}}) ->
|
||||
iolist_to_binary(io_lib:format("~4..0B-~2..0B-~2..0BT~2..0B:~2..0B:~2..0BZ",
|
||||
[Year, Month, Day, Hour, Minute, Second]));
|
||||
datetime_to_iso8601(undefined) -> undefined.
|
||||
%%% Internal functions
|
||||
|
||||
send_json(Req, Status, Data) ->
|
||||
Headers = #{
|
||||
<<"content-type">> => <<"application/json">>,
|
||||
<<"access-control-allow-origin">> => <<"*">>,
|
||||
<<"access-control-expose-headers">> => <<"Content-Range">>
|
||||
},
|
||||
Body = jsx:encode(Data),
|
||||
cowboy_req:reply(Status, Headers, Body, Req),
|
||||
{ok, Body, []}.
|
||||
-spec list_reports(cowboy_req:req()) -> {ok, binary(), cowboy_req:req()}.
|
||||
list_reports(Req) ->
|
||||
case handler_utils:auth_admin(Req) of
|
||||
{ok, AdminId, Req1} ->
|
||||
Filters = parse_report_filters(Req1),
|
||||
Pagination = handler_utils:parse_pagination_params(Req1),
|
||||
case logic_report:list_reports(AdminId) of
|
||||
{ok, AllReports} ->
|
||||
Filtered = apply_report_filters(AllReports, Filters),
|
||||
Sorted = sort_reports(Filtered, Pagination),
|
||||
Total = length(Sorted),
|
||||
Page = lists:sublist(Sorted, maps:get(offset, Pagination) + 1, maps:get(limit, Pagination)),
|
||||
Json = [handler_utils:report_to_json(R) || R <- Page],
|
||||
ExtraHeaders = pagination_headers(Pagination, Total),
|
||||
handler_utils:send_json(Req1, 200, Json, ExtraHeaders);
|
||||
{error, access_denied} ->
|
||||
handler_utils:send_error(Req1, 403, <<"Admin access required">>)
|
||||
end;
|
||||
{error, Code, Msg, Req1} ->
|
||||
handler_utils:send_error(Req1, Code, Msg)
|
||||
end.
|
||||
|
||||
send_error(Req, Status, Message) ->
|
||||
Body = jsx:encode(#{error => Message}),
|
||||
cowboy_req:reply(Status, #{<<"content-type">> => <<"application/json">>}, Body, Req),
|
||||
{ok, Body, []}.
|
||||
parse_report_filters(Req) ->
|
||||
Qs = cowboy_req:parse_qs(Req),
|
||||
#{
|
||||
status => proplists:get_value(<<"status">>, Qs),
|
||||
target_type => proplists:get_value(<<"target_type">>, Qs),
|
||||
q => proplists:get_value(<<"q">>, Qs)
|
||||
}.
|
||||
|
||||
apply_report_filters(Reports, Filters) ->
|
||||
Status = maps:get(status, Filters, undefined),
|
||||
TargetType = maps:get(target_type, Filters, undefined),
|
||||
Q = maps:get(q, Filters, undefined),
|
||||
F1 = case Status of
|
||||
undefined -> Reports;
|
||||
_ -> [R || R <- Reports, R#report.status =:= Status]
|
||||
end,
|
||||
F2 = case TargetType of
|
||||
undefined -> F1;
|
||||
_ -> [R || R <- F1, R#report.target_type =:= TargetType]
|
||||
end,
|
||||
case Q of
|
||||
undefined -> F2;
|
||||
_ -> [R || R <- F2,
|
||||
string:str(binary_to_list(R#report.reason), binary_to_list(Q)) > 0]
|
||||
end.
|
||||
|
||||
sort_reports(Reports, #{sort := Sort, order := Order}) ->
|
||||
Field = binary_to_existing_atom(Sort, utf8),
|
||||
lists:sort(
|
||||
fun(A, B) ->
|
||||
ValA = report_field(A, Field),
|
||||
ValB = report_field(B, Field),
|
||||
if Order == <<"asc">> -> ValA =< ValB;
|
||||
true -> ValA >= ValB
|
||||
end
|
||||
end, Reports).
|
||||
|
||||
report_field(#report{created_at = V}, created_at) -> V;
|
||||
report_field(#report{status = V}, status) -> V;
|
||||
report_field(_, _) -> undefined.
|
||||
|
||||
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">>
|
||||
}.
|
||||
Reference in New Issue
Block a user