Skip to content

Commit

Permalink
Merge pull request #1684 from coopcycle/fix/1534-checkout-flow
Browse files Browse the repository at this point in the history
Fix: registration during the checkout flow
  • Loading branch information
alexsegura authored Mar 5, 2024
2 parents 83aff4b + 31f23be commit a5c8467
Show file tree
Hide file tree
Showing 11 changed files with 529 additions and 182 deletions.
36 changes: 27 additions & 9 deletions src/API.js
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,6 @@ Client.prototype.createRequest = function(method, url, data, options = {}) {
}

const authorized = !(!this.credentials.token || options.anonymous)
console.log(`${method} ${url}${authorized ? '' : ' (anon.)'}`)

if (authorized && this.credentials.token) {
headers.Authorization = `Bearer ${this.credentials.token}`
Expand All @@ -137,6 +136,8 @@ Client.prototype.createRequest = function(method, url, data, options = {}) {
}
}

console.log(`→ ${method} ${url}${headers.Authorization ? '' : ' (anon.)'}`)

let req = {
method,
url,
Expand All @@ -159,29 +160,46 @@ Client.prototype.createRequest = function(method, url, data, options = {}) {
return req
}

Client.prototype.request = function(method, uri, data, options = {}) {
Client.prototype.request = function (method, uri, data, options = {}) {
const req = this.createRequest(method, uri, data, options)
return this.axios.request(req);
const start = Date.now()
return this.axios
.request(req)
.then(response => {
const duration = Date.now() - start
console.log(`⬅ ${method} ${uri} | ${response.status} | ${duration}ms`)

return response
})
.catch(error => {
if (error.response) {
console.warn(`⬅ ${method} ${uri} | ${error.response.status}`)
} else {
console.warn(`⬅ ${method} ${uri} | ${error.message}`)
}

return Promise.reject(error)
})
}

Client.prototype.get = function(uri, data, options = {}) {
Client.prototype.get = function(uri, options = {}) {

return enhanceRequest(this, 'GET', uri, data, options);
return enhanceRequest(this, 'GET', uri, {}, options)
}

Client.prototype.post = function(uri, data) {
Client.prototype.post = function(uri, data, options = {}) {

return enhanceRequest(this, 'POST', uri, data);
return enhanceRequest(this, 'POST', uri, data, options);
}

Client.prototype.put = function(uri, data, options = {}) {

return enhanceRequest(this, 'PUT', uri, data, options);
}

Client.prototype.delete = function(uri) {
Client.prototype.delete = function(uri, options = {}) {

return enhanceRequest(this, 'DELETE', uri);
return enhanceRequest(this, 'DELETE', uri, {}, options);
}

function enhanceRequest(client, method, uri, data, options = {}) {
Expand Down
2 changes: 1 addition & 1 deletion src/navigation/checkout/Restaurant.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ function Restaurant(props) {
const { showFooter, httpClient, restaurant, openingHoursSpecification } = props

const { isLoading, isError, data } = useQuery([ 'menus', restaurant.hasMenu ], async () => {
return await httpClient.get(restaurant.hasMenu, {}, { anonymous: true })
return await httpClient.get(restaurant.hasMenu, { anonymous: true })
})

const currentTimeSlot = useMemo(
Expand Down
12 changes: 6 additions & 6 deletions src/redux/Account/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import _ from 'lodash'
import { logout, setLoading } from '../App/actions'
import { selectHttpClient, selectIsAuthenticated } from '../App/selectors'
import { selectOrderAccessTokensById } from './selectors'
import { selectCheckoutAuthorizationHeaders } from '../Checkout/selectors'

/*
* Action Types
Expand Down Expand Up @@ -56,9 +57,9 @@ export function loadOrders(cb) {
export function loadOrder(order, cb) {
return (dispatch, getState) => {
const orderAccessToken = selectOrderAccessTokensById(getState(), order['@id'])
const httpClient = selectHttpClient(getState(), orderAccessToken)
const httpClient = selectHttpClient(getState())

httpClient.get(order['@id'])
httpClient.get(order['@id'], { headers: selectCheckoutAuthorizationHeaders(getState(), order, orderAccessToken) })
.then(res => {
dispatch(updateOrderSuccess(res))
if (cb) { cb() }
Expand Down Expand Up @@ -99,8 +100,7 @@ export function loadAddresses() {

const httpClient = getState().app.httpClient


httpClient.get('/api/me')
return httpClient.get('/api/me')
.then(res => {
dispatch(loadAddressesSuccess(res.addresses))
})
Expand Down Expand Up @@ -171,9 +171,9 @@ export function subscribe(order, onMessage) {
const baseURL = getState().app.baseURL

const orderAccessToken = selectOrderAccessTokensById(getState(), order['@id'])
const httpClient = selectHttpClient(getState(), orderAccessToken)
const httpClient = selectHttpClient(getState())

httpClient.get(`${order['@id']}/centrifugo`)
httpClient.get(`${order['@id']}/centrifugo`, { headers: selectCheckoutAuthorizationHeaders(getState(), order, orderAccessToken) })
.then(res => {

const url = parseUrl(baseURL)
Expand Down
134 changes: 89 additions & 45 deletions src/redux/App/actions.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createAction } from 'redux-actions'
import { CommonActions, StackActions } from '@react-navigation/native'
import { CommonActions } from '@react-navigation/native'
import tracker from '../../analytics/Tracker'
import analyticsEvent from '../../analytics/Event'
import userProperty from '../../analytics/UserProperty'
Expand All @@ -10,9 +10,19 @@ import Settings from '../../Settings'
import NavigationHolder from '../../NavigationHolder'
import i18n from '../../i18n'
import { setCurrencyCode } from '../../utils/formatting'
import { selectInitialRouteName, selectIsAuthenticated } from './selectors'
import { assignAllCarts, updateCarts, clearAddress } from '../Checkout/actions';
import {
selectHttpClient,
selectInitialRouteName,
selectIsAuthenticated, selectResumeCheckoutAfterActivation,
} from './selectors'
import {
assignAllCarts,
updateCarts,
clearAddress,
setRestaurant,
} from '../Checkout/actions'
import { loadAddresses, loadAddressesSuccess } from '../Account/actions';
import { selectRestaurant } from '../Checkout/selectors'

/*
* Action Types
Expand Down Expand Up @@ -168,16 +178,16 @@ function authenticationRequest() {
}

function authenticationSuccess(user) {
return (dispatch, getState) => {
dispatch(setLoading(true))
dispatch(_authenticationSuccess())
dispatch(loadAddresses())
dispatch(assignAllCarts())
dispatch(setLoading(false))
return async (dispatch, getState) => {
await dispatch(loadAddresses())
await dispatch(assignAllCarts())

setRolesProperty(user)
tracker.logEvent(
analyticsEvent.user.login._category,
analyticsEvent.user.login.success)

dispatch(_authenticationSuccess())
}
}

Expand Down Expand Up @@ -408,8 +418,8 @@ export function login(email, password, navigate = true) {
dispatch(authenticationRequest())

httpClient.login(email, password)
.then(user => {
dispatch(authenticationSuccess(user));
.then(user => dispatch(authenticationSuccess(user)))
.then(() => {
if (navigate) {
// FIXME
// Use setTimeout() to let room for loader to hide
Expand Down Expand Up @@ -461,7 +471,11 @@ export function register(data, checkEmailRouteName, loginRouteName, resumeChecko

} else {
dispatch(setLoading(false))
dispatch(_resumeCheckoutAfterActivation(resumeCheckoutAfterActivation))

if (resumeCheckoutAfterActivation) {
const restaurant = selectRestaurant(getState())
dispatch(_resumeCheckoutAfterActivation(restaurant['@id']));
}

// FIXME When using navigation, we can still go back to the filled form
NavigationHolder.navigate(checkEmailRouteName, { email: user.email, loginRouteName })
Expand All @@ -479,16 +493,14 @@ export function register(data, checkEmailRouteName, loginRouteName, resumeChecko

export function confirmRegistration(token) {
return (dispatch, getState) => {
const { app } = getState()
const { httpClient, resumeCheckoutAfterActivation } = app
const httpClient = selectHttpClient(getState())
const checkoutToResumeAfterActivation = selectResumeCheckoutAfterActivation(getState())

dispatch(setLoading(true))
dispatch(authenticationRequest())

httpClient.confirmRegistration(token)
.then(user => {
dispatch(authenticationSuccess(user))

.then(user => dispatch(authenticationSuccess(user)))
.then(() => {
//remove RegisterConfirmScreen from stack
NavigationHolder.dispatch(CommonActions.reset({
index: 0,
Expand All @@ -497,8 +509,8 @@ export function confirmRegistration(token) {
],
}))

if (resumeCheckoutAfterActivation) {
dispatch(resumeCheckout())
if (checkoutToResumeAfterActivation) {
dispatch(resumeCheckout(checkoutToResumeAfterActivation))
} else {
navigateToHome(dispatch, getState)
}
Expand Down Expand Up @@ -534,12 +546,47 @@ export function guestModeOn() {
}
}

export function resumeCheckout() {
function resumeCheckout(vendorId) {
return (dispatch, getState) => {
dispatch(_resumeCheckoutAfterActivation(false))
NavigationHolder.dispatch(CommonActions.navigate({
name: 'CheckoutNav',
}))
dispatch(_resumeCheckoutAfterActivation(null))

dispatch(setRestaurant(vendorId))

NavigationHolder.dispatch(
CommonActions.reset({
routes: [
{
name: 'CheckoutNav',
state: {
routes: [
{
name: 'Main',
state: {
routes: [
{ name: 'CheckoutHome' },
{
name: 'CheckoutRestaurant',
},
{
name: 'CheckoutSummary',
},
],
}
},
{
name: 'CheckoutSubmitOrder',
state: {
routes: [
{ name: 'CheckoutMoreInfos' },
]
}
},
],
}
},
],
}),
)
}
}

Expand All @@ -554,7 +601,11 @@ export function resetPassword(username, checkEmailRouteName, resumeCheckoutAfter
.resetPassword(username)
.then(response => {
dispatch(resetPasswordRequestSuccess());
dispatch(_resumeCheckoutAfterActivation(resumeCheckoutAfterActivation));

if (resumeCheckoutAfterActivation) {
const restaurant = selectRestaurant(getState())
dispatch(_resumeCheckoutAfterActivation(restaurant['@id']));
}

NavigationHolder.navigate(checkEmailRouteName, { email: username });
})
Expand All @@ -567,18 +618,17 @@ export function resetPassword(username, checkEmailRouteName, resumeCheckoutAfter

export function setNewPassword(token, password) {
return (dispatch, getState) => {
const { app } = getState();
const { httpClient, resumeCheckoutAfterActivation } = app;
const httpClient = selectHttpClient(getState())
const checkoutToResumeAfterActivation = selectResumeCheckoutAfterActivation(getState())

dispatch(authenticationRequest());

httpClient
.setNewPassword(token, password)
.then(user => {
dispatch(authenticationSuccess(user));

if (resumeCheckoutAfterActivation) {
dispatch(resumeCheckout());
.then(user => dispatch(authenticationSuccess(user)))
.then(() => {
if (checkoutToResumeAfterActivation) {
dispatch(resumeCheckout(checkoutToResumeAfterActivation));
} else {
navigateToHome(dispatch, getState);
}
Expand Down Expand Up @@ -629,10 +679,8 @@ export function loginWithFacebook(accessToken, navigate = true) {
dispatch(authenticationRequest())

httpClient.loginWithFacebook(accessToken)
.then(user => {

dispatch(authenticationSuccess(user));

.then(user => dispatch(authenticationSuccess(user)))
.then(() => {
if (navigate) {
// FIXME
// Use setTimeout() to let room for loader to hide
Expand Down Expand Up @@ -662,10 +710,8 @@ export function signInWithApple(identityToken, navigate = true) {
dispatch(authenticationRequest())

httpClient.signInWithApple(identityToken)
.then(user => {

dispatch(authenticationSuccess(user));

.then(user => dispatch(authenticationSuccess(user)))
.then(() => {
if (navigate) {
// FIXME
// Use setTimeout() to let room for loader to hide
Expand Down Expand Up @@ -695,10 +741,8 @@ export function googleSignIn(idToken, navigate = true) {
dispatch(authenticationRequest())

httpClient.googleSignIn(idToken)
.then(user => {

dispatch(authenticationSuccess(user));

.then(user => dispatch(authenticationSuccess(user)))
.then(() => {
if (navigate) {
// FIXME
// Use setTimeout() to let room for loader to hide
Expand Down
2 changes: 1 addition & 1 deletion src/redux/App/reducers.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ const initialState = {
nonInputError: null,
requested: false,
},
resumeCheckoutAfterActivation: false,
resumeCheckoutAfterActivation: null, // vendor id where checkout was initiated
servers: [],
selectServerError: null,
settings: {
Expand Down
Loading

0 comments on commit a5c8467

Please sign in to comment.