#1486 back test updateDiscount

This commit is contained in:
Carlos Jimenez Ruiz 2019-06-05 13:39:15 +02:00
parent 05fc1f08a8
commit 605dabbe19
11 changed files with 254 additions and 192 deletions

View File

@ -86,5 +86,8 @@
"The sales of the current ticket can't be modified": "Las lineas de este ticket no pueden ser modificadas", "The sales of the current ticket can't be modified": "Las lineas de este ticket no pueden ser modificadas",
"The sales of the receiver ticket can't be modified": "Las lineas del ticket al que envias no pueden ser modificadas", "The sales of the receiver ticket can't be modified": "Las lineas del ticket al que envias no pueden ser modificadas",
"NO_AGENCY_AVAILABLE": "No hay agencias disponibles", "NO_AGENCY_AVAILABLE": "No hay agencias disponibles",
"The current ticket can't be modified": "El ticket actual no puede ser modificado" "The current ticket can't be modified": "El ticket actual no puede ser modificado",
"The sales of this ticket can't be modified": "Las lineas de este ticket no pueden ser modificadas",
"Please select at least one sale": "Por favor selecciona al menos una linea",
"All sales must belong to the same ticket": "Todas las lineas deben pertenecer al mismo ticket"
} }

View File

@ -1,92 +0,0 @@
const app = require('vn-loopback/server/server');
// #1486 back test updateDiscount
xdescribe('sale updateDiscount()', () => {
const originalSaleId = 14;
let componentId;
let originalSale;
let saleComponentsRestore;
beforeAll(async done => {
originalSale = await app.models.Sale.findById(originalSaleId);
let manaDiscount = await app.models.ComponentRate.findOne({where: {code: 'mana'}});
componentId = manaDiscount.id;
saleComponentsRestore = await app.models.SaleComponent.findOne({
where: {
componentFk: componentId,
saleFk: originalSaleId
}
});
done();
});
afterAll(async done => {
originalSale.save();
saleComponentsRestore.save();
done();
});
it('should throw an error if any sale discount is not a number', async() => {
let error;
const ticketId = 1;
const sales = [
{discount: 'pepinillos'}
];
try {
await app.models.Sale.updateDiscount(ticketId, sales);
} catch (err) {
error = err;
}
expect(error.message).toEqual('The value should be a number');
});
it('should throw an error if the ticket is invoiced already', async() => {
let error;
const ticketId = 7;
const sales = [
{discount: 100}
];
try {
await app.models.Sale.updateDiscount(ticketId, sales);
} catch (err) {
error = err;
}
expect(error.message).toEqual(`The sales of this ticket can't be modified`);
});
it('should update the discount if the salesPerson has mana', async() => {
let createdSaleComponent = await app.models.SaleComponent.findOne({
where: {
componentFk: componentId,
saleFk: originalSaleId
}
});
expect(createdSaleComponent).toBeNull();
const ticketId = 8;
const sales = [
{
id: originalSaleId,
discount: 100}
];
await app.models.Sale.updateDiscount(ticketId, sales);
let updatedSale = await app.models.Sale.findById(originalSaleId);
createdSaleComponent = await app.models.SaleComponent.findOne({
where: {
componentFk: componentId,
saleFk: originalSaleId
}
});
expect(createdSaleComponent.componentFk).toEqual(componentId);
expect(updatedSale.discount).toEqual(100);
});
});

View File

