-
Notifications
You must be signed in to change notification settings - Fork 1
/
operations.js
675 lines (528 loc) · 19 KB
/
operations.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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
var hash = require('./hash');
function nonEmpty40(value) {
if (!value.trim()) {
return 'This is mandatory';
}
if (value.length > 40) {
return 'This must be shorter than 40 characters';
}
};
var ADDRESS_FIELD_VALIDATORS = {
firstname: nonEmpty40,
lastname: nonEmpty40,
street: nonEmpty40,
city: nonEmpty40,
tel: function (value) {
var phone = parseInt(value);
if (isNaN(phone)) {
return "This is not a valid phone number.";
}
},
zip: function(value) {
var zip = parseInt(value);
if (isNaN(zip) || zip > 9999 || zip < 1000 || value.length != 4) {
return 'This is not a valid zip code';
}
},
email: function (value) {
if (value.length > 50) {
return 'You have a pretty long email address';
}
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!re.test(value)) {
return 'This is not a valid email address';
}
}
};
var REVIEW_FIELD_VALIDATORS = {
accept: function(value) {
if (!value) {
return 'You must accept the Terms';
}
}
};
function validateAddress(dataArray, hasAlt) {
var errors = [];
for (var i in dataArray) {
var name = dataArray[i].name;
if (name.indexOf("delivery") !== -1 && !hasAlt) {
return errors;
}
name = name.substring(name.lastIndexOf(".") + 1);
var validator = ADDRESS_FIELD_VALIDATORS[name];
if (typeof validator === 'function') {
var error = validator(dataArray[i].value);
if (error) {
errors.push({ name: dataArray[i].name, message: error });
}
}
}
return errors;
}
function validateReview(dataArray) {
var errors = [];
var found = false;
for (var i in dataArray) {
if (dataArray[i].name === 'accept') {
dataArray[i].value = dataArray[i].value === 'on' || dataArray[i].value === true;
found = true;
}
}
if (!found) {
dataArray.push({ name: 'accept', value: false });
}
for (var i in dataArray) {
var validator = REVIEW_FIELD_VALIDATORS[dataArray[i].name];
if (typeof validator === 'function') {
var error = validator(dataArray[i].value);
if (error) {
errors.push({ name: dataArray[i].name, message: error });
}
}
}
return errors;
}
var PAGE_FORM_VALIDATORS = {
address: validateAddress,
review: validateReview
};
function validatePage(page, dataArray, hasAlt) {
var pageValidator = PAGE_FORM_VALIDATORS[page];
var errors;
if (typeof pageValidator === 'function') {
errors = pageValidator(dataArray, hasAlt);
}
return errors;
}
/* =============================================== */
exports.getPageData = function(link) {
var data = link.data;
if (!data) {
link.send(400, "Missing data.");
return;
}
if (!data.page) {
link.send(400, "Missing page key of data.");
return;
}
getSettings(link.params.dsSettings, function(err, settings) {
if (err || !settings) {
link.send(500, "Error while accessing the settings");
return;
}
// TODO add a mechanism to check all these default setting options to avoid multiple code checks
settings.payments = settings.payments || {};
var checkout = link.session.checkout || {};
var pageData = validateFormNew(link, checkout, data.page);
var urls = settings.payments.urls || {};
getCart(link.params.dsCarts, link.session._sid, function (err, cart) {
if (err) {
link.send(400, err);
return;
}
// cart is empty, redirect to shop page
if (!cart || !cart.items || JSON.stringify(cart.items) === "{}") {
var shopUrl = urls.shop || "/";
link.res.headers["Location"] = shopUrl;
var res = {
"redirect": shopUrl
};
link.send(200, res);
return;
}
var paid = false;
if (link.session && link.session.checkout && link.session.checkout.paid && link.session.checkout.paid.query) {
paid = true;
}
// verify payment
if (pageData.page === "payment" && paid) {
pageData.page = "confirmation";
}
if (pageData.page === "confirmation" && !paid) {
pageData.page = "review";
}
// validate limits
settings.limits = settings.limits || {};
settings.limits = {
min: settings.limits.min || 0,
max: settings.limits.max || 0
}
var limits = settings.limits;
var subtotal = checkout.costs.subtotal;
if (subtotal < limits.min || subtotal > limits.max) {
pageData.page = "cart"
}
switch (pageData.page) {
case 'review':
pageData.data = pageData.data || [];
pageData.data = pageData.data.concat(checkout.address);
break;
case 'payment':
var pspid = settings.payments.pspid;
var passphrase = settings.payments.passphrase;
checkout.costs = checkout.costs || {};
var formData = {
PSPID: pspid,
ORDERID: link.session.payments.orderid,
LANGUAGE: 'de_CH',
CURRENCY: 'CHF',
AMOUNT: checkout.costs.total
};
// user data
var fname, lname;
for (var i in checkout.address) {
switch (checkout.address[i].name) {
case 'invoice.firstname':
fname = checkout.address[i].value;
break;
case 'invoice.lastname':
lname = checkout.address[i].value;
break;
case 'invoice.email':
formData.EMAIL = checkout.address[i].value;
break;
case 'invoice.street':
formData.OWNERADDRESS = checkout.address[i].value;
break;
case 'invoice.city':
formData.OWNERTOWN = checkout.address[i].value;
break;
case 'invoice.region':
formData.OWNERCTY = checkout.address[i].value;
break;
case 'invoice.tel':
formData.OWNERTELNO = checkout.address[i].value;
break;
}
}
formData.CN = fname + ' ' + lname;
// redirect urls
var protocol = (link.req.connection.encrypted ? "https://" : "http://");
var operationLink = protocol + link.req.headers.host + "/@/" + link.operation.module + "/paymentResult";
formData.ACCEPTURL = operationLink + "?s=a";
formData.DECLINEURL = operationLink + "?s=d";
formData.EXCEPTIONURL = operationLink + "?s=e";
formData.CANCELURL = operationLink + "?s=c";
formData.CATALOGURL = urls.shop;
formData.HOMEURL = urls.home;
// look and feel
var lookAndFeel = settings.payments.lookAndFeel;
for (var prop in lookAndFeel) {
formData[prop.toUpperCase()] = lookAndFeel[prop];
}
// sign the form data object
formData = hash.sign(formData, passphrase);
pageData.data = formData;
link.send(200, pageData);
}
if (pageData.page !== "payment") {
link.send(200, pageData);
}
});
});
};
var PAGE_ORDER = ['address', 'review', 'payment', 'confirmation'];
function validateFormNew (link, checkout, page) {
var result = {
data: [],
errors: [],
page: page
};
for (var i in PAGE_ORDER) {
result.page = PAGE_ORDER[i];
result.data = checkout[PAGE_ORDER[i]];
// if no data was saved so far for this page show no errors
if (!result.data) {
break;
}
// validate the up to the current page
result.errors = validatePage(result.page, result.data);
if (result.errors && result.errors.length) {
break;
}
// we reached the desired page
if (result.page === page) {
break;
}
}
return result;
}
exports.savePageData = function(link) {
var data = link.data;
if (!data) {
link.send(400, "Missing data.");
return;
}
if (!data.page) {
link.send(400, "Missing page key of data.");
return;
}
if (!data.form) {
link.send(400, "Missing form key of data.");
return;
}
var hasAlt = false;
for (var i in data.form) {
if (data.form[i].name === "hasAlt") {
hasAlt = true;
break;
}
}
var errors = validatePage(data.page, data.form, hasAlt);
// we found an error
if (errors && errors.length) {
link.send(200, { data: data.form, errors: errors, page: data.page });
return;
}
var valid = true;
if (!hasAlt) {
for (var i = 0; i < data.form.length; ++i) {
var info = data.form[i].name.split(".");
if (info[0] === "delivery") {
for (var j = 0; j < data.form.length; ++j) {
var secundInfo = data.form[j].name.split(".");
if (secundInfo[1] === info[1]) {
data.form[i].value = data.form[j].value;
break;
}
}
}
}
}
var checkout = link.session.checkout || {};
checkout[data.page] = data.form;
if (data.page === "address") {
checkout["confirmation"] = data.form;
}
if (data.page === "payment") {
checkout.paying = true;
}
link.session.set({ checkout: checkout }, function (err) {
if (err) {
link.send(400, err);
return;
}
var formData = validateFormNew(link, checkout, data.page);
// reset the accept field on every change
if (checkout['review']) {
checkout['review'].accept = false;
}
link.send(200, formData);
});
};
exports.paymentResult = function (link) {
var session = link.session || {};
var checkout = session.checkout || {};
if (!checkout.address) { return link.send(400, "Address array is required."); }
if (!checkout.review) { return link.send(400, "Accept terms and conditions."); }
if (!checkout.payment) { return link.send(400, "You have to pay, first."); }
var query = link.query;
if (!query.s) { return link.send(400, "Missing s key."); }
getSettings(link.params.dsSettings, function (err, settings) {
if (err) {
link.send(400, err);
return;
}
getCart(link.params.dsCarts, link.session._sid, function (err, cart) {
if (err) {
link.send(400, err);
return;
}
// cart is empty, redirect
if (!cart || JSON.stringify(cart.items) === "{}") {
var shopUrl = (settings.payments.urls || {}).shop || "/";
link.res.headers["Location"] = shopUrl;
link.send(302);
return;
}
var redirectLink;
var payments = settings.payments = settings.payments || {};
payments.urls = payments.urls || {};
if (!payments.passphrase) { return link.send(400, "Message to admin: passphrase is undefined."); }
if (!payments.pspid) { return link.send(400, "Message to admin: pspid is undefined."); }
var s = query.s;
delete query.s;
switch (s) {
/////////////////////////
// Accept
/////////////////////////
case "a":
var shasign = query.SHASIGN;
if (!shasign) { return link.send(400, "Missing SHASIGN."); }
delete query.SHASIGN;
var signedHash = hash.sign(link.query, payments.passphrase);
if (!signedHash || shasign !== signedHash.SHASIGN) {
return link.send(400, "Invalid SHASIGN.");
}
redirectLink = payments.urls.accepturl;
break;
/////////////////////////
// Decline
/////////////////////////
case "d":
redirectLink = payments.urls.declineurl;
break;
/////////////////////////
// Cancel
/////////////////////////
case "c":
redirectLink = payments.urls.cancelurl;
break;
/////////////////////////
// Cancel
/////////////////////////
case "e":
redirectLink = payments.urls.exceptionurl;
break;
}
if (s === "a") {
var paid = {
query: link.query
};
var checkout = link.session.checkout || {};
checkout.paid = paid;
checkout.paying = false;
link.session.set({ checkout: checkout }, function (err) {
if (err) {
link.send(400, err);
return;
}
link.res.headers["Location"] = redirectLink;
link.send(302);
});
return;
}
var checkout = link.session.checkout || {};
checkout.paying = false;
link.session.set({ checkout: checkout }, function (err) {
var payments = link.session.payments || {};
payments.trials = payments.trials || 1;
payments.orderid = cart._id + "_" + (++payments.trials);
link.session.set({ payments: payments }, function (err) {
link.res.headers["Location"] = redirectLink;
link.send(302);
});
});
});
});
};
exports.placeOrder = function(link) {
// validate address
if (!link.params || !link.params.orderFile) {
link.send(400, "Missing orderFile from placeOrder operation parameters.");
return;
}
if (!link.session.checkout) {
link.send(400, "The checkout object is missing.");
return;
}
if (!link.session.checkout.costs) {
link.send(400, "The checkout.costs object is missing.");
return;
}
var checkout = link.session.checkout;
if (!checkout.address || !checkout.address.length) {
link.send(400, "The address array is missing.");
return;
}
if (!checkout.address || !checkout.payment.length) {
link.send(400, "The payment array is missing.");
return;
}
if (!checkout.paid && !checkout.paid.query) {
link.send(400, "Oh, you have to accept paying, first!");
return;
}
// insert the the cart info, totals and user information in orders collection
getCart(link.params.dsCarts, link.session._sid, function (err, cart) {
if (err) {
link.send(400, err);
return;
}
getCollection(link.params.dsOrders, function (err, ordersCollection) {
if (err) {
link.send(400, err);
return;
}
var costs = link.session.checkout.costs;
var userInfo = {
invoice: {},
delivery: {}
};
// build the user info object
for (var i in checkout.address) {
var current = checkout.address[i];
var info = current.name.split(".");
userInfo[info[0]][info[1]] = current.value;
}
var newDocument = {
id: link.session.payments.orderid,
cart: cart,
totals: costs,
userInfo: userInfo
};
ordersCollection.insert(newDocument, function (err, doc) {
if (err) {
link.send(400, err);
return;
}
var Order;
try {
Order = require(M.app.getPath() + '/' + link.params.orderFile);
} catch (e) {
link.session.end(true, function() {
link.send(400, e.message);
});
return;
}
Order.start(link.session, link.params, function (err, data) {
if (err) { console.error(err); }
link.session.end(true, function() {
link.send(200, data);
});
});
});
});
});
};
function getCollection (dataSourceName, callback) {
M.datasource.resolve(dataSourceName, function(err, ds) {
if (err) {
callback(err);
return;
}
M.database.open(ds, function(err, db) {
if (err) {
callback(err);
return;
}
db.collection(ds.collection, callback);
});
});
}
function getSettings(dataSourceName, callback) {
getCollection(dataSourceName, function (err, collection) {
if (err) { return callback(err); }
collection.findOne({}, callback);
});
}
/*
* Get the cart
*
* Returns in the callback:
* - error: first parameter or
* - the document that contains the items from the cart
*
* */
function getCart (dsCart, sid, callback) {
getCollection(dsCart, function (err, collection ) {
if (err) {
callback(err);
return;
}
collection.findOne({ _id: sid }, function(err, cart) {
if (err) { return callback(err); }
callback(null, cart);
});
});
}