transactions refactor #1546
gitea/salix/test This commit looks good Details

This commit is contained in:
Joan Sanchez 2019-06-21 08:26:59 +02:00
parent 7c23f92957
commit 5d63a14b15
5 changed files with 142 additions and 129 deletions

View File

@ -89,7 +89,7 @@
"Please select at least one sale": "Por favor selecciona al menos una linea", "Please select at least one sale": "Por favor selecciona al menos una linea",
"All sales must belong to the same ticket": "Todas las lineas deben pertenecer al mismo ticket", "All sales must belong to the same ticket": "Todas las lineas deben pertenecer al mismo ticket",
"NO_ZONE_FOR_THIS_PARAMETERS": "Para este día no hay ninguna zona configurada", "NO_ZONE_FOR_THIS_PARAMETERS": "Para este día no hay ninguna zona configurada",
"That item doesn't exists": "El artículo no existe", "This item doesn't exists": "El artículo no existe",
"NOT_ZONE_WITH_THIS_PARAMETERS": "Para este día no hay ninguna zona configurada", "NOT_ZONE_WITH_THIS_PARAMETERS": "Para este día no hay ninguna zona configurada",
"Extension format is invalid": "El formato de la extensión es inválido" "Extension format is invalid": "El formato de la extensión es inválido"
} }

View File

