ticket module transactions + tests

This commit is contained in:
Carlos Jimenez Ruiz 2021-08-12 11:21:59 +02:00
parent 708c0035c0
commit 2b4afdd04d
33 changed files with 754 additions and 338 deletions

View File

@ -7,23 +7,23 @@ module.exports = Self => {
accessType: 'WRITE', accessType: 'WRITE',
accepts: [{ accepts: [{
arg: 'id', arg: 'id',
type: 'Number', type: 'number',
required: true, required: true,
description: 'The ticket id', description: 'The ticket id',
http: {source: 'path'} http: {source: 'path'}
}, },
{ {
arg: 'itemId', arg: 'itemId',
type: 'Number', type: 'number',
required: true required: true
}, },
{ {
arg: 'quantity', arg: 'quantity',
type: 'Number', type: 'number',
required: true required: true
}], }],
returns: { returns: {
type: 'Object', type: 'object',
root: true root: true
}, },
http: { http: {
@ -35,8 +35,8 @@ module.exports = Self => {
Self.addSale = async(ctx, id, itemId, quantity, options) => { Self.addSale = async(ctx, id, itemId, quantity, options) => {
const $t = ctx.req.__; // $translate const $t = ctx.req.__; // $translate
const models = Self.app.models; const models = Self.app.models;
let tx;
const myOptions = {}; const myOptions = {};
let tx;
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);

View File

@ -22,7 +22,7 @@ module.exports = function(Self) {
}); });
Self.canBeInvoiced = async(ticketsIds, options) => { Self.canBeInvoiced = async(ticketsIds, options) => {
let myOptions = {}; const myOptions = {};
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);

View File

@ -19,8 +19,13 @@ module.exports = Self => {
} }
}); });
Self.canHaveStowaway = async id => { Self.canHaveStowaway = async(id, options) => {
const models = Self.app.models; const models = Self.app.models;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const ticket = await models.Ticket.findById(id, { const ticket = await models.Ticket.findById(id, {
include: { include: {
relation: 'ship', relation: 'ship',
@ -28,8 +33,10 @@ module.exports = Self => {
fields: ['id'] fields: ['id']
} }
} }
}); }, myOptions);
const warehouse = await models.Warehouse.findById(ticket.warehouseFk);
const warehouse = await models.Warehouse.findById(ticket.warehouseFk, null, myOptions);
const hasStowaway = ticket.ship() ? true : false; const hasStowaway = ticket.ship() ? true : false;
const validStowaway = warehouse && warehouse.hasStowaway && !hasStowaway; const validStowaway = warehouse && warehouse.hasStowaway && !hasStowaway;

View File

@ -90,8 +90,8 @@ module.exports = Self => {
Self.componentUpdate = async(ctx, options) => { Self.componentUpdate = async(ctx, options) => {
const args = ctx.args; const args = ctx.args;
const myOptions = {};
let tx; let tx;
let myOptions = {};
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);

View File

@ -19,69 +19,87 @@ module.exports = Self => {
} }
}); });
Self.deleteStowaway = async(ctx, id) => { Self.deleteStowaway = async(ctx, id, options) => {
const models = Self.app.models; const models = Self.app.models;
const $t = ctx.req.__; // $translate const $t = ctx.req.__; // $translate
const ticket = await Self.findById(id, { const myOptions = {};
include: [{ let tx;
relation: 'ship'
}, { if (typeof options == 'object')
relation: 'stowaway' Object.assign(myOptions, options);
}, {
relation: 'client', if (!myOptions.transaction) {
scope: { tx = await Self.beginTransaction({});
include: { myOptions.transaction = tx;
relation: 'salesPersonUser', }
scope: {
fields: ['id', 'name'] try {
const ticket = await Self.findById(id, {
include: [{
relation: 'ship'
}, {
relation: 'stowaway'
}, {
relation: 'client',
scope: {
include: {
relation: 'salesPersonUser',
scope: {
fields: ['id', 'name']
}
} }
} }
}]
}, myOptions);
let stowawayFk;
let shipFk;
if (ticket.stowaway()) {
shipFk = ticket.stowaway().shipFk;
stowawayFk = ticket.stowaway().id;
} else if (ticket.ship()) {
shipFk = ticket.ship().shipFk;
stowawayFk = ticket.ship().id;
}
const stowaway = await models.Stowaway.findOne({
where: {
id: stowawayFk,
shipFk: shipFk
} }
}] }, myOptions);
}); const result = await stowaway.destroy(myOptions);
let stowawayFk; const state = await models.State.findOne({
let shipFk; where: {
if (ticket.stowaway()) { code: 'BOARDING'
shipFk = ticket.stowaway().shipFk; }
stowawayFk = ticket.stowaway().id; }, myOptions);
} else if (ticket.ship()) { const ticketTracking = await models.TicketTracking.findOne({
shipFk = ticket.ship().shipFk; where: {
stowawayFk = ticket.ship().id; ticketFk: shipFk,
stateFk: state.id
}
}, myOptions);
await ticketTracking.destroy(myOptions);
const salesPerson = ticket.client().salesPersonUser();
if (salesPerson) {
const origin = ctx.req.headers.origin;
const message = $t('This ticket is not an stowaway anymore', {
ticketId: stowawayFk,
ticketUrl: `${origin}/#!/ticket/${stowawayFk}/sale`
});
await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message);
}
if (tx) await tx.commit();
return result;
} catch (e) {
if (tx) await tx.rollback();
throw e;
} }
const stowaway = await models.Stowaway.findOne({
where: {
id: stowawayFk,
shipFk: shipFk
}
});
const result = await stowaway.destroy();
const state = await models.State.findOne({
where: {
code: 'BOARDING'
}
});
const ticketTracking = await models.TicketTracking.findOne({
where: {
ticketFk: shipFk,
stateFk: state.id
}
});
await ticketTracking.destroy();
const salesPerson = ticket.client().salesPersonUser();
if (salesPerson) {
const origin = ctx.req.headers.origin;
const message = $t('This ticket is not an stowaway anymore', {
ticketId: stowawayFk,
ticketUrl: `${origin}/#!/ticket/${stowawayFk}/sale`
});
await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message);
}
return result;
}; };
}; };

View File

