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

Clean up policy actions #6080

Merged
merged 7 commits into from
Nov 4, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
30 changes: 21 additions & 9 deletions src/libs/Navigation/AppNavigator/AuthScreens.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import Navigation from '../Navigation';
import * as User from '../../actions/User';
import {setModalVisibility} from '../../actions/Modal';
import NameValuePair from '../../actions/NameValuePair';
import {getPolicyList} from '../../actions/Policy';
import * as Policy from '../../actions/Policy';
import modalCardStyleInterpolator from './modalCardStyleInterpolator';
import createCustomModalStackNavigator from './createCustomModalStackNavigator';
import getOperatingSystem from '../../getOperatingSystem';
Expand Down Expand Up @@ -168,15 +168,12 @@ class AuthScreens extends React.Component {
// Load policies, maybe creating a new policy first.
Linking.getInitialURL()
.then((url) => {
// url is null on mobile unless the app was opened via a deeplink
if (url) {
const path = new URL(url).pathname;
const exitTo = new URLSearchParams(url).get('exitTo');
const shouldCreateFreePolicy = Str.startsWith(path, Str.normalizeUrl(ROUTES.LOGIN_WITH_SHORT_LIVED_TOKEN)) && exitTo === ROUTES.WORKSPACE_NEW;
getPolicyList(shouldCreateFreePolicy);
} else {
getPolicyList(false);
if (this.shouldCreateFreePolicy(url)) {
Policy.createAndGetPolicyList();
return;
}

Policy.getPolicyList();
});

// Refresh the personal details, timezone and betas every 30 minutes
Expand Down Expand Up @@ -228,6 +225,21 @@ class AuthScreens extends React.Component {
this.interval = null;
}

/**
* @param {String} [url]
* @returns {Boolean}
*/
shouldCreateFreePolicy(url = '') {
if (!url) {
return false;
}

const path = new URL(url).pathname;
const exitTo = new URLSearchParams(url).get('exitTo');
return Str.startsWith(path, Str.normalizeUrl(ROUTES.LOGIN_WITH_SHORT_LIVED_TOKEN))
&& exitTo === ROUTES.WORKSPACE_NEW;
}

render() {
const commonModalScreenOptions = {
headerShown: false,
Expand Down
72 changes: 42 additions & 30 deletions src/libs/actions/Policy.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import _ from 'underscore';
import Onyx from 'react-native-onyx';
import lodashMerge from 'lodash/merge';
import lodashGet from 'lodash/get';
import * as API from '../API';
import ONYXKEYS from '../../ONYXKEYS';
Expand Down Expand Up @@ -102,7 +103,7 @@ function updateAllPolicies(policyCollection) {
* @param {Boolean} [shouldAutomaticallyReroute]
* @returns {Promise}
*/
function create(name = '', shouldAutomaticallyReroute = true) {
function create(name = '') {
let res = null;
return API.Policy_Create({type: CONST.POLICY.TYPE.FREE, policyName: name})
.then((response) => {
Expand All @@ -123,14 +124,22 @@ function create(name = '', shouldAutomaticallyReroute = true) {
role: CONST.POLICY.ROLE.ADMIN,
outputCurrency: response.policy.outputCurrency,
});
}).then(() => {
const policyID = lodashGet(res, 'policyID');
if (shouldAutomaticallyReroute) {
Navigation.dismissModal();
Navigation.navigate(policyID ? ROUTES.getWorkspaceInitialRoute(policyID) : ROUTES.HOME);
}
return Promise.resolve(policyID);
});
}).then(() => Promise.resolve(lodashGet(res, 'policyID')));
}

/**
* @param {String} policyID
*/
function navigateToPolicy(policyID) {
Navigation.dismissModal();
Navigation.navigate(policyID ? ROUTES.getWorkspaceInitialRoute(policyID) : ROUTES.HOME);
}

/**
* @param {String} [name]
*/
function createAndNavigate(name = '') {
create(name).then(navigateToPolicy);
}

/**
Expand All @@ -144,40 +153,41 @@ function create(name = '', shouldAutomaticallyReroute = true) {
*
* This way, we ensure that there's no race condition between creating the new policy and fetching existing ones,
* and we also don't have to wait for full policies to load before navigating to the new policy.
*
* @param {Boolean} [shouldCreateNewPolicy]
*/
function getPolicyList(shouldCreateNewPolicy = false) {
let newPolicyID;
const createPolicyPromise = shouldCreateNewPolicy
? create('', false)
: Promise.resolve();
createPolicyPromise
.then((policyID) => {
newPolicyID = policyID;
return API.GetPolicySummaryList();
})
function getPolicyList() {
const policyCollection = {};
API.GetPolicySummaryList()
.then((data) => {
if (data.jsonCode === 200) {
const policyDataToStore = transformPolicyListToOnyxCollection(data.policySummaryList || []);
updateAllPolicies(policyDataToStore);
}

if (shouldCreateNewPolicy) {
Navigation.dismissModal();
Navigation.navigate(newPolicyID ? ROUTES.getWorkspaceInitialRoute(newPolicyID) : ROUTES.HOME);
lodashMerge(policyCollection, transformPolicyListToOnyxCollection(data.policySummaryList || []));
}

return API.GetPolicyList();
})
.then((data) => {
if (data.jsonCode === 200) {
const policyDataToStore = transformPolicyListToOnyxCollection(data.policyList || []);
updateAllPolicies(policyDataToStore);
lodashMerge(policyCollection, transformPolicyListToOnyxCollection(data.policyList || []));
}
})
.finally(() => {
roryabraham marked this conversation as resolved.
Show resolved Hide resolved
if (_.isEmpty(policyCollection)) {
return;
}

updateAllPolicies(policyCollection);
});
}

function createAndGetPolicyList() {
let newPolicyID;
create()
.then((policyID) => {
newPolicyID = policyID;
return getPolicyList();
})
.then(() => navigateToPolicy(newPolicyID));
}

/**
* Is the user an admin of a free policy (aka workspace)?
*
Expand Down Expand Up @@ -364,4 +374,6 @@ export {
update,
setWorkspaceErrors,
hideWorkspaceAlertMessage,
createAndNavigate,
createAndGetPolicyList,
};
8 changes: 4 additions & 4 deletions src/pages/home/sidebar/SidebarScreen.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import {
} from '../../../components/Icon/Expensicons';
import Permissions from '../../../libs/Permissions';
import ONYXKEYS from '../../../ONYXKEYS';
import {create, isAdminOfFreePolicy} from '../../../libs/actions/Policy';
import * as Policy from '../../../libs/actions/Policy';
Copy link
Contributor

Choose a reason for hiding this comment

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

NAB: Why * and not just replace create with createAndNavigate?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

More context here: #5984 (comment)

Basically we are going to change these all eventually so I got to this one now.

import Performance from '../../../libs/Performance';
import NameValuePair from '../../../libs/actions/NameValuePair';

Expand Down Expand Up @@ -76,7 +76,7 @@ class SidebarScreen extends Component {

// It's also possible that we already have a workspace policy. In either case we will not toggle the menu but do still want to set the NVP in this case since the user does
// not need to create a workspace.
if (!isAdminOfFreePolicy(this.props.allPolicies) && !isDisplayingWorkspaceRoute) {
if (!Policy.isAdminOfFreePolicy(this.props.allPolicies) && !isDisplayingWorkspaceRoute) {
this.toggleCreateMenu();
}

Expand Down Expand Up @@ -183,14 +183,14 @@ class SidebarScreen extends Component {
onSelected: () => Navigation.navigate(ROUTES.IOU_BILL),
},
] : []),
...(Permissions.canUseFreePlan(this.props.betas) && !isAdminOfFreePolicy(this.props.allPolicies) ? [
...(Permissions.canUseFreePlan(this.props.betas) && !Policy.isAdminOfFreePolicy(this.props.allPolicies) ? [
{
icon: NewWorkspace,
iconWidth: 46,
iconHeight: 40,
text: this.props.translate('workspace.new.newWorkspace'),
description: this.props.translate('workspace.new.getTheExpensifyCardAndMore'),
onSelected: () => create(),
onSelected: () => Policy.createAndNavigate(),
},
] : []),
]}
Expand Down