refs #5036 refactor transaction and fixing ticket logs
gitea/salix/pipeline/head This commit looks good Details

This commit is contained in:
Alexandre Riera 2023-01-11 13:24:55 +01:00
parent bebbe1c846
commit a0491de9f9
3 changed files with 246 additions and 188 deletions

View File

@ -7,29 +7,16 @@ module.exports = function(Self) {
}; };
Self.observe('before save', async function(ctx) { Self.observe('before save', async function(ctx) {
const loopBackContext = LoopBackContext.getCurrentContext();
const models = ctx.Model.app.models; const models = ctx.Model.app.models;
const definition = ctx.Model.definition; const definition = ctx.Model.definition;
const Model = models[definition.name]; const Model = models[definition.name];
const settings = definition.settings;
let opts = ctx.options; let opts = ctx.options;
if (!opts) opts = ctx.options = {}; if (!opts) opts = ctx.options = {};
// Check for transactions // await txBegin(ctx);
if (opts.txLevel)
opts.txLevel++;
else if (!opts.transaction) {
opts.txLevel = 1;
opts.transaction = await Model.beginTransaction({});
}
try { // try {
// Check if grabUser is active // await grabUserLog(ctx, 'login');
if (loopBackContext && settings.log && settings.log.grabUser) {
const userId = loopBackContext.active.accessToken.userId;
const user = await models.Account.findById(userId, {fields: ['name']}, opts);
await Model.rawSql(`CALL account.myUser_loginWithName(?)`, [user.name], opts);
}
let oldInstance; let oldInstance;
let newInstance; let newInstance;
@ -54,44 +41,22 @@ module.exports = function(Self) {
ctx.hookState.oldInstance = oldInstance; ctx.hookState.oldInstance = oldInstance;
ctx.hookState.newInstance = newInstance; ctx.hookState.newInstance = newInstance;
} catch (e) { // } catch (e) {
await txEnd(ctx, true); // await txEnd(ctx, true);
} // }
}); });
async function txEnd(ctx, undoChanges) {
const opts = ctx.options || {};
if (opts.txLevel) {
opts.txLevel--;
if (opts.txLevel === 0) {
const tx = opts.transaction;
delete opts.txLevel;
delete opts.transaction;
if (undoChanges)
await tx.rollback();
else
await tx.commit();
}
}
}
Self.observe('after save', async function(ctx) { Self.observe('after save', async function(ctx) {
const loopBackContext = LoopBackContext.getCurrentContext(); const loopBackContext = LoopBackContext.getCurrentContext();
await logInModel(ctx, loopBackContext);
});
async function logInModel(ctx, loopBackContext) {
const models = ctx.Model.app.models; const models = ctx.Model.app.models;
const definition = ctx.Model.definition; const definition = ctx.Model.definition;
const Model = models[definition.name];
const settings = ctx.Model.definition.settings; const settings = ctx.Model.definition.settings;
const relations = ctx.Model.relations; const relations = ctx.Model.relations;
let opts = ctx.options; let opts = ctx.options;
if (!opts) opts = ctx.options = {}; if (!opts) opts = ctx.options = {};
try { // try {
let primaryKey; let primaryKey;
for (let property in definition.properties) { for (let property in definition.properties) {
if (definition.properties[property].id) { if (definition.properties[property].id) {
@ -182,15 +147,14 @@ module.exports = function(Self) {
const logModel = settings.log.model; const logModel = settings.log.model;
await models[logModel].create(logsToSave, opts); await models[logModel].create(logsToSave, opts);
// Check if grabUser is active // await grabUserLog(ctx, 'logout');
if (settings.log && settings.log.grabUser) await Model.rawSql(`CALL account.myUser_logout()`, null, opts); // } catch (e) {
} catch (e) { // await txEnd(ctx, true);
await txEnd(ctx, true); // throw e;
throw e; // }
}
await txEnd(ctx); // await txEnd(ctx);
} });
Self.observe('before delete', async function(ctx) { Self.observe('before delete', async function(ctx) {
const models = ctx.Model.app.models; const models = ctx.Model.app.models;
@ -199,6 +163,11 @@ module.exports = function(Self) {
let opts = ctx.options; let opts = ctx.options;
if (!opts) opts = ctx.options = {}; if (!opts) opts = ctx.options = {};
// await txBegin(ctx);
// try {
// await grabUserLog(ctx, 'login');
if (ctx.where) { if (ctx.where) {
const affectedModel = definition.name; const affectedModel = definition.name;
let deletedInstances = await models[affectedModel].find({ let deletedInstances = await models[affectedModel].find({
@ -220,20 +189,21 @@ module.exports = function(Self) {
ctx.hookState.oldInstance = arrangedDeletedInstances; ctx.hookState.oldInstance = arrangedDeletedInstances;
} }
} }
// } catch (e) {
// await txEnd(ctx, true);
// }
}); });
Self.observe('after delete', async function(ctx) { Self.observe('after delete', async function(ctx) {
const loopBackContext = LoopBackContext.getCurrentContext(); const loopBackContext = LoopBackContext.getCurrentContext();
if (ctx.hookState.oldInstance) logDeletedInstances(ctx, loopBackContext);
});
async function logDeletedInstances(ctx, loopBackContext) {
const models = ctx.Model.app.models; const models = ctx.Model.app.models;
const definition = ctx.Model.definition; const definition = ctx.Model.definition;
const settings = definition.settings; const settings = definition.settings;
let opts = ctx.options; let opts = ctx.options;
if (!opts) opts = ctx.options = {}; if (!opts) opts = ctx.options = {};
// try {
if (ctx.hookState.oldInstance) {
ctx.hookState.oldInstance.forEach(async instance => { ctx.hookState.oldInstance.forEach(async instance => {
let userFk; let userFk;
if (loopBackContext) if (loopBackContext)
@ -257,6 +227,14 @@ module.exports = function(Self) {
await models[logModel].create(logRecord, opts); await models[logModel].create(logRecord, opts);
}); });
} }
// await grabUserLog(ctx, 'logout');
// } catch (e) {
// await txEnd(ctx, true);
// throw e;
// }
// await txEnd(ctx);
});
// Get log values from a foreign key // Get log values from a foreign key
async function fkToValue(instance, ctx) { async function fkToValue(instance, ctx) {
@ -381,4 +359,69 @@ module.exports = function(Self) {
return 'delete'; return 'delete';
} }
/**
* The functions txBegin and txEnd are used to transactionate the loggable.
* When a new transaction is created, they add a txLevel because in some cases
* the transactions are performed in a recursive way.
*
* The function grabUserLog check if the option grabUser is active in the Model and
* login or logout the user in the database depending on the action.
*
* Now they are commented out because the way to handle the errors
* that occur in the database that leave opened transactions has not been found.
* (https://redmine.verdnatura.es/issues/5036)
**/
// async function txBegin(ctx) {
// const opts = ctx.options || {};
// const models = ctx.Model.app.models;
// const definition = ctx.Model.definition;
// const Model = models[definition.name];
// if (opts.txLevel)
// opts.txLevel++;
// else if (!opts.transaction) {
// opts.txLevel = 1;
// opts.transaction = await Model.beginTransaction({});
// }
// }
// async function txEnd(ctx, undoChanges) {
// const opts = ctx.options || {};
// if (opts.txLevel) {
// opts.txLevel--;
// if (opts.txLevel === 0) {
// const tx = opts.transaction;
// delete opts.txLevel;
// delete opts.transaction;
// if (undoChanges)
// await tx.rollback();
// else
// await tx.commit();
// }
// }
// }
// async function grabUserLog(ctx, logAction) {
// const opts = ctx.options || {};
// const models = ctx.Model.app.models;
// const definition = ctx.Model.definition;
// const settings = definition.settings;
// const Model = models[definition.name];
// const hasGrabUser = settings.log && settings.log.grabUser;
// if (logAction === 'login' && hasGrabUser) {
// const loopBackContext = LoopBackContext.getCurrentContext();
// if (loopBackContext) {
// const userId = loopBackContext.active.accessToken.userId;
// const user = await models.Account.findById(userId, {fields: ['name']}, opts);
// await Model.rawSql(`CALL account.myUser_loginWithName(?)`, [user.name], opts);
// }
// } else if (logAction === 'logout' && hasGrabUser)
// await Model.rawSql(`CALL account.myUser_logout()`, null, opts);
// }
}; };

View File

@ -91,7 +91,11 @@ exports.getChanges = (original, changes) => {
const isPrivate = firstChar == '$'; const isPrivate = firstChar == '$';
if (isPrivate) return; if (isPrivate) return;
if (changes[property] != original[property]) { const hasChanges = original[property] instanceof Date ?
changes[property]?.getTime() != original[property]?.getTime() :
changes[property] != original[property];
if (hasChanges) {
newChanges[property] = changes[property]; newChanges[property] = changes[property];
if (original[property] != undefined) if (original[property] != undefined)

View File

@ -160,18 +160,29 @@ module.exports = Self => {
'shipped', 'shipped',
'landed', 'landed',
'isDeleted', 'isDeleted',
'routeFk' 'routeFk',
'nickname'
], ],
include: [ include: [
{ {
relation: 'client', relation: 'client',
scope: { scope: {
fields: 'salesPersonFk' fields: 'salesPersonFk'
},
include: [
{
relation: 'address',
scope: {
fields: 'nickname'
} }
}] }
]
},
]
}, myOptions); }, myOptions);
args.routeFk = null; args.routeFk = null;
if (args.isWithoutNegatives === false) delete args.isWithoutNegatives;
const updatedTicket = Object.assign({}, args); const updatedTicket = Object.assign({}, args);
delete updatedTicket.ctx; delete updatedTicket.ctx;
delete updatedTicket.option; delete updatedTicket.option;