order module transactions

This commit is contained in:
Carlos Jimenez Ruiz 2021-12-15 15:29:22 +01:00
parent 6aa3101e42
commit b4f1e66fed
31 changed files with 672 additions and 259 deletions

View File

@ -52,8 +52,6 @@
"Agency cannot be blank": "La agencia no puede quedar en blanco",
"You can't make changes on a client with verified data": "No puedes hacer cambios en un cliente con datos comprobados",
"This address doesn't exist": "Este consignatario no existe",
"You can't create an order for a inactive client": "You can't create an order for a inactive client",
"You can't create an order for a client that doesn't has tax data verified": "You can't create an order for a client that doesn't has tax data verified",
"You must delete the claim id %d first": "Antes debes borrar la reclamación %d",
"You don't have enough privileges": "No tienes suficientes permisos",
"Cannot check Equalization Tax in this NIF/CIF": "No se puede marcar RE en este NIF/CIF",

View File

@ -21,22 +21,35 @@ module.exports = Self => {
}
});
Self.addToOrder = async params => {
let isEditable = await Self.app.models.Order.isEditable(params.orderFk);
Self.addToOrder = async(params, options) => {
const myOptions = {};
let tx;
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
const isEditable = await Self.app.models.Order.isEditable(params.orderFk, myOptions);
if (!isEditable)
throw new UserError('This order is not editable');
let promises = [];
params.items.forEach(item => {
const promises = [];
for (const item of params.items) {
promises.push(
Self.rawSql(
`CALL hedera.order_addItem(?, ?, ?, ?)`,
[params.orderFk, item.warehouseFk, item.itemFk, item.quantity]
[params.orderFk, item.warehouseFk, item.itemFk, item.quantity],
myOptions
)
);
});
}
await Promise.all(promises);
return true;
};
};

View File

@ -22,18 +22,29 @@ module.exports = Self => {
});
Self.removes = async params => {
const myOptions = {};
let tx;
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
if (!params.rows || !params.rows.length)
throw new UserError('There is nothing to delete');
let isEditable = await Self.app.models.Order.isEditable(params.actualOrderId);
const isEditable = await Self.app.models.Order.isEditable(params.actualOrderId, myOptions);
if (!isEditable)
throw new UserError('This order is not editable');
let promises = [];
const promises = [];
for (let i = 0; i < params.rows.length; i++)
promises.push(Self.app.models.OrderRow.destroyById(params.rows[i]));
promises.push(Self.app.models.OrderRow.destroyById(params.rows[i], myOptions));
return await Promise.all(promises);
return Promise.all(promises);
};
};

View File

