Browse Source

First implementation of database

keplyx 1 year ago
parent
commit
64a584927b

+ 20
- 54
admin/categories.php View File

@@ -1,26 +1,11 @@
1 1
 <?php
2 2
 $relativePath = "../";
3
+require_once $relativePath . 'classes/dao.php';
3 4
 
4
-$file = '../data/stock-v2.json';
5
-$fp = fopen($file, 'r');
6
-$result = fread($fp, filesize($file));
7
-fclose($fp);
5
+$dao = new Dao();
6
+
7
+$categories = $dao->get_categories();
8 8
 
9
-ob_start();
10
-?>
11
-<tr>
12
-    <th class="id-column">Id</th>
13
-    <th class="name-column">Nom</th>
14
-    <th class="icon-column">
15
-        <a href="https://materialdesignicons.com/" target="_blank">
16
-            Icone
17
-            <i class="fas fa-external-link-alt"></i>
18
-        </a>
19
-    </th>
20
-    <th class="actions-column">Actions</th>
21
-</tr>
22
-<?php
23
-$tableHeader = ob_get_clean();
24 9
 ob_start();
25 10
 ?>
26 11
 <div class="admin-container">
@@ -30,48 +15,23 @@ ob_start();
30 15
     </a>
31 16
 
32 17
     <h1 class="text-center">Gestion des Catégories</h1>
33
-    <h2 class="text-center">Ajouter une catégorie</h2>
34
-    <table>
35
-        <tbody>
36
-        <?= $tableHeader ?>
37
-        <tr>
38
-            <td>
39
-                <input type="text" class="form-control" id="idInput" placeholder="Id">
40
-            </td>
41
-            <td>
42
-                <input type="text" class="form-control" id="nameInput" placeholder="Nom">
43
-            </td>
44
-            <td>
45
-                <input type="text" class="form-control" id="iconInput" placeholder="Icone">
46
-            </td>
47
-            <td>
48
-                <button type="submit" class="btn btn-success" onclick="addNewItem()"><i class="fas fa-check"></i>
49
-                </button>
50
-            </td>
51
-        </tr>
52
-        </tbody>
53
-    </table>
54 18
 
55
-    <h2 class="text-center">Liste des catégories</h2>
56
-    <table id="categoriesTable">
57
-        <tbody>
58
-        <?= $tableHeader ?>
59
-        </tbody>
60
-    </table>
61
-
62
-    <div style="display: flex; margin-top: 100px; margin-bottom: 100px">
63
-        <button class="btn btn-success btn-lg" style="margin: auto"
64
-                onclick="saveDataset()">
65
-            Sauvegarder les catégories
19
+    <div style="display: flex">
20
+        <button class="btn btn-success" style="margin: auto" onclick="listManager.showEditPopup(-1)">
21
+            <i class="mdi mdi-plus"></i>
66 22
         </button>
67 23
     </div>
68 24
 
25
+    <ul id="dataList">
26
+
27
+    </ul>
28
+
69 29
     <script type="text/javascript">
70
-        let json_dump = <?php echo $result; ?>;
30
+        let json_dump = <?php echo json_encode($categories); ?>;
71 31
     </script>
72 32
 
73 33
 
74
-</>
34
+</div>
75 35
 
76 36
 <link type="text/css" rel="stylesheet" href="https://cdn.materialdesignicons.com/4.4.95/css/materialdesignicons.min.css"
77 37
       media="screen,projection"/>
@@ -82,6 +42,12 @@ ob_start();
82 42
 <?php
83 43
 $pageContent = ob_get_clean();
84 44
 $pageTitle = "Gestion des catégories";
85
-$pageScripts = "<script type=\"text/javascript\" src=\"" . $relativePath . "assets/js/saveManager.js\"></script><script type=\"text/javascript\" src=\"" . $relativePath . "assets/js/categories.js\"></script>";
45
+$pageScripts =
46
+    "
47
+    <script type=\"text/javascript\" src=\"" . $relativePath . "assets/js/jquery-confirm-defaults.js\"></script>
48
+    <script type=\"text/javascript\" src=\"" . $relativePath . "assets/js/saveManager.js\"></script>
49
+    <script type=\"text/javascript\" src=\"" . $relativePath . "assets/js/listManager.js\"></script>
50
+    <script type=\"text/javascript\" src=\"" . $relativePath . "assets/js/categories.js\"></script>
51
+    ";
86 52
 include($relativePath . "includes/template.php");
87 53
 ?>

+ 0
- 57
admin/convert_json.php View File

