-module(admin_handler_subscription_stats_tests). -include_lib("eunit/include/eunit.hrl"). -include("records.hrl"). -define(TABLES, [admin, admin_audit, subscription, ticket]). -define(ADMIN_ID, <<"adm_test_1">>). setup() -> eh_test_support:start_mnesia(), eh_test_support:ensure_tables(?TABLES), eh_test_support:ensure_jwt(), eh_test_support:seed_admin(#{id => ?ADMIN_ID}), ok. cleanup(_) -> eh_test_support:unload_cowboy(), eh_test_support:delete_tables(?TABLES), eh_test_support:stop_mnesia(), ok. admin_subscription_stats_test_() -> {foreach, fun setup/0, fun cleanup/1, [ {"GET stats – empty", {timeout, 60, fun test_stats_empty/0}}, {"GET stats – with subscriptions", {timeout, 60, fun test_stats_with_data/0}}, {"GET – unauthorized", {timeout, 60, fun test_unauthorized/0}}, {"POST – method not allowed", {timeout, 60, fun test_wrong_method/0}} ]}. test_stats_empty() -> {Status, _, Body} = eh_test_support:call(admin_handler_subscription_stats, #{ method => <<"GET">>, path => <<"/v1/admin/subscriptions/stats">>, auth => ?ADMIN_ID }), ?assertEqual(200, Status), Result = jsx:decode(Body, [return_maps]), ?assertEqual(0, maps:get(<<"total_subscriptions">>, Result)), ?assertEqual(0, maps:get(<<"trial_subscriptions">>, Result)), ?assertEqual([], maps:get(<<"ending_paid_subscriptions">>, Result)). test_stats_with_data() -> {ok, _} = core_subscription:create(<<"u1">>, monthly, false), Now = calendar:universal_time(), Expires = eh_test_support:days_from_now(15), ok = mnesia:dirty_write(#subscription{ id = <<"sub_paid">>, user_id = <<"u2">>, plan = annual, status = active, trial_used = true, started_at = Now, expires_at = Expires, created_at = Now, updated_at = Now }), {Status, _, Body} = eh_test_support:call(admin_handler_subscription_stats, #{ method => <<"GET">>, path => <<"/v1/admin/subscriptions/stats">>, auth => ?ADMIN_ID }), ?assertEqual(200, Status), Result = jsx:decode(Body, [return_maps]), ?assertEqual(2, maps:get(<<"total_subscriptions">>, Result)), ?assertEqual(1, maps:get(<<"trial_subscriptions">>, Result)), ByPlan = maps:get(<<"subscriptions_by_plan">>, Result), ?assertEqual(1, maps:get(<<"monthly">>, ByPlan)), ?assertEqual(1, maps:get(<<"annual">>, ByPlan)), Ending = maps:get(<<"ending_paid_subscriptions">>, Result), ?assertEqual(1, length(Ending)). test_unauthorized() -> {Status, _, _} = eh_test_support:call(admin_handler_subscription_stats, #{ method => <<"GET">>, path => <<"/v1/admin/subscriptions/stats">>, auth => none }), ?assertEqual(401, Status). test_wrong_method() -> {Status, _, _} = eh_test_support:call(admin_handler_subscription_stats, #{ method => <<"POST">>, path => <<"/v1/admin/subscriptions/stats">>, auth => ?ADMIN_ID }), ?assertEqual(405, Status).