philomena/lib/philomena_web/controllers/commission_controller.ex

113 lines
2.5 KiB
Elixir
Raw Permalink Normal View History

2019-11-18 01:09:15 +01:00
defmodule PhilomenaWeb.CommissionController do
use PhilomenaWeb, :controller
alias Philomena.Commissions.{Item, Commission}
alias Philomena.Repo
import Ecto.Query
plug PhilomenaWeb.MapParameterPlug, [param: "commission"] when action in [:index]
2019-12-04 16:00:41 +01:00
plug :preload_commission
2019-11-18 01:09:15 +01:00
def index(conn, params) do
commissions =
commission_search(params["commission"])
|> Repo.paginate(conn.assigns.scrivener)
2020-01-11 05:20:19 +01:00
render(conn, "index.html",
title: "Commissions",
commissions: commissions,
layout_class: "layout--wide"
)
2019-11-18 01:09:15 +01:00
end
defp commission_search(attrs) when is_map(attrs) do
item_type = presence(attrs["item_type"])
categories = presence(attrs["category"])
keywords = presence(attrs["keywords"])
price_min = to_f(presence(attrs["price_min"]) || 0)
price_max = to_f(presence(attrs["price_max"]) || 9999)
query =
commission_search(nil)
|> where([_c, ci], ci.base_price > ^price_min and ci.base_price < ^price_max)
query =
if item_type do
query
|> where([_c, ci], ci.item_type == ^item_type)
else
query
end
query =
if categories do
query
|> where([c, _ci], fragment("? @> ?", c.categories, ^categories))
else
query
end
query =
if keywords do
query
2020-01-11 05:20:19 +01:00
|> where(
[c, _ci],
ilike(c.information, ^like_sanitize(keywords)) or
ilike(c.will_create, ^like_sanitize(keywords))
)
2019-11-18 01:09:15 +01:00
else
query
end
query
end
defp commission_search(_attrs) do
from c in Commission,
where: c.open == true,
where: c.commission_items_count > 0,
2020-01-11 05:20:19 +01:00
inner_join: ci in Item,
on: ci.commission_id == c.id,
2019-11-18 01:09:15 +01:00
group_by: c.id,
order_by: [asc: fragment("random()")],
preload: [user: [awards: :badge], items: [example_image: :tags]]
end
defp presence(nil),
do: nil
2020-01-11 05:20:19 +01:00
2019-11-18 01:09:15 +01:00
defp presence([]),
do: nil
2020-01-11 05:20:19 +01:00
2019-11-18 01:09:15 +01:00
defp presence(string) when is_binary(string),
do: if(String.trim(string) == "", do: nil, else: string)
2020-01-11 05:20:19 +01:00
2019-11-18 01:09:15 +01:00
defp presence(object),
do: object
defp to_f(input) do
case Float.parse(to_string(input)) do
{float, _rest} -> float
2020-01-11 05:20:19 +01:00
_error -> 0.0
2019-11-18 01:09:15 +01:00
end
end
defp like_sanitize(input) do
"%" <> String.replace(input, ["\\", "%", "_"], &<<"\\", &1>>) <> "%"
end
2019-12-04 16:00:41 +01:00
defp preload_commission(conn, _opts) do
user = conn.assigns.current_user
case user do
nil ->
conn
2020-01-11 05:20:19 +01:00
user ->
2019-12-04 16:00:41 +01:00
user = Repo.preload(user, :commission)
assign(conn, :current_user, user)
2019-12-04 16:00:41 +01:00
end
end
2019-12-16 20:24:38 +01:00
end