philomena/lib/philomena_web/controllers/admin/dnp_entry_controller.ex

68 lines
1.8 KiB
Elixir
Raw Normal View History

2019-12-12 22:44:50 +01:00
defmodule PhilomenaWeb.Admin.DnpEntryController do
use PhilomenaWeb, :controller
alias PhilomenaWeb.TextRenderer
2019-12-12 22:44:50 +01:00
alias Philomena.DnpEntries.DnpEntry
alias Philomena.Repo
import Ecto.Query
plug :verify_authorized
plug :load_resource, model: DnpEntry, only: [:show, :edit, :update]
def index(conn, %{"states" => states}) when is_list(states) do
DnpEntry
|> where([d], d.aasm_state in ^states)
|> load_entries(conn)
end
def index(conn, %{"q" => q}) when is_binary(q) do
q = to_ilike(q)
DnpEntry
|> join(:inner, [d], _ in assoc(d, :tag))
|> join(:inner, [d, _t], _ in assoc(d, :requesting_user))
2020-01-11 05:20:19 +01:00
|> where(
[d, t, u],
ilike(u.name, ^q) or ilike(t.name, ^q) or ilike(d.reason, ^q) or ilike(d.conditions, ^q) or
ilike(d.instructions, ^q)
)
2019-12-12 22:44:50 +01:00
|> load_entries(conn)
end
def index(conn, _params) do
DnpEntry
|> where([d], d.aasm_state in ["requested", "claimed", "rescinded", "acknowledged"])
|> load_entries(conn)
end
defp load_entries(dnp_entries, conn) do
dnp_entries =
dnp_entries
|> preload([:tag, :requesting_user, :modifying_user])
|> order_by(desc: :updated_at)
|> Repo.paginate(conn.assigns.scrivener)
bodies =
dnp_entries
|> Enum.map(&%{body: &1.conditions, body_md: &1.conditions_md})
|> TextRenderer.render_collection(conn)
2019-12-12 22:44:50 +01:00
2020-01-11 05:20:19 +01:00
dnp_entries = %{dnp_entries | entries: Enum.zip(bodies, dnp_entries.entries)}
2019-12-12 22:44:50 +01:00
2020-01-11 05:20:19 +01:00
render(conn, "index.html",
layout_class: "layout--wide",
title: "Admin - DNP Entries",
dnp_entries: dnp_entries
)
2019-12-12 22:44:50 +01:00
end
defp verify_authorized(conn, _opts) do
case Canada.Can.can?(conn.assigns.current_user, :index, DnpEntry) do
2020-01-11 05:20:19 +01:00
true -> conn
2019-12-12 22:44:50 +01:00
_false -> PhilomenaWeb.NotAuthorizedPlug.call(conn)
end
end
defp to_ilike(query), do: "%" <> query <> "%"
end