summaryrefslogtreecommitdiff
path: root/src/chef/logic/categories.clj
blob: aa9931e21cdf38e0140726942bc0bfae70ca3e71 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
(ns chef.logic.categories
  (:require [clojure.string :as cstr]
            [honey.sql :as sql]
            [next.jdbc :as jdbc]
            [chef.database :as cdb]))

(defn get-all-categories []
  (->> {:select [:*]
        :from   [:categories]}
       sql/format
       (jdbc/execute! @cdb/db)
       (filter #(pos? (:categories/id %)))                  ; Filter out root category
       ))

(defn get-category [id]
  (->> {:select [:*]
        :from   [:categories]
        :where  [:= :id id]}
       sql/format
       (jdbc/execute! @cdb/db)
       first))

(defn find-categories-with-parent [parent-id]
  (->> {:select [:*]
        :from   [:categories]
        :where  [:= :parent parent-id]}
       sql/format
       (jdbc/execute! @cdb/db)))

(defn create-category! [parent]
  (->> {:insert-into [:categories]
        :values      [{:name   "New category"
                       :parent parent}]}
       sql/format
       (jdbc/execute! @cdb/db)))

(defn- delete-category! [id]
  (->> {:delete-from [:categories]
        :where       [:= :id id]}
       sql/format
       (jdbc/execute! @cdb/db)))

(defn- delete-category-children! [id]
  (doseq [child (find-categories-with-parent id)]
    (delete-category! (:categories/id child))
    (delete-category-children! (:categories/id child))))

(defn delete-category-and-children! [id]
  (delete-category! id)
  (delete-category-children! id))

(defn update-category! [id updates]
  (->> {:update :categories
        :set    updates
        :where  [:= :id id]}
       sql/format
       (jdbc/execute! @cdb/db)))

(defn get-parents [category]
  (loop [parents (list)
         category category]
    (let [updated-parents (conj parents category)]
      (if (not= -1 (:categories/parent category))
        (recur updated-parents
               (get-category (:categories/parent category)))
        updated-parents))))

(defn generate-path [category]
  (->> category
       get-parents
       (map #(:categories/name %))
       (cstr/join " > ")))