2669 - Changes to the translate values function #577

Merged
carlosjr merged 6 commits from 2669-loggable_refactor into dev 2021-03-22 09:24:52 +00:00
6 changed files with 126 additions and 98 deletions

View File

@ -134,8 +134,9 @@ module.exports = function(Self) {
if (value instanceof Object) if (value instanceof Object)
continue; continue;
if (value === undefined || value === null) continue; if (value === undefined) continue;
if (value) {
for (let relationName in relations) { for (let relationName in relations) {
const relation = relations[relationName]; const relation = relations[relationName];
if (relation.keyFrom == key && key != 'id') { if (relation.keyFrom == key && key != 'id') {
@ -177,6 +178,7 @@ module.exports = function(Self) {
break; break;
} }
} }
}
result[key] = value; result[key] = value;
} }
return result; return result;

View File

@ -3,7 +3,7 @@
* @param {Object} instance - The model or context instance * @param {Object} instance - The model or context instance
* @param {Object} changes - Object containing changes * @param {Object} changes - Object containing changes
*/ */
exports.translateValues = async(instance, changes) => { exports.translateValues = async(instance, changes, options = {}) => {
const models = instance.app.models; const models = instance.app.models;
function getRelation(instance, property) { function getRelation(instance, property) {
const relations = instance.definition.settings.relations; const relations = instance.definition.settings.relations;
@ -38,12 +38,20 @@ exports.translateValues = async(instance, changes) => {
const properties = Object.assign({}, changes); const properties = Object.assign({}, changes);
for (let property in properties) { for (let property in properties) {
const firstChar = property.substring(0, 1);
const isPrivate = firstChar == '$';
if (isPrivate) {
delete properties[property];
continue;
}
const relation = getRelation(instance, property); const relation = getRelation(instance, property);
const value = properties[property]; const value = properties[property];
let finalValue = value; const hasValue = value != null && value != undefined;
if (relation) { let finalValue = value;
let fieldsToShow = ['alias', 'name', 'code', 'description']; if (relation && hasValue) {
let fieldsToShow = ['nickname', 'name', 'code', 'description'];
const modelName = relation.model; const modelName = relation.model;
const model = models[modelName]; const model = models[modelName];
const log = model.definition.settings.log; const log = model.definition.settings.log;
@ -53,7 +61,7 @@ exports.translateValues = async(instance, changes) => {
const row = await model.findById(value, { const row = await model.findById(value, {
fields: fieldsToShow fields: fieldsToShow
}); }, options);
const newValue = getValue(row); const newValue = getValue(row);
if (newValue) finalValue = newValue; if (newValue) finalValue = newValue;
} }
@ -76,7 +84,12 @@ exports.translateValues = async(instance, changes) => {
exports.getChanges = (original, changes) => { exports.getChanges = (original, changes) => {
const oldChanges = {}; const oldChanges = {};
const newChanges = {}; const newChanges = {};
for (let property in changes) { for (let property in changes) {
const firstChar = property.substring(0, 1);
const isPrivate = firstChar == '$';
if (isPrivate) return;
if (changes[property] != original[property]) { if (changes[property] != original[property]) {
newChanges[property] = changes[property]; newChanges[property] = changes[property];

View File

@ -19,11 +19,10 @@ module.exports = Self => {
} }
}); });
Self.importToNewRefundTicket = async(ctx, id) => { Self.importToNewRefundTicket = async(ctx, id, options) => {
const models = Self.app.models; const models = Self.app.models;
const token = ctx.req.accessToken; const token = ctx.req.accessToken;
const userId = token.userId; const userId = token.userId;
const tx = await Self.beginTransaction({});
const filter = { const filter = {
where: {id: id}, where: {id: id},
include: [ include: [
@ -63,29 +62,39 @@ module.exports = Self => {
] ]
}; };
let tx;
let myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
try { try {
let options = {transaction: tx};
const worker = await models.Worker.findOne({ const worker = await models.Worker.findOne({
where: {userFk: userId} where: {userFk: userId}
}, options); }, myOptions);
const obsevationType = await models.ObservationType.findOne({ const obsevationType = await models.ObservationType.findOne({
where: {description: 'comercial'} where: {description: 'comercial'}
}, options); }, myOptions);
const agencyMode = await models.AgencyMode.findOne({ const agencyMode = await models.AgencyMode.findOne({
where: {code: 'refund'} where: {code: 'refund'}
}, options); }, myOptions);
const state = await models.State.findOne({ const state = await models.State.findOne({
where: {code: 'DELIVERED'} where: {code: 'DELIVERED'}
}, options); }, myOptions);
const zone = await models.Zone.findOne({ const zone = await models.Zone.findOne({
where: {agencyModeFk: agencyMode.id} where: {agencyModeFk: agencyMode.id}
}, options); }, myOptions);
const claim = await models.Claim.findOne(filter, options); const claim = await models.Claim.findOne(filter, myOptions);
const today = new Date(); const today = new Date();
const newRefundTicket = await models.Ticket.create({ const newRefundTicket = await models.Ticket.create({
@ -98,33 +107,33 @@ module.exports = Self => {
addressFk: claim.ticket().addressFk, addressFk: claim.ticket().addressFk,
agencyModeFk: agencyMode.id, agencyModeFk: agencyMode.id,
zoneFk: zone.id zoneFk: zone.id
}, options); }, myOptions);
await saveObservation({ await saveObservation({
description: `Reclama ticket: ${claim.ticketFk}`, description: `Reclama ticket: ${claim.ticketFk}`,
ticketFk: newRefundTicket.id, ticketFk: newRefundTicket.id,
observationTypeFk: obsevationType.id observationTypeFk: obsevationType.id
}, options); }, myOptions);
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
}, options); }, myOptions);
const salesToRefund = await models.ClaimBeginning.find(salesFilter, options); const salesToRefund = await models.ClaimBeginning.find(salesFilter, myOptions);
const createdSales = await addSalesToTicket(salesToRefund, newRefundTicket.id, options); const createdSales = await addSalesToTicket(salesToRefund, newRefundTicket.id, myOptions);
await insertIntoClaimEnd(createdSales, id, worker.id, options); await insertIntoClaimEnd(createdSales, id, worker.id, myOptions);
await Self.rawSql('CALL vn.ticketCalculateClon(?, ?)', [ await Self.rawSql('CALL vn.ticketCalculateClon(?, ?)', [
newRefundTicket.id, claim.ticketFk newRefundTicket.id, claim.ticketFk
], options); ], myOptions);
await tx.commit(); if (tx) await tx.commit();
return newRefundTicket; return newRefundTicket;
} catch (e) { } catch (e) {
await tx.rollback(); if (tx) await tx.rollback();
throw e; throw e;
} }
}; };

View File

@ -1,42 +1,43 @@
const app = require('vn-loopback/server/server'); const app = require('vn-loopback/server/server');
const LoopBackContext = require('loopback-context'); const LoopBackContext = require('loopback-context');
const models = app.models;
describe('claimBeginning', () => { describe('claimBeginning', () => {
const claimManagerId = 72; const claimManagerId = 72;
let ticket;
let refundTicketSales;
let salesInsertedInClaimEnd;
const activeCtx = { const activeCtx = {
accessToken: {userId: claimManagerId}, accessToken: {userId: claimManagerId},
}; };
const ctx = {req: activeCtx}; const ctx = {req: activeCtx};
afterAll(async done => {
try {
await app.models.Ticket.destroyById(ticket.id);
await app.models.Ticket.rawSql(`DELETE FROM vn.orderTicket WHERE ticketFk ='${ticket.id}';`);
} catch (error) {
console.error(error);
}
done();
});
describe('importToNewRefundTicket()', () => { describe('importToNewRefundTicket()', () => {
it('should create a new ticket with negative sales and insert the negative sales into claimEnd', async() => { it('should create a new ticket with negative sales and insert the negative sales into claimEnd', async() => {
spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
active: activeCtx active: activeCtx
}); });
let claimId = 1; let claimId = 1;
ticket = await app.models.ClaimBeginning.importToNewRefundTicket(ctx, claimId);
refundTicketSales = await app.models.Sale.find({where: {ticketFk: ticket.id}}); const tx = await models.Entry.beginTransaction({});
salesInsertedInClaimEnd = await app.models.ClaimEnd.find({where: {claimFk: claimId}}); try {
const options = {transaction: tx};
const ticket = await models.ClaimBeginning.importToNewRefundTicket(ctx, claimId, options);
const refundTicketSales = await models.Sale.find({
where: {ticketFk: ticket.id}
}, options);
const salesInsertedInClaimEnd = await models.ClaimEnd.find({
where: {claimFk: claimId}
}, options);
expect(refundTicketSales.length).toEqual(1); expect(refundTicketSales.length).toEqual(1);
expect(refundTicketSales[0].quantity).toEqual(-5); expect(refundTicketSales[0].quantity).toEqual(-5);
expect(salesInsertedInClaimEnd[0].saleFk).toEqual(refundTicketSales[0].id); expect(salesInsertedInClaimEnd[0].saleFk).toEqual(refundTicketSales[0].id);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
}); });
}); });

View File

@ -1,8 +1,7 @@
const app = require('vn-loopback/server/server'); const app = require('vn-loopback/server/server');
const LoopBackContext = require('loopback-context'); const LoopBackContext = require('loopback-context');
describe('entry import()', () => { fdescribe('entry import()', () => {
let newEntry;
const buyerId = 35; const buyerId = 35;
const companyId = 442; const companyId = 442;
const travelId = 1; const travelId = 1;
@ -52,9 +51,9 @@ describe('entry import()', () => {
} }
}; };
const tx = await app.models.Entry.beginTransaction({}); const tx = await app.models.Entry.beginTransaction({});
try {
const options = {transaction: tx}; const options = {transaction: tx};
const newEntry = await app.models.Entry.create({
newEntry = await app.models.Entry.create({
dated: new Date(), dated: new Date(),
supplierFk: supplierId, supplierFk: supplierId,
travelFk: travelId, travelFk: travelId,
@ -65,7 +64,7 @@ describe('entry import()', () => {
await app.models.Entry.importBuys(ctx, newEntry.id, options); await app.models.Entry.importBuys(ctx, newEntry.id, options);
const updatedEntry = await app.models.Entry.findById(newEntry.id, null, options); const updatedEntry = await app.models.Entry.findById(null, null, options);
const entryBuys = await app.models.Buy.find({ const entryBuys = await app.models.Buy.find({
where: {entryFk: newEntry.id} where: {entryFk: newEntry.id}
}, options); }, options);
@ -74,7 +73,10 @@ describe('entry import()', () => {
expect(updatedEntry.ref).toEqual(expectedRef); expect(updatedEntry.ref).toEqual(expectedRef);
expect(entryBuys.length).toEqual(2); expect(entryBuys.length).toEqual(2);
// Restores
await tx.rollback(); await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
}); });
}); });

View File

@ -2,7 +2,8 @@
"name": "Ticket", "name": "Ticket",
"base": "Loggable", "base": "Loggable",
"log": { "log": {
"model":"TicketLog" "model":"TicketLog",
"showField": "id"
}, },
"options": { "options": {
"mysql": { "mysql": {