All files / helpers/reports index.js

27.27% Statements 27/99
17.94% Branches 7/39
11.76% Functions 2/17
28.42% Lines 27/95

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                          61x                       57x 57x 57x 57x           57x 57x   57x                               57x 57x 57x     57x 52x 52x   52x   52x     57x       57x           57x                                     57x         57x                                       57x   57x 57x   57x   57x                                                                                                                                                                                                 1x                                                                        
/* eslint-disable no-empty */
/* eslint-disable no-plusplus */
/* eslint-disable default-param-last */
/* eslint-disable no-use-before-define */
/* eslint-disable no-param-reassign */
import excel from 'exceljs';
import fs from 'fs';
import path from 'path';
import uniqid from 'uniqid';
import APIError from '../error';
import { PATH_TEMP } from '../../../root';
import { genereteWaybillPDF } from '../../source/reports/pdf/waybillPrintPdf';
 
const MAX_ROWS_LIMIT = 10000;
 
async function writeExcelToResponse(
  res,
  headers = [],
  rows = [],
  colorHeaderFont = '#ffffff',
  colorHeaderBg = '#f79c20',
  worksheetName = 'worksheet',
  reportType = '',
  rowsCallback = null
) {
  const filenameUniqueId = `${worksheetName}${uniqid()}.xlsx`;
  const filePath = path.join(PATH_TEMP, filenameUniqueId);
  const fileName = `${worksheetName}.xlsx`;
  const options = {
    filename: filePath,
    useStyles: true,
    useSharedStrings: false,
  };
 
  const workbook = new excel.stream.xlsx.WorkbookWriter(options);
  const worksheet = workbook.addWorksheet(worksheetName);
 
  try {
    // Exemplo Colunas
    /* headers = [
      { header: 'Id', key: 'id', width: 10 },
      { header: 'Name', key: 'name', width: 30 },
      { header: 'Address', key: 'address', width: 30},
      { header: 'Age', key: 'age', width: 10, outlineLevel: 1}
    ]; */
 
    // Exemplo Rows
    /* rows = [ { id: 1, address: 'Jack Smith', age: 23, name: 'Massachusetts' },
        { id: 2, address: 'Adam Johnson', age: 27, name: 'New York' },
        { id: 3, address: 'Katherin Carter', age: 26, name: 'Washington DC' },
        { id: 4, address: 'Jack London', age: 33, name: 'Nevada' },
        { id: 5, address: 'Jason Bourne', age: 36, name: 'California' } ]; */
 
    const limit = MAX_ROWS_LIMIT;
    let offset = 0;
    let rowsLength = 0;
 
    // ROW CALLBACK MEMORY
    if (typeof rowsCallback === 'function') {
      rows.length = 0; // Limpa o array e libera memoria
      headers.length = 0; // Limpa o array e libera memoria
 
      await rowsCallback({ offset, limit, subQuery: false }); // Busca registros em lote
 
      rowsLength = rows.length;
    }
 
    worksheet.columns = headers.map((it) =>
      typeof it === 'object' ? it : { header: it }
    );
 
    headers.forEach((value, ix) => {
      if (value.numFmt) {
        worksheet.getColumn(ix + 1).numFmt = value.numFmt;
      }
    });
 
    Iif (rows.length) {
      const rowExcelFirst = worksheet.addRow(rows[0]);
      const firstRow = worksheet.getRow(1);
      for (let index = 1; index < headers.length + 1; index++) {
        firstRow.getCell(index).fill = {
          type: 'pattern',
          pattern: 'solid',
          fgColor: { argb: colorHeaderBg.replace('#', '') },
        };
      }
      worksheet.getRow(1).font = {
        color: { argb: colorHeaderFont.replace('#', '') },
        bold: true,
      };
 
      rowExcelFirst.commit();
      rows.splice(0, 1);
    }
 
    rows.forEach((row, index) => {
      worksheet.addRow(row).commit();
      rows[index] = undefined;
    });
 
    Iif (typeof rowsCallback === 'function' && rowsLength === limit) {
      while (rowsLength === limit) {
        rows.length = 0; // Limpa o array e libera memoria
        headers.length = 0; // Limpa o array e libera memoria
 
        offset += limit;
 
        await rowsCallback({ offset, limit, subQuery: false }); // Busca registros em lote
 
        rowsLength = rows.length; // Nao remover
 
        rows.forEach((row, index) => {
          worksheet.addRow(row).commit();
          rows[index] = undefined;
        });
 
        if (rowsLength < limit) break;
      }
    }
 
    worksheet.commit();
 
    try {
      await workbook.commit();
 
      Iif (reportType === 'bg') return { filePath, fileName, filenameUniqueId };
 
      res.download(filePath, fileName, async () => {
        await removeFile(filePath);
      });
    } catch (e) {
      await removeFile(filePath);
      throw new APIError('EXCEL_DOCUMENT', e);
    }
  } catch (e) {
    try {
      await workbook.commit();
      await removeFile(filePath);
      throw new APIError('EXCEL_DOCUMENT', e);
    } catch (e2) {
      try {
        await removeFile(filePath);
      } catch (e3) {
        throw new APIError('EXCEL_DOCUMENT', e3);
      }
      throw new APIError('EXCEL_DOCUMENT', e2);
    }
  }
}
 
