@driveflux/api-functions 0.0.7-next.2 → 0.0.7-next.21

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 (98) 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 +102 -398
  7. package/dist/auth/register.js.map +1 -1
  8. package/dist/auth/tokens.js +115 -430
  9. package/dist/auth/verifications.js +177 -583
  10. package/dist/constants.js +5 -4
  11. package/dist/mailjet/calls/manage-contacts-in-list.d.ts +2 -2
  12. package/dist/mailjet/calls/manage-contacts-in-list.d.ts.map +1 -1
  13. package/dist/mailjet/calls/manage-contacts-in-list.js +24 -168
  14. package/dist/mailjet/calls/manage-contacts-in-list.js.map +1 -1
  15. package/dist/mailjet/calls/manage-subscription-status.d.ts +2 -2
  16. package/dist/mailjet/calls/manage-subscription-status.d.ts.map +1 -1
  17. package/dist/mailjet/calls/manage-subscription-status.js +14 -154
  18. package/dist/mailjet/calls/manage-subscription-status.js.map +1 -1
  19. package/dist/mailjet/calls/request-service.d.ts +1 -1
  20. package/dist/mailjet/calls/request-service.d.ts.map +1 -1
  21. package/dist/mailjet/calls/request-service.js +18 -183
  22. package/dist/mailjet/refresh-email-preferences.js +26 -225
  23. package/dist/mailjet/set-contact.d.ts +2 -2
  24. package/dist/mailjet/set-contact.d.ts.map +1 -1
  25. package/dist/mailjet/set-contact.js +26 -217
  26. package/dist/mailjet/set-contact.js.map +1 -1
  27. package/dist/mailjet/types.d.ts +2 -2
  28. package/dist/mailjet/types.d.ts.map +1 -1
  29. package/dist/mailjet/types.js +2 -1
  30. package/dist/mailjet/utils/convert-to-array.d.ts +1 -1
  31. package/dist/mailjet/utils/convert-to-array.d.ts.map +1 -1
  32. package/dist/mailjet/utils/convert-to-array.js +9 -58
  33. package/dist/mailjet/utils/extract-email-preferences.d.ts +1 -1
  34. package/dist/mailjet/utils/extract-email-preferences.d.ts.map +1 -1
  35. package/dist/mailjet/utils/extract-email-preferences.js +41 -217
  36. package/dist/mailjet/utils/lists.js +30 -249
  37. package/dist/mailjet/utils/update-email-references.d.ts +2 -2
  38. package/dist/mailjet/utils/update-email-references.d.ts.map +1 -1
  39. package/dist/mailjet/utils/update-email-references.js +27 -208
  40. package/dist/mailjet/utils/update-email-references.js.map +1 -1
  41. package/dist/notion/client.js +48 -197
  42. package/dist/notion/helpful.js +29 -170
  43. package/dist/notion/schemas/block.js +49 -43
  44. package/dist/notion/schemas/common.js +17 -14
  45. package/dist/notion/schemas/database.js +125 -159
  46. package/dist/notion/schemas/emoji.js +3 -2
  47. package/dist/notion/schemas/file.js +10 -10
  48. package/dist/notion/schemas/kb.js +9 -8
  49. package/dist/notion/schemas/page.js +126 -171
  50. package/dist/notion/schemas/parent.js +9 -8
  51. package/dist/notion/schemas/user.js +21 -20
  52. package/dist/reservation/agree.d.ts +1 -1
  53. package/dist/reservation/agree.d.ts.map +1 -1
  54. package/dist/reservation/agree.js +19 -158
  55. package/dist/reservation/checks.d.ts +1 -1
  56. package/dist/reservation/checks.d.ts.map +1 -1
  57. package/dist/reservation/checks.js +23 -178
  58. package/dist/reservation/display-vehicle.d.ts +17 -17
  59. package/dist/reservation/display-vehicle.js +142 -514
  60. package/dist/reservation/display-vehicle.js.map +1 -1
  61. package/dist/reservation/fetch-or-create.d.ts +2 -2
  62. package/dist/reservation/fetch-or-create.d.ts.map +1 -1
  63. package/dist/reservation/fetch-or-create.js +199 -482
  64. package/dist/reservation/fetch-or-create.js.map +1 -1
  65. package/dist/reservation/invoice.d.ts +3 -3
  66. package/dist/reservation/invoice.d.ts.map +1 -1
  67. package/dist/reservation/invoice.js +198 -496
  68. package/dist/reservation/invoice.js.map +1 -1
  69. package/dist/reservation/payer.d.ts +1 -1
  70. package/dist/reservation/payer.d.ts.map +1 -1
  71. package/dist/reservation/payer.js +28 -177
  72. package/dist/reservation/reserve.d.ts +1 -1
  73. package/dist/reservation/reserve.d.ts.map +1 -1
  74. package/dist/reservation/reserve.js +36 -196
  75. package/dist/reservation/reserve.js.map +1 -1
  76. package/dist/reservation/types.d.ts +1 -0
  77. package/dist/reservation/types.d.ts.map +1 -1
  78. package/dist/reservation/types.js +2 -1
  79. package/dist/reservation/vehicle.d.ts +1 -1
  80. package/dist/reservation/vehicle.d.ts.map +1 -1
  81. package/dist/reservation/vehicle.js +26 -188
  82. package/dist/reservation/vehicle.js.map +1 -1
  83. package/dist/slack.d.ts +2 -2
  84. package/dist/slack.d.ts.map +1 -1
  85. package/dist/slack.js +67 -273
  86. package/dist/validation.d.ts +4 -4
  87. package/dist/validation.d.ts.map +1 -1
  88. package/dist/validation.js +89 -139
  89. package/dist/validation.js.map +1 -1
  90. package/dist/vehicle/vehicle-pricing/constants.d.ts +1 -1
  91. package/dist/vehicle/vehicle-pricing/constants.d.ts.map +1 -1
  92. package/dist/vehicle/vehicle-pricing/constants.js +33 -36
  93. package/dist/vehicle/vehicle-pricing/index.d.ts +1 -1
  94. package/dist/vehicle/vehicle-pricing/index.d.ts.map +1 -1
  95. package/dist/vehicle/vehicle-pricing/index.js +101 -259
  96. package/dist/vehicle/vehicle-pricing/index.js.map +1 -1
  97. package/dist/vehicle/vehicle-pricing/types.js +2 -1
  98. package/package.json +21 -21
