@driveflux/api-functions 0.0.3 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/auth/confirm.js +73 -327
  2. package/dist/auth/emails.js +43 -210
  3. package/dist/auth/formatter.js +11 -11
  4. package/dist/auth/otp.js +122 -392
  5. package/dist/auth/register.d.ts +1 -1
  6. package/dist/auth/register.js +100 -396
  7. package/dist/auth/tokens.js +115 -430
  8. package/dist/auth/verifications.js +154 -512
  9. package/dist/constants.js +5 -4
  10. package/dist/mailjet/calls/manage-contacts-in-list.js +22 -166
  11. package/dist/mailjet/calls/manage-subscription-status.js +13 -153
  12. package/dist/mailjet/calls/request-service.js +18 -183
  13. package/dist/mailjet/refresh-email-preferences.js +26 -225
  14. package/dist/mailjet/set-contact.js +23 -214
  15. package/dist/mailjet/types.js +2 -1
  16. package/dist/mailjet/utils/convert-to-array.js +9 -58
  17. package/dist/mailjet/utils/extract-email-preferences.js +41 -217
  18. package/dist/mailjet/utils/lists.js +30 -249
  19. package/dist/mailjet/utils/update-email-references.js +27 -208
  20. package/dist/notion/client.js +48 -197
  21. package/dist/notion/helpful.js +29 -170
  22. package/dist/notion/schemas/block.js +49 -43
  23. package/dist/notion/schemas/common.js +17 -14
  24. package/dist/notion/schemas/database.js +125 -159
  25. package/dist/notion/schemas/emoji.js +3 -2
  26. package/dist/notion/schemas/file.js +10 -10
  27. package/dist/notion/schemas/kb.js +9 -8
  28. package/dist/notion/schemas/page.js +126 -171
  29. package/dist/notion/schemas/parent.js +9 -8
  30. package/dist/notion/schemas/user.js +21 -20
  31. package/dist/reservation/agree.js +19 -158
  32. package/dist/reservation/checks.js +23 -178
  33. package/dist/reservation/display-vehicle.js +142 -514
  34. package/dist/reservation/fetch-or-create.js +197 -482
  35. package/dist/reservation/invoice.d.ts.map +1 -1
  36. package/dist/reservation/invoice.js +199 -501
  37. package/dist/reservation/invoice.js.map +1 -1
  38. package/dist/reservation/payer.js +28 -177
  39. package/dist/reservation/reserve.js +31 -191
  40. package/dist/reservation/types.js +2 -1
  41. package/dist/reservation/vehicle.js +24 -186
  42. package/dist/slack.js +67 -273
  43. package/dist/validation.d.ts +11 -11
  44. package/dist/validation.d.ts.map +1 -1
  45. package/dist/validation.js +63 -96
  46. package/dist/validation.js.map +1 -1
  47. package/dist/vehicle/vehicle-pricing/constants.js +33 -36
  48. package/dist/vehicle/vehicle-pricing/index.js +99 -257
  49. package/dist/vehicle/vehicle-pricing/types.js +2 -1
  50. package/package.json +10 -10
