refs #4823 Many changes

This commit is contained in:
Guillermo Bonet 2023-05-09 11:59:21 +02:00
parent a7bc5a807c
commit 7058ab837b
6 changed files with 143 additions and 125 deletions

View File

@ -4,7 +4,7 @@ import moment from 'moment';
import chalk from 'chalk'; import chalk from 'chalk';
// Añade la hora a todos los console.log // Añade la hora a todos los console.log
// console.log = (...args) => console.info(`[${new moment().format('YYYY-MM-DD hh:mm:ss A')}]`, ...args); console.log = (...args) => console.info(chalk.gray(`[${new moment().format('YYYY-MM-DD hh:mm:ss A')}]`), ...args);
const env = process.env; const env = process.env;
class Floriday { class Floriday {
async start() { async start() {
@ -18,7 +18,7 @@ class Floriday {
} catch (err) { } catch (err) {
utils.criticalError(err); utils.criticalError(err);
} }
await this.trunk(); await this.schedule();
} }
async tryConn() { async tryConn() {
@ -37,14 +37,16 @@ class Floriday {
const intervalTime = JSON.parse(env.IS_PRODUCTION) const intervalTime = JSON.parse(env.IS_PRODUCTION)
? env.MS_PRODUCTION_SCHEDULE ? env.MS_PRODUCTION_SCHEDULE
: env.MS_TEST_SCHEDULE; : env.MS_TEST_SCHEDULE;
setInterval(async () => {
while (true) {
try { try {
await this.trunk(); await this.trunk();
} await new Promise(resolve => setTimeout(resolve, intervalTime));
catch (err) { } catch (err) {
await this.tryConn(); await this.tryConn();
await new Promise(resolve => setTimeout(resolve, intervalTime));
} }
}, intervalTime); }
} catch (err) { } catch (err) {
throw new Error(err); throw new Error(err);
} }
@ -60,7 +62,7 @@ class Floriday {
// Continuar con todo lo que haga falta realizar en la rutina // Continuar con todo lo que haga falta realizar en la rutina
} catch (err) { } catch (err) {
throw new Error(err); throw err;
} }
} }

View File

