Browse Source

Added ability to set article category

keplyx 4 years ago
parent
commit
cf599f0ef9
5 changed files with 180 additions and 33 deletions
  1. 7
    1
      assets/js/ajaxManager.js
  2. 5
    0
      assets/js/articles.js
  3. 123
    17
      assets/js/listManager.js
  4. 38
    14
      classes/dao.php
  5. 7
    1
      classes/postHandler.php

+ 7
- 1
assets/js/ajaxManager.js View File

@@ -1,6 +1,13 @@
1 1
 
2 2
 class AjaxManager {
3 3
 
4
+    static async getAll() {
5
+        let categories = await AjaxManager.get('category');
6
+        let articles = await AjaxManager.get('article');
7
+        let article_categories = await AjaxManager.get('article_categories');
8
+        return {articles: articles, categories: categories, article_categories: article_categories};
9
+    }
10
+
4 11
     static async get(type) {
5 12
         let data = {
6 13
             type: type,
@@ -40,7 +47,6 @@ class AjaxManager {
40 47
             action: isNew ? 'create' : 'update',
41 48
             data: data,
42 49
         };
43
-        console.log(formattedData);
44 50
         let response = await $.ajax({
45 51
             type: "POST",
46 52
             url: "save_manager.php",

+ 5
- 0
assets/js/articles.js View File

@@ -23,5 +23,10 @@ $(document).ready(function () {
23 23
                 description: 'Code',
24 24
                 type: 'text'
25 25
             },
26
+            {
27
+                name: 'category',
28
+                description: 'Catégories',
29
+                type: 'checkboxes'
30
+            },
26 31
         ]);
27 32
 });

+ 123
- 17
assets/js/listManager.js View File

@@ -5,15 +5,27 @@ class ListManager {
5 5
     editableTypes = [];
6 6
     type = '';
7 7
 
8
+    referredTable = [];
9
+    associationTable = [];
8 10
 
9 11
     constructor(listContainer, type, editableTypes) {
10 12
         this.listContainer = listContainer;
11 13
         this.editableTypes = editableTypes;
12 14
         this.type = type;
13
-        AjaxManager.get(type).then((data) => {
14
-            this.currentData = data;
15
-            this.generateList()
16
-        });
15
+
16
+        if (type === 'article') {
17
+            AjaxManager.getAll().then((data) => {
18
+                this.currentData = data['articles'];
19
+                this.referredTable = data['categories'];
20
+                this.associationTable = data['article_categories'];
21
+                this.generateList()
22
+            });
23
+        } else {
24
+            AjaxManager.get(type).then((data) => {
25
+                this.currentData = data;
26
+                this.generateList()
27
+            });
28
+        }
17 29
     }
18 30
 
19 31
     generateList() {
@@ -37,34 +49,84 @@ class ListManager {
37 49
         $('#listItem_' + id).remove();
38 50
     }
39 51
 
52
+    getCategoriesOfArticle(articleId) {
53
+        let filteredList = [];
54
+        for (let i = 0; i < this.associationTable.length; i++) {
55
+            if (this.associationTable[i]['article_id'] === articleId)
56
+                filteredList.push(this.associationTable[i]['category_id']);
57
+        }
58
+        return filteredList;
59
+    }
60
+
61
+    getCategoryOfId(categoryId) {
62
+        for (let i = 0; i < this.referredTable.length; i++) {
63
+            if (this.referredTable[i]['id'] === categoryId) {
64
+                return this.referredTable[i];
65
+            }
66
+        }
67
+        return "";
68
+    }
69
+
70
+    getCategoryIcons(articleId) {
71
+        let icons = "";
72
+        let categories = this.getCategoriesOfArticle(articleId);
73
+        for (let i = 0; i < categories.length; i++) {
74
+            icons += "<i class='mdi mdi-" + this.getCategoryOfId(categories[i])["icon"] + "' style='margin-right: 5px'></i>";
75
+        }
76
+        return icons;
77
+    }
78
+
40 79
     getListItem(item) {
41 80
         let listItem = "<li id='listItem_" + item["id"] + "'><div>";
42 81
         for (let i = 0; i < this.editableTypes.length; i++) {
43 82
             listItem += "<span class='list-" + this.editableTypes[i]["name"] + "'>";
44 83
             if (this.editableTypes[i]["type"] === "icon")
45 84
                 listItem += "<i class='mdi mdi-" + item["icon"] + "' style='margin-right: 5px'></i></span>";
46
-            else
85
+            else if (this.editableTypes[i]["type"] === 'checkboxes') {
86
+                listItem += this.getCategoryIcons(item['id']);
87
+            } else
47 88
                 listItem += item[this.editableTypes[i]["name"]] + '</span>';
48 89
         }
49 90
         listItem += "</div></li>";
50 91
         return listItem;
51 92
     }
52 93
 
94
+    getCategoryCheckboxes(articleId) {
95
+        let checkboxes = "<div id='checkboxesContainer' style='display: flex'>";
96
+        let categories = [];
97
+        if (articleId !== undefined)
98
+            categories = this.getCategoriesOfArticle(articleId);
99
+        for (let i = 0; i < this.referredTable.length; i++) {
100
+            let id = this.referredTable[i]['id'];
101
+            let cat = this.getCategoryOfId(id);
102
+            let checked = categories.indexOf(id) !== -1 ? 'checked' : '';
103
+            checkboxes +=
104
+                '<div class="custom-control custom-checkbox" style="margin-right: 20px">\n' +
105
+                '<input type="checkbox" class="custom-control-input" id="checkbox_' + id + '"' + checked + ' >\n' +
106
+                '<label class="custom-control-label" for="checkbox_' + id + '">' +
107
+                '<i class="mdi mdi-' + cat["icon"] + '" style="margin-right: 5px"></i>' +
108
+                '</label>\n' +
109
+                '</div>';
110
+        }
111
+        checkboxes += '</div>';
112
+        return checkboxes;
113
+    }
114
+
53 115
     getFormData(defaultValues) {
54 116
         let formData = '<form action="" class="categoryForm"><div class="form-group">';
55 117
         for (let i = 0; i < this.editableTypes.length; i++) {
56 118
             let inputId = this.editableTypes[i]['name'] + 'Input';
57 119
             let inputType = this.editableTypes[i]['type'] === 'number' ? 'number' : 'text';
58
-            let value = defaultValues[this.editableTypes[i]['name']];
120
+            let value = defaultValues[this.editableTypes[i]['name']] !== undefined ? defaultValues[this.editableTypes[i]['name']] : '';
59 121
             let icon = '';
60
-            if (this.editableTypes[i]['name'] === 'icon') {
61
-                icon = "<i class='mdi mdi-" + value + "' style='margin-left: 5px'></i>";
62
-                let onchangeCallback = function (value) {
63
-                    console.log($(icon));
64
-                }
122
+            formData += '<label for="' + inputId + '">' + this.editableTypes[i]['description'] + ' :</label>';
123
+            if (this.editableTypes[i]['type'] !== 'checkboxes') {
124
+                if (this.editableTypes[i]['name'] === 'icon')
125
+                    formData += "<i class='mdi mdi-" + value + "' style='margin-left: 5px'></i>";
126
+                formData += '<input id="' + inputId + '" type="' + inputType + '" placeholder="Entrez une valeur" class="form-control" value="' + value + '" required />';
127
+            } else {
128
+                formData += this.getCategoryCheckboxes(defaultValues['id']);
65 129
             }
66
-            formData += '<label for="' + inputId + '">' + this.editableTypes[i]['description'] + ' :</label>' + icon +
67
-                '<input id="' + inputId + '" type="' + inputType + '" placeholder="Entrez une valeur" class="form-control" value="' + value + '" required />';
68 130
         }
69 131
         formData += "</div></form>";
70 132
         return formData;
@@ -89,6 +151,18 @@ class ListManager {
89 151
         return isValid;
90 152
     }
91 153
 
154
+    getCheckedCategories(content) {
155
+        let checkedList = [];
156
+        let checkboxes = content.find('#checkboxesContainer').children();
157
+        for (let i = 0; i < checkboxes.length; i++) {
158
+            let input = $(checkboxes[i]).find('input')[0];
159
+            let id = $(input).attr('id').replace('checkbox_', '');
160
+            if (input.checked)
161
+                checkedList.push(id);
162
+        }
163
+        return checkedList;
164
+    }
165
+
92 166
     insertFormDataIntoObject(values, object) {
93 167
         for (let i = 0; i < values.length; i++) {
94 168
             object[this.editableTypes[i]['name']] = values[i];
@@ -105,11 +179,30 @@ class ListManager {
105 179
         }
106 180
     }
107 181
 
182
+    updateListItemCategories(categories, index) {
183
+        if (index === -1)
184
+            index = this.displayedData.length -1;
185
+        let iconContainer = this.displayedData[index].find(".list-category");
186
+        for (let i = 0; i < categories.length; i++) {
187
+            iconContainer.html(this.getCategoryIcons(this.currentData[index]['id']));
188
+        }
189
+    }
190
+
191
+    updateAssociationList(articleId, newCategories) {
192
+        let newTable = [];
193
+        for (let i = 0; i < this.associationTable.length; i++) {
194
+            if (this.associationTable[i]['article_id'] !== articleId)
195
+                newTable.push(this.associationTable[i]);
196
+        }
197
+        for (let i = 0; i < newCategories.length; i++) {
198
+            newTable.push({article_id: articleId, category_id: newCategories[i]});
199
+        }
200
+        console.log(newTable);
201
+        this.associationTable = newTable;
202
+    }
203
+
108 204
     showEditPopup(index) {
109
-        let defaultValues = {
110
-            name: "",
111
-            icon: ""
112
-        };
205
+        let defaultValues = {};
113 206
         let title = "Créer une nouvelle entrée";
114 207
         if (index !== -1) {
115 208
             defaultValues = this.currentData[index];
@@ -126,6 +219,7 @@ class ListManager {
126 219
                     btnClass: 'btn-blue',
127 220
                     action: async function () {
128 221
                         let values = thisInstance.getFormValues(this.$content);
222
+
129 223
                         if (!thisInstance.isFormValid(values)) {
130 224
                             $.alert('Merci de rentrer toutes les valeurs');
131 225
                             return false;
@@ -149,6 +243,18 @@ class ListManager {
149 243
                         } else if (id === -1) {
150 244
                             $.alert("Erreur serveur !");
151 245
                         }
246
+                        if (id > 0 && thisInstance.type === 'article') {
247
+                            let categories = thisInstance.getCheckedCategories(this.$content);
248
+                            let data = {
249
+                                id: id,
250
+                                categories: categories
251
+                            };
252
+                            let result = await AjaxManager.save(data, true, 'article_categories');
253
+                            if (result) {
254
+                                thisInstance.updateAssociationList(id, categories);
255
+                                thisInstance.updateListItemCategories(categories, index);
256
+                            }
257
+                        }
152 258
                     }
153 259
                 },
154 260
                 deleteButton: {

+ 38
- 14
classes/dao.php View File

@@ -35,17 +35,37 @@ class Dao
35 35
         return $cursor->fetchAll(PDO::FETCH_ASSOC);
36 36
     }
37 37
 
38
-    public function get_article_categories($article_id)
38
+    public function get_article_categories()
39 39
     {
40
-        $sql = 'SELECT category_id FROM article_categories WHERE article_id=?';
40
+        $sql = 'SELECT * FROM article_categories';
41 41
         $cursor = $this->conn->prepare($sql);
42
-        $cursor->execute([$article_id]);
43
-        $result = $cursor->fetchAll(PDO::FETCH_ASSOC);
44
-        $final = [];
45
-        foreach ($result as $row) {
46
-            array_push($final, $row["category_id"]);
42
+        $cursor->execute();
43
+        return $cursor->fetchAll(PDO::FETCH_ASSOC);
44
+    }
45
+
46
+    public function remove_article_categories_of_article($articleId)
47
+    {
48
+        $sql = 'DELETE FROM article_categories WHERE article_id=?';
49
+        $cursor = $this->conn->prepare($sql);
50
+        return $cursor->execute([$articleId]);
51
+    }
52
+
53
+    public function remove_article_categories_of_category($categoryId)
54
+    {
55
+        $sql = 'DELETE FROM article_categories WHERE category_id=?';
56
+        $cursor = $this->conn->prepare($sql);
57
+        return $cursor->execute([$categoryId]);
58
+    }
59
+
60
+    public function save_article_categories($articleId, $categories)
61
+    {
62
+        foreach ($categories as $category) {
63
+            $sql = 'INSERT INTO article_categories (article_id, category_id) VALUES (?, ?)';
64
+            $cursor = $this->conn->prepare($sql);
65
+            $data = [$articleId, $category];
66
+            $cursor->execute($data);
47 67
         }
48
-        return $final;
68
+        return 1;
49 69
     }
50 70
 
51 71
     public function get_categories()
@@ -56,7 +76,8 @@ class Dao
56 76
         return $cursor->fetchAll(PDO::FETCH_ASSOC);
57 77
     }
58 78
 
59
-    public function create_category($category) {
79
+    public function create_category($category)
80
+    {
60 81
         $sql = 'INSERT INTO categories (name, icon) VALUES (?, ?)';
61 82
         $cursor = $this->conn->prepare($sql);
62 83
         $data = [$category["name"], $category["icon"]];
@@ -79,13 +100,15 @@ class Dao
79 100
         $cursor = $this->conn->prepare($sql);
80 101
         $data = [$id];
81 102
         $result = $cursor->execute($data);
82
-        if ($result)
103
+        if ($result) {
104
+            $this->remove_article_categories_of_category($id);
83 105
             return $cursor->rowCount();
84
-        else
106
+        } else
85 107
             return 0;
86 108
     }
87 109
 
88
-    public function create_article($article) {
110
+    public function create_article($article)
111
+    {
89 112
         $sql = 'INSERT INTO articles (name, description, price, code) VALUES (?, ?, ?, ?)';
90 113
         $cursor = $this->conn->prepare($sql);
91 114
         $data = [$article["name"], $article["description"], $article["price"], $article["code"]];
@@ -108,9 +131,10 @@ class Dao
108 131
         $cursor = $this->conn->prepare($sql);
109 132
         $data = [$id];
110 133
         $result = $cursor->execute($data);
111
-        if ($result)
134
+        if ($result) {
135
+            $this->remove_article_categories_of_article($id);
112 136
             return $cursor->rowCount();
113
-        else
137
+        } else
114 138
             return 0;
115 139
     }
116 140
 }

+ 7
- 1
classes/postHandler.php View File

@@ -3,7 +3,7 @@ require_once 'dao.php';
3 3
 
4 4
 class PostHandler
5 5
 {
6
-    private $valid_types = ["article", "category"];
6
+    private $valid_types = ["article", "category", "article_categories"];
7 7
     private $valid_actions = ["create", "update", "remove", "get"];
8 8
 
9 9
     private $action;
@@ -62,6 +62,10 @@ class PostHandler
62 62
             $result = $this->dao->create_article($this->data);
63 63
         } else if ($this->type == "category") {
64 64
             $result = $this->dao->create_category($this->data);
65
+        } else if ($this->type == "article_categories") {
66
+            $result = $this->dao->remove_article_categories_of_article($this->data['id']);
67
+            if ($result)
68
+                $result = $this->dao->save_article_categories($this->data['id'], $this->data['categories']);
65 69
         } else
66 70
             $this->setUnknownTypeResponse();
67 71
         return $result;
@@ -101,6 +105,8 @@ class PostHandler
101 105
             $result = $this->dao->get_articles();
102 106
         } else if ($this->type == "category") {
103 107
             $result = $this->dao->get_categories();
108
+        } else if ($this->type == "article_categories") {
109
+            $result = $this->dao->get_article_categories();
104 110
         } else
105 111
             $this->setUnknownTypeResponse();
106 112
         return $result;

Loading…
Cancel
Save