refs #4823 Used bulkCreate to insert all at once
This commit is contained in:
parent
6e2a304a69
commit
5a4ccb76fe
|
@ -1,14 +1,10 @@
|
||||||
import { checkCon, closeCon } from './models/sequelize.js';
|
import { checkCon, closeCon } from './models/sequelize.js';
|
||||||
import * as utils from './utils.js';
|
import * as utils from './utils.js';
|
||||||
import moment from 'moment';
|
|
||||||
import chalk from 'chalk';
|
import chalk from 'chalk';
|
||||||
|
|
||||||
const env = process.env;
|
const env = process.env;
|
||||||
|
|
||||||
if (JSON.parse(env.TIME_STAMPS)) // Add time to all console.log
|
class Floriday {
|
||||||
console.log = (...args) => console.info(chalk.gray(`[${new moment().format('YYYY-MM-DD hh:mm:ss A')}]`), ...args);
|
|
||||||
|
|
||||||
class Floriday {
|
|
||||||
async start() {
|
async start() {
|
||||||
try {
|
try {
|
||||||
await utils.checkConfig();
|
await utils.checkConfig();
|
||||||
|
@ -72,7 +68,7 @@ if (JSON.parse(env.TIME_STAMPS)) // Add time to all console.log
|
||||||
try {
|
try {
|
||||||
this.stopSchedule = false;
|
this.stopSchedule = false;
|
||||||
await closeCon();
|
await closeCon();
|
||||||
console.warn(chalk.dim('Bye, come back soon 👋'))
|
console.warn(chalk.dim('\nBye, come back soon 👋'))
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
utils.criticalError(err);
|
utils.criticalError(err);
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,12 +1,12 @@
|
||||||
import { Sequelize } from 'sequelize';
|
import { Sequelize } from 'sequelize';
|
||||||
import dotenv from 'dotenv';
|
import dotenv from 'dotenv';
|
||||||
import chalk from 'chalk';
|
import chalk from 'chalk';
|
||||||
import fs from 'fs';
|
|
||||||
import * as utils from '../utils.js';
|
import * as utils from '../utils.js';
|
||||||
|
|
||||||
dotenv.config();
|
dotenv.config();
|
||||||
const env = process.env;
|
const env = process.env;
|
||||||
let sequelize;
|
let sequelize;
|
||||||
|
|
||||||
console.clear()
|
console.clear()
|
||||||
console.log(chalk.hex('#06c581')(
|
console.log(chalk.hex('#06c581')(
|
||||||
`
|
`
|
||||||
|
@ -86,6 +86,7 @@ try {
|
||||||
onDelete: 'CASCADE',
|
onDelete: 'CASCADE',
|
||||||
onUpdate: 'CASCADE',
|
onUpdate: 'CASCADE',
|
||||||
*/
|
*/
|
||||||
|
/*
|
||||||
models.characteristic.belongsTo(models.tradeItem, {
|
models.characteristic.belongsTo(models.tradeItem, {
|
||||||
foreignKey: 'tradeItemId',
|
foreignKey: 'tradeItemId',
|
||||||
targetKey: 'tradeItemId',
|
targetKey: 'tradeItemId',
|
||||||
|
@ -142,7 +143,6 @@ try {
|
||||||
foreignKey: 'supplyLineId',
|
foreignKey: 'supplyLineId',
|
||||||
targetKey: 'supplyLineId',
|
targetKey: 'supplyLineId',
|
||||||
});
|
});
|
||||||
/*
|
|
||||||
models.warehouse.belongsTo(models.organization, {
|
models.warehouse.belongsTo(models.organization, {
|
||||||
foreignKey: 'organizationId',
|
foreignKey: 'organizationId',
|
||||||
targetKey: 'organizationId',
|
targetKey: 'organizationId',
|
||||||
|
@ -158,7 +158,8 @@ try {
|
||||||
models.clockPresaleSupply.belongsTo(models.organization, {
|
models.clockPresaleSupply.belongsTo(models.organization, {
|
||||||
foreignKey: 'organizationId',
|
foreignKey: 'organizationId',
|
||||||
targetKey: 'organizationId',
|
targetKey: 'organizationId',
|
||||||
});*/
|
});
|
||||||
|
*/
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
utils.criticalError(err);
|
utils.criticalError(err);
|
||||||
}
|
}
|
||||||
|
@ -169,11 +170,13 @@ try {
|
||||||
await utils.startSpin(`${actionMsg} models...`, true);
|
await utils.startSpin(`${actionMsg} models...`, true);
|
||||||
await sequelize.sync(action);
|
await sequelize.sync(action);
|
||||||
|
|
||||||
|
/*
|
||||||
// Create views
|
// Create views
|
||||||
sequelize.query(fs.readFileSync('routines/views/supplyOffer.sql', 'utf-8'));
|
sequelize.query(fs.readFileSync('routines/views/supplyOffer.sql', 'utf-8'));
|
||||||
|
|
||||||
// Create procedures
|
// Create procedures
|
||||||
sequelize.query(fs.readFileSync('routines/procedures/offerRefresh.sql', 'utf-8'));
|
sequelize.query(fs.readFileSync('routines/procedures/offerRefresh.sql', 'utf-8'));
|
||||||
|
*/
|
||||||
|
|
||||||
await utils.okSpin();
|
await utils.okSpin();
|
||||||
}
|
}
|
||||||
|
@ -216,7 +219,8 @@ async function checkCon() {
|
||||||
* Close the connection to the database
|
* Close the connection to the database
|
||||||
*/
|
*/
|
||||||
async function closeCon() {
|
async function closeCon() {
|
||||||
utils.startSpin('Closing database connection...', true);
|
await utils.failSpin(null, true);
|
||||||
|
await utils.startSpin('Closing database connection...', true);
|
||||||
try {
|
try {
|
||||||
await sequelize.close()
|
await sequelize.close()
|
||||||
await utils.okSpin();
|
await utils.okSpin();
|
||||||
|
|
366
utils.js
366
utils.js
|
@ -131,7 +131,7 @@ export async function sleep(ms) {
|
||||||
*/
|
*/
|
||||||
export async function syncModel(model) {
|
export async function syncModel(model) {
|
||||||
await startSpin(`Syncing ${model}...`, true);
|
await startSpin(`Syncing ${model}...`, true);
|
||||||
let i = 1;
|
let i = 0;
|
||||||
try {
|
try {
|
||||||
const dbSeqNum = await models.sequenceNumber.findOne({ where: { model } })
|
const dbSeqNum = await models.sequenceNumber.findOne({ where: { model } })
|
||||||
let curSeqNum = dbSeqNum?.maxSequenceNumber ?? 0;
|
let curSeqNum = dbSeqNum?.maxSequenceNumber ?? 0;
|
||||||
|
@ -166,43 +166,46 @@ export async function syncModel(model) {
|
||||||
for (curSeqNum; curSeqNum < maxSeqNum; curSeqNum++) {
|
for (curSeqNum; curSeqNum < maxSeqNum; curSeqNum++) {
|
||||||
let params, misSeqNum;
|
let params, misSeqNum;
|
||||||
if (model === 'organization')
|
if (model === 'organization')
|
||||||
params = new URLSearchParams({organizationType: 'SUPPLIER'}).toString();
|
params = new URLSearchParams({ organizationType: 'SUPPLIER'} ).toString();
|
||||||
else if (model === 'supplyLine')
|
else if (model === 'supplyLine' )
|
||||||
params = new URLSearchParams({postFilterSelectedTradeItems: false}).toString();
|
params = new URLSearchParams({ postFilterSelectedTradeItems: false }).toString();
|
||||||
|
else if (model === 'tradeItem')
|
||||||
|
params = new URLSearchParams({
|
||||||
|
postFilterSelectedTradeItems: false,
|
||||||
|
postFilterSelectedTradeItemPackingConfigurations: false,
|
||||||
|
}).toString();
|
||||||
|
|
||||||
const res = (await vnRequest('GET', `${syncUrl}${curSeqNum}${params ? `?${params}` : ''}`)).data;
|
const res = (await vnRequest('GET', `${syncUrl}${curSeqNum}${params ? `?${params}` : ''}`)).data;
|
||||||
curSeqNum = res.maximumSequenceNumber;
|
curSeqNum = res.maximumSequenceNumber;
|
||||||
const objects = res.results;
|
const objects = res.results;
|
||||||
misSeqNum = maxSeqNum - curSeqNum;
|
misSeqNum = maxSeqNum - curSeqNum;
|
||||||
txtSpin(`Syncing ${i - 1} ${model}, ${misSeqNum} missing...`);
|
txtSpin(`Syncing ${i} ${model}, ${misSeqNum} missing...`);
|
||||||
for (let object of objects) {
|
|
||||||
switch (model) {
|
switch (model) {
|
||||||
case 'organization':
|
case 'organization':
|
||||||
await insertOrganization(object);
|
await insertOrganizations(objects);
|
||||||
break;
|
break;
|
||||||
case 'warehouse':
|
case 'warehouse':
|
||||||
await insertWarehouse(object);
|
await insertWarehouses(objects);
|
||||||
break;
|
break;
|
||||||
case 'tradeItem':
|
case 'tradeItem':
|
||||||
await insertTradeItem(object);
|
await insertTradeItems(objects);
|
||||||
break;
|
break;
|
||||||
case 'supplyLine':
|
case 'supplyLine':
|
||||||
await insertSupplyLine(object);
|
await insertSupplyLines(objects);
|
||||||
break;
|
break;
|
||||||
case 'clockPresaleSupply':
|
case 'clockPresaleSupply':
|
||||||
await insertClockPresalesSupply(object);
|
await insertClockPresalesSupply(objects);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
throw new Error('Unsupported model');
|
throw new Error('Unsupported model');
|
||||||
}
|
}
|
||||||
|
|
||||||
txtSpin(`Syncing ${i++} ${model}, ${misSeqNum} missing...`);
|
txtSpin(`Syncing ${i = i + objects.length} ${model}, ${misSeqNum} missing...`);
|
||||||
};
|
|
||||||
|
|
||||||
await insertSequenceNumber(model, curSeqNum);
|
await insertSequenceNumber(model, curSeqNum);
|
||||||
}
|
}
|
||||||
await insertSequenceNumber(model, maxSeqNum);
|
await insertSequenceNumber(model, maxSeqNum);
|
||||||
txtSpin((i != 1)
|
txtSpin((i)
|
||||||
? `Syncing ${i} ${model}...`
|
? `Syncing ${i} ${model}...`
|
||||||
: `Syncing ${model}...`);
|
: `Syncing ${model}...`);
|
||||||
await okSpin(null, true);
|
await okSpin(null, true);
|
||||||
|
@ -279,89 +282,147 @@ export async function insertSequenceNumber(model, sequenceNumber) {
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Insert trade item and dependences in the database.
|
* Insert trade items and dependencies in the database.
|
||||||
*
|
*
|
||||||
* @param {Array} tradeItem An array containing the tradeItem data to be inserted
|
* @param {Array} tradeItems An array containing the trade item data to be inserted
|
||||||
*/
|
*/
|
||||||
export async function insertTradeItem(tradeItem) {
|
export async function insertTradeItems(tradeItems) {
|
||||||
const tx = await models.sequelize.transaction();
|
const tx = await models.sequelize.transaction();
|
||||||
try {
|
try {
|
||||||
// Upsert trade item
|
const tradeItemsData = tradeItems.map((tradeItem) => ({
|
||||||
await models.tradeItem.upsert({
|
|
||||||
...tradeItem,
|
...tradeItem,
|
||||||
organizationId: tradeItem.supplierOrganizationId,
|
organizationId: tradeItem.supplierOrganizationId,
|
||||||
lastSync: moment(),
|
lastSync: moment().format('YYYY-MM-DD HH:mm:ss'),
|
||||||
}, { transaction: tx });
|
}));
|
||||||
|
|
||||||
// Upsert characteristics
|
await models.tradeItem.bulkCreate(tradeItemsData, {
|
||||||
if (tradeItem.characteristics)
|
updateOnDuplicate: [
|
||||||
if (tradeItem.characteristics.length)
|
'tradeItemId',
|
||||||
for (const characteristic of tradeItem.characteristics) {
|
'code',
|
||||||
await models.characteristic.upsert({
|
'gtin',
|
||||||
|
'vbnProductCode',
|
||||||
|
'name',
|
||||||
|
'isDeleted',
|
||||||
|
'sequenceNumber',
|
||||||
|
'tradeItemVersion',
|
||||||
|
'isCustomerSpecific',
|
||||||
|
'isHiddenInCatalog',
|
||||||
|
'organizationId',
|
||||||
|
],
|
||||||
|
transaction: tx,
|
||||||
|
});
|
||||||
|
|
||||||
|
const characteristics = [];
|
||||||
|
const seasonalPeriods = [];
|
||||||
|
const photos = [];
|
||||||
|
const packingConfigurations = [];
|
||||||
|
const countryOfOriginIsoCodes = [];
|
||||||
|
const botanicalNames = [];
|
||||||
|
|
||||||
|
for (const tradeItem of tradeItemsData) {
|
||||||
|
if (tradeItem.characteristics?.length)
|
||||||
|
for (const characteristic of tradeItem.characteristics)
|
||||||
|
characteristics.push({
|
||||||
tradeItemId: tradeItem.tradeItemId,
|
tradeItemId: tradeItem.tradeItemId,
|
||||||
...characteristic,
|
...characteristic,
|
||||||
}, { transaction: tx });
|
});
|
||||||
}
|
|
||||||
// Upsert seasonal periods
|
if (tradeItem.seasonalPeriods?.length)
|
||||||
if (tradeItem.seasonalPeriods)
|
for (const seasonalPeriod of tradeItem.seasonalPeriods)
|
||||||
if (tradeItem.seasonalPeriods.length)
|
seasonalPeriods.push({
|
||||||
for (const seasonalPeriod of tradeItem.seasonalPeriods) {
|
|
||||||
await models.seasonalPeriod.upsert({
|
|
||||||
tradeItemId: tradeItem.tradeItemId,
|
tradeItemId: tradeItem.tradeItemId,
|
||||||
...seasonalPeriod,
|
...seasonalPeriod,
|
||||||
}, { transaction: tx });
|
});
|
||||||
}
|
|
||||||
|
|
||||||
// Upsert photos
|
if (tradeItem.photos?.length)
|
||||||
if (tradeItem.photos)
|
for (const photo of tradeItem.photos)
|
||||||
if (tradeItem.photos.length)
|
photos.push({
|
||||||
for (const photo of tradeItem.photos) {
|
|
||||||
await models.photo.upsert({
|
|
||||||
...photo,
|
...photo,
|
||||||
tradeItemId: tradeItem.tradeItemId,
|
tradeItemId: tradeItem.tradeItemId,
|
||||||
}, { transaction: tx });
|
});
|
||||||
}
|
|
||||||
|
|
||||||
// Upsert packing configurations
|
if (tradeItem.packingConfigurations?.length) {
|
||||||
if (tradeItem.packingConfigurations)
|
|
||||||
if (tradeItem.packingConfigurations.length)
|
|
||||||
for (const packingConfiguration of tradeItem.packingConfigurations) {
|
for (const packingConfiguration of tradeItem.packingConfigurations) {
|
||||||
const uuid = uuidv4();
|
const uuid = uuidv4();
|
||||||
|
|
||||||
await models.packingConfiguration.upsert({
|
packingConfigurations.push({
|
||||||
packingConfigurationId: uuid,
|
packingConfigurationId: uuid,
|
||||||
...packingConfiguration,
|
...packingConfiguration,
|
||||||
additionalPricePerPiece_currency: packingConfiguration.additionalPricePerPiece.currency,
|
additionalPricePerPiece_currency: packingConfiguration.additionalPricePerPiece.currency,
|
||||||
additionalPricePerPiece_value: packingConfiguration.additionalPricePerPiece.value,
|
additionalPricePerPiece_value: packingConfiguration.additionalPricePerPiece.value,
|
||||||
tradeItemId: tradeItem.tradeItemId,
|
tradeItemId: tradeItem.tradeItemId,
|
||||||
}, { transaction: tx });
|
});
|
||||||
|
|
||||||
await models.package.upsert({
|
models.package.upsert({
|
||||||
...packingConfiguration.package,
|
...packingConfiguration.package,
|
||||||
packingConfigurationId: uuid,
|
packingConfigurationId: uuid,
|
||||||
}, { transaction: tx });
|
}, { transaction: tx });
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Upsert country of origin ISO codes
|
if (tradeItem.countryOfOriginIsoCodes?.length)
|
||||||
if (tradeItem.countryOfOriginIsoCodes)
|
for (const isoCode of tradeItem.countryOfOriginIsoCodes)
|
||||||
if (tradeItem.countryOfOriginIsoCodes.length)
|
countryOfOriginIsoCodes.push({
|
||||||
for (const isoCode of tradeItem.countryOfOriginIsoCodes || []) {
|
|
||||||
await models.countryOfOriginIsoCode.upsert({
|
|
||||||
isoCode,
|
isoCode,
|
||||||
tradeItemId: tradeItem.tradeItemId,
|
tradeItemId: tradeItem.tradeItemId,
|
||||||
}, { transaction: tx });
|
});
|
||||||
}
|
|
||||||
|
|
||||||
// Upsert botanical names
|
if (tradeItem.botanicalNames?.length)
|
||||||
if (tradeItem.botanicalNames)
|
for (const botanicalName of tradeItem.botanicalNames)
|
||||||
if (tradeItem.botanicalNames.length)
|
botanicalNames.push({
|
||||||
for (const botanicalName of tradeItem.botanicalNames) {
|
|
||||||
await models.botanicalName.upsert({
|
|
||||||
botanicalNameId: uuidv4(),
|
botanicalNameId: uuidv4(),
|
||||||
name: botanicalName,
|
name: botanicalName,
|
||||||
tradeItemId: tradeItem.tradeItemId,
|
tradeItemId: tradeItem.tradeItemId,
|
||||||
}, { transaction: tx });
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (characteristics?.length)
|
||||||
|
await models.characteristic.bulkCreate(characteristics, {
|
||||||
|
updateOnDuplicate: ['tradeItemId', 'vbnCode', 'vbnValueCode'],
|
||||||
|
transaction: tx,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (seasonalPeriods?.length)
|
||||||
|
await models.seasonalPeriod.bulkCreate(seasonalPeriods, {
|
||||||
|
updateOnDuplicate: ['tradeItemId', 'startWeek', 'endWeek'],
|
||||||
|
transaction: tx,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (photos?.length)
|
||||||
|
await models.photo.bulkCreate(photos, {
|
||||||
|
updateOnDuplicate: ['tradeItemId', 'url', 'type', 'primary'],
|
||||||
|
transaction: tx,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (packingConfigurations?.length)
|
||||||
|
await models.packingConfiguration.bulkCreate(packingConfigurations, {
|
||||||
|
updateOnDuplicate: [
|
||||||
|
'packingConfigurationId',
|
||||||
|
'piecesPerPackage',
|
||||||
|
'bunchesPerPackage',
|
||||||
|
'photoUrl',
|
||||||
|
'packagesPerLayer',
|
||||||
|
'layersPerLoadCarrier',
|
||||||
|
'additionalPricePerPiece_currency',
|
||||||
|
'additionalPricePerPiece_value',
|
||||||
|
'transportHeightInCm',
|
||||||
|
'loadCarrierType',
|
||||||
|
'isPrimary',
|
||||||
|
],
|
||||||
|
transaction: tx,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (countryOfOriginIsoCodes?.length)
|
||||||
|
await models.countryOfOriginIsoCode.bulkCreate(countryOfOriginIsoCodes, {
|
||||||
|
updateOnDuplicate: ['tradeItemId', 'isoCode'],
|
||||||
|
transaction: tx,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (botanicalNames?.length)
|
||||||
|
await models.botanicalName.bulkCreate(botanicalNames, {
|
||||||
|
updateOnDuplicate: ['botanicalNameId', 'name', 'tradeItemId'],
|
||||||
|
transaction: tx,
|
||||||
|
});
|
||||||
|
|
||||||
await tx.commit();
|
await tx.commit();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
@ -373,17 +434,40 @@ export async function insertTradeItem(tradeItem) {
|
||||||
/**
|
/**
|
||||||
* Insert clock presales supply in the database.
|
* Insert clock presales supply in the database.
|
||||||
*
|
*
|
||||||
* @param {Array} clockPresaleSupply An array containing the clockPresaleSupply data to be inserted
|
* @param {Array} clockPresalesSupply An array containing the clockPresaleSupplies data to be inserted
|
||||||
*/
|
*/
|
||||||
export async function insertClockPresalesSupply(clockPresaleSupply) {
|
export async function insertClockPresalesSupply(clockPresalesSupply) {
|
||||||
const tx = await models.sequelize.transaction();
|
const tx = await models.sequelize.transaction();
|
||||||
try {
|
try {
|
||||||
await models.clockPresaleSupply.upsert({
|
const clockPresalesSupplyWithDefaults = clockPresalesSupply.map((clockPresaleSupply) => ({
|
||||||
...clockPresaleSupply,
|
...clockPresaleSupply,
|
||||||
pricePerPiece_currency: clockPresaleSupply.pricePerPiece.currency,
|
pricePerPiece_currency: clockPresaleSupply.pricePerPiece.currency,
|
||||||
pricePerPiece_value: clockPresaleSupply.pricePerPiece.value,
|
pricePerPiece_value: clockPresaleSupply.pricePerPiece.value,
|
||||||
organizationId: clockPresaleSupply.supplierOrganizationId,
|
organizationId: clockPresaleSupply.supplierOrganizationId,
|
||||||
}, { transaction: tx });
|
}));
|
||||||
|
|
||||||
|
await models.clockPresaleSupply.bulkCreate(clockPresalesSupplyWithDefaults, {
|
||||||
|
updateOnDuplicate: [
|
||||||
|
'supplyLineId',
|
||||||
|
'status',
|
||||||
|
'tradeItemId',
|
||||||
|
'pricePerPiece_currency',
|
||||||
|
'pricePerPiece_value',
|
||||||
|
'deliveryNoteReference',
|
||||||
|
'numberOfPieces',
|
||||||
|
'packingConfigurations',
|
||||||
|
'tradePeriod_startDateTime',
|
||||||
|
'tradePeriod_endDateTime',
|
||||||
|
'organizationId',
|
||||||
|
'tradeInstrument',
|
||||||
|
'salesChannel',
|
||||||
|
'sequenceNumber',
|
||||||
|
'creationDateTime',
|
||||||
|
'lastModifiedDateTime',
|
||||||
|
],
|
||||||
|
transaction: tx,
|
||||||
|
});
|
||||||
|
|
||||||
await tx.commit();
|
await tx.commit();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
await tx.rollback();
|
await tx.rollback();
|
||||||
|
@ -392,14 +476,14 @@ export async function insertClockPresalesSupply(clockPresaleSupply) {
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Insert warehouse in the database.
|
* Insert warehouses in the database.
|
||||||
*
|
*
|
||||||
* @param {Array} warehouse An array containing the warehouse data to be inserted
|
* @param {Array} warehouses An array containing the warehouses data to be inserted
|
||||||
*/
|
*/
|
||||||
export async function insertWarehouse(warehouse) {
|
export async function insertWarehouses(warehouses) {
|
||||||
const tx = await models.sequelize.transaction();
|
const tx = await models.sequelize.transaction();
|
||||||
try {
|
try {
|
||||||
await models.warehouse.upsert({
|
const warehousesWithDefaults = warehouses.map((warehouse) => ({
|
||||||
...warehouse,
|
...warehouse,
|
||||||
location_gln: warehouse.location.gln,
|
location_gln: warehouse.location.gln,
|
||||||
location_address_addressLine: warehouse.location.address.addressLine,
|
location_address_addressLine: warehouse.location.address.addressLine,
|
||||||
|
@ -407,8 +491,14 @@ export async function insertWarehouse(warehouse) {
|
||||||
location_address_countryCode: warehouse.location.address.countryCode,
|
location_address_countryCode: warehouse.location.address.countryCode,
|
||||||
location_address_postalCode: warehouse.location.address.postalCode,
|
location_address_postalCode: warehouse.location.address.postalCode,
|
||||||
location_address_stateOrProvince: warehouse.location.address.stateOrProvince,
|
location_address_stateOrProvince: warehouse.location.address.stateOrProvince,
|
||||||
lastSync: moment(),
|
lastSync: moment().format('YYYY-MM-DD HH:mm:ss'),
|
||||||
}, { transaction: tx });
|
}));
|
||||||
|
|
||||||
|
await models.warehouse.bulkCreate(warehousesWithDefaults, {
|
||||||
|
updateOnDuplicate: ['location_gln', 'location_address_addressLine', 'location_address_city', 'location_address_countryCode', 'location_address_postalCode', 'location_address_stateOrProvince', 'lastSync'],
|
||||||
|
transaction: tx,
|
||||||
|
});
|
||||||
|
|
||||||
await tx.commit();
|
await tx.commit();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
await tx.rollback();
|
await tx.rollback();
|
||||||
|
@ -417,18 +507,24 @@ export async function insertWarehouse(warehouse) {
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Insert organization in the database.
|
* Insert organizations in the database.
|
||||||
*
|
*
|
||||||
* @param {Array} organization An array containing the organization data to be inserted
|
* @param {Array} organizations An array containing the organizations data to be inserted
|
||||||
*/
|
*/
|
||||||
export async function insertOrganization(organization) {
|
export async function insertOrganizations(organizations) {
|
||||||
const tx = await models.sequelize.transaction();
|
const tx = await models.sequelize.transaction();
|
||||||
try {
|
try {
|
||||||
await models.organization.upsert({
|
const organizationsWithDefaults = organizations.map((organization) => ({
|
||||||
...organization,
|
...organization,
|
||||||
isConnected: JSON.parse(env.ORGS_ALWAYS_CONN),
|
isConnected: JSON.parse(env.ORGS_ALWAYS_CONN),
|
||||||
lastSync: moment(),
|
lastSync: moment().format('YYYY-MM-DD HH:mm:ss'),
|
||||||
}, { transaction: tx });
|
}));
|
||||||
|
|
||||||
|
await models.organization.bulkCreate(organizationsWithDefaults, {
|
||||||
|
updateOnDuplicate: ['isConnected', 'lastSync'],
|
||||||
|
transaction: tx,
|
||||||
|
});
|
||||||
|
|
||||||
await tx.commit();
|
await tx.commit();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
await tx.rollback();
|
await tx.rollback();
|
||||||
|
@ -436,14 +532,8 @@ export async function insertOrganization(organization) {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/* Checkear dependecias supply line
|
||||||
* Insert supply line and dependences in the database.
|
|
||||||
*
|
|
||||||
* @param {Array} supplyLine An array containing the supply line data to be inserted
|
|
||||||
*/
|
|
||||||
export async function insertSupplyLine(supplyLine) {
|
|
||||||
const tx = await models.sequelize.transaction();
|
|
||||||
try {
|
|
||||||
// Check if the warehouse exists, and if it doesn't, create it
|
// Check if the warehouse exists, and if it doesn't, create it
|
||||||
let warehouse = await models.warehouse.findOne({
|
let warehouse = await models.warehouse.findOne({
|
||||||
where: { warehouseId: supplyLine.warehouseId }
|
where: { warehouseId: supplyLine.warehouseId }
|
||||||
|
@ -472,7 +562,17 @@ export async function insertSupplyLine(supplyLine) {
|
||||||
await insertTradeItem(tradeItem);
|
await insertTradeItem(tradeItem);
|
||||||
}
|
}
|
||||||
|
|
||||||
await models.supplyLine.upsert({
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Insert supply lines and dependencies in the database.
|
||||||
|
*
|
||||||
|
* @param {Array} supplyLines An array containing the supply line data to be inserted
|
||||||
|
*/
|
||||||
|
export async function insertSupplyLines(supplyLines) {
|
||||||
|
const tx = await models.sequelize.transaction();
|
||||||
|
try {
|
||||||
|
const supplyLinesData = supplyLines.map((supplyLine) => ({
|
||||||
...supplyLine,
|
...supplyLine,
|
||||||
organizationId: supplyLine.supplierOrganizationId,
|
organizationId: supplyLine.supplierOrganizationId,
|
||||||
deliveryPeriodStartDateTime: supplyLine.deliveryPeriod?.startDateTime ?? null,
|
deliveryPeriodStartDateTime: supplyLine.deliveryPeriod?.startDateTime ?? null,
|
||||||
|
@ -481,28 +581,60 @@ export async function insertSupplyLine(supplyLine) {
|
||||||
orderPeriodEndDateTime: supplyLine.orderPeriod?.endDateTime ?? null,
|
orderPeriodEndDateTime: supplyLine.orderPeriod?.endDateTime ?? null,
|
||||||
agreementReference_code: supplyLine.agreementReference?.code ?? null,
|
agreementReference_code: supplyLine.agreementReference?.code ?? null,
|
||||||
agreementReference_description: supplyLine.agreementReference?.description ?? null,
|
agreementReference_description: supplyLine.agreementReference?.description ?? null,
|
||||||
lastSync: moment(),
|
lastSync: moment().format('YYYY-MM-DD HH:mm:ss'),
|
||||||
}, { transaction: tx });
|
}));
|
||||||
|
|
||||||
// Upsert packing configurations
|
await models.supplyLine.bulkCreate(supplyLinesData, { transaction: tx });
|
||||||
if (supplyLine.packingConfigurations.length)
|
|
||||||
for (const packingConfiguration of supplyLine.packingConfigurations)
|
|
||||||
await models.supplyLinePackingConfiguration.upsert({
|
|
||||||
packingConfigurationId: uuidv4(),
|
|
||||||
...packingConfiguration,
|
|
||||||
packageVbnPackageCode: packingConfiguration.package.vbnPackageCode,
|
|
||||||
packageCustomPackageId: packingConfiguration.package.customPackageId,
|
|
||||||
additionalPricePerPieceCurrency: packingConfiguration.additionalPricePerPiece.currency,
|
|
||||||
additionalPricePerPieceValue: packingConfiguration.additionalPricePerPiece.value,
|
|
||||||
supplyLineId: supplyLine.supplyLineId,
|
|
||||||
}, { transaction: tx });
|
|
||||||
|
|
||||||
// Upsert volume price
|
const packingConfigurations = [];
|
||||||
for (let volumePrice of supplyLine.volumePrices)
|
const volumePrices = [];
|
||||||
await models.volumePrice.upsert({
|
|
||||||
supplyLineId: supplyLine.supplyLineId,
|
for (const supplyLine of supplyLinesData)
|
||||||
...volumePrice,
|
if (supplyLine.packingConfigurations?.length) {
|
||||||
}, { transaction: tx });
|
for (const packingConfiguration of supplyLine.packingConfigurations)
|
||||||
|
packingConfigurations.push({
|
||||||
|
packingConfigurationId: uuidv4(),
|
||||||
|
...packingConfiguration,
|
||||||
|
packageVbnPackageCode: packingConfiguration.package.vbnPackageCode,
|
||||||
|
packageCustomPackageId: packingConfiguration.package.customPackageId,
|
||||||
|
additionalPricePerPieceCurrency: packingConfiguration.additionalPricePerPiece.currency,
|
||||||
|
additionalPricePerPieceValue: packingConfiguration.additionalPricePerPiece.value,
|
||||||
|
supplyLineId: supplyLine.supplyLineId,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (supplyLine.volumePrices?.length)
|
||||||
|
for (const volumePrice of supplyLine.volumePrices)
|
||||||
|
volumePrices.push({
|
||||||
|
supplyLineId: supplyLine.supplyLineId,
|
||||||
|
...volumePrice,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (packingConfigurations.length)
|
||||||
|
await models.supplyLinePackingConfiguration.bulkCreate(packingConfigurations, {
|
||||||
|
updateOnDuplicate: [
|
||||||
|
'packingConfigurationId',
|
||||||
|
'packageVbnPackageCode',
|
||||||
|
'packageCustomPackageId',
|
||||||
|
'piecesPerPackage',
|
||||||
|
'bunchesPerPackage',
|
||||||
|
'photoUrl',
|
||||||
|
'packagesPerLayer',
|
||||||
|
'layersPerLoadCarrier',
|
||||||
|
'transportHeightInCm',
|
||||||
|
'loadCarrierType',
|
||||||
|
'additionalPricePerPieceCurrency',
|
||||||
|
'additionalPricePerPieceValue',
|
||||||
|
'isPrimary'
|
||||||
|
],
|
||||||
|
transaction: tx,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (volumePrices.length)
|
||||||
|
await models.volumePrice.bulkCreate(volumePrices, {
|
||||||
|
updateOnDuplicate: ['supplyLineId', 'unit', 'pricePerPiece'],
|
||||||
|
transaction: tx,
|
||||||
|
});
|
||||||
|
|
||||||
await tx.commit();
|
await tx.commit();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
@ -630,9 +762,15 @@ export async function startSpin(msg, isNew) {
|
||||||
if (JSON.parse(env.TIME_STAMPS) && msg)
|
if (JSON.parse(env.TIME_STAMPS) && msg)
|
||||||
msg = `${chalk.gray(`[${new moment().format('YYYY-MM-DD hh:mm:ss A')}]`)} ${msg}`;
|
msg = `${chalk.gray(`[${new moment().format('YYYY-MM-DD hh:mm:ss A')}]`)} ${msg}`;
|
||||||
|
|
||||||
(isNew)
|
(!isNew)
|
||||||
? spinner = ora(msg).start()
|
? spinner.start()
|
||||||
: spinner.start();
|
: spinner = ora({
|
||||||
|
text: msg,
|
||||||
|
indent: 1,
|
||||||
|
spinner: 'arc',
|
||||||
|
interval: 40,
|
||||||
|
color: 'white',
|
||||||
|
}).start();
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -696,7 +834,7 @@ export async function failSpin(err, clear) {
|
||||||
if (clear)
|
if (clear)
|
||||||
spinner.clear();
|
spinner.clear();
|
||||||
}
|
}
|
||||||
throw err;
|
if (err) throw err;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -718,7 +856,8 @@ export async function criticalSpin(err) {
|
||||||
* @param {Error} err Error object
|
* @param {Error} err Error object
|
||||||
**/
|
**/
|
||||||
export async function criticalError(err) {
|
export async function criticalError(err) {
|
||||||
console.log(chalk.red.bold(`[CRITICAL]`), chalk.red(err.message));
|
const msg = `${chalk.red.bold(' └─────')} ${chalk.red.bold('[CRITICAL]')}`;
|
||||||
|
console.log(`${msg} ${chalk.red(err.message)}`);
|
||||||
process.exit();
|
process.exit();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -728,5 +867,6 @@ export async function criticalError(err) {
|
||||||
* @param {Error} err
|
* @param {Error} err
|
||||||
**/
|
**/
|
||||||
export async function warning(err) {
|
export async function warning(err) {
|
||||||
console.log(chalk.yellow.bold(`[WARNING]`), (err.response?.status && err.response?.data?.message) ?? chalk.yellow(err.message));
|
const msg = `${chalk.yellow.bold(' └─────')} ${chalk.yellow.bold('[WARNING]')}`;
|
||||||
|
console.log(`${msg} ${chalk.yellow((err.response?.status && err.response?.data?.message) ?? err.message)}`);
|
||||||
};
|
};
|
Loading…
Reference in New Issue