more tests fixed + small refactors

This commit is contained in:
Carlos Jimenez Ruiz 2020-10-08 16:00:19 +02:00
parent 641eb93282
commit b6b84cfea7
24 changed files with 411 additions and 326 deletions

View File

@ -1,6 +1,6 @@
const app = require('vn-loopback/server/server'); const app = require('vn-loopback/server/server');
describe('updateCollectionSale()', () => { // #2495 updateCollectionSale reparar polución de unitarios
it('return a new collection', async() => { it('return a new collection', async() => {
let ctx = {req: {accessToken: {userId: 106}}}; let ctx = {req: {accessToken: {userId: 106}}};
let response = await app.models.Collection.updateCollectionSale(ctx, 1, 5, 5, 5, 1, 4, false, 'UXN', 1, 1); let response = await app.models.Collection.updateCollectionSale(ctx, 1, 5, 5, 5, 1, 4, false, 'UXN', 1, 1);

View File

@ -32,7 +32,7 @@ describe('Item regularize path', () => {
expect(userLocalWarehouse).toContain('Warehouse Four'); expect(userLocalWarehouse).toContain('Warehouse Four');
}); });
it('should search for an specific item', async() => { it('should search for a specific item', async() => {
await page.accessToSearchResult('Ranged weapon pistol 9mm'); await page.accessToSearchResult('Ranged weapon pistol 9mm');
await page.waitForState('item.card.summary'); await page.waitForState('item.card.summary');
}); });

View File

@ -1,10 +1,17 @@
const app = require('vn-loopback/server/server'); const app = require('vn-loopback/server/server');
const LoopBackContext = require('loopback-context');
describe('claimBeginning', () => { describe('claimBeginning', () => {
const salesAssistantId = 21;
let ticket; let ticket;
let refundTicketSales; let refundTicketSales;
let salesInsertedInClaimEnd; let salesInsertedInClaimEnd;
const activeCtx = {
accessToken: {userId: salesAssistantId},
};
const ctx = {req: activeCtx};
afterAll(async() => { afterAll(async() => {
let promises = []; let promises = [];
promises.push(app.models.Ticket.destroyById(ticket.id)); promises.push(app.models.Ticket.destroyById(ticket.id));
@ -16,9 +23,11 @@ describe('claimBeginning', () => {
describe('importToNewRefundTicket()', () => { describe('importToNewRefundTicket()', () => {
it('should create a new ticket with negative sales and insert the negative sales into claimEnd', async() => { it('should create a new ticket with negative sales and insert the negative sales into claimEnd', async() => {
let ctxOfSalesAssistant = {req: {accessToken: {userId: 21}}}; spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
active: activeCtx
});
let claimId = 1; let claimId = 1;
ticket = await app.models.ClaimBeginning.importToNewRefundTicket(ctxOfSalesAssistant, claimId); ticket = await app.models.ClaimBeginning.importToNewRefundTicket(ctx, claimId);
await app.models.Ticket.findById(ticket.id); await app.models.Ticket.findById(ticket.id);

View File

@ -1,6 +1,17 @@
const app = require('vn-loopback/server/server'); const app = require('vn-loopback/server/server');
describe('regularizeClaim()', () => { describe('regularizeClaim()', () => {
const ctx = {
req: {
accessToken: {userId: 18},
headers: {origin: 'http://localhost'}
}
};
ctx.req.__ = (value, params) => {
return params.nickname;
};
const chatModel = app.models.Chat;
const claimFk = 1; const claimFk = 1;
const pendentState = 1; const pendentState = 1;
const resolvedState = 3; const resolvedState = 3;
@ -10,33 +21,27 @@ describe('regularizeClaim()', () => {
let claimEnds = []; let claimEnds = [];
let trashTicket; let trashTicket;
afterAll(async done => { afterEach(async done => {
let claim = await app.models.Claim.findById(claimFk); try {
await claim.updateAttributes({ let claim = await app.models.Claim.findById(claimFk);
claimStateFk: pendentState, await claim.updateAttributes({
hasToPickUp: false claimStateFk: pendentState,
}); hasToPickUp: false
await app.models.Ticket.destroyById(trashTicket.id); });
claimEnds.forEach(async line => { for (claimEnd of claimEnds)
await line.destroy(); await claimEnd.destroy();
});
if (trashTicket)
await app.models.Ticket.destroyById(trashTicket.id);
} catch (error) {
console.error(error);
}
done(); done();
}); });
it('should send a chat message with value "Trash" and then change claim state to resolved', async() => { it('should send a chat message with value "Trash" and then change claim state to resolved', async() => {
const ctx = {
req: {
accessToken: {userId: 18},
headers: {origin: 'http://localhost'}
}
};
ctx.req.__ = (value, params) => {
return params.nickname;
};
const chatModel = app.models.Chat;
spyOn(chatModel, 'sendCheckingPresence').and.callThrough(); spyOn(chatModel, 'sendCheckingPresence').and.callThrough();
claimEnds = await app.models.ClaimEnd.importTicketSales(ctx, { claimEnds = await app.models.ClaimEnd.importTicketSales(ctx, {
@ -61,23 +66,16 @@ describe('regularizeClaim()', () => {
}); });
it('should send a chat message with value "Bueno" and then change claim state to resolved', async() => { it('should send a chat message with value "Bueno" and then change claim state to resolved', async() => {
const ctx = {
req: {
accessToken: {userId: 18},
headers: {origin: 'http://localhost'}
}
};
ctx.req.__ = (value, params) => {
return params.nickname;
};
const chatModel = app.models.Chat;
spyOn(chatModel, 'sendCheckingPresence').and.callThrough(); spyOn(chatModel, 'sendCheckingPresence').and.callThrough();
claimEnds.forEach(async claimEnd => { claimEnds = await app.models.ClaimEnd.importTicketSales(ctx, {
claimEnd.updateAttributes({claimDestinationFk: okDestination}); claimFk: claimFk,
ticketFk: 1
}); });
for (claimEnd of claimEnds)
await claimEnd.updateAttributes({claimDestinationFk: okDestination});
await app.models.Claim.regularizeClaim(ctx, claimFk); await app.models.Claim.regularizeClaim(ctx, claimFk);
expect(chatModel.sendCheckingPresence).toHaveBeenCalledWith(ctx, 18, 'Bueno'); expect(chatModel.sendCheckingPresence).toHaveBeenCalledWith(ctx, 18, 'Bueno');
@ -85,23 +83,16 @@ describe('regularizeClaim()', () => {
}); });
it('should send a chat message to the salesPerson when claim isPickUp is enabled', async() => { it('should send a chat message to the salesPerson when claim isPickUp is enabled', async() => {
const ctx = {
req: {
accessToken: {userId: 18},
headers: {origin: 'http://localhost'}
}
};
ctx.req.__ = (value, params) => {
return params.nickname;
};
const chatModel = app.models.Chat;
spyOn(chatModel, 'sendCheckingPresence').and.callThrough(); spyOn(chatModel, 'sendCheckingPresence').and.callThrough();
claimEnds.forEach(async claimEnd => { claimEnds = await app.models.ClaimEnd.importTicketSales(ctx, {
claimEnd.updateAttributes({claimDestinationFk: okDestination}); claimFk: claimFk,
ticketFk: 1
}); });
for (claimEnd of claimEnds)
await claimEnd.updateAttributes({claimDestinationFk: okDestination});
await app.models.Claim.regularizeClaim(ctx, claimFk); await app.models.Claim.regularizeClaim(ctx, claimFk);
expect(chatModel.sendCheckingPresence).toHaveBeenCalledWith(ctx, 18, 'Bueno'); expect(chatModel.sendCheckingPresence).toHaveBeenCalledWith(ctx, 18, 'Bueno');

View File

@ -2,8 +2,7 @@ const app = require('vn-loopback/server/server');
describe('Update Claim', () => { describe('Update Claim', () => {
let newDate = new Date(); let newDate = new Date();
let newInstance; let originalData = {
let original = {
ticketFk: 3, ticketFk: 3,
clientFk: 101, clientFk: 101,
ticketCreated: newDate, ticketCreated: newDate,
@ -14,19 +13,8 @@ describe('Update Claim', () => {
observation: 'observation' observation: 'observation'
}; };
beforeAll(async done => {
newInstance = await app.models.Claim.create(original);
done();
});
afterAll(async done => {
await app.models.Claim.destroyById(newInstance.id);
done();
});
it(`should throw an error as the user doesn't have rights`, async() => { it(`should throw an error as the user doesn't have rights`, async() => {
let newClaim = await app.models.Claim.create(originalData);
const forbiddenState = 3; const forbiddenState = 3;
const salesPersonId = 18; const salesPersonId = 18;
let data = { let data = {
@ -40,15 +28,20 @@ describe('Update Claim', () => {
} }
} }
}; };
await app.models.Claim.updateClaim(ctx, newInstance.id, data) await app.models.Claim.updateClaim(ctx, newClaim.id, data)
.catch(e => { .catch(e => {
error = e; error = e;
}); });
expect(error.message).toEqual(`You don't have enough privileges to change that field`); expect(error.message).toEqual(`You don't have enough privileges to change that field`);
// restores
await app.models.Claim.destroyById(newClaim.id);
}); });
it(`should success to update the claim within privileges `, async() => { it(`should success to update the claim within privileges `, async() => {
let newClaim = await app.models.Claim.create(originalData);
const correctState = 4; const correctState = 4;
const salesPersonId = 18; const salesPersonId = 18;
let data = { let data = {
@ -63,14 +56,18 @@ describe('Update Claim', () => {
} }
} }
}; };
await app.models.Claim.updateClaim(ctx, newInstance.id, data); await app.models.Claim.updateClaim(ctx, newClaim.id, data);
let claimUpdated = await app.models.Claim.findById(newInstance.id); let updatedClaim = await app.models.Claim.findById(newClaim.id);
expect(claimUpdated.observation).toEqual(data.observation); expect(updatedClaim.observation).toEqual(data.observation);
// restores
await app.models.Claim.destroyById(newClaim.id);
}); });
it('should change some sensible fields as salesAssistant', async() => { it('should change some sensible fields as salesAssistant', async() => {
let newClaim = await app.models.Claim.create(originalData);
const chatModel = app.models.Chat; const chatModel = app.models.Chat;
spyOn(chatModel, 'sendCheckingPresence').and.callThrough(); spyOn(chatModel, 'sendCheckingPresence').and.callThrough();
@ -90,13 +87,16 @@ describe('Update Claim', () => {
ctx.req.__ = (value, params) => { ctx.req.__ = (value, params) => {
return params.nickname; return params.nickname;
}; };
await app.models.Claim.updateClaim(ctx, newInstance.id, data); await app.models.Claim.updateClaim(ctx, newClaim.id, data);
let claimUpdated = await app.models.Claim.findById(newInstance.id); let updatedClaim = await app.models.Claim.findById(newClaim.id);
expect(claimUpdated.observation).toEqual(data.observation); expect(updatedClaim.observation).toEqual(data.observation);
expect(claimUpdated.claimStateFk).toEqual(data.claimStateFk); expect(updatedClaim.claimStateFk).toEqual(data.claimStateFk);
expect(claimUpdated.workerFk).toEqual(data.workerFk); expect(updatedClaim.workerFk).toEqual(data.workerFk);
expect(chatModel.sendCheckingPresence).toHaveBeenCalled(); expect(chatModel.sendCheckingPresence).toHaveBeenCalled();
// restores
await app.models.Claim.destroyById(newClaim.id);
}); });
}); });

View File

@ -4,13 +4,20 @@ describe('Client Create', () => {
const clientName = 'Wade'; const clientName = 'Wade';
const AccountName = 'Deadpool'; const AccountName = 'Deadpool';
afterAll(async done => { afterEach(async done => {
let address = await app.models.Address.findOne({where: {nickname: clientName}}); let address = await app.models.Address.findOne({where: {nickname: clientName}});
let client = await app.models.Client.findOne({where: {name: clientName}}); let client = await app.models.Client.findOne({where: {name: clientName}});
let account = await app.models.Account.findOne({where: {name: AccountName}}); let account = await app.models.Account.findOne({where: {name: AccountName}});
await app.models.Address.destroyById(address.id);
await app.models.Client.destroyById(client.id); if (address && client && account) {
await app.models.Account.destroyById(account.id); try {
await app.models.Address.destroyById(address.id);
await app.models.Client.destroyById(client.id);
await app.models.Account.destroyById(account.id);
} catch (error) {
console.error(error);
}
}
done(); done();
}); });
@ -46,13 +53,8 @@ describe('Client Create', () => {
expect(client.socialName).toEqual(newAccount.socialName); expect(client.socialName).toEqual(newAccount.socialName);
}); });
it('should find an existing account', async() => {
let account = await app.models.Account.findOne({where: {name: newAccount.userName}});
expect(account.name).toEqual(newAccount.userName);
});
it('should not be able to create a user if exists', async() => { it('should not be able to create a user if exists', async() => {
await app.models.Client.createWithUser(newAccount);
try { try {
let client = await app.models.Client.createWithUser(newAccount); let client = await app.models.Client.createWithUser(newAccount);

View File

@ -137,3 +137,4 @@ describe('Buy latests buys filter()', () => {
expect(results.length).toBe(1); expect(results.length).toBe(1);
}); });
}); });

View File

@ -1,20 +1,14 @@
const app = require('vn-loopback/server/server'); const app = require('vn-loopback/server/server');
const LoopBackContext = require('loopback-context');
describe('invoiceOut delete()', () => { describe('invoiceOut delete()', () => {
const invoiceOutId = 2; const invoiceOutId = 2;
let originalInvoiceOut; let originalInvoiceOut;
let originalTicket; let originalTicket;
const userId = 106;
afterAll(async done => { const activeCtx = {
const newInvoiceOut = await app.models.InvoiceOut.create(originalInvoiceOut); accessToken: {userId: userId},
await newInvoiceOut.updateAttribute('ref', originalInvoiceOut.ref); };
const promises = [];
promises.push(originalTicket.updateAttribute('refFk', newInvoiceOut.ref));
Promise.all(promises);
done();
});
it('should check that there is one ticket in the target invoiceOut', async() => { it('should check that there is one ticket in the target invoiceOut', async() => {
const invoiceOut = await app.models.InvoiceOut.findById(invoiceOutId); const invoiceOut = await app.models.InvoiceOut.findById(invoiceOutId);
@ -25,6 +19,9 @@ describe('invoiceOut delete()', () => {
}); });
it(`should delete the target invoiceOut then check the ticket doesn't have a refFk anymore`, async() => { it(`should delete the target invoiceOut then check the ticket doesn't have a refFk anymore`, async() => {
spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
active: activeCtx
});
originalInvoiceOut = await app.models.InvoiceOut.findById(invoiceOutId); originalInvoiceOut = await app.models.InvoiceOut.findById(invoiceOutId);
await app.models.InvoiceOut.delete(invoiceOutId); await app.models.InvoiceOut.delete(invoiceOutId);
originalTicket = await app.models.Ticket.findById(3); originalTicket = await app.models.Ticket.findById(3);
@ -32,5 +29,10 @@ describe('invoiceOut delete()', () => {
expect(deletedInvoiceOut).toBeNull(); expect(deletedInvoiceOut).toBeNull();
expect(originalTicket.refFk).toBeNull(); expect(originalTicket.refFk).toBeNull();
// restores
const restoredInvoiceOut = await app.models.InvoiceOut.create(originalInvoiceOut);
await restoredInvoiceOut.updateAttribute('ref', originalInvoiceOut.ref);
await originalTicket.updateAttribute('refFk', restoredInvoiceOut.ref);
}); });
}); });

View File

@ -4,16 +4,6 @@ describe('invoiceOut regenerate()', () => {
const invoiceReportFk = 30; const invoiceReportFk = 30;
const invoiceOutId = 1; const invoiceOutId = 1;
afterAll(async done => {
const invoiceOut = await app.models.InvoiceOut.findById(invoiceOutId);
await invoiceOut.updateAttributes({hasPdf: true});
await app.models.InvoiceOut.rawSql(`
DELETE FROM vn.printServerQueue
WHERE reportFk = ?`, [invoiceReportFk]);
done();
});
it('should check that the invoice has a PDF and is not in print generation queue', async() => { it('should check that the invoice has a PDF and is not in print generation queue', async() => {
const invoiceOut = await app.models.InvoiceOut.findById(invoiceOutId); const invoiceOut = await app.models.InvoiceOut.findById(invoiceOutId);
const [queue] = await app.models.InvoiceOut.rawSql(` const [queue] = await app.models.InvoiceOut.rawSql(`
@ -35,5 +25,12 @@ describe('invoiceOut regenerate()', () => {
expect(invoiceOut.hasPdf).toBeFalsy(); expect(invoiceOut.hasPdf).toBeFalsy();
expect(queue.total).toEqual(1); expect(queue.total).toEqual(1);
// restores
const invoiceOutToRestore = await app.models.InvoiceOut.findById(invoiceOutId);
await invoiceOutToRestore.updateAttributes({hasPdf: true});
await app.models.InvoiceOut.rawSql(`
DELETE FROM vn.printServerQueue
WHERE reportFk = ?`, [invoiceReportFk]);
}); });
}); });

View File

@ -1,13 +1,7 @@
const app = require('vn-loopback/server/server'); const app = require('vn-loopback/server/server');
describe('item updateTaxes()', () => { describe('item updateTaxes()', () => {
afterAll(async done => { let taxesInFixtures = [{id: 3, taxClassFk: 1}];
let taxesInFixtures = [{id: 3, taxClassFk: 1}];
await app.models.Item.updateTaxes(taxesInFixtures);
done();
});
it('should throw an error if the taxClassFk is blank', async() => { it('should throw an error if the taxClassFk is blank', async() => {
let error; let error;
@ -29,14 +23,12 @@ describe('item updateTaxes()', () => {
let taxes = [{id: 3, taxClassFk: 2}]; let taxes = [{id: 3, taxClassFk: 2}];
let result = await app.models.Item.updateTaxes(taxes); await app.models.Item.updateTaxes(taxes);
taxCountry = await app.models.ItemTaxCountry.findById(3);
expect(result).toBeTruthy();
});
it('should confirm the tax class was updated', async() => {
let taxCountry = await app.models.ItemTaxCountry.findById(3);
expect(taxCountry.taxClassFk).toEqual(2); expect(taxCountry.taxClassFk).toEqual(2);
// restores
await app.models.Item.updateTaxes(taxesInFixtures);
}); });
}); });

View File

@ -14,18 +14,9 @@ describe('route guessPriority()', () => {
done(); done();
}); });
it('should confirm the tickets in the target route have no priority yet', async() => { it('should call guessPriority() and then check the tickets in the target route now have their priorities defined', async() => {
routeTicketsToRestore = await app.models.Ticket.find({where: {routeFk: targetRouteId}}); routeTicketsToRestore = await app.models.Ticket.find({where: {routeFk: targetRouteId}});
expect(routeTicketsToRestore.length).toEqual(2);
expect(routeTicketsToRestore[0].id).toEqual(23);
expect(routeTicketsToRestore[0].priority).toBeNull();
expect(routeTicketsToRestore[1].id).toEqual(24);
expect(routeTicketsToRestore[1].priority).toBeNull();
});
it('should call guessPriority() and then check the tickets in the target route now have their priorities defined', async() => {
await app.models.Route.guessPriority(targetRouteId); await app.models.Route.guessPriority(targetRouteId);
let routeTickets = await app.models.Ticket.find({where: {routeFk: targetRouteId}, fields: ['id', 'priority']}); let routeTickets = await app.models.Ticket.find({where: {routeFk: targetRouteId}, fields: ['id', 'priority']});

View File

@ -1,46 +1,43 @@
const app = require('vn-loopback/server/server'); const app = require('vn-loopback/server/server');
const LoopBackContext = require('loopback-context');
describe('route updateVolume()', () => { describe('route updateVolume()', () => {
const routeId = 1; const routeId = 1;
const workerFk = 9; const userId = 50;
const ctx = {req: {accessToken: {userId: workerFk}}}; const activeCtx = {
let originalRoute; accessToken: {userId: userId},
let ticketToRestore; };
let logIdToDestroy; const ctx = {req: activeCtx};
afterAll(async done => { it('should confirm the route volume is updated and logged when a ticket is added', async() => {
await originalRoute.updateAttributes({m3: 1.8}); spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
await ticketToRestore.updateAttributes({routeFk: null}); active: activeCtx
await app.models.RouteLog.destroyById(logIdToDestroy); });
done(); const route = await app.models.Route.findById(routeId);
});
it('should confirm the original volume of the route is the expected', async() => { expect(route.m3).toEqual(1.8);
originalRoute = await app.models.Route.findById(routeId);
expect(originalRoute.m3).toEqual(1.8); const ticket = await app.models.Ticket.findById(14);
});
it('should confirm the route volume is updated when a ticket is added', async() => { await ticket.updateAttributes({routeFk: routeId});
ticketToRestore = await app.models.Ticket.findById(14);
let updatedTicket = await app.models.Ticket.findById(14);
await updatedTicket.updateAttributes({routeFk: routeId});
await app.models.Route.updateVolume(ctx, routeId); await app.models.Route.updateVolume(ctx, routeId);
let updatedRoute = await app.models.Route.findById(routeId); const updatedRoute = await app.models.Route.findById(routeId);
expect(updatedRoute.m3).not.toEqual(originalRoute.m3); expect(updatedRoute.m3).not.toEqual(route.m3);
});
it('should confirm the change is logged', async() => { const logs = await app.models.RouteLog.find({fields: ['id', 'newInstance']});
let logs = await app.models.RouteLog.find({fields: ['id', 'newInstance']});
let m3Log = logs.filter(log => { const m3Log = logs.filter(log => {
return log.newInstance.m3 === 1.9; return log.newInstance.m3 === updatedRoute.m3;
}); });
logIdToDestroy = m3Log[0].id; const logIdToDestroy = m3Log[0].id;
expect(m3Log.length).toEqual(1); expect(m3Log.length).toEqual(1);
// restores
await ticket.updateAttributes({routeFk: null});
await route.updateAttributes({m3: 1.8});
await app.models.RouteLog.destroyById(logIdToDestroy);
}); });
}); });

View File

@ -2,12 +2,12 @@ const app = require('vn-loopback/server/server');
describe('sale deleteSales()', () => { describe('sale deleteSales()', () => {
let sale; let sale;
let newsale; let newSale;
beforeAll(async done => { beforeAll(async done => {
sale = await app.models.Sale.findOne({where: {id: 9}}); sale = await app.models.Sale.findOne({where: {id: 9}});
sale.id = null; sale.id = null;
newsale = await app.models.Sale.create(sale); newSale = await app.models.Sale.create(sale);
done(); done();
}); });
@ -31,7 +31,7 @@ describe('sale deleteSales()', () => {
it('should delete the sales', async() => { it('should delete the sales', async() => {
let ctx = {req: {accessToken: {userId: 9}}}; let ctx = {req: {accessToken: {userId: 9}}};
const sales = [{id: newsale.id, instance: 0}]; const sales = [{id: newSale.id, instance: 0}];
const ticketId = 16; const ticketId = 16;
let res = await app.models.Sale.deleteSales(ctx, sales, ticketId); let res = await app.models.Sale.deleteSales(ctx, sales, ticketId);

View File

@ -16,14 +16,6 @@ describe('sale updatePrice()', () => {
done(); done();
}); });
afterAll(async done => {
await originalSale.save();
await app.models.SaleComponent.updateAll({componentFk: manaComponentId, saleFk: saleId}, {value: 0});
await originalSalesPersonMana.save();
done();
});
it('should throw an error if the ticket is not editable', async() => { it('should throw an error if the ticket is not editable', async() => {
let ctx = {req: {accessToken: {userId: 18}}}; let ctx = {req: {accessToken: {userId: 18}}};
let immutableSaleId = 1; let immutableSaleId = 1;
@ -43,36 +35,49 @@ describe('sale updatePrice()', () => {
let price = ''; let price = '';
await app.models.Sale.updatePrice(ctx, saleId, price); await app.models.Sale.updatePrice(ctx, saleId, price);
let saleUpdated = await app.models.Sale.findById(saleId); let updatedSale = await app.models.Sale.findById(saleId);
expect(saleUpdated.price).toEqual(0); expect(updatedSale.price).toEqual(0);
// restores
await originalSale.updateAttributes(originalSale);
await app.models.SaleComponent.updateAll({componentFk: manaComponentId, saleFk: saleId}, {value: 0});
await originalSalesPersonMana.updateAttributes(originalSalesPersonMana);
}); });
it('should now set price as a decimal number in a string', async() => { it('should now set price as a number in a string', async() => {
let ctx = {req: {accessToken: {userId: 18}}}; let ctx = {req: {accessToken: {userId: 18}}};
let price = '8'; let price = '8';
await app.models.Sale.updatePrice(ctx, saleId, price); await app.models.Sale.updatePrice(ctx, saleId, price);
let saleUpdated = await app.models.Sale.findById(saleId); let updatedSale = await app.models.Sale.findById(saleId);
expect(saleUpdated.price).toEqual(8); expect(updatedSale.price).toEqual(8);
// restores
await originalSale.updateAttributes(originalSale);
await app.models.SaleComponent.updateAll({componentFk: manaComponentId, saleFk: saleId}, {value: 0});
await originalSalesPersonMana.updateAttributes(originalSalesPersonMana);
}); });
it('should set price as a decimal number and check the sale has the mana component', async() => { it('should set price as a decimal number and check the sale has the mana component changing the salesPersonMana', async() => {
let ctx = {req: {accessToken: {userId: 18}}}; let ctx = {req: {accessToken: {userId: 18}}};
let price = 5.4; let price = 5.4;
await app.models.Sale.updatePrice(ctx, saleId, price); await app.models.Sale.updatePrice(ctx, saleId, price);
let saleUpdated = await app.models.Sale.findById(saleId); let updatedSale = await app.models.Sale.findById(saleId);
createdSaleComponent = await app.models.SaleComponent.findOne({where: {saleFk: saleId, componentFk: manaComponentId}}); createdSaleComponent = await app.models.SaleComponent.findOne({where: {saleFk: saleId, componentFk: manaComponentId}});
expect(saleUpdated.price).toBe(price); expect(updatedSale.price).toBe(price);
expect(createdSaleComponent.value).toEqual(-2.04); expect(createdSaleComponent.value).toEqual(-2.04);
});
it('should check that the mana of salesPerson changed', async() => {
let updatedSalesPersonMana = await app.models.WorkerMana.findById(18); let updatedSalesPersonMana = await app.models.WorkerMana.findById(18);
expect(updatedSalesPersonMana.amount).not.toEqual(originalSalesPersonMana.amount); expect(updatedSalesPersonMana.amount).not.toEqual(originalSalesPersonMana.amount);
// restores
await originalSale.updateAttributes(originalSale);
await app.models.SaleComponent.updateAll({componentFk: manaComponentId, saleFk: saleId}, {value: 0});
await originalSalesPersonMana.updateAttributes(originalSalesPersonMana);
}); });
}); });

View File

@ -1,9 +1,23 @@
const app = require('vn-loopback/server/server'); const app = require('vn-loopback/server/server');
const LoopBackContext = require('loopback-context');
describe('ticket changeState()', () => { describe('ticket changeState()', () => {
const salesPersonId = 18;
const employeeId = 1;
const productionId = 49;
let activeCtx = {
accessToken: {userId: 9},
};
let ctx = {req: activeCtx};
let ticket; let ticket;
beforeAll(async done => { beforeAll(async done => {
spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
active: activeCtx
});
});
beforeEach(async done => {
let originalTicket = await app.models.Ticket.findOne({where: {id: 16}}); let originalTicket = await app.models.Ticket.findOne({where: {id: 16}});
originalTicket.id = null; originalTicket.id = null;
ticket = await app.models.Ticket.create(originalTicket); ticket = await app.models.Ticket.create(originalTicket);
@ -18,7 +32,7 @@ describe('ticket changeState()', () => {
}); });
it('should throw if the ticket is not editable and the user isnt production', async() => { it('should throw if the ticket is not editable and the user isnt production', async() => {
let ctx = {req: {accessToken: {userId: 18}}}; activeCtx.accessToken.userId = salesPersonId;
let params = {ticketFk: 2, stateFk: 3}; let params = {ticketFk: 2, stateFk: 3};
let errCode; let errCode;
@ -32,7 +46,7 @@ describe('ticket changeState()', () => {
}); });
it('should throw an error if a worker with employee role attemps to a forbidden state', async() => { it('should throw an error if a worker with employee role attemps to a forbidden state', async() => {
let ctx = {req: {accessToken: {userId: 1}}}; activeCtx.accessToken.userId = employeeId;
let params = {ticketFk: 11, stateFk: 13}; let params = {ticketFk: 11, stateFk: 13};
let errCode; let errCode;
@ -46,29 +60,21 @@ describe('ticket changeState()', () => {
}); });
it('should be able to create a ticket tracking line for a not editable ticket if the user has the production role', async() => { it('should be able to create a ticket tracking line for a not editable ticket if the user has the production role', async() => {
let ctx = {req: {accessToken: {userId: 49}}}; activeCtx.accessToken.userId = productionId;
let params = {ticketFk: ticket.id, stateFk: 3}; let params = {ticketFk: ticket.id, stateFk: 3};
let res = await app.models.TicketTracking.changeState(ctx, params); let ticketTracking = await app.models.TicketTracking.changeState(ctx, params);
expect(res.__data.ticketFk).toBe(params.ticketFk); expect(ticketTracking.__data.ticketFk).toBe(params.ticketFk);
expect(res.__data.stateFk).toBe(params.stateFk); expect(ticketTracking.__data.stateFk).toBe(params.stateFk);
expect(res.__data.workerFk).toBe(49); expect(ticketTracking.__data.workerFk).toBe(49);
expect(res.__data.id).toBeDefined(); expect(ticketTracking.__data.id).toBeDefined();
// restores
await app.models.TicketTracking.destroyById(ticketTracking.__data.id);
}); });
it('should return an array with the created ticket tracking line', async() => { it('should update the ticket tracking line when the user is salesperson, uses the state assigned and a valid worker id', async() => {
let ctx = {req: {accessToken: {userId: 49}}};
let params = {ticketFk: ticket.id, stateFk: 3};
let res = await app.models.TicketTracking.changeState(ctx, params);
expect(res.__data.ticketFk).toBe(params.ticketFk);
expect(res.__data.stateFk).toBe(params.stateFk);
expect(res.__data.workerFk).toBe(49);
expect(res.__data.id).toBeDefined();
});
it('should return an array with the created ticket tracking line when the user is salesperson, uses the state assigned and thes a workerFk given', async() => {
let ctx = {req: {accessToken: {userId: 18}}}; let ctx = {req: {accessToken: {userId: 18}}};
let assignedState = await app.models.State.findOne({where: {code: 'PICKER_DESIGNED'}}); let assignedState = await app.models.State.findOne({where: {code: 'PICKER_DESIGNED'}});
let params = {ticketFk: ticket.id, stateFk: assignedState.id, workerFk: 1}; let params = {ticketFk: ticket.id, stateFk: assignedState.id, workerFk: 1};

View File

@ -1,24 +1,42 @@
const app = require('vn-loopback/server/server'); const app = require('vn-loopback/server/server');
const LoopBackContext = require('loopback-context');
describe('ticket setDelivered()', () => { describe('ticket setDelivered()', () => {
const userId = 50;
const activeCtx = {
accessToken: {userId: userId},
};
let ticketOne; let ticketOne;
let ticketTwo; let ticketTwo;
beforeAll(async done => { beforeAll(async done => {
let originalTicketOne = await app.models.Ticket.findById(8); spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
let originalTicketTwo = await app.models.Ticket.findById(10); active: activeCtx
});
try {
let originalTicketOne = await app.models.Ticket.findById(8);
let originalTicketTwo = await app.models.Ticket.findById(10);
originalTicketOne.id = null; originalTicketOne.id = null;
originalTicketTwo.id = null; originalTicketTwo.id = null;
ticketOne = await app.models.Ticket.create(originalTicketOne);
ticketTwo = await app.models.Ticket.create(originalTicketTwo); ticketOne = await app.models.Ticket.create(originalTicketOne);
ticketTwo = await app.models.Ticket.create(originalTicketTwo);
} catch (error) {
console.error(error);
}
done(); done();
}); });
afterAll(async done => { afterAll(async done => {
await app.models.Ticket.destroyById(ticketOne.id); try {
await app.models.Ticket.destroyById(ticketTwo.id); await app.models.Ticket.destroyById(ticketOne.id);
await app.models.Ticket.destroyById(ticketTwo.id);
} catch (error) {
console.error(error);
}
done(); done();
}); });
@ -31,6 +49,8 @@ describe('ticket setDelivered()', () => {
let state = await app.models.TicketTracking.setDelivered(ctx, params); let state = await app.models.TicketTracking.setDelivered(ctx, params);
expect(state.id).toEqual(delivered.id); expect(state.id).toEqual(delivered.id);
// restores
await app.models.TicketTracking.destroyById(state.id);
}); });
}); });

View File

@ -5,9 +5,8 @@ describe('ticket filter()', () => {
const ctx = {req: {accessToken: {userId: 9}}, args: {}}; const ctx = {req: {accessToken: {userId: 9}}, args: {}};
const filter = {order: 'id DESC'}; const filter = {order: 'id DESC'};
const result = await app.models.Ticket.filter(ctx, filter); const result = await app.models.Ticket.filter(ctx, filter);
const ticketId = result[0].id;
expect(ticketId).toEqual(24); expect(result.length).toEqual(24);
}); });
it('should return the tickets matching the problems on true', async() => { it('should return the tickets matching the problems on true', async() => {
@ -71,7 +70,7 @@ describe('ticket filter()', () => {
const length = result.length; const length = result.length;
const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; const anyResult = result[Math.floor(Math.random() * Math.floor(length))];
expect(result.length).toEqual(7); expect(length).toEqual(7);
expect(anyResult.state).toMatch(/(Libre|Arreglar)/); expect(anyResult.state).toMatch(/(Libre|Arreglar)/);
}); });

View File

@ -1,41 +1,53 @@
const app = require('vn-loopback/server/server'); const app = require('vn-loopback/server/server');
const LoopBackContext = require('loopback-context');
describe('ticket makeInvoice()', () => { describe('ticket makeInvoice()', () => {
const userId = 19;
const activeCtx = {
accessToken: {userId: userId},
};
const ctx = {req: activeCtx};
let invoice; let invoice;
let ticketId = 11; let ticketId = 11;
const okState = 3; const okState = 3;
afterAll(async done => { beforeAll(async done => {
let ticket = await app.models.Ticket.findById(11); spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
await ticket.updateAttributes({refFk: null}); active: activeCtx
let ticketTrackings = await app.models.TicketTracking.find({
where: {
ticketFk: ticketId,
stateFk: {neq: okState}
},
order: 'id DESC'
}); });
});
for (let state of ticketTrackings) afterAll(async done => {
await state.destroy(); try {
let ticket = await app.models.Ticket.findById(11);
await ticket.updateAttributes({refFk: null});
let invoiceOut = await app.models.InvoiceOut.findById(invoice.invoiceFk); let ticketTrackings = await app.models.TicketTracking.find({
await invoiceOut.destroy(); where: {
ticketFk: ticketId,
stateFk: {neq: okState}
},
order: 'id DESC'
});
for (let state of ticketTrackings)
await state.destroy();
let invoiceOut = await app.models.InvoiceOut.findById(invoice.invoiceFk);
await invoiceOut.destroy();
} catch (error) {
console.error(error);
}
done(); done();
}); });
it('should invoice a ticket', async() => { it('should invoice a ticket, then try again to fail', async() => {
let ctx = {req: {accessToken: {userId: 9}}};
invoice = await app.models.Ticket.makeInvoice(ctx, ticketId); invoice = await app.models.Ticket.makeInvoice(ctx, ticketId);
expect(invoice.invoiceFk).toBeDefined(); expect(invoice.invoiceFk).toBeDefined();
expect(invoice.serial).toEqual('T'); expect(invoice.serial).toEqual('T');
});
it('should not invoice an already invoiced ticket', async() => {
let ctx = {req: {accessToken: {userId: 9}}};
let error; let error;
await app.models.Ticket.makeInvoice(ctx, ticketId).catch(e => { await app.models.Ticket.makeInvoice(ctx, ticketId).catch(e => {
@ -43,5 +55,7 @@ describe('ticket makeInvoice()', () => {
}).finally(() => { }).finally(() => {
expect(error.message).toEqual(`This ticket can't be invoiced`); expect(error.message).toEqual(`This ticket can't be invoiced`);
}); });
expect(error).toBeDefined();
}); });
}); });

View File

@ -1,18 +1,16 @@
const app = require('vn-loopback/server/server'); const app = require('vn-loopback/server/server');
const LoopBackContext = require('loopback-context');
const models = app.models; const models = app.models;
describe('ticket setDeleted()', () => { describe('ticket setDeleted()', () => {
const userId = 106;
const employeeUser = 110;
const activeCtx = {
accessToken: {userId: userId},
};
it('should throw an error if the given ticket has a claim', async() => { it('should throw an error if the given ticket has a claim', async() => {
const ctx = {req: activeCtx};
const ticketId = 16; const ticketId = 16;
const ctx = {
req: {
accessToken: {userId: 106},
headers: {
origin: 'http://localhost:5000'
},
__: () => {}
}
};
let error; let error;
try { try {
@ -26,7 +24,9 @@ describe('ticket setDeleted()', () => {
}); });
it('should delete the ticket, remove the stowaway link and change the stowaway ticket state to "FIXING" and get rid of the itemshelving', async() => { it('should delete the ticket, remove the stowaway link and change the stowaway ticket state to "FIXING" and get rid of the itemshelving', async() => {
const employeeUser = 110; spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
active: activeCtx
});
const ctx = { const ctx = {
req: { req: {
accessToken: {userId: employeeUser}, accessToken: {userId: employeeUser},
@ -96,7 +96,8 @@ describe('ticket setDeleted()', () => {
expect(stowaway).toBeNull(); expect(stowaway).toBeNull();
expect(stowawayTicketState.code).toEqual('FIXING'); expect(stowawayTicketState.code).toEqual('FIXING');
await shipTicket.destroy(); // restores
await stowawayTicket.destroy(); await models.Ticket.destroyById(shipTicket.id);
await models.Ticket.destroyById(stowawayTicket.id);
}); });
}); });

View File

@ -1,18 +1,36 @@
const app = require('vn-loopback/server/server'); const app = require('vn-loopback/server/server');
const LoopBackContext = require('loopback-context');
describe('sale transferSales()', () => { describe('sale transferSales()', () => {
let createdTicketId; const userId = 101;
const activeCtx = {
accessToken: {userId: userId},
};
const ctx = {req: activeCtx};
let createdTicketsIds = []; let createdTicketsIds = [];
afterAll(async done => { beforeAll(() => {
createdTicketsIds.forEach(async createdTicketId => { spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
await app.models.Ticket.destroyById(createdTicketId); active: activeCtx
}); });
});
afterEach(async done => {
if (createdTicketsIds.length) {
try {
createdTicketsIds.forEach(async createdTicketId => {
await app.models.Ticket.destroyById(createdTicketId);
});
} catch (error) {
console.error(error);
}
}
done(); done();
}); });
it('should throw an error as the ticket is not editable', async() => { it('should throw an error as the ticket is not editable', async() => {
const ctx = {req: {accessToken: {userId: 101}}};
let error; let error;
const currentTicketId = 1; const currentTicketId = 1;
@ -29,7 +47,6 @@ describe('sale transferSales()', () => {
}); });
it('should throw an error if the receiving ticket is not editable', async() => { it('should throw an error if the receiving ticket is not editable', async() => {
const ctx = {req: {accessToken: {userId: 101}}};
let error; let error;
const currentTicketId = 16; const currentTicketId = 16;
@ -45,60 +62,41 @@ describe('sale transferSales()', () => {
expect(error).toBeDefined(); expect(error).toBeDefined();
}); });
it('should transfer the sales from one ticket to a new one', async() => { it('should transfer the sales from one ticket to a new one then send them back and delete the created ticket', async() => {
const ctx = {req: {accessToken: {userId: 101}}}; const formerTicketId = 11;
let currentTicket = await app.models.Ticket.findById(11); let createdTicketId = undefined;
let originalTicketSales = await app.models.Ticket.getSales(currentTicket.id);
salesToRestone = originalTicketSales;
expect(originalTicketSales.length).toEqual(2); let formerTicketSales = await app.models.Ticket.getSales(formerTicketId);
const currentTicketId = currentTicket.id; expect(formerTicketSales.length).toEqual(2);
const receiverTicketId = undefined;
let createdTicket = await app.models.Ticket.transferSales( let createdTicket = await app.models.Ticket.transferSales(
ctx, currentTicketId, receiverTicketId, originalTicketSales); ctx, formerTicketId, createdTicketId, formerTicketSales);
createdTicketId = createdTicket.id; createdTicketId = createdTicket.id;
createdTicketsIds.push(createdTicket.id); createdTicketsIds.push(createdTicketId);
originalTicketSales = await app.models.Ticket.getSales(currentTicket.id); formerTicketSales = await app.models.Ticket.getSales(formerTicketId);
receiverTicketSales = await app.models.Ticket.getSales(createdTicket.id); createdTicketSales = await app.models.Ticket.getSales(createdTicketId);
expect(originalTicketSales.length).toEqual(0); expect(formerTicketSales.length).toEqual(0);
expect(receiverTicketSales.length).toEqual(2);
});
it('should transfer back the sales and set the created ticket as deleted', async() => {
const ctx = {req: {accessToken: {userId: 101}}};
const currentTicket = await app.models.Ticket.findById(createdTicketId);
const receiverTicketId = 11;
let createdTicket = await app.models.Ticket.findById(createdTicketId);
let createdTicketSales = await app.models.Ticket.getSales(createdTicketId);
let receiverTicketSales = await app.models.Ticket.getSales(receiverTicketId);
const currentTicketId = currentTicket.id;
const sales = createdTicketSales;
expect(createdTicket.isDeleted).toBeFalsy();
expect(createdTicketSales.length).toEqual(2); expect(createdTicketSales.length).toEqual(2);
expect(receiverTicketSales.length).toEqual(0);
await app.models.Ticket.transferSales( await app.models.Ticket.transferSales(
ctx, currentTicketId, receiverTicketId, sales); ctx, createdTicketId, formerTicketId, createdTicketSales);
formerTicketSales = await app.models.Ticket.getSales(formerTicketId);
createdTicketSales = await app.models.Ticket.getSales(createdTicketId);
createdTicket = await app.models.Ticket.findById(createdTicketId); createdTicket = await app.models.Ticket.findById(createdTicketId);
createdTicketSales = await app.models.Ticket.getSales(createdTicketId);
receiverTicketSales = await app.models.Ticket.getSales(receiverTicketId);
expect(createdTicket.isDeleted).toBeTruthy(); expect(createdTicket.isDeleted).toBeTruthy();
expect(formerTicketSales.length).toEqual(2);
expect(createdTicketSales.length).toEqual(0); expect(createdTicketSales.length).toEqual(0);
expect(receiverTicketSales.length).toEqual(2);
}); });
describe('sale transferPartialSales()', () => { describe('sale transferPartialSales()', () => {
it('should throw an error in the quantity to transfer exceeds the amount from the original sale', async() => { it('should throw an error in the quantity to transfer exceeds the amount from the original sale', async() => {
const ctx = {req: {accessToken: {userId: 101}}};
let error; let error;
let currentTicket = await app.models.Ticket.findById(11); let currentTicket = await app.models.Ticket.findById(11);
let currentTicketSales = await app.models.Ticket.getSales(currentTicket.id); let currentTicketSales = await app.models.Ticket.getSales(currentTicket.id);
@ -119,44 +117,51 @@ describe('sale transferSales()', () => {
}); });
it('should transfer two sales to a new ticket but one shall be partial', async() => { it('should transfer two sales to a new ticket but one shall be partial', async() => {
const ctx = {req: {accessToken: {userId: 101}}}; const formerTicketId = 11;
const originalTicketId = 11; let createdTicketId = undefined;
const receiverTicketId = undefined;
let currentTicketSales = await app.models.Ticket.getSales(originalTicketId); let formerTicketSales = await app.models.Ticket.getSales(formerTicketId);
const originalPartialSaleId = currentTicketSales[0].id; const partialSaleId = formerTicketSales[0].id;
const originalCompleteSaleId = currentTicketSales[1].id; const completeSaleId = formerTicketSales[1].id;
let originalQuantity = currentTicketSales[0].quantity; let partialSaleTotalQuantity = formerTicketSales[0].quantity;
currentTicketSales[0].quantity = 1;
expect(partialSaleTotalQuantity).toEqual(15);
formerTicketSales[0].quantity = 1;
let createdTicket = await app.models.Ticket.transferSales( let createdTicket = await app.models.Ticket.transferSales(
ctx, originalTicketId, receiverTicketId, currentTicketSales); ctx, formerTicketId, createdTicketId, formerTicketSales);
createdTicketId = createdTicket.id; createdTicketId = createdTicket.id;
createdTicketsIds.push(createdTicket.id); createdTicketsIds.push(createdTicket.id);
currentTicketSales = await app.models.Ticket.getSales(originalTicketId); formerTicketSales = await app.models.Ticket.getSales(formerTicketId);
receiverTicketSales = await app.models.Ticket.getSales(createdTicketId); createdTicketSales = await app.models.Ticket.getSales(createdTicketId);
const [createdPartialSale] = receiverTicketSales.filter(sale => { const [createdPartialSale] = createdTicketSales.filter(sale => {
return sale.id != originalCompleteSaleId; return sale.id != completeSaleId;
}); });
expect(currentTicketSales.length).toEqual(1); expect(formerTicketSales.length).toEqual(1);
expect(currentTicketSales[0].quantity).toEqual(originalQuantity -= 1); expect(formerTicketSales[0].quantity).toEqual(partialSaleTotalQuantity - 1);
expect(receiverTicketSales.length).toEqual(2); expect(createdTicketSales.length).toEqual(2);
expect(createdPartialSale.quantity).toEqual(1); expect(createdPartialSale.quantity).toEqual(1);
let saleToRestore = await app.models.Sale.findById(originalPartialSaleId); let saleToRestore = await app.models.Sale.findById(partialSaleId);
await saleToRestore.updateAttribute('quantity', originalQuantity); await saleToRestore.updateAttribute('quantity', partialSaleTotalQuantity);
let saleToReturnToTicket = await app.models.Sale.findById(originalCompleteSaleId); let saleToReturnToTicket = await app.models.Sale.findById(completeSaleId);
await saleToReturnToTicket.updateAttribute('ticketFk', originalTicketId); await saleToReturnToTicket.updateAttribute('ticketFk', formerTicketId);
currentTicketSales = await app.models.Ticket.getSales(originalTicketId); formerTicketSales = await app.models.Ticket.getSales(formerTicketId);
expect(currentTicketSales.length).toEqual(2); const [returningPartialSale] = formerTicketSales.filter(sale => {
return sale.id == partialSaleId;
});
expect(returningPartialSale.quantity).toEqual(partialSaleTotalQuantity);
expect(formerTicketSales.length).toEqual(2);
}); });
}); });
}); });

View File

@ -1,4 +1,11 @@
const app = require('vn-loopback/server/server'); const app = require('vn-loopback/server/server');
const LoopBackContext = require('loopback-context');
const userId = 9;
const activeCtx = {
accessToken: {userId: userId},
};
const ctx = {req: activeCtx};
describe('ticket updateEditableTicket()', () => { describe('ticket updateEditableTicket()', () => {
const validTicketId = 12; const validTicketId = 12;
@ -7,7 +14,6 @@ describe('ticket updateEditableTicket()', () => {
const originalData = {addressFk: 123}; const originalData = {addressFk: 123};
afterAll(async done => { afterAll(async done => {
let ctx = {req: {accessToken: {userId: 9}}};
await app.models.Ticket.updateEditableTicket(ctx, validTicketId, originalData); await app.models.Ticket.updateEditableTicket(ctx, validTicketId, originalData);
done(); done();
@ -15,7 +21,6 @@ describe('ticket updateEditableTicket()', () => {
it('should now throw an error if the ticket is not editable', async() => { it('should now throw an error if the ticket is not editable', async() => {
let error; let error;
let ctx = {req: {accessToken: {userId: 9}}};
await app.models.Ticket.updateEditableTicket(ctx, invalidTicketId, data).catch(e => { await app.models.Ticket.updateEditableTicket(ctx, invalidTicketId, data).catch(e => {
error = e; error = e;
@ -27,8 +32,9 @@ describe('ticket updateEditableTicket()', () => {
}); });
it('should edit the ticket address', async() => { it('should edit the ticket address', async() => {
let ctx = {req: {accessToken: {userId: 9}}}; spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
active: activeCtx
});
await app.models.Ticket.updateEditableTicket(ctx, validTicketId, data); await app.models.Ticket.updateEditableTicket(ctx, validTicketId, data);
let updatedTicket = await app.models.Ticket.findById(validTicketId); let updatedTicket = await app.models.Ticket.findById(validTicketId);

View File

@ -1,4 +1,6 @@
const LoopBackContext = require('loopback-context');
module.exports = Self => { module.exports = Self => {
require('../methods/ticket/changeWorker')(Self); require('../methods/ticket/changeWorker')(Self);
require('../methods/ticket/getVolume')(Self); require('../methods/ticket/getVolume')(Self);
@ -34,13 +36,16 @@ module.exports = Self => {
require('../methods/ticket/getComponentsSum')(Self); require('../methods/ticket/getComponentsSum')(Self);
Self.observe('before save', async function(ctx) { Self.observe('before save', async function(ctx) {
const loopBackContext = LoopBackContext.getCurrentContext();
const httpCtx = loopBackContext.active;
if (ctx.isNewInstance) return; if (ctx.isNewInstance) return;
let changes = ctx.data || ctx.instance; let changes = ctx.data || ctx.instance;
if (changes.routeFk === null && ctx.currentInstance.routeFk != null) { if (changes.routeFk === null && ctx.currentInstance.routeFk != null) {
let instance = JSON.parse(JSON.stringify(ctx.currentInstance)); let instance = JSON.parse(JSON.stringify(ctx.currentInstance));
let userId = ctx.options.accessToken.userId; let userId = httpCtx.accessToken.userId;
let logRecord = { let logRecord = {
originFk: ctx.currentInstance.routeFk, originFk: ctx.currentInstance.routeFk,
userFk: userId, userFk: userId,

View File

@ -18,7 +18,7 @@ describe('Termograph createThermograph()', () => {
done(); done();
}); });
it(`should create a thermograph which is saved in both thermograph and travelThermograph`, async() => { it(`should be able to create just once a thermograph which is saved in both thermograph and travelThermograph`, async() => {
let createdTravelThermograpth = await models.TravelThermograph.findOne({where: {thermographFk: thermographId}}); let createdTravelThermograpth = await models.TravelThermograph.findOne({where: {thermographFk: thermographId}});
expect(createdTravelThermograpth).toBeNull(); expect(createdTravelThermograpth).toBeNull();
@ -32,9 +32,7 @@ describe('Termograph createThermograph()', () => {
expect(createdTravelThermograpth.warehouseFk).toEqual(warehouseId); expect(createdTravelThermograpth.warehouseFk).toEqual(warehouseId);
expect(createdTravelThermograpth.temperature).toEqual(temperature); expect(createdTravelThermograpth.temperature).toEqual(temperature);
});
it(`should not be able to created duplicated entries`, async() => {
let error; let error;
try { try {

View File

@ -1,12 +1,37 @@
const app = require('vn-loopback/server/server'); const app = require('vn-loopback/server/server');
const LoopBackContext = require('loopback-context');
describe('workerTimeControl add/delete timeEntry()', () => {
const HHRRId = 37;
const teamBossId = 13;
const employeeId = 1;
let activeCtx = {
accessToken: {userId: 50},
};
let ctx = {req: activeCtx};
describe('workerTimeControl addTimeEntry()', () => {
let timeEntry; let timeEntry;
let createdTimeEntry; let createdTimeEntry;
afterEach(async() => {
if (createdTimeEntry) {
try {
await app.models.WorkerTimeControl.destroyById(createdTimeEntry.id);
} catch (error) {
console.error(error);
}
}
});
beforeAll(() => {
spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
active: activeCtx
});
});
it('should fail to add a time entry if the target user is not a subordinate', async() => { it('should fail to add a time entry if the target user is not a subordinate', async() => {
activeCtx.accessToken.userId = employeeId;
let error; let error;
let ctx = {req: {accessToken: {userId: 1}}};
let data = { let data = {
workerFk: 2, workerFk: 2,
timed: new Date() timed: new Date()
@ -24,8 +49,8 @@ describe('workerTimeControl addTimeEntry()', () => {
}); });
it('should fail to add if the current and the target user are the same and is not team boss', async() => { it('should fail to add if the current and the target user are the same and is not team boss', async() => {
activeCtx.accessToken.userId = employeeId;
let error; let error;
let ctx = {req: {accessToken: {userId: 1}}};
let data = { let data = {
workerFk: 1, workerFk: 1,
timed: new Date() timed: new Date()
@ -42,12 +67,11 @@ describe('workerTimeControl addTimeEntry()', () => {
expect(error.message).toBe(`You don't have enough privileges`); expect(error.message).toBe(`You don't have enough privileges`);
}); });
it('should add if the current user is team boss and the target user is a subordinate', async() => { it('should add if the current user is team boss and the target user is a himself', async() => {
todayAtSix = new Date(); activeCtx.accessToken.userId = teamBossId;
let todayAtSix = new Date();
todayAtSix.setHours(18, 30, 0, 0); todayAtSix.setHours(18, 30, 0, 0);
let teamBossId = 13;
let ctx = {req: {accessToken: {userId: teamBossId}}};
let data = { let data = {
workerFk: teamBossId, workerFk: teamBossId,
timed: todayAtSix timed: todayAtSix
@ -60,10 +84,20 @@ describe('workerTimeControl addTimeEntry()', () => {
expect(createdTimeEntry).toBeDefined(); expect(createdTimeEntry).toBeDefined();
}); });
it('should try but fail to delete the created time entry for the team boss as team boss', async() => { it('should try but fail to delete his own time entry', async() => {
activeCtx.accessToken.userId = teamBossId;
let error; let error;
let teamBossId = 13; let todayAtSeven = new Date();
let ctx = {req: {accessToken: {userId: teamBossId}}}; todayAtSeven.setHours(19, 30, 0, 0);
let data = {
workerFk: teamBossId,
timed: todayAtSeven
};
timeEntry = await app.models.WorkerTimeControl.addTimeEntry(ctx, data);
createdTimeEntry = await app.models.WorkerTimeControl.findById(timeEntry.id);
try { try {
await app.models.WorkerTimeControl.deleteTimeEntry(ctx, createdTimeEntry.id); await app.models.WorkerTimeControl.deleteTimeEntry(ctx, createdTimeEntry.id);
@ -77,13 +111,23 @@ describe('workerTimeControl addTimeEntry()', () => {
}); });
it('should delete the created time entry for the team boss as HHRR', async() => { it('should delete the created time entry for the team boss as HHRR', async() => {
let HHRRId = 37; activeCtx.accessToken.userId = HHRRId;
let ctx = {req: {accessToken: {userId: HHRRId}}};
let todayAtFive = new Date();
todayAtFive.setHours(17, 30, 0, 0);
let data = {
workerFk: teamBossId,
timed: todayAtFive
};
timeEntry = await app.models.WorkerTimeControl.addTimeEntry(ctx, data);
createdTimeEntry = await app.models.WorkerTimeControl.findById(timeEntry.id);
expect(createdTimeEntry).toBeDefined(); expect(createdTimeEntry).toBeDefined();
ctx.req.accessToken.userId = HHRRId; await app.models.WorkerTimeControl.deleteTimeEntry(ctx, createdTimeEntry.id);
await app.models.WorkerTimeControl.deleteTimeEntry(ctx, timeEntry.id);
createdTimeEntry = await app.models.WorkerTimeControl.findById(timeEntry.id); createdTimeEntry = await app.models.WorkerTimeControl.findById(timeEntry.id);