async function oldWriteExcelToResponse(
  res,
  headers = [],
  rows = [],
  colorHeaderFont = '#ffffff',
  colorHeaderBg = '#f79c20',
  worksheetName = 'worksheet'
) {
  const workbook = new excel.Workbook();
  const worksheet = workbook.addWorksheet(worksheetName);
 
  // Exemplo Colunas
  /* headers = [
    { header: 'Id', key: 'id', width: 10 },
    { header: 'Name', key: 'name', width: 30 },
    { header: 'Address', key: 'address', width: 30},
    { header: 'Age', key: 'age', width: 10, outlineLevel: 1}
  ]; */
 
  // Exemplo Rows
  /* rows = [ { id: 1, address: 'Jack Smith', age: 23, name: 'Massachusetts' },
      { id: 2, address: 'Adam Johnson', age: 27, name: 'New York' },
      { id: 3, address: 'Katherin Carter', age: 26, name: 'Washington DC' },
      { id: 4, address: 'Jack London', age: 33, name: 'Nevada' },
      { id: 5, address: 'Jason Bourne', age: 36, name: 'California' } ]; */
 
  worksheet.columns = headers.map((it) =>
    typeof it === 'object' ? it : { header: it }
  );
 
  if (rows.length) {
    worksheet.addRow(rows[0]);
    rows.splice(0, 1);
 
    worksheet.getRow(1).fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: colorHeaderBg.replace('#', '') },
    };
    worksheet.getRow(1).font = {
      color: { argb: colorHeaderFont.replace('#', '') },
      bold: true,
    };
  }
 
  rows.forEach((row, index) => {
    worksheet.addRow(row);
    rows[index] = undefined;
  });
 
  headers.forEach((value, ix) => {
    if (value.numFmt) {
      worksheet.getColumn(ix + 1).numFmt = value.numFmt;
    }
  });
 
  res.setHeader(
    'Content-Type',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  );
  res.setHeader(
    'Content-Disposition',
    `attachment; filename=${worksheetName}.xlsx`
  );
 
  try {
    await workbook.xlsx.write(res);
    res.status(200).end();
  } catch (e) {
    throw new APIError('EXCEL_DOCUMENT');
  }
}
 
function writeWaybillToPdf(res, rows = []) {
  const pdfDoc = genereteWaybillPDF(rows);
 
  const chunks = [];
 
  pdfDoc.on('data', (chunk) => {
    chunks.push(chunk);
  });
 
  pdfDoc.end();
  pdfDoc.on('end', () => {
    const result = Buffer.concat(chunks);
    res.end(result);
  });
}
 
async function removeFile(filePath) {
  return new Promise((resolve, reject) => {
    fs.access(filePath, fs.constants.F_OK, (err) => {
      if (err) {
        resolve();
      } else {
        fs.unlink(filePath, (err, data) => {
          if (err) reject(err);
          else resolve(data);
        });
      }
    });
  });
}
 
export default {
  writeExcelToResponse,
  oldWriteExcelToResponse,
  removeFile,
  writeWaybillToPdf,
};