summaryrefslogtreecommitdiff
path: root/public/assets/js/admin/lessons.js
blob: 1a088757a6543426c95e88f6a1b72f151982ea2d (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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
// Globals
// -----------------------------------------------------------------------------
var categories = [];
var privileges = [ { id: 0, label: 'Δημόσιο' } ];
var lessons = [];
var table;



// Supplamentary functions
// -----------------------------------------------------------------------------

// array.indexOf polyfill
// --- -- -- - - -
if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}


// function for sorting an array by 'label' attribute
// --- -- -- - - -
function compare_label (a,b) {
    if ( a.label < b.label ) { return -1; }
    if ( a.label > b.label ) { return 1; }
    return 0;
}


// function for sorting an array by 'breadcrumb' attribute
// --- -- -- - - -
function compare_breadcrumb (a,b) {
    if ( a.breadcrumb < b.breadcrumb ) { return -1; }
    if ( a.breadcrumb > b.breadcrumb ) { return 1; }
    return 0;
}

// return category record by category-id
// --- -- -- - - -
function lesson_record(id) {
    var record = 0;
    lessons.forEach(el => { if (el.id == id) record = el; });
   
    return record;
}

/** course(id) 
 * label of course with
 * @param id (int)
 */
function course_(id) {
    let reply = false;
    categories.forEach( cat => { if (cat.id == id) reply = cat.label; })
    return reply;
}

/** privilege(id) 
 * label of privilege with
 * @param id (int)
 */
function privilege_(id) {
    let reply = false;
    privileges.forEach( pri => { if (pri.id == id) reply = pri.label; });
    return reply;
}


//// return children of parent
//// --- -- -- - - -
//function childs_of_parents(list) {
//    // if 'list' is integer then make it an one-item list
//    parents = (Number.isInteger(list)) ? [ list ] : list;
//
//    var childs = [];
//
//    if (parents.length == 0) { return []; }
//
//    parents.forEach( pid => {
//        categories.forEach( el => { if (el.parent == pid) childs.push(el.id)});
//    });
//
//    var grandchilds = childs_of_parents(childs);
//
//    return childs.concat(grandchilds);
//}


// create actions html (edit and delete buttons)
// --- -- -- - - -
function create_actions_html(el) {

    var pub, del, edit;

    // preapre [show|hide]-file as reference
    if (el.status == 1) {
        pub = '<span class="btn btn-sm"><i class="fas fa-eye"></i></span>';

    } else {
        pub = '<span class="btn btn-sm"><i class="fas fa-eye-slash"></i></span>';
    }

    del = "";

    fast_edit = [
        '<button type="button" class="btn btn-sm btn-light"',
            'data-bs-toggle="modal" data-bs-target="#manageLessons"',
            'data-id="'+ el.id +'">',
            '<i class="fa-solid fa-bolt"></i>',
        '</button>'
    ].join('\n');

    edit = [
        '<a type="button" class="btn btn-sm btn-warning "',
            'href="/admin/edit_lesson/'+ el.id +'">',
            '<i class="fas fa-pencil-alt"></i>',
        '</a>'
    ].join('\n');

    return pub +' '+ fast_edit +' '+ edit +' '+ del;
}



