;; This buffer is for Clojure experiments and evaluation.

;; Press C-j to evaluate the last expression.

;; You can also press C-u C-j to evaluate the expression and pretty-print its result.

(defn bad? [a]
  (> (Math/abs (- (Math/round (* 100 a))
                  (* 100 a)))
     0.0001))

(defn improved [t]
  (* (Math/round (* 100 (first t))) 0.01))

(def bad-db (d/db auto-ap.datomic/conn))

(def bad-invoices (d/q '[:find ?t (user/improved ?total) 
                         :in $
                         :where
                         #_[?t :invoice/client [:client/code "NGAK"]]
                         [?t :invoice/total ?total]
                         [(user/bad? ?total)]
                         ]
                       bad-db ))

(d/transact auto-ap.datomic/conn (->> (d/q '[:find ?ea (user/improved ?total)
                                             :in $ [?t ... ]
                                             :where
                                             #_[?t :invoice/client [:client/code "NGAK"]]
                                             [?t :invoice/total ?total]
                                             [?t :invoice/expense-accounts ?ea]
                                             [?ea :invoice-expense-account/amount ?eam]
                                             ]
                                           (d/db auto-ap.datomic/conn) (mapv first bad-invoices))
                                      (mapv (fn [[ea total]]
                                              {:db/id ea
                                               :invoice-expense-account/amount total}))))

(d/transact auto-ap.datomic/conn (->> (d/q '[:find ?t (user/improved ?total) 
                                             :in $
                                             :where
                                             #_[?t :invoice/client [:client/code "NGAK"]]
                                             [?t :invoice/total ?total]
                                             [(user/bad? ?total)]
                                             ]
                                           (d/db auto-ap.datomic/conn) )
                                      (mapv (fn [[invoice total]]
                                              {:db/id invoice
                                               :invoice/total total}))))

(d/q '[:find ?t ?total
       :in $
       :where
       #_[?t :invoice/client [:client/code "NGAK"]]
       [?t :invoice-expense-account/amount ?total]
       [(user/bad? ?total)]
       ]
     (d/db auto-ap.datomic/conn) )