@@ -1,57 +0,0 @@
1
-<?php
2
-
3
-echo 'Ouverture du fichier V1...
4
-';
5
-$file = '../data/stock.json';
6
-$fp = fopen($file, 'r');
7
-$result = json_decode(fread($fp, filesize($file)));
8
-fclose($fp);
9
-
10
-
11
-function getConvertedTypes($oldTypes) {
12
-    $newTypes = [];
13
-    $counter = 1;
14
-    foreach ($oldTypes as $type) {
15
-        array_push($newTypes, (object) ["id" => strval($counter), "name" => $type, "icon" => "file"]);
16
-        $counter += 1;
17
-    }
18
-    return $newTypes;
19
-}
20
-
21
-function getConvertedArticles($articles, $newTypes) {
22
-    foreach ($articles as $article) {
23
-        $article->description = "Pas de description";
24
-        foreach ($article->type as $key=>$value) {
25
-            $article->type[$key] = getTypeIdFromName($value, $newTypes);
26
-        }
27
-    }
28
-    return $articles;
29
-}
30
-
31
-function getTypeIdFromName($name, $types) {
32
-    foreach ($types as $type) {
33
-        if ($type->name == $name)
34
-            return $type->id;
35
-    }
36
-}
37
-
38
-if ($result) {
39
-    echo 'Conversion en cours...
40
-    ';
41
-    $newTypes = getConvertedTypes($result->types);
42
-    $newArticles = getConvertedArticles($result->articles, $newTypes);
43
-    $v2File = json_encode(["types"=>$newTypes, "articles"=>$newArticles]);
44
-    echo 'Conversion réussie...
45
-    ';
46
-    echo 'Sauvegarde dans fichier V2...
47
-    ';
48
-    $fp = fopen('../data/stock-v2.json', 'w');
49
-    $result = fwrite($fp, $v2File);
50
-    fclose($fp);
51
-    echo 'Sauvegarde réussie...
52
-    ';
53
-} else {
54
-    echo 'Echec!
55
-    '; // Allows to create a newline
56
-    var_dump($_POST);
57
-}

+ 39
- 0
admin/save_manager.php View File

@@ -0,0 +1,39 @@
1
+<?php
2
+$relativePath = "../";
3
+require_once $relativePath . 'classes/dao.php';
4
+
5
+$rest_json = file_get_contents("php://input");
6
+$_POST = json_decode($rest_json, true);
7
+
8
+
9
+//var_dump($_POST);
10
+$result = -1;
11
+$status = 0;
12
+$message = "Success";
13
+
14
+$dao = new Dao();
15
+
16
+if ($_POST["function"] == "create_category")
17
+    $result = $dao->create_category($_POST["data"]);
18
+else if ($_POST["function"] == "update_category") {
19
+    $result = $dao->update_category($_POST["data"]);
20
+} else if ($_POST["function"] == "remove_category")
21
+    $result = $dao->remove_category($_POST["data"]);
22
+else {
23
+    $status = 1;
24
+    $message = "Error: Unknown function";
25
+}
26
+
27
+if ($result < 0) {
28
+    $status = 2;
29
+    $message = "Error: SQL error";
30
+}
31
+
32
+$array = array(
33
+    "status" => $status,
34
+    "message" => $message,
35
+    "data" => $result,
36
+);
37
+
38
+echo json_encode($array);
39
+

+ 25
- 15
admin/stock.php View File

@@ -1,10 +1,16 @@
1 1
 <?php
2 2
 $relativePath = "../";
3
+require_once $relativePath.'classes/dao.php';
3 4
 
4
-$file = '../data/stock-v2.json';
5
-$fp = fopen($file, 'r');
6
-$result = fread($fp, filesize($file));
7
-fclose($fp);
5
+$dao = new Dao();
6
+
7
+$stock = $dao->get_articles();
8
+$categories = $dao->get_categories();
9
+
10
+for ($i = 0; $i < sizeof($stock); $i++) {
11
+    $article_categories = $dao->get_article_categories($stock[$i]["id"]);
12
+    $stock[$i]["type"] = $article_categories;
13
+}
8 14
 
9 15
 ob_start();
10 16
 ?>
@@ -16,7 +22,6 @@ ob_start();
16 22
     <th class="code-column">Code Barre</th>
17 23
     <th class="type-column">Type</th>
18 24
     <th class="image-column">Image</th>
19
-    <th class="actions-column">Actions</th>
20 25
 </tr>
21 26
 <?php
22 27
 $tableHeader = ob_get_clean();
@@ -29,7 +34,7 @@ ob_start();
29 34
     </a>
30 35
 
31 36
     <h1 class="text-center">Gestion des Stocks</h1>
32
-    <?php if ($result): ?>
37
+    <?php if ($stock): ?>
33 38
     <h2 class="text-center">Ajouter un article</h2>
34 39
     <table>
35 40
         <tbody>
@@ -56,10 +61,6 @@ ob_start();
56 61
             <td>
57 62
                 <input type="text" class="form-control" id="imageInput" placeholder="Lien Image">
58 63
             </td>
59
-            <td>
60
-                <button type="submit" class="btn btn-success" onclick="addNewItem()"><i class="fas fa-check"></i>
61
-                </button>
62
-            </td>
63 64
         </tr>
64 65
         </tbody>
65 66
     </table>
@@ -87,13 +88,22 @@ ob_start();
87 88
         </div>
88 89
     <?php endif; ?>
89 90
     <script type="text/javascript">
90
-        let json_dump =
91
+        let json_dump = {
92
+            types:
93
+            <?php
94
+            if ($categories)
95
+                echo json_encode($categories);
96
+            else
97
+                echo 'undefined';
98
+            ?>,
99
+            articles:
91 100
             <?php
92
-            if ($result)
93
-                echo $result;
101
+            if ($stock)
102
+                echo json_encode($stock);
94 103
             else
95
-                echo 'undefined'
96
-            ?>;
104
+                echo 'undefined';
105
+            ?>
106
+        }
97 107
     </script>
