;; 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.

(-> (order "WrNb9vXPkflwbVz7sCHGkpr8k3VZY" )
    :order
    ((fn [order]
       (let [[client loc] (location_id->client-location (:location_id order))]
         (remove-nils
          #:sales-order
          {:date (coerce/to-date (time/to-time-zone (coerce/to-date-time (:created_at order)) (time/time-zone-for-id "America/Los_Angeles"))) 
           :client [:client/code client]
           :location loc
           :external-id (str "square/order/" client "-" loc "-" (:id order))
           :total (-> order :net_amounts :total_money amount->money)
           :tax (-> order :net_amounts :tax_money amount->money)
           :tip (-> order :net_amounts :tip_money amount->money)
           :discount (-> order :net_amounts :discount_money amount->money)
           :service-charge (-> order :net_amounts :service_charge_money amount->money)
           :returns (+ (- (-> order :return_amounts :total_money amount->money)
                          (-> order :return_amounts :tax_money amount->money)
                          (-> order :return_amounts :tip_money amount->money)
                          (-> order :return_amounts :service_charge_money amount->money)

                          ;; not returning discount money since that was already marked off the price
                          ;;(-> order :return_amounts :discount_money amount->money)
                          ))
           :charges (->> (:tenders order)
                         (map (fn [t]
                                (remove-nils 
                                 #:charge
                                 {:type-name (:type t)
                                  :processor (condp = (some-> (:note t) str/lower-case)
                                               "doordash" :ccp-processor/doordash
                                               "dd"  :ccp-processor/doordash
                                               "ubereats" :ccp-processor/uber-eats
                                               "ue"  :ccp-processor/uber-eats
                                               "grubhub" :ccp-processor/grubhub
                                               "grub" :ccp-processor/grubhub
                                               "gh" :ccp-processor/grubhub
                                               (condp = (:name (:source order))
                                                 "GRUBHUB" :ccp-processor/grubhub
                                                 "UBEREATS" :ccp-processor/uber-eats
                                                 "DOORDASH" :ccp-processor/doordash
                                                 :ccp-processor/na))
                                  :total (amount->money (:amount_money t))
                                  :tip (amount->money (:tip_money t))}))))
           :line-items (->> (:line_items order)
                            (map (fn [li]
                                   (remove-nils 
                                    #:order-line-item
                                    {:item-name (:name li)
                                     :category (if (= "GIFT_CARD" (:item_type li))
                                                 "Gift Card"
                                                 (item-id->category-name (:catalog_object_id li)))
                                     :total (amount->money (:total_money li))
                                     :tax (amount->money (:total_tax_money li))
                                     :discount (amount->money (:total_discount_money li))}))))}))))
    (clojure.pprint/pprint))




(d/query {:query {:find '[?d4 ?type (sum ?total) (sum ?tip)]
                  :with '[?s ?charge]
                  :in '[$] 
                  :where 
                  '[[?c :client/code "NGVZ"]
                   [?s :sales-order/client ?c]
                   [?s :sales-order/charges ?charge]
                   [?charge :charge/type-name ?type]
                   [?charge :charge/total ?total]
                   [?charge :charge/tip ?tip]
                   [?s :sales-order/date ?date]
                   [(clj-time.coerce/to-date-time ?date) ?d2]
                   [(auto-ap.time/localize ?d2) ?d3]
                    [(auto-ap.time/unparse-local ?d3 auto-ap.time/normal-date) ?d4]
                    [(= ?d4 "06/25/2021")]]}
          :args [(d/db conn)]})

(count (settlements "ACNTYY8WVZ6DV"))

@(d/transact conn (->> (d/query {:query {:find '[?s]
                                        :in '[$] 
                                        :where 
                                        '[[?c :client/code "NGVZ"]
                                          [?s :sales-order/client ?c]
                                          [?s :sales-order/charges ?charge]
                                          [?charge :charge/type-name ?type]
                                          [?charge :charge/total ?total]
                                          [?charge :charge/tip ?tip]
                                          [?s :sales-order/date ?date]
                                          [(clj-time.coerce/to-date-time ?date) ?d2]
                                          [(auto-ap.time/localize ?d2) ?d3]
                                          [(auto-ap.time/unparse-local ?d3 auto-ap.time/normal-date) ?d4]
                                          [(= ?d4 "06/25/2021")]]}
                                :args [(d/db conn)]})
                      (mapv (fn [[s]]
                              [:db/retractEntity s]))
                      ))