@ -119,12 +119,17 @@ module.exports = Self => {
} }
}); });
Self.filter = async(ctx, filter) => { Self.filter = async(ctx, filter, options) => {
const userId = ctx.req.accessToken.userId; const userId = ctx.req.accessToken.userId;
const conn = Self.dataSource.connector; const conn = Self.dataSource.connector;
const models = Self.app.models; const models = Self.app.models;
const args = ctx.args; const args = ctx.args;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
// Apply filter by team // Apply filter by team
const teamMembersId = []; const teamMembersId = [];
if (args.myTeam != null) { if (args.myTeam != null) {
@ -132,7 +137,8 @@ module.exports = Self => {
include: { include: {
relation: 'collegues' relation: 'collegues'
} }
}); }, myOptions);
const collegues = worker.collegues() || []; const collegues = worker.collegues() || [];
collegues.forEach(collegue => { collegues.forEach(collegue => {
teamMembersId.push(collegue.collegueFk); teamMembersId.push(collegue.collegueFk);
@ -204,7 +210,7 @@ module.exports = Self => {
filter = mergeFilters(filter, {where}); filter = mergeFilters(filter, {where});
let stmts = []; const stmts = [];
let stmt; let stmt;
stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.filter'); stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.filter');
@ -306,7 +312,7 @@ module.exports = Self => {
break; break;
} }
let problems = {[condition]: [ const problems = {[condition]: [
{'tp.isFreezed': hasProblem}, {'tp.isFreezed': hasProblem},
{'tp.risk': hasProblem}, {'tp.risk': hasProblem},
{'tp.hasTicketRequest': hasProblem}, {'tp.hasTicketRequest': hasProblem},
@ -318,15 +324,15 @@ module.exports = Self => {
stmt.merge(conn.makeOrderBy(filter.order)); stmt.merge(conn.makeOrderBy(filter.order));
stmt.merge(conn.makeLimit(filter)); stmt.merge(conn.makeLimit(filter));
let ticketsIndex = stmts.push(stmt) - 1; const ticketsIndex = stmts.push(stmt) - 1;
stmts.push( stmts.push(
`DROP TEMPORARY TABLE `DROP TEMPORARY TABLE
tmp.filter, tmp.filter,
tmp.ticket_problems`); tmp.ticket_problems`);
let sql = ParameterizedSQL.join(stmts, ';'); const sql = ParameterizedSQL.join(stmts, ';');
let result = await conn.executeStmt(sql); const result = await conn.executeStmt(sql, myOptions);
return result[ticketsIndex]; return result[ticketsIndex];
}; };

View File

@ -10,7 +10,7 @@ module.exports = Self => {
http: {source: 'path'} http: {source: 'path'}
}, },
returns: { returns: {
type: 'Number', type: 'number',
root: true root: true
}, },
http: { http: {
@ -19,8 +19,14 @@ module.exports = Self => {
} }
}); });
Self.freightCost = async ticketFk => { Self.freightCost = async(ticketFk, options) => {
const [freightCost] = await Self.rawSql(`SELECT vn.ticket_getFreightCost(?) total`, [ticketFk]); const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const [freightCost] = await Self.rawSql(`SELECT vn.ticket_getFreightCost(?) total`, [ticketFk], myOptions);
return freightCost.total; return freightCost.total;
}; };
}; };

View File

@ -10,7 +10,7 @@ module.exports = Self => {
http: {source: 'path'} http: {source: 'path'}
}, },
returns: { returns: {
type: 'Number', type: 'number',
root: true root: true
}, },
http: { http: {
@ -18,10 +18,15 @@ module.exports = Self => {
verb: 'GET' verb: 'GET'
} }
}); });
Self.getComponentsSum = async id => { Self.getComponentsSum = async(id, options) => {
const models = Self.app.models; const models = Self.app.models;
let componentsSum = []; const myOptions = {};
let sales = await models.Sale.find({
if (typeof options == 'object')
Object.assign(myOptions, options);
const componentsSum = [];
const sales = await models.Sale.find({
include: { include: {
relation: 'components', relation: 'components',
scope: {fields: ['value', 'componentFk'], scope: {fields: ['value', 'componentFk'],
@ -31,10 +36,10 @@ module.exports = Self => {
} }
}, },
where: {ticketFk: id} where: {ticketFk: id}
}); }, myOptions);
for (let sale of sales) { for (let sale of sales) {
for (let component of sale.components()) { for (let component of sale.components()) {
let componentId = componentsSum[component.componentFk]; const componentId = componentsSum[component.componentFk];
if (!componentId) { if (!componentId) {
componentsSum[component.componentFk] = { componentsSum[component.componentFk] = {
componentFk: component.componentFk, componentFk: component.componentFk,

View File

@ -20,25 +20,30 @@ module.exports = Self => {
} }
}); });
Self.getPossibleStowaways = async ticketFk => { Self.getPossibleStowaways = async(ticketFk, options) => {
const models = Self.app.models; const models = Self.app.models;
const canHaveStowaway = await models.Ticket.canHaveStowaway(ticketFk); const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const canHaveStowaway = await models.Ticket.canHaveStowaway(ticketFk, myOptions);
if (!canHaveStowaway) if (!canHaveStowaway)
throw new UserError(`Can't create stowaway for this ticket`); throw new UserError(`Can't create stowaway for this ticket`);
let ship = await models.Ticket.findById(ticketFk); const ship = await models.Ticket.findById(ticketFk, null, myOptions);
if (!ship || !ship.shipped) if (!ship || !ship.shipped)
return []; return [];
let lowestDate = new Date(ship.shipped.getTime()); const lowestDate = new Date(ship.shipped.getTime());
lowestDate.setHours(0, 0, -1, 0); lowestDate.setHours(0, 0, -1, 0);
let highestDate = new Date(ship.shipped.getTime()); const highestDate = new Date(ship.shipped.getTime());
highestDate.setHours(23, 59, 59); highestDate.setHours(23, 59, 59);
let possibleStowaways = await models.Ticket.find({ const possibleStowaways = await models.Ticket.find({
where: { where: {
id: {neq: ticketFk}, id: {neq: ticketFk},
clientFk: ship.clientFk, clientFk: ship.clientFk,
@ -62,7 +67,7 @@ module.exports = Self => {
}, },
}, },
] ]
}); }, myOptions);
return possibleStowaways; return possibleStowaways;
}; };

View File

@ -23,7 +23,7 @@ module.exports = Self => {
Self.getSales = async(id, options) => { Self.getSales = async(id, options) => {
const models = Self.app.models; const models = Self.app.models;
let myOptions = {}; const myOptions = {};
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);

View File

@ -18,8 +18,13 @@ module.exports = Self => {
} }
}); });
Self.getSalesPersonMana = async ticketId => { Self.getSalesPersonMana = async(ticketId, options) => {
const myOptions = {};
const models = Self.app.models; const models = Self.app.models;
if (typeof options == 'object')
Object.assign(myOptions, options);
const ticket = await models.Ticket.findById(ticketId, { const ticket = await models.Ticket.findById(ticketId, {
include: [{ include: [{
relation: 'client', relation: 'client',
@ -28,14 +33,16 @@ module.exports = Self => {
} }
}], }],
fields: ['id', 'clientFk'] fields: ['id', 'clientFk']
}); }, myOptions);
if (!ticket) return 0; if (!ticket) return 0;
const mana = await models.WorkerMana.findOne({ const mana = await models.WorkerMana.findOne({
where: { where: {
workerFk: ticket.client().salesPersonFk workerFk: ticket.client().salesPersonFk
}, fields: 'amount'}); },
fields: 'amount'
}, myOptions);
return mana ? mana.amount : 0; return mana ? mana.amount : 0;
}; };