98 108
 
99 109
 

+ 16
- 10
assets/css/categories.css View File

@@ -1,19 +1,25 @@
1
-#categoriesTable tr {
2
-    border-bottom: 1px solid #dedede;
1
+#dataList {
2
+    list-style: none;
3 3
 }
4 4
 
5
-.mdi {
6
-    font-size: 2rem;
5
+#dataList li {
6
+    text-align: center;
7
+    height: 50px;
8
+    line-height: 50px;
9
+    display: flex;
10
+    cursor: pointer;
11
+    transition: 0.2s;
7 12
 }
8 13
 
9
-.actions-column {
10
-    width: 100px;
14
+#dataList li:hover {
15
+    background-color: #e5e5e5;
11 16
 }
12 17
 
13
-.id-column {
14
-    width: 200px;
18
+#dataList li div {
19
+    margin: auto;
20
+    display: flex;
15 21
 }
16 22
 
17
-.icon-column {
18
-    width: 200px;
23
+.mdi {
24
+    font-size: 2rem;
19 25
 }

+ 9
- 0
assets/css/jquery-confirm.min.css
File diff suppressed because it is too large
View File


+ 139
- 131
assets/js/categories.js View File

@@ -1,135 +1,143 @@
1
-let currentDataset = [];
2
-let currentTypes = [];
3
-let originalEditedItem = {};
4
-
5
-function initValuesFromPHPDump() {
6
-    currentDataset = json_dump.articles; // json_dump is set using PHP
7
-    currentTypes = json_dump.types;
8
-    console.log(currentDataset);
9
-    console.log(currentTypes);
10
-    generateTable(currentTypes);
11
-}
1
+// let listContainer = $("#dataList");
2
+// let currentTypes = [];
3
+// let displayedTypes = [];
12 4
 
5
+let listManager;
13 6
 
14 7
 $(document).ready(function () {
15
-    initValuesFromPHPDump();
16
-    setEditFieldValues('', '', '');
8
+    listManager = new ListManager($("#dataList"), json_dump,
9
+        [
10
+            {
11
+                name: 'icon',
12
+                description: 'Icone',
13
+                type: 'icon'
14
+            },
15
+            {
16
+                name: 'name',
17
+                description: 'Nom',
18
+                type: 'text'
19
+            },
20
+        ]);
17 21
 });
18
-
19
-
20
-function generateTable(dataset) {
21
-    for (let i = 0; i < dataset.length; i++) {
22
-        generateLine(dataset[i]);
23
-    }
24
-}
25
-
26
-function generateLine(item) {
27
-    $.selector_cache('#categoriesTable').append(
28
-        '<tr id="row_' + item.id + '">' +
29
-        '<td>' + item.id + '</td>' +
30
-        '<td>' + item.name + '</td>' +
31
-        '<td><span class="mdi mdi-' + item.icon + '"></span></td>' +
32
-        '<td>' +
33
-        '<button class="btn btn-danger" id="delete_' + item.id + '" onclick="deleteItem(this)"><i class="fas fa-times"></i></button>' +
34
-        '<button class="btn btn-primary" id="edit_' + item.id + '" onclick="editItem(this)"><i class="fas fa-edit"></i></button>' +
35
-        '</td>' +
36
-        '</tr>'
37
-    );
38
-}
39
-
40
-function addNewItem() {
41
-    if (isItemInputFilled()) {
42
-        let item = {
43
-            id: $.selector_cache('#idInput').val(),
44
-            name: $.selector_cache('#nameInput').val(),
45
-            icon: $.selector_cache('#iconInput').val(),
46
-        };
47
-        if (isIdAvailable(item.id)) {
48
-            updateExistingItemsType(originalEditedItem.id, item.id);
49
-            setEditFieldValues('', '', '');
50
-            currentTypes.push(item);
51
-            generateLine(item);
52
-        }
53
-    }
54
-}
55
-
56
-function editItem(elem) {
57
-    if (isItemInputEmpty()) {
58
-        let id = elem.id.replace('edit_', '');
59
-        let item = getTypeOfId(id);
60
-        originalEditedItem = item;
61
-        setEditFieldValues(item.id, item.name, item.icon);
62
-        removeItemFromList(item); // Move the item in the edit fields
63
-    }
64
-}
65
-
66
-function deleteItem(elem) {
67
-    let id = elem.id.replace('delete_', '');
68
-    let item = getTypeOfId(id);
69
-    updateExistingItemsType(id, undefined);
70
-    removeItemFromList(item);
71
-}
72
-
73
-function removeItemFromList(item) {
74
-    currentTypes.splice(currentTypes.indexOf(item), 1);
75
-    $('#row_' + item.id).remove();
76
-}
77
-
78
-function setEditFieldValues(id, name, icon) {
79
-    $.selector_cache('#idInput').val(id);
80
-    $.selector_cache('#nameInput').val(name);
81
-    $.selector_cache('#iconInput').val(icon);
82
-}
83
-
84
-function updateExistingItemsType(oldTypeID, newTypeID) {
85
-    for (let i = 0; i < currentDataset.length; i++) {
86
-        for (let k = 0; k < currentDataset[i].type.length; k++) {
87
-            if (currentDataset[i].type[k] === oldTypeID) {
88
-                console.log(newTypeID);
89
-                if (newTypeID !== undefined)
90
-                    currentDataset[i].type[k] = newTypeID;
91
-                else
92
-                    currentDataset[i].type.splice(k, 1);
93
-                break;
94
-            }
95
-        }
96
-    }
97
-}
98
-
99
-function getTypeOfId(id) {
100
-    let item = {};
101
-    for (let i = 0; i < currentTypes.length; i++) {
102
-        if (currentTypes[i].id === id) {
103
-            item = currentTypes[i];
104
-            break;
105
-        }
106
-    }
107
-    return item;
108
-}
109
-
110
-function isIdAvailable(id) {
111
-    let isAvailable = true;
112
-    for (let i = 0; i < currentTypes.length; i++) {
113
-        if (currentTypes[i].id === id) {
114
-            isAvailable = false;
115
-            break;
116
-        }
117
-    }
118
-    return isAvailable;
119
-}
120
-
121
-function isItemInputEmpty() {
122
-    return $.selector_cache('#idInput').val() === '' &&
123
-        $.selector_cache('#nameInput').val() === '' &&
124
-        $.selector_cache('#iconInput').val() === '';
125
-}
126
-
127
-function isItemInputFilled() {
128
-    return $.selector_cache('#idInput').val() !== '' &&
129
-        $.selector_cache('#nameInput').val() !== '' &&
130
-        $.selector_cache('#iconInput').val() !== '';
131
-}
132
-
133
-function saveDataset() {
134
-    SaveManager.saveData(currentTypes, currentDataset);
135
-}
22
+//
23
+// function initValuesFromPHPDump() {
24
+//     currentTypes = json_dump;
25
+//     console.log(currentTypes);
26
+//
27
+// }
28
+//
29
+// $(document).ready(function () {
30
+//     initValuesFromPHPDump();
31
+//     generateList();
32
+//     console.log(displayedTypes);
33
+// });
34
+//
35
+// function generateList() {
36
+//     for (let i = 0; i < currentTypes.length; i++) {
37
+//         createNewListEntry(currentTypes[i]);
38
+//     }
39
+// }
40
+//
41
+// function createNewListEntry(type) {
42
+//     displayedTypes.push(
43
+//         $("<li id='listItem_" + type["id"] + "' onclick='showEditPopup(" + displayedTypes.length + ")'>" +
44
+//         "<div>" +
45
+//         "<span class='category-icon'><i class='mdi mdi-" + type["icon"] + "'></i></span>" +
46
+//         "<span class='category-title'>" + type["name"] + "</span>" +
47
+//         "</div>" +
48
+//         "</li>"));
49
+//     listContainer.append(displayedTypes[displayedTypes.length - 1]);
50
+// }
51
+//
52
+// function deleteListEntry(id) {
53
+//     $('#listItem_' + id).remove();
54
+// }
55
+//
56
+//
57
+// function showEditPopup(index) {
58
+//     let defaultValues = {
59
+//         name: "",
60
+//         icon: ""
61
+//     };
62
+//     let title = "Créer une catégorie";
63
+//     if (index !== -1) {
64
+//         defaultValues = currentTypes[index];
65
+//         title = "Modifier la catégorie";
66
+//     }
67
+//     $.confirm({
68
+//         title: title,
69
+//         content:
70
+//             '<form action="" class="categoryForm">' +
71
+//             '<div class="form-group">' +
72
+//             '<label for="nameInput">Nom :</label>' +
73
+//             '<input id="nameInput" type="text" placeholder="Nom" class="name-input form-control" value="' + defaultValues['name'] + '" required />' +
74
+//             '<label for="iconInput">Icone :</label>' +
75
+//             '<input id="iconInput" type="text" placeholder="icone" class="icon-input form-control" value="' + defaultValues['icon'] + '" required />' +
76
+//             '</div>' +
77
+//             '</form>',
78
+//         buttons: {
79
+//             formSubmit: {
80
+//                 text: 'Sauvegarder',
81
+//                 btnClass: 'btn-blue',
82
+//                 action: async function () {
83
+//                     let name = this.$content.find('#nameInput').val();
84
+//                     let icon = this.$content.find('#iconInput').val();
85
+//                     if (!name) {
86
+//                         $.alert('Merci de donner un nom');
87
+//                         return false;
88
+//                     } else if (!icon) {
89
+//                         $.alert('Merci de donner une icone');
90
+//                         return false;
91
+//                     }
92
+//                     let itemToSave;
93
+//                     if (index !== -1) {
94
+//                         currentTypes[index]['name'] = name;
95
+//                         currentTypes[index]['icon'] = icon;
96
+//                         itemToSave = currentTypes[index];
97
+//                         displayedTypes[index].find(".category-title").text(name);
98
+//                         displayedTypes[index].find(".mdi")[0].className = "mdi mdi-" + icon;
99
+//                     } else {
100
+//                         itemToSave = {
101
+//                             name: name,
102
+//                             icon: icon,
103
+//                             display_order: 0,
104
+//                         };
105
+//                     }
106
+//                     let id = await SaveManager.saveCategory(itemToSave, index === -1);
107
+//                     if (id >= 0 && index === -1) {
108
+//                         itemToSave = {
109
+//                             name: name,
110
+//                             icon: icon,
111
+//                             display_order: 0,
112
+//                             id: id
113
+//                         };
114
+//                         currentTypes[displayedTypes.length] = itemToSave;
115
+//                         createNewListEntry(itemToSave);
116
+//                     }
117
+//                 }
118
+//             },
119
+//             deleteButton: {
120
+//                 text: 'Supprimer',
121
+//                 btnClass: 'btn-red',
122
+//                 isHidden: index === -1,
123
+//                 action: function () {
124
+//                     let id = currentTypes[index]['id'];
125
+//                     SaveManager.deleteCategory(id);
126
+//                     deleteListEntry(id);
127
+//                 }
128
+//             },
129
+//             cancelButton: {
130
+//                 text: 'Annuler',
131
+//             },
132
+//         },
133
+//         onContentReady: function () {
134
+//             // bind to events
135
+//             let jc = this;
136
+//             this.$content.find('form').on('submit', function (e) {
137
+//                 // if the user submits the form by pressing enter in the field.
138
+//                 e.preventDefault();
139
+//                 jc.$$formSubmit.trigger('click'); // reference the button and click it
140
+//             });
141
+//         }
142
+//     });
143
+// }

+ 0
- 75
assets/js/init.js View File

@@ -70,78 +70,3 @@ function animateCss($elem, animationName, callback) {
70 70
             callback();
71 71
     });
