Files
integreat/src/clj/auto_ap/db/invoices.clj
2018-04-10 10:51:21 -07:00

64 lines
2.4 KiB
Clojure

(ns auto-ap.db.invoices
(:require [auto-ap.db.utils :refer [clj->db db->clj get-conn]]
[auto-ap.parse :as parse]
[auto-ap.db.companies :as companies]
[auto-ap.db.vendors :as vendors]
[auto-ap.entities.companies :as company]
[auto-ap.entities.vendors :as vendor]
[clojure.java.jdbc :as j]))
(defn insert-multi! [rows]
(j/insert-multi! (get-conn)
:invoices
(map clj->db rows)))
(defn with-relations [results]
(let [companies (reduce
#(assoc %1 (:id %2) %2)
{}
(companies/get-all))
vendors (reduce
#(assoc %1 (:id %2) %2)
{}
(vendors/get-all))]
(println companies vendors)
(->> results
(map #(assoc % :vendor (vendors (:vendor-id %))))
(map #(assoc % :company (companies (:company-id %)))))))
(defn get-all []
(->> (j/query (get-conn)
(str " SELECT invoices.* "
" FROM invoices "))
(map db->clj)
with-relations
))
(defn approve []
(map db->clj (j/update! (get-conn) :invoices {:imported true} [] )))
(defn reject []
(j/delete! (get-conn) :invoices ["imported = false"]))
(defn get-unpaid [company]
(if company
(with-relations (map db->clj (j/query (get-conn) ["SELECT * FROM invoices WHERE imported=true AND company_id = ?" (Integer/parseInt company)])))
(with-relations (map db->clj (j/query (get-conn) "SELECT * FROM invoices WHERE imported=true")))))
(defn get-pending [company]
(if company
(with-relations (map db->clj (j/query (get-conn) ["SELECT * FROM invoices WHERE (imported=false or imported is null) AND company_id = ?" (Integer/parseInt company)])))
(with-relations (map db->clj (j/query (get-conn) "SELECT * FROM invoices WHERE imported=false or imported is null")))))
(defn import [parsed-invoices companies vendors]
(insert-multi!
(for [{:keys [total date invoice-number customer-identifier vendor-code] :as row} parsed-invoices]
(do
(dissoc (assoc row
:company-id (:id (parse/best-match companies customer-identifier))
:vendor-id (:id (first (filter #(= (:code %) vendor-code) vendors)))
:imported false
:potential-duplicate false)
:vendor-code)))))