@ -1,32 +1,36 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('order addToOrder()', () => {
const orderId = 8;
let rowToDelete;
afterAll(async() => {
await app.models.OrderRow.removes({rows: [rowToDelete], actualOrderId: orderId});
});
it('should add a row to a given order', async() => {
let unmodifiedRows = await app.models.OrderRow.find({where: {orderFk: orderId}});
const tx = await models.Order.beginTransaction({});
expect(unmodifiedRows.length).toBe(2);
try {
const options = {transaction: tx};
let params = {
orderFk: orderId,
items: [{
itemFk: 1,
quantity: 10,
warehouseFk: 1
}]
};
const unmodifiedRows = await models.OrderRow.find({where: {orderFk: orderId}}, options);
await app.models.OrderRow.addToOrder(params);
expect(unmodifiedRows.length).toBe(2);
let modifiedRows = await app.models.OrderRow.find({where: {orderFk: orderId}});
const params = {
orderFk: orderId,
items: [{
itemFk: 1,
quantity: 10,
warehouseFk: 1
}]
};
rowToDelete = modifiedRows[modifiedRows.length - 1].id;
await models.OrderRow.addToOrder(params, options);
expect(modifiedRows.length).toBe(3);
const modifiedRows = await models.OrderRow.find({where: {orderFk: orderId}}, options);
expect(modifiedRows.length).toBe(3);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
});

View File

@ -1,20 +1,18 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('order removes()', () => {
let row;
let newRow;
beforeAll(async() => {
row = await app.models.OrderRow.findOne({where: {id: 12}});
row.id = null;
newRow = await app.models.OrderRow.create(row);
});
it('should throw an error if rows property is empty', async() => {
const tx = await models.Order.beginTransaction({});
let error;
try {
await app.models.OrderRow.removes({rows: []});
const options = {transaction: tx};
await models.OrderRow.removes({rows: []}, options);
await tx.rollback();
} catch (e) {
await tx.rollback();
error = e;
}
@ -22,10 +20,17 @@ describe('order removes()', () => {
});
it('should throw an error if the row selected is not editable', async() => {
const tx = await models.Order.beginTransaction({});
let error;
try {
await app.models.OrderRow.removes({rows: [2]});
const options = {transaction: tx};
await models.OrderRow.removes({rows: [2]}, options);
await tx.rollback();
} catch (e) {
await tx.rollback();
error = e;
}
@ -33,13 +38,24 @@ describe('order removes()', () => {
});
it('should delete the row', async() => {
let params = {
rows: [newRow.id],
actualOrderId: 16
};
const tx = await models.Order.beginTransaction({});
let res = await app.models.OrderRow.removes(params);
try {
const options = {transaction: tx};
expect(res).toEqual([{count: 1}]);
const params = {
rows: [12],
actualOrderId: 16
};
const res = await models.OrderRow.removes(params, options);
expect(res).toEqual([{count: 1}]);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
});

View File

@ -19,29 +19,12 @@ module.exports = Self => {
}
});
Self.confirm = async(ctx, orderFk, option) => {
Self.confirm = async(ctx, orderFk) => {
const userId = ctx.req.accessToken.userId;
const myOptions = {};
let tx;
if (typeof options == 'object')
Object.assign(myOptions, options);
const query = `CALL hedera.order_confirmWithUser(?, ?)`;
const response = await Self.rawSql(query, [orderFk, userId]);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
try {
const query = `CALL hedera.order_confirmWithUser(?, ?)`;
const response = await Self.rawSql(query, [orderFk, userId], myOptions);
if (tx) await tx.commit();
return response;
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
return response;
};
};

View File

@ -3,7 +3,7 @@ const ParameterizedSQL = require('loopback-connector').ParameterizedSQL;
module.exports = Self => {
Self.remoteMethod('getItemTypeAvailable', {
description: 'Gets the item types available for an rder and item category ',
description: 'Gets the item types available for an order and item category',
accessType: 'READ',
accepts: [{
arg: 'id',
@ -27,11 +27,16 @@ module.exports = Self => {
}
});
Self.getItemTypeAvailable = async(orderId, itemCategoryId) => {
Self.getItemTypeAvailable = async(orderId, itemCategoryId, options) => {
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const stmts = [];
let stmt;
const order = await app.models.Order.findById(orderId);
const order = await app.models.Order.findById(orderId, null, myOptions);
stmt = new ParameterizedSQL('call vn.available_calc(?, ?, ?)', [
order.landed,
order.addressFk,
@ -78,7 +83,7 @@ module.exports = Self => {
stmts.push('DROP TEMPORARY TABLE tmp.item');
const sql = ParameterizedSQL.join(stmts, ';');
const result = await Self.rawStmt(sql);
const result = await Self.rawStmt(sql, myOptions);
return result[categoriesIndex];
};

View File

@ -3,7 +3,7 @@ module.exports = Self => {
description: 'Gets the sourceApp type set',
accessType: 'READ',
returns: {
type: ['String'],
type: ['string'],
root: true
},
http: {

View File

@ -21,10 +21,14 @@ module.exports = Self => {
}
});
Self.getTaxes = async orderFk => {
let conn = Self.dataSource.connector;
let stmts = [];
Self.getTaxes = async(orderFk, options) => {
const conn = Self.dataSource.connector;
const stmts = [];
let stmt;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.order');
@ -37,15 +41,15 @@ module.exports = Self => {
stmts.push('CALL hedera.order_getTax()');
let orderTaxIndex = stmts.push('SELECT * FROM tmp.orderAmount') - 1;
const orderTaxIndex = stmts.push('SELECT * FROM tmp.orderAmount') - 1;
stmts.push(`
DROP TEMPORARY TABLE
tmp.order,
tmp.orderTax`);
let sql = ParameterizedSQL.join(stmts, ';');
let result = await conn.executeStmt(sql);
const sql = ParameterizedSQL.join(stmts, ';');
const result = await conn.executeStmt(sql, myOptions);
return result[orderTaxIndex];
};

View File

@ -19,9 +19,14 @@ module.exports = Self => {
}
});
Self.getTotal = async orderFk => {
let query = `SELECT hedera.order_getTotal(?) total;`;
let [total] = await Self.rawSql(query, [orderFk]);
Self.getTotal = async(orderFk, options) => {
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const query = `SELECT hedera.order_getTotal(?) total;`;
const [total] = await Self.rawSql(query, [orderFk], myOptions);
return total.total;
};

View File

@ -19,9 +19,14 @@ module.exports = Self => {
}
});
Self.getTotalVolume = async orderFk => {
let query = `SELECT vn.orderTotalVolume(?) totalVolume, vn.orderTotalVolumeBoxes(?) totalBoxes`;
let [res] = await Self.rawSql(query, [orderFk, orderFk]);
Self.getTotalVolume = async(orderFk, options) => {
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const query = `SELECT vn.orderTotalVolume(?) totalVolume, vn.orderTotalVolumeBoxes(?) totalBoxes`;
const [res] = await Self.rawSql(query, [orderFk, orderFk], myOptions);
return res;
};
};

View File

@ -19,9 +19,14 @@ module.exports = Self => {
}
});
Self.getVAT = async orderId => {
Self.getVAT = async(orderId, options) => {
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
let totalTax = 0.00;
let taxes = await Self.app.models.Order.getTaxes(orderId);
const taxes = await Self.app.models.Order.getTaxes(orderId, myOptions);
taxes.forEach(tax => {
totalTax += tax.tax;
});

View File

@ -18,8 +18,13 @@ module.exports = Self => {
}
});
Self.getVolumes = async orderFk => {
let [volume] = await Self.rawSql(`CALL vn.orderListVolume(?)`, [orderFk]);
Self.getVolumes = async(orderFk, options) => {
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const [volume] = await Self.rawSql(`CALL vn.orderListVolume(?)`, [orderFk], myOptions);
return volume;
};
};

View File

@ -19,8 +19,13 @@ module.exports = Self => {
}
});
Self.isEditable = async orderId => {
let exists = await Self.app.models.Order.findOne({
Self.isEditable = async(orderId, options) => {
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const exists = await Self.app.models.Order.findOne({
where: {id: orderId},
fields: ['isConfirmed', 'clientFk'],
include: [
@ -32,7 +37,7 @@ module.exports = Self => {
}
}
]
});
}, myOptions);
if (exists && exists.client().type().code !== 'normal')
return true;

View File

@ -32,8 +32,19 @@ module.exports = Self => {
}
});
Self.new = async(landed, addressId, agencyModeId) => {
let address = await Self.app.models.Address.findOne({
Self.new = async(landed, addressId, agencyModeId, options) => {
const myOptions = {};
let tx;
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
const address = await Self.app.models.Address.findOne({
where: {id: addressId},
fields: ['clientFk'],
include: [
@ -45,11 +56,11 @@ module.exports = Self => {
}
}
]
});
}, myOptions);
if (address.client().type().code === 'normal') {
if (!address.client().isActive)
throw new UserError(`You can't create an order for a inactive client`);
throw new UserError(`You can't create an order for an inactive client`);
}
query = `CALL vn.orderListCreate(?, ?, ?, ?);`;
@ -58,7 +69,7 @@ module.exports = Self => {
agencyModeId,
addressId,
'SALIX'
]);
], myOptions);
return result[0].vOrderId;
};

View File

@ -18,16 +18,27 @@ module.exports = Self => {
}
});
Self.newFromTicket = async ticketFk => {
let ticket = await Self.app.models.Ticket.findOne({
Self.newFromTicket = async(ticketFk, options) => {
const myOptions = {};
let tx;
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
const ticket = await Self.app.models.Ticket.findOne({
where: {id: ticketFk}
});
}, myOptions);
let landed = ticket.landed;
let addressFk = ticket.addressFk;
let agencyModeFk = ticket.agencyModeFk;
const landed = ticket.landed;
const addressFk = ticket.addressFk;
const agencyModeFk = ticket.agencyModeFk;
let orderID = await Self.app.models.Order.new(landed, addressFk, agencyModeFk);
const orderID = await Self.app.models.Order.new(landed, addressFk, agencyModeFk, myOptions);
return orderID;
};

View File

@ -1,4 +1,4 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('order filter()', () => {
const ctx = {
@ -8,51 +8,102 @@ describe('order filter()', () => {
};
it('should call the filter method with a basic search', async() => {
const filter = {where: {'o.id': 2}};
const result = await app.models.Order.filter(ctx, filter);
const orderId = result[0].id;
const tx = await models.Order.beginTransaction({});
expect(orderId).toEqual(2);
try {
const options = {transaction: tx};
const filter = {where: {'o.id': 2}};
const result = await models.Order.filter(ctx, filter, options);
const orderId = result[0].id;
expect(orderId).toEqual(2);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
it('should call the filter method with a single advanced search', async() => {
const filter = {where: {'o.confirmed': false}};
const result = await app.models.Order.filter(ctx, filter);
const tx = await models.Order.beginTransaction({});
expect(result.length).toEqual(16);
try {
const options = {transaction: tx};
const filter = {where: {'o.confirmed': false}};
const result = await models.Order.filter(ctx, filter, options);
expect(result.length).toEqual(16);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
it('should call the filter method with a complex advanced search', async() => {
const filter = {where: {'o.confirmed': false, 'c.salesPersonFk': 18}};
const result = await app.models.Order.filter(ctx, filter);
const tx = await models.Order.beginTransaction({});
expect(result.length).toEqual(9);
expect(result[0].id).toEqual(7);
try {
const options = {transaction: tx};
const filter = {where: {'o.confirmed': false, 'c.salesPersonFk': 18}};
const result = await models.Order.filter(ctx, filter, options);
expect(result.length).toEqual(9);
expect(result[0].id).toEqual(7);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
it('should return the orders matching the showEmpty on false', async() => {
const filter = {};
ctx.args = {showEmpty: false};
const result = await app.models.Order.filter(ctx, filter);
const hasEmptyLines = result.some(order => {
return order.total === 0;
});
const tx = await models.Order.beginTransaction({});
expect(hasEmptyLines).toBeFalsy();
try {
const options = {transaction: tx};
ctx.args = {showEmpty: null};
const filter = {};
ctx.args = {showEmpty: false};
const result = await models.Order.filter(ctx, filter, options);
const hasEmptyLines = result.some(order => {
return order.total === 0;
});
expect(hasEmptyLines).toBeFalsy();
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
it('should return the orders matching the showEmpty on true', async() => {
const filter = {};
ctx.args = {showEmpty: true};
const result = await app.models.Order.filter(ctx, filter);
const hasEmptyLines = result.some(order => {
return order.total === 0;
});
const tx = await models.Order.beginTransaction({});
expect(hasEmptyLines).toBeTruthy();
try {
const options = {transaction: tx};
ctx.args = {showEmpty: null};
const filter = {};
ctx.args = {showEmpty: true};
const result = await models.Order.filter(ctx, filter, options);
const hasEmptyLines = result.some(order => {
return order.total === 0;
});
expect(hasEmptyLines).toBeTruthy();
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
});

View File

@ -1,19 +1,41 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('order getItemTypeAvailable()', () => {
it('should call the getItemTypeAvailable method with a valid order and item category', async() => {
let orderId = 11;
let itemCategoryId = 1;
let result = await app.models.Order.getItemTypeAvailable(orderId, itemCategoryId);
const tx = await models.Order.beginTransaction({});
expect(result.length).toEqual(1);
try {
const options = {transaction: tx};
const orderId = 11;
const itemCategoryId = 1;
const result = await models.Order.getItemTypeAvailable(orderId, itemCategoryId, options);
expect(result.length).toEqual(1);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
it('should call the getItemTypeAvailable method with the same order and different item category', async() => {
let orderId = 11;
let itemCategoryId = 4;//
let result = await app.models.Order.getItemTypeAvailable(orderId, itemCategoryId);
const tx = await models.Order.beginTransaction({});
expect(result.length).toEqual(0);
try {
const options = {transaction: tx};
const orderId = 11;
const itemCategoryId = 4;
const result = await models.Order.getItemTypeAvailable(orderId, itemCategoryId, options);
expect(result.length).toEqual(0);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
});

View File

@ -1,31 +1,75 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('order getTaxes()', () => {
it('should call the getTaxes method and return undefined if its called with a string', async() => {
let result = await app.models.Order.getTaxes('string');
const tx = await models.Order.beginTransaction({});
expect(result.length).toEqual(0);
try {
const options = {transaction: tx};
const result = await models.Order.getTaxes('string', options);
expect(result.length).toEqual(0);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
it('should call the getTaxes method and return undefined if its called with unknown id', async() => {
let result = await app.models.Order.getTaxes(99999999999999999999999);
const tx = await models.Order.beginTransaction({});
expect(result.length).toEqual(0);
try {
const options = {transaction: tx};
const result = await models.Order.getTaxes(9999, options);
expect(result.length).toEqual(0);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
it('should call the getTaxes method and return the taxes splited if different type of taxes', async() => {
let result = await app.models.Order.getTaxes(1);
const tx = await models.Order.beginTransaction({});
const expectedResult = result[0].tax + result[1].tax;
try {
const options = {transaction: tx};
expect(expectedResult).toEqual(20.29);
expect(result.length).toEqual(2);
const result = await models.Order.getTaxes(1, options);
const expectedResult = result[0].tax + result[1].tax;
expect(expectedResult).toEqual(20.29);
expect(result.length).toEqual(2);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
it('should call the getTaxes method and return the taxes for them same type', async() => {
let result = await app.models.Order.getTaxes(2);
const tx = await models.Order.beginTransaction({});
expect(result[0].tax).toEqual(9.1);
expect(result.length).toEqual(1);
try {
const options = {transaction: tx};
const result = await models.Order.getTaxes(2, options);
expect(result[0].tax).toEqual(9.1);
expect(result.length).toEqual(1);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
});

View File

@ -1,9 +1,19 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('order getTotal()', () => {
it('should return the order total', async() => {
let result = await app.models.Order.getTotal(1);
const tx = await models.Order.beginTransaction({});
expect(result).toEqual(155.89);
try {
const options = {transaction: tx};
const result = await models.Order.getTotal(1, options);
expect(result).toEqual(155.89);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
});

View File

@ -1,10 +1,21 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('order getTotalVolume()', () => {
it('should return the total', async() => {
let result = await app.models.Order.getTotalVolume(1);
const tx = await models.Order.beginTransaction({});
expect(result.totalVolume).toEqual(1.568);
expect(result.totalBoxes).toEqual(11.1);
try {
const options = {transaction: tx};
const result = await models.Order.getTotalVolume(1, options);
expect(result.totalVolume).toEqual(1.568);
expect(result.totalBoxes).toEqual(11.1);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
});

View File

@ -1,9 +1,20 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('order getVAT()', () => {
it('should return the order VAT', async() => {
const result = await app.models.Order.getVAT(1);
const tx = await models.Order.beginTransaction({});
expect(result).toEqual(20.29);
try {
const options = {transaction: tx};
const result = await models.Order.getVAT(1, options);
expect(result).toEqual(20.29);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
});

View File

@ -1,9 +1,20 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('order getVolumes()', () => {
it('should return the volumes of a given order id', async() => {
let [result] = await app.models.Order.getVolumes(1);
const tx = await models.Order.beginTransaction({});
expect(result.volume).toEqual(1.09);
try {
const options = {transaction: tx};
const [result] = await models.Order.getVolumes(1, options);
expect(result.volume).toEqual(1.09);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
});

View File

@ -1,21 +1,54 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('order isEditable()', () => {
it('should return false when the given order is not editable', async() => {
let isEditable = await app.models.Order.isEditable(2);
const tx = await models.Order.beginTransaction({});
expect(isEditable).toBeFalsy();
try {
const options = {transaction: tx};
const isEditable = await models.Order.isEditable(2, options);
expect(isEditable).toBeFalsy();
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
it('should return false when the given order doesnt exists', async() => {
let isEditable = await app.models.Order.isEditable(99999);
const tx = await models.Order.beginTransaction({});
expect(isEditable).toBeFalsy();
try {
const options = {transaction: tx};
const isEditable = await models.Order.isEditable(999, options);
expect(isEditable).toBeFalsy();
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
it('should return true when the given order is editable', async() => {
let isEditable = await app.models.Order.isEditable(16);
const tx = await models.Order.beginTransaction({});
expect(isEditable).toBeTruthy();
try {
const options = {transaction: tx};
const isEditable = await models.Order.isEditable(16, options);
expect(isEditable).toBeTruthy();
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
});

View File

@ -1,36 +1,49 @@
const app = require('vn-loopback/server/server');
let UserError = require('vn-loopback/util/user-error');
const models = require('vn-loopback/server/server').models;
const UserError = require('vn-loopback/util/user-error');
describe('order new()', () => {
let orderId;
afterAll(async() => {
await app.models.Order.destroyById(orderId);
});
it('should throw an error if the client isnt active', async() => {
const tx = await models.Order.beginTransaction({});
let error;
let landed = new Date();
let addressFk = 6;
let agencyModeFk = 1;
try {
const options = {transaction: tx};
await app.models.Order.new(landed, addressFk, agencyModeFk)
.catch(e => {
error = e;
});
const landed = new Date();
const addressFk = 6;
const agencyModeFk = 1;
expect(error).toEqual(new UserError(`You can't create an order for a inactive client`));
await models.Order.new(landed, addressFk, agencyModeFk, options);
await tx.rollback();
} catch (e) {
await tx.rollback();
error = e;
}
expect(error).toEqual(new UserError(`You can't create an order for an inactive client`));
});
it('should now create a new order when all conditions are met', async() => {
let landed = new Date();
let addressFk = 121;
let agencyModeFk = 1;
const tx = await models.Order.beginTransaction({});
orderId = await app.models.Order.new(landed, addressFk, agencyModeFk);
try {
const options = {transaction: tx};
let highestOrderIdInFixtures = 3;
const landed = new Date();
const addressFk = 121;
const agencyModeFk = 1;
expect(orderId).toBeGreaterThan(highestOrderIdInFixtures);
orderId = await models.Order.new(landed, addressFk, agencyModeFk, options);
const highestOrderIdInFixtures = 3;
expect(orderId).toBeGreaterThan(highestOrderIdInFixtures);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
});

View File

@ -0,0 +1,24 @@
const models = require('vn-loopback/server/server').models;
describe('order newFromTicket()', () => {
it('should create a new order from an existing ticket', async() => {
const tx = await models.Order.beginTransaction({});
try {
const options = {transaction: tx};
const ticketId = 11;
const orderId = await models.Order.newFromTicket(ticketId, options);
const highestOrderIdInFixtures = 3;
expect(orderId).toBeGreaterThan(highestOrderIdInFixtures);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
});

View File

@ -1,36 +1,91 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
describe('order summary()', () => {
it('should return a summary object containing data from 1 order', async() => {
let result = await app.models.Order.summary(1);
const tx = await models.Order.beginTransaction({});
expect(result.id).toEqual(1);
expect(result.clientFk).toEqual(1101);
try {
const options = {transaction: tx};
const result = await models.Order.summary(1, options);
expect(result.id).toEqual(1);
expect(result.clientFk).toEqual(1101);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
it('should return a summary object containing sales from 1 order', async() => {
let result = await app.models.Order.summary(1);
const tx = await models.Order.beginTransaction({});
expect(result.rows.length).toEqual(3);
try {
const options = {transaction: tx};
const result = await models.Order.summary(1, options);
expect(result.rows.length).toEqual(3);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
it('should return a summary object containing subTotal for 1 order', async() => {
let result = await app.models.Order.summary(1);
const tx = await models.Order.beginTransaction({});
expect(Math.round(result.subTotal * 100) / 100).toEqual(135.60);
try {
const options = {transaction: tx};
const result = await models.Order.summary(1, options);
expect(Math.round(result.subTotal * 100) / 100).toEqual(135.60);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
it('should return a summary object containing VAT for 1 order', async() => {
let result = await app.models.Order.summary(1);
const tx = await models.Order.beginTransaction({});
expect(Math.round(result.VAT * 100) / 100).toEqual(20.29);
try {
const options = {transaction: tx};
const result = await models.Order.summary(1, options);
expect(Math.round(result.VAT * 100) / 100).toEqual(20.29);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
it('should return a summary object containing total for 1 order', async() => {
let result = await app.models.Order.summary(1);
let total = result.subTotal + result.VAT;
let expectedTotal = Math.round(total * 100) / 100;
const tx = await models.Order.beginTransaction({});
expect(result.total).toEqual(expectedTotal);
try {
const options = {transaction: tx};
const result = await models.Order.summary(1, options);
const total = result.subTotal + result.VAT;
const expectedTotal = Math.round(total * 100) / 100;
expect(result.total).toEqual(expectedTotal);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
});

View File

@ -1,61 +1,93 @@
const app = require('vn-loopback/server/server');
const models = require('vn-loopback/server/server').models;
const UserError = require('vn-loopback/util/user-error');
describe('Order updateBasicData', () => {
const orderId = 21;
afterAll(async() => {
let validparams = {note: null};
await app.models.Order.updateBasicData(orderId, validparams);
});
it('should return an error if the order is confirmed', async() => {
const tx = await models.Order.beginTransaction({});
let error;
try {
const options = {transaction: tx};
const params = [];
const orderConfirmed = 1;
let params = [];
let orderConfirmed = 1;
await models.Order.updateBasicData(orderConfirmed, params, options);
await app.models.Order.updateBasicData(orderConfirmed, params)
.catch(e => {
error = e;
});
await tx.rollback();
} catch (e) {
await tx.rollback();
error = e;
}
const expectedError = `You can't make changes on the basic data of an confirmed order or with rows`;
expect(error.toString()).toContain(`You can't make changes on the basic data of an confirmed order or with rows`);
expect(error).toEqual(new UserError(expectedError));
});
it('should return an error if the order has rows', async() => {
const tx = await models.Order.beginTransaction({});
let error;
try {
const options = {transaction: tx};
let params = [];
let orderWithRows = 16;
const params = [];
const orderWithRows = 16;
await app.models.Order.updateBasicData(orderWithRows, params)
.catch(e => {
error = e;
});
await models.Order.updateBasicData(orderWithRows, params, options);
expect(error.toString()).toContain(`You can't make changes on the basic data of an confirmed order or with rows`);
await tx.rollback();
} catch (e) {
await tx.rollback();
error = e;
}
const expectedError = `You can't make changes on the basic data of an confirmed order or with rows`;
expect(error).toEqual(new UserError(expectedError));
});
it('should skip invalid params', async() => {
let success;
const tx = await models.Order.beginTransaction({});
let invalidparams = {invalid: 'param for update'};
try {
const options = {transaction: tx};
let success;
await app.models.Order.updateBasicData(orderId, invalidparams)
.then(() => success = true);
const invalidparams = {invalid: 'param for update'};
expect(success).toBeTruthy();
await models.Order.updateBasicData(orderId, invalidparams, options)
.then(() => success = true);
expect(success).toBeTruthy();
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
it('should update the client fiscal data and return the count if changes made', async() => {
let validparams = {note: 'test note'};
const tx = await models.Order.beginTransaction({});
let order = await app.models.Order.findById(orderId);
try {
const options = {transaction: tx};
expect(order.note).toEqual(null);
const validparams = {note: 'test note'};
let result = await app.models.Order.updateBasicData(orderId, validparams);
const order = await models.Order.findById(orderId, null, options);
expect(result.note).toEqual('test note');
expect(order.note).toEqual(null);
const result = await models.Order.updateBasicData(orderId, validparams, options);
expect(result.note).toEqual('test note');
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
});

View File

@ -19,17 +19,22 @@ module.exports = Self => {
}
});
Self.summary = async orderId => {
let models = Self.app.models;
let summary = await getOrderData(Self, orderId);
Self.summary = async(orderId, options) => {
const models = Self.app.models;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const summary = await getOrderData(Self, orderId, myOptions);
summary.subTotal = getSubTotal(summary.rows);
summary.VAT = await models.Order.getVAT(orderId);
summary.total = await models.Order.getTotal(orderId);
summary.VAT = await models.Order.getVAT(orderId, myOptions);
summary.total = await models.Order.getTotal(orderId, myOptions);
return summary;
};
async function getOrderData(Self, orderId) {
let filter = {
async function getOrderData(Self, orderId, options) {
const filter = {
include: [
{
relation: 'agencyMode', scope: {fields: ['name']}},
@ -69,7 +74,7 @@ module.exports = Self => {
where: {id: orderId}
};
return await Self.findOne(filter);
return Self.findOne(filter, options);
}
function getSubTotal(rows) {

View File

@ -31,16 +31,26 @@ module.exports = Self => {
}
});
Self.updateBasicData = async(id, params) => {
let models = Self.app.models;
Self.updateBasicData = async(id, params, options) => {
const models = Self.app.models;
const myOptions = {};
let tx;
let order = await models.Order.findById(id);
let orderRows = await models.OrderRow.find({where: {orderFk: id}});
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
const order = await models.Order.findById(id, null, myOptions);
const orderRows = await models.OrderRow.find({where: {orderFk: id}}, myOptions);
if (order.isConfirmed || orderRows.length != 0)
throw new UserError(`You can't make changes on the basic data of an confirmed order or with rows`);
let updateParams = pick(params, [
const updateParams = pick(params, [
'clientFk',
'addressFk',
'landed',
@ -48,8 +58,8 @@ module.exports = Self => {
'note',
]);
if (Object.keys(updateParams).length)
await order.updateAttributes(updateParams);
await order.updateAttributes(updateParams, myOptions);
return await order;
return order;
};
};

View File

@ -1,5 +1,5 @@
You can't create an order for a frozen client: No puedes crear una orden a un cliente congelado
You can't create an order for a inactive client: No puedes crear una orden a un cliente inactivo
You can't create an order for an inactive client: No puedes crear una orden a un cliente inactivo
You can't create an order for a client that doesn't has tax data verified:
No puedes crear una orden a un cliente cuyos datos fiscales no han sido verificados
You can't create an order for a client that has a debt: No puedes crear una orden a un cliente que tiene deuda