currently gets all the tradeitems from arcadia and inserts them

This commit is contained in:
Pau 2023-01-10 13:24:43 +01:00
parent 82b6fba8f8
commit 8500175cef
7 changed files with 163 additions and 16 deletions

View File

@ -1,24 +1,27 @@
import moment from 'moment';
import { getClientToken } from './utils.js';
import * as vnUtils from './utils.js';
import dotenv from 'dotenv';
dotenv.config();
import models from './models/index.js';
let tokenExpirationDate = await getClientToken(models);
let tokenExpirationDate = await vnUtils.getClientToken(models);
try {
setInterval(async () => {
console.log('Querying the API to check for new data...');
vnUtils.getTradeitems(8714231154815);
console.log('Current token expiration date: ', tokenExpirationDate);
if (moment().isAfter(tokenExpirationDate)) {
console.log('Token expired, getting a new one...');
tokenExpirationDate = await getClientToken(models);
tokenExpirationDate = await vnUtils.getClientToken(models);
}
}, process.env.STATUS == 'development' ? 2500 : 5000);
}, process.env.STATUS == 'development' ? 10000 : 20000);
} catch (error) {
console.error('Unable to connect to the database:', error);
}

View File

@ -13,7 +13,7 @@ const clientConfig = {
type: Sequelize.STRING,
},
currentToken: {
type: Sequelize.STRING,
type: Sequelize.STRING(5000),
},
tokenExpiration: {
type: Sequelize.STRING,

View File

@ -12,7 +12,7 @@ import additionalPricePerPiece from './additionalPricePerPiece.js';
import botanicalNames from './botanicalNames.js';
import countryOfOriginIsoCodes from './countryOfOriginIsoCodes.js';
import packageModel from './package.js';
import packagingConfigurations from './packagingConfigurations.js';
import packingConfigurations from './packingConfigurations.js';
import photos from './photos.js';
import seasonalPeriod from './seasonalPeriod.js';
import tradeItem from './tradeItem.js';
@ -24,7 +24,7 @@ let models = {
botanicalNames: botanicalNames(sequelize),
countryOfOriginIsoCodes: countryOfOriginIsoCodes(sequelize),
package: packageModel(sequelize),
packagingConfigurations: packagingConfigurations(sequelize),
packingConfigurations: packingConfigurations(sequelize),
photos: photos(sequelize),
seasonalPeriod: seasonalPeriod(sequelize),
tradeItem: tradeItem(sequelize),
@ -35,12 +35,13 @@ let models = {
if (process.env.FORCE_SYNC === 'true') {
console.log('Syncing the models...');
await sequelize.sync({ force: true });
}
if (process.env.SECRETS === 'true') {
await models.clientConfig.create({
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
});
}
export default models;

View File

@ -7,7 +7,8 @@ const tradeItem = {
autoIncrement: true,
},
tradeItemId: {
type: Sequelize.UUID
type: Sequelize.UUID,
unique: true,
},
supplierOrganizationId: {
type: Sequelize.UUID

View File

@ -4,7 +4,9 @@
"type": "module",
"scripts": {
"start": "node index.js",
"dev-sync": "FORCE_SYNC=true node index.js"
"dev-sync": "FORCE_SYNC=true node index.js",
"dev-secrets": "SECRETS=true node index.js",
"dev-both": "FORCE_SYNC=true SECRETS=true node index.js"
},
"dependencies": {
"dotenv": "^16.0.3",

152
utils.js
View File

@ -1,5 +1,8 @@
import moment from 'moment';
import fetch from 'node-fetch';
import dotenv from 'dotenv';
import models from './models/index.js';
dotenv.config();
/**
* The Endpoint where the Access Token is requested
*/
@ -11,7 +14,7 @@ const _accessTokenEndpoint = 'https://idm.staging.floriday.io/oauth2/ausmw6b47z1
* @param {sequelize.models} models
* @returns {Date} tokenExpirationDate formated as YYYY-MM-DD HH:mm:ss
*/
async function getClientToken(models) {
async function getClientToken() {
const clientConfigData = await models.clientConfig.findAll();
const now = moment().format('YYYY-MM-DD HH:mm:ss');
@ -46,8 +49,7 @@ async function getClientToken(models) {
.add(tokenResponse.expires_in, 's')
.format('YYYY-MM-DD HH:mm:ss');
updateClientConfig(
models,
await updateClientConfig(
clientId,
clientSecret,
accessToken,
@ -61,7 +63,6 @@ async function getClientToken(models) {
}
}
/**
* Updates the Access Token in the client config table
*
@ -71,7 +72,7 @@ async function getClientToken(models) {
* @param {String} accessToken
* @param {String} tokenExpirationDate
*/
async function updateClientConfig(models, clientId, clientSecret, accessToken, tokenExpirationDate) {
async function updateClientConfig(clientId, clientSecret, accessToken, tokenExpirationDate) {
try {
console.log('Updating the client config with the new token...');
await models.clientConfig.update(
@ -95,4 +96,143 @@ async function updateClientConfig(models, clientId, clientSecret, accessToken, t
}
}
export { getClientToken, updateClientConfig };
/**
* returns the current Access Token
*
* @returns
*/
async function getJWT() {
const clientConfigData = await models.clientConfig.findAll();
return clientConfigData[0].currentToken;
}
async function getTradeitems(organizationGln) {
const headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + await getJWT(),
'X-Api-Key': process.env.API_KEY,
};
const BASE_CUSTOMER_URL = 'https://api.staging.floriday.io/customers-api/2022v2/';
//const BASE_SUPPLIER_URL = 'https://api.staging.floriday.io/suppliers-api/2022v2/';
// Get the organization id from the organizationGln
const organizationsUrl = `${BASE_CUSTOMER_URL}organizations/gln/${organizationGln}`;
const organizationsRequest = await fetch(organizationsUrl, {
method: 'GET',
headers: headers,
});
const organizationsResponse = await organizationsRequest.json();
const organizationId = organizationsResponse.organizationId;
// Get the tradeitems from the organization
const tradeitemsUrl = `${BASE_CUSTOMER_URL}trade-items?supplierOrganizationId=${organizationId}`;
const tradeitemsRequest = await fetch(tradeitemsUrl, {
method: 'GET',
headers: headers,
});
const tradeitemsResponse = await tradeitemsRequest.json();
tradeitemsResponse.forEach(async item => {
try{
models.tradeItem.upsert({
tradeItemId: item.tradeItemId,
supplierOrganizationId: item.supplierOrganizationId,
code: item.code,
gtin: item.gtin,
vbnProductCode: item.vbnProductCode,
name: item.name,
isDeleted: item.isDeleted,
sequenceNumber: item.sequenceNumber,
tradeItemVersion: item.tradeItemVersion,
isCustomerSpecific: item.isCustomerSpecific,
isHiddenInCatalog: item.isHiddenInCatalog,
});
item.characteristics.forEach((characteristic) => {
models.characteristics.upsert({
tradeItemFk: item.tradeItemId,
vnbCode: characteristic.vnbCode,
vnbValueCode: characteristic.vnbValueCode,
});
});
item.seasonalPeriods.forEach((seasonalPeriod) => {
models.seasonalPeriod.upsert({
tradeItemFk: item.tradeItemId,
startWeek: seasonalPeriod.startWeek,
endWeek: seasonalPeriod.endWeek,
});
});
item.photos.forEach((photo) => {
models.photos.upsert({
tradeItemFk: item.tradeItemId,
photoId: photo.id,
url: photo.url,
seasonalPeriodFk: photo.seasonalPeriod,
type: photo.type,
primary: photo.primary,
});
});
item.packingConfigurations.forEach( async (packagingConfiguration) => {
let createdPackingConfig = await models.packingConfigurations.upsert({
tradeItemFk: item.tradeItemId,
piecesPerPackage: packagingConfiguration.piecesPerPackage,
bunchesPerPackage: packagingConfiguration.bunchesPerPackage,
photoUrl: packagingConfiguration.photoUrl,
packagesPerLayer: packagingConfiguration.packagesPerLayer,
layersPerLoadCarrier: packagingConfiguration.layersPerLoadCarrier,
transportHeightInCm: packagingConfiguration.transportHeightInCm,
loadCarrierType: packagingConfiguration.loadCarrierType,
isPrimary: packagingConfiguration.isPrimary,
});
if (createdPackingConfig.isNewRecord) {
models.package.upsert({
packingConfigurationsFk: createdPackingConfig[0].id,
vbnPackageCode: packagingConfiguration.package.vbnPackageCode,
vbnPackageValueCode: packagingConfiguration.package.vbnPackageValueCode,
});
models.additionalPricePerPiece.upsert({
packingConfigurationsFk: createdPackingConfig.dataValues.id,
currency: packagingConfiguration.additionalPricePerPiece.currency,
value: packagingConfiguration.additionalPricePerPiece.value,
});
}
});
item.botanicalNames.forEach((botanicalName) => {
models.botanicalNames.upsert({
tradeItemFk: item.tradeItemId,
name: botanicalName,
});
});
item.countryOfOriginIsoCodes.forEach((countryOfOriginIsoCode) => {
models.countryOfOriginIsoCodes.upsert({
tradeItemFk: item.tradeItemId,
isoCode: countryOfOriginIsoCode,
});
});
} catch (error) {
console.log('There was an error while saving the data to the database');
console.log(error);
}
});
}
export { getClientToken, updateClientConfig, getJWT, getTradeitems };