-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathemailOverview.ts
More file actions
417 lines (354 loc) · 11.2 KB
/
emailOverview.ts
File metadata and controls
417 lines (354 loc) · 11.2 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
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
/**
* Sample HTTP server for previewing of email templates
*
* How to use:
*
* 1. yarn email-overview
* 2. Open http://localhost:4444/
*
*/
import * as http from 'http';
import * as url from 'url';
import templates, { Template } from '../src/templates';
import type { TemplateVariables, TemplateEventData } from 'hawk-worker-sender/types/template-variables';
import * as Twig from 'twig';
import { DatabaseController } from '../../../lib/db/controller';
import { GroupedEventDBScheme, ProjectDBScheme, UserDBScheme, WorkspaceDBScheme } from '@hawk.so/types';
import { ObjectId } from 'mongodb';
import * as path from 'path';
import * as dotenv from 'dotenv';
import { HttpStatusCode } from '../../../lib/utils/consts';
import { countDaysAfterPayday } from '../../../lib/utils/payday';
/**
* Merge email worker .env and root workers .env
*/
const rootEnv = dotenv.config({ path: path.resolve(__dirname, '../../../.env') }).parsed;
const localEnv = dotenv.config({ path: path.resolve(__dirname, '../.env') }).parsed;
Object.assign(process.env, rootEnv, localEnv);
/**
* Server for rendering email templates
*/
class EmailTestServer {
/**
* Node.js http server
*/
private server: http.Server;
/**
* Events DB
*/
private eventsDb: DatabaseController = new DatabaseController(process.env.MONGO_EVENTS_DATABASE_URI);
/**
* Accounts DB
*/
private accountsDb: DatabaseController = new DatabaseController(process.env.MONGO_ACCOUNTS_DATABASE_URI);
/**
* Server port
*/
private readonly port: number;
/**
* Creates server
*
* @param port - port to expose
*/
constructor(port: number) {
this.port = port;
this.server = http.createServer(async (req, res) => {
try {
await this.onRequest(req, res);
} catch (error) {
console.log('Error: ', error);
this.sendHTML(error.message, res);
}
});
}
/**
* Starts server
*/
public async start(): Promise<void> {
await this.eventsDb.connect();
await this.accountsDb.connect();
this.server.listen(this.port);
this.server.on('listening', () => {
const link = `http://localhost:${this.port}/`;
console.log('\x1b[36m%s\x1b[0m', '\nEmail overview is now available on ' + link + '\n');
});
this.server.on('error', (error) => {
console.log('Failed to run server', error);
});
}
/**
* Request handler
*
* @param request - accepted request
* @param response - response that will be sent
*/
private async onRequest(request: http.IncomingMessage, response: http.ServerResponse): Promise<void> {
const queryParams = (new url.URL(request.url, `http://localhost:${this.port}`)).searchParams;
console.log('Got request: ', request.url);
if (!queryParams) {
return;
}
const email = queryParams.get('email');
const projectId = queryParams.get('projectId');
const workspaceId = queryParams.get('workspaceId');
const userId = queryParams.get('users');
const eventIds = queryParams.getAll('eventIds');
const type = queryParams.get('type');
if (request.url.includes('fetchEvents')) {
this.fetchEvents(projectId as string, response);
return;
}
if (!email) {
this.showForm(response);
return;
}
const project = await this.getProject(projectId);
const workspace = await this.getWorkspace(workspaceId);
const user = await this.getUser(userId);
const ids = typeof eventIds === 'string' ? [ eventIds ] : eventIds;
const events = await Promise.all(ids.map(async (eventId: string) => {
const [event, daysRepeated] = await this.getEventData(projectId as string, eventId.trim());
return {
event,
daysRepeated,
newCount: 3,
usersAffected: 144,
};
})) as TemplateEventData[];
const templateData = {
events,
host: process.env.GARAGE_URL || 'http://localhost:8080',
hostOfStatic: process.env.API_STATIC_URL || 'http://localhost:4000/static',
project,
workspace,
user,
period: 10,
reason: 'error on the payment server side',
daysAfterPayday: countDaysAfterPayday(workspace.lastChargeDate, workspace.paidUntil),
daysAfterBlock: 5,
daysLeft: 3,
eventsCount: workspace.billingPeriodEventsCount,
eventsLimit: 100000,
tariffPlanId: '5f47f031ff71510040f433c1',
password: '1as2eadd321a3cDf',
plan: {
name: 'Корпоративный',
},
workspaceName: workspace.name,
};
try {
const { subject, text, html } = await this.render(email as string, templateData);
switch (type) {
case 'text':
this.sendHTML(text.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + '<br>' + '$2'), response);
break;
case 'subject':
this.sendHTML(subject, response);
break;
default:
this.sendHTML(html, response);
break;
}
} catch (e) {
console.log('Rendering error', e);
}
}
/**
* Render form to fill GET params
*
* @param response - node http response stream
*/
private async showForm(response: http.ServerResponse): Promise<void> {
const projects = await this.getAllProjects();
const workspaces = await this.getAllWorkspaces();
const users = await this.getAllUsers();
const renderForm = (): Promise<string> => new Promise((resolve, reject): void => {
Twig.renderFile(path.resolve(__dirname, 'emailOverviewForm.twig'),
{
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore because @types/twig doesn't match the docs
templates: Object.keys(templates),
projects,
workspaces,
users,
},
(err: Error, result: string) => {
if (err) {
reject(err);
}
resolve(result);
});
});
const form = await renderForm();
this.sendHTML(form as string, response);
}
/**
* Sends HTML to browser
*
* @param html - what to send
* @param response - node http response stream
*/
private sendHTML(html: string, response: http.ServerResponse): void {
response.writeHead(HttpStatusCode.Ok, {
'Content-Type': 'text/html; charset=utf-8',
});
response.write(html);
response.end();
}
/**
* Sends JSON to browser
*
* @param json - what to send
* @param response - node http response stream
*/
private sendJSON(json: Record<string, unknown> | unknown[], response: http.ServerResponse): void {
response.writeHead(HttpStatusCode.Ok, {
'Content-Type': 'application/json',
});
response.write(JSON.stringify(json));
response.end();
}
/**
* Render email template
*
* @param templateName - template to render
* @param variables - variables for template
*/
private async render(templateName: string, variables: TemplateVariables): Promise<Template> {
const template: Template = templates[templateName];
const renderedTemplate: Template = {
subject: '',
text: '',
html: '',
};
await Promise.all(Object.keys(template).map((key) => {
return new Promise(
(resolve, reject) => Twig.renderFile(
template[key as keyof Template],
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore because @types/twig doesn't match the docs
variables,
(err: Error, res: string): void => {
if (err) {
console.log('Rendering error', err);
reject(err);
}
renderedTemplate[key as keyof Template] = res;
resolve(null);
})
);
}));
return renderedTemplate;
}
/**
* Return events by project id
*
* @param projectId - events owner
* @param response - http response stream
*/
private async fetchEvents(projectId: string, response: http.ServerResponse): Promise<void> {
const events = await this.getEventsByProjectId(projectId);
this.sendJSON(events, response);
}
/**
* Get event data for email
*
* @param projectId - project events are related to
* @param eventId - id of event
*/
private async getEventData(
projectId: string,
eventId: string
): Promise<[GroupedEventDBScheme, number]> {
const connection = await this.eventsDb.getConnection();
const event = await connection.collection(`events:${projectId}`).findOne({
_id: new ObjectId(eventId),
});
const daysRepeated = await connection.collection(`dailyEvents:${projectId}`).countDocuments({
groupHash: event.groupHash,
});
return [event, daysRepeated];
}
/**
* Get project info
*
* @param projectId - project id
*/
private async getProject(projectId: string): Promise<ProjectDBScheme | null> {
const connection = await this.accountsDb.getConnection();
return connection.collection('projects').findOne({ _id: new ObjectId(projectId) });
}
/**
* Get workspace info
*
* @param workspaceId - workspace id
*/
private async getWorkspace(workspaceId: string): Promise<WorkspaceDBScheme | null> {
const connection = await this.accountsDb.getConnection();
return connection.collection('workspaces').findOne({ _id: new ObjectId(workspaceId) });
}
/**
* Calculate days after payday
* Return number of days after payday. If payday is in the future, return 0
*
* @param workspace - workspace data
* @returns {Promise<number>} number of days after payday
*/
private async calculateDaysAfterPayday(
workspace: WorkspaceDBScheme
): Promise<number> {
if (!workspace.lastChargeDate) {
return 0;
}
const days = countDaysAfterPayday(workspace.lastChargeDate, workspace.paidUntil);
return days > 0 ? days : 0;
}
/**
* Get user info
*
* @param userId - user id
*/
private async getUser(userId: string): Promise<UserDBScheme | null> {
const connection = await this.accountsDb.getConnection();
return connection.collection('users').findOne({ _id: new ObjectId(userId) });
}
/**
* Get all projects
*/
private async getAllProjects(): Promise<ProjectDBScheme[]> {
const connection = await this.accountsDb.getConnection();
return connection.collection('projects').find(null, { limit: 10 })
.toArray();
}
/**
* Get all workspaces
*/
private async getAllWorkspaces(): Promise<WorkspaceDBScheme[]> {
const connection = await this.accountsDb.getConnection();
return connection.collection('workspaces').find(null, { limit: 10 })
.toArray();
}
/**
* Get all users
*/
private async getAllUsers(): Promise<UserDBScheme[]> {
const connection = await this.accountsDb.getConnection();
return connection.collection('users').find(null, { limit: 10 })
.toArray();
}
/**
* Get all projects
*
* @param projectId - project id
*/
private async getEventsByProjectId(projectId: string): Promise<GroupedEventDBScheme[]> {
const connection = await this.eventsDb.getConnection();
return connection.collection(`events:${projectId}`).find(null, {
limit: 30,
})
.toArray();
}
}
const EMAIL_TEST_SERVER_PORT = 4444;
const server = new EmailTestServer(EMAIL_TEST_SERVER_PORT);
server.start();