samat

mail@pastecode.io avatar
unknown
javascript
a month ago
18 kB
1
Indexable
Never
const _lg = require("single-line-logger")._lg;
const { Variables } = require("camunda-external-task-client-js");
const crud = require("./crud");
const DBC = require("../lib/dbc");

async function sarSaveRespPerson({ task, taskService }) {
    try {
        const vars = task.variables.getAll();

        const company = vars.companyName;
        const bin = vars.companyBIN.toString();
        const respPerson = vars.responsible_person;
        const { location } = vars;
        const isTechTeam = vars.isTechTeam ? vars.isTechTeam : false;
        // eslint-disable-next-line no-prototype-builtins
        const fullCode = vars.hasOwnProperty("fullCode") ? vars.fullCode : null;
        if (fullCode) {
            location.assets_project_id = location.code;
        }
        let compId = 0;
        let teamIds = [];
        let teamId = 0;

        compId = await crud.getCompanyIdByBin(bin);
        _lg(`sarSaveRespPerson: compId: ${compId}`);
        if (!compId) {
            compId = await crud.addCompany({ name: company, bin: bin });
        }
        teamIds = await crud.listTeams({ company_id: compId });
        _lg(`sarSaveRespPerson: teamIds: ${teamIds}`);

        let result = false;
        if (teamIds) {
            // eslint-disable-next-line no-plusplus
            for (let i = 0; i < teamIds.length; i++) {
                result = await crud.isProjectTeam(teamIds[i].id, location.assets_project_id);
                if (result) {
                    teamId = teamIds[i].id;
                    break;
                }
            }
        }
        if (!teamId) {
            teamId = await crud.addTeam({
                name: company,
                company_id: compId,
                resp_emp: JSON.stringify(respPerson),
                last_upd: new Date(),
                is_tech_team: isTechTeam,
            });
            await crud.setProjectTeam(teamId, location.assets_project_id);
        } else if (isTechTeam) {
            await crud.updateTeam(
                {
                    resp_emp: JSON.stringify(respPerson),
                    last_upd: new Date(),
                    is_tech_team: isTechTeam,
                },
                { id: teamId },
            );
        } else {
            await crud.updateTeam(
                {
                    resp_emp: JSON.stringify(respPerson),
                    last_upd: new Date(),
                },
                { id: teamId },
            );
        }
        // const docs = await getTeamDocs(teamId)
        const variables = new Variables().setAllTyped({
            compId: {
                value: compId,
                type: "Integer",
            },
            teamId: {
                value: teamId,
                type: "Integer",
            },
        });
        _lg(`sarSaveRespPerson: vars: ${variables}`);
        await crud.refreshMaterializedView("public.company_project_info");
        await taskService.complete(task, variables).then((taskServiceResult) => {
            _lg(`Result: ${taskServiceResult}`);
        });
    } catch (error) {
        _lg(error);
        await taskService.handleFailure(task, {
            errorMessage: error && error.message ? `${error.message}.` : "See logs for details",
            errorDetails: "See logs for details",
            retries: 0,
            retryTimeout: 1000,
        });
    }
}

async function sarSaveTeamDocs({ task, taskService }) {
    try {
        const typedValues = task.variables.getAll();
        const { teamId } = typedValues;
        const docs = typedValues.documents;
        const isTechTeam = typedValues.isTechTeam ? typedValues.isTechTeam : false;

        if (teamId && docs && !isTechTeam) {
            await crud.updateTeam(
                {
                    docs_checked: JSON.stringify(docs),
                },
                {
                    id: teamId,
                },
            );
        }
        await taskService.complete(task).then((result) => {
            _lg(`Result: ${result}`);
        });
    } catch (error) {
        _lg(error);
        await taskService.handleFailure(task, {
            errorMessage: error && error.message ? `${error.message}.` : "See logs for details",
            errorDetails: "See logs for details",
            retries: 0,
            retryTimeout: 1000,
        });
    }
}

function parseDate(dateStr) {
    let day; let month; let year;

    if (dateStr.includes("-")) {
        // Case for 'YYYY-MM-DD' format
        [year, month, day] = dateStr.split("-");
    } else if (dateStr.includes(".")) {
        // Case for 'DD.MM.YYYY' format
        [day, month, year] = dateStr.split(".");
    } else {
        throw new Error("Invalid date format");
    }

    return {
        day: parseInt(day, 10),
        month: parseInt(month, 10),
        year: parseInt(year, 10)
    };
}

