UNPKG

@adyen/kyc-components

Version:

This guide assumes that you have already an account with Adyen. A legalEntity needs to be created, and you need to have a `legalEntityId` to instatiate a Component.

1,095 lines 167 kB
try { let e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}, n = new e.Error().stack; n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "f5a08eee-6b7c-4c34-8a1c-0679d30bffce", e._sentryDebugIdIdentifier = "sentry-dbid-f5a08eee-6b7c-4c34-8a1c-0679d30bffce"); } catch (e) {} import { i as Typography, o as createLogger, r as useTranslation, t as Trans } from "./translation-BYvhW5zA.js"; import { B as INDIVIDUAL_VALID_CHAR_REGEX, C as useDataset, D as useCapabilities, E as useAllowedCountries, G as SPECIAL_CHARS, H as NO_ALPHABET_REGEX, Q as hasMaximumTwoRepeatedCharacters, T as datasetUtilities, Y as getFormattingRegEx, c as isLegalRepresentativeNeeded, ct as standardKanjiValidator, et as hasText, ft as useAccountHolder, it as isInvalidName, j as useToggleContext, k as Header, lt as standardKatakanaValidator, nt as isEmpty, o as getAgeRangeForLegalRepresentative, s as getAgeToday, st as matchesRegex, w as datasetIdentifier, x as Alert, z as EMOJI_REGEX } from "./resolveEnvironment-DNmu53Rr.js"; import { r as Loader, t as Button } from "./Button-i8I2dHP8.js"; import { n as httpGet, r as httpPost, s as useApiContext } from "./http-8qgzqVqk.js"; import { t as LegalEntityTypes } from "./legal-entity-type-0MfCGzUf.js"; import { t as getLegalEntityCountry } from "./getLegalEntityCountry-BHh7Ux8v.js"; import { t as useSettingsContext } from "./useSettingsContext-Bpf4UqRT.js"; import { i as drop, n as cloneObject, o as objectsDeepEqual, r as doArraysMatch } from "./AnalyticsContext-BFrJmsp0.js"; import { r as euCountries, t as CountryCodes } from "./country-code-CJk2hdPu.js"; import { l as individualDocumentMapping, s as individualApiKeyMapping, u as individualObscuredFields } from "./processCapabilities-fPuXc9gL.js"; import { t as TaskTypes } from "./taskTypes-NawDTp5n.js"; import { n as attachNomineeToRole, r as filterOutUnwantedAssociationsIfRootLE, s as getOwnEntityAssociations, u as hasNomineesChanged } from "./entityAssociationUtil-C-wflW8q.js"; import { t as DecisionMakerTypes } from "./decision-maker-type-NR4GFAeT.js"; import { t as Scenarios } from "./get-scenarios-Bb-paHmJ.js"; import { t as getAllowedDecisionMakerRoles } from "./decisionMakerRoles-DIG8zo1C.js"; import { i as useAnalyticsContext, t as Modal } from "./Modal-BLP2aF-u.js"; import { t as SettingNames } from "./types-Cwq1JAWT.js"; import { n as useToastContext } from "./invalidateRootLegalEntity-DLpPeD5p.js"; import { a as idNowPostSubmit, i as idNowModalChildEntityId, o as shouldShowIdNowModal, s as showIdNowModal } from "./bafinUtils-BKq-s1Ka.js"; import { n as translateTranslatable, r as LoaderWrapper } from "./utils-C1buyvRw.js"; import { t as Confirm } from "./Confirm-CA-gL38n.js"; import { t as TrustedFieldsProviders } from "./trusted-fields-provider-DLz8KKVf.js"; import { n as Image } from "./unincorporated-partnership-nnTW3FnG.js"; import { t as getIndividualLegalEntityName } from "./getName-D4ECvzcI.js"; import { t as useScenarios } from "./useScenarios-DciPyzQ-.js"; import { t as useCreateLegalEntity } from "./useCreateLegalEntity-CoBr-K0N.js"; import { a as individualFormDefaultData, i as GuidanceQuestionValues, n as getOnfidoIdentityTypeToApiIdentityTypeMap, o as shouldNavigateToAdditionalPersonalDetailsForMissingData, r as GuidanceQuestion, s as useCreateInvitation, t as mapLegalEntityToIndividualSchema } from "./mapLegalEntityToIndividualSchema-7sVfeCn9.js"; import { t as useUpdateLegalEntity } from "./useUpdateLegalEntity-B0XYfxbB.js"; import { c as addressValidators, d as useProviderStatus, t as Address } from "./Address-DDqWoeSK.js"; import { a as contactDetailsValidationRules, c as getAsyncPhoneValidationRules, i as phonePrefixes_default, l as getPhonePlaceholder, n as contactDetailFields, o as defaultFieldMetadata, r as PhoneField, s as fieldConfig, t as ContactDetails, u as useValidatePhoneNumberImperatively } from "./ContactDetails-BJgD_bMt.js"; import { i as FormFlow, n as addValidityToForms, o as useFormComposer, r as getRequiredForms, s as FormContextProvider, t as useFormContext } from "./useFormContext-CYHfY4k5.js"; import { n as composePerScenarioFormConfigurations, r as getPropsFromConfigurations } from "./process-field-configurations-DQlTj--V.js"; import { n as useFormRouterContext, t as ErrorPanel } from "./ErrorPanel-DGlzO81g.js"; import { n as mergeFieldMetadataIntoProps, t as createFormUtils } from "./formUtils-DVc3a6gf.js"; import { n as preTranslatedSummaryItem } from "./summaryItem-uDWmtYtt.js"; import { r as isTruthyValidator, t as useMultiForm } from "./useMultiForm-ducdUyQ6.js"; import { i as useScenarioConfiguration, n as getPage, r as getPageName, s as AdyenKycSdkError, t as mapExistingFile } from "./mapExistingFile-BmI24MBQ.js"; import { t as useTaskLandedEvent } from "./useTaskLandedEvent-BXtOctC4.js"; import { n as InputEmail, t as MaskedInput } from "./MaskedInput-_dYxgb7_.js"; import { t as JP_ADDRESS_REQUIRED_FIELDS } from "./jpAddressSchema-pVY2Cqvr.js"; import { n as toFullWidth, r as mapJpAddressSummary, t as mapJpAddressSchemaToAddressLocalizations } from "./mapJpAddressSchemaToAddressLocalizations-Dzcl40cA.js"; import { i as mapAddressLabels, l as addressFields, n as getAddressSchemaLabelsByCountry } from "./utils-DNIZ6F6L.js"; import { i as isValidationError, o as processValidationErrors, s as isMaintenanceModeError } from "./validationError-COmWiy16.js"; import { a as createDocumentRequest, d as mergeAttachments, l as getFileExtention, o as documentApiUtils, s as getDocument, u as getIdDocument } from "./validate-DkjeS-zE.js"; import { t as getLocalizedIdDocumentTypeOptions } from "./utils-DwujAUJC.js"; import { r as formatObject } from "./utils-DdHbAadK.js"; import { a as getFieldsWithExistingData, i as DocumentGuidance, n as TaxInformationField, r as MemoizedDocumentUpload } from "./TaxInformationField-DXH6WfO9.js"; import { a as isJapanLocalizationEnabled, i as individualRules, n as DECISION_MAKER_TYPES_WITH_JOBTITLE, t as COUNTRIES_WHICH_USE_MULTIPLE_IDENTITY_TYPES } from "./Individual.rules-Cc2Uigav.js"; import { t as localizeDateString } from "./localizeDateString-Bmx3yBcR.js"; import { t as omitObscuredFieldsIfUnchanged } from "./omitObscuredFieldsIfUnchanged-BehYhDYw.js"; import { _ as licenseCardNumberDefaultConfig, a as fromIndividualConflictSchema, c as createAddressConflictRule, d as useExtractDocumentInformation, f as IdentityNumber, g as getAsyncIdNumberValidationRule, h as defaultFieldMetadata$1, i as mapExtractionResultToSchema, l as useDataConflicts, m as defaultFieldConfig, n as UploadedDocument, o as toIndividualConflictSchema, p as idNumberFields, r as useIdVerificationToken, s as IdVerificationMethod_module_default, t as validateExtractionResult, u as addressToString, v as licenseCardNumberDefaultMetadata } from "./validateExtractionResult-BTnVuGgD.js"; import { A as taxInformationDefaultFieldMetadata, S as getDefaultTaxIdNumberType, T as taxIdNumberOptions, k as taxInformationDefaultFieldConfig } from "./utils-C9vhUXDJ.js"; import { n as emailPattern } from "./basePatterns-plHFNzgJ.js"; import { t as resolveFieldMetadata } from "./fieldConfigurations-CZCFghnK.js"; import { t as Field } from "./Field-DoXLi6EY.js"; import { t as LandingLayout } from "./LandingLayout-CUAkXrpL.js"; import { t as Select } from "./Select-DUo2rOfa.js"; import { n as convertFullToHalf, t as TextArea } from "./TextArea-CT04Dg1N.js"; import { t as Dropzone } from "./Dropzone-BzDQ_VtL.js"; import { n as getFormProps, t as getFieldProps } from "./getProps-1L-urpfA.js"; import { t as Link } from "./Link-JFzfaUOa.js"; import { t as InputText } from "./InputText-B0N7am-q.js"; import { n as formatDateObj, t as InputDate } from "./InputDate-CPkdZkHB.js"; import { n as CountryField } from "./CountryField-D-Q958WF.js"; import { t as RadioGroup } from "./RadioGroup-qV8mGGwm.js"; import { t as ContextGuidance } from "./ContextGuidance-R45SnI5u.js"; import { n as nameFields, t as Name } from "./Name-Dz2Meujh.js"; import { t as isEmpty$1 } from "./isEmpty-BVlBH98t.js"; import { t as DataConflictsModal } from "./DataConflictsModal-DXsYUQRX.js"; import { r as mapSchemaFieldsToApiScriptLocalization } from "./mapAddressLocalizationToJpAddressSchema-CBeBTFmC.js"; import { Suspense, lazy, memo } from "preact/compat"; import { useCallback as useCallback$1, useEffect as useEffect$1, useMemo as useMemo$1, useRef as useRef$1, useState as useState$1 } from "preact/hooks"; import { Fragment as Fragment$1, jsx, jsxs } from "preact/jsx-runtime"; import { signal } from "@preact/signals"; import { skipToken, useMutation, useQuery, useQueryClient } from "@tanstack/preact-query"; import { Show } from "@preact/signals/utils"; import { Onfido } from "onfido-sdk-ui"; import parsePhoneNumber from "libphonenumber-js/mobile"; //#region src/api/entityVerifications/useVerifyIdNumber.ts var verifyIdNumber = async (legalEntityId, baseUrl, data) => { return await httpPost({ baseUrl, path: `legalEntities/${legalEntityId}/verifications/idNumber`, errorHandler: async (response) => { const responseData = await response; if (responseData.status === 422) return { status: 422, message: responseData.detail, errorCode: responseData.errorCode }; if (responseData.status === 500) return { status: 500, message: "Service did not respond, do not block verification" }; } }, data); }; var useVerifyIdNumber = (options) => { const { rootLegalEntityId, baseUrl } = useApiContext(); return useMutation({ mutationFn: (data) => verifyIdNumber(rootLegalEntityId.value, baseUrl.value, data), ...options }); }; //#endregion //#region src/api/idVerificationProviders/idVerificationStartCheck.ts var startVerificationCheck = async (rootLegalEntityId, baseUrl, data) => { return httpPost({ baseUrl, path: `legalEntities/${rootLegalEntityId}/providers/idVerification/process` }, data); }; var useIdVerificationStartCheck = (options) => { const { rootLegalEntityId, baseUrl } = useApiContext(); return useMutation({ mutationFn: (data) => startVerificationCheck(rootLegalEntityId.value, baseUrl.value, data), ...options }); }; //#endregion //#region src/utils/customerSupportUtils.ts var customerSupportPresubmitProcess = (legalEntityResponse, legalEntityToSubmit) => { if (legalEntityResponse.type === "individual") return processCustomerSupportForIndividual(legalEntityResponse, legalEntityToSubmit); if (legalEntityResponse.type === "organization") return processCustomerSupportForOrganization(legalEntityResponse, legalEntityToSubmit); }; var processCustomerSupportForOrganization = (legalEntityResponse, legalEntityToSubmit) => { if (!legalEntityResponse.organization?.support) return legalEntityToSubmit.organization?.support ?? void 0; if (legalEntityResponse.organization?.countryOfGoverningLaw !== legalEntityToSubmit.organization?.countryOfGoverningLaw) { const customerSupport = legalEntityResponse.organization?.support; switch (legalEntityToSubmit.organization?.countryOfGoverningLaw) { case CountryCodes.Japan: return unsetCustomerSupportNumber(customerSupport); default: return customerSupport; } } }; var processCustomerSupportForIndividual = (legalEntityResponse, legalEntityToSubmit) => { if (!legalEntityResponse.individual?.support) return legalEntityToSubmit.individual?.support ?? void 0; if (legalEntityResponse.individual?.residentialAddress.country !== legalEntityToSubmit.individual?.residentialAddress.country) { const customerSupport = legalEntityResponse.individual?.support; switch (legalEntityToSubmit.individual?.residentialAddress.country) { case CountryCodes.Japan: return unsetCustomerSupportNumber(customerSupport); default: return customerSupport; } } }; var unsetCustomerSupportNumber = (customerSupport) => { return customerSupport ? { email: customerSupport.email, phone: { number: "", type: "mobile" } } : void 0; }; //#endregion //#region src/utils/getSSNType.ts var ERROR_CODES = { SSN_REMEDIATION: "1_316", SSN_4_DIGITS_VALIDATION: "1_3062", PERSONAL_DETAILS_VALIDATION: "1_30" }; var getSSNType = (formVerifcationErrors, existingIdNumber) => { return check4DigitSsnFailed(formVerifcationErrors) || existingIdNumber?.length === 9 ? "ssn" : "ssnLastFour"; }; var check4DigitSsnFailed = (formVerifcationErrors) => { return (formVerifcationErrors?.[ERROR_CODES.PERSONAL_DETAILS_VALIDATION])?.[ERROR_CODES.SSN_4_DIGITS_VALIDATION]?.some((error) => error.code === ERROR_CODES.SSN_REMEDIATION); }; //#endregion //#region src/components/Shared/fields/Name/validate.ts var nameValidationRulesV4 = () => { return { firstName: [{ modes: ["blur"], validate: (input) => !matchesRegex(NO_ALPHABET_REGEX, input), errorMessage: "nameMustContainLetters" }, { modes: ["blur"], validate: (input) => !matchesRegex(EMOJI_REGEX, input) && !hasMaximumTwoRepeatedCharacters(input) && !isInvalidName(input) && matchesRegex(INDIVIDUAL_VALID_CHAR_REGEX, input), errorMessage: "checkForTypos" }], lastName: [{ modes: ["blur"], validate: (input) => !matchesRegex(NO_ALPHABET_REGEX, input), errorMessage: "nameMustContainLetters" }, { modes: ["blur"], validate: (input) => !matchesRegex(EMOJI_REGEX, input) && !hasMaximumTwoRepeatedCharacters(input) && !isInvalidName(input) && matchesRegex(INDIVIDUAL_VALID_CHAR_REGEX, input), errorMessage: "checkForTypos" }] }; }; getFormattingRegEx(SPECIAL_CHARS.replace("-", "")); //#endregion //#region src/components/Individual/forms/AdditionalPersonalDetails/validate.ts var isNotOutOfRangeBirthDateValidatorRule = { modes: ["blur"], validate: (birthDate) => !isEmpty(birthDate) && new Date(birthDate) < /* @__PURE__ */ new Date(), errorMessage: "invalidDateOfBirth" }; var buildMinimumAgeValidationRule = (minimumAge) => ({ modes: ["blur"], validate: (birthDate) => !!birthDate && getAgeToday(birthDate) >= minimumAge, errorMessage: { key: "youMustXYearsOldToContinue", values: { minimumAge: minimumAge.toString() } } }); var getCountrySpecificMinimumAgeValidationRule = (country) => { if (!country) return buildMinimumAgeValidationRule(13); if ([ ...euCountries, CountryCodes.UnitedKingdom, CountryCodes.Switzerland ].some((c) => c === country)) return buildMinimumAgeValidationRule(16); switch (country) { case CountryCodes.HongKong: case CountryCodes.Singapore: return buildMinimumAgeValidationRule(18); default: return buildMinimumAgeValidationRule(13); } }; var additionalPersonalDetailsValidators = ({ country, isFeatureEnabled = () => false, isSettingEnabled = () => false, taskType, idNumberType, idNumberExempt, idNumber, existingIdNumber, formVerificationErrors, t, taxIdNumberType }) => ({ taxInformation: resolveFieldMetadata(taxInformationDefaultFieldConfig[country], { taxIdNumberType, companyType: LegalEntityTypes.INDIVIDUAL }, taxInformationDefaultFieldMetadata)?.validators, birthDate: (() => { const baseValidators = [isNotOutOfRangeBirthDateValidatorRule]; if (isSettingEnabled("enforceLegalAge")) return [...baseValidators, buildMinimumAgeValidationRule(18)]; if (isFeatureEnabled("EnableAgeVerification")) { if (taskType === TaskTypes.LEGAL_REPRESENTATIVE_DETAILS) return [...baseValidators, buildMinimumAgeValidationRule(18)]; return [...baseValidators, getCountrySpecificMinimumAgeValidationRule(country)]; } return baseValidators; })(), ...isFeatureEnabled("StrictNameAndAddressValidationV4") ? nameValidationRulesV4() : void 0, ...contactDetailsValidationRules, idNumber: (() => { const derivedIdNumberType = country === CountryCodes.UnitedStates || country === CountryCodes.PuertoRico ? getSSNType(formVerificationErrors, existingIdNumber) : idNumberType; return idNumberExempt ? { validate: () => { return idNumberExempt || !isEmpty(idNumber); }, modes: ["blur"] } : resolveFieldMetadata(defaultFieldConfig[country], { idNumberType: derivedIdNumberType }, defaultFieldMetadata$1)?.validators; })(), ...addressValidators({ isFeatureEnabled, country, t }) }); //#endregion //#region src/components/Shared/fields/LocalizedNameFields/validate.ts var localizedNameValidationRulesV4 = (isFeatureEnabled = () => false, country) => { if (isJapanLocalizationEnabled(isFeatureEnabled, country)) return { jaHaniFirstName: [{ modes: ["blur"], validate: hasText, errorMessage: "fieldIsRequired" }, { modes: ["blur"], validate: (input) => standardKanjiValidator(input), errorMessage: "checkForTypos" }], jaHaniLastName: [{ modes: ["blur"], validate: hasText, errorMessage: "fieldIsRequired" }, { modes: ["blur"], validate: (input) => standardKanjiValidator(input), errorMessage: "checkForTypos" }], jaKanaFirstName: [{ modes: ["blur"], validate: hasText, errorMessage: "fieldIsRequired" }, { modes: ["blur"], validate: (input) => standardKatakanaValidator(input), errorMessage: "ensureValidFullWidthKatakana" }], jaKanaLastName: [{ modes: ["blur"], validate: hasText, errorMessage: "fieldIsRequired" }, { modes: ["blur"], validate: (input) => standardKatakanaValidator(input), errorMessage: "ensureValidFullWidthKatakana" }] }; return {}; }; //#endregion //#region src/components/Individual/forms/BasicDetails/validate.ts var basicDetailsValidators = ({ isFeatureEnabled = () => false, country }) => ({ ...contactDetailsValidationRules, ...isFeatureEnabled("StrictNameAndAddressValidationV4") ? nameValidationRulesV4() : void 0, ...localizedNameValidationRulesV4(isFeatureEnabled, country) }); //#endregion //#region src/components/Individual/forms/IdDocumentUpload/types.ts var onfidoDocumentTypeMapping = [ { id: "driversLicense", name: "driversLicense", hasBackPage: true }, { id: "identityCard", name: "identityCard", hasBackPage: true }, { id: "passport", name: "passport", hasBackPage: false } ]; //#endregion //#region src/api/idNowProvider/useIdNowProvider.ts var getIdNowProviderIdentificationStatus = async (rootLegalEntityId, baseUrl, legalEntityId) => { return httpGet({ baseUrl, path: `legalEntities/${rootLegalEntityId}/child/${legalEntityId}/provider/idnow/identification/status`, errorHandler: async (response) => { const responseData = await response; if (responseData.status === 404) return { status: 404, message: responseData.detail, errorCode: responseData.errorCode }; } }); }; var useIdNowIdentificationStatus = (legalEntityId, options) => { const { rootLegalEntityId, baseUrl } = useApiContext(); return useQuery({ queryKey: legalEntityId === skipToken ? [] : ["idNowProviderIdentificationStatus", legalEntityId], queryFn: legalEntityId === skipToken ? skipToken : () => getIdNowProviderIdentificationStatus(rootLegalEntityId.value, baseUrl.value, legalEntityId), ...options }); }; var idNowProviderStartIdentification = async (rootLegalEntityId, baseUrl, legalEntityId) => { return httpPost({ baseUrl, path: `legalEntities/${rootLegalEntityId}/child/${legalEntityId}/provider/idnow/identification/start` }); }; var useIdNowStartIdentification = (legalEntityId, options) => { const { rootLegalEntityId, baseUrl } = useApiContext(); return useQuery({ queryKey: legalEntityId === skipToken ? [] : ["idNowProviderStartIdentification", legalEntityId], queryFn: legalEntityId === skipToken ? skipToken : () => idNowProviderStartIdentification(rootLegalEntityId.value, baseUrl.value, legalEntityId), ...options }); }; var IdNowVerificationModal_module_default = { "idnow-header": "_idnow-header_m87oy_1", idnowHeader: "_idnow-header_m87oy_1", "idnow-verification-header-iframe-container": "_idnow-verification-header-iframe-container_m87oy_7", idnowVerificationHeaderIframeContainer: "_idnow-verification-header-iframe-container_m87oy_7", "idnow-verification-header-iframe": "_idnow-verification-header-iframe_m87oy_7", idnowVerificationHeaderIframe: "_idnow-verification-header-iframe_m87oy_7", "idnow-verification-header-image": "_idnow-verification-header-image_m87oy_18", idnowVerificationHeaderImage: "_idnow-verification-header-image_m87oy_18" }; //#endregion //#region src/components/Individual/forms/IdNowVerificationModal/IFrameWidget.ts var MOUNT_TIMEOUT = 10 * 1e3; var activeWidget; var IFrameWidget = class { iframeUrl; iframeElement; mountInProgress = false; constructor(iframeElement, url, _vendor, _sdkToken) { try { this.iframeUrl = new URL(url); } catch (err) { throw new AdyenKycSdkError("WIDGET_URL_MALFORMED", err); } this.iframeElement = iframeElement; } unmount() { if (this.mountInProgress) throw new AdyenKycSdkError("Cannot unmount widget, mounting is still in progress"); this.iframeElement.remove(); activeWidget = null; } async mount() { if (activeWidget) throw new AdyenKycSdkError(`You can only have one ${this.constructor.name} mounted at a time`); activeWidget = this; if (this.mountInProgress) throw new AdyenKycSdkError("Cannot mount widget, mounting is already in progress"); this.mountInProgress = true; try { await new Promise((resolve, reject) => { const timeoutId = setTimeout(() => { this.mountInProgress = false; reject(new AdyenKycSdkError("WIDGET_TIMEOUT")); }, MOUNT_TIMEOUT); const cancelTimeout = () => { if (timeoutId) clearTimeout(timeoutId); }; this.iframeElement.addEventListener("load", () => { cancelTimeout(); this.mountInProgress = false; resolve(); }); requestAnimationFrame(() => { try { this.iframeElement.setAttribute("src", this.iframeUrl.href); } catch (ex) { cancelTimeout(); this.mountInProgress = false; reject(ex); } }); }); } catch (err) { throw new AdyenKycSdkError("WIDGET_LAUNCH_FAILED", err); } } async mountAndWaitForResponse() { await this.mount(); } }; //#endregion //#region src/components/Individual/forms/IdNowVerificationModal/IdNowVerificationModal.tsx var passportFrontGreenImage$1 = lazy(() => import("./passport-front-green-BWuD3-Fs.js")); /** * Checks if the IDnow identification status is considered successful. * @param status - The status object from the IDnow provider. * @returns True if the provider status is 'SUCCESS', 'SUCCESS_DATA_CHANGED', or 'REVIEW_PENDING'. */ var isIdNowSuccessful = (status) => { const providerStatus = status?.providerStatus; return providerStatus === "SUCCESS" || providerStatus === "SUCCESS_DATA_CHANGED" || providerStatus === "REVIEW_PENDING"; }; var IdNowVerificationModal = ({ handleFinish }) => { const { t } = useTranslation(["individual", "common"]); const [isConfirmPresented, setIsConfirmPresented] = useState$1(false); const [genericError, setGenericError] = useState$1(false); const widgetContainerRef = useRef$1(null); const iFrameRef = useRef$1(null); const iFrameWidgetRef = useRef$1(null); const [page, setPage] = useState$1(1); const queryClient = useQueryClient(); const { showToast } = useToastContext(); const { data: idNowStatus, isLoading: isStatusLoading, isError: isStatusError, refetch: refetchIdNowIdentificationStatus } = useIdNowIdentificationStatus(idNowModalChildEntityId.value?.id ?? skipToken, { enabled: !!idNowModalChildEntityId.value?.id, refetchOnMount: "always", refetchInterval: (query) => { if (query.state.status === "error") return false; return 1e4; }, retry: (failureCount, error) => { if ("status" in error && (error.status === 404 || error.status === 500)) return false; return failureCount < 3; } }); const { data: idNowStart, isLoading, isError: idNowStartError, refetch: refetchIdNowStartIdentification } = useIdNowStartIdentification(idNowModalChildEntityId.value?.id ?? skipToken, { enabled: !!idNowModalChildEntityId.value?.id && page === 2 }); const handleDismiss = () => { setIsConfirmPresented(true); }; const handleCancelDismiss = () => { setIsConfirmPresented(false); }; const handleConfirmDismiss = () => { setPage(1); setGenericError(false); setIsConfirmPresented(false); showIdNowModal.value = false; if (idNowStartError && idNowModalChildEntityId.value?.id) queryClient.resetQueries({ queryKey: ["idNowProviderStartIdentification", idNowModalChildEntityId.value?.id] }); idNowModalChildEntityId.value = void 0; iFrameWidgetRef.current?.unmount(); iFrameRef.current?.remove(); if (idNowPostSubmit.value) handleFinish?.(); idNowPostSubmit.value = false; }; if (idNowStatus?.status === "finished") { if (isIdNowSuccessful(idNowStatus)) { idNowPostSubmit.value = true; showToast({ label: t(($) => $["successfullyUpdatedDetails"], { ns: "common" }), variant: "success" }); handleConfirmDismiss(); } else if (page === 2) handleConfirmDismiss(); } if (!isLoading && idNowStartError) { setGenericError(true); setPage(1); } const initializeIdNowWidget = useCallback$1(async (url) => { const container = widgetContainerRef.current; if (!container) return; const iFrame = document.createElement("iframe"); iFrameRef.current = iFrame; iFrame.setAttribute("allowFullscreen", "true"); iFrame.setAttribute("name", "idnow"); iFrame.classList.add(IdNowVerificationModal_module_default.idnowVerificationHeaderIframe); iFrame.setAttribute("height", "800"); iFrame.setAttribute("allow", "camera *;microphone *;geolocation *;clipboard-read *;clipboard-write *"); container.appendChild(iFrame); try { iFrameWidgetRef.current = new IFrameWidget(iFrame, url, "idnow", ""); await iFrameWidgetRef.current.mountAndWaitForResponse(); } catch (err) { console.error("Error occurred:", err); setGenericError(true); setPage(1); } }, []); useEffect$1(() => { if (page === 2 && !isLoading && idNowStart && idNowStart?.url) (async () => { await refetchIdNowIdentificationStatus(); await initializeIdNowWidget(idNowStart.url); })(); return () => { iFrameWidgetRef.current?.unmount(); iFrameRef.current?.remove(); }; }, [ isLoading, page, initializeIdNowWidget, refetchIdNowIdentificationStatus, idNowStart ]); return /* @__PURE__ */ jsxs(Fragment$1, { children: [!isStatusLoading && /* @__PURE__ */ jsxs(Modal, { size: page === 2 ? "large" : "medium", showCloseButton: !isLoading && !isStatusLoading, onClose: handleDismiss, ariaLabel: t(($) => $["identityVerification"]), children: [page === 1 && /* @__PURE__ */ jsx("div", { className: IdNowVerificationModal_module_default.idnowHeader, children: /* @__PURE__ */ jsx(LandingLayout, { media: /* @__PURE__ */ jsx(Image, { className: IdNowVerificationModal_module_default.idnowVerificationHeaderImage, lazyLoadedImage: passportFrontGreenImage$1 }), title: t(($) => $["identityVerification"]), description: /* @__PURE__ */ jsxs(Fragment$1, { children: [ t(($) => $["idNowDescription"], { ns: "individual" }), /* @__PURE__ */ jsx("br", {}), /* @__PURE__ */ jsx("br", {}), getIndividualLegalEntityName(idNowModalChildEntityId.value) && t(($) => $["idNowDescriptionName"], { ns: "individual", name: getIndividualLegalEntityName(idNowModalChildEntityId.value) }) ] }), error: !isLoading && (genericError || isStatusError) ? /* @__PURE__ */ jsx(Alert, { variant: "error", title: t(($) => $["thereWasAnErrorTryAgain"], { ns: "common" }) }) : void 0, actions: /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx(Button, { onClick: async () => { setGenericError(false); setPage(2); await refetchIdNowStartIdentification(); }, disabled: isLoading || isStatusLoading || idNowStatus?.status === "finished" && isIdNowSuccessful(idNowStatus), fullWidth: true, children: idNowStatus?.status === "pending" ? t(($) => $["continueVerification"], { ns: "common" }) : t(($) => $["startVerification"], { ns: "common" }) }), /* @__PURE__ */ jsx(Button, { disabled: isLoading || isStatusLoading, variant: "tertiary", onClick: handleConfirmDismiss, fullWidth: true, children: idNowPostSubmit.value ? t(($) => $["finishLater"], { ns: "common" }) : t(($) => $["editDetails"], { ns: "common" }) })] }) }) }), page === 2 && (isLoading ? /* @__PURE__ */ jsx(Loader, {}) : /* @__PURE__ */ jsx("div", { ref: widgetContainerRef, className: IdNowVerificationModal_module_default.idnowVerificationHeaderIframeContainer }))] }), isConfirmPresented && /* @__PURE__ */ jsx(Confirm, { confirmText: t(($) => $["leave"], { ns: "common" }), onCancel: handleCancelDismiss, onConfirm: handleConfirmDismiss, title: t(($) => $["unsavedChanges"], { ns: "common" }) })] }); }; //#endregion //#region src/components/Individual/forms/IdVerification/idVerificationProviderId.ts var idVerificationProviderId = signal(); //#endregion //#region src/utils/areArraysDifferent.ts var areArraysDifferent = (a = [], b = []) => { if (a.length !== b.length) return true; const sortedA = [...a].sort(); const sortedB = [...b].sort(); return sortedA.some((item, index) => item !== sortedB[index]); }; //#endregion //#region src/utils/useModalAction.ts var useModalAction = () => { const userEvents = useAnalyticsContext(); return useCallback$1((label, actionType, setModalState, callback) => { userEvents.addPageEvent(actionType === "open" ? "Opened modal" : actionType === "close" ? "Closed modal" : "Clicked button", { actionType, label }); setModalState(actionType === "open"); callback?.(); }, [userEvents]); }; //#endregion //#region src/components/Individual/helpers/roleUtils.ts var calculateRoles = (data) => { return [ { isApplicable: data?.signatoryQuestionnaire?.isSignatory === GuidanceQuestionValues.YES, role: DecisionMakerTypes.SIGNATORY }, { isApplicable: data?.uboQuestionnaire?.isOwner === GuidanceQuestionValues.YES, role: DecisionMakerTypes.OWNER }, { isApplicable: data?.uboQuestionnaire?.isControllingPerson === GuidanceQuestionValues.YES, role: DecisionMakerTypes.CONTROLLING_PERSON }, { isApplicable: data?.uboQuestionnaire?.isDirector === GuidanceQuestionValues.YES, role: DecisionMakerTypes.DIRECTOR } ].filter(({ isApplicable }) => isApplicable).map(({ role }) => role); }; //#endregion //#region src/components/Individual/helpers/shouldShowMotionCapture.ts var showIndividualMotionCapture = signal(void 0); var setShowIndividualMotionCapture = (showMotionCapture) => { showIndividualMotionCapture.value = showMotionCapture; }; var hasMotionCaptureScenario = signal(void 0); var setHasMotionCaptureScenario = (scenarios) => { hasMotionCaptureScenario.value = scenarios?.some((scenario) => scenario === Scenarios.L_MOTION || scenario === Scenarios.L1_ID); }; var allowedRolesForMotionCapture = [DecisionMakerTypes.SIGNATORY]; var shouldShowMotionCapture = ({ capabilities, userRoles, taskType, hasMotionScenario, hasLiveSelfieError, isInvitedEntity = false }) => { if (hasLiveSelfieError) return true; if (isInvitedEntity) return shouldShowMotionCaptureForInvitedEntity({ capabilities, userRoles }); if (!hasMotionScenario) return false; const isIndividual = taskType === TaskTypes.INDIVIDUAL; const hasRequiredRole = userRoles?.some((role) => allowedRolesForMotionCapture.includes(role)); const hasRequiredCapability = capabilities?.issueBankAccount?.requested ?? false; return (isIndividual || hasRequiredRole) && hasRequiredCapability; }; var shouldShowMotionCaptureForInvitedEntity = ({ capabilities, userRoles }) => { if (!userRoles || !userRoles.includes("signatory") || capabilities === void 0) return false; const rootCapabilitiesToShowMotionCaptureFor = [ "issueBankAccount", "receiveFromThirdParty", "sendToThirdParty" ]; return Object.keys(capabilities).some((capabilityName) => rootCapabilitiesToShowMotionCaptureFor.includes(capabilityName) && capabilities[capabilityName]?.requested); }; //#endregion //#region src/components/Shared/fields/IdFieldTypeSelector/countryIdNumberTypes.ts var individualIdNumberOptions = { [CountryCodes.Spain]: [{ id: "dni", name: "dni" }, { id: "nie", name: "nie" }] }; var additionallIdNumberOptions = { [CountryCodes.NewZealand]: [{ id: "driversLicense", name: "driversLicense" }, { id: "passport", name: "passportNumber" }], [CountryCodes.HongKong]: [ { id: "proofOfIdentityCard", name: "stateIssuedProofOfIdentityCard" }, { id: "driversLicense", name: "driversLicense" }, { id: "passport", name: "passportNumber" } ], [CountryCodes.Australia]: [{ id: "driversLicense", name: "driversLicense" }, { id: "passport", name: "passportNumber" }] }; //#endregion //#region src/components/Shared/fields/IdFieldTypeSelector/IndividualIdNumberTypeSelector.tsx function IndividualIdNumberTypeSelector({ country, selected, handleFieldChange }) { const { t } = useTranslation("common"); const options = useMemo$1(() => individualIdNumberOptions[country] ?? [], [country]); useEffect$1(() => { if (!selected && options.length > 0) handleFieldChange(options[0].id); }, [ options, selected, handleFieldChange ]); if (options.length <= 1) return null; return /* @__PURE__ */ jsx(Field, { el: "fieldset", name: "individualIdNumberType", label: t(($) => $["whichTypeOfIdNumberDoYouHave"]), children: (childProps) => /* @__PURE__ */ jsx(RadioGroup, { ...childProps, name: "individualIdNumberType", items: options, value: selected, onChange: (value) => handleFieldChange(value) }) }); } //#endregion //#region src/components/Shared/PatriotActDisclosure/PatriotActDisclosure.tsx var PatriotActDisclosure = () => { const { t } = useTranslation("common"); return /* @__PURE__ */ jsx("div", { className: "u-margin-bottom-12", children: /* @__PURE__ */ jsx(Typography, { variant: "caption", color: "secondary", children: t(($) => $["toHelpTheGovernmentFight"]) }) }); }; //#endregion //#region src/components/Individual/helpers/isDecisionMakerTask.ts var isDecisionMakerTask = (taskType) => taskType === TaskTypes.DECISION_MAKER || taskType === TaskTypes.TRUST_MEMBER_COMPANY_OWNER || taskType === TaskTypes.UNINCORPORATED_PARTNERSHIP_MEMBER_COMPANY_OWNER; //#endregion //#region src/components/Individual/fields/DriversLicense/DriversLicense.tsx var DriversLicense = ({ country, driversLicense, onIssuerStateChange, onLicenseNumberInput, onLicenseNumberBlur, onCardNumberInput, onCardNumberBlur, formUtils, isValid, errorMessages, guidanceText, shouldValidate }) => { const { t: commonT } = useTranslation("common"); const { t: individualT } = useTranslation("individual"); const { dataset: auStates } = useDataset(datasetIdentifier.state("AU")); const isCountryAustralia = country === CountryCodes.Australia; const isCountryNewZealand = country === CountryCodes.NewZealand; return /* @__PURE__ */ jsxs(Fragment$1, { children: [ isCountryAustralia && onIssuerStateChange !== void 0 && /* @__PURE__ */ jsx(Field, { name: "issuerState", label: formUtils.getLabel("issuerState"), isValid: isValid.issuerState, errorMessage: errorMessages.issuerState, children: (childProps) => /* @__PURE__ */ jsx(Select, { ...childProps, name: "issuerState", onChange: onIssuerStateChange, isInvalid: false, items: auStates, placeholder: commonT(($) => $["selectState"]), selected: driversLicense.issuerState }) }), /* @__PURE__ */ jsxs("div", { className: "adyen-kyc-field-wrapper", children: [/* @__PURE__ */ jsx(MaskedInput, { name: "idNumber", type: "text", label: formUtils.getLabel("idNumber", "idNumber"), formatGuidance: guidanceText.idNumber, errorMessage: errorMessages.idNumber, shouldValidate, isValid: Boolean(isValid.idNumber), "aria-required": formUtils.isRequiredField("idNumber"), "aria-invalid": !isValid.idNumber, onBlur: onLicenseNumberBlur, readonly: formUtils.isReadOnly("idNumber"), value: driversLicense.idNumber ?? "", onInput: onLicenseNumberInput, acceptObscuredValue: formUtils?.isObscured("idNumber"), ...formUtils.getMask("idNumber") }), /* @__PURE__ */ jsx(MaskedInput, { name: "licenseCardNumber", type: "text", label: formUtils.getLabel("licenseCardNumber", "licenseCardNumber"), formatGuidance: guidanceText.licenseCardNumber, errorMessage: errorMessages.licenseCardNumber, shouldValidate, isValid: Boolean(isValid.licenseCardNumber), "aria-required": formUtils.isRequiredField("licenseCardNumber"), "aria-invalid": !isValid.licenseCardNumber, onBlur: onCardNumberBlur, readonly: formUtils.isReadOnly("licenseCardNumber"), value: driversLicense.licenseCardNumber ?? "", onInput: onCardNumberInput, acceptObscuredValue: formUtils?.isObscured("licenseCardNumber"), ...formUtils.getMask("licenseCardNumber") })] }), (isCountryAustralia || isCountryNewZealand) && /* @__PURE__ */ jsx(ContextGuidance, { title: individualT(($) => $["whereCanIFindTheseNumbersOnMyDriversLicense"]), content: /* @__PURE__ */ jsxs(Fragment$1, { children: [isCountryAustralia ? `${individualT(($) => $["whereToFindNumbersOnDriversLicense"])}\u00A0` : `${individualT(($) => $["whereToFindNumbersOnDriversLicense__NZ"])}\u00A0`, /* @__PURE__ */ jsx(Link, { href: isCountryAustralia ? "https://www.usi.gov.au/about/forms-id/drivers-licence" : "https://www.nzta.govt.nz/driver-licences/getting-a-licence/your-driver-licence-explained/", children: individualT(($) => $["iStillCantFindIt"]) })] }), titleId: "whereCanIFindTheseNumbersOnMyDriversLicense", contentId: "whereToFindNumbersOnDriversLicense" }) ] }); }; //#endregion //#region src/components/Individual/forms/AdditionalPersonalDetails/Identity/TypeOfIdentity/index.tsx var TypeOfIdentity = ({ availableIdentityTypesOptions, selectedIdentityType, setSelectedIdentityType, label, errorMessage, isValid }) => { const { t } = useTranslation(["common", "individual"]); return /* @__PURE__ */ jsx(Field, { name: "typeOfIdentity", label, errorMessage, isValid, helper: t(($) => $["typeOfIdentitySubtitle"], { ns: "individual" }), children: (childProps) => /* @__PURE__ */ jsx(Select, { ...childProps, name: "typeOfIdentity", isInvalid: false, items: availableIdentityTypesOptions.map(({ id, name }) => ({ id, name: t(($) => $[name]) })), placeholder: t(($) => $["selectOne"]), selected: selectedIdentityType, onChange: (event) => setSelectedIdentityType(event.target.value) }) }); }; //#endregion //#region src/components/Individual/forms/AdditionalPersonalDetails/Identity/validate.ts var identityValidationRules = (country) => { switch (country) { case CountryCodes.Australia: return { typeOfIdentity: [isTruthyValidator], issuerState: [isTruthyValidator] }; case CountryCodes.HongKong: case CountryCodes.NewZealand: return { typeOfIdentity: [isTruthyValidator] }; default: return {}; } }; //#endregion //#region src/components/Individual/forms/AdditionalPersonalDetails/Identity/Identity.tsx function Identity(props) { const { additionalPersonalDetails, country, idNumberType, handleFieldChange } = props; const { data, errors, fieldValidationErrors, formVerificationErrors, id: dataStoreId, labels, obscuredFields, optionalFields, requiredFields, readOnlyFields, shouldValidate, validators, valid } = additionalPersonalDetails; const initialFormUtilProps = useMemo$1(() => { return { validators: { ...identityValidationRules(country), ...validators }, labels, obscuredFields, readOnlyFields, optionalFields, requiredFields }; }, [ country, validators, labels, obscuredFields, readOnlyFields, optionalFields, requiredFields ]); const licenseCardNumberMetaData = useMemo$1(() => { return resolveFieldMetadata(licenseCardNumberDefaultConfig[country], {}, licenseCardNumberDefaultMetadata); }, [country]); const idNumberMetadata = useMemo$1(() => { return resolveFieldMetadata(defaultFieldConfig[country], { idNumberType: data?.typeOfIdentity }, defaultFieldMetadata$1); }, [country, data?.typeOfIdentity]); const mergedProps = useMemo$1(() => { return mergeFieldMetadataIntoProps("idNumber", idNumberMetadata, mergeFieldMetadataIntoProps("licenseCardNumber", licenseCardNumberMetaData, initialFormUtilProps)); }, [ idNumberMetadata, initialFormUtilProps, licenseCardNumberMetaData ]); const { t } = useTranslation("common"); const formUtils = useMemo$1(() => createFormUtils(mergedProps, t), [mergedProps, t]); const { form } = useFormContext(); const defaultIdNumber = form?.defaultData?.additionalPersonalDetails?.idNumber; const ssnType = getSSNType(formVerificationErrors, defaultIdNumber); const today = /* @__PURE__ */ new Date(); const maxExpiryDateSelection = new Date((/* @__PURE__ */ new Date()).setFullYear(today.getFullYear() + 10)); const isCountryAustralia = country === CountryCodes.Australia; const isCountryNewZealand = country === CountryCodes.NewZealand; useEffect$1(() => { if (data?.typeOfIdentity === "nationalIdNumber") handleFieldChange("typeOfIdentity")(void 0); }, [data?.typeOfIdentity, handleFieldChange]); if (!handleFieldChange) return; const identityProps = getFieldProps(additionalPersonalDetails, idNumberFields); if (country === CountryCodes.UnitedStates || country === CountryCodes.PuertoRico) return /* @__PURE__ */ jsx(IdentityNumber, { ...identityProps, errors, dataStoreId, country, formVerificationErrors, handleFieldChange, idNumberType: ssnType }); return COUNTRIES_WHICH_USE_MULTIPLE_IDENTITY_TYPES.includes(country) ? /* @__PURE__ */ jsxs(Fragment$1, { children: [ /* @__PURE__ */ jsx(TypeOfIdentity, { availableIdentityTypesOptions: additionallIdNumberOptions?.[country], selectedIdentityType: data?.typeOfIdentity, setSelectedIdentityType: handleFieldChange("typeOfIdentity"), label: formUtils.getLabel("typeOfIdentity"), isValid: Boolean(valid?.typeOfIdentity), errorMessage: formUtils.getErrorMessage("typeOfIdentity", errors, fieldValidationErrors) }), (isCountryAustralia || isCountryNewZealand) && data?.typeOfIdentity === "passport" && /* @__PURE__ */ jsx(MaskedInput, { name: "idNumber", type: "text", label: formUtils.getLabel("idNumber", "idNumber"), formatGuidance: translateTranslatable(t, idNumberMetadata.guidanceText), errorMessage: formUtils.getErrorMessage("idNumber", errors, fieldValidationErrors), shouldValidate, isValid: Boolean(valid?.idNumber), "aria-required": formUtils.isRequiredField("idNumber"), "aria-invalid": !valid?.idNumber, onBlur: handleFieldChange("idNumber", "blur"), readonly: formUtils.isReadOnly("idNumber"), value: data?.idNumber ?? "", onInput: handleFieldChange("idNumber", "input"), acceptObscuredValue: formUtils?.isObscured("idNumber"), ...formUtils.getMask("idNumber") }), isCountryNewZealand && data?.typeOfIdentity === "passport" && /* @__PURE__ */ jsx(Field, { name: "expiryDate", label: formUtils.getLabel("passportExpiryDate"), errorMessage: formUtils.getErrorMessage("expiryDate", errors, fieldValidationErrors), isValid: valid?.expiryDate, children: (childProps) => /* @__PURE__ */ jsx(InputDate, { ...childProps, name: "expiryDate", value: data?.expiryDate, placeholder: t(($) => $["datePlaceholder"]), readonly: formUtils.isReadOnly("expiryDate"), onInput: handleFieldChange("expiryDate", "input"), onBlur: handleFieldChange("expiryDate", "blur"), "aria-required": true, "aria-invalid": !valid?.expiryDate, min: formatDateObj(today), max: formatDateObj(maxExpiryDateSelection) }) }), (isCountryAustralia || isCountryNewZealand) && data?.typeOfIdentity === "driversLicense" && /* @__PURE__ */ jsx(DriversLicense, { country, driversLicense: data, onIssuerStateChange: handleFieldChange("issuerState"), onLicenseNumberInput: handleFieldChange("idNumber", "input"), onLicenseNumberBlur: handleFieldChange("idNumber", "blur"), onCardNumberInput: handleFieldChange("licenseCardNumber", "input"), onCardNumberBlur: handleFieldChange("licenseCardNumber", "blur"), formUtils, isValid: { idNumber: Boolean(valid?.idNumber), licenseCardNumber: Boolean(valid?.licenseCardNumber), issuerState: Boolean(valid?.issuerState) }, guidanceText: { idNumber: translateTranslatable(t, idNumberMetadata.guidanceText), licenseCardNumber: translateTranslatable(t, licenseCardNumberMetaData.guidanceText) }, errorMessages: { idNumber: formUtils.getErrorMessage("idNumber", errors, fieldValidationErrors), licenseCardNumber: formUtils.getErrorMessage("licenseCardNumber", errors, fieldValidationErrors), issuerState: formUtils.getErrorMessage("issuerState", errors, fieldValidationErrors) }, shouldValidate }), country === CountryCodes.HongKong && /* @__PURE__ */ jsx(MaskedInput, { name: "idNumber", type: "text", label: formUtils.getLabel("idNumber", "idNumber"), formatGuidance: translateTranslatable(t, idNumberMetadata.guidanceText), errorMessage: formUtils.getErrorMessage("idNumber", errors, fieldValidationErrors), shouldValidate, isValid: Boolean(valid?.idNumber), "aria-required": formUtils.isRequiredField("idNumber"), "aria-invalid": Boolean(!valid?.idNumber), onBlur: handleFieldChange("idNumber", "blur"), readonly: formUtils.isReadOnly("idNumber"), value: data?.idNumber ?? "", onInput: handleFieldChange("idNumber", "input"), acceptObscuredValue: formUtils?.isObscured("idNumber"), ...formUtils.getMask("idNumber") }) ] }) : /* @__PURE__ */ jsx(IdentityNumber, { ...identityProps, errors, country, dataStoreId, idNumberType, handleFieldChange }); } //#endregion //#region src/components/Individual/forms/AdditionalPersonalDetails/Identity/Identity.types.ts var additionalIdentityInfoFields = [ "typeOfIdentity", "licenseCardNumber", "issuerState", "expiryDate" ]; //#endregion //#region src/components/Individual/forms/AdditionalPersonalDetails/AdditionalPersonalDetails.tsx var LazyJpAddress = lazy(async () => (await import("./JpAddress-Bd5rPU32.js")).JpAddress); var additionalPersonalDetailsFields = [ "birthDate", ...idNumberFields, ...additionalIdentityInfoFields, "country", "nationality", "placeOfBirth", ...addressFields, ...JP_ADDRESS_REQUIRED_FIELDS, "taxInformation" ]; function AdditionalPersonalDetails(props) { const { t } = useTranslation(["common", "individual"]); const allowedCountries = useAllowedCountries(); const [showLegalRepresentativePrompt, setShowLegalRepresentativePrompt] = useState$1(false); const { isSettingEnabled } = useSettingsContext(); const { isFeatureEnabled } = useToggleContext(); const { form } = useFormContext(); const isAgeVerificationFeatureEnabled = isFeatureEnabled("EnableAgeVerification"); const isSettingsEnforceLegalAgeEnabled = isSettingEnabled(SettingNames.EnforceLegalAge); const { country: defaultCountry, data, formVerificationErrors, heading, shouldValidate, valid, fieldValidationErrors, errors = {}, taskType, handleFieldChange } = props; const country = data?.country ?? defaultCountry; const isIndividual = taskType === TaskTypes.INDIVIDUAL; const taxIdNumberType = getDefaultTaxIdNumberType(form.data?.additionalPersonalDetails?.taxInformation, country, LegalEntityTypes.INDIVIDUAL); const showField = (fieldKeys) => fieldKeys.some((field) => formUtils.isRequiredField(field) || formUtils.isOptionalField(field)); const formUtils = createFormUtils(mergeFieldMetadataIntoProps("taxInformation", resolveFieldMetadata(taxInformationDefaultFieldConfig[country], { taxIdNumberType, companyType: LegalEntityTypes.INDIVIDUAL }, taxInformationDefaultFieldMetadata), props), t); const birthDateErrorMessage = formUtils.getErrorMessage("birthDate", errors, fieldValidationErrors); const addressProps = getFieldProps(props, addressFields); const jpAddressProps = getFieldProps(props, JP_ADDRESS_REQUIRED_FIELDS); if (!handleFieldChange) return; const handleBirthDateChange = (event) => { handleFieldChange("birthDate", "blur")(event); if (isAgeVerificationFeatureEnabled && !isSettingsEnforceLegalAgeEnabled && isLegalRepresentativeNeeded(event.currentTarget.value, country, taskType)) setShowLegalRepresentativePrompt(true); }; const isRootIndividual = taskType === TaskTypes.INDIVIDUAL; const canEditCountry = isSettingEnabled(SettingNames.AllowPrefilledCountryEdit) || isDecisionMakerTask(taskType); return /* @__PURE__ */ jsxs("form", { "aria-describedby": "ariaErrorField", children: [ heading && /* @__PURE__ */ jsx(Header, { title: heading }), /* @__PURE__ */ jsx(ErrorPanel, { verificationErrors: formVerificationErrors, validationErrors: fieldValidationErrors, formUtils, id: "ariaErrorField" }), /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx(Typography, { el: "h3", variant: "title", children: t(($) => $["residentialAddress"]) }), /* @__PURE__ */ jsx(Typography, { el: "p", variant: "body", children: t(($) => $["thisPersonsPrimaryAddress"], { ns: "individual" }) })] }), formUtils.isRequiredField("country") && /* @__PURE__ */ jsx(CountryField, { data: { country }, valid: { country: valid?.country }, errors: { country: formUtils.getErrorMessage("country", errors, fieldValidationErrors) }, labels: { country: formUtils.getLabel("country") }, readonly: formUtils.isReadOnly("country") || !canEditCountry, allowedCountries: isRootIndividual ? allowedCountries : void 0, handleChangeFor: handleFieldChange }), isJapanLocalizationEnabled(isFeatureEnabled, country) ? /* @__PURE__ */ jsx(Suspense, { fallback: /* @__PURE__ */ jsx(Loader, {}), children: /* @__PURE__ */ jsx(LazyJpAddress, { ...jpAddressProps, addressType: "residentialAddress"