-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Expand file tree
/
Copy pathuseConfirmationValidation.ts
More file actions
319 lines (263 loc) · 13.1 KB
/
Copy pathuseConfirmationValidation.ts
File metadata and controls
319 lines (263 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
import {useCurrencyListActions} from '@hooks/useCurrencyList';
import {isValidPerDiemExpenseAmount} from '@libs/actions/IOU/PerDiem';
import {getIsMissingAttendeesViolation} from '@libs/AttendeeUtils';
import {isCategoryMissing} from '@libs/CategoryUtils';
import {convertToFrontendAmountAsString} from '@libs/CurrencyUtils';
import {isTaxAmountInvalid, isValidMoneyRequestAmount, validateAmount} from '@libs/MoneyRequestUtils';
import type {getTagLists as getTagListsFn} from '@libs/PolicyUtils';
import {isAttendeeTrackingEnabled} from '@libs/PolicyUtils';
import {hasEnabledTags, hasMatchingTag} from '@libs/TagsOptionsListUtils';
import {isValidTimeExpenseAmount} from '@libs/TimeTrackingUtils';
import {
areRequiredFieldsEmpty,
getCalculatedTaxAmount,
getTag,
getTaxAmount,
hasTaxRateWithMatchingValue,
isCreatedMissing,
isMerchantMissing,
isScanRequest as isScanRequestUtil,
} from '@libs/TransactionUtils';
import {isValidInputLength} from '@libs/ValidationUtils';
import type {IOUType} from '@src/CONST';
import CONST from '@src/CONST';
import type {TranslationPaths} from '@src/languages/types';
import type * as OnyxTypes from '@src/types/onyx';
import type {Attendee, Participant} from '@src/types/onyx/IOU';
import type {PaymentMethodType} from '@src/types/onyx/OriginalMessage';
import type {CurrentUserPersonalDetails} from '@src/types/onyx/PersonalDetails';
import type {OnyxEntry} from 'react-native-onyx';
type ValidationResult = {errorKey: TranslationPaths; shouldSetDidConfirmSplit?: boolean} | {errorKey: null};
type UseConfirmationValidationParams = {
/** Transaction being validated */
transaction: OnyxEntry<OnyxTypes.Transaction>;
/** Report the IOU is being created on */
transactionReport: OnyxEntry<OnyxTypes.Report>;
/** Transaction ID, used to scope tag/violation lookups */
transactionID: string | undefined;
/** IOU type being confirmed (submit / split / track / pay / invoice) */
iouType: IOUType;
/** Total IOU amount being validated */
iouAmount: number;
/** Current merchant value entered for the IOU */
iouMerchant: string | undefined;
/** Currently selected category */
iouCategory: string;
/** Currency the IOU is being created in */
iouCurrencyCode: string;
/** Currently selected attendees */
iouAttendees: Attendee[];
/** Policy the IOU belongs to */
policy: OnyxEntry<OnyxTypes.Policy>;
/** Policy tag lists, used for tag validation */
policyTags: OnyxEntry<OnyxTypes.PolicyTagLists>;
/** Pre-resolved tag lists for the policy (output of getTagLists) */
policyTagLists: ReturnType<typeof getTagListsFn>;
/** Policy categories, used for category validation */
policyCategories: OnyxEntry<OnyxTypes.PolicyCategories>;
/** Participants selected for this IOU */
selectedParticipants: Participant[];
/** Personal details of the current user */
currentUserPersonalDetails: CurrentUserPersonalDetails;
/** Whether we are editing an existing split bill */
isEditingSplitBill: boolean | undefined;
/** Whether the merchant field is required for this flow */
isMerchantRequired: boolean | undefined;
/** Whether the merchant value passes full validation (length, required, disallowed values) */
isMerchantFieldValid: boolean;
/** Whether the merchant field is empty / partial (from {@link useFormErrorManagement}) */
isMerchantEmpty: boolean;
/** When editing a split bill, whether per-field errors should be shown (SmartScan failure paths) */
shouldDisplayFieldError: boolean;
/** Whether the tax section is enabled for this policy */
shouldShowTax: boolean;
/** Whether the transaction is a distance request */
isDistanceRequest: boolean;
/** Whether the distance request route is still pending */
isDistanceRequestWithPendingRoute: boolean;
/** Whether the transaction is a per-diem request */
isPerDiemRequest: boolean;
/** Whether the transaction is a time-tracking request */
isTimeRequest: boolean;
/** Truthy when the route to the confirmation page has a known error */
routeError: string | null | undefined;
/** Whether the confirmation fields are read-only (date is not inline-editable) */
isReadOnly: boolean;
/** Whether the date field is shown for this flow (mirrors the footer's date visibility) */
shouldShowDate: boolean;
};
/**
* Runs the set of pure validation checks for the Money Request confirmation
* flow and returns either a translation key describing the first failure, or
* a success signal.
*
* Side effects (setting form error, firing onConfirm / onSendMoney,
* navigating to the company info route, showing the delegate-no-access modal)
* stay in the caller.
*
* The Invoice -> Company Info routing check stays in the caller as well:
* it is a routing decision that happens before validation runs, so the
* caller guards the call to `validate()` with its own
* `iouType === INVOICE && !hasInvoicingDetails(policy)` check.
*/
function useConfirmationValidation({
transaction,
transactionReport,
transactionID,
iouType,
iouAmount,
iouMerchant,
iouCategory,
iouCurrencyCode,
iouAttendees,
policy,
policyTags,
policyTagLists,
policyCategories,
selectedParticipants,
currentUserPersonalDetails,
isEditingSplitBill,
isMerchantRequired,
isMerchantFieldValid,
isMerchantEmpty,
shouldDisplayFieldError,
shouldShowTax,
isDistanceRequest,
isDistanceRequestWithPendingRoute,
isPerDiemRequest,
isTimeRequest,
routeError,
isReadOnly,
shouldShowDate,
}: UseConfirmationValidationParams): {validate: (paymentType?: PaymentMethodType) => ValidationResult | null} {
const {getCurrencyDecimals} = useCurrencyListActions();
const selectedParticipantsCount = selectedParticipants.length;
const validate = (paymentType?: PaymentMethodType): ValidationResult | null => {
if (!!routeError || !transactionID) {
return null;
}
if (selectedParticipantsCount === 0) {
return {errorKey: 'iou.error.noParticipantSelected'};
}
const firstParticipant = transaction?.participants?.at(0);
const isP2P = !!(firstParticipant?.accountID && !firstParticipant?.isPolicyExpenseChat && !firstParticipant?.isSelfDM);
// P2P manual submit: $0 is invalid unless scan/time/distance (same guard as legacy inline confirm).
if (!isScanRequestUtil(transaction) && !isTimeRequest && !isDistanceRequest && iouAmount === 0 && isP2P) {
return {errorKey: 'common.error.invalidAmount'};
}
// isAmountSet only applies to manual expenses — scan, per diem, distance, and time set amount programmatically.
if (transaction?.iouRequestType === CONST.IOU.REQUEST_TYPE.MANUAL && !transaction?.isAmountSet) {
return {errorKey: 'common.error.fieldRequired'};
}
if (
transaction?.iouRequestType === CONST.IOU.REQUEST_TYPE.MANUAL &&
transaction?.isAmountSet &&
!isScanRequestUtil(transaction) &&
!isTimeRequest &&
!isDistanceRequest &&
!isEditingSplitBill &&
!isValidMoneyRequestAmount(iouAmount, iouType, true, isP2P)
) {
return {errorKey: 'common.error.invalidAmount'};
}
// The date is an inline, clearable required field in the new manual flow for every type that shows it
// (manual, distance, time, invoice, ...). Block confirmation when the user cleared it. Gating on the same
// `shouldShowDate && !isReadOnly` condition that renders the inline picker keeps validation and UI in sync,
// and skips read-only/scan flows where the date is populated server-side.
if (shouldShowDate && !isReadOnly && isCreatedMissing(transaction)) {
return {errorKey: 'common.error.fieldRequired'};
}
const merchantValue = iouMerchant ?? '';
const {isValid: isMerchantLengthValid} = isValidInputLength(merchantValue, CONST.MERCHANT_NAME_MAX_BYTES);
if (!isMerchantLengthValid) {
return {errorKey: 'iou.error.invalidMerchant'};
}
if (isMerchantRequired) {
if (!isEditingSplitBill && !isMerchantFieldValid) {
return {errorKey: 'iou.error.invalidMerchant'};
}
if (isEditingSplitBill && (isMerchantEmpty || (shouldDisplayFieldError && isMerchantMissing(transaction)))) {
return {errorKey: 'iou.error.invalidMerchant'};
}
} else if (transaction?.isMerchantSet && !isMerchantFieldValid) {
return {errorKey: 'iou.error.invalidMerchant'};
}
if (iouCategory.length > CONST.API_TRANSACTION_CATEGORY_MAX_LENGTH) {
return {errorKey: 'iou.error.invalidCategoryLength'};
}
const isCategoryBeingCreated = policyCategories?.[iouCategory]?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD;
// The 'Uncategorized'/'none' sentinel means no category, so treat it as missing (not out of policy) here, mirroring
// isCategoryMissing/ViolationsUtils. Otherwise it wrongly blocks confirmation when the policy lacks that literal category.
if (iouCategory && !isCategoryMissing(iouCategory) && policyCategories && !policyCategories[iouCategory]?.enabled && !isCategoryBeingCreated) {
return {errorKey: 'violations.categoryOutOfPolicy'};
}
const transactionTag = getTag(transaction);
if (transactionTag.length > CONST.API_TRANSACTION_TAG_MAX_LENGTH) {
return {errorKey: 'iou.error.invalidTagLength'};
}
if (transactionTag && hasEnabledTags(policyTagLists) && !hasMatchingTag(policyTags, transactionTag)) {
return {errorKey: 'violations.tagOutOfPolicy'};
}
// Since invoices are not expense reports that need attendee tracking, this validation should not apply to invoices
const isMissingAttendeesViolation =
iouType !== CONST.IOU.TYPE.INVOICE &&
getIsMissingAttendeesViolation(
policyCategories,
iouCategory,
iouAttendees,
currentUserPersonalDetails,
isAttendeeTrackingEnabled(policy),
policy?.type === CONST.POLICY.TYPE.CORPORATE,
);
if (isMissingAttendeesViolation) {
return {errorKey: 'violations.missingAttendees'};
}
if (shouldShowTax && !!transaction?.taxCode && !hasTaxRateWithMatchingValue(policy, transaction)) {
return {errorKey: 'violations.taxOutOfPolicy'};
}
// In the new manual expense flow the tax amount is edited inline, so the standalone tax amount step's
// guard (tax amount can't exceed the tax computed from the rate and the expense amount) runs here.
// This also blocks creation when an invalid tax amount was persisted to the draft and then reloaded.
if (shouldShowTax && !isDistanceRequest) {
const decimals = getCurrencyDecimals(iouCurrencyCode);
const maxTaxAmount = getCalculatedTaxAmount(policy, transaction, iouCurrencyCode, decimals);
const currentTaxAmount = convertToFrontendAmountAsString(Math.abs(getTaxAmount(transaction, false)), decimals);
if (isTaxAmountInvalid(currentTaxAmount, maxTaxAmount, decimals)) {
return {errorKey: 'iou.error.invalidTaxAmount'};
}
}
if (isPerDiemRequest && (transaction?.comment?.customUnit?.subRates ?? []).length === 0) {
return {errorKey: 'iou.error.invalidSubrateLength'};
}
if (iouType !== CONST.IOU.TYPE.PAY) {
const decimals = getCurrencyDecimals(iouCurrencyCode);
if (isDistanceRequest && !isDistanceRequestWithPendingRoute && !validateAmount(String(iouAmount), decimals, CONST.IOU.DISTANCE_REQUEST_AMOUNT_MAX_LENGTH)) {
return {errorKey: 'common.error.invalidAmount'};
}
if (isDistanceRequest && Math.abs(iouAmount) > CONST.IOU.MAX_SAFE_AMOUNT) {
return {errorKey: 'iou.error.distanceAmountTooLarge'};
}
if (isTimeRequest && !isValidTimeExpenseAmount(iouAmount, decimals)) {
return {errorKey: 'iou.timeTracking.amountTooLargeError'};
}
if (isPerDiemRequest && !isValidPerDiemExpenseAmount(transaction?.comment?.customUnit ?? {}, decimals)) {
return {errorKey: 'iou.error.invalidQuantity'};
}
if (isEditingSplitBill && areRequiredFieldsEmpty(transaction, transactionReport)) {
return {errorKey: 'iou.error.genericSmartscanFailureMessage', shouldSetDidConfirmSplit: true};
}
if (isEditingSplitBill && iouAmount === 0) {
return {errorKey: 'iou.error.invalidAmount'};
}
return {errorKey: null};
}
// PAY branch: require payment method
if (!paymentType) {
return null;
}
return {errorKey: null};
};
return {validate};
}
export default useConfirmationValidation;
export type {UseConfirmationValidationParams};