Untitled

mail@pastecode.io avatar
unknown
plain_text
19 days ago
7.7 kB
3
Indexable
Never
module.exports = app => {
  const menu = {
    parentMenu: app.parentMenu.sdh,
    menus: {
      7642: {
        title: 'Quản lý đề tài (2)', link: '/user/sau-dai-hoc/de-tai', parentKey: 7500
      }
    }
  };

  app.permission.add(
    { name: 'sdhDeTai:read', menu },
    { name: 'sdhDeTai:write' },
    { name: 'sdhDeTai:delete' },
  );

  app.get('/user/sau-dai-hoc/de-tai', app.permission.check('sdhDeTai:read'), app.templates.admin);
  app.get('/user/sau-dai-hoc/so-quyet-dinh/:mssv', app.permission.check('sdhDeTai:read'), app.templates.admin);

  //APIs----------------------------------------------------------------------------------------------------------------------------------
  app.get('/api/sdh/de-tai', app.permission.check('sdhDeTai:read'), async (req, res) => {
    try {
      const items = await app.model.sdhDeTai.getAll({}, '*', 'ID');
      res.send({ items });
    } catch (error) {
      res.send({ error });
    }
  });

  app.get('/api/sdh/de-tai/page/:pageNumber/:pageSize', app.permission.check('sdhDeTai:read'), async (req, res) => {
    try {
      const { pageNumber, pageSize } = req.params;
      let { filter } = req.query || {};
      filter = filter || {};

      const { rows: list, pagenumber, pagesize, pagetotal, totalitem, newestsoquyetdinh } = await app.model.sdhDeTai.searchPage(Number(pageNumber), Number(pageSize), app.utils.stringify(filter));
      list.forEach(item => {
        if (item.canBo !== '[{"MSCB":null,"vaiTro":null,"hoTenCanBo":null,"from":null}]') {
          try {
            let cleanedString = item.canBo
              .replace(/\\"/g, '"')
              .replace(/""/g, '"');

            item.canBo = JSON.parse(cleanedString);
          } catch (err) {
            item.canBo = [];
          }
        } else {
          item.canBo = [];
        }
      });

      res.send({ page: { list, pageNumber: pagenumber, pageSize: pagesize, pageTotal: pagetotal, totalItem: totalitem, newestSoQuyetDinh: newestsoquyetdinh } });
    } catch (error) {
      app.consoleError(error);
      res.send({ error });
    }
  });

  app.get('/api/sdh/cbhd/page/:pageNumber/:pageSize', app.permission.check('sdhDeTai:read'), async (req, res) => {
    try {
      const { pageNumber, pageSize } = req.params;
      let { filter } = req.query || {};
      filter = filter || {};
      const searchTerm = typeof req.query.condition === 'string' ? req.query.condition : '';

      const { rows: list, pagenumber, pagesize, pagetotal, totalitem } = await app.model.sdhDeTai.sdhCanBoHuongDanSearchPage(Number(pageNumber), Number(pageSize), app.utils.stringify(filter), searchTerm);

      res.send({ page: { list, pageNumber: pagenumber, pageSize: pagesize, pageTotal: pagetotal, totalItem: totalitem } });
    } catch (error) {
      app.consoleError(error);
      res.send({ error });
    }
  });

  app.get('/api/sdh/cbhd/item/:shcc', app.permission.check('sdhDeTai:read'), async (req, res) => {
    try {
      const mscb = req.params.shcc;
      const { belong_to } = req.query;
      const belongToMapper = {
        'TCHC': async () => await app.model.tchcCanBo.get({ shcc: mscb }),
        'CBNT': async () => await app.model.dtCanBoNgoaiTruong.get({ shcc: mscb }),
        'SDHCB': async () => await app.model.sdhCanBo.get({ id: mscb }).then(item => ({ ...item, shcc: item.id })),
      };

      const canBo = await belongToMapper[belong_to]();

      res.send({
        item: { ...canBo }
      });
    } catch (error) {
      app.consoleError(error);
      res.send({ error });
    }
  });

  app.post('/api/sdh/de-tai', app.permission.check('sdhDeTai:write'), async (req, res) => {
    try {
      const { data } = req.body;

      const deTaiData = {
        'tenDeTai': data.tenDeTai,
        'mssv': data.mssv,
        'ghiChu': data.ghiChu,
        'noiDung': data.noiDung
      };

      const deTaiItem = await app.model.sdhDeTai.create(deTaiData);

      const soQuyetDinhData = {
        'ten': data.tenSqd,
        'time': Date.now(),
        'idDeTai': deTaiItem.id,
        'id': data.soQuyetDinh
      };

      const soQuyetDinhItem = await app.model.sdhSoQuyetDinh.create(soQuyetDinhData);

      const updatedCbhd = await Promise.all(data.cbhd.map(async (item) => {
        if (!item.shcc && item.hoTenCanBo && item.trinhDo) {
          const [firstName, ...lastNameParts] = item.hoTenCanBo.split(' ');
          const lastName = lastNameParts.join(' ');
          const temp = await app.model.sdhCanBo.create({
            'ho': firstName,
            'ten': lastName,
            'trinhDo': item.trinhDo
          });
          const { id, ...restItem } = temp;
          console.log(temp.id);
          return { shcc: temp.id, ...restItem, belongTo: 'SDHCB' };
        }
        return item;
      }));


      console.log(updatedCbhd, 'updated cbhd');

      data.cbhd = updatedCbhd;

      console.log(data.cbhd, 'sljslkdfjsdkljf');

      await Promise.all(data.cbhd.flatMap(item => {
        if (item.belongTo !== 'SDHCB') {
          const [shcc, belongTo] = item.shcc.split(' - ');
          item.belongTo = belongTo;
          item.shcc = shcc;
        }
        app.model.sdhCbhd.create({
          'vaiTro': item.vaiTro,
          'idCanBo': item.shcc,
          'mssv': data.mssv,
          'belongTo': item.belongTo,
        });
        app.model.sdhSoQuyetDinhDetail.create({
          'soQuyetDinh': soQuyetDinhItem.soQuyetDinh,
          'tenDeTai': data.tenDeTai,
          ...item
        });
      }));

      const item = {
        deTai: deTaiItem,
        soQuyetDinh: soQuyetDinhItem,
      };
      res.send({ item });
    } catch (error) {
      app.consoleError(req, error);
      res.send({ error });
    }
  });

  app.put('/api/sdh/de-tai', app.permission.check('sdhDeTai:write'), async (req, res) => {
    try {
      const { data, id } = req.body;
      const deTaiData = {
        'tenDeTai': data.tenDeTai,
        'mssv': data.mssv,
        'ghiChu': data.ghiChu,
        'noiDung': data.noiDung
      };

      const soQuyetDinhData = {
        'ten': data.tenSqd,
        'time': Date.now(),
        'idDeTai': id,
        'id': data.soQuyetDinh
      };

      for (let i = 0; i < data.cbhd.length; i++) {
        const item = data.cbhd[i];
        if (!item.shcc && item.hoTen && item.trinhDo) {
          const [firstName, ...lastNameParts] = item.hoTen.split(' ');
          const lastName = lastNameParts.join(' ');
          const temp = await app.model.sdhCanBo.create({
            'ho': firstName,
            'ten': lastName,
            'trinhDo': item.trinhDo
          });
          data.cbhd[i] = { ...res, shcc: temp.id, ...data.cbhd[i], belongTo: 'SDHCB' };
          delete data.cbhd[i].id;
        }
      }

      await app.model.sdhCbhd.delete({ mssv: data.mssv });
      await Promise.all([
        app.model.sdhSoQuyetDinh.update({ idDeTai: id, active: 0 }, { active: 1 }),
        app.model.sdhDeTai.update({ id }, deTaiData),

        app.model.sdhSoQuyetDinh.create(soQuyetDinhData),
        ...data.cbhd.flatMap(item => [
          app.model.sdhCbhd.create({
            'vaiTro': item.vaiTro,
            'idCanBo': item.shcc.split(' - ').length > 1 ? item.shcc.split(' - ')[0] : item.shcc,
            'belongTo': item.shcc.split(' - ').length > 1 ? item.shcc.split(' - ')[1] : item.shcc,
            'mssv': data.mssv
          }),
          app.model.sdhSoQuyetDinhDetail.create({
            'soQuyetDinh': soQuyetDinhData.id,
            'tenDeTai': data.tenDeTai,
          })
        ])
      ]);

      res.send({ 'message': 'success' });
    } catch (error) {
      app.consoleError(req, error);
      res.send({ error });
    }
  });
};
Leave a Comment