defmodule NotificationDispatcher.Context.NotificationContext do @moduledoc """ The Notifications context. """ import Ecto.Query, warn: false def get_repo(), do: Application.fetch_env!(:notification_dispatcher, :repo) alias NotificationDispatcher.Schema.{Device, NotificationMessage} def get_notification_message!(id), do: get_repo().get!(NotificationMessage, id) def get_one_notification_message!(channel) do NotificationMessage.query_main() |> NotificationMessage.where_channel(channel) |> NotificationMessage.limit(1) |> get_repo().one() end def get_by_type_and_language(type, language) do NotificationMessage.query_main() |> NotificationMessage.where_type(type) |> NotificationMessage.where_locale(language) |> NotificationMessage.limit(1) |> get_repo().one() end def get_by_type(type) do NotificationMessage.query_main() |> NotificationMessage.where_type(type) |> NotificationMessage.limit(1) |> get_repo().one() end def create_notification_message(attrs \\ %{}) do %NotificationMessage{} |> NotificationMessage.changeset(attrs) |> get_repo().insert() end def delete_notification_message(%NotificationMessage{} = notification_message) do get_repo().delete(notification_message) end def get_devices(user_ids) do Device.query_main() |> Device.where_user_id_in(user_ids) |> get_repo().all() end def get_device!(id) do Device.query_main |> Device.where(id) |> get_repo().one end def get_device(id) do device = get_device!(id) if is_nil(device), do: :not_found, else: {:ok, device} end def update_device(%Device{} = device, attrs) do device |> Device.changeset_update(attrs) |> get_repo().update end def create_device(attrs \\ %{}, user_id) do attrs = Map.put(attrs, "user_id", user_id) os = case attrs["os"] do "android" -> 0 "ios" -> 1 _ -> 2 end attrs = Map.put(attrs, "os", os) %Device{} |> Device.changeset(attrs) |> get_repo().insert( on_conflict: [ set: [ device_token: attrs["device_token"], os: attrs["os"] ] ], conflict_target: [:device_token], returning: [:id] ) end end