Files
integreat/src/clj/auto_ap/ssr/admin/accounts.clj
2023-10-22 21:53:47 -07:00

413 lines
22 KiB
Clojure

(ns auto-ap.ssr.admin.accounts
(:require
[auto-ap.datomic
:refer [add-sorter-fields
apply-pagination
apply-sort-3
audit-transact
conn
merge-query
pull-many
query2]]
[auto-ap.query-params :as query-params]
[auto-ap.routes.utils
:refer [wrap-admin wrap-client-redirect-unauthenticated]]
[auto-ap.solr :as solr]
[auto-ap.ssr-routes :as ssr-routes]
[auto-ap.ssr.components :as com]
[auto-ap.ssr.form-cursor :as fc]
[auto-ap.ssr.grid-page-helper :as helper]
[auto-ap.ssr.nested-form-params :refer [wrap-nested-form-params]]
[auto-ap.ssr.svg :as svg]
[auto-ap.ssr.utils
:refer [apply-middleware-to-all-handlers
entity-id
html-response
many-entity
ref->enum-schema
ref->select-options
temp-id
validation-error
wrap-form-4xx-2
wrap-schema-decode]]
[bidi.bidi :as bidi]
[clojure.string :as str]
[datomic.api :as dc]
[hiccup2.core :as hiccup]
[malli.core :as mc]))
(defn filters [request]
[:form {"hx-trigger" "change delay:500ms, keyup changed from:.hot-filter delay:1000ms"
"hx-get" (bidi/path-for ssr-routes/only-routes
:admin-account-table)
"hx-target" "#account-table"
"hx-indicator" "#account-table"}
[:fieldset.space-y-6
(com/field {:label "Name"}
(com/text-input {:name "name"
:id "name"
:class "hot-filter"
:value (:name (:parsed-query-params request))
:placeholder "Cash"
:size :small}))
(com/field {:label "Code"}
(com/text-input {:name "code"
:id "code"
:class "hot-filter"
:value (:code (:parsed-query-params request))
:placeholder "11101"
:size :small}))]])
(def default-read '[:db/id
:account/code
:account/name
:account/numeric-code
:account/location
{[:account/type :xform iol-ion.query/ident] [:db/ident]
[:account/invoice-allowance :xform iol-ion.query/ident] [:db/ident]
[:account/vendor-allowance :xform iol-ion.query/ident] [:db/ident]
[:account/applicability :xform iol-ion.query/ident] [:db/ident]
:account/client-overrides [{:account-client-override/client [:client/name :db/id]}
:account-client-override/name
:db/id]}])
(defn fetch-ids [db request]
(let [query-params (:parsed-query-params request)
query (cond-> {:query {:find []
:in '[$ ]
:where '[]}
:args [db ]}
(:sort query-params) (add-sorter-fields {"name" ['[?e :account/name ?n]
'[(clojure.string/upper-case ?n) ?sort-name]]
"code" ['[(get-else $ ?e :account/numeric-code 0) ?sort-code]]
"type" ['[?e :account/type ?t]
'[?t :db/ident ?ti]
'[(name ?ti) ?sort-type]]}
query-params)
(some->> query-params :name not-empty)
(merge-query {:query {:find []
:in ['?ns]
:where ['[?e :account/name ?an]
'[(clojure.string/upper-case ?an) ?upper-an]
'[(clojure.string/includes? ?upper-an ?ns)]]}
:args [(str/upper-case (:name query-params))]})
(some->> query-params :code)
(merge-query {:query {:find []
:in ['?nc]
:where ['[?e :account/numeric-code ?nc]
]}
:args [(:code query-params)]})
true
(merge-query {:query {:find ['?sort-default '?e]
:where ['[?e :account/code ?un]
'[(clojure.string/upper-case ?un) ?sort-default]]}}))]
(cond->> (query2 query)
true (apply-sort-3 query-params)
true (apply-pagination query-params))))
(defn hydrate-results [ids db _]
(let [results (->> (pull-many db default-read ids)
(group-by :db/id))
refunds (->> ids
(map results)
(map first))]
refunds))
(defn fetch-page [request]
(let [db (dc/db conn)
{ids-to-retrieve :ids matching-count :count} (fetch-ids db request)]
[(->> (hydrate-results ids-to-retrieve db request))
matching-count]))
(def grid-page
(helper/build {:id "account-table"
:nav (com/admin-aside-nav)
:page-specific-nav filters
:fetch-page fetch-page
:parse-query-params (comp
(query-params/parse-key :code query-params/parse-long)
(helper/default-parse-query-params grid-page))
:action-buttons (fn [request]
[(com/button {:hx-get (str (bidi/path-for ssr-routes/only-routes
:admin-account-new-dialog))
:hx-target "#modal-content"
:hx-swap "innerHTML"
:color :primary}
"New Account")])
:row-buttons (fn [request entity]
[(com/icon-button {:hx-get (str (bidi/path-for ssr-routes/only-routes
:admin-account-edit-dialog
:db/id (:db/id entity)))
:hx-target "#modal-content"
:hx-swap "innerHTML"}
svg/pencil)])
:breadcrumbs [[:a {:href (bidi/path-for ssr-routes/only-routes
:admin)}
"Admin"]
[:a {:href (bidi/path-for ssr-routes/only-routes
:admin-accounts)}
"Accounts"]]
:title "Accounts"
:entity-name "Account"
:route :admin-account-table
:headers [{:key "code"
:name "Code"
:sort-key "code"
:render :account/numeric-code}
{:key "name"
:name "Name"
:sort-key "name"
:render :account/name}
{:key "type"
:name "Type"
:sort-key "type"
:render #(some->> % :account/type name (com/pill {:color :primary}))}
{:key "location"
:name "Location"
:sort-key "location"
:render :account/location}]}))
(def row* (partial helper/row* grid-page))
(def table* (partial helper/table* grid-page))
(defn account-save [{:keys [form-params request-method] :as request}]
(let [entity (cond-> form-params
(= :post request-method) (assoc :db/id "new"))
_ (cond (= :post request-method)
(when-let [extant (seq (dc/q '[:find ?x :in $ ?nc :where [?x :account/numeric-code ?nc]] (dc/db conn) (:account/numeric-code entity)))]
(validation-error (format "The code %d is already in use." (:account/numeric-code entity)))))
{:keys [tempids]} (audit-transact [[:upsert-entity (cond-> entity
(:account/numeric-code entity) (assoc :account/code (str (:account/numeric-code entity))))]]
(:identity request))
updated-account (dc/pull (dc/db conn)
default-read
(or (get tempids (:db/id entity)) (:db/id entity)))]
(solr/index-documents-raw solr/impl
"accounts"
(into [{"id" (:db/id updated-account)
"account_id" (:db/id updated-account)
"name" (:account/name updated-account)
"numeric_code" (:account/numeric-code updated-account)
"location" (:account/location updated-account)
"applicability" (some-> updated-account :account/applicability clojure.core/name)}]
(for [o (:account/client-overrides updated-account)]
{"id" (:db/id o)
"account_id" (:db/id updated-account)
"name" (:account-client-override/name o)
"numeric_code" (:account/numeric-code updated-account)
"location" (:account/location updated-account)
"applicability" (clojure.core/name (:account/applicability updated-account))
"client_id" (:db/id (:account-client-override/client o))
"account_client_override_id" (:db/id o)})))
(html-response
(row* identity updated-account {:flash? true})
:headers {"hx-trigger" "modalclose"
"hx-retarget" (format "#account-table tr[data-id=\"%d\"]" (:db/id updated-account))})))
;; TODO use cursor
;; TODO index based list not dbid
(defn client-override* [override]
[:div.flex.gap-2.mb-2.client-override
[:div.w-96
(fc/with-field :db/id
(com/hidden {:name (fc/field-name)
:value (fc/field-value)}))
(fc/with-field :account-client-override/client
(com/validated-field {:errors (fc/field-errors)}
(com/typeahead-2 {:name (fc/field-name)
:placeholder "Search..."
:url (bidi/path-for ssr-routes/only-routes
:company-search)
:value (fc/field-value)
:value-fn :db/id ;; TODO hydration something here
:content-fn :client/name})))]
(fc/with-field :account-client-override/name
[:div.w-96
(com/validated-field {:errors (fc/field-errors)}
(com/text-input {:name (fc/field-name)
:class "w-full"
:value (fc/field-value)}))])
[:div (com/a-icon-button {"_" (hiccup/raw "on click halt the event then transition the closest <.client-override />'s opacity to 0 then remove closest <.client-override />")} svg/x)]])
;; TODO each form:
;; elimante typeahead1
;; work with new dialog
;; use cursor
;; ensure all dialogs are opened the same way
;; form level validation
;; form level validation
;; componentize
;; ensure all dependency oriented stuff works the same way
;; make sure that "new row index" stuff works ok
(defn dialog* [& {:keys [account form-params form-errors]}]
(com/modal
{}
[:form#edit-form (merge {:hx-ext "response-targets"
:hx-swap "outerHTML swap:300ms"
:hx-target-400 "#form-errors .error-content"}
form-params)
[:fieldset {:class "hx-disable"}
(com/modal-card
{}
[:div.flex [:div.p-2 "Account"] [:p.ml-2.rounded.bg-gray-200.p-2.dark:bg-gray-600 (:account/numeric-code account) " - " (:account/name account)]]
(fc/start-form
account form-errors
[:div.space-y-1
(when-let [id (:db/id account)]
(com/hidden {:name "db/id"
:value id}))
(fc/with-field :account/numeric-code
(when (nil? (fc/field-value))
(com/validated-field {:label "Numeric code"
:errors (fc/field-errors)}
(com/text-input {:name (fc/field-name)
:autofocus true
:class "w-32"}))))
(fc/with-field :account/name
(com/validated-field {:label "Name"
:errors (fc/field-errors)}
(com/text-input {:name (fc/field-name)
:autofocus true
:class "w-32"
:value (fc/field-value)})))
(fc/with-field :account/type
(com/validated-field {:label "Account Type"
:errors (fc/field-errors)}
(com/select {:name (fc/field-name)
:class "w-36"
:id "type"
:value (some-> (fc/field-value) name)
:options (ref->select-options "account-type")})))
(fc/with-field :account/location
(com/validated-field {:label "Location"
:errors (fc/field-errors)}
(com/text-input {:name (fc/field-name)
:class "w-16"
:value (fc/field-value)})))
(fc/with-field :account/invoice-allowance
(com/validated-field {:label "Invoice Allowance"
:errors (fc/field-errors)}
(com/select {:name (fc/field-name)
:value (some-> (fc/field-value) name)
:class "w-36"
:options (ref->select-options "allowance")})))
(fc/with-field :account/vendor-allowance
(com/validated-field {:label "Vendor Allowance"
:errors (fc/field-errors)}
(com/select {:name (fc/field-name)
:class "w-36"
:value (some-> (fc/field-value) name)
:options (ref->select-options "allowance")})))
(fc/with-field :account/applicability
(com/validated-field {:label "Applicability"
:errors (fc/field-errors)}
(com/select {:name (fc/field-name)
:class "w-36"
:value (some-> (fc/field-value) name)
:options (ref->select-options "account-applicability")})))
(fc/with-field :account/client-overrides
(com/field {:label "Client Overrides" :id "client-overrides"}
(when (fc/field-value)
(doall
(for [override fc/*current*]
(fc/with-cursor override
(client-override* override)))))))
(com/a-button {:hx-get (bidi/path-for ssr-routes/only-routes
:admin-account-client-override-new)
:hx-vals (hiccup/raw "js:{index: document.getElementById('client-overrides').children.length - 1}")
:hx-target "#client-overrides"
:hx-swap "beforeend"}
"New override")
[:div#form-errors [:span.error-content]]])
(com/validated-save-button {:errors []} ;; TODO
"Save account"))]]))
(defn new-client-override [{ {:keys [index]} :query-params}]
(let [index (or index 0)
account {:account/client-overrides (conj (into [] (repeat index {}))
{:db/id (str (java.util.UUID/randomUUID))})}] ;; TODO schema decode is not working
(html-response
(fc/start-form account []
(fc/with-cursor (get-in fc/*current* [:account/client-overrides index])
(client-override* fc/*current*))))))
(defn account-edit-dialog [request]
(let [account (some-> request :route-params :db/id (#(dc/pull (dc/db conn) default-read %)))]
(html-response (dialog* :account account
:form-params {:hx-put (str (bidi/path-for ssr-routes/only-routes
:admin-account-edit-save))})
:headers {"hx-trigger" "modalopen"})))
(defn account-new-dialog [_]
(html-response (dialog* :account nil
:form-params {:hx-post (str (bidi/path-for ssr-routes/only-routes
:admin-account-new-save))})
:headers {"hx-trigger" "modalopen"}))
(defn account-save-error [request]
;; TODO hydration
;; TODO consistency of error handling and passing, on all form examples
(let [entity (some-> request :last-form)]
(html-response (dialog* :account entity
:form-errors (:form-errors request)
:form-params (if (:db/id entity)
{:hx-put (str (bidi/path-for ssr-routes/only-routes
:admin-transaction-rule-edit-save))}
{:hx-post (str (bidi/path-for ssr-routes/only-routes
:admin-transaction-rule-edit-save))}))
:headers {"hx-retarget" "#edit-form fieldset"
"hx-reselect" "#edit-form fieldset"})))
(def account-schema (mc/schema
[:map
[:db/id {:optional true} [:maybe entity-id]]
[:account/numeric-code {:optional true} [:maybe :int]]
[:account/name [:string {:min 1}]]
[:account/location [:maybe :string]]
[:account/type (ref->enum-schema "account-type")]
[:account/applicability (ref->enum-schema "account-applicability")]
[:account/invoice-allowance (ref->enum-schema "allowance")]
[:account/vendor-allowance (ref->enum-schema "allowance")]
[:account/client-overrides {:optional true}
[:maybe
(many-entity {}
[:db/id [:or entity-id temp-id]]
[:account-client-override/client [:or entity-id :string]]
[:account-client-override/name [:string {:min 2}]])]]]))
(def key->handler
(apply-middleware-to-all-handlers
(->>
{:admin-accounts (helper/page-route grid-page)
:admin-account-table (helper/table-route grid-page)
:admin-account-client-override-new (-> new-client-override
(wrap-schema-decode :query-schema [:map
[:index {:optional true
:default 0} [nat-int? {:default 0}]]])
wrap-admin wrap-client-redirect-unauthenticated)
:admin-account-save (-> account-save
(wrap-schema-decode :form-schema account-schema)
(wrap-nested-form-params)
(wrap-form-4xx-2 account-save-error))
:admin-account-edit-dialog (-> account-edit-dialog
(wrap-schema-decode :route-schema [:map [:db/id entity-id]]))
:admin-account-new-dialog account-new-dialog})
(fn [h]
(-> h
(wrap-admin)
(wrap-client-redirect-unauthenticated)))))