salix/modules/entry/back/methods/entry/getBuys.js

135 lines
4.1 KiB
JavaScript

const UserError = require('vn-loopback/util/user-error');
const mergeFilters = require('vn-loopback/util/filter').mergeFilters;
module.exports = Self => {
Self.remoteMethodCtx('getBuys', {
description: 'Returns buys for one entry',
accessType: 'READ',
accepts: [{
arg: 'id',
type: 'number',
required: true,
description: 'The entry id',
http: {source: 'path'}
},
{
arg: 'filter',
type: 'object',
description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string'
}
],
returns: {
type: ['object'],
root: true
},
http: {
path: `/:id/getBuys`,
verb: 'GET'
}
});
Self.getBuys = async(ctx, id, filter, options) => {
const userId = ctx.req.accessToken.userId;
const models = Self.app.models;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const client = await Self.app.models.Client.findById(userId, myOptions);
const supplier = await Self.app.models.Supplier.findOne({where: {nif: client.fi}}, myOptions);
if (supplier) {
const isEntryOwner = (await Self.findById(id)).supplierFk === supplier.id;
if (!isEntryOwner) throw new UserError('Access Denied');
}
let defaultFilter = {
where: {entryFk: id},
fields: [
'id',
'itemFk',
'stickers',
'packing',
'grouping',
'packing',
'groupingMode',
'quantity',
'packagingFk',
'weight',
'buyingValue',
'price2',
'price3',
'printedStickers',
'entryFk'
],
include: [{
relation: 'entry',
scope: {
fields: [
'id', 'supplierFk'
],
include: {
relation: 'supplier', scope: {
fields: ['id']
}
}
}
},
{
relation: 'item',
scope: {
fields: [
'id',
'typeFk',
'stems',
'name',
'category',
'subName',
'size',
'minPrice',
'tag5',
'value5',
'tag6',
'value6',
'tag7',
'value7',
'tag8',
'value8',
'tag9',
'value9',
'tag10',
'value10',
'groupingMode',
'inkFk',
'originFk',
'producerFk',
'comment'
],
include: [
{
relation: 'itemType',
scope: {
fields: ['code', 'description']
}
},
{
relation: 'origin',
scope: {
fields: ['code']
}
},
{
relation: 'producer',
scope: {
fields: ['name']
}
}
]
}
}]
};
defaultFilter = mergeFilters(defaultFilter, filter);
return models.Buy.find(defaultFilter, myOptions);
};
};