debianize-mobilizon/lib/mobilizon/reports/report.ex

83 lines
2.3 KiB
Elixir
Raw Normal View History

defmodule Mobilizon.Reports.Report do
@moduledoc """
2019-09-07 02:38:13 +02:00
Represents a report entity.
"""
2019-09-07 02:38:13 +02:00
use Ecto.Schema
2019-09-07 02:38:13 +02:00
import Ecto.Changeset
2019-09-07 02:38:13 +02:00
alias Mobilizon.Actors.Actor
2019-09-07 02:38:13 +02:00
alias Mobilizon.Events.{Comment, Event}
alias Mobilizon.Reports.{Note, ReportStatus}
alias Mobilizon.Web.Endpoint
2019-09-07 02:38:13 +02:00
@type t :: %__MODULE__{
content: String.t(),
status: ReportStatus.t(),
url: String.t(),
2019-09-07 02:38:13 +02:00
reported: Actor.t(),
reporter: Actor.t(),
manager: Actor.t(),
event: Event.t(),
comments: [Comment.t()],
notes: [Note.t()]
}
@required_attrs [:url, :reported_id, :reporter_id]
@optional_attrs [:content, :status, :manager_id, :event_id, :local]
2019-09-07 02:38:13 +02:00
@attrs @required_attrs ++ @optional_attrs
@timestamps_opts [type: :utc_datetime]
@derive {Jason.Encoder, only: [:status, :url]}
schema "reports" do
field(:content, :string)
2019-09-07 02:38:13 +02:00
field(:status, ReportStatus, default: :open)
field(:url, :string)
field(:local, :boolean, default: true)
# The reported actor
belongs_to(:reported, Actor)
# The actor who reported
belongs_to(:reporter, Actor)
# The actor who last acted on this report
belongs_to(:manager, Actor)
# The eventual Event inside the report
belongs_to(:event, Event)
# The eventual Comments inside the report
many_to_many(:comments, Comment, join_through: "reports_comments", on_replace: :delete)
# The notes associated to the report
has_many(:notes, Note, foreign_key: :report_id)
timestamps()
end
@doc false
2019-09-13 01:55:45 +02:00
@spec changeset(t, map) :: Ecto.Changeset.t()
def changeset(%__MODULE__{} = report, attrs) do
report
2019-09-07 02:38:13 +02:00
|> cast(attrs, @attrs)
|> maybe_generate_url()
|> maybe_put_comments(attrs)
2019-09-07 02:38:13 +02:00
|> validate_required(@required_attrs)
end
defp maybe_put_comments(%Ecto.Changeset{} = changeset, %{comments: comments}) do
put_assoc(changeset, :comments, comments)
end
defp maybe_put_comments(%Ecto.Changeset{} = changeset, _), do: changeset
@spec maybe_generate_url(Ecto.Changeset.t()) :: Ecto.Changeset.t()
defp maybe_generate_url(%Ecto.Changeset{} = changeset) do
with res when res in [:error, {:data, nil}] <- fetch_field(changeset, :url),
url <- "#{Endpoint.url()}/report/#{Ecto.UUID.generate()}" do
put_change(changeset, :url, url)
else
_ -> changeset
end
end
end