From 10c7aa70d6fe11767ed91b547fc277e16b72f0ab Mon Sep 17 00:00:00 2001 From: carlosjr Date: Mon, 5 Jul 2021 12:00:49 +0200 Subject: [PATCH 1/7] claim module transactions for filter, summary and isEditable --- modules/claim/back/methods/claim/filter.js | 22 +++--- .../claim/back/methods/claim/getSummary.js | 25 ++++--- .../claim/back/methods/claim/isEditable.js | 12 +++- .../back/methods/claim/specs/filter.spec.js | 57 ++++++++++++---- .../methods/claim/specs/getSummary.spec.js | 23 +++++-- .../methods/claim/specs/isEditable.spec.js | 68 +++++++++++++++---- 6 files changed, 155 insertions(+), 52 deletions(-) diff --git a/modules/claim/back/methods/claim/filter.js b/modules/claim/back/methods/claim/filter.js index 50d20410b..16f23433b 100644 --- a/modules/claim/back/methods/claim/filter.js +++ b/modules/claim/back/methods/claim/filter.js @@ -79,10 +79,14 @@ module.exports = Self => { } }); - Self.filter = async(ctx, filter) => { - let conn = Self.dataSource.connector; + Self.filter = async(ctx, filter, options) => { + const conn = Self.dataSource.connector; + const myOptions = {}; - let where = buildFilter(ctx.args, (param, value) => { + if (typeof options == 'object') + Object.assign(myOptions, options); + + const where = buildFilter(ctx.args, (param, value) => { switch (param) { case 'search': return /^\d+$/.test(value) @@ -111,10 +115,9 @@ module.exports = Self => { filter = mergeFilters(ctx.args.filter, {where}); - let stmts = []; - let stmt; + const stmts = []; - stmt = new ParameterizedSQL( + const stmt = new ParameterizedSQL( `SELECT cl.id, c.name, cl.clientFk, cl.workerFk, u.name AS userName, cs.description, cl.created FROM claim cl LEFT JOIN client c ON c.id = cl.clientFk @@ -124,10 +127,11 @@ module.exports = Self => { ); stmt.merge(conn.makeSuffix(filter)); - let itemsIndex = stmts.push(stmt) - 1; + const itemsIndex = stmts.push(stmt) - 1; + + const sql = ParameterizedSQL.join(stmts, ';'); + const result = await conn.executeStmt(sql, myOptions); - let sql = ParameterizedSQL.join(stmts, ';'); - let result = await conn.executeStmt(sql); return itemsIndex === 0 ? result : result[itemsIndex]; }; }; diff --git a/modules/claim/back/methods/claim/getSummary.js b/modules/claim/back/methods/claim/getSummary.js index 9b04d29a9..d6722d11f 100644 --- a/modules/claim/back/methods/claim/getSummary.js +++ b/modules/claim/back/methods/claim/getSummary.js @@ -19,12 +19,16 @@ module.exports = Self => { } }); - Self.getSummary = async id => { - let promises = []; - let summary = {}; + Self.getSummary = async(id, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const promises = []; + const summary = {}; // Claim - let filter = { where: {id: id}, include: [ @@ -61,13 +65,14 @@ module.exports = Self => { ] }; - promises.push(Self.app.models.Claim.find(filter)); + promises.push(Self.app.models.Claim.find(filter, myOptions)); // Claim detail filter = { where: {claimFk: id}, include: [ - {relation: 'sale', + { + relation: 'sale', scope: { fields: ['concept', 'ticketFk', 'price', 'quantity', 'discount', 'itemFk'], include: { @@ -77,7 +82,7 @@ module.exports = Self => { } ] }; - promises.push(Self.app.models.ClaimBeginning.find(filter)); + promises.push(Self.app.models.ClaimBeginning.find(filter, myOptions)); // Claim developments filter = { @@ -109,7 +114,7 @@ module.exports = Self => { } ] }; - promises.push(Self.app.models.ClaimDevelopment.find(filter)); + promises.push(Self.app.models.ClaimDevelopment.find(filter, myOptions)); // Claim action filter = { @@ -126,9 +131,9 @@ module.exports = Self => { {relation: 'claimBeggining'} ] }; - promises.push(Self.app.models.ClaimEnd.find(filter)); + promises.push(Self.app.models.ClaimEnd.find(filter, myOptions)); - let res = await Promise.all(promises); + const res = await Promise.all(promises, myOptions); [summary.claim] = res[0]; summary.salesClaimed = res[1]; diff --git a/modules/claim/back/methods/claim/isEditable.js b/modules/claim/back/methods/claim/isEditable.js index ce68153b5..cd14d70c7 100644 --- a/modules/claim/back/methods/claim/isEditable.js +++ b/modules/claim/back/methods/claim/isEditable.js @@ -19,15 +19,21 @@ module.exports = Self => { } }); - Self.isEditable = async(ctx, id) => { + Self.isEditable = async(ctx, id, options) => { const userId = ctx.req.accessToken.userId; - const isClaimManager = await Self.app.models.Account.hasRole(userId, 'claimManager'); + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const isClaimManager = await Self.app.models.Account.hasRole(userId, 'claimManager', myOptions); + const claim = await Self.app.models.Claim.findById(id, { fields: ['claimStateFk'], include: [{ relation: 'claimState' }] - }); + }, myOptions); const isClaimResolved = claim && claim.claimState().code == 'resolved'; diff --git a/modules/claim/back/methods/claim/specs/filter.spec.js b/modules/claim/back/methods/claim/specs/filter.spec.js index 187fffaa4..b26afe8c4 100644 --- a/modules/claim/back/methods/claim/specs/filter.spec.js +++ b/modules/claim/back/methods/claim/specs/filter.spec.js @@ -2,26 +2,59 @@ const app = require('vn-loopback/server/server'); describe('claim filter()', () => { it('should return 1 result filtering by id', async() => { - let result = await app.models.Claim.filter({args: {filter: {}, search: 1}}); + const tx = await app.models.Claim.beginTransaction({}); - expect(result.length).toEqual(1); - expect(result[0].id).toEqual(1); + try { + const options = {transaction: tx}; + + const result = await app.models.Claim.filter({args: {filter: {}, search: 1}}, null, options); + + expect(result.length).toEqual(1); + expect(result[0].id).toEqual(1); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return 1 result filtering by string', async() => { - let result = await app.models.Claim.filter({args: {filter: {}, search: 'Tony Stark'}}); + const tx = await app.models.Claim.beginTransaction({}); - expect(result.length).toEqual(1); - expect(result[0].id).toEqual(4); + try { + const options = {transaction: tx}; + + const result = await app.models.Claim.filter({args: {filter: {}, search: 'Tony Stark'}}, null, options); + + expect(result.length).toEqual(1); + expect(result[0].id).toEqual(4); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return 4 results filtering by worker id', async() => { - let result = await app.models.Claim.filter({args: {filter: {}, workerFk: 18}}); + const tx = await app.models.Claim.beginTransaction({}); - expect(result.length).toEqual(4); - expect(result[0].id).toEqual(1); - expect(result[1].id).toEqual(2); - expect(result[2].id).toEqual(3); - expect(result[3].id).toEqual(4); + try { + const options = {transaction: tx}; + + const result = await app.models.Claim.filter({args: {filter: {}, workerFk: 18}}, null, options); + + expect(result.length).toEqual(4); + expect(result[0].id).toEqual(1); + expect(result[1].id).toEqual(2); + expect(result[2].id).toEqual(3); + expect(result[3].id).toEqual(4); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/claim/back/methods/claim/specs/getSummary.spec.js b/modules/claim/back/methods/claim/specs/getSummary.spec.js index 445903377..541f42cfb 100644 --- a/modules/claim/back/methods/claim/specs/getSummary.spec.js +++ b/modules/claim/back/methods/claim/specs/getSummary.spec.js @@ -2,12 +2,23 @@ const app = require('vn-loopback/server/server'); describe('claim getSummary()', () => { it('should return summary with claim, salesClaimed, developments and actions defined ', async() => { - let result = await app.models.Claim.getSummary(1); - let keys = Object.keys(result); + const tx = await app.models.Claim.beginTransaction({}); - expect(keys).toContain('claim'); - expect(keys).toContain('salesClaimed'); - expect(keys).toContain('developments'); - expect(keys).toContain('actions'); + try { + const options = {transaction: tx}; + + const result = await app.models.Claim.getSummary(1, options); + const keys = Object.keys(result); + + expect(keys).toContain('claim'); + expect(keys).toContain('salesClaimed'); + expect(keys).toContain('developments'); + expect(keys).toContain('actions'); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/claim/back/methods/claim/specs/isEditable.spec.js b/modules/claim/back/methods/claim/specs/isEditable.spec.js index 19436e16f..3afea7843 100644 --- a/modules/claim/back/methods/claim/specs/isEditable.spec.js +++ b/modules/claim/back/methods/claim/specs/isEditable.spec.js @@ -4,30 +4,74 @@ describe('claim isEditable()', () => { const salesPerdonId = 18; const claimManagerId = 72; it('should return false if the given claim does not exist', async() => { - let ctx = {req: {accessToken: {userId: claimManagerId}}}; - let result = await app.models.Claim.isEditable(ctx, 99999); + const tx = await app.models.Claim.beginTransaction({}); - expect(result).toEqual(false); + try { + const options = {transaction: tx}; + + const ctx = {req: {accessToken: {userId: claimManagerId}}}; + const result = await app.models.Claim.isEditable(ctx, 99999, options); + + expect(result).toEqual(false); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should not be able to edit a resolved claim for a salesPerson', async() => { - let ctx = {req: {accessToken: {userId: salesPerdonId}}}; - let result = await app.models.Claim.isEditable(ctx, 4); + const tx = await app.models.Claim.beginTransaction({}); - expect(result).toEqual(false); + try { + const options = {transaction: tx}; + + const ctx = {req: {accessToken: {userId: salesPerdonId}}}; + const result = await app.models.Claim.isEditable(ctx, 4, options); + + expect(result).toEqual(false); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should be able to edit a resolved claim for a claimManager', async() => { - let ctx = {req: {accessToken: {userId: claimManagerId}}}; - let result = await app.models.Claim.isEditable(ctx, 4); + const tx = await app.models.Claim.beginTransaction({}); - expect(result).toEqual(true); + try { + const options = {transaction: tx}; + + const ctx = {req: {accessToken: {userId: claimManagerId}}}; + const result = await app.models.Claim.isEditable(ctx, 4, options); + + expect(result).toEqual(true); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should be able to edit a claim for a claimManager', async() => { - let ctx = {req: {accessToken: {userId: salesPerdonId}}}; - let result = await app.models.Claim.isEditable(ctx, 1); + const tx = await app.models.Claim.beginTransaction({}); - expect(result).toEqual(true); + try { + const options = {transaction: tx}; + + const ctx = {req: {accessToken: {userId: salesPerdonId}}}; + const result = await app.models.Claim.isEditable(ctx, 1, options); + + expect(result).toEqual(true); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); From 3b2b4e381943370a14d96b315320adbee2c12fe9 Mon Sep 17 00:00:00 2001 From: carlosjr Date: Thu, 8 Jul 2021 15:53:30 +0200 Subject: [PATCH 2/7] client module changes for transactions --- back/methods/dms/removeFile.js | 4 +- .../back/methods/claim/createFromSales.js | 4 +- .../back/methods/client-dms/removeFile.js | 32 ++- .../client-dms/specs/removeFile.spec.js | 23 +- .../methods/client/addressesPropagateRe.js | 21 +- .../back/methods/client/canCreateTicket.js | 11 +- .../back/methods/client/confirmTransaction.js | 40 ++- .../client/back/methods/client/consumption.js | 55 ++-- .../back/methods/client/createAddress.js | 29 +- .../back/methods/client/createReceipt.js | 53 ++-- .../back/methods/client/createWithUser.js | 40 +-- .../back/methods/client/getAverageInvoiced.js | 11 +- modules/client/back/methods/client/getCard.js | 35 ++- modules/client/back/methods/client/getDebt.js | 11 +- modules/client/back/methods/client/getMana.js | 11 +- .../back/methods/client/getTransactions.js | 17 +- .../back/methods/client/hasCustomerRole.js | 38 +-- .../back/methods/client/isValidClient.js | 21 +- .../back/methods/client/lastActiveTickets.js | 38 ++- modules/client/back/methods/client/sendSms.js | 22 +- .../client/specs/addressesPropagateRe.spec.js | 50 ++-- .../client/specs/canBeInvoiced.spec.js | 21 +- .../client/specs/canCreateTicket.spec.js | 34 ++- .../client/specs/confirmTransaction.spec.js | 36 +-- .../methods/client/specs/consumption.spec.js | 118 +++++--- .../client/specs/createAddress.spec.js | 182 ++++++------ .../client/specs/createReceipt.spec.js | 220 ++++++++------- .../client/specs/createWithUser.spec.js | 89 +++--- .../client/specs/getAverageInvoiced.spec.js | 16 +- .../back/methods/client/specs/getCard.spec.js | 22 +- .../back/methods/client/specs/getDebt.spec.js | 16 +- .../back/methods/client/specs/getMana.spec.js | 16 +- .../client/specs/getTransactions.spec.js | 18 +- .../client/specs/hasCustomerRole.spec.js | 81 +++--- .../client/specs/isValidClient.spec.js | 98 +++++-- .../client/specs/lastActiveTickets.spec.js | 29 +- .../back/methods/client/specs/sendSms.spec.js | 35 ++- .../back/methods/client/specs/summary.spec.js | 109 +++++-- .../client/specs/threeLastActive.spec.js | 12 - .../client/specs/updateAddress.spec.js | 132 +++++---- .../client/specs/updateFiscalData.spec.js | 83 +++--- .../methods/client/specs/uploadFile.spec.js | 29 +- modules/client/back/methods/client/summary.js | 33 ++- .../back/methods/client/updateAddress.js | 161 ++++++----- .../back/methods/client/updateFiscalData.js | 267 ++++++++++-------- .../client/back/methods/client/uploadFile.js | 108 ++++--- .../createWithInsurance.js | 39 +-- .../createWithInsurance.spec.js | 72 ++--- .../methods/greuge/specs/sumAmount.spec.js | 21 +- .../client/back/methods/greuge/sumAmount.js | 11 +- modules/client/back/methods/receipt/filter.js | 110 ++++---- .../back/methods/receipt/specs/filter.spec.js | 22 +- .../methods/recovery/hasActiveRecovery.js | 24 +- .../recovery/hasActiveRecovery.spec.js | 30 +- modules/client/back/methods/sms/send.js | 33 ++- 55 files changed, 1715 insertions(+), 1178 deletions(-) delete mode 100644 modules/client/back/methods/client/specs/threeLastActive.spec.js diff --git a/back/methods/dms/removeFile.js b/back/methods/dms/removeFile.js index 1c50137a0..a9ff36883 100644 --- a/back/methods/dms/removeFile.js +++ b/back/methods/dms/removeFile.js @@ -21,8 +21,9 @@ module.exports = Self => { }); Self.removeFile = async(ctx, id, options) => { + const models = Self.app.models; let tx; - let myOptions = {}; + const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); @@ -33,7 +34,6 @@ module.exports = Self => { } try { - const models = Self.app.models; const dms = await models.Dms.findById(id, null, myOptions); const trashDmsType = await models.DmsType.findOne({ where: {code: 'trash'} diff --git a/modules/claim/back/methods/claim/createFromSales.js b/modules/claim/back/methods/claim/createFromSales.js index 32d1edd97..2dd1b75c2 100644 --- a/modules/claim/back/methods/claim/createFromSales.js +++ b/modules/claim/back/methods/claim/createFromSales.js @@ -25,8 +25,9 @@ module.exports = Self => { }); Self.createFromSales = async(ctx, ticketId, sales, options) => { + const models = Self.app.models; let tx; - let myOptions = {}; + const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); @@ -35,7 +36,6 @@ module.exports = Self => { tx = await Self.beginTransaction({}); myOptions.transaction = tx; } - const models = Self.app.models; const userId = ctx.req.accessToken.userId; try { diff --git a/modules/client/back/methods/client-dms/removeFile.js b/modules/client/back/methods/client-dms/removeFile.js index 5ff123630..786a32928 100644 --- a/modules/client/back/methods/client-dms/removeFile.js +++ b/modules/client/back/methods/client-dms/removeFile.js @@ -4,12 +4,12 @@ module.exports = Self => { accessType: 'WRITE', accepts: { arg: 'id', - type: 'Number', + type: 'number', description: 'The document id', http: {source: 'path'} }, returns: { - type: 'Object', + type: 'object', root: true }, http: { @@ -18,13 +18,33 @@ module.exports = Self => { } }); - Self.removeFile = async(ctx, id) => { + Self.removeFile = async(ctx, id, options) => { const models = Self.app.models; - const clientDms = await Self.findById(id); + let tx; + const myOptions = {}; - await models.Dms.removeFile(ctx, clientDms.dmsFk); + if (typeof options == 'object') + Object.assign(myOptions, options); - return clientDms.destroy(); + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + const clientDms = await Self.findById(id, null, myOptions); + + await models.Dms.removeFile(ctx, clientDms.dmsFk, myOptions); + + const destroyedClient = await clientDms.destroy(myOptions); + + if (tx) await tx.commit(); + + return destroyedClient; + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } }; }; diff --git a/modules/client/back/methods/client-dms/specs/removeFile.spec.js b/modules/client/back/methods/client-dms/specs/removeFile.spec.js index c663e881e..6dac71293 100644 --- a/modules/client/back/methods/client-dms/specs/removeFile.spec.js +++ b/modules/client/back/methods/client-dms/specs/removeFile.spec.js @@ -1,17 +1,24 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('ClientDms removeFile()', () => { - const clientDmsFk = 3; it(`should return an error for a user without enough privileges`, async() => { - let clientId = 1101; - let ctx = {req: {accessToken: {userId: clientId}}}; + const tx = await models.Client.beginTransaction({}); let error; - await app.models.ClientDms.removeFile(ctx, clientDmsFk).catch(e => { + + try { + const options = {transaction: tx}; + const clientDmsFk = 3; + const clientId = 1101; + const ctx = {req: {accessToken: {userId: clientId}}}; + + await models.ClientDms.removeFile(ctx, clientDmsFk, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); error = e; - }).finally(() => { - expect(error.message).toEqual(`You don't have enough privileges`); - }); + } expect(error).toBeDefined(); }); diff --git a/modules/client/back/methods/client/addressesPropagateRe.js b/modules/client/back/methods/client/addressesPropagateRe.js index 31cafa654..bd6742cbb 100644 --- a/modules/client/back/methods/client/addressesPropagateRe.js +++ b/modules/client/back/methods/client/addressesPropagateRe.js @@ -12,7 +12,7 @@ module.exports = function(Self) { }, { arg: 'data', - type: 'Object', + type: 'object', required: true, description: 'data with new value', http: {source: 'body'} @@ -29,12 +29,21 @@ module.exports = function(Self) { } }); - Self.addressesPropagateRe = async(id, data) => { - if (data.hasOwnProperty('isEqualizated')) { - let client = await Self.app.models.Client.findById(id); + Self.addressesPropagateRe = async(id, data, options) => { + const models = Self.app.models; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const isEqualizated = Object.prototype.hasOwnProperty.call(data, 'isEqualizated'); + if (isEqualizated) { + const client = await models.Client.findById(id, null, myOptions); + if (client) { - await Self.app.models.Address.updateAll({clientFk: id}, data); - await client.updateAttributes({hasToInvoiceByAddress: false}); + await models.Address.updateAll({clientFk: id}, data, myOptions); + await client.updateAttributes({hasToInvoiceByAddress: false}, myOptions); + return true; } } diff --git a/modules/client/back/methods/client/canCreateTicket.js b/modules/client/back/methods/client/canCreateTicket.js index a47a5f6f3..fa10c0172 100644 --- a/modules/client/back/methods/client/canCreateTicket.js +++ b/modules/client/back/methods/client/canCreateTicket.js @@ -20,8 +20,15 @@ module.exports = Self => { } }); - Self.canCreateTicket = async id => { - const client = await Self.app.models.Client.findById(id); + Self.canCreateTicket = async(id, options) => { + const models = Self.app.models; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const client = await models.Client.findById(id, null, myOptions); + const canCreateTicket = client && client.isActive; if (!canCreateTicket) return false; diff --git a/modules/client/back/methods/client/confirmTransaction.js b/modules/client/back/methods/client/confirmTransaction.js index 467a8627b..a1969d6fd 100644 --- a/modules/client/back/methods/client/confirmTransaction.js +++ b/modules/client/back/methods/client/confirmTransaction.js @@ -9,7 +9,7 @@ module.exports = Self => { description: 'Transaction id' }], returns: { - type: 'Object', + type: 'object', root: true }, http: { @@ -18,23 +18,32 @@ module.exports = Self => { } }); - Self.confirmTransaction = async(ctx, id) => { - let userId = ctx.req.accessToken.userId; - let tx = await Self.beginTransaction({}); + Self.confirmTransaction = async(ctx, id, options) => { + const models = Self.app.models; + const userId = ctx.req.accessToken.userId; + + let tx; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } try { - let options = {transaction: tx}; + const oldTpvTransaction = await models.TpvTransaction.findById(id, null, myOptions); - let oldTpvTransaction = await Self.app.models.TpvTransaction.findById(id, null, options); + const confirm = await Self.rawSql('CALL hedera.tpvTransaction_confirmById(?)', [id], myOptions); - let confirm = await Self.rawSql('CALL hedera.tpvTransaction_confirmById(?)', [id], options); + const tpvTransaction = await models.TpvTransaction.findById(id, null, myOptions); - let tpvTransaction = await Self.app.models.TpvTransaction.findById(id, null, options); + const oldInstance = {status: oldTpvTransaction.status}; + const newInstance = {status: tpvTransaction.status}; - let oldInstance = {status: oldTpvTransaction.status}; - let newInstance = {status: tpvTransaction.status}; - - let logRecord = { + const logRecord = { originFk: tpvTransaction.clientFk, userFk: userId, action: 'update', @@ -44,12 +53,13 @@ module.exports = Self => { newInstance: newInstance }; - await Self.app.models.ClientLog.create(logRecord, options); + await models.ClientLog.create(logRecord, myOptions); + + if (tx) await tx.commit(); - await tx.commit(); return confirm; } catch (e) { - await tx.rollback(); + if (tx) await tx.rollback(); throw e; } }; diff --git a/modules/client/back/methods/client/consumption.js b/modules/client/back/methods/client/consumption.js index 8430c4661..0e94608a3 100644 --- a/modules/client/back/methods/client/consumption.js +++ b/modules/client/back/methods/client/consumption.js @@ -10,44 +10,52 @@ module.exports = Self => { accepts: [ { arg: 'filter', - type: 'Object', + type: 'object', description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string' - }, { + }, + { arg: 'search', - type: 'String', + type: 'string', description: `If it's and integer searchs by id, otherwise it searchs by name` - }, { + }, + { arg: 'itemId', - type: 'Number', + type: 'number', description: 'Item id' - }, { + }, + { arg: 'categoryId', - type: 'Number', + type: 'number', description: 'Category id' - }, { + }, + { arg: 'typeId', - type: 'Number', + type: 'number', description: 'Item type id', - }, { + }, + { arg: 'buyerId', - type: 'Number', + type: 'number', description: 'Buyer id' - }, { + }, + { arg: 'from', - type: 'Date', + type: 'date', description: `The from date filter` - }, { + }, + { arg: 'to', - type: 'Date', + type: 'date', description: `The to date filter` - }, { + }, + { arg: 'grouped', - type: 'Boolean', + type: 'boolean', description: 'Group by item' } ], returns: { - type: ['Object'], + type: ['object'], root: true }, http: { @@ -56,7 +64,12 @@ module.exports = Self => { } }); - Self.consumption = async(ctx, filter) => { + Self.consumption = async(ctx, filter, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + const conn = Self.dataSource.connector; const args = ctx.args; const where = buildFilter(ctx.args, (param, value) => { @@ -83,7 +96,7 @@ module.exports = Self => { }); filter = mergeFilters(filter, {where}); - let stmt = new ParameterizedSQL('SELECT'); + const stmt = new ParameterizedSQL('SELECT'); if (args.grouped) stmt.merge(`SUM(s.quantity) AS quantity,`); else @@ -121,6 +134,6 @@ module.exports = Self => { stmt.merge(conn.makePagination(filter)); - return conn.executeStmt(stmt); + return conn.executeStmt(stmt, myOptions); }; }; diff --git a/modules/client/back/methods/client/createAddress.js b/modules/client/back/methods/client/createAddress.js index 450b16722..8e6db2a22 100644 --- a/modules/client/back/methods/client/createAddress.js +++ b/modules/client/back/methods/client/createAddress.js @@ -62,7 +62,7 @@ module.exports = function(Self) { }], returns: { root: true, - type: 'Object' + type: 'object' }, http: { verb: 'post', @@ -70,18 +70,26 @@ module.exports = function(Self) { } }); - Self.createAddress = async(ctx, clientFk) => { + Self.createAddress = async(ctx, clientFk, options) => { const models = Self.app.models; const args = ctx.args; - const tx = await models.Address.beginTransaction({}); + let tx; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } try { - const options = {transaction: tx}; const province = await models.Province.findById(args.provinceFk, { include: { relation: 'country' } - }, options); + }, myOptions); const isUeeMember = province.country().isUeeMember; if (!isUeeMember && !args.incotermsFk) @@ -91,19 +99,20 @@ module.exports = function(Self) { throw new UserError(`Customs agent is required for a non UEE member`); delete args.ctx; // Remove unwanted properties - const newAddress = await models.Address.create(args, options); - const client = await Self.findById(clientFk, null, options); + const newAddress = await models.Address.create(args, myOptions); + const client = await Self.findById(clientFk, null, myOptions); if (args.isDefaultAddress) { await client.updateAttributes({ defaultAddressFk: newAddress.id - }, options); + }, myOptions); } - await tx.commit(); + if (tx) await tx.commit(); + return newAddress; } catch (e) { - await tx.rollback(); + if (tx) await tx.rollback(); throw e; } }; diff --git a/modules/client/back/methods/client/createReceipt.js b/modules/client/back/methods/client/createReceipt.js index 7eb47e70a..c93a86047 100644 --- a/modules/client/back/methods/client/createReceipt.js +++ b/modules/client/back/methods/client/createReceipt.js @@ -48,19 +48,26 @@ module.exports = function(Self) { } }); - Self.createReceipt = async ctx => { + Self.createReceipt = async(ctx, options) => { const models = Self.app.models; const args = ctx.args; - const tx = await models.Address.beginTransaction({}); + let tx; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } try { - const options = {transaction: tx}; - delete args.ctx; // Remove unwanted properties - const newReceipt = await models.Receipt.create(args, options); - const clientOriginal = await models.Client.findById(args.clientFk); - const bank = await models.Bank.findById(args.bankFk); - const accountingType = await models.AccountingType.findById(bank.accountingTypeFk); + const newReceipt = await models.Receipt.create(args, myOptions); + const originalClient = await models.Client.findById(args.clientFk, myOptions); + const bank = await models.Bank.findById(args.bankFk, null, myOptions); + const accountingType = await models.AccountingType.findById(bank.accountingTypeFk, null, myOptions); if (accountingType.code == 'compensation') { if (!args.compensationAccount) @@ -70,14 +77,16 @@ module.exports = function(Self) { where: { account: args.compensationAccount } - }); + }, myOptions); + let clientCompensation = {}; + if (!supplierCompensation) { clientCompensation = await models.Client.findOne({ where: { accountingAccount: args.compensationAccount } - }); + }, myOptions); } if (!supplierCompensation && !clientCompensation) throw new UserError('Invalid account'); @@ -87,20 +96,21 @@ module.exports = function(Self) { [ args.compensationAccount, args.bankFk, - accountingType.receiptDescription + clientOriginal.accountingAccount, + accountingType.receiptDescription + originalClient.accountingAccount, args.amountPaid, args.companyFk, - clientOriginal.accountingAccount + originalClient.accountingAccount ], - options); + myOptions + ); } else if (accountingType.isAutoConciliated == true) { - const description = `${clientOriginal.id} : ${clientOriginal.socialName} - ${accountingType.receiptDescription}`; + const description = `${originalClient.id} : ${originalClient.socialName} - ${accountingType.receiptDescription}`; const [xdiarioNew] = await Self.rawSql( `SELECT xdiario_new(?, CURDATE(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ledger;`, [ null, bank.account, - clientOriginal.accountingAccount, + originalClient.accountingAccount, description, args.amountPaid, 0, @@ -112,13 +122,14 @@ module.exports = function(Self) { false, args.companyFk ], - options); + myOptions + ); await Self.rawSql( `SELECT xdiario_new(?, CURDATE(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`, [ xdiarioNew.ledger, - clientOriginal.accountingAccount, + originalClient.accountingAccount, bank.account, description, 0, @@ -131,13 +142,15 @@ module.exports = function(Self) { false, args.companyFk ], - options); + myOptions + ); } - await tx.commit(); + if (tx) await tx.commit(); + return newReceipt; } catch (e) { - await tx.rollback(); + if (tx) await tx.rollback(); throw e; } }; diff --git a/modules/client/back/methods/client/createWithUser.js b/modules/client/back/methods/client/createWithUser.js index 79713b467..f32979d52 100644 --- a/modules/client/back/methods/client/createWithUser.js +++ b/modules/client/back/methods/client/createWithUser.js @@ -16,22 +16,29 @@ module.exports = function(Self) { } }); - Self.createWithUser = async data => { - let firstEmail = data.email ? data.email.split(',')[0] : null; - let user = { + Self.createWithUser = async(data, options) => { + const models = Self.app.models; + let tx; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + const firstEmail = data.email ? data.email.split(',')[0] : null; + const user = { name: data.userName, email: firstEmail, password: parseInt(Math.random() * 100000000000000) }; - const Account = Self.app.models.Account; - const Address = Self.app.models.Address; - const tx = await Account.beginTransaction({}); try { - let options = {transaction: tx}; - - let account = await Account.create(user, options); - let client = await Self.create({ + const account = await models.Account.create(user, myOptions); + const client = await Self.create({ id: account.id, name: data.name, fi: data.fi, @@ -44,9 +51,9 @@ module.exports = function(Self) { provinceFk: data.provinceFk, countryFk: data.countryFk, isEqualizated: data.isEqualizated - }, options); + }, myOptions); - let address = await Address.create({ + const address = await models.Address.create({ clientFk: client.id, nickname: client.name, city: client.city, @@ -55,16 +62,17 @@ module.exports = function(Self) { provinceFk: client.provinceFk, isEqualizated: client.isEqualizated, isActive: true - }, options); + }, myOptions); await client.updateAttributes({ defaultAddressFk: address.id - }, options); + }, myOptions); + + if (tx) await tx.commit(); - await tx.commit(); return client; } catch (e) { - await tx.rollback(); + if (tx) await tx.rollback(); throw e; } }; diff --git a/modules/client/back/methods/client/getAverageInvoiced.js b/modules/client/back/methods/client/getAverageInvoiced.js index 5c806879c..95d01a88c 100644 --- a/modules/client/back/methods/client/getAverageInvoiced.js +++ b/modules/client/back/methods/client/getAverageInvoiced.js @@ -19,9 +19,14 @@ module.exports = Self => { } }); - Self.getAverageInvoiced = async clientFk => { - let query = `SELECT invoiced FROM vn.annualAverageInvoiced WHERE clientFk = ?`; - let [invoiced] = await Self.rawSql(query, [clientFk]); + Self.getAverageInvoiced = async(clientFk, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const query = `SELECT invoiced FROM vn.annualAverageInvoiced WHERE clientFk = ?`; + const [invoiced] = await Self.rawSql(query, [clientFk], myOptions); return invoiced; }; diff --git a/modules/client/back/methods/client/getCard.js b/modules/client/back/methods/client/getCard.js index 5379f4e0e..c3ce00bf3 100644 --- a/modules/client/back/methods/client/getCard.js +++ b/modules/client/back/methods/client/getCard.js @@ -9,7 +9,7 @@ module.exports = function(Self) { http: {source: 'path'} }, returns: { - type: 'Object', + type: 'object', root: true }, http: { @@ -18,8 +18,13 @@ module.exports = function(Self) { } }); - Self.getCard = async function(id) { - let client = await Self.findOne({ + Self.getCard = async(id, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const client = await Self.findOne({ where: { id: id }, @@ -29,38 +34,44 @@ module.exports = function(Self) { scope: { fields: ['id', 'name'] } - }, { + }, + { relation: 'province', scope: { fields: ['id', 'name'] } - }, { - }, { + }, + { relation: 'salesPersonUser', scope: { fields: ['id', 'name'] } - }, { + }, + { relation: 'country', scope: { fields: ['id', 'country'] } - }, { + }, + { relation: 'payMethod', scope: { fields: ['id', 'name'] } - }, { + }, + { relation: 'account', scope: { fields: ['id', 'name', 'active'] } } ] - }); + }, myOptions); - let query = `SELECT vn.clientGetDebt(?, CURDATE()) AS debt`; - client.debt = (await Self.rawSql(query, [id]))[0].debt; + const query = `SELECT vn.clientGetDebt(?, CURDATE()) AS debt`; + const data = await Self.rawSql(query, [id], myOptions); + + client.debt = data[0].debt; return client; }; diff --git a/modules/client/back/methods/client/getDebt.js b/modules/client/back/methods/client/getDebt.js index c4f167731..8eb0f2480 100644 --- a/modules/client/back/methods/client/getDebt.js +++ b/modules/client/back/methods/client/getDebt.js @@ -19,9 +19,14 @@ module.exports = Self => { } }); - Self.getDebt = async clientFk => { - let query = `SELECT vn.clientGetDebt(?, CURDATE()) AS debt`; - let [debt] = await Self.rawSql(query, [clientFk]); + Self.getDebt = async(clientFk, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const query = `SELECT vn.clientGetDebt(?, CURDATE()) AS debt`; + const [debt] = await Self.rawSql(query, [clientFk], myOptions); return debt; }; diff --git a/modules/client/back/methods/client/getMana.js b/modules/client/back/methods/client/getMana.js index 88e337e32..8b6604e21 100644 --- a/modules/client/back/methods/client/getMana.js +++ b/modules/client/back/methods/client/getMana.js @@ -19,9 +19,14 @@ module.exports = Self => { } }); - Self.getMana = async clientFk => { - let query = `SELECT vn.clientGetMana(?) AS mana`; - let [mana] = await Self.rawSql(query, [clientFk]); + Self.getMana = async(clientFk, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const query = `SELECT vn.clientGetMana(?) AS mana`; + const [mana] = await Self.rawSql(query, [clientFk], myOptions); return mana; }; diff --git a/modules/client/back/methods/client/getTransactions.js b/modules/client/back/methods/client/getTransactions.js index ab8a23347..45183bbdc 100644 --- a/modules/client/back/methods/client/getTransactions.js +++ b/modules/client/back/methods/client/getTransactions.js @@ -7,12 +7,12 @@ module.exports = Self => { accessType: 'READ', accepts: [{ arg: 'filter', - type: 'Object', + type: 'object', description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string', http: {source: 'query'} }], returns: { - type: ['Object'], + type: ['object'], root: true }, http: { @@ -21,9 +21,14 @@ module.exports = Self => { } }); - Self.getTransactions = async filter => { - let conn = Self.dataSource.connector; - let stmt = new ParameterizedSQL(` + Self.getTransactions = async(filter, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const conn = Self.dataSource.connector; + const stmt = new ParameterizedSQL(` SELECT t.id, t.clientFk, @@ -39,6 +44,6 @@ module.exports = Self => { stmt.merge(conn.makeSuffix(filter, 't')); - return await Self.rawStmt(stmt); + return Self.rawStmt(stmt, myOptions); }; }; diff --git a/modules/client/back/methods/client/hasCustomerRole.js b/modules/client/back/methods/client/hasCustomerRole.js index 559de1fc7..d66839936 100644 --- a/modules/client/back/methods/client/hasCustomerRole.js +++ b/modules/client/back/methods/client/hasCustomerRole.js @@ -2,23 +2,13 @@ module.exports = Self => { Self.remoteMethod('hasCustomerRole', { description: 'Comprueba si un usuario tiene el rol de cliente', accessType: 'READ', - accepts: [ - { - arg: 'id', - type: 'string', - required: true, - description: 'The user id', - http: {source: 'path'} - }, { - arg: 'context', - type: 'object', - required: true, - description: 'Filter defining where', - http: function(context) { - return context.req.query; - } - } - ], + accepts: [{ + arg: 'id', + type: 'string', + required: true, + description: 'The user id', + http: {source: 'path'} + }], returns: { type: 'boolean', root: true @@ -29,17 +19,19 @@ module.exports = Self => { } }); - Self.hasCustomerRole = (id, context, callback) => { - let query = ` + Self.hasCustomerRole = (id, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const query = ` SELECT COUNT(*) > 0 isCustomer FROM salix.Account A JOIN salix.Role r ON r.id = A.roleFK WHERE r.name = 'customer' AND A.id IN (?)`; - Self.rawSql(query, [id]).then( - instances => callback(null, instances[0]), - err => callback(err) - ); + return Self.rawSql(query, [id], myOptions); }; }; diff --git a/modules/client/back/methods/client/isValidClient.js b/modules/client/back/methods/client/isValidClient.js index 692da79ee..a3bb0151f 100644 --- a/modules/client/back/methods/client/isValidClient.js +++ b/modules/client/back/methods/client/isValidClient.js @@ -9,14 +9,6 @@ module.exports = Self => { required: true, description: 'The user id', http: {source: 'path'} - }, { - arg: 'context', - type: 'object', - required: true, - description: 'Filter defining where', - http: function(context) { - return context.req.query; - } } ], returns: { @@ -29,8 +21,13 @@ module.exports = Self => { } }); - Self.isValidClient = async id => { - let query = ` + Self.isValidClient = async(id, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const query = ` SELECT r.name FROM salix.Account a JOIN vn.client c ON a.id = c.id @@ -38,9 +35,9 @@ module.exports = Self => { JOIN salix.Role r ON r.id = rm.roleId WHERE a.id = ? AND c.isActive AND c.isTaxDataChecked`; - let roleNames = await Self.rawSql(query, [id]); + const roleNames = await Self.rawSql(query, [id], myOptions); - let isEmployee = roleNames.findIndex(role => { + const isEmployee = roleNames.findIndex(role => { return role.name === 'employee'; }); diff --git a/modules/client/back/methods/client/lastActiveTickets.js b/modules/client/back/methods/client/lastActiveTickets.js index 7444dff45..da38dbee8 100644 --- a/modules/client/back/methods/client/lastActiveTickets.js +++ b/modules/client/back/methods/client/lastActiveTickets.js @@ -2,19 +2,22 @@ module.exports = Self => { Self.remoteMethod('lastActiveTickets', { description: 'Returns the last three active tickets of a client', accessType: 'READ', - accepts: [{ - arg: 'id', - type: 'Number', - required: true, - description: 'Client id', - http: {source: 'path'} - }, { - arg: 'ticketId', - type: 'Number', - required: true - }], + accepts: [ + { + arg: 'id', + type: 'number', + required: true, + description: 'Client id', + http: {source: 'path'} + }, + { + arg: 'ticketId', + type: 'number', + required: true + } + ], returns: { - type: ['Object'], + type: ['object'], root: true }, http: { @@ -23,8 +26,13 @@ module.exports = Self => { } }); - Self.lastActiveTickets = async(id, ticketId) => { - const ticket = await Self.app.models.Ticket.findById(ticketId); + Self.lastActiveTickets = async(id, ticketId, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const ticket = await Self.app.models.Ticket.findById(ticketId, null, myOptions); const query = ` SELECT t.id, @@ -47,7 +55,7 @@ module.exports = Self => { ORDER BY t.shipped LIMIT 10`; - return Self.rawSql(query, [id, ticketId, ticket.warehouseFk]); + return Self.rawSql(query, [id, ticketId, ticket.warehouseFk], myOptions); }; }; diff --git a/modules/client/back/methods/client/sendSms.js b/modules/client/back/methods/client/sendSms.js index a39d4c75a..cc11d17be 100644 --- a/modules/client/back/methods/client/sendSms.js +++ b/modules/client/back/methods/client/sendSms.js @@ -5,23 +5,23 @@ module.exports = Self => { accessType: 'WRITE', accepts: [{ arg: 'id', - type: 'Number', + type: 'number', required: true, description: 'The ticket id', http: {source: 'path'} }, { arg: 'destination', - type: 'String', + type: 'string', required: true, }, { arg: 'message', - type: 'String', + type: 'string', required: true, }], returns: { - type: 'Object', + type: 'object', root: true }, http: { @@ -30,11 +30,17 @@ module.exports = Self => { } }); - Self.sendSms = async(ctx, id, destination, message) => { + Self.sendSms = async(ctx, id, destination, message, options) => { + const models = Self.app.models; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + const userId = ctx.req.accessToken.userId; - let sms = await Self.app.models.Sms.send(ctx, id, destination, message); - let logRecord = { + const sms = await models.Sms.send(ctx, id, destination, message); + const logRecord = { originFk: id, userFk: userId, action: 'insert', @@ -48,7 +54,7 @@ module.exports = Self => { } }; - const clientLog = await Self.app.models.ClientLog.create(logRecord); + const clientLog = await models.ClientLog.create(logRecord, myOptions); sms.logId = clientLog.id; diff --git a/modules/client/back/methods/client/specs/addressesPropagateRe.spec.js b/modules/client/back/methods/client/specs/addressesPropagateRe.spec.js index 412385092..069c7bd25 100644 --- a/modules/client/back/methods/client/specs/addressesPropagateRe.spec.js +++ b/modules/client/back/methods/client/specs/addressesPropagateRe.spec.js @@ -1,40 +1,30 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Client addressesPropagateRe', () => { - let client; - beforeEach(async() => { - client = await app.models.Client.findById(1101); - await app.models.Address.update({clientFk: 1101}, {isEqualizated: false}); - await client.updateAttributes({hasToInvoiceByAddress: true}); - }); - - afterAll(async done => { - await app.models.Address.update({clientFk: 1101}, {isEqualizated: false}); - await client.updateAttributes({hasToInvoiceByAddress: true}); - - done(); - }); - it('should propagate the isEqualizated on both addresses of Mr Wayne and set hasToInvoiceByAddress to false', async() => { - let id = 1101; - let data = { - isEqualizated: true - }; + const tx = await models.Client.beginTransaction({}); - let resultAddress = await app.models.Address.find({where: {clientFk: id}}); - let resultClient = await app.models.Client.find({where: {id: id}}); + try { + const options = {transaction: tx}; - expect(resultAddress[0].isEqualizated).toBeFalsy(); - expect(resultAddress[1].isEqualizated).toBeFalsy(); - expect(resultClient[0].hasToInvoiceByAddress).toBeTruthy(); + let id = 1101; + let data = { + isEqualizated: true + }; - await app.models.Client.addressesPropagateRe(id, data); + await models.Client.addressesPropagateRe(id, data, options); - resultAddress = await app.models.Address.find({where: {clientFk: id}}); - resultClient = await app.models.Client.find({where: {id: id}}); + const addresses = await models.Address.find({where: {clientFk: id}}, options); + const client = await models.Client.findById(id, null, options); - expect(resultAddress[0].isEqualizated).toBeTruthy(); - expect(resultAddress[1].isEqualizated).toBeTruthy(); - expect(resultClient[0].hasToInvoiceByAddress).toBeFalsy(); + expect(addresses[0].isEqualizated).toBeTruthy(); + expect(addresses[1].isEqualizated).toBeTruthy(); + expect(client.hasToInvoiceByAddress).toBeFalsy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/client/back/methods/client/specs/canBeInvoiced.spec.js b/modules/client/back/methods/client/specs/canBeInvoiced.spec.js index 0ac1a3930..c070eba37 100644 --- a/modules/client/back/methods/client/specs/canBeInvoiced.spec.js +++ b/modules/client/back/methods/client/specs/canBeInvoiced.spec.js @@ -1,4 +1,4 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); describe('client canBeInvoiced()', () => { @@ -7,7 +7,6 @@ describe('client canBeInvoiced()', () => { const activeCtx = { accessToken: {userId: userId} }; - const models = app.models; beforeAll(async done => { spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ @@ -18,7 +17,7 @@ describe('client canBeInvoiced()', () => { }); it('should return falsy for a client without the data checked', async() => { - const tx = await models.Ticket.beginTransaction({}); + const tx = await models.Client.beginTransaction({}); try { const options = {transaction: tx}; @@ -37,7 +36,7 @@ describe('client canBeInvoiced()', () => { }); it('should return falsy for a client with invoicing disabled', async() => { - const tx = await models.Ticket.beginTransaction({}); + const tx = await models.Client.beginTransaction({}); try { const options = {transaction: tx}; @@ -56,8 +55,18 @@ describe('client canBeInvoiced()', () => { }); it('should return truthy for an invoiceable client', async() => { - const canBeInvoiced = await models.Client.canBeInvoiced(clientId); + const tx = await models.Client.beginTransaction({}); - expect(canBeInvoiced).toEqual(true); + try { + const options = {transaction: tx}; + + const canBeInvoiced = await models.Client.canBeInvoiced(clientId, options); + + expect(canBeInvoiced).toEqual(true); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); }); diff --git a/modules/client/back/methods/client/specs/canCreateTicket.spec.js b/modules/client/back/methods/client/specs/canCreateTicket.spec.js index c8bacd364..2a2797899 100644 --- a/modules/client/back/methods/client/specs/canCreateTicket.spec.js +++ b/modules/client/back/methods/client/specs/canCreateTicket.spec.js @@ -1,17 +1,37 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Client canCreateTicket', () => { it('should receive true if the client is active', async() => { - let id = 1105; - let canCreateTicket = await app.models.Client.canCreateTicket(id); + const tx = await models.Client.beginTransaction({}); - expect(canCreateTicket).toBeTruthy(); + try { + const options = {transaction: tx}; + + const id = 1105; + const canCreateTicket = await models.Client.canCreateTicket(id, null, options); + + expect(canCreateTicket).toBeTruthy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); it(`should receive false if the client isn't active`, async() => { - let id = 1106; - let canCreateTicket = await app.models.Client.canCreateTicket(id); + const tx = await models.Client.beginTransaction({}); - expect(canCreateTicket).toBe(false); + try { + const options = {transaction: tx}; + + const id = 1106; + const canCreateTicket = await models.Client.canCreateTicket(id, null, options); + + expect(canCreateTicket).toBe(false); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); }); diff --git a/modules/client/back/methods/client/specs/confirmTransaction.spec.js b/modules/client/back/methods/client/specs/confirmTransaction.spec.js index 5fe638001..ce1034887 100644 --- a/modules/client/back/methods/client/specs/confirmTransaction.spec.js +++ b/modules/client/back/methods/client/specs/confirmTransaction.spec.js @@ -1,24 +1,26 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Client confirmTransaction', () => { - const transactionId = 2; - - afterAll(async done => { - await app.models.Client.rawSql(` - CALL hedera.tpvTransaction_undo(?)`, [transactionId]); - - done(); - }); - it('should call confirmTransaction() method to mark transaction as confirmed', async() => { - let ctx = {req: {accessToken: {userId: 1}}}; - await app.models.Client.confirmTransaction(ctx, transactionId); + const tx = await models.Client.beginTransaction({}); + const transactionId = 2; - let [receipt] = await app.models.Client.rawSql( - `SELECT receiptFk - FROM hedera.tpvTransaction - WHERE id = ?`, [transactionId]); + try { + const options = {transaction: tx}; - expect(receipt.receiptFk).toBeGreaterThan(0); + let ctx = {req: {accessToken: {userId: 1}}}; + await models.Client.confirmTransaction(ctx, transactionId, options); + + let [receipt] = await models.Client.rawSql( + `SELECT receiptFk + FROM hedera.tpvTransaction + WHERE id = ?`, [transactionId], options); + + expect(receipt.receiptFk).toBeGreaterThan(0); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); }); diff --git a/modules/client/back/methods/client/specs/consumption.spec.js b/modules/client/back/methods/client/specs/consumption.spec.js index 277f59a88..06a121e03 100644 --- a/modules/client/back/methods/client/specs/consumption.spec.js +++ b/modules/client/back/methods/client/specs/consumption.spec.js @@ -1,60 +1,90 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('client consumption() filter', () => { it('should return a list of buyed items by ticket', async() => { - const ctx = {req: {accessToken: {userId: 9}}, args: {}}; - const filter = { - where: { - clientFk: 1101 - }, - order: 'itemTypeFk, itemName, itemSize' - }; - const result = await app.models.Client.consumption(ctx, filter); + const tx = await models.Client.beginTransaction({}); - expect(result.length).toEqual(10); + try { + const options = {transaction: tx}; + + const ctx = {req: {accessToken: {userId: 9}}, args: {}}; + const filter = { + where: { + clientFk: 1101 + }, + order: 'itemTypeFk, itemName, itemSize' + }; + const result = await app.models.Client.consumption(ctx, filter, options); + + expect(result.length).toEqual(10); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); it('should return a list of tickets grouped by item', async() => { - const ctx = {req: {accessToken: {userId: 9}}, - args: { - grouped: true - } - }; - const filter = { - where: { - clientFk: 1101 - }, - order: 'itemFk' - }; - const result = await app.models.Client.consumption(ctx, filter); + const tx = await models.Client.beginTransaction({}); - const firstRow = result[0]; - const secondRow = result[1]; - const thirdRow = result[2]; + try { + const options = {transaction: tx}; - expect(result.length).toEqual(3); - expect(firstRow.quantity).toEqual(10); - expect(secondRow.quantity).toEqual(15); - expect(thirdRow.quantity).toEqual(20); + const ctx = {req: {accessToken: {userId: 9}}, + args: { + grouped: true + } + }; + const filter = { + where: { + clientFk: 1101 + }, + order: 'itemFk' + }; + const result = await app.models.Client.consumption(ctx, filter, options); + + const firstRow = result[0]; + const secondRow = result[1]; + const thirdRow = result[2]; + + expect(result.length).toEqual(3); + expect(firstRow.quantity).toEqual(10); + expect(secondRow.quantity).toEqual(15); + expect(thirdRow.quantity).toEqual(20); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); it('should return a list of tickets from the item id 4', async() => { - const ctx = {req: {accessToken: {userId: 9}}, - args: { - itemId: 4 - } - }; - const filter = { - where: { - clientFk: 1101 - }, - order: 'itemTypeFk, itemName, itemSize' - }; - const result = await app.models.Client.consumption(ctx, filter); + const tx = await models.Client.beginTransaction({}); - const expectedItemId = 4; - const firstRow = result[0]; + try { + const options = {transaction: tx}; - expect(firstRow.itemFk).toEqual(expectedItemId); + const ctx = {req: {accessToken: {userId: 9}}, + args: { + itemId: 4 + } + }; + const filter = { + where: { + clientFk: 1101 + }, + order: 'itemTypeFk, itemName, itemSize' + }; + const result = await app.models.Client.consumption(ctx, filter, options); + + const expectedItemId = 4; + const firstRow = result[0]; + + expect(firstRow.itemFk).toEqual(expectedItemId); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); }); diff --git a/modules/client/back/methods/client/specs/createAddress.spec.js b/modules/client/back/methods/client/specs/createAddress.spec.js index 73c9e0297..d934ae1c8 100644 --- a/modules/client/back/methods/client/specs/createAddress.spec.js +++ b/modules/client/back/methods/client/specs/createAddress.spec.js @@ -1,4 +1,4 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Address createAddress', () => { const clientFk = 1101; @@ -7,107 +7,131 @@ describe('Address createAddress', () => { const customAgentOneId = 1; it('should throw a non uee member error if no incoterms is defined', async() => { - const expectedResult = 'My edited address'; - const ctx = { - args: { - provinceFk: provinceFk, - nickname: expectedResult, - street: 'Wall Street', - city: 'New York', - customsAgentFk: customAgentOneId - } - }; + const tx = await models.Client.beginTransaction({}); + + let error; try { - await app.models.Client.createAddress(ctx, clientFk); + const options = {transaction: tx}; + + const expectedResult = 'My edited address'; + const ctx = { + args: { + provinceFk: provinceFk, + nickname: expectedResult, + street: 'Wall Street', + city: 'New York', + customsAgentFk: customAgentOneId + } + }; + + await models.Client.createAddress(ctx, clientFk, options); + + await tx.rollback(); } catch (e) { - err = e; + await tx.rollback(); + error = e; } - expect(err).toBeDefined(); - expect(err.message).toEqual('Incoterms is required for a non UEE member'); + expect(error).toBeDefined(); + expect(error.message).toEqual('Incoterms is required for a non UEE member'); }); it('should throw a non uee member error if no customsAgent is defined', async() => { - const expectedResult = 'My edited address'; - const ctx = { - args: { - provinceFk: provinceFk, - nickname: expectedResult, - street: 'Wall Street', - city: 'New York', - incotermsFk: incotermsFk - } - }; + const tx = await models.Client.beginTransaction({}); + + let error; try { - await app.models.Client.createAddress(ctx, clientFk); + const options = {transaction: tx}; + + const expectedResult = 'My edited address'; + const ctx = { + args: { + provinceFk: provinceFk, + nickname: expectedResult, + street: 'Wall Street', + city: 'New York', + incotermsFk: incotermsFk + } + }; + + await models.Client.createAddress(ctx, clientFk, options); + + await tx.rollback(); } catch (e) { - err = e; + await tx.rollback(); + error = e; } - expect(err).toBeDefined(); - expect(err.message).toEqual('Customs agent is required for a non UEE member'); - }); - - it('should verify that client defaultAddressFk is untainted', async() => { - const client = await app.models.Client.findById(clientFk); - - expect(client.defaultAddressFk).toEqual(1); + expect(error).toBeDefined(); + expect(error.message).toEqual('Customs agent is required for a non UEE member'); }); it('should create a new address and set as a client default address', async() => { - const ctx = { - args: { - clientFk: 1101, - provinceFk: 1, - nickname: 'My address', - street: 'Wall Street', - city: 'New York', - phone: 678678678, - mobile: 678678678, - postalCode: 46680, - agencyModeFk: 1, - incotermsFk: incotermsFk, - customsAgentFk: customAgentOneId, - isDefaultAddress: true - } - }; + const tx = await models.Client.beginTransaction({}); - const address = await app.models.Client.createAddress(ctx, clientFk); - const client = await app.models.Client.findById(clientFk); + try { + const options = {transaction: tx}; - expect(client.defaultAddressFk).toEqual(address.id); + const ctx = { + args: { + clientFk: 1101, + provinceFk: 1, + nickname: 'My address', + street: 'Wall Street', + city: 'New York', + phone: 678678678, + mobile: 678678678, + postalCode: 46680, + agencyModeFk: 1, + incotermsFk: incotermsFk, + customsAgentFk: customAgentOneId, + isDefaultAddress: true + } + }; - // restores - await client.updateAttributes({defaultAddressFk: 1}); - await address.destroy(); + const address = await models.Client.createAddress(ctx, clientFk, options); + const client = await models.Client.findById(clientFk, null, options); + + expect(client.defaultAddressFk).toEqual(address.id); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); it('should create a new address and set all properties', async() => { - const ctx = { - args: { - clientFk: 1101, - provinceFk: 1, - nickname: 'My address', - street: 'Wall Street', - city: 'New York', - phone: '678678678', - mobile: '678678678', - postalCode: '46680', - agencyModeFk: 1, - incotermsFk: incotermsFk, - customsAgentFk: customAgentOneId, - isDefaultAddress: true - } - }; + const tx = await models.Client.beginTransaction({}); - address = await app.models.Client.createAddress(ctx, clientFk); + try { + const options = {transaction: tx}; - expect(address).toEqual(jasmine.objectContaining(ctx.args)); - // restores - const client = await app.models.Client.findById(clientFk); - await client.updateAttributes({defaultAddressFk: 1}); - await address.destroy(); + const ctx = { + args: { + clientFk: 1101, + provinceFk: 1, + nickname: 'My address', + street: 'Wall Street', + city: 'New York', + phone: '678678678', + mobile: '678678678', + postalCode: '46680', + agencyModeFk: 1, + incotermsFk: incotermsFk, + customsAgentFk: customAgentOneId, + isDefaultAddress: true + } + }; + + address = await models.Client.createAddress(ctx, clientFk, options); + + expect(address).toEqual(jasmine.objectContaining(ctx.args)); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); }); diff --git a/modules/client/back/methods/client/specs/createReceipt.spec.js b/modules/client/back/methods/client/specs/createReceipt.spec.js index cc5526310..929e43e49 100644 --- a/modules/client/back/methods/client/specs/createReceipt.spec.js +++ b/modules/client/back/methods/client/specs/createReceipt.spec.js @@ -1,4 +1,4 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); describe('Client createReceipt', () => { @@ -27,49 +27,55 @@ describe('Client createReceipt', () => { }); it('should create a new receipt', async() => { - const bankFk = 1; - ctx.args = { - clientFk: clientFk, - payed: payed, - companyFk: companyFk, - bankFk: bankFk, - amountPaid: amountPaid, - description: description - }; + const tx = await models.Client.beginTransaction({}); - const receipt = await app.models.Client.createReceipt(ctx); - delete ctx.args.payed; + try { + const options = {transaction: tx}; - const till = await app.models.Till.findOne({ - where: { + const bankFk = 1; + ctx.args = { + clientFk: clientFk, + payed: payed, + companyFk: companyFk, bankFk: bankFk, - in: amountPaid, - number: clientFk - } - }); + amountPaid: amountPaid, + description: description + }; - expect(receipt).toEqual(jasmine.objectContaining(ctx.args)); + const receipt = await models.Client.createReceipt(ctx, options); + delete ctx.args.payed; - // restores - await receipt.destroy(); - await till.destroy(); + expect(receipt).toEqual(jasmine.objectContaining(ctx.args)); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); it('should throw Compensation account is empty', async() => { - const bankFk = 3; + const tx = await models.Client.beginTransaction({}); - ctx.args = { - clientFk: clientFk, - payed: payed, - companyFk: companyFk, - bankFk: bankFk, - amountPaid: amountPaid, - description: description - }; + let error; try { - await app.models.Client.createReceipt(ctx); + const options = {transaction: tx}; + + const bankFk = 3; + ctx.args = { + clientFk: clientFk, + payed: payed, + companyFk: companyFk, + bankFk: bankFk, + amountPaid: amountPaid, + description: description + }; + + await models.Client.createReceipt(ctx, options); + + await tx.rollback(); } catch (e) { + await tx.rollback(); error = e; } @@ -78,21 +84,29 @@ describe('Client createReceipt', () => { }); it('should throw Invalid account if compensationAccount does not belongs to a client nor a supplier', async() => { + const tx = await models.Client.beginTransaction({}); + let error; - const bankFk = 3; - ctx.args = { - clientFk: clientFk, - payed: payed, - companyFk: companyFk, - bankFk: bankFk, - amountPaid: amountPaid, - description: description, - compensationAccount: 'non existing account' - }; try { - await app.models.Client.createReceipt(ctx); + const options = {transaction: tx}; + + const bankFk = 3; + ctx.args = { + clientFk: clientFk, + payed: payed, + companyFk: companyFk, + bankFk: bankFk, + amountPaid: amountPaid, + description: description, + compensationAccount: 'non existing account' + }; + + await models.Client.createReceipt(ctx, options); + + await tx.rollback(); } catch (e) { + await tx.rollback(); error = e; } @@ -101,84 +115,78 @@ describe('Client createReceipt', () => { }); it('should create a new receipt with a compensation for a client', async() => { - const bankFk = 3; + const tx = await models.Client.beginTransaction({}); - ctx.args = { - clientFk: clientFk, - payed: payed, - companyFk: companyFk, - bankFk: bankFk, - amountPaid: amountPaid, - description: description, - compensationAccount: '4300000001' - }; - const receipt = await app.models.Client.createReceipt(ctx); - const receiptCompensated = await app.models.Receipt.findOne({ - where: { - clientFk: 1, - bankFk: ctx.args.bankFk - } - }); + try { + const options = {transaction: tx}; - const till = await app.models.Till.findOne({ - where: { + const bankFk = 3; + + ctx.args = { + clientFk: clientFk, + payed: payed, + companyFk: companyFk, bankFk: bankFk, - in: amountPaid, - number: clientFk - } - }); + amountPaid: amountPaid, + description: description, + compensationAccount: '4300000001' + }; + const receipt = await models.Client.createReceipt(ctx, options); + const receiptCompensated = await models.Receipt.findOne({ + where: { + clientFk: 1, + bankFk: ctx.args.bankFk + } + }, options); - delete ctx.args.payed; + delete ctx.args.payed; - expect(receipt).toEqual(jasmine.objectContaining(ctx.args)); - expect(receipt.amountPaid).toEqual(-receiptCompensated.amountPaid); + expect(receipt).toEqual(jasmine.objectContaining(ctx.args)); + expect(receipt.amountPaid).toEqual(-receiptCompensated.amountPaid); - // restores - await receipt.destroy(); - await receiptCompensated.destroy(); - await till.destroy(); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); it('should create a new receipt with a compensation for a supplier', async() => { - const bankFk = 3; + const tx = await models.Client.beginTransaction({}); - ctx.args = { - clientFk: clientFk, - payed: payed, - companyFk: companyFk, - bankFk: bankFk, - amountPaid: amountPaid, - description: description, - compensationAccount: '4100000001' - }; - const receipt = await app.models.Client.createReceipt(ctx); + try { + const options = {transaction: tx}; - const paymentCompensated = await app.models.Payment.findOne({ - where: { - clientFk: ctx.args.sale, - payed: ctx.args.payed, - amountPaid: ctx.args.amountPaid, - bankFk: ctx.args.bankFk - } - }); + const bankFk = 3; - const till = await app.models.Till.findOne({ - where: { - bankFk: ctx.args.bankFk, - in: amountPaid, - number: clientFk - } - }); + ctx.args = { + clientFk: clientFk, + payed: payed, + companyFk: companyFk, + bankFk: bankFk, + amountPaid: amountPaid, + description: description, + compensationAccount: '4100000001' + }; + const receipt = await models.Client.createReceipt(ctx, options); - delete ctx.args.payed; + const paymentCompensated = await models.Payment.findOne({ + where: { + clientFk: ctx.args.sale, + payed: ctx.args.payed, + amountPaid: ctx.args.amountPaid, + bankFk: ctx.args.bankFk + } + }, options); - expect(receipt).toEqual(jasmine.objectContaining(ctx.args)); + delete ctx.args.payed; - expect(paymentCompensated.amountPaid).toEqual(paymentCompensated.amountPaid); + expect(receipt).toEqual(jasmine.objectContaining(ctx.args)); - // restores - await receipt.destroy(); - await paymentCompensated.destroy(); - await till.destroy(); + expect(paymentCompensated.amountPaid).toEqual(paymentCompensated.amountPaid); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); }); diff --git a/modules/client/back/methods/client/specs/createWithUser.spec.js b/modules/client/back/methods/client/specs/createWithUser.spec.js index 35de8b300..307a2be48 100644 --- a/modules/client/back/methods/client/specs/createWithUser.spec.js +++ b/modules/client/back/methods/client/specs/createWithUser.spec.js @@ -1,28 +1,7 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Client Create', () => { - const clientName = 'Wade'; - const AccountName = 'Deadpool'; - - afterEach(async done => { - let address = await app.models.Address.findOne({where: {nickname: clientName}}); - let client = await app.models.Client.findOne({where: {name: clientName}}); - let account = await app.models.Account.findOne({where: {name: AccountName}}); - - if (address && client && account) { - 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(); - }); - - let newAccount = { + const newAccount = { userName: 'Deadpool', email: 'Deadpool@marvel.com', fi: '16195279J', @@ -33,34 +12,66 @@ describe('Client Create', () => { }; it(`should not find Deadpool as he's not created yet`, async() => { - let account = await app.models.Account.findOne({where: {name: newAccount.userName}}); - let client = await app.models.Client.findOne({where: {name: newAccount.name}}); + const tx = await models.Client.beginTransaction({}); - expect(account).toEqual(null); - expect(client).toEqual(null); + try { + const options = {transaction: tx}; + + const account = await models.Account.findOne({where: {name: newAccount.userName}}, options); + const client = await models.Client.findOne({where: {name: newAccount.name}}, options); + + expect(account).toEqual(null); + expect(client).toEqual(null); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); it('should create a new account', async() => { - let client = await app.models.Client.createWithUser(newAccount); - let account = await app.models.Account.findOne({where: {name: newAccount.userName}}); + const tx = await models.Client.beginTransaction({}); - expect(account.name).toEqual(newAccount.userName); + try { + const options = {transaction: tx}; - expect(client.id).toEqual(account.id); - expect(client.name).toEqual(newAccount.name); - expect(client.email).toEqual(newAccount.email); - expect(client.fi).toEqual(newAccount.fi); - expect(client.socialName).toEqual(newAccount.socialName); + const client = await models.Client.createWithUser(newAccount, options); + const account = await models.Account.findOne({where: {name: newAccount.userName}}, options); + + expect(account.name).toEqual(newAccount.userName); + expect(client.id).toEqual(account.id); + expect(client.name).toEqual(newAccount.name); + expect(client.email).toEqual(newAccount.email); + expect(client.fi).toEqual(newAccount.fi); + expect(client.socialName).toEqual(newAccount.socialName); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); it('should not be able to create a user if exists', async() => { - await app.models.Client.createWithUser(newAccount); + const tx = await models.Client.beginTransaction({}); + + let error; + try { - let client = await app.models.Client.createWithUser(newAccount); + const options = {transaction: tx}; + + await models.Client.createWithUser(newAccount, options); + const client = await models.Client.createWithUser(newAccount, options); expect(client).toBeNull(); - } catch (err) { - expect(err.details.codes.name[0]).toEqual('uniqueness'); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; } + + const errorName = error.details.codes.name[0]; + + expect(errorName).toEqual('uniqueness'); }); }); diff --git a/modules/client/back/methods/client/specs/getAverageInvoiced.spec.js b/modules/client/back/methods/client/specs/getAverageInvoiced.spec.js index 6b4949833..3a4458736 100644 --- a/modules/client/back/methods/client/specs/getAverageInvoiced.spec.js +++ b/modules/client/back/methods/client/specs/getAverageInvoiced.spec.js @@ -1,9 +1,19 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('client getAverageInvoiced()', () => { it('should call the getAverageInvoiced method', async() => { - const {invoiced} = await app.models.Client.getAverageInvoiced(1101); + const tx = await models.Client.beginTransaction({}); - expect(invoiced).toEqual(1500); + try { + const options = {transaction: tx}; + + const {invoiced} = await models.Client.getAverageInvoiced(1101, options); + + expect(invoiced).toEqual(1500); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); }); diff --git a/modules/client/back/methods/client/specs/getCard.spec.js b/modules/client/back/methods/client/specs/getCard.spec.js index f4f6d63c9..a7e985311 100644 --- a/modules/client/back/methods/client/specs/getCard.spec.js +++ b/modules/client/back/methods/client/specs/getCard.spec.js @@ -1,12 +1,22 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Client getCard()', () => { it('should receive a formated card of Bruce Wayne', async() => { - let id = 1101; - let result = await app.models.Client.getCard(id); + const tx = await models.Client.beginTransaction({}); - expect(result.id).toEqual(id); - expect(result.name).toEqual('Bruce Wayne'); - expect(result.debt).toEqual(jasmine.any(Number)); + try { + const options = {transaction: tx}; + + const id = 1101; + const result = await models.Client.getCard(id, options); + + expect(result.id).toEqual(id); + expect(result.name).toEqual('Bruce Wayne'); + expect(result.debt).toEqual(jasmine.any(Number)); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); }); diff --git a/modules/client/back/methods/client/specs/getDebt.spec.js b/modules/client/back/methods/client/specs/getDebt.spec.js index 0028c640d..93b80dad4 100644 --- a/modules/client/back/methods/client/specs/getDebt.spec.js +++ b/modules/client/back/methods/client/specs/getDebt.spec.js @@ -1,10 +1,20 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('client getDebt()', () => { it('should return the client debt', async() => { - let result = await app.models.Client.getDebt(1101); + const tx = await models.Client.beginTransaction({}); - expect(result.debt).toEqual(jasmine.any(Number)); + try { + const options = {transaction: tx}; + + const result = await models.Client.getDebt(1101, options); + + expect(result.debt).toEqual(jasmine.any(Number)); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); }); diff --git a/modules/client/back/methods/client/specs/getMana.spec.js b/modules/client/back/methods/client/specs/getMana.spec.js index 2db58426c..00170eac9 100644 --- a/modules/client/back/methods/client/specs/getMana.spec.js +++ b/modules/client/back/methods/client/specs/getMana.spec.js @@ -1,9 +1,19 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('client getMana()', () => { it('should call the getMana method', async() => { - let result = await app.models.Client.getMana(1105); + const tx = await models.Client.beginTransaction({}); - expect(result.mana).toEqual(0.34); + try { + const options = {transaction: tx}; + + const result = await models.Client.getMana(1105, options); + + expect(result.mana).toEqual(0.34); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); }); diff --git a/modules/client/back/methods/client/specs/getTransactions.spec.js b/modules/client/back/methods/client/specs/getTransactions.spec.js index 34db3d1f7..992355668 100644 --- a/modules/client/back/methods/client/specs/getTransactions.spec.js +++ b/modules/client/back/methods/client/specs/getTransactions.spec.js @@ -1,10 +1,20 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Client getTransations', () => { it('should call getTransations() method to receive a list of Web Payments from Bruce Wayne', async() => { - let filter = {where: {clientFk: 1101}}; - let result = await app.models.Client.getTransactions(filter); + const tx = await models.Client.beginTransaction({}); - expect(result[1].id).toBeTruthy(); + try { + const options = {transaction: tx}; + + const filter = {where: {clientFk: 1101}}; + const result = await models.Client.getTransactions(filter, options); + + expect(result[1].id).toBeTruthy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); }); diff --git a/modules/client/back/methods/client/specs/hasCustomerRole.spec.js b/modules/client/back/methods/client/specs/hasCustomerRole.spec.js index 96bc74f8a..6cd4f63a3 100644 --- a/modules/client/back/methods/client/specs/hasCustomerRole.spec.js +++ b/modules/client/back/methods/client/specs/hasCustomerRole.spec.js @@ -1,59 +1,74 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Client hasCustomerRole', () => { - it('should call the hasCustomerRole() method with a customer id', done => { - let id = 1101; - let params = {}; + it('should call the hasCustomerRole() method with a customer id', async() => { + const tx = await models.Client.beginTransaction({}); - let callback = (error, result) => { - if (error) return done.fail(error); + try { + const options = {transaction: tx}; + + const id = 1101; + + const [result] = await models.Client.hasCustomerRole(id, options); expect(result).toEqual(jasmine.objectContaining({isCustomer: 1})); - done(); - }; - app.models.Client.hasCustomerRole(id, params, callback); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); - it('should call the hasCustomerRole() method with a non customer id', done => { - let id = 8; - let params = {}; + it('should call the hasCustomerRole() method with a non customer id', async() => { + const tx = await models.Client.beginTransaction({}); - let callback = (error, result) => { - if (error) return done.fail(error); + try { + const options = {transaction: tx}; + + const id = 8; + const [result] = await models.Client.hasCustomerRole(id, options); expect(result).toEqual(jasmine.objectContaining({isCustomer: 0})); - done(); - }; - app.models.Client.hasCustomerRole(id, params, callback); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); - it('should call the hasCustomerRole() method with an unreal id', done => { - let id = 999; - let params = {}; + it('should call the hasCustomerRole() method with an unreal id', async() => { + const tx = await models.Client.beginTransaction({}); - let callback = (error, result) => { - if (error) return done.fail(error); + try { + const options = {transaction: tx}; + + const id = 999; + + const [result] = await models.Client.hasCustomerRole(id, options); expect(result).toEqual(jasmine.objectContaining({isCustomer: 0})); - done(); - }; - app.models.Client.hasCustomerRole(id, params, callback); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); - it('should call the hasCustomerRole() method with an invalid id', done => { - let id = 'WRONG!'; - let params = {}; + it('should call the hasCustomerRole() method with an invalid id', async() => { + const tx = await models.Client.beginTransaction({}); - let callback = (error, result) => { - if (error) return done.fail(error); + try { + const options = {transaction: tx}; + + const id = 'WRONG!'; + + const [result] = await models.Client.hasCustomerRole(id, options); expect(result).toEqual(jasmine.objectContaining({isCustomer: 0})); - done(); - }; - app.models.Client.hasCustomerRole(id, params, callback); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); }); diff --git a/modules/client/back/methods/client/specs/isValidClient.spec.js b/modules/client/back/methods/client/specs/isValidClient.spec.js index 9d7af1d59..34bab4646 100644 --- a/modules/client/back/methods/client/specs/isValidClient.spec.js +++ b/modules/client/back/methods/client/specs/isValidClient.spec.js @@ -1,45 +1,105 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Client isValidClient', () => { it('should call the isValidClient() method with a client id and receive true', async() => { - let id = 1101; - let result = await app.models.Client.isValidClient(id); + const tx = await models.Client.beginTransaction({}); - expect(result).toBeTruthy(); + try { + const options = {transaction: tx}; + + const id = 1101; + const result = await models.Client.isValidClient(id, options); + + expect(result).toBeTruthy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); it('should call the isValidClient() method with an employee id to receive false', async() => { - let id = 1; - let result = await app.models.Client.isValidClient(id); + const tx = await models.Client.beginTransaction({}); - expect(result).toBeFalsy(); + try { + const options = {transaction: tx}; + + const id = 1; + const result = await models.Client.isValidClient(id, options); + + expect(result).toBeFalsy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); it('should call the isValidClient() method with an unexistant id and receive false', async() => { - let id = 999; - let result = await app.models.Client.isValidClient(id); + const tx = await models.Client.beginTransaction({}); - expect(result).toBeFalsy(); + try { + const options = {transaction: tx}; + + const id = 999; + const result = await models.Client.isValidClient(id, options); + + expect(result).toBeFalsy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); it('should call the isValidClient() method with an invalid id and receive false', async() => { - let id = 'Pepinillos'; - let result = await app.models.Client.isValidClient(id); + const tx = await models.Client.beginTransaction({}); - expect(result).toBeFalsy(); + try { + const options = {transaction: tx}; + + const id = 'Pepinillos'; + const result = await models.Client.isValidClient(id, options); + + expect(result).toBeFalsy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); it('should call the isValidClient() method with a customer id which isnt active and return false', async() => { - let id = '1106'; - let result = await app.models.Client.isValidClient(id); + const tx = await models.Client.beginTransaction({}); - expect(result).toBeFalsy(); + try { + const options = {transaction: tx}; + + const id = '1106'; + const result = await models.Client.isValidClient(id, options); + + expect(result).toBeFalsy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); it('should call the isValidClient() method with a customer id which his data isnt verified and return false', async() => { - let id = '110'; - let result = await app.models.Client.isValidClient(id); + const tx = await models.Client.beginTransaction({}); - expect(result).toBeFalsy(); + try { + const options = {transaction: tx}; + + const id = '110'; + const result = await models.Client.isValidClient(id, options); + + expect(result).toBeFalsy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); }); diff --git a/modules/client/back/methods/client/specs/lastActiveTickets.spec.js b/modules/client/back/methods/client/specs/lastActiveTickets.spec.js index 8ed3c9805..55d2ec0f4 100644 --- a/modules/client/back/methods/client/specs/lastActiveTickets.spec.js +++ b/modules/client/back/methods/client/specs/lastActiveTickets.spec.js @@ -1,18 +1,27 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Client last active tickets', () => { it('should receive an array of last active tickets of Bruce Wayne', async() => { - const ticketId = 22; - const clientId = 1109; - const warehouseId = 5; - const result = await app.models.Client.lastActiveTickets(clientId, ticketId, warehouseId); + const tx = await models.Client.beginTransaction({}); - const length = result.length; - const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; + try { + const options = {transaction: tx}; + const ticketId = 22; + const clientId = 1109; - const properties = Object.keys(anyResult); + const result = await models.Client.lastActiveTickets(clientId, ticketId, options); - expect(properties.length).toEqual(9); - expect(result.length).toEqual(3); + const length = result.length; + const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; + + const properties = Object.keys(anyResult); + + expect(properties.length).toEqual(9); + expect(result.length).toEqual(3); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); }); diff --git a/modules/client/back/methods/client/specs/sendSms.spec.js b/modules/client/back/methods/client/specs/sendSms.spec.js index c8de1916f..290fab103 100644 --- a/modules/client/back/methods/client/specs/sendSms.spec.js +++ b/modules/client/back/methods/client/specs/sendSms.spec.js @@ -1,29 +1,28 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; const soap = require('soap'); describe('client sendSms()', () => { - let createdLog; - - afterAll(async done => { - await app.models.ClientLog.destroyById(createdLog.id); - - done(); - }); - it('should now send a message and log it', async() => { spyOn(soap, 'createClientAsync').and.returnValue('a so fake client'); - let ctx = {req: {accessToken: {userId: 9}}}; - let id = 1101; - let destination = 222222222; - let message = 'this is the message created in a test'; + const tx = await models.Client.beginTransaction({}); - let sms = await app.models.Client.sendSms(ctx, id, destination, message); + try { + const options = {transaction: tx}; + const ctx = {req: {accessToken: {userId: 9}}}; + const id = 1101; + const destination = 222222222; + const message = 'this is the message created in a test'; - logId = sms.logId; + const sms = await models.Client.sendSms(ctx, id, destination, message, options); - createdLog = await app.models.ClientLog.findById(logId); - let json = JSON.parse(JSON.stringify(createdLog.newInstance)); + const createdLog = await models.ClientLog.findById(sms.logId); + const json = JSON.parse(JSON.stringify(createdLog.newInstance)); - expect(json.message).toEqual(message); + expect(json.message).toEqual(message); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); }); diff --git a/modules/client/back/methods/client/specs/summary.spec.js b/modules/client/back/methods/client/specs/summary.spec.js index e09f04205..dedc1f8ea 100644 --- a/modules/client/back/methods/client/specs/summary.spec.js +++ b/modules/client/back/methods/client/specs/summary.spec.js @@ -1,46 +1,123 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('client summary()', () => { it('should return a summary object containing data', async() => { - let result = await app.models.Client.summary(1101); + const clientId = 1101; + const tx = await models.Client.beginTransaction({}); - expect(result.id).toEqual(1101); - expect(result.name).toEqual('Bruce Wayne'); + try { + const options = {transaction: tx}; + + const result = await models.Client.summary(clientId, options); + + expect(result.id).toEqual(clientId); + expect(result.name).toEqual('Bruce Wayne'); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); it('should return a summary object containing mana', async() => { - let result = await app.models.Client.summary(1105); + const clientId = 1105; + const tx = await models.Client.beginTransaction({}); - expect(result.mana.mana).toEqual(0.34); + try { + const options = {transaction: tx}; + + const result = await models.Client.summary(clientId, options); + + expect(result.mana.mana).toEqual(0.34); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); it('should return a summary object containing debt', async() => { - let result = await app.models.Client.summary(1101); + const clientId = 1101; + const tx = await models.Client.beginTransaction({}); - expect(result.debt.debt).toEqual(jasmine.any(Number)); + try { + const options = {transaction: tx}; + + const result = await models.Client.summary(clientId, options); + + expect(result.debt.debt).toEqual(jasmine.any(Number)); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); it('should return a summary object containing averageInvoiced', async() => { - let result = await app.models.Client.summary(1101); + const clientId = 1101; + const tx = await models.Client.beginTransaction({}); - expect(result.averageInvoiced.invoiced).toEqual(1500); + try { + const options = {transaction: tx}; + + const result = await models.Client.summary(clientId, options); + + expect(result.averageInvoiced.invoiced).toEqual(1500); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); it('should return a summary object containing totalGreuge', async() => { - let result = await app.models.Client.summary(1101); + const clientId = 1101; + const tx = await models.Client.beginTransaction({}); - expect(result.totalGreuge).toEqual(203.71); + try { + const options = {transaction: tx}; + + const result = await models.Client.summary(clientId, options); + + expect(result.totalGreuge).toEqual(203.71); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); it('should return a summary object without containing active recoveries', async() => { - let result = await app.models.Client.summary(1101); + const clientId = 1101; + const tx = await models.Client.beginTransaction({}); - expect(result.recovery).toEqual(null); + try { + const options = {transaction: tx}; + + const result = await models.Client.summary(clientId, options); + + expect(result.recovery).toEqual(null); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); it('should return a summary object containing active recoveries', async() => { - let result = await app.models.Client.summary(1102); + const clientId = 1102; + const tx = await models.Client.beginTransaction({}); - expect(result.recovery.id).toEqual(3); + try { + const options = {transaction: tx}; + + const result = await models.Client.summary(clientId, options); + + expect(result.recovery.id).toEqual(3); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); }); diff --git a/modules/client/back/methods/client/specs/threeLastActive.spec.js b/modules/client/back/methods/client/specs/threeLastActive.spec.js deleted file mode 100644 index 82ee7a5a8..000000000 --- a/modules/client/back/methods/client/specs/threeLastActive.spec.js +++ /dev/null @@ -1,12 +0,0 @@ -const app = require('vn-loopback/server/server'); - -describe('client lastActiveTickets()', () => { - it('should return the last three active tickets', async() => { - const clientId = 1109; - const ticketId = 19; - - let result = await app.models.Client.lastActiveTickets(clientId, ticketId); - - expect(result.length).toEqual(3); - }); -}); diff --git a/modules/client/back/methods/client/specs/updateAddress.spec.js b/modules/client/back/methods/client/specs/updateAddress.spec.js index a41b9f285..e3e65f604 100644 --- a/modules/client/back/methods/client/specs/updateAddress.spec.js +++ b/modules/client/back/methods/client/specs/updateAddress.spec.js @@ -1,4 +1,4 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Address updateAddress', () => { const clientId = 1101; @@ -8,93 +8,105 @@ describe('Address updateAddress', () => { const customAgentOneId = 1; it('should throw the non uee member error if no incoterms is defined', async() => { - let err; - const ctx = { - args: { - provinceFk: provinceId, - customsAgentFk: customAgentOneId - } - }; + const tx = await models.Client.beginTransaction({}); + + let error; try { - await app.models.Client.updateAddress(ctx, clientId, addressId); + const options = {transaction: tx}; + const ctx = { + args: { + provinceFk: provinceId, + customsAgentFk: customAgentOneId + } + }; + + await models.Client.updateAddress(ctx, clientId, addressId, options); + + await tx.rollback(); } catch (e) { - err = e; + await tx.rollback(); + error = e; } - expect(err).toBeDefined(); - expect(err.message).toEqual('Incoterms is required for a non UEE member'); + expect(error).toBeDefined(); + expect(error.message).toEqual('Incoterms is required for a non UEE member'); }); it('should throw a non uee member error if no customsAgent is defined', async() => { - let err; - const ctx = { - args: { - provinceFk: provinceId, - incotermsFk: incotermsId - } - }; + const tx = await models.Client.beginTransaction({}); + + let error; try { - await app.models.Client.updateAddress(ctx, clientId, addressId); + const options = {transaction: tx}; + const ctx = { + args: { + provinceFk: provinceId, + incotermsFk: incotermsId + } + }; + + await models.Client.updateAddress(ctx, clientId, addressId, options); + + await tx.rollback(); } catch (e) { - err = e; + await tx.rollback(); + error = e; } - expect(err).toBeDefined(); - expect(err.message).toEqual('Customs agent is required for a non UEE member'); + expect(error).toBeDefined(); + expect(error.message).toEqual('Customs agent is required for a non UEE member'); }); it('should update the adress from a non uee member with no error thrown', async() => { - const expectedResult = 'My edited address'; - const ctx = { - args: { - provinceFk: provinceId, - nickname: expectedResult, - incotermsFk: incotermsId, - customsAgentFk: customAgentOneId - } - }; + const tx = await models.Client.beginTransaction({}); - let oldAddress = await app.models.Address.findById(addressId); + try { + const options = {transaction: tx}; + const ctx = { + args: { + provinceFk: provinceId, + nickname: expectedResult, + incotermsFk: incotermsId, + customsAgentFk: customAgentOneId + } + }; + const expectedResult = 'My edited address'; - await app.models.Client.updateAddress(ctx, clientId, addressId); + await models.Client.updateAddress(ctx, clientId, addressId, options); - let address = await app.models.Address.findById(addressId); + const address = await models.Address.findById(addressId, null, options); - expect(address.nickname).toEqual(expectedResult); + expect(address.nickname).toEqual(expectedResult); - // restores - await address.updateAttributes({ - nickname: oldAddress.nickname, - provinceFk: oldAddress.provinceFk, - customsAgentFk: null, - incotermsFk: null - }); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); it('should update the address', async() => { - const expectedResult = 'My second time edited address'; - const ctx = { - args: { - nickname: expectedResult - } - }; + const tx = await models.Client.beginTransaction({}); - oldAddress = await app.models.Address.findById(addressId); + try { + const options = {transaction: tx}; + const ctx = { + args: { + nickname: expectedResult + } + }; + const expectedResult = 'My second time edited address'; - await app.models.Client.updateAddress(ctx, clientId, addressId); + await models.Client.updateAddress(ctx, clientId, addressId, options); - address = await app.models.Address.findById(addressId); + const address = await models.Address.findById(addressId, null, options); - expect(address.nickname).toEqual(expectedResult); + expect(address.nickname).toEqual(expectedResult); - // restores - await address.updateAttributes({ - nickname: oldAddress.nickname, - provinceFk: oldAddress.provinceFk, - customsAgentFk: null, - incotermsFk: null - }); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); }); diff --git a/modules/client/back/methods/client/specs/updateFiscalData.spec.js b/modules/client/back/methods/client/specs/updateFiscalData.spec.js index 9b5aac0b5..a0a46c610 100644 --- a/modules/client/back/methods/client/specs/updateFiscalData.spec.js +++ b/modules/client/back/methods/client/specs/updateFiscalData.spec.js @@ -1,61 +1,76 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Client updateFiscalData', () => { const clientId = 1101; const employeeId = 1; const salesAssistantId = 21; const administrativeId = 5; - afterAll(async done => { - const ctx = {req: {accessToken: {userId: administrativeId}}}; - ctx.args = {postcode: 46460}; - - await app.models.Client.updateFiscalData(ctx, clientId); - - done(); - }); it('should return an error if the user is not salesAssistant and the isTaxDataChecked value is true', async() => { - const ctx = {req: {accessToken: {userId: employeeId}}}; - ctx.args = {}; + const tx = await models.Client.beginTransaction({}); let error; - await app.models.Client.updateFiscalData(ctx, clientId) - .catch(e => { - error = e; - }); + + try { + const options = {transaction: tx}; + const ctx = {req: {accessToken: {userId: employeeId}}}; + ctx.args = {}; + + await models.Client.updateFiscalData(ctx, clientId, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } expect(error.message).toEqual(`You can't make changes on a client with verified data`); }); it('should return an error if the salesAssistant did not fill the sage data before checking verified data', async() => { - const client = await app.models.Client.findById(clientId); - await client.updateAttribute('isTaxDataChecked', false); - - const ctx = {req: {accessToken: {userId: salesAssistantId}}}; - ctx.args = {isTaxDataChecked: true}; + const tx = await models.Client.beginTransaction({}); let error; - await app.models.Client.updateFiscalData(ctx, clientId) - .catch(e => { - error = e; - }); + + try { + const options = {transaction: tx}; + + const client = await models.Client.findById(clientId, options); + await client.updateAttribute('isTaxDataChecked', false, options); + + const ctx = {req: {accessToken: {userId: salesAssistantId}}}; + ctx.args = {isTaxDataChecked: true}; + + await models.Client.updateFiscalData(ctx, clientId, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } expect(error.message).toEqual('You need to fill sage information before you check verified data'); - - // Restores - await client.updateAttribute('isTaxDataChecked', true); }); - it('should update the client fiscal data and return the count if changes made', async() => { - const ctx = {req: {accessToken: {userId: administrativeId}}}; - ctx.args = {postcode: 46680}; + it('should update the client fiscal data', async() => { + const tx = await models.Client.beginTransaction({}); - const client = await app.models.Client.findById(clientId); + try { + const options = {transaction: tx}; + const ctx = {req: {accessToken: {userId: administrativeId}}}; + ctx.args = {postcode: 46680}; - expect(client.postcode).toEqual('46460'); + const client = await models.Client.findById(clientId, null, options); - const result = await app.models.Client.updateFiscalData(ctx, clientId); + expect(client.postcode).toEqual('46460'); - expect(result.postcode).toEqual('46680'); + const result = await models.Client.updateFiscalData(ctx, clientId, options); + + expect(result.postcode).toEqual('46680'); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); }); diff --git a/modules/client/back/methods/client/specs/uploadFile.spec.js b/modules/client/back/methods/client/specs/uploadFile.spec.js index f52c1e665..7fee75892 100644 --- a/modules/client/back/methods/client/specs/uploadFile.spec.js +++ b/modules/client/back/methods/client/specs/uploadFile.spec.js @@ -1,19 +1,26 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Client uploadFile()', () => { it(`should return an error for a user without enough privileges`, async() => { - let clientId = 1101; - let currentUserId = 1102; - let paymentLawTypeId = 12; - let ctx = {req: {accessToken: {userId: currentUserId}}, args: {dmsTypeId: paymentLawTypeId}}; + const tx = await models.Client.beginTransaction({}); let error; - await app.models.Client.uploadFile(ctx, clientId).catch(e => { - error = e; - }).finally(() => { - expect(error.message).toEqual(`You don't have enough privileges`); - }); - expect(error).toBeDefined(); + try { + const options = {transaction: tx}; + const clientId = 1101; + const currentUserId = 1102; + const paymentLawTypeId = 12; + const ctx = {req: {accessToken: {userId: currentUserId}}, args: {dmsTypeId: paymentLawTypeId}}; + + await models.Client.uploadFile(ctx, clientId, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error.message).toEqual(`You don't have enough privileges`); }); }); diff --git a/modules/client/back/methods/client/summary.js b/modules/client/back/methods/client/summary.js index 009cd310e..dccf7f39c 100644 --- a/modules/client/back/methods/client/summary.js +++ b/modules/client/back/methods/client/summary.js @@ -19,21 +19,26 @@ module.exports = Self => { } }); - Self.summary = async clientFk => { - let models = Self.app.models; - let summaryObj = await getSummary(models.Client, clientFk); + Self.summary = async(clientFk, options) => { + const models = Self.app.models; + const myOptions = {}; - summaryObj.mana = await models.Client.getMana(clientFk); - summaryObj.debt = await models.Client.getDebt(clientFk); - summaryObj.averageInvoiced = await models.Client.getAverageInvoiced(clientFk); - summaryObj.totalGreuge = await models.Greuge.sumAmount(clientFk); - summaryObj.recovery = await getRecoveries(models.Recovery, clientFk); + if (typeof options == 'object') + Object.assign(myOptions, options); + + const summaryObj = await getSummary(models.Client, clientFk, myOptions); + + summaryObj.mana = await models.Client.getMana(clientFk, myOptions); + summaryObj.debt = await models.Client.getDebt(clientFk, myOptions); + summaryObj.averageInvoiced = await models.Client.getAverageInvoiced(clientFk, myOptions); + summaryObj.totalGreuge = await models.Greuge.sumAmount(clientFk, myOptions); + summaryObj.recovery = await getRecoveries(models.Recovery, clientFk, myOptions); return summaryObj; }; - async function getSummary(client, clientId) { - let filter = { + async function getSummary(clientModel, clientId, options) { + const filter = { include: [ { relation: 'account', @@ -115,17 +120,17 @@ module.exports = Self => { where: {id: clientId} }; - return await client.findOne(filter); + return clientModel.findOne(filter, options); } - async function getRecoveries(recovery, clientId) { - let filter = { + async function getRecoveries(recoveryModel, clientId, options) { + const filter = { where: { and: [{clientFk: clientId}, {or: [{finished: null}, {finished: {gt: Date.now()}}]}] }, limit: 1 }; - return await recovery.findOne(filter); + return recoveryModel.findOne(filter, options); } }; diff --git a/modules/client/back/methods/client/updateAddress.js b/modules/client/back/methods/client/updateAddress.js index 27f9faf1c..a32c7eff5 100644 --- a/modules/client/back/methods/client/updateAddress.js +++ b/modules/client/back/methods/client/updateAddress.js @@ -3,71 +3,73 @@ const UserError = require('vn-loopback/util/user-error'); module.exports = function(Self) { Self.remoteMethod('updateAddress', { description: 'Updates a client address updating default address', - accepts: [{ - arg: 'ctx', - type: 'object', - http: {source: 'context'} - }, - { - arg: 'clientId', - type: 'number', - description: 'The client id', - http: {source: 'path'} - }, - { - arg: 'addressId', - type: 'number', - description: 'The address id', - http: {source: 'path'} - }, - { - arg: 'nickname', - type: 'string' - }, - { - arg: 'city', - type: 'string' - }, - { - arg: 'street', - type: 'string' - }, - { - arg: 'phone', - type: 'any' - }, - { - arg: 'mobile', - type: 'any' - }, - { - arg: 'postalCode', - type: 'any' - }, - { - arg: 'provinceFk', - type: 'any' - }, - { - arg: 'agencyModeFk', - type: 'any' - }, - { - arg: 'incotermsFk', - type: 'any' - }, - { - arg: 'customsAgentFk', - type: 'any' - }, - { - arg: 'isActive', - type: 'boolean' - }, - { - arg: 'isEqualizated', - type: 'boolean' - }], + accepts: [ + { + arg: 'ctx', + type: 'object', + http: {source: 'context'} + }, + { + arg: 'clientId', + type: 'number', + description: 'The client id', + http: {source: 'path'} + }, + { + arg: 'addressId', + type: 'number', + description: 'The address id', + http: {source: 'path'} + }, + { + arg: 'nickname', + type: 'string' + }, + { + arg: 'city', + type: 'string' + }, + { + arg: 'street', + type: 'string' + }, + { + arg: 'phone', + type: 'any' + }, + { + arg: 'mobile', + type: 'any' + }, + { + arg: 'postalCode', + type: 'any' + }, + { + arg: 'provinceFk', + type: 'any' + }, + { + arg: 'agencyModeFk', + type: 'any' + }, + { + arg: 'incotermsFk', + type: 'any' + }, + { + arg: 'customsAgentFk', + type: 'any' + }, + { + arg: 'isActive', + type: 'boolean' + }, + { + arg: 'isEqualizated', + type: 'boolean' + } + ], returns: { root: true, type: 'object' @@ -78,26 +80,37 @@ module.exports = function(Self) { } }); - Self.updateAddress = async(ctx, clientId, addressId) => { + Self.updateAddress = async(ctx, clientId, addressId, options) => { const models = Self.app.models; const args = ctx.args; - const tx = await models.Address.beginTransaction({}); + let tx; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + try { - const options = {transaction: tx}; const address = await models.Address.findOne({ where: { id: addressId, clientFk: clientId } - }); + }, myOptions); + const provinceId = args.provinceFk || address.provinceFk; const province = await models.Province.findById(provinceId, { include: { relation: 'country' } - }, options); + }, myOptions); const isUeeMember = province.country().isUeeMember; + const incotermsId = args.incotermsFk || address.incotermsFk; if (!isUeeMember && !incotermsId) throw new UserError(`Incoterms is required for a non UEE member`); @@ -107,12 +120,14 @@ module.exports = function(Self) { throw new UserError(`Customs agent is required for a non UEE member`); delete args.ctx; // Remove unwanted properties - const updatedAddress = await address.updateAttributes(ctx.args, options); - await tx.commit(); + const updatedAddress = await address.updateAttributes(ctx.args, myOptions); + + if (tx) await tx.commit(); + return updatedAddress; } catch (e) { - await tx.rollback(); + if (tx) await tx.rollback(); throw e; } }; diff --git a/modules/client/back/methods/client/updateFiscalData.js b/modules/client/back/methods/client/updateFiscalData.js index a3d40a4d8..539d89d3a 100644 --- a/modules/client/back/methods/client/updateFiscalData.js +++ b/modules/client/back/methods/client/updateFiscalData.js @@ -4,97 +4,99 @@ module.exports = Self => { Self.remoteMethod('updateFiscalData', { description: 'Updates fiscal data of a client', accessType: 'WRITE', - accepts: [{ - arg: 'ctx', - type: 'Object', - http: {source: 'context'} - }, - { - arg: 'id', - type: 'Number', - description: 'The client id', - http: {source: 'path'} - }, - { - arg: 'socialName', - type: 'string' - }, - { - arg: 'fi', - type: 'string' - }, - { - arg: 'street', - type: 'string' - }, - { - arg: 'postcode', - type: 'string' - }, - { - arg: 'city', - type: 'string' - }, - { - arg: 'countryFk', - type: 'number' - }, - { - arg: 'provinceFk', - type: 'number' - }, - { - arg: 'sageTaxTypeFk', - type: 'any' - }, - { - arg: 'sageTransactionTypeFk', - type: 'any' - }, - { - arg: 'transferorFk', - type: 'any' - }, - { - arg: 'hasToInvoiceByAddress', - type: 'boolean' - }, - { - arg: 'hasToInvoice', - type: 'boolean' - }, - { - arg: 'isActive', - type: 'boolean' - }, - { - arg: 'isFreezed', - type: 'boolean' - }, - { - arg: 'isVies', - type: 'boolean' - }, - { - arg: 'isToBeMailed', - type: 'boolean' - }, - { - arg: 'isEqualizated', - type: 'boolean' - }, - { - arg: 'isTaxDataVerified', - type: 'boolean' - }, - { - arg: 'isTaxDataChecked', - type: 'boolean' - }, - { - arg: 'despiteOfClient', - type: 'number' - }], + accepts: [ + { + arg: 'ctx', + type: 'object', + http: {source: 'context'} + }, + { + arg: 'id', + type: 'number', + description: 'The client id', + http: {source: 'path'} + }, + { + arg: 'socialName', + type: 'string' + }, + { + arg: 'fi', + type: 'string' + }, + { + arg: 'street', + type: 'string' + }, + { + arg: 'postcode', + type: 'string' + }, + { + arg: 'city', + type: 'string' + }, + { + arg: 'countryFk', + type: 'number' + }, + { + arg: 'provinceFk', + type: 'number' + }, + { + arg: 'sageTaxTypeFk', + type: 'any' + }, + { + arg: 'sageTransactionTypeFk', + type: 'any' + }, + { + arg: 'transferorFk', + type: 'any' + }, + { + arg: 'hasToInvoiceByAddress', + type: 'boolean' + }, + { + arg: 'hasToInvoice', + type: 'boolean' + }, + { + arg: 'isActive', + type: 'boolean' + }, + { + arg: 'isFreezed', + type: 'boolean' + }, + { + arg: 'isVies', + type: 'boolean' + }, + { + arg: 'isToBeMailed', + type: 'boolean' + }, + { + arg: 'isEqualizated', + type: 'boolean' + }, + { + arg: 'isTaxDataVerified', + type: 'boolean' + }, + { + arg: 'isTaxDataChecked', + type: 'boolean' + }, + { + arg: 'despiteOfClient', + type: 'number' + } + ], returns: { arg: 'res', type: 'string', @@ -106,46 +108,65 @@ module.exports = Self => { } }); - Self.updateFiscalData = async(ctx, clientId) => { + Self.updateFiscalData = async(ctx, clientId, options) => { + let tx; + const myOptions = {}; const models = Self.app.models; const args = ctx.args; const userId = ctx.req.accessToken.userId; - const isSalesAssistant = await models.Account.hasRole(userId, 'salesAssistant'); const $t = ctx.req.__; - const client = await models.Client.findById(clientId); + if (typeof options == 'object') + Object.assign(myOptions, options); - if (!isSalesAssistant && client.isTaxDataChecked) - throw new UserError(`You can't make changes on a client with verified data`); - - // Sage data validation - const taxDataChecked = args.isTaxDataChecked; - const sageTaxChecked = client.sageTaxTypeFk || args.sageTaxTypeFk; - const sageTransactionChecked = client.sageTransactionTypeFk || args.sageTransactionTypeFk; - const hasSageData = sageTaxChecked && sageTransactionChecked; - - if (taxDataChecked && !hasSageData) - throw new UserError(`You need to fill sage information before you check verified data`); - - if (args.despiteOfClient) { - const logRecord = { - originFk: clientId, - userFk: userId, - action: 'update', - changedModel: 'Client', - changedModelId: clientId, - description: $t(`Client checked as validated despite of duplication`, { - clientId: args.despiteOfClient - }) - }; - - await models.ClientLog.create(logRecord); + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; } - // Remove unwanted properties - delete args.ctx; - delete args.id; + try { + const isSalesAssistant = await models.Account.hasRole(userId, 'salesAssistant', myOptions); + const client = await models.Client.findById(clientId, null, myOptions); - return client.updateAttributes(args); + if (!isSalesAssistant && client.isTaxDataChecked) + throw new UserError(`You can't make changes on a client with verified data`); + + // Sage data validation + const taxDataChecked = args.isTaxDataChecked; + const sageTaxChecked = client.sageTaxTypeFk || args.sageTaxTypeFk; + const sageTransactionChecked = client.sageTransactionTypeFk || args.sageTransactionTypeFk; + const hasSageData = sageTaxChecked && sageTransactionChecked; + + if (taxDataChecked && !hasSageData) + throw new UserError(`You need to fill sage information before you check verified data`); + + if (args.despiteOfClient) { + const logRecord = { + originFk: clientId, + userFk: userId, + action: 'update', + changedModel: 'Client', + changedModelId: clientId, + description: $t(`Client checked as validated despite of duplication`, { + clientId: args.despiteOfClient + }) + }; + + await models.ClientLog.create(logRecord, myOptions); + } + + // Remove unwanted properties + delete args.ctx; + delete args.id; + + const updatedClient = await client.updateAttributes(args, myOptions); + + if (tx) await tx.commit(); + + return updatedClient; + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } }; }; diff --git a/modules/client/back/methods/client/uploadFile.js b/modules/client/back/methods/client/uploadFile.js index 6ec96e301..121c1a567 100644 --- a/modules/client/back/methods/client/uploadFile.js +++ b/modules/client/back/methods/client/uploadFile.js @@ -2,42 +2,50 @@ module.exports = Self => { Self.remoteMethodCtx('uploadFile', { description: 'Upload and attach a file to a client', accessType: 'WRITE', - accepts: [{ - arg: 'id', - type: 'Number', - description: 'The client id', - http: {source: 'path'} - }, { - arg: 'warehouseId', - type: 'Number', - description: 'The warehouse id', - required: true - }, { - arg: 'companyId', - type: 'Number', - description: 'The company id', - required: true - }, { - arg: 'dmsTypeId', - type: 'Number', - description: 'The dms type id', - required: true - }, { - arg: 'reference', - type: 'String', - required: true - }, { - arg: 'description', - type: 'String', - required: true - }, { - arg: 'hasFile', - type: 'Boolean', - description: 'True if has an attached file', - required: true - }], + accepts: [ + { + arg: 'id', + type: 'number', + description: 'The client id', + http: {source: 'path'} + }, + { + arg: 'warehouseId', + type: 'number', + description: 'The warehouse id', + required: true + }, + { + arg: 'companyId', + type: 'number', + description: 'The company id', + required: true + }, + { + arg: 'dmsTypeId', + type: 'number', + description: 'The dms type id', + required: true + }, + { + arg: 'reference', + type: 'string', + required: true + }, + { + arg: 'description', + type: 'string', + required: true + }, + { + arg: 'hasFile', + type: 'boolean', + description: 'True if has an attached file', + required: true + } + ], returns: { - type: 'Object', + type: 'object', root: true }, http: { @@ -46,31 +54,39 @@ module.exports = Self => { } }); - Self.uploadFile = async(ctx, id) => { + Self.uploadFile = async(ctx, id, options) => { const models = Self.app.models; + let tx; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + const promises = []; - const tx = await Self.beginTransaction({}); try { - const options = {transaction: tx}; - - const uploadedFiles = await models.Dms.uploadFile(ctx, options); + const uploadedFiles = await models.Dms.uploadFile(ctx, myOptions); uploadedFiles.forEach(dms => { const newClientDms = models.ClientDms.create({ clientFk: id, dmsFk: dms.id - }, options); + }, myOptions); promises.push(newClientDms); }); - const resolvedPromises = await Promise.all(promises); + const resolvedPromises = await Promise.all(promises, myOptions); - await tx.commit(); + if (tx) await tx.commit(); return resolvedPromises; - } catch (err) { - await tx.rollback(); - throw err; + } catch (e) { + if (tx) await tx.rollback(); + throw e; } }; }; diff --git a/modules/client/back/methods/credit-classification/createWithInsurance.js b/modules/client/back/methods/credit-classification/createWithInsurance.js index bccfa6193..853f68389 100644 --- a/modules/client/back/methods/credit-classification/createWithInsurance.js +++ b/modules/client/back/methods/credit-classification/createWithInsurance.js @@ -1,17 +1,13 @@ module.exports = Self => { Self.remoteMethod('createWithInsurance', { description: 'Creates both classification and one insurance', - accepts: [{ - arg: 'data', - type: 'object', - http: {source: 'body'} - }, { - arg: 'context', - type: 'object', - http: function(ctx) { - return ctx; + accepts: [ + { + arg: 'data', + type: 'object', + http: {source: 'body'} } - }], + ], returns: { root: true, type: 'boolean' @@ -22,29 +18,36 @@ module.exports = Self => { } }); - Self.createWithInsurance = async(data, ctx) => { - const tx = await Self.beginTransaction({}); + Self.createWithInsurance = async(data, options) => { const models = Self.app.models; + let tx; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } try { - let options = {transaction: tx}; - const newClassification = await Self.create({ client: data.clientFk, started: data.started - }, options); + }, myOptions); await models.CreditInsurance.create({ creditClassification: newClassification.id, credit: data.credit, grade: data.grade - }, options); + }, myOptions); - await tx.commit(); + if (tx) await tx.commit(); return newClassification; } catch (e) { - await tx.rollback(); + if (tx) await tx.rollback(); throw e; } }; diff --git a/modules/client/back/methods/credit-classification/createWithInsurance.spec.js b/modules/client/back/methods/credit-classification/createWithInsurance.spec.js index 10a00786c..fdc14a953 100644 --- a/modules/client/back/methods/credit-classification/createWithInsurance.spec.js +++ b/modules/client/back/methods/credit-classification/createWithInsurance.spec.js @@ -1,64 +1,26 @@ -const app = require('vn-loopback/server/server'); -const LoopBackContext = require('loopback-context'); +const models = require('vn-loopback/server/server').models; describe('Client createWithInsurance', () => { - const activeCtx = { - accessToken: {userId: 1101}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - const ctx = {req: activeCtx}; - activeCtx.http.req.__ = value => { - return value; - }; - - it('should verify the classifications and insurances are untainted', async() => { - let classifications = await app.models.CreditClassification.find(); - let insurances = await app.models.CreditInsurance.find(); - - expect(classifications.length).toEqual(5); - expect(insurances.length).toEqual(3); - }); - - it('should not create the insurance if couldnt create the classification', async() => { - let error; - let data = {clientFk: null, started: Date.now(), credit: 999, grade: 255}; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - await app.models.CreditClassification.createWithInsurance(data, ctx) - .catch(e => { - error = e; - }); - - expect(error.toString()).toBe('Error: ER_BAD_NULL_ERROR: Column \'client\' cannot be null'); - - let classifications = await app.models.CreditClassification.find(); - let insurances = await app.models.CreditInsurance.find(); - - expect(classifications.length).toEqual(5); - expect(insurances.length).toEqual(3); - }); - it('should create a new client credit classification with insurance', async() => { - let data = {clientFk: 1101, started: Date.now(), credit: 999, grade: 255}; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - let result = await app.models.CreditClassification.createWithInsurance(data, ctx); + const tx = await models.Client.beginTransaction({}); - expect(result.client).toEqual(1101); + try { + const options = {transaction: tx}; + const data = {clientFk: 1101, started: Date.now(), credit: 999, grade: 255}; - let classifications = await app.models.CreditClassification.find(); - let insurances = await app.models.CreditInsurance.find(); + const result = await models.CreditClassification.createWithInsurance(data, options); - expect(classifications.length).toEqual(6); - expect(insurances.length).toEqual(4); + expect(result.client).toEqual(1101); - // restore - await app.models.CreditClassification.destroyById(result.id); + const classifications = await models.CreditClassification.find(); + const insurances = await models.CreditInsurance.find(); + + expect(classifications.length).toEqual(6); + expect(insurances.length).toEqual(4); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); }); diff --git a/modules/client/back/methods/greuge/specs/sumAmount.spec.js b/modules/client/back/methods/greuge/specs/sumAmount.spec.js index fc84bca98..25b9e44a4 100644 --- a/modules/client/back/methods/greuge/specs/sumAmount.spec.js +++ b/modules/client/back/methods/greuge/specs/sumAmount.spec.js @@ -1,14 +1,21 @@ -const totalGreuge = require('../sumAmount'); +const models = require('vn-loopback/server/server').models; describe('Greuge totalGreuge()', () => { it('should call the sumAmount method', async() => { - let clientFk = 1; - let self = jasmine.createSpyObj('self', ['remoteMethod', 'rawSql']); - self.rawSql.and.returnValue(Promise.resolve([{sumAmount: 6000}])); - totalGreuge(self); + const tx = await models.Client.beginTransaction({}); - let result = await self.sumAmount(clientFk); + try { + const options = {transaction: tx}; - expect(result).toBe(6000); + const clientId = 1; + + const result = await models.Client.sumAmount(clientId, options); + + expect(result).toBe(6000); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); }); diff --git a/modules/client/back/methods/greuge/sumAmount.js b/modules/client/back/methods/greuge/sumAmount.js index dcc780168..198ef7251 100644 --- a/modules/client/back/methods/greuge/sumAmount.js +++ b/modules/client/back/methods/greuge/sumAmount.js @@ -18,10 +18,15 @@ module.exports = Self => { } }); - Self.sumAmount = async clientFk => { - let query = `SELECT SUM(amount) AS sumAmount FROM vn.greuge WHERE clientFk = ?`; + Self.sumAmount = async(clientFk, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const query = `SELECT SUM(amount) AS sumAmount FROM vn.greuge WHERE clientFk = ?`; try { - let [response] = await Self.rawSql(query, [clientFk]); + const [response] = await Self.rawSql(query, [clientFk], myOptions); return response ? response.sumAmount : 0; } catch (e) { diff --git a/modules/client/back/methods/receipt/filter.js b/modules/client/back/methods/receipt/filter.js index b32249d4b..e29ccf8f2 100644 --- a/modules/client/back/methods/receipt/filter.js +++ b/modules/client/back/methods/receipt/filter.js @@ -7,23 +7,25 @@ module.exports = Self => { accepts: [ { arg: 'filter', - type: 'Object', + type: 'object', description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string', http: {source: 'query'} - }, { + }, + { arg: 'clientId', - type: 'Number', + type: 'number', description: 'The client id', required: true, - }, { + }, + { arg: 'companyId', - type: 'Number', + type: 'number', description: 'The company id', required: true, } ], returns: { - type: ['Object'], + type: ['object'], root: true }, http: { @@ -32,51 +34,56 @@ module.exports = Self => { } }); - Self.filter = async(filter, clientId, companyId) => { - let stmt = new ParameterizedSQL( + Self.filter = async(filter, clientId, companyId, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const stmt = new ParameterizedSQL( `SELECT * FROM ( - SELECT - r.id, - r.isConciliate, - r.payed, - r.workerFk, - c.code company, - r.created, - r.invoiceFk description, - NULL debit, - r.amountPaid credit, - r.bankFk, - u.name userName, - r.clientFk, - FALSE hasPdf, - FALSE isInvoice - FROM vn.receipt r - LEFT JOIN vn.worker w ON w.id = r.workerFk - LEFT JOIN account.user u ON u.id = w.userFk - JOIN vn.company c ON c.id = r.companyFk - WHERE r.clientFk = ? AND r.companyFk = ? - UNION ALL - SELECT - i.id, - TRUE, - i.issued, - NULL, - c.code, - i.created, - i.ref, - i.amount, - NULL, - NULL, - NULL, - i.clientFk, - i.hasPdf, - TRUE isInvoice - FROM vn.invoiceOut i - JOIN vn.company c ON c.id = i.companyFk - WHERE i.clientFk = ? AND i.companyFk = ? - ORDER BY payed DESC, created DESC - ) t - ORDER BY payed DESC, created DESC`, [ + SELECT + r.id, + r.isConciliate, + r.payed, + r.workerFk, + c.code company, + r.created, + r.invoiceFk description, + NULL debit, + r.amountPaid credit, + r.bankFk, + u.name userName, + r.clientFk, + FALSE hasPdf, + FALSE isInvoice + FROM vn.receipt r + LEFT JOIN vn.worker w ON w.id = r.workerFk + LEFT JOIN account.user u ON u.id = w.userFk + JOIN vn.company c ON c.id = r.companyFk + WHERE r.clientFk = ? AND r.companyFk = ? + UNION ALL + SELECT + i.id, + TRUE, + i.issued, + NULL, + c.code, + i.created, + i.ref, + i.amount, + NULL, + NULL, + NULL, + i.clientFk, + i.hasPdf, + TRUE isInvoice + FROM vn.invoiceOut i + JOIN vn.company c ON c.id = i.companyFk + WHERE i.clientFk = ? AND i.companyFk = ? + ORDER BY payed DESC, created DESC + ) t ORDER BY payed DESC, created DESC`, + [ clientId, companyId, clientId, @@ -85,6 +92,7 @@ module.exports = Self => { ); stmt.merge(Self.makeLimit(filter)); - return await Self.rawStmt(stmt); + + return Self.rawStmt(stmt, myOptions); }; }; diff --git a/modules/client/back/methods/receipt/specs/filter.spec.js b/modules/client/back/methods/receipt/specs/filter.spec.js index a06cb9b51..0ddc9b3a7 100644 --- a/modules/client/back/methods/receipt/specs/filter.spec.js +++ b/modules/client/back/methods/receipt/specs/filter.spec.js @@ -1,12 +1,22 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('receipt filter()', () => { it('should return the receipts', async() => { - const filter = {limit: 20}; - const clientId = 1101; - const companyId = 442; - let result = await app.models.Receipt.filter(filter, clientId, companyId); + const tx = await models.Client.beginTransaction({}); - expect(result.length).toBeGreaterThan(0); + try { + const options = {transaction: tx}; + const filter = {limit: 20}; + const clientId = 1101; + const companyId = 442; + + const result = await models.Receipt.filter(filter, clientId, companyId, options); + + expect(result.length).toBeGreaterThan(0); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); }); diff --git a/modules/client/back/methods/recovery/hasActiveRecovery.js b/modules/client/back/methods/recovery/hasActiveRecovery.js index 81a8a5f40..a0d0064eb 100644 --- a/modules/client/back/methods/recovery/hasActiveRecovery.js +++ b/modules/client/back/methods/recovery/hasActiveRecovery.js @@ -21,14 +21,20 @@ module.exports = Self => { } }); - Self.hasActiveRecovery = async id => { - let result = await Self.rawSql( - `SELECT count(*) AS hasActiveRecovery - FROM vn.recovery - WHERE clientFk = ? - AND IFNULL(finished,CURDATE()) >= CURDATE();`, - [id] - ); - return result[0].hasActiveRecovery != 0; + Self.hasActiveRecovery = async(id, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const query = ` + SELECT count(*) AS hasActiveRecovery + FROM vn.recovery + WHERE clientFk = ? + AND IFNULL(finished,CURDATE()) >= CURDATE(); + `; + const [result] = await Self.rawSql(query, [id], myOptions); + + return result.hasActiveRecovery != 0; }; }; diff --git a/modules/client/back/methods/recovery/hasActiveRecovery.spec.js b/modules/client/back/methods/recovery/hasActiveRecovery.spec.js index efd2190dc..1a3d5887e 100644 --- a/modules/client/back/methods/recovery/hasActiveRecovery.spec.js +++ b/modules/client/back/methods/recovery/hasActiveRecovery.spec.js @@ -1,15 +1,35 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('client hasActiveRecovery', () => { it(`should return false if the client doesn't owes`, async() => { - let hasActiveRecovery = await app.models.Recovery.hasActiveRecovery(1101); + const tx = await models.Client.beginTransaction({}); - expect(hasActiveRecovery).toBeFalsy(); + try { + const options = {transaction: tx}; + + const hasActiveRecovery = await models.Recovery.hasActiveRecovery(1101, options); + + expect(hasActiveRecovery).toBeFalsy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); it('should return true if the client owes', async() => { - let hasActiveRecovery = await app.models.Recovery.hasActiveRecovery(1102); + const tx = await models.Client.beginTransaction({}); - expect(hasActiveRecovery).toBeTruthy(); + try { + const options = {transaction: tx}; + + const hasActiveRecovery = await models.Recovery.hasActiveRecovery(1102, options); + + expect(hasActiveRecovery).toBeTruthy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } }); }); diff --git a/modules/client/back/methods/sms/send.js b/modules/client/back/methods/sms/send.js index 153036e05..c5cb6ace2 100644 --- a/modules/client/back/methods/sms/send.js +++ b/modules/client/back/methods/sms/send.js @@ -6,22 +6,24 @@ module.exports = Self => { Self.remoteMethod('send', { description: 'Sends SMS to a destination phone', accessType: 'WRITE', - accepts: [{ - arg: 'destinationFk', - type: 'Integer' - }, - { - arg: 'destination', - type: 'String', - required: true, - }, - { - arg: 'message', - type: 'String', - required: true, - }], + accepts: [ + { + arg: 'destinationFk', + type: 'integer' + }, + { + arg: 'destination', + type: 'string', + required: true, + }, + { + arg: 'message', + type: 'string', + required: true, + } + ], returns: { - type: 'Object', + type: 'object', root: true }, http: { @@ -82,6 +84,7 @@ module.exports = Self => { }; const sms = await Self.create(newSms); + if (statusCode != 200) throw new UserError(`We weren't able to send this SMS`); From 878e989c027a9ea5f35c8dbcf1a3299acfa715df Mon Sep 17 00:00:00 2001 From: joan Date: Mon, 12 Jul 2021 08:29:21 +0200 Subject: [PATCH 3/7] HOTFIX: Disable address without a province --- .../back/methods/client/updateAddress.js | 26 ++++++++++--------- 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/modules/client/back/methods/client/updateAddress.js b/modules/client/back/methods/client/updateAddress.js index 27f9faf1c..1ee6e5db8 100644 --- a/modules/client/back/methods/client/updateAddress.js +++ b/modules/client/back/methods/client/updateAddress.js @@ -91,20 +91,22 @@ module.exports = function(Self) { } }); const provinceId = args.provinceFk || address.provinceFk; - const province = await models.Province.findById(provinceId, { - include: { - relation: 'country' - } - }, options); + if (provinceId) { + const province = await models.Province.findById(provinceId, { + include: { + relation: 'country' + } + }, options); - const isUeeMember = province.country().isUeeMember; - const incotermsId = args.incotermsFk || address.incotermsFk; - if (!isUeeMember && !incotermsId) - throw new UserError(`Incoterms is required for a non UEE member`); + const isUeeMember = province.country().isUeeMember; + const incotermsId = args.incotermsFk || address.incotermsFk; + if (!isUeeMember && !incotermsId) + throw new UserError(`Incoterms is required for a non UEE member`); - const customsAgentId = args.customsAgentFk || address.customsAgentFk; - if (!isUeeMember && !customsAgentId) - throw new UserError(`Customs agent is required for a non UEE member`); + const customsAgentId = args.customsAgentFk || address.customsAgentFk; + if (!isUeeMember && !customsAgentId) + throw new UserError(`Customs agent is required for a non UEE member`); + } delete args.ctx; // Remove unwanted properties const updatedAddress = await address.updateAttributes(ctx.args, options); From dd3473b93de05e702c5e604dd903b11692605871 Mon Sep 17 00:00:00 2001 From: carlosjr Date: Mon, 12 Jul 2021 12:50:15 +0200 Subject: [PATCH 4/7] small refactors correcting constants and adding transactions --- back/methods/user-config/getUserConfig.js | 14 +++++--- .../user-config/specs/getUserConfig.spec.js | 19 ++++++++--- .../claim/back/methods/claim/getSummary.js | 2 +- .../client/back/methods/client/uploadFile.js | 2 +- .../back/methods/entry/editLatestBuys.js | 4 +-- .../methods/invoice-in/specs/filter.spec.js | 34 +++++++++---------- .../methods/invoice-in/specs/summary.spec.js | 6 ++-- .../back/methods/invoiceOut/delete.js | 4 +-- .../methods/invoiceOut/specs/book.spec.js | 10 +++--- .../invoiceOut/specs/createPdf.spec.js | 4 +-- .../methods/invoiceOut/specs/delete.spec.js | 16 ++++----- .../methods/invoiceOut/specs/download.spec.js | 4 +-- .../methods/invoiceOut/specs/filter.spec.js | 22 ++++++------ .../invoiceOut/specs/getTickets.spec.js | 6 ++-- .../methods/invoiceOut/specs/summary.spec.js | 14 ++++---- modules/zone/back/methods/zone/deleteZone.js | 4 +-- 16 files changed, 90 insertions(+), 75 deletions(-) diff --git a/back/methods/user-config/getUserConfig.js b/back/methods/user-config/getUserConfig.js index 663ef71b4..4de8049e7 100644 --- a/back/methods/user-config/getUserConfig.js +++ b/back/methods/user-config/getUserConfig.js @@ -12,18 +12,22 @@ module.exports = function(Self) { } }); - Self.getUserConfig = async ctx => { + Self.getUserConfig = async(ctx, options) => { const models = Self.app.models; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); let userConfig = await models.UserConfig.findOne({ where: {userFk: ctx.req.accessToken.userId} - }); + }, myOptions); const companyFilter = {where: {code: 'VNL'}}; - const company = await models.Company.findOne(companyFilter); + const company = await models.Company.findOne(companyFilter, myOptions); const warehouseFilter = {where: {code: 'ALG'}}; - const warehouse = await models.Warehouse.findOne(warehouseFilter); + const warehouse = await models.Warehouse.findOne(warehouseFilter, myOptions); if (!userConfig) { let newConfig = { @@ -32,7 +36,7 @@ module.exports = function(Self) { userFk: ctx.req.accessToken.userId }; - userConfig = await models.UserConfig.create(newConfig); + userConfig = await models.UserConfig.create(newConfig, myOptions); } return userConfig; }; diff --git a/back/methods/user-config/specs/getUserConfig.spec.js b/back/methods/user-config/specs/getUserConfig.spec.js index c86f3e0f2..8b510a706 100644 --- a/back/methods/user-config/specs/getUserConfig.spec.js +++ b/back/methods/user-config/specs/getUserConfig.spec.js @@ -1,10 +1,21 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('userConfig getUserConfig()', () => { it(`should return the configuration data of a given user`, async() => { - const result = await app.models.UserConfig.getUserConfig({req: {accessToken: {userId: 9}}}); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - expect(result.warehouseFk).toEqual(1); - expect(result.companyFk).toEqual(442); + try { + const ctx = {req: {accessToken: {userId: 9}}}; + const result = await models.UserConfig.getUserConfig(ctx, options); + + expect(result.warehouseFk).toEqual(1); + expect(result.companyFk).toEqual(442); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/claim/back/methods/claim/getSummary.js b/modules/claim/back/methods/claim/getSummary.js index d6722d11f..512e4a77f 100644 --- a/modules/claim/back/methods/claim/getSummary.js +++ b/modules/claim/back/methods/claim/getSummary.js @@ -133,7 +133,7 @@ module.exports = Self => { }; promises.push(Self.app.models.ClaimEnd.find(filter, myOptions)); - const res = await Promise.all(promises, myOptions); + const res = await Promise.all(promises); [summary.claim] = res[0]; summary.salesClaimed = res[1]; diff --git a/modules/client/back/methods/client/uploadFile.js b/modules/client/back/methods/client/uploadFile.js index 121c1a567..99ede27c6 100644 --- a/modules/client/back/methods/client/uploadFile.js +++ b/modules/client/back/methods/client/uploadFile.js @@ -79,7 +79,7 @@ module.exports = Self => { promises.push(newClientDms); }); - const resolvedPromises = await Promise.all(promises, myOptions); + const resolvedPromises = await Promise.all(promises); if (tx) await tx.commit(); diff --git a/modules/entry/back/methods/entry/editLatestBuys.js b/modules/entry/back/methods/entry/editLatestBuys.js index 7e6a8a22f..53b92d966 100644 --- a/modules/entry/back/methods/entry/editLatestBuys.js +++ b/modules/entry/back/methods/entry/editLatestBuys.js @@ -66,7 +66,7 @@ module.exports = Self => { const model = models[modelName]; try { - let promises = []; + const promises = []; const targets = lines.map(line => { return line[identifier]; @@ -78,7 +78,7 @@ module.exports = Self => { for (let target of targets) promises.push(model.upsertWithWhere({id: target}, value, myOptions)); - const result = await Promise.all(promises, myOptions); + const result = await Promise.all(promises); if (tx) await tx.commit(); diff --git a/modules/invoiceIn/back/methods/invoice-in/specs/filter.spec.js b/modules/invoiceIn/back/methods/invoice-in/specs/filter.spec.js index 0d7c37461..954a33f98 100644 --- a/modules/invoiceIn/back/methods/invoice-in/specs/filter.spec.js +++ b/modules/invoiceIn/back/methods/invoice-in/specs/filter.spec.js @@ -1,8 +1,8 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('InvoiceIn filter()', () => { it('should return the invoice in matching supplier name', async() => { - const tx = await app.models.Entry.beginTransaction({}); + const tx = await models.InvoiceIn.beginTransaction({}); const options = {transaction: tx}; try { @@ -12,7 +12,7 @@ describe('InvoiceIn filter()', () => { } }; - const result = await app.models.InvoiceIn.filter(ctx, {}, options); + const result = await models.InvoiceIn.filter(ctx, {}, options); expect(result.length).toEqual(5); expect(result[0].supplierName).toEqual('Plants SL'); @@ -25,7 +25,7 @@ describe('InvoiceIn filter()', () => { }); it('should return the invoice in matching supplier reference', async() => { - const tx = await app.models.Entry.beginTransaction({}); + const tx = await models.InvoiceIn.beginTransaction({}); const options = {transaction: tx}; try { @@ -35,7 +35,7 @@ describe('InvoiceIn filter()', () => { } }; - const result = await app.models.InvoiceIn.filter(ctx, {}, options); + const result = await models.InvoiceIn.filter(ctx, {}, options); expect(result.length).toEqual(1); expect(result[0].supplierRef).toEqual('1241'); @@ -48,7 +48,7 @@ describe('InvoiceIn filter()', () => { }); it('should return the invoice in matching the serial number', async() => { - const tx = await app.models.Entry.beginTransaction({}); + const tx = await models.InvoiceIn.beginTransaction({}); const options = {transaction: tx}; try { @@ -58,7 +58,7 @@ describe('InvoiceIn filter()', () => { } }; - const result = await app.models.InvoiceIn.filter(ctx, {}, options); + const result = await models.InvoiceIn.filter(ctx, {}, options); expect(result.length).toEqual(1); expect(result[0].serialNumber).toEqual(1002); @@ -71,7 +71,7 @@ describe('InvoiceIn filter()', () => { }); it('should return the invoice in matching the account', async() => { - const tx = await app.models.Entry.beginTransaction({}); + const tx = await models.InvoiceIn.beginTransaction({}); const options = {transaction: tx}; try { @@ -81,7 +81,7 @@ describe('InvoiceIn filter()', () => { } }; - const result = await app.models.InvoiceIn.filter(ctx, {}, options); + const result = await models.InvoiceIn.filter(ctx, {}, options); expect(result.length).toEqual(5); expect(result[0].account).toEqual('4000020002'); @@ -94,7 +94,7 @@ describe('InvoiceIn filter()', () => { }); it('should return the invoice in matching the awb code', async() => { - const tx = await app.models.Entry.beginTransaction({}); + const tx = await models.InvoiceIn.beginTransaction({}); const options = {transaction: tx}; try { @@ -104,7 +104,7 @@ describe('InvoiceIn filter()', () => { } }; - const result = await app.models.InvoiceIn.filter(ctx, {}, options); + const result = await models.InvoiceIn.filter(ctx, {}, options); const firstRow = result[0]; expect(result.length).toEqual(1); @@ -119,7 +119,7 @@ describe('InvoiceIn filter()', () => { }); it('should return the invoice in matching the amount', async() => { - const tx = await app.models.Entry.beginTransaction({}); + const tx = await models.InvoiceIn.beginTransaction({}); const options = {transaction: tx}; try { @@ -129,7 +129,7 @@ describe('InvoiceIn filter()', () => { } }; - const result = await app.models.InvoiceIn.filter(ctx, {}, options); + const result = await models.InvoiceIn.filter(ctx, {}, options); expect(result.length).toEqual(1); expect(result[0].amount).toEqual(64.23); @@ -142,7 +142,7 @@ describe('InvoiceIn filter()', () => { }); it('should return the invoice in matching "from" and "to"', async() => { - const tx = await app.models.Entry.beginTransaction({}); + const tx = await models.InvoiceIn.beginTransaction({}); const options = {transaction: tx}; try { @@ -155,7 +155,7 @@ describe('InvoiceIn filter()', () => { args: {from, to} }; - const result = await app.models.InvoiceIn.filter(ctx, {}, options); + const result = await models.InvoiceIn.filter(ctx, {}, options); expect(result.length).toEqual(6); @@ -167,7 +167,7 @@ describe('InvoiceIn filter()', () => { }); it('should return the booked invoice in', async() => { - const tx = await app.models.Entry.beginTransaction({}); + const tx = await models.InvoiceIn.beginTransaction({}); const options = {transaction: tx}; try { @@ -177,7 +177,7 @@ describe('InvoiceIn filter()', () => { } }; - const result = await app.models.InvoiceIn.filter(ctx, {}, options); + const result = await models.InvoiceIn.filter(ctx, {}, options); expect(result.length).toEqual(6); expect(result[0].isBooked).toBeTruthy(); diff --git a/modules/invoiceIn/back/methods/invoice-in/specs/summary.spec.js b/modules/invoiceIn/back/methods/invoice-in/specs/summary.spec.js index 5fc749548..8ebd68832 100644 --- a/modules/invoiceIn/back/methods/invoice-in/specs/summary.spec.js +++ b/modules/invoiceIn/back/methods/invoice-in/specs/summary.spec.js @@ -1,12 +1,12 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('invoiceIn summary()', () => { it('should return a summary object containing data from one invoiceIn', async() => { - const tx = await app.models.Entry.beginTransaction({}); + const tx = await models.InvoiceIn.beginTransaction({}); const options = {transaction: tx}; try { - const summary = await app.models.InvoiceIn.summary(1, options); + const summary = await models.InvoiceIn.summary(1, options); expect(summary.supplierRef).toEqual('1234'); diff --git a/modules/invoiceOut/back/methods/invoiceOut/delete.js b/modules/invoiceOut/back/methods/invoiceOut/delete.js index e40fa6e6c..96b5e652e 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/delete.js +++ b/modules/invoiceOut/back/methods/invoiceOut/delete.js @@ -22,7 +22,7 @@ module.exports = Self => { Self.delete = async(id, options) => { let tx; - let myOptions = {}; + const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); @@ -42,7 +42,7 @@ module.exports = Self => { promises.push(ticket.updateAttribute('refFk', null, myOptions)); }); - await Promise.all(promises, myOptions); + await Promise.all(promises); await invoiceOut.destroy(myOptions); diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js index 8da5c853d..ee72f2218 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js @@ -1,20 +1,20 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('invoiceOut book()', () => { const invoiceOutId = 5; it('should update the booked property', async() => { - const tx = await app.models.InvoiceOut.beginTransaction({}); + const tx = await models.InvoiceOut.beginTransaction({}); const options = {transaction: tx}; try { - const originalInvoiceOut = await app.models.InvoiceOut.findById(invoiceOutId, {}, options); + const originalInvoiceOut = await models.InvoiceOut.findById(invoiceOutId, {}, options); const bookedDate = originalInvoiceOut.booked; const invoiceOutRef = originalInvoiceOut.ref; - await app.models.InvoiceOut.book(invoiceOutRef, options); + await models.InvoiceOut.book(invoiceOutRef, options); - const updatedInvoiceOut = await app.models.InvoiceOut.findById(invoiceOutId, {}, options); + const updatedInvoiceOut = await models.InvoiceOut.findById(invoiceOutId, {}, options); expect(updatedInvoiceOut.booked).not.toEqual(bookedDate); expect(updatedInvoiceOut.hasPdf).toBeFalsy(); diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/createPdf.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/createPdf.spec.js index 3372411c1..60dd5576d 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/createPdf.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/createPdf.spec.js @@ -1,4 +1,4 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; const got = require('got'); describe('InvoiceOut createPdf()', () => { @@ -19,7 +19,7 @@ describe('InvoiceOut createPdf()', () => { }; spyOn(got, 'stream').and.returnValue(response); - let result = await app.models.InvoiceOut.createPdf(ctx, invoiceId); + const result = await models.InvoiceOut.createPdf(ctx, invoiceId); expect(result.hasPdf).toBe(true); }); diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/delete.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/delete.spec.js index 88a69eac5..a662cb318 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/delete.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/delete.spec.js @@ -1,4 +1,4 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); describe('invoiceOut delete()', () => { @@ -9,12 +9,12 @@ describe('invoiceOut delete()', () => { }; it('should check that there is one ticket in the target invoiceOut', async() => { - const tx = await app.models.InvoiceOut.beginTransaction({}); + const tx = await models.InvoiceOut.beginTransaction({}); const options = {transaction: tx}; try { - const invoiceOut = await app.models.InvoiceOut.findById(invoiceOutId, {}, options); - const tickets = await app.models.Ticket.find({where: {refFk: invoiceOut.ref}}, options); + const invoiceOut = await models.InvoiceOut.findById(invoiceOutId, {}, options); + const tickets = await models.Ticket.find({where: {refFk: invoiceOut.ref}}, options); expect(tickets.length).toEqual(1); expect(tickets[0].id).toEqual(3); @@ -27,7 +27,7 @@ describe('invoiceOut delete()', () => { }); it(`should delete the target invoiceOut then check the ticket doesn't have a refFk anymore`, async() => { - const tx = await app.models.InvoiceOut.beginTransaction({}); + const tx = await models.InvoiceOut.beginTransaction({}); const options = {transaction: tx}; try { @@ -35,11 +35,11 @@ describe('invoiceOut delete()', () => { active: activeCtx }); - await app.models.InvoiceOut.delete(invoiceOutId, options); + await models.InvoiceOut.delete(invoiceOutId, options); - const originalTicket = await app.models.Ticket.findById(3, {}, options); + const originalTicket = await models.Ticket.findById(3, {}, options); - const deletedInvoiceOut = await app.models.InvoiceOut.findById(invoiceOutId, {}, options); + const deletedInvoiceOut = await models.InvoiceOut.findById(invoiceOutId, {}, options); expect(deletedInvoiceOut).toBeNull(); expect(originalTicket.refFk).toBeNull(); diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/download.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/download.spec.js index 09289896f..2d9056708 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/download.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/download.spec.js @@ -1,8 +1,8 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('InvoiceOut download()', () => { it('should return the downloaded fine name', async() => { - let result = await app.models.InvoiceOut.download(1); + const result = await models.InvoiceOut.download(1); expect(result[1]).toEqual('text/plain'); expect(result[2]).toEqual('filename="README.md"'); diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/filter.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/filter.spec.js index 2762e9bd6..2a530048e 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/filter.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/filter.spec.js @@ -1,11 +1,11 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('InvoiceOut filter()', () => { let today = new Date(); today.setHours(2, 0, 0, 0); it('should return the invoice out matching ref', async() => { - const tx = await app.models.InvoiceOut.beginTransaction({}); + const tx = await models.InvoiceOut.beginTransaction({}); const options = {transaction: tx}; try { @@ -15,7 +15,7 @@ describe('InvoiceOut filter()', () => { } }; - const result = await app.models.InvoiceOut.filter(ctx, {}, options); + const result = await models.InvoiceOut.filter(ctx, {}, options); expect(result.length).toEqual(1); expect(result[0].ref).toEqual('T4444444'); @@ -28,7 +28,7 @@ describe('InvoiceOut filter()', () => { }); it('should return the invoice out matching clientFk', async() => { - const tx = await app.models.InvoiceOut.beginTransaction({}); + const tx = await models.InvoiceOut.beginTransaction({}); const options = {transaction: tx}; try { @@ -38,7 +38,7 @@ describe('InvoiceOut filter()', () => { } }; - const result = await app.models.InvoiceOut.filter(ctx, {}, options); + const result = await models.InvoiceOut.filter(ctx, {}, options); expect(result.length).toEqual(1); expect(result[0].ref).toEqual('T2222222'); @@ -51,7 +51,7 @@ describe('InvoiceOut filter()', () => { }); it('should return the invoice out matching hasPdf', async() => { - const tx = await app.models.InvoiceOut.beginTransaction({}); + const tx = await models.InvoiceOut.beginTransaction({}); const options = {transaction: tx}; try { @@ -61,7 +61,7 @@ describe('InvoiceOut filter()', () => { } }; - const result = await app.models.InvoiceOut.filter(ctx, {}, options); + const result = await models.InvoiceOut.filter(ctx, {}, options); expect(result.length).toEqual(5); @@ -73,7 +73,7 @@ describe('InvoiceOut filter()', () => { }); it('should return the invoice out matching amount', async() => { - const tx = await app.models.InvoiceOut.beginTransaction({}); + const tx = await models.InvoiceOut.beginTransaction({}); const options = {transaction: tx}; try { @@ -83,7 +83,7 @@ describe('InvoiceOut filter()', () => { } }; - const result = await app.models.InvoiceOut.filter(ctx, {}, options); + const result = await models.InvoiceOut.filter(ctx, {}, options); expect(result.length).toEqual(1); expect(result[0].ref).toEqual('T2222222'); @@ -96,7 +96,7 @@ describe('InvoiceOut filter()', () => { }); it('should return the invoice out matching min and max', async() => { - const tx = await app.models.InvoiceOut.beginTransaction({}); + const tx = await models.InvoiceOut.beginTransaction({}); const options = {transaction: tx}; try { @@ -107,7 +107,7 @@ describe('InvoiceOut filter()', () => { } }; - let result = await app.models.InvoiceOut.filter(ctx, {}, options); + let result = await models.InvoiceOut.filter(ctx, {}, options); expect(result.length).toEqual(3); diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/getTickets.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/getTickets.spec.js index fffe4b760..67be3dfac 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/getTickets.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/getTickets.spec.js @@ -1,13 +1,13 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('entry getTickets()', () => { const invoiceOutId = 4; it('should get the ticket of an invoiceOut', async() => { - const tx = await app.models.InvoiceOut.beginTransaction({}); + const tx = await models.InvoiceOut.beginTransaction({}); const options = {transaction: tx}; try { - const result = await app.models.InvoiceOut.getTickets(invoiceOutId, {}, options); + const result = await models.InvoiceOut.getTickets(invoiceOutId, {}, options); expect(result.length).toEqual(1); diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/summary.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/summary.spec.js index 35bccfa1e..2db4077c3 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/summary.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/summary.spec.js @@ -1,12 +1,12 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('invoiceOut summary()', () => { it('should return a summary object containing data from one invoiceOut', async() => { - const tx = await app.models.InvoiceOut.beginTransaction({}); + const tx = await models.InvoiceOut.beginTransaction({}); const options = {transaction: tx}; try { - const result = await app.models.InvoiceOut.summary(1, options); + const result = await models.InvoiceOut.summary(1, options); expect(result.invoiceOut.id).toEqual(1); @@ -18,11 +18,11 @@ describe('invoiceOut summary()', () => { }); it(`should return a summary object containing it's supplier country`, async() => { - const tx = await app.models.InvoiceOut.beginTransaction({}); + const tx = await models.InvoiceOut.beginTransaction({}); const options = {transaction: tx}; try { - const summary = await app.models.InvoiceOut.summary(1, options); + const summary = await models.InvoiceOut.summary(1, options); const supplier = summary.invoiceOut.supplier(); expect(summary.invoiceOut.ref).toEqual('T1111111'); @@ -37,11 +37,11 @@ describe('invoiceOut summary()', () => { }); it(`should return a summary object containing idata from it's tax types`, async() => { - const tx = await app.models.InvoiceOut.beginTransaction({}); + const tx = await models.InvoiceOut.beginTransaction({}); const options = {transaction: tx}; try { - const summary = await app.models.InvoiceOut.summary(1, options); + const summary = await models.InvoiceOut.summary(1, options); expect(summary.invoiceOut.ref).toEqual('T1111111'); expect(summary.invoiceOut.taxesBreakdown.length).toEqual(2); diff --git a/modules/zone/back/methods/zone/deleteZone.js b/modules/zone/back/methods/zone/deleteZone.js index 05ffcda54..fb228bcf4 100644 --- a/modules/zone/back/methods/zone/deleteZone.js +++ b/modules/zone/back/methods/zone/deleteZone.js @@ -26,7 +26,7 @@ module.exports = Self => { today.setHours(0, 0, 0, 0); let tx; - let myOptions = {}; + const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); @@ -68,7 +68,7 @@ module.exports = Self => { }, myOptions)); } } - await Promise.all(promises, myOptions); + await Promise.all(promises); await models.Zone.destroyById(id, myOptions); if (tx) await tx.commit(); From 21e34de1dd4aa85b5a9db44bfbbb0605a4db1358 Mon Sep 17 00:00:00 2001 From: carlosjr Date: Mon, 12 Jul 2021 12:54:59 +0200 Subject: [PATCH 5/7] item module transactions --- .../item/back/methods/fixed-price/filter.js | 72 +++---- .../methods/fixed-price/specs/filter.spec.js | 176 +++++++++++------- .../specs/upsertFixedPrice.spec.js | 95 ++++++---- .../methods/fixed-price/upsertFixedPrice.js | 115 ++++++------ .../methods/item-barcode/specs/toItem.spec.js | 18 +- .../item/back/methods/item-barcode/toItem.js | 21 ++- .../back/methods/item-tag/filterItemTags.js | 39 ++-- .../item-tag/specs/filterItemTags.spec.js | 16 +- modules/item/back/methods/item/clone.js | 31 +-- .../item/back/methods/item/createIntrastat.js | 103 ++++++---- modules/item/back/methods/item/filter.js | 9 +- modules/item/back/methods/item/getBalance.js | 10 +- modules/item/back/methods/item/getCard.js | 15 +- modules/item/back/methods/item/getSummary.js | 27 +-- .../back/methods/item/getVisibleAvailable.js | 42 +++-- .../item/back/methods/item/getWasteByItem.js | 11 +- .../back/methods/item/getWasteByWorker.js | 11 +- .../back/methods/item/lastEntriesFilter.js | 9 +- modules/item/back/methods/item/new.js | 47 +++-- modules/item/back/methods/item/regularize.js | 90 +++++---- .../back/methods/item/specs/clone.spec.js | 51 +++-- .../item/specs/createIntrastat.spec.js | 35 ++-- .../back/methods/item/specs/filter.spec.js | 14 +- .../methods/item/specs/getBalance.spec.js | 50 ++--- .../back/methods/item/specs/getCard.spec.js | 23 +++ .../back/methods/item/specs/getDiary.spec.js | 12 -- .../methods/item/specs/getSummary.spec.js | 31 ++- .../item/specs/getVisibleAvailable.spec.js | 55 +++--- .../methods/item/specs/getWasteByItem.spec.js | 24 ++- .../item/specs/getWasteByWorker.spec.js | 22 ++- .../item/specs/lastEntriesFilter.spec.js | 36 +++- .../item/back/methods/item/specs/new.spec.js | 72 ++++--- .../methods/item/specs/regularize.spec.js | 47 ++--- .../methods/item/specs/updateTaxes.spec.js | 49 +++-- modules/item/back/methods/item/updateTaxes.js | 42 +++-- modules/item/back/methods/tag/filterValue.js | 38 ++-- .../methods/tag/specs/filterValue.spec.js | 75 ++++++-- 37 files changed, 1012 insertions(+), 621 deletions(-) create mode 100644 modules/item/back/methods/item/specs/getCard.spec.js delete mode 100644 modules/item/back/methods/item/specs/getDiary.spec.js diff --git a/modules/item/back/methods/fixed-price/filter.js b/modules/item/back/methods/fixed-price/filter.js index 22cf2bf44..c15ae67f0 100644 --- a/modules/item/back/methods/fixed-price/filter.js +++ b/modules/item/back/methods/fixed-price/filter.js @@ -80,12 +80,12 @@ module.exports = Self => { }, { arg: 'mine', - type: 'Boolean', + type: 'boolean', description: `Search requests attended by the current user` } ], returns: { - type: ['Object'], + type: ['object'], root: true }, http: { @@ -94,9 +94,13 @@ module.exports = Self => { } }); - Self.filter = async(ctx, filter) => { + Self.filter = async(ctx, filter, options) => { const conn = Self.dataSource.connector; - let userId = ctx.req.accessToken.userId; + const userId = ctx.req.accessToken.userId; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); if (ctx.args.mine) ctx.args.buyerFk = userId; @@ -128,36 +132,35 @@ module.exports = Self => { filter = mergeFilters(filter, {where}); const stmts = []; - let stmt; - stmt = new ParameterizedSQL( - `SELECT fp.id, - fp.itemFk, - fp.warehouseFk, - fp.rate2, - fp.rate3, - fp.started, - fp.ended, - i.minPrice, - i.hasMinPrice, - i.name, - i.subName, - i.tag5, - i.value5, - i.tag6, - i.value6, - i.tag7, - i.value7, - i.tag8, - i.value8, - i.tag9, - i.value9, - i.tag10, - i.value10 - FROM priceFixed fp - JOIN item i ON i.id = fp.itemFk - JOIN itemType it ON it.id = i.typeFk` - ); + const stmt = new ParameterizedSQL(` + SELECT fp.id, + fp.itemFk, + fp.warehouseFk, + fp.rate2, + fp.rate3, + fp.started, + fp.ended, + i.minPrice, + i.hasMinPrice, + i.name, + i.subName, + i.tag5, + i.value5, + i.tag6, + i.value6, + i.tag7, + i.value7, + i.tag8, + i.value8, + i.tag9, + i.value9, + i.tag10, + i.value10 + FROM priceFixed fp + JOIN item i ON i.id = fp.itemFk + JOIN itemType it ON it.id = i.typeFk + `); if (ctx.args.tags) { let i = 1; @@ -186,7 +189,8 @@ module.exports = Self => { const fixedPriceIndex = stmts.push(stmt) - 1; const sql = ParameterizedSQL.join(stmts, ';'); - const result = await conn.executeStmt(sql); + const result = await conn.executeStmt(sql, myOptions); + return fixedPriceIndex === 0 ? result : result[fixedPriceIndex]; }; }; diff --git a/modules/item/back/methods/fixed-price/specs/filter.spec.js b/modules/item/back/methods/fixed-price/specs/filter.spec.js index ff259357f..bdb28efd9 100644 --- a/modules/item/back/methods/fixed-price/specs/filter.spec.js +++ b/modules/item/back/methods/fixed-price/specs/filter.spec.js @@ -1,86 +1,136 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('fixed price filter()', () => { it('should return 1 result filtering by item ID', async() => { - const itemID = 3; - const ctx = { - req: {accessToken: {userId: 1}}, - args: { - search: itemID - } - }; - const result = await app.models.FixedPrice.filter(ctx); + const tx = await models.FixedPrice.beginTransaction({}); - expect(result.length).toEqual(1); - expect(result[0].id).toEqual(2); - expect(result[0].itemFk).toEqual(itemID); + try { + const options = {transaction: tx}; + const itemID = 3; + const ctx = { + req: {accessToken: {userId: 1}}, + args: { + search: itemID + } + }; + const result = await models.FixedPrice.filter(ctx, null, options); + + expect(result.length).toEqual(1); + expect(result[0].id).toEqual(2); + expect(result[0].itemFk).toEqual(itemID); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return 1 result filtering by item type code', async() => { - const itemCode = 'CRI'; - const ctx = { - req: {accessToken: {userId: 1}}, - args: { - search: itemCode - } - }; - const itemType = await app.models.ItemType.findOne({ - where: {code: itemCode}, - fields: ['id'] - }); - const items = await app.models.Item.find({ - where: {typeFk: itemType.id}, - fields: ['id'] - }); - const IDs = items.map(item => { - return item.id; - }); + const tx = await models.FixedPrice.beginTransaction({}); - const result = await app.models.FixedPrice.filter(ctx); - const firstResult = result[0]; + try { + const options = {transaction: tx}; + const itemCode = 'CRI'; + const ctx = { + req: {accessToken: {userId: 1}}, + args: { + search: itemCode + } + }; + const itemType = await models.ItemType.findOne({ + where: {code: itemCode}, + fields: ['id'] + }, options); + const items = await models.Item.find({ + where: {typeFk: itemType.id}, + fields: ['id'] + }, options); + const IDs = items.map(item => { + return item.id; + }); - expect(result.length).toEqual(1); - expect(firstResult.id).toEqual(2); - expect(IDs).toContain(firstResult.itemFk); + const result = await models.FixedPrice.filter(ctx, null, options); + const firstResult = result[0]; + + expect(result.length).toEqual(1); + expect(firstResult.id).toEqual(2); + expect(IDs).toContain(firstResult.itemFk); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return 2 results filtering by warehouse', async() => { - const warehouseID = 1; - const ctx = { - req: {accessToken: {userId: 1}}, - args: { - warehouseFk: warehouseID - } - }; - const result = await app.models.FixedPrice.filter(ctx); - const length = result.length; - const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; + const tx = await models.FixedPrice.beginTransaction({}); - expect(result.length).toEqual(2); - expect(anyResult.warehouseFk).toEqual(warehouseID); + try { + const options = {transaction: tx}; + const warehouseID = 1; + const ctx = { + req: {accessToken: {userId: 1}}, + args: { + warehouseFk: warehouseID + } + }; + const result = await models.FixedPrice.filter(ctx, null, options); + const length = result.length; + const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; + + expect(result.length).toEqual(2); + expect(anyResult.warehouseFk).toEqual(warehouseID); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return no results filtering by hasMinPrice', async() => { - const ctx = { - req: {accessToken: {userId: 1}}, - args: { - hasMinPrice: true - } - }; - const result = await app.models.FixedPrice.filter(ctx); + const tx = await models.FixedPrice.beginTransaction({}); - expect(result.length).toEqual(0); + try { + const options = {transaction: tx}; + const ctx = { + req: {accessToken: {userId: 1}}, + args: { + hasMinPrice: true + } + }; + const result = await models.FixedPrice.filter(ctx, null, options); + + expect(result.length).toEqual(0); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return no results filtering by typeFk', async() => { - const ctx = { - req: {accessToken: {userId: 1}}, - args: { - typeFk: 1 - } - }; - const result = await app.models.FixedPrice.filter(ctx); + const tx = await models.FixedPrice.beginTransaction({}); - expect(result.length).toEqual(1); + try { + const options = {transaction: tx}; + const ctx = { + req: {accessToken: {userId: 1}}, + args: { + typeFk: 1 + } + }; + const result = await models.FixedPrice.filter(ctx, null, options); + + expect(result.length).toEqual(1); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/item/back/methods/fixed-price/specs/upsertFixedPrice.spec.js b/modules/item/back/methods/fixed-price/specs/upsertFixedPrice.spec.js index 63c211293..68eacfbad 100644 --- a/modules/item/back/methods/fixed-price/specs/upsertFixedPrice.spec.js +++ b/modules/item/back/methods/fixed-price/specs/upsertFixedPrice.spec.js @@ -1,62 +1,75 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('upsertFixedPrice()', () => { const now = new Date(); const fixedPriceId = 1; let originalFixedPrice; - let originalItem; beforeAll(async() => { - originalFixedPrice = await app.models.FixedPrice.findById(fixedPriceId); - originalItem = await app.models.Item.findById(originalFixedPrice.itemFk); - }); - - afterAll(async() => { - await originalFixedPrice.save(); - await originalItem.save(); + originalFixedPrice = await models.FixedPrice.findById(fixedPriceId); }); it(`should toggle the hasMinPrice boolean if there's a minPrice and update the rest of the data`, async() => { - const ctx = {args: { - id: fixedPriceId, - itemFk: originalFixedPrice.itemFk, - warehouseFk: 1, - rate2: 100, - rate3: 300, - started: now, - ended: now, - minPrice: 100, - hasMinPrice: false - }}; + const tx = await models.FixedPrice.beginTransaction({}); - const result = await app.models.FixedPrice.upsertFixedPrice(ctx, ctx.args.id); + try { + const options = {transaction: tx}; + const ctx = {args: { + id: fixedPriceId, + itemFk: originalFixedPrice.itemFk, + warehouseFk: 1, + rate2: 100, + rate3: 300, + started: now, + ended: now, + minPrice: 100, + hasMinPrice: false + }}; - delete ctx.args.started; - delete ctx.args.ended; - ctx.args.hasMinPrice = true; + const result = await models.FixedPrice.upsertFixedPrice(ctx, options); - expect(result).toEqual(jasmine.objectContaining(ctx.args)); + delete ctx.args.started; + delete ctx.args.ended; + ctx.args.hasMinPrice = true; + + expect(result).toEqual(jasmine.objectContaining(ctx.args)); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it(`should toggle the hasMinPrice boolean if there's no minPrice and update the rest of the data`, async() => { - const ctx = {args: { - id: fixedPriceId, - itemFk: originalFixedPrice.itemFk, - warehouseFk: 1, - rate2: 2.5, - rate3: 2, - started: now, - ended: now, - minPrice: 0, - hasMinPrice: true - }}; + const tx = await models.FixedPrice.beginTransaction({}); - const result = await app.models.FixedPrice.upsertFixedPrice(ctx, ctx.args.id); + try { + const options = {transaction: tx}; + const ctx = {args: { + id: fixedPriceId, + itemFk: originalFixedPrice.itemFk, + warehouseFk: 1, + rate2: 2.5, + rate3: 2, + started: now, + ended: now, + minPrice: 0, + hasMinPrice: true + }}; - delete ctx.args.started; - delete ctx.args.ended; - ctx.args.hasMinPrice = false; + const result = await models.FixedPrice.upsertFixedPrice(ctx, options); - expect(result).toEqual(jasmine.objectContaining(ctx.args)); + delete ctx.args.started; + delete ctx.args.ended; + ctx.args.hasMinPrice = false; + + expect(result).toEqual(jasmine.objectContaining(ctx.args)); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/item/back/methods/fixed-price/upsertFixedPrice.js b/modules/item/back/methods/fixed-price/upsertFixedPrice.js index dbdeebdab..46283d63a 100644 --- a/modules/item/back/methods/fixed-price/upsertFixedPrice.js +++ b/modules/item/back/methods/fixed-price/upsertFixedPrice.js @@ -2,48 +2,50 @@ module.exports = Self => { Self.remoteMethod('upsertFixedPrice', { description: 'Inserts or updates a fixed price for an item', accessType: 'WRITE', - accepts: [{ - arg: 'ctx', - type: 'object', - http: {source: 'context'} - }, - { - arg: 'id', - type: 'number', - description: 'The fixed price id' - }, - { - arg: 'itemFk', - type: 'number' - }, - { - arg: 'warehouseFk', - type: 'number' - }, - { - arg: 'started', - type: 'date' - }, - { - arg: 'ended', - type: 'date' - }, - { - arg: 'rate2', - type: 'number' - }, - { - arg: 'rate3', - type: 'number' - }, - { - arg: 'minPrice', - type: 'number' - }, - { - arg: 'hasMinPrice', - type: 'any' - }], + accepts: [ + { + arg: 'ctx', + type: 'object', + http: {source: 'context'} + }, + { + arg: 'id', + type: 'number', + description: 'The fixed price id' + }, + { + arg: 'itemFk', + type: 'number' + }, + { + arg: 'warehouseFk', + type: 'number' + }, + { + arg: 'started', + type: 'date' + }, + { + arg: 'ended', + type: 'date' + }, + { + arg: 'rate2', + type: 'number' + }, + { + arg: 'rate3', + type: 'number' + }, + { + arg: 'minPrice', + type: 'number' + }, + { + arg: 'hasMinPrice', + type: 'any' + } + ], returns: { type: 'object', root: true @@ -54,21 +56,29 @@ module.exports = Self => { } }); - Self.upsertFixedPrice = async ctx => { + Self.upsertFixedPrice = async(ctx, options) => { const models = Self.app.models; - const args = ctx.args; - const tx = await models.Address.beginTransaction({}); - try { - const options = {transaction: tx}; - delete args.ctx; // removed unwanted data + let tx; + const myOptions = {}; + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + delete args.ctx; // removed unwanted data const fixedPrice = await models.FixedPrice.upsert(args, options); const targetItem = await models.Item.findById(args.itemFk, null, options); + await targetItem.updateAttributes({ minPrice: args.minPrice, hasMinPrice: args.minPrice ? true : false - }, options); + }, myOptions); const itemFields = [ 'minPrice', @@ -99,16 +109,17 @@ module.exports = Self => { } }; - const result = await models.FixedPrice.findById(fixedPrice.id, filter, options); + const result = await models.FixedPrice.findById(fixedPrice.id, filter, myOptions); const item = result.item(); for (let key of itemFields) result[key] = item[key]; - await tx.commit(); + if (tx) await tx.commit(); + return result; } catch (e) { - await tx.rollback(); + if (tx) await tx.rollback(); throw e; } }; diff --git a/modules/item/back/methods/item-barcode/specs/toItem.spec.js b/modules/item/back/methods/item-barcode/specs/toItem.spec.js index 9e81dc590..5547a3886 100644 --- a/modules/item/back/methods/item-barcode/specs/toItem.spec.js +++ b/modules/item/back/methods/item-barcode/specs/toItem.spec.js @@ -1,10 +1,20 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('item-barcode toItem()', () => { it('should return the same number if there is a barcode and a item with the same ID', async() => { - let barcode = 3; - let result = await app.models.ItemBarcode.toItem(barcode); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - expect(result).toBe(3); + try { + const barcode = 3; + const result = await models.ItemBarcode.toItem(barcode, options); + + expect(result).toBe(3); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/item/back/methods/item-barcode/toItem.js b/modules/item/back/methods/item-barcode/toItem.js index 0fbbf4508..96e9d5981 100644 --- a/modules/item/back/methods/item-barcode/toItem.js +++ b/modules/item/back/methods/item-barcode/toItem.js @@ -4,12 +4,12 @@ module.exports = Self => { accessType: 'READ', accepts: [{ arg: 'barcode', - type: 'Number', + type: 'number', required: true, description: 'barcode' }], returns: { - type: 'Number', + type: 'number', root: true }, http: { @@ -18,11 +18,18 @@ module.exports = Self => { } }); - Self.toItem = async barcode => { - let query = `SELECT vn.barcodeToItem(?)`; - let [item] = await Self.rawSql(query, [barcode]); + Self.toItem = async(barcode, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const query = `SELECT vn.barcodeToItem(?)`; + let [item] = await Self.rawSql(query, [barcode], myOptions); + if (item) - item = Object.values(item); - return item[0]; + item = Object.values(item)[0]; + + return item; }; }; diff --git a/modules/item/back/methods/item-tag/filterItemTags.js b/modules/item/back/methods/item-tag/filterItemTags.js index ed5973c17..8a02f5880 100644 --- a/modules/item/back/methods/item-tag/filterItemTags.js +++ b/modules/item/back/methods/item-tag/filterItemTags.js @@ -5,17 +5,19 @@ module.exports = Self => { Self.remoteMethod('filterItemTags', { description: 'Returns the distinct values of a tag property', accessType: 'READ', - accepts: [{ - arg: 'tagFk', - type: 'number', - required: true, - description: 'The foreign key from tag table', - http: {source: 'path'} - }, { - arg: 'filter', - type: 'Object', - description: `Filter defining where, order, offset, and limit - must be a JSON-encoded string` - }], + accepts: [ + { + arg: 'tagFk', + type: 'number', + required: true, + description: 'The foreign key from tag table', + http: {source: 'path'} + }, { + arg: 'filter', + type: 'object', + description: `Filter defining where, order, offset, and limit - must be a JSON-encoded string` + } + ], returns: { root: true, type: ['object'] @@ -26,16 +28,21 @@ module.exports = Self => { } }); - Self.filterItemTags = async(tagFk, filter) => { - let conn = Self.dataSource.connector; - let where = {tagFk: tagFk}; - myFilter = mergeFilters(filter, {where}); + Self.filterItemTags = async(tagFk, filter, options) => { + const conn = Self.dataSource.connector; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const where = {tagFk: tagFk}; + const myFilter = mergeFilters(filter, {where}); stmt = new ParameterizedSQL( `SELECT DISTINCT(value) FROM itemTag`); stmt.merge(conn.makeSuffix(myFilter)); - return await conn.executeStmt(stmt); + return conn.executeStmt(stmt, myOptions); }; }; diff --git a/modules/item/back/methods/item-tag/specs/filterItemTags.spec.js b/modules/item/back/methods/item-tag/specs/filterItemTags.spec.js index 272367327..3c6d2ccff 100644 --- a/modules/item/back/methods/item-tag/specs/filterItemTags.spec.js +++ b/modules/item/back/methods/item-tag/specs/filterItemTags.spec.js @@ -1,9 +1,19 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('item filterItemTags()', () => { it('should filter ItemTags table', async() => { - let [result] = await app.models.ItemTag.filterItemTags(1, {}); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - expect(result.value).toEqual('Black'); + try { + const [result] = await models.ItemTag.filterItemTags(1, null, options); + + expect(result.value).toEqual('Black'); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/item/back/methods/item/clone.js b/modules/item/back/methods/item/clone.js index f543164fc..04d018961 100644 --- a/modules/item/back/methods/item/clone.js +++ b/modules/item/back/methods/item/clone.js @@ -12,7 +12,7 @@ module.exports = Self => { http: {source: 'path'} }], returns: { - type: 'Object', + type: 'object', description: 'new cloned itemId', root: true, }, @@ -22,13 +22,21 @@ module.exports = Self => { } }); - Self.clone = async itemId => { - let tx = await Self.beginTransaction({}); + Self.clone = async(itemId, options) => { + let tx; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } try { - let options = {transaction: tx}; + const origin = await Self.findById(itemId, null, myOptions); - const origin = await Self.findById(itemId, null, options); if (!origin) throw new UserError(`This item doesn't exists`); @@ -38,16 +46,17 @@ module.exports = Self => { origin.comment = undefined; origin.size = undefined; - const newItem = await Self.create(origin, options); + const newItem = await Self.create(origin, myOptions); - await cloneTaxes(origin.id, newItem.id, options); - await cloneBotanical(origin.id, newItem.id, options); - await cloneTags(origin.id, newItem.id, options); + await cloneTaxes(origin.id, newItem.id, myOptions); + await cloneBotanical(origin.id, newItem.id, myOptions); + await cloneTags(origin.id, newItem.id, myOptions); + + if (tx) await tx.commit(); - await tx.commit(); return newItem; } catch (e) { - await tx.rollback(); + if (tx) await tx.rollback(); throw e; } }; diff --git a/modules/item/back/methods/item/createIntrastat.js b/modules/item/back/methods/item/createIntrastat.js index bd921f29a..3109dace3 100644 --- a/modules/item/back/methods/item/createIntrastat.js +++ b/modules/item/back/methods/item/createIntrastat.js @@ -2,23 +2,25 @@ module.exports = Self => { Self.remoteMethod('createIntrastat', { description: 'Creates a new item intrastat', accessType: 'WRITE', - accepts: [{ - arg: 'id', - type: 'number', - required: true, - description: 'The item id', - http: {source: 'path'} - }, - { - arg: 'intrastatId', - type: 'number', - required: true - }, - { - arg: 'description', - type: 'string', - required: true - }], + accepts: [ + { + arg: 'id', + type: 'number', + required: true, + description: 'The item id', + http: {source: 'path'} + }, + { + arg: 'intrastatId', + type: 'number', + required: true + }, + { + arg: 'description', + type: 'string', + required: true + } + ], returns: { type: 'boolean', root: true @@ -29,31 +31,52 @@ module.exports = Self => { } }); - Self.createIntrastat = async(id, intrastatId, description) => { + Self.createIntrastat = async(id, intrastatId, description, options) => { const models = Self.app.models; - const country = await models.Country.findOne({ - where: {code: 'ES'} - }); + const myOptions = {}; + let tx; - const itemTaxCountry = await models.ItemTaxCountry.findOne({ - where: { - itemFk: id, - countryFk: country.id - }, - order: 'effectived DESC' - }); - const taxClassCode = await models.TaxClassCode.findOne({ - where: { - taxClassFk: itemTaxCountry.taxClassFk - }, - order: 'effectived DESC' - }); + if (typeof options == 'object') + Object.assign(myOptions, options); - return models.Intrastat.create({ - id: intrastatId, - description: description, - taxClassFk: itemTaxCountry.taxClassFk, - taxCodeFk: taxClassCode.taxCodeFk - }); + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + const country = await models.Country.findOne({ + where: {code: 'ES'} + }, myOptions); + + const itemTaxCountry = await models.ItemTaxCountry.findOne({ + where: { + itemFk: id, + countryFk: country.id + }, + order: 'effectived DESC' + }, myOptions); + + const taxClassCode = await models.TaxClassCode.findOne({ + where: { + taxClassFk: itemTaxCountry.taxClassFk + }, + order: 'effectived DESC' + }, myOptions); + + const intrastat = await models.Intrastat.create({ + id: intrastatId, + description: description, + taxClassFk: itemTaxCountry.taxClassFk, + taxCodeFk: taxClassCode.taxCodeFk + }, myOptions); + + if (tx) await tx.commit(); + + return intrastat; + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } }; }; diff --git a/modules/item/back/methods/item/filter.js b/modules/item/back/methods/item/filter.js index dca808aa3..a10eff711 100644 --- a/modules/item/back/methods/item/filter.js +++ b/modules/item/back/methods/item/filter.js @@ -71,7 +71,7 @@ module.exports = Self => { Self.filter = async(ctx, filter, options) => { const conn = Self.dataSource.connector; - let myOptions = {}; + const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); @@ -83,7 +83,9 @@ module.exports = Self => { where: {code: ctx.args.search}, fields: ['itemFk'] }, myOptions); + const itemIds = []; + for (const item of items) itemIds.push(item.itemFk); @@ -116,12 +118,11 @@ module.exports = Self => { return {'intr.description': value}; } }); + filter = mergeFilters(filter, {where}); const stmts = []; - let stmt; - - stmt = new ParameterizedSQL( + const stmt = new ParameterizedSQL( `SELECT i.id, i.image, diff --git a/modules/item/back/methods/item/getBalance.js b/modules/item/back/methods/item/getBalance.js index 916757c46..50372652d 100644 --- a/modules/item/back/methods/item/getBalance.js +++ b/modules/item/back/methods/item/getBalance.js @@ -19,9 +19,15 @@ module.exports = Self => { } }); - Self.getBalance = async filter => { + Self.getBalance = async(filter, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + const where = filter.where; - let [diary] = await Self.rawSql(`CALL vn.item_getBalance(?, ?)`, [where.itemFk, where.warehouseFk]); + const query = 'CALL vn.item_getBalance(?, ?)'; + const [diary] = await Self.rawSql(query, [where.itemFk, where.warehouseFk], myOptions); for (const entry of diary) if (entry.clientType === 'loses') entry.highlighted = true; diff --git a/modules/item/back/methods/item/getCard.js b/modules/item/back/methods/item/getCard.js index 69b5c1116..8bb88fc86 100644 --- a/modules/item/back/methods/item/getCard.js +++ b/modules/item/back/methods/item/getCard.js @@ -19,12 +19,13 @@ module.exports = Self => { } }); - Self.getCard = async id => { - let item = {}; + Self.getCard = async(id, options) => { + const myOptions = {}; - // Item basic data - let filter = { - where: {id: id}, + if (typeof options == 'object') + Object.assign(myOptions, options); + + const filter = { include: [ { relation: 'itemType', @@ -58,8 +59,8 @@ module.exports = Self => { } ] }; - [item] = await Self.app.models.Item.find(filter); + const item = await Self.app.models.Item.findById(id, filter, myOptions); - return item; + return item ? item : {}; }; }; diff --git a/modules/item/back/methods/item/getSummary.js b/modules/item/back/methods/item/getSummary.js index 4ef9652ca..6422d87ff 100644 --- a/modules/item/back/methods/item/getSummary.js +++ b/modules/item/back/methods/item/getSummary.js @@ -19,14 +19,18 @@ module.exports = Self => { } }); - Self.getSummary = async(ctx, id) => { - let promises = []; - let summary = {}; + Self.getSummary = async(ctx, id, options) => { const models = Self.app.models; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const promises = []; + const summary = {}; // Item basic data and taxes let filter = { - where: {id: id}, include: [ {relation: 'itemType', scope: { @@ -67,7 +71,7 @@ module.exports = Self => { } ] }; - promises.push(models.Item.find(filter)); + promises.push(models.Item.findById(id, filter, myOptions)); // Tags filter = { @@ -79,35 +83,36 @@ module.exports = Self => { relation: 'tag' } }; - promises.push(models.ItemTag.find(filter)); + promises.push(models.ItemTag.find(filter, myOptions)); // Botanical filter = { where: {itemFk: id}, include: [{relation: 'genus'}, {relation: 'specie'}] }; - promises.push(models.ItemBotanical.find(filter)); + promises.push(models.ItemBotanical.find(filter, myOptions)); // Niches filter = { where: {itemFk: id}, include: {relation: 'warehouse'} }; - promises.push(models.ItemNiche.find(filter)); + promises.push(models.ItemNiche.find(filter, myOptions)); let res = await Promise.all(promises); - [summary.item] = res[0]; + summary.item = res[0]; summary.tags = res[1]; [summary.botanical] = res[2]; summary.niches = res[3]; - const userConfig = await models.UserConfig.getUserConfig(ctx); + const userConfig = await models.UserConfig.getUserConfig(ctx, myOptions); - res = await models.Item.getVisibleAvailable(summary.item.id, userConfig.warehouseFk); + res = await models.Item.getVisibleAvailable(summary.item.id, userConfig.warehouseFk, null, myOptions); summary.available = res.available; summary.visible = res.visible; + return summary; }; }; diff --git a/modules/item/back/methods/item/getVisibleAvailable.js b/modules/item/back/methods/item/getVisibleAvailable.js index 0dd578733..b291ad9b4 100644 --- a/modules/item/back/methods/item/getVisibleAvailable.js +++ b/modules/item/back/methods/item/getVisibleAvailable.js @@ -5,19 +5,20 @@ module.exports = Self => { accepts: [ { arg: 'id', - type: 'Number', + type: 'number', required: true, }, { arg: 'warehouseFk', - type: 'Number', + type: 'number', required: true, }, { arg: 'dated', - type: 'Date', + type: 'date', required: false, - }], + } + ], returns: { type: ['object'], root: true @@ -28,32 +29,43 @@ module.exports = Self => { } }); - Self.getVisibleAvailable = async(id, warehouseFk, dated = new Date()) => { - let stmts = []; + Self.getVisibleAvailable = async(id, warehouseFk, dated = new Date(), options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const stmts = []; stmts.push(new ParameterizedSQL( - 'CALL cache.available_refresh(@availableCalc, FALSE, ?, ?)', [ + 'CALL cache.available_refresh(@availableCalc, FALSE, ?, ?)', + [ warehouseFk, dated - ] + ], + myOptions )); + stmts.push(new ParameterizedSQL( 'CALL cache.visible_refresh(@visibleCalc, FALSE,?)', [ warehouseFk ] )); + const visibleIndex = stmts.push(new ParameterizedSQL( - 'SELECT visible FROM cache.visible WHERE calc_id = @visibleCalc AND item_id = ?', [ - id - ] + 'SELECT visible FROM cache.visible WHERE calc_id = @visibleCalc AND item_id = ?', + [id], + myOptions )) - 1; + const availableIndex = stmts.push(new ParameterizedSQL( - 'SELECT available FROM cache.available WHERE calc_id = @availableCalc AND item_id = ?', [ - id - ] + 'SELECT available FROM cache.available WHERE calc_id = @availableCalc AND item_id = ?', + [id], + myOptions )) - 1; + const sql = ParameterizedSQL.join(stmts, ';'); - let res = await Self.rawStmt(sql); + const res = await Self.rawStmt(sql, myOptions); return { available: res[availableIndex][0] ? res[availableIndex][0].available : 0, diff --git a/modules/item/back/methods/item/getWasteByItem.js b/modules/item/back/methods/item/getWasteByItem.js index 21a68c359..a797667f5 100644 --- a/modules/item/back/methods/item/getWasteByItem.js +++ b/modules/item/back/methods/item/getWasteByItem.js @@ -17,7 +17,7 @@ module.exports = Self => { } ], returns: { - type: ['Object'], + type: ['object'], root: true }, http: { @@ -26,7 +26,12 @@ module.exports = Self => { } }); - Self.getWasteByItem = async(buyer, family) => { + Self.getWasteByItem = async(buyer, family, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + const wastes = await Self.rawSql(` SELECT *, 100 * dwindle / total AS percentage FROM ( @@ -41,7 +46,7 @@ module.exports = Self => { AND week = WEEK(TIMESTAMPADD(WEEK,-1,CURDATE()), 1) GROUP BY buyer, itemFk ) sub - ORDER BY family, percentage DESC`, [buyer, family]); + ORDER BY family, percentage DESC`, [buyer, family], myOptions); const details = []; diff --git a/modules/item/back/methods/item/getWasteByWorker.js b/modules/item/back/methods/item/getWasteByWorker.js index 032472696..5e40831b9 100644 --- a/modules/item/back/methods/item/getWasteByWorker.js +++ b/modules/item/back/methods/item/getWasteByWorker.js @@ -4,7 +4,7 @@ module.exports = Self => { accessType: 'READ', accepts: [], returns: { - type: ['Object'], + type: ['object'], root: true }, http: { @@ -13,7 +13,12 @@ module.exports = Self => { } }); - Self.getWasteByWorker = async() => { + Self.getWasteByWorker = async options => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + const wastes = await Self.rawSql(` SELECT *, 100 * dwindle / total AS percentage FROM ( @@ -26,7 +31,7 @@ module.exports = Self => { AND week = WEEK(TIMESTAMPADD(WEEK,-1,CURDATE()), 1) GROUP BY buyer, family ) sub - ORDER BY percentage DESC`); + ORDER BY percentage DESC`, null, myOptions); const details = []; diff --git a/modules/item/back/methods/item/lastEntriesFilter.js b/modules/item/back/methods/item/lastEntriesFilter.js index 6f22f637f..83a8fe7a2 100644 --- a/modules/item/back/methods/item/lastEntriesFilter.js +++ b/modules/item/back/methods/item/lastEntriesFilter.js @@ -21,8 +21,13 @@ module.exports = Self => { } }); - Self.lastEntriesFilter = async filter => { + Self.lastEntriesFilter = async(filter, options) => { const conn = Self.dataSource.connector; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + const stmt = new ParameterizedSQL( `SELECT w.id AS warehouseFk, @@ -64,6 +69,6 @@ module.exports = Self => { LEFT JOIN edi.ekt ek ON b.ektFk = ek.id`); stmt.merge(conn.makeSuffix(filter)); - return conn.executeStmt(stmt); + return conn.executeStmt(stmt, myOptions); }; }; diff --git a/modules/item/back/methods/item/new.js b/modules/item/back/methods/item/new.js index e6288aede..0771b6b14 100644 --- a/modules/item/back/methods/item/new.js +++ b/modules/item/back/methods/item/new.js @@ -2,7 +2,7 @@ let UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethod('new', { - description: 'Create a new item and returns the new ID', + description: 'returns the created item', accessType: 'WRITE', accepts: [{ arg: 'params', @@ -19,8 +19,20 @@ module.exports = Self => { } }); - Self.new = async params => { - let validUpdateParams = [ + Self.new = async(params, options) => { + const models = Self.app.models; + const myOptions = {}; + let tx; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + const validUpdateParams = [ 'provisionalName', 'typeFk', 'intrastatFk', @@ -33,20 +45,21 @@ module.exports = Self => { throw new UserError(`You don't have enough privileges to do that`); } - let tx = await Self.beginTransaction({}); try { - let options = {transaction: tx}; - - let provisionalName = params.provisionalName; + const provisionalName = params.provisionalName; delete params.provisionalName; - let item = await Self.app.models.Item.create(params, options); + const item = await models.Item.create(params, myOptions); + + const typeTags = await models.ItemTypeTag.find({ + where: {itemTypeFk: item.typeFk} + }, myOptions); - let typeTags = await Self.app.models.ItemTypeTag.find({where: {itemTypeFk: item.typeFk}}); let query = `SET @isTriggerDisabled = TRUE`; - await Self.rawSql(query, null, options); - let nameTag = await Self.app.models.Tag.findOne({where: {name: 'Nombre temporal'}}); + await Self.rawSql(query, null, myOptions); + + let nameTag = await models.Tag.findOne({where: {name: 'Nombre temporal'}}); let newTags = []; @@ -55,17 +68,19 @@ module.exports = Self => { newTags.push({itemFk: item.id, tagFk: typeTag.tagFk, value: '', priority: typeTag.priority}); }); - await Self.app.models.ItemTag.create(newTags, options); + await models.ItemTag.create(newTags, myOptions); query = `SET @isTriggerDisabled = FALSE`; - await Self.rawSql(query, null, options); + await Self.rawSql(query, null, myOptions); query = `CALL vn.itemRefreshTags(?)`; - await Self.rawSql(query, [item.id], options); - await tx.commit(); + await Self.rawSql(query, [item.id], myOptions); + + if (tx) await tx.commit(); + return item; } catch (e) { - await tx.rollback(); + if (tx) await tx.rollback(); throw e; } }; diff --git a/modules/item/back/methods/item/regularize.js b/modules/item/back/methods/item/regularize.js index bd908c2b7..8aec2fa02 100644 --- a/modules/item/back/methods/item/regularize.js +++ b/modules/item/back/methods/item/regularize.js @@ -2,22 +2,26 @@ module.exports = Self => { Self.remoteMethodCtx('regularize', { description: 'Sends items to the trash', accessType: 'WRITE', - accepts: [{ - arg: 'itemFk', - type: 'number', - required: true, - description: 'The item id', - }, { - arg: 'quantity', - type: 'number', - required: true, - description: 'The visible quantity', - }, { - arg: 'warehouseFk', - type: 'number', - required: true, - description: 'The id of the warehouse where the inventory happened', - }], + accepts: [ + { + arg: 'itemFk', + type: 'number', + required: true, + description: 'The item id', + }, + { + arg: 'quantity', + type: 'number', + required: true, + description: 'The visible quantity', + }, + { + arg: 'warehouseFk', + type: 'number', + required: true, + description: 'The id of the warehouse where the inventory happened', + } + ], returns: { type: 'boolean', root: true @@ -28,37 +32,44 @@ module.exports = Self => { } }); - Self.regularize = async(ctx, itemFk, quantity, warehouseFk) => { + Self.regularize = async(ctx, itemFk, quantity, warehouseFk, options) => { const models = Self.app.models; + const myOptions = {}; + let tx; - const itemDestination = await models.ClaimDestination.findOne({ - include: { - relation: 'address', - scope: { - fields: ['clientFk'] - } - }, - where: {description: 'Corregido'} - }); + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } - let tx = await Self.beginTransaction({}); try { - let options = {transaction: tx}; + const itemDestination = await models.ClaimDestination.findOne({ + include: { + relation: 'address', + scope: { + fields: ['clientFk'] + } + }, + where: {description: 'Corregido'} + }, myOptions); - let item = await models.Item.findById(itemFk); + const item = await models.Item.findById(itemFk, null, myOptions); - let ticketFk = await getTicketId({ + let ticketId = await getTicketId({ clientFk: itemDestination.address.clientFk, addressFk: itemDestination.addressFk, warehouseFk: warehouseFk - }, options); + }, myOptions); - if (!ticketFk) { - ticketFk = await createTicket(ctx, { + if (!ticketId) { + ticketId = await createTicket(ctx, { clientId: itemDestination.address().clientFk, warehouseId: warehouseFk, addressId: itemDestination.addressFk - }, options); + }, myOptions); } res = await models.Item.getVisibleAvailable(itemFk, warehouseFk); @@ -66,17 +77,18 @@ module.exports = Self => { let newQuantity = res.visible - quantity; await models.Sale.create({ - ticketFk: ticketFk, + ticketFk: ticketId, itemFk: itemFk, concept: item.name, quantity: newQuantity, discount: 100 - }, options); + }, myOptions); - await tx.commit(); - return ticketFk; + if (tx) await tx.commit(); + + return ticketId; } catch (e) { - await tx.rollback(); + if (tx) await tx.rollback(); throw e; } diff --git a/modules/item/back/methods/item/specs/clone.spec.js b/modules/item/back/methods/item/specs/clone.spec.js index 55142ee63..d376b9e5b 100644 --- a/modules/item/back/methods/item/specs/clone.spec.js +++ b/modules/item/back/methods/item/specs/clone.spec.js @@ -1,4 +1,4 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('item clone()', () => { let nextItemId; @@ -8,30 +8,47 @@ describe('item clone()', () => { LEFT JOIN vn.item i2 ON i1.id + 1 = i2.id WHERE i2.id IS NULL ORDER BY i1.id LIMIT 1`; - [nextAvailableId] = await app.models.Item.rawSql(query); + [nextAvailableId] = await models.Item.rawSql(query); nextItemId = nextAvailableId.id; }); it('should clone the given item and it should have the expected id', async() => { - let itemFk = 1; - let result = await app.models.Item.clone(itemFk); + const tx = await models.FixedPrice.beginTransaction({}); - expect(result.id).toEqual(nextItemId); - expect(result.image).toBeUndefined(); - expect(result.itemTag).toBeUndefined(); - expect(result.comment).toBeUndefined(); - expect(result.description).toBeUndefined(); + try { + const options = {transaction: tx}; + const itemFk = 1; + const result = await models.Item.clone(itemFk, options); + + expect(result.id).toEqual(nextItemId); + expect(result.image).toBeUndefined(); + expect(result.itemTag).toBeUndefined(); + expect(result.comment).toBeUndefined(); + expect(result.description).toBeUndefined(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should attempt to clone the given item but give an error as it doesnt exist', async() => { - let error; - let itemFk = 999; - await app.models.Item.clone(itemFk) - .catch(e => { - expect(e.message).toContain(`This item doesn't exists`); - error = e; - }); + const tx = await models.FixedPrice.beginTransaction({}); - expect(error).toBeDefined(); + let error; + + try { + const options = {transaction: tx}; + const itemFk = 999; + await models.Item.clone(itemFk, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error.message).toContain(`This item doesn't exists`); }); }); diff --git a/modules/item/back/methods/item/specs/createIntrastat.spec.js b/modules/item/back/methods/item/specs/createIntrastat.spec.js index fb10de858..60c85a810 100644 --- a/modules/item/back/methods/item/specs/createIntrastat.spec.js +++ b/modules/item/back/methods/item/specs/createIntrastat.spec.js @@ -1,22 +1,25 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('createIntrastat()', () => { - let newIntrastat; - - afterAll(async done => { - await app.models.Intrastat.destroyById(newIntrastat.id); - - done(); - }); - it('should create a new intrastat', async() => { - const intrastatId = 588420239; - const description = 'Tropical Flowers'; - const itemId = 9; - newIntrastat = await app.models.Item.createIntrastat(itemId, intrastatId, description); + const tx = await models.FixedPrice.beginTransaction({}); - expect(newIntrastat.description).toEqual(description); - expect(newIntrastat.taxClassFk).toEqual(1); - expect(newIntrastat.taxCodeFk).toEqual(21); + try { + const options = {transaction: tx}; + const intrastatId = 588420239; + const description = 'Tropical Flowers'; + const itemId = 9; + + const newIntrastat = await models.Item.createIntrastat(itemId, intrastatId, description, options); + + expect(newIntrastat.description).toEqual(description); + expect(newIntrastat.taxClassFk).toEqual(1); + expect(newIntrastat.taxCodeFk).toEqual(21); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/item/back/methods/item/specs/filter.spec.js b/modules/item/back/methods/item/specs/filter.spec.js index 340bc0db2..572aa0167 100644 --- a/modules/item/back/methods/item/specs/filter.spec.js +++ b/modules/item/back/methods/item/specs/filter.spec.js @@ -1,14 +1,14 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('item filter()', () => { it('should return 1 result filtering by id', async() => { - const tx = await app.models.Item.beginTransaction({}); + const tx = await models.Item.beginTransaction({}); const options = {transaction: tx}; try { const filter = {}; const ctx = {args: {filter: filter, search: 1}}; - const result = await app.models.Item.filter(ctx, filter, options); + const result = await models.Item.filter(ctx, filter, options); expect(result.length).toEqual(1); expect(result[0].id).toEqual(1); @@ -21,13 +21,13 @@ describe('item filter()', () => { }); it('should return 1 result filtering by barcode', async() => { - const tx = await app.models.Item.beginTransaction({}); + const tx = await models.Item.beginTransaction({}); const options = {transaction: tx}; try { const filter = {}; const ctx = {args: {filter: filter, search: 4444444444}}; - const result = await app.models.Item.filter(ctx, filter, options); + const result = await models.Item.filter(ctx, filter, options); expect(result.length).toEqual(1); expect(result[0].id).toEqual(2); @@ -40,7 +40,7 @@ describe('item filter()', () => { }); it('should return 2 results using filter and tags', async() => { - const tx = await app.models.Item.beginTransaction({}); + const tx = await models.Item.beginTransaction({}); const options = {transaction: tx}; try { @@ -50,7 +50,7 @@ describe('item filter()', () => { }; const tags = [{value: 'medical box', tagFk: 58}]; const ctx = {args: {filter: filter, typeFk: 5, tags: tags}}; - const result = await app.models.Item.filter(ctx, filter, options); + const result = await models.Item.filter(ctx, filter, options); expect(result.length).toEqual(2); diff --git a/modules/item/back/methods/item/specs/getBalance.spec.js b/modules/item/back/methods/item/specs/getBalance.spec.js index 601683471..5143a346f 100644 --- a/modules/item/back/methods/item/specs/getBalance.spec.js +++ b/modules/item/back/methods/item/specs/getBalance.spec.js @@ -1,33 +1,39 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); describe('item getBalance()', () => { it('should return the balance lines of a client type loses in which one has highlighted true', async() => { - const activeCtx = { - accessToken: {userId: 9}, - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - const losesClientId = 1111; - const ticket = await app.models.Ticket.findById(7); - const originalClientId = ticket.clientFk; - await ticket.updateAttribute('clientFk', losesClientId); + try { + const activeCtx = { + accessToken: {userId: 9}, + }; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx + }); + const losesClientId = 1111; + const ticket = await models.Ticket.findById(7, null, options); - const filter = { - where: { - itemFk: 1, - warehouseFk: 1 - } - }; - const results = await app.models.Item.getBalance(filter); + await ticket.updateAttribute('clientFk', losesClientId, options); - const result = results.find(element => element.clientType == 'loses'); + const filter = { + where: { + itemFk: 1, + warehouseFk: 1 + } + }; + const results = await models.Item.getBalance(filter, options); - expect(result.highlighted).toBe(true); + const result = results.find(element => element.clientType == 'loses'); - // restores - await ticket.updateAttribute('clientFk', originalClientId); + expect(result.highlighted).toBe(true); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/item/back/methods/item/specs/getCard.spec.js b/modules/item/back/methods/item/specs/getCard.spec.js new file mode 100644 index 000000000..b604a7c1a --- /dev/null +++ b/modules/item/back/methods/item/specs/getCard.spec.js @@ -0,0 +1,23 @@ +const models = require('vn-loopback/server/server').models; + +describe('item getCard()', () => { + it('should return the item', async() => { + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; + + try { + const itemId = 1; + + const result = await models.Item.getCard(itemId, options); + + expect(result.id).toEqual(itemId); + expect(result.itemType()).toEqual(jasmine.any(Object)); + expect(result.tags()).toEqual(jasmine.any(Array)); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); +}); diff --git a/modules/item/back/methods/item/specs/getDiary.spec.js b/modules/item/back/methods/item/specs/getDiary.spec.js deleted file mode 100644 index 2903fc426..000000000 --- a/modules/item/back/methods/item/specs/getDiary.spec.js +++ /dev/null @@ -1,12 +0,0 @@ -const app = require('vn-loopback/server/server'); - -describe('item getBalance()', () => { - it('should check the property balance of the 4 resultant entries', async() => { - let params = {where: {itemFk: 1, warehouseFk: 2}}; - let result = await app.models.Item.getBalance(params); - - expect(result.length).toBe(2); - expect(result[0].balance).toBe(-100); - expect(result[1].balance).toBe(-200); - }); -}); diff --git a/modules/item/back/methods/item/specs/getSummary.spec.js b/modules/item/back/methods/item/specs/getSummary.spec.js index 4a6d18e1b..a658b4289 100644 --- a/modules/item/back/methods/item/specs/getSummary.spec.js +++ b/modules/item/back/methods/item/specs/getSummary.spec.js @@ -1,16 +1,27 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('item getSummary()', () => { it('should return summary with item, tags, botanical, niches, available and visible defined ', async() => { - const ctx = {req: {accessToken: {userId: 1}}}; - let result = await app.models.Item.getSummary(ctx, 1); - let keys = Object.keys(result); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - expect(keys).toContain('item'); - expect(keys).toContain('tags'); - expect(keys).toContain('botanical'); - expect(keys).toContain('niches'); - expect(keys).toContain('available'); - expect(keys).toContain('visible'); + try { + const ctx = {req: {accessToken: {userId: 1}}}; + + const result = await models.Item.getSummary(ctx, 1, options); + const keys = Object.keys(result); + + expect(keys).toContain('item'); + expect(keys).toContain('tags'); + expect(keys).toContain('botanical'); + expect(keys).toContain('niches'); + expect(keys).toContain('available'); + expect(keys).toContain('visible'); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/item/back/methods/item/specs/getVisibleAvailable.spec.js b/modules/item/back/methods/item/specs/getVisibleAvailable.spec.js index 77e6cea8f..8e4864ee8 100644 --- a/modules/item/back/methods/item/specs/getVisibleAvailable.spec.js +++ b/modules/item/back/methods/item/specs/getVisibleAvailable.spec.js @@ -1,33 +1,46 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('item getVisibleAvailable()', () => { it('should check available visible for today', async() => { - const itemFk = 1; - const warehouseFk = 1; - const dated = new Date(); - let result = await app.models.Item.getVisibleAvailable(itemFk, warehouseFk, dated); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - expect(result.available).toEqual(187); - expect(result.visible).toEqual(92); - }); + try { + const itemFk = 1; + const warehouseFk = 1; + const dated = new Date(); - it('should check available visible for no dated', async() => { - const itemFk = 1; - const warehouseFk = 1; - let result = await app.models.Item.getVisibleAvailable(itemFk, warehouseFk); + const result = await models.Item.getVisibleAvailable(itemFk, warehouseFk, dated, options); - expect(result.available).toEqual(187); - expect(result.visible).toEqual(92); + expect(result.available).toEqual(187); + expect(result.visible).toEqual(92); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should check available visible for yesterday', async() => { - const itemFk = 1; - const warehouseFk = 1; - let dated = new Date(); - dated.setDate(dated.getDate() - 1); - let result = await app.models.Item.getVisibleAvailable(itemFk, warehouseFk, dated); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - expect(result.available).toEqual(0); - expect(result.visible).toEqual(92); + try { + const itemFk = 1; + const warehouseFk = 1; + const dated = new Date(); + dated.setDate(dated.getDate() - 1); + + const result = await models.Item.getVisibleAvailable(itemFk, warehouseFk, dated, options); + + expect(result.available).toEqual(0); + expect(result.visible).toEqual(92); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/item/back/methods/item/specs/getWasteByItem.spec.js b/modules/item/back/methods/item/specs/getWasteByItem.spec.js index dabad4fc6..68ba02887 100644 --- a/modules/item/back/methods/item/specs/getWasteByItem.spec.js +++ b/modules/item/back/methods/item/specs/getWasteByItem.spec.js @@ -1,14 +1,24 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Item getWasteByItem()', () => { it('should check for the waste breakdown by worker and item', async() => { - const result = await app.models.Item.getWasteByItem('CharlesXavier', 'Cymbidium'); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - const length = result.length; - const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; + try { + const result = await models.Item.getWasteByItem('CharlesXavier', 'Cymbidium', options); - expect(anyResult.buyer).toEqual('CharlesXavier'); - expect(anyResult.family).toEqual('Cymbidium'); - expect(anyResult.lines.length).toBeGreaterThanOrEqual(2); + const length = result.length; + const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; + + expect(anyResult.buyer).toEqual('CharlesXavier'); + expect(anyResult.family).toEqual('Cymbidium'); + expect(anyResult.lines.length).toBeGreaterThanOrEqual(2); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/item/back/methods/item/specs/getWasteByWorker.spec.js b/modules/item/back/methods/item/specs/getWasteByWorker.spec.js index 9ffe96bf7..c8b9d5e15 100644 --- a/modules/item/back/methods/item/specs/getWasteByWorker.spec.js +++ b/modules/item/back/methods/item/specs/getWasteByWorker.spec.js @@ -1,13 +1,23 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Item getWasteByWorker()', () => { it('should check for the waste breakdown for every worker', async() => { - const result = await app.models.Item.getWasteByWorker(); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - const length = result.length; - const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; + try { + const result = await models.Item.getWasteByWorker(options); - expect(anyResult.buyer).toMatch(/(CharlesXavier|HankPym|DavidCharlesHaller)/); - expect(anyResult.lines.length).toBeGreaterThanOrEqual(3); + const length = result.length; + const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; + + expect(anyResult.buyer).toMatch(/(CharlesXavier|HankPym|DavidCharlesHaller)/); + expect(anyResult.lines.length).toBeGreaterThanOrEqual(3); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/item/back/methods/item/specs/lastEntriesFilter.spec.js b/modules/item/back/methods/item/specs/lastEntriesFilter.spec.js index f64bfed8a..6c692848b 100644 --- a/modules/item/back/methods/item/specs/lastEntriesFilter.spec.js +++ b/modules/item/back/methods/item/specs/lastEntriesFilter.spec.js @@ -1,4 +1,4 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('item lastEntriesFilter()', () => { const minDate = new Date(value); @@ -7,18 +7,38 @@ describe('item lastEntriesFilter()', () => { maxHour.setHours(23, 59, 59, 59); it('should return one entry for a given item', async() => { - const filter = {where: {itemFk: 1, landed: {between: [minDate, maxDate]}}}; - const result = await app.models.Item.lastEntriesFilter(filter); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - expect(result.length).toEqual(1); + try { + const filter = {where: {itemFk: 1, landed: {between: [minDate, maxDate]}}}; + const result = await models.Item.lastEntriesFilter(filter, options); + + expect(result.length).toEqual(1); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return five entries for a given item', async() => { - minDate.setMonth(minDate.getMonth() - 2, 1); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - const filter = {where: {itemFk: 1, landed: {between: [minDate, maxDate]}}}; - const result = await app.models.Item.lastEntriesFilter(filter); + try { + minDate.setMonth(minDate.getMonth() - 2, 1); - expect(result.length).toEqual(5); + const filter = {where: {itemFk: 1, landed: {between: [minDate, maxDate]}}}; + const result = await models.Item.lastEntriesFilter(filter, options); + + expect(result.length).toEqual(5); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/item/back/methods/item/specs/new.spec.js b/modules/item/back/methods/item/specs/new.spec.js index da2d99bb6..049ad0ff2 100644 --- a/modules/item/back/methods/item/specs/new.spec.js +++ b/modules/item/back/methods/item/specs/new.spec.js @@ -1,45 +1,41 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('item new()', () => { - let item; - - afterAll(async done => { - try { - let sql = 'DELETE FROM vn.itemLog WHERE originFk = ?'; - await app.models.Item.rawSql(sql, [item.id]); - - sql = 'DELETE FROM vn.item WHERE id = ?'; - await app.models.Item.rawSql(sql, [item.id]); - } catch (error) { - console.error(error); - } - - done(); - }); - it('should create a new item, adding the name as a tag', async() => { - let itemParams = { - intrastatFk: 5080000, - originFk: 1, - provisionalName: 'planta', - typeFk: 2, - relevancy: 0 - }; - item = await app.models.Item.new(itemParams); - let temporalNameTag = await app.models.Tag.findOne({where: {name: 'Nombre temporal'}}); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - let temporalName = await app.models.ItemTag.findOne({ - where: { - itemFk: item.id, - tagFk: temporalNameTag.id, - } - }); - item = await app.models.Item.findById(item.id); + try { + const itemParams = { + intrastatFk: 5080000, + originFk: 1, + provisionalName: 'planta', + typeFk: 2, + relevancy: 0 + }; - expect(item.intrastatFk).toEqual(5080000); - expect(item.originFk).toEqual(1); - expect(item.typeFk).toEqual(2); - expect(item.name).toEqual('planta'); - expect(temporalName.value).toEqual('planta'); + let item = await models.Item.new(itemParams, options); + const temporalNameTag = await models.Tag.findOne({where: {name: 'Nombre temporal'}}, options); + + const temporalName = await models.ItemTag.findOne({ + where: { + itemFk: item.id, + tagFk: temporalNameTag.id, + } + }, options); + + item = await models.Item.findById(item.id, null, options); + + expect(item.intrastatFk).toEqual(5080000); + expect(item.originFk).toEqual(1); + expect(item.typeFk).toEqual(2); + expect(item.name).toEqual('planta'); + expect(temporalName.value).toEqual('planta'); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/item/back/methods/item/specs/regularize.spec.js b/modules/item/back/methods/item/specs/regularize.spec.js index d34dca25f..ea0cdfa5a 100644 --- a/modules/item/back/methods/item/specs/regularize.spec.js +++ b/modules/item/back/methods/item/specs/regularize.spec.js @@ -1,29 +1,32 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('regularize()', () => { - const itemFk = 1; - const warehouseFk = 1; - const trashAddress = 11; - let trashTicket; - - afterAll(async done => { - await app.models.Ticket.destroyById(trashTicket.id); - - done(); - }); - it('should create a new ticket and add a line', async() => { - let ctx = {req: {accessToken: {userId: 18}}}; - let res = await app.models.Item.getVisibleAvailable(itemFk, warehouseFk); - let visible = res.visible; - let saleQuantity = visible - 11; + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - let ticketFk = await app.models.Item.regularize(ctx, itemFk, 11, warehouseFk); - let sale = await app.models.Sale.findOne({where: {ticketFk: ticketFk}}); - trashTicket = await app.models.Ticket.findById(ticketFk); + try { + const ctx = {req: {accessToken: {userId: 18}}}; + const itemId = 1; + const warehouseId = 1; + const quantity = 11; + const date = undefined; - expect(sale.quantity).toEqual(saleQuantity); - expect(sale.discount).toEqual(100); - expect(trashTicket.addressFk).toEqual(trashAddress); + const res = await models.Item.getVisibleAvailable(itemId, warehouseId, date, options); + + const visible = res.visible; + const expectedQuantity = visible - quantity; + + const ticketId = await models.Item.regularize(ctx, itemId, quantity, warehouseId, options); + const sale = await models.Sale.findOne({where: {ticketFk: ticketId}}, options); + + expect(sale.quantity).toEqual(expectedQuantity); + expect(sale.discount).toEqual(100); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/item/back/methods/item/specs/updateTaxes.spec.js b/modules/item/back/methods/item/specs/updateTaxes.spec.js index 7ed6fa29a..66d2ce81c 100644 --- a/modules/item/back/methods/item/specs/updateTaxes.spec.js +++ b/modules/item/back/methods/item/specs/updateTaxes.spec.js @@ -1,34 +1,47 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('item updateTaxes()', () => { - let taxesInFixtures = [{id: 3, taxClassFk: 1}]; - it('should throw an error if the taxClassFk is blank', async() => { + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; + let error; - let taxes = [{id: 3, taxClassFk: undefined}]; - await app.models.Item.updateTaxes(taxes) - .catch(err => { - expect(err.message).toEqual('Tax class cannot be blank'); - error = err; - }); + try { + const taxes = [{id: 3, taxClassFk: undefined}]; - expect(error).toBeDefined(); + await models.Item.updateTaxes(taxes, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error.message).toEqual('Tax class cannot be blank'); }); it('should update the tax of a given country of an item', async() => { - let taxCountry = await app.models.ItemTaxCountry.findById(3); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - expect(taxCountry.taxClassFk).toEqual(1); + try { + let taxCountry = await models.ItemTaxCountry.findById(3, null, options); - let taxes = [{id: 3, taxClassFk: 2}]; + expect(taxCountry.taxClassFk).toEqual(1); - await app.models.Item.updateTaxes(taxes); - taxCountry = await app.models.ItemTaxCountry.findById(3); + const taxes = [{id: 3, taxClassFk: 2}]; - expect(taxCountry.taxClassFk).toEqual(2); + await models.Item.updateTaxes(taxes, options); - // restores - await app.models.Item.updateTaxes(taxesInFixtures); + taxCountry = await models.ItemTaxCountry.findById(3, null, options); + + expect(taxCountry.taxClassFk).toEqual(2); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/modules/item/back/methods/item/updateTaxes.js b/modules/item/back/methods/item/updateTaxes.js index 9b7ffd372..70a82757a 100644 --- a/modules/item/back/methods/item/updateTaxes.js +++ b/modules/item/back/methods/item/updateTaxes.js @@ -21,18 +21,38 @@ module.exports = Self => { } }); - Self.updateTaxes = async taxes => { - let promises = []; - for (let tax of taxes) { - if (!tax.taxClassFk) - throw new UserError('Tax class cannot be blank'); + Self.updateTaxes = async(taxes, options) => { + const myOptions = {}; + let tx; - promises.push(Self.app.models.ItemTaxCountry.update( - {id: tax.id}, - {taxClassFk: tax.taxClassFk} - )); + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + const promises = []; + + for (let tax of taxes) { + if (!tax.taxClassFk) + throw new UserError('Tax class cannot be blank'); + + promises.push(Self.app.models.ItemTaxCountry.update( + {id: tax.id}, + {taxClassFk: tax.taxClassFk} + ), myOptions); + } + await Promise.all(promises); + + if (tx) await tx.commit(); + + return true; + } catch (e) { + if (tx) await tx.rollback(); + throw e; } - await Promise.all(promises); - return true; }; }; diff --git a/modules/item/back/methods/tag/filterValue.js b/modules/item/back/methods/tag/filterValue.js index 84e44e554..062127a74 100644 --- a/modules/item/back/methods/tag/filterValue.js +++ b/modules/item/back/methods/tag/filterValue.js @@ -3,17 +3,20 @@ const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; module.exports = Self => { Self.remoteMethod('filterValue', { description: 'Returns a list of tag values', - accepts: [{ - arg: 'id', - type: 'Number', - required: true, - description: 'The tag id', - http: {source: 'path'} - }, { - arg: 'filter', - type: 'Object', - description: `Filter defining where, order, offset, and limit - must be a JSON-encoded string` - }], + accepts: [ + { + arg: 'id', + type: 'number', + required: true, + description: 'The tag id', + http: {source: 'path'} + }, + { + arg: 'filter', + type: 'object', + description: `Filter defining where, order, offset, and limit - must be a JSON-encoded string` + } + ], returns: { type: ['object'], root: true @@ -24,11 +27,16 @@ module.exports = Self => { } }); - Self.filterValue = async(id, filter) => { + Self.filterValue = async(id, filter, options) => { const conn = Self.dataSource.connector; - const tag = await Self.findById(id); + const myOptions = {}; + if (typeof options == 'object') + Object.assign(myOptions, options); + + const tag = await Self.findById(id); let stmt; + if (!tag.isFree && tag.sourceTable) { stmt = new ParameterizedSQL( `SELECT value FROM ( @@ -36,7 +44,7 @@ module.exports = Self => { } else stmt = new ParameterizedSQL(`SELECT value FROM itemTag`); - let where = filter.where; + const where = filter.where; if (where && where.value) { stmt.merge(conn.makeWhere({value: {like: `%${where.value}%`}})); stmt.merge(` @@ -46,6 +54,6 @@ module.exports = Self => { stmt.merge(conn.makeLimit(filter)); - return conn.executeStmt(stmt); + return conn.executeStmt(stmt, myOptions); }; }; diff --git a/modules/item/back/methods/tag/specs/filterValue.spec.js b/modules/item/back/methods/tag/specs/filterValue.spec.js index 8647c9fa2..9e5cf2da2 100644 --- a/modules/item/back/methods/tag/specs/filterValue.spec.js +++ b/modules/item/back/methods/tag/specs/filterValue.spec.js @@ -1,37 +1,76 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('tag filterValue()', () => { const colorTagId = 1; it('should return a list of color values', async() => { - const filter = {limit: 5}; - const result = await app.models.Tag.filterValue(colorTagId, filter); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - expect(result.length).toEqual(5); + try { + const filter = {limit: 5}; + const result = await models.Tag.filterValue(colorTagId, filter, options); + + expect(result.length).toEqual(5); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return the values matching color "Blue"', async() => { - const filter = {where: {value: 'Blue'}, limit: 5}; - const result = await app.models.Tag.filterValue(colorTagId, filter); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - expect(result.length).toEqual(2); - expect(result[0].value).toEqual('Blue'); - expect(result[1].value).toEqual('Blue/Silver'); + try { + const filter = {where: {value: 'Blue'}, limit: 5}; + const result = await models.Tag.filterValue(colorTagId, filter, options); + + expect(result.length).toEqual(2); + expect(result[0].value).toEqual('Blue'); + expect(result[1].value).toEqual('Blue/Silver'); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return the values matching color "Blue/Silver"', async() => { - const filter = {where: {value: 'Blue/Silver'}, limit: 5}; - const result = await app.models.Tag.filterValue(colorTagId, filter); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - expect(result.length).toEqual(1); - expect(result[0].value).toEqual('Blue/Silver'); + try { + const filter = {where: {value: 'Blue/Silver'}, limit: 5}; + const result = await models.Tag.filterValue(colorTagId, filter, options); + + expect(result.length).toEqual(1); + expect(result[0].value).toEqual('Blue/Silver'); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); it('should return the values matching color "Silver"', async() => { - const filter = {where: {value: 'Silver'}, limit: 5}; - const result = await app.models.Tag.filterValue(colorTagId, filter); + const tx = await models.Item.beginTransaction({}); + const options = {transaction: tx}; - expect(result.length).toEqual(2); - expect(result[0].value).toEqual('Silver'); - expect(result[1].value).toEqual('Blue/Silver'); + try { + const filter = {where: {value: 'Silver'}, limit: 5}; + const result = await models.Tag.filterValue(colorTagId, filter, options); + + expect(result.length).toEqual(2); + expect(result[0].value).toEqual('Silver'); + expect(result[1].value).toEqual('Blue/Silver'); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); From 98a691c1526f63460359abee5cac731c187b428a Mon Sep 17 00:00:00 2001 From: carlosjr Date: Mon, 12 Jul 2021 15:00:20 +0200 Subject: [PATCH 6/7] minor changes --- .../back/methods/client/createReceipt.js | 2 +- .../back/methods/client/updateAddress.js | 61 ++++++++----------- .../methods/fixed-price/upsertFixedPrice.js | 4 +- .../item/back/methods/item/createIntrastat.js | 59 +++++++----------- 4 files changed, 50 insertions(+), 76 deletions(-) diff --git a/modules/client/back/methods/client/createReceipt.js b/modules/client/back/methods/client/createReceipt.js index c93a86047..131a1d61f 100644 --- a/modules/client/back/methods/client/createReceipt.js +++ b/modules/client/back/methods/client/createReceipt.js @@ -65,7 +65,7 @@ module.exports = function(Self) { try { delete args.ctx; // Remove unwanted properties const newReceipt = await models.Receipt.create(args, myOptions); - const originalClient = await models.Client.findById(args.clientFk, myOptions); + const originalClient = await models.Client.findById(args.clientFk, null, myOptions); const bank = await models.Bank.findById(args.bankFk, null, myOptions); const accountingType = await models.AccountingType.findById(bank.accountingTypeFk, null, myOptions); diff --git a/modules/client/back/methods/client/updateAddress.js b/modules/client/back/methods/client/updateAddress.js index b8b5bbc0a..d1a498fe7 100644 --- a/modules/client/back/methods/client/updateAddress.js +++ b/modules/client/back/methods/client/updateAddress.js @@ -83,54 +83,41 @@ module.exports = function(Self) { Self.updateAddress = async(ctx, clientId, addressId, options) => { const models = Self.app.models; const args = ctx.args; - let tx; const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); - if (!myOptions.transaction) { - tx = await Self.beginTransaction({}); - myOptions.transaction = tx; - } + const address = await models.Address.findOne({ + where: { + id: addressId, + clientFk: clientId + } + }, myOptions); - try { - const address = await models.Address.findOne({ - where: { - id: addressId, - clientFk: clientId + const provinceId = args.provinceFk || address.provinceFk; + if (provinceId) { + const province = await models.Province.findById(provinceId, { + include: { + relation: 'country' } }, myOptions); - const provinceId = args.provinceFk || address.provinceFk; - if (provinceId) { - const province = await models.Province.findById(provinceId, { - include: { - relation: 'country' - } - }, myOptions); + const isUeeMember = province.country().isUeeMember; + const incotermsId = args.incotermsFk || address.incotermsFk; - const isUeeMember = province.country().isUeeMember; - const incotermsId = args.incotermsFk || address.incotermsFk; + if (!isUeeMember && !incotermsId) + throw new UserError(`Incoterms is required for a non UEE member`); - if (!isUeeMember && !incotermsId) - throw new UserError(`Incoterms is required for a non UEE member`); - - const customsAgentId = args.customsAgentFk || address.customsAgentFk; - if (!isUeeMember && !customsAgentId) - throw new UserError(`Customs agent is required for a non UEE member`); - } - - delete args.ctx; // Remove unwanted properties - - const updatedAddress = await address.updateAttributes(ctx.args, myOptions); - - if (tx) await tx.commit(); - - return updatedAddress; - } catch (e) { - if (tx) await tx.rollback(); - throw e; + const customsAgentId = args.customsAgentFk || address.customsAgentFk; + if (!isUeeMember && !customsAgentId) + throw new UserError(`Customs agent is required for a non UEE member`); } + + delete args.ctx; // Remove unwanted properties + + const updatedAddress = await address.updateAttributes(ctx.args, myOptions); + + return updatedAddress; }; }; diff --git a/modules/item/back/methods/fixed-price/upsertFixedPrice.js b/modules/item/back/methods/fixed-price/upsertFixedPrice.js index 46283d63a..ad35ec3a1 100644 --- a/modules/item/back/methods/fixed-price/upsertFixedPrice.js +++ b/modules/item/back/methods/fixed-price/upsertFixedPrice.js @@ -72,8 +72,8 @@ module.exports = Self => { try { delete args.ctx; // removed unwanted data - const fixedPrice = await models.FixedPrice.upsert(args, options); - const targetItem = await models.Item.findById(args.itemFk, null, options); + const fixedPrice = await models.FixedPrice.upsert(args, myOptions); + const targetItem = await models.Item.findById(args.itemFk, null, myOptions); await targetItem.updateAttributes({ minPrice: args.minPrice, diff --git a/modules/item/back/methods/item/createIntrastat.js b/modules/item/back/methods/item/createIntrastat.js index 3109dace3..d43d2e27f 100644 --- a/modules/item/back/methods/item/createIntrastat.js +++ b/modules/item/back/methods/item/createIntrastat.js @@ -34,49 +34,36 @@ module.exports = Self => { Self.createIntrastat = async(id, intrastatId, description, options) => { const models = Self.app.models; const myOptions = {}; - let tx; if (typeof options == 'object') Object.assign(myOptions, options); - if (!myOptions.transaction) { - tx = await Self.beginTransaction({}); - myOptions.transaction = tx; - } + const country = await models.Country.findOne({ + where: {code: 'ES'} + }, myOptions); - try { - const country = await models.Country.findOne({ - where: {code: 'ES'} - }, myOptions); + const itemTaxCountry = await models.ItemTaxCountry.findOne({ + where: { + itemFk: id, + countryFk: country.id + }, + order: 'effectived DESC' + }, myOptions); - const itemTaxCountry = await models.ItemTaxCountry.findOne({ - where: { - itemFk: id, - countryFk: country.id - }, - order: 'effectived DESC' - }, myOptions); + const taxClassCode = await models.TaxClassCode.findOne({ + where: { + taxClassFk: itemTaxCountry.taxClassFk + }, + order: 'effectived DESC' + }, myOptions); - const taxClassCode = await models.TaxClassCode.findOne({ - where: { - taxClassFk: itemTaxCountry.taxClassFk - }, - order: 'effectived DESC' - }, myOptions); + const intrastat = await models.Intrastat.create({ + id: intrastatId, + description: description, + taxClassFk: itemTaxCountry.taxClassFk, + taxCodeFk: taxClassCode.taxCodeFk + }, myOptions); - const intrastat = await models.Intrastat.create({ - id: intrastatId, - description: description, - taxClassFk: itemTaxCountry.taxClassFk, - taxCodeFk: taxClassCode.taxCodeFk - }, myOptions); - - if (tx) await tx.commit(); - - return intrastat; - } catch (e) { - if (tx) await tx.rollback(); - throw e; - } + return intrastat; }; }; From ea78db144159f2760f0752e99a9e5396b56169ba Mon Sep 17 00:00:00 2001 From: joan Date: Tue, 13 Jul 2021 08:59:36 +0200 Subject: [PATCH 7/7] 3012 - Hotfix: Get ticket list --- modules/invoiceOut/front/summary/index.html | 6 ++---- modules/invoiceOut/front/summary/index.js | 12 +++++++++++- modules/invoiceOut/front/summary/index.spec.js | 18 ++++++++++++++++-- 3 files changed, 29 insertions(+), 7 deletions(-) diff --git a/modules/invoiceOut/front/summary/index.html b/modules/invoiceOut/front/summary/index.html index 0dd9bfe0b..0406a39c5 100644 --- a/modules/invoiceOut/front/summary/index.html +++ b/modules/invoiceOut/front/summary/index.html @@ -1,9 +1,7 @@ + data="tickets">
@@ -56,7 +54,7 @@

Ticket

- + Ticket id diff --git a/modules/invoiceOut/front/summary/index.js b/modules/invoiceOut/front/summary/index.js index c0f8b4825..2446e986a 100644 --- a/modules/invoiceOut/front/summary/index.js +++ b/modules/invoiceOut/front/summary/index.js @@ -5,8 +5,10 @@ import './style.scss'; class Controller extends Summary { set invoiceOut(value) { this._invoiceOut = value; - if (value && value.id) + if (value && value.id) { this.getSummary(); + this.getTickets(); + } } get invoiceOut() { @@ -17,6 +19,14 @@ class Controller extends Summary { return this.$http.get(`InvoiceOuts/${this.invoiceOut.id}/summary`) .then(res => this.summary = res.data); } + + getTickets() { + this.$.$applyAsync(() => { + const query = `InvoiceOuts/${this.invoiceOut.id}/getTickets`; + this.$.ticketsModel.url = query; + this.$.ticketsModel.refresh(); + }); + } } ngModule.vnComponent('vnInvoiceOutSummary', { diff --git a/modules/invoiceOut/front/summary/index.spec.js b/modules/invoiceOut/front/summary/index.spec.js index fadf0ad89..be6ad0a18 100644 --- a/modules/invoiceOut/front/summary/index.spec.js +++ b/modules/invoiceOut/front/summary/index.spec.js @@ -1,4 +1,5 @@ import './index.js'; +import crudModel from 'core/mocks/crud-model'; describe('InvoiceOut', () => { describe('Component summary', () => { @@ -13,17 +14,30 @@ describe('InvoiceOut', () => { $scope = $rootScope.$new(); const $element = angular.element(''); controller = $componentController('vnInvoiceOutSummary', {$element, $scope}); - controller.invoiceOut = {id: 1}; + controller._invoiceOut = {id: 1}; + controller.$.ticketsModel = crudModel; })); describe('getSummary()', () => { it('should perform a query to set summary', () => { - $httpBackend.when('GET', `InvoiceOuts/1/summary`).respond(200, 'the data you are looking for'); + $httpBackend.expect('GET', `InvoiceOuts/1/summary`).respond(200, 'the data you are looking for'); controller.getSummary(); $httpBackend.flush(); expect(controller.summary).toEqual('the data you are looking for'); }); }); + + describe('getTickets()', () => { + it('should perform a and then call to the ticketModel refresh() method', () => { + jest.spyOn(controller.$.ticketsModel, 'refresh'); + + controller.getTickets(); + $scope.$apply(); + + expect(controller.$.ticketsModel.url).toEqual('InvoiceOuts/1/getTickets'); + expect(controller.$.ticketsModel.refresh).toHaveBeenCalledWith(); + }); + }); }); });