defmodule Ami.Event do use Ecto.Schema import Ecto.{ Query } alias Ami.{ User, Repo, # Community, CommunityEvent } schema "events" do @timestamps_opts [type: :naive_datetime_usec] field(:title, :string) field(:body, :string) field(:event_type, :integer) field(:starts_on, :utc_datetime_usec) field(:ends_on, :utc_datetime_usec) field(:created_at, :utc_datetime_usec) field(:updated_at, :utc_datetime_usec) field(:weekly_recurrence, :boolean, default: false) field(:whole_community, :boolean, default: false) belongs_to(:author, User, foreign_key: :user_id) has_many(:community_events, CommunityEvent) has_many(:communities, through: [:community_events, :community]) end defp start_date_for(frequency) do case frequency do "daily" -> Timex.beginning_of_day(Timex.now()) "weekly" -> Timex.beginning_of_week(Timex.now()) "monthly" -> Timex.beginning_of_month(Timex.now()) end end def fetch_nonmember_news(frequency) do start_date = start_date_for(frequency) Repo.all( from( e in __MODULE__, where: e.event_type == 0 and e.starts_on >= ^start_date, or_where: e.event_type == 0 and e.weekly_recurrence == true ) ) end def fetch_member_news(%Ami.User{} = user, frequency) do user = Repo.preload(user, [:communities]) user_communities_ids = Enum.map(user.communities, fn com -> com.id end) start_date = start_date_for(frequency) community_news = Repo.all( from( e in __MODULE__, where: e.event_type == 1, where: e.starts_on >= ^start_date, where: e.whole_community == true, or_where: e.whole_community == true and e.weekly_recurrence == true ) ) |> Enum.concat( Repo.all( from( e in __MODULE__, where: e.event_type == 1, where: e.weekly_recurrence == false, join: c in assoc(e, :communities), where: c.id in ^user_communities_ids, where: e.starts_on >= ^start_date ) ) ) |> Enum.concat( Repo.all( from( e in __MODULE__, where: e.event_type == 1, join: c in assoc(e, :communities), where: c.id in ^user_communities_ids, where: e.weekly_recurrence == true ) ) ) |> Enum.uniq() if length(community_news) == 0, do: fetch_nonmember_news(frequency), else: community_news end end