@ -99,25 +99,25 @@ try {
/* ------------------------------ */ /* ------------------------------ */
models.characteristic.belongsTo(models.tradeItem, { models.characteristic.belongsTo(models.tradeItem, {
foreignKey: 'tradeItemFk', foreignKey: 'tradeItemId',
as: 'tradeItem_Fk', as: 'tradeItem_Fk',
targetKey: 'tradeItemId', targetKey: 'tradeItemId',
}); });
models.seasonalPeriod.belongsTo(models.tradeItem, { models.seasonalPeriod.belongsTo(models.tradeItem, {
foreignKey: 'tradeItemFk', foreignKey: 'tradeItemId',
as: 'tradeItem_Fk', as: 'tradeItem_Fk',
targetKey: 'tradeItemId', targetKey: 'tradeItemId',
}); });
models.photo.belongsTo(models.tradeItem, { models.photo.belongsTo(models.tradeItem, {
foreignKey: 'tradeItemFk', foreignKey: 'tradeItemId',
as: 'tradeItem_Fk', as: 'tradeItem_Fk',
targetKey: 'tradeItemId', targetKey: 'tradeItemId',
}); });
models.packingConfiguration.belongsTo(models.tradeItem, { models.packingConfiguration.belongsTo(models.tradeItem, {
foreignKey: 'tradeItemFk', foreignKey: 'tradeItemId',
as: 'tradeItem_Fk', as: 'tradeItem_Fk',
targetKey: 'tradeItemId', targetKey: 'tradeItemId',
}); });
@ -136,13 +136,13 @@ try {
models.botanicalName.belongsTo(models.tradeItem, { models.botanicalName.belongsTo(models.tradeItem, {
foreignKey: 'tradeItemFk', foreignKey: 'tradeItemId',
as: 'tradeItem_Fk', as: 'tradeItem_Fk',
targetKey: 'tradeItemId', targetKey: 'tradeItemId',
}); });
models.countryOfOriginIsoCode.belongsTo(models.tradeItem, { models.countryOfOriginIsoCode.belongsTo(models.tradeItem, {
foreignKey: 'tradeItemFk', foreignKey: 'tradeItemId',
as: 'tradeItem_Fk', as: 'tradeItem_Fk',
targetKey: 'tradeItemId', targetKey: 'tradeItemId',
}); });
@ -154,7 +154,7 @@ try {
}); });
models.supplyLine.belongsTo(models.tradeItem, { models.supplyLine.belongsTo(models.tradeItem, {
foreignKey: 'tradeItemFk', foreignKey: 'tradeItemId',
as: 'tradeItem_Fk', as: 'tradeItem_Fk',
targetKey: 'tradeItemId', targetKey: 'tradeItemId',
}); });
@ -162,7 +162,13 @@ try {
models.tradeItem.belongsTo(models.supplier, { models.tradeItem.belongsTo(models.supplier, {
foreignKey: 'supplierOrganizationId', foreignKey: 'supplierOrganizationId',
as: 'supplierOrganization_Id', as: 'supplierOrganization_Id',
targetKey: 'organizationId', targetKey: 'supplierOrganizationId',
});
models.supplyLine.belongsTo(models.supplier, {
foreignKey: 'supplierOrganizationId',
as: 'supplierOrganization_Id',
targetKey: 'supplierOrganizationId',
}); });
} catch (err) { } catch (err) {
throw new Error(err) throw new Error(err)

View File

@ -1,7 +1,7 @@
import { Sequelize } from 'sequelize'; import { Sequelize } from 'sequelize';
const connections = { const connections = {
organizationId: { supplierOrganizationId: {
type: Sequelize.STRING, type: Sequelize.STRING,
primaryKey: true, primaryKey: true,
allowNull: false, allowNull: false,

View File

@ -1,13 +1,13 @@
import { Sequelize } from 'sequelize'; import { Sequelize } from 'sequelize';
const suppliers = { const suppliers = {
sequenceNumber: { supplierOrganizationId: {
type: Sequelize.INTEGER, type: Sequelize.STRING,
allowNull: false, allowNull: false,
primaryKey: true, primaryKey: true,
}, },
organizationId: { sequenceNumber: {
type: Sequelize.STRING, type: Sequelize.INTEGER,
allowNull: false, allowNull: false,
primaryKey: true, primaryKey: true,
}, },

View File

@ -8,22 +8,28 @@ const supplyLine = {
status: { status: {
type: Sequelize.STRING, type: Sequelize.STRING,
}, },
supplierOrganizationId: { pricePerPiece_currency: {
type: Sequelize.STRING, type: Sequelize.STRING,
}, },
pricePerPiece: { pricePerPiece_value: {
type: Sequelize.JSON, type: Sequelize.DECIMAL(10,2),
}, },
numberOfPieces : { numberOfPieces : {
type: Sequelize.INTEGER, type: Sequelize.INTEGER,
}, },
deliveryPeriod: { deliveryPeriod_startDateTime: {
type: Sequelize.JSON, type: Sequelize.DATE,
}, },
orderPeriod: { deliveryPeriod_endDateTime: {
type: Sequelize.JSON, type: Sequelize.DATE,
}, },
wharehouseId: { orderPeriod_startDateTime: {
type: Sequelize.DATE,
},
orderPeriod_endDateTime: {
type: Sequelize.DATE,
},
warehouseId: {
type: Sequelize.STRING, type: Sequelize.STRING,
}, },
sequenceNumber: { sequenceNumber: {
@ -38,10 +44,10 @@ const supplyLine = {
salesUnit: { salesUnit: {
type: Sequelize.STRING, type: Sequelize.STRING,
}, },
agreementReferenceCode: { agreementReference_code: {
type: Sequelize.STRING, type: Sequelize.STRING,
}, },
agreementReferenceDescription: { agreementReference_description: {
type: Sequelize.STRING, type: Sequelize.STRING,
}, },
isLimited: { isLimited: {

186
utils.js
View File

@ -307,14 +307,14 @@ export async function syncSuppliers(){
if (timeFinish) if (timeFinish)
spinner.text = spinner.text + ` (${timeLeft})` spinner.text = spinner.text + ` (${timeLeft})`
await models.supplier.upsert({ await models.supplier.upsert({
supplierOrganizationId: supplier.organizationId,
sequenceNumber: supplier.sequenceNumber, sequenceNumber: supplier.sequenceNumber,
companyGln: supplier.companyGln, companyGln: supplier.companyGln ? supplier.companyGln : null,
name: supplier.name ? supplier.name : null, name: supplier.name ? supplier.name : null,
commercialName: supplier.commercialName ? supplier.commercialName : null, commercialName: supplier.commercialName ? supplier.commercialName : null,
email: supplier.email ? supplier.email : null, email: supplier.email ? supplier.email : null,
phone: supplier.phone ? supplier.phone : null, phone: supplier.phone ? supplier.phone : null,
website: supplier.website ? supplier.website : null, website: supplier.website ? supplier.website : null,
organizationId: supplier.organizationId ? supplier.organizationId : null,
rfhRelationId: supplier.rfhRelationId ? supplier.rfhRelationId : null, rfhRelationId: supplier.rfhRelationId ? supplier.rfhRelationId : null,
paymentProviders: supplier.paymentProviders.length ? `${supplier.paymentProviders}` : null, paymentProviders: supplier.paymentProviders.length ? `${supplier.paymentProviders}` : null,
endDate: supplier.endDate ? supplier.endDate : null, endDate: supplier.endDate ? supplier.endDate : null,
@ -363,34 +363,34 @@ export async function syncConn(){
spinner.text = `Syncing ${i++} connections...` spinner.text = `Syncing ${i++} connections...`
if (connection.isConnected == false) if (connection.isConnected == false)
continue; continue;
let remoteConnection = remoteConnections.find(remoteConnection => remoteConnection == connection.organizationId); let remoteConnection = remoteConnections.find(remoteConnection => remoteConnection == connection.supplierOrganizationId);
if (remoteConnection == undefined){ if (remoteConnection == undefined){
console.log('Connection: ', connection, 'does not exist in the remote server'); console.log('Connection: ', connection, 'does not exist in the remote server');
console.log('Creating remote connection'); console.log('Creating remote connection');
await fetch(`${env.API_URL}/connections/${connection.organizationId}`, { await fetch(`${env.API_URL}/connections/${connection.supplierOrganizationId}`, {
method: 'PUT', method: 'PUT',
headers headers
}); });
await models.connection.update({ isConnected: true }, { await models.connection.update({ isConnected: true }, {
where: { where: {
organizationId: connection.organizationId supplierOrganizationId: connection.supplierOrganizationId
} }
}); });
await models.supplier.update({ isConnected: true }, { await models.supplier.update({ isConnected: true }, {
where: { where: {
organizationId: connection.organizationId supplierOrganizationId: connection.supplierOrganizationId
} }
}); });
} else { } else {
await models.connection.update({ isConnected: true }, { await models.connection.update({ isConnected: true }, {
where: { where: {
organizationId: connection.organizationId supplierOrganizationId: connection.supplierOrganizationId
} }
}); });
await models.supplier.update({ isConnected: true }, { await models.supplier.update({ isConnected: true }, {
where: { where: {
organizationId: connection.organizationId supplierOrganizationId: connection.supplierOrganizationId
} }
}); });
} }
@ -409,7 +409,7 @@ export async function syncTradeItems(){
for (let supplier of suppliers) { for (let supplier of suppliers) {
if (!supplier.isConnected) continue; if (!supplier.isConnected) continue;
let query = `${env.API_URL}/trade-items?supplierOrganizationId=${supplier.organizationId}`; let query = `${env.API_URL}/trade-items?supplierOrganizationId=${supplier.supplierOrganizationId}`;
let headers = { let headers = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'Authorization': `Bearer ${await getCurrentToken()}`, 'Authorization': `Bearer ${await getCurrentToken()}`,
@ -439,8 +439,8 @@ export async function syncTradeItems(){
} }
/** /**
* Syncs the supply lines for suppliers that are connected * Syncs the supply lines for suppliers that are connected to do this,
* to do this, it fetches all the supply lines for every tradeitem of the suppliers * it fetches all the supply lines for every tradeitem of the suppliers
*/ */
export async function syncSupplyLines(){ export async function syncSupplyLines(){
try { try {
@ -459,7 +459,7 @@ export async function syncSupplyLines(){
let tradeItems = await models.tradeItem.findAll({ let tradeItems = await models.tradeItem.findAll({
where: { where: {
supplierOrganizationId: suppliers.map(supplier => supplier.organizationId) supplierOrganizationId: suppliers.map(supplier => supplier.supplierOrganizationId)
} }
}); });
@ -473,13 +473,12 @@ export async function syncSupplyLines(){
// Launch a promise for each supplier // Launch a promise for each supplier
for (let tradeItem of tradeItems) { for (let tradeItem of tradeItems) {
let supplier = suppliers.find(supplier => supplier.organizationId == tradeItem.supplierOrganizationId); let supplier = suppliers.find(supplier => supplier.supplierOrganizationId == tradeItem.supplierOrganizationId);
// eslint-disable-next-line no-async-promise-executor
let promise = new Promise(async (resolve) => { let promise = new Promise(async (resolve) => {
try { try {
let url = `${env.API_URL}/supply-lines/sync/0` let url = `${env.API_URL}/supply-lines/sync/0`
const params = new URLSearchParams({ const params = new URLSearchParams({
supplierOrganizationId: supplier.organizationId, supplierOrganizationId: supplier.supplierOrganizationId,
tradeItemId: tradeItem.tradeItemId, tradeItemId: tradeItem.tradeItemId,
postFilterSelectedTradeItems: false postFilterSelectedTradeItems: false
}); });
@ -488,19 +487,23 @@ export async function syncSupplyLines(){
headers headers
}); });
if (request.status == 429) { // Too many request
resolve([]);
return;
}
let supplyLines = await request.json(); let supplyLines = await request.json();
if (supplyLines.length == 0) { if (!supplyLines.results.length) {
console.log('No supply lines for supplier: ', supplier.commercialName, ' - ' , tradeItem.name);
resolve([]); resolve([]);
return; return;
} }
resolve(supplyLines); resolve(supplyLines);
} catch (error) { } catch (err) {
console.log('Error while syncing supply lines for: ', supplier.commercialName, ' - ' , tradeItem.name); console.log('Error while syncing supply lines for: ', supplier.commercialName, ' - ' , tradeItem.name);
console.log(error); console.log(err);
resolve([]); resolve([]);
} }
}); });
@ -516,43 +519,10 @@ export async function syncSupplyLines(){
maximumSequenceNumber = supplyLine.maximumSequenceNumber; maximumSequenceNumber = supplyLine.maximumSequenceNumber;
supplyLine = supplyLine.results; supplyLine = supplyLine.results;
try { try {
for (let line of supplyLine) { if (supplyLine) {
for (let line of supplyLine) {
let tradeItem = await models.tradeItem.findOne({ let tradeItem = await models.tradeItem.findOne({
where: {
tradeItemId: line.tradeItemId
}
});
if (!tradeItem) {
console.log('Trade item not found for supply line: ', line.supplyLineId);
console.log('Requesting data for trade item id: ', line.tradeItemId);
let urlTradeItem = `${env.API_URL}/trade-items?tradeItemIds=${line.tradeItemId}`;
let queryTradeItem = await fetch(urlTradeItem, {
method: 'GET',
headers
});
let tradeItem = await queryTradeItem.json();
if (tradeItem.length == 0) {
console.log('Trade item not found for supply line: ', line.supplyLineId);
console.log('Trade item id: ', line.tradeItemId);
continue;
}
let supplier = await models.supplier.findOne({
where: {
organizationId: tradeItem[0].supplierOrganizationId
}
});
await insertItem(tradeItem[0], supplier);
tradeItem = await models.tradeItem.findOne({
where: { where: {
tradeItemId: line.tradeItemId tradeItemId: line.tradeItemId
} }
@ -560,46 +530,80 @@ export async function syncSupplyLines(){
if (!tradeItem) { if (!tradeItem) {
console.log('Trade item not found for supply line: ', line.supplyLineId); console.log('Trade item not found for supply line: ', line.supplyLineId);
console.log('Trade item id: ', line.tradeItemId); console.log('Requesting data for trade item id: ', line.tradeItemId);
continue;
let queryTradeItem = await fetch(`${env.API_URL}/trade-items?tradeItemIds=${line.tradeItemId}`, {
method: 'GET',
headers
});
let tradeItem = await queryTradeItem.json();
if (tradeItem.length == 0) {
console.log('Trade item not found for supply line: ', line.supplyLineId);
console.log('Trade item id: ', line.tradeItemId);
continue;
}
let supplier = await models.supplier.findOne({
where: {
supplierOrganizationId: tradeItem[0].supplierOrganizationId
}
});
await insertItem(tradeItem[0], supplier);
tradeItem = await models.tradeItem.findOne({
where: {
tradeItemId: line.tradeItemId
}
});
if (!tradeItem) {
console.log('Trade item not found for supply line: ', line.supplyLineId);
console.log('Trade item id: ', line.tradeItemId);
continue;
}
} }
await models.supplyLine.upsert({
supplyLineId: line.supplyLineId,
status: line.status,
supplierOrganizationId: line.supplierOrganizationId,
pricePerPiece_currency: line.pricePerPiece.currency,
pricePerPiece_value: line.pricePerPiece.value,
numberOfPieces: line.numberOfPieces,
deliveryPeriod_startDateTime: line.deliveryPeriod.startDateTime,
deliveryPeriod_endDateTime: line.deliveryPeriod.endDateTime,
orderPeriod_startDateTime: line.orderPeriod.startDateTime,
orderPeriod_endDateTime: line.orderPeriod.endDateTime,
warehouseId: line.warehouseId,
sequenceNumber: line.sequenceNumber,
type: line.type,
isDeleted: line.isDeleted,
salesUnit: line.salesUnit,
agreementReference_code: line.agreementReference.code ? line.agreementReference.code : null,
agreementReference_description: line.agreementReference.description ? line.agreementReference.description : null,
isLimited: line.isLimited,
isCustomerSpecific: line.isCustomerSpecific,
tradeItemId: line.tradeItemId,
});
} }
await models.supplyLine.upsert({
supplyLineId: line.supplyLineId,
status: line.status,
supplierOrganizationId: line.supplierOrganizationId,
pricePerPiece: line.pricePerPiece,
numberOfPieces: line.numberOfPieces,
deliveryPeriod: line.deliveryPeriod,
orderPeriod: line.orderPeriod,
wharehouseId: line.wharehouseId,
sequenceNumber: line.sequenceNumber,
type: line.type,
isDeleted: line.isDeleted,
salesUnit: line.salesUnit,
agreementReferenceCode: line.agreementReference.code,
agreementReferenceDescription: line.agreementReference.description,
isLimited: line.isLimited,
isCustomerSpecific: line.isCustomerSpecific,
tradeItemFk: line.tradeItemId,
});
} }
} catch (err) { } catch (err) {
spinner.fail(); spinner.fail();
console.log('Error while syncing supply lines - ' + supplyLine.results[0].tradeItemId); throw err;
throw new Error(err);
} }
} }
spinner.succeed(); spinner.succeed();
console.log('Found', suppliers.length, 'connected suppliers'); console.log('Found', suppliers.length, 'connected suppliers');
await syncSequence(currentSequenceNumber,'supplyLines' ,maximumSequenceNumber); await syncSequence(currentSequenceNumber, 'supplyLines' ,maximumSequenceNumber);
} catch (err) { } catch (err) {
throw new Error(err); throw err;
} }
} }
@ -609,7 +613,7 @@ export async function insertItem(tradeItem, supplier) {
let currentSupp = await models.supplier.findOne({ let currentSupp = await models.supplier.findOne({
where: { where: {
organizationId: tradeItem.supplierOrganizationId supplierOrganizationId: tradeItem.supplierOrganizationId
} }
}); });
@ -619,7 +623,7 @@ export async function insertItem(tradeItem, supplier) {
await currentSupp.save({transaction: tx}); await currentSupp.save({transaction: tx});
await models.connection.upsert({ await models.connection.upsert({
organizationId: tradeItem.supplierOrganizationId, supplierOrganizationId: tradeItem.supplierOrganizationId,
connect: true, connect: true,
}, {transaction: tx}); }, {transaction: tx});
@ -646,7 +650,7 @@ export async function insertItem(tradeItem, supplier) {
await models.characteristic.upsert({ await models.characteristic.upsert({
vbnCode: characteristic.vbnCode, vbnCode: characteristic.vbnCode,
vbnValueCode: characteristic.vbnValueCode, vbnValueCode: characteristic.vbnValueCode,
tradeItemFk: tradeItem.tradeItemId, tradeItemId: tradeItem.tradeItemId,
}, {transaction: tx}); }, {transaction: tx});
} }
@ -656,7 +660,7 @@ export async function insertItem(tradeItem, supplier) {
await models.seasonalPeriod.upsert({ await models.seasonalPeriod.upsert({
startWeek: seasonalPeriod.startWeek, startWeek: seasonalPeriod.startWeek,
endWeek: seasonalPeriod.endWeek, endWeek: seasonalPeriod.endWeek,
tradeItemFk: tradeItem.tradeItemId, tradeItemId: tradeItem.tradeItemId,
}, {transaction: tx}); }, {transaction: tx});
} }
@ -668,7 +672,7 @@ export async function insertItem(tradeItem, supplier) {
url: photo.url, url: photo.url,
type: photo.type, type: photo.type,
primary: photo.primary, primary: photo.primary,
tradeItemFk: tradeItem.tradeItemId, tradeItemId: tradeItem.tradeItemId,
}, {transaction: tx}); }, {transaction: tx});
let packingConfigurations = tradeItem.packingConfigurations; let packingConfigurations = tradeItem.packingConfigurations;
@ -688,7 +692,7 @@ export async function insertItem(tradeItem, supplier) {
transportHeightInCm: packingConfiguration.transportHeightInCm, transportHeightInCm: packingConfiguration.transportHeightInCm,
loadCarrierType: packingConfiguration.loadCarrierType, loadCarrierType: packingConfiguration.loadCarrierType,
isPrimary: packingConfiguration.isPrimary, isPrimary: packingConfiguration.isPrimary,
tradeItemFk: tradeItem.tradeItemId, tradeItemId: tradeItem.tradeItemId,
}, {transaction: tx}); }, {transaction: tx});
await models.package.upsert({ await models.package.upsert({
@ -705,7 +709,7 @@ export async function insertItem(tradeItem, supplier) {
for (let countryOfOriginIsoCode of countryOfOriginIsoCodes) { for (let countryOfOriginIsoCode of countryOfOriginIsoCodes) {
await models.countryOfOriginIsoCode.upsert({ await models.countryOfOriginIsoCode.upsert({
isoCode: countryOfOriginIsoCode, isoCode: countryOfOriginIsoCode,
tradeItemFk: tradeItem.tradeItemId, tradeItemId: tradeItem.tradeItemId,
}, {transaction: tx}); }, {transaction: tx});
} }
@ -714,7 +718,7 @@ export async function insertItem(tradeItem, supplier) {
for (let botanicalName of botanicalNames) { for (let botanicalName of botanicalNames) {
await models.botanicalName.upsert({ await models.botanicalName.upsert({
name: botanicalName.name, name: botanicalName.name,
tradeItemFk: tradeItem.tradeItemId, tradeItemId: tradeItem.tradeItemId,
}, {transaction: tx}); }, {transaction: tx});
} }