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70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
import {
	getDomain,
	isDomainTransfer,
	isDomainProduct,
	isDomainMapping,
	isGSuiteOrGoogleWorkspaceProductSlug,
} from '@automattic/calypso-products';
import { getContactDetailsType } from '@automattic/wpcom-checkout';
import debugFactory from 'debug';
import { useTranslate } from 'i18n-calypso';
import { getLocaleSlug } from 'calypso/lib/i18n-utils';
import { login } from 'calypso/lib/paths';
import { addQueryArgs } from 'calypso/lib/route';
import wp from 'calypso/lib/wp';
import { recordTracksEvent } from 'calypso/state/analytics/actions';
import {
	isCompleteAndValid,
	prepareDomainContactValidationRequest,
	prepareGSuiteContactValidationRequest,
	formatDomainContactValidationResponse,
	getSignupValidationErrorResponse,
} from '../types/wpcom-store-state';
import type { RequestCartProduct, ResponseCart } from '@automattic/shopping-cart';
import type {
	ManagedContactDetails,
	ManagedContactDetailsErrors,
	DomainContactValidationResponse,
	ContactDetailsType,
	ContactValidationRequestContactInformation,
	SignupValidationResponse,
	RawDomainContactValidationResponse,
	RawContactValidationResponseMessages,
	ContactValidationResponseMessages,
} from '@automattic/wpcom-checkout';
import type { CalypsoDispatch } from 'calypso/state/types';
import type { TranslateResult } from 'i18n-calypso';

const debug = debugFactory( 'calypso:composite-checkout:contact-validation' );

const getEmailTakenLoginRedirectMessage = (
	emailAddress: string,
	reduxDispatch: CalypsoDispatch,
	translate: ReturnType< typeof useTranslate >
) => {
	const { href, pathname } = window.location;
	const isJetpackCheckout = pathname.includes( '/checkout/jetpack' );
	const isAkismetCheckout = pathname.includes( '/checkout/akismet' );
	const isGiftingCheckout = pathname.includes( '/gift/' );

	// Users with a WP.com account should return to the checkout page
	// once they are logged in to complete the process. The flow for them is
	// checkout -> login -> checkout.
	const currentURLQueryParameters = Object.fromEntries( new URL( href ).searchParams.entries() );
	const redirectTo =
		isJetpackCheckout || isAkismetCheckout || isGiftingCheckout
			? addQueryArgs( { ...currentURLQueryParameters, flow: 'coming_from_login' }, pathname )
			: '/checkout/no-site?cart=no-user';

	const loginUrl = login( { redirectTo, emailAddress } );

	reduxDispatch(
		recordTracksEvent( 'calypso_checkout_wpcom_email_exists', {
			email: emailAddress,
		} )
	);

	return translate(
		'That email address is already in use. If you have an existing account, {{a}}please log in{{/a}}.',
		{
			components: {
				a: (
					<a
						onClick={ () =>
							reduxDispatch(
								recordTracksEvent( 'calypso_checkout_composite_login_click', {
									email: emailAddress,
								} )
							)
						}
						href={ loginUrl }
					/>
				),
			},
		}
	);
};

async function runContactValidationCheck(
	contactInfo: ManagedContactDetails,
	responseCart: ResponseCart
): Promise< DomainContactValidationResponse > {
	const contactDetailsType = getContactDetailsType( responseCart );
	debug( 'validating contact details for', contactDetailsType );

	switch ( contactDetailsType ) {
		case 'tax':
			return getTaxValidationResult( contactInfo );
		case 'domain':
			return getDomainValidationResult( responseCart.products, contactInfo );
		case 'gsuite':
			return getGSuiteValidationResult( responseCart.products, contactInfo );
		default:
			return isCompleteAndValid( contactInfo )
				? { success: true }
				: { success: false, messages: {}, messages_simple: [] };
	}
}

async function runLoggedOutEmailValidationCheck(
	contactInfo: ManagedContactDetails,
	reduxDispatch: CalypsoDispatch,
	translate: ReturnType< typeof useTranslate >
): Promise< unknown > {
	const email = contactInfo.email?.value ?? '';
	return getSignupEmailValidationResult( email, ( newEmail: string ) =>
		getEmailTakenLoginRedirectMessage( newEmail, reduxDispatch, translate )
	);
}

