feat: refs #7905 getBuysCsv
gitea/salix/pipeline/head This commit looks good Details

This commit is contained in:
Guillermo Bonet 2024-09-06 13:50:49 +02:00
parent d10db686e5
commit 0ad4d3a959
3 changed files with 87 additions and 0 deletions

42
loopback/util/flatten.js Normal file
View File

@ -0,0 +1,42 @@
/**
* Flattens an array of objects by converting each object into a flat structure.
*
* @param {Array} dataArray Array of objects to be flattened
* @return {Array} Array of flattened objects
*/
function flatten(dataArray) {
return dataArray.map(item => flattenObj(item.__data));
}
/**
* Recursively flattens an object, converting nested properties into a single level object
* with keys representing the original nested structure.
*
* @param {Object} data The object to be flattened
* @param {String} [prefix=''] Optional prefix for nested keys
* @return {Object} Flattened object
*/
function flattenObj(data, prefix = '') {
let result = {};
try {
for (let key in data) {
if (!data[key]) continue;
const newKey = prefix ? `${prefix}_${key}` : key;
const value = data[key];
if (typeof value === 'object' && value !== null && !Array.isArray(value))
Object.assign(result, flattenObj(value.__data, newKey));
else
result[newKey] = value;
}
} catch (error) {
console.error(error);
}
return result;
}
module.exports = {
flatten,
flattenObj,
};

View File

@ -0,0 +1,44 @@
const {toCSV} = require('vn-loopback/util/csv');
const {flatten} = require('vn-loopback/util/flatten');
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('getBuysCsv', {
description: 'Returns buys for one entry in CSV file format',
accessType: 'READ',
accepts: [{
arg: 'id',
type: 'number',
required: true,
description: 'The entry id',
http: {source: 'path'}
}
],
returns: [
{
arg: 'body',
type: 'file',
root: true
}, {
arg: 'Content-Type',
type: 'String',
http: {target: 'header'}
}, {
arg: 'Content-Disposition',
type: 'String',
http: {target: 'header'}
}
],
http: {
path: `/:id/getBuysCsv`,
verb: 'GET'
}
});
Self.getBuysCsv = async(ctx, id, options) => {
const data = await Self.getBuys(ctx, id, null, options);
if (!data.length) throw new UserError('The entry has no lines or does not exist');
const dataFlatted = flatten(data);
return [toCSV(dataFlatted), 'text/csv', `inline; filename="buys-${id}.csv"`];
};
};

View File

@ -3,6 +3,7 @@ module.exports = Self => {
require('../methods/entry/filter')(Self);
require('../methods/entry/getEntry')(Self);
require('../methods/entry/getBuys')(Self);
require('../methods/entry/getBuysCsv')(Self);
require('../methods/entry/importBuys')(Self);
require('../methods/entry/importBuysPreview')(Self);
require('../methods/entry/lastItemBuys')(Self);