defmodule Core.Posts do @moduledoc false alias Core.Syndication alias Core.Posts.Post def get!(id) do Post.Query.base() |> Core.Repo.get!(id) end def get(id) do Post.Query.base() |> Core.Repo.get(id) end def get_published_post(id) do Post.Query.published() |> Core.Repo.get(id) end def get_published_blog!(%Date{} = publish_date, slug) when is_binary(slug) do Post.Query.published() |> Post.Query.where_publish_date_and_slug(publish_date, slug) |> Core.Repo.one!() end def get_published_status!(id) do Post.Query.published() |> Post.Query.where_kind(:status) |> Core.Repo.get!(id) end @recent_posts_count 10 def get_all_recent_blogs do Post.Query.recent_blogs(@recent_posts_count) |> Core.Repo.all() end def get_all_recent_statuses do Post.Query.recent_statuses(@recent_posts_count) |> Core.Repo.all() end def get_published_recent_posts(kind, count \\ @recent_posts_count) do Post.Query.recent_posts(kind, count) |> Post.Query.published() |> Core.Repo.all() end def list_posts(kind, params \\ %{}) do Post.Query.base() |> Post.Query.where_kind(kind) |> Flop.validate_and_run(params, for: Schema.Post) end def list_published_posts(kind, params \\ %{}) do Post.Query.base() |> Post.Query.published() |> Post.Query.where_kind(kind) |> Flop.validate_and_run(params, for: Schema.Post) end def publish_date_time(%Schema.Post{published_at: nil}), do: nil def publish_date_time(%Schema.Post{published_at: published_at}) do Core.DateTime.to_local_time(published_at) end def publish_date(%Schema.Post{} = post) do post |> publish_date_time() |> DateTime.to_date() end def change_post(%Schema.Post{} = post \\ %Schema.Post{}, attrs) do Post.content_changeset(post, attrs) end def create_post(attrs) do attrs |> change_post() |> Core.Repo.insert() |> do_syndication() end def update_post(%Schema.Post{} = post, attrs) do post |> change_post(attrs) |> Core.Repo.update() |> do_syndication() end def create_or_update_post(%Schema.Post{} = post, attrs) do post |> change_post(attrs) |> Core.Repo.insert_or_update() |> do_syndication() end def publish_post(%Schema.Post{} = post, published_at \\ DateTime.utc_now()) do post |> Post.publish_changeset(published_at) |> Core.Repo.update() |> do_syndication() end def delete_post(%Schema.Post{} = post, deleted_at \\ DateTime.utc_now()) do post |> Post.delete_changeset(deleted_at) |> Core.Repo.update() end def unpublish_post(%Schema.Post{} = post) do post |> Post.unpublish_changeset() |> Core.Repo.update() |> do_syndication() end def undelete_post(%Schema.Post{} = post) do post |> Post.undelete_changeset() |> Core.Repo.update() |> do_syndication() end defp do_syndication(%Schema.Post{} = post) do %{"post_id" => post.id} |> Syndication.SyndicatePostWorker.new() |> Oban.insert() post end defp do_syndication({:ok, %Schema.Post{} = post}) do do_syndication(post) {:ok, post} end defp do_syndication(other), do: other end