Merge pull request 'feat: refs #7905 getBuysCsv' (!2900) from 7905-getBuysCsv into dev
gitea/salix/pipeline/head This commit looks good Details

Reviewed-on: #2900
Reviewed-by: Javi Gallego <jgallego@verdnatura.es>
Reviewed-by: Javier Segarra <jsegarra@verdnatura.es>
This commit is contained in:
Guillermo Bonet 2024-09-05 09:44:38 +00:00
commit 620ce5d45e
4 changed files with 88 additions and 0 deletions

View File

@ -0,0 +1,2 @@
INSERT IGNORE INTO salix.ACL (model,property,principalId)
VALUES ('Entry','getBuysCsv','supplier');

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

@ -0,0 +1,43 @@
/**
* 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,42 @@
const {toCSV} = require('vn-loopback/util/csv');
const {flatten} = require('vn-loopback/util/flatten');
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);
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);