72 72
 }
73
-
74
-
75
-jconfirm.defaults = {
76
-    title: 'Title',
77
-    titleClass: '',
78
-    type: 'red',
79
-    typeAnimated: true,
80
-    draggable: false,
81
-    dragWindowGap: 15,
82
-    dragWindowBorder: true,
83
-    animateFromElement: true,
84
-    smoothContent: true,
85
-    content: 'content',
86
-    escapeKey: 'ok',
87
-    buttons: {},
88
-    defaultButtons: {
89
-        ok: {
90
-            keys: ['enter'],
91
-            text: 'OK',
92
-            action: function () {
93
-            }
94
-        },
95
-        close: {
96
-            action: function () {
97
-            }
98
-        },
99
-    },
100
-    contentLoaded: function (data, status, xhr) {
101
-    },
102
-    icon: '',
103
-    lazyOpen: false,
104
-    bgOpacity: null,
105
-    theme: 'supervan',
106
-    animation: 'scale',
107
-    closeAnimation: 'scale',
108
-    animationSpeed: 300,
109
-    animationBounce: 1,
110
-    rtl: false,
111
-    container: 'body',
112
-    containerFluid: false,
113
-    backgroundDismiss: false,
114
-    backgroundDismissAnimation: 'shake',
115
-    autoClose: false,
116
-    closeIcon: null,
117
-    closeIconClass: false,
118
-    watchInterval: 100,
119
-    columnClass: 'xlarge',
120
-    boxWidth: '50%',
121
-    scrollToPreviousElement: true,
122
-    scrollToPreviousElementAnimate: true,
123
-    useBootstrap: true,
124
-    offsetTop: 40,
125
-    offsetBottom: 40,
126
-    bootstrapClasses: {
127
-        container: 'container',
128
-        containerFluid: 'container-fluid',
129
-        row: 'row',
130
-    },
131
-    onContentReady: function () {
132
-    },
133
-    onOpenBefore: function () {
134
-        // after the modal is displayed.
135
-        $('body').css('overflow', 'hidden');
136
-    },
137
-    onOpen: function () {
138
-    },
139
-    onClose: function () {
140
-        // before the modal is hidden.
141
-        $('body').css('overflow', 'auto');
142
-    },
143
-    onDestroy: function () {
144
-    },
145
-    onAction: function () {
146
-    }
147
-};

