Stage 8
This commit is contained in:
@@ -11,11 +11,24 @@ create_calendar(UserId, Title, Description) ->
|
||||
|
||||
%% Создание календаря с указанной политикой подтверждения
|
||||
create_calendar(UserId, Title, Description, Confirmation) ->
|
||||
Type = personal, % По умолчанию
|
||||
create_calendar(UserId, Title, Description, Confirmation, Type).
|
||||
|
||||
create_calendar(UserId, Title, Description, Confirmation, Type) ->
|
||||
case core_user:get_by_id(UserId) of
|
||||
{ok, User} ->
|
||||
case User#user.status of
|
||||
active ->
|
||||
core_calendar:create(UserId, Title, Description, Confirmation);
|
||||
% Проверяем подписку для commercial календарей
|
||||
case Type of
|
||||
commercial ->
|
||||
case logic_subscription:can_create_commercial_calendar(UserId) of
|
||||
true -> ok;
|
||||
false -> {error, subscription_required}
|
||||
end;
|
||||
personal -> ok
|
||||
end,
|
||||
core_calendar:create(UserId, Title, Description, Confirmation, Type);
|
||||
_ ->
|
||||
{error, user_inactive}
|
||||
end;
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
-module(logic_subscription).
|
||||
-include("records.hrl").
|
||||
|
||||
-export([start_trial/1, activate_subscription/3, cancel_subscription/2]).
|
||||
-export([get_user_subscription/1, get_subscription/2, list_subscriptions/1]).
|
||||
-export([check_user_subscription/1, can_create_commercial_calendar/1]).
|
||||
-export([handle_expired_subscriptions/0]).
|
||||
|
||||
-define(TRIAL_DAYS, 30).
|
||||
|
||||
%% ============ Управление подписками ============
|
||||
|
||||
%% Начать пробный период (вызывается при первой попытке создать commercial календарь)
|
||||
start_trial(UserId) ->
|
||||
case core_subscription:get_active_by_user(UserId) of
|
||||
{ok, _} ->
|
||||
{error, already_has_subscription};
|
||||
{error, not_found} ->
|
||||
% Проверяем, не использовал ли пользователь уже пробный период
|
||||
{ok, AllSubs} = core_subscription:list_by_user(UserId),
|
||||
case lists:any(fun(S) -> S#subscription.trial_used == true orelse S#subscription.plan == trial end, AllSubs) of
|
||||
true ->
|
||||
{error, trial_already_used};
|
||||
false ->
|
||||
case core_subscription:create(UserId, trial, true) of
|
||||
{ok, Subscription} ->
|
||||
{ok, Subscription};
|
||||
Error -> Error
|
||||
end
|
||||
end
|
||||
end.
|
||||
|
||||
%% Активировать платную подписку
|
||||
activate_subscription(UserId, Plan, PaymentInfo) ->
|
||||
case process_payment(PaymentInfo, plan_price(Plan)) of
|
||||
ok ->
|
||||
% Проверяем, была ли у пользователя хоть одна подписка
|
||||
{ok, AllSubs} = core_subscription:list_by_user(UserId),
|
||||
TrialUsed = length(AllSubs) > 0,
|
||||
|
||||
% Деактивируем старые подписки
|
||||
case core_subscription:get_active_by_user(UserId) of
|
||||
{ok, Active} ->
|
||||
core_subscription:update_status(Active#subscription.id, expired);
|
||||
_ -> ok
|
||||
end,
|
||||
|
||||
% Создаём новую подписку
|
||||
case core_subscription:create(UserId, Plan, TrialUsed) of
|
||||
{ok, Subscription} ->
|
||||
{ok, Subscription};
|
||||
Error -> Error
|
||||
end;
|
||||
{error, payment_failed} ->
|
||||
{error, payment_failed}
|
||||
end.
|
||||
|
||||
%% Отменить подписку
|
||||
cancel_subscription(AdminId, SubscriptionId) ->
|
||||
case is_admin(AdminId) of
|
||||
true ->
|
||||
case core_subscription:get_by_id(SubscriptionId) of
|
||||
{ok, Subscription} ->
|
||||
core_subscription:update_status(SubscriptionId, cancelled);
|
||||
Error -> Error
|
||||
end;
|
||||
false -> {error, access_denied}
|
||||
end.
|
||||
|
||||
%% ============ Получение информации ============
|
||||
|
||||
%% Получить активную подписку пользователя
|
||||
get_user_subscription(UserId) ->
|
||||
case core_subscription:get_active_by_user(UserId) of
|
||||
{ok, Subscription} ->
|
||||
{ok, format_subscription(Subscription)};
|
||||
{error, not_found} ->
|
||||
{ok, #{status => free}}
|
||||
end.
|
||||
|
||||
%% Получить подписку по ID (только админ)
|
||||
get_subscription(AdminId, SubscriptionId) ->
|
||||
case is_admin(AdminId) of
|
||||
true -> core_subscription:get_by_id(SubscriptionId);
|
||||
false -> {error, access_denied}
|
||||
end.
|
||||
|
||||
%% Список подписок пользователя
|
||||
list_subscriptions(UserId) ->
|
||||
core_subscription:list_by_user(UserId).
|
||||
|
||||
%% ============ Проверки ============
|
||||
|
||||
%% Проверить статус подписки пользователя
|
||||
check_user_subscription(UserId) ->
|
||||
case core_subscription:get_active_by_user(UserId) of
|
||||
{ok, Sub} ->
|
||||
Now = calendar:universal_time(),
|
||||
case Sub#subscription.expires_at > Now of
|
||||
true -> {ok, active, Sub#subscription.plan};
|
||||
false -> {ok, expired, free}
|
||||
end;
|
||||
{error, not_found} ->
|
||||
{ok, free, free}
|
||||
end.
|
||||
|
||||
%% Проверить, может ли пользователь создавать коммерческие календари
|
||||
%% Если у пользователя нет активной подписки, но он ещё не использовал пробный период,
|
||||
%% автоматически запускаем пробный период
|
||||
can_create_commercial_calendar(UserId) ->
|
||||
case check_user_subscription(UserId) of
|
||||
{ok, active, _} ->
|
||||
true;
|
||||
{ok, free, free} ->
|
||||
% Пользователь без подписки - проверяем, не использовал ли он уже пробный период
|
||||
{ok, AllSubs} = core_subscription:list_by_user(UserId),
|
||||
TrialUsed = lists:any(fun(S) -> S#subscription.trial_used == true orelse S#subscription.plan == trial end, AllSubs),
|
||||
case TrialUsed of
|
||||
false ->
|
||||
% Автоматически запускаем пробный период
|
||||
case start_trial(UserId) of
|
||||
{ok, _} -> true;
|
||||
_ -> false
|
||||
end;
|
||||
true ->
|
||||
false
|
||||
end;
|
||||
_ ->
|
||||
false
|
||||
end.
|
||||
|
||||
%% ============ Обслуживание ============
|
||||
|
||||
%% Обработать истёкшие подписки (вызывается периодически)
|
||||
handle_expired_subscriptions() ->
|
||||
core_subscription:check_expired().
|
||||
|
||||
%% ============ Внутренние функции ============
|
||||
|
||||
is_admin(UserId) ->
|
||||
case core_user:get_by_id(UserId) of
|
||||
{ok, User} -> User#user.role =:= admin;
|
||||
_ -> false
|
||||
end.
|
||||
|
||||
plan_price(monthly) -> 999; % $9.99
|
||||
plan_price(quarterly) -> 2499; % $24.99
|
||||
plan_price(biannual) -> 4499; % $44.99
|
||||
plan_price(annual) -> 7999; % $79.99
|
||||
plan_price(trial) -> 0.
|
||||
|
||||
process_payment(_PaymentInfo, _Amount) ->
|
||||
% Заглушка платёжного шлюза - всегда успешно
|
||||
ok.
|
||||
|
||||
format_subscription(Subscription) ->
|
||||
#{
|
||||
id => Subscription#subscription.id,
|
||||
plan => Subscription#subscription.plan,
|
||||
status => Subscription#subscription.status,
|
||||
trial_used => Subscription#subscription.trial_used,
|
||||
started_at => datetime_to_iso8601(Subscription#subscription.started_at),
|
||||
expires_at => datetime_to_iso8601(Subscription#subscription.expires_at)
|
||||
}.
|
||||
|
||||
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])).
|
||||
Reference in New Issue
Block a user