2022-10-24 12:20:09 +00:00
|
|
|
const JSZip = require('jszip');
|
|
|
|
const fs = require('fs-extra');
|
2022-10-26 07:33:03 +00:00
|
|
|
const UserError = require('vn-loopback/util/user-error');
|
2022-10-24 12:20:09 +00:00
|
|
|
|
|
|
|
module.exports = Self => {
|
|
|
|
Self.remoteMethodCtx('downloadZip', {
|
|
|
|
description: 'Download a zip file with multiple invoices pdfs',
|
|
|
|
accessType: 'READ',
|
|
|
|
accepts: [
|
|
|
|
{
|
|
|
|
arg: 'ids',
|
2022-12-20 08:48:58 +00:00
|
|
|
type: 'string',
|
|
|
|
description: 'The invoices ids',
|
|
|
|
}
|
|
|
|
],
|
|
|
|
returns: [
|
|
|
|
{
|
|
|
|
arg: 'body',
|
|
|
|
type: 'file',
|
|
|
|
root: true
|
|
|
|
}, {
|
|
|
|
arg: 'Content-Type',
|
|
|
|
type: 'string',
|
|
|
|
http: {target: 'header'}
|
|
|
|
}, {
|
|
|
|
arg: 'Content-Disposition',
|
|
|
|
type: 'string',
|
|
|
|
http: {target: 'header'}
|
2022-10-24 12:20:09 +00:00
|
|
|
}
|
|
|
|
],
|
|
|
|
http: {
|
|
|
|
path: '/downloadZip',
|
2022-12-20 08:48:58 +00:00
|
|
|
verb: 'GET'
|
2024-02-26 05:57:17 +00:00
|
|
|
},
|
2024-04-19 08:49:57 +00:00
|
|
|
accessScopes: ['DEFAULT', 'read:multimedia']
|
2022-10-24 12:20:09 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
Self.downloadZip = async function(ctx, ids, options) {
|
|
|
|
const models = Self.app.models;
|
|
|
|
const myOptions = {};
|
2022-12-20 08:48:58 +00:00
|
|
|
const zip = new JSZip();
|
2022-10-24 12:20:09 +00:00
|
|
|
|
|
|
|
if (typeof options == 'object')
|
|
|
|
Object.assign(myOptions, options);
|
|
|
|
|
2022-12-20 09:40:39 +00:00
|
|
|
const zipConfig = await models.ZipConfig.findOne(null, myOptions);
|
2022-10-24 12:20:09 +00:00
|
|
|
let totalSize = 0;
|
2022-12-20 08:48:58 +00:00
|
|
|
ids = ids.split(',');
|
|
|
|
|
2022-10-24 12:20:09 +00:00
|
|
|
for (let id of ids) {
|
2022-10-26 07:33:03 +00:00
|
|
|
if (zipConfig && totalSize > zipConfig.maxSize) throw new UserError('Files are too large');
|
2022-10-24 12:20:09 +00:00
|
|
|
const invoiceOutPdf = await models.InvoiceOut.download(ctx, id, myOptions);
|
|
|
|
const fileName = extractFileName(invoiceOutPdf[2]);
|
|
|
|
const body = invoiceOutPdf[0];
|
|
|
|
const sizeInBytes = (await fs.promises.stat(body.path)).size;
|
|
|
|
const sizeInMegabytes = sizeInBytes / (1024 * 1024);
|
|
|
|
totalSize += sizeInMegabytes;
|
|
|
|
zip.file(fileName, body);
|
|
|
|
}
|
2022-12-20 08:48:58 +00:00
|
|
|
|
|
|
|
const stream = zip.generateNodeStream({streamFiles: true});
|
|
|
|
|
|
|
|
return [stream, 'application/zip', `filename="download.zip"`];
|
2022-10-24 12:20:09 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
function extractFileName(str) {
|
|
|
|
const matches = str.match(/"(.*?)"/);
|
|
|
|
return matches ? matches[1] : str;
|
|
|
|
}
|
|
|
|
};
|