+ 73
- 0
assets/js/jquery-confirm-defaults.js View File

@@ -0,0 +1,73 @@
1
+jconfirm.defaults = {
2
+    title: 'Title',
3
+    titleClass: '',
4
+    type: 'red',
5
+    typeAnimated: true,
6
+    draggable: false,
7
+    dragWindowGap: 15,
8
+    dragWindowBorder: true,
9
+    animateFromElement: false,
10
+    smoothContent: true,
11
+    content: 'content',
12
+    escapeKey: 'ok',
13
+    buttons: {},
14
+    defaultButtons: {
15
+        ok: {
16
+            keys: ['enter'],
17
+            text: 'OK',
18
+            action: function () {
19
+            }
20
+        },
21
+        close: {
22
+            action: function () {
23
+            }
24
+        },
25
+    },
26
+    contentLoaded: function (data, status, xhr) {
27
+    },
28
+    icon: '',
29
+    lazyOpen: false,
30
+    bgOpacity: null,
31
+    theme: 'material',
32
+    animation: 'scale',
33
+    closeAnimation: 'scale',
34
+    animationSpeed: 300,
35
+    animationBounce: 1.3,
36
+    rtl: false,
37
+    container: 'body',
38
+    containerFluid: false,
39
+    backgroundDismiss: false,
40
+    backgroundDismissAnimation: 'shake',
41
+    autoClose: false,
42
+    closeIcon: null,
43
+    closeIconClass: false,
44
+    watchInterval: 100,
45
+    columnClass: 'xlarge',
46
+    boxWidth: '50%',
47
+    scrollToPreviousElement: true,
48
+    scrollToPreviousElementAnimate: true,
49
+    useBootstrap: true,
50
+    offsetTop: 40,
51
+    offsetBottom: 40,
52
+    bootstrapClasses: {
53
+        container: 'container',
54
+        containerFluid: 'container-fluid',
55
+        row: 'row',
56
+    },
57
+    onContentReady: function () {
58
+    },
59
+    onOpenBefore: function () {
60
+        // after the modal is displayed.
61
+        $('body').css('overflow', 'hidden');
62
+    },
63
+    onOpen: function () {
64
+    },
65
+    onClose: function () {
66
+        // before the modal is hidden.
67
+        $('body').css('overflow', 'auto');
68
+    },
69
+    onDestroy: function () {
70
+    },
71
+    onAction: function () {
72
+    }
73
+};

