All files / controllers notifications.js

1.05% Statements 1/95
0% Branches 0/42
8.33% Functions 1/12
1.07% Lines 1/93

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    2x                                                                                                          
/* eslint-disable no-param-reassign */
/* eslint-disable no-plusplus */
/* eslint-disable import/no-named-as-default-member */
import moment from 'moment-timezone';
import path from 'path';
import fs from 'fs';
import UserNotificationInformation from '../source/userNotification/information';
import UserNotificationUpdate from '../source/userNotification/update';
import UserNotificationDelete from '../source/userNotification/delete';
import UserNotificationAttachmentDelete from '../source/userNotificationAttachment/delete';
import APIError from '../helpers/error';
import I18n from '../helpers/i18n';
import UserNotificationTypes from '../database/enumerators/userNotification';
import { PATH_ROOT } from '../../root';
import { sequelize } from '../../config/database';
import ReportsHelper from '../helpers/reports';
import UserNotificationCreate from '../source/userNotification/create';
import UserNotificationAttachmentCreate from '../source/userNotificationAttachment/create';
 
async function getNotifications(req, res) {
  try {
    const response = {
      success: false,
      data: {
        notifications: [],
      },
    };
 
    const { userId } = req;
    const { appLanguage } = req.query;
 
    const notifications =
      await UserNotificationInformation.getAllUserNotifications(
        { userId },
        { order: [['createdAt', 'DESC']] }
      );
 
    response.success = true;
    response.data.notifications = notifications.map((notification) => {
      const notificationTypes = UserNotificationTypes.getTypeValues(
        notification.type,
        appLanguage
      );
 
      let { attachments } = notification;
 
      if (attachments && attachments.length) {
        attachments = attachments.filter((attach) => {
          const pathNotDownloaded = path.resolve(PATH_ROOT, attach.storagePath);
 
          // Se o arquivo nao baixado existe entao atribui ele senao procura por arquivo baixado
          if (fs.existsSync(pathNotDownloaded)) {
            return true;
          }
 
          const parsedDownloadedFile = path.parse(attach.storagePath);
          const pathDownloaded = path.resolve(
            PATH_ROOT,
            parsedDownloadedFile.dir,
            `downloaded_${parsedDownloadedFile.base}`
          );
 
          if (fs.existsSync(pathDownloaded)) {
            return true;
          }
 
          return false;
        });
      }
 
      return {
        id: notification.id,
        type: notification.type,
        name: notificationTypes.name,
        readed: notification.readed,
        icon: notificationTypes.icon,
        firstTitle: notification.firstTitle,
        secondTitle: notification.secondTitle,
        description: notification.description,
        date: moment(notification.createdAt).format('DD/MM/YYYY HH:mm'),
        content: {
          title: notification.contentTitle,
          message: notification.contentMessage,
          attachments:
            attachments && attachments.length
              ? attachments.map((attach) => ({
                  notifId: notification.id,
                  id: attach.id,
                  name: attach.name,
                  type: attach.type,
                }))
              : [],
        },
      };
    });
 
    return res.json(response);
  } catch (err) {
    throw new APIError('UNKNOWN_ERROR', err);
  }
}
 
async function downloadFile(req, res) {
  try {
    const { notifId, id } = req.body;
    const { userId } = req;
 
    const notification = await UserNotificationInformation.getUserNotification({
      id: notifId,
      userId,
    });
 
    // Se existe arrachments
    if (
      notification &&
      notification.attachments &&
      notification.attachments.length
    ) {
      // Obtem o attachment pelo id
      const fileToDownload = notification.attachments.find(
        (attach) => attach.id === id
      );
 
      // Se encontrou o attachment
      if (fileToDownload) {
        // Verifica se existe o arquivo
        let filePath = '';
        let renameDownloaded = true;
 
        const pathNotDownloaded = path.resolve(
          PATH_ROOT,
          fileToDownload.storagePath
        );
 
        // Se o arquivo nao baixado existe entao atribui ele senao procura por arquivo baixado
        if (fs.existsSync(pathNotDownloaded)) {
          filePath = pathNotDownloaded;
        } else {
          const parsedDownloadedFile = path.parse(fileToDownload.storagePath);
          const pathDownloaded = path.resolve(
            PATH_ROOT,
            parsedDownloadedFile.dir,
            `downloaded_${parsedDownloadedFile.base}`
          );
 
          if (fs.existsSync(pathDownloaded)) {
            filePath = pathDownloaded;
            renameDownloaded = false;
          }
        }
 
        if (filePath) {
          res.download(filePath, fileToDownload.name, async () => {
            // Essa regra e necessaria para limpeza de arquivos ja baixados via cron
            if (renameDownloaded) {
              const parsedOldPath = path.parse(filePath);
              const newPath = path.resolve(
                parsedOldPath.dir,
                `downloaded_${parsedOldPath.base}`
              );
              fs.renameSync(filePath, newPath);
            }
          });
          return;
        }
      }
    }
  } catch (err) {
    throw new APIError('UNKNOWN_ERROR', err);
  }
 
  throw new APIError('', I18n.t('BEE2564' /* Falha ao baixar o arquivo */));
}
 
