Stage 3.2
This commit is contained in:
85
src/core/core_calendar.erl
Normal file
85
src/core/core_calendar.erl
Normal file
@@ -0,0 +1,85 @@
|
||||
-module(core_calendar).
|
||||
-include("records.hrl").
|
||||
|
||||
-export([create/3, get_by_id/1, list_by_owner/1, update/2, delete/1]).
|
||||
-export([generate_id/0]).
|
||||
|
||||
%% Создание календаря
|
||||
create(OwnerId, Title, Description) ->
|
||||
Id = generate_id(),
|
||||
Calendar = #calendar{
|
||||
id = Id,
|
||||
owner_id = OwnerId,
|
||||
title = Title,
|
||||
description = Description,
|
||||
tags = [],
|
||||
type = personal,
|
||||
confirmation = manual,
|
||||
rating_avg = 0.0,
|
||||
rating_count = 0,
|
||||
status = active,
|
||||
created_at = calendar:universal_time(),
|
||||
updated_at = calendar:universal_time()
|
||||
},
|
||||
|
||||
F = fun() ->
|
||||
mnesia:write(Calendar),
|
||||
{ok, Calendar}
|
||||
end,
|
||||
|
||||
case mnesia:transaction(F) of
|
||||
{atomic, Result} -> Result;
|
||||
{aborted, Reason} -> {error, Reason}
|
||||
end.
|
||||
|
||||
%% Получение календаря по ID
|
||||
get_by_id(Id) ->
|
||||
case mnesia:dirty_read(calendar, Id) of
|
||||
[] -> {error, not_found};
|
||||
[Calendar] -> {ok, Calendar}
|
||||
end.
|
||||
|
||||
%% Список календарей владельца
|
||||
list_by_owner(OwnerId) ->
|
||||
Match = #calendar{owner_id = OwnerId, status = active, _ = '_'},
|
||||
Calendars = mnesia:dirty_match_object(Match),
|
||||
{ok, Calendars}.
|
||||
|
||||
%% Обновление календаря
|
||||
update(Id, Updates) ->
|
||||
F = fun() ->
|
||||
case mnesia:read(calendar, Id) of
|
||||
[] ->
|
||||
{error, not_found};
|
||||
[Calendar] ->
|
||||
UpdatedCalendar = apply_updates(Calendar, Updates),
|
||||
mnesia:write(UpdatedCalendar),
|
||||
{ok, UpdatedCalendar}
|
||||
end
|
||||
end,
|
||||
|
||||
case mnesia:transaction(F) of
|
||||
{atomic, Result} -> Result;
|
||||
{aborted, Reason} -> {error, Reason}
|
||||
end.
|
||||
|
||||
%% Удаление календаря (soft delete)
|
||||
delete(Id) ->
|
||||
update(Id, [{status, deleted}]).
|
||||
|
||||
%% Внутренние функции
|
||||
generate_id() ->
|
||||
base64:encode(crypto:strong_rand_bytes(16), #{mode => urlsafe, padding => false}).
|
||||
apply_updates(Calendar, Updates) ->
|
||||
Updated = lists:foldl(fun({Field, Value}, C) ->
|
||||
set_field(Field, Value, C)
|
||||
end, Calendar, Updates),
|
||||
Updated#calendar{updated_at = calendar:universal_time()}.
|
||||
|
||||
set_field(title, Value, C) -> C#calendar{title = Value};
|
||||
set_field(description, Value, C) -> C#calendar{description = Value};
|
||||
set_field(tags, Value, C) -> C#calendar{tags = Value};
|
||||
set_field(type, Value, C) -> C#calendar{type = Value};
|
||||
set_field(confirmation, Value, C) -> C#calendar{confirmation = Value};
|
||||
set_field(status, Value, C) -> C#calendar{status = Value};
|
||||
set_field(_, _, C) -> C.
|
||||
Reference in New Issue
Block a user