+ 10
- 0
assets/js/jquery-confirm.min.js
File diff suppressed because it is too large
View File


+ 167
- 0
assets/js/listManager.js View File

@@ -0,0 +1,167 @@
1
+
2
+class ListManager {
3
+
4
+    currentTypes = [];
5
+    displayedTypes = [];
6
+    editableTypes = [];
7
+
8
+    constructor(listContainer, initialData, editableTypes) {
9
+        this.listContainer = listContainer;
10
+        this.currentTypes = initialData;
11
+        this.editableTypes = editableTypes;
12
+        this.generateList();
13
+    }
14
+
15
+    generateList() {
16
+        for (let i = 0; i < this.currentTypes.length; i++) {
17
+            this.createNewListEntry(this.currentTypes[i]);
18
+        }
19
+    }
20
+
21
+    createNewListEntry(item) {
22
+        let listItem = this.getListItem(item);
23
+        this.displayedTypes.push($(listItem));
24
+        const index = this.displayedTypes.length-1;
25
+        let JQueryItem = this.displayedTypes[index];
26
+        this.listContainer.append(JQueryItem);
27
+        JQueryItem.on('click', () => {
28
+            this.showEditPopup(index);
29
+        });
30
+    }
31
+
32
+    deleteListEntry(id) {
33
+        $('#listItem_' + id).remove();
34
+    }
35
+
36
+    getListItem(item) {
37
+        let listItem = "<li id='listItem_" + item["id"] + "'><div>";
38
+        for (let i = 0; i < this.editableTypes.length; i++) {
39
+            listItem += "<span class='list-" + this.editableTypes[i]["name"] + "'>";
40
+            if (this.editableTypes[i]["type"] === "icon")
41
+                listItem += "<i class='mdi mdi-" + item["icon"] + "' style='margin-right: 5px'></i></span>";
42
+            else
43
+                listItem += item["name"] + '</span>';
44
+        }
45
+        listItem += "</div></li>";
46
+        return listItem;
47
+    }
48
+
49
+    getFormData(defaultValues) {
50
+        let formData = '<form action="" class="categoryForm"><div class="form-group">';
51
+        for (let i = 0; i < this.editableTypes.length; i++) {
52
+            let inputId = this.editableTypes[i]['name'] + 'Input';
53
+            let value = defaultValues[this.editableTypes[i]['name']];
54
+            formData += '<label for="' + inputId + '">' + this.editableTypes[i]['description'] + ' :</label>' +
55
+                '<input id="' + inputId + '" type="text" placeholder="Entrez une valeur" class="form-control" value="' + value + '" required />';
56
+        }
57
+        formData += "</div></form>";
58
+        return formData;
59
+    }
60
+
61
+    getFormValues(form) {
62
+        let values = [];
63
+        for (let i = 0; i < this.editableTypes.length; i++) {
64
+            values.push(form.find('#' + this.editableTypes[i]['name'] + 'Input').val())
65
+        }
66
+        return values;
67
+    }
68
+
69
+    isFormValid(values) {
70
+        let isValid = true;
71
+        for (let i = 0; i < values.length; i++) {
72
+            if (values[i] === '') {
73
+                isValid = false;
74
+                break;
75
+            }
76
+        }
77
+        return isValid;
78
+    }
79
+
80
+    insertFormDataIntoObject(values, object) {
81
+        for (let i = 0; i < values.length; i++) {
82
+            object[this.editableTypes[i]['name']] = values[i];
83
+        }
84
+        return object;
85
+    }
86
+
87
+    updateListItem(values, index) {
88
+        for (let i = 0; i < values.length; i++) {
89
+            if (this.editableTypes[i]['type'] === 'icon')
90
+                this.displayedTypes[index].find(".mdi")[0].className = "mdi mdi-" + values[i];
91
+            else
92
+                this.displayedTypes[index].find(".list-" + this.editableTypes[i]['name']).text(values[i]);
93
+        }
94
+    }
95
+
96
+    showEditPopup(index) {
97
+        let defaultValues = {
98
+            name: "",
99
+            icon: ""
100
+        };
101
+        let title = "Créer une nouvelle entrée";
102
+        if (index !== -1) {
103
+            defaultValues = this.currentTypes[index];
104
+            title = "Modifier l'entrée";
105
+        }
106
+        let formData = this.getFormData(defaultValues);
107
+        let thisInstance = this;
108
+        $.confirm({
109
+            title: title,
110
+            content: formData,
111
+            buttons: {
112
+                formSubmit: {
113
+                    text: 'Sauvegarder',
114
+                    btnClass: 'btn-blue',
115
+                    action: async function () {
116
+                        let values = thisInstance.getFormValues(this.$content);
117
+                        if (!thisInstance.isFormValid(values)) {
118
+                            $.alert('Merci de rentrer toutes les valeurs');
119
+                            return false;
120
+                        }
121
+                        let itemToSave =  {};
122
+                        if (index !== -1) {
123
+                            itemToSave = thisInstance.currentTypes[index];
124
+                        }
125
+
126
+                        itemToSave = thisInstance.insertFormDataIntoObject(values, itemToSave);
127
+
128
+                        if (index !== -1) {
129
+                            thisInstance.currentTypes[index] = itemToSave;
130
+                            thisInstance.updateListItem(values, index);
131
+                        }
132
+                        let id = await SaveManager.saveCategory(itemToSave, index === -1);
133
+                        if (id >= 0 && index === -1) {
134
+                            itemToSave["id"] = id;
135
+                            thisInstance.currentTypes[thisInstance.displayedTypes.length] = itemToSave;
136
+                            thisInstance.createNewListEntry(itemToSave);
137
+                        }
138
+                    }
139
+                },
140
+                deleteButton: {
141
+                    text: 'Supprimer',
142
+                    btnClass: 'btn-red',
143
+                    isHidden: index === -1,
144
+                    action: function () {
145
+                        let id = thisInstance.currentTypes[index]['id'];
146
+                        SaveManager.deleteCategory(id);
147
+                        thisInstance.deleteListEntry(id);
148
+                    }
149
+                },
150
+                cancelButton: {
151
+                    text: 'Annuler',
152
+                },
153
+            },
154
+            onContentReady: function () {
155
+                // bind to events
156
+                let jc = this;
157
+                this.$content.find('form').on('submit', function (e) {
158
+                    // if the user submits the form by pressing enter in the field.
159
+                    e.preventDefault();
160
+                    jc.$$formSubmit.trigger('click'); // reference the button and click it
161
+                });
162
+            }
163
+        });
164
+    }
165
+
166
+
167
+}

