(ns auto-ap.jobs.vendor-usages
  (:require
   [auto-ap.datomic :refer [conn]]
   [auto-ap.jobs.core :refer [execute]]
   [datomic.api :as dc]))

(defn refresh-vendor-usages []
  @(dc/transact-async
    conn
    (->> (dc/q '[:find  ?v ?c (count ?e)
                 :in    $
                 :where
                 [?v :vendor/name]
                 (or-join [?v ?c ?e]
                          (and 
                           [?e :invoice/vendor ?v]
                           [?e :invoice/client ?c])
                          (and
                           [?e :transaction/vendor ?v]
                           [?e :transaction/client ?c])
                          (and
                           [?e :journal-entry/vendor ?v]
                           [?e :journal-entry/client ?c]))]
               (dc/db conn))
         (map (fn [[v c cnt]]
                #:vendor-usage {:vendor v
                                :client c
                                :key    (str v "-" c)
                                :count  cnt})))))

(defn -main [& _]
  (execute "vendor-usages" refresh-vendor-usages))
