defmodule Ami.TeaserImageAttachment do use Ecto.Schema use Arc.Ecto.Schema import Ecto.{ Changeset, Query } alias Ami.{ Course, Repo } alias Ami.TeaserImageAttachmentUploader.Type schema "teaser_image_attachments" do field(:name, :string) field(:page_position, :integer) field(:file, Type) timestamps() belongs_to(:course, Course) end def changeset(struct, params \\ %{}) do struct |> cast(params, [:course_id, :name, :page_position]) |> cast_attachments(params, [:file], allows_path: true) |> case do %{valid?: false, changes: changes} = changeset when changes == %{} -> %{changeset | action: :ignore} changeset -> changeset end end # enum page_position: [ :main, :detail, :box, :certificate, :teaser_box, :download_certificate ] def page_positions do [ {"main", 0}, {"detail", 1}, {"box", 2}, {"certificate", 3}, {"teaser_box", 4}, {"download_certificate", 5} ] end def preload_main_teaser_images(course) do course |> Repo.preload( teaser_image_attachments: from(ti in __MODULE__, where: ti.page_position == 0) ) end def preload_preview_images(course) do course |> Repo.preload( teaser_image_attachments: from(ti in __MODULE__, where: ti.page_position == 4) ) end def preload_detail_teaser_images(course) do course |> Repo.preload( teaser_image_attachments: from(ti in __MODULE__, where: ti.page_position == 1) ) end def preload_certificate_teaser_images(course) do course |> Repo.preload( teaser_image_attachments: from(ti in __MODULE__, where: ti.page_position == 3) ) end def preload_download_certificate_teaser_images(course) do course |> Repo.preload( teaser_image_attachments: from(ti in __MODULE__, where: ti.page_position == 5) ) end def teaser_image_from(list) do ti = List.last(list) env = Application.get_env(:ami_web, :env) if !is_nil(ti) do case Regex.match?(~r{/\d+/\w+}, ti.file.file_name) do true -> case env do :dev -> "https://ami-aws-staging.s3.amazonaws.com/uploads/teaser_image/file#{ ti.file.file_name }" :staging -> "https://ami-aws-staging.s3.amazonaws.com/uploads/teaser_image/file#{ ti.file.file_name }" :prod -> "https://ami-aws-s3.s3.amazonaws.com/uploads/teaser_image/file#{ti.file.file_name}" end _ -> case env do :dev -> "https://ami-aws-staging.s3.amazonaws.com/uploads/teaser_image/file/#{ ti.file.file_name }" :staging -> "https://ami-aws-staging.s3.amazonaws.com/uploads/teaser_image/file/#{ ti.file.file_name }" :prod -> "https://ami-aws-s3.s3.amazonaws.com/uploads/teaser_image/file/#{ti.file.file_name}" end end end end end