-module(logic_calendar). -include("records.hrl"). -export([create_calendar/3, create_calendar/4, get_calendar/2, list_calendars/1, update_calendar/3, delete_calendar/2]). -export([can_access/2, can_edit/2]). %% Создание календаря с политикой по умолчанию (manual) create_calendar(UserId, Title, Description) -> create_calendar(UserId, Title, Description, manual). %% Создание календаря с указанной политикой подтверждения create_calendar(UserId, Title, Description, Confirmation) -> case core_user:get_by_id(UserId) of {ok, User} -> case User#user.status of active -> core_calendar:create(UserId, Title, Description, Confirmation); _ -> {error, user_inactive} end; {error, _} -> {error, user_not_found} end. %% Получение календаря с проверкой доступа get_calendar(UserId, CalendarId) -> case core_calendar:get_by_id(CalendarId) of {ok, Calendar} -> case can_access(UserId, Calendar) of true -> {ok, Calendar}; false -> {error, access_denied} end; Error -> Error end. %% Список календарей пользователя list_calendars(UserId) -> core_calendar:list_by_owner(UserId). %% Обновление календаря update_calendar(UserId, CalendarId, Updates) -> case core_calendar:get_by_id(CalendarId) of {ok, Calendar} -> case can_edit(UserId, Calendar) of true -> ValidUpdates = validate_updates(Updates), core_calendar:update(CalendarId, ValidUpdates); false -> {error, access_denied} end; Error -> Error end. %% Удаление календаря delete_calendar(UserId, CalendarId) -> case core_calendar:get_by_id(CalendarId) of {ok, Calendar} -> case can_edit(UserId, Calendar) of true -> core_calendar:delete(CalendarId); false -> {error, access_denied} end; Error -> Error end. %% Проверка прав доступа (просмотр) can_access(UserId, #calendar{owner_id = UserId, status = active}) -> true; can_access(_UserId, #calendar{type = commercial, status = active}) -> true; can_access(_UserId, _) -> false. %% Проверка прав редактирования can_edit(UserId, #calendar{owner_id = UserId, status = active}) -> true; can_edit(_UserId, #calendar{owner_id = _OwnerId}) -> false; can_edit(_, _) -> false. %% Валидация полей обновления validate_updates(Updates) -> lists:filter(fun validate_update/1, Updates). validate_update({title, Value}) when is_binary(Value) -> true; validate_update({description, Value}) when is_binary(Value) -> true; validate_update({tags, Value}) when is_list(Value) -> true; validate_update({type, Value}) when Value =:= personal; Value =:= commercial -> true; validate_update({confirmation, Value}) -> case Value of auto -> true; manual -> true; {timeout, N} when is_integer(N), N > 0 -> true; _ -> false end; validate_update(_) -> false.