diff --git a/README.md b/README.md index 69c3657..bf7eb85 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,7 @@ DB_HOST = localhost DB_DIALECT = mariadb DB_TIMEOUT_RECONECT = 30000 DB_MAX_CONN_POOL = 40 +DB_TIMEZONE = Europe/Madrid #GENERAL CONFIG IS_PRODUCTION = false diff --git a/floriday.js b/floriday.js index 4c99a64..dd95689 100644 --- a/floriday.js +++ b/floriday.js @@ -18,7 +18,6 @@ class Floriday { } catch (err) { utils.criticalError(err); } - await this.schedule(); } async tryConn() { @@ -54,10 +53,8 @@ class Floriday { async trunk() { try{ - if (moment().isAfter(await utils.getCurrentTokenExpiration())) { - this.tokenExpirationDate = await utils.requestToken(models); - } - await utils.syncSupplyLines(); + //await utils.syncSupplyLines(); + await utils.newSyncSupplyLines(); // Continuar con todo lo que haga falta realizar en la rutina @@ -67,8 +64,9 @@ class Floriday { } async stop() { + await utils.deleteConnections(); await closeConn(); - console.log(chalk.dim('Bye, come back soon 👋')) + console.warn(chalk.dim('Bye, come back soon 👋')) } } diff --git a/models/sequelize.js b/models/sequelize.js index d216d9b..13cf5bb 100644 --- a/models/sequelize.js +++ b/models/sequelize.js @@ -20,7 +20,7 @@ console.log(chalk.hex('#06c581')( let sequelize, conSpinner try { - conSpinner = ora('Creating connection...').start(); + conSpinner = ora('Creating database connection...').start(); sequelize = createConn(); await checkConn(); conSpinner.succeed(); @@ -207,6 +207,7 @@ function createConn() { acquire: 60000, idle: 10000, }, + timezone: env.DB_TIMEZONE, }); } @@ -222,10 +223,10 @@ async function checkConn() { } /** - * Close connection + * Close the connection to the database */ async function closeConn() { - const spinner = ora('Stopping connection...').start(); + const spinner = ora('Closing database connection...').start(); try { await sequelize.close() spinner.succeed(); diff --git a/models/supplier/connections.js b/models/supplier/connections.js index 51cbfc6..936d9f8 100644 --- a/models/supplier/connections.js +++ b/models/supplier/connections.js @@ -6,10 +6,6 @@ const connections = { primaryKey: true, allowNull: false, }, - connect: { - type: Sequelize.BOOLEAN, - defaultValue: false, - }, }; export default (sequelize) => { diff --git a/utils.js b/utils.js index 25207b8..85f6e43 100644 --- a/utils.js +++ b/utils.js @@ -14,10 +14,8 @@ const env = process.env; * @returns {Date} tokenExpirationDate formated as YYYY-MM-DD HH:mm:ss */ export async function requestToken() { - let spinner; + let spinner = ora(`Requesting new token...`).start(); try { - spinner = ora(`Requesting new token...`).start(); - const clientConfigData = await models.clientConfig.findOne(); let tokenExpirationDate, token; @@ -91,8 +89,10 @@ export async function requestToken() { * @returns {string} */ export async function getCurrentToken() { - let data = await models.clientConfig.findOne(); - return data.currentToken + if (moment().isAfter(await getCurrentTokenExpiration())) + return await requestToken(models); + else + return (await models.clientConfig.findOne()).currentToken; } /** @@ -119,24 +119,23 @@ export async function checkConfig() { } /** - * Returns the expiration data of current token + * Returns the expiration of current token * * @returns {string} */ export async function getCurrentTokenExpiration() { - let data = await models.clientConfig.findOne(); - return data.tokenExpiration + return (await models.clientConfig.findOne()).tokenExpiration; } /** - * Updates the Access Token in the client config table + * Updates the access token in the client config table * * @param {String} clientId * @param {String} clientSecret * @param {String} accessToken * @param {String} tokenExpirationDate */ -export async function updateClientConfig(clientId, clientSecret, accessToken, tokenExpirationDate) { +export async function updateClientConfig(clientId, clientSecret, currentToken, tokenExpiration) { try { const spinner = ora(`Updating token...`).start(); if (!JSON.parse(process.env.USE_SECRETS_DB)) @@ -144,16 +143,15 @@ export async function updateClientConfig(clientId, clientSecret, accessToken, to await models.clientConfig.upsert({ id: 1, - clientId: clientId, - clientSecret: clientSecret, - currentToken: accessToken, - tokenExpiration: tokenExpirationDate + clientId, + clientSecret, + currentToken, + tokenExpiration, }); spinner.succeed(); - } catch (error) { + } catch (err) { spinner.fail(); - console.log('There was a error while updating the client config'); - console.log(error); + throw(err); } } @@ -335,7 +333,7 @@ export async function syncSuppliers(){ } export async function syncConn(){ - const spinner = ora(`Syncing connections...`).start(); + const spinner = ora(`Creating connections...`).start(); try { let connections = await models.connection.findAll(); @@ -349,14 +347,10 @@ export async function syncConn(){ let i = 1; for (let connection of connections){ - spinner.text = `Syncing ${i++} connections...` - if (connection.isConnected == false) - continue; + spinner.text = `Creating ${i++} connections...` let remoteConnection = remoteConnections.data.find(remoteConnection => remoteConnection == connection.supplierOrganizationId); if (!remoteConnection){ - console.log('Connection: ', connection.supplierOrganizationId, 'does not exist in the remote server'); - console.log('Creating remote connection'); await axios.put(`${env.API_URL}/connections/${connection.supplierOrganizationId}`, null, { headers }); await models.connection.update({ isConnected: true }, { where: { @@ -453,13 +447,12 @@ export async function syncSupplyLines(){ // eslint-disable-next-line no-async-promise-executor let promise = new Promise(async (resolve) => { try { - let url = `${env.API_URL}/supply-lines/sync/0` const params = new URLSearchParams({ supplierOrganizationId: supplier.supplierOrganizationId, tradeItemId: tradeItem.tradeItemId, postFilterSelectedTradeItems: false - }); - let request = await axios.get(`${url}?${params.toString()}`, { headers }); + }).toString(); + let request = await axios.get(`${`${env.API_URL}/supply-lines`}?${params}`, { headers }); if (request.status == 429) { // Too many request resolve([]); @@ -575,6 +568,52 @@ export async function syncSupplyLines(){ } } +export async function newSyncSupplyLines() { + try { + let headers = { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${await getCurrentToken()}`, + 'X-Api-Key': process.env.API_KEY + }; + + let suppliersWithTradeItem = await models.tradeItem.findAll({ + attributes: ['supplierOrganizationId'], + group: ['supplierOrganizationId'] + }); + + let connectedSuppliers = await models.supplier.findAll({ + attributes: ['supplierOrganizationId'], + where: { isConnected: true } + }); + + let suppliers = suppliersWithTradeItem.filter(supplier => { + return connectedSuppliers.some(connectedSupplier => { + return connectedSupplier.supplierOrganizationId === supplier.supplierOrganizationId; + }); + }).map(supplier => supplier.supplierOrganizationId); + + for (let supplier of suppliers) { + const params = new URLSearchParams({ + supplierOrganizationId: supplier, + }).toString(); + let request = await axios.get(`${`${env.API_URL}/supply-lines`}?${params}`, { headers }); + + if (!request.data.length) + continue + + let supplyLines = request.data; + + for (let supplyLine of supplyLines) { + console.log(supplyLine) + } + } + console.log('Finalizado') + } + catch (err) { + throw err; + } +} + /** * Insert the trade item * @@ -588,7 +627,6 @@ export async function insertItem(tradeItem) { // Upsert supplier connection await models.connection.upsert({ supplierOrganizationId: tradeItem.supplierOrganizationId, - connect: true, }, { transaction: tx }); // Upsert trade item @@ -669,11 +707,44 @@ export async function insertItem(tradeItem) { } /** - * Throw critical error + * Deletes the connections in Floriday + **/ +export async function deleteConnections() { + const spinner = ora(`Deleting connections...`).start(); + try { + let i = 1; + let headers = { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${await getCurrentToken()}`, + 'X-Api-Key': process.env.API_KEY + }; + let connections = (await axios.get(`${env.API_URL}/connections`, { headers })).data; + for (let connection of connections) { + await axios.delete(`${env.API_URL}/connections/${connection}`, { headers }); + spinner.text = `Deleting ${i++} connections...` + } + spinner.succeed(); + } catch (err) { + spinner.fail(); + util.criticalError(err); + } +} + +/** + * Critical error * * @param {err} **/ export async function criticalError(err) { console.log(chalk.red.bold(`[CRITICAL]`), chalk.red(`${err.message}`)); process.exit(); +} + +/** + * Warning + * + * @param {err} + **/ +export async function warning(err) { + console.log(chalk.yellow.bold(`[WARNING]`), chalk.yellow(`${err.message}`)); } \ No newline at end of file