+ 18
- 54
assets/js/saveManager.js View File

@@ -1,76 +1,40 @@
1 1
 
2 2
 class SaveManager {
3 3
 
4
-    static saveData(types, dataset) {
5
-        let finalDataset = {
6
-            v1: SaveManager.generateV1JSON(types, dataset),
7
-            v2: SaveManager.generateV2JSON(types, dataset)
4
+    static deleteCategory(id) {
5
+        let data = {
6
+            function: "remove_category",
7
+            data: id,
8 8
         };
9
-        console.log(finalDataset);
9
+        console.log(data);
10 10
         $.ajax({
11 11
             type: "POST",
12
-            url: "write_json.php",
13
-            data: JSON.stringify(finalDataset),
12
+            url: "save_manager.php",
13
+            data: JSON.stringify(data),
14 14
             dataType: "json",
15 15
             contentType: "application/json; charset=utf-8",
16 16
             complete: function (data) {
17
-                alert(data.responseText);
17
+                $.alert(data.responseText);
18 18
                 console.log(data);
19 19
             },
20 20
         });
21 21
     }
22 22
 
23
-    static generateV1JSON(savedTypes, savedDataset) {
24
-        let types = [];
25
-        // Replace type objects by names
26
-        for (let i = 0; i < savedTypes.length; i++) {
27
-            types.push(savedTypes[i].name);
28
-        }
29
-        let dataset = JSON.parse(JSON.stringify(savedDataset)); // Deep copy of object
30
-        for (let i = 0; i < dataset.length; i++) {
31
-            // Replace type ids by names
32
-            for (let k = 0; k < dataset[i].type.length; k++) {
33
-                dataset[i].type[k] = SaveManager.getTypeOfId(savedTypes, dataset[i].type[k]).name;
34
-            }
35
-            // remove the description field
36
-            delete dataset[i].description
37
-        }
38
-        return {
39
-            types: types,
40
-            articles: dataset
41
-        }
42
-    }
43
-
44
-    static generateV2JSON(savedTypes, savedDataset) {
45
-        return {
46
-            types: savedTypes,
47
-            articles: savedDataset
48
-        }
49
-    }
50
-
51
-    static getTypeOfId(types, id) {
52
-        let item = {};
53
-        for (let i = 0; i < types.length; i++) {
54
-            if (types[i].id === id) {
55
-                item = types[i];
56
-                break;
57
-            }
58
-        }
59
-        return item;
60
-    }
23
+    static async saveCategory(category, isNew) {
24
+        let data = {
25
+            function: isNew ? "create_category" : "update_category",
26
+            data: category,
27
+        };
61 28
 
62
-    static convertToV2() {
63
-        $.ajax({
29
+        let response = await $.ajax({
64 30
             type: "POST",
65
-            url: "convert_json.php",
31
+            url: "save_manager.php",
32
+            data: JSON.stringify(data),
66 33
             dataType: "json",
67 34
             contentType: "application/json; charset=utf-8",
68
-            complete: function (data) {
69
-                alert(data.responseText);
70
-                console.log(data);
71
-                window.location.reload();
72
-            },
73 35
         });
36
+        console.log(response);
37
+        return response['data'];
74 38
     }
75 39
 }
76 40
 

+ 2
- 0
assets/js/sortable.min.js
File diff suppressed because it is too large
View File


+ 83
- 0
classes/dao.php View File

@@ -0,0 +1,83 @@
1
+<?php
2
+
3
+
4
+class Dao
5
+{
6
+    private $conn;
7
+
8
+    public function __construct()
9
+    {
10
+        $username = 'proximo';
11
+        $password = $this->read_password();
12
+        $dsn = 'mysql:dbname=proximo;host=127.0.0.1';
13
+        try {
14
+            $this->conn = new PDO($dsn, $username, $password, [PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8']);
15
+        } catch (PDOException $e) {
16
+            echo "error";
17
+            echo $e;
18
+        }
19
+    }
20
+
21
+    private function read_password()
22
+    {
23
+        $real_path = __DIR__ . DIRECTORY_SEPARATOR . ".htpassdb";
24
+        $file = fopen($real_path, "r") or die("Unable to open DB password file!");
25
+        $password = fgets($file);
26
+        fclose($file);
27
+        return trim($password);
28
+    }
29
+
30
+    public function get_articles()
31
+    {
32
+        $sql = 'SELECT * FROM articles';
33
+        $cursor = $this->conn->prepare($sql);
34
+        $cursor->execute();
35
+        return $cursor->fetchAll(PDO::FETCH_ASSOC);
36
+    }
37
+
38
+    public function get_article_categories($article_id)
39
+    {
40
+        $sql = 'SELECT category_id FROM article_categories WHERE article_id=?';
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"]);
47
+        }
48
+        return $final;
49
+    }
50
+
51
+    public function get_categories()
52
+    {
53
+        $sql = 'SELECT * FROM categories';
54
+        $cursor = $this->conn->prepare($sql);
55
+        $cursor->execute();
56
+        return $cursor->fetchAll(PDO::FETCH_ASSOC);
57
+    }
58
+
59
+    public function create_category($category) {
60
+        $sql = 'INSERT INTO categories (name, icon) VALUES (?, ?)';
61
+        $cursor = $this->conn->prepare($sql);
62
+        $data = [$category["name"], $category["icon"]];
63
+        $cursor->execute($data);
64
+        return $this->conn->lastInsertId();
65
+    }
66
+
67
+    public function update_category($category)
68
+    {
69
+        $sql = 'UPDATE categories SET name=?, icon=? WHERE id=?';
70
+        $cursor = $this->conn->prepare($sql);
71
+        $data = [$category["name"], $category["icon"], $category["id"]];
72
+        $cursor->execute($data);
73
+        return $category["id"];
74
+    }
75
+
76
+    public function remove_category($id)
77
+    {
78
+        $sql = 'DELETE FROM categories WHERE id=?';
79
+        $cursor = $this->conn->prepare($sql);
80
+        $data = [$id];
81
+        return $cursor->execute($data);
82
+    }
83
+}

+ 4
- 2
includes/template.php View File

@@ -28,8 +28,8 @@ if (!isset($hasHeader))
28 28
     <link type="text/css" rel="stylesheet" href="<?= $relativePath ?>assets/css/hamburger.css"
29 29
           media="screen,projection"/>
30 30
     <link type="text/css" rel="stylesheet" href="<?= $relativePath ?>assets/css/sidenav.css" media="screen,projection"/>
31
-    <link type="text/css" rel="stylesheet" href="<?= $relativePath ?>assets/css/bootstrapOverwrite.css"
32
-          media="screen,projection"/>
31
+    <link type="text/css" rel="stylesheet" href="<?= $relativePath ?>assets/css/bootstrapOverwrite.css" media="screen,projection"/>
32
+    <link type="text/css" rel="stylesheet" href="<?= $relativePath ?>assets/css/jquery-confirm.min.css" media="screen,projection"/>
33 33
     <link rel="icon" type="image/png" href="<?= $relativePath ?>assets/images/favicon.png">
34 34
     <!--Let browser know website is optimized for mobile-->
35 35
     <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
@@ -71,6 +71,8 @@ if (!isset($hasHeader))
71 71
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.2/jquery-confirm.min.js"></script>
72 72
 <script type="text/javascript" src="<?= $relativePath ?>assets/js/init.js"></script>
73 73
 <script type="text/javascript" src="<?= $relativePath ?>assets/js/sidenav.js"></script>
74
+<script type="text/javascript" src="<?= $relativePath ?>assets/js/jquery-confirm.min.js"></script>
75
+<script src="<?= $relativePath ?>assets/js/sortable.min.js"></script>
74 76
 <?= $pageScripts ?>
75 77
 
76 78
 </body>

Loading…
Cancel
Save