2.1 KiB · text History e569b6d
defmodule CartosnapApp.Trips.Trip do
  @moduledoc """
  A named span of time photos are filed under: a shared album. Its owner
  (`user`) can invite members (`CartosnapApp.Trips.TripMember`), who file
  their own photos under it too. A trip with a `share_token` can also be
  viewed by anyone holding `/s/<token>`; see `CartosnapApp.Trips.share_trip/2`.
  Separately, a `public` trip is open to anyone who comes across it: listed
  on the front page and viewable at `/t/<id>` (`Trips.set_public/3`).
  """

  use Ecto.Schema
  import Ecto.Changeset

  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id
  schema "photo_trips" do
    field :date_end, :date
    field :date_start, :date
    field :geo, Geo.PostGIS.Geometry
    field :meta, :map
    field :name, :string
    field :user, :binary_id
    field :share_token, :string
    field :share_promoted_only, :boolean, default: false
    field :public, :boolean, default: false
    field :public_promoted_only, :boolean, default: false
    field :areas, :boolean, default: true

    many_to_many :photos, CartosnapApp.Photos.Photo,
      join_through: "photo_photo_trips",
      join_keys: [trip: :id, photo: :id]

    has_many :members, CartosnapApp.Trips.TripMember

    timestamps()
  end

  @doc "`user` is set on the struct by the caller, never cast."
  def changeset(trip, attrs) do
    trip
    |> cast(attrs, [:name, :date_start, :date_end])
    |> validate_required([:name, :date_start, :date_end])
    |> validate_length(:name, max: 200)
    |> validate_dates()
  end

  @doc "Whether the album is split into areas (`CartosnapApp.Trips.Areas`)."
  def areas_changeset(trip, attrs), do: cast(trip, attrs, [:areas])

  @doc "Sharing settings. The token is made by the context, never cast."
  def share_changeset(trip, attrs) do
    cast(trip, attrs, [:share_promoted_only, :public_promoted_only])
  end

  defp validate_dates(changeset) do
    start = get_field(changeset, :date_start)
    finish = get_field(changeset, :date_end)

    if start && finish && Date.compare(finish, start) == :lt do
      add_error(changeset, :date_end, "must be on or after the start")
    else
      changeset
    end
  end
end