refs #4823 Changes in structure
This commit is contained in:
parent
69227f3853
commit
5a754967ba
|
@ -39,6 +39,8 @@ DB_USER = root
|
|||
DB_PWD = root
|
||||
DB_HOST = localhost
|
||||
DB_DIALECT = mariadb
|
||||
DB_TIMEOUT_RECONECT = 30000
|
||||
DB_MAX_CONN_POOL = 40
|
||||
|
||||
#GENERAL CONFIG
|
||||
IS_PRODUCTION = false
|
||||
|
@ -46,6 +48,7 @@ SECRETS = true
|
|||
FORCE_SYNC = true
|
||||
SYNC_SEQUENCE = true
|
||||
SYNC_SUPPLIER = true
|
||||
SYNC_CONN = true
|
||||
SYNC_TRADEITEM = true
|
||||
```
|
||||
|
||||
|
|
63
floriday.js
63
floriday.js
|
@ -1,6 +1,7 @@
|
|||
import * as vnUtils from './utils.js';
|
||||
import { models } from './models/index.js';
|
||||
import * as utils from './utils.js';
|
||||
import { models, checkConn, closeConn } from './models/index.js';
|
||||
import moment from 'moment';
|
||||
import chalk from 'chalk';
|
||||
|
||||
// Añade la hora a todos los console.log
|
||||
// console.log = (...args) => console.info(`${new moment().format('HH:mm:ss')} -`, ...args);
|
||||
|
@ -8,27 +9,63 @@ const env = process.env;
|
|||
class Floriday {
|
||||
async start() {
|
||||
try {
|
||||
this.tokenExpirationDate = await vnUtils.getClientToken(models);
|
||||
if (JSON.parse(env.SYNC_SEQUENCE)) await vnUtils.syncSequence()
|
||||
if (JSON.parse(env.SYNC_SUPPLIER)) await vnUtils.syncSuppliers();
|
||||
await vnUtils.syncConnections();
|
||||
if (JSON.parse(env.SYNC_TRADEITEM)) await vnUtils.syncTradeItems();
|
||||
this.tokenExpirationDate = await utils.requestToken(models);
|
||||
if (JSON.parse(env.SYNC_SEQUENCE)) await utils.syncSequence()
|
||||
if (JSON.parse(env.SYNC_SUPPLIER)) await utils.syncSuppliers();
|
||||
if (JSON.parse(env.SYNC_CONN)) await utils.syncConn();
|
||||
if (JSON.parse(env.SYNC_TRADEITEM)) await utils.syncTradeItems();
|
||||
} catch (err) {
|
||||
vnUtils.criticalError(err);
|
||||
utils.criticalError(err);
|
||||
}
|
||||
await this.troncal()
|
||||
}
|
||||
|
||||
async tryConn() {
|
||||
try {
|
||||
utils.sleep(env.DB_TIMEOUT_RECONECT);
|
||||
await checkConn();
|
||||
await this.schedule();
|
||||
}
|
||||
catch (err) {
|
||||
throw new Error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async schedule() {
|
||||
async schedule () {
|
||||
try {
|
||||
const intervalTime = JSON.parse(env.IS_PRODUCTION) ? 300000 : 5000;
|
||||
setInterval(async () => {
|
||||
try {
|
||||
await this.troncal();
|
||||
}
|
||||
catch (err) {
|
||||
await this.tryConn();
|
||||
}
|
||||
}, intervalTime);
|
||||
} catch (err) {
|
||||
throw new Error(err);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
async troncal() {
|
||||
try{
|
||||
if (moment().isAfter(await vnUtils.getCurrentTokenExpiration())) {
|
||||
this.tokenExpirationDate = await vnUtils.getClientToken(models);
|
||||
if (moment().isAfter(await utils.getCurrentTokenExpiration())) {
|
||||
this.tokenExpirationDate = await utils.requestToken(models);
|
||||
}
|
||||
await vnUtils.syncSupplyLines();
|
||||
await utils.syncSupplyLines();
|
||||
|
||||
// Continuar con todo lo que haga falta realizar en el evento
|
||||
|
||||
} catch (err) {
|
||||
throw(err);
|
||||
throw new Error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async stop() {
|
||||
await closeConn();
|
||||
console.log(chalk.dim('Bye, come back soon 👋'))
|
||||
}
|
||||
}
|
||||
|
||||
export default Floriday;
|
16
main.js
16
main.js
|
@ -1,20 +1,18 @@
|
|||
import Floriday from './floriday.js';
|
||||
const env = process.env;
|
||||
|
||||
async function main() {
|
||||
const floriday = new Floriday();
|
||||
|
||||
await floriday.start();
|
||||
|
||||
process.on('SIGINT', async function() {
|
||||
console.log('\nBye <3')
|
||||
process.on('SIGINT', async () => {
|
||||
await floriday.stop();
|
||||
process.exit();
|
||||
});
|
||||
|
||||
await floriday.schedule()
|
||||
const intervalTime = JSON.parse(env.IS_PRODUCTION) ? 300000 : 5000;
|
||||
setInterval(async () => {
|
||||
await floriday.schedule();
|
||||
}, intervalTime);
|
||||
try {
|
||||
await floriday.schedule()
|
||||
} catch (err) {
|
||||
await floriday.tryConn();
|
||||
}
|
||||
}
|
||||
main();
|
171
models/index.js
171
models/index.js
|
@ -16,10 +16,11 @@ console.log(chalk.hex('#06c581')(
|
|||
`
|
||||
))
|
||||
|
||||
let sequelize = createConnection();
|
||||
const conSpinner = ora('Creating connection...').start();
|
||||
let sequelize, conSpinner
|
||||
try {
|
||||
await sequelize.authenticate();
|
||||
conSpinner = ora('Creating connection...').start();
|
||||
sequelize = createConn();
|
||||
await checkConn();
|
||||
conSpinner.succeed();
|
||||
} catch (err) {
|
||||
conSpinner.fail();
|
||||
|
@ -86,81 +87,84 @@ let models = {
|
|||
connection: connections(sequelize),
|
||||
};
|
||||
|
||||
/* Remove ID atribute from models */
|
||||
models.characteristic.removeAttribute('id');
|
||||
models.seasonalPeriod.removeAttribute('id');
|
||||
models.package.removeAttribute('id');
|
||||
models.botanicalName.removeAttribute('id');
|
||||
models.countryOfOriginIsoCode.removeAttribute('id');
|
||||
/* ------------------------------ */
|
||||
try {
|
||||
/* Remove ID atribute from models */
|
||||
models.characteristic.removeAttribute('id');
|
||||
models.seasonalPeriod.removeAttribute('id');
|
||||
models.package.removeAttribute('id');
|
||||
models.botanicalName.removeAttribute('id');
|
||||
models.countryOfOriginIsoCode.removeAttribute('id');
|
||||
/* ------------------------------ */
|
||||
|
||||
models.characteristic.belongsTo(models.tradeItem, {
|
||||
foreignKey: 'tradeItemFk',
|
||||
as: 'tradeItem_Fk',
|
||||
targetKey: 'tradeItemId',
|
||||
});
|
||||
models.characteristic.belongsTo(models.tradeItem, {
|
||||
foreignKey: 'tradeItemFk',
|
||||
as: 'tradeItem_Fk',
|
||||
targetKey: 'tradeItemId',
|
||||
});
|
||||
|
||||
models.seasonalPeriod.belongsTo(models.tradeItem, {
|
||||
foreignKey: 'tradeItemFk',
|
||||
as: 'tradeItem_Fk',
|
||||
targetKey: 'tradeItemId',
|
||||
});
|
||||
models.seasonalPeriod.belongsTo(models.tradeItem, {
|
||||
foreignKey: 'tradeItemFk',
|
||||
as: 'tradeItem_Fk',
|
||||
targetKey: 'tradeItemId',
|
||||
});
|
||||
|
||||
models.photo.belongsTo(models.tradeItem, {
|
||||
foreignKey: 'tradeItemFk',
|
||||
as: 'tradeItem_Fk',
|
||||
targetKey: 'tradeItemId',
|
||||
});
|
||||
models.photo.belongsTo(models.tradeItem, {
|
||||
foreignKey: 'tradeItemFk',
|
||||
as: 'tradeItem_Fk',
|
||||
targetKey: 'tradeItemId',
|
||||
});
|
||||
|
||||
models.packingConfiguration.belongsTo(models.tradeItem, {
|
||||
foreignKey: 'tradeItemFk',
|
||||
as: 'tradeItem_Fk',
|
||||
targetKey: 'tradeItemId',
|
||||
});
|
||||
models.packingConfiguration.belongsTo(models.tradeItem, {
|
||||
foreignKey: 'tradeItemFk',
|
||||
as: 'tradeItem_Fk',
|
||||
targetKey: 'tradeItemId',
|
||||
});
|
||||
|
||||
models.packingConfiguration.hasMany(models.package, {
|
||||
foreignKey: 'packingConfigurationFk',
|
||||
as: 'package_Fk',
|
||||
targetKey: 'packingConfigurationId',
|
||||
});
|
||||
models.packingConfiguration.hasMany(models.package, {
|
||||
foreignKey: 'packingConfigurationFk',
|
||||
as: 'package_Fk',
|
||||
targetKey: 'packingConfigurationId',
|
||||
});
|
||||
|
||||
models.package.belongsTo(models.packingConfiguration, {
|
||||
foreignKey: 'packingConfigurationFk',
|
||||
as: 'packingConfiguration_Fk',
|
||||
targetKey: 'packingConfigurationId',
|
||||
});
|
||||
models.package.belongsTo(models.packingConfiguration, {
|
||||
foreignKey: 'packingConfigurationFk',
|
||||
as: 'packingConfiguration_Fk',
|
||||
targetKey: 'packingConfigurationId',
|
||||
});
|
||||
|
||||
|
||||
models.botanicalName.belongsTo(models.tradeItem, {
|
||||
foreignKey: 'tradeItemFk',
|
||||
as: 'tradeItem_Fk',
|
||||
targetKey: 'tradeItemId',
|
||||
});
|
||||
models.botanicalName.belongsTo(models.tradeItem, {
|
||||
foreignKey: 'tradeItemFk',
|
||||
as: 'tradeItem_Fk',
|
||||
targetKey: 'tradeItemId',
|
||||
});
|
||||
|
||||
models.countryOfOriginIsoCode.belongsTo(models.tradeItem, {
|
||||
foreignKey: 'tradeItemFk',
|
||||
as: 'tradeItem_Fk',
|
||||
targetKey: 'tradeItemId',
|
||||
});
|
||||
models.countryOfOriginIsoCode.belongsTo(models.tradeItem, {
|
||||
foreignKey: 'tradeItemFk',
|
||||
as: 'tradeItem_Fk',
|
||||
targetKey: 'tradeItemId',
|
||||
});
|
||||
|
||||
models.volumePrice.belongsTo(models.supplyLine, {
|
||||
foreignKey: 'supplyLineFk',
|
||||
as: 'supplyLine_Fk',
|
||||
targetKey: 'supplyLineId',
|
||||
});
|
||||
models.volumePrice.belongsTo(models.supplyLine, {
|
||||
foreignKey: 'supplyLineFk',
|
||||
as: 'supplyLine_Fk',
|
||||
targetKey: 'supplyLineId',
|
||||
});
|
||||
|
||||
models.supplyLine.belongsTo(models.tradeItem, {
|
||||
foreignKey: 'tradeItemFk',
|
||||
as: 'tradeItem_Fk',
|
||||
targetKey: 'tradeItemId',
|
||||
});
|
||||
|
||||
models.tradeItem.belongsTo(models.supplier, {
|
||||
foreignKey: 'supplierOrganizationId',
|
||||
as: 'supplierOrganization_Id',
|
||||
targetKey: 'organizationId',
|
||||
});
|
||||
models.supplyLine.belongsTo(models.tradeItem, {
|
||||
foreignKey: 'tradeItemFk',
|
||||
as: 'tradeItem_Fk',
|
||||
targetKey: 'tradeItemId',
|
||||
});
|
||||
|
||||
models.tradeItem.belongsTo(models.supplier, {
|
||||
foreignKey: 'supplierOrganizationId',
|
||||
as: 'supplierOrganization_Id',
|
||||
targetKey: 'organizationId',
|
||||
});
|
||||
} catch (err) {
|
||||
throw new Error(err)
|
||||
}
|
||||
|
||||
let action, isForce;
|
||||
if (JSON.parse(process.env.FORCE_SYNC)) {
|
||||
|
@ -195,23 +199,44 @@ catch (err) {
|
|||
/**
|
||||
* Creates the connection to the database.
|
||||
*
|
||||
* @example
|
||||
* let sequelize = createConnection();
|
||||
*
|
||||
* @returns {Sequelize} Sequelize instance with the connection to the database.
|
||||
*/
|
||||
function createConnection() {
|
||||
function createConn() {
|
||||
return new Sequelize(process.env.DB_SCHEMA, process.env.DB_USER, process.env.DB_PWD, {
|
||||
host: process.env.DB_HOST,
|
||||
dialect: process.env.DB_DIALECT,
|
||||
logging: false,
|
||||
pool: {
|
||||
max: 40,
|
||||
min: 0,
|
||||
max: parseInt(process.env.DB_MAX_CONN_POOL),
|
||||
acquire: 60000,
|
||||
idle: 10000,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export { models } ;
|
||||
/**
|
||||
* Check if connection is ok
|
||||
*/
|
||||
async function checkConn() {
|
||||
try {
|
||||
await sequelize.authenticate();
|
||||
} catch (err) {
|
||||
throw new Error (err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Close connection
|
||||
*/
|
||||
async function closeConn() {
|
||||
const spinner = ora('Stopping connection...').start();
|
||||
try {
|
||||
await sequelize.close()
|
||||
spinner.succeed();
|
||||
} catch (err) {
|
||||
spinner.fail();
|
||||
criticalError(err)
|
||||
}
|
||||
}
|
||||
|
||||
export { models, checkConn, closeConn};
|
458
utils.js
458
utils.js
|
@ -17,7 +17,7 @@ const url = 'https://api.staging.floriday.io/customers-api/2022v2';
|
|||
* @param {sequelize.models} models
|
||||
* @returns {Date} tokenExpirationDate formated as YYYY-MM-DD HH:mm:ss
|
||||
*/
|
||||
export async function getClientToken() {
|
||||
export async function requestToken() {
|
||||
const clientConfigData = await models.clientConfig.findOne();
|
||||
|
||||
if (!clientConfigData)
|
||||
|
@ -41,7 +41,7 @@ export async function getClientToken() {
|
|||
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`)
|
||||
.join('&');
|
||||
|
||||
const tokenRequest = await fetch(tokenEndpoint, {
|
||||
const response = await fetch(tokenEndpoint, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
|
@ -49,26 +49,22 @@ export async function getClientToken() {
|
|||
body,
|
||||
});
|
||||
|
||||
const tokenResponse = await tokenRequest.json();
|
||||
const responseData = await response.json();
|
||||
|
||||
if (tokenRequest.ok) {
|
||||
if (response.ok) {
|
||||
spinner.succeed();
|
||||
} else {
|
||||
spinner.fail();
|
||||
criticalError(new Error(`Token request failed with status: ${tokenRequest.status} - ${tokenRequest.statusText}`));
|
||||
criticalError(new Error(`Token request failed with status: ${response.status} - ${response.statusText}`));
|
||||
}
|
||||
|
||||
const accessToken = tokenResponse.access_token;
|
||||
let now = moment().format('YYYY-MM-DD HH:mm:ss');
|
||||
|
||||
let tokenExpirationDate = moment(now)
|
||||
.add(tokenResponse.expires_in, 's')
|
||||
let tokenExpirationDate = moment()
|
||||
.add(responseData.expires_in, 's')
|
||||
.format('YYYY-MM-DD HH:mm:ss');
|
||||
|
||||
await updateClientConfig(
|
||||
clientId,
|
||||
clientSecret,
|
||||
accessToken,
|
||||
responseData.access_token,
|
||||
tokenExpirationDate
|
||||
);
|
||||
|
||||
|
@ -80,19 +76,28 @@ export async function getClientToken() {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current token
|
||||
*
|
||||
* @returns {string}
|
||||
*/
|
||||
export async function getCurrentToken() {
|
||||
let data = await models.clientConfig.findOne().currentToken;
|
||||
return data.currentToken;
|
||||
let data = await models.clientConfig.findOne();
|
||||
return data.currentToken
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the expiration data of current token
|
||||
*
|
||||
* @returns {string}
|
||||
*/
|
||||
export async function getCurrentTokenExpiration() {
|
||||
let data = await models.clientConfig.findOne();
|
||||
return data.tokenExpiration;
|
||||
return data.tokenExpiration
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the Access Token in the client config table
|
||||
* Updates the Access Token in the client config table
|
||||
*
|
||||
* @param {sequelize.models} models
|
||||
* @param {String} clientId
|
||||
|
@ -119,16 +124,6 @@ export async function updateClientConfig(clientId, clientSecret, accessToken, to
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the current Access Token
|
||||
*
|
||||
* @returns
|
||||
*/
|
||||
export async function getJWT() {
|
||||
const clientConfigData = await models.clientConfig.findAll();
|
||||
return clientConfigData[0].currentToken;
|
||||
}
|
||||
|
||||
/**
|
||||
* pauses the execution of the script for the given amount of milliseconds
|
||||
*
|
||||
|
@ -203,7 +198,7 @@ export async function syncSequence(current = 0, model = null , maximumSequenceNu
|
|||
spinner.succeed();
|
||||
} catch (err) {
|
||||
spinner.fail();
|
||||
throw(err);
|
||||
throw new Error(err);
|
||||
}
|
||||
} else if (current) {
|
||||
|
||||
|
@ -248,14 +243,20 @@ export async function syncSuppliers(){
|
|||
try {
|
||||
let headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${await getJWT()}`,
|
||||
'Authorization': `Bearer ${await getCurrentToken()}`,
|
||||
'X-Api-Key': process.env.API_KEY
|
||||
};
|
||||
|
||||
|
||||
const response = await fetch(`${url}/organizations/current-max-sequence`, {
|
||||
method: 'GET',
|
||||
headers
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
spinner.fail();
|
||||
criticalError(new Error(`Max sequence request failed with status: ${response.status} - ${response.statusText}`));
|
||||
}
|
||||
|
||||
const maxSequenceNumber = await response.json();
|
||||
let timeFinish, timeToGoSec, timeToGoMin, timeLeft;
|
||||
for (let curSequenceNumber = 0; curSequenceNumber <= maxSequenceNumber; curSequenceNumber++) {
|
||||
|
@ -305,65 +306,72 @@ export async function syncSuppliers(){
|
|||
}
|
||||
catch (err) {
|
||||
spinner.fail();
|
||||
throw(err);
|
||||
throw new Error(err);
|
||||
}
|
||||
}
|
||||
|
||||
export async function syncConnections(){
|
||||
let connections = await models.connection.findAll();
|
||||
|
||||
let headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${await getJWT()}`,
|
||||
'X-Api-Key': process.env.API_KEY
|
||||
};
|
||||
|
||||
let remoteConnections = await fetch(`${url}/connections`, {
|
||||
method: 'GET',
|
||||
headers
|
||||
});
|
||||
|
||||
remoteConnections = await remoteConnections.json();
|
||||
|
||||
for (let connection of connections){
|
||||
if (connection.isConnected == false){
|
||||
continue;
|
||||
}
|
||||
let remoteConnection = remoteConnections.find(remoteConnection => remoteConnection == connection.organizationId);
|
||||
|
||||
if (remoteConnection == undefined){
|
||||
console.log('Connection: ', connection, 'does not exist in the remote server');
|
||||
console.log('Creating remote connection');
|
||||
await fetch(`${url}/connections/${connection.organizationId}`, {
|
||||
method: 'PUT',
|
||||
headers
|
||||
});
|
||||
await models.connection.update({ isConnected: true }, {
|
||||
where: {
|
||||
organizationId: connection.organizationId
|
||||
}
|
||||
});
|
||||
await models.supplier.update({ isConnected: true }, {
|
||||
where: {
|
||||
organizationId: connection.organizationId
|
||||
}
|
||||
});
|
||||
} else {
|
||||
console.log('Connection: ', connection, 'exists in the remote server');
|
||||
await models.connection.update({ isConnected: true }, {
|
||||
where: {
|
||||
organizationId: connection.organizationId
|
||||
}
|
||||
});
|
||||
await models.supplier.update({ isConnected: true }, {
|
||||
where: {
|
||||
organizationId: connection.organizationId
|
||||
}
|
||||
});
|
||||
export async function syncConn(){
|
||||
const spinner = ora(`Syncing connections...`).start();
|
||||
try {
|
||||
let connections = await models.connection.findAll();
|
||||
|
||||
let headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${await getCurrentToken()}`,
|
||||
'X-Api-Key': process.env.API_KEY
|
||||
};
|
||||
|
||||
let remoteConnections = await fetch(`${url}/connections`, {
|
||||
method: 'GET',
|
||||
headers
|
||||
});
|
||||
|
||||
remoteConnections = await remoteConnections.json();
|
||||
|
||||
let i = 1;
|
||||
for (let connection of connections){
|
||||
spinner.text = `Syncing ${i++} connections...`
|
||||
if (connection.isConnected == false){
|
||||
continue;
|
||||
}
|
||||
let remoteConnection = remoteConnections.find(remoteConnection => remoteConnection == connection.organizationId);
|
||||
|
||||
if (remoteConnection == undefined){
|
||||
console.log('Connection: ', connection, 'does not exist in the remote server');
|
||||
console.log('Creating remote connection');
|
||||
await fetch(`${url}/connections/${connection.organizationId}`, {
|
||||
method: 'PUT',
|
||||
headers
|
||||
});
|
||||
await models.connection.update({ isConnected: true }, {
|
||||
where: {
|
||||
organizationId: connection.organizationId
|
||||
}
|
||||
});
|
||||
await models.supplier.update({ isConnected: true }, {
|
||||
where: {
|
||||
organizationId: connection.organizationId
|
||||
}
|
||||
});
|
||||
} else {
|
||||
await models.connection.update({ isConnected: true }, {
|
||||
where: {
|
||||
organizationId: connection.organizationId
|
||||
}
|
||||
});
|
||||
await models.supplier.update({ isConnected: true }, {
|
||||
where: {
|
||||
organizationId: connection.organizationId
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
}
|
||||
spinner.succeed();
|
||||
} catch (err) {
|
||||
spinner.fail();
|
||||
throw new Error(err);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export async function syncTradeItems(){
|
||||
|
@ -378,7 +386,7 @@ export async function syncTradeItems(){
|
|||
let query = `${url}/trade-items?supplierOrganizationId=${supplier.organizationId}`;
|
||||
let headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${await getJWT()}`,
|
||||
'Authorization': `Bearer ${await getCurrentToken()}`,
|
||||
'X-Api-Key': process.env.API_KEY
|
||||
};
|
||||
try {
|
||||
|
@ -391,7 +399,6 @@ export async function syncTradeItems(){
|
|||
let tradeItems = await request.json();
|
||||
|
||||
if (!tradeItems.length) {
|
||||
console.log('No trade items for supplier: ', supplier.commercialName);
|
||||
continue;
|
||||
}
|
||||
|
||||
|
@ -419,164 +426,167 @@ export async function syncTradeItems(){
|
|||
* to do this, it fetches all the supply lines for every tradeitem of the suppliers
|
||||
*/
|
||||
export async function syncSupplyLines(){
|
||||
|
||||
let currentSequenceNumber = await models.sequenceNumber.findOne({
|
||||
where: {
|
||||
model: 'supplyLines'
|
||||
}
|
||||
});
|
||||
|
||||
const spinner = ora(`Syncing trade items...`).start();
|
||||
let suppliers = await models.supplier.findAll({
|
||||
where: {
|
||||
isConnected: true
|
||||
}
|
||||
});
|
||||
|
||||
let tradeItems = await models.tradeItem.findAll({
|
||||
where: {
|
||||
supplierOrganizationId: suppliers.map(supplier => supplier.organizationId)
|
||||
}
|
||||
});
|
||||
|
||||
let promises = [];
|
||||
|
||||
let headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${await getJWT()}`,
|
||||
'X-Api-Key': process.env.API_KEY
|
||||
};
|
||||
|
||||
// Launch a promise for each supplier
|
||||
for (let tradeItem of tradeItems) {
|
||||
let supplier = suppliers.find(supplier => supplier.organizationId == tradeItem.supplierOrganizationId);
|
||||
console.log('Requesting supply lines for ' + supplier.commercialName + ' - ' + tradeItem.name);
|
||||
// eslint-disable-next-line no-async-promise-executor
|
||||
let promise = new Promise(async (resolve) => {
|
||||
try {
|
||||
let url = `${url}/supply-lines/sync/0`
|
||||
const params = new URLSearchParams({
|
||||
supplierOrganizationId: supplier.organizationId,
|
||||
tradeItemId: tradeItem.tradeItemId,
|
||||
postFilterSelectedTradeItems: false
|
||||
});
|
||||
url.search = params;
|
||||
|
||||
let request = await fetch(url.toString(), {
|
||||
method: 'GET',
|
||||
headers
|
||||
});
|
||||
|
||||
let supplyLines = await request.json();
|
||||
|
||||
if (supplyLines.length == 0) {
|
||||
console.log('No supply lines for supplier: ', supplier.commercialName, ' - ' , tradeItem.name);
|
||||
resolve([]);
|
||||
return;
|
||||
}
|
||||
|
||||
resolve(supplyLines);
|
||||
|
||||
} catch (error) {
|
||||
console.log('Error while syncing supply lines for: ', supplier.commercialName, ' - ' , tradeItem.name);
|
||||
console.log(error);
|
||||
resolve([]);
|
||||
try {
|
||||
let currentSequenceNumber = await models.sequenceNumber.findOne({ // TODO: Mirar como manejar este error
|
||||
where: {
|
||||
model: 'supplyLines'
|
||||
}
|
||||
});
|
||||
|
||||
promises.push(promise);
|
||||
|
||||
}
|
||||
|
||||
let supplyLines = await Promise.all(promises);
|
||||
let maximumSequenceNumber;
|
||||
|
||||
for (let supplyLine of supplyLines) {
|
||||
maximumSequenceNumber = supplyLine.maximumSequenceNumber;
|
||||
supplyLine = supplyLine.results;
|
||||
try {
|
||||
for (let line of supplyLine) {
|
||||
|
||||
let tradeItem = await models.tradeItem.findOne({
|
||||
where: {
|
||||
tradeItemId: line.tradeItemId
|
||||
}
|
||||
});
|
||||
const spinner = ora(`Syncing trade items...`).start();
|
||||
let suppliers = await models.supplier.findAll({
|
||||
where: {
|
||||
isConnected: true
|
||||
}
|
||||
});
|
||||
|
||||
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 = `${url}/trade-items?tradeItemIds=${line.tradeItemId}`;
|
||||
|
||||
let queryTradeItem = await fetch(urlTradeItem, {
|
||||
let tradeItems = await models.tradeItem.findAll({
|
||||
where: {
|
||||
supplierOrganizationId: suppliers.map(supplier => supplier.organizationId)
|
||||
}
|
||||
});
|
||||
|
||||
let promises = [];
|
||||
|
||||
let headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${await getCurrentToken()}`,
|
||||
'X-Api-Key': process.env.API_KEY
|
||||
};
|
||||
|
||||
// Launch a promise for each supplier
|
||||
for (let tradeItem of tradeItems) {
|
||||
let supplier = suppliers.find(supplier => supplier.organizationId == tradeItem.supplierOrganizationId);
|
||||
console.log('Requesting supply lines for ' + supplier.commercialName + ' - ' + tradeItem.name);
|
||||
// eslint-disable-next-line no-async-promise-executor
|
||||
let promise = new Promise(async (resolve) => {
|
||||
try {
|
||||
let url = `${url}/supply-lines/sync/0`
|
||||
const params = new URLSearchParams({
|
||||
supplierOrganizationId: supplier.organizationId,
|
||||
tradeItemId: tradeItem.tradeItemId,
|
||||
postFilterSelectedTradeItems: false
|
||||
});
|
||||
url.search = params;
|
||||
|
||||
let request = await fetch(url.toString(), {
|
||||
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 supplyLines = await request.json();
|
||||
|
||||
if (supplyLines.length == 0) {
|
||||
console.log('No supply lines for supplier: ', supplier.commercialName, ' - ' , tradeItem.name);
|
||||
resolve([]);
|
||||
return;
|
||||
}
|
||||
|
||||
let supplier = await models.supplier.findOne({
|
||||
where: {
|
||||
organizationId: tradeItem[0].supplierOrganizationId
|
||||
}
|
||||
});
|
||||
|
||||
await insertItem(tradeItem[0], supplier);
|
||||
|
||||
tradeItem = await models.tradeItem.findOne({
|
||||
|
||||
resolve(supplyLines);
|
||||
|
||||
} catch (error) {
|
||||
console.log('Error while syncing supply lines for: ', supplier.commercialName, ' - ' , tradeItem.name);
|
||||
console.log(error);
|
||||
resolve([]);
|
||||
}
|
||||
});
|
||||
|
||||
promises.push(promise);
|
||||
|
||||
}
|
||||
|
||||
let supplyLines = await Promise.all(promises);
|
||||
let maximumSequenceNumber;
|
||||
|
||||
for (let supplyLine of supplyLines) {
|
||||
maximumSequenceNumber = supplyLine.maximumSequenceNumber;
|
||||
supplyLine = supplyLine.results;
|
||||
try {
|
||||
for (let line of supplyLine) {
|
||||
|
||||
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('Trade item id: ', line.tradeItemId);
|
||||
continue;
|
||||
console.log('Requesting data for trade item id: ', line.tradeItemId);
|
||||
|
||||
let urlTradeItem = `${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: {
|
||||
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: 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,
|
||||
});
|
||||
|
||||
|
||||
}
|
||||
|
||||
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) {
|
||||
spinner.fail();
|
||||
console.log('Error while syncing supply lines - ' + supplyLine.results[0].tradeItemId);
|
||||
throw new Error(err);
|
||||
}
|
||||
} catch (error) {
|
||||
spinner.fail();
|
||||
console.log('Error while syncing supply lines - ' + supplyLine.results[0].tradeItemId);
|
||||
console.log(error);
|
||||
}
|
||||
spinner.succeed();
|
||||
console.log('Found', suppliers.length, 'connected suppliers');
|
||||
|
||||
await syncSequence(currentSequenceNumber,'supplyLines' ,maximumSequenceNumber);
|
||||
} catch (err) {
|
||||
throw new Error(err);
|
||||
}
|
||||
spinner.succeed();
|
||||
console.log('Found', suppliers.length, 'connected suppliers');
|
||||
|
||||
await syncSequence(currentSequenceNumber,'supplyLines' ,maximumSequenceNumber);
|
||||
}
|
||||
|
||||
export async function insertItem(tradeItem, supplier) {
|
||||
|
|
Loading…
Reference in New Issue