@ -1,6 +1,5 @@
const app = require('vn-loopback/server/server'); const app = require('vn-loopback/server/server');
// #1489 updatePrice backTest
describe('sale updatePrice()', () => { describe('sale updatePrice()', () => {
let originalSale; let originalSale;
let originalSalesPersonMana; let originalSalesPersonMana;

View File

@ -1,73 +0,0 @@
let UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethod('updateDiscount', {
description: 'Changes the discount of a sale',
accessType: 'WRITE',
accepts: [{
arg: 'ticketFk',
type: 'number',
required: true,
description: 'ticket id',
}, {
arg: 'sales',
type: ['object'],
required: true,
description: 'sale ID, newDiscount, price, ticket',
}],
returns: {
type: 'string',
root: true
},
http: {
path: `/updateDiscount`,
verb: 'post'
}
});
Self.updateDiscount = async(ticketFk, sales) => {
const validDiscounts = sales.every(sale => {
return !isNaN(sale.discount);
});
if (!validDiscounts)
throw new UserError(`The value should be a number`);
let model = Self.app.models;
let ticket = await model.Ticket.findById(ticketFk, {
include: {
relation: 'client',
scope: {
fields: ['salesPersonFk']
}
},
});
if (ticket.refFk)
throw new UserError(`The sales of this ticket can't be modified`);
let manaDiscount;
let buyerDiscount = await model.ComponentRate.findOne({where: {code: 'buyerDiscount'}});
let usesMana = await model.WorkerMana.findOne({where: {workerFk: ticket.client().salesPersonFk}, fields: 'amount'});
let componentId = buyerDiscount.id;
if (usesMana) {
manaDiscount = await model.ComponentRate.findOne({where: {code: 'mana'}});
componentId = manaDiscount.id;
}
for (let i = 0; i < sales.length; i++) {
let currentLine = await model.Sale.findOne({where: {id: sales[i].id}, fields: 'price'});
let value = ((-currentLine.price * sales[i].discount) / 100);
await model.SaleComponent.upsert({saleFk: sales[i].id, value: value, componentFk: componentId});
await model.Sale.update({id: sales[i].id}, {discount: sales[i].discount});
}
if (usesMana) {
query = `call vn.manaSpellersRequery(?)`;
await Self.rawSql(query, [ticket.client().salesPersonFk]);
}
};
};

View File

@ -0,0 +1,102 @@
const app = require('vn-loopback/server/server');
describe('sale updateDiscount()', () => {
const originalSaleId = 14;
let componentId;
let originalSale;
let salesPersonMana;
beforeAll(async done => {
originalSale = await app.models.Sale.findById(originalSaleId);
let manaDiscount = await app.models.ComponentRate.findOne({where: {code: 'mana'}});
componentId = manaDiscount.id;
let ticket = await app.models.Ticket.findById(originalSale.ticketFk);
let client = await app.models.Client.findById(ticket.clientFk);
salesPersonMana = await app.models.WorkerMana.findById(client.salesPersonFk);
done();
});
afterAll(async done => {
await originalSale.save();
await createdSaleComponent.destroy();
await salesPersonMana.save();
done();
});
it('should throw an error if no sales were selected', async() => {
let error;
const ticketId = 8;
const sales = [];
const newDiscount = 10;
try {
await app.models.Ticket.updateDiscount(ticketId, sales, newDiscount);
} catch (err) {
error = err;
}
expect(error.message).toEqual('Please select at least one sale');
});
it('should throw an error if no sales belong to different tickets', async() => {
let error;
const ticketId = 8;
const sales = [1, 14];
const newDiscount = 10;
try {
await app.models.Ticket.updateDiscount(ticketId, sales, newDiscount);
} catch (err) {
error = err;
}
expect(error.message).toEqual('All sales must belong to the same ticket');
});
it('should throw an error if the ticket is invoiced already', async() => {
let error;
const ticketId = 7;
const sales = [22];
const newDiscount = 100;
try {
await app.models.Ticket.updateDiscount(ticketId, sales, newDiscount);
} catch (err) {
error = err;
}
expect(error.message).toEqual(`The sales of this ticket can't be modified`);
});
it('should update the discount if the salesPerson has mana', async() => {
createdSaleComponent = await app.models.SaleComponent.findOne({
where: {
componentFk: componentId,
saleFk: originalSaleId
}
});
expect(createdSaleComponent).toBeNull();
const ticketId = 8;
const sales = [originalSaleId];
const newDiscount = 100;
await app.models.Ticket.updateDiscount(ticketId, sales, newDiscount);
let updatedSale = await app.models.Sale.findById(originalSaleId);
createdSaleComponent = await app.models.SaleComponent.findOne({
where: {
componentFk: componentId,
saleFk: originalSaleId
}
});
expect(createdSaleComponent.componentFk).toEqual(componentId);
expect(updatedSale.discount).toEqual(100);
});
});

View File

@ -0,0 +1,121 @@
let UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethod('updateDiscount', {
description: 'Changes the discount of a sale',
accessType: 'WRITE',
accepts: [
{
arg: 'id',
description: 'The ticket id',
type: 'number',
required: true,
http: {source: 'path'}
},
{
arg: 'salesIds',
description: 'The sales id',
type: ['number'],
required: true,
}, {
arg: 'newDiscount',
description: 'The new discount',
type: 'number',
required: true
}
],
returns: {
type: 'string',
root: true
},
http: {
path: `/:id/updateDiscount`,
verb: 'post'
}
});
Self.updateDiscount = async(id, salesIds, newDiscount) => {
const models = Self.app.models;
const transaction = await Self.beginTransaction({});
const options = {transaction};
try {
const filter = {
fields: ['id', 'ticketFk', 'price'],
where: {
id: {inq: salesIds}
},
include: {
relation: 'ticket',
scope: {
include: {
relation: 'client',
scope: {
fields: ['salesPersonFk']
}
},
fields: ['id', 'clientFk']
}
}
};
let sales = await models.Sale.find(filter, options);
if (sales.length === 0)
throw new UserError('Please select at least one sale');
const allFromSameTicket = sales.every(sale => sale.ticketFk === id);
if (!allFromSameTicket)
throw new UserError('All sales must belong to the same ticket');
const isEditable = await models.Ticket.isEditable(id);
if (!isEditable)
throw new UserError(`The sales of this ticket can't be modified`);
const ticket = await models.Ticket.findById(id, {
include: {
relation: 'client',
scope: {
fields: ['salesPersonFk']
}
},
});
const salesPersonId = ticket.client().salesPersonFk;
const usesMana = await models.WorkerMana.findOne({
where: {
workerFk: salesPersonId
},
fields: 'amount'}, options);
const componentCode = usesMana ? 'mana' : 'buyerDiscount';
const discountComponent = await models.ComponentRate.findOne({
where: {code: componentCode}}, options);
const componentId = discountComponent.id;
let promises = [];
for (let sale of sales) {
const value = ((-sale.price * newDiscount) / 100);
const newComponent = models.SaleComponent.upsert({
saleFk: sale.id,
value: value,
componentFk: componentId}, options);
const updatedSale = models.Sale.update({id: sale.id},
{discount: newDiscount}, options);
promises.push([newComponent, updatedSale]);
}
await Promise.all(promises);
query = `call vn.manaSpellersRequery(?)`;
await Self.rawSql(query, [salesPersonId], options);
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
};
};

View File

@ -4,7 +4,6 @@ module.exports = Self => {
require('../methods/sale/moveToTicket')(Self); require('../methods/sale/moveToTicket')(Self);
require('../methods/sale/reserve')(Self); require('../methods/sale/reserve')(Self);
require('../methods/sale/removes')(Self); require('../methods/sale/removes')(Self);
require('../methods/sale/updateDiscount')(Self);
require('../methods/sale/updatePrice')(Self); require('../methods/sale/updatePrice')(Self);
require('../methods/sale/updateQuantity')(Self); require('../methods/sale/updateQuantity')(Self);
}; };

View File

@ -22,4 +22,5 @@ module.exports = Self => {
require('../methods/ticket/makeInvoice')(Self); require('../methods/ticket/makeInvoice')(Self);
require('../methods/ticket/updateEditableTicket')(Self); require('../methods/ticket/updateEditableTicket')(Self);
require('../methods/ticket/checkEmptiness')(Self); require('../methods/ticket/checkEmptiness')(Self);
require('../methods/ticket/updateDiscount')(Self);
}; };

View File

@ -34,19 +34,19 @@ class Controller {
} }
updateDiscount() { updateDiscount() {
let editLines = []; let salesIds = [];
let modified = false; let modified = false;
for (let i = 0; i < this.edit.length; i++) { for (let i = 0; i < this.edit.length; i++) {
if (this.newDiscount != this.edit[0].discount || this.bulk || !this.newDiscount) { if (this.newDiscount != this.edit[0].discount || this.bulk || !this.newDiscount) {
editLines.push({id: this.edit[i].id, discount: this.newDiscount}); salesIds.push(this.edit[i].id);
modified = true; modified = true;
} }
} }
if (modified) { if (modified) {
const ticketId = parseInt(this.$state.params.id); const params = {salesIds: salesIds, newDiscount: this.newDiscount};
const params = {ticketFk: ticketId, sales: editLines}; const query = `/api/Tickets/${this.$state.params.id}/updateDiscount`;
this.$http.post(`/ticket/api/Sales/updateDiscount`, params).then(() => { this.$http.post(query, params).then(() => {
this.vnApp.showSuccess(this.$translate.instant('Data saved!')); this.vnApp.showSuccess(this.$translate.instant('Data saved!'));
this.clear(); this.clear();
modified = false; modified = false;

View File

@ -18,9 +18,9 @@ describe('Ticket', () => {
}; };
}}; }};
$state = _$state_; $state = _$state_;
$state.params.id = 1; $state.params.id = 11;
controller = $componentController('vnTicketSaleEditDiscount', {$scope, $state}); controller = $componentController('vnTicketSaleEditDiscount', {$scope, $state});
controller._edit = [{id: 3, discount: 15}]; controller._edit = [{id: 3}];
controller.onHide = () => {}; controller.onHide = () => {};
})); }));
@ -58,14 +58,16 @@ describe('Ticket', () => {
controller.bulk = true; controller.bulk = true;
controller.newDiscount = 15; controller.newDiscount = 15;
$httpBackend.expectPOST(`/ticket/api/Sales/updateDiscount`).respond(); $httpBackend.expectPOST(`/api/Tickets/11/updateDiscount`).respond();
controller.updateDiscount(); controller.updateDiscount();
$httpBackend.flush(); $httpBackend.flush();
}); });
it('should call vnApp.showError if the discount value hasnt has been modified and the bulk value is false', () => { it(`should throw if there's no changes on discount and it isn't bulk`, () => {
controller.bulk = false; controller.bulk = false;
controller.newDiscount = 15;
controller.edit = [{discount: 15}];
spyOn(controller.vnApp, 'showError'); spyOn(controller.vnApp, 'showError');
controller.updateDiscount(); controller.updateDiscount();