Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[No QA][Free trial] Implement all Free Trials utility functions #43844

Merged
Show file tree
Hide file tree
Changes from 23 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
127d350
Add NVP_FIRST_DAY_FREE_TRIAL Onyx key
fabioh8010 Jun 13, 2024
3aaaac1
Add NVP_LAST_DAY_FREE_TRIAL Onyx key
fabioh8010 Jun 13, 2024
12fa116
Add NVP_BILLING_FUND_ID Onyx key
fabioh8010 Jun 13, 2024
91affbd
Add NVP_PRIVATE_AMOUNT_OWNED Onyx key
fabioh8010 Jun 13, 2024
a8f194f
Add NVP_PRIVATE_OWNER_BILLING_GRACE_PERIOD_END Onyx key
fabioh8010 Jun 13, 2024
9f41e9b
Add SHARED_NVP_PRIVATE_USER_BILLING_GRACE_PERIOD_END Onyx key
fabioh8010 Jun 13, 2024
3127c9d
Implement isChatUsedForOnboarding() and getChatUsedForOnboarding() fu…
fabioh8010 Jun 14, 2024
4eb8d41
Add descriptive comment to isSystemChat() function
fabioh8010 Jun 14, 2024
92ba0c8
Implement SubscriptionUtils.calculateRemainingFreeTrialDays() function
fabioh8010 Jun 14, 2024
ce591a3
Improve ReportUtilsTest tests
fabioh8010 Jun 14, 2024
ac22ed8
Implement SubscriptionUtils.isUserOnFreeTrial() function
fabioh8010 Jun 14, 2024
c012ed3
Implement SubscriptionUtils.hasUserFreeTrialEnded() function
fabioh8010 Jun 14, 2024
ccd5758
Implement SubscriptionUtils.doesUserHavePaymentCardAdded() function
fabioh8010 Jun 14, 2024
5fa1f17
Implement SubscriptionUtils.shouldRestrictUserBillableActions() function
fabioh8010 Jun 14, 2024
8e27a71
Improve shouldRestrictUserBillableActions() logic
fabioh8010 Jun 14, 2024
52074be
Fix TS errors
fabioh8010 Jun 14, 2024
dbec623
Merge remote-tracking branch 'origin/main' into feature/free-trials/o…
fabioh8010 Jun 14, 2024
0cf96d7
Prettier
fabioh8010 Jun 14, 2024
35e9bba
Changes ReportUtils.requiresAttentionFromCurrentUser() to include fre…
fabioh8010 Jun 17, 2024
a3e1c4a
Merge remote-tracking branch 'origin/main' into feature/free-trials/o…
fabioh8010 Jun 17, 2024
7eb5a07
Add another test for ReportUtils.requiresAttentionFromCurrentUser()
fabioh8010 Jun 17, 2024
cfd25ee
Merge remote-tracking branch 'origin/main' into feature/free-trials/o…
fabioh8010 Jun 17, 2024
7b5456d
Prettier fix
fabioh8010 Jun 17, 2024
efe02e1
Fix dates
fabioh8010 Jun 17, 2024
903a6c6
Merge remote-tracking branch 'origin/main' into feature/free-trials/o…
fabioh8010 Jun 18, 2024
9954f49
Address review comments
fabioh8010 Jun 18, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions src/ONYXKEYS.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,21 @@ const ONYXKEYS = {
/** The NVP with the last action taken (for the Quick Action Button) */
NVP_QUICK_ACTION_GLOBAL_CREATE: 'nvp_quickActionGlobalCreate',

/** The start date (yyyy-MM-dd HH:mm:ss) of the workspace owner’s free trial period. */
NVP_FIRST_DAY_FREE_TRIAL: 'nvp_private_firstDayFreeTrial',

/** The end date (yyyy-MM-dd HH:mm:ss) of the workspace owner’s free trial period. */
NVP_LAST_DAY_FREE_TRIAL: 'nvp_private_lastDayFreeTrial',

/** ID associated with the payment card added by the user. */
NVP_BILLING_FUND_ID: 'nvp_expensify_billingFundID',

/** The amount owed by the workspace’s owner. */
NVP_PRIVATE_AMOUNT_OWNED: 'nvp_private_amountOwed',

/** The end date (epoch timestamp) of the workspace owner’s grace period after the free trial ends. */
NVP_PRIVATE_OWNER_BILLING_GRACE_PERIOD_END: 'nvp_private_billingGracePeriodEnd',

/** Does this user have push notifications enabled for this device? */
PUSH_NOTIFICATIONS_ENABLED: 'pushNotificationsEnabled',

Expand Down Expand Up @@ -376,6 +391,10 @@ const ONYXKEYS = {

// Search Page related
SNAPSHOT: 'snapshot_',

// Shared NVPs
/** Collection of objects where each objects represents a workspace’s owner which is past due billing AND the user is a member of. */
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would this sound better?

Suggested change
/** Collection of objects where each objects represents a workspace’s owner which is past due billing AND the user is a member of. */
/** Collection of objects where each object represents a workspace’s non-owner(normal users and admins) who is member of a workspace where the owner is past due billing. */

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rojiphil That is not true, each object represents the workspace owner where the user is member of. I've changed to Collection of objects where each object represents the owner of the workspace that is past due billing AND the user is a member of. Wdyt?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah! You are right. It makes sense too.

SHARED_NVP_PRIVATE_USER_BILLING_GRACE_PERIOD_END: 'sharedNVP_private_billingGracePeriodEnd_',
},

/** List of Form ids */
Expand Down Expand Up @@ -589,6 +608,7 @@ type OnyxCollectionValuesMapping = {
[ONYXKEYS.COLLECTION.POLICY_JOIN_MEMBER]: OnyxTypes.PolicyJoinMember;
[ONYXKEYS.COLLECTION.POLICY_CONNECTION_SYNC_PROGRESS]: OnyxTypes.PolicyConnectionSyncProgress;
[ONYXKEYS.COLLECTION.SNAPSHOT]: OnyxTypes.SearchResults;
[ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_USER_BILLING_GRACE_PERIOD_END]: OnyxTypes.BillingGraceEndPeriod;
};

type OnyxValuesMapping = {
Expand Down Expand Up @@ -699,6 +719,11 @@ type OnyxValuesMapping = {
[ONYXKEYS.CACHED_PDF_PATHS]: Record<string, string>;
[ONYXKEYS.POLICY_OWNERSHIP_CHANGE_CHECKS]: Record<string, OnyxTypes.PolicyOwnershipChangeChecks>;
[ONYXKEYS.NVP_QUICK_ACTION_GLOBAL_CREATE]: OnyxTypes.QuickAction;
[ONYXKEYS.NVP_FIRST_DAY_FREE_TRIAL]: string;
[ONYXKEYS.NVP_LAST_DAY_FREE_TRIAL]: string;
[ONYXKEYS.NVP_BILLING_FUND_ID]: number;
[ONYXKEYS.NVP_PRIVATE_AMOUNT_OWNED]: number;
[ONYXKEYS.NVP_PRIVATE_OWNER_BILLING_GRACE_PERIOD_END]: number;
};

type OnyxValues = OnyxValuesMapping & OnyxCollectionValuesMapping & OnyxFormValuesMapping & OnyxFormDraftValuesMapping;
Expand Down
1 change: 1 addition & 0 deletions src/libs/AccountUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type {Account} from '@src/types/onyx';
const isValidateCodeFormSubmitting = (account: OnyxEntry<Account>) =>
!!account?.isLoading && account.loadingForm === (account.requiresTwoFactorAuth ? CONST.FORMS.VALIDATE_TFA_CODE_FORM : CONST.FORMS.VALIDATE_CODE_FORM);

/** Whether the accound ID is an odd number, useful for A/B testing. */
const isAccountIDOddNumber = (accountID: number) => accountID % 2 === 1;

export default {isValidateCodeFormSubmitting, isAccountIDOddNumber};
28 changes: 27 additions & 1 deletion src/libs/ReportUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ import type {Comment, Receipt, TransactionChanges, WaypointCollection} from '@sr
import type {EmptyObject} from '@src/types/utils/EmptyObject';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
import type IconAsset from '@src/types/utils/IconAsset';
import AccountUtils from './AccountUtils';
import * as IOU from './actions/IOU';
import * as PolicyActions from './actions/Policy/Policy';
import * as store from './actions/ReimbursementAccount/store';
Expand All @@ -82,6 +83,7 @@ import * as PolicyUtils from './PolicyUtils';
import type {LastVisibleMessage} from './ReportActionsUtils';
import * as ReportActionsUtils from './ReportActionsUtils';
import StringUtils from './StringUtils';
import * as SubscriptionUtils from './SubscriptionUtils';
import * as TransactionUtils from './TransactionUtils';
import * as Url from './Url';
import type {AvatarSource} from './UserUtils';
Expand Down Expand Up @@ -1035,12 +1037,15 @@ function isGroupChat(report: OnyxEntry<Report> | Partial<Report>): boolean {
return getChatType(report) === CONST.REPORT.CHAT_TYPE.GROUP;
}

/**
* Only returns true if this is the Expensify DM report.
*/
function isSystemChat(report: OnyxEntry<Report>): boolean {
return getChatType(report) === CONST.REPORT.CHAT_TYPE.SYSTEM;
}

/**
* Only returns true if this is our main 1:1 DM report with Concierge
* Only returns true if this is our main 1:1 DM report with Concierge.
*/
function isConciergeChatReport(report: OnyxInputOrEntry<Report>): boolean {
const participantAccountIDs = Object.keys(report?.participants ?? {})
Expand Down Expand Up @@ -2285,6 +2290,7 @@ function isUnreadWithMention(reportOrOption: OnyxEntry<Report> | OptionData): bo
* - is unread and the user was mentioned in one of the unread comments
* - is for an outstanding task waiting on the user
* - has an outstanding child expense that is waiting for an action from the current user (e.g. pay, approve, add bank account)
* - is either the system or concierge chat, the user free trial has ended and it didn't add a payment card yet
*
* @param option (report or optionItem)
* @param parentReportAction (the report action the current report is a thread of)
Expand Down Expand Up @@ -2315,6 +2321,10 @@ function requiresAttentionFromCurrentUser(optionOrReport: OnyxEntry<Report> | Op
return true;
}

if (isChatUsedForOnboarding(optionOrReport) && SubscriptionUtils.hasUserFreeTrialEnded() && !SubscriptionUtils.doesUserHavePaymentCardAdded()) {
return true;
}

return false;
}

Expand Down Expand Up @@ -6964,6 +6974,20 @@ function shouldShowMerchantColumn(transactions: Transaction[]) {
return transactions.some((transaction) => isExpenseReport(allReports?.[transaction.reportID] ?? {}));
}

/**
* Whether the report is a system chat or concierge chat, depending on the user's account ID.
*/
function isChatUsedForOnboarding(report: OnyxEntry<Report>): boolean {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NAB: we should add some context that these are used for A/B testing because it could be rather confusing for anyone reading this that we're doing different logic depending on whether accountID is odd or even.

return AccountUtils.isAccountIDOddNumber(currentUserAccountID ?? -1) ? isSystemChat(report) : isConciergeChatReport(report);
}

/**
* Get the report (system or concierge chat) used for the user's onboarding process.
*/
function getChatUsedForOnboarding(): OnyxEntry<Report> {
return Object.values(allReports ?? {}).find(isChatUsedForOnboarding);
}

export {
addDomainToShortMention,
areAllRequestsBeingSmartScanned,
Expand Down Expand Up @@ -7236,6 +7260,8 @@ export {
isDraftReport,
changeMoneyRequestHoldStatus,
createDraftWorkspaceAndNavigateToConfirmationScreen,
isChatUsedForOnboarding,
getChatUsedForOnboarding,
};

export type {
Expand Down
130 changes: 130 additions & 0 deletions src/libs/SubscriptionUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import {differenceInCalendarDays, fromUnixTime, isAfter, isBefore, parse as parseDate} from 'date-fns';
import type {OnyxCollection, OnyxEntry} from 'react-native-onyx';
import Onyx from 'react-native-onyx';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type {BillingGraceEndPeriod, Policy} from '@src/types/onyx';

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 ownerBillingGraceEndPeriod: OnyxEntry<number>;
Onyx.connect({
key: ONYXKEYS.NVP_PRIVATE_OWNER_BILLING_GRACE_PERIOD_END,
callback: (value) => (ownerBillingGraceEndPeriod = value),
});

let amountOwed: OnyxEntry<number>;
Onyx.connect({
key: ONYXKEYS.NVP_PRIVATE_AMOUNT_OWNED,
callback: (value) => (amountOwed = value),
});

let allPolicies: OnyxCollection<Policy>;
Onyx.connect({
key: ONYXKEYS.COLLECTION.POLICY,
callback: (value) => (allPolicies = value),
waitForCollectionCallback: true,
});

/**
* Calculates the remaining number of days of the workspace owner's free trial before it ends.
*/
function calculateRemainingFreeTrialDays(): number {
if (!lastDayFreeTrial) {
return 0;
}

const difference = differenceInCalendarDays(parseDate(lastDayFreeTrial, CONST.DATE.FNS_DATE_TIME_FORMAT_STRING, new Date()), new Date());
fabioh8010 marked this conversation as resolved.
Show resolved Hide resolved
return difference < 0 ? 0 : difference;
}

/**
* Whether the workspace's owner is on its free trial period.
*/
function isUserOnFreeTrial(): boolean {
if (!firstDayFreeTrial || !lastDayFreeTrial) {
return true;
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's an incorrect value when either of those values hasn't been set/loaded yet or user hasn't started the free trial yet.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are right, adjusted! cc @chiragsalian


const currentDate = new Date();
const firstDayFreeTrialDate = parseDate(firstDayFreeTrial, CONST.DATE.FNS_DATE_TIME_FORMAT_STRING, new Date());
const lastDayFreeTrialDate = parseDate(lastDayFreeTrial, CONST.DATE.FNS_DATE_TIME_FORMAT_STRING, new Date());

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, new Date());
fabioh8010 marked this conversation as resolved.
Show resolved Hide resolved

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 {
// 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(new Date(), fromUnixTime(userBillingGracePeriodEnd.value))) {
// Extracts the owner account ID from the collection member key.
const ownerAccountID = entryKey.slice(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_USER_BILLING_GRACE_PERIOD_END.length);

const ownerPolicy = allPolicies?.[`${ONYXKEYS.COLLECTION.POLICY}${policyID}`];
if (String(ownerPolicy?.ownerAccountID ?? -1) === 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 (ownerBillingGraceEndPeriod && amountOwed !== undefined && isAfter(new Date(), fromUnixTime(ownerBillingGraceEndPeriod))) {
return true;
}

return false;
}

export {calculateRemainingFreeTrialDays, doesUserHavePaymentCardAdded, hasUserFreeTrialEnded, isUserOnFreeTrial, shouldRestrictUserBillableActions};
17 changes: 6 additions & 11 deletions src/libs/actions/Policy/Member.ts
Original file line number Diff line number Diff line change
Expand Up @@ -247,26 +247,26 @@ function removeMembers(accountIDs: number[], policyID: string) {
key: policyKey,
value: {employeeList: optimisticMembersState},
},
...announceRoomMembers.onyxOptimisticData,
];
optimisticData.push(...announceRoomMembers.onyxOptimisticData);

const successData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: policyKey,
value: {employeeList: successMembersState},
},
...announceRoomMembers.onyxSuccessData,
];
successData.push(...announceRoomMembers.onyxSuccessData);

const failureData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: policyKey,
value: {employeeList: failureMembersState},
},
...announceRoomMembers.onyxFailureData,
];
failureData.push(...announceRoomMembers.onyxFailureData);

const pendingChatMembers = ReportUtils.getPendingChatMembers(accountIDs, [], CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE);

Expand Down Expand Up @@ -551,10 +551,8 @@ function addMembersToWorkspace(invitedEmailsToAccountIDs: InvitedEmailsToAccount
employeeList: optimisticMembersState,
},
},
...newPersonalDetailsOnyxData.optimisticData,
...membersChats.onyxOptimisticData,
...announceRoomMembers.onyxOptimisticData,
];
optimisticData.push(...newPersonalDetailsOnyxData.optimisticData, ...membersChats.onyxOptimisticData, ...announceRoomMembers.onyxOptimisticData);

const successData: OnyxUpdate[] = [
{
Expand All @@ -564,10 +562,8 @@ function addMembersToWorkspace(invitedEmailsToAccountIDs: InvitedEmailsToAccount
employeeList: successMembersState,
},
},
...newPersonalDetailsOnyxData.finallyData,
...membersChats.onyxSuccessData,
...announceRoomMembers.onyxSuccessData,
];
successData.push(...newPersonalDetailsOnyxData.finallyData, ...membersChats.onyxSuccessData, ...announceRoomMembers.onyxSuccessData);

const failureData: OnyxUpdate[] = [
{
Expand All @@ -580,9 +576,8 @@ function addMembersToWorkspace(invitedEmailsToAccountIDs: InvitedEmailsToAccount
employeeList: failureMembersState,
},
},
...membersChats.onyxFailureData,
...announceRoomMembers.onyxFailureData,
];
failureData.push(...membersChats.onyxFailureData, ...announceRoomMembers.onyxFailureData);

const params: AddMembersToWorkspaceParams = {
employees: JSON.stringify(logins.map((login) => ({email: login}))),
Expand Down
Loading
Loading