TX fixes, debug disabled, glob transaction timeout
gitea/salix/master This commit looks good Details

This commit is contained in:
Juan Ferrer 2019-06-12 17:31:45 +02:00
parent 3ff95fa45e
commit 58cc90929f
20 changed files with 216 additions and 170 deletions

View File

@ -33,5 +33,4 @@ COPY \
README.md \ README.md \
./ ./
ENV DEBUG=strong-remoting:shared-method
CMD ["pm2-docker", "./loopback/server/server.js"] CMD ["pm2-docker", "./loopback/server/server.js"]

View File

@ -112,7 +112,7 @@ module.exports = function(Self) {
for (let key1 in ctx.Model.relations) { for (let key1 in ctx.Model.relations) {
let val1 = ctx.Model.relations[key1]; let val1 = ctx.Model.relations[key1];
if (val1.keyFrom == key && key != 'id') { if (val1.keyFrom == key && key != 'id') {
let recordSet = await ctx.Model.app.models[val1.modelTo.modelName].findById(val, options); let recordSet = await ctx.Model.app.models[val1.modelTo.modelName].findById(val, null, options);
let showField = val1.modelTo && val1.modelTo.definition.settings.log && val1.modelTo.definition.settings.log.showField && recordSet && recordSet[val1.modelTo.definition.settings.log.showField]; let showField = val1.modelTo && val1.modelTo.definition.settings.log && val1.modelTo.definition.settings.log.showField && recordSet && recordSet[val1.modelTo.definition.settings.log.showField];
if (!showField) { if (!showField) {

View File

@ -11,6 +11,20 @@ module.exports = function(Self) {
setup() { setup() {
Self.super_.setup.call(this); Self.super_.setup.call(this);
/**
* Setting a global transaction timeout to find out if the service
* is blocked because the connection pool is empty.
*/
this.once('dataSourceAttached', () => {
let orgBeginTransaction = this.beginTransaction;
this.beginTransaction = function(options, cb) {
options = options || {};
if (!options.timeout)
options.timeout = 30000;
return orgBeginTransaction.call(this, options, cb);
};
});
// Register field ACL validation // Register field ACL validation
/* this.beforeRemote('prototype.patchAttributes', ctx => this.checkUpdateAcls(ctx)); /* this.beforeRemote('prototype.patchAttributes', ctx => this.checkUpdateAcls(ctx));
this.beforeRemote('updateAll', ctx => this.checkUpdateAcls(ctx)); this.beforeRemote('updateAll', ctx => this.checkUpdateAcls(ctx));
@ -41,10 +55,11 @@ module.exports = function(Self) {
}, },
async crud(deletes, updates, creates) { async crud(deletes, updates, creates) {
let transaction = await this.beginTransaction({}); let tx = await this.beginTransaction({});
let options = {transaction};
try { try {
let options = {transaction: tx};
if (deletes) { if (deletes) {
let promises = []; let promises = [];
for (let id of deletes) for (let id of deletes)
@ -65,9 +80,9 @@ module.exports = function(Self) {
} }
} }
await transaction.commit(); await tx.commit();
} catch (error) { } catch (error) {
await transaction.rollback(); await tx.rollback();
throw error; throw error;
} }
}, },

View File

@ -21,39 +21,40 @@ module.exports = Self => {
Self.clone = async id => { Self.clone = async id => {
const models = Self.app.models; const models = Self.app.models;
const transaction = await Self.beginTransaction({}); const tx = await Self.beginTransaction({});
const options = {transaction};
// Find original zone
const zone = await models.Zone.findOne({
fields: [
'name',
'hour',
'warehouseFk',
'agencyModeFk',
'travelingDays',
'price',
'bonus',
'isVolumetric'],
where: {id}
}, options);
const hour = zone.hour;
const offset = hour.getTimezoneOffset() * 60000;
hour.setTime(hour.getTime() + offset);
// Find all original included geolocations
const includedGeo = await models.ZoneIncluded.find({
fields: ['geoFk', 'isIncluded'],
where: {zoneFk: id}
}, options);
// Find all original selected days
const calendarDays = await models.ZoneCalendar.find({
where: {zoneFk: id}
}, options);
try { try {
let options = {transaction: tx};
// Find original zone
const zone = await models.Zone.findOne({
fields: [
'name',
'hour',
'warehouseFk',
'agencyModeFk',
'travelingDays',
'price',
'bonus',
'isVolumetric'],
where: {id}
}, options);
const hour = zone.hour;
const offset = hour.getTimezoneOffset() * 60000;
hour.setTime(hour.getTime() + offset);
// Find all original included geolocations
const includedGeo = await models.ZoneIncluded.find({
fields: ['geoFk', 'isIncluded'],
where: {zoneFk: id}
}, options);
// Find all original selected days
const calendarDays = await models.ZoneCalendar.find({
where: {zoneFk: id}
}, options);
const newZone = await Self.create(zone, options); const newZone = await Self.create(zone, options);
const newIncludedGeo = includedGeo.map(included => { const newIncludedGeo = includedGeo.map(included => {
included.zoneFk = newZone.id; included.zoneFk = newZone.id;
@ -66,11 +67,11 @@ module.exports = Self => {
await models.ZoneIncluded.create(newIncludedGeo, options); await models.ZoneIncluded.create(newIncludedGeo, options);
await models.ZoneCalendar.create(newCalendayDays, options); await models.ZoneCalendar.create(newCalendayDays, options);
await transaction.commit(); await tx.commit();
return newZone; return newZone;
} catch (e) { } catch (e) {
await transaction.rollback(); await tx.rollback();
throw e; throw e;
} }
}; };

View File

@ -19,7 +19,7 @@ module.exports = Self => {
} }
}); });
async function addSalesToTicket(salesToRefund, ticketFk, transaction) { async function addSalesToTicket(salesToRefund, ticketFk, options) {
let formatedSales = []; let formatedSales = [];
salesToRefund.forEach(sale => { salesToRefund.forEach(sale => {
let formatedSale = { let formatedSale = {
@ -35,10 +35,10 @@ module.exports = Self => {
}; };
formatedSales.push(formatedSale); formatedSales.push(formatedSale);
}); });
return await Self.app.models.Sale.create(formatedSales, transaction); return await Self.app.models.Sale.create(formatedSales, options);
} }
async function insertIntoClaimEnd(createdSales, claimId, workerId, transaction) { async function insertIntoClaimEnd(createdSales, claimId, workerId, options) {
let formatedSales = []; let formatedSales = [];
createdSales.forEach(sale => { createdSales.forEach(sale => {
let formatedSale = { let formatedSale = {
@ -48,17 +48,17 @@ module.exports = Self => {
}; };
formatedSales.push(formatedSale); formatedSales.push(formatedSale);
}); });
return await Self.app.models.ClaimEnd.create(formatedSales, transaction); return await Self.app.models.ClaimEnd.create(formatedSales, options);
} }
async function saveObservation(observation, transaction) { async function saveObservation(observation, options) {
let query = `INSERT INTO vn.ticketObservation(ticketFk, observationTypeFk, description) VALUES(?, ?, ?) let query = `INSERT INTO vn.ticketObservation(ticketFk, observationTypeFk, description) VALUES(?, ?, ?)
ON DUPLICATE KEY UPDATE description = CONCAT(vn.ticketObservation.description, VALUES(description),' ')`; ON DUPLICATE KEY UPDATE description = CONCAT(vn.ticketObservation.description, VALUES(description),' ')`;
await Self.rawSql(query, [ await Self.rawSql(query, [
observation.ticketFk, observation.ticketFk,
observation.observationTypeFk, observation.observationTypeFk,
observation.description observation.description
], transaction); ], options);
} }
Self.importToNewRefundTicket = async(ctx, id) => { Self.importToNewRefundTicket = async(ctx, id) => {
@ -109,37 +109,39 @@ module.exports = Self => {
] ]
}; };
let transaction = await Self.beginTransaction({}); let tx = await Self.beginTransaction({});
try { try {
let newRefundTicket = await models.Ticket.new(ctx, params, {transaction: transaction}); let options = {transaction: tx};
let newRefundTicket = await models.Ticket.new(ctx, params, options);
let observation = { let observation = {
description: `Reclama ticket: ${claim.ticketFk}`, description: `Reclama ticket: ${claim.ticketFk}`,
ticketFk: newRefundTicket.id, ticketFk: newRefundTicket.id,
observationTypeFk: obsevationType.id observationTypeFk: obsevationType.id
}; };
await saveObservation(observation, {transaction: transaction}); await saveObservation(observation, options);
await models.TicketTracking.create({ await models.TicketTracking.create({
ticketFk: newRefundTicket.id, ticketFk: newRefundTicket.id,
stateFk: state.id, stateFk: state.id,
workerFk: worker.id workerFk: worker.id
}, {transaction: transaction}); }, options);
let salesToRefund = await models.ClaimBeginning.find(salesFilter); let salesToRefund = await models.ClaimBeginning.find(salesFilter);
let createdSales = await addSalesToTicket(salesToRefund, newRefundTicket.id, {transaction: transaction}); let createdSales = await addSalesToTicket(salesToRefund, newRefundTicket.id, options);
insertIntoClaimEnd(createdSales, id, worker.id, {transaction: transaction}); insertIntoClaimEnd(createdSales, id, worker.id, options);
await Self.rawSql('CALL vn.ticketCalculateClon(?, ?)', [ await Self.rawSql('CALL vn.ticketCalculateClon(?, ?)', [
newRefundTicket.id, claim.ticketFk newRefundTicket.id, claim.ticketFk
], {transaction: transaction}); ], options);
await transaction.commit(); await tx.commit();
return newRefundTicket; return newRefundTicket;
} catch (e) { } catch (e) {
await transaction.rollback(); await tx.rollback();
throw e; throw e;
} }
}; };

View File

@ -26,27 +26,29 @@ module.exports = Self => {
Self.createFromSales = async(ctx, params) => { Self.createFromSales = async(ctx, params) => {
let model = Self.app.models; let model = Self.app.models;
let transaction = await Self.beginTransaction({}); let tx = await Self.beginTransaction({});
try { try {
let options = {transaction: tx};
let userId = ctx.req.accessToken.userId; let userId = ctx.req.accessToken.userId;
let worker = await Self.app.models.Worker.findOne({where: {userFk: userId}}); let worker = await Self.app.models.Worker.findOne({where: {userFk: userId}});
params.claim.workerFk = worker.id; params.claim.workerFk = worker.id;
let newClaim = await Self.create(params.claim, {transaction}); let newClaim = await Self.create(params.claim, options);
let promises = []; let promises = [];
for (let i = 0; i < params.sales.length; i++) { for (let i = 0; i < params.sales.length; i++) {
promises.push(model.ClaimBeginning.create( promises.push(model.ClaimBeginning.create({
{saleFk: params.sales[i].id, saleFk: params.sales[i].id,
claimFk: newClaim.id, claimFk: newClaim.id,
quantity: params.sales[i].quantity}, quantity: params.sales[i].quantity
{transaction})); }, options));
} }
await Promise.all(promises); await Promise.all(promises);
await transaction.commit(); await tx.commit();
return newClaim; return newClaim;
} catch (e) { } catch (e) {
transaction.rollback(); await tx.rollback();
throw e; throw e;
} }
}; };

View File

@ -30,8 +30,10 @@ module.exports = Self => {
where: {claimFk: params.claimFk} where: {claimFk: params.claimFk}
}); });
let transaction = await Self.beginTransaction({}); let tx = await Self.beginTransaction({});
try { try {
let options = {transaction: tx};
for (let i = 0; i < claimEnds.length; i++) { for (let i = 0; i < claimEnds.length; i++) {
const claimEnd = claimEnds[i]; const claimEnd = claimEnds[i];
const destination = claimEnd.claimDestination(); const destination = claimEnd.claimDestination();
@ -45,7 +47,7 @@ module.exports = Self => {
addressFk: addressFk, addressFk: addressFk,
companyFk: sale.ticket().companyFk, companyFk: sale.ticket().companyFk,
warehouseFk: sale.ticket().warehouseFk warehouseFk: sale.ticket().warehouseFk
}, transaction); }, options);
let address = await models.Address.findOne({ let address = await models.Address.findOne({
where: {id: addressFk} where: {id: addressFk}
@ -58,7 +60,7 @@ module.exports = Self => {
warehouseFk: sale.ticket().warehouseFk, warehouseFk: sale.ticket().warehouseFk,
companyFk: sale.ticket().companyFk, companyFk: sale.ticket().companyFk,
userId: userId userId: userId
}, transaction); }, options);
} }
await models.Sale.create({ await models.Sale.create({
@ -68,7 +70,7 @@ module.exports = Self => {
quantity: -sale.quantity, quantity: -sale.quantity,
price: sale.price, price: sale.price,
discount: 100 discount: 100
}, {transaction: transaction}); }, options);
if (sale.ticket().client().salesPerson()) { if (sale.ticket().client().salesPerson()) {
await sendMessage(ctx, { await sendMessage(ctx, {
@ -78,20 +80,20 @@ module.exports = Self => {
quantity: sale.quantity, quantity: sale.quantity,
concept: sale.concept, concept: sale.concept,
nickname: address.nickname nickname: address.nickname
}, transaction); }, options);
} }
} }
let claim = await Self.findById(params.claimFk); let claim = await Self.findById(params.claimFk);
claim = await claim.updateAttributes({ claim = await claim.updateAttributes({
claimStateFk: resolvedState claimStateFk: resolvedState
}, {transaction: transaction}); }, options);
await transaction.commit(); await tx.commit();
return claim; return claim;
} catch (e) { } catch (e) {
await transaction.rollback(); await tx.rollback();
throw e; throw e;
} }
}; };
@ -117,7 +119,7 @@ module.exports = Self => {
}); });
} }
async function getTicketId(params, transaction) { async function getTicketId(params, options) {
const currentDate = new Date(); const currentDate = new Date();
currentDate.setHours(null, null, null); currentDate.setHours(null, null, null);
@ -129,12 +131,12 @@ module.exports = Self => {
shipped: currentDate, shipped: currentDate,
landed: currentDate landed: currentDate
} }
}, {transaction: transaction}); }, options);
return ticket && ticket.id; return ticket && ticket.id;
} }
async function createTicket(ctx, params, transaction) { async function createTicket(ctx, params, options) {
let ticket = await Self.app.models.Ticket.new(ctx, let ticket = await Self.app.models.Ticket.new(ctx,
{ {
shipped: new Date(), shipped: new Date(),
@ -144,18 +146,18 @@ module.exports = Self => {
companyFk: params.companyFk, companyFk: params.companyFk,
addressFk: params.addressFk, addressFk: params.addressFk,
userId: params.userId userId: params.userId
}, {transaction: transaction}); }, options);
return ticket.id; return ticket.id;
} }
async function sendMessage(ctx, params, transaction) { async function sendMessage(ctx, params, options) {
const message = `Envio ${params.quantity} unidades de "${params.concept}" (#${params.itemFk}) a ` const message = `Envio ${params.quantity} unidades de "${params.concept}" (#${params.itemFk}) a `
+ `"${params.nickname}" provenientes del ticket #${params.ticketFk}`; + `"${params.nickname}" provenientes del ticket #${params.ticketFk}`;
await Self.app.models.Message.send(ctx, { await Self.app.models.Message.send(ctx, {
recipientFk: params.recipientFk, recipientFk: params.recipientFk,
message: message message: message
}, {transaction: transaction}); }, options);
} }
}; };

View File

@ -19,23 +19,25 @@ module.exports = function(Self) {
Self.createDefaultAddress = async data => { Self.createDefaultAddress = async data => {
const Address = Self.app.models.Address; const Address = Self.app.models.Address;
const Client = Self.app.models.Client; const Client = Self.app.models.Client;
const transaction = await Address.beginTransaction({}); const tx = await Address.beginTransaction({});
try { try {
let options = {transaction: tx};
let address = data.address; let address = data.address;
let newAddress = await Address.create(address, {transaction}); let newAddress = await Address.create(address, options);
let client = await Client.findById(address.clientFk, {transaction}); let client = await Client.findById(address.clientFk, options);
if (data.isDefaultAddress) { if (data.isDefaultAddress) {
await client.updateAttributes({ await client.updateAttributes({
defaultAddressFk: newAddress.id defaultAddressFk: newAddress.id
}, {transaction}); }, options);
} }
await transaction.commit(); await tx.commit();
return newAddress; return newAddress;
} catch (e) { } catch (e) {
await transaction.rollback(); await tx.rollback();
throw e; throw e;
} }
}; };

View File

@ -19,15 +19,17 @@ module.exports = Self => {
}); });
Self.confirmTransaction = async(ctx, id) => { Self.confirmTransaction = async(ctx, id) => {
let transaction = await Self.beginTransaction({});
let userId = ctx.req.accessToken.userId; let userId = ctx.req.accessToken.userId;
let tx = await Self.beginTransaction({});
try { try {
let oldTpvTransaction = await Self.app.models.TpvTransaction.findById(id, {options: transaction}); let options = {transaction: tx};
let confirm = await Self.rawSql('CALL hedera.tpvTransactionConfirmById(?)', [id], {options: transaction}); let oldTpvTransaction = await Self.app.models.TpvTransaction.findById(id, null, options);
let tpvTransaction = await Self.app.models.TpvTransaction.findById(id, {options: transaction}); let confirm = await Self.rawSql('CALL hedera.tpvTransactionConfirmById(?)', [id], options);
let tpvTransaction = await Self.app.models.TpvTransaction.findById(id, null, options);
let oldInstance = {status: oldTpvTransaction.status}; let oldInstance = {status: oldTpvTransaction.status};
let newInstance = {status: tpvTransaction.status}; let newInstance = {status: tpvTransaction.status};
@ -42,12 +44,12 @@ module.exports = Self => {
newInstance: newInstance newInstance: newInstance
}; };
await Self.app.models.ClientLog.create(logRecord, {options: transaction}); await Self.app.models.ClientLog.create(logRecord, options);
await transaction.commit(); await tx.commit();
return confirm; return confirm;
} catch (e) { } catch (e) {
await transaction.rollback(); await tx.rollback();
throw e; throw e;
} }
}; };

View File

@ -25,10 +25,12 @@ module.exports = function(Self) {
}; };
const Account = Self.app.models.Account; const Account = Self.app.models.Account;
const Address = Self.app.models.Address; const Address = Self.app.models.Address;
const transaction = await Account.beginTransaction({}); const tx = await Account.beginTransaction({});
try { try {
let account = await Account.create(user, {transaction}); let options = {transaction: tx};
let account = await Account.create(user, options);
let client = await Self.create({ let client = await Self.create({
id: account.id, id: account.id,
name: data.name, name: data.name,
@ -42,7 +44,7 @@ module.exports = function(Self) {
provinceFk: data.provinceFk, provinceFk: data.provinceFk,
countryFk: data.countryFk, countryFk: data.countryFk,
isEqualizated: data.isEqualizated isEqualizated: data.isEqualizated
}, {transaction}); }, options);
let address = await Address.create({ let address = await Address.create({
@ -54,16 +56,16 @@ module.exports = function(Self) {
provinceFk: client.provinceFk, provinceFk: client.provinceFk,
isEqualizated: client.isEqualizated, isEqualizated: client.isEqualizated,
isActive: true isActive: true
}, {transaction}); }, options);
await client.updateAttributes({ await client.updateAttributes({
defaultAddressFk: address.id defaultAddressFk: address.id
}, {transaction}); }, options);
await transaction.commit(); await tx.commit();
return client; return client;
} catch (e) { } catch (e) {
await transaction.rollback(); await tx.rollback();
throw e; throw e;
} }
}; };

View File

@ -22,12 +22,14 @@ module.exports = Self => {
} }
}); });
Self.createWithInsurance = async (data, ctx) => { Self.createWithInsurance = async(data, ctx) => {
let transaction = await Self.beginTransaction({}); let tx = await Self.beginTransaction({});
try { try {
let options = {transaction: tx};
let classificationSchema = {client: data.clientFk, started: data.started}; let classificationSchema = {client: data.clientFk, started: data.started};
let newClassification = await Self.create(classificationSchema, {transaction}); let newClassification = await Self.create(classificationSchema, options);
let CreditInsurance = Self.app.models.CreditInsurance; let CreditInsurance = Self.app.models.CreditInsurance;
let insuranceSchema = { let insuranceSchema = {
creditClassification: newClassification.id, creditClassification: newClassification.id,
@ -35,13 +37,13 @@ module.exports = Self => {
grade: data.grade grade: data.grade
}; };
let newCreditInsurance = await CreditInsurance.create(insuranceSchema, {transaction}); let newCreditInsurance = await CreditInsurance.create(insuranceSchema, options);
await transaction.commit(); await tx.commit();
await CreditInsurance.messageSend(newCreditInsurance, ctx.req.accessToken); await CreditInsurance.messageSend(newCreditInsurance, ctx.req.accessToken);
return newClassification; return newClassification;
} catch (e) { } catch (e) {
transaction.rollback(); await tx.rollback();
throw e; throw e;
} }
}; };

View File

@ -21,24 +21,24 @@ module.exports = Self => {
}); });
Self.delete = async id => { Self.delete = async id => {
const transaction = await Self.beginTransaction({}); const tx = await Self.beginTransaction({});
try { try {
let options = {transaction: tx};
let invoiceOut = await Self.findById(id); let invoiceOut = await Self.findById(id);
let tickets = await Self.app.models.Ticket.find({where: {refFk: invoiceOut.ref}}); let tickets = await Self.app.models.Ticket.find({where: {refFk: invoiceOut.ref}});
const promises = []; const promises = [];
tickets.forEach(ticket => { tickets.forEach(ticket => {
promises.push(ticket.updateAttribute('refFk', null, {transaction})); promises.push(ticket.updateAttribute('refFk', null, options));
}); });
return Promise.all(promises).then(async() => { await Promise.all(promises);
await invoiceOut.destroy({transaction}); await invoiceOut.destroy(options);
await transaction.commit(); await tx.commit();
return tickets;
return tickets;
});
} catch (e) { } catch (e) {
await transaction.rollback(); await tx.rollback();
throw e; throw e;
} }
}; };

View File

@ -24,11 +24,13 @@ module.exports = Self => {
const models = Self.app.models; const models = Self.app.models;
const invoiceReportFk = 30; // FIXME - Should be deprecated const invoiceReportFk = 30; // FIXME - Should be deprecated
const worker = await models.Worker.findOne({where: {userFk: userId}}); const worker = await models.Worker.findOne({where: {userFk: userId}});
const transaction = await Self.beginTransaction({}); const tx = await Self.beginTransaction({});
try { try {
let options = {transaction: tx};
// Remove all invoice references from tickets // Remove all invoice references from tickets
const invoiceOut = await models.InvoiceOut.findById(id, {transaction}); const invoiceOut = await models.InvoiceOut.findById(id, null, options);
await invoiceOut.updateAttributes({ await invoiceOut.updateAttributes({
hasPdf: false hasPdf: false
}); });
@ -36,13 +38,13 @@ module.exports = Self => {
// Send to print queue // Send to print queue
await Self.rawSql(` await Self.rawSql(`
INSERT INTO vn.printServerQueue (reportFk, param1, workerFk) INSERT INTO vn.printServerQueue (reportFk, param1, workerFk)
VALUES (?, ?, ?)`, [invoiceReportFk, id, worker.id], {transaction}); VALUES (?, ?, ?)`, [invoiceReportFk, id, worker.id], options);
await transaction.commit(); await tx.commit();
return invoiceOut; return invoiceOut;
} catch (e) { } catch (e) {
await transaction.rollback(); await tx.rollback();
throw e; throw e;
} }
}; };

View File

@ -23,11 +23,12 @@ module.exports = Self => {
}); });
Self.clone = async itemId => { Self.clone = async itemId => {
let transaction = await Self.beginTransaction({}); let tx = await Self.beginTransaction({});
let options = {transaction};
try { try {
const origin = await Self.findById(itemId, options); let options = {transaction: tx};
const origin = await Self.findById(itemId, null, options);
if (!origin) if (!origin)
throw new UserError(`That item doesn't exists`); throw new UserError(`That item doesn't exists`);
@ -46,11 +47,10 @@ module.exports = Self => {
await cloneTags(origin.id, newItem.id, promises, options); await cloneTags(origin.id, newItem.id, promises, options);
await Promise.all(promises); await Promise.all(promises);
await transaction.commit(); await tx.commit();
return newItem; return newItem;
} catch (e) { } catch (e) {
await transaction.rollback(); await tx.rollback();
throw e; throw e;
} }
}; };

View File

@ -33,16 +33,18 @@ module.exports = Self => {
throw new UserError(`You don't have enough privileges to do that`); throw new UserError(`You don't have enough privileges to do that`);
} }
let transaction = await Self.beginTransaction({}); let tx = await Self.beginTransaction({});
try { try {
let options = {transaction: tx};
let provisionalName = params.provisionalName; let provisionalName = params.provisionalName;
delete params.provisionalName; delete params.provisionalName;
let item = await Self.app.models.Item.create(params, {transaction: transaction}); let item = await Self.app.models.Item.create(params, options);
let typeTags = await Self.app.models.ItemTypeTag.find({where: {itemTypeFk: item.typeFk}}); let typeTags = await Self.app.models.ItemTypeTag.find({where: {itemTypeFk: item.typeFk}});
let query = `SET @isTriggerDisabled = TRUE`; let query = `SET @isTriggerDisabled = TRUE`;
await Self.rawSql(query, null, {transaction: transaction}); await Self.rawSql(query, null, options);
let nameTag = await Self.app.models.Tag.findOne({where: {name: 'Nombre temporal'}}); let nameTag = await Self.app.models.Tag.findOne({where: {name: 'Nombre temporal'}});
@ -53,18 +55,18 @@ module.exports = Self => {
newTags.push({itemFk: item.id, tagFk: typeTag.tagFk, value: '', priority: typeTag.priority}); newTags.push({itemFk: item.id, tagFk: typeTag.tagFk, value: '', priority: typeTag.priority});
}); });
await Self.app.models.ItemTag.create(newTags, {transaction: transaction}); await Self.app.models.ItemTag.create(newTags, options);
query = `SET @isTriggerDisabled = FALSE`; query = `SET @isTriggerDisabled = FALSE`;
await Self.rawSql(query, null, {transaction: transaction}); await Self.rawSql(query, null, options);
query = `CALL vn.itemRefreshTags(?)`; query = `CALL vn.itemRefreshTags(?)`;
await Self.rawSql(query, [item.id], {transaction: transaction}); await Self.rawSql(query, [item.id], options);
await transaction.commit(); await tx.commit();
return item; return item;
} catch (e) { } catch (e) {
await transaction.rollback(); await tx.rollback();
throw e; throw e;
} }
}; };

View File

@ -42,15 +42,17 @@ module.exports = Self => {
where: {description: 'Corregido'} where: {description: 'Corregido'}
}); });
let transaction = await Self.beginTransaction({}); let tx = await Self.beginTransaction({});
try { try {
let options = {transaction: tx};
let item = await models.Item.findById(itemFk); let item = await models.Item.findById(itemFk);
let ticketFk = await getTicketId({ let ticketFk = await getTicketId({
clientFk: itemDestination.address.clientFk, clientFk: itemDestination.address.clientFk,
addressFk: itemDestination.addressFk, addressFk: itemDestination.addressFk,
warehouseFk: warehouseFk warehouseFk: warehouseFk
}, transaction); }, options);
if (!ticketFk) { if (!ticketFk) {
ticketFk = await createTicket(ctx, { ticketFk = await createTicket(ctx, {
@ -58,15 +60,15 @@ module.exports = Self => {
addressFk: itemDestination.addressFk, addressFk: itemDestination.addressFk,
warehouseFk: warehouseFk, warehouseFk: warehouseFk,
userId: userId userId: userId
}, transaction); }, options);
} }
let query = ` let query = `
CALL vn.getItemVisibleAvailable(?,curdate(),?,?)`; CALL vn.getItemVisibleAvailable(?,curdate(),?,?)`;
let options = [itemFk, warehouseFk, true]; let params = [itemFk, warehouseFk, true];
let [res] = await Self.rawSql(query, options, {transaction: transaction}); let [res] = await Self.rawSql(query, params, options);
let newQuantity = res[0].visible - quantity; let newQuantity = res[0].visible - quantity;
@ -76,16 +78,16 @@ module.exports = Self => {
concept: item.name, concept: item.name,
quantity: newQuantity, quantity: newQuantity,
discount: 100 discount: 100
}, {transaction: transaction}); }, options);
await transaction.commit(); await tx.commit();
return ticketFk; return ticketFk;
} catch (e) { } catch (e) {
await transaction.rollback(); await tx.rollback();
throw e; throw e;
} }
async function createTicket(ctx, params, transaction) { async function createTicket(ctx, params, options) {
let ticket = await Self.app.models.Ticket.new( let ticket = await Self.app.models.Ticket.new(
ctx, ctx,
{ {
@ -96,13 +98,13 @@ module.exports = Self => {
companyFk: params.companyFk, companyFk: params.companyFk,
addressFk: params.addressFk, addressFk: params.addressFk,
userId: params.userId userId: params.userId
}, {transaction: transaction}); }, options);
return ticket.id; return ticket.id;
} }
async function getTicketId(params, transaction) { async function getTicketId(params, options) {
const currentDate = new Date(); const currentDate = new Date();
currentDate.setHours(null, null, null); currentDate.setHours(null, null, null);
@ -113,7 +115,7 @@ module.exports = Self => {
shipped: currentDate, shipped: currentDate,
landed: currentDate landed: currentDate
} }
}, {transaction: transaction}); }, options);
return ticket && ticket.id; return ticket && ticket.id;
} }

View File

@ -51,9 +51,11 @@ module.exports = Self => {
userId: userId userId: userId
}; };
let transaction = await Self.beginTransaction({}); let tx = await Self.beginTransaction({});
try { try {
let newTicket = await model.Ticket.new(ctx, newTicketParams, {transaction: transaction}); let options = {transaction: tx};
let newTicket = await model.Ticket.new(ctx, newTicketParams, options);
let selectedSalesId = []; let selectedSalesId = [];
params.sales.forEach(sale => { params.sales.forEach(sale => {
@ -63,13 +65,13 @@ module.exports = Self => {
await model.Sale.updateAll( await model.Sale.updateAll(
{id: {inq: selectedSalesId}}, {id: {inq: selectedSalesId}},
{ticketFk: newTicket.id}, {ticketFk: newTicket.id},
{transaction}); options
);
await transaction.commit();
await tx.commit();
return newTicket; return newTicket;
} catch (e) { } catch (e) {
await transaction.rollback(); await tx.rollback();
throw e; throw e;
} }
}; };

View File

@ -32,10 +32,11 @@ module.exports = Self => {
Self.confirm = async ctx => { Self.confirm = async ctx => {
const models = Self.app.models; const models = Self.app.models;
let transaction = await Self.beginTransaction({}); let tx = await Self.beginTransaction({});
let options = {transaction: transaction};
try { try {
let options = {transaction: tx};
let item = await models.Item.findById(ctx.args.itemFk); let item = await models.Item.findById(ctx.args.itemFk);
if (!item) if (!item)
throw new UserError(`That item doesn't exists`); throw new UserError(`That item doesn't exists`);
@ -88,9 +89,9 @@ module.exports = Self => {
message: message message: message
}, options); }, options);
await transaction.commit(); await tx.commit();
} catch (error) { } catch (error) {
await transaction.rollback(); await tx.rollback();
throw error; throw error;
} }
}; };

View File

@ -27,11 +27,11 @@ module.exports = function(Self) {
Self.makeInvoice = async(ctx, id) => { Self.makeInvoice = async(ctx, id) => {
let userId = ctx.req.accessToken.userId; let userId = ctx.req.accessToken.userId;
let $ = Self.app.models; let $ = Self.app.models;
let tx = await Self.beginTransaction({});
let options = {};
options.transaction = await Self.beginTransaction({});
try { try {
let options = {transaction: tx};
let ticket = await $.Ticket.findById(id, {fields: ['id', 'clientFk', 'companyFk']}); let ticket = await $.Ticket.findById(id, {fields: ['id', 'clientFk', 'companyFk']});
let clientCanBeInvoiced = await $.Client.canBeInvoiced(ticket.clientFk); let clientCanBeInvoiced = await $.Client.canBeInvoiced(ticket.clientFk);
@ -64,11 +64,11 @@ module.exports = function(Self) {
query = `INSERT INTO printServerQueue(reportFk, param1, workerFk) VALUES (?, ?, ?)`; query = `INSERT INTO printServerQueue(reportFk, param1, workerFk) VALUES (?, ?, ?)`;
await Self.rawSql(query, [3, invoice, user.id], options); await Self.rawSql(query, [3, invoice, user.id], options);
await options.transaction.commit(); await tx.commit();
return {invoiceFk: invoice, serial}; return {invoiceFk: invoice, serial};
} catch (e) { } catch (e) {
options.transaction.rollback(); await tx.rollback();
throw e; throw e;
} }
}; };

View File

@ -21,8 +21,9 @@ module.exports = Self => {
} }
}); });
Self.new = async(ctx, params, transaction) => { Self.new = async(ctx, params, options) => {
let address = await Self.app.models.Address.findOne({ let $ = Self.app.models;
let address = await $.Address.findOne({
where: {id: params.addressFk}, where: {id: params.addressFk},
fields: ['id', 'clientFk'], fields: ['id', 'clientFk'],
include: [ include: [
@ -41,7 +42,7 @@ module.exports = Self => {
let agencyMode; let agencyMode;
if (params && params.agencyModeFk) if (params && params.agencyModeFk)
agencyMode = await Self.app.models.AgencyMode.findById(params.agencyModeFk); agencyMode = await $.AgencyMode.findById(params.agencyModeFk);
if (address.client().type().code === 'normal' && (!agencyMode || agencyMode.code != 'refund')) { if (address.client().type().code === 'normal' && (!agencyMode || agencyMode.code != 'refund')) {
if (address.client().isFreezed) if (address.client().isFreezed)
@ -51,12 +52,19 @@ module.exports = Self => {
throw new UserError(`You can't create a ticket for a inactive client`); throw new UserError(`You can't create a ticket for a inactive client`);
} }
if (!transaction || !transaction.commit) let tx;
transaction = await Self.beginTransaction({});
if ((typeof options) != 'object')
options = {};
if (!options.transaction) {
tx = await Self.beginTransaction({});
options.transaction = tx;
}
try { try {
if (!params.shipped && params.landed) { if (!params.shipped && params.landed) {
params.shipped = await Self.app.models.Agency.getShipped(ctx, { params.shipped = await $.Agency.getShipped(ctx, {
landed: params.landed, landed: params.landed,
addressFk: address.id, addressFk: address.id,
agencyModeFk: params.agencyModeFk, agencyModeFk: params.agencyModeFk,
@ -65,7 +73,7 @@ module.exports = Self => {
} }
if (params.shipped && !params.landed) { if (params.shipped && !params.landed) {
const landedResult = await Self.app.models.Agency.getLanded(ctx, { const landedResult = await $.Agency.getLanded(ctx, {
shipped: params.shipped, shipped: params.shipped,
addressFk: address.id, addressFk: address.id,
agencyModeFk: params.agencyModeFk, agencyModeFk: params.agencyModeFk,
@ -89,9 +97,9 @@ module.exports = Self => {
params.routeFk || null, params.routeFk || null,
params.landed, params.landed,
params.userId params.userId
], {options: transaction}); ], options);
let ticket = await Self.app.models.Ticket.findById(result[1][0].newTicketId, {options: transaction}); let ticket = await $.Ticket.findById(result[1][0].newTicketId, null, options);
let cleanInstance = JSON.parse(JSON.stringify(ticket)); let cleanInstance = JSON.parse(JSON.stringify(ticket));
let logRecord = { let logRecord = {
@ -104,12 +112,12 @@ module.exports = Self => {
newInstance: cleanInstance newInstance: cleanInstance
}; };
await Self.app.models.TicketLog.create(logRecord, {options: transaction}); await $.TicketLog.create(logRecord, options);
await transaction.commit(); if (tx) await tx.commit();
return await ticket; return await ticket;
} catch (e) { } catch (e) {
await transaction.rollback(); if (tx) await tx.rollback();
throw e; throw e;
} }
}; };