@@ -1,532 +1,174 @@
1
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
2
- try {
3
- var info = gen[key](arg);
4
- var value = info.value;
5
- } catch (error) {
6
- reject(error);
7
- return;
8
- }
9
- if (info.done) {
10
- resolve(value);
11
- } else {
12
- Promise.resolve(value).then(_next, _throw);
13
- }
14
- }
15
- function _async_to_generator(fn) {
16
- return function() {
17
- var self = this, args = arguments;
18
- return new Promise(function(resolve, reject) {
19
- var gen = fn.apply(self, args);
20
- function _next(value) {
21
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
22
- }
23
- function _throw(err) {
24
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
25
- }
26
- _next(undefined);
27
- });
28
- };
29
- }
30
- function _ts_generator(thisArg, body) {
31
- var f, y, t, _ = {
32
- label: 0,
33
- sent: function() {
34
- if (t[0] & 1) throw t[1];
35
- return t[1];
36
- },
37
- trys: [],
38
- ops: []
39
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
40
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
41
- return this;
42
- }), g;
43
- function verb(n) {
44
- return function(v) {
45
- return step([
46
- n,
47
- v
48
- ]);
49
- };
50
- }
51
- function step(op) {
52
- if (f) throw new TypeError("Generator is already executing.");
53
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
54
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
55
- if (y = 0, t) op = [
56
- op[0] & 2,
57
- t.value
58
- ];
59
- switch(op[0]){
60
- case 0:
61
- case 1:
62
- t = op;
63
- break;
64
- case 4:
65
- _.label++;
66
- return {
67
- value: op[1],
68
- done: false
69
- };
70
- case 5:
71
- _.label++;
72
- y = op[1];
73
- op = [
74
- 0
75
- ];
76
- continue;
77
- case 7:
78
- op = _.ops.pop();
79
- _.trys.pop();
80
- continue;
81
- default:
82
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
83
- _ = 0;
84
- continue;
85
- }
86
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
87
- _.label = op[1];
88
- break;
89
- }
90
- if (op[0] === 6 && _.label < t[1]) {
91
- _.label = t[1];
92
- t = op;
93
- break;
94
- }
95
- if (t && _.label < t[2]) {
96
- _.label = t[2];
97
- _.ops.push(op);
98
- break;
99
- }
100
- if (t[2]) _.ops.pop();
101
- _.trys.pop();
102
- continue;
103
- }
104
- op = body.call(thisArg, _);
105
- } catch (e) {
106
- op = [
107
- 6,
108
- e
109
- ];
110
- y = 0;
111
- } finally{
112
- f = t = 0;
113
- }
114
- if (op[0] & 5) throw op[1];
115
- return {
116
- value: op[0] ? op[1] : void 0,
117
- done: true
118
- };
119
- }
120
- }
121
1
  import { config } from '@driveflux/config/backend';
122
2
  import { prisma } from '@driveflux/db';
123
3
  import { send } from '@driveflux/email';
124
4
  import { verificationEmail } from '@driveflux/email-templates/flux/verification';
125
5
  import { enhancedFetch } from '@driveflux/fetch';
126
- import { makeProblem, PROBLEM_CONFLICT, PROBLEM_EXTERNAL, PROBLEM_INTERNAL, PROBLEM_INVALID_DATA, PROBLEM_NOT_FOUND, PROBLEM_NOT_IMPLEMENTED } from '@driveflux/problem';
6
+ import { makeProblem, PROBLEM_CONFLICT, PROBLEM_EXTERNAL, PROBLEM_INTERNAL, PROBLEM_INVALID_DATA, PROBLEM_NOT_FOUND, PROBLEM_NOT_IMPLEMENTED, } from '@driveflux/problem';
127
7
  import { reportProblem } from '@driveflux/reporter';
128
8
  import { Err, Ok } from '@driveflux/result';
129
9
  import { z } from 'zod';
130
10
  import { cleanupPhoneNumber } from './formatter.js';
131
11
  import { clearToken, createEmailToken, createSMSToken } from './tokens.js';
