refs #4823 Added new env DB_TIMEZONE, and bugs fix

This commit is contained in:
Guillermo Bonet 2023-05-11 14:36:55 +02:00
parent 4a264cf147
commit 8fc7660183
5 changed files with 108 additions and 41 deletions

View File

@ -43,6 +43,7 @@ DB_HOST = localhost
DB_DIALECT = mariadb DB_DIALECT = mariadb
DB_TIMEOUT_RECONECT = 30000 DB_TIMEOUT_RECONECT = 30000
DB_MAX_CONN_POOL = 40 DB_MAX_CONN_POOL = 40
DB_TIMEZONE = Europe/Madrid
#GENERAL CONFIG #GENERAL CONFIG
IS_PRODUCTION = false IS_PRODUCTION = false

View File

@ -18,7 +18,6 @@ class Floriday {
} catch (err) { } catch (err) {
utils.criticalError(err); utils.criticalError(err);
} }
await this.schedule();
} }
async tryConn() { async tryConn() {
@ -54,10 +53,8 @@ class Floriday {
async trunk() { async trunk() {
try{ try{
if (moment().isAfter(await utils.getCurrentTokenExpiration())) { //await utils.syncSupplyLines();
this.tokenExpirationDate = await utils.requestToken(models); await utils.newSyncSupplyLines();
}
await utils.syncSupplyLines();
// Continuar con todo lo que haga falta realizar en la rutina // Continuar con todo lo que haga falta realizar en la rutina
@ -67,8 +64,9 @@ class Floriday {
} }
async stop() { async stop() {
await utils.deleteConnections();
await closeConn(); await closeConn();
console.log(chalk.dim('Bye, come back soon 👋')) console.warn(chalk.dim('Bye, come back soon 👋'))
} }
} }

View File

@ -20,7 +20,7 @@ console.log(chalk.hex('#06c581')(
let sequelize, conSpinner let sequelize, conSpinner
try { try {
conSpinner = ora('Creating connection...').start(); conSpinner = ora('Creating database connection...').start();
sequelize = createConn(); sequelize = createConn();
await checkConn(); await checkConn();
conSpinner.succeed(); conSpinner.succeed();
@ -207,6 +207,7 @@ function createConn() {
acquire: 60000, acquire: 60000,
idle: 10000, idle: 10000,
}, },
timezone: env.DB_TIMEZONE,
}); });
} }
@ -222,10 +223,10 @@ async function checkConn() {
} }
/** /**
* Close connection * Close the connection to the database
*/ */
async function closeConn() { async function closeConn() {
const spinner = ora('Stopping connection...').start(); const spinner = ora('Closing database connection...').start();
try { try {
await sequelize.close() await sequelize.close()
spinner.succeed(); spinner.succeed();

View File

@ -6,10 +6,6 @@ const connections = {
primaryKey: true, primaryKey: true,
allowNull: false, allowNull: false,
}, },
connect: {
type: Sequelize.BOOLEAN,
defaultValue: false,
},
}; };
export default (sequelize) => { export default (sequelize) => {

127
utils.js
View File

@ -14,10 +14,8 @@ const env = process.env;
* @returns {Date} tokenExpirationDate formated as YYYY-MM-DD HH:mm:ss * @returns {Date} tokenExpirationDate formated as YYYY-MM-DD HH:mm:ss
*/ */
export async function requestToken() { export async function requestToken() {
let spinner; let spinner = ora(`Requesting new token...`).start();
try { try {
spinner = ora(`Requesting new token...`).start();
const clientConfigData = await models.clientConfig.findOne(); const clientConfigData = await models.clientConfig.findOne();
let tokenExpirationDate, token; let tokenExpirationDate, token;
@ -91,8 +89,10 @@ export async function requestToken() {
* @returns {string} * @returns {string}
*/ */
export async function getCurrentToken() { export async function getCurrentToken() {
let data = await models.clientConfig.findOne(); if (moment().isAfter(await getCurrentTokenExpiration()))
return data.currentToken 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} * @returns {string}
*/ */
export async function getCurrentTokenExpiration() { export async function getCurrentTokenExpiration() {
let data = await models.clientConfig.findOne(); return (await models.clientConfig.findOne()).tokenExpiration;
return data.tokenExpiration
} }
/** /**
* Updates the Access Token in the client config table * Updates the access token in the client config table
* *
* @param {String} clientId * @param {String} clientId
* @param {String} clientSecret * @param {String} clientSecret
* @param {String} accessToken * @param {String} accessToken
* @param {String} tokenExpirationDate * @param {String} tokenExpirationDate
*/ */
export async function updateClientConfig(clientId, clientSecret, accessToken, tokenExpirationDate) { export async function updateClientConfig(clientId, clientSecret, currentToken, tokenExpiration) {
try { try {
const spinner = ora(`Updating token...`).start(); const spinner = ora(`Updating token...`).start();
if (!JSON.parse(process.env.USE_SECRETS_DB)) if (!JSON.parse(process.env.USE_SECRETS_DB))
@ -144,16 +143,15 @@ export async function updateClientConfig(clientId, clientSecret, accessToken, to
await models.clientConfig.upsert({ await models.clientConfig.upsert({
id: 1, id: 1,
clientId: clientId, clientId,
clientSecret: clientSecret, clientSecret,
currentToken: accessToken, currentToken,
tokenExpiration: tokenExpirationDate tokenExpiration,
}); });
spinner.succeed(); spinner.succeed();
} catch (error) { } catch (err) {
spinner.fail(); spinner.fail();
console.log('There was a error while updating the client config'); throw(err);
console.log(error);
} }
} }
@ -335,7 +333,7 @@ export async function syncSuppliers(){
} }
export async function syncConn(){ export async function syncConn(){
const spinner = ora(`Syncing connections...`).start(); const spinner = ora(`Creating connections...`).start();
try { try {
let connections = await models.connection.findAll(); let connections = await models.connection.findAll();
@ -349,14 +347,10 @@ export async function syncConn(){
let i = 1; let i = 1;
for (let connection of connections){ for (let connection of connections){
spinner.text = `Syncing ${i++} connections...` spinner.text = `Creating ${i++} connections...`
if (connection.isConnected == false)
continue;
let remoteConnection = remoteConnections.data.find(remoteConnection => remoteConnection == connection.supplierOrganizationId); let remoteConnection = remoteConnections.data.find(remoteConnection => remoteConnection == connection.supplierOrganizationId);
if (!remoteConnection){ 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 axios.put(`${env.API_URL}/connections/${connection.supplierOrganizationId}`, null, { headers });
await models.connection.update({ isConnected: true }, { await models.connection.update({ isConnected: true }, {
where: { where: {
@ -453,13 +447,12 @@ export async function syncSupplyLines(){
// eslint-disable-next-line no-async-promise-executor // 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`
const params = new URLSearchParams({ const params = new URLSearchParams({
supplierOrganizationId: supplier.supplierOrganizationId, supplierOrganizationId: supplier.supplierOrganizationId,
tradeItemId: tradeItem.tradeItemId, tradeItemId: tradeItem.tradeItemId,
postFilterSelectedTradeItems: false postFilterSelectedTradeItems: false
}); }).toString();
let request = await axios.get(`${url}?${params.toString()}`, { headers }); let request = await axios.get(`${`${env.API_URL}/supply-lines`}?${params}`, { headers });
if (request.status == 429) { // Too many request if (request.status == 429) { // Too many request
resolve([]); 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 * Insert the trade item
* *
@ -588,7 +627,6 @@ export async function insertItem(tradeItem) {
// Upsert supplier connection // Upsert supplier connection
await models.connection.upsert({ await models.connection.upsert({
supplierOrganizationId: tradeItem.supplierOrganizationId, supplierOrganizationId: tradeItem.supplierOrganizationId,
connect: true,
}, { transaction: tx }); }, { transaction: tx });
// Upsert trade item // 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} * @param {err}
**/ **/
export async function criticalError(err) { export async function criticalError(err) {
console.log(chalk.red.bold(`[CRITICAL]`), chalk.red(`${err.message}`)); console.log(chalk.red.bold(`[CRITICAL]`), chalk.red(`${err.message}`));
process.exit(); process.exit();
}
/**
* Warning
*
* @param {err}
**/
export async function warning(err) {
console.log(chalk.yellow.bold(`[WARNING]`), chalk.yellow(`${err.message}`));
} }