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