Files
EventHubBack/src/core/core_admin.erl

112 lines
3.3 KiB
Erlang

-module(core_admin).
-include("records.hrl").
-export([create/3, get_by_email/1, get_by_id/1, list_all/0,
update_role/2, block/1, unblock/1, update_last_login/1]).
-export([update/2]).
create(Email, Password, Role) ->
case get_by_email(Email) of
{ok, _} ->
{error, email_exists};
{error, not_found} ->
Id = infra_utils:generate_id(16),
{ok, Hash} = argon2:hash(Password),
Now = calendar:universal_time(),
Admin = #admin{
id = Id,
email = Email,
password_hash = Hash,
role = Role,
status = active,
created_at = Now,
updated_at = Now
},
mnesia:dirty_write(Admin),
{ok, Admin}
end.
%% Обновление администратора (любые поля)
update(AdminId, Updates) ->
F = fun() ->
case mnesia:read(admin, AdminId) of
[] -> {error, not_found};
[Admin] ->
UpdatedAdmin = apply_updates(Admin, Updates),
mnesia:write(UpdatedAdmin),
{ok, UpdatedAdmin}
end
end,
case mnesia:transaction(F) of
{atomic, Result} -> Result;
{aborted, Reason} -> {error, Reason}
end.
get_by_email(Email) ->
Match = #admin{email = Email, _ = '_'},
case mnesia:dirty_match_object(Match) of
[Admin] -> {ok, Admin};
[] -> {error, not_found}
end.
get_by_id(Id) ->
case mnesia:dirty_read({admin, Id}) of
[Admin] -> {ok, Admin};
[] -> {error, not_found}
end.
list_all() ->
mnesia:dirty_match_object(#admin{_ = '_'}).
update_role(Id, NewRole) when is_atom(NewRole) ->
case get_by_id(Id) of
{ok, Admin} ->
Updated = Admin#admin{role = NewRole, updated_at = calendar:universal_time()},
mnesia:dirty_write(Updated),
{ok, Updated};
Error -> Error
end.
update_last_login(Id) ->
case get_by_id(Id) of
{ok, Admin} ->
Updated = Admin#admin{last_login = calendar:universal_time()},
mnesia:dirty_write(Updated),
{ok, Updated};
Error -> Error
end.
block(Id) ->
update_status(Id, blocked).
unblock(Id) ->
update_status(Id, active).
update_status(Id, Status) ->
case get_by_id(Id) of
{ok, Admin} ->
Updated = Admin#admin{status = Status, updated_at = calendar:universal_time()},
mnesia:dirty_write(Updated),
{ok, Updated};
Error -> Error
end.
%%%===================================================================
%%% ВНУТРЕННИЕ ФУНКЦИИ
%%%===================================================================
apply_updates(Admin, []) -> Admin;
apply_updates(Admin, [{Field, Value} | Rest]) ->
NewAdmin = case Field of
email -> Admin#admin{email = Value};
password_hash -> Admin#admin{password_hash = Value};
role -> Admin#admin{role = Value};
status -> Admin#admin{status = Value};
nickname -> Admin#admin{nickname = Value};
avatar_url -> Admin#admin{avatar_url = Value};
timezone -> Admin#admin{timezone = Value};
language -> Admin#admin{language = Value};
phone -> Admin#admin{phone = Value};
preferences -> Admin#admin{preferences = Value};
_ -> Admin
end,
apply_updates(NewAdmin#admin{updated_at = calendar:universal_time()}, Rest).