Skip to content
Snippets Groups Projects
export.js 12 KiB
Newer Older
$(document).ready(() => {

    const pathToSfeduAPIAdapter = $('#sync_api_url').html().trim();

    let loadedDisciplines = {};
    let allGroups = {};

    let $groups = $('#json_groups');

    let groupsRaw = $.parseJSON($groups.html() || '{}');
    Object.values(groupsRaw).forEach((value) => {
        value.groups.forEach((group) => {
            let newGroup = {
                groupNum: group.GroupNum,
                groupID: group.ID,
                gradeID: value.grade_id,
                gradeNum: value.grade_num,
                formID: group.FormID,
                formName: group.FormName
            };
            allGroups[group.ID] = newGroup;
        });
    });

    $groups.remove();

    function customMenu(node) {
        var items = {
            export: {
                label: "Выгрузить",
                action: function (obj) {
                    const selected = $('#groupTree').jstree().get_selected();

                    function processDiscipline(selectedDiscipline, callback) {

                        let logDisciplineError = function (groupID, disciplineID, errorID, url) {
                            $.post(g_URLdir + url, {groupID: groupID, disciplineID: disciplineID, error: errorID}).success((disciplines) => {
                            }).fail(jqXHR => {
                                const status = parseInt(jqXHR.status);
                                let message = errorText;
                                try {
                                    if (status === 400)
                                        message = JSON.parse(jqXHR.responseText).message;
                                } catch (error) {
                                }
                                if (status !== 0)
                                    Popup.error(message);
                            });
                        try {
                            if (selectedDiscipline.startsWith("discipline_")) {
                                const singleNumRegexp = /\w_(\d+)/;

                                const parseClass = function (str) {

                                    singleNumRegexp.lastIndex = 0;
                                    let foundMatch = singleNumRegexp.exec(str);
                                    return foundMatch ? parseInt(foundMatch[1]) : 0;

                                };

                                const disciplineID = parseClass(selectedDiscipline);
                                const disciplineInfo = loadedDisciplines[disciplineID];
                                const parent = $('#groupTree').jstree().get_parent(selectedDiscipline);
                                const groupID = parseClass(parent);
                                const groupInfo = allGroups[groupID];
                                //console.log(groupInfo);
                                //console.log(disciplineInfo);
                                const planExtId = "000" + disciplineInfo.PlanExternalID;
                                const disciplineExtId = disciplineInfo.DisciplineExternalID;

                                $.get(pathToSfeduAPIAdapter + '/forms', {
                                    year: settings.year.toString() + "-" + (settings.year + 1).toString().substr(2, 2),
                                    semester: settings.semesterNum,
                                    plan: planExtId,
                                    disciplineID: disciplineID,
                                    discipline: disciplineExtId,
                                    groupnum: groupInfo.groupNum,
                                    groupid: groupInfo.groupID,
                                    faculty: settings.facultyID
                                }).success((response) => {
                                    console.log(response);
                                    let errorMessage = '';
                                    if (response[1].Errors === '') {
                                        Popup.success(`ведомость по дисциплине ${disciplineInfo.SubjectName}${disciplineID} для ${groupInfo.groupNum}  группы ${groupInfo.gradeNum} курса выгружена`);
                                        let node = $('#groupTree').jstree(true).get_node(selectedDiscipline);
                                        //node.type = "discipline_broken";
                                        $('#groupTree').jstree(true).set_type(node, "discipline_exported");
                                        $('#groupTree').jstree(true).redraw(true);
                                        Popup.error(`не выгружена ведомость для "${disciplineInfo.SubjectName}" №${disciplineID} для ${groupInfo.groupNum}  группы ${groupInfo.gradeNum} курса`);
                                        let node = $('#groupTree').jstree(true).get_node(selectedDiscipline);
                                        //node.type = "discipline_broken";
                                        $('#groupTree').jstree(true).set_type(node, "discipline_broken");
                                        $('#groupTree').jstree(true).redraw(true);
                                        if (typeof response[1].Errors.Error[1] !== 'undefined') {
                                            errorMessage = response[1].Errors.Error[1]['faultstring'];
                                            if (typeof errorMessage === 'undefined') {
                                                errorMessage = response[1].Errors.Error[1]['Description']
                                            }
                                        }
                                        if (errorMessage !== '' && typeof errorMessage !== 'undefined') {
                                        logDisciplineError(groupInfo.groupID, disciplineInfo.ID, errorCode, 'handler/discipline/setDisciplineErrorForGroup');
                                        callback();
                                    }
                                }).fail(jqXHR => {
                                    const status = parseInt(jqXHR.status);
                                    try {
                                        if (status === 400)
                                            message = JSON.parse(jqXHR.responseText).message;
                                    } catch (error) {
                                        logDisciplineError(groupInfo.groupID, disciplineInfo.ID, 5, 'handler/discipline/setDisciplineErrorForGroup');
                                        logDisciplineError(groupInfo.groupID, disciplineInfo.ID, 6, 'handler/discipline/setDisciplineErrorForGroup');

                    let requests = selected.reduce((promiseChain, item) => {
                        return promiseChain.then(() => new Promise((resolve) => {
                            processDiscipline(item, resolve)
                        }));
                    }, Promise.resolve());

                    requests.then(() => Popup.success('Выгружены все выделенные дисциплины'))
                }
            },
        };

        if (!node.id.startsWith("discipline_")) {
            // Delete the "delete" menu item
            delete items.export;
        }

        return items;
    }
    $(function () {
            $('#groupTree').jstree(
                {
                    "core": {
                        // so that create works
                        "check_callback": true,
                        error: function (err) {
                            console.log(err);
                        }
                    },
                            "icon": "../static/img/icons/delete.png"
                            "icon": "../static/img/icons/ok.png"
                            "icon": "../static/img/icons/tick.png"
                            "icon": "../static/img/icons/up.png"
                    "contextmenu": {"items": customMenu},

    $('#groupTree').on("changed.jstree", function (e, data) {
        const singleNumRegexp = /\w_(\d+)/;

        const parseClass = function (str) {

            singleNumRegexp.lastIndex = 0;
            let foundMatch = singleNumRegexp.exec(str);
            return foundMatch ? parseInt(foundMatch[1]) : 0;

        };

        let getDisciplines = function (groupID, url, onSuccess, onFail, successText, errorText) {
            $.post(g_URLdir + url, {groupID: groupID}).success((disciplines) => {
                onSuccess(JSON.parse(JSON.parse(disciplines).response));
            }).fail(jqXHR => {
                onFail();
                const status = parseInt(jqXHR.status);
                try {
                    if (status === 400)
                        message = JSON.parse(jqXHR.responseText).message;
                } catch (error) {
                }
                if (status !== 0)
                    Popup.error(message);
            });
        };

        if (data.selected[0] && data.selected[0].startsWith("group_")) {
            if (!$('#groupTree').jstree().is_leaf(data.selected)) return;
            let groupID = parseClass(data.selected[0]);

            if (!data.node.data.loading) {
                data.node.data.loading = true;

                getDisciplines(groupID, 'handler/discipline/getDisciplinesForGroup',
                    function (disciplines) {
                        jQuery.each(disciplines, function (i, val) {
                            loadedDisciplines[i] = val;
                            $('#groupTree').jstree().create_node(data.selected, {
                                "id": "discipline_" + val.ID + "_group_" + groupID,
                                // TODO: refactor:
                                "type": val.lastExportDate ? (val.lastExportError ? "discipline_broken" : (val.isOutdated ? "discipline_outdated" : "discipline_exported")) : "discipline_new",
                                "text": val.lastExportDate ? val.SubjectName + "" + val.ID + ", последняя дата: " + val.lastExportDate : val.SubjectName + "" + val.ID ,
                            }, "last");
                        });
                        data.node.data.loading = false;
                        $('#groupTree').jstree().open_node(data.selected);
                    },
                    function () {
                        data.node.data.loading = false;
                    }, "дисциплины загрузились", "ошибка");
            }
        } else if (data.selected[0] && data.selected[0].startsWith("discipline_")) {
        }
    })