-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathMoneyRequestPreviewContent.tsx
376 lines (345 loc) · 20.7 KB
/
MoneyRequestPreviewContent.tsx
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
import {truncate} from 'lodash';
import lodashSortBy from 'lodash/sortBy';
import React, {useMemo} from 'react';
import {View} from 'react-native';
import type {GestureResponderEvent} from 'react-native';
import ConfirmedRoute from '@components/ConfirmedRoute';
import Icon from '@components/Icon';
import * as Expensicons from '@components/Icon/Expensicons';
import {ReceiptScan} from '@components/Icon/Expensicons';
import MoneyRequestSkeletonView from '@components/MoneyRequestSkeletonView';
import MultipleAvatars from '@components/MultipleAvatars';
import OfflineWithFeedback from '@components/OfflineWithFeedback';
import PressableWithoutFeedback from '@components/Pressable/PressableWithoutFeedback';
import ReportActionItemImages from '@components/ReportActionItem/ReportActionItemImages';
import {showContextMenuForReport} from '@components/ShowContextMenuContext';
import Text from '@components/Text';
import useLocalize from '@hooks/useLocalize';
import useStyleUtils from '@hooks/useStyleUtils';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import useWindowDimensions from '@hooks/useWindowDimensions';
import ControlSelection from '@libs/ControlSelection';
import * as CurrencyUtils from '@libs/CurrencyUtils';
import * as DeviceCapabilities from '@libs/DeviceCapabilities';
import * as IOUUtils from '@libs/IOUUtils';
import * as OptionsListUtils from '@libs/OptionsListUtils';
import * as ReceiptUtils from '@libs/ReceiptUtils';
import * as ReportActionsUtils from '@libs/ReportActionsUtils';
import * as ReportUtils from '@libs/ReportUtils';
import * as TransactionUtils from '@libs/TransactionUtils';
import ViolationsUtils from '@libs/Violations/ViolationsUtils';
import variables from '@styles/variables';
import * as PaymentMethods from '@userActions/PaymentMethods';
import * as Report from '@userActions/Report';
import CONST from '@src/CONST';
import type {IOUMessage} from '@src/types/onyx/OriginalMessage';
import type {EmptyObject} from '@src/types/utils/EmptyObject';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
import type {MoneyRequestPreviewProps} from './types';
function MoneyRequestPreviewContent({
iouReport,
isBillSplit,
session,
action,
personalDetails,
chatReport,
transaction,
contextMenuAnchor,
chatReportID,
reportID,
onPreviewPressed,
containerStyles,
walletTerms,
checkIfContextMenuActive = () => {},
shouldShowPendingConversionMessage = false,
isHovered = false,
isWhisper = false,
transactionViolations,
}: MoneyRequestPreviewProps) {
const theme = useTheme();
const styles = useThemeStyles();
const StyleUtils = useStyleUtils();
const {translate} = useLocalize();
const {isSmallScreenWidth, windowWidth} = useWindowDimensions();
const sessionAccountID = session?.accountID;
const managerID = iouReport?.managerID ?? -1;
const ownerAccountID = iouReport?.ownerAccountID ?? -1;
const isPolicyExpenseChat = ReportUtils.isPolicyExpenseChat(chatReport);
const participantAccountIDs = action.actionName === CONST.REPORT.ACTIONS.TYPE.IOU && isBillSplit ? action.originalMessage.participantAccountIDs ?? [] : [managerID, ownerAccountID];
const participantAvatars = OptionsListUtils.getAvatarsForAccountIDs(participantAccountIDs, personalDetails ?? {});
const sortedParticipantAvatars = lodashSortBy(participantAvatars, (avatar) => avatar.id);
if (isPolicyExpenseChat && isBillSplit) {
sortedParticipantAvatars.push(ReportUtils.getWorkspaceIcon(chatReport));
}
// Pay button should only be visible to the manager of the report.
const isCurrentUserManager = managerID === sessionAccountID;
const {amount: requestAmount, currency: requestCurrency, comment: requestComment, merchant} = ReportUtils.getTransactionDetails(transaction) ?? {};
const description = truncate(requestComment, {length: CONST.REQUEST_PREVIEW.MAX_LENGTH});
const requestMerchant = truncate(merchant, {length: CONST.REQUEST_PREVIEW.MAX_LENGTH});
const hasReceipt = TransactionUtils.hasReceipt(transaction);
const isScanning = hasReceipt && TransactionUtils.isReceiptBeingScanned(transaction);
const isPending = TransactionUtils.isPending(transaction);
const isOnHold = TransactionUtils.isOnHold(transaction);
const isSettlementOrApprovalPartial = Boolean(iouReport?.pendingFields?.partial);
const isPartialHold = isSettlementOrApprovalPartial && isOnHold;
const hasViolations = TransactionUtils.hasViolation(transaction?.transactionID ?? '', transactionViolations);
const hasNoticeTypeViolations = TransactionUtils.hasNoticeTypeViolation(transaction?.transactionID ?? '', transactionViolations);
const hasFieldErrors = TransactionUtils.hasMissingSmartscanFields(transaction);
const isDistanceRequest = TransactionUtils.isDistanceRequest(transaction);
const isFetchingWaypointsFromServer = TransactionUtils.isFetchingWaypointsFromServer(transaction);
const isCardTransaction = TransactionUtils.isCardTransaction(transaction);
const isSettled = ReportUtils.isSettled(iouReport?.reportID);
const isDeleted = action?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE;
const isFullySettled = isSettled && !isSettlementOrApprovalPartial;
const isFullyApproved = ReportUtils.isReportApproved(iouReport) && !isSettlementOrApprovalPartial;
const shouldShowRBR = hasNoticeTypeViolations || hasViolations || hasFieldErrors || (!isFullySettled && !isFullyApproved && isOnHold);
/*
Show the merchant for IOUs and expenses only if:
- the merchant is not empty, is custom, or is not related to scanning smartscan;
- the expense is not a distance expense with a pending route and amount = 0 - in this case,
the merchant says: "Route pending...", which is already shown in the amount field;
*/
const shouldShowMerchant =
!!requestMerchant &&
requestMerchant !== CONST.TRANSACTION.PARTIAL_TRANSACTION_MERCHANT &&
requestMerchant !== CONST.TRANSACTION.DEFAULT_MERCHANT &&
!(isFetchingWaypointsFromServer && !requestAmount);
const shouldShowDescription = !!description && !shouldShowMerchant && !isScanning;
let merchantOrDescription = requestMerchant;
if (!shouldShowMerchant) {
merchantOrDescription = description || '';
}
const receiptImages = hasReceipt ? [ReceiptUtils.getThumbnailAndImageURIs(transaction)] : [];
const hasPendingWaypoints = transaction?.pendingFields?.waypoints;
const showMapAsImage = isDistanceRequest && hasPendingWaypoints;
const getSettledMessage = (): string => {
if (isCardTransaction) {
return translate('common.done');
}
return translate('iou.settledExpensify');
};
const showContextMenu = (event: GestureResponderEvent) => {
showContextMenuForReport(event, contextMenuAnchor, reportID, action, checkIfContextMenuActive);
};
const getPreviewHeaderText = (): string => {
let message = translate('iou.cash');
if (isDistanceRequest) {
message = translate('common.distance');
} else if (isScanning) {
message = translate('common.receipt');
} else if (isBillSplit) {
message = translate('iou.split');
}
if (isSettled && !iouReport?.isCancelledIOU && !isPartialHold) {
message += ` ${CONST.DOT_SEPARATOR} ${getSettledMessage()}`;
return message;
}
if (shouldShowRBR && transaction) {
const violations = TransactionUtils.getTransactionViolations(transaction.transactionID, transactionViolations);
if (violations?.[0]) {
const violationMessage = ViolationsUtils.getViolationTranslation(violations[0], translate);
const violationsCount = violations.filter((v) => v.type === CONST.VIOLATION_TYPES.VIOLATION).length;
const isTooLong = violationsCount > 1 || violationMessage.length > 15;
const hasViolationsAndFieldErrors = violationsCount > 0 && hasFieldErrors;
return `${message} ${CONST.DOT_SEPARATOR} ${isTooLong || hasViolationsAndFieldErrors ? translate('violations.reviewRequired') : violationMessage}`;
}
const isMerchantMissing = TransactionUtils.isMerchantMissing(transaction);
const isAmountMissing = TransactionUtils.isAmountMissing(transaction);
if (isAmountMissing && isMerchantMissing) {
message += ` ${CONST.DOT_SEPARATOR} ${translate('violations.reviewRequired')}`;
} else if (isAmountMissing) {
message += ` ${CONST.DOT_SEPARATOR} ${translate('iou.missingAmount')}`;
} else if (isMerchantMissing) {
message += ` ${CONST.DOT_SEPARATOR} ${translate('iou.missingMerchant')}`;
} else if (!(isSettled && !isSettlementOrApprovalPartial) && isOnHold) {
message += ` ${CONST.DOT_SEPARATOR} ${translate('iou.hold')}`;
}
} else if (hasNoticeTypeViolations && transaction && !ReportUtils.isReportApproved(iouReport) && !ReportUtils.isSettled(iouReport?.reportID)) {
message += ` • ${translate('violations.reviewRequired')}`;
} else if (ReportUtils.isPaidGroupPolicyExpenseReport(iouReport) && ReportUtils.isReportApproved(iouReport) && !ReportUtils.isSettled(iouReport?.reportID) && !isPartialHold) {
message += ` ${CONST.DOT_SEPARATOR} ${translate('iou.approved')}`;
} else if (iouReport?.isCancelledIOU) {
message += ` ${CONST.DOT_SEPARATOR} ${translate('iou.canceled')}`;
} else if (!(isSettled && !isSettlementOrApprovalPartial) && isOnHold) {
message += ` ${CONST.DOT_SEPARATOR} ${translate('iou.hold')}`;
}
return message;
};
const getDisplayAmountText = (): string => {
if (isScanning) {
return translate('iou.receiptScanning');
}
if (isFetchingWaypointsFromServer && !requestAmount) {
return translate('iou.fieldPending');
}
return CurrencyUtils.convertToDisplayString(requestAmount, requestCurrency);
};
const getDisplayDeleteAmountText = (): string => {
const iouOriginalMessage: IOUMessage | EmptyObject = action?.actionName === CONST.REPORT.ACTIONS.TYPE.IOU ? action.originalMessage : {};
const {amount = 0, currency = CONST.CURRENCY.USD} = iouOriginalMessage;
return CurrencyUtils.convertToDisplayString(amount, currency);
};
const displayAmount = isDeleted ? getDisplayDeleteAmountText() : getDisplayAmountText();
const shouldShowSplitShare = isBillSplit && !!requestAmount && requestAmount > 0;
// If available, retrieve the split share from the splits object of the transaction, if not, display an even share.
const splitShare = useMemo(
() =>
shouldShowSplitShare &&
(transaction?.comment?.splits?.find((split) => split.accountID === sessionAccountID)?.amount ??
IOUUtils.calculateAmount(isPolicyExpenseChat ? 1 : participantAccountIDs.length - 1, requestAmount, requestCurrency ?? '', action.actorAccountID === sessionAccountID)),
[shouldShowSplitShare, isPolicyExpenseChat, action.actorAccountID, participantAccountIDs.length, transaction?.comment?.splits, requestAmount, requestCurrency, sessionAccountID],
);
const childContainer = (
<View>
<OfflineWithFeedback
errors={walletTerms?.errors}
onClose={() => {
PaymentMethods.clearWalletTermsError();
Report.clearIOUError(chatReportID);
}}
errorRowStyles={[styles.mbn1]}
needsOffscreenAlphaCompositing
>
<View
style={[
isScanning || isWhisper ? [styles.reportPreviewBoxHoverBorder, styles.reportContainerBorderRadius] : undefined,
!onPreviewPressed ? [styles.moneyRequestPreviewBox, containerStyles] : {},
]}
>
{showMapAsImage && (
<View style={styles.reportActionItemImages}>
<ConfirmedRoute
transaction={transaction}
interactive={false}
/>
</View>
)}
{!showMapAsImage && hasReceipt && (
<ReportActionItemImages
images={receiptImages}
isHovered={isHovered || isScanning}
size={1}
/>
)}
{isEmptyObject(transaction) && !ReportActionsUtils.isMessageDeleted(action) && action.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE ? (
<MoneyRequestSkeletonView />
) : (
<View style={[styles.expenseAndReportPreviewBoxBody, hasReceipt ? styles.mtn1 : {}]}>
<View style={styles.expenseAndReportPreviewTextButtonContainer}>
<View style={styles.expenseAndReportPreviewTextContainer}>
<View style={[styles.flexRow]}>
<Text style={[styles.textLabelSupporting, styles.flex1, styles.lh16]}>{getPreviewHeaderText()}</Text>
{!isSettled && shouldShowRBR && (
<Icon
src={Expensicons.DotIndicator}
fill={theme.danger}
/>
)}
</View>
<View style={styles.reportPreviewAmountSubtitleContainer}>
<View style={[styles.flexRow]}>
<View style={[styles.flex1, styles.flexRow, styles.alignItemsCenter]}>
<Text
style={[
styles.textHeadlineH1,
isBillSplit &&
StyleUtils.getAmountFontSizeAndLineHeight(isSmallScreenWidth, windowWidth, displayAmount.length, sortedParticipantAvatars.length),
isDeleted && styles.lineThrough,
]}
numberOfLines={1}
>
{displayAmount}
</Text>
{ReportUtils.isSettled(iouReport?.reportID) && !isPartialHold && !isBillSplit && (
<View style={styles.defaultCheckmarkWrapper}>
<Icon
src={Expensicons.Checkmark}
fill={theme.iconSuccessFill}
/>
</View>
)}
</View>
{isBillSplit && (
<View style={styles.moneyRequestPreviewBoxAvatar}>
<MultipleAvatars
icons={sortedParticipantAvatars}
shouldStackHorizontally
size="small"
shouldUseCardBackground
/>
</View>
)}
</View>
<View style={[styles.flexRow]}>
<View style={[styles.flex1]}>
{!isCurrentUserManager && shouldShowPendingConversionMessage && (
<Text style={[styles.textLabel, styles.colorMuted]}>{translate('iou.pendingConversionMessage')}</Text>
)}
{(shouldShowMerchant || shouldShowDescription) && (
<Text style={[styles.textLabelSupporting, styles.textNormal]}>{merchantOrDescription}</Text>
)}
</View>
{splitShare && (
<Text style={[styles.textLabel, styles.colorMuted, styles.ml1, styles.amountSplitPadding]}>
{translate('iou.yourSplit', {amount: CurrencyUtils.convertToDisplayString(splitShare ?? 0, requestCurrency ?? '')})}
</Text>
)}
</View>
{isScanning && (
<View style={[styles.flexRow, styles.alignItemsCenter, styles.mt2]}>
<Icon
src={ReceiptScan}
height={variables.iconSizeExtraSmall}
width={variables.iconSizeExtraSmall}
fill={theme.textSupporting}
/>
<Text style={[styles.textMicroSupporting, styles.ml1, styles.amountSplitPadding]}>{translate('iou.receiptScanInProgress')}</Text>
</View>
)}
{isPending && (
<View style={[styles.flexRow, styles.alignItemsCenter, styles.mt2]}>
<Icon
src={Expensicons.CreditCardHourglass}
height={variables.iconSizeExtraSmall}
width={variables.iconSizeExtraSmall}
fill={theme.textSupporting}
/>
<Text style={[styles.textMicroSupporting, styles.ml1, styles.amountSplitPadding]}>{translate('iou.transactionPending')}</Text>
</View>
)}
</View>
</View>
</View>
</View>
)}
</View>
</OfflineWithFeedback>
</View>
);
if (!onPreviewPressed) {
return childContainer;
}
const shouldDisableOnPress = isBillSplit && isEmptyObject(transaction);
return (
<PressableWithoutFeedback
onPress={shouldDisableOnPress ? undefined : onPreviewPressed}
onPressIn={() => DeviceCapabilities.canUseTouchScreen() && ControlSelection.block()}
onPressOut={() => ControlSelection.unblock()}
onLongPress={showContextMenu}
shouldUseHapticsOnLongPress
accessibilityLabel={isBillSplit ? translate('iou.split') : translate('iou.cash')}
accessibilityHint={CurrencyUtils.convertToDisplayString(requestAmount, requestCurrency)}
style={[
styles.moneyRequestPreviewBox,
containerStyles,
shouldDisableOnPress && styles.cursorDefault,
(isSettled || ReportUtils.isReportApproved(iouReport)) && isSettlementOrApprovalPartial && styles.offlineFeedback.pending,
]}
>
{childContainer}
</PressableWithoutFeedback>
);
}
MoneyRequestPreviewContent.displayName = 'MoneyRequestPreview';
export default MoneyRequestPreviewContent;