export async function validateContactDetails(
	contactInfo: ManagedContactDetails,
	isLoggedOutCart: boolean,
	responseCart: ResponseCart,
	showErrorMessageBriefly: ( message: string ) => void,
	applyDomainContactValidationResults: ( results: ManagedContactDetailsErrors ) => void,
	clearDomainContactErrorMessages: () => void,
	reduxDispatch: CalypsoDispatch,
	translate: ReturnType< typeof useTranslate >,
	shouldDisplayErrors: boolean
): Promise< boolean > {
	debug( 'validating contact details; shouldDisplayErrors', shouldDisplayErrors );

	reduxDispatch(
		recordTracksEvent( 'calypso_checkout_validating_contact_info', {
			country: contactInfo.countryCode?.value,
			postal: contactInfo.postalCode?.value,
		} )
	);

	const completeValidationCheck = ( validationResult: unknown ): boolean => {
		debug( 'validating contact details result', validationResult );
		if ( shouldDisplayErrors ) {
			handleContactValidationResult( {
				translate,
				showErrorMessage: showErrorMessageBriefly,
				validationResult,
				applyDomainContactValidationResults,
				clearDomainContactErrorMessages,
			} );
		}
		return isContactValidationResponseValid( validationResult );
	};

	if ( isLoggedOutCart ) {
		const loggedOutValidationResult = await runLoggedOutEmailValidationCheck(
			contactInfo,
			reduxDispatch,
			translate
		);
		if ( shouldDisplayErrors ) {
			handleContactValidationResult( {
				translate,
				showErrorMessage: showErrorMessageBriefly,
				validationResult: loggedOutValidationResult,
				applyDomainContactValidationResults,
				clearDomainContactErrorMessages,
			} );
		}

		if ( ! isContactValidationResponseValid( loggedOutValidationResult ) ) {
			return false;
		}
	}

	return completeValidationCheck( await runContactValidationCheck( contactInfo, responseCart ) );
}

function isSignupValidationResponse( data: unknown ): data is SignupValidationResponse {
	const dataResponse = data as SignupValidationResponse;
	if ( dataResponse?.success !== false && dataResponse?.success !== true ) {
		return false;
	}
	return true;
}

function isRawContactValidationResponse(
	data: unknown
): data is RawDomainContactValidationResponse {
	const dataResponse = data as RawDomainContactValidationResponse;
	return dataResponse?.success === false || dataResponse?.success === true;
}

function isContactValidationResponse( data: unknown ): data is DomainContactValidationResponse {
	const dataResponse = data as DomainContactValidationResponse;
	return dataResponse?.success === false || dataResponse?.success === true;
}

export function isContactValidationResponseValid( data: unknown ): boolean {
	if ( ! isContactValidationResponse( data ) ) {
		throw new Error( 'Invalid contact validation response.' );
	}
	if ( ! data.success ) {
		debug( 'Validation response says that the contact details not valid' );
		return false;
	}
	return true;
}

function prepareContactDetailsForValidation(
	type: ContactDetailsType,
	contactDetails: ManagedContactDetails
): ContactValidationRequestContactInformation {
	if ( type === 'domain' || type === 'tax' ) {
		const { contact_information } = prepareDomainContactValidationRequest( contactDetails );
		return contact_information;
	}
	if ( type === 'gsuite' ) {
		const { contact_information } = prepareGSuiteContactValidationRequest( contactDetails );
		return contact_information;
	}
	throw new Error( `Unknown validation type: ${ type }` );
}

// https://stackoverflow.com/a/65072147/2615868
export const hydrateNestedObject = (
	obj: Record< string, unknown > | unknown = {},
	paths: string[] = [],
	value: unknown
): Record< string, unknown > => {
	const inputObj = obj === null ? {} : { ...( obj as Record< string, unknown > ) };

	if ( paths.length === 0 ) {
		return inputObj;
	}

	if ( paths.length === 1 ) {
		const path = paths[ 0 ];
		inputObj[ path ] = value;
		return { ...inputObj, [ path ]: value };
	}

	const [ path, ...rest ] = paths;
	const currentNode = inputObj[ path ];

	const childNode = hydrateNestedObject( currentNode, rest, value );

	return { ...inputObj, [ path ]: childNode };
};

async function wpcomValidateSignupEmail( {
	email,
	is_from_registrationless_checkout,
}: {
	email: string;
	is_from_registrationless_checkout: boolean;
} ): Promise< SignupValidationResponse > {
	return wp.req
		.post( '/signups/validation/user/', null, {
			locale: getLocaleSlug(),
			email,
			is_from_registrationless_checkout,
		} )
		.then( ( data: unknown ) => {
			if ( ! isSignupValidationResponse( data ) ) {
				throw new Error( 'Signup validation returned unknown response.' );
			}
			return data;
		} );
}

function convertValidationMessages(
	rawMessages: RawContactValidationResponseMessages
): ContactValidationResponseMessages {
	// Reshape the error messages to a nested object
	const formattedMessages = Object.keys( rawMessages ).reduce( ( obj, key ) => {
		const messages = rawMessages[ key as keyof typeof rawMessages ];
		const fieldKeys = key.split( '.' );
		return hydrateNestedObject( obj, fieldKeys, messages );
	}, {} );
	debug( 'Parsed validation error messages keys', rawMessages, 'into', formattedMessages );
	return formattedMessages;
}