$(document).ready(function() {

    // When document is ready
    // -------------------------------------------------------------------------


    // inti category (select2)
    // ...
    $("#privilege_id").select2({
        placeholder: 'Επίπεδο Πρόσβασης',
        dropdownParent: $('#manageLessons'),
        width: '100%'
    });
    
    /** init selec2 element (used to specify parent-category)
     * --- -- -- - - -
     */
    $("#course_id").select2({
        placeholder: 'Κεφάλαιο',
        dropdownParent: $('#manageLessons'),
        width: '100%',
    });

    
    /** init_table
     * --- -- -- - - -
     * get categories
     * constuct categories array
     * render dataTable 
     */
    function init_table() {

        // get all categories from server (ajax)
        $.getJSON( "/admin/api/lessons")
        .done(function( json ) {
            // then ...

            // reset categories
            lessons.length = 0;

            // construct (new) categories data
            Object.keys(json).forEach( key => {
                el = json[key];
                lessons.push({
                    id: parseInt(el.id),
                    title: el.title,
                    course_id: el.course_id,
                    course: course_(el.course_id),
                    privilege_id: el.privilege_id,
                    privilege: privilege_(el.privilege_id),
                    actions: create_actions_html(el)
                });
            });

            // sort by breadcrumb
            // categories.sort( compare_breadcrumb );

            // destroy previous datatable table instances
            $('#dt-lessons').dataTable().fnClearTable();
            $('#dt-lessons').dataTable().fnDestroy();

            // (re-)create categories datatable
            table = $('#dt-lessons').DataTable({
                language: { url: '/libs/DataTables/localization/Greek.json' },           
                data: lessons,
                ordering: false,
                columns: [
                    { data: 'id' },
                    { data: 'title' },
                    { data: 'course' },
                    { data: 'privilege' },
                    { data: 'actions' }
                ]
            });

        })
        .fail(function( jqxhr, textStatus, error ) {
            console.log( "Request Failed (" + error +")" );
        });

    }


    $.when(     // when loaded posts and categories

        $.getJSON( "/admin/api/categories" ),

        $.getJSON( "/admin/api/privileges" )

    ).done( function( categories_response, privileges_response ) {

        // construct categories data
        // ---
        Object.keys(categories_response[0]).forEach( key => {
            cat = categories_response[0][key];
            categories.push({
                id: cat.rec.id,
                label: cat.breadcrumb.replaceAll('\t', ' / ')
            });
        });
        categories.sort( compare_label );  // sort categories by breadcrumb

        // construct provileges data
        // ---
        Object.keys(privileges_response[0]).forEach( key => {
            priv = privileges_response[0][key];
            privileges.push({
                id: priv.id,
                label: priv.label
            });
        });
        privileges.sort( compare_label );  // sort categories by breadcrumb

        set_parent_options( $('#course_id'), categories );
        set_parent_options( $('#privilege_id'), privileges );

        init_table();   // init table on first run
    });


    /** set_parent_options()
     * 
     * -> create options for parents <select>
     * -> choose selected parent
     * 
     * NOTE:
     * the targer <select> should be a select2 control
     * 
     * @param parents (array): array of parents
     * @param selected (int): selected parent
     */
    function set_parent_options(selector, list, selected_value = false) {

        list.forEach( li => {   // attach options into <select> control
            selector.append(`<option value="${li.id}">${li.label}</option>`);
        });

        if (selected_value !== false) {     // mark selected option(s)
            selector.val(selected_value).trigger('change');
        }
        else { selector.val(null).trigger('change'); }
    }



    /** When modal show-up
     * -------------------------------------------------------------------------
     * ... prepare the manage-category form 
     * ... update select2 with possible parents
     */
    $('#manageLesson').on('show.bs.modal', event => {
        var button = $(event.relatedTarget);        // Button that triggered the modal
        var id = parseInt( button.data('id') );     // category_id from data-id
        // var modal = $(this);    // modal object     
        
        //// update modal literature
        //// ---
        //$('#manageCategory .modal-title').html(             // modal title
        //    (id) ? 'Ενημέρωση Κατηγορίας' : 'Δημιουργία Κατηγορίας'
        //);
        //$('#manageCategory form input[name=id]').val( id );     // category id (hidden)
        //$('#manageCategory form input[name=label]').val(    // category label
        //    (id) ? category_record(id).label : ""
        //);
        //prepare_parents_element(id);        // prepare <select> for parents
    })


    /** set_parent_options()
     * 
     * -> create options for parents <select>
     * -> choose selected parent
     * 
     * NOTE:
     * the targer <select> should be a select2 control
     * 
     * @param parents (array): array of parents
     * @param selected (int): selected parent
     */
        function set_parent_options(selector, list, selected_value = false) {

            list.forEach( li => {   // attach options into <select> control
                selector.append(`<option value="${li.id}">${li.label}</option>`);
            });
    
            if (selected_value !== false) {     // mark selected option(s)
                selector.val(selected_value).trigger('change');
            }
            else { selector.val(null).trigger('change'); }
        }
    




    // When form is submited
    // -------------------------------------------------------------------------

    $('#manageCategory form').submit( event => {
        event.preventDefault();

        // prepare data to POST
        var data = {
            id: parseInt($('#manageCategory form input[name=id]').val()),
            label: $('#manageCategory form input[name=label]').val(),
            parent_id: parseInt($('#parent_id').select2('data')[0].id)
        };

        // select action url (add or update)
        var request = '/admin/api/categories/' + ((data.id == 0)  ? 'add' : 'update');

        // send POST request
        $.post(request, data)
        .done(function( data ) {

            $('#manageCategory').modal('hide');     // when done, close modal

            init_table();       // reload table of categories
        });       

    });

});