@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,099 lines • 291 kB
JavaScript
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] = "b3f95035-8b67-44ae-8af3-250ca55feda0", e._sentryDebugIdIdentifier = "sentry-dbid-b3f95035-8b67-44ae-8af3-250ca55feda0");
} catch (e) {}
import { i as Typography, o as createLogger, r as useTranslation } from "./translation-BYvhW5zA.js";
import { E as useAllowedCountries, T as datasetUtilities, at as isUndefinedOrNull, ft as useAccountHolder, j as useToggleContext, k as Header, nt as isEmpty, rt as isISIN, x as Alert } from "./resolveEnvironment-DNmu53Rr.js";
import { r as Loader, t as Button } from "./Button-i8I2dHP8.js";
import { r as httpPost, s as useApiContext } from "./http-8qgzqVqk.js";
import { r as useLegalEntity, t as ROOT_LE } from "./useLegalEntity-CtlUQv_J.js";
import { t as LegalEntityTypes } from "./legal-entity-type-0MfCGzUf.js";
import { t as useSettingsContext } from "./useSettingsContext-Bpf4UqRT.js";
import { c as entriesOf, i as drop, l as keysOf, o as objectsDeepEqual, r as doArraysMatch } from "./AnalyticsContext-BFrJmsp0.js";
import { t as StackLayout } from "./StackLayout-IUdNMDgW.js";
import { t as TaskVerificationStatus } from "./TaskVerificationStatus-CKHPTEpH.js";
import { n as TASK_STATUS_POLLING_INTERVAL_MS } from "./taskStatus-BtekPA8E.js";
import { t as CountryCodes } from "./country-code-CJk2hdPu.js";
import { _ as businessDetailsKeyMapping, f as solePropBusinessDetailsApiKeyMapping, g as businessDetailsDocumentMapping, h as businessDetailsApiKeyMapping, m as solePropBusinessDetailsKeyMapping, p as solePropBusinessDetailsDocumentMapping } from "./processCapabilities-fPuXc9gL.js";
import { t as TaskTypes } from "./taskTypes-NawDTp5n.js";
import { r as filterOutUnwantedAssociationsIfRootLE, s as getOwnEntityAssociations } from "./entityAssociationUtil-C-wflW8q.js";
import { t as Scenarios } from "./get-scenarios-Bb-paHmJ.js";
import { t as useBusinessLines } from "./useBusinessLines-BFsRoAAj.js";
import { t as Card } from "./Card-BCGLpdw7.js";
import { i as useAnalyticsContext, n as ModalContent, r as KEYBOARD_KEYS, t as Modal } from "./Modal-BLP2aF-u.js";
import { t as SettingNames } from "./types-Cwq1JAWT.js";
import { n as useToastContext, t as useInvalidateRootLegalEntity } from "./invalidateRootLegalEntity-DLpPeD5p.js";
import { c as CompanyTypesValues } from "./bafinUtils-BKq-s1Ka.js";
import { r as LoaderWrapper } from "./utils-C1buyvRw.js";
import { t as Confirm } from "./Confirm-CA-gL38n.js";
import { t as HandlerContext } from "./HandlerContext-DeMa68z0.js";
import { t as useScenarios } from "./useScenarios-DciPyzQ-.js";
import { t as useCreateLegalEntity } from "./useCreateLegalEntity-CoBr-K0N.js";
import { t as useUpdateLegalEntity } from "./useUpdateLegalEntity-B0XYfxbB.js";
import { a as defaultFieldMetadata, i as defaultFieldConfig, l as formatAddressForCleanse, n as STATE_FIELD, r as StateField, t as Address, u as useAddressCleanse } from "./Address-DDqWoeSK.js";
import { i as FormFlow, n as addValidityToForms, o as useFormComposer, 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 { t as StructuredList } from "./StructuredList-CUyo9-3i.js";
import { t as ErrorPanel } from "./ErrorPanel-DGlzO81g.js";
import { n as mergeFieldMetadataIntoProps, t as createFormUtils } from "./formUtils-DVc3a6gf.js";
import { n as summaryStep, r as Summary_module_default } from "./Summary-HxzWpI7W.js";
import { t as useMultiForm } from "./useMultiForm-ducdUyQ6.js";
import { i as useScenarioConfiguration, r as getPageName, t as mapExistingFile } from "./mapExistingFile-BmI24MBQ.js";
import { t as useTaskLandedEvent } from "./useTaskLandedEvent-BXtOctC4.js";
import { a as alphanumericInputs, i as alphaInputs, l as numericInputs, s as makeMask, t as MaskedInput } from "./MaskedInput-_dYxgb7_.js";
import { i as mapJpAddressSummaryNewSummary, n as toFullWidth, t as mapJpAddressSchemaToAddressLocalizations } from "./mapJpAddressSchemaToAddressLocalizations-Dzcl40cA.js";
import { a as mapAddressLabelsNewSummary, c as COUNTRIES_WITH_STATES_DATASET, n as getAddressSchemaLabelsByCountry, r as getKeyForField, t as getAddressSchemaForCountry } from "./utils-DNIZ6F6L.js";
import { i as isValidationError, n as isBusinessSelectionLegalArrangementError, o as processValidationErrors, s as isMaintenanceModeError } from "./validationError-COmWiy16.js";
import { a as createDocumentRequest, c as getDocuments, f as mergeProofOfOwnershipAttachments, l as getFileExtention, o as documentApiUtils, s as getDocument } from "./validate-DkjeS-zE.js";
import { r as formatObject } from "./utils-DdHbAadK.js";
import { a as getFieldsWithExistingData, n as TaxInformationField, r as MemoizedDocumentUpload, t as TAX_INFORMATION_FIELD } from "./TaxInformationField-DXH6WfO9.js";
import { a as isJapanLocalizationEnabled } from "./Individual.rules-Cc2Uigav.js";
import { t as uppercase } from "./uppercase-DvjwUM0n.js";
import { a as validateNotEmptyOnBlur, n as validateJaKanaLegalCompanyName, o as validatePatternOnBlur, t as validateJaHaniLegalCompanyName } from "./patternValidators-DFve5Dzt.js";
import { A as taxInformationDefaultFieldMetadata, C as getTaxIdNumberOptions, O as getTaxInformationPlaceholderText, _ as COUNTRIES_WITH_POSSIBLE_TAX_EXEMPTION_FOR_SOLE_PROPS, b as REGISTRATION_NUMBER_EXEMPTION_RULES, c as COUNTRIES_THAT_DO_NOT_USE_TAX_ID_FOR_SOLE_PROP, d as COUNTRIES_THAT_USE_TAX_ID_INSTEAD_OF_VAT, g as COUNTRIES_WITH_POSSIBLE_TAX_EXEMPTION_FOR_COMPANIES, h as COUNTRIES_WITH_POSSIBLE_REGISTRATION_EXEMPTIONS_FOR_SOLE_PROPS, i as COUNTRIES_REQUIRING_E_INVOICING_CODE, k as taxInformationDefaultFieldConfig, l as COUNTRIES_THAT_REQUIRE_DATE_OF_INCORPORATION, m as COUNTRIES_WITH_OPTIONAL_REGISTRATION_NUMBER_SOLE_PROPS, o as COUNTRIES_THAT_DONT_REQUIRE_COMPANY_REGISTRATION, p as COUNTRIES_WITH_OPTIONAL_REGISTRATION_NUMBER, s as COUNTRIES_THAT_DONT_REQUIRE_SOLE_PROP_REGISTRATION, u as COUNTRIES_THAT_USES_UEN_OR_GST, v as COUNTRIES_WITH_POSSIBLE_TRUSTEE_TAXID_ABSENT_V4, w as getValidCompanyTypesForTaxIdNumberType, x as TAX_ID_REQUIRED_COUNTRIES_ORGANIZATION, y as COUNTRY_OF_GOVERNING_LAW_POSSIBLE } from "./utils-C9vhUXDJ.js";
import { t as resolveFieldMetadata } from "./fieldConfigurations-CZCFghnK.js";
import { t as Field } from "./Field-DoXLi6EY.js";
import { t as TileGroup } from "./TileGroup-DitwS4Ud.js";
import { t as LandingLayout } from "./LandingLayout-CUAkXrpL.js";
import { n as useDebouncedCallback } from "./debouncedInputEvent-Fwwp_K_-.js";
import { t as Checkbox } from "./Checkbox-D7BRIoQL.js";
import { n as convertFullToHalf } from "./TextArea-CT04Dg1N.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, t as COUNTRY_FIELD } from "./CountryField-D-Q958WF.js";
import { t as RadioGroup } from "./RadioGroup-qV8mGGwm.js";
import { t as createFormRules } from "./form-rules-CUUQGacJ.js";
import { t as isEmpty$1 } from "./isEmpty-BVlBH98t.js";
import { t as DataConflictsModal } from "./DataConflictsModal-DXsYUQRX.js";
import { n as mapApiScriptLocalizationToSchemaFields, r as mapSchemaFieldsToApiScriptLocalization, t as mapAddressLocalizationToJpAddressSchema } from "./mapAddressLocalizationToJpAddressSchema-CBeBTFmC.js";
import { t as currencyByCountry } from "./types-QSnyOf8p.js";
import { t as Divider } from "./Divider-BENvVRnz.js";
import { t as DetailViewLayout } from "./DetailViewLayout-DNCGEd7b.js";
import { a as LegalFormField, c as getNestedTrustedFields, i as InputCurrency, l as isDateOlderThanAYear, n as Currency, o as mapFinancialReportsToFinancialInformation, r as InputNumber, s as mapFinancialInformationToFinancialReport, t as CURRENCY_FIELD, u as mapAddressData } from "./Currency-vBXSDU5b.js";
import { n as SummarySection, t as NewSummary } from "./NewSummary-FJiQCTkv.js";
import { t as useTaskStatus } from "./useTaskStatus-wrAxqtIR.js";
import { t as ListItem } from "./ListItem-V4x0raZw.js";
import { a as getValidCompanyTypesForRegistrationNumberType, c as getRegistrationNumberHelperText, i as getCompanyRegistrationNumberOptions, l as registrationNumberDefaultFieldConfig, n as getDefaultRegistrationNumberType, r as inferCompanyRegistrationNumberType, s as exemptFromRegistrationNumberDefaultFieldMetadata, u as registrationNumberDefaultFieldMetadata } from "./CompanyRegistrationNumberTypeSelector-CEyBgEhu.js";
import { n as useCreateBusinessLine, r as useIndustryCodes, t as useUpdateBusinessLine } from "./useUpdateBusinessLines-Cncate8L.js";
import { n as formatCurrency } from "./formatCurrency-Cq3WFpdZ.js";
import { S as DBA_NAME_FIELD, _ as defaultFieldMetadata$1, a as isRegistrationNumberAbsentStateV4Scenario, b as doingBusinessAsFieldMetadata, c as BusinessRegistrationNumberField, g as defaultFieldConfig$1, h as getDefaultVatNumberType, i as isRegistrationExemptionAllowed, l as MemoizedConstitutionalDocument, m as VatNumberField, n as getCountryOfGoverningLaw, o as isUsingCompanySearch, p as VAT_NUMBER_FIELD, r as isFinancialInformationRequired, s as BUSINESS_REGISTRATION_NUMBER_FIELD, t as countryToTaxInfoTypeMap, u as registrationAddressFields, v as vatAbsenceReasonMetadata, x as DBANameField, y as doingBusinessAsAbsentFieldMetadata } from "./utils-BzBvc-hS.js";
import { f as industryCodeFieldMetadata, l as IndustryCodeField, t as INDUSTRY_CODE_FIELD } from "./constants-D91Cv1L9.js";
import { a as defaultFieldMetadata$2, i as defaultFieldConfigV4, o as defaultFieldMetadataV4, r as defaultFieldConfig$2, s as getLegalCompanyNameGuidanceText, t as LEGAL_COMPANY_NAME_FIELD } from "./LegalCompanyNameField-aMxj3FHy.js";
import { s as organizationTypesToSkipCompanyStructureForm } from "./utils-QZkZBg_Z.js";
import { Suspense, lazy } from "preact/compat";
import { useCallback as useCallback$1, useContext as useContext$1, useEffect as useEffect$1, useMemo as useMemo$1, useRef as useRef$1, useState as useState$1 } from "preact/hooks";
import cx from "classnames";
import { Fragment as Fragment$1, jsx, jsxs } from "preact/jsx-runtime";
import { createModel, signal, useModel, useSignal } from "@preact/signals";
import { queryOptions, skipToken, useMutation, useQuery, useQueryClient } from "@tanstack/preact-query";
import { createContext as createContext$1 } from "preact";
import { Show } from "@preact/signals/utils";
//#region src/components/Shared/fields/DateOfIncorporationField/DateOfIncorporationField.tsx
var DATE_OF_INCORPORATION_FIELD = ["dateOfIncorporation"];
function DateOfIncorporationField({ data, valid, errors, placeholder, readonly, handleChangeFor }) {
const { t } = useTranslation("common");
return /* @__PURE__ */ jsx(Field, {
name: "dateOfIncorporation",
label: t(($) => $["dateOfIncorporation"]),
errorMessage: errors.dateOfIncorporation,
isValid: valid.dateOfIncorporation,
children: (childProps) => /* @__PURE__ */ jsx(InputDate, {
...childProps,
"aria-required": true,
"aria-invalid": !valid.dateOfIncorporation,
name: "dateOfIncorporation",
value: data.dateOfIncorporation,
placeholder,
readonly,
onInput: handleChangeFor("dateOfIncorporation", "input"),
onBlur: handleChangeFor("dateOfIncorporation", "blur"),
max: formatDateObj(/* @__PURE__ */ new Date()),
min: formatDateObj(new Date(1900, 0, 1))
})
});
}
//#endregion
//#region src/components/Shared/fields/DateOfIncorporationField/fieldConfig.ts
var validateDateOfIncorporation = (dateOfIncorporation) => {
if (!dateOfIncorporation) return false;
const date = new Date(dateOfIncorporation);
return date < /* @__PURE__ */ new Date() && date > new Date(1900, 0, 1);
};
var dateOfIncorporationFieldMetadata = { validators: [validateNotEmptyOnBlur, {
modes: ["blur"],
validate: validateDateOfIncorporation,
errorMessage: "invalidDateOfIncorporation"
}] };
//#endregion
//#region src/components/Shared/fields/EInvoicingCodeField/EInvoicingCodeField.tsx
var EINVOICING_CODE_FIELD = ["eInvoicingCode"];
function EInvoicingCodeField({ data, valid, errors, labels, readonly, mask, shouldValidate, handleChangeFor }) {
const { t } = useTranslation("common");
const [noInvoicingCode, setNoInvoicingCode] = useState$1(false);
const handleNoInvoicingCode = () => {
setNoInvoicingCode(!noInvoicingCode);
handleChangeFor("eInvoicingCode")("0000000");
};
return /* @__PURE__ */ jsxs("div", {
className: "adyen-kyc-field",
children: [/* @__PURE__ */ jsx(MaskedInput, {
name: "eInvoicingCode",
type: "text",
label: labels.eInvoicingCode ?? "",
formatGuidance: t(($) => $["the7CharacterIdentifierAssignedToThis"], { example: "MP10YNU" }),
errorMessage: errors.eInvoicingCode,
isValid: valid.eInvoicingCode ?? false,
value: data.eInvoicingCode ?? "",
readonly: readonly || noInvoicingCode,
shouldValidate,
onInput: handleChangeFor("eInvoicingCode", "input"),
onBlur: handleChangeFor("eInvoicingCode", "blur"),
disabled: noInvoicingCode,
"aria-required": true,
"aria-invalid": !valid.eInvoicingCode,
...mask
}), /* @__PURE__ */ jsx(Field, {
name: "noEInvoicingCode",
children: (childProps) => /* @__PURE__ */ jsx(Checkbox, {
...childProps,
name: "noEInvoicingCode",
"aria-required": false,
"aria-invalid": false,
label: t(($) => $["thisCompanyDoesntHaveAnSDI"]),
checked: noInvoicingCode,
onChange: handleNoInvoicingCode
})
})]
});
}
//#endregion
//#region src/components/Shared/fields/EInvoicingCodeField/fieldConfig.ts
var eInvoicingCodeFieldMetadata = {
validators: validatePatternOnBlur(/^[A-Z0-9]{7}$/),
mask: {
mask: makeMask(...alphanumericInputs(16)),
transformOnType: uppercase
}
};
var legalEntityIdentifierFieldMetadata = {
validators: [{
modes: ["blur"],
validate: (val) => {
const isValidLength = val ? val.length === 20 : false;
const hasLettersAndNumbers = val ? /[a-zA-Z]/.test(val) && /[0-9]/.test(val) : false;
return isValidLength && hasLettersAndNumbers;
},
errorMessage: {
key: "enterNCharactersWithAMixForExample",
values: {
numChars: "20",
example: "529900T8BM49AURSDO55"
}
}
}],
mask: {
mask: makeMask(...alphanumericInputs(20)),
transformOnType: uppercase
}
};
//#endregion
//#region src/components/Shared/fields/LegalEntityIdentifierField/LegalEntityIdentifierField.tsx
var LEGAL_ENTITY_IDENTIFIER_FIELD = ["legalEntityIdentifier", "exemptedFromLegalEntityIdentifier"];
function LegalEntityIdentifierField({ data, valid, errors, handleChangeFor, shouldValidate, canExempt = true }) {
const { t } = useTranslation("common");
const placeholder = data.exemptedFromLegalEntityIdentifier ? "" : "529900T8BM49AURSDO55";
const isExempted = Boolean(data.exemptedFromLegalEntityIdentifier);
const handleExemptedChange = (isChecked) => {
handleChangeFor("exemptedFromLegalEntityIdentifier", "blur")(isChecked);
if (isChecked) handleChangeFor("legalEntityIdentifier", "input")("");
};
return /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx(MaskedInput, {
type: "text",
name: "legalEntityIdentifier",
label: t(($) => $["legalEntityIdentifier"]),
onInput: handleChangeFor("legalEntityIdentifier", "input"),
onBlur: handleChangeFor("legalEntityIdentifier", "blur"),
value: data.legalEntityIdentifier ?? "",
isValid: Boolean(valid?.legalEntityIdentifier),
errorMessage: errors.legalEntityIdentifier,
disabled: isExempted,
helper: /* @__PURE__ */ jsxs(Typography, {
variant: "caption",
color: "secondary",
children: [
t(($) => $["aUniqueIdentifierForGlobalFinancialReporting"]),
" ",
/* @__PURE__ */ jsx(Link, {
href: "https://search.gleif.org/#/search/",
external: true,
inline: true,
children: t(($) => $["lookUpYourLEI"])
})
]
}),
helperPosition: "below",
persistHelper: true,
shouldValidate,
placeholder,
mask: legalEntityIdentifierFieldMetadata.mask?.mask,
transformOnType: legalEntityIdentifierFieldMetadata.mask?.transformOnType
}), canExempt && /* @__PURE__ */ jsx(Field, {
name: "exemptedFromLegalEntityIdentifier",
children: (childProps) => /* @__PURE__ */ jsx(Checkbox, {
...childProps,
name: "exemptedFromLegalEntityIdentifier",
value: "exemptedFromLegalEntityIdentifier",
checked: isExempted,
label: t(($) => $["iDontHaveAnLEI"]),
onChange: handleExemptedChange
})
})] });
}
//#endregion
//#region src/components/Shared/fields/StockExchangeMICField/fieldConfig.ts
var stockExchangeMICFieldMetadata = {
validators: [validateNotEmptyOnBlur, validatePatternOnBlur(/^[a-zA-Z0-9]{4}$/)],
mask: {
mask: makeMask(...alphanumericInputs(4)),
transformOnType: uppercase
}
};
//#endregion
//#region src/components/Shared/fields/StockExchangeMICField/StockExchangeMICField.tsx
var STOCK_EXCHANGE_MIC_FIELD = ["stockExchangeMIC"];
function StockExchangeMICField({ data, valid, errors, readonly, mask, shouldValidate, handleChangeFor }) {
const { t } = useTranslation("common");
return /* @__PURE__ */ jsx(MaskedInput, {
name: "stockExchangeMIC",
type: "text",
label: t(($) => $["stockExchangeMIC"]),
formatGuidance: t(($) => $["enterNCharactersForExample"], {
numChars: "4",
example: "XNAS"
}),
...mask,
errorMessage: errors.stockExchangeMIC,
isValid: valid.stockExchangeMIC ?? false,
value: data.stockExchangeMIC ?? "",
readonly,
shouldValidate,
onInput: handleChangeFor("stockExchangeMIC", "input"),
onBlur: handleChangeFor("stockExchangeMIC", "blur"),
"aria-required": true,
"aria-invalid": !valid.stockExchangeMIC
});
}
//#endregion
//#region src/components/Shared/fields/StockISINField/fieldConfig.ts
var stockISINFieldMetadata = {
validators: [validateNotEmptyOnBlur, {
modes: ["blur"],
validate: (value) => !!value && isISIN(value)
}],
mask: {
mask: makeMask(...alphaInputs(2), ...alphanumericInputs(9), ...numericInputs(1)),
transformOnType: uppercase
}
};
//#endregion
//#region src/components/Shared/fields/StockISINField/StockISINField.tsx
var STOCK_ISIN_FIELD = ["stockISIN"];
function StockISINField({ data, valid, errors, readonly, mask, shouldValidate, handleChangeFor }) {
const { t } = useTranslation("common");
return /* @__PURE__ */ jsx(MaskedInput, {
name: "stockISIN",
type: "text",
label: t(($) => $["stockISIN"]),
formatGuidance: t(($) => $["validationPleaseEnterAValidStockISIN"], { example: "NL0012969182" }),
...mask,
errorMessage: errors.stockISIN,
isValid: valid.stockISIN ?? false,
value: data.stockISIN ?? "",
readonly,
shouldValidate,
onInput: handleChangeFor("stockISIN", "input"),
onBlur: handleChangeFor("stockISIN", "blur"),
"aria-required": true,
"aria-invalid": !valid.stockISIN
});
}
//#endregion
//#region src/components/Shared/fields/StockTickerSymbol/fieldConfig.ts
var stockTickerSymbolFieldMetadata = {
validators: [validateNotEmptyOnBlur, validatePatternOnBlur(/^[A-Z\d]{1,5}$/)],
mask: {
mask: makeMask(...alphanumericInputs(1), ...alphanumericInputs(4)),
transformOnType: uppercase
}
};
//#endregion
//#region src/components/Shared/fields/StockTickerSymbol/StockTickerSymbolField.tsx
var STOCK_TICKER_SYMBOL_FIELD = ["stockTickerSymbol"];
function StockTickerSymbolField({ data, valid, errors, readonly, mask, shouldValidate, handleChangeFor }) {
const { t } = useTranslation("common");
return /* @__PURE__ */ jsx(MaskedInput, {
name: "stockTickerSymbol",
type: "text",
label: t(($) => $["stockTickerSymbol"]),
formatGuidance: t(($) => $["enterAMaximumOfNCharactersForExample"], {
maxChars: "5",
example: "ADYEN"
}),
...mask,
errorMessage: errors.stockTickerSymbol,
isValid: valid.stockTickerSymbol ?? false,
value: data.stockTickerSymbol ?? "",
readonly,
shouldValidate,
onInput: handleChangeFor("stockTickerSymbol", "input"),
onBlur: handleChangeFor("stockTickerSymbol", "blur"),
"aria-required": true,
"aria-invalid": !valid.stockTickerSymbol
});
}
//#endregion
//#region src/utils/useDebouncedState.ts
/**
* Like {@link useState}, but waits for the given amount of time before applying *only* the most recent update.
*
* @param wait the time to wait, in milliseconds
* @param initialState (optional) the default value
*/
function useDebouncedState(wait, initialState) {
const [state, _setState] = useState$1(initialState);
return [state, useDebouncedCallback(_setState, wait)];
}
//#endregion
//#region src/components/EFP/fields/LegalFormField/types.ts
var LEGAL_FORM_FIELDS = ["legalForm", "legalFormLabel"];
var legalFormFieldMetadata = {
label: "legalForm",
validators: [validateNotEmptyOnBlur]
};
//#endregion
//#region src/api/companyDataSet/useClearCompanyData.ts
var clearCompanyData = async (legalEntityId, baseUrl) => {
return httpPost({
baseUrl,
path: `legalEntities/${legalEntityId}/companyDataset/clearCompanyData`
});
};
var useClearCompanyData = (options) => {
const { rootLegalEntityId, baseUrl } = useApiContext();
const logger = createLogger();
return useMutation({
mutationFn: () => {
return clearCompanyData(rootLegalEntityId.value, baseUrl.value);
},
retry: 0,
onError: (e) => logger.error(e),
...options
});
};
//#endregion
//#region src/components/Shared/fields/LocalizedLegalCompanyNameField/types.ts
var JAPANESE_LEGAL_COMPANY_NAME_FIELDS = ["jaHaniLegalCompanyName", "jaKanaLegalCompanyName"];
//#endregion
//#region src/hooks/useLegalCompanyNameField/useLegalCompanyNameField.ts
function useLegalCompanyNameField({ data, valid, errors, fieldProblems, country, formUtils, handleChange, t }) {
const { isFeatureEnabled } = useToggleContext();
const fieldKeys = getFieldKeys(isFeatureEnabled, country);
const labels = formUtils.getFieldLabels(fieldKeys);
const fieldErrors = formUtils.getFieldErrors(errors, fieldProblems, fieldKeys);
const fieldsTransformInput = {
jaHaniLegalCompanyName: toFullWidth,
jaKanaLegalCompanyName: toFullWidth,
legalCompanyName: convertFullToHalf
};
const fieldsTransformMode = {
jaHaniLegalCompanyName: "blur",
jaKanaLegalCompanyName: "blur",
legalCompanyName: "blur"
};
return fieldKeys.map((fieldKey) => {
if (formUtils.isRequiredField(fieldKey) || formUtils.isOptionalField(fieldKey)) {
const guidance = fieldKey === "legalCompanyName" ? getLegalCompanyNameGuidanceText(t, { country }) : void 0;
return {
name: fieldKey,
value: data[fieldKey] ?? "",
readonly: formUtils.isReadOnly(fieldKey),
onInput: handleChange(fieldKey, "input"),
onBlur: handleChange(fieldKey, "blur"),
isValid: valid[fieldKey],
errorMessage: fieldErrors[fieldKey],
label: labels[fieldKey],
guidance,
onKeyDown: handleKeyDown,
transformInput: fieldsTransformInput[fieldKey],
transformMode: fieldsTransformMode[fieldKey]
};
}
});
}
var getFieldKeys = (isFeatureEnabled = () => false, country) => {
if (isJapanLocalizationEnabled(isFeatureEnabled, country)) return [...JAPANESE_LEGAL_COMPANY_NAME_FIELDS, ...LEGAL_COMPANY_NAME_FIELD];
return LEGAL_COMPANY_NAME_FIELD;
};
var handleKeyDown = (e) => {
if (e.key === KEYBOARD_KEYS.enter) e.preventDefault();
};
//#endregion
//#region src/components/Shared/fields/CountryOfGoverningLawField/CountryOfGoverningLawField.tsx
var COUNTRY_OF_GOVERNING_LAW_FIELD = ["countryOfGoverningLaw"];
function CountryOfGoverningLawField({ data, valid, errors, labels, readonly, handleChangeFor, allowedCountries, country }) {
const { t } = useTranslation("common");
useEffect$1(() => {
if (country === CountryCodes.UnitedKingdom && !data.countryOfGoverningLaw) {
const countryOfGoverningLawEvent = { target: {
name: "countryOfGoverningLaw",
value: CountryCodes.UnitedKingdom
} };
handleChangeFor("countryOfGoverningLaw")(countryOfGoverningLawEvent);
}
}, [country]);
return /* @__PURE__ */ jsx(CountryField, {
name: "countryOfGoverningLaw",
data: { country: data.countryOfGoverningLaw },
valid: { country: valid.countryOfGoverningLaw },
errors: { country: errors.countryOfGoverningLaw },
labels: { country: labels?.countryOfGoverningLaw || t(($) => $["countryOfGoverningLaw"]) },
readonly,
allowedCountries,
handleChangeFor: () => handleChangeFor("countryOfGoverningLaw")
});
}
var localizedLegalCompanyNameFieldConfig = {
jaHaniLegalCompanyName: {
config: {
label: "jaHaniLegalCompanyName",
validators: validateJaHaniLegalCompanyName
},
metadata: { label: "jaHaniLegalCompanyName" }
},
jaKanaLegalCompanyName: {
config: {
label: "jaKanaLegalCompanyName",
validators: validateJaKanaLegalCompanyName
},
metadata: { label: "jaKanaLegalCompanyName" }
}
};
var BasicInformation_module_default = {
"basic-information": "_basic-information_1rbd4_1",
basicInformation: "_basic-information_1rbd4_1"
};
//#endregion
//#region src/components/Business/forms/BasicInformation/BasicInformation.tsx
var BASIC_INFORMATION_FIELDS = [
...COUNTRY_FIELD,
...LEGAL_COMPANY_NAME_FIELD,
"jaHaniLegalCompanyName",
"jaKanaLegalCompanyName",
...TAX_INFORMATION_FIELD,
...STATE_FIELD,
...BUSINESS_REGISTRATION_NUMBER_FIELD,
...COUNTRY_OF_GOVERNING_LAW_FIELD
];
var FormDescription = ({ description, t }) => {
return /* @__PURE__ */ jsxs("div", { children: [
description,
" ",
/* @__PURE__ */ jsx(Link, {
href: "https://www.adyen.com/privacy-policy",
external: true,
children: t(($) => $["privacyStatement"])
})
] });
};
var EMPTY_OBJ$5 = {};
function BasicInformation({ id, country, shouldValidate, fieldValidationErrors = EMPTY_OBJ$5, formVerificationErrors = EMPTY_OBJ$5, isTopLevelEntity, disableCountry, companyType, taskType }) {
const { t } = useTranslation(["common", "business"]);
const { t: businessT } = useTranslation("business");
const { isSettingEnabled } = useSettingsContext();
const { isFeatureEnabled } = useToggleContext();
const { form } = useFormContext();
const allowedCountries = useAllowedCountries();
const isAllowedEditPrefilledCountry = isSettingEnabled(SettingNames.AllowPrefilledCountryEdit);
const state = form.data.basicInformation?.stateOrProvince;
const currentCountryTaxInformation = form.data.basicInformation?.taxInformation?.find((tax) => tax.country === country);
const handleChangeFor = useCallback$1((fieldName, mode) => form.handleChangeFor("basicInformation", fieldName, mode), [form]);
const formUtils = useMemo$1(() => {
const initialProps = {
data: form.data.basicInformation ?? {},
fieldValidationErrors,
formVerificationErrors,
allFields: form.allFields?.basicInformation ?? [],
requiredFields: form.requiredFields?.basicInformation ?? [],
optionalFields: form.optionalFields?.basicInformation ?? [],
trustedFields: form.trustedFields?.basicInformation ?? [],
obscuredFields: form.obscuredFields?.basicInformation ?? [],
errors: form.errors.basicInformation ?? {},
valid: form.valid.basicInformation ?? {},
handleFieldChange: handleChangeFor
};
const formUtilProps = initialProps.allFields?.reduce((acc, field) => {
switch (field) {
case "country": return acc;
case "legalCompanyName": return mergeFieldMetadataIntoProps(field, resolveFieldMetadata(isFeatureEnabled("StrictNameAndAddressValidationV4") ? defaultFieldConfigV4[country] : defaultFieldConfig$2[country], {}, isFeatureEnabled("StrictNameAndAddressValidationV4") ? defaultFieldMetadataV4 : defaultFieldMetadata$2), acc);
case "countryOfGoverningLaw": return acc;
case "stateOrProvince": return mergeFieldMetadataIntoProps(field, resolveFieldMetadata(defaultFieldConfig[country], { isBusiness: true }, defaultFieldMetadata), acc);
case "taxInformation": return mergeFieldMetadataIntoProps(field, resolveFieldMetadata(taxInformationDefaultFieldConfig[country], {
taxIdNumberType: currentCountryTaxInformation?.type,
companyType
}, taxInformationDefaultFieldMetadata), acc);
case "jaHaniLegalCompanyName": return mergeFieldMetadataIntoProps(field, resolveFieldMetadata(localizedLegalCompanyNameFieldConfig.jaHaniLegalCompanyName.config, {}, localizedLegalCompanyNameFieldConfig.jaHaniLegalCompanyName.metadata), acc);
case "jaKanaLegalCompanyName": return mergeFieldMetadataIntoProps(field, resolveFieldMetadata(localizedLegalCompanyNameFieldConfig.jaKanaLegalCompanyName.config, {}, localizedLegalCompanyNameFieldConfig.jaKanaLegalCompanyName.metadata), acc);
default: return acc;
}
}, initialProps);
return createFormUtils(formUtilProps ?? initialProps, t);
}, [
companyType,
country,
currentCountryTaxInformation?.type,
form.allFields?.basicInformation,
form.data.basicInformation,
form.errors.basicInformation,
form.obscuredFields?.basicInformation,
form.optionalFields?.basicInformation,
form.requiredFields?.basicInformation,
form.trustedFields?.basicInformation,
form.valid.basicInformation,
handleChangeFor,
isFeatureEnabled,
t,
fieldValidationErrors,
formVerificationErrors
]);
const showField = (fieldKeys) => fieldKeys.some((field) => {
switch (field) {
case "registrationNumberType":
case "registrationNumber":
if (isUsingCompanySearch(country, taskType)) return form.data.basicInformation?.country === "US" ? (formUtils.isRequiredField(field) || formUtils.isOptionalField(field)) && form.data.basicInformation?.stateOrProvince : formUtils.isRequiredField(field) || formUtils.isOptionalField(field);
return formUtils.isRequiredField(field) || formUtils.isOptionalField(field);
default: return formUtils.isRequiredField(field) || formUtils.isOptionalField(field);
}
});
const legalCompanyNameFields = useLegalCompanyNameField({
data: form.data.basicInformation ?? {},
valid: form.valid.basicInformation ?? {},
errors: form.errors.basicInformation ?? {},
fieldProblems: form.fieldProblems.basicInformation ?? {},
country,
formUtils,
handleChange: handleChangeFor,
t: businessT
});
return /* @__PURE__ */ jsxs("form", {
id,
className: BasicInformation_module_default.basicInformation,
children: [
/* @__PURE__ */ jsx(Header, {
title: t(($) => $["basicInformationFormHeading"], { ns: "business" }),
children: /* @__PURE__ */ jsx(FormDescription, {
slot: "description",
description: t(($) => $["basicInformationFormDescription"], { ns: "business" }),
t
})
}),
/* @__PURE__ */ jsx(ErrorPanel, {
id: "ariaErrorField",
verificationErrors: formVerificationErrors,
validationErrors: fieldValidationErrors,
formUtils
}),
legalCompanyNameFields.map((field) => /* @__PURE__ */ jsx(Field, {
name: field?.name ?? "",
label: field?.label,
formatGuidance: field?.guidance,
errorMessage: field?.errorMessage,
isValid: Boolean(field?.isValid),
children: (childProps) => /* @__PURE__ */ jsx(InputText, {
...childProps,
"aria-required": true,
"aria-invalid": !field?.isValid,
name: field?.name,
value: field?.value,
readonly: field?.readonly,
onInput: field ? field.onInput : () => {},
transformInput: field?.transformInput,
transformMode: field?.transformMode,
onBlur: field?.onBlur,
onKeyDown: field?.onKeyDown
})
}, field?.name)),
/* @__PURE__ */ jsxs("fieldset", { children: [
/* @__PURE__ */ jsx(CountryField, {
data: formUtils.getFieldData(form.data.basicInformation ?? {}, COUNTRY_FIELD),
valid: formUtils.getFieldValid(form.valid.basicInformation ?? {}, COUNTRY_FIELD),
errors: formUtils.getFieldErrors(form.errors.basicInformation ?? {}, fieldValidationErrors, COUNTRY_FIELD),
labels: formUtils.getFieldLabels(COUNTRY_FIELD, { country: "countryRegionOfEstablishment" }),
readonly: formUtils.isReadOnly("country") || !isAllowedEditPrefilledCountry || Boolean(disableCountry),
handleChangeFor,
allowedCountries: isTopLevelEntity ? allowedCountries : void 0
}),
COUNTRY_OF_GOVERNING_LAW_POSSIBLE.includes(country) && showField(COUNTRY_OF_GOVERNING_LAW_FIELD) && /* @__PURE__ */ jsx(CountryOfGoverningLawField, {
data: formUtils.getFieldData(form.data.basicInformation ?? {}, COUNTRY_OF_GOVERNING_LAW_FIELD),
country,
valid: formUtils.getFieldValid(form.valid.basicInformation ?? {}, COUNTRY_OF_GOVERNING_LAW_FIELD),
errors: formUtils.getFieldErrors(form.errors.basicInformation ?? {}, fieldValidationErrors, COUNTRY_OF_GOVERNING_LAW_FIELD),
labels: formUtils.getFieldLabels(COUNTRY_OF_GOVERNING_LAW_FIELD),
readonly: false,
allowedCountries: isTopLevelEntity ? allowedCountries : void 0,
handleChangeFor
}),
showField(STATE_FIELD) && /* @__PURE__ */ jsx(StateField, {
data: formUtils.getFieldData(form.data.basicInformation ?? {}, STATE_FIELD),
valid: formUtils.getFieldValid(form.valid.basicInformation ?? {}, STATE_FIELD),
errors: formUtils.getFieldErrors(form.errors.basicInformation ?? {}, fieldValidationErrors, STATE_FIELD),
labels: formUtils.getFieldLabels(STATE_FIELD),
readonly: formUtils.isReadOnly("stateOrProvince"),
handleChangeFor,
selectedCountry: country
}),
showField(TAX_INFORMATION_FIELD) && /* @__PURE__ */ jsx(TaxInformationField, {
data: formUtils.getFieldData(form.data.basicInformation ?? {}, TAX_INFORMATION_FIELD),
valid: formUtils.getFieldValid(form.valid.basicInformation ?? {}, TAX_INFORMATION_FIELD),
errors: formUtils.getFieldErrors(form.errors.basicInformation ?? {}, fieldValidationErrors, TAX_INFORMATION_FIELD),
labels: formUtils.getFieldLabels(TAX_INFORMATION_FIELD, { exemptedFromTax: "iDontHaveATaxId" }),
mask: formUtils.getMask("taxInformation"),
placeholder: getTaxInformationPlaceholderText({
country,
companyType,
taxIdNumberType: currentCountryTaxInformation?.type
}),
readonly: formUtils.isReadOnly("taxInformation"),
shouldValidate,
handleChangeFor,
canExempt: showField(["exemptedFromTax"]),
registrationNumber: form.data.basicInformation?.registrationNumber,
country,
entityType: companyType,
defaultData: form.defaultData?.basicInformation?.taxInformation
}),
showField(BUSINESS_REGISTRATION_NUMBER_FIELD) && /* @__PURE__ */ jsx(BusinessRegistrationNumberField, {
data: formUtils.getFieldData(form.data.basicInformation ?? {}, BUSINESS_REGISTRATION_NUMBER_FIELD),
valid: formUtils.getFieldValid(form.valid.basicInformation ?? {}, BUSINESS_REGISTRATION_NUMBER_FIELD),
errors: formUtils.getFieldErrors(form.errors.basicInformation ?? {}, fieldValidationErrors, BUSINESS_REGISTRATION_NUMBER_FIELD),
helperText: getRegistrationNumberHelperText(businessT, {
country,
companyType
}),
readonly: formUtils.isReadOnly("registrationNumber"),
optional: formUtils.isOptionalField("registrationNumber"),
shouldValidate,
handleChangeFor,
country,
state,
canExempt: showField(["exemptedFromRegistrationNumber"]),
companyType
})
] })
]
});
}
//#endregion
//#region src/utils/performance.ts
/**
* Start timing an operation
* @param key - Unique identifier for the operation
* @param timings - Map to store timing information
* @returns The start timestamp
*/
var startTiming = (key, timings = /* @__PURE__ */ new Map()) => {
const startTime = Date.now();
timings.set(key, { startTime });
return startTime;
};
/**
* End timing an operation and calculate duration
* @param key - Unique identifier for the operation
* @param timings - Map containing timing information
* @returns The duration in milliseconds, or undefined if timing wasn't started
*/
var endTiming = (key, timings) => {
const timing = timings.get(key);
if (!timing || timing.endTime) return;
const endTime = Date.now();
const duration = endTime - timing.startTime;
const updatedTiming = {
...timing,
endTime,
duration
};
timings.set(key, updatedTiming);
return duration;
};
/**
* Execute a function with automatic timing
* @param key - Unique identifier for the operation
* @param fn - Function to execute
* @param analytics - UserEvents instance for logging
* @param timings - Optional map to store timing information
* @returns Promise that resolves with the function result and timing duration
*/
var withTiming = async (key, fn, analytics, timings = /* @__PURE__ */ new Map()) => {
startTiming(key, timings);
try {
const result = await fn();
const duration = endTiming(key, timings) || 0;
analytics.addEvent("Performance", {
actionType: "resolve",
actionLevel: "page",
label: key,
additionalData: { duration }
});
return {
result,
duration
};
} catch (error) {
const duration = endTiming(key, timings) || 0;
analytics.addEvent("Performance", {
actionType: "reject",
actionLevel: "page",
label: key,
additionalData: { duration }
});
throw error;
}
};
/**
* Convenience function to track async operation timing
* @param key - Unique identifier for the operation
* @param fn - Function to execute
* @param analytics - UserEvents instance for logging
* @returns Promise that resolves with the function result
*/
var trackPerformance = async (key, fn, analytics) => {
const { result } = await withTiming(key, fn, analytics);
return result;
};
//#endregion
//#region src/api/companySearch/useCompanySearch.ts
/**
* Supports querying declaratively (`useCompanySearch` hook) and imperatively
* (`queryClient.fetchQuery()`) with the same config, ensuring no deviation occurs
* between the two types.
*/
var companySearchQueryOptions = (rootLegalEntityId, baseUrl, data, userEvents, options) => {
return queryOptions({
queryKey: ["companySearch", data],
queryFn: () => trackPerformance("companySearchNetworkTime", () => handleCompanySearch(rootLegalEntityId, baseUrl, data), userEvents),
retry: 0,
meta: {
onSuccess: (data) => {
userEvents.addPageEvent("Success", {
actionType: "resolve",
returnValue: "companySearch",
additionalData: {
numberOfResults: data.results.length,
..."provider" in data && { provider: data.provider }
}
});
},
onError: () => {
userEvents.addPageEvent("Encountered error", {
actionType: "resolve",
returnValue: "companySearch",
returnType: "backend"
});
}
},
...options
});
};
var useCompanySearch = (data, options) => {
const { rootLegalEntityId, baseUrl } = useApiContext();
const userEvents = useAnalyticsContext();
return useQuery(companySearchQueryOptions(rootLegalEntityId.value, baseUrl.value, data, userEvents, options));
};
var handleCompanySearch = async (rootLegalEntityId, baseUrl, data) => {
return httpPost({
baseUrl,
path: `legalEntities/${rootLegalEntityId}/companySearch/search`
}, {
name: data.name,
country: data.country,
stateOrProvince: data.state,
...data.registrationNumber ? { registrationNumber: data.registrationNumber } : {},
resultSizeLimit: data.resultSizeLimit ?? 15
});
};
//#endregion
//#region src/api/companyDataSet/handleCompanyDataset.ts
var handleCompanyDataset = async (rootLegalEntityId, baseUrl, data) => {
return httpPost({
baseUrl,
path: `legalEntities/${rootLegalEntityId}/companyDataset/select`
}, data);
};
//#endregion
//#region src/api/tinVerification/useVerifyTin.ts
/**
* Supports querying declaratively (`useVerifyTin` hook) and imperatively
* (`queryClient.fetchQuery()`) with the same config, ensuring no deviation occurs
* between the two types.
*/
var verifyTinQueryOptions = (rootLegalEntityId, baseUrl, data, userEvents, options) => {
return queryOptions({
queryKey: ["verifyTin", data],
queryFn: data ? () => trackPerformance("verifyTinNetworkTime", () => verifyTin(rootLegalEntityId, baseUrl, data), userEvents) : skipToken,
retry: 0,
meta: {
onSuccess: (data) => {
if (data.matched === true) userEvents.addPageEvent("Success", {
actionType: "verify",
returnValue: "verifyTin",
returnType: "validation"
});
else userEvents.addPageEvent("Encountered error", {
actionType: "verify",
returnValue: "verifyTin",
returnType: "validation"
});
},
onError: () => {
userEvents.addPageEvent("Encountered error", {
actionType: "verify",
returnValue: "verifyTin",
returnType: "backend"
});
}
},
...options
});
};
var verifyTin = async (legalEntityId, baseUrl, data) => {
return httpPost({
baseUrl,
path: `legalEntities/${legalEntityId}/verifyTin`
}, data);
};
//#endregion
//#region src/api/companySelection/useCompanySelection.ts
var useCompanySelection = (options) => {
const { rootLegalEntityId, baseUrl } = useApiContext();
const userEvents = useAnalyticsContext();
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (data) => trackPerformance("companySelectionNetworkTime", () => handleCompanySelection(rootLegalEntityId.value, baseUrl.value, queryClient, data, userEvents), userEvents),
onSuccess: (data) => {
userEvents.addPageEvent("Success", {
actionType: "select",
returnValue: "companySelection",
returnType: "validation",
additionalData: { tinMatched: data.tinMatched === true }
});
},
onError: () => {
userEvents.addPageEvent("Encountered error", {
actionType: "select",
returnValue: "companySelection",
returnType: "backend"
});
},
retry: (count, error) => {
if ("errorCode" in error && typeof error.errorCode == "string") {
if (error.errorCode === "00_422") return false;
}
return count === 0;
},
...options
});
};
var handleCompanySelection = async (rootLegalEntityId, baseUrl, queryClient, data, userEvents) => {
switch (data.country) {
case CountryCodes.UnitedStates: {
const verifyTinQueryInput = {
name: data.name,
tin: data.tin
};
const [companyDatasetResult, tinMatchResult] = await Promise.allSettled([handleCompanyDataset(rootLegalEntityId, baseUrl, { id: data.id }), queryClient.fetchQuery(verifyTinQueryOptions(rootLegalEntityId, baseUrl, verifyTinQueryInput, userEvents))]);
if (companyDatasetResult.status === "rejected") throw companyDatasetResult;
return {
...companyDatasetResult.value,
tinMatched: tinMatchResult.status === "fulfilled" ? tinMatchResult.value.matched : false
};
}
default: {
const companyDatasetResult = await handleCompanyDataset(rootLegalEntityId, baseUrl, { id: data.id });
return {
...companyDatasetResult,
registrationNumberMatched: companyDatasetResult.registrationNumber ? data.registrationNumber === companyDatasetResult.registrationNumber : void 0
};
}
}
};
//#endregion
//#region src/components/Business/forms/BusinessSelection/BusinessInformationCard/BusinessInformationCard.tsx
function BusinessInformation({ fetching, selectedBusiness }) {
const { t } = useTranslation(["common", "business"]);
const items = useMemo$1(() => selectedBusiness ? entriesOf(selectedBusiness).reduce((acc, [key, value]) => {
switch (key) {
case "legalForm":
if (value) acc[0].details = value;
break;
case "name":
if (value) acc[1].details = value;
break;
case "registeredAddress":
case "principalPlaceOfBusinessAddress":
if (value && typeof value !== "string" && "fullAddress" in value) acc[2].details = value.fullAddress;
break;
default: break;
}
return acc;
}, [
{
term: t(($) => $["legalForm"], { ns: "common" }),
details: ""
},
{
term: t(($) => $["legalCompanyName"], { ns: "common" }),
details: ""
},
{
term: t(($) => $["address"], { ns: "common" }),
details: ""
}
]).filter((item) => !!item.details) : [], [selectedBusiness, t]);
if (fetching) return /* @__PURE__ */ jsx(Loader, { size: "large" });
return /* @__PURE__ */ jsx(StructuredList, { items });
}
function BusinessInformationCard({ result, isSelected, currentBusinessSelection, fetching, error, handleSelectBusiness, retryCompanySelection }) {
const { t } = useTranslation(["common", "business"]);
const isLegalArrangementError = error && isBusinessSelectionLegalArrangementError(error);
return /* @__PURE__ */ jsx(Card, {
selected: isSelected,
onClick: isSelected ? void 0 : handleSelectBusiness,
children: /* @__PURE__ */ jsxs(StackLayout, { children: [/* @__PURE__ */ jsx(ListItem, {
avatar: {
iconName: "company",
circle: true
},
title: result.name,
description: result.registrationNumber,
accessory: fetching && isSelected ? /* @__PURE__ */ jsx(Loader, { size: "medium" }) : null
}), isSelected && !fetching && !isLegalArrangementError && /* @__PURE__ */ jsx(StackLayout, { children: error ? /* @__PURE__ */ jsx(Alert, {
variant: "info",
type: "callToAction",
title: t(($) => $["businessDetailsFailedToLoad"], { ns: "business" }),
actions: /* @__PURE__ */ jsx(Button, {
testId: "reloadBusiness",
onClick: retryCompanySelection,
variant: "link",
children: t(($) => $["tryAgain"], { ns: "common" })
}),
testId: "failedToLoad"
}) : /* @__PURE__ */ jsx(Card, {
variant: "secondary",
padding: "large",
children: /* @__PURE__ */ jsx(BusinessInformation, {
fetching,
selectedBusiness: currentBusinessSelection
})
}) })] })
});
}
function CompanyNotListedCard({ isSelected, handleSelectBusiness, fetching }) {
const { t } = useTranslation(["business"]);
return /* @__PURE__ */ jsx(Card, {
selected: isSelected,
onClick: isSelected ? void 0 : handleSelectBusiness,
children: /* @__PURE__ */ jsx(ListItem, {
title: t(($) => $["myBusinessIsntHere"], { ns: "business" }),
accessory: fetching && isSelected ? /* @__PURE__ */ jsx(Loader, { size: "medium" }) : null
})
});
}
//#endregion
//#region src/components/Business/forms/BusinessSelection/BusinessSelection.tsx
var BUSINESS_SELECTION_FIELDS = ["selectedBusinessId"];
var EMPTY_OBJ$4 = {};
function BusinessSelection({ id, country, fieldValidationErrors = EMPTY_OBJ$4, formVerificationErrors = EMPTY_OBJ$4 }) {
const { t } = useTranslation(["common", "business"]);
const { baseUrl, rootLegalEntityId } = useApiContext();
const { form } = useFormContext();
const queryClient = useQueryClient();
const userEvents = useAnalyticsContext();
const logger = createLogger();
const companySearchStateModel = useContext$1(CompanySearchStateContext);
const { data: companySearchResponse, isLoading: searching } = useCompanySearch({
name: companySearchStateModel.companySearchName.value ?? "",
country,
state: form.data.basicInformation?.stateOrProvince,
registrationNumber: form.data.basicInformation?.registrationNumber
});
const { data: selectData, error: selectError, mutateAsync: selectCompany, reset: resetSelectMutationState } = useCompanySelection();
const { mutateAsync: clearCompanyData } = useClearCompanyData();
const currentTin = form.data.basicInformation?.taxInformation?.find((taxId) => taxId.country === country)?.number;
const currentRegistrationNumber = form.data.basicInformation?.registrationNumber;
const handleChange = useCallback$1((fieldName, mode) => form.handleChangeFor("businessSelection", fieldName, mode), [form]);
/**
* This ID is internal to this form, controlling selection for UI & data flow purposes. The
* multiform state is used to determine whether the form is set & valid, ready for the user to progress.
*/
const selectedId = useSignal("");
const isSelectPending = useSignal(false);
const selectedCompanyIdx = companySearchResponse?.results.findIndex((searchResult) => searchResult.resultId === selectedId.value);
/**
* Reset company selection when re-entering form.
*
* The mutation makes this a bit awkward, as we won't have any data when re-entering. Whilst we
* could perhaps auto-select the result, without caching, we'd have another spinner & wait time for
* the user. Better to force a manual re-selection to work around our rough implementation details.
*/
const isInitializedRef = useRef$1(false);
if (!isInitializedRef.current) {
if (form.data.businessSelection?.selectedBusinessId) {
handleChange("selectedBusinessId", "blur")("");
form.setErrors("businessSelection", "selectedBusinessId", null);
}
isInitializedRef.current = true;
}
const fetchCompanyData = async (result) => {
isSelectPending.value = true;
resetSelectMutationState();
try {
const companySelectionResponse = await selectCompany({
id: result.resultId,
name: result.name,
tin: currentTin ?? "",
registrationNumber: currentRegistrationNumber ?? "",
country
});
handleChange("selectedBusinessId", "blur")(result.resultId);
companySearchStateModel.selectCompany(companySelectionResponse, selectedCompanyIdx, country);
} catch (e) {
if (isBusinessSelectionLegalArrangementError(e)) {
companySearchStateModel.disallowSelection("LEGAL_ARRANGEMENT");
handleChange("selectedBusinessId", "blur")("LEGAL_ARRANGEMENT_ERR");
} else logger.error(e);
} finally {
isSelectPending.value = false;
}
};
const handleSelectBusiness = (result) => {
selectedId.value = result.resultId;
companySearchStateModel.resetCompanySearchData();
fetchCompanyData(result);
};
const handleSelectNotListed = async () => {
selectedId.value = "notListed";
companySearchStateModel.resetCompanySearchData();
clearCompanyData();
if (country !== CountryCodes.UnitedStates) return handleChange("selectedBusinessId", "blur")("notListed");
try {
isSelectPending.value = true;
const tinVerificationParams = {
name: form.data.basicInformation?.legalCompanyName ?? "",
tin: currentTin ?? ""
};
const { matched } = await queryClient.fetchQuery(verifyTinQueryOptions(rootLegalEntityId.peek(), baseUrl.peek(), tinVerificationParams, userEvents));
companySearchStateModel.setVerificationMatched(!!matched);
handleChange("selectedBusinessId", "blur")("notListed");
} catch (e) {
logger.error(e);
companySearch