-
Notifications
You must be signed in to change notification settings - Fork 90
Expand file tree
/
Copy pathhandler.js
More file actions
227 lines (193 loc) · 7.02 KB
/
handler.js
File metadata and controls
227 lines (193 loc) · 7.02 KB
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
const axios = require("axios");
module.exports = { main: async function (event, context) {
console.log(`*** occ url [${process.env['GATEWAY_URL_OCC']}]`);
console.log(`*** fraud api url [${process.env['GATEWAY_URL_FRAUDREPORT']}]`);
console.log(`*** admin api url [${process.env['GATEWAY_URL_ADMINAPI']}]`);
// tracing
var traceCtxHeaders = extractTraceHeaders(event.extensions.request.headers);
orderCode = event.data.orderCode;
bpCode = event.data.processCode;
baseSite = process.env.BASE_SITE;
console.log(`event = ${JSON.stringify(event.data)}`);
console.log(`Processing business process ${bpCode} for order ${orderCode} from site ${baseSite}`);
// retrieve order from Commerce
var order = await getOrder(orderCode, baseSite, traceCtxHeaders);
var results = [];
// run checks
await checkEmailAddress(order, results, traceCtxHeaders);
await checkNumberOfOrders(order, results, traceCtxHeaders);
await checkOrderValue(order, results);
var score = getScore(results);
console.log(`Score for order ${orderCode}: ${score}`);
var returnStatus = 'OK';
if (score >= 100) {
returnStatus= 'POTENTIAL';
console.log(`Order ${orderCode} failed validation`);
await setOrderInvalid(orderCode);
await createFraudReport(orderCode, results, false, traceCtxHeaders);
var msg = `Order ${orderCode} failed validation and has been put on hold :stopwatch: \n`
msg += JSON.stringify(results, null, 2);
await slackMessage(msg);
}
else
{
console.log(`Order ${orderCode} passed validation`);
await createFraudReport(orderCode, results, true, traceCtxHeaders);
var msg = `Order ${orderCode} passed validation :thumbsup:\n`;
//msg += JSON.stringify(results, null, 2);
await slackMessage(msg);
}
await returnBusinessProcessResult(returnStatus, bpCode, traceCtxHeaders);
console.log("returning processing complete.");
return "processing complete";
} }
async function getOrder(code, site, traceCtx) {
const ordersUrl = `${process.env['GATEWAY_URL_OCC']}/${site}/orders/${code}`;
console.log("orderUrl: %s", ordersUrl)
const response = await axios.get(ordersUrl,{headers:traceCtx});
console.log(JSON.stringify(response.data, null, 2))
return response.data;
}
async function checkNumberOfOrders(order, results, traceCtx)
{
const ordersUrl = `${process.env['GATEWAY_URL_OCC']}/${order.store}/users/${order.user.uid}/orders`;
console.log("orderUrl: %s", ordersUrl)
var response = await axios.head(ordersUrl, { headers:traceCtx });
console.log("total number of orders = " + response.headers['x-total-count']);
if (response.headers['x-total-count'] == 1)
{
results.push({
"Name": "Previous orders",
"Result": "Failed",
"Score": 10
});
}
else {
results.push({
"Name": "Previous orders",
"Result": "Passed",
"Score": 0
});
}
}
async function checkEmailAddress(order, results, traceCtx)
{
const response = await axios.get(`${process.env.URL_EMAIL_CHECK_SERVICE}&email=${order.user.uid}`, { headers:traceCtx });
console.log(`Result from email check : ${JSON.stringify(response.data)}`);
if (response.data.disposable)
{
results.push({
"Name": "Disposable email address",
"Result": "Failed",
"Score": 100
});
}
else {
results.push({
"Name": "Disposable email address",
"Result": "Passed",
"Score": 0
});
}
if (response.data.result != 'undeliverable')
{
results.push({
"Name": "Deliverable email address",
"Result": "Passed",
"Score": 0
});
}
else
{
results.push({
"Name": "Deliverable email address",
"Result": "Failed",
"Score": 100
});
}
}
async function checkOrderValue(order, results)
{
if (order.totalPrice.value > 500) {
results.push({
"Name": "High order value",
"Result": "Failed",
"Score": 100
});
}
else
{
results.push({
"Name": "High order value",
"Result": "Passed",
"Score": 0
});
}
}
async function returnBusinessProcessResult(result, bpCode, traceCtx) {
var body = {
"event":`${bpCode}_externalFraudCheckEvent`,
"choice" : result
};
console.log(`BP result - ${JSON.stringify(body)}`);
var postResponse = axios.post(`${process.env['GATEWAY_URL_ADMINAPI']}/businessprocess/events`, body, { headers:traceCtx});
console.log(`BP result response - ${postResponse.status}`);
}
async function setOrderInvalid(orderCode, traceCtx) {
var body = {
code: orderCode,
versionID: null,
potentiallyFraudulent: true,
status: { code : 'CHECKED_INVALID' }
}
console.log("Saving order state");
var postResponse = await axios.post(`${process.env['GATEWAY_URL_FRAUDREPORT']}/Orders`, body, { headers:traceCtx});
return postResponse;
}
async function createFraudReport(orderCode, results, passed, traceCtx)
{
var body = {
code: orderCode + "_FR_0",
order : { code : orderCode},
provider : "xf-lambda",
timestamp : `/Date(${Date.now()})/`,
status: { code : passed ? 'OK' : 'FRAUD' }
}
console.log("Saving fraud report");
var postResponse = await axios.post(`${process.env['GATEWAY_URL_FRAUDREPORT']}/FraudReports`, body, { headers:traceCtx});
for (var r in results) {
var entry = results[r];
var scoringBody = {
name : `${entry.Name} (${entry.Result})`,
score : entry.Score,
explanation : `${entry.Name} (${entry.Result})`,
fraudReport : { code: orderCode + "_FR_0", order: {code : orderCode }}
}
console.log("Saving fraud report scoring");
var entryResponse = await axios.post(`${process.env['GATEWAY_URL_FRAUDREPORT']}/FraudSymptomScorings`, scoringBody, { headers:traceCtx, auth: { username: `${process.env.FRAUD_REPORT_USERNAME}`, password: `${process.env.FRAUD_REPORT_PASSWORD}`}});
console.log(`saving symptom scoring Response: ${entryResponse.status} -- ${entryResponse.body}`);
}
}
function extractTraceHeaders(headers) {
const traceHeaders = ['x-request-id', 'x-b3-traceid', 'x-b3-spanid', 'x-b3-parentspanid', 'x-b3-sampled', 'x-b3-Flags', 'x-ot-span-context']
var map = {};
for (var h in traceHeaders) {
var headerName = traceHeaders[h];
var headerVal = headers[headerName];
if (headerVal !== undefined) {
map[headerName] = headerVal
}
}
return map;
}
function getScore(results)
{
var score = 0;
for (var r in results) {
score += results[r].Score;
}
return score;
}
async function slackMessage(message) {
await axios.post(process.env.SLACK_URL, {text:message});
}