Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@commercetools/csv-parser-orders

Package Overview
Dependencies
Maintainers
8
Versions
52
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@commercetools/csv-parser-orders - npm Package Compare versions

Comparing version 1.2.4 to 1.2.5

4

bin/csvparserorder.js

@@ -8,4 +8,4 @@ #!/usr/bin/env node

*/
'use strict';
'use strict'
require('../lib/cli.js');
require('../lib/cli.js')

@@ -41,3 +41,5 @@ 'use strict';

var args = _yargs2.default.usage('\n\nUsage: $0 [options]\nConvert commercetools order CSV data to JSON.').showHelpOnFail(false).option('help', {
const args = _yargs2.default.usage(`\n
Usage: $0 [options]
Convert commercetools order CSV data to JSON.`).showHelpOnFail(false).option('help', {
alias: 'h'

@@ -56,3 +58,3 @@ }).help('help', 'Show help text.').option('version', {

describe: 'Path to input CSV file.'
}).coerce('inputFile', function (arg) {
}).coerce('inputFile', arg => {
if (arg !== 'stdin') return _fs2.default.createReadStream(String(arg));

@@ -65,3 +67,3 @@

describe: 'Path to output JSON file.'
}).coerce('outputFile', function (arg) {
}).coerce('outputFile', arg => {
if (arg !== 'stdout') return _fs2.default.createWriteStream(String(arg));

@@ -91,9 +93,9 @@

var logError = function logError(error) {
var errorFormatter = new _prettyError2.default();
const logError = error => {
const errorFormatter = new _prettyError2.default();
if (_npmlog2.default.level === 'verbose') process.stderr.write('ERR: ' + errorFormatter.render(error));else process.stderr.write('ERR: ' + (error.message || error));
if (_npmlog2.default.level === 'verbose') process.stderr.write(`ERR: ${errorFormatter.render(error)}`);else process.stderr.write(`ERR: ${error.message || error}`);
};
var errorHandler = function errorHandler(errors) {
const errorHandler = errors => {
if (Array.isArray(errors)) errors.forEach(logError);else logError(errors);

@@ -104,35 +106,26 @@

var getModuleConfig = function getModuleConfig() {
return {
logger: {
error: _npmlog2.default.error.bind(undefined, ''),
warn: _npmlog2.default.warn.bind(undefined, ''),
info: _npmlog2.default.info.bind(undefined, ''),
verbose: _npmlog2.default.verbose.bind(undefined, '')
},
csvConfig: {
delimiter: args.delimiter,
batchSize: args.batchSize,
strictMode: args.strictMode
}
};
};
const getModuleConfig = () => ({
logger: {
error: _npmlog2.default.error.bind(undefined, ''),
warn: _npmlog2.default.warn.bind(undefined, ''),
info: _npmlog2.default.info.bind(undefined, ''),
verbose: _npmlog2.default.verbose.bind(undefined, '')
},
csvConfig: {
delimiter: args.delimiter,
batchSize: args.batchSize,
strictMode: args.strictMode
}
});
if (args.outputFile === process.stdout) _npmlog2.default.stream = _fs2.default.createWriteStream(args.logFile);
var methodMapping = {
lineitemstate: function lineitemstate(config) {
return new _lineItemState2.default(config);
},
returninfo: function returninfo(config) {
return new _addReturnInfo2.default(config);
},
deliveries: function deliveries(config) {
return new _deliveries2.default(config);
}
};
const methodMapping = {
lineitemstate: config => new _lineItemState2.default(config),
returninfo: config => new _addReturnInfo2.default(config),
deliveries: config => new _deliveries2.default(config)
// Register error listener
args.outputFile.on('error', errorHandler);
// Register error listener
};args.outputFile.on('error', errorHandler);
methodMapping[args.type](getModuleConfig()).parse(args.inputFile, args.outputFile);

@@ -6,3 +6,3 @@ 'use strict';

});
var CONSTANTS = {
const CONSTANTS = {
host: {

@@ -24,6 +24,5 @@ api: 'https://api.sphere.io',

}
};
// Go through object because `freeze` works shallow
Object.keys(CONSTANTS).forEach(function (key) {
// Go through object because `freeze` works shallow
};Object.keys(CONSTANTS).forEach(key => {
Object.freeze(CONSTANTS[key]);

@@ -30,0 +29,0 @@ });

@@ -7,4 +7,2 @@ 'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _highland = require('highland');

@@ -26,12 +24,5 @@

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/* eslint class-methods-use-this:["error", {"exceptMethods":["_processData"]}]*/
var AbstractParser = function () {
function AbstractParser() {
var conf = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var moduleName = arguments[1];
_classCallCheck(this, AbstractParser);
/* eslint class-methods-use-this:["error",{"exceptMethods":["_processData"]}] */
class AbstractParser {
constructor(conf = {}, moduleName) {
this.moduleName = moduleName;

@@ -46,51 +37,37 @@

this.logger = (0, _lodash.defaults)(conf.logger || {}, {
error: function error() {},
warn: function warn() {},
info: function info() {},
verbose: function verbose() {}
error: () => {},
warn: () => {},
info: () => {},
verbose: () => {}
});
}
_createClass(AbstractParser, [{
key: '_streamInput',
value: function _streamInput(input, output) {
var _this = this;
_streamInput(input, output) {
let rowIndex = 1;
var rowIndex = 1;
return (0, _highland2.default)(input).through((0, _csvParser2.default)({
separator: this.csvConfig.delimiter,
strict: this.csvConfig.strictMode
})).stopOnError(err => {
this.logger.error(err);
return output.emit('error', err);
}).batch(this.csvConfig.batchSize).doto(data => {
this.logger.verbose(`Parsed row-${rowIndex}: ${JSON.stringify(data)}`);
rowIndex += 1;
}).flatMap(_highland2.default).flatMap(data => (0, _highland2.default)(this._processData(data))).stopOnError(err => {
this.logger.error(err);
return output.emit('error', err);
}).doto(data => this.logger.verbose(`Converted row-${rowIndex}: ${JSON.stringify(data)}`));
}
return (0, _highland2.default)(input).through((0, _csvParser2.default)({
separator: this.csvConfig.delimiter,
strict: this.csvConfig.strictMode
})).stopOnError(function (err) {
_this.logger.error(err);
return output.emit('error', err);
}).batch(this.csvConfig.batchSize).doto(function (data) {
_this.logger.verbose('Parsed row-' + rowIndex + ': ' + JSON.stringify(data));
rowIndex += 1;
}).flatMap(_highland2.default).flatMap(function (data) {
return (0, _highland2.default)(_this._processData(data));
}).stopOnError(function (err) {
_this.logger.error(err);
return output.emit('error', err);
}).doto(function (data) {
return _this.logger.verbose('Converted row-' + rowIndex + ': ' + JSON.stringify(data));
});
}
}, {
key: '_getMissingHeaders',
value: function _getMissingHeaders(data) {
var headerDiff = (0, _lodash.difference)(_constants2.default.requiredHeaders[this.moduleName], Object.keys(data));
_getMissingHeaders(data) {
const headerDiff = (0, _lodash.difference)(_constants2.default.requiredHeaders[this.moduleName], Object.keys(data));
return headerDiff;
}
}, {
key: '_processData',
value: function _processData() {
throw new Error('Method AbstractParser._processData has to be overridden!');
}
}]);
return headerDiff;
}
return AbstractParser;
}();
_processData() {
throw new Error('Method AbstractParser._processData has to be overridden!');
}
}
exports.default = AbstractParser;

@@ -7,4 +7,2 @@ 'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _JSONStream = require('JSONStream');

@@ -22,110 +20,84 @@

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
class AddReturnInfoParser extends _abstractParser2.default {
constructor(config) {
super(config, 'returnInfo');
}
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var AddReturnInfoParser = function (_AbstractParser) {
_inherits(AddReturnInfoParser, _AbstractParser);
function AddReturnInfoParser(config) {
_classCallCheck(this, AddReturnInfoParser);
return _possibleConstructorReturn(this, (AddReturnInfoParser.__proto__ || Object.getPrototypeOf(AddReturnInfoParser)).call(this, config, 'returnInfo'));
parse(input, output) {
this.logger.info('Starting Return Info CSV conversion');
this._streamInput(input, output).reduce([], AddReturnInfoParser._reduceOrders).stopOnError(err => {
this.logger.error(err);
return output.emit('error', err);
}).pipe(_JSONStream2.default.stringify(false)).pipe(output);
}
_createClass(AddReturnInfoParser, [{
key: 'parse',
value: function parse(input, output) {
var _this2 = this;
_processData(data) {
this.logger.verbose('Processing data to CTP format');
this.logger.info('Starting Return Info CSV conversion');
this._streamInput(input, output).reduce([], AddReturnInfoParser._reduceOrders).stopOnError(function (err) {
_this2.logger.error(err);
return output.emit('error', err);
}).pipe(_JSONStream2.default.stringify(false)).pipe(output);
}
}, {
key: '_processData',
value: function _processData(data) {
this.logger.verbose('Processing data to CTP format');
const missingHeaders = this._getMissingHeaders(data);
if (missingHeaders.length) return Promise.reject(new Error(`Required headers missing: '${missingHeaders.join(',')}'`));
var missingHeaders = this._getMissingHeaders(data);
if (missingHeaders.length) return Promise.reject('Required headers missing: \'' + missingHeaders.join(',') + '\'');
/**
* Sample returnInfo object that the API supports:
*
* orderNumber: String,
* returnInfo: [{
* returnTrackingId: String,
* returnDate: DateTime,
* items: [{
* quantity: String,
* lineItemId: String,
* comment: String,
* shipmentState: Ref
* }]
* }]
*/
var result = {
orderNumber: data.orderNumber,
returnInfo: [{
returnTrackingId: data.returnTrackingId,
_returnId: data._returnId, // Internal value to group the returnInfo
returnDate: data.returnDate,
items: [{
quantity: parseInt(data.quantity, 10),
lineItemId: data.lineItemId,
comment: data.comment,
shipmentState: data.shipmentState
}]
/**
* Sample returnInfo object that the API supports:
*
* orderNumber: String,
* returnInfo: [{
* returnTrackingId: String,
* returnDate: DateTime,
* items: [{
* quantity: String,
* lineItemId: String,
* comment: String,
* shipmentState: Ref
* }]
* }]
*/
const result = {
orderNumber: data.orderNumber,
returnInfo: [{
returnTrackingId: data.returnTrackingId,
_returnId: data._returnId, // Internal value to group the returnInfo
returnDate: data.returnDate,
items: [{
quantity: parseInt(data.quantity, 10),
lineItemId: data.lineItemId,
comment: data.comment,
shipmentState: data.shipmentState
}]
};
return Promise.resolve(result);
}
}], [{
key: '_reduceOrders',
value: function _reduceOrders(allOrders, currentOrder) {
var _existingOrder$return;
}]
};
return Promise.resolve(result);
}
/**
* Reduce all orders to one order object
* 1. Group all orders by the orderNumber
* 2. Group all returnInfo of an order by the _returnId
*/
static _reduceOrders(allOrders, currentOrder) {
/**
* Reduce all orders to one order object
* 1. Group all orders by the orderNumber
* 2. Group all returnInfo of an order by the _returnId
*/
// push first order into final array
if (!allOrders.length) return allOrders.concat(currentOrder);
// push first order into final array
if (!allOrders.length) return allOrders.concat(currentOrder);
// find order in final array with this orderNumber
var existingOrder = (0, _lodash.find)(allOrders, ['orderNumber', currentOrder.orderNumber]);
// find order in final array with this orderNumber
const existingOrder = (0, _lodash.find)(allOrders, ['orderNumber', currentOrder.orderNumber]);
// if currentOrder (with this orderNumber) haven't been inserted yet
// push it directly into final array
if (!existingOrder) return allOrders.concat(currentOrder);
// if currentOrder (with this orderNumber) haven't been inserted yet
// push it directly into final array
if (!existingOrder) return allOrders.concat(currentOrder);
// if there is already an order with this orderNumber
// get all returnInfos with same returnId
var existingReturnInfos = (0, _lodash.filter)(existingOrder.returnInfo, ['_returnId', currentOrder.returnInfo[0]._returnId]);
// if there is already an order with this orderNumber
// get all returnInfos with same returnId
const existingReturnInfos = (0, _lodash.filter)(existingOrder.returnInfo, ['_returnId', currentOrder.returnInfo[0]._returnId]);
// if there is no returnInfo with this returnId push those from currentOrder
if (!existingReturnInfos.length) (_existingOrder$return = existingOrder.returnInfo).push.apply(_existingOrder$return, _toConsumableArray(currentOrder.returnInfo));else
// else concat items from currentOrder
existingReturnInfos.forEach(function (returnInfo) {
var _returnInfo$items;
// if there is no returnInfo with this returnId push those from currentOrder
if (!existingReturnInfos.length) existingOrder.returnInfo.push(...currentOrder.returnInfo);else
// else concat items from currentOrder
existingReturnInfos.forEach(returnInfo => {
returnInfo.items.push(...currentOrder.returnInfo[0].items);
});
(_returnInfo$items = returnInfo.items).push.apply(_returnInfo$items, _toConsumableArray(currentOrder.returnInfo[0].items));
});
return allOrders;
}
}]);
return AddReturnInfoParser;
}(_abstractParser2.default);
return allOrders;
}
}
exports.default = AddReturnInfoParser;

@@ -7,4 +7,2 @@ 'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _lodash = require('lodash');

@@ -36,255 +34,209 @@

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
class DeliveriesParser extends _abstractParser2.default {
constructor(config) {
super(config, 'deliveries');
}
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var DeliveriesParser = function (_AbstractParser) {
_inherits(DeliveriesParser, _AbstractParser);
function DeliveriesParser(config) {
_classCallCheck(this, DeliveriesParser);
return _possibleConstructorReturn(this, (DeliveriesParser.__proto__ || Object.getPrototypeOf(DeliveriesParser)).call(this, config, 'deliveries'));
parse(input, output) {
this.logger.info('Starting Deliveries CSV conversion');
this._streamInput(input, output).reduce([], DeliveriesParser._groupByDeliveryId).stopOnError(err => {
this.logger.error(err);
return output.emit('error', err);
}).flatMap(data => (0, _highland2.default)(DeliveriesParser._cleanOrders(data))).pipe(_JSONStream2.default.stringify(false)).pipe(output);
}
_createClass(DeliveriesParser, [{
key: 'parse',
value: function parse(input, output) {
var _this2 = this;
// Take objectized CSV row and create an order object from it
_processData(data) {
this.logger.verbose('Processing data to CTP format');
const csvHeaders = Object.keys(data);
const headerDiff = _lodash2.default.difference(_constants2.default.requiredHeaders.deliveries, csvHeaders);
this.logger.info('Starting Deliveries CSV conversion');
this._streamInput(input, output).reduce([], DeliveriesParser._groupByDeliveryId).stopOnError(function (err) {
_this2.logger.error(err);
return output.emit('error', err);
}).flatMap(function (data) {
return (0, _highland2.default)(DeliveriesParser._cleanOrders(data));
}).pipe(_JSONStream2.default.stringify(false)).pipe(output);
}
if (headerDiff.length) return Promise.reject(new Error(`Required headers missing: '${headerDiff.join(',')}'`));
// Take objectized CSV row and create an order object from it
/**
* Sample delivery object that the API supports
* {
* "id": String,
* "createdAt": DateTime,
* "items": [
* {
* "id": String,
* "quantity": Number
* }
* ],
* "parcels": [
* {
* "id": String,
* "createdAt": DateTime,
* "measurements": {
* "heightInMillimeter": Number,
* "lengthInMillimeter": Number,
* "widthInMillimeter": Number,
* "weightInGram": Number
* }
* "trackingData": {
* "trackingId": String,
* "provider": String,
* "providerTransaction": String,
* "carrier": String,
* "isReturn": Boolean
* }
* }
* ]
* }
*/
}, {
key: '_processData',
value: function _processData(data) {
this.logger.verbose('Processing data to CTP format');
var csvHeaders = Object.keys(data);
var headerDiff = _lodash2.default.difference(_constants2.default.requiredHeaders.deliveries, csvHeaders);
/**
* Sample result - order object with shippingInfo.deliveries
* {
* "orderNumber": String
* "shippingInfo": {
* "deliveries": [
* ...
* ]
* }
* }
*/
if (headerDiff.length) return Promise.reject(new Error('Required headers missing: \'' + headerDiff.join(',') + '\''));
// Basic delivery object with delivery item
const delivery = {
id: data['delivery.id'],
items: [{
// there can be multiple delivery items with same item.id and
// item.quantity therefore we use unique identifier _itemGroupId
_groupId: data._itemGroupId,
id: data['item.id'],
quantity: parseInt(data['item.quantity'], 10)
}]
/**
* Sample delivery object that the API supports
* {
* "id": String,
* "createdAt": DateTime,
* "items": [
* {
* "id": String,
* "quantity": Number
* }
* ],
* "parcels": [
* {
* "id": String,
* "createdAt": DateTime,
* "measurements": {
* "heightInMillimeter": Number,
* "lengthInMillimeter": Number,
* "widthInMillimeter": Number,
* "weightInGram": Number
* }
* "trackingData": {
* "trackingId": String,
* "provider": String,
* "providerTransaction": String,
* "carrier": String,
* "isReturn": Boolean
* }
* }
* ]
* }
*/
/**
* Sample result - order object with shippingInfo.deliveries
* {
* "orderNumber": String
* "shippingInfo": {
* "deliveries": [
* ...
* ]
* }
* }
*/
// Basic delivery object with delivery item
var delivery = {
id: data['delivery.id'],
items: [{
// there can be multiple delivery items with same item.id and
// item.quantity therefore we use unique identifier _itemGroupId
_groupId: data['_itemGroupId'],
id: data['item.id'],
quantity: parseInt(data['item.quantity'], 10)
}]
};
// Add parcel info if it is present
if (data['parcel.id']) {
var parcel = DeliveriesParser._parseParcelInfo(data);
};if (data['parcel.id']) {
const parcel = DeliveriesParser._parseParcelInfo(data);
if (parcel.measurements && Object.keys(parcel.measurements).length !== 4) return Promise.reject(new Error('All measurement fields are mandatory'));
if (parcel.measurements && Object.keys(parcel.measurements).length !== 4) return Promise.reject(new Error('All measurement fields are mandatory'));
delivery.parcels = [parcel];
}
var order = {
orderNumber: data['orderNumber'],
shippingInfo: {
deliveries: [delivery]
}
};
return Promise.resolve(order);
delivery.parcels = [parcel];
}
// remove internal properties
const order = {
orderNumber: data.orderNumber,
shippingInfo: {
deliveries: [delivery]
}
};
return Promise.resolve(order);
}
}], [{
key: '_cleanOrders',
value: function _cleanOrders(orders) {
orders.forEach(function (order) {
return order.shippingInfo.deliveries.forEach(function (delivery) {
return delivery.items.forEach(function (item) {
// eslint-disable-next-line no-param-reassign
delete item._groupId;
});
});
});
return [orders];
}
// remove internal properties
static _cleanOrders(orders) {
orders.forEach(order => order.shippingInfo.deliveries.forEach(delivery => delivery.items.forEach(item => {
// eslint-disable-next-line no-param-reassign
delete item._groupId;
})));
return [orders];
}
// Will merge newOrder with orders in results array
// Will merge newOrder with orders in results array
static _groupByDeliveryId(results, newOrder) {
/*
Merge orders in following steps:
1. Group all orders by orderNumber
1. Group all delivery items by _itemGroupId
2. Group all parcel items by parcel.id
*/
}, {
key: '_groupByDeliveryId',
value: function _groupByDeliveryId(results, newOrder) {
/*
Merge orders in following steps:
1. Group all orders by orderNumber
1. Group all delivery items by _itemGroupId
2. Group all parcel items by parcel.id
*/
// if newOrder is the first record, just push it to the results
if (!results.length) return [newOrder];
// if newOrder is the first record, just push it to the results
if (!results.length) return [newOrder];
// find newOrder in results using its orderNumber
const existingOrder = results.find(order => order.orderNumber === newOrder.orderNumber);
// find newOrder in results using its orderNumber
var existingOrder = results.find(function (order) {
return order.orderNumber === newOrder.orderNumber;
});
if (!existingOrder) results.push(newOrder);else {
const oldDeliveries = existingOrder.shippingInfo.deliveries;
const newDelivery = newOrder.shippingInfo.deliveries[0];
if (!existingOrder) results.push(newOrder);else {
var oldDeliveries = existingOrder.shippingInfo.deliveries;
var newDelivery = newOrder.shippingInfo.deliveries[0];
// find newDelivery in results using its id
const existingDelivery = oldDeliveries.find(delivery => delivery.id === newDelivery.id);
// find newDelivery in results using its id
var existingDelivery = oldDeliveries.find(function (delivery) {
return delivery.id === newDelivery.id;
});
// if this delivery is not yet in results array, insert it
if (!existingDelivery) oldDeliveries.push(newDelivery);else {
DeliveriesParser._mergeDeliveryItems(existingDelivery.items, newDelivery.items[0], existingDelivery);
// if this delivery is not yet in results array, insert it
if (!existingDelivery) oldDeliveries.push(newDelivery);else {
DeliveriesParser._mergeDeliveryItems(existingDelivery.items, newDelivery.items[0], existingDelivery);
// if delivery have parcels, merge them
if (newDelivery.parcels) DeliveriesParser._mergeDeliveryParcels(existingDelivery.parcels, newDelivery.parcels[0], existingDelivery);
}
// if delivery have parcels, merge them
if (newDelivery.parcels) DeliveriesParser._mergeDeliveryParcels(existingDelivery.parcels, newDelivery.parcels[0], existingDelivery);
}
return results;
}
// merge delivery parcels to one array based on parcel.id field
return results;
}
}, {
key: '_mergeDeliveryParcels',
value: function _mergeDeliveryParcels(allParcels, newParcel, delivery) {
// try to find this parcel in array using parcel id
var duplicitParcel = allParcels.find(function (parcel) {
return parcel.id === newParcel.id;
});
// merge delivery parcels to one array based on parcel.id field
static _mergeDeliveryParcels(allParcels, newParcel, delivery) {
// try to find this parcel in array using parcel id
const duplicitParcel = allParcels.find(parcel => parcel.id === newParcel.id);
// if this parcel item is not yet in array, insert it
if (!duplicitParcel) return allParcels.push(newParcel);
// if this parcel item is not yet in array, insert it
if (!duplicitParcel) return allParcels.push(newParcel);
// if this parcel is already in array, check if parcels are equal
if (!_lodash2.default.isEqual(duplicitParcel, newParcel)) throw new Error('Delivery with id \'' + delivery.id + '\' has a parcel with' + (' id \'' + newParcel.id + '\' which has different') + (' values across multiple rows.\n Original parcel: \'' + JSON.stringify(duplicitParcel) + '\'\n Invalid parcel: \'' + JSON.stringify(newParcel) + '\''));
// if this parcel is already in array, check if parcels are equal
if (!_lodash2.default.isEqual(duplicitParcel, newParcel)) throw new Error(`Delivery with id '${delivery.id}' has a parcel with` + ` id '${newParcel.id}' which has different` + ` values across multiple rows.
Original parcel: '${JSON.stringify(duplicitParcel)}'
Invalid parcel: '${JSON.stringify(newParcel)}'`);
return allParcels;
}
return allParcels;
}
// merge delivery items to one array based on _groupId field
// merge delivery items to one array based on _groupId field
static _mergeDeliveryItems(allItems, newItem, delivery) {
const duplicitItem = allItems.find(item => item._groupId === newItem._groupId);
}, {
key: '_mergeDeliveryItems',
value: function _mergeDeliveryItems(allItems, newItem, delivery) {
var duplicitItem = allItems.find(function (item) {
return item._groupId === newItem._groupId;
});
// if an item is not yet in array, insert it
if (!duplicitItem) return allItems.push(newItem);
// if an item is not yet in array, insert it
if (!duplicitItem) return allItems.push(newItem);
// if this item is already in array, check if items are equal
if (!_lodash2.default.isEqual(duplicitItem, newItem)) throw new Error(`Delivery with id '${delivery.id}' has an item` + ` with itemGroupId '${newItem._groupId}' which has different` + ` values across multiple rows.
Original row: '${JSON.stringify(duplicitItem)}'
Invalid row: '${JSON.stringify(newItem)}'`);
// if this item is already in array, check if items are equal
if (!_lodash2.default.isEqual(duplicitItem, newItem)) throw new Error('Delivery with id \'' + delivery.id + '\' has an item' + (' with itemGroupId \'' + newItem._groupId + '\' which has different') + (' values across multiple rows.\n Original row: \'' + JSON.stringify(duplicitItem) + '\'\n Invalid row: \'' + JSON.stringify(newItem) + '\''));
return allItems;
}
return allItems;
}
}, {
key: '_parseParcelInfo',
value: function _parseParcelInfo(data) {
var transitionMap = {
'parcel.height': 'measurements.heightInMillimeter',
'parcel.length': 'measurements.lengthInMillimeter',
'parcel.width': 'measurements.widthInMillimeter',
'parcel.weight': 'measurements.weightInGram',
'parcel.trackingId': 'trackingData.trackingId',
'parcel.providerTransaction': 'trackingData.providerTransaction',
'parcel.provider': 'trackingData.provider',
'parcel.carrier': 'trackingData.carrier',
'parcel.isReturn': 'trackingData.isReturn'
};
static _parseParcelInfo(data) {
const transitionMap = {
'parcel.height': 'measurements.heightInMillimeter',
'parcel.length': 'measurements.lengthInMillimeter',
'parcel.width': 'measurements.widthInMillimeter',
'parcel.weight': 'measurements.weightInGram',
'parcel.trackingId': 'trackingData.trackingId',
'parcel.providerTransaction': 'trackingData.providerTransaction',
'parcel.provider': 'trackingData.provider',
'parcel.carrier': 'trackingData.carrier',
'parcel.isReturn': 'trackingData.isReturn'
};
var parcel = {
id: data['parcel.id']
};
const parcel = {
id: data['parcel.id']
// Build parcel object
Object.keys(data).forEach(function (fieldName) {
if (!transitionMap[fieldName]) return;
};Object.keys(data).forEach(fieldName => {
if (!transitionMap[fieldName]) return;
// All values are loaded as a string
var fieldValue = data[fieldName];
// All values are loaded as a string
let fieldValue = data[fieldName];
// do not set empty values
if (fieldValue === '') return;
// do not set empty values
if (fieldValue === '') return;
// Cast measurements to Number
if (/^measurements/.test(transitionMap[fieldName])) fieldValue = Number(fieldValue);
// Cast measurements to Number
if (/^measurements/.test(transitionMap[fieldName])) fieldValue = Number(fieldValue);
// Cast isReturn field to Boolean
if (fieldName === 'parcel.isReturn') fieldValue = fieldValue === '1' || fieldValue.toLowerCase() === 'true';
// Cast isReturn field to Boolean
if (fieldName === 'parcel.isReturn') fieldValue = fieldValue === '1' || fieldValue.toLowerCase() === 'true';
_objectPath2.default.set(parcel, transitionMap[fieldName], fieldValue);
});
_objectPath2.default.set(parcel, transitionMap[fieldName], fieldValue);
});
return parcel;
}
}]);
return DeliveriesParser;
}(_abstractParser2.default);
return parcel;
}
}
exports.default = DeliveriesParser;

@@ -7,4 +7,2 @@ 'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _JSONStream = require('JSONStream');

@@ -20,58 +18,48 @@

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
class LineItemStateParser extends _abstractParser2.default {
constructor(config) {
super(config, 'lineItemState');
}
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
parse(input, output) {
this.logger.info('Starting LineItemState CSV conversion');
this._streamInput(input, output).reduce([], LineItemStateParser._groupByOrderNumber).stopOnError(err => {
this.logger.error(err);
return output.emit('error', err);
}).flatMap(data => data).pipe(_JSONStream2.default.stringify()).pipe(output);
}
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
// Will merge newLineItemState with lineItems in results array
static _groupByOrderNumber(results, newLineItemState) {
const existingItem = results.find(lineItem => lineItem.orderNumber === newLineItemState.orderNumber);
var LineItemStateParser = function (_AbstractParser) {
_inherits(LineItemStateParser, _AbstractParser);
if (existingItem) existingItem.lineItems.push(...newLineItemState.lineItems);else results.push(newLineItemState);
function LineItemStateParser(config) {
_classCallCheck(this, LineItemStateParser);
return _possibleConstructorReturn(this, (LineItemStateParser.__proto__ || Object.getPrototypeOf(LineItemStateParser)).call(this, config, 'lineItemState'));
return results;
}
_createClass(LineItemStateParser, [{
key: 'parse',
value: function parse(input, output) {
var _this2 = this;
_processData(data) {
this.logger.verbose('Processing data to CTP format');
this.logger.info('Starting LineItemState CSV conversion');
this._streamInput(input, output).stopOnError(function (err) {
_this2.logger.error(err);
return output.emit('error', err);
}).pipe(_JSONStream2.default.stringify()).pipe(output);
}
}, {
key: '_processData',
value: function _processData(data) {
this.logger.verbose('Processing data to CTP format');
const missingHeaders = this._getMissingHeaders(data);
if (missingHeaders.length) return Promise.reject(new Error(`Required headers missing: '${missingHeaders.join(',')}'`));
var missingHeaders = this._getMissingHeaders(data);
if (missingHeaders.length) return Promise.reject('Required headers missing: \'' + missingHeaders.join(',') + '\'');
const state = {
quantity: parseInt(data.quantity, 10),
fromState: data.fromState,
toState: data.toState
};
var state = {
quantity: parseInt(data.quantity, 10),
fromState: data.fromState,
toState: data.toState
};
if (data._fromStateQty) state._fromStateQty = parseInt(data._fromStateQty, 10);
if (data._fromStateQty) state._fromStateQty = parseInt(data._fromStateQty, 10);
var result = {
orderNumber: data.orderNumber,
lineItems: [{
id: data.lineItemId,
state: [state]
}]
};
return Promise.resolve(result);
}
}]);
return LineItemStateParser;
}(_abstractParser2.default);
const result = {
orderNumber: data.orderNumber,
lineItems: [{
id: data.lineItemId,
state: [state]
}]
};
return Promise.resolve(result);
}
}
exports.default = LineItemStateParser;
{
"name": "@commercetools/csv-parser-orders",
"version": "1.2.4",
"version": "1.2.5",
"description": "Module that parses order csv to json",

@@ -25,3 +25,3 @@ "keywords": [

],
"main": "./lib/index.js",
"main": "lib/index.js",
"bin": {

@@ -34,2 +34,5 @@ "csvparserorder": "bin/csvparserorder.js"

],
"scripts": {
"build": "cross-env NODE_ENV=cli babel src --out-dir lib"
},
"dependencies": {

@@ -36,0 +39,0 @@ "JSONStream": "^1.3.1",

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc