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 \
./
ENV DEBUG=strong-remoting:shared-method
CMD ["pm2-docker", "./loopback/server/server.js"]

View File

@ -112,7 +112,7 @@ module.exports = function(Self) {
for (let key1 in ctx.Model.relations) {
let val1 = ctx.Model.relations[key1];
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];
if (!showField) {

View File

@ -11,6 +11,20 @@ module.exports = function(Self) {
setup() {
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
/* this.beforeRemote('prototype.patchAttributes', ctx => this.checkUpdateAcls(ctx));
this.beforeRemote('updateAll', ctx => this.checkUpdateAcls(ctx));
@ -41,10 +55,11 @@ module.exports = function(Self) {
},
async crud(deletes, updates, creates) {
let transaction = await this.beginTransaction({});
let options = {transaction};
let tx = await this.beginTransaction({});
try {
let options = {transaction: tx};
if (deletes) {
let promises = [];
for (let id of deletes)
@ -65,9 +80,9 @@ module.exports = function(Self) {
}
}
await transaction.commit();
await tx.commit();
} catch (error) {
await transaction.rollback();
await tx.rollback();
throw error;
}
},

View File

@ -21,39 +21,40 @@ module.exports = Self => {
Self.clone = async id => {
const models = Self.app.models;
const transaction = 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);
const tx = await Self.beginTransaction({});
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 newIncludedGeo = includedGeo.map(included => {
included.zoneFk = newZone.id;
@ -66,11 +67,11 @@ module.exports = Self => {
await models.ZoneIncluded.create(newIncludedGeo, options);
await models.ZoneCalendar.create(newCalendayDays, options);
await transaction.commit();
await tx.commit();
return newZone;
} catch (e) {
await transaction.rollback();
await tx.rollback();
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 = [];
salesToRefund.forEach(sale => {
let formatedSale = {
@ -35,10 +35,10 @@ module.exports = Self => {
};
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 = [];
createdSales.forEach(sale => {
let formatedSale = {
@ -48,17 +48,17 @@ module.exports = Self => {
};
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(?, ?, ?)
ON DUPLICATE KEY UPDATE description = CONCAT(vn.ticketObservation.description, VALUES(description),' ')`;
await Self.rawSql(query, [
observation.ticketFk,
observation.observationTypeFk,
observation.description
], transaction);
], options);
}
Self.importToNewRefundTicket = async(ctx, id) => {
@ -109,37 +109,39 @@ module.exports = Self => {
]
};
let transaction = await Self.beginTransaction({});
let tx = await Self.beginTransaction({});
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 = {
description: `Reclama ticket: ${claim.ticketFk}`,
ticketFk: newRefundTicket.id,
observationTypeFk: obsevationType.id
};
await saveObservation(observation, {transaction: transaction});
await saveObservation(observation, options);
await models.TicketTracking.create({
ticketFk: newRefundTicket.id,
stateFk: state.id,
workerFk: worker.id
}, {transaction: transaction});
}, options);
let salesToRefund = await models.ClaimBeginning.find(salesFilter);
let createdSales = await addSalesToTicket(salesToRefund, newRefundTicket.id, {transaction: transaction});
insertIntoClaimEnd(createdSales, id, worker.id, {transaction: transaction});
let createdSales = await addSalesToTicket(salesToRefund, newRefundTicket.id, options);
insertIntoClaimEnd(createdSales, id, worker.id, options);
await Self.rawSql('CALL vn.ticketCalculateClon(?, ?)', [
newRefundTicket.id, claim.ticketFk
], {transaction: transaction});
], options);
await transaction.commit();
await tx.commit();
return newRefundTicket;
} catch (e) {
await transaction.rollback();
await tx.rollback();
throw e;
}
};

View File

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

View File

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

View File

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

View File

@ -19,15 +19,17 @@ module.exports = Self => {
});
Self.confirmTransaction = async(ctx, id) => {
let transaction = await Self.beginTransaction({});
let userId = ctx.req.accessToken.userId;
let tx = await Self.beginTransaction({});
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 newInstance = {status: tpvTransaction.status};
@ -42,12 +44,12 @@ module.exports = Self => {
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;
} catch (e) {
await transaction.rollback();
await tx.rollback();
throw e;
}
};

View File

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

View File

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

View File

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

View File

@ -24,11 +24,13 @@ module.exports = Self => {
const models = Self.app.models;
const invoiceReportFk = 30; // FIXME - Should be deprecated
const worker = await models.Worker.findOne({where: {userFk: userId}});
const transaction = await Self.beginTransaction({});
const tx = await Self.beginTransaction({});
try {
let options = {transaction: tx};
// 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({
hasPdf: false
});
@ -36,13 +38,13 @@ module.exports = Self => {
// Send to print queue
await Self.rawSql(`
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;
} catch (e) {
await transaction.rollback();
await tx.rollback();
throw e;
}
};

View File

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

View File

@ -33,16 +33,18 @@ module.exports = Self => {
throw new UserError(`You don't have enough privileges to do that`);
}
let transaction = await Self.beginTransaction({});
let tx = await Self.beginTransaction({});
try {
let options = {transaction: tx};
let provisionalName = 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 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'}});
@ -53,18 +55,18 @@ module.exports = Self => {
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`;
await Self.rawSql(query, null, {transaction: transaction});
await Self.rawSql(query, null, options);
query = `CALL vn.itemRefreshTags(?)`;
await Self.rawSql(query, [item.id], {transaction: transaction});
await transaction.commit();
await Self.rawSql(query, [item.id], options);
await tx.commit();
return item;
} catch (e) {
await transaction.rollback();
await tx.rollback();
throw e;
}
};

View File

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

View File

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

View File

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

View File

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

View File

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