<commit_before>/**************************************************************************************
 * Copyright (c) 2013-2015, Finnish Social Science Data Archive/University of Tampere *
 *                                                                                *
 * All rights reserved.                                                               *
 *                                                                                *
 * Redistribution and use in source and binary forms, with or without modification,   *
 * are permitted provided that the following conditions are met:                      *
 * 1. Redistributions of source code must retain the above copyright notice, this     *
 *    list of conditions and the following disclaimer.                                *
 * 2. Redistributions in binary form must reproduce the above copyright notice,       *
 *    this list of conditions and the following disclaimer in the documentation       *
 *    and/or other materials provided with the distribution.                          *
 * 3. Neither the name of the copyright holder nor the names of its contributors      *
 *    may be used to endorse or promote products derived from this software           *
 *    without specific prior written permission.                                      *
 *                                                                                *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND    *
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED      *
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE             *
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR   *
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES     *
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;       *
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON     *
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT            *
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS      *
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                       *
 **************************************************************************************/

define(function (require) {
    'use strict';

    var resultParser = require('./resultParser');

    return {
        APPROVE: function (options) {
            this
                .click(require('./formAction')('approve')(options, function (response) {

                    if(resultParser(response.result).getResult() === 'NO_CHANGES') {
                        require('./assignUrl')('view', {no: ''});
                    } else {
                        $.extend(options.data, response.data);
                        options.$events.trigger('refresh.metka');
                    }
                }, [
                    'OPERATION_SUCCESSFUL',
                    'RESTRICTION_VALIDATION_FAILURE',
                    'NO_CHANGES'
                ], "approve"));
        },
        CANCEL: function (options) {
            options.title = MetkaJS.L10N.get('general.buttons.cancel');
        },
        CLAIM: function (options) {
            this
                .click(function () {
                    $(".modal-footer").find("button").attr('disabled', 'disabled');
                    require('./server')('/revision/ajax/claim', {
                        data: JSON.stringify(options.data.key),
                        success: function (response) {
                            $(".modal-footer").find("button").removeAttr('disabled');
                            $.extend(options.data, response.data);
                            options.$events.trigger('refresh.metka');
                            location.reload();
                        },
                        error: function() {
                            $(".modal-footer").find("button").removeAttr('disabled');
                        }
                    });
                });
        },
        BEGIN_EDIT: function (options) {
            this
                .click(function () {
                    $(".modal-footer").find("button").attr('disabled', 'disabled');
                    require('./server')('/revision/ajax/beginEdit', {
                        data: JSON.stringify(options.data.key),
                        success: function (response) {
                            $(".modal-footer").find("button").removeAttr('disabled');
                            if(resultParser(response.result).getResult() === 'REVISION_UPDATE_SUCCESSFUL') {
                                $.extend(options.data, response.data);
                                options.$events.trigger('refresh.metka');
                                location.reload();
                            } else {
                                require('./resultViewer')(response.result, 'beginEdit', function() {
                                    require('./assignUrl')('view');
                                });
                            }
                        },
                        error: function() {
                            $(".modal-footer").find("button").removeAttr('disabled');
                        }
                    });
                });
        },
        COMPARE: function (options) {
            options.title = MetkaJS.L10N.get('general.revision.compare');
            this.prop('disabled', true);
        },
        CUSTOM: function(options) {

        },
        DISMISS: function (options) {
            options.title = MetkaJS.L10N.get('general.buttons.close');
        },
        EDIT: function (options) {
            this.click(require('./formAction')('edit')(options, function (response) {
                $(".modal-footer").find("button").removeAttr('disabled');
                $.extend(options.data, response.data);
                options.$events.trigger('refresh.metka');
                history.replaceState(undefined, '', require('./url')('view'));
                location.reload()
            }, [
                'REVISION_FOUND',
                'REVISION_CREATED'
            ], "edit"));
        },
        HISTORY: function (options) {
            $.extend(true, options, {
                preventDismiss: true
            });
            this
                .click(function () {
                    var o = options;
                    function checkRadioGroups() {
                        var beginVal = parseInt($('input[name="beginGrp"]:checked').val());
                        var endVal = parseInt($('input[name="endGrp"]:checked').val())
                        if (beginVal) {
                            $('input[name="endGrp"]').each(function () {
                                if (parseInt($(this).val()) <= beginVal) {
                                    $(this).attr('disabled', true);
                                } else {
                                    $(this).attr('disabled', false);
                                }
                            });
                        }
                        if (endVal) {
                            $('input[name="beginGrp"]').each(function () {
                                if (parseInt($(this).val()) >= endVal) {
                                    $(this).attr('disabled', true);
                                } else {
                                    $(this).attr('disabled', false);
                                }
                            });
                        }
                        if (typeof beginVal !== 'undefined' && typeof endVal !== 'undefined') {
                            if (beginVal >= endVal) {
                                $('#compareRevisions').prop('disabled', true);
                            } else {
                                $('#compareRevisions').prop('disabled', false);
                            }
                        }
                    }

                    var $table = $('
')
                        .append($('
')
                            .append($('
')
                                .append((function () {
                                    var arr = [
                                        'general.revision',
                                        'general.revision.publishDate',
                                        'general.revision.compare.begin',
                                        'general.revision.compare.end'
                                    ];

                                    return arr.map(function (entry) {
                                        return $('')
                                            .text(MetkaJS.L10N.get(entry));
                                    });
                                })())));

                    require('./modal')($.extend(true, require('./optionsBase')(), {
                        title: MetkaJS.L10N.get('general.revision.revisions'),
                        body: $table,
                        large: true,
                        buttons: [{
                            type: 'COMPARE',
                            //preventDismiss: true,
                            create: function () {
                                this
                                    .attr('id', 'compareRevisions')
                                    .click(function () {
                                        var $table = $('
')
                                            .append($('
')
                                                .append($('
')
                                                    .append([
                                                        MetkaJS.L10N.get("dialog.history.path"),
                                                        ///MetkaJS.L10N.get("dialog.history.language"),
                                                        MetkaJS.L10N.get("dialog.history.original"),
                                                        MetkaJS.L10N.get("dialog.history.current")
                                                    ].map(function (entry) {
                                                            return $('')
                                                                .text(entry);
                                                        }))));
                                        require('./modal')($.extend(true, require('./optionsBase')(), {
                                            title: MetkaJS.L10N.get('general.revision.revisions'),
                                            body: $table,
                                            large: true,
                                            buttons: [{
                                                type: 'DISMISS'
                                            }]
                                        }));

                                        require('./server')('/revision/revisionCompare', {
                                            data: JSON.stringify({
                                                id: o.data.key.id,
                                                begin: $('input[name="beginGrp"]:checked').val(),
                                                end: $('input[name="endGrp"]:checked').val(),
                                                type: o.data.configuration.type
                                            }),
                                            success: function (response) {
                                                if (resultParser(response.result).getResult() === 'OPERATION_SUCCESSFUL') {
                                                    $table
                                                        .append($('
')
                                                            .append(response.rows.map(function (row) {
                                                                var parts = row.key.split('[');
                                                                return $('
')
                                                                    .append([
                                                                        // TODO: get field title (titles are all over GUI conf, which is a problem)
                                                                        //parts[0],
                                                                        // TODO: get language from
                                                                        //parts[1].substr(0, parts[1].length - 1),
                                                                        row.key,
                                                                        row.original,
                                                                        row.current
                                                                    ].map(function (entry) {
                                                                            return $('')
                                                                                .text(entry.supplant({
                                                                                rowNumber: MetkaJS.L10N.get("dialog.history.compare.rowId"),
                                                                                newRow: MetkaJS.L10N.get("dialog.history.compare.newRow"),
                                                                                removedRow: MetkaJS.L10N.get("dialog.history.compare.removedRow"),
                                                                                }));
                                                                        }));
                                                            })));
                                                }
                                            }
                                        });
                                    });

                            }
                        }, {
                            type: 'DISMISS'
                        }]
                    }));
                    require('./server')('/revision/revisionHistory', {
                        data: JSON.stringify({
                            id: options.data.key.id
                        }),
                        success: function (response) {
                            $table
                                .append($('
')
                                    .append(response.rows.map(function (row) {
                                        return $('
')
                                            .append((function () {
                                                var publishDate = new Date(row.publishDate);
                                                if (publishDate.getFullYear() === 1970)
                                                    publishDate = null;
                                                var items = [
                                                    $('', {
                                                        href: require('./url')('view', row),
                                                        text: row.no
                                                    }),
                                                    publishDate !== null ? publishDate.getDate() + "." + parseInt(publishDate.getMonth()+1) + "." + publishDate.getFullYear() : "",
                                                    $('<input>', {
                                                        type: 'radio',
                                                        name: 'beginGrp',
                                                        value: row.no,
                                                        change: checkRadioGroups
                                                    }),
                                                    $('<input>', {
                                                        type: 'radio',
                                                        name: 'endGrp',
                                                        value: row.no,
                                                        change: checkRadioGroups
                                                    })
                                                ];

                                                return items.map(function (entry) {
                                                    return $('')
                                                        .append(entry);
                                                });
                                            })());
                                    })));

                            checkRadioGroups();
                            $(".modal-footer").find("button").removeAttr('disabled');
                        },
                        error: function() {
                            $(".modal-footer").find("button").removeAttr('disabled');
                        }
                    });
                });
        },
        NO: function (options) {
            options.title = MetkaJS.L10N.get('general.buttons.no');
        },
        REMOVE: function (options) {
            this.click(require('./remove')(options));
        },
        RELEASE: function (options) {
            this
                .click(function () {
                    $(".modal-footer").find("button").attr('disabled', 'disabled');
                    var $this = $(this);
                    require('./server')('/revision/ajax/release', {
                        data: JSON.stringify(options.data.key),
                        success: function (response) {
                            $(".modal-footer").find("button").removeAttr('disabled');
                            $.extend(options.data, response.data);
                            options.$events.trigger('refresh.metka');
                            location.reload();
                        },
                        error: function (){
                            $(".modal-footer").find("button").removeAttr('disabled');
                        }
                    });
                });
        },
        RESTORE: function (options) {
            this
                .click(function () {
                    $(".modal-footer").find("button").attr('disabled', 'disabled');
                    var $this = $(this);
                    var request = $.extend({
                        data: JSON.stringify(options.data.key),
                        success: function (response) {
                            $(".modal-footer").find("button").removeAttr('disabled');
                            $.extend(options.data, response.data);
                            options.$events.trigger('refresh.metka');
                        },
                        error: function () {
                            $(".modal-footer").find("button").removeAttr('disabled');
                        }
                    }, options.request);
                    require('./server')('/revision/ajax/restore', request);
                });
        },
        REVERTCONFIRM: function (options) {
            options.title = MetkaJS.L10N.get('general.buttons.revert');
        },
        REVERT: function (options){
            this
                .click(function() {
                    var $this = $(this);
                    console.log(options);
                    var $table = $('
')
                        .append($('
')
                            .append($('
')
                                .append((function () {
                                    var arr = [
                                        'general.revision',
                                        'general.revision.publishDate',
                                        ''
                                    ];

                                    return arr.map(function (entry) {
                                        return $('')
                                            .text(MetkaJS.L10N.get(entry));
                                    });
                                }))));
                    require('./modal')($.extend(true, require('./optionsBase')(), {
                        title: MetkaJS.L10N.get('general.revision.revert'),
                        body: $table,
                        //large: false,
                        buttons: [{
                            type: 'REVERTCONFIRM',
                            create: function() {
                                options.title = MetkaJS.L10N.get('general.buttons.revert');
                                this
                                    .attr('id', 'revertRevision')
                                    .click(function() {
                                        $(".modal-footer").find("button").attr('disabled', 'disabled');
                                        var request = {
                                            data: JSON.stringify({
                                                targetNo: parseInt($('input[name="revertRadio"]:checked').val()),
                                                key: options.data.key
                                            }),
                                            success: function(response) {
                                                $(".modal-footer").find("button").removeAttr('disabled');
                                                options.$events.trigger('refresh.metka');
                                                require('./assignUrl')('view', {
                                                    id: response.data.key.id,
                                                    no: response.data.key.no
                                                });
                                            }, error: function() {
                                                $(".modal-footer").find("button").removeAttr('disabled');
                                            }
                                        };
                                        require('./server')('/revision/ajax/revert', request);
                                        // Ajax-kutsu
                                    })
                            }
                        }, {
                            type: 'DISMISS'
                        }]
                    }));
                    require('./server')('/revision/revisionHistory', {
                        data: JSON.stringify({
                            id: options.data.key.id
                        }),
                        success: function(response){
                            $table
                                .append($('
')
                                    .append(response.rows.map(function(row){
                                        return $('
')
                                            .append((function(){
                                                var publishDate = new Date(row.publishDate);
                                                if (publishDate.getFullYear() === 1970)
                                                    publishDate = null;
                                                var items = [
                                                    $('', {
                                                        href: require('./url')('view', row),
                                                        text: row.no
                                                    }),
                                                    publishDate !== null ? publishDate.getDate() + "." + parseInt(publishDate.getMonth()+1) + "."+ publishDate.getFullYear() : "",
                                                    $('<input>', {
                                                        type: 'radio',
                                                        name: 'revertRadio',
                                                        value: row.no
                                                    })
                                                ];
                                                return items.map(function(entry){
                                                    return $('')
                                                        .append(entry)
                                                });
                                            }))
                                    })));
                        }
                    })
                })
        },
        SAVE: function (options) {
            this
                .click(require('./save')(options, function (response) {
                    $(".modal-footer").find("button").removeAttr('disabled');
                    $.extend(options.data, response.data);
                    // Fire an event so that metka doesn't ask for confirmation if moving from page
                    var evt = new CustomEvent('saved');
                    window.dispatchEvent(evt);
                    options.$events.trigger('refresh.metka');
                }));
        },
        YES: function (options) {
            options.title = MetkaJS.L10N.get('general.buttons.yes');
        },
        OK: function(options) {
            options.title = MetkaJS.L10N.get('general.buttons.ok');
        }
    };
});
<commit_msg>Metka ei varoita tallentamattomista muutoksista aineiston hyväksymisen jälkeen sivulta poistuttaessa<commit_after>/**************************************************************************************
 * Copyright (c) 2013-2015, Finnish Social Science Data Archive/University of Tampere *
 *                                                                                *
 * All rights reserved.                                                               *
 *                                                                                *
 * Redistribution and use in source and binary forms, with or without modification,   *
 * are permitted provided that the following conditions are met:                      *
 * 1. Redistributions of source code must retain the above copyright notice, this     *
 *    list of conditions and the following disclaimer.                                *
 * 2. Redistributions in binary form must reproduce the above copyright notice,       *
 *    this list of conditions and the following disclaimer in the documentation       *
 *    and/or other materials provided with the distribution.                          *
 * 3. Neither the name of the copyright holder nor the names of its contributors      *
 *    may be used to endorse or promote products derived from this software           *
 *    without specific prior written permission.                                      *
 *                                                                                *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND    *
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED      *
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE             *
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR   *
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES     *
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;       *
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON     *
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT            *
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS      *
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                       *
 **************************************************************************************/

define(function (require) {
    'use strict';

    var resultParser = require('./resultParser');

    return {
        APPROVE: function (options) {
            this
                .click(require('./formAction')('approve')(options, function (response) {

                    if(resultParser(response.result).getResult() === 'NO_CHANGES') {
                        require('./assignUrl')('view', {no: ''});
                    } else {
                        $.extend(options.data, response.data);
                        // Fire an event so that metka doesn't ask for confirmation if moving from page
                        var evt = new CustomEvent('saved');
                        window.dispatchEvent(evt);
                        options.$events.trigger('refresh.metka');
                    }
                }, [
                    'OPERATION_SUCCESSFUL',
                    'RESTRICTION_VALIDATION_FAILURE',
                    'NO_CHANGES'
                ], "approve"));
        },
        CANCEL: function (options) {
            options.title = MetkaJS.L10N.get('general.buttons.cancel');
        },
        CLAIM: function (options) {
            this
                .click(function () {
                    $(".modal-footer").find("button").attr('disabled', 'disabled');
                    require('./server')('/revision/ajax/claim', {
                        data: JSON.stringify(options.data.key),
                        success: function (response) {
                            $(".modal-footer").find("button").removeAttr('disabled');
                            $.extend(options.data, response.data);
                            options.$events.trigger('refresh.metka');
                            location.reload();
                        },
                        error: function() {
                            $(".modal-footer").find("button").removeAttr('disabled');
                        }
                    });
                });
        },
        BEGIN_EDIT: function (options) {
            this
                .click(function () {
                    $(".modal-footer").find("button").attr('disabled', 'disabled');
                    require('./server')('/revision/ajax/beginEdit', {
                        data: JSON.stringify(options.data.key),
                        success: function (response) {
                            $(".modal-footer").find("button").removeAttr('disabled');
                            if(resultParser(response.result).getResult() === 'REVISION_UPDATE_SUCCESSFUL') {
                                $.extend(options.data, response.data);
                                options.$events.trigger('refresh.metka');
                                location.reload();
                            } else {
                                require('./resultViewer')(response.result, 'beginEdit', function() {
                                    require('./assignUrl')('view');
                                });
                            }
                        },
                        error: function() {
                            $(".modal-footer").find("button").removeAttr('disabled');
                        }
                    });
                });
        },
        COMPARE: function (options) {
            options.title = MetkaJS.L10N.get('general.revision.compare');
            this.prop('disabled', true);
        },
        CUSTOM: function(options) {

        },
        DISMISS: function (options) {
            options.title = MetkaJS.L10N.get('general.buttons.close');
        },
        EDIT: function (options) {
            this.click(require('./formAction')('edit')(options, function (response) {
                $(".modal-footer").find("button").removeAttr('disabled');
                $.extend(options.data, response.data);
                options.$events.trigger('refresh.metka');
                history.replaceState(undefined, '', require('./url')('view'));
                location.reload()
            }, [
                'REVISION_FOUND',
                'REVISION_CREATED'
            ], "edit"));
        },
        HISTORY: function (options) {
            $.extend(true, options, {
                preventDismiss: true
            });
            this
                .click(function () {
                    var o = options;
                    function checkRadioGroups() {
                        var beginVal = parseInt($('input[name="beginGrp"]:checked').val());
                        var endVal = parseInt($('input[name="endGrp"]:checked').val())
                        if (beginVal) {
                            $('input[name="endGrp"]').each(function () {
                                if (parseInt($(this).val()) <= beginVal) {
                                    $(this).attr('disabled', true);
                                } else {
                                    $(this).attr('disabled', false);
                                }
                            });
                        }
                        if (endVal) {
                            $('input[name="beginGrp"]').each(function () {
                                if (parseInt($(this).val()) >= endVal) {
                                    $(this).attr('disabled', true);
                                } else {
                                    $(this).attr('disabled', false);
                                }
                            });
                        }
                        if (typeof beginVal !== 'undefined' && typeof endVal !== 'undefined') {
                            if (beginVal >= endVal) {
                                $('#compareRevisions').prop('disabled', true);
                            } else {
                                $('#compareRevisions').prop('disabled', false);
                            }
                        }
                    }

                    var $table = $('
')
                        .append($('
')
                            .append($('
')
                                .append((function () {
                                    var arr = [
                                        'general.revision',
                                        'general.revision.publishDate',
                                        'general.revision.compare.begin',
                                        'general.revision.compare.end'
                                    ];

                                    return arr.map(function (entry) {
                                        return $('')
                                            .text(MetkaJS.L10N.get(entry));
                                    });
                                })())));

                    require('./modal')($.extend(true, require('./optionsBase')(), {
                        title: MetkaJS.L10N.get('general.revision.revisions'),
                        body: $table,
                        large: true,
                        buttons: [{
                            type: 'COMPARE',
                            //preventDismiss: true,
                            create: function () {
                                this
                                    .attr('id', 'compareRevisions')
                                    .click(function () {
                                        var $table = $('
')
                                            .append($('
')
                                                .append($('
')
                                                    .append([
                                                        MetkaJS.L10N.get("dialog.history.path"),
                                                        ///MetkaJS.L10N.get("dialog.history.language"),
                                                        MetkaJS.L10N.get("dialog.history.original"),
                                                        MetkaJS.L10N.get("dialog.history.current")
                                                    ].map(function (entry) {
                                                            return $('')
                                                                .text(entry);
                                                        }))));
                                        require('./modal')($.extend(true, require('./optionsBase')(), {
                                            title: MetkaJS.L10N.get('general.revision.revisions'),
                                            body: $table,
                                            large: true,
                                            buttons: [{
                                                type: 'DISMISS'
                                            }]
                                        }));

                                        require('./server')('/revision/revisionCompare', {
                                            data: JSON.stringify({
                                                id: o.data.key.id,
                                                begin: $('input[name="beginGrp"]:checked').val(),
                                                end: $('input[name="endGrp"]:checked').val(),
                                                type: o.data.configuration.type
                                            }),
                                            success: function (response) {
                                                if (resultParser(response.result).getResult() === 'OPERATION_SUCCESSFUL') {
                                                    $table
                                                        .append($('
')
                                                            .append(response.rows.map(function (row) {
                                                                var parts = row.key.split('[');
                                                                return $('
')
                                                                    .append([
                                                                        // TODO: get field title (titles are all over GUI conf, which is a problem)
                                                                        //parts[0],
                                                                        // TODO: get language from
                                                                        //parts[1].substr(0, parts[1].length - 1),
                                                                        row.key,
                                                                        row.original,
                                                                        row.current
                                                                    ].map(function (entry) {
                                                                            return $('')
                                                                                .text(entry.supplant({
                                                                                rowNumber: MetkaJS.L10N.get("dialog.history.compare.rowId"),
                                                                                newRow: MetkaJS.L10N.get("dialog.history.compare.newRow"),
                                                                                removedRow: MetkaJS.L10N.get("dialog.history.compare.removedRow"),
                                                                                }));
                                                                        }));
                                                            })));
                                                }
                                            }
                                        });
                                    });

                            }
                        }, {
                            type: 'DISMISS'
                        }]
                    }));
                    require('./server')('/revision/revisionHistory', {
                        data: JSON.stringify({
                            id: options.data.key.id
                        }),
                        success: function (response) {
                            $table
                                .append($('
')
                                    .append(response.rows.map(function (row) {
                                        return $('
')
                                            .append((function () {
                                                var publishDate = new Date(row.publishDate);
                                                if (publishDate.getFullYear() === 1970)
                                                    publishDate = null;
                                                var items = [
                                                    $('', {
                                                        href: require('./url')('view', row),
                                                        text: row.no
                                                    }),
                                                    publishDate !== null ? publishDate.getDate() + "." + parseInt(publishDate.getMonth()+1) + "." + publishDate.getFullYear() : "",
                                                    $('<input>', {
                                                        type: 'radio',
                                                        name: 'beginGrp',
                                                        value: row.no,
                                                        change: checkRadioGroups
                                                    }),
                                                    $('<input>', {
                                                        type: 'radio',
                                                        name: 'endGrp',
                                                        value: row.no,
                                                        change: checkRadioGroups
                                                    })
                                                ];

                                                return items.map(function (entry) {
                                                    return $('')
                                                        .append(entry);
                                                });
                                            })());
                                    })));

                            checkRadioGroups();
                            $(".modal-footer").find("button").removeAttr('disabled');
                        },
                        error: function() {
                            $(".modal-footer").find("button").removeAttr('disabled');
                        }
                    });
                });
        },
        NO: function (options) {
            options.title = MetkaJS.L10N.get('general.buttons.no');
        },
        REMOVE: function (options) {
            this.click(require('./remove')(options));
        },
        RELEASE: function (options) {
            this
                .click(function () {
                    $(".modal-footer").find("button").attr('disabled', 'disabled');
                    var $this = $(this);
                    require('./server')('/revision/ajax/release', {
                        data: JSON.stringify(options.data.key),
                        success: function (response) {
                            $(".modal-footer").find("button").removeAttr('disabled');
                            $.extend(options.data, response.data);
                            options.$events.trigger('refresh.metka');
                            location.reload();
                        },
                        error: function (){
                            $(".modal-footer").find("button").removeAttr('disabled');
                        }
                    });
                });
        },
        RESTORE: function (options) {
            this
                .click(function () {
                    $(".modal-footer").find("button").attr('disabled', 'disabled');
                    var $this = $(this);
                    var request = $.extend({
                        data: JSON.stringify(options.data.key),
                        success: function (response) {
                            $(".modal-footer").find("button").removeAttr('disabled');
                            $.extend(options.data, response.data);
                            options.$events.trigger('refresh.metka');
                        },
                        error: function () {
                            $(".modal-footer").find("button").removeAttr('disabled');
                        }
                    }, options.request);
                    require('./server')('/revision/ajax/restore', request);
                });
        },
        REVERTCONFIRM: function (options) {
            options.title = MetkaJS.L10N.get('general.buttons.revert');
        },
        REVERT: function (options){
            this
                .click(function() {
                    var $this = $(this);
                    console.log(options);
                    var $table = $('
')
                        .append($('
')
                            .append($('
')
                                .append((function () {
                                    var arr = [
                                        'general.revision',
                                        'general.revision.publishDate',
                                        ''
                                    ];

                                    return arr.map(function (entry) {
                                        return $('')
                                            .text(MetkaJS.L10N.get(entry));
                                    });
                                }))));
                    require('./modal')($.extend(true, require('./optionsBase')(), {
                        title: MetkaJS.L10N.get('general.revision.revert'),
                        body: $table,
                        //large: false,
                        buttons: [{
                            type: 'REVERTCONFIRM',
                            create: function() {
                                options.title = MetkaJS.L10N.get('general.buttons.revert');
                                this
                                    .attr('id', 'revertRevision')
                                    .click(function() {
                                        $(".modal-footer").find("button").attr('disabled', 'disabled');
                                        var request = {
                                            data: JSON.stringify({
                                                targetNo: parseInt($('input[name="revertRadio"]:checked').val()),
                                                key: options.data.key
                                            }),
                                            success: function(response) {
                                                $(".modal-footer").find("button").removeAttr('disabled');
                                                options.$events.trigger('refresh.metka');
                                                require('./assignUrl')('view', {
                                                    id: response.data.key.id,
                                                    no: response.data.key.no
                                                });
                                            }, error: function() {
                                                $(".modal-footer").find("button").removeAttr('disabled');
                                            }
                                        };
                                        require('./server')('/revision/ajax/revert', request);
                                        // Ajax-kutsu
                                    })
                            }
                        }, {
                            type: 'DISMISS'
                        }]
                    }));
                    require('./server')('/revision/revisionHistory', {
                        data: JSON.stringify({
                            id: options.data.key.id
                        }),
                        success: function(response){
                            $table
                                .append($('
')
                                    .append(response.rows.map(function(row){
                                        return $('
')
                                            .append((function(){
                                                var publishDate = new Date(row.publishDate);
                                                if (publishDate.getFullYear() === 1970)
                                                    publishDate = null;
                                                var items = [
                                                    $('', {
                                                        href: require('./url')('view', row),
                                                        text: row.no
                                                    }),
                                                    publishDate !== null ? publishDate.getDate() + "." + parseInt(publishDate.getMonth()+1) + "."+ publishDate.getFullYear() : "",
                                                    $('<input>', {
                                                        type: 'radio',
                                                        name: 'revertRadio',
                                                        value: row.no
                                                    })
                                                ];
                                                return items.map(function(entry){
                                                    return $('')
                                                        .append(entry)
                                                });
                                            }))
                                    })));
                        }
                    })
                })
        },
        SAVE: function (options) {
            this
                .click(require('./save')(options, function (response) {
                    $(".modal-footer").find("button").removeAttr('disabled');
                    $.extend(options.data, response.data);
                    // Fire an event so that metka doesn't ask for confirmation if moving from page
                    var evt = new CustomEvent('saved');
                    window.dispatchEvent(evt);
                    options.$events.trigger('refresh.metka');
                }));
        },
        YES: function (options) {
            options.title = MetkaJS.L10N.get('general.buttons.yes');
        },
        OK: function(options) {
            options.title = MetkaJS.L10N.get('general.buttons.ok');
        }
    };
});
<|endoftext|>


<commit_before>
jQuery(document).ready(function($) {

    var cookie = 'mezzanine-admin-tree';
    var at = ('; ' + document.cookie).indexOf('; ' + cookie + '=');
    var ids = '';

    if (at > -1) {
        ids = document.cookie.substr(at + cookie.length + 1).split(';')[0];
    }

    var toggleID = function(opened, id) {
        // Add or remove the page ID from the cookie IDs string.
        var index = $.inArray(id, ids.split(','));
        if (opened) {
            if (index == -1) {
                if (ids) {ids += ',';}
                ids += id;
            }
        } else if (index > -1) {
            ids = ids.split(',');
            ids.splice(index, 1);
            ids = ids.join(',');
        }
        document.cookie = cookie + '=' + ids + '; path=/';
    };

    function showButtonWithChildren() {
        $('ol:has(li.page)').parent().find('.tree-toggle').css({visibility: 'visible'});
        $('ol:not(:has(li.page))').parent().find('.tree-toggle').css({visibility: 'hidden'});
    }

    showButtonWithChildren();

    $('#tree .tree-toggle').click(function() {
        // Show/hide the branch and toggle the icon.
        var pageLink = $(this);
        pageLink.parents('li:first').find('ol:first').toggle();
        pageLink.find('.icon').toggle();
        // Add or remove the page ID from the cookie.
        var opened = pageLink.find('.tree-close:visible').length == 1;
        var id = pageLink.attr('id').split('-')[1];
        toggleID(opened, id);
        return false;
    });

    // Show previously opened branches.
    $('#tree ol').find('ol').hide();
    if (ids) {
        $('#page-' + ids.split(',').join(', #page-')).each(function(){
            var pageLink = $(this);
            pageLink.parents('li:first').find('ol:first').toggle();
            pageLink.find('.tree-close').show();
            pageLink.find('.tree-open').hide();
        });
    }

    // The dropdown list for adding a new page contains URLs for each
    // model - redirect when selected.
    $('.addlist a').click(function(e) {
        e.preventDefault();
        // Ensure the branch is saved as open when adding to it so that
        // the new branch will be visible directly after saving.
        var link = $(this);
        var id = link.parents('.addlist:first').attr('id');
        if (id) {
            toggleID(true, id.split('-')[1]);
        }
        var addUrl = link.attr('href');
        if (addUrl) {
            location.href = addUrl;
        }
        return true;
    });

    // AJAX callback that's triggered when dragging a page to re-order
    // it has ended.
    var updateOrdering = function(event, ui) {
        var parent = ui.item.parents('li:first');

        var args = {
            id: ui.item[0].id,
            parent_id: parent.length ? parent[0].id : "null",
            siblings: ui.item.parent().children().map(function(index, elem) {
                return elem.id;
            }).get(),
            csrfmiddlewaretoken: window.__csrf_token
        };

        $.post(window.__page_ordering_url, args, function(data) {
            if (String(data).substr(0, 2) !== "ok") {
                location.reload();
            } else {
                $(".messagelist").remove();
            }
        });

        showButtonWithChildren();
    };

    //var updateOrdering = function ($item, container, _super, event) {
    //    /**/
    //    $item.removeClass(container.group.options.draggedClass).removeAttr("style");
    //    $("body").removeClass(container.group.options.bodyClass);
    //
    //    /* Send ajax */
    //    var parent = $item.parents('li:first');
    //
    //    var args = {
    //        id: $item[0].id,
    //        parent_id: parent.length ? parent[0].id : "null",
    //        siblings: $item.parent().children().map(function(index, elem) {
    //            return elem.id;
    //        }).get(),
    //        csrfmiddlewaretoken: window.__csrf_token
    //    };
    //
    //    $.post(window.__page_ordering_url, args, function(data) {
    //        if (String(data).substr(0, 2) !== "ok") {
    //            location.reload();
    //        } else {
    //            $(".messagelist").remove();
    //        }
    //    });
    //
    //    /**/
    //    showButtonWithChildren();
    //};

    // Make the pages sortable via drag and drop.
    // The `connectWith` option needs to be set separately to get
    // around a performance bug with `sortable`.
    var $tree = $('#tree > ol').nestedSortable({
        handle: '.ordering',
        opacity: 0.5,
        stop: updateOrdering,
        forcePlaceholderSize: true,
        placeholder: 'placeholder',
        revert: 150,
        helper: 'clone',
        items: 'li.page',
        tabSize: 25,
        tolerance: 'pointer',
        toleranceElement: '> div',
        isTree: true,
        expandOnHover: 1000,
        startCollapsed: true
    });

});
<commit_msg>Fix adding children for leaf<commit_after>
jQuery(document).ready(function($) {

    var cookie = 'mezzanine-admin-tree';
    var at = ('; ' + document.cookie).indexOf('; ' + cookie + '=');
    var ids = '';

    if (at > -1) {
        ids = document.cookie.substr(at + cookie.length + 1).split(';')[0];
    }

    var toggleID = function(opened, id) {
        // Add or remove the page ID from the cookie IDs string.
        var index = $.inArray(id, ids.split(','));
        if (opened) {
            if (index == -1) {
                if (ids) {ids += ',';}
                ids += id;
            }
        } else if (index > -1) {
            ids = ids.split(',');
            ids.splice(index, 1);
            ids = ids.join(',');
        }
        document.cookie = cookie + '=' + ids + '; path=/';
    };

    function showButtonWithChildren() {
        $('ol:has(li.page)').parent().find('.tree-toggle').css({visibility: 'visible'});
        $('ol:not(:has(li.page))').parent().find('.tree-toggle').css({visibility: 'hidden'});
    }

    showButtonWithChildren();

    $('#tree .tree-toggle').click(function() {
        // Show/hide the branch and toggle the icon.
        var pageLink = $(this);
        pageLink.parents('li:first').find('ol:first').toggle();
        pageLink.find('.icon').toggle();
        // Add or remove the page ID from the cookie.
        var opened = pageLink.find('.tree-close:visible').length == 1;
        var id = pageLink.attr('id').split('-')[1];
        toggleID(opened, id);
        return false;
    });

    // Show previously opened branches.
    $('#tree ol').find('ol').hide();
    if (ids) {
        $('#page-' + ids.split(',').join(', #page-')).each(function(){
            var pageLink = $(this);
            pageLink.parents('li:first').find('ol:first').toggle();
            pageLink.find('.tree-close').show();
            pageLink.find('.tree-open').hide();
        });
    }

    $('#tree ol').find('ol:not(:has(li.page))').show();

    // The dropdown list for adding a new page contains URLs for each
    // model - redirect when selected.
    $('.addlist a').click(function(e) {
        e.preventDefault();
        // Ensure the branch is saved as open when adding to it so that
        // the new branch will be visible directly after saving.
        var link = $(this);
        var id = link.parents('.addlist:first').attr('id');
        if (id) {
            toggleID(true, id.split('-')[1]);
        }
        var addUrl = link.attr('href');
        if (addUrl) {
            location.href = addUrl;
        }
        return true;
    });

    // AJAX callback that's triggered when dragging a page to re-order
    // it has ended.
    var updateOrdering = function(event, ui) {
        var parent = ui.item.parents('li:first');

        var args = {
            id: ui.item[0].id,
            parent_id: parent.length ? parent[0].id : "null",
            siblings: ui.item.parent().children().map(function(index, elem) {
                return elem.id;
            }).get(),
            csrfmiddlewaretoken: window.__csrf_token
        };

        $.post(window.__page_ordering_url, args, function(data) {
            if (String(data).substr(0, 2) !== "ok") {
                location.reload();
            } else {
                $(".messagelist").remove();
            }
        });

        showButtonWithChildren();
    };

    // Make the pages sortable via drag and drop.
    // The `connectWith` option needs to be set separately to get
    // around a performance bug with `sortable`.
    var $tree = $('#tree > ol').nestedSortable({
        handle: '.ordering',
        opacity: 0.5,
        stop: updateOrdering,
        forcePlaceholderSize: true,
        placeholder: 'placeholder',
        revert: 150,
        helper: 'clone',
        items: 'li.page',
        tabSize: 25,
        tolerance: 'pointer',
        toleranceElement: '> div',
        isTree: true,
        expandOnHover: 1000,
        startCollapsed: true
    });

});
<|endoftext|>


<commit_before>const mongoose = require('mongoose');
// eslint-disable-next-line no-unused-vars
const { info, error } = require('../src/logger');

const { connect, close } = require('../src/utils/database');

const RoleModel = mongoose.model('role', new mongoose.Schema({
	name: { type: String, required: true },
	permissions: [{ type: String }],
}, {
	timestamps: true,
}));

// How to use more than one schema per collection on mongodb
// https://stackoverflow.com/questions/14453864/use-more-than-one-schema-per-collection-on-mongodb

module.exports = {
	up: async function up() {
		await connect();
		// ////////////////////////////////////////////////////
		// Make changes to the database here.
		// Hint: Access models via this('modelName'), not an imported model to have
		// access to the correct database connection. Otherwise Mongoose calls never return.
		// User
		await RoleModel.findOneAndUpdate(
			{
				name: 'user',
			}, {
				$pull: { permissions: { $in: ['USER_VIEW', 'USER_EDIT'] } },
			},
		).lean().exec();
		await RoleModel.findOneAndUpdate(
			{
				name: 'user',
			}, {
				$addToSet: { permissions: { $each: ['STUDENT_EDIT'] } },
			},
		).lean().exec();

		// Teacher
		await RoleModel.findOneAndUpdate(
			{
				name: 'teacher',
			}, {
				$pull: { permissions: { $in: ['HOMEWORK_CREATE', 'HOMEWORK_EDIT', 'USER_CREATE'] } },
			},
		).lean().exec();
		await RoleModel.findOneAndUpdate(
			{
				name: 'teacher',
			}, {
				$addToSet: { permissions: { $each: ['STUDENT_LIST', 'TEACHER_LIST'] } },
			},
		).lean().exec();

		// Administrator
		await RoleModel.findOneAndUpdate(
			{
				name: 'administrator',
			}, {
				$pull: { permissions: { $in: ['USER_CREATE'] } },
			},
		).lean().exec();
		await RoleModel.findOneAndUpdate(
			{
				name: 'administrator',
			}, {
				$addToSet: {
					permissions: {
						$each: [
							'STUDENT_LIST',
							'TEACHER_CREATE', 'TEACHER_EDIT', 'TEACHER_LIST',
						],
					},
				},
			},
		).lean().exec();

		// Superhero
		await RoleModel.findOneAndUpdate(
			{
				name: 'superhero',
			}, {
				$addToSet: {
					permissions: {
						$each: [
							'STUDENT_CREATE', 'STUDENT_DELETE', 'STUDENT_LIST',
							'TEACHER_CREATE', 'TEACHER_DELETE', 'TEACHER_EDIT', 'TEACHER_LIST'],
					},
				},
			},
		).lean().exec();
		// ////////////////////////////////////////////////////
		await close();
	},

	down: async function down() {
		await connect();
		// ////////////////////////////////////////////////////
		// Implement the necessary steps to roll back the migration here.
		// User
		await RoleModel.findOneAndUpdate(
			{
				name: 'user',
			}, {
				$addToSet: { permissions: { $each: ['USER_VIEW', 'USER_EDIT'] } },
			},
		).lean().exec();
		await RoleModel.findOneAndUpdate(
			{
				name: 'user',
			}, {
				$pull: { permissions: { $in: ['STUDENT_EDIT'] } },
			},
		).lean().exec();

		// Teacher
		await RoleModel.findOneAndUpdate(
			{
				name: 'teacher',
			}, {
				$addToSet: { permissions: { $each: ['HOMEWORK_CREATE', 'HOMEWORK_EDIT', 'USER_CREATE'] } },
			},
		).lean().exec();
		await RoleModel.findOneAndUpdate(
			{
				name: 'teacher',
			}, {
				$pull: { permissions: { $in: ['STUDENT_LIST', 'TEACHER_LIST'] } },
			},
		).lean().exec();

		// Administrator
		await RoleModel.findOneAndUpdate(
			{
				name: 'administrator',
			}, {
				$addToSet: { permissions: { $each: ['USER_CREATE'] } },
			},
		).lean().exec();
		await RoleModel.findOneAndUpdate(
			{
				name: 'administrator',
			}, {
				$pull: {
					permissions: {
						$in: [
							'STUDENT_LIST',
							'TEACHER_CREATE', 'TEACHER_EDIT', 'TEACHER_LIST',
						],
					},
				},
			},
		).lean().exec();

		// Superhero
		await RoleModel.findOneAndUpdate(
			{
				name: 'superhero',
			}, {
				$pull: {
					permissions: {
						$in: [
							'STUDENT_CREATE', 'STUDENT_DELETE', 'STUDENT_LIST',
							'TEACHER_CREATE', 'TEACHER_DELETE', 'TEACHER_EDIT', 'TEACHER_LIST',
						],
					},
				},
			},
		).lean().exec();
		// ////////////////////////////////////////////////////
		await close();
	},
};
<commit_msg>class and course permissions migration<commit_after>const mongoose = require('mongoose');
// eslint-disable-next-line no-unused-vars
const { info, error } = require('../src/logger');

const { connect, close } = require('../src/utils/database');

const RoleModel = mongoose.model('role', new mongoose.Schema({
	name: { type: String, required: true },
	permissions: [{ type: String }],
}, {
	timestamps: true,
}));

// How to use more than one schema per collection on mongodb
// https://stackoverflow.com/questions/14453864/use-more-than-one-schema-per-collection-on-mongodb

module.exports = {
	up: async function up() {
		await connect();
		// ////////////////////////////////////////////////////
		// Make changes to the database here.
		// Hint: Access models via this('modelName'), not an imported model to have
		// access to the correct database connection. Otherwise Mongoose calls never return.
		// User
		await RoleModel.findOneAndUpdate(
			{
				name: 'user',
			}, {
				$pull: { permissions: { $in: ['USER_VIEW', 'USER_EDIT', 'USERGROUP_VIEW'] } },
			},
		).lean().exec();
		await RoleModel.findOneAndUpdate(
			{
				name: 'user',
			}, {
				$addToSet: { permissions: { $each: ['STUDENT_EDIT', 'CLASS_VIEW', 'COURSE_VIEW'] } },
			},
		).lean().exec();

		// Teacher
		await RoleModel.findOneAndUpdate(
			{
				name: 'teacher',
			}, {
				$pull: {
					permissions: {
						$in: ['HOMEWORK_CREATE', 'HOMEWORK_EDIT', 'USER_CREATE', 'USERGROUP_CREATE', 'USERGROUP_EDIT'],
					},
				},
			},
		).lean().exec();
		await RoleModel.findOneAndUpdate(
			{
				name: 'teacher',
			}, {
				$addToSet: {
					permissions: {
						$each: [
							'STUDENT_LIST',
							'TEACHER_LIST',
							'CLASS_CREATE',
							'CLASS_EDIT',
							'COURSE_CREATE',
							'COURSE_REMOVE',
						],
					},
				},
			},
		).lean().exec();

		// Administrator
		await RoleModel.findOneAndUpdate(
			{
				name: 'administrator',
			}, {
				$pull: {
					permissions: {
						$in: ['USER_CREATE', 'USERGROUP_CREATE',
							'USERGROUP_EDIT', 'USERGROUP_FULL_ADMIN'],
					},
				},
			},
		).lean().exec();
		await RoleModel.findOneAndUpdate(
			{
				name: 'administrator',
			}, {
				$addToSet: {
					permissions: {
						$each: [
							'STUDENT_LIST', 'TEACHER_CREATE', 'TEACHER_EDIT',
							'TEACHER_LIST', 'CLASS_CREATE', 'CLASS_EDIT',
							'CLASS_FULL_ADMIN', 'COURSE_CREATE', 'COURSE_EDIT',
							'COURSE_REMOVE',
						],
					},
				},
			},
		).lean().exec();

		// Superhero
		await RoleModel.findOneAndUpdate(
			{
				name: 'superhero',
			}, {
				$addToSet: {
					permissions: {
						$each: [
							'STUDENT_CREATE', 'STUDENT_DELETE', 'STUDENT_LIST',
							'TEACHER_CREATE', 'TEACHER_DELETE', 'TEACHER_EDIT', 'TEACHER_LIST'],
					},
				},
			},
		).lean().exec();
		// ////////////////////////////////////////////////////
		await close();

		// demo
		await RoleModel.findOneAndUpdate(
			{
				name: 'demo',
			}, {
				$pull: { permissions: { $in: ['USERGROUP_VIEW'] } },
			},
		).lean().exec();
		await RoleModel.findOneAndUpdate(
			{
				name: 'demo',
			}, {
				$addToSet: { permissions: { $each: ['CLASS_VIEW', 'COURSE_VIEW'] } },
			},
		).lean().exec();
	},

	down: async function down() {
		await connect();
		// ////////////////////////////////////////////////////
		// Implement the necessary steps to roll back the migration here.
		// User
		await RoleModel.findOneAndUpdate(
			{
				name: 'user',
			}, {
				$addToSet: {
					permissions: {
						$each: ['HOMEWORK_CREATE', 'HOMEWORK_EDIT',
							'USER_CREATE', 'USERGROUP_CREATE', 'USERGROUP_EDIT'],
					},
				},
			},
		).lean().exec();
		await RoleModel.findOneAndUpdate(
			{
				name: 'user',
			}, {
				$pull: { permissions: { $in: ['STUDENT_EDIT', 'CLASS_VIEW', 'COURSE_VIEW'] } },
			},
		).lean().exec();

		// Teacher
		await RoleModel.findOneAndUpdate(
			{
				name: 'teacher',
			}, {
				$addToSet: { permissions: { $each: ['HOMEWORK_CREATE', 'HOMEWORK_EDIT', 'USER_CREATE'] } },
			},
		).lean().exec();
		await RoleModel.findOneAndUpdate(
			{
				name: 'teacher',
			}, {
				$pull: {
					permissions: {
						$in: [
							'STUDENT_LIST',
							'TEACHER_LIST',
							'CLASS_CREATE',
							'CLASS_EDIT',
							'COURSE_CREATE',
							'COURSE_REMOVE',
						],
					},
				},
			},
		).lean().exec();

		// Administrator
		await RoleModel.findOneAndUpdate(
			{
				name: 'administrator',
			}, {
				$addToSet: {
					permissions: {
						$each: ['USER_CREATE', 'USERGROUP_CREATE',
							'USERGROUP_EDIT', 'USERGROUP_FULL_ADMIN'],
					},
				},
			},
		).lean().exec();
		await RoleModel.findOneAndUpdate(
			{
				name: 'administrator',
			}, {
				$pull: {
					permissions: {
						$in: [
							'STUDENT_LIST', 'TEACHER_CREATE', 'TEACHER_EDIT',
							'TEACHER_LIST', 'CLASS_CREATE', 'CLASS_EDIT',
							'CLASS_FULL_ADMIN', 'COURSE_CREATE', 'COURSE_EDIT',
							'COURSE_REMOVE',
						],
					},
				},
			},
		).lean().exec();

		// Superhero
		await RoleModel.findOneAndUpdate(
			{
				name: 'superhero',
			}, {
				$pull: {
					permissions: {
						$in: [
							'STUDENT_CREATE', 'STUDENT_DELETE', 'STUDENT_LIST',
							'TEACHER_CREATE', 'TEACHER_DELETE', 'TEACHER_EDIT', 'TEACHER_LIST',
						],
					},
				},
			},
		).lean().exec();

		// demo
		await RoleModel.findOneAndUpdate(
			{
				name: 'demo',
			}, {
				$pull: { permissions: { $in: ['CLASS_VIEW', 'COURSE_VIEW'] } },
			},
		).lean().exec();
		await RoleModel.findOneAndUpdate(
			{
				name: 'demo',
			}, {
				$addToSet: { permissions: { $each: ['USERGROUP_VIEW'] } },
			},
		).lean().exec();
		// ////////////////////////////////////////////////////
		await close();
	},
};
<|endoftext|>