View File

@ -18,7 +18,16 @@ module.exports = Self => {
} }
}); });
Self.getTotalVolume = async ticketFk => { Self.getTotalVolume = async(ticketFk, options) => {
return (await Self.rawSql(`SELECT vn.ticketTotalVolume(?) totalVolume, vn.ticketTotalVolumeBoxes(?) totalBoxes`, [ticketFk, ticketFk]))[0]; const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const volumeData = await Self.rawSql(`
SELECT vn.ticketTotalVolume(?) totalVolume, vn.ticketTotalVolumeBoxes(?) totalBoxes
`, [ticketFk, ticketFk], myOptions);
return volumeData[0];
}; };
}; };

View File

@ -19,8 +19,13 @@ module.exports = Self => {
} }
}); });
Self.getVolume = async ticketFk => { Self.getVolume = async(ticketFk, options) => {
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
return Self.rawSql(`SELECT * FROM vn.saleVolume return Self.rawSql(`SELECT * FROM vn.saleVolume
WHERE ticketFk = ?`, [ticketFk]); WHERE ticketFk = ?`, [ticketFk], myOptions);
}; };
}; };

View File

@ -12,7 +12,7 @@ module.exports = function(Self) {
} }
], ],
returns: { returns: {
type: 'Boolean', type: 'boolean',
root: true root: true
}, },
http: { http: {
@ -24,25 +24,27 @@ module.exports = function(Self) {
Self.isEmpty = async(id, options) => { Self.isEmpty = async(id, options) => {
const models = Self.app.models; const models = Self.app.models;
if ((typeof options) != 'object') const myOptions = {};
options = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const hasSales = await models.Sale.count({ const hasSales = await models.Sale.count({
ticketFk: id ticketFk: id
}, options); }, myOptions);
const hasPackages = await models.TicketPackaging.count({ const hasPackages = await models.TicketPackaging.count({
ticketFk: id ticketFk: id
}, options); }, myOptions);
const hasServices = await models.TicketService.count({ const hasServices = await models.TicketService.count({
ticketFk: id ticketFk: id
}, options); }, myOptions);
const hasPurchaseRequests = await models.TicketRequest.count({ const hasPurchaseRequests = await models.TicketRequest.count({
ticketFk: id, ticketFk: id,
isOk: true isOk: true
}, options); }, myOptions);
const isEmpty = !hasSales && !hasPackages && const isEmpty = !hasSales && !hasPackages &&
!hasServices && !hasPurchaseRequests; !hasServices && !hasPurchaseRequests;

View File

@ -25,7 +25,7 @@ module.exports = Self => {
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);
const ticket = await Self.app.models.Ticket.findById(id, { const ticket = await Self.findById(id, {
fields: ['isDeleted', 'refFk'] fields: ['isDeleted', 'refFk']
}, myOptions); }, myOptions);

View File

@ -27,8 +27,8 @@ module.exports = function(Self) {
const userId = ctx.req.accessToken.userId; const userId = ctx.req.accessToken.userId;
const models = Self.app.models; const models = Self.app.models;
const myOptions = {};
let tx; let tx;
let myOptions = {};
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);

View File

@ -1,10 +1,10 @@
const app = require('vn-loopback/server/server'); const models = require('vn-loopback/server/server').models;
describe('ticket addSale()', () => { describe('ticket addSale()', () => {
const ticketId = 13; const ticketId = 13;
it('should create a new sale for the ticket with id 13', async() => { it('should create a new sale for the ticket with id 13', async() => {
const tx = await app.models.Ticket.beginTransaction({}); const tx = await models.Ticket.beginTransaction({});
try { try {
const options = {transaction: tx}; const options = {transaction: tx};
@ -18,7 +18,7 @@ describe('ticket addSale()', () => {
}; };
const itemId = 4; const itemId = 4;
const quantity = 10; const quantity = 10;
const newSale = await app.models.Ticket.addSale(ctx, ticketId, itemId, quantity, options); const newSale = await models.Ticket.addSale(ctx, ticketId, itemId, quantity, options);
expect(newSale.itemFk).toEqual(4); expect(newSale.itemFk).toEqual(4);
@ -30,7 +30,7 @@ describe('ticket addSale()', () => {
}); });
it('should not be able to add a sale if the item quantity is not available', async() => { it('should not be able to add a sale if the item quantity is not available', async() => {
const tx = await app.models.Ticket.beginTransaction({}); const tx = await models.Ticket.beginTransaction({});
let error; let error;
@ -47,7 +47,7 @@ describe('ticket addSale()', () => {
const itemId = 11; const itemId = 11;
const quantity = 10; const quantity = 10;
await app.models.Ticket.addSale(ctx, ticketId, itemId, quantity, options); await models.Ticket.addSale(ctx, ticketId, itemId, quantity, options);
await tx.rollback(); await tx.rollback();
} catch (e) { } catch (e) {
@ -59,7 +59,7 @@ describe('ticket addSale()', () => {
}); });
it('should not be able to add a sale if the ticket is not editable', async() => { it('should not be able to add a sale if the ticket is not editable', async() => {
const tx = await app.models.Ticket.beginTransaction({}); const tx = await models.Ticket.beginTransaction({});
let error; let error;
@ -75,7 +75,7 @@ describe('ticket addSale()', () => {
const notEditableTicketId = 1; const notEditableTicketId = 1;
const itemId = 4; const itemId = 4;
const quantity = 10; const quantity = 10;
await app.models.Ticket.addSale(ctx, notEditableTicketId, itemId, quantity, options); await models.Ticket.addSale(ctx, notEditableTicketId, itemId, quantity, options);
await tx.rollback(); await tx.rollback();
} catch (e) { } catch (e) {

View File

@ -1,6 +1,5 @@
const app = require('vn-loopback/server/server'); const models = require('vn-loopback/server/server').models;
const LoopBackContext = require('loopback-context'); const LoopBackContext = require('loopback-context');
const models = app.models;
describe('ticket canBeInvoiced()', () => { describe('ticket canBeInvoiced()', () => {
const userId = 19; const userId = 19;
@ -82,8 +81,19 @@ describe('ticket canBeInvoiced()', () => {
}); });
it('should return truthy for an invoiceable ticket', async() => { it('should return truthy for an invoiceable ticket', async() => {
const canBeInvoiced = await models.Ticket.canBeInvoiced([ticketId]); const tx = await models.Ticket.beginTransaction({});
expect(canBeInvoiced).toEqual(true); try {
const options = {transaction: tx};
const canBeInvoiced = await models.Ticket.canBeInvoiced([ticketId], options);
expect(canBeInvoiced).toEqual(true);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
}); });

View File

@ -1,17 +1,39 @@
const app = require('vn-loopback/server/server'); const models = require('vn-loopback/server/server').models;
describe('ticket canHaveStowaway()', () => { describe('ticket canHaveStowaway()', () => {
it('should return true if the ticket warehouse have hasStowaway equal 1', async() => { it('should return true if the ticket warehouse have hasStowaway equal 1', async() => {
const ticketId = 16; const tx = await models.Ticket.beginTransaction({});
let canStowaway = await app.models.Ticket.canHaveStowaway(ticketId);
expect(canStowaway).toBeTruthy(); try {
const options = {transaction: tx};
const ticketId = 16;
const canStowaway = await models.Ticket.canHaveStowaway(ticketId, options);
expect(canStowaway).toBeTruthy();
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
it('should return false if the ticket warehouse dont have hasStowaway equal 0', async() => { it('should return false if the ticket warehouse dont have hasStowaway equal 0', async() => {
const ticketId = 10; const tx = await models.Ticket.beginTransaction({});
let canStowaway = await app.models.Ticket.canHaveStowaway(ticketId);
expect(canStowaway).toBeFalsy(); try {
const options = {transaction: tx};
const ticketId = 10;
const canStowaway = await models.Ticket.canHaveStowaway(ticketId, options);
expect(canStowaway).toBeFalsy();
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
}); });

View File

@ -1,4 +1,4 @@
const app = require('vn-loopback/server/server'); const models = require('vn-loopback/server/server').models;
describe('ticket componentUpdate()', () => { describe('ticket componentUpdate()', () => {
const userID = 1101; const userID = 1101;
@ -16,20 +16,20 @@ describe('ticket componentUpdate()', () => {
let componentValue; let componentValue;
beforeAll(async() => { beforeAll(async() => {
const deliveryComponenet = await app.models.Component.findOne({where: {code: 'delivery'}}); const deliveryComponenet = await models.Component.findOne({where: {code: 'delivery'}});
deliveryComponentId = deliveryComponenet.id; deliveryComponentId = deliveryComponenet.id;
componentOfSaleSeven = `SELECT value FROM vn.saleComponent WHERE saleFk = 7 AND componentFk = ${deliveryComponentId}`; componentOfSaleSeven = `SELECT value FROM vn.saleComponent WHERE saleFk = 7 AND componentFk = ${deliveryComponentId}`;
componentOfSaleEight = `SELECT value FROM vn.saleComponent WHERE saleFk = 8 AND componentFk = ${deliveryComponentId}`; componentOfSaleEight = `SELECT value FROM vn.saleComponent WHERE saleFk = 8 AND componentFk = ${deliveryComponentId}`;
[componentValue] = await app.models.SaleComponent.rawSql(componentOfSaleSeven); [componentValue] = await models.SaleComponent.rawSql(componentOfSaleSeven);
firstvalueBeforeChange = componentValue.value; firstvalueBeforeChange = componentValue.value;
[componentValue] = await app.models.SaleComponent.rawSql(componentOfSaleEight); [componentValue] = await models.SaleComponent.rawSql(componentOfSaleEight);
secondvalueBeforeChange = componentValue.value; secondvalueBeforeChange = componentValue.value;
}); });
it('should change the agencyMode to modify the sale components value', async() => { it('should change the agencyMode to modify the sale components value', async() => {
const tx = await app.models.SaleComponent.beginTransaction({}); const tx = await models.SaleComponent.beginTransaction({});
try { try {
const options = {transaction: tx}; const options = {transaction: tx};
@ -59,12 +59,12 @@ describe('ticket componentUpdate()', () => {
} }
}; };
await app.models.Ticket.componentUpdate(ctx, options); await models.Ticket.componentUpdate(ctx, options);
[componentValue] = await app.models.SaleComponent.rawSql(componentOfSaleSeven, null, options); [componentValue] = await models.SaleComponent.rawSql(componentOfSaleSeven, null, options);
let firstvalueAfterChange = componentValue.value; let firstvalueAfterChange = componentValue.value;
[componentValue] = await app.models.SaleComponent.rawSql(componentOfSaleEight, null, options); [componentValue] = await models.SaleComponent.rawSql(componentOfSaleEight, null, options);
let secondvalueAfterChange = componentValue.value; let secondvalueAfterChange = componentValue.value;
expect(firstvalueBeforeChange).not.toEqual(firstvalueAfterChange); expect(firstvalueBeforeChange).not.toEqual(firstvalueAfterChange);
@ -78,7 +78,7 @@ describe('ticket componentUpdate()', () => {
}); });
it('should change the addressFk and check that delivery observations have been changed', async() => { it('should change the addressFk and check that delivery observations have been changed', async() => {
const tx = await app.models.SaleComponent.beginTransaction({}); const tx = await models.SaleComponent.beginTransaction({});
try { try {
const options = {transaction: tx}; const options = {transaction: tx};
@ -107,10 +107,10 @@ describe('ticket componentUpdate()', () => {
} }
} }
}; };
const observationTypeDelivery = await app.models.ObservationType.findOne({ const observationTypeDelivery = await models.ObservationType.findOne({
where: {code: 'delivery'} where: {code: 'delivery'}
}, options); }, options);
const originalTicketObservation = await app.models.TicketObservation.findOne({ const originalTicketObservation = await models.TicketObservation.findOne({
where: { where: {
ticketFk: args.id, ticketFk: args.id,
observationTypeFk: observationTypeDelivery.id} observationTypeFk: observationTypeDelivery.id}
@ -118,9 +118,9 @@ describe('ticket componentUpdate()', () => {
expect(originalTicketObservation).toBeDefined(); expect(originalTicketObservation).toBeDefined();
await app.models.Ticket.componentUpdate(ctx, options); await models.Ticket.componentUpdate(ctx, options);
const removedTicketObservation = await app.models.TicketObservation.findOne({ const removedTicketObservation = await models.TicketObservation.findOne({
where: { where: {
ticketFk: ticketID, ticketFk: ticketID,
observationTypeFk: observationTypeDelivery.id} observationTypeFk: observationTypeDelivery.id}

View File

@ -1,4 +1,4 @@
const app = require('vn-loopback/server/server'); const models = require('vn-loopback/server/server').models;
describe('ticket deleteStowaway()', () => { describe('ticket deleteStowaway()', () => {
const shipId = 16; const shipId = 16;
@ -14,51 +14,62 @@ describe('ticket deleteStowaway()', () => {
}; };
it(`should create an stowaway, delete it and see the states of both stowaway and ship go back to the last states`, async() => { it(`should create an stowaway, delete it and see the states of both stowaway and ship go back to the last states`, async() => {
await app.models.Stowaway.rawSql(` const tx = await models.Ticket.beginTransaction({});
INSERT INTO stowaway (id, shipFk) VALUES (?, ?)
`, [stowawayId, shipId]);
await app.models.Stowaway.rawSql(
`CALL ticketStateUpdate(?, ?)`, [shipId, 'BOARDING']);
await app.models.Stowaway.rawSql(
`CALL ticketStateUpdate(?, ?)`, [stowawayId, 'BOARDING']);
let createdStowaways = await app.models.Stowaway.count({id: stowawayId, shipFk: shipId}); try {
const options = {transaction: tx};
expect(createdStowaways).toEqual(1); await models.Stowaway.rawSql(`
INSERT INTO stowaway (id, shipFk) VALUES (?, ?)
`, [stowawayId, shipId], options);
await models.Stowaway.rawSql(
`CALL ticketStateUpdate(?, ?)`, [shipId, 'BOARDING'], options);
await models.Stowaway.rawSql(
`CALL ticketStateUpdate(?, ?)`, [stowawayId, 'BOARDING'], options);
let shipState = await app.models.TicketLastState.findOne({ let createdStowaways = await models.Stowaway.count({id: stowawayId, shipFk: shipId}, options);
where: {
ticketFk: shipId
}
});
let stowawayState = await app.models.TicketLastState.findOne({
where: {
ticketFk: stowawayId
}
});
expect(shipState.name).toEqual('Embarcando'); expect(createdStowaways).toEqual(1);
expect(stowawayState.name).toEqual('Embarcando');
await app.models.Ticket.deleteStowaway(ctx, shipId); let shipState = await models.TicketLastState.findOne({
await app.models.Ticket.deleteStowaway(ctx, stowawayId); where: {
ticketFk: shipId
}
}, options);
let stowawayState = await models.TicketLastState.findOne({
where: {
ticketFk: stowawayId
}
}, options);
createdStowaways = await app.models.Stowaway.count({id: stowawayId, shipFk: shipId}); expect(shipState.name).toEqual('Embarcando');
expect(stowawayState.name).toEqual('Embarcando');
expect(createdStowaways).toEqual(0); await models.Ticket.deleteStowaway(ctx, shipId, options);
await models.Ticket.deleteStowaway(ctx, stowawayId, options);
shipState = await app.models.TicketLastState.findOne({ createdStowaways = await models.Stowaway.count({id: stowawayId, shipFk: shipId}, options);
where: {
ticketFk: shipId
}
});
stowawayState = await app.models.TicketLastState.findOne({
where: {
ticketFk: stowawayId
}
});
expect(shipState.name).toEqual('OK'); expect(createdStowaways).toEqual(0);
expect(stowawayState.name).toEqual('Libre');
shipState = await models.TicketLastState.findOne({
where: {
ticketFk: shipId
}
}, options);
stowawayState = await models.TicketLastState.findOne({
where: {
ticketFk: stowawayId
}
}, options);
expect(shipState.name).toEqual('OK');
expect(stowawayState.name).toEqual('Libre');
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
}); });

View File

@ -1,106 +1,205 @@
const app = require('vn-loopback/server/server'); const models = require('vn-loopback/server/server').models;
describe('ticket filter()', () => { describe('ticket filter()', () => {
it('should return the tickets matching the filter', async() => { it('should return the tickets matching the filter', async() => {
const ctx = {req: {accessToken: {userId: 9}}, args: {}}; const tx = await models.Ticket.beginTransaction({});
const filter = {order: 'id DESC'};
const result = await app.models.Ticket.filter(ctx, filter);
expect(result.length).toEqual(24); try {
const options = {transaction: tx};
const ctx = {req: {accessToken: {userId: 9}}, args: {}};
const filter = {order: 'id DESC'};
const result = await models.Ticket.filter(ctx, filter, options);
expect(result.length).toEqual(24);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
it('should return the tickets matching the problems on true', async() => { it('should return the tickets matching the problems on true', async() => {
const yesterday = new Date(); const tx = await models.Ticket.beginTransaction({});
yesterday.setHours(0, 0, 0, 0);
const today = new Date();
today.setHours(23, 59, 59, 59);
const ctx = {req: {accessToken: {userId: 9}}, args: { try {
problems: true, const options = {transaction: tx};
from: yesterday,
to: today
}};
const filter = {};
const result = await app.models.Ticket.filter(ctx, filter);
expect(result.length).toEqual(4); const yesterday = new Date();
yesterday.setHours(0, 0, 0, 0);
const today = new Date();
today.setHours(23, 59, 59, 59);
const ctx = {req: {accessToken: {userId: 9}}, args: {
problems: true,
from: yesterday,
to: today
}};
const filter = {};
const result = await models.Ticket.filter(ctx, filter, options);
expect(result.length).toEqual(4);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
it('should return the tickets matching the problems on false', async() => { it('should return the tickets matching the problems on false', async() => {
const yesterday = new Date(); const tx = await models.Ticket.beginTransaction({});
yesterday.setDate(yesterday.getDate() - 1);
yesterday.setHours(0, 0, 0, 0);
const today = new Date();
today.setHours(23, 59, 59, 59);
const ctx = {req: {accessToken: {userId: 9}}, args: { try {
problems: false, const options = {transaction: tx};
from: yesterday,
to: today
}};
const filter = {};
const result = await app.models.Ticket.filter(ctx, filter);
expect(result.length).toEqual(6); const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
yesterday.setHours(0, 0, 0, 0);
const today = new Date();
today.setHours(23, 59, 59, 59);
const ctx = {req: {accessToken: {userId: 9}}, args: {
problems: false,
from: yesterday,
to: today
}};
const filter = {};
const result = await models.Ticket.filter(ctx, filter, options);
expect(result.length).toEqual(6);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
it('should return the tickets matching the problems on null', async() => { it('should return the tickets matching the problems on null', async() => {
const ctx = {req: {accessToken: {userId: 9}}, args: {problems: null}}; const tx = await models.Ticket.beginTransaction({});
const filter = {};
const result = await app.models.Ticket.filter(ctx, filter);
expect(result.length).toEqual(24); try {
const options = {transaction: tx};
const ctx = {req: {accessToken: {userId: 9}}, args: {problems: null}};
const filter = {};
const result = await models.Ticket.filter(ctx, filter, options);
expect(result.length).toEqual(24);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
it('should return the tickets matching the orderId 11', async() => { it('should return the tickets matching the orderId 11', async() => {
const ctx = {req: {accessToken: {userId: 9}}, args: {orderFk: 11}}; const tx = await models.Ticket.beginTransaction({});
const filter = {};
const result = await app.models.Ticket.filter(ctx, filter);
const firstRow = result[0];
expect(result.length).toEqual(1); try {
expect(firstRow.id).toEqual(11); const options = {transaction: tx};
const ctx = {req: {accessToken: {userId: 9}}, args: {orderFk: 11}};
const filter = {};
const result = await models.Ticket.filter(ctx, filter, options);
const firstRow = result[0];
expect(result.length).toEqual(1);
expect(firstRow.id).toEqual(11);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
it('should return the tickets with grouped state "Pending" and not "Ok" nor "BOARDING"', async() => { it('should return the tickets with grouped state "Pending" and not "Ok" nor "BOARDING"', async() => {
const ctx = {req: {accessToken: {userId: 9}}, args: {pending: true}}; const tx = await models.Ticket.beginTransaction({});
const filter = {};
const result = await app.models.Ticket.filter(ctx, filter);
const length = result.length; try {
const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; const options = {transaction: tx};
expect(length).toEqual(7); const ctx = {req: {accessToken: {userId: 9}}, args: {pending: true}};
expect(anyResult.state).toMatch(/(Libre|Arreglar)/); const filter = {};
const result = await models.Ticket.filter(ctx, filter, options);
const length = result.length;
const anyResult = result[Math.floor(Math.random() * Math.floor(length))];
expect(length).toEqual(7);
expect(anyResult.state).toMatch(/(Libre|Arreglar)/);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
it('should return the tickets that are not pending', async() => { it('should return the tickets that are not pending', async() => {
const ctx = {req: {accessToken: {userId: 9}}, args: {pending: false}}; const tx = await models.Ticket.beginTransaction({});
const filter = {};
const result = await app.models.Ticket.filter(ctx, filter);
const firstRow = result[0];
const secondRow = result[1];
const thirdRow = result[2];
expect(result.length).toEqual(12); try {
expect(firstRow.state).toEqual('Entregado'); const options = {transaction: tx};
expect(secondRow.state).toEqual('Entregado');
expect(thirdRow.state).toEqual('Entregado'); const ctx = {req: {accessToken: {userId: 9}}, args: {pending: false}};
const filter = {};
const result = await models.Ticket.filter(ctx, filter, options);
const firstRow = result[0];
const secondRow = result[1];
const thirdRow = result[2];
expect(result.length).toEqual(12);
expect(firstRow.state).toEqual('Entregado');
expect(secondRow.state).toEqual('Entregado');
expect(thirdRow.state).toEqual('Entregado');
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
it('should return the tickets from the worker team', async() => { it('should return the tickets from the worker team', async() => {
const ctx = {req: {accessToken: {userId: 18}}, args: {myTeam: true}}; const tx = await models.Ticket.beginTransaction({});
const filter = {};
const result = await app.models.Ticket.filter(ctx, filter);
expect(result.length).toEqual(20); try {
const options = {transaction: tx};
const ctx = {req: {accessToken: {userId: 18}}, args: {myTeam: true}};
const filter = {};
const result = await models.Ticket.filter(ctx, filter, options);
expect(result.length).toEqual(20);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
it('should return the tickets that are not from the worker team', async() => { it('should return the tickets that are not from the worker team', async() => {
const ctx = {req: {accessToken: {userId: 18}}, args: {myTeam: false}}; const tx = await models.Ticket.beginTransaction({});
const filter = {};
const result = await app.models.Ticket.filter(ctx, filter);
expect(result.length).toEqual(4); try {
const options = {transaction: tx};
const ctx = {req: {accessToken: {userId: 18}}, args: {myTeam: false}};
const filter = {};
const result = await models.Ticket.filter(ctx, filter, options);
expect(result.length).toEqual(4);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
}); });

View File

@ -1,17 +1,39 @@
const app = require('vn-loopback/server/server'); const models = require('vn-loopback/server/server').models;
describe('ticket freightCost()', () => { describe('ticket freightCost()', () => {
it('should return the freight cost of a given ticket', async() => { it('should return the freight cost of a given ticket', async() => {
let ticketId = 7; const tx = await models.Ticket.beginTransaction({});
let freightCost = await app.models.Ticket.freightCost(ticketId);
expect(freightCost).toBe(4); try {
const options = {transaction: tx};
const ticketId = 7;
const freightCost = await models.Ticket.freightCost(ticketId, options);
expect(freightCost).toBe(4);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
it('should return null if the ticket does not exist', async() => { it('should return null if the ticket does not exist', async() => {
let ticketId = 99; const tx = await models.Ticket.beginTransaction({});
let freightCost = await app.models.Ticket.freightCost(ticketId);
expect(freightCost).toBeNull(); try {
const options = {transaction: tx};
const ticketId = 99;
const freightCost = await models.Ticket.freightCost(ticketId, options);
expect(freightCost).toBeNull();
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
}); });

View File

@ -1,20 +1,42 @@
const app = require('vn-loopback/server/server'); const models = require('vn-loopback/server/server').models;
describe('ticket getComponentsSum()', () => { describe('ticket getComponentsSum()', () => {
it('should get the list of component for the ticket sales', async() => { it('should get the list of component for the ticket sales', async() => {
const ticketId = 7; const tx = await models.Ticket.beginTransaction({});
const components = await app.models.Ticket.getComponentsSum(ticketId);
const length = components.length;
const anyComponent = components[Math.floor(Math.random() * Math.floor(length))];
expect(components.length).toBeGreaterThan(0); try {
expect(anyComponent.componentFk).toBeDefined(); const options = {transaction: tx};
const ticketId = 7;
const components = await models.Ticket.getComponentsSum(ticketId, options);
const length = components.length;
const anyComponent = components[Math.floor(Math.random() * Math.floor(length))];
expect(components.length).toBeGreaterThan(0);
expect(anyComponent.componentFk).toBeDefined();
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
it('should return 0 if the given ticket does not have sales', async() => { it('should return 0 if the given ticket does not have sales', async() => {
const ticketWithoutSales = 21; const tx = await models.Ticket.beginTransaction({});
const components = await app.models.Ticket.getComponentsSum(ticketWithoutSales);
expect(components.length).toEqual(0); try {
const options = {transaction: tx};
const ticketWithoutSales = 21;
const components = await models.Ticket.getComponentsSum(ticketWithoutSales, options);
expect(components.length).toEqual(0);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
}); });

View File

@ -1,30 +1,60 @@
const app = require('vn-loopback/server/server'); const models = require('vn-loopback/server/server').models;
let UserError = require('vn-loopback/util/user-error'); let UserError = require('vn-loopback/util/user-error');
describe('ticket getPossibleStowaways()', () => { describe('ticket getPossibleStowaways()', () => {
it(`should throw an error if Can't create stowaway for this ticket`, async() => { it(`should throw an error if Can't create stowaway for this ticket`, async() => {
let error; const tx = await models.Ticket.beginTransaction({});
let ticketId = 10;
await app.models.Ticket.getPossibleStowaways(ticketId) let error;
.catch(e => {
error = e; try {
}); const options = {transaction: tx};
const ticketId = 10;
await models.Ticket.getPossibleStowaways(ticketId, options);
await tx.rollback();
} catch (e) {
await tx.rollback();
error = e;
}
expect(error).toEqual(new UserError(`Can't create stowaway for this ticket`)); expect(error).toEqual(new UserError(`Can't create stowaway for this ticket`));
}); });
it('should return an empty list of tickets for a valid ticket', async() => { it('should return an empty list of tickets for a valid ticket', async() => {
let ticketId = 12; const tx = await models.Ticket.beginTransaction({});
let possibleStowaways = await app.models.Ticket.getPossibleStowaways(ticketId);
expect(possibleStowaways.length).toEqual(0); try {
const options = {transaction: tx};
const ticketId = 12;
const possibleStowaways = await models.Ticket.getPossibleStowaways(ticketId, options);
expect(possibleStowaways.length).toEqual(0);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
it('should return allowed list of tickets for a valid ticket', async() => { it('should return allowed list of tickets for a valid ticket', async() => {
let ticketId = 16; const tx = await models.Ticket.beginTransaction({});
let possibleStowaways = await app.models.Ticket.getPossibleStowaways(ticketId);
expect(possibleStowaways.length).toEqual(1); try {
const options = {transaction: tx};
const ticketId = 16;
const possibleStowaways = await models.Ticket.getPossibleStowaways(ticketId, options);
expect(possibleStowaways.length).toEqual(1);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
}); });

View File

@ -1,14 +1,25 @@
const app = require('vn-loopback/server/server'); const models = require('vn-loopback/server/server').models;
describe('ticket getSales()', () => { describe('ticket getSales()', () => {
it('should return the sales of a ticket', async() => { it('should return the sales of a ticket', async() => {
let sales = await app.models.Ticket.getSales(16); const tx = await models.Ticket.beginTransaction({});
expect(sales.length).toEqual(4); try {
expect(sales[0].item).toBeDefined(); const options = {transaction: tx};
expect(sales[1].item).toBeDefined();
expect(sales[2].item).toBeDefined(); const sales = await models.Ticket.getSales(16, options);
expect(sales[3].item).toBeDefined();
expect(sales[0].claim).toBeDefined(); expect(sales.length).toEqual(4);
expect(sales[0].item).toBeDefined();
expect(sales[1].item).toBeDefined();
expect(sales[2].item).toBeDefined();
expect(sales[3].item).toBeDefined();
expect(sales[0].claim).toBeDefined();
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
}); });

View File

@ -1,15 +1,37 @@
const app = require('vn-loopback/server/server'); const models = require('vn-loopback/server/server').models;
describe('ticket getSalesPersonMana()', () => { describe('ticket getSalesPersonMana()', () => {
it('should get the mana of a salesperson of a given ticket', async() => { it('should get the mana of a salesperson of a given ticket', async() => {
let mana = await app.models.Ticket.getSalesPersonMana(1); const tx = await models.Ticket.beginTransaction({});
expect(mana).toEqual(124); try {
const options = {transaction: tx};
const mana = await models.Ticket.getSalesPersonMana(1, options);
expect(mana).toEqual(124);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
it('should return 0 if the given ticket does not exist', async() => { it('should return 0 if the given ticket does not exist', async() => {
let mana = await app.models.Ticket.getSalesPersonMana(99); const tx = await models.Ticket.beginTransaction({});
expect(mana).toEqual(0); try {
const options = {transaction: tx};
const mana = await models.Ticket.getSalesPersonMana(99, options);
expect(mana).toEqual(0);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
}); });

View File

@ -1,13 +1,23 @@
const app = require('vn-loopback/server/server'); const models = require('vn-loopback/server/server').models;
describe('ticket getTotalVolume()', () => { describe('ticket getTotalVolume()', () => {
it('should return the total volume of a ticket', async() => { it('should return the total volume of a ticket', async() => {
let ticketFk = 1; const tx = await models.Ticket.beginTransaction({});
let expectedResult = 1.568; try {
const options = {transaction: tx};
let result = await app.models.Ticket.getTotalVolume(ticketFk); const ticketFk = 1;
const expectedResult = 1.568;
expect(result.totalVolume).toEqual(expectedResult); const result = await models.Ticket.getTotalVolume(ticketFk, options);
expect(result.totalVolume).toEqual(expectedResult);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
}); });

View File

@ -1,11 +1,21 @@
const app = require('vn-loopback/server/server'); const models = require('vn-loopback/server/server').models;
describe('ticket getVolume()', () => { describe('ticket getVolume()', () => {
it('should call the getVolume method', async() => { it('should call the getVolume method', async() => {
let ticketFk = 1; const tx = await models.Ticket.beginTransaction({});
await app.models.Ticket.getVolume(ticketFk)
.then(response => { try {
expect(response[0].volume).toEqual(1.09); const options = {transaction: tx};
});
const ticketId = 1;
const result = await models.Ticket.getVolume(ticketId, options);
expect(result[0].volume).toEqual(1.09);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
}); });

View File

@ -1,8 +1,8 @@
const app = require('vn-loopback/server/server'); const models = require('vn-loopback/server/server').models;
describe('ticket isEditable()', () => { describe('ticket isEditable()', () => {
it('should return false if the given ticket does not exist', async() => { it('should return false if the given ticket does not exist', async() => {
const tx = await app.models.Ticket.beginTransaction({}); const tx = await models.Ticket.beginTransaction({});
let result; let result;
try { try {
@ -11,7 +11,7 @@ describe('ticket isEditable()', () => {
req: {accessToken: {userId: 9}} req: {accessToken: {userId: 9}}
}; };
result = await app.models.Ticket.isEditable(ctx, 9999, options); result = await models.Ticket.isEditable(ctx, 9999, options);
await tx.rollback(); await tx.rollback();
} catch (e) { } catch (e) {
@ -23,12 +23,12 @@ describe('ticket isEditable()', () => {
}); });
it(`should return false if the given ticket isn't invoiced but isDeleted`, async() => { it(`should return false if the given ticket isn't invoiced but isDeleted`, async() => {
const tx = await app.models.Ticket.beginTransaction({}); const tx = await models.Ticket.beginTransaction({});
let result; let result;
try { try {
const options = {transaction: tx}; const options = {transaction: tx};
const deletedTicket = await app.models.Ticket.findOne({ const deletedTicket = await models.Ticket.findOne({
where: { where: {
invoiceOut: null, invoiceOut: null,
isDeleted: true isDeleted: true
@ -40,7 +40,7 @@ describe('ticket isEditable()', () => {
req: {accessToken: {userId: 9}} req: {accessToken: {userId: 9}}
}; };
result = await app.models.Ticket.isEditable(ctx, deletedTicket.id, options); result = await models.Ticket.isEditable(ctx, deletedTicket.id, options);
await tx.rollback(); await tx.rollback();
} catch (e) { } catch (e) {
@ -52,7 +52,7 @@ describe('ticket isEditable()', () => {
}); });
it('should return true if the given ticket is editable', async() => { it('should return true if the given ticket is editable', async() => {
const tx = await app.models.Ticket.beginTransaction({}); const tx = await models.Ticket.beginTransaction({});
let result; let result;
try { try {
@ -61,7 +61,7 @@ describe('ticket isEditable()', () => {
req: {accessToken: {userId: 9}} req: {accessToken: {userId: 9}}
}; };
result = await app.models.Ticket.isEditable(ctx, 16, options); result = await models.Ticket.isEditable(ctx, 16, options);
await tx.rollback(); await tx.rollback();
} catch (e) { } catch (e) {
@ -73,7 +73,7 @@ describe('ticket isEditable()', () => {
}); });
it('should not be able to edit a deleted or invoiced ticket even for salesAssistant', async() => { it('should not be able to edit a deleted or invoiced ticket even for salesAssistant', async() => {
const tx = await app.models.Ticket.beginTransaction({}); const tx = await models.Ticket.beginTransaction({});
let result; let result;
try { try {
@ -82,7 +82,7 @@ describe('ticket isEditable()', () => {
req: {accessToken: {userId: 21}} req: {accessToken: {userId: 21}}
}; };
result = await app.models.Ticket.isEditable(ctx, 19, options); result = await models.Ticket.isEditable(ctx, 19, options);
await tx.rollback(); await tx.rollback();
} catch (e) { } catch (e) {
@ -94,7 +94,7 @@ describe('ticket isEditable()', () => {
}); });
it('should not be able to edit a deleted or invoiced ticket even for productionBoss', async() => { it('should not be able to edit a deleted or invoiced ticket even for productionBoss', async() => {
const tx = await app.models.Ticket.beginTransaction({}); const tx = await models.Ticket.beginTransaction({});
let result; let result;
try { try {
@ -103,7 +103,7 @@ describe('ticket isEditable()', () => {
req: {accessToken: {userId: 50}} req: {accessToken: {userId: 50}}
}; };
result = await app.models.Ticket.isEditable(ctx, 19, options); result = await models.Ticket.isEditable(ctx, 19, options);
await tx.rollback(); await tx.rollback();
} catch (e) { } catch (e) {
@ -115,7 +115,7 @@ describe('ticket isEditable()', () => {
}); });
it('should not be able to edit a deleted or invoiced ticket even for salesPerson', async() => { it('should not be able to edit a deleted or invoiced ticket even for salesPerson', async() => {
const tx = await app.models.Ticket.beginTransaction({}); const tx = await models.Ticket.beginTransaction({});
let result; let result;
try { try {
@ -124,7 +124,7 @@ describe('ticket isEditable()', () => {
req: {accessToken: {userId: 18}} req: {accessToken: {userId: 18}}
}; };
result = await app.models.Ticket.isEditable(ctx, 19, options); result = await models.Ticket.isEditable(ctx, 19, options);
await tx.rollback(); await tx.rollback();
} catch (e) { } catch (e) {

View File

@ -1,27 +1,71 @@
const app = require('vn-loopback/server/server'); const models = require('vn-loopback/server/server').models;
describe('ticket isEmpty()', () => { describe('ticket isEmpty()', () => {
it('should return false if the ticket contains any packages', async() => { it('should return false if the ticket contains any packages', async() => {
let result = await app.models.Ticket.isEmpty(3); const tx = await models.Ticket.beginTransaction({});
expect(result).toBeFalsy(); try {
const options = {transaction: tx};
const result = await models.Ticket.isEmpty(3, options);
expect(result).toBeFalsy();
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
it('should return false if the ticket contains any services', async() => { it('should return false if the ticket contains any services', async() => {
let result = await app.models.Ticket.isEmpty(8); const tx = await models.Ticket.beginTransaction({});
expect(result).toBeFalsy(); try {
const options = {transaction: tx};
const result = await models.Ticket.isEmpty(8, options);
expect(result).toBeFalsy();
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
it('should return false if the ticket contains any purchase request', async() => { it('should return false if the ticket contains any purchase request', async() => {
let result = await app.models.Ticket.isEmpty(11); const tx = await models.Ticket.beginTransaction({});
expect(result).toBeFalsy(); try {
const options = {transaction: tx};
const result = await models.Ticket.isEmpty(11, options);
expect(result).toBeFalsy();
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
it('should return false if the ticket contains any sale', async() => { it('should return false if the ticket contains any sale', async() => {
let result = await app.models.Ticket.isEmpty(4); const tx = await models.Ticket.beginTransaction({});
expect(result).toBeFalsy(); try {
const options = {transaction: tx};
const result = await models.Ticket.isEmpty(4, options);
expect(result).toBeFalsy();
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
}); });

View File

@ -1,34 +1,67 @@
const app = require('vn-loopback/server/server'); const models = require('vn-loopback/server/server').models;
describe('ticket isLocked()', () => { describe('ticket isLocked()', () => {
it('should return true if the given ticket does not exist', async() => { it('should return true if the given ticket does not exist', async() => {
let result = await app.models.Ticket.isLocked(99999); const tx = await models.Ticket.beginTransaction({});
expect(result).toEqual(true); try {
const options = {transaction: tx};
const result = await models.Ticket.isLocked(99999, options);
expect(result).toEqual(true);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
it('should return true if the given ticket is invoiced', async() => { it('should return true if the given ticket is invoiced', async() => {
let invoicedTicket = await app.models.Ticket.findOne({ const tx = await models.Ticket.beginTransaction({});
where: {invoiceOut: {neq: null}},
fields: ['id']
});
let result = await app.models.Ticket.isLocked(invoicedTicket.id); try {
const options = {transaction: tx};
expect(result).toEqual(true); const invoicedTicket = await models.Ticket.findOne({
where: {invoiceOut: {neq: null}},
fields: ['id']
}, options);
const result = await models.Ticket.isLocked(invoicedTicket.id, options);
expect(result).toEqual(true);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
it(`should return true if the given ticket isn't invoiced but deleted`, async() => { it(`should return true if the given ticket isn't invoiced but deleted`, async() => {
let deletedTicket = await app.models.Ticket.findOne({ const tx = await models.Ticket.beginTransaction({});
where: {
invoiceOut: null,
isDeleted: true
},
fields: ['id']
});
let result = await app.models.Ticket.isLocked(deletedTicket.id); try {
const options = {transaction: tx};
expect(result).toEqual(true); const deletedTicket = await models.Ticket.findOne({
where: {
invoiceOut: null,
isDeleted: true
},
fields: ['id']
}, options);
const result = await models.Ticket.isLocked(deletedTicket.id, options);
expect(result).toEqual(true);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
}); });

View File

@ -1,6 +1,5 @@
const app = require('vn-loopback/server/server'); const models = require('vn-loopback/server/server').models;
const LoopBackContext = require('loopback-context'); const LoopBackContext = require('loopback-context');
const models = app.models;
describe('ticket makeInvoice()', () => { describe('ticket makeInvoice()', () => {
const userId = 19; const userId = 19;
@ -107,6 +106,7 @@ describe('ticket makeInvoice()', () => {
await tx.rollback(); await tx.rollback();
} catch (e) { } catch (e) {
await tx.rollback(); await tx.rollback();
throw e;
} }
}); });
}); });