@ -19,12 +19,112 @@ module.exports = Self => {
} }
}); });
async function addSalesToTicket(salesToRefund, ticketFk, options) { Self.importToNewRefundTicket = async(ctx, id) => {
const models = Self.app.models;
const token = ctx.req.accessToken;
const userId = token.userId;
const tx = await Self.beginTransaction({});
const filter = {
where: {id: id},
include: [
{
relation: 'ticket',
scope: {
fields: ['id', 'clientFk', 'warehouseFk', 'companyFk', 'addressFk']
}
}
]
};
const salesFilter = {
where: {claimFk: id},
include: [
{
relation: 'sale',
scope: {
fields: [
'id',
'itemFk',
'concept',
'price',
'discount',
'reserved',
'isPicked',
'created',
'priceFixed',
'isPriceFixed']
}
}
]
};
try {
let options = {transaction: tx};
const worker = await models.Worker.findOne({
where: {userFk: userId}
}, options);
const obsevationType = await models.ObservationType.findOne({
where: {description: 'comercial'}
}, options);
const agency = await models.AgencyMode.findOne({
where: {code: 'refund'}
}, options);
const state = await models.State.findOne({
where: {code: 'DELIVERED'}
}, options);
const claim = await models.Claim.findOne(filter, options);
const today = new Date();
const newRefundTicket = await models.Ticket.new(ctx, {
clientFk: claim.ticket().clientFk,
shipped: today,
landed: today,
warehouseFk: claim.ticket().warehouseFk,
companyFk: claim.ticket().companyFk,
addressFk: claim.ticket().addressFk,
agencyModeFk: agency.id,
userId: userId
}, options);
await saveObservation({
description: `Reclama ticket: ${claim.ticketFk}`,
ticketFk: newRefundTicket.id,
observationTypeFk: obsevationType.id
}, options);
await models.TicketTracking.create({
ticketFk: newRefundTicket.id,
stateFk: state.id,
workerFk: worker.id
}, options);
const salesToRefund = await models.ClaimBeginning.find(salesFilter, options);
const createdSales = await addSalesToTicket(salesToRefund, newRefundTicket.id, options);
await insertIntoClaimEnd(createdSales, id, worker.id, options);
await Self.rawSql('CALL vn.ticketCalculateClon(?, ?)', [
newRefundTicket.id, claim.ticketFk
], options);
await tx.commit();
return newRefundTicket;
} catch (e) {
await tx.rollback();
throw e;
}
};
async function addSalesToTicket(salesToRefund, ticketId, options) {
let formatedSales = []; let formatedSales = [];
salesToRefund.forEach(sale => { salesToRefund.forEach(sale => {
let formatedSale = { let formatedSale = {
itemFk: sale.sale().itemFk, itemFk: sale.sale().itemFk,
ticketFk: ticketFk, ticketFk: ticketId,
concept: sale.sale().concept, concept: sale.sale().concept,
quantity: -Math.abs(sale.quantity), quantity: -Math.abs(sale.quantity),
price: sale.sale().price, price: sale.sale().price,
@ -39,7 +139,7 @@ module.exports = Self => {
} }
async function insertIntoClaimEnd(createdSales, claimId, workerId, options) { async function insertIntoClaimEnd(createdSales, claimId, workerId, options) {
let formatedSales = []; const formatedSales = [];
createdSales.forEach(sale => { createdSales.forEach(sale => {
let formatedSale = { let formatedSale = {
saleFk: sale.id, saleFk: sale.id,
@ -48,101 +148,17 @@ module.exports = Self => {
}; };
formatedSales.push(formatedSale); formatedSales.push(formatedSale);
}); });
return await Self.app.models.ClaimEnd.create(formatedSales, options); await Self.app.models.ClaimEnd.create(formatedSales, options);
} }
async function saveObservation(observation, options) { async function saveObservation(observation, options) {
let query = `INSERT INTO vn.ticketObservation(ticketFk, observationTypeFk, description) VALUES(?, ?, ?) const 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
], options); ], options);
} }
Self.importToNewRefundTicket = async(ctx, id) => {
let models = Self.app.models;
let token = ctx.req.accessToken;
let userId = token.userId;
let worker = await models.Worker.findOne({where: {userFk: userId}});
let obsevationType = await models.ObservationType.findOne({where: {description: 'comercial'}});
let agency = await models.AgencyMode.findOne({where: {code: 'refund'}});
let state = await models.State.findOne({where: {code: 'DELIVERED'}});
let filter = {
where: {id: id},
include: [
{
relation: 'ticket',
scope: {
fields: ['id', 'clientFk', 'warehouseFk', 'companyFk', 'addressFk']
}
}
]
};
let claim = await models.Claim.findOne(filter);
let today = new Date();
let params = {
clientFk: claim.ticket().clientFk,
shipped: today,
landed: today,
warehouseFk: claim.ticket().warehouseFk,
companyFk: claim.ticket().companyFk,
addressFk: claim.ticket().addressFk,
agencyModeFk: agency.id,
userId: userId
};
let salesFilter = {
where: {claimFk: id},
include: [
{
relation: 'sale',
scope: {
fields: ['id', 'itemFk', 'concept', 'price', 'discount', 'reserved', 'isPicked', 'created', 'priceFixed', 'isPriceFixed']
}
}
]
};
let tx = await Self.beginTransaction({});
try {
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, options);
await models.TicketTracking.create({
ticketFk: newRefundTicket.id,
stateFk: state.id,
workerFk: worker.id
}, options);
let salesToRefund = await models.ClaimBeginning.find(salesFilter);
let createdSales = await addSalesToTicket(salesToRefund, newRefundTicket.id, options);
insertIntoClaimEnd(createdSales, id, worker.id, options);
await Self.rawSql('CALL vn.ticketCalculateClon(?, ?)', [
newRefundTicket.id, claim.ticketFk
], options);
await tx.commit();
return newRefundTicket;
} catch (e) {
await tx.rollback();
throw e;
}
};
}; };

View File

@ -26,26 +26,32 @@ module.exports = Self => {
Self.createFromSales = async(ctx, params) => { Self.createFromSales = async(ctx, params) => {
let model = Self.app.models; let model = Self.app.models;
let userId = ctx.req.accessToken.userId;
let tx = await Self.beginTransaction({}); let tx = await Self.beginTransaction({});
try { try {
let options = {transaction: tx}; let options = {transaction: tx};
const worker = await Self.app.models.Worker.findOne({
let userId = ctx.req.accessToken.userId; where: {userFk: userId}
let worker = await Self.app.models.Worker.findOne({where: {userFk: userId}}); }, options);
params.claim.workerFk = worker.id; params.claim.workerFk = worker.id;
let newClaim = await Self.create(params.claim, options); let newClaim = await Self.create(params.claim, options);
let promises = []; 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
}, options));
}
await Promise.all(promises);
await tx.commit();
for (const sale of params.sales) {
const newClaimBeginning = model.ClaimBeginning.create({
saleFk: sale.id,
claimFk: newClaim.id,
quantity: sale.quantity
}, options);
promises.push(newClaimBeginning);
}
await Promise.all(promises);
await tx.commit();
return newClaim; return newClaim;
} catch (e) { } catch (e) {
await tx.rollback(); await tx.rollback();

View File

@ -30,7 +30,7 @@ module.exports = Self => {
const origin = await Self.findById(itemId, null, options); const origin = await Self.findById(itemId, null, options);
if (!origin) if (!origin)
throw new UserError(`That item doesn't exists`); throw new UserError(`This item doesn't exists`);
origin.itemTag = undefined; origin.itemTag = undefined;
origin.description = undefined; origin.description = undefined;
@ -40,12 +40,9 @@ module.exports = Self => {
const newItem = await Self.create(origin, options); const newItem = await Self.create(origin, options);
let promises = []; await cloneTaxes(origin.id, newItem.id, options);
await cloneBotanical(origin.id, newItem.id, options);
await cloneTaxes(origin.id, newItem.id, promises, options); await cloneTags(origin.id, newItem.id, options);
await cloneBotanical(origin.id, newItem.id, promises, options);
await cloneTags(origin.id, newItem.id, promises, options);
await Promise.all(promises);
await tx.commit(); await tx.commit();
return newItem; return newItem;
@ -59,36 +56,32 @@ module.exports = Self => {
* Clone original taxes to new item * Clone original taxes to new item
* @param {Integer} originalId - Original item id * @param {Integer} originalId - Original item id
* @param {Integer} newId - New item id * @param {Integer} newId - New item id
* @param {Array} promises - Array of promises
* @param {Object} options - Transaction options * @param {Object} options - Transaction options
*/ */
async function cloneTaxes(originalId, newId, promises, options) { async function cloneTaxes(originalId, newId, options) {
const models = Self.app.models; const models = Self.app.models;
const originalTaxes = await models.ItemTaxCountry.find({ const originalTaxes = await models.ItemTaxCountry.find({
where: {itemFk: originalId}, where: {itemFk: originalId},
fields: ['botanical', 'countryFk', 'taxClassFk'] fields: ['botanical', 'countryFk', 'taxClassFk']
}, options); }, options);
originalTaxes.forEach(tax => { for (tax of originalTaxes) {
tax.itemFk = newId; tax.itemFk = newId;
const newItemTax = models.ItemTaxCountry.upsertWithWhere({ await models.ItemTaxCountry.upsertWithWhere({
itemFk: newId, itemFk: newId,
countryFk: tax.countryFk, countryFk: tax.countryFk,
}, tax, options); }, tax, options);
}
promises.push(newItemTax);
});
} }
/** /**
* Clone original botanical to new item * Clone original botanical to new item
* @param {Integer} originalId - Original item id * @param {Integer} originalId - Original item id
* @param {Integer} newId - New item id * @param {Integer} newId - New item id
* @param {Array} promises - Array of promises
* @param {Object} options - Transaction options * @param {Object} options - Transaction options
*/ */
async function cloneBotanical(originalId, newId, promises, options) { async function cloneBotanical(originalId, newId, options) {
const models = Self.app.models; const models = Self.app.models;
const botanical = await models.ItemBotanical.findOne({ const botanical = await models.ItemBotanical.findOne({
where: {itemFk: originalId}, where: {itemFk: originalId},
@ -97,8 +90,8 @@ module.exports = Self => {
if (botanical) { if (botanical) {
botanical.itemFk = newId; botanical.itemFk = newId;
const newBotanical = models.ItemBotanical.create(botanical, options);
promises.push(newBotanical); await models.ItemBotanical.create(botanical, options);
} }
} }
@ -106,10 +99,9 @@ module.exports = Self => {
* Clone original item tags to new item * Clone original item tags to new item
* @param {Integer} originalId - Original item id * @param {Integer} originalId - Original item id
* @param {Integer} newId - New item id * @param {Integer} newId - New item id
* @param {Array} promises - Array of promises
* @param {Object} options - Transaction options * @param {Object} options - Transaction options
*/ */
async function cloneTags(originalId, newId, promises, options) { async function cloneTags(originalId, newId, options) {
const models = Self.app.models; const models = Self.app.models;
const originalTags = await models.ItemTag.find({ const originalTags = await models.ItemTag.find({
where: { where: {
@ -118,11 +110,10 @@ module.exports = Self => {
fields: ['tagFk', 'value', 'priority'] fields: ['tagFk', 'value', 'priority']
}, options); }, options);
originalTags.forEach(tag => { for (tag of originalTags) {
tag.itemFk = newId; tag.itemFk = newId;
const newTag = models.ItemTag.create(tag, options); await models.ItemTag.create(tag, options);
promises.push(newTag); }
});
} }
}; };

View File

@ -28,7 +28,7 @@ describe('item clone()', () => {
let itemFk = 999; let itemFk = 999;
await app.models.Item.clone(itemFk) await app.models.Item.clone(itemFk)
.catch(e => { .catch(e => {
expect(e.message).toContain(`That item doesn't exists`); expect(e.message).toContain(`This item doesn't exists`);
error = e; error = e;
}); });