Рефакторинг обработчиков. Часть 1 #21

This commit is contained in:
2026-05-10 22:14:38 +03:00
parent a35d6f7acc
commit 6403f061df
46 changed files with 3082 additions and 2091 deletions
+104 -69
View File
@@ -1,101 +1,136 @@
-module(admin_handler_reviews).
-behaviour(cowboy_handler).
-export([init/2]).
-export([trails/0]).
-include("records.hrl").
-export([init/2]).
%%% cowboy_handler callback
init(Req, _Opts) ->
case cowboy_req:method(Req) of
<<"GET">> -> list_reviews(Req);
<<"GET">> -> list_reviews(Req);
<<"PATCH">> -> bulk_update_reviews(Req);
_ -> send_error(Req, 405, <<"Method not allowed">>)
_ -> handler_utils:send_error(Req, 405, <<"Method not allowed">>)
end.
%%% Swagger metadata
trails() ->
[
#{ % GET list
path => <<"/v1/admin/reviews">>,
method => <<"GET">>,
description => <<"List all reviews (admin)">>,
tags => [<<"Reviews">>],
parameters => [
#{name => <<"target_type">>, in => <<"query">>, schema => #{type => string}, description => <<"calendar or event">>},
#{name => <<"target_id">>, in => <<"query">>, schema => #{type => string}, description => <<"ID of target">>},
#{name => <<"user_id">>, in => <<"query">>, schema => #{type => string}, description => <<"Filter by user">>},
#{name => <<"status">>, in => <<"query">>, schema => #{type => string}, description => <<"visible, hidden, deleted, or all">>},
#{name => <<"limit">>, in => <<"query">>, schema => #{type => integer}, description => <<"Page size">>},
#{name => <<"offset">>, in => <<"query">>, schema => #{type => integer}, description => <<"Offset">>}
],
responses => #{
200 => #{
description => <<"Array of reviews">>,
content => #{<<"application/json">> => #{schema => #{
type => array,
items => review_schema()
}}}
}
}
},
#{ % PATCH bulk update
path => <<"/v1/admin/reviews">>,
method => <<"PATCH">>,
description => <<"Bulk update review statuses">>,
tags => [<<"Reviews">>],
requestBody => #{
required => true,
content => #{<<"application/json">> => #{schema => #{
type => array,
items => #{
type => object,
properties => #{
id => #{type => string},
status => #{type => string, enum => [<<"visible">>, <<"hidden">>, <<"deleted">>]}
}
}
}}}
},
responses => #{
200 => #{description => <<"Number of updated reviews">>}
}
}
].
review_schema() ->
#{
type => object,
properties => #{
id => #{type => string},
user_id => #{type => string},
target_type => #{type => string, enum => [<<"calendar">>, <<"event">>]},
target_id => #{type => string},
rating => #{type => integer, minimum => 1, maximum => 5},
comment => #{type => string},
status => #{type => string, enum => [<<"visible">>, <<"hidden">>, <<"deleted">>]},
reason => #{type => string, nullable => true},
likes => #{type => integer},
dislikes => #{type => integer},
created_at => #{type => string, format => <<"date-time">>},
updated_at => #{type => string, format => <<"date-time">>}
}
}.
%%% Internal functions
list_reviews(Req) ->
case auth_admin(Req) of
case handler_utils:auth_admin(Req) of
{ok, _AdminId, Req1} ->
Filters = parse_filters(Req1),
Reviews = logic_review:list_admin_reviews(Filters),
Json = [review_to_json(R) || R <- Reviews],
send_json(Req1, 200, Json);
Filters = parse_review_filters(Req1),
Pagination = handler_utils:parse_pagination_params(Req1),
{ok, Total, Reviews} = logic_review:list_admin_reviews(Filters, Pagination),
Json = [handler_utils:review_to_json(R) || R <- Reviews],
ExtraHeaders = pagination_headers(Pagination, Total),
handler_utils:send_json(Req1, 200, Json, ExtraHeaders);
{error, Code, Msg, Req1} ->
send_error(Req1, Code, Msg)
handler_utils:send_error(Req1, Code, Msg)
end.
bulk_update_reviews(Req) ->
case auth_admin(Req) of
case handler_utils:auth_admin(Req) of
{ok, _AdminId, Req1} ->
try
{ok, Body, Req2} = cowboy_req:read_body(Req1),
Operations = jsx:decode(Body, [return_maps]),
true = is_list(Operations),
case logic_review:bulk_update_status(Operations) of
{ok, Count} ->
send_json(Req2, 200, #{updated_count => Count});
{ok, UpdatedCount} ->
handler_utils:send_json(Req2, 200, #{updated_count => UpdatedCount});
{error, Reason} ->
send_error(Req2, 400, Reason)
handler_utils:send_error(Req2, 400, Reason)
end
catch
_:_ -> send_error(Req1, 400, <<"Invalid JSON body">>)
_:_ -> handler_utils:send_error(Req1, 400, <<"Invalid JSON body">>)
end;
{error, Code, Msg, Req1} ->
send_error(Req1, Code, Msg)
handler_utils:send_error(Req1, Code, Msg)
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, Msg, Req1} ->
{error, Code, Msg, Req1}
end.
%% Извлечение параметров фильтрации из query string.
%% Например: ?target_type=event&target_id=...&user_id=...
parse_filters(Req) ->
parse_review_filters(Req) ->
Qs = cowboy_req:parse_qs(Req),
lists:filtermap(
fun
({<<"target_type">>, Val}) -> {true, {target_type, Val}};
({<<"target_id">>, Val}) -> {true, {target_id, Val}};
({<<"user_id">>, Val}) -> {true, {user_id, Val}};
(_) -> false
end,
Qs
).
review_to_json(R) ->
#{
id => R#review.id,
user_id => R#review.user_id,
target_type => R#review.target_type,
target_id => R#review.target_id,
rating => R#review.rating,
comment => R#review.comment,
status => R#review.status,
created_at => datetime_to_iso8601(R#review.created_at),
updated_at => datetime_to_iso8601(R#review.updated_at)
target_type => proplists:get_value(<<"target_type">>, Qs),
target_id => proplists:get_value(<<"target_id">>, Qs),
user_id => proplists:get_value(<<"user_id">>, Qs),
status => proplists:get_value(<<"status">>, Qs)
}.
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.
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, []}.
send_error(Req, Status, Message) ->
Body = jsx:encode(#{error => Message}),
cowboy_req:reply(Status, #{<<"content-type">> => <<"application/json">>}, Body, Req),
{ok, Body, []}.
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">>
}.