defmodule Ami.CommunityUser do use Ecto.Schema use Timex import Ecto.Changeset import Ecto.Query alias Ami.{ User, Community, Repo } schema "community_users" do @timestamps_opts [type: :naive_datetime_usec] field(:status, :integer) field(:is_moderator, :boolean) field(:created_at, :utc_datetime_usec) field(:updated_at, :utc_datetime_usec) belongs_to(:user, User) belongs_to(:community, Community) end def create(params \\ %{}) do %__MODULE__{} |> cast(params, [:status, :is_moderator, :user_id, :community_id]) |> cast(%{created_at: DateTime.utc_now(), updated_at: DateTime.utc_now()}, [ :created_at, :updated_at ]) |> validate_uniqueness(params) |> Repo.insert() end defp validate_uniqueness(changeset, _params) do query = from( cu in __MODULE__, where: cu.user_id == ^changeset.changes.user_id, where: cu.community_id == ^changeset.changes.community_id, where: cu.is_moderator == false, select: count(cu.id) ) count = Repo.one(query) cond do count > 0 -> add_error(changeset, :community, "You already requested to join this community") count == 0 -> changeset end end def membership_status(status) do case status do 0 -> "pending" 1 -> "accepted" 2 -> "rejected" 3 -> "banned" _ -> status end end def already_registered_with_community?(user_id, community_id) do [count] = Repo.all( from( cm in __MODULE__, where: cm.community_id == ^community_id and cm.user_id == ^user_id, select: count("*") ) ) case count do 0 -> false _ -> true end end def present_for?(user_id, community_id) do Repo.one( from( cu in __MODULE__, where: cu.community_id == ^community_id and cu.user_id == ^user_id, where: cu.status == 1, select: count(cu.id) ) ) > 0 end def created_since?(community_user, days_count) do interval = Interval.new(from: community_user.created_at, until: DateTime.utc_now()) |> Interval.duration(:days) interval == days_count end end