(import-macros {:compile-html HTML} :macros)
(local lib (require :lib))
(local templates (require :templates))
(local dicts (require :dicts))
(fn all-orders [db]
(lib.group-by
(_G.must
(luna.db.query-assoc db
"SELECT orders.id,
orders.placement_time AS \"placement-time\",
orders.name \"contact-name\",
orders.contact,
orders.state,
order_lines.id AS \"order-line-id\",
order_lines.quantity,
products.image1,
products.name,
products.type,
products.packaging,
products.title,
products.price_per \"price-per\"
FROM orders
INNER JOIN order_lines ON orders.id = order_lines.order_id
INNER JOIN products ON products.name = order_lines.product_name
WHERE orders.state != 'cart'
ORDER BY orders.placement_time DESC, orders.id"
{}))
[:id :placement-time :state :contact-name :contact]))
(fn content [orders authenticated?]
[(HTML
[:aside {}
(templates.header "/shop/orders" authenticated?)])
(HTML
[:section {:class "content"}
[:div {:class "mb-1"} [:a {:href "/"} "⟵ Обратно к списку"]]
[:h2 {:class "product-page-title"} "Список заказов"]
(table.concat
(icollect [_ order (ipairs orders)]
(let [total (accumulate [sum 0 _ v (ipairs order.rest)]
(+ sum (* v.quantity v.price-per)))]
(HTML
[:section {:class "mb-2 font-size-0-875" }
[:h3 {:class "mb-0-25"} [:a {:href (.. "/shop/order/" order.id)} order.id]]
[:div {:class "mb-0-25 d-flex gap-0-25"}
(templates.order-state order.state)
(if (= "placed" order.state)
(HTML
[:form {:action "/shop/order/state" :method "POST"}
[:select {:name "state" :required true}
[:option {:value ""} "Новое состояние"]
[:option {:value "done"} "Выполнен"]
[:option {:value "canceled"} "Отменен"]]
[:input {:type "hidden" :name "id" :value order.id}]
[:button {:type "submit"} "Применить"]])
"")]
[:em {:class "d-block mb-0-5"}
"Дата: " order.placement-time
" / " "контакт: " order.contact
" / " "как обращаться: " order.contact-name]
(templates.order-lines order.rest)
[:div {} "—"]
[:div {} [:strong {} (.. "Итого: " (lib.format-price total) "₽")]]]))))])])
(fn render [request db authenticated?]
(if authenticated?
(values 200 {} (templates.base (content (all-orders db) authenticated?)))
(values 302 {:Location "/"} "")))
{: render}