-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget-tracking-no.js
110 lines (92 loc) · 2.86 KB
/
get-tracking-no.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
if (!process.env.NETLIFY) {
require("dotenv").config();
}
const { GoogleSpreadsheet } = require("google-spreadsheet");
const {
GOOGLE_SERVICE_ACCOUNT_EMAIL,
GOOGLE_PRIVATE_KEY,
GOOGLE_SPREADSHEET_ID_FROM_URL,
} = process.env;
if (!GOOGLE_SERVICE_ACCOUNT_EMAIL)
throw new Error("No GOOGLE_SERVICE_ACCOUNT_EMAIL env var set");
if (!GOOGLE_PRIVATE_KEY) throw new Error("No GOOGLE_PRIVATE_KEY env var set");
if (!GOOGLE_SPREADSHEET_ID_FROM_URL)
throw new Error("No GOOGLE_SPREADSHEET_ID_FROM_URL env var set");
exports.handler = async (event) => {
if (event.httpMethod !== "POST") {
return {
statusCode: 405,
body: JSON.stringify({ error: "Method Not Allowed!" }),
headers: { Allow: "POST" },
};
}
const { reference_no = null } = JSON.parse(event.body);
let validationError = [];
if (!reference_no) {
let error = {
field: "reference_no",
message: "No Reference Number. Submitted",
};
validationError.push(error);
}
if (validationError.length > 0) {
return {
statusCode: 422,
body: JSON.stringify({ errors: validationError }),
};
}
try {
const doc = new GoogleSpreadsheet(GOOGLE_SPREADSHEET_ID_FROM_URL);
await doc.useServiceAccountAuth({
client_email: GOOGLE_SERVICE_ACCOUNT_EMAIL,
private_key: GOOGLE_PRIVATE_KEY.replace(/\\n/g, "\n"),
});
await doc.loadInfo();
const sheet = doc.sheetsById[1];
const rows = await sheet.getRows();
const rowIndex = rows.findIndex((x) => x.reference_no == reference_no);
if (rowIndex == -1) {
let error = {
statusCode: 404,
body: JSON.stringify({ error: "Reference Number Not Found!" }),
};
return error;
}
const {
tracking_no = "",
courier = "",
sent = null,
deliverable = true
} = rows[rowIndex];
if (!deliverable || deliverable === "FALSE") {
return {
statusCode: 400,
body: JSON.stringify({
message: "Order is Not Considered as *Deliverable*",
}),
};
}
if (!sent || (sent && sent.toLowerCase() != "yes")) {
return {
statusCode: 400,
body: JSON.stringify({
message: "Order Not Yet Delivered",
}),
};
}
return {
statusCode: 200,
body: JSON.stringify({
tracking_no,
courier,
sent,
}),
};
} catch (e) {
console.log(e.toString());
return {
statusCode: 500,
body: e.toString(),
};
}
};