-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
SubscriptionUtils.ts
461 lines (393 loc) · 13.1 KB
/
SubscriptionUtils.ts
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
import {differenceInSeconds, fromUnixTime, isAfter, isBefore, parse as parseDate} from 'date-fns';
import Onyx from 'react-native-onyx';
import type {OnyxCollection, OnyxEntry} from 'react-native-onyx';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type {BillingGraceEndPeriod, BillingStatus, Fund, FundList, Policy, StripeCustomerID} from '@src/types/onyx';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
import * as PolicyUtils from './PolicyUtils';
const PAYMENT_STATUS = {
POLICY_OWNER_WITH_AMOUNT_OWED: 'policy_owner_with_amount_owed',
POLICY_OWNER_WITH_AMOUNT_OWED_OVERDUE: 'policy_owner_with_amount_owed_overdue',
OWNER_OF_POLICY_UNDER_INVOICING: 'owner_of_policy_under_invoicing',
OWNER_OF_POLICY_UNDER_INVOICING_OVERDUE: 'owner_of_policy_under_invoicing_overdue',
BILLING_DISPUTE_PENDING: 'billing_dispute_pending',
CARD_AUTHENTICATION_REQUIRED: 'authentication_required',
INSUFFICIENT_FUNDS: 'insufficient_funds',
CARD_EXPIRED: 'expired_card',
CARD_EXPIRE_SOON: 'card_expire_soon',
RETRY_BILLING_SUCCESS: 'retry_billing_success',
RETRY_BILLING_ERROR: 'retry_billing_error',
GENERIC_API_ERROR: 'generic_api_error',
} as const;
let currentUserAccountID = -1;
Onyx.connect({
key: ONYXKEYS.SESSION,
callback: (value) => {
currentUserAccountID = value?.accountID ?? -1;
},
});
let amountOwed: OnyxEntry<number>;
Onyx.connect({
key: ONYXKEYS.NVP_PRIVATE_AMOUNT_OWED,
callback: (value) => (amountOwed = value),
});
let stripeCustomerId: OnyxEntry<StripeCustomerID>;
Onyx.connect({
key: ONYXKEYS.NVP_PRIVATE_STRIPE_CUSTOMER_ID,
callback: (value) => {
if (!value) {
return;
}
stripeCustomerId = value;
},
});
let billingDisputePending: OnyxEntry<number>;
Onyx.connect({
key: ONYXKEYS.NVP_PRIVATE_BILLING_DISPUTE_PENDING,
callback: (value) => (billingDisputePending = value),
});
let billingStatus: OnyxEntry<BillingStatus>;
Onyx.connect({
key: ONYXKEYS.NVP_PRIVATE_BILLING_STATUS,
callback: (value) => (billingStatus = value),
});
let ownerBillingGraceEndPeriod: OnyxEntry<number>;
Onyx.connect({
key: ONYXKEYS.NVP_PRIVATE_OWNER_BILLING_GRACE_PERIOD_END,
callback: (value) => (ownerBillingGraceEndPeriod = value),
});
let fundList: OnyxEntry<FundList>;
Onyx.connect({
key: ONYXKEYS.FUND_LIST,
callback: (value) => {
if (!value) {
return;
}
fundList = value;
},
});
let retryBillingSuccessful: OnyxEntry<boolean>;
Onyx.connect({
key: ONYXKEYS.SUBSCRIPTION_RETRY_BILLING_STATUS_SUCCESSFUL,
initWithStoredValues: false,
callback: (value) => {
if (value === undefined) {
return;
}
retryBillingSuccessful = value;
},
});
let retryBillingFailed: OnyxEntry<boolean>;
Onyx.connect({
key: ONYXKEYS.SUBSCRIPTION_RETRY_BILLING_STATUS_FAILED,
callback: (value) => {
if (value === undefined) {
return;
}
retryBillingFailed = value;
},
initWithStoredValues: false,
});
let firstDayFreeTrial: OnyxEntry<string>;
Onyx.connect({
key: ONYXKEYS.NVP_FIRST_DAY_FREE_TRIAL,
callback: (value) => (firstDayFreeTrial = value),
});
let lastDayFreeTrial: OnyxEntry<string>;
Onyx.connect({
key: ONYXKEYS.NVP_LAST_DAY_FREE_TRIAL,
callback: (value) => (lastDayFreeTrial = value),
});
let userBillingFundID: OnyxEntry<number>;
Onyx.connect({
key: ONYXKEYS.NVP_BILLING_FUND_ID,
callback: (value) => (userBillingFundID = value),
});
let userBillingGraceEndPeriodCollection: OnyxCollection<BillingGraceEndPeriod>;
Onyx.connect({
key: ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_USER_BILLING_GRACE_PERIOD_END,
callback: (value) => (userBillingGraceEndPeriodCollection = value),
waitForCollectionCallback: true,
});
let allPolicies: OnyxCollection<Policy>;
Onyx.connect({
key: ONYXKEYS.COLLECTION.POLICY,
callback: (value) => (allPolicies = value),
waitForCollectionCallback: true,
});
/**
* @returns The date when the grace period ends.
*/
function getOverdueGracePeriodDate(): OnyxEntry<number> {
return ownerBillingGraceEndPeriod;
}
/**
* @returns Whether the workspace owner has an overdue grace period.
*/
function hasOverdueGracePeriod(): boolean {
return !!ownerBillingGraceEndPeriod ?? false;
}
/**
* @returns Whether the workspace owner's grace period is overdue.
*/
function hasGracePeriodOverdue(): boolean {
return !!ownerBillingGraceEndPeriod && Date.now() > new Date(ownerBillingGraceEndPeriod).getTime();
}
/**
* @returns The amount owed by the workspace owner.
*/
function getAmountOwed(): number {
return amountOwed ?? 0;
}
/**
* @returns Whether there is an amount owed by the workspace owner.
*/
function hasAmountOwed(): boolean {
return !!amountOwed;
}
/**
* @returns Whether there is a card authentication error.
*/
function hasCardAuthenticatedError() {
return stripeCustomerId?.status === 'authentication_required' && amountOwed === 0;
}
/**
* @returns Whether there is a billing dispute pending.
*/
function hasBillingDisputePending() {
return !!billingDisputePending ?? false;
}
/**
* @returns Whether there is a card expired error.
*/
function hasCardExpiredError() {
return billingStatus?.declineReason === 'expired_card' && amountOwed !== 0;
}
/**
* @returns Whether there is an insufficient funds error.
*/
function hasInsufficientFundsError() {
return billingStatus?.declineReason === 'insufficient_funds' && amountOwed !== 0;
}
/**
* @returns The card to be used for subscription billing.
*/
function getCardForSubscriptionBilling(): Fund | undefined {
return Object.values(fundList ?? {}).find((card) => card?.isDefault);
}
/**
* @returns Whether the card is due to expire soon.
*/
function hasCardExpiringSoon(): boolean {
if (!isEmptyObject(billingStatus)) {
return false;
}
const card = getCardForSubscriptionBilling();
if (!card) {
return false;
}
const cardYear = card?.accountData?.cardYear;
const cardMonth = card?.accountData?.cardMonth;
const currentYear = new Date().getFullYear();
const currentMonth = new Date().getMonth();
const isExpiringThisMonth = cardYear === currentYear && cardMonth === currentMonth;
const isExpiringNextMonth = cardYear === (currentMonth === 12 ? currentYear + 1 : currentYear) && cardMonth === (currentMonth === 12 ? 1 : currentMonth + 1);
return isExpiringThisMonth || isExpiringNextMonth;
}
/**
* @returns Whether there is a retry billing error.
*/
function hasRetryBillingError(): boolean {
return !!retryBillingFailed ?? false;
}
/**
* @returns Whether the retry billing was successful.
*/
function isRetryBillingSuccessful(): boolean {
return !!retryBillingSuccessful ?? false;
}
type SubscriptionStatus = {
status: string;
isError?: boolean;
};
/**
* @returns The subscription status.
*/
function getSubscriptionStatus(): SubscriptionStatus | undefined {
if (hasOverdueGracePeriod()) {
if (hasAmountOwed()) {
// 1. Policy owner with amount owed, within grace period
if (!hasGracePeriodOverdue()) {
return {
status: PAYMENT_STATUS.POLICY_OWNER_WITH_AMOUNT_OWED,
isError: true,
};
}
// 2. Policy owner with amount owed, overdue (past grace period)
if (hasGracePeriodOverdue()) {
return {
status: PAYMENT_STATUS.POLICY_OWNER_WITH_AMOUNT_OWED_OVERDUE,
};
}
} else {
// 3. Owner of policy under invoicing, within grace period
if (!hasGracePeriodOverdue()) {
return {
status: PAYMENT_STATUS.OWNER_OF_POLICY_UNDER_INVOICING,
};
}
// 4. Owner of policy under invoicing, overdue (past grace period)
if (hasGracePeriodOverdue()) {
return {
status: PAYMENT_STATUS.OWNER_OF_POLICY_UNDER_INVOICING_OVERDUE,
};
}
}
}
// 5. Billing disputed by cardholder
if (hasBillingDisputePending()) {
return {
status: PAYMENT_STATUS.BILLING_DISPUTE_PENDING,
};
}
// 6. Card not authenticated
if (hasCardAuthenticatedError()) {
return {
status: PAYMENT_STATUS.CARD_AUTHENTICATION_REQUIRED,
};
}
// 7. Insufficient funds
if (hasInsufficientFundsError()) {
return {
status: PAYMENT_STATUS.INSUFFICIENT_FUNDS,
};
}
// 8. Card expired
if (hasCardExpiredError()) {
return {
status: PAYMENT_STATUS.CARD_EXPIRED,
};
}
// 9. Card due to expire soon
if (hasCardExpiringSoon()) {
return {
status: PAYMENT_STATUS.CARD_EXPIRE_SOON,
};
}
// 10. Retry billing success
if (isRetryBillingSuccessful()) {
return {
status: PAYMENT_STATUS.RETRY_BILLING_SUCCESS,
isError: false,
};
}
// 11. Retry billing error
if (hasRetryBillingError()) {
return {
status: PAYMENT_STATUS.RETRY_BILLING_ERROR,
isError: true,
};
}
return undefined;
}
/**
* @returns Whether there is a subscription red dot error.
*/
function hasSubscriptionRedDotError(): boolean {
return getSubscriptionStatus()?.isError ?? false;
}
/**
* @returns Whether there is a subscription green dot info.
*/
function hasSubscriptionGreenDotInfo(): boolean {
return !getSubscriptionStatus()?.isError ?? false;
}
/**
* Calculates the remaining number of days of the workspace owner's free trial before it ends.
*/
function calculateRemainingFreeTrialDays(): number {
if (!lastDayFreeTrial) {
return 0;
}
const currentDate = new Date();
const diffInSeconds = differenceInSeconds(parseDate(lastDayFreeTrial, CONST.DATE.FNS_DATE_TIME_FORMAT_STRING, currentDate), currentDate);
const diffInDays = Math.ceil(diffInSeconds / 86400);
return diffInDays < 0 ? 0 : diffInDays;
}
/**
* Whether the workspace's owner is on its free trial period.
*/
function isUserOnFreeTrial(): boolean {
if (!firstDayFreeTrial || !lastDayFreeTrial) {
return false;
}
const currentDate = new Date();
const firstDayFreeTrialDate = parseDate(firstDayFreeTrial, CONST.DATE.FNS_DATE_TIME_FORMAT_STRING, currentDate);
const lastDayFreeTrialDate = parseDate(lastDayFreeTrial, CONST.DATE.FNS_DATE_TIME_FORMAT_STRING, currentDate);
return isAfter(currentDate, firstDayFreeTrialDate) && isBefore(currentDate, lastDayFreeTrialDate);
}
/**
* Whether the workspace owner's free trial period has ended.
*/
function hasUserFreeTrialEnded(): boolean {
if (!lastDayFreeTrial) {
return false;
}
const currentDate = new Date();
const lastDayFreeTrialDate = parseDate(lastDayFreeTrial, CONST.DATE.FNS_DATE_TIME_FORMAT_STRING, currentDate);
return isAfter(currentDate, lastDayFreeTrialDate);
}
/**
* Whether the user has a payment card added to its account.
*/
function doesUserHavePaymentCardAdded(): boolean {
return userBillingFundID !== undefined;
}
/**
* Whether the user's billable actions should be restricted.
*/
function shouldRestrictUserBillableActions(policyID: string): boolean {
const currentDate = new Date();
const policy = allPolicies?.[`${ONYXKEYS.COLLECTION.POLICY}${policyID}`];
// This logic will be executed if the user is a workspace's non-owner (normal user or admin).
// We should restrict the workspace's non-owner actions if it's member of a workspace where the owner is
// past due and is past its grace period end.
for (const userBillingGraceEndPeriodEntry of Object.entries(userBillingGraceEndPeriodCollection ?? {})) {
const [entryKey, userBillingGracePeriodEnd] = userBillingGraceEndPeriodEntry;
if (userBillingGracePeriodEnd && isAfter(currentDate, fromUnixTime(userBillingGracePeriodEnd.value))) {
// Extracts the owner account ID from the collection member key.
const ownerAccountID = Number(entryKey.slice(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_USER_BILLING_GRACE_PERIOD_END.length));
if (PolicyUtils.isPolicyOwner(policy, ownerAccountID)) {
return true;
}
}
}
// If it reached here it means that the user is actually the workspace's owner.
// We should restrict the workspace's owner actions if it's past its grace period end date and it's owing some amount.
if (
PolicyUtils.isPolicyOwner(policy, currentUserAccountID) &&
ownerBillingGraceEndPeriod &&
amountOwed !== undefined &&
amountOwed > 0 &&
isAfter(currentDate, fromUnixTime(ownerBillingGraceEndPeriod))
) {
return true;
}
return false;
}
export {
calculateRemainingFreeTrialDays,
doesUserHavePaymentCardAdded,
hasUserFreeTrialEnded,
isUserOnFreeTrial,
shouldRestrictUserBillableActions,
getSubscriptionStatus,
hasSubscriptionRedDotError,
getAmountOwed,
getOverdueGracePeriodDate,
getCardForSubscriptionBilling,
hasSubscriptionGreenDotInfo,
hasRetryBillingError,
PAYMENT_STATUS,
};