Skip to content

Commit

Permalink
Merge pull request Expensify#43844 from fabioh8010/feature/free-trial…
Browse files Browse the repository at this point in the history
…s/onyx-keys-and-utility-functions

[No QA][Free trial] Implement all Free Trials utility functions
  • Loading branch information
chiragsalian authored Jun 19, 2024
2 parents de66757 + 9954f49 commit 765127b
Show file tree
Hide file tree
Showing 11 changed files with 655 additions and 68 deletions.
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 object represents the owner of the workspace that is past due billing AND the user is a member of. */
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 @@ -2274,6 +2279,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 @@ -2304,6 +2310,10 @@ function requiresAttentionFromCurrentUser(optionOrReport: OnyxEntry<Report> | Op
return true;
}

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

return false;
}

Expand Down Expand Up @@ -6943,6 +6953,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 {
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 @@ -7214,6 +7238,8 @@ export {
isDraftReport,
changeMoneyRequestHoldStatus,
createDraftWorkspaceAndNavigateToConfirmationScreen,
isChatUsedForOnboarding,
getChatUsedForOnboarding,
};

export type {
Expand Down
135 changes: 135 additions & 0 deletions src/libs/SubscriptionUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import {differenceInSeconds, 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 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();

// 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 = 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 && amountOwed > 0 && isAfter(currentDate, 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

0 comments on commit 765127b

Please sign in to comment.