@@ -1,205 +1,6 @@
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 _define_property(obj, key, value) {
31
- if (key in obj) {
32
- Object.defineProperty(obj, key, {
33
- value: value,
34
- enumerable: true,
35
- configurable: true,
36
- writable: true
37
- });
38
- } else {
39
- obj[key] = value;
40
- }
41
- return obj;
42
- }
43
- function _object_spread(target) {
44
- for(var i = 1; i < arguments.length; i++){
45
- var source = arguments[i] != null ? arguments[i] : {};
46
- var ownKeys = Object.keys(source);
47
- if (typeof Object.getOwnPropertySymbols === "function") {
48
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
49
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
50
- }));
51
- }
52
- ownKeys.forEach(function(key) {
53
- _define_property(target, key, source[key]);
54
- });
55
- }
56
- return target;
57
- }
58
- function ownKeys(object, enumerableOnly) {
59
- var keys = Object.keys(object);
60
- if (Object.getOwnPropertySymbols) {
61
- var symbols = Object.getOwnPropertySymbols(object);
62
- if (enumerableOnly) {
63
- symbols = symbols.filter(function(sym) {
64
- return Object.getOwnPropertyDescriptor(object, sym).enumerable;
65
- });
66
- }
67
- keys.push.apply(keys, symbols);
68
- }
69
- return keys;
70
- }
71
- function _object_spread_props(target, source) {
72
- source = source != null ? source : {};
73
- if (Object.getOwnPropertyDescriptors) {
74
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
75
- } else {
76
- ownKeys(Object(source)).forEach(function(key) {
77
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
78
- });
79
- }
80
- return target;
81
- }
82
- function _object_without_properties(source, excluded) {
83
- if (source == null) return {};
84
- var target = _object_without_properties_loose(source, excluded);
85
- var key, i;
86
- if (Object.getOwnPropertySymbols) {
87
- var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
88
- for(i = 0; i < sourceSymbolKeys.length; i++){
89
- key = sourceSymbolKeys[i];
90
- if (excluded.indexOf(key) >= 0) continue;
91
- if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
92
- target[key] = source[key];
93
- }
94
- }
95
- return target;
96
- }
97
- function _object_without_properties_loose(source, excluded) {
98
- if (source == null) return {};
99
- var target = {};
100
- var sourceKeys = Object.keys(source);
101
- var key, i;
102
- for(i = 0; i < sourceKeys.length; i++){
103
- key = sourceKeys[i];
104
- if (excluded.indexOf(key) >= 0) continue;
105
- target[key] = source[key];
106
- }
107
- return target;
108
- }
109
- function _ts_generator(thisArg, body) {
110
- var f, y, t, _ = {
111
- label: 0,
112
- sent: function() {
113
- if (t[0] & 1) throw t[1];
114
- return t[1];
115
- },
116
- trys: [],
117
- ops: []
118
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
119
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
120
- return this;
121
- }), g;
122
- function verb(n) {
123
- return function(v) {
124
- return step([
125
- n,
126
- v
127
- ]);
128
- };
129
- }
130
- function step(op) {
131
- if (f) throw new TypeError("Generator is already executing.");
132
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
133
- 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;
134
- if (y = 0, t) op = [
135
- op[0] & 2,
136
- t.value
137
- ];
138
- switch(op[0]){
139
- case 0:
140
- case 1:
141
- t = op;
142
- break;
143
- case 4:
144
- _.label++;
145
- return {
146
- value: op[1],
147
- done: false
148
- };
149
- case 5:
150
- _.label++;
151
- y = op[1];
152
- op = [
153
- 0
154
- ];
155
- continue;
156
- case 7:
157
- op = _.ops.pop();
158
- _.trys.pop();
159
- continue;
160
- default:
161
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
162
- _ = 0;
163
- continue;
164
- }
165
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
166
- _.label = op[1];
167
- break;
168
- }
169
- if (op[0] === 6 && _.label < t[1]) {
170
- _.label = t[1];
171
- t = op;
172
- break;
173
- }
174
- if (t && _.label < t[2]) {
175
- _.label = t[2];
176
- _.ops.push(op);
177
- break;
178
- }
179
- if (t[2]) _.ops.pop();
180
- _.trys.pop();
181
- continue;
182
- }
183
- op = body.call(thisArg, _);
184
- } catch (e) {
185
- op = [
186
- 6,
187
- e
188
- ];
189
- y = 0;
190
- } finally{
191
- f = t = 0;
192
- }
193
- if (op[0] & 5) throw op[1];
194
- return {
195
- value: op[0] ? op[1] : void 0,
196
- done: true
197
- };
198
- }
199
- }
200
1
  import { config } from '@driveflux/config/backend';