async function setToDb(user, biot) {
    _lg(`setToDb: user iin ${user.iin}`);
    let newCompId = null;
    let newTeamId = null;
    let teamId = null;
    let newEmpId = null;
    let empId = null;
    let existEmp = null;
    _lg(`setToDb: getCompanyIdByBin ${user.company.bin}`);
    const respBin = await crud.getCompanyIdByBin(user.company.bin);
    if (respBin != null) {
        user.company.id = respBin;
    }
    if (!user.company.hasOwnProperty("id")) {
        // если новая компания
        _lg("setToDb: addCompany");
        newCompId = await crud.addCompany({
            name: user.company.name,
            bin: user.company.bin,
        });
        if (newCompId) {
            // тогда и новая команда
            _lg("setToDb: addTeam");
            newTeamId = await crud.addTeam({
                name: user.company.name,
                company_id: newCompId,
            });
            if (newTeamId) {
                await crud.setProjectTeam(newTeamId, user.project.code);
            }
        }
    } else {
        _lg(`setToDb: company has id ${user.company.id}`);
        // Компания уже существует, ищем, есть ли команда на проекте
        const resp = await crud.listTeams({ company_id: user.company.id });
        if (resp) {
            // teamId = resp.data[0].id
            const teamIds = resp;
            // Ищем есть ли уже команда на проекте
            for (let i = 0; i < teamIds.length; i += 1) {
                const curTeamId = teamIds[i].id;
                const response = await crud.listBpProjectTeams({
                    team_id: curTeamId,
                    project_id: user.project.code,
                });
                if (response) {
                    if (response.length > 0) {
                        teamId = response[0].team_id;
                        break;
                    }
                }
            }
            // Создание команды на проект
            if (!teamId) {
                const response = await crud.addTeam({
                    name: user.company.name,
                    company_id: user.company.id,
                });
                if (response) {
                    newTeamId = response;
                    await crud.setProjectTeam(newTeamId, user.project.code);
                }
            }
        }
    }

    let existEmpReqData = {};
    if (user.iin && user.iin.length > 10) {
        existEmpReqData = { iin: user.iin.toString() };
    } else {
        const docTypeField = `docs->>'${user.doc_type}'`;
        existEmpReqData = {};
        existEmpReqData[docTypeField] = user.id_card;
    }
    existEmp = await crud.listEmployees(existEmpReqData);
    if (existEmp) {
        if (existEmp.length > 0) {
            empId = existEmp[0].id;
            if (biot) {
                await crud.updateEmployee(
                    {
                        qual_id: JSON.stringify({
                            biot: biot,
                            created: new Date(),
                            status: "Имеется",
                        }),
                    },
                    {
                        id: empId,
                    },
                );
            }
            await crud.updateEmployee({
                photo: Array.isArray(user.photo) && user.photo.length > 0 ? user.photo[0] : {},
            }, {
                id: empId,
            })
        }
    }
    if (!empId) {
        _lg("setToDb: employee does not exist");
        const doc = {};
        if (!user.iin || user.iin.length < 2) {
            doc[user.doc_type] = user.id_card;
        }

        const { day, month, year } = parseDate(user.birth_date);

        const reqData = {
            f_name: user.f_name,
            l_name: user.l_name,
            m_name: user.m_name,
            docs: doc,
            iin: user.iin.toString(),
            birth_date: new Date(Date.UTC(year, month, day)),
            photo: Array.isArray(user.photo) && user.photo.length > 0 ? user.photo[0] : {},
            company_id: newCompId || user.company.id,
        };

        if (user.phone) {
            reqData.phone = `${user.phone}`;
        }

        const response = await crud.addEmployee(reqData);

        _lg(`setToDb: employee added ${user.iin}`);
        if (response) {
            newEmpId = response;
            await crud.setMemberships({
                new_emp_id: newEmpId,
                new_team_id: newTeamId || teamId,
            });

            _lg(`setToDb: membership set ${user.iin}`);
            await crud.clearCard((+user.personal_card_id).toString(), newEmpId);

            _lg(`setToDb: card cleared ${(+user.personal_card_id).toString()}`);
            const newEmpStatusData = {
                project_id: user.project.code,
                team_id: newTeamId || teamId,
                emp_id: newEmpId,
                status: "done",
                kind_of_work: user.kind_of_work,
                enter_date: new Date(),
                position: user.position.id,
                zone: user.zone && user.zone === "Зеленая зона" ? "Green" : "Red",
            };
            if (+user.personal_card_id) {
                newEmpStatusData.card_identifier = (+user.personal_card_id).toString();
            }
            if (biot) {
                newEmpStatusData.area = user.block ? user.block.name : user.project.name;
                newEmpStatusData.enter_date = user.proceed_date ? user.proceed_date : new Date();
            }
            await crud.addEmpStatus(newEmpStatusData);
        }
    } else {
        _lg(`setToDb: employee exists ${empId}`);
        const editEmpData = {};
        if (user.phone) {
            editEmpData.phone = `${user.phone}`;
        }

        if (user.photo) {
            editEmpData.photo = Array.isArray(user.photo) && user.photo.length > 0 ? user.photo[0] : {};
        }
        await crud.updateEmployee(editEmpData, {
            id: empId,
        });

        _lg(`setToDb: employee updated ${empId}`);
        const response = await crud.listEmpStatuses({ emp_id: empId });
        if (response) {
            if (response.length > 0) {
                const arr = response;
                let editEmpStatusData;
                for (let i = 0; i < arr.length; i++) {
                    editEmpStatusData = null;
                    if (arr[i].project_id === user.project.code) {
                        editEmpStatusData = {
                            status: "done",
                            kind_of_work: user.kind_of_work,
                            enter_date: new Date(),
                            position: user.position.id,
                            zone: user.zone && user.zone === "Зеленая зона" ? "Green" : "Red",
                        };
                        if (biot) {
                            editEmpStatusData.area = user.block ? user.block.name : user.project.name;
                        }
                        if (+user.personal_card_id) {
                            editEmpStatusData.card_identifier = (+user.personal_card_id).toString();
                        }
                    } else if (+user.personal_card_id) {
                        editEmpStatusData = {
                            card_identifier: (+user.personal_card_id).toString(),
                        };
                    }
                    if (editEmpStatusData) {
                        await crud.updateEmpStatus(editEmpStatusData, {
                            id: arr[i].id,
                        });
                    }
                }
            }
        }
        await crud.clearCard((+user.personal_card_id).toString(), empId);

        _lg(`setToDb: card cleared ${user.personal_card_id}`);
        const response2 = await crud.listEmpStatuses({
            emp_id: empId,
            project_id: user.project.code,
        });
        if (response2.length === 0) {
            const newEmpStatusData = {
                project_id: user.project.code,
                team_id: newTeamId || teamId,
                emp_id: empId,
                status: "done",
                kind_of_work: user.kind_of_work,
                enter_date: new Date(),
                position: user.position.id,
                zone: user.zone && user.zone === "Зеленая зона" ? "Green" : "Red",
            };
            if (biot) {
                newEmpStatusData.area = user.block ? user.block.name : user.project.name;
                newEmpStatusData.enter_date = user.proceed_date ? user.proceed_date : new Date();
            }
            if (+user.personal_card_id) {
                newEmpStatusData.card_identifier = (+user.personal_card_id).toString();
            }
            await crud.addEmpStatus(newEmpStatusData);
        }
    }
}

