-
Notifications
You must be signed in to change notification settings - Fork 3k
/
ReportPreview.tsx
385 lines (341 loc) · 19.8 KB
/
ReportPreview.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
377
378
379
380
381
382
383
384
385
import ExpensiMark from 'expensify-common/lib/ExpensiMark';
import React, {useMemo} from 'react';
import type {StyleProp, ViewStyle} from 'react-native';
import {View} from 'react-native';
import type {OnyxCollection, OnyxEntry} from 'react-native-onyx';
import {withOnyx} from 'react-native-onyx';
import Button from '@components/Button';
import Icon from '@components/Icon';
import * as Expensicons from '@components/Icon/Expensicons';
import OfflineWithFeedback from '@components/OfflineWithFeedback';
import PressableWithoutFeedback from '@components/Pressable/PressableWithoutFeedback';
import RenderHTML from '@components/RenderHTML';
import SettlementButton from '@components/SettlementButton';
import {showContextMenuForReport} from '@components/ShowContextMenuContext';
import Text from '@components/Text';
import useLocalize from '@hooks/useLocalize';
import usePermissions from '@hooks/usePermissions';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import ControlSelection from '@libs/ControlSelection';
import * as CurrencyUtils from '@libs/CurrencyUtils';
import * as DeviceCapabilities from '@libs/DeviceCapabilities';
import Navigation from '@libs/Navigation/Navigation';
import * as ReceiptUtils from '@libs/ReceiptUtils';
import * as ReportActionUtils from '@libs/ReportActionsUtils';
import * as ReportUtils from '@libs/ReportUtils';
import * as TransactionUtils from '@libs/TransactionUtils';
import type {ContextMenuAnchor} from '@pages/home/report/ContextMenu/ReportActionContextMenu';
import * as IOU from '@userActions/IOU';
import CONST from '@src/CONST';
import type {TranslationPaths} from '@src/languages/types';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import type {Policy, Report, ReportAction, Transaction, TransactionViolations, UserWallet} from '@src/types/onyx';
import type {PaymentMethodType} from '@src/types/onyx/OriginalMessage';
import ReportActionItemImages from './ReportActionItemImages';
type ReportPreviewOnyxProps = {
/** The policy tied to the money request report */
policy: OnyxEntry<Policy>;
/** ChatReport associated with iouReport */
chatReport: OnyxEntry<Report>;
/** Active IOU Report for current report */
iouReport: OnyxEntry<Report>;
/** All the transactions, used to update ReportPreview label and status */
transactions: OnyxCollection<Transaction>;
/** All of the transaction violations */
transactionViolations: OnyxCollection<TransactionViolations>;
/** The user's wallet account */
userWallet: OnyxEntry<UserWallet>;
};
type ReportPreviewProps = ReportPreviewOnyxProps & {
/** All the data of the action */
action: ReportAction;
/** The associated chatReport */
chatReportID: string;
/** The active IOUReport, used for Onyx subscription */
iouReportID: string;
/** The report's policyID, used for Onyx subscription */
policyID: string;
/** Extra styles to pass to View wrapper */
containerStyles?: StyleProp<ViewStyle>;
/** Popover context menu anchor, used for showing context menu */
contextMenuAnchor?: ContextMenuAnchor;
/** Callback for updating context menu active state, used for showing context menu */
checkIfContextMenuActive?: () => void;
/** Whether a message is a whisper */
isWhisper?: boolean;
/** Whether the corresponding report action item is hovered */
isHovered?: boolean;
};
function ReportPreview({
iouReport,
policy,
iouReportID,
policyID,
chatReportID,
chatReport,
action,
containerStyles,
contextMenuAnchor,
transactions,
transactionViolations,
isHovered = false,
isWhisper = false,
checkIfContextMenuActive = () => {},
userWallet,
}: ReportPreviewProps) {
const theme = useTheme();
const styles = useThemeStyles();
const {translate} = useLocalize();
const {canUseViolations} = usePermissions();
const {hasMissingSmartscanFields, areAllRequestsBeingSmartScanned, hasOnlyTransactionsWithPendingRoutes, hasNonReimbursableTransactions} = useMemo(
() => ({
hasMissingSmartscanFields: ReportUtils.hasMissingSmartscanFields(iouReportID),
areAllRequestsBeingSmartScanned: ReportUtils.areAllRequestsBeingSmartScanned(iouReportID, action),
hasOnlyTransactionsWithPendingRoutes: ReportUtils.hasOnlyTransactionsWithPendingRoutes(iouReportID),
hasNonReimbursableTransactions: ReportUtils.hasNonReimbursableTransactions(iouReportID),
}),
// When transactions get updated these status may have changed, so that is a case where we also want to run this.
// eslint-disable-next-line react-hooks/exhaustive-deps
[transactions, iouReportID, action],
);
const managerID = iouReport?.managerID ?? 0;
const {totalDisplaySpend, reimbursableSpend} = ReportUtils.getMoneyRequestSpendBreakdown(iouReport);
const iouSettled = ReportUtils.isSettled(iouReportID);
const numberOfRequests = ReportActionUtils.getNumberOfMoneyRequests(action);
const moneyRequestComment = action?.childLastMoneyRequestComment ?? '';
const isPolicyExpenseChat = ReportUtils.isPolicyExpenseChat(chatReport);
const isOpenExpenseReport = isPolicyExpenseChat && ReportUtils.isOpenExpenseReport(iouReport);
const isApproved = ReportUtils.isReportApproved(iouReport);
const canAllowSettlement = ReportUtils.hasUpdatedTotal(iouReport, policy);
const allTransactions = TransactionUtils.getAllReportTransactions(iouReportID);
const transactionsWithReceipts = ReportUtils.getTransactionsWithReceipts(iouReportID);
const numberOfScanningReceipts = transactionsWithReceipts.filter((transaction) => TransactionUtils.isReceiptBeingScanned(transaction)).length;
const numberOfPendingRequests = transactionsWithReceipts.filter((transaction) => TransactionUtils.isPending(transaction) && TransactionUtils.isCardTransaction(transaction)).length;
const hasReceipts = transactionsWithReceipts.length > 0;
const isScanning = hasReceipts && areAllRequestsBeingSmartScanned;
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
const hasErrors = hasMissingSmartscanFields || (canUseViolations && ReportUtils.hasViolations(iouReportID, transactionViolations)) || ReportUtils.hasActionsWithErrors(iouReportID);
const lastThreeTransactionsWithReceipts = transactionsWithReceipts.slice(-3);
const lastThreeReceipts = lastThreeTransactionsWithReceipts.map((transaction) => ReceiptUtils.getThumbnailAndImageURIs(transaction));
let formattedMerchant = numberOfRequests === 1 ? TransactionUtils.getMerchant(allTransactions[0]) : null;
const formattedDescription = numberOfRequests === 1 ? TransactionUtils.getDescription(allTransactions[0]) : null;
if (TransactionUtils.isPartialMerchant(formattedMerchant ?? '')) {
formattedMerchant = null;
}
const shouldShowSubmitButton = isOpenExpenseReport && reimbursableSpend !== 0;
const shouldDisableSubmitButton = shouldShowSubmitButton && !ReportUtils.isAllowedToSubmitDraftExpenseReport(iouReport);
// The submit button should be success green colour only if the user is submitter and the policy does not have Scheduled Submit turned on
const isWaitingForSubmissionFromCurrentUser = useMemo(
() => chatReport?.isOwnPolicyExpenseChat && !policy?.harvesting?.enabled,
[chatReport?.isOwnPolicyExpenseChat, policy?.harvesting?.enabled],
);
const getDisplayAmount = (): string => {
if (totalDisplaySpend) {
return CurrencyUtils.convertToDisplayString(totalDisplaySpend, iouReport?.currency);
}
if (isScanning) {
return translate('iou.receiptScanning');
}
if (hasOnlyTransactionsWithPendingRoutes) {
return translate('iou.routePending');
}
// If iouReport is not available, get amount from the action message (Ex: "Domain20821's Workspace owes $33.00" or "paid ₫60" or "paid -₫60 elsewhere")
let displayAmount = '';
const actionMessage = action.message?.[0]?.text ?? '';
const splits = actionMessage.split(' ');
splits.forEach((split) => {
if (!/\d/.test(split)) {
return;
}
displayAmount = split;
});
return displayAmount;
};
const getPreviewMessage = () => {
if (isScanning) {
return translate('common.receipt');
}
let payerOrApproverName = isPolicyExpenseChat ? ReportUtils.getPolicyName(chatReport) : ReportUtils.getDisplayNameForParticipant(managerID, true);
if (isApproved) {
return translate('iou.managerApproved', {manager: payerOrApproverName});
}
let paymentVerb: TranslationPaths = 'iou.payerOwes';
if (iouSettled || iouReport?.isWaitingOnBankAccount) {
paymentVerb = 'iou.payerPaid';
} else if (hasNonReimbursableTransactions) {
paymentVerb = 'iou.payerSpent';
payerOrApproverName = ReportUtils.getDisplayNameForParticipant(chatReport?.ownerAccountID, true);
}
return translate(paymentVerb, {payer: payerOrApproverName});
};
const bankAccountRoute = ReportUtils.getBankAccountRoute(chatReport);
const shouldShowPayButton = useMemo(() => IOU.canIOUBePaid(iouReport, chatReport, policy), [iouReport, chatReport, policy]);
const shouldShowApproveButton = useMemo(() => IOU.canApproveIOU(iouReport, chatReport, policy), [iouReport, chatReport, policy]);
const shouldDisableApproveButton = shouldShowApproveButton && !ReportUtils.isAllowedToApproveExpenseReport(iouReport);
const shouldShowSettlementButton = shouldShowPayButton || shouldShowApproveButton;
const shouldPromptUserToAddBankAccount = ReportUtils.hasMissingPaymentMethod(userWallet, iouReportID);
const shouldShowRBR = !iouSettled && hasErrors;
/*
Show subtitle if at least one of the money requests is not being smart scanned, and either:
- There is more than one money request – in this case, the "X requests, Y scanning" subtitle is shown;
- There is only one money request, it has a receipt and is not being smart scanned – in this case, the request merchant or description is shown;
* There is an edge case when there is only one distance request with a pending route and amount = 0.
In this case, we don't want to show the merchant or description because it says: "Pending route...", which is already displayed in the amount field.
*/
const shouldShowSingleRequestMerchantOrDescription =
numberOfRequests === 1 && (!!formattedMerchant || !!formattedDescription) && !(hasOnlyTransactionsWithPendingRoutes && !totalDisplaySpend);
const shouldShowSubtitle = !isScanning && (shouldShowSingleRequestMerchantOrDescription || numberOfRequests > 1);
const {isSupportTextHtml, supportText} = useMemo(() => {
if (formattedMerchant) {
return {isSupportTextHtml: false, supportText: formattedMerchant};
}
if (formattedDescription ?? moneyRequestComment) {
const parsedSubtitle = new ExpensiMark().replace(formattedDescription ?? moneyRequestComment);
return {isSupportTextHtml: !!parsedSubtitle, supportText: parsedSubtitle ? `<muted-text>${parsedSubtitle}</muted-text>` : ''};
}
return {
isSupportTextHtml: false,
supportText: translate('iou.requestCount', {
count: numberOfRequests - numberOfScanningReceipts - numberOfPendingRequests,
scanningReceipts: numberOfScanningReceipts,
pendingReceipts: numberOfPendingRequests,
}),
};
}, [formattedMerchant, formattedDescription, moneyRequestComment, translate, numberOfRequests, numberOfScanningReceipts, numberOfPendingRequests]);
return (
<OfflineWithFeedback
pendingAction={iouReport?.pendingFields?.preview}
shouldDisableOpacity={!!(action.pendingAction ?? action.isOptimisticAction)}
needsOffscreenAlphaCompositing
>
<View style={[styles.chatItemMessage, containerStyles]}>
<PressableWithoutFeedback
onPress={() => {
Navigation.navigate(ROUTES.REPORT_WITH_ID.getRoute(iouReportID));
}}
onPressIn={() => DeviceCapabilities.canUseTouchScreen() && ControlSelection.block()}
onPressOut={() => ControlSelection.unblock()}
onLongPress={(event) => showContextMenuForReport(event, contextMenuAnchor, chatReportID, action, checkIfContextMenuActive)}
shouldUseHapticsOnLongPress
style={[styles.flexRow, styles.justifyContentBetween, styles.reportPreviewBox]}
role="button"
accessibilityLabel={translate('iou.viewDetails')}
>
<View style={[styles.reportPreviewBox, isHovered || isScanning || isWhisper ? styles.reportPreviewBoxHoverBorder : undefined]}>
{hasReceipts && (
<ReportActionItemImages
images={lastThreeReceipts}
total={transactionsWithReceipts.length}
size={CONST.RECEIPT.MAX_REPORT_PREVIEW_RECEIPTS}
/>
)}
<View style={[styles.expenseAndReportPreviewBoxBody, hasReceipts ? styles.mtn1 : {}]}>
<View style={styles.expenseAndReportPreviewTextButtonContainer}>
<View style={styles.expenseAndReportPreviewTextContainer}>
<View style={styles.flexRow}>
<View style={[styles.flex1, styles.flexRow, styles.alignItemsCenter]}>
<Text style={[styles.textLabelSupporting, styles.lh16]}>{getPreviewMessage()}</Text>
</View>
{shouldShowRBR && (
<Icon
src={Expensicons.DotIndicator}
fill={theme.danger}
/>
)}
{!shouldShowRBR && shouldPromptUserToAddBankAccount && (
<Icon
src={Expensicons.DotIndicator}
fill={theme.success}
/>
)}
</View>
<View style={styles.reportPreviewAmountSubtitleContainer}>
<View style={styles.flexRow}>
<View style={[styles.flex1, styles.flexRow, styles.alignItemsCenter]}>
<Text style={styles.textHeadlineH1}>{getDisplayAmount()}</Text>
{ReportUtils.isSettled(iouReportID) && (
<View style={styles.defaultCheckmarkWrapper}>
<Icon
src={Expensicons.Checkmark}
fill={theme.iconSuccessFill}
/>
</View>
)}
</View>
</View>
{shouldShowSubtitle && supportText && (
<View style={styles.flexRow}>
<View style={[styles.flex1, styles.flexRow, styles.alignItemsCenter]}>
{isSupportTextHtml ? (
<RenderHTML html={supportText} />
) : (
<Text style={[styles.textLabelSupporting, styles.textNormal, styles.lh20]}>{supportText}</Text>
)}
</View>
</View>
)}
</View>
</View>
{shouldShowSettlementButton && (
<SettlementButton
currency={iouReport?.currency}
policyID={policyID}
chatReportID={chatReportID}
iouReport={iouReport}
onPress={(paymentType?: PaymentMethodType) => chatReport && iouReport && paymentType && IOU.payMoneyRequest(paymentType, chatReport, iouReport)}
enablePaymentsRoute={ROUTES.ENABLE_PAYMENTS}
addBankAccountRoute={bankAccountRoute}
shouldHidePaymentOptions={!shouldShowPayButton}
shouldShowApproveButton={shouldShowApproveButton}
shouldDisableApproveButton={shouldDisableApproveButton}
kycWallAnchorAlignment={{
horizontal: CONST.MODAL.ANCHOR_ORIGIN_HORIZONTAL.LEFT,
vertical: CONST.MODAL.ANCHOR_ORIGIN_VERTICAL.BOTTOM,
}}
paymentMethodDropdownAnchorAlignment={{
horizontal: CONST.MODAL.ANCHOR_ORIGIN_HORIZONTAL.RIGHT,
vertical: CONST.MODAL.ANCHOR_ORIGIN_VERTICAL.BOTTOM,
}}
isDisabled={!canAllowSettlement}
/>
)}
{shouldShowSubmitButton && (
<Button
medium
success={isWaitingForSubmissionFromCurrentUser}
text={translate('common.submit')}
onPress={() => iouReport && IOU.submitReport(iouReport)}
isDisabled={shouldDisableSubmitButton}
/>
)}
</View>
</View>
</View>
</PressableWithoutFeedback>
</View>
</OfflineWithFeedback>
);
}
ReportPreview.displayName = 'ReportPreview';
export default withOnyx<ReportPreviewProps, ReportPreviewOnyxProps>({
policy: {
key: ({policyID}) => `${ONYXKEYS.COLLECTION.POLICY}${policyID}`,
},
chatReport: {
key: ({chatReportID}) => `${ONYXKEYS.COLLECTION.REPORT}${chatReportID}`,
},
iouReport: {
key: ({iouReportID}) => `${ONYXKEYS.COLLECTION.REPORT}${iouReportID}`,
},
transactions: {
key: ONYXKEYS.COLLECTION.TRANSACTION,
},
transactionViolations: {
key: ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS,
},
userWallet: {
key: ONYXKEYS.USER_WALLET,
},
})(ReportPreview);