Рефакторинг обработчиков. Часть 1 #21
This commit is contained in:
@@ -1,197 +1,122 @@
|
||||
%%%-------------------------------------------------------------------
|
||||
%%% @doc Административный обработчик подписок.
|
||||
%%% GET – список с пагинацией и фильтрацией.
|
||||
%%% @end
|
||||
%%%-------------------------------------------------------------------
|
||||
-module(admin_handler_subscriptions).
|
||||
-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:binding(id, Req) of
|
||||
undefined -> handle_collection(Req);
|
||||
_SubId -> handle_item(Req)
|
||||
end.
|
||||
|
||||
%% ================== Коллекция ==================
|
||||
handle_collection(Req) ->
|
||||
case cowboy_req:method(Req) of
|
||||
<<"GET">> -> list_subscriptions(Req);
|
||||
<<"POST">> -> create_subscription(Req);
|
||||
_ -> send_error(Req, 405, <<"Method not allowed">>)
|
||||
<<"GET">> -> list_subscriptions(Req);
|
||||
_ -> handler_utils:send_error(Req, 405, <<"Method not allowed">>)
|
||||
end.
|
||||
|
||||
%% ================== Элемент ==================
|
||||
handle_item(Req) ->
|
||||
SubId = cowboy_req:binding(id, Req),
|
||||
case cowboy_req:method(Req) of
|
||||
<<"GET">> -> get_subscription(SubId, Req);
|
||||
<<"PUT">> -> update_subscription(SubId, Req);
|
||||
<<"DELETE">> -> delete_subscription(SubId, Req);
|
||||
_ -> send_error(Req, 405, <<"Method not allowed">>)
|
||||
end.
|
||||
-spec trails() -> [map()].
|
||||
trails() ->
|
||||
[
|
||||
#{
|
||||
path => <<"/v1/admin/subscriptions">>,
|
||||
method => <<"GET">>,
|
||||
description => <<"List all subscriptions (admin)">>,
|
||||
tags => [<<"Subscriptions">>],
|
||||
parameters => [
|
||||
#{name => <<"plan">>, in => <<"query">>, schema => #{type => string, enum => [<<"monthly">>, <<"quarterly">>, <<"biannual">>, <<"annual">>]}, description => <<"Filter by plan">>},
|
||||
#{name => <<"status">>, in => <<"query">>, schema => #{type => string, enum => [<<"active">>, <<"expired">>, <<"cancelled">>]}, description => <<"Filter by status">>},
|
||||
#{name => <<"limit">>, in => <<"query">>, schema => #{type => integer}, description => <<"Page size">>},
|
||||
#{name => <<"offset">>, in => <<"query">>, schema => #{type => integer}, description => <<"Offset">>}
|
||||
],
|
||||
responses => #{
|
||||
200 => #{
|
||||
description => <<"Array of subscriptions">>,
|
||||
content => #{<<"application/json">> => #{schema => #{
|
||||
type => array,
|
||||
items => subscription_schema()
|
||||
}}}
|
||||
}
|
||||
}
|
||||
}
|
||||
].
|
||||
|
||||
%% ================== GET /subscriptions ==================
|
||||
list_subscriptions(Req) ->
|
||||
case auth_admin(Req) of
|
||||
{ok, _AdminId, Req1} ->
|
||||
Subs = core_subscription:list_subscriptions(),
|
||||
send_json(Req1, 200, [subscription_to_json(S) || S <- Subs]);
|
||||
{error, Code, Message, Req1} ->
|
||||
send_error(Req1, Code, Message)
|
||||
end.
|
||||
|
||||
%% ================== GET /subscriptions/:id ==================
|
||||
get_subscription(Id, Req) ->
|
||||
case auth_admin(Req) of
|
||||
{ok, _AdminId, Req1} ->
|
||||
case core_subscription:get_by_id(Id) of
|
||||
{ok, Sub} ->
|
||||
send_json(Req1, 200, subscription_to_json(Sub));
|
||||
{error, not_found} ->
|
||||
send_error(Req1, 404, <<"Subscription not found">>)
|
||||
end;
|
||||
{error, Code, Message, Req1} ->
|
||||
send_error(Req1, Code, Message)
|
||||
end.
|
||||
|
||||
%% ================== POST /subscriptions ==================
|
||||
create_subscription(Req) ->
|
||||
case auth_admin(Req) of
|
||||
{ok, AdminId, Req1} ->
|
||||
{ok, Body, Req2} = cowboy_req:read_body(Req1),
|
||||
try
|
||||
Decoded = jsx:decode(Body, [return_maps]),
|
||||
case Decoded of
|
||||
#{<<"user_id">> := UserId, <<"plan">> := Plan} ->
|
||||
case validate_plan(Plan) of
|
||||
true ->
|
||||
SubData = maps:merge(#{
|
||||
<<"status">> => <<"active">>,
|
||||
<<"trial_used">> => false
|
||||
}, maps:without([<<"id">>], Decoded)), % ← исправлено: Decoded, а не Body
|
||||
case core_subscription:create_subscription(SubData) of
|
||||
{ok, Sub} ->
|
||||
log_audit(AdminId, <<"create_subscription">>, <<"subscription">>, Sub#subscription.id, UserId),
|
||||
send_json(Req2, 201, subscription_to_json(Sub));
|
||||
{error, Reason} ->
|
||||
send_error(Req2, 500, Reason)
|
||||
end;
|
||||
false ->
|
||||
send_error(Req2, 400, <<"Invalid plan value">>)
|
||||
end;
|
||||
_ ->
|
||||
send_error(Req2, 400, <<"Missing 'user_id' or 'plan' field">>)
|
||||
end
|
||||
catch
|
||||
_:_ -> send_error(Req2, 400, <<"Invalid JSON">>)
|
||||
end;
|
||||
{error, Code, Message, Req1} ->
|
||||
send_error(Req1, Code, Message)
|
||||
end.
|
||||
|
||||
%% ================== PUT /subscriptions/:id ==================
|
||||
update_subscription(Id, Req) ->
|
||||
case auth_admin(Req) of
|
||||
{ok, AdminId, Req1} ->
|
||||
{ok, Body, Req2} = cowboy_req:read_body(Req1),
|
||||
try
|
||||
Updates = jsx:decode(Body, [return_maps]),
|
||||
case map_size(Updates) > 0 of
|
||||
true ->
|
||||
case core_subscription:update_subscription(Id, Updates) of
|
||||
{ok, Sub} ->
|
||||
log_audit(AdminId, <<"update_subscription">>, <<"subscription">>, Id, <<"">>),
|
||||
send_json(Req2, 200, subscription_to_json(Sub));
|
||||
{error, not_found} ->
|
||||
send_error(Req2, 404, <<"Subscription not found">>);
|
||||
{error, Reason} ->
|
||||
send_error(Req2, 500, Reason)
|
||||
end;
|
||||
false ->
|
||||
send_error(Req2, 400, <<"Request body is empty">>)
|
||||
end
|
||||
catch
|
||||
_:_ -> send_error(Req2, 400, <<"Invalid JSON">>)
|
||||
end;
|
||||
{error, Code, Message, Req1} ->
|
||||
send_error(Req1, Code, Message)
|
||||
end.
|
||||
|
||||
%% ================== DELETE /subscriptions/:id ==================
|
||||
delete_subscription(Id, Req) ->
|
||||
case auth_admin(Req) of
|
||||
{ok, AdminId, Req1} ->
|
||||
case core_subscription:delete_subscription(Id) of
|
||||
{ok, deleted} ->
|
||||
log_audit(AdminId, <<"delete_subscription">>, <<"subscription">>, Id, <<"">>),
|
||||
send_json(Req1, 200, #{status => <<"deleted">>});
|
||||
{error, not_found} ->
|
||||
send_error(Req1, 404, <<"Subscription not found">>)
|
||||
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.
|
||||
|
||||
%% ================== Сериализация ==================
|
||||
subscription_to_json(S) ->
|
||||
subscription_schema() ->
|
||||
#{
|
||||
id => S#subscription.id,
|
||||
user_id => S#subscription.user_id,
|
||||
plan => atom_to_binary(S#subscription.plan, utf8),
|
||||
status => atom_to_binary(S#subscription.status, utf8),
|
||||
trial_used => S#subscription.trial_used,
|
||||
started_at => datetime_to_iso8601(S#subscription.started_at),
|
||||
expires_at => datetime_to_iso8601(S#subscription.expires_at),
|
||||
created_at => datetime_to_iso8601(S#subscription.created_at),
|
||||
updated_at => datetime_to_iso8601(S#subscription.updated_at)
|
||||
type => object,
|
||||
properties => #{
|
||||
id => #{type => string},
|
||||
user_id => #{type => string},
|
||||
plan => #{type => string, enum => [<<"monthly">>, <<"quarterly">>, <<"biannual">>, <<"annual">>]},
|
||||
status => #{type => string, enum => [<<"active">>, <<"expired">>, <<"cancelled">>]},
|
||||
trial_used => #{type => boolean},
|
||||
started_at => #{type => string, format => <<"date-time">>},
|
||||
expires_at => #{type => string, format => <<"date-time">>},
|
||||
created_at => #{type => string, format => <<"date-time">>},
|
||||
updated_at => #{type => string, format => <<"date-time">>}
|
||||
}
|
||||
}.
|
||||
|
||||
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
|
||||
|
||||
%% ================== Валидация ==================
|
||||
validate_plan(Plan) when is_binary(Plan) ->
|
||||
lists:member(Plan, [<<"monthly">>, <<"yearly">>, <<"quarterly">>, <<"biannual">>, <<"annual">>]);
|
||||
validate_plan(_) -> false.
|
||||
list_subscriptions(Req) ->
|
||||
case handler_utils:auth_admin(Req) of
|
||||
{ok, _AdminId, Req1} ->
|
||||
Filters = parse_subscription_filters(Req1),
|
||||
Pagination = handler_utils:parse_pagination_params(Req1),
|
||||
{ok, AllSubscriptions} = core_subscription:list_all(),
|
||||
Filtered = apply_filters(AllSubscriptions, Filters),
|
||||
Sorted = sort_subscriptions(Filtered, Pagination),
|
||||
Total = length(Sorted),
|
||||
Page = lists:sublist(Sorted, maps:get(offset, Pagination) + 1, maps:get(limit, Pagination)),
|
||||
Json = [handler_utils:subscription_to_json(S) || S <- Page],
|
||||
ExtraHeaders = pagination_headers(Pagination, Total),
|
||||
handler_utils:send_json(Req1, 200, Json, ExtraHeaders);
|
||||
{error, Code, Msg, Req1} ->
|
||||
handler_utils:send_error(Req1, Code, Msg)
|
||||
end.
|
||||
|
||||
%% ================== HTTP-ответы ==================
|
||||
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, []}.
|
||||
parse_subscription_filters(Req) ->
|
||||
Qs = cowboy_req:parse_qs(Req),
|
||||
#{
|
||||
plan => proplists:get_value(<<"plan">>, Qs),
|
||||
status => proplists:get_value(<<"status">>, Qs)
|
||||
}.
|
||||
|
||||
send_error(Req, Code, Message) ->
|
||||
Headers = #{
|
||||
<<"content-type">> => <<"application/json">>,
|
||||
<<"access-control-allow-origin">> => <<"*">>,
|
||||
<<"access-control-expose-headers">> => <<"Content-Range">>
|
||||
},
|
||||
Body = jsx:encode(#{error => Message}),
|
||||
cowboy_req:reply(Code, Headers, Body, Req),
|
||||
{ok, Body, []}.
|
||||
apply_filters(Subs, Filters) ->
|
||||
Plan = maps:get(plan, Filters, undefined),
|
||||
Status = maps:get(status, Filters, undefined),
|
||||
F1 = case Plan of
|
||||
undefined -> Subs;
|
||||
_ -> [S || S <- Subs, S#subscription.plan =:= Plan]
|
||||
end,
|
||||
case Status of
|
||||
undefined -> F1;
|
||||
_ -> [S || S <- F1, S#subscription.status =:= Status]
|
||||
end.
|
||||
|
||||
sort_subscriptions(Subs, #{sort := Sort, order := Order}) ->
|
||||
Field = binary_to_existing_atom(Sort, utf8),
|
||||
lists:sort(
|
||||
fun(A, B) ->
|
||||
ValA = sub_field(A, Field),
|
||||
ValB = sub_field(B, Field),
|
||||
if Order == <<"asc">> -> ValA =< ValB;
|
||||
true -> ValA >= ValB
|
||||
end
|
||||
end, Subs).
|
||||
|
||||
sub_field(#subscription{created_at = V}, created_at) -> V;
|
||||
sub_field(#subscription{expires_at = V}, expires_at) -> V;
|
||||
sub_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