Skip to content

Commit

Permalink
chore(manypets): add logs for signing flow
Browse files Browse the repository at this point in the history
  • Loading branch information
guilhermespopolin committed Jul 7, 2023
1 parent f411945 commit f233987
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 21 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { isApolloError, useApolloClient } from '@apollo/client'
import { datadogLogs } from '@datadog/browser-logs'
import { datadogRum } from '@datadog/browser-rum'
import styled from '@emotion/styled'
import { useTranslation } from 'next-i18next'
import { useRouter } from 'next/router'
Expand Down Expand Up @@ -242,26 +243,35 @@ const useSignMigration = (

const handleSubmitSign: FormEventHandler<HTMLFormElement> = useCallback(
async (event) => {
if (!shopSession) return

event.preventDefault()

if (!shopSession) return

if (!shopSession.customer || !shopSession.customer.ssn) {
throw new Error('Must have customer data and ssn in it')
}

const shopSessionId = shopSession.id
const { authenticationStatus: customerAuthenticationStatus, ssn } = shopSession.customer
manypetsLogger.addContext('shopSessionId', shopSessionId)

datadogRum.addAction('ManyPets StartingSigning', {
shopSessionId,
entriesCount: shopSession.cart.entries.length,
customerAuthenticationStatus,
})

try {
if (shopSession.cart.entries.length === 0) {
manypetsLogger.debug('Cart is empty, filling it with migration offers')
manypetsLogger.info('Cart is empty. Filling it with migration offers')
await fillCart({ variables: { shopSessionId, offerIds } })
} else {
const cartOfferIds = new Set(shopSession.cart.entries.map((entry) => entry.id))
if (
offerIds.length === shopSession.cart.entries.length &&
offerIds.every((id) => cartOfferIds.has(id))
) {
manypetsLogger.debug('Cart already filled with expected offers')
manypetsLogger.info('Cart already filled with expected offers')
} else {
throw new Error(
`Cart has unexpected items in it. cartOfferIds=${Array.from(
Expand All @@ -271,12 +281,13 @@ const useSignMigration = (
}
}

const { authenticationStatus: customerAuthenticationStatus, ssn } = shopSession.customer
manypetsLogger.info('ManyPets StartingCheckoutSign')
startCheckoutSign({
customerAuthenticationStatus,
shopSessionId,
ssn,
async onSuccess() {
manypetsLogger.info('ManyPets Successfully sign shopsession. Moving on to checkout')
const checkoutSteps = await fetchCheckoutSteps({ apolloClient, shopSession })
const checkoutStepIndex = checkoutSteps.findIndex(
(item) => item === CheckoutStep.Checkout,
Expand Down
19 changes: 9 additions & 10 deletions apps/store/src/pages/manypets/migration/[shopSessionId].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -91,23 +91,20 @@ export const getServerSideProps: GetServerSideProps<Props, Params> = async (cont
// Make sure we don't identify different member based on accessToken - this breaks signing
resetAuthTokens({ req, res })

const slug = `${STORYBLOK_MANYPETS_FOLDER_SLUG}/migration`
const apolloClient = await initializeApolloServerSide({ req, res, locale })

const [shopSession, pageStory, translations] = await Promise.all([
fetchMigrationSession(apolloClient, shopSessionId).catch((err) => {
console.error('Failed to find shopSession', err)
}),
getStoryBySlug<ManyPetsMigrationStory>(`${STORYBLOK_MANYPETS_FOLDER_SLUG}/migration`, {
fetchMigrationSession(apolloClient, shopSessionId),
getStoryBySlug<ManyPetsMigrationStory>(slug, {
locale,
// Uncomment for local debug
// version: 'draft',
}),
serverSideTranslations(locale),
])

if (!shopSession) {
return { notFound: true }
}
]).catch((error) => {
throw new Error(`Failed to fetch data for ${slug}: ${error.message}`, { cause: error })
})

const { data, errors } = await apolloClient.query<
ManyPetsMigrationOffersQuery,
Expand All @@ -118,15 +115,17 @@ export const getServerSideProps: GetServerSideProps<Props, Params> = async (cont
})

if (errors) {
console.error(`Failed to fetch shopsession ${shopSessionId}`, { cause: errors })
return { notFound: true }
}

// It should not be possible to get any other offers that are not pet related offers here, but we're
// It should not be possible to get any other offers that are not pet related here, but we're
// filtering them just to be safe.
const offers = data.petMigrationOffers.filter(isPetRelatedOffer)
// Since it shouldn't be possible to have offers with different tier levels, like SE_DOG_BASIC and SE_DOG_STANDARD,
// any offer can be used to determine the tier level and therefore get the appropriate comparison table data.
const baseOffer = offers[0]
// TODO: take total cost from shopsession.cart.cost
const totalCost: Money = {
amount: offers.reduce((sum, offer) => sum + offer.cost.net.amount, 0),
currencyCode: baseOffer.cost.net.currencyCode,
Expand Down
8 changes: 4 additions & 4 deletions apps/store/src/services/bankId/useBankIdCheckoutSign.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export const useBankIdCheckoutSign = ({ dispatch }: Options) => {
dispatch({ type: 'startCheckoutSign', ssn, customerAuthenticationStatus })

if (customerAuthenticationStatus === ShopSessionAuthenticationStatus.AuthenticationRequired) {
bankIdLogger.debug('Authentication required for returning member')
bankIdLogger.info('Authentication required for returning member')
startLogin({
ssn,
onSuccess() {
Expand Down Expand Up @@ -92,12 +92,12 @@ export const useBankIdCheckoutSignApi = ({ dispatch }: Options) => {
subscriber.next(apiStatusToBankIdState(status))
if (status === ShopSessionSigningStatus.Signed && completion) {
signingResult.stopPolling()
bankIdLogger.debug('Signing complete')
bankIdLogger.info('Signing complete')
const { accessToken, refreshToken } = await exchangeAuthorizationCode(
completion.authorizationCode,
)
saveAuthTokens({ accessToken, refreshToken })
bankIdLogger.debug('Got access token')
bankIdLogger.info('Got access token')
subscriber.complete()
}
},
Expand All @@ -120,7 +120,7 @@ export const useBankIdCheckoutSignApi = ({ dispatch }: Options) => {
if (userError) {
subscriber.error(userError)
} else if (signing) {
bankIdLogger.debug('Signing started')
bankIdLogger.info('Signing started')
startPolling(signing.id)
}
},
Expand Down
4 changes: 2 additions & 2 deletions apps/store/src/services/bankId/useBankIdLogin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ export const useBankIdLoginApi = ({ dispatch }: HookOptions) => {
const subscriptionRef = useRef<Subscription | null>(null)
const startLogin = useCallback(
({ ssn, onSuccess }: BankIdLoginOptions) => {
bankIdLogger.debug('Starting BankId login')
bankIdLogger.info('Starting BankId login')
// Future ideas
// - try Observable.from().forEach to await final result and Promise.finally to clean up ref
subscriptionRef.current = loginMemberSeBankId(ssn).subscribe({
Expand All @@ -78,7 +78,7 @@ export const useBankIdLoginApi = ({ dispatch }: HookOptions) => {
statusResponse.authorizationCode,
)
saveAuthTokens({ accessToken, refreshToken })
bankIdLogger.debug('Got access token')
bankIdLogger.info('Got access token')
onSuccess()
}
},
Expand Down

0 comments on commit f233987

Please sign in to comment.