diff --git a/src/libs/DebugUtils.ts b/src/libs/DebugUtils.ts index 79271bdc03c7..fd8ad40d7501 100644 --- a/src/libs/DebugUtils.ts +++ b/src/libs/DebugUtils.ts @@ -468,6 +468,7 @@ function validateReportDraftProperty(key: keyof Report, value: string) { case 'iouReportID': case 'preexistingReportID': case 'private_isArchived': + case 'welcomeMessage': return validateString(value); case 'hasOutstandingChildRequest': case 'hasOutstandingChildTask': @@ -513,6 +514,7 @@ function validateReportDraftProperty(key: keyof Report, value: string) { pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION, pendingFields: 'object', notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE, + permissions: 'array', }, 'number', ); @@ -621,6 +623,7 @@ function validateReportDraftProperty(key: keyof Report, value: string) { partial: CONST.RED_BRICK_ROAD_PENDING_ACTION, reimbursed: CONST.RED_BRICK_ROAD_PENDING_ACTION, preview: CONST.RED_BRICK_ROAD_PENDING_ACTION, + welcomeMessage: CONST.RED_BRICK_ROAD_PENDING_ACTION, }); } } diff --git a/src/libs/ReportUtils.ts b/src/libs/ReportUtils.ts index e4480c511931..027b11c516f1 100644 --- a/src/libs/ReportUtils.ts +++ b/src/libs/ReportUtils.ts @@ -52,7 +52,7 @@ import type {ErrorFields, Errors, Icon, PendingAction} from '@src/types/onyx/Ony import type {OriginalMessageChangeLog, PaymentMethodType} from '@src/types/onyx/OriginalMessage'; import type {Status} from '@src/types/onyx/PersonalDetails'; import type {ConnectionName} from '@src/types/onyx/Policy'; -import type {NotificationPreference, Participants, Participant as ReportParticipant} from '@src/types/onyx/Report'; +import type {InvoiceReceiverType, NotificationPreference, Participants, Participant as ReportParticipant} from '@src/types/onyx/Report'; import type {Message, OldDotReportAction, ReportActions} from '@src/types/onyx/ReportAction'; import type {PendingChatMember} from '@src/types/onyx/ReportMetadata'; import type {SearchPolicy, SearchReport, SearchTransaction} from '@src/types/onyx/SearchResults'; @@ -6774,7 +6774,7 @@ function getChatByParticipants(newParticipantList: number[], reports: OnyxCollec /** * Attempts to find an invoice chat report in onyx with the provided policyID and receiverID. */ -function getInvoiceChatByParticipants(policyID: string, receiverID: string | number, reports: OnyxCollection = allReports): OnyxEntry { +function getInvoiceChatByParticipants(receiverID: string | number, receiverType: InvoiceReceiverType, policyID?: string, reports: OnyxCollection = allReports): OnyxEntry { return Object.values(reports ?? {}).find((report) => { if (!report || !isInvoiceRoom(report) || isArchivedRoom(report)) { return false; @@ -6782,6 +6782,7 @@ function getInvoiceChatByParticipants(policyID: string, receiverID: string | num const isSameReceiver = report.invoiceReceiver && + report.invoiceReceiver.type === receiverType && (('accountID' in report.invoiceReceiver && report.invoiceReceiver.accountID === receiverID) || ('policyID' in report.invoiceReceiver && report.invoiceReceiver.policyID === receiverID)); diff --git a/src/libs/actions/IOU.ts b/src/libs/actions/IOU.ts index c0906f77850a..2832b0e610c3 100644 --- a/src/libs/actions/IOU.ts +++ b/src/libs/actions/IOU.ts @@ -39,6 +39,7 @@ import GoogleTagManager from '@libs/GoogleTagManager'; import * as IOUUtils from '@libs/IOUUtils'; import * as LocalePhoneNumber from '@libs/LocalePhoneNumber'; import * as Localize from '@libs/Localize'; +import Log from '@libs/Log'; import isSearchTopmostCentralPane from '@libs/Navigation/isSearchTopmostCentralPane'; import Navigation from '@libs/Navigation/Navigation'; import * as NextStepUtils from '@libs/NextStepUtils'; @@ -65,6 +66,7 @@ import type * as OnyxTypes from '@src/types/onyx'; import type {Attendee, Participant, Split} from '@src/types/onyx/IOU'; import type {ErrorFields, Errors} from '@src/types/onyx/OnyxCommon'; import type {PaymentMethodType} from '@src/types/onyx/OriginalMessage'; +import type {InvoiceReceiver, InvoiceReceiverType} from '@src/types/onyx/Report'; import type ReportAction from '@src/types/onyx/ReportAction'; import type {OnyxData} from '@src/types/onyx/Request'; import type {SearchPolicy, SearchReport, SearchTransaction} from '@src/types/onyx/SearchResults'; @@ -2071,6 +2073,25 @@ function getDeleteTrackExpenseInformation( return {parameters, optimisticData, successData, failureData, shouldDeleteTransactionThread, chatReport}; } +/** + * Get the invoice receiver type based on the receiver participant. + * @param receiverParticipant The participant who will receive the invoice or the invoice receiver object directly. + * @returns The invoice receiver type. + */ +function getReceiverType(receiverParticipant: Participant | InvoiceReceiver | undefined): InvoiceReceiverType { + if (!receiverParticipant) { + Log.warn('getReceiverType called with no receiverParticipant'); + return CONST.REPORT.INVOICE_RECEIVER_TYPE.INDIVIDUAL; + } + if ('type' in receiverParticipant && receiverParticipant.type) { + return receiverParticipant.type; + } + if ('policyID' in receiverParticipant && receiverParticipant.policyID) { + return CONST.REPORT.INVOICE_RECEIVER_TYPE.BUSINESS; + } + return CONST.REPORT.INVOICE_RECEIVER_TYPE.INDIVIDUAL; +} + /** Gathers all the data needed to create an invoice. */ function getSendInvoiceInformation( transaction: OnyxEntry, @@ -2086,17 +2107,18 @@ function getSendInvoiceInformation( const {amount = 0, currency = '', created = '', merchant = '', category = '', tag = '', taxCode = '', taxAmount = 0, billable, comment, participants} = transaction ?? {}; const trimmedComment = (comment?.comment ?? '').trim(); const senderWorkspaceID = participants?.find((participant) => participant?.isSender)?.policyID ?? '-1'; - const receiverParticipant = participants?.find((participant) => participant?.accountID) ?? invoiceChatReport?.invoiceReceiver; + const receiverParticipant: Participant | InvoiceReceiver | undefined = participants?.find((participant) => participant?.accountID) ?? invoiceChatReport?.invoiceReceiver; const receiverAccountID = receiverParticipant && 'accountID' in receiverParticipant && receiverParticipant.accountID ? receiverParticipant.accountID : -1; let receiver = ReportUtils.getPersonalDetailsForAccountID(receiverAccountID); let optimisticPersonalDetailListAction = {}; + const receiverType = getReceiverType(receiverParticipant); // STEP 1: Get existing chat report OR build a new optimistic one let isNewChatReport = false; let chatReport = !isEmptyObject(invoiceChatReport) && invoiceChatReport?.reportID ? invoiceChatReport : null; if (!chatReport) { - chatReport = ReportUtils.getInvoiceChatByParticipants(senderWorkspaceID, receiverAccountID) ?? null; + chatReport = ReportUtils.getInvoiceChatByParticipants(receiverAccountID, receiverType, senderWorkspaceID) ?? null; } if (!chatReport) { @@ -6896,7 +6918,7 @@ function getPayMoneyRequestParams( } if (ReportUtils.isIndividualInvoiceRoom(chatReport) && payAsBusiness && activePolicyID) { - const existingB2BInvoiceRoom = ReportUtils.getInvoiceChatByParticipants(chatReport.policyID ?? '', activePolicyID); + const existingB2BInvoiceRoom = ReportUtils.getInvoiceChatByParticipants(activePolicyID, CONST.REPORT.INVOICE_RECEIVER_TYPE.BUSINESS, chatReport.policyID); if (existingB2BInvoiceRoom) { chatReport = existingB2BInvoiceRoom; } diff --git a/src/types/onyx/Policy.ts b/src/types/onyx/Policy.ts index 5ea02862599e..4fdd95d7e3d9 100644 --- a/src/types/onyx/Policy.ts +++ b/src/types/onyx/Policy.ts @@ -1491,9 +1491,15 @@ type PolicyInvoicingDetails = OnyxCommon.OnyxValueWithOfflineFeedback<{ /** Account balance */ stripeConnectAccountBalance?: number; + /** AccountID */ + stripeConnectAccountID?: string; + /** bankAccountID of selected BBA for payouts */ transferBankAccountID?: number; }; + + /** The markUp */ + markUp?: number; }>; /** Names of policy features */ @@ -1630,6 +1636,9 @@ type Policy = OnyxCommon.OnyxValueWithOfflineFeedback< harvesting?: { /** Whether the scheduled submit is enabled */ enabled: boolean; + + /** The ID of the Bedrock job that runs harvesting */ + jobID?: number; }; /** Whether the self approval or submitting is enabled */ diff --git a/src/types/onyx/Report.ts b/src/types/onyx/Report.ts index 8e79ff1accf5..ca15806c0aca 100644 --- a/src/types/onyx/Report.ts +++ b/src/types/onyx/Report.ts @@ -30,6 +30,9 @@ type Participant = OnyxCommon.OnyxValueWithOfflineFeedback<{ /** Whether the participant is visible in the report */ notificationPreference: NotificationPreference; + + /** Permissions granted to the participant */ + permissions?: Array>; }>; /** Types of invoice receivers in a report */ @@ -49,6 +52,9 @@ type InvoiceReceiver = policyID: string; }; +/** Type of invoice receiver */ +type InvoiceReceiverType = InvoiceReceiver['type']; + /** Record of report participants, indexed by their accountID */ type Participants = Record; @@ -217,6 +223,9 @@ type Report = OnyxCommon.OnyxValueWithOfflineFeedback< /** Whether the report is archived */ // eslint-disable-next-line @typescript-eslint/naming-convention private_isArchived?: string; + + /** The report's welcome message */ + welcomeMessage?: string; }, 'addWorkspaceRoom' | 'avatar' | 'createChat' | 'partial' | 'reimbursed' | 'preview' >; @@ -226,4 +235,4 @@ type ReportCollectionDataSet = CollectionDataSet; diff --git a/tests/actions/IOUTest.ts b/tests/actions/IOUTest.ts index 49e1150f1a57..d7d3b6fd1d79 100644 --- a/tests/actions/IOUTest.ts +++ b/tests/actions/IOUTest.ts @@ -10,6 +10,7 @@ import * as PolicyActions from '@src/libs/actions/Policy/Policy'; import * as Report from '@src/libs/actions/Report'; import * as ReportActions from '@src/libs/actions/ReportActions'; import * as User from '@src/libs/actions/User'; +import * as API from '@src/libs/API'; import DateUtils from '@src/libs/DateUtils'; import * as Localize from '@src/libs/Localize'; import * as NumberUtils from '@src/libs/NumberUtils'; @@ -24,6 +25,8 @@ import type {ReportActionsCollectionDataSet} from '@src/types/onyx/ReportAction' import type {TransactionCollectionDataSet} from '@src/types/onyx/Transaction'; import {toCollectionDataSet} from '@src/types/utils/CollectionDataSet'; import {isEmptyObject} from '@src/types/utils/EmptyObject'; +import * as InvoiceData from '../data/Invoice'; +import type {InvoiceTestData} from '../data/Invoice'; import createRandomPolicy, {createCategoryTaxExpenseRules} from '../utils/collections/policies'; import createRandomReport from '../utils/collections/reports'; import createRandomTransaction from '../utils/collections/transaction'; @@ -3454,6 +3457,33 @@ describe('actions/IOU', () => { }); describe('sendInvoice', () => { + it('creates a new invoice chat when one has been converted from individual to business', async () => { + // Mock API.write for this test + const writeSpy = jest.spyOn(API, 'write').mockImplementation(jest.fn()); + + // Given a convertedInvoiceReport is stored in Onyx + const {policy, transaction, convertedInvoiceChat}: InvoiceTestData = InvoiceData; + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${convertedInvoiceChat?.reportID}`, convertedInvoiceChat ?? {}); + + // And data for when a new invoice is sent to a user + const currentUserAccountID = 32; + const companyName = 'b1-53019'; + const companyWebsite = 'https://www.53019.com'; + + // When the user sends a new invoice to an individual + IOU.sendInvoice(currentUserAccountID, transaction, undefined, undefined, policy, undefined, undefined, companyName, companyWebsite); + + // Then a new invoice chat is created instead of incorrectly using the invoice chat which has been converted from individual to business + expect(writeSpy).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + invoiceRoomReportID: expect.not.stringMatching(convertedInvoiceChat.reportID) as string, + }), + expect.anything(), + ); + writeSpy.mockRestore(); + }); + it('should not clear transaction pending action when send invoice fails', async () => { // Given a send invoice request mockFetch?.pause?.(); diff --git a/tests/data/Invoice.ts b/tests/data/Invoice.ts new file mode 100644 index 000000000000..c94c7ce816be --- /dev/null +++ b/tests/data/Invoice.ts @@ -0,0 +1,290 @@ +// Test data for Invoices. The values come from the Onyx store in the app while manually testing. +import type {OnyxEntry} from 'react-native-onyx'; +import CONST from '@src/CONST'; +import type * as OnyxTypes from '@src/types/onyx'; +import type {InvoiceReceiver} from '@src/types/onyx/Report'; + +const policy: OnyxEntry = { + id: 'CC048FA711B35B1F', + type: 'team', + name: "53019's Workspace", + role: 'admin', + owner: 'a1@53019.com', + ownerAccountID: 32, + isPolicyExpenseChatEnabled: true, + outputCurrency: 'USD', + autoReporting: true, + autoReportingFrequency: 'instant', + approvalMode: 'OPTIONAL', + harvesting: { + enabled: true, + jobID: 7206965285807173000, + }, + customUnits: { + // eslint-disable-next-line @typescript-eslint/naming-convention + '39C3FF491F559': { + customUnitID: '39C3FF491F559', + name: 'Distance', + attributes: { + unit: 'mi', + }, + rates: { + // eslint-disable-next-line @typescript-eslint/naming-convention + '928A74633831E': { + customUnitRateID: '928A74633831E', + name: 'Default Rate', + rate: 67, + enabled: true, + currency: 'USD', + }, + }, + defaultCategory: 'Car', + enabled: true, + }, + }, + areCategoriesEnabled: true, + areTagsEnabled: false, + areDistanceRatesEnabled: false, + areWorkflowsEnabled: false, + areReportFieldsEnabled: false, + areConnectionsEnabled: false, + employeeList: { + // eslint-disable-next-line @typescript-eslint/naming-convention + 'a1@53019.com': { + role: 'admin', + errors: {}, + email: 'a1@53019.com', + forwardsTo: '', + submitsTo: 'a1@53019.com', + }, + }, + pendingFields: {}, + chatReportIDAnnounce: 0, + chatReportIDAdmins: 1811331783036078, + approver: 'a1@53019.com', + areCompanyCardsEnabled: false, + areExpensifyCardsEnabled: false, + areInvoicesEnabled: true, + arePerDiemRatesEnabled: false, + areRulesEnabled: false, + autoReimbursement: { + limit: 0, + }, + autoReimbursementLimit: 0, + autoReportingOffset: 1, + avatarURL: '', + defaultBillable: false, + description: '', + disabledFields: { + defaultBillable: true, + reimbursable: false, + }, + fieldList: { + // eslint-disable-next-line @typescript-eslint/naming-convention + text_title: { + defaultValue: '{report:type} {report:startdate}', + deletable: true, + disabledOptions: [], + externalIDs: [], + fieldID: 'text_title', + isTax: false, + keys: [], + name: 'title', + orderWeight: 0, + target: 'expense', + type: 'formula', + values: [], + }, + }, + hasMultipleTagLists: false, + invoice: { + markUp: 0, + companyName: 'b1-53019', + companyWebsite: 'https://www.53019.com', + pendingFields: {}, + bankAccount: { + stripeConnectAccountBalance: 0, + stripeConnectAccountID: 'acct_1QVeO7S7tHTCCfyY', + transferBankAccountID: 29, + }, + }, + preventSelfApproval: false, + reimbursementChoice: 'reimburseManual', + requiresCategory: false, + requiresTag: false, + tax: { + trackingEnabled: false, + }, + mccGroup: { + airlines: { + category: 'Travel', + groupID: 'airlines', + }, + commuter: { + category: 'Car', + groupID: 'commuter', + }, + gas: { + category: 'Car', + groupID: 'gas', + }, + goods: { + category: 'Materials', + groupID: 'goods', + }, + groceries: { + category: 'Meals and Entertainment', + groupID: 'groceries', + }, + hotel: { + category: 'Travel', + groupID: 'hotel', + }, + mail: { + category: 'Office Supplies', + groupID: 'mail', + }, + meals: { + category: 'Meals and Entertainment', + groupID: 'meals', + }, + rental: { + category: 'Travel', + groupID: 'rental', + }, + services: { + category: 'Professional Services', + groupID: 'services', + }, + taxi: { + category: 'Travel', + groupID: 'taxi', + }, + uncategorized: { + category: 'Other', + groupID: 'uncategorized', + }, + utilities: { + category: 'Utilities', + groupID: 'utilities', + }, + }, +}; + +const transaction: OnyxEntry = { + amount: 100, + attendees: [ + { + email: 'a1@53019.com', + login: 'a1@53019.com', + displayName: 'a1', + avatarUrl: 'https://d2k5nsl2zxldvw.cloudfront.net/images/avatars/default-avatar_9.png', + accountID: 32, + text: 'a1@53019.com', + selected: true, + reportID: '3634215302663162', + }, + ], + comment: { + customUnit: { + customUnitRateID: '_FAKE_P2P_ID_', + }, + }, + created: '2024-12-13', + currency: 'USD', + iouRequestType: 'manual', + reportID: '3634215302663162', + transactionID: '1', + isFromGlobalCreate: true, + merchant: '(none)', + splitPayerAccountIDs: [32], + shouldShowOriginalAmount: true, + participants: [ + { + accountID: 33, + login: 'b1@53019.com', + isPolicyExpenseChat: false, + reportID: '', + selected: true, + iouType: 'invoice', + }, + { + policyID: 'CC048FA711B35B1F', + isSender: true, + selected: false, + iouType: 'invoice', + }, + ], + tag: '', + category: '', + billable: false, +}; + +const convertedInvoiceChat: OnyxTypes.Report = { + chatType: CONST.REPORT.CHAT_TYPE.INVOICE, + currency: 'USD', + description: '', + hasOutstandingChildRequest: false, + hasOutstandingChildTask: false, + + // The invoice receiver shouldn't have an accountID when the type is business, + // but this is to test that it still works if the value is present, so cast it to unknown + invoiceReceiver: { + accountID: 33, + policyID: '5F2F82F98C848CAA', + type: 'policy', + } as unknown as InvoiceReceiver, + isCancelledIOU: false, + isOwnPolicyExpenseChat: false, + isPinned: false, + isWaitingOnBankAccount: false, + lastActionType: 'REPORTPREVIEW', + lastActorAccountID: 32, + lastMessageHtml: 'paid $1.00', + lastMessageText: 'paid $1.00', + lastReadSequenceNumber: 0, + lastReadTime: '2024-12-13 19:45:28.942', + lastVisibleActionCreated: '2024-12-13 19:19:01.794', + lastVisibleActionLastModified: '2024-12-13 19:19:01.794', + managerID: 0, + nonReimbursableTotal: 0, + oldPolicyName: '', + ownerAccountID: 0, + participants: { + // eslint-disable-next-line @typescript-eslint/naming-convention + '32': { + notificationPreference: 'always', + role: 'admin', + }, + // eslint-disable-next-line @typescript-eslint/naming-convention + '33': { + notificationPreference: 'always', + permissions: [CONST.REPORT.PERMISSIONS.READ, CONST.REPORT.PERMISSIONS.WRITE, CONST.REPORT.PERMISSIONS.SHARE, CONST.REPORT.PERMISSIONS.OWN], + }, + }, + policyAvatar: '', + policyID: 'CC048FA711B35B1F', + policyName: "53019's Workspace", + // eslint-disable-next-line @typescript-eslint/naming-convention + private_isArchived: '', + reportID: '7605647250932303', + reportName: 'Chat Report', + stateNum: 0, + statusNum: 0, + total: 0, + type: 'chat', + unheldNonReimbursableTotal: 0, + unheldTotal: 0, + visibility: 'private', + welcomeMessage: '', + writeCapability: 'all', +}; + +type InvoiceTestData = { + policy: OnyxEntry; + transaction: OnyxEntry; + convertedInvoiceChat: OnyxTypes.Report; +}; + +export type {InvoiceTestData}; +export {policy, transaction, convertedInvoiceChat}; diff --git a/tests/unit/ReportUtilsTest.ts b/tests/unit/ReportUtilsTest.ts index e1eda3171355..85cf0125a5eb 100644 --- a/tests/unit/ReportUtilsTest.ts +++ b/tests/unit/ReportUtilsTest.ts @@ -1,6 +1,6 @@ /* eslint-disable @typescript-eslint/naming-convention */ import {addDays, format as formatDate} from 'date-fns'; -import type {OnyxEntry} from 'react-native-onyx'; +import type {OnyxCollection, OnyxEntry} from 'react-native-onyx'; import Onyx from 'react-native-onyx'; import DateUtils from '@libs/DateUtils'; import * as ReportUtils from '@libs/ReportUtils'; @@ -10,6 +10,7 @@ import ONYXKEYS from '@src/ONYXKEYS'; import type {PersonalDetailsList, Policy, Report, ReportAction} from '@src/types/onyx'; import {toCollectionDataSet} from '@src/types/utils/CollectionDataSet'; import * as NumberUtils from '../../src/libs/NumberUtils'; +import {convertedInvoiceChat} from '../data/Invoice'; import * as LHNTestUtils from '../utils/LHNTestUtils'; import {fakePersonalDetails} from '../utils/LHNTestUtils'; import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; @@ -1414,4 +1415,19 @@ describe('ReportUtils', () => { ).toBeTruthy(); }); }); + + describe('getInvoiceChatByParticipants', () => { + it('only returns an invoice chat if the receiver type matches', () => { + // Given an invoice chat that has been converted from an individual to policy receiver type + const reports: OnyxCollection = { + [convertedInvoiceChat.reportID]: convertedInvoiceChat, + }; + + // When we send another invoice to the individual from global create and call getInvoiceChatByParticipants + const invoiceChatReport = ReportUtils.getInvoiceChatByParticipants(33, CONST.REPORT.INVOICE_RECEIVER_TYPE.INDIVIDUAL, convertedInvoiceChat.policyID, reports); + + // Then no invoice chat should be returned because the receiver type does not match + expect(invoiceChatReport).toBeUndefined(); + }); + }); });