async function deleteNotification(req, res) {
  try {
    const response = {
      success: false,
      data: true,
    };
 
    const { notifId } = req.body;
    const { userId } = req;
 
    const notification = await UserNotificationInformation.getUserNotification({
      id: notifId,
      userId,
    });
 
    if (notification) {
      await sequelize.transaction(async (transaction) => {
        await UserNotificationDelete.deleteUserNotification(notifId, {
          transaction,
        });
 
        if (
          notification &&
          notification.attachments &&
          notification.attachments.length
        ) {
          for (
            let index = 0;
            index < notification.attachments.length;
            index++
          ) {
            const attach = notification.attachments[index];
 
            await UserNotificationAttachmentDelete.deleteUserNotificationAttachment(
              attach.id,
              { transaction }
            );
          }
        }
      });
 
      // Remove arquivos do disco
      for (let index = 0; index < notification.attachments.length; index++) {
        const attach = notification.attachments[index];
 
        // Verifica se existe o arquivo
        let filePath = '';
 
        const pathNotDownloaded = path.resolve(PATH_ROOT, attach.storagePath);
 
        // Se o arquivo nao baixado existe entao atribui ele senao procura por arquivo baixado
        if (fs.existsSync(pathNotDownloaded)) {
          filePath = pathNotDownloaded;
        } else {
          const parsedDownloadedFile = path.parse(attach.storagePath);
          const pathDownloaded = path.resolve(
            PATH_ROOT,
            parsedDownloadedFile.dir,
            `downloaded_${parsedDownloadedFile.base}`
          );
 
          if (fs.existsSync(pathDownloaded)) {
            filePath = pathDownloaded;
          }
        }
 
        if (filePath) fs.unlinkSync(filePath);
      }
 
      response.success = true;
    }
 
    return res.json(response);
  } catch (err) {
    throw new APIError('UNKNOWN_ERROR', err);
  }
}
 
async function setNotificationAsRead(req, res) {
  try {
    const response = {
      success: false,
      data: true,
    };
 
    const { notifId } = req.body;
    const { userId } = req;
 
    const notification = await UserNotificationInformation.getUserNotification({
      id: notifId,
      userId,
      readed: false,
    });
 
    if (notification) {
      await UserNotificationUpdate.updateUserNotification(notifId, {
        readed: true,
      });
      response.success = true;
    }
 
    return res.json(response);
  } catch (err) {
    throw new APIError('UNKNOWN_ERROR', err);
  }
}
 
async function newNotificationUser(titleFile, headers, rows, userId) {
  await sequelize.transaction(async (transaction) => {
    const { fileName, filePath, filenameUniqueId } =
      await ReportsHelper.writeExcelToResponse(
        null,
        headers,
        rows,
        undefined,
        undefined,
        titleFile,
        'bg'
      );
 
    fs.renameSync(filePath, path.join(PATH_ROOT, 'report', filenameUniqueId));
    const storagePath = `report/${filenameUniqueId}`;
 
    // Enviar notificacao
    const userNotification =
      await UserNotificationCreate.createUserNotification(
        {
          userId,
          type: UserNotificationTypes.REPORT,
          readed: false,
          firstTitle: I18n.t('BEE528' /* Relatório */),
          secondTitle: fileName,
          description: I18n.t(
            'BEE2569' /* Relatório gerado via segundo plano */
          ),
          contentTitle: `${I18n.t('BEE528' /* Relatório */)} - ${fileName}`,
          contentMessage: I18n.t(
            'BEE2569' /* Relatório gerado via segundo plano */
          ),
        },
        { transaction }
      );
    await UserNotificationAttachmentCreate.createUserNotificationAttachment(
      {
        userNotificationId: userNotification.id,
        name: fileName,
        type: 'xlsx',
        storagePath,
      },
      { transaction }
    );
  });
}
 
export default {
  getNotifications,
  downloadFile,
  deleteNotification,
  setNotificationAsRead,
  newNotificationUser,
};