-
Notifications
You must be signed in to change notification settings - Fork 3
/
generatePurchaseCSV.js
224 lines (199 loc) · 7.59 KB
/
generatePurchaseCSV.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
'use strict';
const Logger = require('dw/system/Logger');
const Order = require('dw/order/Order');
const Status = require('dw/system/Status');
const FileWriter = require('dw/io/FileWriter');
const CSVStreamWriter = require('dw/io/CSVStreamWriter');
var Transaction = require('dw/system/Transaction');
const bloomreachLogger = Logger.getLogger('bloomreach_purchase_job', 'bloomreach');
const logger = Logger.getLogger('Bloomreach', 'bloomreach');
var BREngagementAPIHelper = require('~/cartridge/scripts/helpers/BloomreachEngagementHelper.js');
var currentSite = require('dw/system/Site').getCurrent();
var CustomObjectMgr = require('dw/object/CustomObjectMgr');
var fileNum = 0;
var ordersToProcess;
var processedAll = true;
var headers;
var csw;
var fw;
var rowsCount = 1;
var maxNoOfRows;
var targetFolder;
var FileNamePrefix;
var chunks = 0;
var headers;
var SFCCAttributesValue;
var updateCustomDateExportPreference = false;
var feedFileGenerationDate;
var csvGeneratorHelper = require('~/cartridge/scripts/helpers/BloomreachEngagementGenerateCSVHelper');
var generatePreInitFile = false;
var webDavFilePath;
/**
* Executed Before Processing of Chunk and Validates all required fields
*/
exports.beforeStep = function () {
var args = arguments[0];
updateCustomDateExportPreference = args.UpdateFromDatePreference;
maxNoOfRows = args.MaxNumberOfRows - 1000;
targetFolder = args.TargetFolder;
FileNamePrefix = args.FileNamePrefix;
generatePreInitFile = args.GeneratePreInitFile;
var orderStatusForExport = [];
if(args.NEW){
orderStatusForExport.push('status=' + Order.ORDER_STATUS_NEW);
}
if(args.CANCELLED){
orderStatusForExport.push('status=' + Order.ORDER_STATUS_CANCELLED);
}
if(args.OPEN){
orderStatusForExport.push('status=' + Order.ORDER_STATUS_OPEN);
}
if(args.CREATED){
orderStatusForExport.push('status=' + Order.ORDER_STATUS_CREATED);
}
if(args.FAILED){
orderStatusForExport.push('status=' + Order.ORDER_STATUS_FAILED);
}
if(args.REPLACED){
orderStatusForExport.push('status=' + Order.ORDER_STATUS_REPLACED);
}
if(args.COMPLETED){
orderStatusForExport.push('status=' + Order.ORDER_STATUS_COMPLETED);
}
try {
feedFileGenerationDate = new Date();
var feedFile = csvGeneratorHelper.createPurchaseFeedFile(FileNamePrefix,targetFolder,fileNum);
webDavFilePath = 'https://' + dw.system.System.getInstanceHostname().toString() + '/on/demandware.servlet/webdav/Sites' + feedFile.fullPath.toString();
fw = new FileWriter(feedFile);
csw = new CSVStreamWriter(fw);
var getAttrSitePref = csvGeneratorHelper.getPurchaseFeedFileHeaders();
var results = csvGeneratorHelper.getFeedAttributes(getAttrSitePref);
headers = results.headers;
SFCCAttributesValue = results.SFCCAttributesValue;
csw.writeNext(headers);
var PurchaseLastRun = null;
if (updateCustomDateExportPreference) {
var lastPurchaseExportCO = CustomObjectMgr.getCustomObject('BloomreachEngagementJobLastExecution', 'lastPurchaseExport');
PurchaseLastRun = lastPurchaseExportCO ? lastPurchaseExportCO.custom.lastExecution : null;
}
ordersToProcess = csvGeneratorHelper.getOrdersForPurchaseFeed(orderStatusForExport,PurchaseLastRun);
if (generatePreInitFile && ordersToProcess.hasNext()) {
var firstOrder = ordersToProcess.next();
const ArrayList = require('dw/util/ArrayList');
var arrOrders = new ArrayList();
arrOrders.push(firstOrder);
ordersToProcess = arrOrders.iterator();
}
} catch (e) {
logger.error('Error: {0}', e.message);
return new Status(Status.ERROR);
}
};
/**
* Executed Before Processing of Chunk and Return total order processed
* @returns {number} order count
*/
exports.getTotalCount = function () {
if (generatePreInitFile)
return 1;
Logger.info('Processed orders {0}', ordersToProcess.count);
return ordersToProcess.count;
};
/**
* Returns a single order to processed
* @returns order - order
*/
exports.read = function () { // eslint-disable-line consistent-return
while (ordersToProcess.hasNext()) {
return ordersToProcess.next();
}
};
/**
* Process order and returns required field in array
* @param order - Product
* @returns {Array} csvOrderArray : Order Details
*/
exports.process = function (bloomreachOrderObject) { // eslint-disable-line consistent-return
try {
var csvOrderArray = csvGeneratorHelper.writePurchaseFeedRow(csw,headers,SFCCAttributesValue,bloomreachOrderObject);
return csvOrderArray;
} catch (ex) {
processedAll = false;
Logger.info('Not able to process order {0} having error {1}', bloomreachOrderObject.orderNo, ex.toString());
}
};
/**
* Executes after processing of every chunk
*/
exports.afterChunk = function () {
chunks++;
Logger.info('Chunk {0} processed successfully', chunks);
};
/**
* Writes a single order to file
* @param {dw.util.List} lines to write
*/
exports.write = function (lines) {
if (rowsCount > maxNoOfRows) {
splitFile();
}
for (var i = 0; i < lines.size(); i++) {
csw.writeNext(lines.get(i).toArray());
}
rowsCount = rowsCount + lines.size();
};
function triggerFileImport() {
var purchaseFeedImportId = currentSite.getCustomPreferenceValue("brEngPurchaseFeedImportId");
var result = BREngagementAPIHelper.bloomReachEngagementAPIService(purchaseFeedImportId, webDavFilePath);
}
function splitFile() {
triggerFileImport();
fw.flush();
csw.close();
fw.close();
fileNum = fileNum + 1;
rowsCount = 1;
if (!targetFolder) {
throw new Error('One or more mandatory parameters are missing.');
}
var feedFile = csvGeneratorHelper.createPurchaseFeedFile(FileNamePrefix,targetFolder,fileNum);
webDavFilePath = 'https://' + dw.system.System.getInstanceHostname().toString() + '/on/demandware.servlet/webdav/Sites' + feedFile.fullPath.toString();
fw = new FileWriter(feedFile);
csw = new CSVStreamWriter(fw);
headers = JSON.parse(csvGeneratorHelper.getPurchaseFeedFileHeaders());
csw.writeNext(Object.keys(headers));
}
/**
* Executes after processing all the chunk and returns the status
* @returns {Object} OK || ERROR
*/
exports.afterStep = function () {
if (!generatePreInitFile) {
ordersToProcess.close();
}
fw.flush();
csw.close();
fw.close();
if (processedAll) {
triggerFileImport();
if(updateCustomDateExportPreference) {
if (currentSite) {
var siteCurrentTime = currentSite.getCalendar().getTime();
var lastPurchaseExportCO = CustomObjectMgr.getCustomObject('BloomreachEngagementJobLastExecution', 'lastPurchaseExport');
if (lastPurchaseExportCO) {
Transaction.wrap(function() {
lastPurchaseExportCO.custom.lastExecution = siteCurrentTime;
});
} else {
Transaction.wrap(function() {
var newPurchaseExportCO = CustomObjectMgr.createCustomObject('BloomreachEngagementJobLastExecution', 'lastPurchaseExport');
newPurchaseExportCO.custom.lastExecution = siteCurrentTime;
});
}
}
}
Logger.info('Export Order Feed Successful');
return new Status(Status.OK, 'OK', 'Export Order Feed Successful');
}
throw new Error('Could not process all the orders');
};