;; 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.
(ns working-on-ezcater-square-v2
  (:require [auto-ap.square.core :as sc]
            [clj-time.core :as time]
            [auto-ap.ezcater.core :as ez])
  )

(auto-ap.routes.queries/put-query
  "ec3bae96-95cd-40aa-b0b1-342ab58efed2"
  " [:find ?d4 ?type ?p2 (sum ?total) (sum ?tip)
   :with ?charge
   :in $
   :where
   [?charge :charge/date ?date]
   [(ground (clj-time.coerce/to-date (clj-time.core/minus (auto-ap.time/local-now) (clj-time.core/days 50)))) ?min-d]
   [(>= ?date ?min-d)]
   [?charge :charge/client ?c]
   [?c :client/code \"NGOP2\"]
   [?charge :charge/type-name ?type]
   [?charge :charge/total ?total]
   [?charge :charge/tip ?tip]
   (or

     (and [_ :expected-deposit/charges ?charge ]
          [(ground :settlement) ?ccp]
          [(ground :settlement) ?p])
     (and 
       (not [_ :expected-deposit/charges ?charge])
       [(get-else $ ?charge :charge/processor :na) ?ccp]
       [(get-else $ ?ccp :db/ident :na) ?p]
       ))
   [(name ?p) ?p2]
   [(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]]
", "")

(user/init-repl)

(in-ns 'auto-ap.square.core)
(require '[auto-ap.square.core :as sc])

(require '[auto-ap.ezcater.core :as ez])

(def square-client (first (sc/get-square-clients "NGOP2")))


(def square-location (first (for [client          (sc/get-square-clients "NGOP2")
                                  square-location (:client/square-locations client)
                                  :when           (:square-location/client-location square-location)]
                              square-location)))


(sc/upsert square-client square-location (time/plus (time/now) (time/days -45)) (time/now))

(sc/upsert-settlements square-client square-location)

(sc/get-order square-client square-location "EYIVOtQj8FgdpgNlpUQP9S51uNbZY" )
(sc/get-payment square-client "vhnZ67vi7BIO6mZ6R609Vsih7nDZY")
k
(sc/get-order square-client square-location "ggjaHEikb81AKjrJC7H4RRqjDXZZY")

(sc/get-payment square-client "zhEgwmQL4cI0P00NGBAzqX5gnX6YY")

(sc/get-order square-client square-location "CdzNsHRryhGNQ9fh4tdYcEBwA4PZY")

(sc/get-order square-client square-location "hipr01buRJcFg2NFeFTjuJ4eV")


(user/start-db)

(def my-search (doall (search (first (get-square-clients "NGOP2"))
                              {:db/id                           17592186106155,
                               :square-location/name            "Oyster Point",
                               :square-location/square-id       "L3GMNBFARX9GG",
                               :square-location/client-location "OP"}
                              #clj-time/date-time "2022-06-30T00:00:00-08:00"
                              #clj-time/date-time "2022-07-01T00:00:00-08:00"
                              
                              )))

(def my-search (doall (search (first (get-square-clients "NGOP2"))
                              {:db/id                           17592186106155,
                               :square-location/name            "Oyster Point",
                               :square-location/square-id       "L3GMNBFARX9GG",
                               :square-location/client-location "OP"}
                              #clj-time/date-time "2022-07-13T00:00:00-08:00"
                              #clj-time/date-time "2022-07-14T00:00:00-08:00"
                              
                              )))

(set/difference 
  

  (filter 

    (comp (set/difference
            (set (map :id
                      (let [search-results       my-search
                            koala-production-ids (->> search-results
                                                      (filter #(= "koala-production" (:name (:source %))))
                                                      (map :id)
                                                      (into #{}))]
                        (let [search-results my-search]
                          (->> search-results
                               (filter (fn [order]
                                         ;; sometimes orders stay open in square. At least one payment
                                         ;; is needed to import, in order to avoid importing orders in-progress.
                                         (and (or (> (count (:tenders order)) 0)
                                                  (seq (:returns order)))
                                              (or (= #{} (set (map #(:status (:card_details %)) (:tenders order))))
                                                  (not= #{} (set/difference
                                                              (set (map #(:status (:card_details %)) (:tenders order)))
                                                              #{"FAILED" "VOIDED"}))))))
                               (filter (fn [order]
                                         (not= "Koala" (:name (:source order)))))
                               (filter (fn has-linked-koala-production? [order]
                                         ;; if a POS order is linked (via note) to a koala-production order, we want
                                         ;; to keep the koala-production order, because it has taxes correct
                                         (not (and (:line_items order) ;; returns do not have line items, so they should be allowed
                                                   (->> (:line_items order)
                                                        (map :note)
                                                        (every? koala-production-ids))))))))))
                 )
            (set (map :id (->> my-search
                               (filter (fn [order]
                                         (and (or (> (count (:tenders order)) 0)
                                                  (seq (:returns order)))
                                              (or (= #{} (set (map #(:status (:card_details %)) (:tenders order))))
                                                  (not= #{} (set/difference
                                                              (set (map #(:status (:card_details %)) (:tenders order)))
                                                              #{"FAILED" "VOIDED"})))
                                              (not= ["CUSTOM_AMOUNT"]
                                                    (mapv :item_type (:line_items order )))
                                              ))))
                      )))
          :id
          )
    my-search))


(doseq [p (->> 
            (d/query {:query {:find  ['?e]
                              :in    ['$]
                              :where ['(or [?e :sales-order/client [:client/code "NGOP2"]]
                                           [?e :sales-refund/client [:client/code "NGOP2"]]
                                           [?e :expected-deposit/client [:client/code "NGOP2"]])]}
                      :args  [(d/db conn)]})
            (map first)
            (map (fn [x] [:db/retractEntity x]))
            (partition-all 100))]
  @(d/transact conn p))


(def weird-order
  {:total_service_charge_money {:amount 0, :currency "USD"},
   :closed_at                  "2022-07-14T02:50:43Z",
   :total_discount_money       {:amount 0, :currency "USD"},
   :total_money                {:amount 120533, :currency "USD"},
   :total_tip_money            {:amount 0, :currency "USD"},
   :taxes
   [{:uid               "64a788f3-13c6-45a8-9333-c7e4ed4b45f2",
     :catalog_object_id "4XTWECYYOZWTGRJ475C3QOQL",
     :catalog_version   1655153159309,
     :name              "9.875%",
     :percentage        "9.875",
     :type              "ADDITIVE",
     :applied_money     {:amount 10833, :currency "USD"},
     :scope             "LINE_ITEM"}],
   :net_amounts
   {:total_money          {:amount 120533, :currency "USD"},
    :tax_money            {:amount 10833, :currency "USD"},
    :discount_money       {:amount 0, :currency "USD"},
    :tip_money            {:amount 0, :currency "USD"},
    :service_charge_money {:amount 0, :currency "USD"}},
   :total_tax_money            {:amount 10833, :currency "USD"},
   :location_id                "L3GMNBFARX9GG",
   :tenders
   [{:id                   "pQgHRVNc3WzBDZVGpORONh5YvaB",
     :location_id          "L3GMNBFARX9GG",
     :transaction_id       "XBo0x9zb7rkpWLAJ79cgihweV",
     :created_at           "2022-07-14T02:50:42Z",
     :note                 "ezcater 7\\13",
     :amount_money         {:amount 120533, :currency "USD"},
     :processing_fee_money {:amount 0, :currency "USD"},
     :type                 "OTHER"}],
   :state                      "COMPLETED",
   :ticket_name                "Ezcater 7-13",
   :updated_at                 "2022-07-14T02:50:43Z",
   :net_amount_due_money       {:amount 0, :currency "USD"},
   :return_amounts
   {:total_money          {:amount 0, :currency "USD"},
    :tax_money            {:amount 0, :currency "USD"},
    :discount_money       {:amount 0, :currency "USD"},
    :tip_money            {:amount 0, :currency "USD"},
    :service_charge_money {:amount 0, :currency "USD"}},
   :line_items
   [{:total_discount_money        {:amount 0, :currency "USD"},
     :total_money                 {:amount 120533, :currency "USD"},
     :total_tax_money             {:amount 10833, :currency "USD"},
     :uid                         "6a293751-027e-45a0-9f5d-e9f4e7cb62fd",
     :variation_total_price_money {:amount 109700, :currency "USD"},
     :item_type                   "CUSTOM_AMOUNT",
     :gross_sales_money           {:amount 109700, :currency "USD"},
     :applied_taxes
     [{:uid           "64a788f3-13c6-45a8-9333-c7e4ed4b45f2",
       :tax_uid       "64a788f3-13c6-45a8-9333-c7e4ed4b45f2",
       :applied_money {:amount 10833, :currency "USD"}}],
     :base_price_money            {:amount 109700, :currency "USD"},
     :quantity                    "1"}],
   :id                         "XBo0x9zb7rkpWLAJ79cgihweV",
   :created_at                 "2022-07-14T02:50:43Z"})

(order->sales-order "a" "b" weird-order)


(doseq [n ["185431988" "186982950" "186344682" "185281242" "184313395" "185477889" "185043055" "184552573" "185042091" "182674641" "184083782" "184200746" "181197904"]]
  (clojure.pprint/pprint 
    @(d/transact auto-ap.datomic/conn [(-> {"id" "bf3dcf5c-a68f-42d9-9084-049133e03d3d", "parent_type" "Caterer", "parent_id" "ef505599-947f-42da-a36c-4b569e33a747", "entity_type" "Order", "entity_id" "178289110", "key" "accepted", "occurred_at" "2022-07-21T19:21:07.549Z"}
                                          (assoc "entity_id" n)
                                          (ez/lookup-order)
                                          (ez/order->sales-order)
                                          (update :sales-order/date coerce/to-date)
                                          (update-in [:sales-order/charges 0 :charge/date] coerce/to-date))])))

;; 
(clojure.pprint/pprint [(-> {"id" "bf3dcf5c-a68f-42d9-9084-049133e03d3d", "parent_type" "Caterer", "parent_id" "91541331-d7ae-4634-9e8b-ccbbcfb2ce70", "entity_type" "Order", "entity_id" "178289110", "key" "accepted", "occurred_at" "2022-07-21T19:21:07.549Z"}
                            (lookup-order)
                            #_(order->sales-order)
                            #_(update :sales-order/date coerce/to-date)
                            #_(update-in [:sales-order/charges 0 :charge/date] coerce/to-date))])