132
- var CheckDuplicationBody = z.object({
12
+ const CheckDuplicationBody = z.object({
133
13
  phoneNumber: z.string(),
134
- email: z.string().transform(function(email) {
135
- return email.toLowerCase().trim();
136
- })
14
+ email: z.string().transform((email) => email.toLowerCase().trim()),
137
15
  });
138
- export var sendVerificationEmail = function(userId, temporaryEmail, next) {
139
- return _async_to_generator(function() {
140
- var user, _tmp, results, destinationEmail, token, updatedUser, tokens, query, link, title, html, result, e;
141
- return _ts_generator(this, function(_state) {
142
- switch(_state.label){
143
- case 0:
144
- if (!(typeof userId === 'string')) return [
145
- 3,
146
- 2
147
- ];
148
- return [
149
- 4,
150
- prisma.user.findUnique({
151
- where: {
152
- id: userId
153
- }
154
- })
155
- ];
156
- case 1:
157
- _tmp = _state.sent();
158
- return [
159
- 3,
160
- 3
161
- ];
162
- case 2:
163
- _tmp = userId;
164
- _state.label = 3;
165
- case 3:
166
- user = _tmp;
167
- if (!user) {
168
- return [
169
- 2,
170
- new Err(makeProblem(PROBLEM_NOT_FOUND, "User ".concat(typeof userId === 'string' ? userId : 'unknown', " not found.")))
171
- ];
172
- }
173
- if (!temporaryEmail) return [
174
- 3,
175
- 5
176
- ];
177
- return [
178
- 4,
179
- verifyEmailUsage(temporaryEmail)
180
- ];
181
- case 4:
182
- results = _state.sent();
183
- if (results === null || results === void 0 ? void 0 : results.err) {
184
- return [
185
- 2,
186
- results
187
- ];
188
- }
189
- _state.label = 5;
190
- case 5:
191
- destinationEmail = temporaryEmail || user.email;
192
- return [
193
- 4,
194
- createEmailToken(user.id, destinationEmail)
195
- ];
196
- case 6:
197
- token = _state.sent();
198
- if (!token) {
199
- return [
200
- 2,
201
- new Err(makeProblem(PROBLEM_NOT_IMPLEMENTED, 'Token was not created'))
202
- ];
203
- }
204
- return [
205
- 4,
206
- prisma.user.update({
207
- where: {
208
- id: user.id
209
- },
210
- data: {
211
- temporaryEmail: destinationEmail
212
- },
213
- include: {
214
- tokens: true
215
- }
216
- })
217
- ];
218
- case 7:
219
- updatedUser = _state.sent();
220
- tokens = updatedUser === null || updatedUser === void 0 ? void 0 : updatedUser.tokens;
221
- if (!tokens) return [
222
- 3,
223
- 9
224
- ];
225
- return [
226
- 4,
227
- Promise.allSettled(tokens.map(function(userToken) {
228
- return _async_to_generator(function() {
229
- return _ts_generator(this, function(_state) {
230
- switch(_state.label){
231
- case 0:
232
- if (!(userToken.scope === 'verify-email' && userToken.id !== token.id)) return [
233
- 3,
234
- 2
235
- ];
236
- return [
237
- 4,
238
- clearToken(userToken.id)
239
- ];
240
- case 1:
241
- return [
242
- 2,
243
- _state.sent()
244
- ];
245
- case 2:
246
- return [
247
- 2
248
- ];
249
- }
250
- });
251
- })();
252
- }))
253
- ];
254
- case 8:
255
- _state.sent();
256
- _state.label = 9;
257
- case 9:
258
- // Query object for the link
259
- query = new URLSearchParams({
260
- email: destinationEmail,
261
- token: token.id,
262
- code: token.value
263
- });
264
- if (next) {
265
- query.append('next', next);
266
- }
267
- link = "".concat(config.appUrl, "/verify?").concat(query);
268
- title = temporaryEmail ? 'Confirm email change' : 'Verify your email address';
269
- _state.label = 10;
270
- case 10:
271
- _state.trys.push([
272
- 10,
273
- 12,
274
- ,
275
- 13
276
- ]);
277
- // Generate html
278
- html = verificationEmail({
279
- user: user.firstName || '',
280
- link: link,
281
- title: "".concat(title),
282
- newEmail: temporaryEmail,
283
- isChanging: !!temporaryEmail
284
- });
285
- return [
286
- 4,
287
- send({
288
- to: {
289
- name: user.firstName || '',
290
- address: destinationEmail
291
- },
292
- subject: "".concat(title),
293
- html: html
294
- })
295
- ];
296
- case 11:
297
- result = _state.sent();
298
- if (result.err) {
299
- console.error('Error sending email:', result.val);
300
- return [
301
- 2,
302
- new Err(makeProblem('email_not_sent', 'Unable to send the verification email'))
303
- ];
304
- }
305
- return [
306
- 2,
307
- new Ok({
308
- success: true,
309
- link: link
310
- })
311
- ];
312
- case 12:
313
- e = _state.sent();
314
- return [
315
- 2,
316
- new Err(makeProblem('email_not_sent', e.message))
317
- ];
318
- case 13:
319
- return [
320
- 2
321
- ];
16
+ export const sendVerificationEmail = async (userId, temporaryEmail, next) => {
17
+ const user = typeof userId === 'string'
18
+ ? await prisma.user.findUnique({ where: { id: userId } })
19
+ : userId;
20
+ if (!user) {
21
+ return new Err(makeProblem(PROBLEM_NOT_FOUND, `User ${typeof userId === 'string' ? userId : 'unknown'} not found.`));
22
+ }
23
+ if (temporaryEmail) {
24
+ const results = await verifyEmailUsage(temporaryEmail);
25
+ if (results?.err) {
26
+ return results;
27
+ }
28
+ }
29
+ const destinationEmail = temporaryEmail || user.email;
30
+ const token = await createEmailToken(user.id, destinationEmail);
31
+ if (!token) {
32
+ return new Err(makeProblem(PROBLEM_NOT_IMPLEMENTED, 'Token was not created'));
33
+ }
34
+ const updatedUser = await prisma.user.update({
35
+ where: {
36
+ id: user.id,
37
+ },
38
+ data: {
39
+ temporaryEmail: destinationEmail,
40
+ },
41
+ include: {
42
+ tokens: true,
43
+ },
44
+ });
45
+ const tokens = updatedUser?.tokens;
46
+ if (tokens) {
47
+ await Promise.allSettled(tokens.map(async (userToken) => {
48
+ if (userToken.scope === 'verify-email' && userToken.id !== token.id) {
49
+ return await clearToken(userToken.id);
322
50
  }
51
+ return;
52
+ }));
53
+ }
54
+ // Query object for the link
55
+ const query = new URLSearchParams({
56
+ email: destinationEmail,
57
+ token: token.id,
58
+ code: token.value,
59
+ });
60
+ if (next) {
61
+ query.append('next', next);
62
+ }
63
+ const link = `${config.appUrl}/verify?${query}`;
64
+ const title = temporaryEmail
65
+ ? 'Confirm email change'
66
+ : 'Verify your email address';
67
+ try {
68
+ // Generate html
69
+ const html = verificationEmail({
70
+ user: user.firstName || '',
71
+ link,
72
+ title: `${title}`,
73
+ newEmail: temporaryEmail,
74
+ isChanging: !!temporaryEmail,
323
75
  });
324
- })();
325
- };
326
- export var verifyEmailUsage = function(newEmail) {
327
- return _async_to_generator(function() {
328
- var existingEmail;
329
- return _ts_generator(this, function(_state) {
330
- switch(_state.label){
331
- case 0:
332
- // TODO: add email regex checking
333
- if (newEmail.length < 3) {
334
- return [
335
- 2,
336
- new Err(makeProblem(PROBLEM_INVALID_DATA, 'Email address needs minimum 3 characters'))
337
- ];
338
- }
339
- return [
340
- 4,
341
- prisma.user.findFirst({
342
- where: {
343
- email: newEmail
344
- }
345
- })
346
- ];
347
- case 1:
348
- existingEmail = _state.sent();
349
- if (existingEmail) {
350
- return [
351
- 2,
352
- new Err(makeProblem(PROBLEM_INVALID_DATA, 'The email address is already in use'))
353
- ];
354
- }
355
- return [
356
- 2,
357
- new Ok({})
358
- ];
359
- }
76
+ // send email
77
+ const result = await send({
78
+ to: {
79
+ name: user.firstName || '',
80
+ address: destinationEmail,
81
+ },
82
+ subject: `${title}`,
83
+ html,
360
84
  });
361
- })();
85
+ if (result.err) {
86
+ console.error('Error sending email:', result.val);
87
+ return new Err(makeProblem('email_not_sent', 'Unable to send the verification email'));
88
+ }
89
+ return new Ok({ success: true, link });
90
+ }
91
+ catch (e) {
92
+ return new Err(makeProblem('email_not_sent', e.message));
93
+ }
362
94
  };
363
- export var sendVerificationSMS = function(userId, phoneNumber) {
364
- return _async_to_generator(function() {
365
- var token;
366
- return _ts_generator(this, function(_state) {
367
- switch(_state.label){
368
- case 0:
369
- return [
370
- 4,
371
- createSMSToken(userId, phoneNumber)
372
- ];
373
- case 1:
374
- token = _state.sent();
375
- if (!token) {
376
- return [
377
- 2,
378
- new Err(makeProblem(PROBLEM_NOT_IMPLEMENTED, 'Token was not created'))
379
- ];
380
- }
381
- return [
382
- 4,
383
- sendSms(phoneNumber, token.value)
384
- ];
385
- case 2:
386
- return [
387
- 2,
388
- _state.sent()
389
- ];
390
- }
391
- });
392
- })();
95
+ export const verifyEmailUsage = async (newEmail) => {
96
+ // TODO: add email regex checking
97
+ if (newEmail.length < 3) {
98
+ return new Err(makeProblem(PROBLEM_INVALID_DATA, 'Email address needs minimum 3 characters'));
99
+ }
100
+ const existingEmail = await prisma.user.findFirst({
101
+ where: {
102
+ email: newEmail,
103
+ },
104
+ });
105
+ if (existingEmail) {
106
+ return new Err(makeProblem(PROBLEM_INVALID_DATA, 'The email address is already in use'));
107
+ }
108
+ return new Ok({});
393
109
  };
394
- var sendSms = function(phoneNumber, code) {
395
- return _async_to_generator(function() {
396
- var body, result, _, e, _1;
397
- return _ts_generator(this, function(_state) {
398
- switch(_state.label){
399
- case 0:
400
- _state.trys.push([
401
- 0,
402
- 4,
403
- ,
404
- 6
405
- ]);
406
- body = {
407
- user: config.esms.apiKey,
408
- pass: config.esms.apiSecret,
409
- to: cleanupPhoneNumber(phoneNumber),
410
- msg: "RM0.00 FLUX verification code: ".concat(code),
411
- sender: 'FLUX'
412
- };
413
- return [
414
- 4,
415
- enhancedFetch('https://api.esms.com.my/sms/send', {
416
- method: 'POST',
417
- body: JSON.stringify(body)
418
- })
419
- ];
420
- case 1:
421
- result = _state.sent();
422
- if (!result.err) return [
423
- 3,
424
- 3
425
- ];
426
- _ = Err.bind;
427
- return [
428
- 4,
429
- reportProblem(makeProblem({
430
- type: 'public',
431
- code: PROBLEM_EXTERNAL,
432
- message: 'Unable to send sms verification',
433
- privateMetadata: {
434
- error: result.val
435
- }
436
- }))
437
- ];
438
- case 2:
439
- return [
440
- 2,
441
- new (_.apply(Err, [
442
- void 0,
443
- _state.sent()
444
- ]))
445
- ];
446
- case 3:
447
- return [
448
- 2,
449
- new Ok({
450
- success: true,
451
- code: code
452
- })
453
- ];
454
- case 4:
455
- e = _state.sent();
456
- _1 = Err.bind;
457
- return [
458
- 4,
459
- reportProblem(makeProblem({
460
- type: 'public',
461
- code: PROBLEM_INTERNAL,
462
- message: 'Unable to send sms verification',
463
- privateMetadata: {
464
- error: e
465
- }
466
- }))
467
- ];
468
- case 5:
469
- return [
470
- 2,
471
- new (_1.apply(Err, [
472
- void 0,
473
- _state.sent()
474
- ]))
475
- ];
476
- case 6:
477
- return [
478
- 2
479
- ];
480
- }
481
- });
482
- })();
110
+ export const sendVerificationSMS = async (userId, phoneNumber) => {
111
+ const token = await createSMSToken(userId, phoneNumber);
112
+ if (!token) {
113
+ return new Err(makeProblem(PROBLEM_NOT_IMPLEMENTED, 'Token was not created'));
114
+ }
115
+ return await sendSms(phoneNumber, token.value);
483
116
  };
484
- export var handleCheckDuplication = function(b) {
485
- return _async_to_generator(function() {
486
- var _CheckDuplicationBody_parse, phoneNumber, email, checkForEmail, checkForMobile;
487
- return _ts_generator(this, function(_state) {
488
- switch(_state.label){
489
- case 0:
490
- _CheckDuplicationBody_parse = CheckDuplicationBody.parse(b), phoneNumber = _CheckDuplicationBody_parse.phoneNumber, email = _CheckDuplicationBody_parse.email;
491
- return [
492
- 4,
493
- prisma.user.findFirst({
494
- where: {
495
- email: email.toLowerCase().trim()
496
- }
497
- })
498
- ];
499
- case 1:
500
- checkForEmail = _state.sent();
501
- if (checkForEmail) {
502
- return [
503
- 2,
504
- new Err(makeProblem(PROBLEM_CONFLICT, 'This email is already registered. Are you trying to sign in?'))
505
- ];
506
- }
507
- return [
508
- 4,
509
- prisma.user.findFirst({
510
- where: {
511
- phoneNumber: phoneNumber.replace(/[\s-]/g, '')
512
- }
513
- })
514
- ];
515
- case 2:
516
- checkForMobile = _state.sent();
517
- if (checkForMobile) {
518
- return [
519
- 2,
520
- new Err(makeProblem(PROBLEM_CONFLICT, 'The phone number is already in use. Please try a different one.'))
521
- ];
522
- }
523
- return [
524
- 2,
525
- new Ok({
526
- notDuplicate: true
527
- })
528
- ];
529
- }
117
+ const sendSms = async (phoneNumber, code) => {
118
+ try {
119
+ const body = {
120
+ user: config.esms.apiKey,
121
+ pass: config.esms.apiSecret,
122
+ to: cleanupPhoneNumber(phoneNumber),
123
+ msg: `RM0.00 FLUX verification code: ${code}`,
124
+ sender: 'FLUX',
125
+ };
126
+ const result = await enhancedFetch('https://api.esms.com.my/sms/send', {
127
+ method: 'POST',
128
+ body: JSON.stringify(body),
530
129
  });
531
- })();
130
+ if (result.err) {
131
+ return new Err(await reportProblem(makeProblem({
132
+ type: 'public',
133
+ code: PROBLEM_EXTERNAL,
134
+ message: 'Unable to send sms verification',
135
+ privateMetadata: {
136
+ error: result.val,
137
+ },
138
+ })));
139
+ }
140
+ return new Ok({ success: true, code });
141
+ }
142
+ catch (e) {
143
+ return new Err(await reportProblem(makeProblem({
144
+ type: 'public',
145
+ code: PROBLEM_INTERNAL,
146
+ message: 'Unable to send sms verification',
147
+ privateMetadata: {
148
+ error: e,
149
+ },
150
+ })));
151
+ }
152
+ };
153
+ export const handleCheckDuplication = async (b) => {
154
+ const { phoneNumber, email } = CheckDuplicationBody.parse(b);
155
+ // Check if the user exists
156
+ const checkForEmail = await prisma.user.findFirst({
157
+ where: {
158
+ email: email.toLowerCase().trim(),
159
+ },
160
+ });
161
+ if (checkForEmail) {
162
+ return new Err(makeProblem(PROBLEM_CONFLICT, 'This email is already registered. Are you trying to sign in?'));
163
+ }
164
+ const checkForMobile = await prisma.user.findFirst({
165
+ where: {
166
+ phoneNumber: phoneNumber.replace(/[\s-]/g, ''),
167
+ },
168
+ });
169
+ if (checkForMobile) {
170
+ return new Err(makeProblem(PROBLEM_CONFLICT, 'The phone number is already in use. Please try a different one.'));
171
+ }
172
+ return new Ok({ notDuplicate: true });
532
173
  };
174
+ //# sourceMappingURL=verifications.js.map