97 lines
2.8 KiB
Erlang
97 lines
2.8 KiB
Erlang
-module(core_report).
|
|
-include("records.hrl").
|
|
|
|
-export([create/4, get_by_id/1, list_by_target/2, list_by_reporter/1, list_all/0]).
|
|
-export([update_status/3, get_count_by_target/2]).
|
|
-export([generate_id/0]).
|
|
-export([count_reports_by_status/1, count_reports_by_admin/2]).
|
|
|
|
%% Создание жалобы
|
|
create(ReporterId, TargetType, TargetId, Reason) ->
|
|
Id = generate_id(),
|
|
Report = #report{
|
|
id = Id,
|
|
reporter_id = ReporterId,
|
|
target_type = TargetType,
|
|
target_id = TargetId,
|
|
reason = Reason,
|
|
status = pending,
|
|
created_at = calendar:universal_time(),
|
|
resolved_at = undefined,
|
|
resolved_by = undefined
|
|
},
|
|
|
|
F = fun() ->
|
|
mnesia:write(Report),
|
|
{ok, Report}
|
|
end,
|
|
|
|
case mnesia:transaction(F) of
|
|
{atomic, Result} -> Result;
|
|
{aborted, Reason} -> {error, Reason}
|
|
end.
|
|
|
|
%% Получение жалобы по ID
|
|
get_by_id(Id) ->
|
|
case mnesia:dirty_read(report, Id) of
|
|
[] -> {error, not_found};
|
|
[Report] -> {ok, Report}
|
|
end.
|
|
|
|
%% Список жалоб на цель
|
|
list_by_target(TargetType, TargetId) ->
|
|
Match = #report{target_type = TargetType, target_id = TargetId, _ = '_'},
|
|
Reports = mnesia:dirty_match_object(Match),
|
|
{ok, Reports}.
|
|
|
|
%% Список жалоб от пользователя
|
|
list_by_reporter(ReporterId) ->
|
|
Match = #report{reporter_id = ReporterId, _ = '_'},
|
|
Reports = mnesia:dirty_match_object(Match),
|
|
{ok, Reports}.
|
|
|
|
%% Список всех жалоб (для админов)
|
|
list_all() ->
|
|
Match = #report{_ = '_'},
|
|
Reports = mnesia:dirty_match_object(Match),
|
|
{ok, Reports}.
|
|
|
|
%% Обновление статуса жалобы
|
|
update_status(Id, Status, ResolvedBy) when Status =:= reviewed; Status =:= dismissed ->
|
|
F = fun() ->
|
|
case mnesia:read(report, Id) of
|
|
[] ->
|
|
{error, not_found};
|
|
[Report] ->
|
|
Updated = Report#report{
|
|
status = Status,
|
|
resolved_at = calendar:universal_time(),
|
|
resolved_by = ResolvedBy
|
|
},
|
|
mnesia:write(Updated),
|
|
{ok, Updated}
|
|
end
|
|
end,
|
|
|
|
case mnesia:transaction(F) of
|
|
{atomic, Result} -> Result;
|
|
{aborted, Reason} -> {error, Reason}
|
|
end.
|
|
|
|
%% Получить количество жалоб на цель
|
|
get_count_by_target(TargetType, TargetId) ->
|
|
Match = #report{target_type = TargetType, target_id = TargetId, status = pending, _ = '_'},
|
|
Reports = mnesia:dirty_match_object(Match),
|
|
length(Reports).
|
|
|
|
count_reports_by_status(Status) ->
|
|
Match = #report{status = Status, _ = '_'},
|
|
length(mnesia:dirty_match_object(Match)).
|
|
|
|
count_reports_by_admin(AdminId, Status) ->
|
|
Match = #report{resolved_by = AdminId, status = Status, _ = '_'},
|
|
length(mnesia:dirty_match_object(Match)).
|
|
|
|
%% Внутренние функции
|
|
generate_id() ->
|
|
base64:encode(crypto:strong_rand_bytes(16), #{mode => urlsafe, padding => false}). |