async function setToDbSub({ task, taskService }) {
    try {
        const vars = task.variables.getAll();
        // eslint-disable-next-line no-prototype-builtins
        const skip = vars.hasOwnProperty("skip") ? vars.skip : false;
        if (skip) {
            await taskService.complete(task).then((result) => {
                _lg(`Result: ${result}`);
            });
        } else {
            const user = vars.employee;

            const company = vars.companyName;
            const bin = vars.companyBIN.toString();
            // eslint-disable-next-line no-prototype-builtins
            const biot = vars.hasOwnProperty("biot") ? vars.biot : null;
            user.kind_of_work = vars.workType;
            user.block = vars.block;
            user.zone = vars.zone;
            user.project = vars.location;
            // eslint-disable-next-line no-prototype-builtins
            const fullCode = vars.hasOwnProperty("fullCode") ? vars.fullCode : null;
            if (fullCode) {
                user.project.assets_project_id = user.project.code;
                // eslint-disable-next-line no-prototype-builtins
            } else if (!user.project.hasOwnProperty("assets_project_id")) {
                user.project.assets_project_id = user.project.code;
            }
            _lg(`SAR_card_id: ${user.personal_card_id}`);
            _lg(`companyBIN: ${vars.companyBIN}`);
            user.company = {
                name: company,
                bin: bin,
            };
            const projectHasWorkType = await crud.tableHas(
                "bp_emp_status",
                `project_id='${user.project.code}' AND kind_of_work='${user.kind_of_work}'`,
            );
            await setToDb(user, biot);

            const variables = new Variables().setAllTyped({
                is_new_kind_of_work: {
                    value: !projectHasWorkType,
                    type: "Boolean",
                },
                project: {
                    value: user.project,
                    type: "Json",
                },
                kind_of_work: {
                    value: user.kind_of_work,
                    type: "String",
                },
            });
            await taskService.complete(task, variables).then((result) => {
                _lg(`Result: ${result}`);
            });
        }
    } catch (error) {
        _lg(error);
        await taskService.handleFailure(task, {
            errorMessage: error && error.message ? `${error.message}.` : "See logs for details",
            errorDetails: "See logs for details",
            retries: 0,
            retryTimeout: 1000,
        });
    }
}

async function setUserToDb({ task, taskService }) {
    try {
        const vars = task.variables.getAll();
        const { user } = vars;
        _lg(`setUserToDb: PUR_card_id: ${user.personal_card_id}`, ` on project: ${user.project.code}`);
        const projectHasWorkType = await DBC.tableHas(
            "bp_emp_status",
            `project_id='${user.project.code}' AND kind_of_work='${user.kind_of_work}'`,
        );
        await setToDb(user, null);

        const variables = new Variables().setAllTyped({
            is_new_kind_of_work: {
                value: !projectHasWorkType,
                type: "Boolean",
            },
            project: {
                value: user.project,
                type: "Json",
            },
            kind_of_work: {
                value: user.kind_of_work,
                type: "String",
            },
        });
        await taskService.complete(task, variables).then((result) => {
            _lg(`Result: ${result}`);
        });
    } catch (error) {
        _lg(error);
        await taskService.handleFailure(task, {
            errorMessage: error && error.message ? `${error.message}.` : "See logs for details",
            errorDetails: "See logs for details",
            retries: 0,
            retryTimeout: 1000,
        });
    }
}

module.exports = {
    sarSaveRespPerson,
    sarSaveTeamDocs,
    setToDbSub,
    setUserToDb,
};
Leave a Comment