(ns register-invoices)

(def totals 

  (into []
        (d/q '[:find [(pull ?i [:db/id
                                :invoice/date
                                {:invoice/expense-accounts [:db/id
                                                            :invoice-expense-account/amount
                                                            {:invoice-expense-account/account [:db/id :account/numeric-code]}
                                                            :invoice-expense-account/location]}]) ...]
               :in $
               :where [?i :invoice/client [:client/code "MBD"]]
               [?i :invoice/date ?d]
               [(<= ?d #inst "2022-01-01T08:00:00")]]
             (d/db conn))))

(clojure.data.csv/write-csv *out* 
                            (doall (for [{:keys [:db/id :invoice/expense-accounts :invoice/date]}                                                                         totals
                                         {:keys [:invoice-expense-account/amount :invoice-expense-account/location :invoice-expense-account/account] :as g} expense-accounts 
                                         ]
                                     [id (:db/id g) (:db/id account) (atime/unparse (coerce/to-date-time date) atime/normal-date) amount (:account/numeric-code account) location]))
                            :separator \tab)