201
2
  import { loadCoupon, PROBLEM_APPLICABLE_NOT_FOUND } from '@driveflux/coupon';
202
- import { prisma } from '@driveflux/db';
3
+ import { prisma, } from '@driveflux/db';
203
4
  import { generateId } from '@driveflux/db/id';
204
5
  import { EMPTY_BILLING_ADDRESS } from '@driveflux/db/models/other';
205
6
  import { PURPOSE_RESERVATION } from '@driveflux/db/models/subscription';
@@ -211,276 +12,176 @@ import { Ok } from '@driveflux/result';
211
12
  import { format } from '@driveflux/time';
212
13
  import { isAfter } from 'date-fns/isAfter';
213
14
  import { subMinutes } from 'date-fns/subMinutes';
214
- export var updateReservationInvoiceIfNeeded = function(oldReservationInvoice, newParams) {
215
- return _async_to_generator(function() {
216
- var couponIsDifferent, update, result, _oldReservationInvoice_discountIds, _result_val, discounts, rest, toDisconnect, disconnectClauses, updated;
217
- return _ts_generator(this, function(_state) {
218
- switch(_state.label){
219
- case 0:
220
- console.log('UPDATING INVOICE IF NEEDED');
221
- couponIsDifferent = oldReservationInvoice.couponCode !== newParams.couponCode;
222
- if (!couponIsDifferent && oldReservationInvoice.stripePaymentIntentId === newParams.paymentIntentId) {
223
- return [
224
- 2,
225
- new Ok(oldReservationInvoice)
226
- ];
227
- }
228
- // If the coupon or payment intent are differnt we should update the invoice
229
- update = {
230
- stripePaymentIntentId: newParams.paymentIntentId,
231
- couponCode: newParams.couponCode
232
- };
233
- if (!couponIsDifferent) return [
234
- 3,
235
- 3
236
- ];
237
- if (!newParams.couponCode) return [
238
- 3,
239
- 2
240
- ];
241
- return [
242
- 4,
243
- coupons.applyCouponToUnsavedInvoice(newParams.couponCode, oldReservationInvoice)
244
- ];
245
- case 1:
246
- result = _state.sent();
247
- if (result.ok) {
248
- ;
249
- _result_val = result.val, discounts = _result_val.discounts, rest = _object_without_properties(_result_val, [
250
- "discounts"
251
- ]);
252
- toDisconnect = discounts ? (_oldReservationInvoice_discountIds = oldReservationInvoice.discountIds) === null || _oldReservationInvoice_discountIds === void 0 ? void 0 : _oldReservationInvoice_discountIds.filter(function(id) {
253
- var _discounts_connect;
254
- return !((_discounts_connect = discounts.connect) === null || _discounts_connect === void 0 ? void 0 : _discounts_connect.some(function(d) {
255
- return d.id === id;
256
- }));
257
- }) : undefined;
258
- disconnectClauses = (toDisconnect === null || toDisconnect === void 0 ? void 0 : toDisconnect.length) ? {
259
- disconnect: toDisconnect.map(function(id) {
260
- return {
261
- id: id
262
- };
263
- })
264
- } : undefined;
265
- update = _object_spread_props(_object_spread({}, update, rest, discounts || disconnectClauses ? {
266
- discounts: _object_spread({}, discounts || {}, disconnectClauses || {})
267
- } : {}), {
268
- metadata: _object_spread_props(_object_spread({}, update.metadata), {
269
- couponCode: newParams.couponCode
270
- }),
271
- providerMetadata: _object_spread_props(_object_spread({}, update.providerMetadata), {
272
- couponCode: newParams.couponCode
273
- })
274
- });
275
- }
276
- if (result.err && result.val.code !== PROBLEM_APPLICABLE_NOT_FOUND) {
277
- return [
278
- 2,
279
- result
280
- ];
15
+ export const updateReservationInvoiceIfNeeded = async (oldReservationInvoice, newParams) => {
16
+ const couponIsDifferent = oldReservationInvoice.couponCode !== newParams.couponCode;
17
+ if (!couponIsDifferent &&
18
+ oldReservationInvoice.stripePaymentIntentId === newParams.paymentIntentId) {
19
+ return new Ok(oldReservationInvoice);
20
+ }
21
+ // If the coupon or payment intent are differnt we should update the invoice
22
+ let update = {
23
+ stripePaymentIntentId: newParams.paymentIntentId,
24
+ couponCode: newParams.couponCode,
25
+ };
26
+ // If the coupon is different, we need to apply the coupon to the invoice
27
+ if (couponIsDifferent) {
28
+ if (newParams.couponCode) {
29
+ const result = await coupons.applyCouponToUnsavedInvoice(newParams.couponCode, oldReservationInvoice);
30
+ if (result.ok) {
31
+ const { discounts, ...rest } = result.val;
32
+ const toDisconnect = discounts
33
+ ? oldReservationInvoice.discountIds?.filter((id) => !discounts.connect?.some((d) => d.id === id))
34
+ : undefined;
35
+ const disconnectClauses = toDisconnect?.length
36
+ ? {
37
+ disconnect: toDisconnect.map((id) => ({ id })),
281
38
  }
282
- return [
283
- 3,
284
- 3
285
- ];
286
- case 2:
287
- if (oldReservationInvoice.discountIds.length) {
288
- // No discounts, so we disconnect all of them
289
- update = {
39
+ : undefined;
40
+ update = {
41
+ ...update,
42
+ ...rest,
43
+ ...(discounts || disconnectClauses
44
+ ? {
290
45
  discounts: {
291
- disconnect: oldReservationInvoice.discountIds.map(function(id) {
292
- return {
293
- id: id
294
- };
295
- })
296
- }
297
- };
298
- }
299
- _state.label = 3;
300
- case 3:
301
- return [
302
- 4,
303
- wrapInResult(biller.updateInvoice(oldReservationInvoice.id, update))
304
- ];
305
- case 4:
306
- updated = _state.sent();
307
- console.log('Updating invoice result', updated);
308
- if (!(updated.err && updated.val.code === 'invoice_pending')) return [
309
- 3,
310
- 6
311
- ];
312
- if (!(oldReservationInvoice.lockedAt && isAfter(oldReservationInvoice.lockedAt, subMinutes(new Date(), 1)) || !oldReservationInvoice.lockedAt)) return [
313
- 3,
314
- 6
315
- ];
316
- return [
317
- 4,
318
- wrapInResult(biller.updateInvoice(oldReservationInvoice.id, _object_spread_props(_object_spread({}, update), {
319
- locked: false,
320
- lockedAt: null,
321
- lockReason: null,
322
- unlockAt: null,
323
- status: 'draft'
324
- })))
325
- ];
326
- case 5:
327
- updated = _state.sent();
328
- _state.label = 6;
329
- case 6:
330
- if (updated.err) {
331
- return [
332
- 2,
333
- updated
334
- ];
335
- }
336
- return [
337
- 2,
338
- new Ok(updated.val)
339
- ];
46
+ ...(discounts || {}),
47
+ ...(disconnectClauses || {}),
48
+ },
49
+ }
50
+ : {}),
51
+ metadata: {
52
+ ...update.metadata,
53
+ couponCode: newParams.couponCode,
54
+ },
55
+ providerMetadata: {
56
+ ...update.providerMetadata,
57
+ couponCode: newParams.couponCode,
58
+ },
59
+ };
340
60
  }
341
- });
342
- })();
343
- };
344
- export var createReservationInvoice = function(param) {
345
- var couponCode = param.couponCode, plan = param.plan, mileagePackage = param.mileagePackage, referralCode = param.referralCode, reservationId = param.reservationId, paymentIntentId = param.paymentIntentId, freeReservation = param.freeReservation, freeReservationReason = param.freeReservationReason, analytics = param.analytics, vehicle = param.vehicle, payer = param.payer, subscribingUser = param.subscribingUser;
346
- return _async_to_generator(function() {
347
- var finalCouponCode, referral, _tmp, referralCoupon, reservationAmount, invoiceCreateDetails, withCoupon;
348
- return _ts_generator(this, function(_state) {
349
- switch(_state.label){
350
- case 0:
351
- if (!freeReservation) return [
352
- 3,
353
- 2
354
- ];
355
- return [
356
- 4,
357
- wrapInResult(biller.createInvoice(getInvoiceCreateDetails({
358
- payer: payer,
359
- vehicle: vehicle,
360
- plan: plan,
361
- mileagePackage: mileagePackage,
362
- paymentIntentId: paymentIntentId,
363
- freeReservation: freeReservation,
364
- freeReservationReason: freeReservationReason,
365
- analytics: analytics,
366
- reservationId: reservationId
367
- })))
368
- ];
369
- case 1:
370
- // It's a free reservation, so we don't need to add a coupon code
371
- return [
372
- 2,
373
- _state.sent()
374
- ];
375
- case 2:
376
- finalCouponCode = couponCode;
377
- _tmp = referralCode;
378
- if (!_tmp) return [
379
- 3,
380
- 4
381
- ];
382
- return [
383
- 4,
384
- prisma.referral.findUnique({
385
- where: {
386
- id: referralCode
387
- }
388
- })
389
- ];
390
- case 3:
391
- _tmp = _state.sent();
392
- _state.label = 4;
393
- case 4:
394
- referral = _tmp;
395
- if (!(!finalCouponCode && referral && referral.discountToReceiverCouponId && referral.discountToReceiverCouponApplicationName === 'reservationFee')) return [
396
- 3,
397
- 6
398
- ];
399
- return [
400
- 4,
401
- loadCoupon(referral.discountToReceiverCouponId)
402
- ];
403
- case 5:
404
- referralCoupon = _state.sent();
405
- if (referralCoupon) {
406
- finalCouponCode = referralCoupon.code;
407
- }
408
- _state.label = 6;
409
- case 6:
410
- reservationAmount = config.reservationFee;
411
- // We leave adding the coupon code applyCouponToUnsavedInvoice()
412
- invoiceCreateDetails = _object_spread_props(_object_spread({}, getInvoiceCreateDetails({
413
- payer: payer,
414
- vehicle: vehicle,
415
- plan: plan,
416
- mileagePackage: mileagePackage,
417
- paymentIntentId: paymentIntentId,
418
- freeReservation: freeReservation,
419
- freeReservationReason: freeReservationReason,
420
- analytics: analytics,
421
- reservationId: reservationId
422
- })), {
423
- lines: [
424
- {
425
- amount: reservationAmount,
426
- description: "Reservation fee for ".concat(vehicleName(vehicle)),
427
- chargingFor: 'reservationFee'
428
- }
429
- ]
430
- });
431
- if (!finalCouponCode) return [
432
- 3,
433
- 8
434
- ];
435
- return [
436
- 4,
437
- coupons.applyCouponToUnsavedInvoice(finalCouponCode, invoiceCreateDetails, 'reservationFee', {
438
- subscriptionPlans: plan,
439
- subscriptionMileagePackages: mileagePackage,
440
- vehicleId: vehicle.id,
441
- vehicleMake: vehicle.make,
442
- userId: subscribingUser.id,
443
- businessId: payer.object === 'business' ? payer.id : undefined,
444
- vehicleType: vehicle.type
445
- })
446
- ];
447
- case 7:
448
- withCoupon = _state.sent();
449
- if (withCoupon.err && withCoupon.val.code !== PROBLEM_APPLICABLE_NOT_FOUND) {
450
- return [
451
- 2,
452
- withCoupon
453
- ];
454
- }
455
- if (withCoupon.ok) {
456
- invoiceCreateDetails = _object_spread_props(_object_spread({}, withCoupon.val), {
457
- metadata: _object_spread_props(_object_spread({}, withCoupon.val.metadata), {
458
- couponCode: finalCouponCode
459
- }),
460
- providerMetadata: _object_spread_props(_object_spread({}, withCoupon.val.providerMetadata), {
461
- couponCode: finalCouponCode
462
- })
463
- });
464
- }
465
- _state.label = 8;
466
- case 8:
467
- return [
468
- 4,
469
- wrapInResult(biller.createInvoice(invoiceCreateDetails))
470
- ];
471
- case 9:
472
- return [
473
- 2,
474
- _state.sent()
475
- ];
61
+ if (result.err && result.val.code !== PROBLEM_APPLICABLE_NOT_FOUND) {
62
+ return result;
476
63
  }
64
+ }
65
+ else if (oldReservationInvoice.discountIds.length) {
66
+ // No discounts, so we disconnect all of them
67
+ update = {
68
+ discounts: {
69
+ disconnect: oldReservationInvoice.discountIds.map((id) => ({
70
+ id,
71
+ })),
72
+ },
73
+ };
74
+ }
75
+ }
76
+ let updated = await wrapInResult(biller.updateInvoice(oldReservationInvoice.id, update));
77
+ // If the invoice was locked due to pending status and we're more than 1 minute old, we unlock it
78
+ if (updated.err && updated.val.code === 'invoice_pending') {
79
+ if ((oldReservationInvoice.lockedAt &&
80
+ isAfter(oldReservationInvoice.lockedAt, subMinutes(new Date(), 1))) ||
81
+ !oldReservationInvoice.lockedAt) {
82
+ updated = await wrapInResult(biller.updateInvoice(oldReservationInvoice.id, {
83
+ ...update,
84
+ locked: false,
85
+ lockedAt: null,
86
+ lockReason: null,
87
+ unlockAt: null,
88
+ status: 'draft',
89
+ }));
90
+ }
91
+ }
92
+ if (updated.err) {
93
+ return updated;
94
+ }
95
+ return new Ok(updated.val);
96
+ };
97
+ export const createReservationInvoice = async ({ invoiceId, couponCode, plan, mileagePackage, referralCode, reservationId, paymentIntentId, freeReservation, freeReservationReason, analytics, vehicle, payer, subscribingUser, }) => {
98
+ if (freeReservation) {
99
+ // It's a free reservation, so we don't need to add a coupon code
100
+ return await wrapInResult(biller.createInvoice(getInvoiceCreateDetails({
101
+ invoiceId,
102
+ payer,
103
+ vehicle,
104
+ plan,
105
+ mileagePackage,
106
+ paymentIntentId,
107
+ freeReservation,
108
+ freeReservationReason,
109
+ analytics,
110
+ reservationId,
111
+ })));
112
+ }
113
+ let finalCouponCode = couponCode;
114
+ // If we don't have a reservation coupon ID, we apply the referral discount if any
115
+ const referral = referralCode &&
116
+ (await prisma.referral.findUnique({
117
+ where: {
118
+ id: referralCode,
119
+ },
120
+ }));
121
+ if (!finalCouponCode &&
122
+ referral &&
123
+ referral.discountToReceiverCouponId &&
124
+ referral.discountToReceiverCouponApplicationName === 'reservationFee') {
125
+ const referralCoupon = await loadCoupon(referral.discountToReceiverCouponId);
126
+ if (referralCoupon) {
127
+ finalCouponCode = referralCoupon.code;
128
+ }
129
+ }
130
+ const reservationAmount = config.reservationFee;
131
+ // We leave adding the coupon code applyCouponToUnsavedInvoice()
132
+ let invoiceCreateDetails = {
133
+ ...getInvoiceCreateDetails({
134
+ invoiceId,
135
+ payer,
136
+ vehicle,
137
+ plan,
138
+ mileagePackage,
139
+ paymentIntentId,
140
+ freeReservation,
141
+ freeReservationReason,
142
+ analytics,
143
+ reservationId,
144
+ }),
145
+ lines: [
146
+ {
147
+ amount: reservationAmount,
148
+ description: `Reservation fee for ${vehicleName(vehicle)}`,
149
+ chargingFor: 'reservationFee',
150
+ },
151
+ ],
152
+ };
153
+ if (finalCouponCode) {
154
+ const withCoupon = await coupons.applyCouponToUnsavedInvoice(finalCouponCode, invoiceCreateDetails, 'reservationFee', {
155
+ subscriptionPlans: plan,
156
+ subscriptionMileagePackages: mileagePackage,
157
+ vehicleId: vehicle.id,
158
+ vehicleMake: vehicle.make,
159
+ userId: subscribingUser.id,
160
+ businessId: payer.object === 'business' ? payer.id : undefined,
161
+ vehicleType: vehicle.type,
477
162
  });
478
- })();
163
+ if (withCoupon.err &&
164
+ withCoupon.val.code !== PROBLEM_APPLICABLE_NOT_FOUND) {
165
+ return withCoupon;
166
+ }
167
+ if (withCoupon.ok) {
168
+ invoiceCreateDetails = {
169
+ ...withCoupon.val,
170
+ metadata: {
171
+ ...withCoupon.val.metadata,
172
+ couponCode: finalCouponCode,
173
+ },
174
+ providerMetadata: {
175
+ ...withCoupon.val.providerMetadata,
176
+ couponCode: finalCouponCode,
177
+ },
178
+ };
179
+ }
180
+ }
181
+ return await wrapInResult(biller.createInvoice(invoiceCreateDetails));
479
182
  };
480
- var getInvoiceCreateDetails = function(param) {
481
- var invoiceId = param.invoiceId, payer = param.payer, date = param.date, reservationDiscountId = param.reservationDiscountId, vehicle = param.vehicle, plan = param.plan, mileagePackage = param.mileagePackage, couponCode = param.couponCode, paymentIntentId = param.paymentIntentId, freeReservation = param.freeReservation, freeReservationReason = param.freeReservationReason, analytics = param.analytics, reservationId = param.reservationId;
482
- var _payer_addresses;
483
- return _object_spread_props(_object_spread({
183
+ const getInvoiceCreateDetails = ({ invoiceId, payer, date, reservationDiscountId, vehicle, plan, mileagePackage, couponCode, paymentIntentId, freeReservation, freeReservationReason, analytics, reservationId, }) => {
184
+ return {
484
185
  id: invoiceId || generateId('Invoice'),
485
186
  taxPercentage: 0,
486
187
  attemptToSavePaymentMethod: true,
@@ -489,19 +190,21 @@ var getInvoiceCreateDetails = function(param) {
489
190
  payerId: payer.id,
490
191
  ownerId: payer.id,
491
192
  payerType: payer.object,
492
- billingAddress: (payer === null || payer === void 0 ? void 0 : (_payer_addresses = payer.addresses) === null || _payer_addresses === void 0 ? void 0 : _payer_addresses.billing) || EMPTY_BILLING_ADDRESS,
493
- date: date !== null && date !== void 0 ? date : new Date(),
193
+ billingAddress: payer?.addresses?.billing || EMPTY_BILLING_ADDRESS,
194
+ date: date ?? new Date(),
494
195
  subscriptionPurpose: PURPOSE_RESERVATION,
495
196
  description: 'Reservation fee for a FLUX subscription',
496
- footer: "Invoice for a FLUX subscription reservation. Due by ".concat(format(date !== null && date !== void 0 ? date : new Date())),
497
- invoiceUrl: "".concat(config.appUrl, "/invoice-preview/").concat(invoiceId)
498
- }, reservationDiscountId ? {
499
- discounts: {
500
- connect: {
501
- id: reservationDiscountId
197
+ footer: `Invoice for a FLUX subscription reservation. Due by ${format(date ?? new Date())}`,
198
+ invoiceUrl: `${config.appUrl}/invoice-preview/${invoiceId}`,
199
+ ...(reservationDiscountId
200
+ ? {
201
+ discounts: {
202
+ connect: {
203
+ id: reservationDiscountId,
204
+ },
205
+ },
502
206
  }
503
- }
504
- } : {}), {
207
+ : {}),
505
208
  lines: [],
506
209
  subscriptionDetails: {
507
210
  vehicleId: vehicle.id,
@@ -510,36 +213,35 @@ var getInvoiceCreateDetails = function(param) {
510
213
  variant: vehicle.variant,
511
214
  year: vehicle.year,
512
215
  plan: plan,
513
- mileagePackage: mileagePackage
216
+ mileagePackage: mileagePackage,
514
217
  },
515
218
  stripePaymentIntentId: paymentIntentId,
516
- providerMetadata: _object_spread({
517
- plan: plan,
518
- mileagePackage: mileagePackage,
219
+ providerMetadata: {
220
+ plan,
221
+ mileagePackage,
519
222
  vehicleId: vehicle.id,
520
- vehicleName: vehicleName(vehicle)
521
- }, reservationId ? {
522
- reservationId: reservationId
523
- } : {}, couponCode ? {
524
- couponCode: couponCode
525
- } : {}),
223
+ vehicleName: vehicleName(vehicle),
224
+ ...(reservationId ? { reservationId } : {}),
225
+ ...(couponCode ? { couponCode } : {}),
226
+ },
526
227
  autoRetry: {
527
228
  enabled: false,
528
229
  interval: 0,
529
230
  maxAttempts: 0,
530
- attempts: 0
231
+ attempts: 0,
531
232
  },
532
- metadata: _object_spread_props(_object_spread({
233
+ metadata: {
533
234
  purpose: PURPOSE_RESERVATION,
534
- reservationId: reservationId,
235
+ reservationId,
535
236
  vehicleName: vehicleName(vehicle),
536
- plan: plan,
537
- mileagePackage: mileagePackage,
538
- couponCode: couponCode
539
- }, freeReservation && freeReservationReason ? {
540
- freeReservationReason: freeReservationReason
541
- } : {}), {
542
- analytics: analytics
543
- })
544
- });
237
+ plan,
238
+ mileagePackage,
239
+ couponCode,
240
+ ...(freeReservation && freeReservationReason
241
+ ? { freeReservationReason }
242
+ : {}),
243
+ analytics,
244
+ },
245
+ };
545
246
  };
247
+ //# sourceMappingURL=invoice.js.map