function convertValidationResponse( rawResponse: unknown ): DomainContactValidationResponse {
	if ( ! isRawContactValidationResponse( rawResponse ) ) {
		throw new Error( 'Contact validation returned unknown response.' );
	}
	if ( rawResponse.success ) {
		return { success: true };
	}
	return {
		success: false,
		messages: convertValidationMessages( rawResponse.messages ),
		messages_simple: rawResponse.messages_simple,
	};
}

async function wpcomValidateTaxContactInformation(
	contactInformation: ContactValidationRequestContactInformation
): Promise< DomainContactValidationResponse > {
	return wp.req
		.post( { path: '/me/tax-contact-information/validate' }, undefined, {
			contact_information: contactInformation,
		} )
		.then( convertValidationResponse );
}

async function wpcomValidateDomainContactInformation(
	contactInformation: ContactValidationRequestContactInformation,
	domainNames: string[]
): Promise< DomainContactValidationResponse > {
	return wp.req
		.post(
			{ path: '/me/domain-contact-information/validate' },
			{
				apiVersion: '1.2',
			},
			{
				contact_information: contactInformation,
				domain_names: domainNames,
			}
		)
		.then( convertValidationResponse );
}

async function wpcomValidateGSuiteContactInformation(
	contactInformation: ContactValidationRequestContactInformation,
	domainNames: string[]
): Promise< DomainContactValidationResponse > {
	return wp.req
		.post( { path: '/me/google-apps/validate' }, undefined, {
			contact_information: contactInformation,
			domain_names: domainNames,
		} )
		.then( convertValidationResponse );
}

export async function getTaxValidationResult(
	contactInfo: ManagedContactDetails
): Promise< DomainContactValidationResponse > {
	const formattedContactDetails = prepareContactDetailsForValidation( 'tax', contactInfo );
	return wpcomValidateTaxContactInformation( formattedContactDetails );
}

async function getDomainValidationResult(
	products: RequestCartProduct[],
	contactInfo: ManagedContactDetails
): Promise< DomainContactValidationResponse > {
	const domainNames = products
		.filter( ( product ) => isDomainProduct( product ) || isDomainTransfer( product ) )
		.filter( ( product ) => ! isDomainMapping( product ) )
		.map( getDomain );
	const formattedContactDetails = prepareContactDetailsForValidation( 'domain', contactInfo );
	return wpcomValidateDomainContactInformation( formattedContactDetails, domainNames );
}

async function getGSuiteValidationResult(
	products: RequestCartProduct[],
	contactInfo: ManagedContactDetails
): Promise< DomainContactValidationResponse > {
	const domainNames = products
		.filter( ( item ) => isGSuiteOrGoogleWorkspaceProductSlug( item.product_slug ) )
		.map( getDomain );
	const formattedContactDetails = prepareContactDetailsForValidation( 'gsuite', contactInfo );
	return wpcomValidateGSuiteContactInformation( formattedContactDetails, domainNames );
}

function handleContactValidationResult( {
	translate,
	showErrorMessage,
	validationResult,
	applyDomainContactValidationResults,
	clearDomainContactErrorMessages,
}: {
	translate: ReturnType< typeof useTranslate >;
	showErrorMessage: ( message: string ) => void;
	validationResult: unknown;
	applyDomainContactValidationResults: ( results: ManagedContactDetailsErrors ) => void;
	clearDomainContactErrorMessages: () => void;
} ) {
	if ( ! isContactValidationResponse( validationResult ) ) {
		return;
	}

	if ( ! validationResult ) {
		showErrorMessage(
			String(
				translate(
					'There was an error validating your contact information. Please contact support.'
				)
			)
		);
	}
	if ( validationResult && ! validationResult.success && validationResult.messages ) {
		showErrorMessage(
			String(
				translate(
					'We could not validate your contact information. Please review and update all the highlighted fields.'
				)
			)
		);
	}
	if ( validationResult?.success ) {
		clearDomainContactErrorMessages();
	} else {
		applyDomainContactValidationResults(
			formatDomainContactValidationResponse( validationResult ?? {} )
		);
	}
}

async function getSignupEmailValidationResult(
	email: string,
	emailTakenLoginRedirect: ( email: string ) => TranslateResult
) {
	const response = await wpcomValidateSignupEmail( {
		email,
		is_from_registrationless_checkout: true,
	} );
	const signupValidationErrorResponse = getSignupValidationErrorResponse(
		response,
		email,
		emailTakenLoginRedirect
	);

	if ( Object.keys( signupValidationErrorResponse ).length === 0 ) {
		return response;
	}
	const validationResponse = {
		...response,
		messages: signupValidationErrorResponse,
	};
	return validationResponse;
}