diff --git a/config/oxlint/oxlint.seatbelt.tsv b/config/oxlint/oxlint.seatbelt.tsv index d942c1bfb996..1202eec531c0 100644 --- a/config/oxlint/oxlint.seatbelt.tsv +++ b/config/oxlint/oxlint.seatbelt.tsv @@ -489,7 +489,6 @@ "../../src/components/TransactionItemRow/DataCells/ChatBubbleCell.tsx" "rulesdir/no-raw-typography" 2 "../../src/components/TransactionItemRow/DataCells/MerchantCell.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/components/UnitPicker.tsx" "@typescript-eslint/no-unnecessary-type-assertion" 1 -"../../src/components/UploadFile.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/components/UserInitialsAvatar.tsx" "@typescript-eslint/no-deprecated/fontSize" 1 "../../src/components/ValidateCodeActionModal/ValidateCodeActionContent.tsx" "rulesdir/no-onyx-loading-status" 1 "../../src/components/ValidateCodeInput.tsx" "react-hooks/set-state-in-effect" 3 diff --git a/src/CONST/index.ts b/src/CONST/index.ts index 5760f528c2c1..0e1e777330b7 100644 --- a/src/CONST/index.ts +++ b/src/CONST/index.ts @@ -1140,6 +1140,51 @@ const CONST = { /** Wise's KYC requirement types we collect */ KYC_REQUIREMENT: { ID_DOCUMENT: 'ID_DOCUMENT', + BUSINESS_SOURCE_OF_WEALTH_INFO: 'BUSINESS_SOURCE_OF_WEALTH_INFO', + BUSINESS_SOURCE_OF_WEALTH_PROOF: 'BUSINESS_SOURCE_OF_WEALTH_PROOF', + }, + /** The source of funds page's answer key, which is Wise's field */ + SOURCE_OF_WEALTH_INFO_KEY: 'businessSourceOfWealthInfo', + /** The key Wise takes the picked sources under, one `{businessSourceOfWealthInfo, isSourceOfFund}` entry per source */ + SOURCE_OF_WEALTH_LIST_KEY: 'sourceOfWealthList', + /** The daily operations page's answer key: the picked sources that fund the business's daily operations, saved as each entry's `isSourceOfFund` */ + SOURCE_OF_FUNDS_KEY: 'sourceOfFunds', + /** Drafted as true while a newly picked source waits for the daily operations page, since the new source can fund daily operations too */ + SOURCE_OF_FUNDS_REVIEW_KEY: 'shouldReviewSourceOfFunds', + /** The server takes up to this many files in one save and drops the rest without an error */ + MAX_NEW_FILES_PER_SAVE: 20, + /** Wise's businessSourceOfWealthInfo values, in Wise's order */ + SOURCE_OF_WEALTH: { + REVENUE: 'REVENUE', + PERSONAL_FUNDING: 'PERSONAL_FUNDING', + BUSINESS_LOAN: 'BUSINESS_LOAN', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: 'FUNDING_AND_SHAREHOLDER_INVESTMENTS', + INVESTMENT_INCOME: 'INVESTMENT_INCOME', + DONATIONS: 'DONATIONS', + GRANTS: 'GRANTS', + LEGAL: 'LEGAL', + }, + /** Wise's documentType values for a BUSINESS_SOURCE_OF_WEALTH_PROOF document */ + SOURCE_OF_WEALTH_DOCUMENT_TYPE: { + TAX_DOCUMENTS: 'TAX_DOCUMENTS', + AUDITED_FINANCIAL_STATEMENTS: 'AUDITED_FINANCIAL_STATEMENTS', + BANK_STATEMENT: 'BANK_STATEMENT', + E_COMMERCE_STATEMENTS: 'E_COMMERCE_STATEMENTS', + INVOICES: 'INVOICES', + CONTRACTS: 'CONTRACTS', + PERSONAL_TAX_DECLARATION: 'PERSONAL_TAX_DECLARATION', + SAVINGS_STATEMENT: 'SAVINGS_STATEMENT', + PAYSLIP: 'PAYSLIP', + PERSONAL_LOAN_AGREEMENT: 'PERSONAL_LOAN_AGREEMENT', + PERSONAL_INVESTMENT: 'PERSONAL_INVESTMENT', + ASSET_SALE_AGREEMENT: 'ASSET_SALE_AGREEMENT', + LOAN_AGREEMENT: 'LOAN_AGREEMENT', + EQUITY_AGREEMENT: 'EQUITY_AGREEMENT', + SUBSCRIPTION_AGREEMENT: 'SUBSCRIPTION_AGREEMENT', + SHARE_SALE_CERTIFICATE: 'SHARE_SALE_CERTIFICATE', + DONATION_RECEIPTS: 'DONATION_RECEIPTS', + WRITTEN_CONFIRMATION: 'WRITTEN_CONFIRMATION', + GRANT_APPROVAL_LETTER: 'GRANT_APPROVAL_LETTER', }, /** Wise's companyType values, the legal form */ COMPANY_TYPE: { diff --git a/src/components/DynamicForm/adapters/FileUploadAdapter.tsx b/src/components/DynamicForm/adapters/FileUploadAdapter.tsx index 69ab9def50ba..d8500bb34613 100644 --- a/src/components/DynamicForm/adapters/FileUploadAdapter.tsx +++ b/src/components/DynamicForm/adapters/FileUploadAdapter.tsx @@ -1,9 +1,7 @@ -import FormContext from '@components/Form/FormContext'; +import useUploadErrorAnnouncement from '@components/DynamicForm/hooks/useUploadErrorAnnouncement'; import FSClassView from '@components/FSClassView'; import UploadFile from '@components/UploadFile'; -import useAccessibilityAnnouncement from '@hooks/useAccessibilityAnnouncement'; - import type {ForwardedFSClassProps} from '@libs/Fullstory/types'; import type {FileObject} from '@src/types/utils/Attachment'; @@ -11,7 +9,7 @@ import type {FileObject} from '@src/types/utils/Attachment'; import type {ComponentProps, ComponentRef, Ref} from 'react'; import type {View} from 'react-native'; -import React, {useContext, useState} from 'react'; +import React, {useState} from 'react'; /** UploadFile settings the adapter passes through unchanged */ type UploadFileSettings = Pick, 'buttonText' | 'acceptedFileTypes' | 'fileLimit' | 'maxFileSize' | 'accessibilityLabel'>; @@ -36,11 +34,7 @@ function FileUploadAdapter({value, onInputChange = () => {}, errorText = '', for const [uploadError, setUploadError] = useState(''); const files = Array.isArray(value) ? value : []; - const shownError = uploadError || errorText; - const {getErrorAnnouncementKey} = useContext(FormContext); - const errorAnnouncementKey = getErrorAnnouncementKey(); - // UploadFile shows the error through a live region, which VoiceOver ignores, so it is announced as it appears and again on each submit - useAccessibilityAnnouncement(shownError, !!shownError, {shouldAnnounceOnNative: true, announcementKey: errorAnnouncementKey}); + const shownError = useUploadErrorAnnouncement(uploadError, errorText); // UploadFile takes no FullStory class, so the mask goes on a View around it return ( @@ -65,3 +59,4 @@ function FileUploadAdapter({value, onInputChange = () => {}, errorText = '', for } export default FileUploadAdapter; +export type {UploadFileSettings}; diff --git a/src/components/DynamicForm/adapters/LabelledFileUploadAdapter.tsx b/src/components/DynamicForm/adapters/LabelledFileUploadAdapter.tsx new file mode 100644 index 000000000000..47d7c70b462c --- /dev/null +++ b/src/components/DynamicForm/adapters/LabelledFileUploadAdapter.tsx @@ -0,0 +1,194 @@ +import Button from '@components/Button'; +import DotIndicatorMessage from '@components/DotIndicatorMessage'; +import FileTypeMenuButton from '@components/DynamicForm/components/FileTypeMenuButton'; +import type {FileTypeOption} from '@components/DynamicForm/components/FileTypeMenuButton'; +import useUploadErrorAnnouncement from '@components/DynamicForm/hooks/useUploadErrorAnnouncement'; +import {getListItemFiles, getListItems} from '@components/DynamicForm/utils/listItems'; +import FSClassView from '@components/FSClassView'; +import Text from '@components/Text'; +import UploadedFileChip from '@components/UploadFile/components/UploadedFileChip'; +import UploadFilePicker from '@components/UploadFile/components/UploadFilePicker'; + +import useLocalize from '@hooks/useLocalize'; +import useThemeStyles from '@hooks/useThemeStyles'; + +import type {ForwardedFSClassProps} from '@libs/Fullstory/types'; + +import CONST from '@src/CONST'; +import type {DynamicFormListItem} from '@src/types/onyx'; +import type {FileObject} from '@src/types/utils/Attachment'; + +import type {ComponentRef, Ref} from 'react'; + +import React, {useState} from 'react'; +import {View} from 'react-native'; + +import type {UploadFileSettings} from './FileUploadAdapter'; + +/** One upload button and the kinds of document it takes */ +type LabelledUpload = { + /** The kinds of document the button takes */ + types: FileTypeOption[]; + + /** Text of the button */ + buttonText: string; + + /** Hint under the button, such as what the document must show */ + description?: string; +}; + +type LabelledFileUploadAdapterProps = Omit & + ForwardedFSClassProps & { + /** One entry per kind of document used so far: `{id, fileType, files}` */ + value?: DynamicFormListItem[]; + + /** Called with every entry after each add or remove */ + onInputChange?: (value: DynamicFormListItem[]) => void; + + /** Validation error, shown under each button that has no file yet, or under the last button when every button has one */ + errorText?: string; + + /** The upload buttons, in order */ + uploads: LabelledUpload[]; + + /** Lets FormProvider scroll to the field when the user asks to fix the errors */ + ref?: Ref>; + }; + +/** + * Upload buttons, each labelling its files with a kind of document it takes. A button with one kind opens the file picker, and a button with more asks which kind first. + * Files list under their button. The file limit counts every file of the field, and the check for a file with the same name only the button's own files, since one file can prove two documents. + */ +function LabelledFileUploadAdapter({ + value, + onInputChange = () => {}, + errorText = '', + uploads, + forwardedFSClass, + ref, + accessibilityLabel, + acceptedFileTypes, + fileLimit, + maxFileSize, +}: LabelledFileUploadAdapterProps) { + const {translate} = useLocalize(); + const styles = useThemeStyles(); + const [uploadError, setUploadError] = useState(''); + const [uploadErrorIndex, setUploadErrorIndex] = useState(); + const entries = getListItems(value); + // Announces the upload error, else the validation error, as it appears + useUploadErrorAnnouncement(uploadError, errorText); + + const getFiles = (upload: LabelledUpload) => entries.filter((entry) => upload.types.some((type) => type.value === entry.fileType)); + const hasFileUnderEveryButton = uploads.every((upload) => getFiles(upload).length > 0); + const getTypeLabel = (fileType: unknown) => uploads.flatMap((upload) => upload.types).find((type) => type.value === fileType)?.label ?? ''; + + const addFiles = (index: number, fileType: string, newFiles: FileObject[]) => { + if (newFiles.length === 0) { + return; + } + // The picker checks the limit against the button's own files, so the field checks it against all of them + if (fileLimit && entries.flatMap(getListItemFiles).length + newFiles.length > fileLimit) { + setUploadErrorIndex(index); + setUploadError(translate('attachmentPicker.tooManyFiles', fileLimit)); + return; + } + const typeEntry = entries.find((entry) => entry.fileType === fileType); + const updatedEntry: DynamicFormListItem = {id: fileType, fileType, files: [...(typeEntry ? getListItemFiles(typeEntry) : []), ...newFiles]}; + onInputChange(typeEntry ? entries.map((entry) => (entry === typeEntry ? updatedEntry : entry)) : [...entries, updatedEntry]); + }; + + const removeFile = (removedEntry: DynamicFormListItem, fileName: string) => { + setUploadError(''); + const files = getListItemFiles(removedEntry).filter((file) => file.name !== fileName); + onInputChange(files.length > 0 ? entries.map((entry) => (entry === removedEntry ? {...entry, files} : entry)) : entries.filter((entry) => entry !== removedEntry)); + }; + + return ( + + {uploads.map((upload, index) => { + const uploadEntries = getFiles(upload); + const buttonAccessibilityLabel = accessibilityLabel ? `${upload.buttonText}, ${accessibilityLabel}` : upload.buttonText; + let shownError = ''; + if (uploadErrorIndex === index && uploadError) { + shownError = uploadError; + } else if (uploadEntries.length === 0 || (hasFileUnderEveryButton && index === uploads.length - 1)) { + shownError = errorText; + } + return ( + 0 && styles.mt5, styles.alignItemsStart]} + > + { + setUploadErrorIndex(index); + setUploadError(error); + }} + fileLimit={fileLimit} + acceptedFileTypes={acceptedFileTypes} + maxFileSize={maxFileSize} + > + {(openPicker) => { + const [onlyType] = upload.types; + if (upload.types.length === 1 && onlyType) { + return ( + + ); + } + return ( + openPicker((files) => addFiles(index, fileType, files))} + /> + ); + }} + + {uploadEntries.map((entry) => ( + // Full width, so a long file name is cut short instead of pushing the remove button out of view + + {upload.types.length > 1 && {getTypeLabel(entry.fileType)}} + {getListItemFiles(entry).map((file) => ( + removeFile(entry, fileName)} + shouldExtendRemoveTouchArea + /> + ))} + + ))} + {!!upload.description && {upload.description}} + {!!shownError && ( + + )} + + ); + })} + + ); +} + +export default LabelledFileUploadAdapter; diff --git a/src/components/DynamicForm/components/DynamicFormFieldsPage.tsx b/src/components/DynamicForm/components/DynamicFormFieldsPage.tsx index 0f5ea07eba95..3b60b60d6f32 100644 --- a/src/components/DynamicForm/components/DynamicFormFieldsPage.tsx +++ b/src/components/DynamicForm/components/DynamicFormFieldsPage.tsx @@ -39,6 +39,7 @@ function DynamicFormFieldsPage({ isRefreshingRequirements, refreshError, shouldDisableNextWhenOffline, + validatePage, }: DynamicFormSubPageProps) { const {translate} = useLocalize(); const styles = useThemeStyles(); @@ -58,7 +59,11 @@ function DynamicFormFieldsPage({ getDynamicFieldErrors(getContentFields(page.content), withInputValues(inputValues), translate, allFields)} + validate={(inputValues) => { + const currentValues = withInputValues(inputValues); + // A field's own error, such as a missing answer, says more than a check of the whole page + return {...validatePage?.(page, currentValues), ...getDynamicFieldErrors(getContentFields(page.content), currentValues, translate, allFields)}; + }} onSubmit={(inputValues) => { const pageValues = toDynamicFormValues(inputValues); onPageSubmit(page, pageValues); diff --git a/src/components/DynamicForm/components/FileTypeMenuButton.tsx b/src/components/DynamicForm/components/FileTypeMenuButton.tsx new file mode 100644 index 000000000000..47c827c9d5a8 --- /dev/null +++ b/src/components/DynamicForm/components/FileTypeMenuButton.tsx @@ -0,0 +1,108 @@ +import Button from '@components/Button'; +import PopoverMenu from '@components/PopoverMenu'; + +import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; +import useLocalize from '@hooks/useLocalize'; +import usePopoverPosition from '@hooks/usePopoverPosition'; + +import {isSafari} from '@libs/Browser'; + +import {close} from '@userActions/Modal'; + +import CONST from '@src/CONST'; +import type {AnchorPosition} from '@src/styles'; + +import type {ComponentRef} from 'react'; + +import React, {useRef, useState} from 'react'; +import {View} from 'react-native'; + +/** A kind of document a file can be labelled with */ +type FileTypeOption = { + /** The key saved with the file */ + value: string; + + /** The name shown to the user */ + label: string; +}; + +type FileTypeMenuButtonProps = { + /** Text of the button */ + buttonText: string; + + /** Read out by screen readers in place of the button text */ + accessibilityLabel: string; + + /** The kinds of document to pick from */ + types: FileTypeOption[]; + + /** Called with the picked kind once the menu is closed, so it can open the file picker */ + onSelect: (fileType: string) => void; +}; + +const ANCHOR_ALIGNMENT = {horizontal: CONST.MODAL.ANCHOR_ORIGIN_HORIZONTAL.LEFT, vertical: CONST.MODAL.ANCHOR_ORIGIN_VERTICAL.TOP}; + +/** A button that asks which kind of document to upload: a menu under the button on wide screens, a sheet from the bottom on narrow ones */ +function FileTypeMenuButton({buttonText, accessibilityLabel, types, onSelect}: FileTypeMenuButtonProps) { + const {translate} = useLocalize(); + const icons = useMemoizedLazyExpensifyIcons(['Document']); + const {calculatePopoverPosition} = usePopoverPosition(); + const anchorRef = useRef>(null); + const [anchorPosition, setAnchorPosition] = useState(); + const [isMenuVisible, setIsMenuVisible] = useState(false); + + const openMenu = () => { + calculatePopoverPosition(anchorRef, ANCHOR_ALIGNMENT).then((position) => { + setAnchorPosition(position); + setIsMenuVisible(true); + }); + }; + + return ( + <> + + + + {!!anchorPosition && ( + setIsMenuVisible(false)} + anchorPosition={anchorPosition} + anchorAlignment={ANCHOR_ALIGNMENT} + anchorRef={anchorRef} + headerText={translate('dynamicForm.selectDocumentToUpload')} + menuItems={types.map((type) => ({key: type.value, text: type.label, icon: icons.Document}))} + shouldUseScrollView + // The header already spaces the list from the top, so the list's own margins for long lists stay off + shouldUseModalPaddingStyle + onItemSelected={(item) => { + setIsMenuVisible(false); + const fileType = item.key; + if (!fileType) { + return; + } + // Safari opens the file picker only from the handler of the user's tap, and the other browsers only once the menu is gone + if (isSafari()) { + onSelect(fileType); + return; + } + close(() => onSelect(fileType)); + }} + enableEdgeToEdgeBottomSafeAreaPadding + /> + )} + + ); +} + +export default FileTypeMenuButton; +export type {FileTypeOption}; diff --git a/src/components/DynamicForm/hooks/useUploadErrorAnnouncement.ts b/src/components/DynamicForm/hooks/useUploadErrorAnnouncement.ts new file mode 100644 index 000000000000..5393761dce60 --- /dev/null +++ b/src/components/DynamicForm/hooks/useUploadErrorAnnouncement.ts @@ -0,0 +1,15 @@ +import FormContext from '@components/Form/FormContext'; + +import useAccessibilityAnnouncement from '@hooks/useAccessibilityAnnouncement'; + +import {useContext} from 'react'; + +/** The error an upload field shows: the upload error, else the validation error. UploadFile shows it through a live region, which VoiceOver ignores, so it is announced as it appears and again on each submit. */ +function useUploadErrorAnnouncement(uploadError: string, errorText: string): string { + const shownError = uploadError || errorText; + const {getErrorAnnouncementKey} = useContext(FormContext); + useAccessibilityAnnouncement(shownError, !!shownError, {shouldAnnounceOnNative: true, announcementKey: getErrorAnnouncementKey()}); + return shownError; +} + +export default useUploadErrorAnnouncement; diff --git a/src/components/DynamicForm/index.tsx b/src/components/DynamicForm/index.tsx index 8725cc46f024..d0a6a05aa34b 100644 --- a/src/components/DynamicForm/index.tsx +++ b/src/components/DynamicForm/index.tsx @@ -67,6 +67,8 @@ function DynamicFormFlow({ isRefreshingRequirements, refreshError, unsavedPageKeys, + isLoading, + validatePage, layout = 'auto', hasConfirmation = true, shouldDisableNextWhenOffline, @@ -212,7 +214,7 @@ function DynamicFormFlow({ Navigation.navigate(buildRoute(unavailablePageTarget), {forceReplace: true}); }, [isOnUnavailablePage, buildRoute, unavailablePageTarget]); - /** Typed answers are drafted as FormProvider cleaned them and inputs left untouched are drafted with their defaults, so the draft matches what the page validated. Sensitive answers go to memory only and reach the screen apart from the draft ones. Lists are drafted as they change, so the screen gets their drafted entries, which hold no sensitive answers. */ + /** Typed answers are drafted as FormProvider cleaned them and inputs left untouched are drafted with their defaults, so the draft matches what the page validated. Sensitive answers are kept in memory and handed to the screen as a separate argument, never written to the draft. Lists are drafted as they change, so the screen gets their drafted entries, which hold no sensitive answers. */ const handlePageSubmit = (page: DynamicFormPage, pageValues: DynamicFormValues) => { const currentValues = {...values, ...pageValues}; const pageFields = getContentFields(page.content).filter(isSupportedField); @@ -359,7 +361,7 @@ function DynamicFormFlow({ shouldShowStepIndicator={isStepIndicatorAsked && stepNames.length > 1} shouldShowOfflineIndicatorInWideScreen={shouldDisableNextWhenOffline} > - {isDraftLoading || isRedirecting || isClearingEarlierVisit || isOnUnavailablePage || (!hasPageToShow && pages.length > 0) ? ( + {isLoading || isDraftLoading || isRedirecting || isClearingEarlierVisit || isOnUnavailablePage || (!hasPageToShow && pages.length > 0) ? ( @@ -391,6 +393,7 @@ function DynamicFormFlow({ refreshError={refreshError} shouldShowFieldErrors={shouldShowFieldErrors} shouldDisableNextWhenOffline={shouldDisableNextWhenOffline} + validatePage={validatePage} > {children} diff --git a/src/components/DynamicForm/renderers/fileRenderer.tsx b/src/components/DynamicForm/renderers/fileRenderer.tsx index 4a4cb0272067..7e42169818fb 100644 --- a/src/components/DynamicForm/renderers/fileRenderer.tsx +++ b/src/components/DynamicForm/renderers/fileRenderer.tsx @@ -1,5 +1,8 @@ import FileUploadAdapter from '@components/DynamicForm/adapters/FileUploadAdapter'; -import {getInputLabel} from '@components/DynamicForm/utils/getLocalizedText'; +import LabelledFileUploadAdapter from '@components/DynamicForm/adapters/LabelledFileUploadAdapter'; +import {getOptionLabel} from '@components/DynamicForm/utils/getFieldOptions'; +import getLocalizedText, {getInputLabel} from '@components/DynamicForm/utils/getLocalizedText'; +import {getListItems} from '@components/DynamicForm/utils/listItems'; import InputWrapper from '@components/Form/InputWrapper'; import CONST from '@src/CONST'; @@ -12,6 +15,31 @@ import type {DynamicFieldRenderer} from './types'; const renderFile: DynamicFieldRenderer<'file'> = (field, {translate, maxFileSize}, inputProps) => { const fileLimit = field.maxFiles ?? CONST.DYNAMIC_FORM_DOCUMENT.FILE_LIMIT; const buttonText = translate(fileLimit > 1 ? 'common.chooseFiles' : 'common.chooseFile'); + const uploadFileProps = {buttonText, fileLimit, acceptedFileTypes: [...CONST.DYNAMIC_FORM_DOCUMENT.ALLOWED_FILE_TYPES], maxFileSize: field.maxFileSize ?? maxFileSize}; + if (field.uploads) { + const {defaultValue, ...labelledInputProps} = inputProps; + return { + isMenuRow: false, + input: ( + ({ + types: upload.fileTypes.map((option) => ({value: option.key, label: getOptionLabel(option, translate)})), + buttonText: getLocalizedText(translate, upload.labelKey, upload.label) ?? translate('dynamicForm.uploadFile'), + description: getLocalizedText(translate, upload.descriptionKey, upload.description), + }))} + accessibilityLabel={getInputLabel(field, translate)} + fileLimit={fileLimit} + acceptedFileTypes={uploadFileProps.acceptedFileTypes} + maxFileSize={uploadFileProps.maxFileSize} + /> + ), + }; + } return { isMenuRow: false, labelAbove: 'heading', @@ -20,11 +48,8 @@ const renderFile: DynamicFieldRenderer<'file'> = (field, {translate, maxFileSize InputComponent={FileUploadAdapter} {...inputProps} valueType="files" - buttonText={buttonText} accessibilityLabel={`${buttonText}, ${getInputLabel(field, translate)}`} - fileLimit={fileLimit} - acceptedFileTypes={[...CONST.DYNAMIC_FORM_DOCUMENT.ALLOWED_FILE_TYPES]} - maxFileSize={field.maxFileSize ?? maxFileSize} + {...uploadFileProps} /> ), }; diff --git a/src/components/DynamicForm/types.ts b/src/components/DynamicForm/types.ts index f8ae86c20173..fed9ef20ae5c 100644 --- a/src/components/DynamicForm/types.ts +++ b/src/components/DynamicForm/types.ts @@ -80,6 +80,12 @@ type DynamicFormFlowProps = Pick Record; + /** When the step indicator shows: `auto` from three shown pages on, `stepper` always, `pages` never */ layout?: DynamicFormLayout; @@ -110,6 +116,7 @@ type DynamicFormSubPageProps = SubPageProps & | 'isRefreshingRequirements' | 'refreshError' | 'shouldDisableNextWhenOffline' + | 'validatePage' > & { pages: DynamicFormPage[]; diff --git a/src/components/DynamicForm/utils/formatDynamicFieldValue.ts b/src/components/DynamicForm/utils/formatDynamicFieldValue.ts index d567f429c34b..e9dc6c8d6edb 100644 --- a/src/components/DynamicForm/utils/formatDynamicFieldValue.ts +++ b/src/components/DynamicForm/utils/formatDynamicFieldValue.ts @@ -6,6 +6,7 @@ import type {DynamicFormField} from '@src/types/onyx'; import getAddressInputKeys, {getAddressCountry, isStateAsked} from './getAddressInputKeys'; import getFieldOptions, {getOptionLabel} from './getFieldOptions'; import isCountryCode from './isCountryCode'; +import {getListItemFiles, getListItems} from './listItems'; /** Street, then city, then state and zip, then country, as in "1 Main Street, Springfield, IL 62701, United States" */ function formatAddress(fieldKey: string, values: DynamicFormValues, translate: LocalizedTranslate): string { @@ -30,7 +31,8 @@ function formatDynamicFieldValue(field: DynamicFormField, values: DynamicFormVal if (Array.isArray(answer)) { const items: unknown[] = answer; if (field.type === 'file') { - return translate('dynamicForm.fileCount', {count: items.length}); + const count = field.uploads ? getListItems(answer).reduce((sum, entry) => sum + getListItemFiles(entry).length, 0) : items.length; + return translate('dynamicForm.fileCount', {count}); } if (field.type !== 'multiselect' && field.type !== 'countryMultiselect') { return ''; diff --git a/src/components/DynamicForm/utils/getDynamicFieldErrors.ts b/src/components/DynamicForm/utils/getDynamicFieldErrors.ts index 796d47f174ac..9cf50a51382e 100644 --- a/src/components/DynamicForm/utils/getDynamicFieldErrors.ts +++ b/src/components/DynamicForm/utils/getDynamicFieldErrors.ts @@ -35,7 +35,7 @@ import {getFieldLabel} from './getLocalizedText'; import getVisibleFields from './getVisibleFields'; import hasProvidedAnswer from './hasProvidedAnswer'; import isSupportedField from './isSupportedField'; -import {getListItems, getListItemSensitiveAnswers} from './listItems'; +import {getListItemFiles, getListItems, getListItemSensitiveAnswers} from './listItems'; import logSchemaProblem from './logSchemaProblem'; import summarizeListItem, {getListItemFallbackTitle} from './summarizeListItem'; @@ -148,6 +148,16 @@ function getLegalNameErrors(value: string, translate: LocalizedTranslate): strin /** For inputs that only accept valid answers: UploadFile checks type and count, AmountForm rejects invalid typing */ const noChecks = () => []; +/** A required field with upload buttons needs a file on each of them, since each button asks for its own document */ +const validateFileUploads: FieldValidator<'file'> = (field, values, translate) => { + if (!field.required || !field.uploads) { + return []; + } + const usedTypes = new Set(getListItems(values[field.key]).flatMap((entry) => (getListItemFiles(entry).length > 0 ? [entry.fileType] : []))); + const hasFileOnEveryButton = field.uploads.every((upload) => upload.fileTypes.some((option) => usedTypes.has(option.key))); + return hasFileOnEveryButton ? [] : [translate('common.error.fieldRequired')]; +}; + const PERCENT_MIN = 1; const PERCENT_MAX = 100; @@ -192,7 +202,7 @@ const VALIDATORS: {[TType in DynamicFormFieldType]: FieldValidator} = { boolean: noChecks, country: noChecks, currency: noChecks, - file: noChecks, + file: validateFileUploads, amount: noChecks, percent: (field, values, translate) => { const percent = Number(getStringAnswer(field, values)); diff --git a/src/components/DynamicForm/utils/listItems.ts b/src/components/DynamicForm/utils/listItems.ts index f0e77da270b7..5a8db9d3e2e3 100644 --- a/src/components/DynamicForm/utils/listItems.ts +++ b/src/components/DynamicForm/utils/listItems.ts @@ -1,6 +1,7 @@ import type {DynamicFormValues} from '@components/DynamicForm/types'; import type {DynamicFormListField, DynamicFormListItem} from '@src/types/onyx'; +import type {FileObject} from '@src/types/utils/Attachment'; import getAnswerKeys from './getAnswerKeys'; import hasSensitiveAnswer from './hasSensitiveAnswer'; @@ -40,6 +41,15 @@ function getListItems(value: unknown): DynamicFormListItem[] { return items.filter(isListItem); } +/** The files an entry holds under `files`, as a labelled upload field stores them, ignoring anything malformed */ +function getListItemFiles(item: DynamicFormListItem): FileObject[] { + const files: unknown = item.files; + if (!Array.isArray(files)) { + return []; + } + return files.filter((file): file is FileObject => typeof file === 'object' && file !== null); +} + /** An entry's sensitive answers, keyed by field key, from the answers kept in memory */ function getListItemSensitiveAnswers(field: DynamicFormListField, itemID: string, values: DynamicFormValues): DynamicFormValues { return Object.fromEntries( @@ -60,4 +70,4 @@ function getRemovedListItemSensitiveKeys(field: DynamicFormListField, values: Dy return Object.keys(values).filter((key) => key.startsWith(`${field.key}${PAGE_NAME_SEPARATOR}`) && !keptKeys.has(key)); } -export {getListItemPageName, getListItemSensitiveAnswers, getListItemSensitiveKey, getListItems, getRemovedListItemSensitiveKeys, isListItem, parseListItemPageName}; +export {getListItemFiles, getListItemPageName, getListItemSensitiveAnswers, getListItemSensitiveKey, getListItems, getRemovedListItemSensitiveKeys, isListItem, parseListItemPageName}; diff --git a/src/components/Form/types.ts b/src/components/Form/types.ts index 5e4ef3b9f76a..4e926cbe72e3 100644 --- a/src/components/Form/types.ts +++ b/src/components/Form/types.ts @@ -11,6 +11,7 @@ import type DatePicker from '@components/DatePicker'; import type CurrencyInlineListAdapter from '@components/DynamicForm/adapters/CurrencyInlineListAdapter'; import type FileUploadAdapter from '@components/DynamicForm/adapters/FileUploadAdapter'; import type InlineSelectionListAdapter from '@components/DynamicForm/adapters/InlineSelectionListAdapter'; +import type LabelledFileUploadAdapter from '@components/DynamicForm/adapters/LabelledFileUploadAdapter'; import type ListFieldAdapter from '@components/DynamicForm/adapters/ListFieldAdapter'; import type TabsAdapter from '@components/DynamicForm/adapters/TabsAdapter'; import type ToggleLinkAdapter from '@components/DynamicForm/adapters/ToggleLinkAdapter'; @@ -103,7 +104,8 @@ type ValidInputs = | typeof YesNoAdapter | typeof TabsAdapter | typeof ToggleLinkAdapter - | typeof ListFieldAdapter; + | typeof ListFieldAdapter + | typeof LabelledFileUploadAdapter; type ValueTypeKey = 'string' | 'boolean' | 'date' | 'country' | 'stringList' | 'disabledListValues' | 'files' | 'listItems'; type ValueTypeMap = { diff --git a/src/components/UploadFile.tsx b/src/components/UploadFile.tsx deleted file mode 100644 index 44fed86f2e03..000000000000 --- a/src/components/UploadFile.tsx +++ /dev/null @@ -1,191 +0,0 @@ -import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; -import useLocalize from '@hooks/useLocalize'; -import useTheme from '@hooks/useTheme'; -import useThemeStyles from '@hooks/useThemeStyles'; - -import {splitExtensionFromFileName} from '@libs/fileDownload/FileUtils'; - -import CONST from '@src/CONST'; -import type {FileObject} from '@src/types/utils/Attachment'; - -import type {StyleProp, ViewStyle} from 'react-native'; -import type {ValueOf} from 'type-fest'; - -import React from 'react'; -import {View} from 'react-native'; - -import AttachmentPicker from './AttachmentPicker'; -import Button from './Button'; -import DotIndicatorMessage from './DotIndicatorMessage'; -import FSClassView from './FSClassView'; -import Icon from './Icon'; -import {PressableWithFeedback} from './Pressable'; -import TextWithMiddleEllipsis from './TextWithMiddleEllipsis'; -import Tooltip from './Tooltip'; - -type UploadFileProps = { - /** Text displayed on button when no file is uploaded */ - buttonText: string; - - uploadedFiles: FileObject[]; - onUpload: (files: FileObject[]) => void; - onRemove: (fileUri: string) => void; - acceptedFileTypes: Array>; - - /** Styles to be assigned to Container */ - style?: StyleProp; - - /** Text to display on error message */ - errorText?: string; - - /** Function called whenever option changes */ - onInputChange?: (value: FileObject[]) => void; - - /** Function to set error message */ - setError: (error: string) => void; - - /** Whether to allow multiple files to be selected. */ - fileLimit?: number; - - totalFilesSizeLimit?: number; - - /** The maximum size of a single file that can be selected. */ - maxFileSize?: number; - - /** Read out by screen readers for the upload button in place of its text, such as to name the document it asks for */ - accessibilityLabel?: string; - - /** Whether each file's remove button reaches the 44x44 minimum touch target past its icon */ - shouldExtendRemoveTouchArea?: boolean; -}; - -function UploadFile({ - buttonText, - uploadedFiles, - onUpload, - onRemove, - acceptedFileTypes, - style, - errorText = '', - setError, - onInputChange = () => {}, - totalFilesSizeLimit = 0, - fileLimit = 0, - maxFileSize = 0, - accessibilityLabel, - shouldExtendRemoveTouchArea = false, -}: UploadFileProps) { - const icons = useMemoizedLazyExpensifyIcons(['Close', 'Paperclip']); - const {translate} = useLocalize(); - const styles = useThemeStyles(); - const theme = useTheme(); - const handleFileUpload = (files: FileObject[]) => { - const resultedFiles = [...uploadedFiles, ...files]; - - const totalSize = resultedFiles.reduce((sum, file) => sum + (file.size ?? 0), 0); - - if (maxFileSize) { - const oversizedFile = files.find((file) => (file.size ?? 0) > maxFileSize); - if (oversizedFile) { - setError(translate('attachmentPicker.sizeExceededWithLimit', maxFileSize / (1024 * 1024))); - return; - } - } - - if (totalFilesSizeLimit) { - if (totalSize > totalFilesSizeLimit) { - setError(translate('attachmentPicker.sizeExceededWithValue', totalFilesSizeLimit / (1024 * 1024))); - return; - } - } - - if (fileLimit && resultedFiles.length > 0 && resultedFiles.length > fileLimit) { - setError(translate('attachmentPicker.tooManyFiles', fileLimit)); - return; - } - - if (acceptedFileTypes.length > 0) { - const filesExtensions = new Set(files.map((file) => splitExtensionFromFileName(file?.name ?? '').fileExtension.toLowerCase())); - - if (acceptedFileTypes.every((element) => !filesExtensions.has(element as string))) { - setError(translate('attachmentPicker.notAllowedExtension')); - return; - } - } - - const uploadedFilesNames = new Set(uploadedFiles.map((uploadedFile) => uploadedFile.name)); - - const newFilesToUpload = files.filter((file) => !uploadedFilesNames.has(file.name)); - - onInputChange(newFilesToUpload); - onUpload(newFilesToUpload); - setError(''); - }; - - return ( - - 1} - > - {({openPicker}) => ( - - )} - - {uploadedFiles.map((file) => ( - - - - - onRemove(file?.name ?? '')} - role={CONST.ROLE.BUTTON} - accessibilityLabel={`${translate('common.remove')}, ${file.name ?? ''}`} - sentryLabel={CONST.SENTRY_LABEL.UPLOAD_FILE.REMOVE_BUTTON} - shouldUseAutoHitSlop={shouldExtendRemoveTouchArea} - > - - - - - ))} - {errorText !== '' && ( - - )} - - ); -} - -export default UploadFile; diff --git a/src/components/UploadFile/components/UploadFilePicker.tsx b/src/components/UploadFile/components/UploadFilePicker.tsx new file mode 100644 index 000000000000..22a66c86a2d0 --- /dev/null +++ b/src/components/UploadFile/components/UploadFilePicker.tsx @@ -0,0 +1,136 @@ +import AttachmentPicker from '@components/AttachmentPicker'; +import Button from '@components/Button'; +import type UploadFileProps from '@components/UploadFile/types'; + +import useLocalize from '@hooks/useLocalize'; + +import {splitExtensionFromFileName} from '@libs/fileDownload/FileUtils'; + +import CONST from '@src/CONST'; +import type {FileObject} from '@src/types/utils/Attachment'; + +import type {ReactNode} from 'react'; + +import React from 'react'; + +type UploadFilePickerProps = Pick< + UploadFileProps, + 'buttonText' | 'acceptedFileTypes' | 'setError' | 'onInputChange' | 'totalFilesSizeLimit' | 'fileLimit' | 'maxFileSize' | 'accessibilityLabel' +> & { + /** Files uploaded so far, which the file limit and the check for a file with the same name count */ + existingFiles: FileObject[]; + + /** Gets the files that pass the checks when the button opens the picker */ + onUpload?: UploadFileProps['onUpload']; + + /** Draws the control that opens the picker in place of the button. The files that pass the checks go to the `onUpload` given to `openPicker`. */ + children?: (openPicker: (onUpload: (files: FileObject[]) => void) => void) => ReactNode; +}; + +/** The name the server stores a file under: lowercased, with every byte outside a-z, 0-9 and `-` replaced by `_`, and the extension kept */ +function getServerFileName(fileName: string): {name: string; extension: string} { + const extensionStart = fileName.lastIndexOf('.'); + const name = extensionStart > 0 ? fileName.slice(0, extensionStart) : fileName; + const storedName = Array.from(new TextEncoder().encode(name.toLowerCase()), (byte) => { + const character = String.fromCharCode(byte); + return /[a-z0-9-]/.test(character) ? character : '_'; + }).join(''); + return {name: storedName, extension: extensionStart > 0 ? fileName.slice(extensionStart).toLowerCase() : ''}; +} + +/** + * A picked file is the same as an uploaded one with the same name, or with the name the server gives the picked file once it saves it. + * A server name with no letter or digit left, such as one written in Japanese, says nothing about the file, so it is not compared. + */ +function isSameFile(pickedFile: FileObject, uploadedFile: FileObject): boolean { + const pickedName = pickedFile.name ?? ''; + if (pickedName === uploadedFile.name) { + return true; + } + const serverName = getServerFileName(pickedName); + return /[a-z0-9]/.test(serverName.name) && `${serverName.name}${serverName.extension}` === uploadedFile.name?.toLowerCase(); +} + +/** The button, or the control drawn by `children`, that opens the file picker and checks the picked files against the limits before reporting them */ +function UploadFilePicker({ + buttonText, + existingFiles, + onUpload, + acceptedFileTypes, + setError, + onInputChange = () => {}, + totalFilesSizeLimit = 0, + fileLimit = 0, + maxFileSize = 0, + accessibilityLabel, + children, +}: UploadFilePickerProps) { + const {translate} = useLocalize(); + const handleFileUpload = (files: FileObject[], upload: (newFiles: FileObject[]) => void) => { + const resultedFiles = [...existingFiles, ...files]; + + const totalSize = resultedFiles.reduce((sum, file) => sum + (file.size ?? 0), 0); + + if (maxFileSize) { + const oversizedFile = files.find((file) => (file.size ?? 0) > maxFileSize); + if (oversizedFile) { + setError(translate('attachmentPicker.sizeExceededWithLimit', maxFileSize / (1024 * 1024))); + return; + } + } + + if (totalFilesSizeLimit) { + if (totalSize > totalFilesSizeLimit) { + setError(translate('attachmentPicker.sizeExceededWithValue', totalFilesSizeLimit / (1024 * 1024))); + return; + } + } + + if (fileLimit && resultedFiles.length > 0 && resultedFiles.length > fileLimit) { + setError(translate('attachmentPicker.tooManyFiles', fileLimit)); + return; + } + + if (acceptedFileTypes.length > 0) { + const filesExtensions = new Set(files.map((file) => splitExtensionFromFileName(file?.name ?? '').fileExtension.toLowerCase())); + + if (acceptedFileTypes.every((element) => !filesExtensions.has(element))) { + setError(translate('attachmentPicker.notAllowedExtension')); + return; + } + } + + const newFilesToUpload = files.filter((file) => !existingFiles.some((uploadedFile) => isSameFile(file, uploadedFile))); + + // The error is set before the files go on, so a check of the receiver can replace it + setError(newFilesToUpload.length < files.length ? translate('attachmentPicker.fileAlreadyAdded') : ''); + onInputChange(newFilesToUpload); + upload(newFilesToUpload); + }; + + return ( + 1} + > + {({openPicker}) => { + const openPickerFor = (upload: (files: FileObject[]) => void) => openPicker({onPicked: (files) => handleFileUpload(files, upload)}); + if (children) { + return children(openPickerFor); + } + return ( + + ); + }} + + ); +} + +export default UploadFilePicker; diff --git a/src/components/UploadFile/components/UploadedFileChip.tsx b/src/components/UploadFile/components/UploadedFileChip.tsx new file mode 100644 index 000000000000..0e6263b9ed94 --- /dev/null +++ b/src/components/UploadFile/components/UploadedFileChip.tsx @@ -0,0 +1,63 @@ +import FSClassView from '@components/FSClassView'; +import Icon from '@components/Icon'; +import {PressableWithFeedback} from '@components/Pressable'; +import TextWithMiddleEllipsis from '@components/TextWithMiddleEllipsis'; +import Tooltip from '@components/Tooltip'; +import type UploadFileProps from '@components/UploadFile/types'; + +import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; +import useLocalize from '@hooks/useLocalize'; +import useTheme from '@hooks/useTheme'; +import useThemeStyles from '@hooks/useThemeStyles'; + +import CONST from '@src/CONST'; +import type {FileObject} from '@src/types/utils/Attachment'; + +import React from 'react'; + +type UploadedFileChipProps = Pick & { + file: FileObject; +}; + +/** One uploaded file: its name with a paperclip, and a button that removes it */ +function UploadedFileChip({file, onRemove, shouldExtendRemoveTouchArea = false}: UploadedFileChipProps) { + const icons = useMemoizedLazyExpensifyIcons(['Close', 'Paperclip']); + const {translate} = useLocalize(); + const styles = useThemeStyles(); + const theme = useTheme(); + return ( + + + + + onRemove(file?.name ?? '')} + role={CONST.ROLE.BUTTON} + accessibilityLabel={`${translate('common.remove')}, ${file.name ?? ''}`} + sentryLabel={CONST.SENTRY_LABEL.UPLOAD_FILE.REMOVE_BUTTON} + shouldUseAutoHitSlop={shouldExtendRemoveTouchArea} + > + + + + + ); +} + +export default UploadedFileChip; diff --git a/src/components/UploadFile/index.tsx b/src/components/UploadFile/index.tsx new file mode 100644 index 000000000000..ada70d85e6bd --- /dev/null +++ b/src/components/UploadFile/index.tsx @@ -0,0 +1,41 @@ +import DotIndicatorMessage from '@components/DotIndicatorMessage'; + +import useThemeStyles from '@hooks/useThemeStyles'; + +import React from 'react'; +import {View} from 'react-native'; + +import type UploadFileProps from './types'; + +import UploadedFileChip from './components/UploadedFileChip'; +import UploadFilePicker from './components/UploadFilePicker'; + +function UploadFile({uploadedFiles, onRemove, style, errorText = '', shouldExtendRemoveTouchArea = false, ...pickerProps}: UploadFileProps) { + const styles = useThemeStyles(); + + return ( + + + {uploadedFiles.map((file) => ( + + ))} + {errorText !== '' && ( + + )} + + ); +} + +export default UploadFile; diff --git a/src/components/UploadFile/types.ts b/src/components/UploadFile/types.ts new file mode 100644 index 000000000000..8fab4d240567 --- /dev/null +++ b/src/components/UploadFile/types.ts @@ -0,0 +1,43 @@ +import type CONST from '@src/CONST'; +import type {FileObject} from '@src/types/utils/Attachment'; + +import type {StyleProp, ViewStyle} from 'react-native'; +import type {TupleToUnion} from 'type-fest'; + +type UploadFileProps = { + /** Text displayed on button when no file is uploaded */ + buttonText: string; + + uploadedFiles: FileObject[]; + onUpload: (files: FileObject[]) => void; + onRemove: (fileUri: string) => void; + acceptedFileTypes: Array>; + + /** Styles to be assigned to Container */ + style?: StyleProp; + + /** Text to display on error message */ + errorText?: string; + + /** Function called whenever option changes */ + onInputChange?: (value: FileObject[]) => void; + + /** Function to set error message */ + setError: (error: string) => void; + + /** Whether to allow multiple files to be selected. */ + fileLimit?: number; + + totalFilesSizeLimit?: number; + + /** The maximum size of a single file that can be selected. */ + maxFileSize?: number; + + /** Read out by screen readers for the upload button in place of its text, such as to name the document it asks for */ + accessibilityLabel?: string; + + /** Whether each file's remove button reaches the 44x44 minimum touch target past its icon */ + shouldExtendRemoveTouchArea?: boolean; +}; + +export default UploadFileProps; diff --git a/src/languages/de.ts b/src/languages/de.ts index 533265a37d19..55cc72da6400 100644 --- a/src/languages/de.ts +++ b/src/languages/de.ts @@ -647,6 +647,7 @@ const translations: TranslationDeepObject = { attachmentImageTooLarge: 'Dieses Bild ist zu groß, um vor dem Hochladen eine Vorschau anzuzeigen.', imageDimensionsTooLarge: 'Die Bildabmessungen sind zu groß zum Verarbeiten. Bitte verwenden Sie ein kleineres Bild.', tooManyFiles: (fileLimit: number) => `Sie können jeweils nur bis zu ${fileLimit} Dateien hochladen.`, + fileAlreadyAdded: 'Eine Datei mit demselben Namen wurde bereits hinzugefügt.', sizeExceededWithValue: (maxUploadSizeInMB: number) => `Dateien überschreiten ${maxUploadSizeInMB} MB. Bitte versuche es erneut.`, someFilesCantBeUploaded: 'Einige Dateien können nicht hochgeladen werden', sizeLimitExceeded: (maxUploadSizeInMB: number) => `Dateien dürfen nicht größer als ${maxUploadSizeInMB} MB sein. Größere Dateien werden nicht hochgeladen.`, @@ -3143,6 +3144,92 @@ const translations: TranslationDeepObject = { description: 'Unternehmensbeschreibung', descriptionHint: 'Beschreiben Sie kurz, was Ihr Unternehmen macht.', }, + sourceOfWealth: { + label: 'Woher stammt das Geld Ihres Unternehmens?', + description: 'Unser Zahlungspartner muss alle Herkunftsquellen des Vermögens überprüfen. Wählen Sie alle zutreffenden Optionen aus.', + options: { + REVENUE: 'Geschäftsumsatz', + PERSONAL_FUNDING: 'Eigenfinanzierung', + BUSINESS_LOAN: 'Geschäftskredit', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: 'Finanzierung und Investitionen von Anteilseignern', + INVESTMENT_INCOME: 'Kapitalerträge', + DONATIONS: 'Spenden', + GRANTS: 'Fördermittel', + LEGAL: 'Rechtlicher Vergleich', + }, + }, + sourceOfFunds: { + label: 'Welche Quellen finanzieren Ihr Tagesgeschäft?', + description: 'Unser Zahlungspartner muss wissen, welche Quellen Ihren Geschäftsbetrieb finanzieren. Wählen Sie alle zutreffenden Optionen aus.', + }, + sourceOfWealthProof: { + title: 'Nachweise der Vermögensherkunft', + description: 'Laden Sie die erforderlichen Dokumente für jede unten aufgeführte Mittelherkunft hoch.', + hints: { + REVENUE: 'Laden Sie eine Steuererklärung, einen geprüften Jahresabschluss oder Geschäftskontoauszüge hoch.', + PERSONAL_FUNDING: 'Laden Sie eine persönliche Steuererklärung, Spar- oder Kontoauszüge oder Gehaltsabrechnungen hoch.', + BUSINESS_LOAN: 'Laden Sie einen Darlehensvertrag und einen Kontoauszug hoch.', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: + 'Laden Sie einen Beteiligungsvertrag, einen Zeichnungsvertrag oder eine Bescheinigung über den Anteilsverkauf hoch, dazu einen Kontoauszug.', + INVESTMENT_INCOME: + 'Laden Sie eine Aufstellung privater Kapitalanlagen, eine Bescheinigung über den Anteilsverkauf oder einen Kaufvertrag über Vermögenswerte hoch, dazu einen Kontoauszug.', + DONATIONS: 'Laden Sie eine Spendenquittung, eine schriftliche Bestätigung oder einen Vertrag hoch, dazu einen Kontoauszug.', + GRANTS: 'Laden Sie einen Förderbescheid, eine schriftliche Bestätigung oder einen Vertrag hoch, dazu einen Kontoauszug.', + LEGAL: 'Laden Sie einen Vertrag, eine schriftliche Bestätigung oder einen Kaufvertrag über Vermögenswerte hoch.', + }, + bankStatementHints: { + REVENUE: 'Muss den Eingang der Umsätze zeigen.', + PERSONAL_FUNDING: 'Muss die von Ihnen eingebrachten Mittel zeigen.', + BUSINESS_LOAN: 'Muss den Eingang der Darlehensmittel zeigen.', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: 'Muss den Eingang der Investitionsmittel zeigen.', + INVESTMENT_INCOME: 'Muss den Eingang der Kapitalerträge zeigen.', + DONATIONS: 'Muss den Eingang der Spende zeigen.', + GRANTS: 'Muss den Eingang der Fördermittel zeigen.', + LEGAL: 'Muss den Eingang der Vergleichszahlung zeigen.', + }, + uploadButtons: { + TAX_DOCUMENTS: 'Steuererklärung hochladen', + AUDITED_FINANCIAL_STATEMENTS: 'Geprüften Jahresabschluss hochladen', + BANK_STATEMENT: 'Kontoauszug hochladen', + E_COMMERCE_STATEMENTS: 'E-Commerce-Abrechnungen hochladen', + INVOICES: 'Rechnungen hochladen', + CONTRACTS: 'Verträge hochladen', + PERSONAL_TAX_DECLARATION: 'Persönliche Steuererklärung hochladen', + SAVINGS_STATEMENT: 'Sparkontoauszug hochladen', + PAYSLIP: 'Gehaltsabrechnung hochladen', + PERSONAL_LOAN_AGREEMENT: 'Privaten Darlehensvertrag hochladen', + PERSONAL_INVESTMENT: 'Aufstellung privater Kapitalanlagen hochladen', + ASSET_SALE_AGREEMENT: 'Kaufvertrag über Vermögenswerte hochladen', + LOAN_AGREEMENT: 'Darlehensvertrag hochladen', + EQUITY_AGREEMENT: 'Beteiligungsvertrag hochladen', + SUBSCRIPTION_AGREEMENT: 'Zeichnungsvertrag hochladen', + SHARE_SALE_CERTIFICATE: 'Bescheinigung über den Anteilsverkauf hochladen', + DONATION_RECEIPTS: 'Spendenquittungen hochladen', + WRITTEN_CONFIRMATION: 'Schriftliche Bestätigung hochladen', + GRANT_APPROVAL_LETTER: 'Förderbescheid hochladen', + }, + documentTypes: { + TAX_DOCUMENTS: 'Steuererklärung', + AUDITED_FINANCIAL_STATEMENTS: 'Geprüfter Jahresabschluss', + BANK_STATEMENT: 'Kontoauszug', + E_COMMERCE_STATEMENTS: 'E-Commerce-Abrechnungen', + INVOICES: 'Rechnungen', + CONTRACTS: 'Verträge', + PERSONAL_TAX_DECLARATION: 'Persönliche Steuererklärung', + SAVINGS_STATEMENT: 'Sparkontoauszug', + PAYSLIP: 'Gehaltsabrechnung', + PERSONAL_LOAN_AGREEMENT: 'Privatdarlehensvertrag', + PERSONAL_INVESTMENT: 'Persönlicher Anlageauszug', + ASSET_SALE_AGREEMENT: 'Kaufvertrag über Vermögenswerte', + LOAN_AGREEMENT: 'Darlehensvertrag', + EQUITY_AGREEMENT: 'Beteiligungsvertrag', + SUBSCRIPTION_AGREEMENT: 'Zeichnungsvertrag', + SHARE_SALE_CERTIFICATE: 'Bescheinigung über den Anteilsverkauf', + DONATION_RECEIPTS: 'Spendenquittungen', + WRITTEN_CONFIRMATION: 'Schriftliche Bestätigung', + GRANT_APPROVAL_LETTER: 'Förderbescheid', + }, + }, terms: { title: 'Bedingungen akzeptieren', subtitle: 'Bitte akzeptieren Sie die folgenden Bedingungen.', @@ -4488,6 +4575,8 @@ ${amount} für ${merchant} – ${date}`, tooManyItems: ({max}: {max: number}) => `Füge höchstens ${max} hinzu`, itemError: ({item, field, error}: {item: string; field: string; error: string}) => `${item}, ${field}: ${error}`, }, + uploadFile: 'Datei hochladen', + selectDocumentToUpload: 'Dokument zum Hochladen auswählen', addItem: ({item}: {item: string}) => `${item} hinzufügen`, removeItemTitle: ({item}: {item: string}) => `${item} entfernen?`, removeItemPrompt: ({name}: {name: string}) => `Möchtest du ${name} wirklich entfernen?`, diff --git a/src/languages/el.ts b/src/languages/el.ts index 0c37ef1e1e4a..6cbcb76a0b3b 100644 --- a/src/languages/el.ts +++ b/src/languages/el.ts @@ -647,6 +647,7 @@ const translations: TranslationDeepObject = { attachmentImageTooLarge: 'Η εικόνα είναι πολύ μεγάλη για προεπισκόπηση πριν από την αποστολή.', imageDimensionsTooLarge: 'Οι διαστάσεις της εικόνας είναι πολύ μεγάλες για επεξεργασία. Παρακαλούμε χρησιμοποιήστε μια μικρότερη εικόνα.', tooManyFiles: (fileLimit: number) => `Μπορείτε να ανεβάζετε έως ${fileLimit} αρχεία κάθε φορά.`, + fileAlreadyAdded: 'Έχει ήδη προστεθεί αρχείο με το ίδιο όνομα.', sizeExceededWithValue: (maxUploadSizeInMB: number) => `Τα αρχεία υπερβαίνουν τα ${maxUploadSizeInMB} MB. Παρακαλούμε δοκιμάστε ξανά.`, someFilesCantBeUploaded: 'Ορισμένα αρχεία δεν μπορούν να μεταφορτωθούν', sizeLimitExceeded: (maxUploadSizeInMB: number) => `Τα αρχεία πρέπει να είναι μικρότερα από ${maxUploadSizeInMB} MB. Τυχόν μεγαλύτερα αρχεία δεν θα αποσταλούν.`, @@ -3201,6 +3202,91 @@ const translations: TranslationDeepObject = { description: 'Περιγραφή επιχείρησης', descriptionHint: 'Περιγράψτε σύντομα τι κάνει η εταιρεία σας.', }, + sourceOfWealth: { + label: 'Από πού προέρχονται τα χρήματα της εταιρείας σας;', + description: 'Ο συνεργάτης πληρωμών μας πρέπει να επαληθεύσει όλες τις πηγές πλούτου. Επιλέξτε όλα όσα ισχύουν.', + options: { + REVENUE: 'Έσοδα επιχείρησης', + PERSONAL_FUNDING: 'Προσωπική χρηματοδότηση', + BUSINESS_LOAN: 'Επιχειρηματικό δάνειο', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: 'Χρηματοδότηση και επενδύσεις μετόχων', + INVESTMENT_INCOME: 'Έσοδα από επενδύσεις', + DONATIONS: 'Δωρεές', + GRANTS: 'Επιχορηγήσεις', + LEGAL: 'Νομικός διακανονισμός', + }, + }, + sourceOfFunds: { + label: 'Ποιες πηγές χρηματοδοτούν τις καθημερινές σας δραστηριότητες;', + description: 'Ο συνεργάτης πληρωμών μας πρέπει να γνωρίζει ποιες πηγές χρηματοδοτούν τις δραστηριότητές σας. Επιλέξτε όλα όσα ισχύουν.', + }, + sourceOfWealthProof: { + title: 'Έγγραφα για την πηγή πλούτου', + description: 'Ανεβάστε τα απαιτούμενα έγγραφα για κάθε προέλευση που αναφέρεται παρακάτω.', + hints: { + REVENUE: 'Μεταφορτώστε φορολογική δήλωση, ελεγμένες οικονομικές καταστάσεις ή εταιρικά αντίγραφα κίνησης λογαριασμού.', + PERSONAL_FUNDING: 'Μεταφορτώστε προσωπική φορολογική δήλωση, αντίγραφα αποταμιευτικού ή τραπεζικού λογαριασμού, ή εκκαθαριστικά μισθοδοσίας.', + BUSINESS_LOAN: 'Μεταφορτώστε σύμβαση δανείου και αντίγραφο κίνησης λογαριασμού.', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: 'Μεταφορτώστε συμφωνία συμμετοχής, σύμβαση εγγραφής ή βεβαίωση πώλησης μετοχών, καθώς και αντίγραφο κίνησης λογαριασμού.', + INVESTMENT_INCOME: + 'Μεταφορτώστε κατάσταση προσωπικών επενδύσεων, βεβαίωση πώλησης μετοχών ή σύμβαση πώλησης περιουσιακών στοιχείων, καθώς και αντίγραφο κίνησης λογαριασμού.', + DONATIONS: 'Μεταφορτώστε απόδειξη δωρεάς, γραπτή επιβεβαίωση ή σύμβαση, καθώς και αντίγραφο κίνησης λογαριασμού.', + GRANTS: 'Μεταφορτώστε επιστολή έγκρισης επιχορήγησης, γραπτή επιβεβαίωση ή σύμβαση, καθώς και αντίγραφο κίνησης λογαριασμού.', + LEGAL: 'Μεταφορτώστε σύμβαση, γραπτή επιβεβαίωση ή σύμβαση πώλησης περιουσιακών στοιχείων.', + }, + bankStatementHints: { + REVENUE: 'Πρέπει να δείχνει τα έσοδα που λήφθηκαν.', + PERSONAL_FUNDING: 'Πρέπει να δείχνει τα κεφάλαια που καταβάλατε.', + BUSINESS_LOAN: 'Πρέπει να δείχνει τα κεφάλαια του δανείου που λήφθηκαν.', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: 'Πρέπει να δείχνει τα κεφάλαια της επένδυσης που λήφθηκαν.', + INVESTMENT_INCOME: 'Πρέπει να δείχνει τα επενδυτικά έσοδα που λήφθηκαν.', + DONATIONS: 'Πρέπει να δείχνει τη δωρεά που λήφθηκε.', + GRANTS: 'Πρέπει να δείχνει τα κεφάλαια της επιχορήγησης που λήφθηκαν.', + LEGAL: 'Πρέπει να δείχνει τα κεφάλαια του διακανονισμού που λήφθηκαν.', + }, + uploadButtons: { + TAX_DOCUMENTS: 'Μεταφόρτωση φορολογικής δήλωσης', + AUDITED_FINANCIAL_STATEMENTS: 'Μεταφόρτωση ελεγμένων οικονομικών καταστάσεων', + BANK_STATEMENT: 'Μεταφόρτωση αντιγράφου κίνησης λογαριασμού', + E_COMMERCE_STATEMENTS: 'Μεταφόρτωση καταστάσεων ηλεκτρονικού εμπορίου', + INVOICES: 'Μεταφόρτωση τιμολογίων', + CONTRACTS: 'Μεταφόρτωση συμβάσεων', + PERSONAL_TAX_DECLARATION: 'Μεταφόρτωση προσωπικής φορολογικής δήλωσης', + SAVINGS_STATEMENT: 'Μεταφόρτωση αντιγράφου αποταμιευτικού λογαριασμού', + PAYSLIP: 'Μεταφόρτωση εκκαθαριστικού μισθοδοσίας', + PERSONAL_LOAN_AGREEMENT: 'Μεταφόρτωση σύμβασης προσωπικού δανείου', + PERSONAL_INVESTMENT: 'Μεταφόρτωση κατάστασης προσωπικών επενδύσεων', + ASSET_SALE_AGREEMENT: 'Μεταφόρτωση σύμβασης πώλησης περιουσιακών στοιχείων', + LOAN_AGREEMENT: 'Μεταφόρτωση σύμβασης δανείου', + EQUITY_AGREEMENT: 'Μεταφόρτωση συμφωνίας συμμετοχής', + SUBSCRIPTION_AGREEMENT: 'Μεταφόρτωση σύμβασης εγγραφής', + SHARE_SALE_CERTIFICATE: 'Μεταφόρτωση βεβαίωσης πώλησης μετοχών', + DONATION_RECEIPTS: 'Μεταφόρτωση αποδείξεων δωρεάς', + WRITTEN_CONFIRMATION: 'Μεταφόρτωση γραπτής επιβεβαίωσης', + GRANT_APPROVAL_LETTER: 'Μεταφόρτωση επιστολής έγκρισης επιχορήγησης', + }, + documentTypes: { + TAX_DOCUMENTS: 'Φορολογική δήλωση', + AUDITED_FINANCIAL_STATEMENTS: 'Ελεγμένες οικονομικές καταστάσεις', + BANK_STATEMENT: 'Κίνηση τραπεζικού λογαριασμού', + E_COMMERCE_STATEMENTS: 'Καταστάσεις ηλεκτρονικού εμπορίου', + INVOICES: 'Τιμολόγια', + CONTRACTS: 'Συμβάσεις', + PERSONAL_TAX_DECLARATION: 'Προσωπική φορολογική δήλωση', + SAVINGS_STATEMENT: 'Κίνηση λογαριασμού ταμιευτηρίου', + PAYSLIP: 'Μισθοδοτική κατάσταση', + PERSONAL_LOAN_AGREEMENT: 'Σύμβαση προσωπικού δανείου', + PERSONAL_INVESTMENT: 'Κατάσταση προσωπικών επενδύσεων', + ASSET_SALE_AGREEMENT: 'Σύμβαση πώλησης περιουσιακών στοιχείων', + LOAN_AGREEMENT: 'Δανειακή σύμβαση', + EQUITY_AGREEMENT: 'Συμφωνία συμμετοχής στο μετοχικό κεφάλαιο', + SUBSCRIPTION_AGREEMENT: 'Συμφωνία εγγραφής', + SHARE_SALE_CERTIFICATE: 'Πιστοποιητικό πώλησης μετοχών', + DONATION_RECEIPTS: 'Αποδείξεις δωρεών', + WRITTEN_CONFIRMATION: 'Γραπτή επιβεβαίωση', + GRANT_APPROVAL_LETTER: 'Επιστολή έγκρισης επιχορήγησης', + }, + }, terms: { title: 'Αποδοχή όρων', subtitle: 'Αποδεχτείτε τους παρακάτω όρους.', @@ -4545,6 +4631,8 @@ ${amount} για ${merchant} - ${date}`, tooManyItems: ({max}: {max: number}) => `Προσθέστε το πολύ ${max}`, itemError: ({item, field, error}: {item: string; field: string; error: string}) => `${item}, ${field}: ${error}`, }, + uploadFile: 'Μεταφόρτωση αρχείου', + selectDocumentToUpload: 'Επιλέξτε έγγραφο για μεταφόρτωση', addItem: ({item}: {item: string}) => `Προσθήκη ${item}`, removeItemTitle: ({item}: {item: string}) => `Αφαίρεση ${item};`, removeItemPrompt: ({name}: {name: string}) => `Θέλετε σίγουρα να αφαιρέσετε ${name};`, diff --git a/src/languages/en.ts b/src/languages/en.ts index bd911a9cc794..1ec9e2d564f3 100644 --- a/src/languages/en.ts +++ b/src/languages/en.ts @@ -733,6 +733,7 @@ const translations = { attachmentImageTooLarge: 'This image is too large to preview before uploading.', imageDimensionsTooLarge: 'Image dimensions are too large to process. Please use a smaller image.', tooManyFiles: (fileLimit: number) => `You can only upload up to ${fileLimit} files at a time.`, + fileAlreadyAdded: 'A file with the same name is already added.', sizeExceededWithValue: (maxUploadSizeInMB: number) => `Files exceeds ${maxUploadSizeInMB} MB. Please try again.`, someFilesCantBeUploaded: "Some files can't be uploaded", sizeLimitExceeded: (maxUploadSizeInMB: number) => `Files must be under ${maxUploadSizeInMB} MB. Any larger files won't be uploaded.`, @@ -3205,6 +3206,90 @@ const translations = { description: 'Business description', descriptionHint: 'Briefly describe what your company does.', }, + sourceOfWealth: { + label: "Where does your company's money come from?", + description: 'Our payments partner needs to verify any sources of wealth. Select all that apply.', + options: { + REVENUE: 'Business revenue', + PERSONAL_FUNDING: 'Personal funding', + BUSINESS_LOAN: 'Business loan', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: 'Funding & shareholder investments', + INVESTMENT_INCOME: 'Investment income', + DONATIONS: 'Donations', + GRANTS: 'Grants', + LEGAL: 'Legal settlement', + }, + }, + sourceOfFunds: { + label: 'Which sources fund your daily operations?', + description: 'Our payments partner needs to know which sources fund your operations. Select all that apply.', + }, + sourceOfWealthProof: { + title: 'Source of wealth documents', + description: 'Upload the required documents for each source listed below.', + hints: { + REVENUE: 'Upload a tax return, audited financial statements, or business bank statements.', + PERSONAL_FUNDING: 'Upload a personal tax declaration, savings or bank statements, or payslips.', + BUSINESS_LOAN: 'Upload a loan agreement and a bank statement.', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: 'Upload an equity agreement, subscription agreement, or share sale certificate, plus a bank statement.', + INVESTMENT_INCOME: 'Upload a personal investment statement, share sale certificate, or asset sale agreement, plus a bank statement.', + DONATIONS: 'Upload a donation receipt, written confirmation, or contract, plus a bank statement.', + GRANTS: 'Upload a grant approval letter, written confirmation, or contract, plus a bank statement.', + LEGAL: 'Upload a contract, written confirmation, or asset sale agreement.', + }, + bankStatementHints: { + REVENUE: 'Must show the revenue received.', + PERSONAL_FUNDING: 'Must show the funds you put in.', + BUSINESS_LOAN: 'Must show the loan funds received.', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: 'Must show the investment funds received.', + INVESTMENT_INCOME: 'Must show the investment income received.', + DONATIONS: 'Must show the donation received.', + GRANTS: 'Must show the grant funds received.', + LEGAL: 'Must show the settlement funds received.', + }, + uploadButtons: { + TAX_DOCUMENTS: 'Upload tax return', + AUDITED_FINANCIAL_STATEMENTS: 'Upload audited financial statements', + BANK_STATEMENT: 'Upload bank statement', + E_COMMERCE_STATEMENTS: 'Upload e-commerce statements', + INVOICES: 'Upload invoices', + CONTRACTS: 'Upload contracts', + PERSONAL_TAX_DECLARATION: 'Upload personal tax declaration', + SAVINGS_STATEMENT: 'Upload savings statement', + PAYSLIP: 'Upload payslip', + PERSONAL_LOAN_AGREEMENT: 'Upload personal loan agreement', + PERSONAL_INVESTMENT: 'Upload personal investment statement', + ASSET_SALE_AGREEMENT: 'Upload asset sale agreement', + LOAN_AGREEMENT: 'Upload loan agreement', + EQUITY_AGREEMENT: 'Upload equity agreement', + SUBSCRIPTION_AGREEMENT: 'Upload subscription agreement', + SHARE_SALE_CERTIFICATE: 'Upload share sale certificate', + DONATION_RECEIPTS: 'Upload donation receipts', + WRITTEN_CONFIRMATION: 'Upload written confirmation', + GRANT_APPROVAL_LETTER: 'Upload grant approval letter', + }, + documentTypes: { + TAX_DOCUMENTS: 'Tax return', + AUDITED_FINANCIAL_STATEMENTS: 'Audited financial statements', + BANK_STATEMENT: 'Bank statement', + E_COMMERCE_STATEMENTS: 'E-commerce statements', + INVOICES: 'Invoices', + CONTRACTS: 'Contracts', + PERSONAL_TAX_DECLARATION: 'Personal tax declaration', + SAVINGS_STATEMENT: 'Savings statement', + PAYSLIP: 'Payslip', + PERSONAL_LOAN_AGREEMENT: 'Personal loan agreement', + PERSONAL_INVESTMENT: 'Personal investment statement', + ASSET_SALE_AGREEMENT: 'Asset sale agreement', + LOAN_AGREEMENT: 'Loan agreement', + EQUITY_AGREEMENT: 'Equity agreement', + SUBSCRIPTION_AGREEMENT: 'Subscription agreement', + SHARE_SALE_CERTIFICATE: 'Share sale certificate', + DONATION_RECEIPTS: 'Donation receipts', + WRITTEN_CONFIRMATION: 'Written confirmation', + GRANT_APPROVAL_LETTER: 'Grant approval letter', + }, + }, terms: { title: 'Accept terms', subtitle: 'Please accept the terms below.', @@ -4704,6 +4789,8 @@ const translations = { tooManyItems: ({max}: {max: number}) => `Add at most ${max}`, itemError: ({item, field, error}: {item: string; field: string; error: string}) => `${item}, ${field}: ${error}`, }, + uploadFile: 'Upload file', + selectDocumentToUpload: 'Select document to upload', addItem: ({item}: {item: string}) => `Add ${item}`, removeItemTitle: ({item}: {item: string}) => `Remove ${item}?`, removeItemPrompt: ({name}: {name: string}) => `Are you sure you want to remove ${name}?`, diff --git a/src/languages/es.ts b/src/languages/es.ts index 070d8c32ca5f..a67c00dfdded 100644 --- a/src/languages/es.ts +++ b/src/languages/es.ts @@ -637,6 +637,7 @@ const translations: TranslationDeepObject = { attachmentImageTooLarge: 'Esta imagen es demasiado grande para obtener una vista previa antes de subirla.', imageDimensionsTooLarge: 'Las dimensiones de la imagen son demasiado grandes para procesar. Por favor, usa una imagen más pequeña.', tooManyFiles: (fileLimit: number) => `Solamente puedes suber ${fileLimit} archivos a la vez.`, + fileAlreadyAdded: 'Ya se añadió un archivo con el mismo nombre.', sizeExceededWithValue: (maxUploadSizeInMB) => `El archivo supera los ${maxUploadSizeInMB} MB. Por favor, vuelve a intentarlo.`, someFilesCantBeUploaded: 'Algunos archivos no se pueden subir', sizeLimitExceeded: (maxUploadSizeInMB) => `Los archivos deben ser menores a ${maxUploadSizeInMB} MB. Los archivos más grandes no se subirán.`, @@ -3123,6 +3124,90 @@ const translations: TranslationDeepObject = { description: 'Descripción de la empresa', descriptionHint: 'Describe brevemente a qué se dedica tu empresa.', }, + sourceOfWealth: { + label: '¿De dónde proviene el dinero de tu empresa?', + description: 'Nuestro socio de pagos necesita verificar todos los orígenes del patrimonio. Selecciona todas las opciones que correspondan.', + options: { + REVENUE: 'Ingresos del negocio', + PERSONAL_FUNDING: 'Financiación personal', + BUSINESS_LOAN: 'Préstamo empresarial', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: 'Financiación e inversiones de accionistas', + INVESTMENT_INCOME: 'Ingresos por inversiones', + DONATIONS: 'Donaciones', + GRANTS: 'Subvenciones', + LEGAL: 'Acuerdo legal', + }, + }, + sourceOfFunds: { + label: '¿Qué fuentes financian tus operaciones diarias?', + description: 'Nuestro socio de pagos necesita saber qué fuentes financian tus operaciones. Selecciona todas las opciones que correspondan.', + }, + sourceOfWealthProof: { + title: 'Documentos del origen del patrimonio', + description: 'Sube los documentos requeridos para cada origen indicado a continuación.', + hints: { + REVENUE: 'Sube una declaración de impuestos, estados financieros auditados o extractos bancarios de la empresa.', + PERSONAL_FUNDING: 'Sube una declaración de impuestos personal, extractos de ahorro o bancarios, o nóminas.', + BUSINESS_LOAN: 'Sube un contrato de préstamo y un extracto bancario.', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: 'Sube un acuerdo de participación, un acuerdo de suscripción o un certificado de venta de acciones, además de un extracto bancario.', + INVESTMENT_INCOME: 'Sube un extracto de inversiones personales, un certificado de venta de acciones o un contrato de venta de activos, además de un extracto bancario.', + DONATIONS: 'Sube un recibo de donación, una confirmación por escrito o un contrato, además de un extracto bancario.', + GRANTS: 'Sube una carta de concesión de la subvención, una confirmación por escrito o un contrato, además de un extracto bancario.', + LEGAL: 'Sube un contrato, una confirmación por escrito o un contrato de venta de activos.', + }, + bankStatementHints: { + REVENUE: 'Debe mostrar los ingresos recibidos.', + PERSONAL_FUNDING: 'Debe mostrar los fondos que aportaste.', + BUSINESS_LOAN: 'Debe mostrar los fondos del préstamo recibidos.', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: 'Debe mostrar los fondos de inversión recibidos.', + INVESTMENT_INCOME: 'Debe mostrar los rendimientos de inversión recibidos.', + DONATIONS: 'Debe mostrar la donación recibida.', + GRANTS: 'Debe mostrar los fondos de la subvención recibidos.', + LEGAL: 'Debe mostrar los fondos del acuerdo recibidos.', + }, + uploadButtons: { + TAX_DOCUMENTS: 'Subir declaración de impuestos', + AUDITED_FINANCIAL_STATEMENTS: 'Subir estados financieros auditados', + BANK_STATEMENT: 'Subir extracto bancario', + E_COMMERCE_STATEMENTS: 'Subir extractos de comercio electrónico', + INVOICES: 'Subir facturas', + CONTRACTS: 'Subir contratos', + PERSONAL_TAX_DECLARATION: 'Subir declaración de impuestos personal', + SAVINGS_STATEMENT: 'Subir extracto de ahorro', + PAYSLIP: 'Subir nómina', + PERSONAL_LOAN_AGREEMENT: 'Subir contrato de préstamo personal', + PERSONAL_INVESTMENT: 'Subir extracto de inversiones personales', + ASSET_SALE_AGREEMENT: 'Subir contrato de venta de activos', + LOAN_AGREEMENT: 'Subir contrato de préstamo', + EQUITY_AGREEMENT: 'Subir acuerdo de participación', + SUBSCRIPTION_AGREEMENT: 'Subir acuerdo de suscripción', + SHARE_SALE_CERTIFICATE: 'Subir certificado de venta de acciones', + DONATION_RECEIPTS: 'Subir recibos de donación', + WRITTEN_CONFIRMATION: 'Subir confirmación por escrito', + GRANT_APPROVAL_LETTER: 'Subir carta de concesión de la subvención', + }, + documentTypes: { + TAX_DOCUMENTS: 'Declaración de impuestos', + AUDITED_FINANCIAL_STATEMENTS: 'Estados financieros auditados', + BANK_STATEMENT: 'Extracto bancario', + E_COMMERCE_STATEMENTS: 'Extractos de comercio electrónico', + INVOICES: 'Facturas', + CONTRACTS: 'Contratos', + PERSONAL_TAX_DECLARATION: 'Declaración de impuestos personal', + SAVINGS_STATEMENT: 'Extracto de ahorros', + PAYSLIP: 'Nómina', + PERSONAL_LOAN_AGREEMENT: 'Contrato de préstamo personal', + PERSONAL_INVESTMENT: 'Extracto de inversiones personales', + ASSET_SALE_AGREEMENT: 'Contrato de venta de activos', + LOAN_AGREEMENT: 'Contrato de préstamo', + EQUITY_AGREEMENT: 'Acuerdo de participación accionarial', + SUBSCRIPTION_AGREEMENT: 'Acuerdo de suscripción', + SHARE_SALE_CERTIFICATE: 'Certificado de venta de acciones', + DONATION_RECEIPTS: 'Recibos de donación', + WRITTEN_CONFIRMATION: 'Confirmación por escrito', + GRANT_APPROVAL_LETTER: 'Carta de aprobación de la subvención', + }, + }, terms: { title: 'Aceptar términos', subtitle: 'Acepta los términos a continuación.', @@ -4471,6 +4556,8 @@ ${amount} para ${merchant} - ${date}`, tooManyItems: ({max}: {max: number}) => `Añade como máximo ${max}`, itemError: ({item, field, error}: {item: string; field: string; error: string}) => `${item}, ${field}: ${error}`, }, + uploadFile: 'Subir archivo', + selectDocumentToUpload: 'Selecciona el documento que quieres subir', addItem: ({item}: {item: string}) => `Añadir ${item}`, removeItemTitle: ({item}: {item: string}) => `¿Eliminar ${item}?`, removeItemPrompt: ({name}: {name: string}) => `¿Seguro que quieres eliminar a ${name}?`, diff --git a/src/languages/fr.ts b/src/languages/fr.ts index becd117838ea..7c2475d1aff1 100644 --- a/src/languages/fr.ts +++ b/src/languages/fr.ts @@ -646,6 +646,7 @@ const translations: TranslationDeepObject = { attachmentImageTooLarge: 'Cette image est trop volumineuse pour être prévisualisée avant le téléversement.', imageDimensionsTooLarge: "Les dimensions de l'image sont trop grandes pour être traitées. Veuillez utiliser une image plus petite.", tooManyFiles: (fileLimit: number) => `Vous pouvez téléverser au maximum ${fileLimit} fichiers à la fois.`, + fileAlreadyAdded: 'Un fichier portant le même nom a déjà été ajouté.', sizeExceededWithValue: (maxUploadSizeInMB: number) => `Les fichiers dépassent ${maxUploadSizeInMB} Mo. Veuillez réessayer.`, someFilesCantBeUploaded: 'Certains fichiers ne peuvent pas être téléversés', sizeLimitExceeded: (maxUploadSizeInMB: number) => `Les fichiers doivent être inférieurs à ${maxUploadSizeInMB} Mo. Les fichiers plus volumineux ne seront pas téléversés.`, @@ -3151,6 +3152,90 @@ const translations: TranslationDeepObject = { description: 'Description de l’entreprise', descriptionHint: 'Décrivez brièvement ce que fait votre entreprise.', }, + sourceOfWealth: { + label: 'D’où provient l’argent de votre entreprise ?', + description: 'Notre partenaire de paiement doit vérifier toutes les origines du patrimoine. Sélectionnez toutes les réponses qui s’appliquent.', + options: { + REVENUE: 'Chiffre d’affaires', + PERSONAL_FUNDING: 'Financement personnel', + BUSINESS_LOAN: 'Prêt professionnel', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: 'Financement et investissements des actionnaires', + INVESTMENT_INCOME: 'Revenus de placements', + DONATIONS: 'Dons', + GRANTS: 'Subventions', + LEGAL: 'Règlement juridique', + }, + }, + sourceOfFunds: { + label: 'Quelles sources financent vos opérations quotidiennes ?', + description: 'Notre partenaire de paiement doit savoir quelles sources financent vos opérations. Sélectionnez toutes les réponses qui s’appliquent.', + }, + sourceOfWealthProof: { + title: 'Justificatifs de l’origine du patrimoine', + description: 'Téléversez les documents requis pour chaque origine indiquée ci-dessous.', + hints: { + REVENUE: 'Importez une déclaration fiscale, des états financiers audités ou des relevés bancaires de l’entreprise.', + PERSONAL_FUNDING: 'Importez une déclaration fiscale personnelle, des relevés d’épargne ou bancaires, ou des fiches de paie.', + BUSINESS_LOAN: 'Importez un contrat de prêt et un relevé bancaire.', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: 'Importez un pacte d’actionnaires, un bulletin de souscription ou un certificat de cession d’actions, ainsi qu’un relevé bancaire.', + INVESTMENT_INCOME: 'Importez un relevé de placements personnels, un certificat de cession d’actions ou un contrat de vente d’actifs, ainsi qu’un relevé bancaire.', + DONATIONS: 'Importez un reçu de don, une confirmation écrite ou un contrat, ainsi qu’un relevé bancaire.', + GRANTS: 'Importez une lettre d’attribution de subvention, une confirmation écrite ou un contrat, ainsi qu’un relevé bancaire.', + LEGAL: 'Importez un contrat, une confirmation écrite ou un contrat de vente d’actifs.', + }, + bankStatementHints: { + REVENUE: 'Doit montrer les revenus reçus.', + PERSONAL_FUNDING: 'Doit montrer les fonds que vous avez apportés.', + BUSINESS_LOAN: 'Doit montrer les fonds du prêt reçus.', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: 'Doit montrer les fonds d’investissement reçus.', + INVESTMENT_INCOME: 'Doit montrer les revenus de placement reçus.', + DONATIONS: 'Doit montrer le don reçu.', + GRANTS: 'Doit montrer les fonds de la subvention reçus.', + LEGAL: 'Doit montrer les fonds du règlement reçus.', + }, + uploadButtons: { + TAX_DOCUMENTS: 'Importer la déclaration fiscale', + AUDITED_FINANCIAL_STATEMENTS: 'Importer les états financiers audités', + BANK_STATEMENT: 'Importer le relevé bancaire', + E_COMMERCE_STATEMENTS: 'Importer les relevés e-commerce', + INVOICES: 'Importer les factures', + CONTRACTS: 'Importer les contrats', + PERSONAL_TAX_DECLARATION: 'Importer la déclaration fiscale personnelle', + SAVINGS_STATEMENT: 'Importer le relevé d’épargne', + PAYSLIP: 'Importer la fiche de paie', + PERSONAL_LOAN_AGREEMENT: 'Importer le contrat de prêt personnel', + PERSONAL_INVESTMENT: 'Importer le relevé de placements personnels', + ASSET_SALE_AGREEMENT: 'Importer le contrat de vente d’actifs', + LOAN_AGREEMENT: 'Importer le contrat de prêt', + EQUITY_AGREEMENT: 'Importer le pacte d’actionnaires', + SUBSCRIPTION_AGREEMENT: 'Importer le bulletin de souscription', + SHARE_SALE_CERTIFICATE: 'Importer le certificat de cession d’actions', + DONATION_RECEIPTS: 'Importer les reçus de dons', + WRITTEN_CONFIRMATION: 'Importer la confirmation écrite', + GRANT_APPROVAL_LETTER: 'Importer la lettre d’attribution de subvention', + }, + documentTypes: { + TAX_DOCUMENTS: 'Déclaration fiscale', + AUDITED_FINANCIAL_STATEMENTS: 'États financiers audités', + BANK_STATEMENT: 'Relevé bancaire', + E_COMMERCE_STATEMENTS: 'Relevés e-commerce', + INVOICES: 'Factures', + CONTRACTS: 'Contrats', + PERSONAL_TAX_DECLARATION: 'Déclaration fiscale personnelle', + SAVINGS_STATEMENT: 'Relevé d’épargne', + PAYSLIP: 'Fiche de paie', + PERSONAL_LOAN_AGREEMENT: 'Contrat de prêt personnel', + PERSONAL_INVESTMENT: 'Relevé de placements personnels', + ASSET_SALE_AGREEMENT: 'Contrat de cession d’actifs', + LOAN_AGREEMENT: 'Contrat de prêt', + EQUITY_AGREEMENT: 'Accord de prise de participation', + SUBSCRIPTION_AGREEMENT: 'Contrat de souscription', + SHARE_SALE_CERTIFICATE: 'Certificat de cession d’actions', + DONATION_RECEIPTS: 'Reçus de dons', + WRITTEN_CONFIRMATION: 'Confirmation écrite', + GRANT_APPROVAL_LETTER: 'Lettre d’attribution de la subvention', + }, + }, terms: { title: 'Accepter les conditions', subtitle: 'Veuillez accepter les conditions ci-dessous.', @@ -4498,6 +4583,8 @@ ${amount} pour ${merchant} - ${date}`, tooManyItems: ({max}: {max: number}) => `Ajoutez au plus ${max}`, itemError: ({item, field, error}: {item: string; field: string; error: string}) => `${item}, ${field} : ${error}`, }, + uploadFile: 'Importer un fichier', + selectDocumentToUpload: 'Sélectionnez le document à importer', addItem: ({item}: {item: string}) => `Ajouter ${item}`, removeItemTitle: ({item}: {item: string}) => `Supprimer ${item} ?`, removeItemPrompt: ({name}: {name: string}) => `Voulez-vous vraiment supprimer ${name} ?`, diff --git a/src/languages/it.ts b/src/languages/it.ts index db053d24c187..0a1db01ed6d8 100644 --- a/src/languages/it.ts +++ b/src/languages/it.ts @@ -646,6 +646,7 @@ const translations: TranslationDeepObject = { attachmentImageTooLarge: 'Questa immagine è troppo grande per essere visualizzata in anteprima prima del caricamento.', imageDimensionsTooLarge: "Le dimensioni dell'immagine sono troppo grandi per essere elaborate. Utilizza un'immagine più piccola.", tooManyFiles: (fileLimit: number) => `Puoi caricare al massimo ${fileLimit} file alla volta.`, + fileAlreadyAdded: 'È già stato aggiunto un file con lo stesso nome.', sizeExceededWithValue: (maxUploadSizeInMB: number) => `I file superano ${maxUploadSizeInMB} MB. Riprova.`, someFilesCantBeUploaded: 'Impossibile caricare alcuni file', sizeLimitExceeded: (maxUploadSizeInMB: number) => `I file devono essere inferiori a ${maxUploadSizeInMB} MB. I file più grandi non verranno caricati.`, @@ -3133,6 +3134,90 @@ const translations: TranslationDeepObject = { description: "Descrizione dell'azienda", descriptionHint: 'Descrivi brevemente di cosa si occupa la tua azienda.', }, + sourceOfWealth: { + label: 'Da dove provengono i fondi della tua azienda?', + description: 'Il nostro partner di pagamento deve verificare tutte le origini del patrimonio. Seleziona tutte le opzioni pertinenti.', + options: { + REVENUE: 'Ricavi aziendali', + PERSONAL_FUNDING: 'Finanziamento personale', + BUSINESS_LOAN: 'Prestito aziendale', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: 'Finanziamenti e investimenti dei soci', + INVESTMENT_INCOME: 'Redditi da investimenti', + DONATIONS: 'Donazioni', + GRANTS: 'Sovvenzioni', + LEGAL: 'Accordo legale', + }, + }, + sourceOfFunds: { + label: 'Quali fonti finanziano le tue attività quotidiane?', + description: 'Il nostro partner di pagamento deve sapere quali fonti finanziano le tue attività. Seleziona tutte le opzioni pertinenti.', + }, + sourceOfWealthProof: { + title: 'Documenti sull’origine del patrimonio', + description: 'Carica i documenti richiesti per ciascuna origine indicata di seguito.', + hints: { + REVENUE: 'Carica una dichiarazione dei redditi, un bilancio certificato o gli estratti conto aziendali.', + PERSONAL_FUNDING: 'Carica una dichiarazione dei redditi personale, estratti di risparmio o bancari, o buste paga.', + BUSINESS_LOAN: 'Carica un contratto di finanziamento e un estratto conto.', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: 'Carica un accordo di partecipazione, un accordo di sottoscrizione o un certificato di vendita di azioni, più un estratto conto.', + INVESTMENT_INCOME: 'Carica un estratto degli investimenti personali, un certificato di vendita di azioni o un contratto di vendita di beni, più un estratto conto.', + DONATIONS: 'Carica una ricevuta di donazione, una conferma scritta o un contratto, più un estratto conto.', + GRANTS: 'Carica una lettera di concessione del contributo, una conferma scritta o un contratto, più un estratto conto.', + LEGAL: 'Carica un contratto, una conferma scritta o un contratto di vendita di beni.', + }, + bankStatementHints: { + REVENUE: 'Deve mostrare i ricavi ricevuti.', + PERSONAL_FUNDING: 'Deve mostrare i fondi che hai versato.', + BUSINESS_LOAN: 'Deve mostrare i fondi del finanziamento ricevuti.', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: 'Deve mostrare i fondi dell’investimento ricevuti.', + INVESTMENT_INCOME: 'Deve mostrare i redditi da investimento ricevuti.', + DONATIONS: 'Deve mostrare la donazione ricevuta.', + GRANTS: 'Deve mostrare i fondi del contributo ricevuti.', + LEGAL: 'Deve mostrare i fondi della transazione ricevuti.', + }, + uploadButtons: { + TAX_DOCUMENTS: 'Carica dichiarazione dei redditi', + AUDITED_FINANCIAL_STATEMENTS: 'Carica bilancio certificato', + BANK_STATEMENT: 'Carica estratto conto', + E_COMMERCE_STATEMENTS: 'Carica estratti e-commerce', + INVOICES: 'Carica fatture', + CONTRACTS: 'Carica contratti', + PERSONAL_TAX_DECLARATION: 'Carica dichiarazione dei redditi personale', + SAVINGS_STATEMENT: 'Carica estratto del conto di risparmio', + PAYSLIP: 'Carica busta paga', + PERSONAL_LOAN_AGREEMENT: 'Carica contratto di prestito personale', + PERSONAL_INVESTMENT: 'Carica estratto degli investimenti personali', + ASSET_SALE_AGREEMENT: 'Carica contratto di vendita di beni', + LOAN_AGREEMENT: 'Carica contratto di finanziamento', + EQUITY_AGREEMENT: 'Carica accordo di partecipazione', + SUBSCRIPTION_AGREEMENT: 'Carica accordo di sottoscrizione', + SHARE_SALE_CERTIFICATE: 'Carica certificato di vendita di azioni', + DONATION_RECEIPTS: 'Carica ricevute di donazione', + WRITTEN_CONFIRMATION: 'Carica conferma scritta', + GRANT_APPROVAL_LETTER: 'Carica lettera di concessione del contributo', + }, + documentTypes: { + TAX_DOCUMENTS: 'Dichiarazione dei redditi', + AUDITED_FINANCIAL_STATEMENTS: 'Bilancio certificato', + BANK_STATEMENT: 'Estratto conto bancario', + E_COMMERCE_STATEMENTS: 'Estratti conto e-commerce', + INVOICES: 'Fatture', + CONTRACTS: 'Contratti', + PERSONAL_TAX_DECLARATION: 'Dichiarazione dei redditi personale', + SAVINGS_STATEMENT: 'Estratto conto di risparmio', + PAYSLIP: 'Busta paga', + PERSONAL_LOAN_AGREEMENT: 'Contratto di prestito personale', + PERSONAL_INVESTMENT: 'Estratto degli investimenti personali', + ASSET_SALE_AGREEMENT: 'Contratto di vendita di beni', + LOAN_AGREEMENT: 'Contratto di prestito', + EQUITY_AGREEMENT: 'Accordo di partecipazione', + SUBSCRIPTION_AGREEMENT: 'Accordo di sottoscrizione', + SHARE_SALE_CERTIFICATE: 'Certificato di vendita di azioni', + DONATION_RECEIPTS: 'Ricevute delle donazioni', + WRITTEN_CONFIRMATION: 'Conferma scritta', + GRANT_APPROVAL_LETTER: 'Lettera di approvazione della sovvenzione', + }, + }, terms: { title: 'Accetta i termini', subtitle: 'Accetta i termini riportati di seguito.', @@ -4467,6 +4552,8 @@ ${amount} per ${merchant} - ${date}`, tooManyItems: ({max}: {max: number}) => `Aggiungi al massimo ${max}`, itemError: ({item, field, error}: {item: string; field: string; error: string}) => `${item}, ${field}: ${error}`, }, + uploadFile: 'Carica file', + selectDocumentToUpload: 'Seleziona il documento da caricare', addItem: ({item}: {item: string}) => `Aggiungi ${item}`, removeItemTitle: ({item}: {item: string}) => `Rimuovere ${item}?`, removeItemPrompt: ({name}: {name: string}) => `Vuoi davvero rimuovere ${name}?`, diff --git a/src/languages/ja.ts b/src/languages/ja.ts index b57a803e944a..8495bb64f717 100644 --- a/src/languages/ja.ts +++ b/src/languages/ja.ts @@ -648,6 +648,7 @@ const translations: TranslationDeepObject = { attachmentImageTooLarge: 'この画像は大きすぎるため、アップロード前にプレビューできません。', imageDimensionsTooLarge: '画像のサイズが大きすぎて処理できません。小さい画像を使用してください。', tooManyFiles: (fileLimit: number) => `一度にアップロードできるファイルは最大${fileLimit}件までです。`, + fileAlreadyAdded: '同じ名前のファイルがすでに追加されています。', sizeExceededWithValue: (maxUploadSizeInMB: number) => `ファイルが ${maxUploadSizeInMB} MB を超えています。もう一度お試しください。`, someFilesCantBeUploaded: '一部のファイルをアップロードできません', sizeLimitExceeded: (maxUploadSizeInMB: number) => `ファイルサイズは${maxUploadSizeInMB}MB以下である必要があります。これより大きいファイルはアップロードされません。`, @@ -3110,6 +3111,90 @@ const translations: TranslationDeepObject = { description: '事業内容', descriptionHint: '会社の事業内容を簡単に説明してください。', }, + sourceOfWealth: { + label: '会社の資金はどこから来ていますか?', + description: '決済パートナーがすべての資産の出所を確認する必要があります。該当するものをすべて選択してください。', + options: { + REVENUE: '事業収益', + PERSONAL_FUNDING: '個人資金', + BUSINESS_LOAN: '事業融資', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: '資金調達・株主からの投資', + INVESTMENT_INCOME: '投資収益', + DONATIONS: '寄付', + GRANTS: '助成金', + LEGAL: '法的和解', + }, + }, + sourceOfFunds: { + label: '日々の事業運営の資金源はどれですか?', + description: '決済パートナーは、事業運営の資金源を把握する必要があります。該当するものをすべて選択してください。', + }, + sourceOfWealthProof: { + title: '資産の出所に関する書類', + description: '以下の各資金源について、必要な書類をアップロードしてください。', + hints: { + REVENUE: '税務申告書、監査済み財務諸表、または事業用口座の銀行取引明細書をアップロードしてください。', + PERSONAL_FUNDING: '個人の確定申告書、預金明細書または銀行取引明細書、あるいは給与明細をアップロードしてください。', + BUSINESS_LOAN: 'ローン契約書と銀行取引明細書をアップロードしてください。', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: '出資契約書、株式引受契約書、または株式売却証明書に加えて、銀行取引明細書をアップロードしてください。', + INVESTMENT_INCOME: '個人投資の明細書、株式売却証明書、または資産売却契約書に加えて、銀行取引明細書をアップロードしてください。', + DONATIONS: '寄付の領収書、書面による確認書、または契約書に加えて、銀行取引明細書をアップロードしてください。', + GRANTS: '助成金の交付決定通知書、書面による確認書、または契約書に加えて、銀行取引明細書をアップロードしてください。', + LEGAL: '契約書、書面による確認書、または資産売却契約書をアップロードしてください。', + }, + bankStatementHints: { + REVENUE: '収益の受領がわかるものが必要です。', + PERSONAL_FUNDING: '拠出した資金がわかるものが必要です。', + BUSINESS_LOAN: 'ローン資金の受領がわかるものが必要です。', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: '投資資金の受領がわかるものが必要です。', + INVESTMENT_INCOME: '投資収益の受領がわかるものが必要です。', + DONATIONS: '寄付の受領がわかるものが必要です。', + GRANTS: '助成金の受領がわかるものが必要です。', + LEGAL: '和解金の受領がわかるものが必要です。', + }, + uploadButtons: { + TAX_DOCUMENTS: '税務申告書をアップロード', + AUDITED_FINANCIAL_STATEMENTS: '監査済み財務諸表をアップロード', + BANK_STATEMENT: '銀行取引明細書をアップロード', + E_COMMERCE_STATEMENTS: 'Eコマースの明細書をアップロード', + INVOICES: '請求書をアップロード', + CONTRACTS: '契約書をアップロード', + PERSONAL_TAX_DECLARATION: '個人の確定申告書をアップロード', + SAVINGS_STATEMENT: '預金明細書をアップロード', + PAYSLIP: '給与明細をアップロード', + PERSONAL_LOAN_AGREEMENT: '個人ローン契約書をアップロード', + PERSONAL_INVESTMENT: '個人投資の明細書をアップロード', + ASSET_SALE_AGREEMENT: '資産売却契約書をアップロード', + LOAN_AGREEMENT: 'ローン契約書をアップロード', + EQUITY_AGREEMENT: '出資契約書をアップロード', + SUBSCRIPTION_AGREEMENT: '株式引受契約書をアップロード', + SHARE_SALE_CERTIFICATE: '株式売却証明書をアップロード', + DONATION_RECEIPTS: '寄付の領収書をアップロード', + WRITTEN_CONFIRMATION: '書面による確認書をアップロード', + GRANT_APPROVAL_LETTER: '助成金の交付決定通知書をアップロード', + }, + documentTypes: { + TAX_DOCUMENTS: '税務申告書', + AUDITED_FINANCIAL_STATEMENTS: '監査済み財務諸表', + BANK_STATEMENT: '銀行取引明細書', + E_COMMERCE_STATEMENTS: 'Eコマースの明細書', + INVOICES: '請求書', + CONTRACTS: '契約書', + PERSONAL_TAX_DECLARATION: '個人の確定申告書', + SAVINGS_STATEMENT: '預金明細書', + PAYSLIP: '給与明細', + PERSONAL_LOAN_AGREEMENT: '個人ローン契約書', + PERSONAL_INVESTMENT: '個人投資の明細書', + ASSET_SALE_AGREEMENT: '資産売却契約書', + LOAN_AGREEMENT: 'ローン契約書', + EQUITY_AGREEMENT: '出資契約書', + SUBSCRIPTION_AGREEMENT: '株式引受契約書', + SHARE_SALE_CERTIFICATE: '株式売却証明書', + DONATION_RECEIPTS: '寄付の領収書', + WRITTEN_CONFIRMATION: '書面による確認書', + GRANT_APPROVAL_LETTER: '助成金の交付決定通知書', + }, + }, terms: { title: '規約に同意', subtitle: '以下の規約に同意してください。', @@ -4422,6 +4507,8 @@ ${integrationName === CONST.ONBOARDING_ACCOUNTING_MAPPING.other ? 'あなたの' tooManyItems: ({max}: {max: number}) => `${max}件以内で追加してください`, itemError: ({item, field, error}: {item: string; field: string; error: string}) => `${item}、${field}:${error}`, }, + uploadFile: 'ファイルをアップロード', + selectDocumentToUpload: 'アップロードする書類を選択', addItem: ({item}: {item: string}) => `${item}を追加`, removeItemTitle: ({item}: {item: string}) => `${item}を削除しますか?`, removeItemPrompt: ({name}: {name: string}) => `本当に${name}を削除しますか?`, diff --git a/src/languages/nl.ts b/src/languages/nl.ts index 22e4b4962132..1422804c3c3a 100644 --- a/src/languages/nl.ts +++ b/src/languages/nl.ts @@ -646,6 +646,7 @@ const translations: TranslationDeepObject = { attachmentImageTooLarge: 'Deze afbeelding is te groot om een voorbeeld te tonen vóór het uploaden.', imageDimensionsTooLarge: 'De afmetingen van de afbeelding zijn te groot om te verwerken. Gebruik een kleinere afbeelding.', tooManyFiles: (fileLimit: number) => `Je kunt maximaal ${fileLimit} bestanden tegelijk uploaden.`, + fileAlreadyAdded: 'Er is al een bestand met dezelfde naam toegevoegd.', sizeExceededWithValue: (maxUploadSizeInMB: number) => `Bestanden zijn groter dan ${maxUploadSizeInMB} MB. Probeer het opnieuw.`, someFilesCantBeUploaded: 'Sommige bestanden kunnen niet worden geüpload', sizeLimitExceeded: (maxUploadSizeInMB: number) => `Bestanden moeten kleiner zijn dan ${maxUploadSizeInMB} MB. Grotere bestanden worden niet geüpload.`, @@ -3133,6 +3134,90 @@ const translations: TranslationDeepObject = { description: 'Bedrijfsomschrijving', descriptionHint: 'Beschrijf kort wat je bedrijf doet.', }, + sourceOfWealth: { + label: 'Waar komt het geld van je bedrijf vandaan?', + description: 'Onze betaalpartner moet alle herkomst van het vermogen controleren. Selecteer alles wat van toepassing is.', + options: { + REVENUE: 'Bedrijfsomzet', + PERSONAL_FUNDING: 'Eigen financiering', + BUSINESS_LOAN: 'Zakelijke lening', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: 'Financiering en investeringen van aandeelhouders', + INVESTMENT_INCOME: 'Beleggingsinkomsten', + DONATIONS: 'Donaties', + GRANTS: 'Subsidies', + LEGAL: 'Juridische schikking', + }, + }, + sourceOfFunds: { + label: 'Welke bronnen financieren je dagelijkse bedrijfsvoering?', + description: 'Onze betaalpartner moet weten welke bronnen je bedrijfsvoering financieren. Selecteer alles wat van toepassing is.', + }, + sourceOfWealthProof: { + title: 'Documenten over de herkomst van het vermogen', + description: 'Upload de vereiste documenten voor elke herkomst die hieronder staat.', + hints: { + REVENUE: 'Upload een belastingaangifte, een gecontroleerde jaarrekening of zakelijke bankafschriften.', + PERSONAL_FUNDING: 'Upload een persoonlijke belastingaangifte, spaar- of bankafschriften, of loonstroken.', + BUSINESS_LOAN: 'Upload een leningsovereenkomst en een bankafschrift.', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: 'Upload een participatieovereenkomst, inschrijvingsovereenkomst of bewijs van aandelenverkoop, plus een bankafschrift.', + INVESTMENT_INCOME: 'Upload een overzicht van persoonlijke beleggingen, een bewijs van aandelenverkoop of een koopovereenkomst voor activa, plus een bankafschrift.', + DONATIONS: 'Upload een donatiebewijs, schriftelijke bevestiging of overeenkomst, plus een bankafschrift.', + GRANTS: 'Upload een toekenningsbrief voor de subsidie, schriftelijke bevestiging of overeenkomst, plus een bankafschrift.', + LEGAL: 'Upload een overeenkomst, schriftelijke bevestiging of koopovereenkomst voor activa.', + }, + bankStatementHints: { + REVENUE: 'Moet de ontvangen omzet tonen.', + PERSONAL_FUNDING: 'Moet het geld tonen dat je hebt ingebracht.', + BUSINESS_LOAN: 'Moet het ontvangen geleende geld tonen.', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: 'Moet het ontvangen investeringsgeld tonen.', + INVESTMENT_INCOME: 'Moet de ontvangen beleggingsinkomsten tonen.', + DONATIONS: 'Moet de ontvangen donatie tonen.', + GRANTS: 'Moet het ontvangen subsidiegeld tonen.', + LEGAL: 'Moet het ontvangen schikkingsbedrag tonen.', + }, + uploadButtons: { + TAX_DOCUMENTS: 'Belastingaangifte uploaden', + AUDITED_FINANCIAL_STATEMENTS: 'Gecontroleerde jaarrekening uploaden', + BANK_STATEMENT: 'Bankafschrift uploaden', + E_COMMERCE_STATEMENTS: 'E-commerceoverzichten uploaden', + INVOICES: 'Facturen uploaden', + CONTRACTS: 'Contracten uploaden', + PERSONAL_TAX_DECLARATION: 'Persoonlijke belastingaangifte uploaden', + SAVINGS_STATEMENT: 'Spaarafschrift uploaden', + PAYSLIP: 'Loonstrook uploaden', + PERSONAL_LOAN_AGREEMENT: 'Persoonlijke leningsovereenkomst uploaden', + PERSONAL_INVESTMENT: 'Overzicht van persoonlijke beleggingen uploaden', + ASSET_SALE_AGREEMENT: 'Koopovereenkomst voor activa uploaden', + LOAN_AGREEMENT: 'Leningsovereenkomst uploaden', + EQUITY_AGREEMENT: 'Participatieovereenkomst uploaden', + SUBSCRIPTION_AGREEMENT: 'Inschrijvingsovereenkomst uploaden', + SHARE_SALE_CERTIFICATE: 'Bewijs van aandelenverkoop uploaden', + DONATION_RECEIPTS: 'Donatiebewijzen uploaden', + WRITTEN_CONFIRMATION: 'Schriftelijke bevestiging uploaden', + GRANT_APPROVAL_LETTER: 'Toekenningsbrief voor subsidie uploaden', + }, + documentTypes: { + TAX_DOCUMENTS: 'Belastingaangifte', + AUDITED_FINANCIAL_STATEMENTS: 'Gecontroleerde jaarrekening', + BANK_STATEMENT: 'Bankafschrift', + E_COMMERCE_STATEMENTS: 'E-commerce-overzichten', + INVOICES: 'Facturen', + CONTRACTS: 'Contracten', + PERSONAL_TAX_DECLARATION: 'Persoonlijke belastingaangifte', + SAVINGS_STATEMENT: 'Spaarafschrift', + PAYSLIP: 'Loonstrook', + PERSONAL_LOAN_AGREEMENT: 'Persoonlijke leningsovereenkomst', + PERSONAL_INVESTMENT: 'Persoonlijk beleggingsoverzicht', + ASSET_SALE_AGREEMENT: 'Overeenkomst voor verkoop van activa', + LOAN_AGREEMENT: 'Leningsovereenkomst', + EQUITY_AGREEMENT: 'Aandelenovereenkomst', + SUBSCRIPTION_AGREEMENT: 'Inschrijvingsovereenkomst', + SHARE_SALE_CERTIFICATE: 'Certificaat van aandelenverkoop', + DONATION_RECEIPTS: 'Donatiebewijzen', + WRITTEN_CONFIRMATION: 'Schriftelijke bevestiging', + GRANT_APPROVAL_LETTER: 'Subsidiebeschikking', + }, + }, terms: { title: 'Voorwaarden accepteren', subtitle: 'Accepteer de onderstaande voorwaarden.', @@ -4465,6 +4550,8 @@ ${amount} voor ${merchant} - ${date}`, tooManyItems: ({max}: {max: number}) => `Voeg er maximaal ${max} toe`, itemError: ({item, field, error}: {item: string; field: string; error: string}) => `${item}, ${field}: ${error}`, }, + uploadFile: 'Bestand uploaden', + selectDocumentToUpload: 'Selecteer het document om te uploaden', addItem: ({item}: {item: string}) => `${item} toevoegen`, removeItemTitle: ({item}: {item: string}) => `${item} verwijderen?`, removeItemPrompt: ({name}: {name: string}) => `Weet je zeker dat je ${name} wilt verwijderen?`, diff --git a/src/languages/pl.ts b/src/languages/pl.ts index cac95c689b36..eef4948f8bd0 100644 --- a/src/languages/pl.ts +++ b/src/languages/pl.ts @@ -651,6 +651,7 @@ const translations: TranslationDeepObject = { attachmentImageTooLarge: 'Ten obraz jest zbyt duży, aby wyświetlić podgląd przed przesłaniem.', imageDimensionsTooLarge: 'Wymiary obrazu są zbyt duże do przetworzenia. Użyj mniejszego obrazu.', tooManyFiles: (fileLimit: number) => `Możesz jednorazowo przesłać maksymalnie ${fileLimit} plików.`, + fileAlreadyAdded: 'Plik o takiej samej nazwie jest już dodany.', sizeExceededWithValue: (maxUploadSizeInMB: number) => `Plik przekracza ${maxUploadSizeInMB} MB. Spróbuj ponownie.`, someFilesCantBeUploaded: 'Niektórych plików nie można przesłać', sizeLimitExceeded: (maxUploadSizeInMB: number) => `Pliki muszą mieć mniej niż ${maxUploadSizeInMB} MB. Większe pliki nie zostaną przesłane.`, @@ -3175,6 +3176,90 @@ const translations: TranslationDeepObject = { description: 'Opis działalności', descriptionHint: 'Krótko opisz, czym zajmuje się Twoja firma.', }, + sourceOfWealth: { + label: 'Skąd pochodzą pieniądze Twojej firmy?', + description: 'Nasz partner płatniczy musi zweryfikować wszystkie źródła majątku. Zaznacz wszystkie pasujące odpowiedzi.', + options: { + REVENUE: 'Przychody firmy', + PERSONAL_FUNDING: 'Środki własne', + BUSINESS_LOAN: 'Kredyt firmowy', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: 'Finansowanie i inwestycje udziałowców', + INVESTMENT_INCOME: 'Dochody z inwestycji', + DONATIONS: 'Darowizny', + GRANTS: 'Dotacje', + LEGAL: 'Ugoda sądowa', + }, + }, + sourceOfFunds: { + label: 'Które źródła finansują codzienną działalność firmy?', + description: 'Nasz partner płatniczy musi wiedzieć, które źródła finansują działalność Twojej firmy. Zaznacz wszystkie pasujące odpowiedzi.', + }, + sourceOfWealthProof: { + title: 'Dokumenty potwierdzające źródło majątku', + description: 'Prześlij wymagane dokumenty dla każdego źródła wymienionego poniżej.', + hints: { + REVENUE: 'Prześlij zeznanie podatkowe, zbadane sprawozdanie finansowe lub firmowe wyciągi bankowe.', + PERSONAL_FUNDING: 'Prześlij osobiste zeznanie podatkowe, wyciągi z konta oszczędnościowego lub bankowego albo odcinki wypłaty.', + BUSINESS_LOAN: 'Prześlij umowę kredytową i wyciąg bankowy.', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: 'Prześlij umowę inwestycyjną, umowę objęcia udziałów lub potwierdzenie sprzedaży udziałów, a do tego wyciąg bankowy.', + INVESTMENT_INCOME: 'Prześlij zestawienie inwestycji osobistych, potwierdzenie sprzedaży udziałów lub umowę sprzedaży aktywów, a do tego wyciąg bankowy.', + DONATIONS: 'Prześlij potwierdzenie darowizny, pisemne potwierdzenie lub umowę, a do tego wyciąg bankowy.', + GRANTS: 'Prześlij decyzję o przyznaniu dotacji, pisemne potwierdzenie lub umowę, a do tego wyciąg bankowy.', + LEGAL: 'Prześlij umowę, pisemne potwierdzenie lub umowę sprzedaży aktywów.', + }, + bankStatementHints: { + REVENUE: 'Musi pokazywać otrzymane przychody.', + PERSONAL_FUNDING: 'Musi pokazywać wniesione przez Ciebie środki.', + BUSINESS_LOAN: 'Musi pokazywać otrzymane środki z kredytu.', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: 'Musi pokazywać otrzymane środki z inwestycji.', + INVESTMENT_INCOME: 'Musi pokazywać otrzymane dochody z inwestycji.', + DONATIONS: 'Musi pokazywać otrzymaną darowiznę.', + GRANTS: 'Musi pokazywać otrzymane środki z dotacji.', + LEGAL: 'Musi pokazywać otrzymane środki z ugody.', + }, + uploadButtons: { + TAX_DOCUMENTS: 'Prześlij zeznanie podatkowe', + AUDITED_FINANCIAL_STATEMENTS: 'Prześlij zbadane sprawozdanie finansowe', + BANK_STATEMENT: 'Prześlij wyciąg bankowy', + E_COMMERCE_STATEMENTS: 'Prześlij zestawienia e-commerce', + INVOICES: 'Prześlij faktury', + CONTRACTS: 'Prześlij umowy', + PERSONAL_TAX_DECLARATION: 'Prześlij osobiste zeznanie podatkowe', + SAVINGS_STATEMENT: 'Prześlij wyciąg z konta oszczędnościowego', + PAYSLIP: 'Prześlij odcinek wypłaty', + PERSONAL_LOAN_AGREEMENT: 'Prześlij umowę pożyczki osobistej', + PERSONAL_INVESTMENT: 'Prześlij zestawienie inwestycji osobistych', + ASSET_SALE_AGREEMENT: 'Prześlij umowę sprzedaży aktywów', + LOAN_AGREEMENT: 'Prześlij umowę kredytową', + EQUITY_AGREEMENT: 'Prześlij umowę inwestycyjną', + SUBSCRIPTION_AGREEMENT: 'Prześlij umowę objęcia udziałów', + SHARE_SALE_CERTIFICATE: 'Prześlij potwierdzenie sprzedaży udziałów', + DONATION_RECEIPTS: 'Prześlij potwierdzenia darowizn', + WRITTEN_CONFIRMATION: 'Prześlij pisemne potwierdzenie', + GRANT_APPROVAL_LETTER: 'Prześlij decyzję o przyznaniu dotacji', + }, + documentTypes: { + TAX_DOCUMENTS: 'Zeznanie podatkowe', + AUDITED_FINANCIAL_STATEMENTS: 'Zbadane sprawozdanie finansowe', + BANK_STATEMENT: 'Wyciąg bankowy', + E_COMMERCE_STATEMENTS: 'Zestawienia z e-commerce', + INVOICES: 'Faktury', + CONTRACTS: 'Umowy', + PERSONAL_TAX_DECLARATION: 'Osobiste zeznanie podatkowe', + SAVINGS_STATEMENT: 'Wyciąg z konta oszczędnościowego', + PAYSLIP: 'Odcinek wypłaty', + PERSONAL_LOAN_AGREEMENT: 'Umowa pożyczki osobistej', + PERSONAL_INVESTMENT: 'Zestawienie inwestycji osobistych', + ASSET_SALE_AGREEMENT: 'Umowa sprzedaży aktywów', + LOAN_AGREEMENT: 'Umowa kredytowa', + EQUITY_AGREEMENT: 'Umowa inwestycyjna', + SUBSCRIPTION_AGREEMENT: 'Umowa objęcia udziałów', + SHARE_SALE_CERTIFICATE: 'Potwierdzenie sprzedaży udziałów', + DONATION_RECEIPTS: 'Potwierdzenia darowizn', + WRITTEN_CONFIRMATION: 'Pisemne potwierdzenie', + GRANT_APPROVAL_LETTER: 'Decyzja o przyznaniu dotacji', + }, + }, terms: { title: 'Akceptacja warunków', subtitle: 'Zaakceptuj poniższe warunki.', @@ -4506,6 +4591,8 @@ ${amount} dla ${merchant} - ${date}`, tooManyItems: ({max}: {max: number}) => `Dodaj maksymalnie ${max}`, itemError: ({item, field, error}: {item: string; field: string; error: string}) => `${item}, ${field}: ${error}`, }, + uploadFile: 'Prześlij plik', + selectDocumentToUpload: 'Wybierz dokument do przesłania', addItem: ({item}: {item: string}) => `Dodaj ${item}`, removeItemTitle: ({item}: {item: string}) => `Usunąć ${item}?`, removeItemPrompt: ({name}: {name: string}) => `Czy na pewno chcesz usunąć ${name}?`, diff --git a/src/languages/pt-BR.ts b/src/languages/pt-BR.ts index ac9baa4a280d..c4bcf9296d6a 100644 --- a/src/languages/pt-BR.ts +++ b/src/languages/pt-BR.ts @@ -645,6 +645,7 @@ const translations: TranslationDeepObject = { attachmentImageTooLarge: 'Esta imagem é grande demais para ser visualizada antes do envio.', imageDimensionsTooLarge: 'As dimensões da imagem são muito grandes para processar. Por favor, use uma imagem menor.', tooManyFiles: (fileLimit: number) => `Você só pode enviar até ${fileLimit} arquivos por vez.`, + fileAlreadyAdded: 'Um arquivo com o mesmo nome já foi adicionado.', sizeExceededWithValue: (maxUploadSizeInMB: number) => `Os arquivos excedem ${maxUploadSizeInMB} MB. Tente novamente.`, someFilesCantBeUploaded: 'Alguns arquivos não podem ser enviados', sizeLimitExceeded: (maxUploadSizeInMB: number) => `Os arquivos devem ter menos de ${maxUploadSizeInMB} MB. Qualquer arquivo maior não será enviado.`, @@ -3137,6 +3138,90 @@ const translations: TranslationDeepObject = { description: 'Descrição da empresa', descriptionHint: 'Descreva brevemente o que sua empresa faz.', }, + sourceOfWealth: { + label: 'De onde vem o dinheiro da sua empresa?', + description: 'Nosso parceiro de pagamentos precisa verificar todas as origens do patrimônio. Selecione todas as opções que se aplicam.', + options: { + REVENUE: 'Receita do negócio', + PERSONAL_FUNDING: 'Recursos próprios', + BUSINESS_LOAN: 'Empréstimo empresarial', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: 'Captação e investimentos de sócios', + INVESTMENT_INCOME: 'Rendimentos de investimentos', + DONATIONS: 'Doações', + GRANTS: 'Subsídios', + LEGAL: 'Acordo judicial', + }, + }, + sourceOfFunds: { + label: 'Quais fontes financiam as operações diárias da sua empresa?', + description: 'Nosso parceiro de pagamentos precisa saber quais fontes financiam as suas operações. Selecione todas as opções que se aplicam.', + }, + sourceOfWealthProof: { + title: 'Documentos da origem do patrimônio', + description: 'Envie os documentos exigidos para cada origem listada abaixo.', + hints: { + REVENUE: 'Envie uma declaração de imposto de renda, demonstrações financeiras auditadas ou extratos bancários da empresa.', + PERSONAL_FUNDING: 'Envie uma declaração de imposto de renda pessoal, extratos de poupança ou bancários, ou holerites.', + BUSINESS_LOAN: 'Envie um contrato de empréstimo e um extrato bancário.', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: 'Envie um acordo de participação, um contrato de subscrição ou um certificado de venda de ações, além de um extrato bancário.', + INVESTMENT_INCOME: 'Envie um extrato de investimentos pessoais, um certificado de venda de ações ou um contrato de venda de ativos, além de um extrato bancário.', + DONATIONS: 'Envie um recibo de doação, uma confirmação por escrito ou um contrato, além de um extrato bancário.', + GRANTS: 'Envie uma carta de concessão do subsídio, uma confirmação por escrito ou um contrato, além de um extrato bancário.', + LEGAL: 'Envie um contrato, uma confirmação por escrito ou um contrato de venda de ativos.', + }, + bankStatementHints: { + REVENUE: 'Deve mostrar a receita recebida.', + PERSONAL_FUNDING: 'Deve mostrar os fundos que você aportou.', + BUSINESS_LOAN: 'Deve mostrar os fundos do empréstimo recebidos.', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: 'Deve mostrar os fundos do investimento recebidos.', + INVESTMENT_INCOME: 'Deve mostrar os rendimentos de investimento recebidos.', + DONATIONS: 'Deve mostrar a doação recebida.', + GRANTS: 'Deve mostrar os fundos do subsídio recebidos.', + LEGAL: 'Deve mostrar os fundos do acordo recebidos.', + }, + uploadButtons: { + TAX_DOCUMENTS: 'Enviar declaração de imposto de renda', + AUDITED_FINANCIAL_STATEMENTS: 'Enviar demonstrações financeiras auditadas', + BANK_STATEMENT: 'Enviar extrato bancário', + E_COMMERCE_STATEMENTS: 'Enviar extratos de e-commerce', + INVOICES: 'Enviar faturas', + CONTRACTS: 'Enviar contratos', + PERSONAL_TAX_DECLARATION: 'Enviar declaração de imposto de renda pessoal', + SAVINGS_STATEMENT: 'Enviar extrato de poupança', + PAYSLIP: 'Enviar holerite', + PERSONAL_LOAN_AGREEMENT: 'Enviar contrato de empréstimo pessoal', + PERSONAL_INVESTMENT: 'Enviar extrato de investimentos pessoais', + ASSET_SALE_AGREEMENT: 'Enviar contrato de venda de ativos', + LOAN_AGREEMENT: 'Enviar contrato de empréstimo', + EQUITY_AGREEMENT: 'Enviar acordo de participação', + SUBSCRIPTION_AGREEMENT: 'Enviar contrato de subscrição', + SHARE_SALE_CERTIFICATE: 'Enviar certificado de venda de ações', + DONATION_RECEIPTS: 'Enviar recibos de doação', + WRITTEN_CONFIRMATION: 'Enviar confirmação por escrito', + GRANT_APPROVAL_LETTER: 'Enviar carta de concessão do subsídio', + }, + documentTypes: { + TAX_DOCUMENTS: 'Declaração de imposto de renda', + AUDITED_FINANCIAL_STATEMENTS: 'Demonstrações financeiras auditadas', + BANK_STATEMENT: 'Extrato bancário', + E_COMMERCE_STATEMENTS: 'Extratos de e-commerce', + INVOICES: 'Faturas', + CONTRACTS: 'Contratos', + PERSONAL_TAX_DECLARATION: 'Declaração de imposto de renda pessoal', + SAVINGS_STATEMENT: 'Extrato de poupança', + PAYSLIP: 'Holerite', + PERSONAL_LOAN_AGREEMENT: 'Contrato de empréstimo pessoal', + PERSONAL_INVESTMENT: 'Extrato de investimentos pessoais', + ASSET_SALE_AGREEMENT: 'Contrato de venda de ativos', + LOAN_AGREEMENT: 'Contrato de empréstimo', + EQUITY_AGREEMENT: 'Acordo de participação societária', + SUBSCRIPTION_AGREEMENT: 'Contrato de subscrição', + SHARE_SALE_CERTIFICATE: 'Certificado de venda de ações', + DONATION_RECEIPTS: 'Recibos de doação', + WRITTEN_CONFIRMATION: 'Confirmação por escrito', + GRANT_APPROVAL_LETTER: 'Carta de aprovação do subsídio', + }, + }, terms: { title: 'Aceitar termos', subtitle: 'Aceite os termos abaixo.', @@ -4466,6 +4551,8 @@ ${amount} para ${merchant} - ${date}`, tooManyItems: ({max}: {max: number}) => `Adicione no máximo ${max}`, itemError: ({item, field, error}: {item: string; field: string; error: string}) => `${item}, ${field}: ${error}`, }, + uploadFile: 'Enviar arquivo', + selectDocumentToUpload: 'Selecione o documento para enviar', addItem: ({item}: {item: string}) => `Adicionar ${item}`, removeItemTitle: ({item}: {item: string}) => `Remover ${item}?`, removeItemPrompt: ({name}: {name: string}) => `Tem certeza de que deseja remover ${name}?`, diff --git a/src/languages/zh-hans.ts b/src/languages/zh-hans.ts index a5f94b430fb6..34b7d56e11b7 100644 --- a/src/languages/zh-hans.ts +++ b/src/languages/zh-hans.ts @@ -643,6 +643,7 @@ const translations: TranslationDeepObject = { attachmentImageTooLarge: '此图片过大,无法在上传前预览。', imageDimensionsTooLarge: '图片尺寸过大,无法处理。请使用较小的图片。', tooManyFiles: (fileLimit: number) => `您一次最多只能上传 ${fileLimit} 个文件。`, + fileAlreadyAdded: '已添加同名文件。', sizeExceededWithValue: (maxUploadSizeInMB: number) => `文件超过 ${maxUploadSizeInMB} MB。请重试。`, someFilesCantBeUploaded: '某些文件无法上传', sizeLimitExceeded: (maxUploadSizeInMB: number) => `文件大小必须小于 ${maxUploadSizeInMB} MB。更大的文件将不会被上传。`, @@ -3023,6 +3024,90 @@ const translations: TranslationDeepObject = { description: '企业描述', descriptionHint: '简要描述贵公司的业务。', }, + sourceOfWealth: { + label: '贵公司的资金来自哪里?', + description: '我们的支付合作伙伴需要核实所有财富来源。请选择所有适用项。', + options: { + REVENUE: '业务收入', + PERSONAL_FUNDING: '个人资金', + BUSINESS_LOAN: '商业贷款', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: '融资和股东投资', + INVESTMENT_INCOME: '投资收益', + DONATIONS: '捐赠', + GRANTS: '补助金', + LEGAL: '法律和解', + }, + }, + sourceOfFunds: { + label: '哪些来源为您的日常运营提供资金?', + description: '我们的支付合作伙伴需要了解哪些来源为您的运营提供资金。请选择所有适用项。', + }, + sourceOfWealthProof: { + title: '财富来源证明文件', + description: '请为下方列出的每项资金来源上传所需文件。', + hints: { + REVENUE: '请上传纳税申报表、经审计的财务报表或企业银行对账单。', + PERSONAL_FUNDING: '请上传个人纳税申报表、储蓄或银行对账单,或工资单。', + BUSINESS_LOAN: '请上传贷款协议和银行对账单。', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: '请上传股权协议、认购协议或股份出售证明,以及银行对账单。', + INVESTMENT_INCOME: '请上传个人投资对账单、股份出售证明或资产出售协议,以及银行对账单。', + DONATIONS: '请上传捐赠收据、书面确认或合同,以及银行对账单。', + GRANTS: '请上传资助批准函、书面确认或合同,以及银行对账单。', + LEGAL: '请上传合同、书面确认或资产出售协议。', + }, + bankStatementHints: { + REVENUE: '必须显示已收到的收入。', + PERSONAL_FUNDING: '必须显示您投入的资金。', + BUSINESS_LOAN: '必须显示已收到的贷款资金。', + FUNDING_AND_SHAREHOLDER_INVESTMENTS: '必须显示已收到的投资资金。', + INVESTMENT_INCOME: '必须显示已收到的投资收益。', + DONATIONS: '必须显示已收到的捐赠。', + GRANTS: '必须显示已收到的资助资金。', + LEGAL: '必须显示已收到的和解资金。', + }, + uploadButtons: { + TAX_DOCUMENTS: '上传纳税申报表', + AUDITED_FINANCIAL_STATEMENTS: '上传经审计的财务报表', + BANK_STATEMENT: '上传银行对账单', + E_COMMERCE_STATEMENTS: '上传电商对账单', + INVOICES: '上传发票', + CONTRACTS: '上传合同', + PERSONAL_TAX_DECLARATION: '上传个人纳税申报表', + SAVINGS_STATEMENT: '上传储蓄对账单', + PAYSLIP: '上传工资单', + PERSONAL_LOAN_AGREEMENT: '上传个人贷款协议', + PERSONAL_INVESTMENT: '上传个人投资对账单', + ASSET_SALE_AGREEMENT: '上传资产出售协议', + LOAN_AGREEMENT: '上传贷款协议', + EQUITY_AGREEMENT: '上传股权协议', + SUBSCRIPTION_AGREEMENT: '上传认购协议', + SHARE_SALE_CERTIFICATE: '上传股份出售证明', + DONATION_RECEIPTS: '上传捐赠收据', + WRITTEN_CONFIRMATION: '上传书面确认', + GRANT_APPROVAL_LETTER: '上传资助批准函', + }, + documentTypes: { + TAX_DOCUMENTS: '纳税申报表', + AUDITED_FINANCIAL_STATEMENTS: '经审计的财务报表', + BANK_STATEMENT: '银行对账单', + E_COMMERCE_STATEMENTS: '电商对账单', + INVOICES: '发票', + CONTRACTS: '合同', + PERSONAL_TAX_DECLARATION: '个人纳税申报表', + SAVINGS_STATEMENT: '储蓄对账单', + PAYSLIP: '工资单', + PERSONAL_LOAN_AGREEMENT: '个人贷款协议', + PERSONAL_INVESTMENT: '个人投资对账单', + ASSET_SALE_AGREEMENT: '资产出售协议', + LOAN_AGREEMENT: '贷款协议', + EQUITY_AGREEMENT: '股权协议', + SUBSCRIPTION_AGREEMENT: '认购协议', + SHARE_SALE_CERTIFICATE: '股份出售证明', + DONATION_RECEIPTS: '捐赠收据', + WRITTEN_CONFIRMATION: '书面确认', + GRANT_APPROVAL_LETTER: '补助金批准函', + }, + }, terms: { title: '接受条款', subtitle: '请接受以下条款。', @@ -4314,6 +4399,8 @@ ${amount},商户:${merchant} - 日期:${date}`, tooManyItems: ({max}: {max: number}) => `最多添加 ${max} 项`, itemError: ({item, field, error}: {item: string; field: string; error: string}) => `${item}、${field}:${error}`, }, + uploadFile: '上传文件', + selectDocumentToUpload: '选择要上传的文件', addItem: ({item}: {item: string}) => `添加${item}`, removeItemTitle: ({item}: {item: string}) => `移除${item}?`, removeItemPrompt: ({name}: {name: string}) => `确定要移除${name}吗?`, diff --git a/src/libs/API/parameters/UpdateWiseOnboardingAdditionalDataParams.ts b/src/libs/API/parameters/UpdateWiseOnboardingAdditionalDataParams.ts index a9cc1189679d..c86282a15aac 100644 --- a/src/libs/API/parameters/UpdateWiseOnboardingAdditionalDataParams.ts +++ b/src/libs/API/parameters/UpdateWiseOnboardingAdditionalDataParams.ts @@ -9,7 +9,10 @@ type UpdateWiseOnboardingAdditionalDataParams = { /** The onboarding page the answers belong to. The server answers any other step with 400 Invalid step. */ step: ValueOf; - /** JSON of the page's answers under flat keys, such as `address.city`. It holds a typed SSN, so it is redacted from the logs. */ + /** + * JSON of the page's answers under flat keys, such as `address.city`. It holds a typed SSN, so it is redacted from the logs. + * A page whose only answers are files sends `{}`, since the server rejects `[]` as "Inputs is not a valid json object". + */ inputs: string; /** JSON of the uploaded file keys the user kept, by field. Left out, the step's files stay as they are. */ diff --git a/src/libs/actions/WiseOnboarding.ts b/src/libs/actions/WiseOnboarding.ts index fe8bc4c57499..0ec168832763 100644 --- a/src/libs/actions/WiseOnboarding.ts +++ b/src/libs/actions/WiseOnboarding.ts @@ -41,7 +41,13 @@ function getOnyxData(step: string, saveID: string): OnyxData).savedFileKey === 'string'; } -/** A draft entry for a file the server holds, named after the last part of its key */ +/** The server names a stored file `----` */ +const SAVED_FILE_NAME_PATTERN = /^\d+-\d+-\d{8}_\d{6}-[0-9a-f]{13}-(.+)$/; + +/** A draft entry for a file the server holds, named as the user named it, or after the last part of its key when the key has another shape */ function toSavedFile(savedFileKey: string): WiseSavedFile { + const storedName = savedFileKey.split('/').at(-1) ?? savedFileKey; return { - name: savedFileKey.split('/').at(-1) ?? savedFileKey, + name: SAVED_FILE_NAME_PATTERN.exec(storedName)?.[1] ?? storedName, uri: savedFileKey, savedFileKey, }; } +/** Separates a labelled file field's key from the file type in the key the server stores its files under */ +const FILE_TYPE_SEPARATOR = '-'; + +/** The key the server stores a labelled file field's files of one type under, such as `proofFile-REVENUE-TAX_DOCUMENTS` */ +function getLabelledFileKey(fieldKey: string, fileType: string): string { + return `${fieldKey}${FILE_TYPE_SEPARATOR}${fileType}`; +} + +/** The answers with the files the server holds under one key: a plain field's list, or the entry of one type of a labelled field, which an empty list removes */ +function withSavedFiles(answers: DynamicFormValues, fileKey: string, savedFileKeys: string[]): DynamicFormValues { + const separatorIndex = fileKey.lastIndexOf(FILE_TYPE_SEPARATOR); + if (separatorIndex === -1) { + return {...answers, [fileKey]: savedFileKeys.map(toSavedFile)}; + } + const fieldKey = fileKey.slice(0, separatorIndex); + const fileType = fileKey.slice(separatorIndex + 1); + const otherEntries = getListItems(answers[fieldKey]).filter((entry) => entry.fileType !== fileType); + return {...answers, [fieldKey]: savedFileKeys.length > 0 ? [...otherEntries, {id: fileType, fileType, files: savedFileKeys.map(toSavedFile)}] : otherEntries}; +} + /** * Every file field the server holds files for on the given pages, as draft entries. A field it emptied comes back as an empty list. * The skipped pages are left out, so the local files of a page whose save failed stay in the draft for the next save. */ function getSavedFileAnswers(documents: Record | null> | undefined, skippedPageKeys: string[] = []): DynamicFormValues { - const answers: DynamicFormValues = {}; + let answers: DynamicFormValues = {}; for (const [pageKey, pageDocuments] of Object.entries(documents ?? {})) { if (skippedPageKeys.includes(pageKey)) { continue; } - for (const [fieldKey, fileKeys] of Object.entries(pageDocuments ?? {})) { - if (fileKeys) { - answers[fieldKey] = fileKeys.map(toSavedFile); + for (const [fileKey, savedFileKeys] of Object.entries(pageDocuments ?? {})) { + if (savedFileKeys) { + answers = withSavedFiles(answers, fileKey, savedFileKeys); } } } @@ -54,14 +81,76 @@ function isWiseOnboardingStep(key: string): key is WiseOnboardingStep { return WISE_ONBOARDING_STEPS.has(key); } +function getStrings(answer: unknown): string[] { + if (!Array.isArray(answer)) { + return []; + } + const items: unknown[] = answer; + return items.filter((item): item is string => typeof item === 'string'); +} + +/** The entries of a `sourceOfWealthList` the server stores, ignoring anything malformed */ +function getSourceOfWealthEntries(sourceOfWealthList: unknown): WiseSourceOfWealthEntry[] { + if (!Array.isArray(sourceOfWealthList)) { + return []; + } + const entries: unknown[] = sourceOfWealthList; + return entries.flatMap((entry) => { + if (typeof entry !== 'object' || entry === null || !('businessSourceOfWealthInfo' in entry) || typeof entry.businessSourceOfWealthInfo !== 'string') { + return []; + } + const isSourceOfFund = 'isSourceOfFund' in entry && typeof entry.isSourceOfFund === 'boolean' ? entry.isSourceOfFund : undefined; + return [ + isSourceOfFund === undefined ? {businessSourceOfWealthInfo: entry.businessSourceOfWealthInfo} : {businessSourceOfWealthInfo: entry.businessSourceOfWealthInfo, isSourceOfFund}, + ]; + }); +} + +/** + * The page's inputs as Wise takes them. Both source of wealth pages save Wise's whole `sourceOfWealthList`, since the server replaces the saved page on every save, + * and every entry says whether the source funds daily operations, since Submit needs it for each one. A lone source funds them. + */ +function toWiseInputs(step: WiseOnboardingStep, inputs: DynamicFormValues): Record { + if (step !== CONST.WISE.ONBOARDING_STEP.BUSINESS_SOURCE_OF_WEALTH_INFO) { + return inputs; + } + const {[CONST.WISE.SOURCE_OF_WEALTH_INFO_KEY]: sources, [CONST.WISE.SOURCE_OF_FUNDS_KEY]: fundingSources, ...otherInputs} = inputs; + const pickedSources = getStrings(sources); + const sourceOfWealthList: WiseSourceOfWealthEntry[] = pickedSources.map((source) => ({ + businessSourceOfWealthInfo: source, + isSourceOfFund: pickedSources.length === 1 || getStrings(fundingSources).includes(source), + })); + return {...otherInputs, [CONST.WISE.SOURCE_OF_WEALTH_LIST_KEY]: sourceOfWealthList}; +} + function getFiles(answer: DynamicFormValues[string]): FileObject[] { return Array.isArray(answer) ? answer.filter((item): item is FileObject => typeof item === 'object' && item !== null) : []; } +/** A page's files by the key the server stores them under. A labelled field lists every type it offers, so a type the user emptied is emptied on the server too. */ +function getFilesByKey(page: DynamicFormPage, answers: DynamicFormValues): Map { + const filesByKey = new Map(); + for (const field of getContentFields(page.content).filter(isSupportedField)) { + if (field.type !== 'file') { + continue; + } + if (!field.uploads) { + filesByKey.set(field.key, getFiles(answers[field.key])); + continue; + } + const entries = getListItems(answers[field.key]); + for (const {key: fileType} of field.uploads.flatMap((upload) => upload.fileTypes)) { + const entry = entries.find((candidate) => candidate.fileType === fileType); + filesByKey.set(getLabelledFileKey(field.key, fileType), entry ? getListItemFiles(entry) : []); + } + } + return filesByKey; +} + /** * The parameters of one `UpdateWiseOnboardingAdditionalData` call for a page the user left with Next. - * Files the server holds are listed in `documents`, new ones are sent as `[]`, and the rest of the answers go in `inputs`. - * Every file field of the page is listed in `documents`, so a file the user removed, or a field the answers now hide, is removed on the server too. + * Files the server holds are listed in `documents`, new ones are sent as `[]`, and the rest of the answers go in `inputs`. A labelled field's files go under `-`. + * Every file key of the page is listed in `documents`, so a file the user removed, or a field the answers now hide, is removed on the server too. * A page whose key is not a step the server accepts gets nothing, since the server would answer it with 400 Invalid step. */ function getWiseOnboardingPageParams(bankAccountID: number, page: DynamicFormPage, answers: DynamicFormValues): UpdateWiseOnboardingAdditionalDataParams | undefined { @@ -78,14 +167,13 @@ function getWiseOnboardingPageParams(bankAccountID: number, page: DynamicFormPag const documents: Record = {}; const newFiles: Record<`${string}[${number}]`, FileObject> = {}; - for (const fieldKey of fileFieldKeys) { - const files = getFiles(answers[fieldKey]); - documents[fieldKey] = files.filter(isSavedFile).map((file) => file.savedFileKey); + for (const [fileKey, files] of getFilesByKey(page, answers)) { + documents[fileKey] = files.filter(isSavedFile).map((file) => file.savedFileKey); const localFiles = files.filter((file) => !isSavedFile(file)); // An entry that cannot be uploaded would reach the server as "[object Object]", so it is left out. It was never on the server, so nothing is lost there. const uploadableFiles = localFiles.filter((file) => isFileUploadable(file)); for (const [index, file] of uploadableFiles.entries()) { - newFiles[`${fieldKey}[${index}]`] = file; + newFiles[`${fileKey}[${index}]`] = file; } } for (const [key, answer] of Object.entries(answers)) { @@ -97,11 +185,12 @@ function getWiseOnboardingPageParams(bankAccountID: number, page: DynamicFormPag return { bankAccountID, step, - inputs: JSON.stringify(inputs), + // The server rejects `[]` as "Inputs is not a valid json object", while `{}` reads as no answers + inputs: Object.keys(inputs).length > 0 ? JSON.stringify(toWiseInputs(step, inputs)) : '{}', ...(fileFieldKeys.size > 0 ? {documents: JSON.stringify(documents)} : {}), ...newFiles, }; } export default getWiseOnboardingPageParams; -export {getSavedFileAnswers, toSavedFile}; +export {getFiles, getLabelledFileKey, getSavedFileAnswers, getSourceOfWealthEntries, isSavedFile, toSavedFile, withSavedFiles}; diff --git a/src/pages/settings/Wallet/EnableGlobalReimbursements/Wise/WiseBusinessOnboardingPage.tsx b/src/pages/settings/Wallet/EnableGlobalReimbursements/Wise/WiseBusinessOnboardingPage.tsx index 4f8e3fa80321..4bb89a928c88 100644 --- a/src/pages/settings/Wallet/EnableGlobalReimbursements/Wise/WiseBusinessOnboardingPage.tsx +++ b/src/pages/settings/Wallet/EnableGlobalReimbursements/Wise/WiseBusinessOnboardingPage.tsx @@ -1,5 +1,8 @@ import FullPageOfflineBlockingView from '@components/BlockingViews/FullPageOfflineBlockingView'; import DynamicFormFlow from '@components/DynamicForm'; +import type {DynamicFormValues} from '@components/DynamicForm/types'; +import {getVisibleContent} from '@components/DynamicForm/utils/getVisibleFields'; +import {getAllFields, getPages} from '@components/DynamicForm/utils/paginate'; import toDynamicFormValues from '@components/DynamicForm/utils/toDynamicFormValues'; import FullScreenLoadingIndicator from '@components/FullscreenLoadingIndicator'; import Header from '@components/Header'; @@ -13,7 +16,7 @@ import usePermissions from '@hooks/usePermissions'; import useWiseOnboardingSaveStatus from '@hooks/useWiseOnboardingSaveStatus'; import {isBankAccountEligibleForGlobalReimbursements, isWiseOnboardingSubmitted} from '@libs/BankAccountUtils'; -import {getSavedFileAnswers} from '@libs/getWiseOnboardingPageParams'; +import {getSavedFileAnswers, getSourceOfWealthEntries} from '@libs/getWiseOnboardingPageParams'; import createDynamicRoute from '@libs/Navigation/helpers/dynamicRoutesUtils/createDynamicRoute'; import {isWiseGlobalReimbursementsIntroPath} from '@libs/Navigation/helpers/enableGlobalReimbursementsNavigationUtils'; import type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavigation/types'; @@ -32,7 +35,7 @@ import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import {DYNAMIC_ROUTES} from '@src/ROUTES'; import type SCREENS from '@src/SCREENS'; -import type {ReimbursementAccount} from '@src/types/onyx'; +import type {DynamicFormPage, ReimbursementAccount} from '@src/types/onyx'; import isLoadingOnyxValue from '@src/types/utils/isLoadingOnyxValue'; import type {OnyxEntry} from 'react-native-onyx'; @@ -41,8 +44,10 @@ import {deepEqual} from 'fast-equals'; import pick from 'lodash/pick'; import React, {useEffect, useEffectEvent, useState} from 'react'; -import US from './forms/US'; +import {getKeptSourceOfFunds, SOURCE_OF_FUNDS_PAGE_KEY} from './forms/requirements/sourceOfFunds'; import getWiseBusinessOnboardingPrefill, {getMissingPrefill, WISE_BUSINESS_ACCOUNT_KEYS} from './getWiseBusinessOnboardingPrefill'; +import getWiseOnboardingForm, {getFieldOverNewFileLimit, getFirstUnansweredRequirementPageKey, getOnboardingStep, getRoutePageKey} from './getWiseOnboardingForm'; +import {getStringList} from './kycRequirementAttributes'; type WiseBusinessOnboardingPageProps = PlatformStackScreenProps; @@ -197,6 +202,81 @@ function WiseBusinessOnboardingPage({route}: WiseBusinessOnboardingPageProps) { saveDraftAnswers(ONYXKEYS.FORMS.WISE_BUSINESS_ONBOARDING_FORM, missingPrefill); }, [isPrefillPending, missingPrefill]); + // The business page's save returns the requirements Expensify collects before Submit, such as enhanced due diligence for a high-risk industry + const isBusinessAccountForThisBank = businessAccount?.data?.bankAccountID === bankAccountID; + const kycRequirements = isBusinessAccountForThisBank ? businessAccount?.data?.wise?.kycRequirements : undefined; + + // A reload or a direct link on one of the pages skips the visit's read, so this bank account's requirements are read without holding up the flow + const shouldReadRequirements = isPrefillDone && !isNewVisit && !isOffline && !isBusinessAccountForThisBank; + useEffect(() => { + if (!shouldReadRequirements) { + return; + } + openReimbursementAccountPage({bankAccountID}); + }, [shouldReadRequirements, bankAccountID]); + + const draftValues = toDynamicFormValues(draft); + const form = getWiseOnboardingForm(kycRequirements, draftValues); + + /** + * Saves a page to Wise as the user leaves it. The two source of wealth pages save one step, which the server replaces whole, so the daily operations page sends the picked sources too. + * Changing the picked sources drops the daily operations answers of the sources no longer picked, and the documents page leaves out the files of a source no longer picked. + */ + const savePage = (page: DynamicFormPage, answers: DynamicFormValues, sensitiveAnswers: DynamicFormValues) => { + const step = getOnboardingStep(form, page.key); + let stepAnswers = answers; + let stepPage: DynamicFormPage = {...page, key: step}; + if (step === CONST.WISE.ONBOARDING_STEP.BUSINESS_SOURCE_OF_WEALTH_PROOF) { + stepPage = {...stepPage, content: getVisibleContent(page.content, {...draftValues, ...answers}, getAllFields(getPages(form)))}; + } else if (step === CONST.WISE.ONBOARDING_STEP.BUSINESS_SOURCE_OF_WEALTH_INFO) { + if (CONST.WISE.SOURCE_OF_FUNDS_KEY in answers) { + saveDraftAnswers(ONYXKEYS.FORMS.WISE_BUSINESS_ONBOARDING_FORM, {[CONST.WISE.SOURCE_OF_FUNDS_REVIEW_KEY]: false}); + stepAnswers = {...answers, [CONST.WISE.SOURCE_OF_WEALTH_INFO_KEY]: draftValues[CONST.WISE.SOURCE_OF_WEALTH_INFO_KEY]}; + } else { + // Editing from the confirmation page skips the daily operations page, so the sources page sends the kept answers, and a new source does not fund them until that page says so + const pickedSources = getStringList(answers[CONST.WISE.SOURCE_OF_WEALTH_INFO_KEY]); + const sourceOfFunds = getKeptSourceOfFunds(pickedSources, draftValues[CONST.WISE.SOURCE_OF_FUNDS_KEY]); + // A newly picked source can fund daily operations too, so the confirmation page asks the daily operations page again. A lone source's answer was filled in, + // not picked, so a second source leaves that page empty. The saved sources tell which were picked before, since the sources input drafts each pick as it is made. + const savedSourcesPage = isBusinessAccountForThisBank ? businessAccount?.data?.wise?.pages?.[CONST.WISE.KYC_REQUIREMENT.BUSINESS_SOURCE_OF_WEALTH_INFO] : undefined; + const savedSources = getSourceOfWealthEntries(savedSourcesPage?.[CONST.WISE.SOURCE_OF_WEALTH_LIST_KEY]).map((entry) => entry.businessSourceOfWealthInfo); + const isFirstChoiceOfFunds = savedSources.length <= 1 && pickedSources.length > 1; + const hasNewSource = pickedSources.length > 1 && pickedSources.some((source) => !savedSources.includes(source)); + saveDraftAnswers(ONYXKEYS.FORMS.WISE_BUSINESS_ONBOARDING_FORM, { + [CONST.WISE.SOURCE_OF_FUNDS_KEY]: isFirstChoiceOfFunds ? [] : sourceOfFunds, + [CONST.WISE.SOURCE_OF_FUNDS_REVIEW_KEY]: hasNewSource, + }); + stepAnswers = {...answers, [CONST.WISE.SOURCE_OF_FUNDS_KEY]: sourceOfFunds}; + } + } + saveWiseOnboardingPage(bankAccountID, stepPage, stepAnswers, sensitiveAnswers); + }; + // The server drops the files past its cap without an error, so a page asks for fewer before it saves + const validatePage = (page: DynamicFormPage, values: DynamicFormValues) => { + const fieldKey = getFieldOverNewFileLimit(form, page, values); + return fieldKey ? {[fieldKey]: translate('attachmentPicker.tooManyFiles', CONST.WISE.MAX_NEW_FILES_PER_SAVE)} : {}; + }; + const buildRoute = (pageName: string, action?: 'edit') => createDynamicRoute(DYNAMIC_ROUTES.WISE_BUSINESS_ONBOARDING.getRoute(pageName, action), introPath); + + // Next on the business page reaches the confirmation page before its save returns, so a requirement that arrives later takes the user to its page. + // A newly picked source takes the user to the daily operations page, with the answers kept so far. + const sourceOfFundsReviewPageKey = draftValues[CONST.WISE.SOURCE_OF_FUNDS_REVIEW_KEY] === true ? getRoutePageKey(form, SOURCE_OF_FUNDS_PAGE_KEY) : undefined; + const unansweredRequirementPageKey = + isPrefillDone && route.params.subPage === CONST.DYNAMIC_FORM.CONFIRMATION_PAGE_KEY + ? (sourceOfFundsReviewPageKey ?? getFirstUnansweredRequirementPageKey(form, draftValues)) + : undefined; + useEffect(() => { + if (!unansweredRequirementPageKey) { + return; + } + Navigation.navigate(buildRoute(unansweredRequirementPageKey), {forceReplace: true}); + }, [unansweredRequirementPageKey, buildRoute]); + + // The business page's save can add or remove requirement pages, so every page after it shows a spinner until the save returns and until the user is moved to a new page + const subPage = route.params.subPage; + const isAfterBusinessPage = !!subPage && subPage !== CONST.WISE.ONBOARDING_STEP.REPRESENTATIVE && subPage !== CONST.WISE.ONBOARDING_STEP.BUSINESS; + const isWaitingForRequirements = isAfterBusinessPage && ((isSaving && unsavedPageKeys.includes(CONST.WISE.ONBOARDING_STEP.BUSINESS)) || !!unansweredRequirementPageKey); + if (isWaitingForConnection) { return ( @@ -219,24 +299,26 @@ function WiseBusinessOnboardingPage({route}: WiseBusinessOnboardingPageProps) { return ( createDynamicRoute(DYNAMIC_ROUTES.WISE_BUSINESS_ONBOARDING.getRoute(pageName, action), introPath)} + buildRoute={buildRoute} shouldReplaceRoute onBack={goBackToIntro} // Each page is saved to Wise as the user leaves it, so a later visit resumes from what the server holds - onPageSubmit={(page, answers, sensitiveAnswers) => saveWiseOnboardingPage(bankAccountID, page, answers, sensitiveAnswers)} + onPageSubmit={savePage} + validatePage={validatePage} // No page saves offline, so a typed SSN never waits for a connection and a later visit never resumes from a save the server has not seen shouldDisableNextWhenOffline submitError={saveError} // Confirm waits while a page is saving, and a visit after a page did not save opens on that page isSavingPages={isSaving} unsavedPageKeys={unsavedPageKeys} + isLoading={isWaitingForRequirements} // The terms page comes after the confirmation page, so the SSN stays in memory until the terms page is done with it isSubmitting={false} onSubmit={() => { diff --git a/src/pages/settings/Wallet/EnableGlobalReimbursements/Wise/forms/US.ts b/src/pages/settings/Wallet/EnableGlobalReimbursements/Wise/forms/US.ts index 7c9916012941..f41aeee61019 100644 --- a/src/pages/settings/Wallet/EnableGlobalReimbursements/Wise/forms/US.ts +++ b/src/pages/settings/Wallet/EnableGlobalReimbursements/Wise/forms/US.ts @@ -101,8 +101,8 @@ const businessPage: DynamicFormPage = { }; /** The US business onboarding form. Each page's key names the onboarding step its answers belong to. */ -const US: DynamicFormSchema = { +const US = { pages: [representativePage, businessPage], -}; +} satisfies DynamicFormSchema; export default US; diff --git a/src/pages/settings/Wallet/EnableGlobalReimbursements/Wise/forms/requirements/sourceOfFunds.ts b/src/pages/settings/Wallet/EnableGlobalReimbursements/Wise/forms/requirements/sourceOfFunds.ts new file mode 100644 index 000000000000..2914b1e333a5 --- /dev/null +++ b/src/pages/settings/Wallet/EnableGlobalReimbursements/Wise/forms/requirements/sourceOfFunds.ts @@ -0,0 +1,43 @@ +import type {DynamicFormValues} from '@components/DynamicForm/types'; + +import {getAnsweredSources, getStringList} from '@pages/settings/Wallet/EnableGlobalReimbursements/Wise/kycRequirementAttributes'; + +import CONST from '@src/CONST'; +import type {DynamicFormPage} from '@src/types/onyx'; +import type {WiseKYCRequirement} from '@src/types/onyx/WiseKYCReview'; + +/** The daily operations page's key. It saves under the BUSINESS_SOURCE_OF_WEALTH_INFO step with the sources page. */ +const SOURCE_OF_FUNDS_PAGE_KEY = 'BUSINESS_SOURCE_OF_FUNDS'; + +/** Which of the picked sources fund the business's daily operations. A lone source funds them, so the page asks only when several are picked. */ +function getSourceOfFundsPage(attributes: WiseKYCRequirement['attributes'], answers: DynamicFormValues): DynamicFormPage { + const pickedSources = getAnsweredSources(attributes, answers[CONST.WISE.SOURCE_OF_WEALTH_INFO_KEY]); + return { + key: SOURCE_OF_FUNDS_PAGE_KEY, + descriptionKey: 'walletPage.wiseOnboarding.sourceOfFunds.description', + content: + pickedSources.length > 1 + ? [ + { + key: CONST.WISE.SOURCE_OF_FUNDS_KEY, + type: 'multiselect', + required: true, + labelKey: 'walletPage.wiseOnboarding.sourceOfFunds.label', + values: pickedSources.map((key) => ({key, labelKey: `walletPage.wiseOnboarding.sourceOfWealth.options.${key}` as const})), + }, + ] + : [], + }; +} + +/** The daily operations answer that still holds once the picked sources change: the sources it named that are still picked, or the lone picked source */ +function getKeptSourceOfFunds(pickedSources: unknown, sourceOfFunds: unknown): string[] { + const sources = getStringList(pickedSources); + if (sources.length === 1) { + return sources; + } + return getStringList(sourceOfFunds).filter((source) => sources.includes(source)); +} + +export default getSourceOfFundsPage; +export {getKeptSourceOfFunds, SOURCE_OF_FUNDS_PAGE_KEY}; diff --git a/src/pages/settings/Wallet/EnableGlobalReimbursements/Wise/forms/requirements/sourceOfWealthInfo.ts b/src/pages/settings/Wallet/EnableGlobalReimbursements/Wise/forms/requirements/sourceOfWealthInfo.ts new file mode 100644 index 000000000000..dd8b3fb6ef6a --- /dev/null +++ b/src/pages/settings/Wallet/EnableGlobalReimbursements/Wise/forms/requirements/sourceOfWealthInfo.ts @@ -0,0 +1,24 @@ +import {getAcceptedSources} from '@pages/settings/Wallet/EnableGlobalReimbursements/Wise/kycRequirementAttributes'; + +import CONST from '@src/CONST'; +import type {DynamicFormPage} from '@src/types/onyx'; +import type {WiseKYCRequirement} from '@src/types/onyx/WiseKYCReview'; + +/** Where the company's money comes from, out of the sources Wise accepts */ +function getSourceOfWealthInfoPage(attributes: WiseKYCRequirement['attributes']): DynamicFormPage { + return { + key: CONST.WISE.KYC_REQUIREMENT.BUSINESS_SOURCE_OF_WEALTH_INFO, + descriptionKey: 'walletPage.wiseOnboarding.sourceOfWealth.description', + content: [ + { + key: CONST.WISE.SOURCE_OF_WEALTH_INFO_KEY, + type: 'multiselect', + required: true, + labelKey: 'walletPage.wiseOnboarding.sourceOfWealth.label', + values: getAcceptedSources(attributes).map((key) => ({key, labelKey: `walletPage.wiseOnboarding.sourceOfWealth.options.${key}` as const})), + }, + ], + }; +} + +export default getSourceOfWealthInfoPage; diff --git a/src/pages/settings/Wallet/EnableGlobalReimbursements/Wise/forms/requirements/sourceOfWealthProof.ts b/src/pages/settings/Wallet/EnableGlobalReimbursements/Wise/forms/requirements/sourceOfWealthProof.ts new file mode 100644 index 000000000000..f658d9f482ae --- /dev/null +++ b/src/pages/settings/Wallet/EnableGlobalReimbursements/Wise/forms/requirements/sourceOfWealthProof.ts @@ -0,0 +1,84 @@ +import type {SourceOfWealth} from '@pages/settings/Wallet/EnableGlobalReimbursements/Wise/kycRequirementAttributes'; +import {getAcceptedDocumentTypes, getAcceptedSources, getSourcesNeedingBankStatement} from '@pages/settings/Wallet/EnableGlobalReimbursements/Wise/kycRequirementAttributes'; + +import CONST from '@src/CONST'; +import type {DynamicFormContentItem, DynamicFormFieldOption, DynamicFormFileUpload, DynamicFormPage} from '@src/types/onyx'; +import type {WiseKYCRequirement} from '@src/types/onyx/WiseKYCReview'; + +import type {ValueOf} from 'type-fest'; + +type SourceOfWealthDocumentType = ValueOf; + +const KNOWN_DOCUMENT_TYPES = new Set(Object.values(CONST.WISE.SOURCE_OF_WEALTH_DOCUMENT_TYPE)); + +function isKnownDocumentType(documentType: string): documentType is SourceOfWealthDocumentType { + return KNOWN_DOCUMENT_TYPES.has(documentType); +} + +/** A document type the App has no name for keeps Wise's key as its label, so the user can still pick it */ +function getDocumentTypeOption(documentType: string): DynamicFormFieldOption { + if (!isKnownDocumentType(documentType)) { + return {key: documentType, label: documentType}; + } + return {key: documentType, labelKey: `walletPage.wiseOnboarding.sourceOfWealthProof.documentTypes.${documentType}`}; +} + +/** An upload button for the given document types. A button for one type is named after it. */ +function getUpload(documentTypes: string[]): DynamicFormFileUpload { + const [onlyType] = documentTypes; + return { + fileTypes: documentTypes.map(getDocumentTypeOption), + ...(documentTypes.length === 1 && onlyType && isKnownDocumentType(onlyType) ? {labelKey: `walletPage.wiseOnboarding.sourceOfWealthProof.uploadButtons.${onlyType}` as const} : {}), + }; +} + +/** A source's upload buttons: one for the documents to pick from, and one for the bank statement when the source needs it besides them */ +function getUploads(attributes: WiseKYCRequirement['attributes'], source: SourceOfWealth): DynamicFormFileUpload[] { + const documentTypes = getAcceptedDocumentTypes(attributes, source); + const bankStatement = CONST.WISE.SOURCE_OF_WEALTH_DOCUMENT_TYPE.BANK_STATEMENT; + const needsBankStatement = getSourcesNeedingBankStatement(attributes).includes(source) && documentTypes.includes(bankStatement); + const otherTypes = needsBankStatement ? documentTypes.filter((documentType) => documentType !== bankStatement) : documentTypes; + return [ + ...(otherTypes.length > 0 ? [getUpload(otherTypes)] : []), + ...(needsBankStatement ? [{...getUpload([bankStatement]), descriptionKey: `walletPage.wiseOnboarding.sourceOfWealthProof.bankStatementHints.${source}` as const}] : []), + ]; +} + +/** + * A source's heading and its upload buttons, shown while the source is picked, since Wise needs proof of every source, funding daily operations or not. The field key names the source, so each saved file's key names its source and its document type. + * The heading lists the documents to pick from when a button offers a choice, since a button for one document is named after it. + */ +function getSourceSection(attributes: WiseKYCRequirement['attributes'], source: SourceOfWealth): DynamicFormContentItem[] { + const showWhen = {key: CONST.WISE.SOURCE_OF_WEALTH_INFO_KEY, equals: [source]}; + const uploads = getUploads(attributes, source); + return [ + { + key: `${source}-heading`, + titleKey: `walletPage.wiseOnboarding.sourceOfWealth.options.${source}`, + ...(uploads.some((upload) => upload.fileTypes.length > 1) ? {descriptionKey: `walletPage.wiseOnboarding.sourceOfWealthProof.hints.${source}` as const} : {}), + showWhen, + }, + { + key: `proofFile-${source}`, + type: 'file', + required: true, + // Wise takes up to 10 files in one review + maxFiles: 10, + labelKey: `walletPage.wiseOnboarding.sourceOfWealth.options.${source}`, + uploads, + showWhen, + }, + ]; +} + +/** Documents proving each picked source, each labelled with a document type Wise accepts for its source */ +function getSourceOfWealthProofPage(attributes: WiseKYCRequirement['attributes']): DynamicFormPage { + return { + key: CONST.WISE.KYC_REQUIREMENT.BUSINESS_SOURCE_OF_WEALTH_PROOF, + titleKey: 'walletPage.wiseOnboarding.sourceOfWealthProof.title', + descriptionKey: 'walletPage.wiseOnboarding.sourceOfWealthProof.description', + content: getAcceptedSources(attributes).flatMap((source) => getSourceSection(attributes, source)), + }; +} + +export default getSourceOfWealthProofPage; diff --git a/src/pages/settings/Wallet/EnableGlobalReimbursements/Wise/getWiseBusinessOnboardingPrefill.ts b/src/pages/settings/Wallet/EnableGlobalReimbursements/Wise/getWiseBusinessOnboardingPrefill.ts index 39d24c6a87d9..10b76bd162c0 100644 --- a/src/pages/settings/Wallet/EnableGlobalReimbursements/Wise/getWiseBusinessOnboardingPrefill.ts +++ b/src/pages/settings/Wallet/EnableGlobalReimbursements/Wise/getWiseBusinessOnboardingPrefill.ts @@ -5,7 +5,7 @@ import isCountryCode from '@components/DynamicForm/utils/isCountryCode'; import {getAllFields, getPages} from '@components/DynamicForm/utils/paginate'; import {getCountryCode, resolveStateCode} from '@libs/CountryUtils'; -import {toSavedFile} from '@libs/getWiseOnboardingPageParams'; +import {getSourceOfWealthEntries, withSavedFiles} from '@libs/getWiseOnboardingPageParams'; import {getCurrentAddress, getStreetLines} from '@libs/PersonalDetailsUtils'; import CONST from '@src/CONST'; @@ -44,20 +44,36 @@ function getStateCode(countryCode: string | undefined, state: string | undefined return Object.hasOwn(stateOptions, stateCode) ? stateCode : undefined; } +/** A saved answer the draft can hold as it is. A key a later save dropped comes back as null. */ +function isSavedAnswer(answer: unknown): answer is string | boolean | string[] { + if (typeof answer === 'string' || typeof answer === 'boolean') { + return true; + } + if (!Array.isArray(answer)) { + return false; + } + const items: unknown[] = answer; + return items.every((item) => typeof item === 'string'); +} + /** The answers of every saved page, with each saved file as a draft entry the next save can tell apart from a new one. A key a later save dropped comes back as null and is left out. */ function getSavedAnswers(wise: WiseBusinessAccountData['wise']): DynamicFormValues { - const answers: DynamicFormValues = {}; + let answers: DynamicFormValues = {}; for (const pageAnswers of Object.values(wise?.pages ?? {})) { - for (const [key, answer] of Object.entries(pageAnswers ?? {})) { - if (answer !== null && answer !== undefined) { + for (const [key, answer] of Object.entries(pageAnswers ?? {})) { + if (key === CONST.WISE.SOURCE_OF_WEALTH_LIST_KEY) { + const entries = getSourceOfWealthEntries(answer); + answers[CONST.WISE.SOURCE_OF_WEALTH_INFO_KEY] = entries.map((entry) => entry.businessSourceOfWealthInfo); + answers[CONST.WISE.SOURCE_OF_FUNDS_KEY] = entries.filter((entry) => entry.isSourceOfFund).map((entry) => entry.businessSourceOfWealthInfo); + } else if (isSavedAnswer(answer)) { answers[key] = answer; } } } for (const pageDocuments of Object.values(wise?.documents ?? {})) { - for (const [fieldKey, fileKeys] of Object.entries(pageDocuments ?? {})) { - if (fileKeys?.length) { - answers[fieldKey] = fileKeys.map(toSavedFile); + for (const [fileKey, savedFileKeys] of Object.entries(pageDocuments ?? {})) { + if (savedFileKeys?.length) { + answers = withSavedFiles(answers, fileKey, savedFileKeys); } } } diff --git a/src/pages/settings/Wallet/EnableGlobalReimbursements/Wise/getWiseOnboardingForm.ts b/src/pages/settings/Wallet/EnableGlobalReimbursements/Wise/getWiseOnboardingForm.ts new file mode 100644 index 000000000000..f0371a9c1e04 --- /dev/null +++ b/src/pages/settings/Wallet/EnableGlobalReimbursements/Wise/getWiseOnboardingForm.ts @@ -0,0 +1,85 @@ +/** Builds the Wise business onboarding form from the US profile pages and the KYC requirements the App collects itself, and maps its URL pages back to save steps */ + +import type {DynamicFormValues} from '@components/DynamicForm/types'; +import getAnswerKeys from '@components/DynamicForm/utils/getAnswerKeys'; +import getContentFields from '@components/DynamicForm/utils/getContentFields'; +import getVisibleFields from '@components/DynamicForm/utils/getVisibleFields'; +import isSupportedField from '@components/DynamicForm/utils/isSupportedField'; +import {getListItemFiles, getListItems} from '@components/DynamicForm/utils/listItems'; +import {getAllFields, getPages} from '@components/DynamicForm/utils/paginate'; + +import {getFiles, isSavedFile} from '@libs/getWiseOnboardingPageParams'; + +import CONST from '@src/CONST'; +import type {DynamicFormPage} from '@src/types/onyx'; +import type {WiseKYCRequirement} from '@src/types/onyx/WiseKYCReview'; + +import {SOURCE_OF_FUNDS_PAGE_KEY} from './forms/requirements/sourceOfFunds'; +import US from './forms/US'; +import getKYCRequirementPages from './kycRequirementLayouts'; + +type WiseOnboardingForm = {pages: DynamicFormPage[]}; + +/** Pages saved under another page's step, since the server takes one step per requirement */ +const STEP_BY_PAGE_KEY: Partial> = { + [SOURCE_OF_FUNDS_PAGE_KEY]: CONST.WISE.KYC_REQUIREMENT.BUSINESS_SOURCE_OF_WEALTH_INFO, +}; + +/** + * The US profile pages, then the pages of each requirement Expensify asks for before Submit, such as enhanced due diligence for a high-risk industry. + * A requirement's pages can depend on the answers so far, such as the daily operations page listing the picked sources. + */ +function getWiseOnboardingForm(kycRequirements: WiseKYCRequirement[] | undefined, answers: DynamicFormValues = {}): WiseOnboardingForm { + const requirementPages = (kycRequirements ?? []) + .filter((requirement) => requirement.requestedBy === CONST.WISE.KYC_REQUIREMENT_REQUESTED_BY.EXPENSIFY) + .flatMap((requirement) => getKYCRequirementPages(requirement, answers)); + return {pages: [...US.pages, ...requirementPages]}; +} + +/** The flow names its pages by URL-safe keys, so a page is mapped back to its schema key, and from there to the step the server saves it under */ +function getOnboardingStep(form: WiseOnboardingForm, routePageKey: string): string { + const pageIndex = getPages(form).findIndex((page) => page.key === routePageKey); + const pageKey = pageIndex === -1 ? routePageKey : (form.pages.at(pageIndex)?.key ?? routePageKey); + return STEP_BY_PAGE_KEY[pageKey] ?? pageKey; +} + +/** The URL-safe key of a page the schema names by its own key */ +function getRoutePageKey(form: WiseOnboardingForm, pageKey: string): string | undefined { + const pageIndex = form.pages.findIndex((page) => page.key === pageKey); + return pageIndex === -1 ? undefined : getPages(form).at(pageIndex)?.key; +} + +function hasAnswer(answer: DynamicFormValues[string]): boolean { + return !!answer && !(Array.isArray(answer) && answer.length === 0); +} + +/** The URL-safe key of the first requirement page with a required question the user sees and has not answered, such as a picked source of funds with no document */ +function getFirstUnansweredRequirementPageKey(form: WiseOnboardingForm, answers: DynamicFormValues): string | undefined { + const pages = getPages(form); + const allFields = getAllFields(pages); + return pages + .slice(US.pages.length) + .find((page) => + getVisibleFields(getContentFields(page.content).filter(isSupportedField), answers, allFields).some( + (field) => field.required && getAnswerKeys(field).every((key) => !hasAnswer(answers[key])), + ), + )?.key; +} + +/** The key of the first shown file field at which the page's files not yet on the server pass the number one save can upload, counted in page order */ +function getFieldOverNewFileLimit(form: WiseOnboardingForm, page: DynamicFormPage, answers: DynamicFormValues): string | undefined { + let newFileCount = 0; + const fileFields = getVisibleFields(getContentFields(page.content).filter(isSupportedField), answers, getAllFields(getPages(form))).filter((field) => field.type === 'file'); + for (const field of fileFields) { + const answer = answers[field.key]; + const files = field.uploads ? getListItems(answer).flatMap(getListItemFiles) : getFiles(answer); + newFileCount += files.filter((file) => !isSavedFile(file)).length; + if (newFileCount > CONST.WISE.MAX_NEW_FILES_PER_SAVE) { + return field.key; + } + } + return undefined; +} + +export default getWiseOnboardingForm; +export {getFieldOverNewFileLimit, getFirstUnansweredRequirementPageKey, getOnboardingStep, getRoutePageKey}; diff --git a/src/pages/settings/Wallet/EnableGlobalReimbursements/Wise/kycRequirementAttributes.ts b/src/pages/settings/Wallet/EnableGlobalReimbursements/Wise/kycRequirementAttributes.ts new file mode 100644 index 000000000000..5ab9479128b9 --- /dev/null +++ b/src/pages/settings/Wallet/EnableGlobalReimbursements/Wise/kycRequirementAttributes.ts @@ -0,0 +1,46 @@ +/** Reads the attributes Wise sends with the source of wealth requirements, ignoring anything malformed */ + +import CONST from '@src/CONST'; +import type {WiseKYCRequirement} from '@src/types/onyx/WiseKYCReview'; + +import type {ValueOf} from 'type-fest'; + +type SourceOfWealth = ValueOf; + +type KYCRequirementAttributes = WiseKYCRequirement['attributes']; + +function getStringList(value: unknown): string[] { + if (!Array.isArray(value)) { + return []; + } + const items: unknown[] = value; + return items.filter((item): item is string => typeof item === 'string'); +} + +/** The sources the user can pick, in the order the App lists them. All of them when Wise lists none. */ +function getAcceptedSources(attributes: KYCRequirementAttributes): SourceOfWealth[] { + const acceptedSources = getStringList(attributes?.acceptedValues); + return Object.values(CONST.WISE.SOURCE_OF_WEALTH).filter((source) => acceptedSources.length === 0 || acceptedSources.includes(source)); +} + +/** The document types Wise accepts for a source. Every type when Wise lists none, since it accepts any of them. */ +function getAcceptedDocumentTypes(attributes: KYCRequirementAttributes, source: SourceOfWealth): string[] { + const documentTypesBySource: unknown = attributes?.acceptedDocumentTypesBySource; + const sourceEntry = typeof documentTypesBySource === 'object' && documentTypesBySource !== null ? Object.entries(documentTypesBySource).find(([key]) => key === source) : undefined; + const documentTypes = getStringList(sourceEntry?.[1]); + return documentTypes.length > 0 ? documentTypes : Object.values(CONST.WISE.SOURCE_OF_WEALTH_DOCUMENT_TYPE); +} + +/** The sources whose proof needs a bank statement besides the other documents */ +function getSourcesNeedingBankStatement(attributes: KYCRequirementAttributes): string[] { + return getStringList(attributes?.sourcesNeedingBankStatement); +} + +/** The picked sources stored under an answer key, in the order the App lists them */ +function getAnsweredSources(attributes: KYCRequirementAttributes, answer: unknown): SourceOfWealth[] { + const answeredSources = getStringList(answer); + return getAcceptedSources(attributes).filter((source) => answeredSources.includes(source)); +} + +export {getAcceptedDocumentTypes, getAcceptedSources, getAnsweredSources, getSourcesNeedingBankStatement, getStringList}; +export type {SourceOfWealth}; diff --git a/src/pages/settings/Wallet/EnableGlobalReimbursements/Wise/kycRequirementLayouts.ts b/src/pages/settings/Wallet/EnableGlobalReimbursements/Wise/kycRequirementLayouts.ts new file mode 100644 index 000000000000..ea3f776fcc0f --- /dev/null +++ b/src/pages/settings/Wallet/EnableGlobalReimbursements/Wise/kycRequirementLayouts.ts @@ -0,0 +1,27 @@ +import type {DynamicFormValues} from '@components/DynamicForm/types'; + +import CONST from '@src/CONST'; +import type {DynamicFormPage} from '@src/types/onyx'; +import type {WiseKYCRequirement} from '@src/types/onyx/WiseKYCReview'; + +import getSourceOfFundsPage from './forms/requirements/sourceOfFunds'; +import getSourceOfWealthInfoPage from './forms/requirements/sourceOfWealthInfo'; +import getSourceOfWealthProofPage from './forms/requirements/sourceOfWealthProof'; + +type KYCRequirementLayout = (attributes: WiseKYCRequirement['attributes'], answers: DynamicFormValues) => DynamicFormPage[]; + +/** The pages the App draws itself, by Wise's requirement key, built from the requirement's attributes and the answers so far. The server sends no layout, and Wise's embedded page collects every other requirement. */ +const KYC_REQUIREMENT_LAYOUTS: Partial> = { + [CONST.WISE.KYC_REQUIREMENT.BUSINESS_SOURCE_OF_WEALTH_INFO]: (attributes, answers) => [getSourceOfWealthInfoPage(attributes), getSourceOfFundsPage(attributes, answers)], + [CONST.WISE.KYC_REQUIREMENT.BUSINESS_SOURCE_OF_WEALTH_PROOF]: (attributes) => [getSourceOfWealthProofPage(attributes)], +}; + +/** The App's pages for a requirement, none when only Wise's embedded page can collect it */ +function getKYCRequirementPages(requirement: WiseKYCRequirement, answers: DynamicFormValues): DynamicFormPage[] { + if (requirement.isHostedOnly) { + return []; + } + return KYC_REQUIREMENT_LAYOUTS[requirement.key]?.(requirement.attributes, answers) ?? []; +} + +export default getKYCRequirementPages; diff --git a/src/types/onyx/DynamicFormField.ts b/src/types/onyx/DynamicFormField.ts index 3b16e90bc358..7d6d0bbb8a46 100644 --- a/src/types/onyx/DynamicFormField.ts +++ b/src/types/onyx/DynamicFormField.ts @@ -189,6 +189,27 @@ type DynamicFormFileField = DynamicFormFieldBase & { /** Largest size of one file, in bytes. The form-wide limit applies when not set. */ maxFileSize?: number; + + /** Upload buttons, each taking its own kinds of document. Files list under their button, and the answer is one `{id, fileType, files}` entry per kind used. A required field needs a file on every button. */ + uploads?: DynamicFormFileUpload[]; +}; + +/** One upload button of a file field */ +type DynamicFormFileUpload = { + /** The kinds of document the button takes. With one kind the button opens the file picker, with more it asks which kind first. */ + fileTypes: DynamicFormFieldOption[]; + + /** Button text, shown when there is no labelKey. "Upload file" when neither is set. */ + label?: string; + + /** Translation of `label`, used instead of it when set */ + labelKey?: TranslationPaths; + + /** Hint under the button, such as what the document must show */ + description?: string; + + /** Translation of `description`, used instead of it when set */ + descriptionKey?: TranslationPaths; }; /** A money amount */ @@ -321,6 +342,7 @@ export type { DynamicFormCountryField, DynamicFormField, DynamicFormFieldOption, + DynamicFormFileUpload, DynamicFormFieldType, DynamicFormHeading, DynamicFormLink, diff --git a/src/types/onyx/ReimbursementAccount.ts b/src/types/onyx/ReimbursementAccount.ts index 7cc9d94d35e2..682491c11c73 100644 --- a/src/types/onyx/ReimbursementAccount.ts +++ b/src/types/onyx/ReimbursementAccount.ts @@ -263,6 +263,15 @@ type ACHData = Partial; + pages?: Record; /** Uploaded file keys, by page key then by field */ documents?: Record>; @@ -371,4 +380,14 @@ type ReimbursementAccount = OnyxCommon.OnyxValueWithOfflineFeedback<{ }>; export default ReimbursementAccount; -export type {Corpay, WiseBusinessOnboarding, BankAccountStep, BankAccountSubStep, ACHData, ReimbursementAccountStep, ReimbursementAccountSubStep, ACHDataReimbursementAccount}; +export type { + Corpay, + WiseBusinessOnboarding, + WiseSourceOfWealthEntry, + BankAccountStep, + BankAccountSubStep, + ACHData, + ReimbursementAccountStep, + ReimbursementAccountSubStep, + ACHDataReimbursementAccount, +}; diff --git a/src/types/onyx/index.ts b/src/types/onyx/index.ts index c047b2b9ed43..e8248445523a 100644 --- a/src/types/onyx/index.ts +++ b/src/types/onyx/index.ts @@ -93,6 +93,7 @@ import type { DynamicFormCountryField, DynamicFormField, DynamicFormFieldOption, + DynamicFormFileUpload, DynamicFormFieldType, DynamicFormHeading, DynamicFormLink, @@ -523,6 +524,7 @@ export type { DynamicFormCountryField, DynamicFormField, DynamicFormFieldOption, + DynamicFormFileUpload, DynamicFormFieldType, DynamicFormHeading, DynamicFormLink, diff --git a/tests/actions/WiseOnboardingTest.ts b/tests/actions/WiseOnboardingTest.ts index 8accbce6c701..b082f40049f0 100644 --- a/tests/actions/WiseOnboardingTest.ts +++ b/tests/actions/WiseOnboardingTest.ts @@ -206,6 +206,22 @@ describe('actions/WiseOnboarding saveWiseOnboardingPage', () => { expect(reimbursementAccount).not.toHaveProperty('wiseOnboardingUnsavedPages.business'); }); + it('stops counting a save as running when the request queue gives up on it', async () => { + // Given a business page save that is running + const writeSpy = jest.spyOn(API, 'write').mockImplementation(() => Promise.resolve()); + saveWiseOnboardingPage(1, BUSINESS_PAGE, {description: 'We sell bikes'}, {}); + const onyxData = writeSpy.mock.lastCall?.[2]; + await Onyx.update(onyxData?.optimisticData ?? []); + expect(isSavingWiseOnboardingPageSelector(await readOnyxValue(ONYXKEYS.RAM_ONLY_WISE_ONBOARDING_PENDING_SAVES))).toBe(true); + + // When the queue gives up after its retries, which applies the failure data without the finally data + await Onyx.update(onyxData?.failureData ?? []); + + // Then the flow stops waiting for the save and the page stays unsaved, so the confirmation page shows the error instead of a spinner that never ends + expect(isSavingWiseOnboardingPageSelector(await readOnyxValue(ONYXKEYS.RAM_ONLY_WISE_ONBOARDING_PENDING_SAVES))).toBe(false); + expect(await readOnyxValue(ONYXKEYS.REIMBURSEMENT_ACCOUNT)).toMatchObject({wiseOnboardingUnsavedPages: {business: true}}); + }); + it('keeps a page unsaved when its earlier save succeeds but its later save fails', async () => { // Given the user saves the business page twice before the first save answers, and the server accepts the first save but rejects the second let requestCount = 0; diff --git a/tests/ui/pages/settings/Wallet/WiseBusinessOnboardingPageTest.tsx b/tests/ui/pages/settings/Wallet/WiseBusinessOnboardingPageTest.tsx index b8d82ff2d89c..b4c1f4e2d806 100644 --- a/tests/ui/pages/settings/Wallet/WiseBusinessOnboardingPageTest.tsx +++ b/tests/ui/pages/settings/Wallet/WiseBusinessOnboardingPageTest.tsx @@ -1,6 +1,7 @@ import {act, render, screen} from '@testing-library/react-native'; import type {DynamicFormFlowProps} from '@components/DynamicForm/types'; +import {getPages} from '@components/DynamicForm/utils/paginate'; import OnyxListItemProvider from '@components/OnyxListItemProvider'; import {toSavedFile} from '@libs/getWiseOnboardingPageParams'; @@ -14,13 +15,14 @@ import WiseBusinessOnboardingPage from '@pages/settings/Wallet/EnableGlobalReimb import {openReimbursementAccountPage} from '@userActions/BankAccounts'; import {saveDraftAnswers} from '@userActions/DynamicForm'; -import {openReimbursementAccountPageForWiseIntro} from '@userActions/WiseOnboarding'; +import saveWiseOnboardingPage, {openReimbursementAccountPageForWiseIntro} from '@userActions/WiseOnboarding'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import SCREENS from '@src/SCREENS'; import type {WiseBusinessOnboardingForm} from '@src/types/form'; -import type {BankAccount, DismissedProductTraining, PrivatePersonalDetails} from '@src/types/onyx'; +import type {BankAccount, DismissedProductTraining, DynamicFormPage, PrivatePersonalDetails} from '@src/types/onyx'; +import type {WiseKYCRequirement} from '@src/types/onyx/WiseKYCReview'; import type ReactNative from 'react-native'; import type {OnyxEntry} from 'react-native-onyx'; @@ -62,6 +64,7 @@ jest.mock('@pages/ErrorPage/NotFoundPage', () => { return {__esModule: true, default: () => }; }); jest.mock('@userActions/DynamicForm', () => ({...jest.requireActual>('@userActions/DynamicForm'), saveDraftAnswers: jest.fn()})); +jest.mock('@userActions/WiseOnboarding', () => ({...jest.requireActual>('@userActions/WiseOnboarding'), __esModule: true, default: jest.fn()})); jest.mock('@userActions/BankAccounts', () => ({hideBankAccountErrors: jest.fn(), openReimbursementAccountPage: jest.fn()})); const INTRO_PATH = 'settings/wallet/global-reimbursements/1'; @@ -94,6 +97,30 @@ const PRIVATE_PERSONAL_DETAILS: PrivatePersonalDetails = { addresses: [{street: '42 Oak Ave', city: 'Austin', state: 'TX', zip: '78704', country: CONST.COUNTRY.US, current: true}], }; +function getExpensifyRequirement(key: string): WiseKYCRequirement { + return {key, state: CONST.WISE.KYC_REQUIREMENT_STATE.NOT_PROVIDED, isHostedOnly: false, requestedBy: CONST.WISE.KYC_REQUIREMENT_REQUESTED_BY.EXPENSIFY}; +} + +/** What the business page's save returns for a high-risk industry */ +const ENHANCED_DUE_DILIGENCE: WiseKYCRequirement[] = [ + getExpensifyRequirement(CONST.WISE.KYC_REQUIREMENT.BUSINESS_SOURCE_OF_WEALTH_INFO), + getExpensifyRequirement(CONST.WISE.KYC_REQUIREMENT.BUSINESS_SOURCE_OF_WEALTH_PROOF), +]; + +/** The server's copy of the sources page, with the first source funding daily operations */ +function getSavedSourcesPages(sources: string[]) { + return { + [CONST.WISE.KYC_REQUIREMENT.BUSINESS_SOURCE_OF_WEALTH_INFO]: { + [CONST.WISE.SOURCE_OF_WEALTH_LIST_KEY]: sources.map((source, index) => ({businessSourceOfWealthInfo: source, isSourceOfFund: index === 0})), + }, + }; +} + +function getFlowPageKeys() { + const schema = mockFlowProps.mock.lastCall?.[0].schema; + return schema && 'pages' in schema ? schema.pages.map((page) => page.key) : []; +} + const {saveDraftAnswers: saveDraftAnswersToOnyx} = jest.requireActual<{saveDraftAnswers: typeof saveDraftAnswers}>('@userActions/DynamicForm'); function readDraft() { @@ -663,4 +690,380 @@ describe('WiseBusinessOnboardingPage', () => { expect(navigateSpy).not.toHaveBeenCalled(); expect(flowProps?.submitError).toBe('common.genericErrorMessage'); }); + it('adds the enhanced due diligence pages after the business page once its save returns them', async () => { + // Given the flow open on the business page, with no requirements yet + await renderPage({reimbursementAccount: REIMBURSEMENT_ACCOUNT, subPage: 'business'}); + expect(getFlowPageKeys()).toEqual(['representative', 'business']); + + // When the business page's save answers for a high-risk industry + await act(() => Onyx.merge(ONYXKEYS.REIMBURSEMENT_ACCOUNT, {achData: {wise: {kycRequirements: ENHANCED_DUE_DILIGENCE}}})); + await waitForBatchedUpdatesWithAct(); + + // Then the sources, the sources that fund daily operations and their proof are asked before the confirmation page + expect(getFlowPageKeys()).toEqual([ + 'representative', + 'business', + CONST.WISE.KYC_REQUIREMENT.BUSINESS_SOURCE_OF_WEALTH_INFO, + 'BUSINESS_SOURCE_OF_FUNDS', + CONST.WISE.KYC_REQUIREMENT.BUSINESS_SOURCE_OF_WEALTH_PROOF, + ]); + }); + + it('ignores requirements saved on the reimbursement account for another bank account', async () => { + // Given requirements the device holds for another bank account + const otherAccount: BusinessReimbursementAccount = {achData: {...REIMBURSEMENT_ACCOUNT.achData, bankAccountID: 2, wise: {kycRequirements: ENHANCED_DUE_DILIGENCE}}}; + + // When the page opens for this bank account and its read has not returned yet + await renderPage({reimbursementAccount: otherAccount, subPage: 'business', shouldLeaveReadRunning: true}); + + // Then only the profile pages are asked + expect(getFlowPageKeys()).toEqual(['representative', 'business']); + }); + + it('reads this bank account on a direct link to the confirmation page and takes the user to the requirement it returns', async () => { + // Given a device that holds another bank account's details, so a reload on the confirmation page has no requirements for this one + const otherAccount: BusinessReimbursementAccount = {achData: {...REIMBURSEMENT_ACCOUNT.achData, bankAccountID: 2}}; + const navigateSpy = jest.spyOn(Navigation, 'navigate').mockImplementation(() => {}); + + // When the confirmation page opens and the read returns this bank account with enhanced due diligence + await renderPage({ + reimbursementAccount: otherAccount, + readResponse: {achData: {...REIMBURSEMENT_ACCOUNT.achData, wise: {kycRequirements: ENHANCED_DUE_DILIGENCE}}}, + subPage: CONST.DYNAMIC_FORM.CONFIRMATION_PAGE_KEY, + }); + + // Then the page reads this bank account and sends the user to the source of funds page, so Submit cannot skip it + expect(openReimbursementAccountPage).toHaveBeenCalledWith({bankAccountID: BANK_ACCOUNT_ID}); + expect(navigateSpy).toHaveBeenCalledWith(expect.stringContaining('business-onboarding/business-source-of-wealth-info'), {forceReplace: true}); + }); + + it('takes the user from the confirmation page to the source of funds page when the requirements arrive', async () => { + // Given the user moved on from the business page to the confirmation page before its save answered + await renderPage({reimbursementAccount: REIMBURSEMENT_ACCOUNT, subPage: CONST.DYNAMIC_FORM.CONFIRMATION_PAGE_KEY}); + const navigateSpy = jest.spyOn(Navigation, 'navigate').mockImplementation(() => {}); + + // When the save answers with the enhanced due diligence requirements + await act(() => Onyx.merge(ONYXKEYS.REIMBURSEMENT_ACCOUNT, {achData: {wise: {kycRequirements: ENHANCED_DUE_DILIGENCE}}})); + await waitForBatchedUpdatesWithAct(); + + // Then the user lands on the first requirement page, replacing the confirmation page, since Submit needs the answers first + expect(navigateSpy).toHaveBeenCalledWith(expect.stringContaining('business-onboarding/business-source-of-wealth-info'), {forceReplace: true}); + }); + + it('shows a spinner in place of the confirmation page while the business page saves, and until the user is moved to the requirement page it returns', async () => { + // Given the user moved on from the business page to the confirmation page before its save answered + await renderPage({reimbursementAccount: REIMBURSEMENT_ACCOUNT, subPage: CONST.DYNAMIC_FORM.CONFIRMATION_PAGE_KEY}); + const navigateSpy = jest.spyOn(Navigation, 'navigate').mockImplementation(() => {}); + await act(() => + Promise.all([ + Onyx.merge(ONYXKEYS.RAM_ONLY_WISE_ONBOARDING_PENDING_SAVES, {[SAVE_ID]: true}), + Onyx.merge(ONYXKEYS.REIMBURSEMENT_ACCOUNT, {wiseOnboardingUnsavedPages: {[CONST.WISE.ONBOARDING_STEP.BUSINESS]: true}}), + ]), + ); + await waitForBatchedUpdatesWithAct(); + + // Then the flow shows a spinner, since the save can add pages the user has to answer before the summary + expect(mockFlowProps.mock.lastCall?.[0].isLoading).toBe(true); + + // When the save answers with the enhanced due diligence requirements + await act(() => + Promise.all([ + Onyx.merge(ONYXKEYS.RAM_ONLY_WISE_ONBOARDING_PENDING_SAVES, {[SAVE_ID]: null}), + Onyx.merge(ONYXKEYS.REIMBURSEMENT_ACCOUNT, { + wiseOnboardingUnsavedPages: {[CONST.WISE.ONBOARDING_STEP.BUSINESS]: null}, + achData: {wise: {kycRequirements: ENHANCED_DUE_DILIGENCE}}, + }), + ]), + ); + await waitForBatchedUpdatesWithAct(); + + // Then the user is sent to the first requirement page, and the spinner stays until they get there, so the summary does not flash + expect(navigateSpy).toHaveBeenCalledWith(expect.stringContaining('business-onboarding/business-source-of-wealth-info'), {forceReplace: true}); + expect(mockFlowProps.mock.lastCall?.[0].isLoading).toBe(true); + }); + + it('shows the confirmation page once the business page saves without new requirements', async () => { + // Given the confirmation page waiting for the business page's save + await renderPage({reimbursementAccount: REIMBURSEMENT_ACCOUNT, subPage: CONST.DYNAMIC_FORM.CONFIRMATION_PAGE_KEY}); + const navigateSpy = jest.spyOn(Navigation, 'navigate').mockImplementation(() => {}); + await act(() => + Promise.all([ + Onyx.merge(ONYXKEYS.RAM_ONLY_WISE_ONBOARDING_PENDING_SAVES, {[SAVE_ID]: true}), + Onyx.merge(ONYXKEYS.REIMBURSEMENT_ACCOUNT, {wiseOnboardingUnsavedPages: {[CONST.WISE.ONBOARDING_STEP.BUSINESS]: true}}), + ]), + ); + await waitForBatchedUpdatesWithAct(); + + // When the save answers without requirements, as for an industry that needs no enhanced due diligence + await act(() => + Promise.all([ + Onyx.merge(ONYXKEYS.RAM_ONLY_WISE_ONBOARDING_PENDING_SAVES, {[SAVE_ID]: null}), + Onyx.merge(ONYXKEYS.REIMBURSEMENT_ACCOUNT, {wiseOnboardingUnsavedPages: {[CONST.WISE.ONBOARDING_STEP.BUSINESS]: null}}), + ]), + ); + await waitForBatchedUpdatesWithAct(); + + // Then the user stays and sees the summary + expect(mockFlowProps.mock.lastCall?.[0].isLoading).toBe(false); + expect(navigateSpy).not.toHaveBeenCalled(); + }); + + it('keeps the confirmation page while a page other than the business page saves', async () => { + // Given the user edited the representative page from the confirmation page and came back before its save answered + await renderPage({reimbursementAccount: REIMBURSEMENT_ACCOUNT, subPage: CONST.DYNAMIC_FORM.CONFIRMATION_PAGE_KEY}); + await act(() => + Promise.all([ + Onyx.merge(ONYXKEYS.RAM_ONLY_WISE_ONBOARDING_PENDING_SAVES, {[SAVE_ID]: true}), + Onyx.merge(ONYXKEYS.REIMBURSEMENT_ACCOUNT, {wiseOnboardingUnsavedPages: {[CONST.WISE.ONBOARDING_STEP.REPRESENTATIVE]: true}}), + ]), + ); + await waitForBatchedUpdatesWithAct(); + + // Then the summary stays, with only Confirm waiting, since that save cannot add pages + const flowProps = mockFlowProps.mock.lastCall?.[0]; + expect(flowProps?.isLoading).toBe(false); + expect(flowProps?.isSavingPages).toBe(true); + }); + + it('shows a spinner in place of a requirement page while the business page saves, since the save can remove it', async () => { + // Given enhanced due diligence on the device from an earlier save, and the user moved on to its first page after picking an industry that does not need it + await renderPage({ + reimbursementAccount: {achData: {...REIMBURSEMENT_ACCOUNT.achData, wise: {kycRequirements: ENHANCED_DUE_DILIGENCE}}}, + subPage: 'business-source-of-wealth-info', + }); + await act(() => + Promise.all([ + Onyx.merge(ONYXKEYS.RAM_ONLY_WISE_ONBOARDING_PENDING_SAVES, {[SAVE_ID]: true}), + Onyx.merge(ONYXKEYS.REIMBURSEMENT_ACCOUNT, {wiseOnboardingUnsavedPages: {[CONST.WISE.ONBOARDING_STEP.BUSINESS]: true}}), + ]), + ); + await waitForBatchedUpdatesWithAct(); + + // Then the flow shows a spinner instead of a page the save is about to drop + expect(mockFlowProps.mock.lastCall?.[0].isLoading).toBe(true); + + // When the save answers without requirements + await act(() => Promise.all([Onyx.merge(ONYXKEYS.RAM_ONLY_WISE_ONBOARDING_PENDING_SAVES, {[SAVE_ID]: null}), Onyx.set(ONYXKEYS.REIMBURSEMENT_ACCOUNT, REIMBURSEMENT_ACCOUNT)])); + await waitForBatchedUpdatesWithAct(); + + // Then the spinner is gone and the flow has no requirement pages left, so it moves the user on from the page that no longer exists + expect(mockFlowProps.mock.lastCall?.[0].isLoading).toBe(false); + expect(getFlowPageKeys()).toEqual(['representative', 'business']); + }); + + it('keeps the business page while its own save runs', async () => { + // Given the user went back to the business page while its save is running + await renderPage({reimbursementAccount: REIMBURSEMENT_ACCOUNT, subPage: CONST.WISE.ONBOARDING_STEP.BUSINESS}); + await act(() => + Promise.all([ + Onyx.merge(ONYXKEYS.RAM_ONLY_WISE_ONBOARDING_PENDING_SAVES, {[SAVE_ID]: true}), + Onyx.merge(ONYXKEYS.REIMBURSEMENT_ACCOUNT, {wiseOnboardingUnsavedPages: {[CONST.WISE.ONBOARDING_STEP.BUSINESS]: true}}), + ]), + ); + await waitForBatchedUpdatesWithAct(); + + // Then the page stays, so the user can change the industry again + expect(mockFlowProps.mock.lastCall?.[0].isLoading).toBe(false); + }); + + it('stops Next on the documents page when its new files pass what one save can upload', async () => { + // Given the documents page open for revenue + await renderPage({reimbursementAccount: {achData: {...REIMBURSEMENT_ACCOUNT.achData, wise: {kycRequirements: ENHANCED_DUE_DILIGENCE}}}, subPage: 'business-source-of-wealth-proof'}); + const flowProps = mockFlowProps.mock.lastCall?.[0]; + const proofPage = flowProps && getPages(flowProps.schema).find((page) => page.key === 'business-source-of-wealth-proof'); + const fieldKey = `proofFile-${CONST.WISE.SOURCE_OF_WEALTH.REVENUE}`; + const getAnswers = (count: number) => ({ + businessSourceOfWealthInfo: [CONST.WISE.SOURCE_OF_WEALTH.REVENUE], + [fieldKey]: [{id: 'TAX_DOCUMENTS', fileType: 'TAX_DOCUMENTS', files: Array.from({length: count}, (_, index) => ({name: `${index}.pdf`, uri: `file://${index}.pdf`}))}], + }); + + // When the page is checked with as many new files as one save takes, and with one more + // Then only the second is stopped, with the message under the revenue field, since the server drops the files past its cap without an error + expect(proofPage && flowProps?.validatePage?.(proofPage, getAnswers(CONST.WISE.MAX_NEW_FILES_PER_SAVE))).toEqual({}); + expect(proofPage && flowProps?.validatePage?.(proofPage, getAnswers(CONST.WISE.MAX_NEW_FILES_PER_SAVE + 1))).toEqual({ + [fieldKey]: 'attachmentPicker.tooManyFiles', + }); + }); + + it('leaves the user on the confirmation page once every requirement page has an answer', async () => { + // Given both requirement pages answered on an earlier visit + await Onyx.set(ONYXKEYS.FORMS.WISE_BUSINESS_ONBOARDING_FORM_DRAFT, { + bankAccountID: String(BANK_ACCOUNT_ID), + businessSourceOfWealthInfo: [CONST.WISE.SOURCE_OF_WEALTH.REVENUE], + [`proofFile-${CONST.WISE.SOURCE_OF_WEALTH.REVENUE}`]: [{id: 'TAX_DOCUMENTS', fileType: 'TAX_DOCUMENTS', files: [toSavedFile('kyc/1/proof.pdf')]}], + }); + const navigateSpy = jest.spyOn(Navigation, 'navigate').mockImplementation(() => {}); + + // When the confirmation page opens with the requirements on the device + await renderPage({ + reimbursementAccount: {achData: {...REIMBURSEMENT_ACCOUNT.achData, wise: {kycRequirements: ENHANCED_DUE_DILIGENCE}}}, + subPage: CONST.DYNAMIC_FORM.CONFIRMATION_PAGE_KEY, + }); + + // Then the user stays to review the answers + expect(navigateSpy).not.toHaveBeenCalled(); + }); + + it('saves the sources page under its requirement key with the daily operations answers it keeps', async () => { + // Given revenue saved as the lone source, and the user adding grants from the confirmation page, which skips the daily operations page. + // The sources input drafts each pick as it is made, so the draft holds both sources before the page is left. + await Onyx.set(ONYXKEYS.FORMS.WISE_BUSINESS_ONBOARDING_FORM_DRAFT, { + bankAccountID: String(BANK_ACCOUNT_ID), + businessSourceOfWealthInfo: [CONST.WISE.SOURCE_OF_WEALTH.REVENUE, CONST.WISE.SOURCE_OF_WEALTH.GRANTS], + sourceOfFunds: [CONST.WISE.SOURCE_OF_WEALTH.REVENUE], + }); + await renderPage({ + reimbursementAccount: { + achData: {...REIMBURSEMENT_ACCOUNT.achData, wise: {kycRequirements: ENHANCED_DUE_DILIGENCE, pages: getSavedSourcesPages([CONST.WISE.SOURCE_OF_WEALTH.REVENUE])}}, + }, + subPage: 'business', + }); + const flowProps = mockFlowProps.mock.lastCall?.[0]; + const sourcesPage: DynamicFormPage = {key: 'business-source-of-wealth-info', content: []}; + const answers = {businessSourceOfWealthInfo: [CONST.WISE.SOURCE_OF_WEALTH.REVENUE, CONST.WISE.SOURCE_OF_WEALTH.GRANTS]}; + + // When the user leaves the sources page, which the flow names by its URL key + act(() => flowProps?.onPageSubmit?.(sourcesPage, answers, {})); + + // Then the page is saved under Wise's requirement key with every source picked and the kept daily operations answers, so every source gets a boolean + expect(saveWiseOnboardingPage).toHaveBeenCalledWith( + BANK_ACCOUNT_ID, + expect.objectContaining({key: CONST.WISE.KYC_REQUIREMENT.BUSINESS_SOURCE_OF_WEALTH_INFO}), + {...answers, sourceOfFunds: [CONST.WISE.SOURCE_OF_WEALTH.REVENUE]}, + {}, + ); + + // And the daily operations answer is drafted empty, since the user never picked it, so the flow asks the daily operations page before Confirm + await waitForBatchedUpdatesWithAct(); + expect((await readDraft())?.sourceOfFunds).toEqual([]); + }); + + it('keeps the drafted daily operations answers when a source is added to several picked sources', async () => { + // Given revenue and grants saved, with revenue funding daily operations as the user chose on the daily operations page, and donations drafted as the user picks it + await Onyx.set(ONYXKEYS.FORMS.WISE_BUSINESS_ONBOARDING_FORM_DRAFT, { + bankAccountID: String(BANK_ACCOUNT_ID), + businessSourceOfWealthInfo: [CONST.WISE.SOURCE_OF_WEALTH.REVENUE, CONST.WISE.SOURCE_OF_WEALTH.GRANTS, CONST.WISE.SOURCE_OF_WEALTH.DONATIONS], + sourceOfFunds: [CONST.WISE.SOURCE_OF_WEALTH.REVENUE], + }); + await renderPage({ + reimbursementAccount: { + achData: { + ...REIMBURSEMENT_ACCOUNT.achData, + wise: {kycRequirements: ENHANCED_DUE_DILIGENCE, pages: getSavedSourcesPages([CONST.WISE.SOURCE_OF_WEALTH.REVENUE, CONST.WISE.SOURCE_OF_WEALTH.GRANTS])}, + }, + }, + subPage: 'business', + }); + const flowProps = mockFlowProps.mock.lastCall?.[0]; + const sourcesPage: DynamicFormPage = {key: 'business-source-of-wealth-info', content: []}; + + // When the user adds donations from the confirmation page + act(() => + flowProps?.onPageSubmit?.( + sourcesPage, + {businessSourceOfWealthInfo: [CONST.WISE.SOURCE_OF_WEALTH.REVENUE, CONST.WISE.SOURCE_OF_WEALTH.GRANTS, CONST.WISE.SOURCE_OF_WEALTH.DONATIONS]}, + {}, + ), + ); + await waitForBatchedUpdatesWithAct(); + + // Then the user's own answer stays to be shown on the daily operations page, and that page is marked to be asked again, since donations can fund daily operations too + const draftAfterSave = await readDraft(); + expect(draftAfterSave?.sourceOfFunds).toEqual([CONST.WISE.SOURCE_OF_WEALTH.REVENUE]); + expect(draftAfterSave?.shouldReviewSourceOfFunds).toBe(true); + }); + + it('does not ask the daily operations page again when no source is added', async () => { + // Given revenue, grants and donations saved, with revenue funding daily operations + await Onyx.set(ONYXKEYS.FORMS.WISE_BUSINESS_ONBOARDING_FORM_DRAFT, { + bankAccountID: String(BANK_ACCOUNT_ID), + businessSourceOfWealthInfo: [CONST.WISE.SOURCE_OF_WEALTH.REVENUE, CONST.WISE.SOURCE_OF_WEALTH.GRANTS], + sourceOfFunds: [CONST.WISE.SOURCE_OF_WEALTH.REVENUE], + }); + await renderPage({ + reimbursementAccount: { + achData: { + ...REIMBURSEMENT_ACCOUNT.achData, + wise: { + kycRequirements: ENHANCED_DUE_DILIGENCE, + pages: getSavedSourcesPages([CONST.WISE.SOURCE_OF_WEALTH.REVENUE, CONST.WISE.SOURCE_OF_WEALTH.GRANTS, CONST.WISE.SOURCE_OF_WEALTH.DONATIONS]), + }, + }, + }, + subPage: 'business', + }); + const flowProps = mockFlowProps.mock.lastCall?.[0]; + const sourcesPage: DynamicFormPage = {key: 'business-source-of-wealth-info', content: []}; + + // When the user removes donations from the confirmation page + act(() => flowProps?.onPageSubmit?.(sourcesPage, {businessSourceOfWealthInfo: [CONST.WISE.SOURCE_OF_WEALTH.REVENUE, CONST.WISE.SOURCE_OF_WEALTH.GRANTS]}, {})); + await waitForBatchedUpdatesWithAct(); + + // Then the daily operations page is not asked again, since its answer still covers every picked source + expect((await readDraft())?.shouldReviewSourceOfFunds).toBe(false); + }); + + it('takes the user from the confirmation page to the daily operations page after a source is added', async () => { + // Given three picked sources with revenue funding daily operations, and donations just added from the confirmation page + await Onyx.set(ONYXKEYS.FORMS.WISE_BUSINESS_ONBOARDING_FORM_DRAFT, { + bankAccountID: String(BANK_ACCOUNT_ID), + businessSourceOfWealthInfo: [CONST.WISE.SOURCE_OF_WEALTH.REVENUE, CONST.WISE.SOURCE_OF_WEALTH.GRANTS, CONST.WISE.SOURCE_OF_WEALTH.DONATIONS], + sourceOfFunds: [CONST.WISE.SOURCE_OF_WEALTH.REVENUE], + shouldReviewSourceOfFunds: true, + }); + const navigateSpy = jest.spyOn(Navigation, 'navigate').mockImplementation(() => {}); + + // When the confirmation page opens + await renderPage({ + reimbursementAccount: {achData: {...REIMBURSEMENT_ACCOUNT.achData, wise: {kycRequirements: ENHANCED_DUE_DILIGENCE}}}, + subPage: CONST.DYNAMIC_FORM.CONFIRMATION_PAGE_KEY, + }); + + // Then the user is sent to the daily operations page, so they can say whether donations fund daily operations too + expect(navigateSpy).toHaveBeenCalledWith(expect.stringContaining('business-onboarding/business-source-of-funds'), {forceReplace: true}); + }); + + it('takes the user from the confirmation page to the daily operations page when its answer is empty', async () => { + // Given two picked sources and an empty daily operations answer, as after a second source is added from the confirmation page + await Onyx.set(ONYXKEYS.FORMS.WISE_BUSINESS_ONBOARDING_FORM_DRAFT, { + bankAccountID: String(BANK_ACCOUNT_ID), + businessSourceOfWealthInfo: [CONST.WISE.SOURCE_OF_WEALTH.REVENUE, CONST.WISE.SOURCE_OF_WEALTH.GRANTS], + sourceOfFunds: [], + }); + const navigateSpy = jest.spyOn(Navigation, 'navigate').mockImplementation(() => {}); + + // When the confirmation page opens + await renderPage({ + reimbursementAccount: {achData: {...REIMBURSEMENT_ACCOUNT.achData, wise: {kycRequirements: ENHANCED_DUE_DILIGENCE}}}, + subPage: CONST.DYNAMIC_FORM.CONFIRMATION_PAGE_KEY, + }); + + // Then the user is sent to the daily operations page before the documents page, so they pick which sources fund daily operations + expect(navigateSpy).toHaveBeenCalledWith(expect.stringContaining('business-onboarding/business-source-of-funds'), {forceReplace: true}); + }); + + it('saves the daily operations page under the sources page step, with the picked sources', async () => { + // Given revenue and grants picked on the sources page + const pickedSources = [CONST.WISE.SOURCE_OF_WEALTH.REVENUE, CONST.WISE.SOURCE_OF_WEALTH.GRANTS]; + await Onyx.set(ONYXKEYS.FORMS.WISE_BUSINESS_ONBOARDING_FORM_DRAFT, {bankAccountID: String(BANK_ACCOUNT_ID), businessSourceOfWealthInfo: pickedSources}); + await renderPage({reimbursementAccount: {achData: {...REIMBURSEMENT_ACCOUNT.achData, wise: {kycRequirements: ENHANCED_DUE_DILIGENCE}}}, subPage: 'business'}); + const flowProps = mockFlowProps.mock.lastCall?.[0]; + const dailyOperationsPage: DynamicFormPage = {key: 'business-source-of-funds', content: []}; + const answers = {sourceOfFunds: [CONST.WISE.SOURCE_OF_WEALTH.REVENUE]}; + + // When the user leaves the daily operations page with Next + act(() => flowProps?.onPageSubmit?.(dailyOperationsPage, answers, {})); + + // Then it is saved under the sources page step with the picked sources, since the server replaces that step's answers whole + expect(saveWiseOnboardingPage).toHaveBeenCalledWith( + BANK_ACCOUNT_ID, + expect.objectContaining({key: CONST.WISE.KYC_REQUIREMENT.BUSINESS_SOURCE_OF_WEALTH_INFO}), + {...answers, businessSourceOfWealthInfo: pickedSources}, + {}, + ); + + // And the page is no longer marked to be asked again, since the user just answered it + await waitForBatchedUpdatesWithAct(); + expect((await readDraft())?.shouldReviewSourceOfFunds).toBe(false); + }); }); diff --git a/tests/unit/ListItemPressableTest.tsx b/tests/unit/ListItemPressableTest.tsx index ac0824b01abe..e7db0ec4ab4c 100644 --- a/tests/unit/ListItemPressableTest.tsx +++ b/tests/unit/ListItemPressableTest.tsx @@ -75,6 +75,31 @@ describe('ListItemPressable', () => { expect(screen.getByLabelText('Item text')).toBeTruthy(); }); + it.each([ + ['selects a checkbox row, since the list Enter shortcut stands down while a checkbox is focused', CONST.ROLE.CHECKBOX, 1], + ['leaves an option row to the list Enter shortcut, so the row is not selected twice', undefined, 0], + ])('Enter on a focused row %s', (_case, accessibilityRole, expectedSelections) => { + // Given a row that leaves Enter to the list, as every row of a list with its Enter shortcut on does + const onSelectRow = jest.fn(); + render( + , + ); + + // When the browser turns Enter on the focused row into a press + fireEvent.press(screen.getByTestId(`${CONST.BASE_LIST_ITEM_TEST_ID}1`), {key: CONST.KEYBOARD_SHORTCUTS.ENTER.shortcutKey}); + + // Then only a checkbox row is selected by it + expect(onSelectRow).toHaveBeenCalledTimes(expectedSelections); + }); + it('should keep the button role for a navigational row when shouldUseOptionRole is false', () => { render( jest.fn(() => new Proxy({}, {get: () => const page: DynamicFormPage = {key: 'identity', title: 'Identity', content: [{key: 'ssn', type: 'text', required: true, sensitive: true}]}; -function renderPage(isLastPage: boolean, shouldDisableNextWhenOffline?: boolean) { +function renderPage(isLastPage: boolean, shouldDisableNextWhenOffline?: boolean, validatePage?: (page: DynamicFormPage) => Record) { render( , ); return jest.mocked(FormProvider).mock.lastCall?.[0]; @@ -64,4 +65,17 @@ describe('DynamicFormFieldsPage', () => { // Then its button is disabled offline, so no page save waits in the queue or fails for want of a connection expect(formProps?.enabledWhenOffline).toBe(false); }); + + it("adds the screen's checks of the whole page to the fields' own, which win on the same field", () => { + // Given a screen that limits the page as a whole, with errors under the SSN field and under another field + const validatePage = jest.fn(() => ({ssn: 'Too many files', other: 'Too many files'})); + const formProps = renderPage(false, false, validatePage); + + // When the page is validated without an SSN + const errors = formProps?.validate?.({}, jest.fn()); + + // Then the screen's error blocks Next, and the missing SSN keeps its own error + expect(validatePage).toHaveBeenCalledWith(page, expect.anything()); + expect(errors).toEqual({ssn: 'common.error.fieldRequired', other: 'Too many files'}); + }); }); diff --git a/tests/unit/components/DynamicForm/DynamicFormFlowTest.tsx b/tests/unit/components/DynamicForm/DynamicFormFlowTest.tsx index 2484c06547f4..f9343d2fcef9 100644 --- a/tests/unit/components/DynamicForm/DynamicFormFlowTest.tsx +++ b/tests/unit/components/DynamicForm/DynamicFormFlowTest.tsx @@ -110,6 +110,7 @@ type RenderFlowOptions = { onRefreshRequirements?: (inputID: string, value: FormValue) => void; shouldDisableNextWhenOffline?: boolean; unsavedPageKeys?: string[]; + isLoading?: boolean; }; function mockSubPage(currentPageName: string, pageIndex: number, isRedirecting: boolean) { @@ -142,6 +143,7 @@ async function renderFlow({ onRefreshRequirements, shouldDisableNextWhenOffline, unsavedPageKeys, + isLoading, }: RenderFlowOptions = {}) { await Onyx.set(`${FORM_ID}Draft`, draft); await Onyx.set(ONYXKEYS.RAM_ONLY_DYNAMIC_FORM_SENSITIVE_ANSWERS, {[FORM_ID]: sensitiveAnswers}); @@ -168,6 +170,7 @@ async function renderFlow({ isSubmitting={submitting} shouldDisableNextWhenOffline={shouldDisableNextWhenOffline} unsavedPageKeys={unsavedPageKeys} + isLoading={isLoading} /> ); const {rerender, unmount} = render(renderWith(isSubmitting)); @@ -569,6 +572,17 @@ describe('DynamicFormFlow', () => { expect(mockCurrentPage).not.toHaveBeenCalled(); }); + it('shows a spinner below the header in place of the page while the screen asks it to', async () => { + // Given a screen waiting for a save that can add pages + // When the flow renders with isLoading + await renderFlow({isLoading: true}); + + // Then the header stays and a spinner replaces the page, so the user does not see a page they are about to leave + expect(HeaderWithBackButtonAndTitle).toHaveBeenCalled(); + expect(ActivityIndicator).toHaveBeenCalled(); + expect(mockCurrentPage).not.toHaveBeenCalled(); + }); + it('sends the user back to the incomplete page without pushing a second copy of it', async () => { // Given a form whose SSN was lost when the app restarted const {subPageOptions, onSubmit} = await renderFlow({draft: {firstName: 'Jane', legalType: 'PRIVATE'}}); diff --git a/tests/unit/components/DynamicForm/adapters/LabelledFileUploadAdapterTest.tsx b/tests/unit/components/DynamicForm/adapters/LabelledFileUploadAdapterTest.tsx new file mode 100644 index 000000000000..b012a5fc45e0 --- /dev/null +++ b/tests/unit/components/DynamicForm/adapters/LabelledFileUploadAdapterTest.tsx @@ -0,0 +1,162 @@ +import {fireEvent, render, screen} from '@testing-library/react-native'; + +import LabelledFileUploadAdapter from '@components/DynamicForm/adapters/LabelledFileUploadAdapter'; + +import type {DynamicFormListItem} from '@src/types/onyx'; +import type {FileObject} from '@src/types/utils/Attachment'; + +import React from 'react'; + +let mockPickedFiles: FileObject[] = []; + +jest.mock('@components/AttachmentPicker', () => ({ + __esModule: true, + default: ({children}: {children: (props: {openPicker: (options: {onPicked: (files: FileObject[]) => void}) => void}) => React.ReactNode}) => + children({openPicker: ({onPicked}) => onPicked(mockPickedFiles)}), +})); +jest.mock('@hooks/useLocalize', () => jest.fn(() => ({translate: (key: string) => key}))); + +const loanFile: FileObject = {name: 'loan.pdf', uri: 'file://loan.pdf'}; +const statementFile: FileObject = {name: 'statement.pdf', uri: 'file://statement.pdf'}; + +const UPLOADS = [ + {types: [{value: 'LOAN_AGREEMENT', label: 'Loan agreement'}], buttonText: 'Upload loan agreement'}, + {types: [{value: 'BANK_STATEMENT', label: 'Bank statement'}], buttonText: 'Upload bank statement'}, +]; + +function renderAdapter(value: DynamicFormListItem[], onInputChange: (value: DynamicFormListItem[]) => void, fileLimit = 0, errorText = '') { + render( + , + ); +} + +describe('LabelledFileUploadAdapter', () => { + it('takes a file under a second button when another button already holds it', () => { + // Given the loan agreement uploaded, since one PDF can show both the agreement and the funds received + const onInputChange = jest.fn(); + renderAdapter([{id: 'LOAN_AGREEMENT', fileType: 'LOAN_AGREEMENT', files: [loanFile]}], onInputChange); + + // When the user picks the same file as the bank statement + mockPickedFiles = [loanFile]; + fireEvent.press(screen.getByText('Upload bank statement')); + + // Then the file is added under the bank statement too + expect(onInputChange).toHaveBeenCalledWith([ + {id: 'LOAN_AGREEMENT', fileType: 'LOAN_AGREEMENT', files: [loanFile]}, + {id: 'BANK_STATEMENT', fileType: 'BANK_STATEMENT', files: [loanFile]}, + ]); + }); + + it('leaves out a file the same button already holds and says why', () => { + // Given the loan agreement uploaded + const onInputChange = jest.fn(); + renderAdapter([{id: 'LOAN_AGREEMENT', fileType: 'LOAN_AGREEMENT', files: [loanFile]}], onInputChange); + + // When the user picks it again under the same button + mockPickedFiles = [loanFile]; + fireEvent.press(screen.getByText('Upload loan agreement')); + + // Then nothing is added, since the same document twice proves nothing more, and the user is told the file is already there + expect(onInputChange).not.toHaveBeenCalled(); + expect(screen.getByText('attachmentPicker.fileAlreadyAdded')).toBeOnTheScreen(); + }); + + it('tells a saved file apart from a new one by the name the server gives it', () => { + // Given a saved file, which the server names in lowercase with its spaces and dots replaced + const onInputChange = jest.fn(); + const savedFile: FileObject = {name: 'loan_agreement_v1.pdf', uri: 'kyc/1/loan_agreement_v1.pdf'}; + renderAdapter([{id: 'LOAN_AGREEMENT', fileType: 'LOAN_AGREEMENT', files: [savedFile]}], onInputChange); + + // When the user picks the same file again under its original name + mockPickedFiles = [{name: 'Loan Agreement v1.pdf', uri: 'file://Loan Agreement v1.pdf'}]; + fireEvent.press(screen.getByText('Upload loan agreement')); + + // Then it is left out as the file the button already holds + expect(onInputChange).not.toHaveBeenCalled(); + expect(screen.getByText('attachmentPicker.fileAlreadyAdded')).toBeOnTheScreen(); + }); + + it('counts the files of every button against the file limit', () => { + // Given a field that takes two files, with the loan agreement uploaded + const onInputChange = jest.fn(); + renderAdapter([{id: 'LOAN_AGREEMENT', fileType: 'LOAN_AGREEMENT', files: [loanFile]}], onInputChange, 2); + + // When the user picks two files under the bank statement button, which holds none yet + mockPickedFiles = [statementFile, {name: 'statement-2.pdf', uri: 'file://statement-2.pdf'}]; + fireEvent.press(screen.getByText('Upload bank statement')); + + // Then nothing is added and the limit is shown, since the limit is on the source's documents as a whole, not on each button + expect(onInputChange).not.toHaveBeenCalled(); + expect(screen.getByText('attachmentPicker.tooManyFiles')).toBeOnTheScreen(); + }); + + it('takes files under a second button while the field stays within the file limit', () => { + // Given a field that takes two files, with the loan agreement uploaded + const onInputChange = jest.fn(); + renderAdapter([{id: 'LOAN_AGREEMENT', fileType: 'LOAN_AGREEMENT', files: [loanFile]}], onInputChange, 2); + + // When the user picks one file under the bank statement button + mockPickedFiles = [statementFile]; + fireEvent.press(screen.getByText('Upload bank statement')); + + // Then the file is added, since the field holds two files in all + expect(onInputChange).toHaveBeenCalledWith([ + {id: 'LOAN_AGREEMENT', fileType: 'LOAN_AGREEMENT', files: [loanFile]}, + {id: 'BANK_STATEMENT', fileType: 'BANK_STATEMENT', files: [statementFile]}, + ]); + }); + + it('takes two different files whose names are in another alphabet', () => { + // Given a contract picked under the loan agreement button, named in Japanese + const onInputChange = jest.fn(); + const contract: FileObject = {name: '契約書.pdf', uri: 'file://契約書.pdf'}; + renderAdapter([{id: 'LOAN_AGREEMENT', fileType: 'LOAN_AGREEMENT', files: [contract]}], onInputChange); + + // When the user picks an invoice under the same button, also named in Japanese + const invoice: FileObject = {name: '請求書.pdf', uri: 'file://請求書.pdf'}; + mockPickedFiles = [invoice]; + fireEvent.press(screen.getByText('Upload loan agreement')); + + // Then it is added, since a new file is compared by its own name + expect(onInputChange).toHaveBeenCalledWith([{id: 'LOAN_AGREEMENT', fileType: 'LOAN_AGREEMENT', files: [contract, invoice]}]); + }); + + it('does not compare a new file with a saved one whose server name kept no letter', () => { + // Given a saved file named in Japanese, which the server stores with every byte of its name as `_` + const onInputChange = jest.fn(); + const savedContract: FileObject = {name: '_________.pdf', uri: 'kyc/1/_________.pdf'}; + renderAdapter([{id: 'LOAN_AGREEMENT', fileType: 'LOAN_AGREEMENT', files: [savedContract]}], onInputChange); + + // When the user picks another file whose Japanese name has as many bytes + const invoice: FileObject = {name: '請求書.pdf', uri: 'file://請求書.pdf'}; + mockPickedFiles = [invoice]; + fireEvent.press(screen.getByText('Upload loan agreement')); + + // Then it is added, since the saved name says nothing about which file it was + expect(onInputChange).toHaveBeenCalledWith([{id: 'LOAN_AGREEMENT', fileType: 'LOAN_AGREEMENT', files: [savedContract, invoice]}]); + }); + + it('shows an error under the last button when every button has a file', () => { + // Given both buttons holding a file, and an error about the field as a whole, such as too many files for one save + // When the field renders + renderAdapter( + [ + {id: 'LOAN_AGREEMENT', fileType: 'LOAN_AGREEMENT', files: [loanFile]}, + {id: 'BANK_STATEMENT', fileType: 'BANK_STATEMENT', files: [statementFile]}, + ], + jest.fn(), + 0, + 'Too many files', + ); + + // Then the error shows once, so the user sees why Next does not go on + expect(screen.getAllByText('Too many files')).toHaveLength(1); + }); +}); diff --git a/tests/unit/components/DynamicForm/getDynamicFieldErrorsTest.ts b/tests/unit/components/DynamicForm/getDynamicFieldErrorsTest.ts index e9c57f42a57d..8b1c1755affa 100644 --- a/tests/unit/components/DynamicForm/getDynamicFieldErrorsTest.ts +++ b/tests/unit/components/DynamicForm/getDynamicFieldErrorsTest.ts @@ -507,4 +507,24 @@ describe('getDynamicFieldErrors with an answer the server holds', () => { // Then the flag is ignored, since only sensitive answers are held back by the server expect(errors).toEqual({firstName: translateLocal('common.error.fieldRequired')}); }); + + it('requires a file on every upload button of a required file field', () => { + // Given a loan's documents, with one button for the loan agreement and one for the bank statement + const loanDocuments: DynamicFormField = { + key: 'proofFile-BUSINESS_LOAN', + type: 'file', + required: true, + uploads: [{fileTypes: [{key: 'LOAN_AGREEMENT'}]}, {fileTypes: [{key: 'BANK_STATEMENT'}]}], + }; + const loanAgreement = {id: 'LOAN_AGREEMENT', fileType: 'LOAN_AGREEMENT', files: [{name: 'loan.pdf', uri: 'file://loan.pdf'}]}; + const bankStatement = {id: 'BANK_STATEMENT', fileType: 'BANK_STATEMENT', files: [{name: 'statement.pdf', uri: 'file://statement.pdf'}]}; + + // When only the loan agreement is uploaded, then both documents + const partialErrors = getDynamicFieldErrors([loanDocuments], {[loanDocuments.key]: [loanAgreement]}, translateLocal); + const completeErrors = getDynamicFieldErrors([loanDocuments], {[loanDocuments.key]: [loanAgreement, bankStatement]}, translateLocal); + + // Then the field stays required until the bank statement is uploaded too, since each button asks for its own document + expect(partialErrors).toEqual({[loanDocuments.key]: translateLocal('common.error.fieldRequired')}); + expect(completeErrors).toEqual({}); + }); }); diff --git a/tests/unit/libs/getWiseOnboardingPageParamsTest.ts b/tests/unit/libs/getWiseOnboardingPageParamsTest.ts index 1cd6595b2c25..8bc72197d0f0 100644 --- a/tests/unit/libs/getWiseOnboardingPageParamsTest.ts +++ b/tests/unit/libs/getWiseOnboardingPageParamsTest.ts @@ -1,4 +1,4 @@ -import getWiseOnboardingPageParams, {getSavedFileAnswers, toSavedFile} from '@libs/getWiseOnboardingPageParams'; +import getWiseOnboardingPageParams, {getLabelledFileKey, getSavedFileAnswers, toSavedFile} from '@libs/getWiseOnboardingPageParams'; import type {DynamicFormPage} from '@src/types/onyx'; @@ -8,6 +8,9 @@ jest.mock('@libs/isFileUploadable', () => ({__esModule: true, default: (file: un const BANK_ACCOUNT_ID = 1; const CITY_KEY = 'address.city'; const FIRST_ID_DOCUMENT_PART = 'idDocument[0]'; +const REVENUE_TAX_RETURNS = getLabelledFileKey('REVENUE', 'TAX_DOCUMENTS'); +const REVENUE_BANK_STATEMENTS = getLabelledFileKey('REVENUE', 'BANK_STATEMENT'); +const REVENUE_INVOICES = getLabelledFileKey('REVENUE', 'INVOICES'); const REPRESENTATIVE_PAGE: DynamicFormPage = { key: 'representative', @@ -110,6 +113,86 @@ describe('getWiseOnboardingPageParams', () => { expect(params.documents).toBe(JSON.stringify({idDocument: []})); }); + it('sends an empty object as the inputs of a page whose only answers are files', () => { + // Given a page that asks for nothing but a file, answered with one new file + const page: DynamicFormPage = {key: 'BUSINESS_SOURCE_OF_WEALTH_PROOF', content: [{key: 'proofFile', type: 'file', required: true}]}; + const proofFile = new File(['statement'], 'statement.pdf', {type: 'application/pdf'}); + + // When the page is turned into a save request + const params = getPageParams(BANK_ACCOUNT_ID, page, {proofFile: [proofFile]}); + + // Then inputs is `{}`, since the server rejects `[]` as "Inputs is not a valid json object", and the file still goes as its own part + expect(params.inputs).toBe('{}'); + expect(params['proofFile[0]']).toBe(proofFile); + }); + + it('sends the files of a labelled field under its key and their type, listing every type it offers', () => { + // Given a source of funds that keeps a saved tax return and adds a new bank statement, and offers invoices too + const page: DynamicFormPage = { + key: 'BUSINESS_SOURCE_OF_WEALTH_PROOF', + content: [{key: 'REVENUE', type: 'file', required: true, uploads: [{fileTypes: [{key: 'TAX_DOCUMENTS'}, {key: 'INVOICES'}]}, {fileTypes: [{key: 'BANK_STATEMENT'}]}]}], + }; + const statement = new File(['statement'], 'statement.pdf', {type: 'application/pdf'}); + const answers = { + REVENUE: [ + {id: 'TAX_DOCUMENTS', fileType: 'TAX_DOCUMENTS', files: [toSavedFile('kyc/1/tax.pdf')]}, + {id: 'BANK_STATEMENT', fileType: 'BANK_STATEMENT', files: [statement]}, + ], + }; + + // When the page is turned into a save request + const params = getPageParams(BANK_ACCOUNT_ID, page, answers); + + // Then each file goes under `.`, so the server knows both, and the unused type is listed empty, so a removed invoice is removed on the server too + expect(params[`${REVENUE_BANK_STATEMENTS}[0]`]).toBe(statement); + expect(params.documents).toBe(JSON.stringify({[REVENUE_TAX_RETURNS]: ['kyc/1/tax.pdf'], [REVENUE_INVOICES]: [], [REVENUE_BANK_STATEMENTS]: []})); + expect(params.inputs).toBe('{}'); + }); + + it('sends the picked sources as the list Wise takes, each with whether it funds daily operations', () => { + // Given the sources page answered with a loan, revenue and grants, after the daily operations page said only the loan funds them + const page: DynamicFormPage = {key: 'BUSINESS_SOURCE_OF_WEALTH_INFO', content: [{key: 'businessSourceOfWealthInfo', type: 'multiselect', required: true}]}; + + // When the page is turned into a save request + const params = getPageParams(BANK_ACCOUNT_ID, page, {businessSourceOfWealthInfo: ['BUSINESS_LOAN', 'REVENUE', 'GRANTS'], sourceOfFunds: ['BUSINESS_LOAN']}); + + // Then the inputs are Wise's sourceOfWealthList, one entry per picked source, since the server replaces the saved page on every save, and the new source has a boolean too, since Submit needs one on every entry + expect(JSON.parse(params.inputs)).toEqual({ + sourceOfWealthList: [ + {businessSourceOfWealthInfo: 'BUSINESS_LOAN', isSourceOfFund: true}, + {businessSourceOfWealthInfo: 'REVENUE', isSourceOfFund: false}, + {businessSourceOfWealthInfo: 'GRANTS', isSourceOfFund: false}, + ], + }); + }); + + it('makes a lone picked source fund daily operations', () => { + // Given the sources page answered with revenue alone, which skips the daily operations page + const page: DynamicFormPage = {key: 'BUSINESS_SOURCE_OF_WEALTH_INFO', content: [{key: 'businessSourceOfWealthInfo', type: 'multiselect', required: true}]}; + + // When the page is turned into a save request + const params = getPageParams(BANK_ACCOUNT_ID, page, {businessSourceOfWealthInfo: ['REVENUE'], sourceOfFunds: []}); + + // Then revenue funds daily operations, whatever the daily operations page held + expect(JSON.parse(params.inputs)).toEqual({sourceOfWealthList: [{businessSourceOfWealthInfo: 'REVENUE', isSourceOfFund: true}]}); + }); + + it('sends every picked source with whether it funds daily operations from the daily operations page', () => { + // Given the daily operations page answered with the loan, out of the loan and revenue picked before + const page: DynamicFormPage = {key: 'BUSINESS_SOURCE_OF_WEALTH_INFO', content: [{key: 'sourceOfFunds', type: 'multiselect', required: true}]}; + + // When the page is turned into a save request with the picked sources + const params = getPageParams(BANK_ACCOUNT_ID, page, {sourceOfFunds: ['BUSINESS_LOAN'], businessSourceOfWealthInfo: ['BUSINESS_LOAN', 'REVENUE']}); + + // Then each source says whether it funds daily operations + expect(JSON.parse(params.inputs)).toEqual({ + sourceOfWealthList: [ + {businessSourceOfWealthInfo: 'BUSINESS_LOAN', isSourceOfFund: true}, + {businessSourceOfWealthInfo: 'REVENUE', isSourceOfFund: false}, + ], + }); + }); + it('gives nothing for a page whose key is not a step the server accepts', () => { // Given a page keyed by something other than a step, which the server would answer with 400 Invalid step const page: DynamicFormPage = {key: 'ownership', content: [{key: 'description', type: 'text', required: true}]}; @@ -134,6 +217,22 @@ describe('getSavedFileAnswers', () => { expect(answers).toEqual({idDocument: [toSavedFile('kyc/1/passport.jpg')], proofOfAddress: []}); }); + it('groups the files of a labelled field into an entry per type', () => { + // Given the server's file keys for a source of funds, with a tax return and a bank statement, and invoices the user removed + const documents = {BUSINESS_SOURCE_OF_WEALTH_PROOF: {[REVENUE_TAX_RETURNS]: ['kyc/1/tax.pdf'], [REVENUE_BANK_STATEMENTS]: ['kyc/1/statement.pdf'], [REVENUE_INVOICES]: []}}; + + // When they are turned into draft answers + const answers = getSavedFileAnswers(documents); + + // Then the source holds one entry per type that has files, as its upload field stores them + expect(answers).toEqual({ + REVENUE: [ + {id: 'TAX_DOCUMENTS', fileType: 'TAX_DOCUMENTS', files: [toSavedFile('kyc/1/tax.pdf')]}, + {id: 'BANK_STATEMENT', fileType: 'BANK_STATEMENT', files: [toSavedFile('kyc/1/statement.pdf')]}, + ], + }); + }); + it('leaves out the files of a page whose save failed', () => { // Given the server's file keys after one page saved and another failed, so the server still holds the failed page's older file const documents = {representative: {idDocument: ['kyc/1/older.jpg']}, business: {proofOfAddress: ['kyc/1/proof.pdf']}}; @@ -145,3 +244,27 @@ describe('getSavedFileAnswers', () => { expect(answers).toEqual({proofOfAddress: [toSavedFile('kyc/1/proof.pdf')]}); }); }); + +describe('toSavedFile', () => { + it('names a stored file as the user named it', () => { + // Given a file the server stored under its account, bank account, upload time and unique ID, followed by the user's file name + const savedFileKey = 'kyc/1/23595723-10834395-20261113_143445-6af720053a1ae-loan-agreement-v2.pdf'; + + // When the file is put back in the draft + const file = toSavedFile(savedFileKey); + + // Then the user's file name is shown, dashes included, and the key still points at the stored file + expect(file).toEqual({name: 'loan-agreement-v2.pdf', uri: savedFileKey, savedFileKey}); + }); + + it('keeps the stored name when the key has another shape', () => { + // Given a stored file name without the server's prefix + const savedFileKey = 'kyc/1/passport.jpg'; + + // When the file is put back in the draft + const file = toSavedFile(savedFileKey); + + // Then the stored name is shown whole, since there is no prefix to take off + expect(file.name).toBe('passport.jpg'); + }); +}); diff --git a/tests/unit/pages/settings/Wallet/EnableGlobalReimbursements/getWiseBusinessOnboardingPrefillTest.ts b/tests/unit/pages/settings/Wallet/EnableGlobalReimbursements/getWiseBusinessOnboardingPrefillTest.ts index b5aeca6d8148..6693c5690b0f 100644 --- a/tests/unit/pages/settings/Wallet/EnableGlobalReimbursements/getWiseBusinessOnboardingPrefillTest.ts +++ b/tests/unit/pages/settings/Wallet/EnableGlobalReimbursements/getWiseBusinessOnboardingPrefillTest.ts @@ -232,6 +232,45 @@ describe('getMissingPrefill', () => { }); }); + it('resumes the picked sources and their documents labelled by type', () => { + // Given the source of funds pages saved earlier, as the server stores them + const businessAccountData: WiseBusinessAccountData = { + ...BUSINESS_ACCOUNT_DATA, + wise: { + pages: { + BUSINESS_SOURCE_OF_WEALTH_INFO: { + sourceOfWealthList: [ + {businessSourceOfWealthInfo: CONST.WISE.SOURCE_OF_WEALTH.BUSINESS_LOAN, isSourceOfFund: true}, + {businessSourceOfWealthInfo: CONST.WISE.SOURCE_OF_WEALTH.REVENUE, isSourceOfFund: false}, + ], + }, + }, + documents: { + BUSINESS_SOURCE_OF_WEALTH_PROOF: { + [`proofFile-REVENUE-TAX_DOCUMENTS`]: ['kyc/42/BusinessTaxReturn.pdf'], + [`proofFile-BUSINESS_LOAN-LOAN_AGREEMENT`]: ['kyc/42/LoanAgreement.pdf'], + [`proofFile-BUSINESS_LOAN-BANK_STATEMENT`]: ['kyc/42/BankStatement.pdf'], + }, + }, + }, + }; + + // When the onboarding builds its starting answers + const prefill = getWiseBusinessOnboardingPrefill(BANK_ACCOUNT_ID, businessAccountData, PRIVATE_PERSONAL_DETAILS); + + // Then the sources come back ticked, and each source's files come back under their document type + expect(prefill).toMatchObject({ + businessSourceOfWealthInfo: [CONST.WISE.SOURCE_OF_WEALTH.BUSINESS_LOAN, CONST.WISE.SOURCE_OF_WEALTH.REVENUE], + [`proofFile-${CONST.WISE.SOURCE_OF_WEALTH.REVENUE}`]: [ + {id: 'TAX_DOCUMENTS', fileType: 'TAX_DOCUMENTS', files: [expect.objectContaining({savedFileKey: 'kyc/42/BusinessTaxReturn.pdf'})]}, + ], + [`proofFile-${CONST.WISE.SOURCE_OF_WEALTH.BUSINESS_LOAN}`]: [ + {id: 'LOAN_AGREEMENT', fileType: 'LOAN_AGREEMENT', files: [expect.objectContaining({savedFileKey: 'kyc/42/LoanAgreement.pdf'})]}, + {id: 'BANK_STATEMENT', fileType: 'BANK_STATEMENT', files: [expect.objectContaining({savedFileKey: 'kyc/42/BankStatement.pdf'})]}, + ], + }); + }); + it('drops an SSN the server holds once a saved page says the representative has none', () => { // Given a representative page saved with "I don't have an SSN" after an SSN was saved, which the server still reports as provided const businessAccountData: WiseBusinessAccountData = { diff --git a/tests/unit/pages/settings/Wallet/EnableGlobalReimbursements/getWiseOnboardingFormTest.ts b/tests/unit/pages/settings/Wallet/EnableGlobalReimbursements/getWiseOnboardingFormTest.ts new file mode 100644 index 000000000000..33c8c1e9d9d3 --- /dev/null +++ b/tests/unit/pages/settings/Wallet/EnableGlobalReimbursements/getWiseOnboardingFormTest.ts @@ -0,0 +1,315 @@ +import type {DynamicFormValues} from '@components/DynamicForm/types'; +import getContentFields from '@components/DynamicForm/utils/getContentFields'; +import isHeading from '@components/DynamicForm/utils/isHeading'; +import isSupportedField from '@components/DynamicForm/utils/isSupportedField'; +import {getPages} from '@components/DynamicForm/utils/paginate'; + +import {getKeptSourceOfFunds, SOURCE_OF_FUNDS_PAGE_KEY} from '@pages/settings/Wallet/EnableGlobalReimbursements/Wise/forms/requirements/sourceOfFunds'; +import getWiseOnboardingForm, { + getFieldOverNewFileLimit, + getFirstUnansweredRequirementPageKey, + getOnboardingStep, +} from '@pages/settings/Wallet/EnableGlobalReimbursements/Wise/getWiseOnboardingForm'; +import getKYCRequirementPages from '@pages/settings/Wallet/EnableGlobalReimbursements/Wise/kycRequirementLayouts'; + +import CONST from '@src/CONST'; +import type {DynamicFormField, DynamicFormPage} from '@src/types/onyx'; +import type {WiseKYCRequirement} from '@src/types/onyx/WiseKYCReview'; + +const PROFILE_PAGE_KEYS = ['representative', 'business']; +const INFO_ROUTE_KEY = 'business-source-of-wealth-info'; +const FUNDS_ROUTE_KEY = 'business-source-of-funds'; +const PROOF_ROUTE_KEY = 'business-source-of-wealth-proof'; + +function getRequirement(key: string, overrides: Partial = {}): WiseKYCRequirement { + return {key, state: CONST.WISE.KYC_REQUIREMENT_STATE.NOT_PROVIDED, isHostedOnly: false, requestedBy: CONST.WISE.KYC_REQUIREMENT_REQUESTED_BY.EXPENSIFY, ...overrides}; +} + +/** A source's documents of one type, as the proof page's upload field stores them */ +function getDocumentEntry(documentType: string) { + return {id: documentType, fileType: documentType, files: [{name: `${documentType}.pdf`, uri: `file://${documentType}.pdf`}]}; +} + +/** The sources page and the daily operations page, built for the given answers */ +function getInfoPages(overrides: Partial = {}, answers: DynamicFormValues = {}): DynamicFormPage[] { + return getKYCRequirementPages(getRequirement(CONST.WISE.KYC_REQUIREMENT.BUSINESS_SOURCE_OF_WEALTH_INFO, overrides), answers); +} + +function getField(page: DynamicFormPage | undefined, key: string): DynamicFormField | undefined { + return getContentFields(page?.content ?? []) + .filter(isSupportedField) + .find((field) => field.key === key); +} + +function getOptionKeys(field: DynamicFormField | undefined): string[] { + return field && 'values' in field ? (field.values ?? []).map((option) => option.key) : []; +} + +const ENHANCED_DUE_DILIGENCE = [getRequirement(CONST.WISE.KYC_REQUIREMENT.BUSINESS_SOURCE_OF_WEALTH_INFO), getRequirement(CONST.WISE.KYC_REQUIREMENT.BUSINESS_SOURCE_OF_WEALTH_PROOF)]; + +describe('getWiseOnboardingForm', () => { + it('adds the pages of each requirement Expensify asks for, after the profile pages and in the server order', () => { + // Given a high-risk business, for which the business page save returned the two source of wealth requirements + // When the form is built + const form = getWiseOnboardingForm(ENHANCED_DUE_DILIGENCE); + + // Then the sources page and the daily operations page follow the profile pages, then the documents page + expect(form.pages.map((page) => page.key)).toEqual([ + ...PROFILE_PAGE_KEYS, + CONST.WISE.KYC_REQUIREMENT.BUSINESS_SOURCE_OF_WEALTH_INFO, + SOURCE_OF_FUNDS_PAGE_KEY, + CONST.WISE.KYC_REQUIREMENT.BUSINESS_SOURCE_OF_WEALTH_PROOF, + ]); + }); + + it.each([ + ['no requirements', undefined], + [ + 'a requirement Wise asked for after Submit', + [getRequirement(CONST.WISE.KYC_REQUIREMENT.BUSINESS_SOURCE_OF_WEALTH_PROOF, {requestedBy: CONST.WISE.KYC_REQUIREMENT_REQUESTED_BY.WISE})], + ], + ['a requirement only Wise can collect', [getRequirement(CONST.WISE.KYC_REQUIREMENT.BUSINESS_SOURCE_OF_WEALTH_INFO, {isHostedOnly: true})]], + ['a requirement the App has no page for', [getRequirement('BUSINESS_ULTIMATE_BENEFICIAL_OWNER_ID')]], + ['the ID document, which the representative page collects', [getRequirement(CONST.WISE.KYC_REQUIREMENT.ID_DOCUMENT)]], + ])('keeps only the profile pages for %s', (_label, kycRequirements) => { + // Given requirements the intake does not draw a page for + // When the form is built + const form = getWiseOnboardingForm(kycRequirements); + + // Then the user sees the profile pages alone, since Wise's embedded page collects the rest + expect(form.pages.map((page) => page.key)).toEqual(PROFILE_PAGE_KEYS); + }); + + it('lets the user pick several sources, out of every value Wise accepts', () => { + // Given the sources page + const field = getField(getInfoPages().at(0), CONST.WISE.SOURCE_OF_WEALTH_INFO_KEY); + + // Then it is a multiselect over Wise's values, since a company's money can come from more than one source and the server forwards the keys as they are + expect(field?.type).toBe('multiselect'); + expect(getOptionKeys(field)).toEqual(Object.values(CONST.WISE.SOURCE_OF_WEALTH)); + }); +}); + +describe('source of wealth pages built from the requirement attributes', () => { + const PROOF_ATTRIBUTES = { + acceptedDocumentTypesBySource: { + REVENUE: ['TAX_DOCUMENTS', 'AUDITED_FINANCIAL_STATEMENTS', 'BANK_STATEMENT'], + BUSINESS_LOAN: ['LOAN_AGREEMENT', 'BANK_STATEMENT'], + DONATIONS: ['DONATION_RECEIPTS', 'CONTRACTS', 'BANK_STATEMENT'], + }, + sourcesNeedingBankStatement: ['BUSINESS_LOAN', 'DONATIONS'], + }; + + function getProofField(source: string) { + const [proofPage] = getKYCRequirementPages(getRequirement(CONST.WISE.KYC_REQUIREMENT.BUSINESS_SOURCE_OF_WEALTH_PROOF, {attributes: PROOF_ATTRIBUTES}), {}); + const field = getField(proofPage, `proofFile-${source}`); + return field?.type === 'file' ? field : undefined; + } + + it('offers only the sources Wise accepts', () => { + // Given Wise accepts two sources + const attributes = {acceptedValues: [CONST.WISE.SOURCE_OF_WEALTH.REVENUE, CONST.WISE.SOURCE_OF_WEALTH.GRANTS]}; + + // When the sources page is built + const field = getField(getInfoPages({attributes}).at(0), CONST.WISE.SOURCE_OF_WEALTH_INFO_KEY); + + // Then only those two are offered + expect(getOptionKeys(field)).toEqual([CONST.WISE.SOURCE_OF_WEALTH.REVENUE, CONST.WISE.SOURCE_OF_WEALTH.GRANTS]); + }); + + it('asks which picked sources fund daily operations only when several are picked', () => { + // Given two picked sources, then one + const severalSources = {[CONST.WISE.SOURCE_OF_WEALTH_INFO_KEY]: [CONST.WISE.SOURCE_OF_WEALTH.BUSINESS_LOAN, CONST.WISE.SOURCE_OF_WEALTH.REVENUE]}; + const oneSource = {[CONST.WISE.SOURCE_OF_WEALTH_INFO_KEY]: [CONST.WISE.SOURCE_OF_WEALTH.REVENUE]}; + + // When the daily operations page is built + const fundsField = getField(getInfoPages({}, severalSources).at(1), CONST.WISE.SOURCE_OF_FUNDS_KEY); + + // Then it lists only the picked sources, in the order of the sources page, and has nothing to ask for a lone source, which funds daily operations, so the flow skips it + expect(getOptionKeys(fundsField)).toEqual([CONST.WISE.SOURCE_OF_WEALTH.REVENUE, CONST.WISE.SOURCE_OF_WEALTH.BUSINESS_LOAN]); + expect(getInfoPages({}, oneSource).at(1)?.content).toEqual([]); + }); + + it('gives a source one button for its documents to pick from, and a separate one for a bank statement it needs besides them', () => { + // Given revenue, which takes any of its documents, and donations, which take one of theirs and a bank statement + // When the documents page is built + const revenueUploads = getProofField(CONST.WISE.SOURCE_OF_WEALTH.REVENUE)?.uploads; + const donationUploads = getProofField(CONST.WISE.SOURCE_OF_WEALTH.DONATIONS)?.uploads; + + // Then revenue has one button for all its types, and donations have one for their other types and one for the bank statement, with a hint on what it must show + expect(revenueUploads?.map((upload) => upload.fileTypes.map((option) => option.key))).toEqual([['TAX_DOCUMENTS', 'AUDITED_FINANCIAL_STATEMENTS', 'BANK_STATEMENT']]); + expect(donationUploads?.map((upload) => upload.fileTypes.map((option) => option.key))).toEqual([['DONATION_RECEIPTS', 'CONTRACTS'], ['BANK_STATEMENT']]); + expect(donationUploads?.at(1)?.descriptionKey).toBe('walletPage.wiseOnboarding.sourceOfWealthProof.bankStatementHints.DONATIONS'); + }); + + it('names a button that takes one document after it, so a source of single documents needs no hint above them', () => { + // Given a business loan, which takes a loan agreement and a bank statement + // When the documents page is built + const [proofPage] = getKYCRequirementPages(getRequirement(CONST.WISE.KYC_REQUIREMENT.BUSINESS_SOURCE_OF_WEALTH_PROOF, {attributes: PROOF_ATTRIBUTES}), {}); + const headings = proofPage?.content.filter(isHeading) ?? []; + const loanHeading = headings.find((heading) => heading.key === `${CONST.WISE.SOURCE_OF_WEALTH.BUSINESS_LOAN}-heading`); + const revenueHeading = headings.find((heading) => heading.key === `${CONST.WISE.SOURCE_OF_WEALTH.REVENUE}-heading`); + + // Then each button names its document, the loan heading has no hint, and revenue, whose button offers a choice, keeps its hint + expect(getProofField(CONST.WISE.SOURCE_OF_WEALTH.BUSINESS_LOAN)?.uploads?.map((upload) => upload.labelKey)).toEqual([ + 'walletPage.wiseOnboarding.sourceOfWealthProof.uploadButtons.LOAN_AGREEMENT', + 'walletPage.wiseOnboarding.sourceOfWealthProof.uploadButtons.BANK_STATEMENT', + ]); + expect(loanHeading?.descriptionKey).toBeUndefined(); + expect(revenueHeading?.descriptionKey).toBe('walletPage.wiseOnboarding.sourceOfWealthProof.hints.REVENUE'); + }); + + it('offers every document type for a source Wise lists none for, and shows a source while it is picked', () => { + // Given Wise lists no document types for grants + // When the documents page is built + const grantsField = getProofField(CONST.WISE.SOURCE_OF_WEALTH.GRANTS); + + // Then grants offer every type, since Wise accepts any of them, and the section follows the sources page, since Wise needs proof of every picked source + expect(grantsField?.uploads?.flatMap((upload) => upload.fileTypes.map((option) => option.key))).toEqual(Object.values(CONST.WISE.SOURCE_OF_WEALTH_DOCUMENT_TYPE)); + expect(grantsField?.showWhen).toEqual({key: CONST.WISE.SOURCE_OF_WEALTH_INFO_KEY, equals: [CONST.WISE.SOURCE_OF_WEALTH.GRANTS]}); + }); +}); + +describe('getKeptSourceOfFunds', () => { + it('keeps the daily operations answers of the sources still picked, and makes a lone source fund daily operations', () => { + // Given revenue and a loan funding daily operations + const sourceOfFunds = [CONST.WISE.SOURCE_OF_WEALTH.REVENUE, CONST.WISE.SOURCE_OF_WEALTH.BUSINESS_LOAN]; + + // When the picked sources change + // Then a source no longer picked drops out, and a lone source is the answer, since the daily operations page is skipped for it + expect(getKeptSourceOfFunds([CONST.WISE.SOURCE_OF_WEALTH.REVENUE, CONST.WISE.SOURCE_OF_WEALTH.GRANTS], sourceOfFunds)).toEqual([CONST.WISE.SOURCE_OF_WEALTH.REVENUE]); + expect(getKeptSourceOfFunds([CONST.WISE.SOURCE_OF_WEALTH.GRANTS], sourceOfFunds)).toEqual([CONST.WISE.SOURCE_OF_WEALTH.GRANTS]); + }); +}); + +describe('getOnboardingStep', () => { + const form = getWiseOnboardingForm(ENHANCED_DUE_DILIGENCE); + + it('names requirement pages in the URL by keys that differ from their requirement keys', () => { + // Given the form with both requirement pages + // When the flow names its pages + // Then the requirement pages get URL-safe keys, which is why the step is looked up before a save + expect(getPages(form).map((page) => page.key)).toEqual([...PROFILE_PAGE_KEYS, INFO_ROUTE_KEY, FUNDS_ROUTE_KEY, PROOF_ROUTE_KEY]); + }); + + it.each([ + ['a requirement page', INFO_ROUTE_KEY, CONST.WISE.KYC_REQUIREMENT.BUSINESS_SOURCE_OF_WEALTH_INFO], + ['the daily operations page, which shares the sources page step', FUNDS_ROUTE_KEY, CONST.WISE.KYC_REQUIREMENT.BUSINESS_SOURCE_OF_WEALTH_INFO], + ['a profile page', 'business', 'business'], + ['a page the form does not have', 'unknown', 'unknown'], + ])('saves %s under the key it was built with', (_label, routeKey, expectedStep) => { + // Given the key the flow gave a page in its URL + // When the step to save the page under is looked up + // Then it is the step the page saves under, since the server stores the answers under it and rejects any other step + expect(getOnboardingStep(form, routeKey)).toBe(expectedStep); + }); +}); + +describe('getFirstUnansweredRequirementPageKey', () => { + const form = getWiseOnboardingForm(ENHANCED_DUE_DILIGENCE); + + it('finds the first requirement page with no answer', () => { + // Given the sources of funds chosen, but no proof uploaded yet + const answers = { + companyRole: CONST.WISE.COMPANY_ROLE.OWNER, + businessSourceOfWealthInfo: [CONST.WISE.SOURCE_OF_WEALTH.REVENUE], + [`proofFile-${CONST.WISE.SOURCE_OF_WEALTH.REVENUE}`]: [], + }; + + // When the next requirement page to open is looked up + // Then it is the proof page, under the key the flow uses in its URL + expect(getFirstUnansweredRequirementPageKey(form, answers)).toBe(PROOF_ROUTE_KEY); + }); + + it('treats an empty list of sources as no answer', () => { + // Given no source of funds picked + // When the next requirement page to open is looked up + // Then it is the source of funds page + expect(getFirstUnansweredRequirementPageKey(form, {businessSourceOfWealthInfo: []})).toBe(INFO_ROUTE_KEY); + }); + + it('finds the proof page while one of the picked sources has no document', () => { + // Given grants and donations picked, only grants funding daily operations, and a document for grants alone + const answers = { + businessSourceOfWealthInfo: [CONST.WISE.SOURCE_OF_WEALTH.GRANTS, CONST.WISE.SOURCE_OF_WEALTH.DONATIONS], + sourceOfFunds: [CONST.WISE.SOURCE_OF_WEALTH.GRANTS], + [`proofFile-${CONST.WISE.SOURCE_OF_WEALTH.GRANTS}`]: [getDocumentEntry('GRANT_APPROVAL_LETTER')], + }; + + // When the next requirement page to open is looked up + // Then it is the proof page, since Wise needs documents for every picked source, funding daily operations or not + expect(getFirstUnansweredRequirementPageKey(form, answers)).toBe(PROOF_ROUTE_KEY); + }); + + it('finds nothing once every requirement page has an answer, or when there are no requirements', () => { + // Given both requirement pages answered, with a document for each picked source + const answers = { + businessSourceOfWealthInfo: [CONST.WISE.SOURCE_OF_WEALTH.GRANTS, CONST.WISE.SOURCE_OF_WEALTH.DONATIONS], + [`proofFile-${CONST.WISE.SOURCE_OF_WEALTH.GRANTS}`]: [getDocumentEntry('GRANT_APPROVAL_LETTER')], + [`proofFile-${CONST.WISE.SOURCE_OF_WEALTH.DONATIONS}`]: [getDocumentEntry('DONATION_RECEIPTS')], + }; + + // When the next requirement page to open is looked up + // Then there is none, and a form without requirements has none either, even with the profile pages empty + expect(getFirstUnansweredRequirementPageKey(form, answers)).toBeUndefined(); + expect(getFirstUnansweredRequirementPageKey(getWiseOnboardingForm(undefined), {})).toBeUndefined(); + }); +}); + +describe('getFieldOverNewFileLimit', () => { + const form = getWiseOnboardingForm(ENHANCED_DUE_DILIGENCE); + const proofPage = getPages(form).find((page) => page.key === PROOF_ROUTE_KEY); + if (!proofPage) { + throw new Error('The form has no proof page'); + } + + /** One entry of a document type holding the given number of files */ + function getEntry(documentType: string, count: number, savedFileKey?: string) { + const files = Array.from({length: count}, (_, index) => ({ + name: `${documentType}-${index}.pdf`, + uri: `file://${documentType}-${index}.pdf`, + ...(savedFileKey ? {savedFileKey} : {}), + })); + return {id: documentType, fileType: documentType, files}; + } + + it('finds no field while the new files fit in one save', () => { + // Given revenue and grants with exactly as many new files as one save takes + const answers = { + businessSourceOfWealthInfo: [CONST.WISE.SOURCE_OF_WEALTH.REVENUE, CONST.WISE.SOURCE_OF_WEALTH.GRANTS], + [`proofFile-${CONST.WISE.SOURCE_OF_WEALTH.REVENUE}`]: [getEntry('TAX_DOCUMENTS', 10)], + [`proofFile-${CONST.WISE.SOURCE_OF_WEALTH.GRANTS}`]: [getEntry('GRANT_APPROVAL_LETTER', 5), getEntry('BANK_STATEMENT', 5)], + }; + + // When the page is checked + // Then no field is over the limit + expect(getFieldOverNewFileLimit(form, proofPage, answers)).toBeUndefined(); + }); + + it('finds the field at which the new files pass what one save takes', () => { + // Given one new file more than one save takes, the last one under grants + const answers = { + businessSourceOfWealthInfo: [CONST.WISE.SOURCE_OF_WEALTH.REVENUE, CONST.WISE.SOURCE_OF_WEALTH.GRANTS], + [`proofFile-${CONST.WISE.SOURCE_OF_WEALTH.REVENUE}`]: [getEntry('TAX_DOCUMENTS', 10)], + [`proofFile-${CONST.WISE.SOURCE_OF_WEALTH.GRANTS}`]: [getEntry('GRANT_APPROVAL_LETTER', 10), getEntry('BANK_STATEMENT', 1)], + }; + + // When the page is checked + // Then grants is over the limit, since the server would drop its last file without an error + expect(getFieldOverNewFileLimit(form, proofPage, answers)).toBe(`proofFile-${CONST.WISE.SOURCE_OF_WEALTH.GRANTS}`); + }); + + it('leaves out files the server holds and fields of sources no longer picked', () => { + // Given ten saved revenue files, eleven new grant files, and new files of a donation source the user unpicked + const answers = { + businessSourceOfWealthInfo: [CONST.WISE.SOURCE_OF_WEALTH.REVENUE, CONST.WISE.SOURCE_OF_WEALTH.GRANTS], + [`proofFile-${CONST.WISE.SOURCE_OF_WEALTH.REVENUE}`]: [getEntry('TAX_DOCUMENTS', 10, 'kyc/1/tax.pdf')], + [`proofFile-${CONST.WISE.SOURCE_OF_WEALTH.GRANTS}`]: [getEntry('GRANT_APPROVAL_LETTER', 10), getEntry('BANK_STATEMENT', 1)], + [`proofFile-${CONST.WISE.SOURCE_OF_WEALTH.DONATIONS}`]: [getEntry('DONATION_RECEIPTS', 10)], + }; + + // When the page is checked + // Then no field is over the limit, since the save sends only the new files of the shown sources + expect(getFieldOverNewFileLimit(form, proofPage, answers)).toBeUndefined(); + }); +});