Simplify convert-parse-tree and sort-postings

This commit is contained in:
Ben Sturmfels 2024-02-23 19:14:29 +11:00
parent 69f13c9a52
commit fb0204d76c
Signed by: bsturmfels
GPG key ID: 023C05E2C9C068F0

View file

@ -63,22 +63,19 @@
"Reformat the parse tree into a similar data structure as used during import."
[tree]
(walk/postwalk #(cond
;; vector of chars to string
(and (vector? %)
(= (type (first %)) java.lang.Character)) (apply str %)
;; posting amount to bigdec
(and (= (type %) clojure.lang.PersistentArrayMap)
(contains? % :amount)) (dissoc (update % :amount bigdec) :_)
;; flatten quoted-tokens
(and (= (type %) clojure.lang.PersistentArrayMap)
(contains? % :token)) (:token %)
;; drop :_ keys
(= (type %) clojure.lang.PersistentArrayMap) (dissoc % :_)
;; convert vector of :key/:value maps to a map
(and (vector? %)
(= (type (first %)) clojure.lang.PersistentArrayMap)
(contains? (first %) :key)) (kv->map %)
:else %)
;; vector of digit chars to bigdec
(and (vector? %) (char? (first %))) (apply str %)
;; vector of chars to string
(and (vector? %) (char? (first %))) (apply str %)
;; posting amount to bigdec
(and (map? %) (contains? % :amount)) (dissoc (update % :amount bigdec) :_)
;; flatten quoted-tokens
(and (map? %) (contains? % :token)) (:token %)
;; drop :_ keys
(map? %) (dissoc % :_)
;; convert vector of :key/:value maps to a map
(and (vector? %) (map? (first %)) (contains? (first %) :key)) (kv->map %)
:else %)
tree))
(defn parse
@ -92,8 +89,10 @@
(convert-parse-tree tree)))
(defn sort-postings
"Sort transaction postings into a predictable order."
"Sort transaction postings into a predictable order and drop zero postings."
[transactions]
(for [t transactions]
(update t :postings
(fn [ps] (sort-by (juxt #(get-in % [:meta :entity]) :account :amount) (filter #(not (zero? (:amount %))) ps))))))
(fn [ps] (->> ps
(filter #(not (zero? (:amount %))))
(sort-by (juxt #(get-in % [:meta :entity]) :account :amount)))))))