(->> (search "ACNTYY8WVZ6DV" #inst "2021-06-25T00:00:00-08:00")
     (map :id)
     #_(mapcat :tenders)
     #_(filter #(= "CARD" (:type %)))
     #_(map :amount_money)
     #_(map :amount)
     count
     #_(reduce + 0 ))


(d/query {:query {:find '[(pull ?s [*])]
                  :in '[$] 
                  :where 
                  '[[?c :client/code "NGVZ"]
                    [?s :sales-order/client ?c]
                    (not [?s :sales-order/charges])
                    #_[?charge :charge/type-name "CARD"]
                    #_[?charge :charge/total ?total]
                    #_[?charge :charge/tip ?tip]
                    [?s :sales-order/date ?date]
                    [(clj-time.coerce/to-date-time ?date) ?d2]
                    [(auto-ap.time/localize ?d2) ?d3]
                    [(auto-ap.time/unparse-local ?d3 auto-ap.time/normal-date) ?d4]
                    [(= ?d4 "06/25/2021")]]}
          :args [(d/db conn)]})


(order "WrNb9vXPkflwbVz7sCHGkpr8k3VZY" )
k





(defn settlements-2 [l d]
  (log/info "Searching for" l)
  (let [settlements (->> (client/get (str "https://connect.squareup.com/v1/" l "/settlements" "?begin_time=" "2021-06-15" "&end_time=" "2021-06-18" "&limit=" "10")
                                     {:headers {"Authorization" "Bearer EAAAEO2xSqesDutZz71hz3eulKmrlKTiEqG3uZ4j25x5GYlOluQ2cj2JxNUXqXD7"
                                                "Content-Type" "application/json"}
                                      :as :json}) 
                         :body
                         (map :id))]
    (loop [[s & xs] (take 15 settlements)
           result []]
      (log/info "Looking up settlement " s " for location " l)
      (let [n (:body (retry #(client/get (str "https://connect.squareup.com/v1/" l "/settlements/" s)
                                        {:headers {"Authorization" "Bearer EAAAEO2xSqesDutZz71hz3eulKmrlKTiEqG3uZ4j25x5GYlOluQ2cj2JxNUXqXD7"
                                                   "Content-Type" "application/json"}
                                         :as :json
                                         :retry-handler (fn [ex try-count http-context]
                                                          (log/warn "Retrying after failure " ex)
                                                          (if (> try-count 4) false true))})))]
        (if (seq xs)
          (recur xs (conj result n))
          (conj result n))))))

(defn daily-settlements-2 []
  (for [settlement (settlements-2 "ACNTYY8WVZ6DV" nil)
        :let [[client loc] (location_id->client-location "ACNTYY8WVZ6DV")]]
    #:expected-deposit {:external-id (str "square/settlement/" (:id settlement))
                        :total (amount->money (:total_money settlement))
                        :client [:client/code client]
                        :location loc
                        :fee (- (reduce + 0 (map (fn [entry]
                                                   (if (= (:type entry) "REFUND")
                                                     (- (amount->money (:fee_money entry)))
                                                     (amount->money (:fee_money entry))))
                                                 (:entries settlement))))
                        :date (-> (:initiated_at settlement)
                                  (coerce/to-date))}))


(clojure.pprint/pprint (daily-settlements-2))



(for [g ["3ZT28C9V6EA08YQ6DDBY12E74TPD" "3ZAM1XMMYDGW8YQ6DDBY12E74TPD" "3Z3B2JHJECQ48YQ6DDBY12E74TPD" "3Z3B2JFKECQ48YQ6DDBY12E74TPD" "3Z3B2JD2YCQ48YQ6DDBY12E74TPD" "3Z6FY3M3PACC8YQ6DDBY12E74TPD" "3ZXAN5JAP9K48YQ6DDBY12E74TPD" "3ZPPMSRM68T08YQ6DDBY12E74TPD" "3Z9YW2MEP80W8YQ26RBY12E74TP9"]]
  (:expected-deposit/fee (d/entity (d/db conn) [:expected-deposit/external-id (str "square/settlement/" g)])))


(d/entity (d/db conn) [:expected-deposit/external-id (str "square/settlement/3Z3KFBM8PF388YQ6DDBY12E74TPD")])




@(d/transact conn [#:expected-deposit{:external-id
                                     "square/settlement/3Z3KFBM8PF388YQ6DDBY12E74TPD",
                                     :total 2282.05,
                                     :client [:client/code "NGVZ"],
                                     :location "NP",
                                     :fee 65.35,
                                     :date #inst "2021-06-17T03:14:22.000-00:00"}])

