-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler-report.js
286 lines (227 loc) · 7.82 KB
/
handler-report.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
'use strict';
const rp = require('request-promise');
const uuid = require('uuid');
const moment = require('moment');
const wkhtmltopdf = require('wkhtmltopdf');
const fs = require('fs');
const handlebars = require('handlebars');
const AWS = require('aws-sdk');
const helper = require('./helper');
const StringDecoder = require('string_decoder').StringDecoder;
process.env['PATH'] = process.env['PATH'] + ':' + process.env['LAMBDA_TASK_ROOT'];
function CreateHTMLData(data,period){
let from_date = "";
let to_date = "";
let filename = "";
if(period.length > 4) {
const periodyear = parseInt(period.substr(0,4));
const monthyear = parseInt(period.substr(5,2));
const daterange = helper.getMonthDateRange(periodyear, monthyear);
from_date = daterange.start.format("DD/MM/YYYY");
to_date = daterange.end.format("DD/MM/YYYY");
filename = daterange.start.format("DDMMYYYY") + "-" + daterange.end.format("DDMMYYYY")
} else {
from_date = "01/01/"+period;
to_date = "31/12/"+period;
filename = period;
}
let lines = [];
let counter = 1
let total = {
airtrans: 0.00,
lodging: 0.00,
meals: 0.00,
mileage: 0.00,
other: 0.00,
grand: 0.00
};
data.forEach((line) => {
const slot = line.slots;
const receiptdate = moment(slot.receiptdateType,"YYYY-MM-DD");
let receipt = {
nr: counter,
description: "",
date: "",
airtrans: 0.00,
lodging: 0.00,
meals: 0.00,
mileage: 0.00,
other: 0.00,
total: 0.00,
}
if(slot.receiptType === "petrol") {
receipt.description = "Diesel Volkswagen Company Car";
receipt.date = receiptdate.format("DD/MM/YYYY");
receipt.airtrans = slot.amountType;
receipt.total = slot.amountType;
total.airtrans = total.airtrans + receipt.airtrans;
total.grand = total.grand + receipt.airtrans;
} else if(slot.receiptType === "restaurant") {
receipt.description = "Meal " + slot.merchantType;
receipt.date = receiptdate.format("DD/MM/YYYY");
receipt.meals = slot.amountType;
receipt.total = slot.amountType;
total.meals = total.meals + receipt.meals;
total.grand = total.grand + receipt.meals;
}
lines.push(receipt);
counter +=1;
})
let HTMLData = {
name: data[0].first_name + " " + data[0].last_name,
from_date: from_date,
to_date: to_date,
lines: lines,
total: total,
filename: filename
}
console.log("htmldata", JSON.stringify(HTMLData))
return HTMLData;
}
function readDBase(chatId, period, env_variables){
const dynamoDb = new AWS.DynamoDB.DocumentClient();
const timestamp = moment();
let ExpressionAttributeValues = {};
let KeyConditionExpression = "";
if(period.length > 4) {
KeyConditionExpression = "receiptdateyear = :receiptdateyear and receiptdatemonth = :receiptdatemonth";
ExpressionAttributeValues = {
":receiptdateyear": period.substr(0,4),
":receiptdatemonth": period.substr(5,2)
};
} else {
KeyConditionExpression = "receiptdateyear = :receiptdateyear";
ExpressionAttributeValues = {
":receiptdateyear": period
};
};
var params = {
IndexName : env_variables.DYNAMODB_INDEX,
TableName : env_variables.DYNAMODB_TABLE,
KeyConditionExpression: KeyConditionExpression,
ExpressionAttributeValues: ExpressionAttributeValues
};
return dynamoDb.query(params).promise();
}
function convertToPDF(htmlbuffer, chat_id, caption, url, filename, data){
const options = { pageSize: 'A4', 'page-width': '297.039', 'orientation':'Landscape' };
var decoder = new StringDecoder('utf8');
const htmlInput = decoder.write(htmlbuffer);
handlebars.registerHelper('set_decimal', function(num){
return num.toFixed(2);
});
var template = handlebars.compile(htmlInput, { strict: true });
var html = template(data);
return new Promise((resolve, reject) => {
let writeFile = fs.createWriteStream('/tmp/'+filename);
wkhtmltopdf(html, options).pipe(writeFile);
writeFile.on('finish', function(){
const fileUpload = fs.createReadStream('/tmp/'+filename)
var rp_options = {
method: 'POST',
uri: url + "sendDocument",
qs: { chat_id: chat_id,
caption: caption,
document: fileUpload
},
formData: {
document: fileUpload
},
headers: {
'content-type': 'multipart/form-data'
}
};
return resolve(rp(rp_options));
});
writeFile.on('error', function(){
reject();
});
});
}
module.exports.expensy_bot_report = (event, context, callback) => {
const env_variables = {
AWS_REGION: process.env.MY_AWS_REGION,
DYNAMODB_INDEX: process.env.DYNAMODB_INDEX,
CONFIG_BUCKET: process.env.CONFIG_BUCKET,
API_GATEWAY_URL: process.env.API_GATEWAY_URL,
HTML_TEMPLATE_FILE: process.env.HTML_TEMPLATE_FILE,
DYNAMODB_TABLE: process.env.DYNAMODB_TABLE,
}
console.log("env_variables", env_variables)
console.log("event", JSON.stringify(event))
const message = JSON.parse(event.Records[0].Sns.Message);
console.log("message", message)
// File
var file_id = message.file_id;
console.log("file_id", file_id)
// Chat ID
var chatId = message.chatId;
console.log("chatId", chatId)
// From
var userNumber = message.userNumber;
console.log("userNumber", userNumber)
// message_id
var message_id = message.message_id;
console.log("message_id", message_id)
// period_id
var period_id = message.period_id;
console.log("period_id", period_id)
var response = {
statusCode: 200,
body: JSON.stringify({
message: '',
input: event,
}),
};
if (chatId) {
let htmltemplatebody = null;
const loadconfigfile = helper.LoadFileFromS3(env_variables.CONFIG_BUCKET, env_variables.HTML_TEMPLATE_FILE);
loadconfigfile.then((data) => {
console.log("success File Retrieved", data)
htmltemplatebody = data.Body;
return readDBase(chatId, period_id, env_variables);
}).then((data) => {
console.log("Database Queried successfully", data);
response.message = "Database Queried successfully";
const htmldata = CreateHTMLData(data.Items, period_id);
return convertToPDF(htmltemplatebody, chatId, "Expenses Report", env_variables.API_GATEWAY_URL, htmldata.filename+"-expensesreport.pdf",htmldata);
}).then((body) => {
console.log("File Succesfull send to telegram", body);
response.message = "File Succesfull send to telegram";
callback(null, response);
}).catch((err) => {
response.statusCode = 400;
response.message = "Error";
console.log("error", err);
callback(err, "error");
});
/*
const loadconfigfile = helper.LoadFileFromS3(env_variables.CONFIG_BUCKET, env_variables.HTML_TEMPLATE_FILE);
loadconfigfile.then((data) => {
console.log("success File Retrieved", data)
const htmldata = {
title: 'Month Report',
author: '@azat_co',
tags: ['express', 'node', 'javascript']
}
return convertToPDF(data.Body, chatId, "My file", env_variables.API_GATEWAY_URL, "test.pdf",htmldata);
}).then((body) => {
console.log("File Succesfull send to telegram", body);
response.message = "File Succesfull send to telegram";
callback(null, response);
}).catch((err) => {
response.statusCode = 400
response.message = "Error"
console.log("error", err)
callback(err, "error");
});
*/
} else {
response.statusCode = 400
response.message = "No chatId";
callback(response, "failed");
}
callback(null, response);
// Use this code if you don't use the http event with the LAMBDA-PROXY integration
// callback(null, { message: 'Go Serverless v1.0! Your function executed successfully!', event });
};