mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 01:28:55 +00:00
feat(costs): link a trip file as an expense receipt (#2839)
A booking confirmation that is also the invoice had to be uploaded a second time to sit on the expense. The expense editor (desktop and phone) now lists the trip's files to link, the booking's own first; the save sends the id in receipt_file_ids, which the server already links. The desktop receipts block moves into its own component.
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
import { Fragment, useState, useMemo, useCallback, useId, type ReactNode } from 'react'
|
||||
import { ArrowDown, ArrowUp, BarChart3, Plus, Search, ArrowRight, ArrowLeftRight, Check, RotateCcw, Pencil, Trash2, AlertCircle, Download, StickyNote, ChevronDown, Receipt, Paperclip, ScanLine, Users } from 'lucide-react'
|
||||
import { ArrowDown, ArrowUp, BarChart3, Plus, Search, ArrowRight, ArrowLeftRight, Check, RotateCcw, Pencil, Trash2, AlertCircle, Download, StickyNote, ChevronDown, Receipt, ScanLine, Users } from 'lucide-react'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { useCanDo } from '../../store/permissionsStore'
|
||||
import { useToast } from '../shared/Toast'
|
||||
@@ -26,6 +26,7 @@ import { useSettlementForm } from './useSettlementForm'
|
||||
import type { CustomSplitUnit } from './usePercentSplit'
|
||||
import { useExpenseForm } from './useExpenseForm'
|
||||
import { ReceiptPreviewModal } from './ReceiptPreviewModal'
|
||||
import { ExpenseReceiptsSection } from './ExpenseReceiptsSection'
|
||||
import { useExpenseDeleteConfirm } from './useExpenseDeleteConfirm'
|
||||
import { FlowPills } from './FlowPills'
|
||||
import type { BudgetParticipantFinal, ReceiptLine } from '@trek/shared'
|
||||
@@ -1128,7 +1129,8 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
|
||||
const titleId = useId()
|
||||
const {
|
||||
cat, currency, customAmounts, customBalanced, day, disableMultiPayer, each, enableMultiPayer, equalShares, fx,
|
||||
handleAddEmptyItem, handleCustomAmountChange, handleReceiptFileSelect, handleRemoveItem, handleRemovePendingReceipt,
|
||||
handleAddEmptyItem, handleCustomAmountChange, handleLinkReceipt, handleReceiptFileSelect, handleRemoveItem, linkableFiles,
|
||||
handleRemovePendingReceipt,
|
||||
handleRemoveReceipt, handleToggleItemParticipant, handleUpdateItemName, handleUpdateItemPrice, isTicketMode,
|
||||
multiPayer, name, nameOf, note, onPayerAmountChange, onTotalChange, participants, payerAmounts, payerId, payerIds,
|
||||
payersOk, pendingReceiptFiles, placeholderShares, previewReceipts: modalPreviewReceipts, receipts, save, saving,
|
||||
@@ -1409,66 +1411,6 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
|
||||
</DialogSection>
|
||||
)
|
||||
|
||||
const receiptRow = 'flex items-center justify-between gap-2 rounded-[10px] border border-edge-faint bg-surface-secondary px-3 py-2'
|
||||
const receiptsSection = (
|
||||
<DialogSection
|
||||
label={t('costs.receiptsTitle') || t('costs.receipts')}
|
||||
className={GROUP}
|
||||
action={(
|
||||
<label className="inline-flex cursor-pointer items-center gap-1 rounded-full bg-surface-tertiary px-2.5 py-1 font-semibold text-content-muted hover:text-content" style={fs(11.5)}>
|
||||
<input
|
||||
type="file"
|
||||
multiple
|
||||
accept="image/*,application/pdf"
|
||||
className="hidden"
|
||||
onChange={e => {
|
||||
handleReceiptFileSelect(e.target.files)
|
||||
e.target.value = ''
|
||||
}}
|
||||
/>
|
||||
<Plus size={12} /> {t('costs.attach')}
|
||||
</label>
|
||||
)}
|
||||
>
|
||||
{uploadingReceipt && (
|
||||
<div className="mb-2 text-content-faint" style={fs(12)}>{t('common.saving')}...</div>
|
||||
)}
|
||||
{receipts.length === 0 && pendingReceiptFiles.length === 0 ? (
|
||||
<div className="py-1 text-content-faint" style={fs(12.5, 'body')}>{t('costs.noReceipts')}</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{receipts.map((r, rIdx) => (
|
||||
<div key={r.id} className={receiptRow}>
|
||||
<button type="button" onClick={() => setModalPreviewReceipts({ receipts, initialIndex: rIdx })}
|
||||
className="inline-flex min-w-0 items-center gap-2 text-start text-content hover:underline" style={fs(13, 'body')}>
|
||||
<Receipt size={14} className="flex-shrink-0 text-content-faint" />
|
||||
<span className="truncate">{r.original_name}</span>
|
||||
</button>
|
||||
<Tooltip label={t('costs.deleteReceipt')}>
|
||||
<button type="button" onClick={() => handleRemoveReceipt(r.id)} aria-label={t('costs.deleteReceipt')} className="flex p-1 text-content-muted hover:text-danger">
|
||||
<Trash2 size={14} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
))}
|
||||
{pendingReceiptFiles.map((file, idx) => (
|
||||
<div key={idx} className={receiptRow}>
|
||||
<div className="inline-flex min-w-0 items-center gap-2" style={fs(13, 'body')}>
|
||||
<Paperclip size={14} className="flex-shrink-0 text-content-faint" />
|
||||
<span className="truncate text-content">{file.name}</span>
|
||||
</div>
|
||||
<Tooltip label={t('costs.deleteReceipt')}>
|
||||
<button type="button" onClick={() => handleRemovePendingReceipt(idx)} aria-label={t('costs.deleteReceipt')} className="flex p-1 text-content-muted hover:text-danger">
|
||||
<Trash2 size={14} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</DialogSection>
|
||||
)
|
||||
|
||||
return (
|
||||
<>
|
||||
<DialogShell
|
||||
@@ -1549,7 +1491,10 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
|
||||
<textarea id="expense-note" value={note} onChange={e => setNote(e.target.value)} rows={3}
|
||||
placeholder={t('costs.notePlaceholder')} maxLength={NOTE_MAX} className={`${TEXTAREA} resize-y`} />
|
||||
</EditorField>
|
||||
{receiptsSection}
|
||||
<ExpenseReceiptsSection className={GROUP} receipts={receipts} pendingFiles={pendingReceiptFiles} uploading={uploadingReceipt}
|
||||
linkable={linkableFiles} onPick={handleReceiptFileSelect} onLink={handleLinkReceipt}
|
||||
onPreview={index => setModalPreviewReceipts({ receipts, initialIndex: index })}
|
||||
onRemove={handleRemoveReceipt} onRemovePending={handleRemovePendingReceipt} />
|
||||
</div>
|
||||
</DialogShell>
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
// FE-COSTS-EXPRECEIPT-001 to FE-COSTS-EXPRECEIPT-004
|
||||
// FE-COSTS-EXPRECEIPT-001 to FE-COSTS-EXPRECEIPT-005
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, fireEvent, within } from '../../../tests/helpers/render'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { useAuthStore } from '../../store/authStore'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store'
|
||||
import { buildBudgetItem, buildTrip, buildUser } from '../../../tests/helpers/factories'
|
||||
import { buildBudgetItem, buildTrip, buildTripFile, buildUser } from '../../../tests/helpers/factories'
|
||||
import type { BudgetItem } from '../../types'
|
||||
import { ExpenseModal } from './CostsPanel'
|
||||
|
||||
@@ -78,4 +78,21 @@ describe('ExpenseModal receipts and note', () => {
|
||||
await user.type(note, 'Paid in cash')
|
||||
expect(note).toHaveValue('Paid in cash')
|
||||
})
|
||||
|
||||
it('FE-COSTS-EXPRECEIPT-005: a file the trip already has is linked as a receipt, uploaded nothing (#2839)', async () => {
|
||||
const user = userEvent.setup()
|
||||
// Without trip files there is nothing to link, so the button stays away.
|
||||
const bare = renderModal(null)
|
||||
expect(within(receiptsCard()).queryByRole('button', { name: 'Link' })).toBeNull()
|
||||
bare.unmount()
|
||||
|
||||
seedStore(useTripStore, { files: [buildTripFile({ id: 51, original_name: 'hotel-confirmation.pdf' })] })
|
||||
renderModal(null)
|
||||
await user.click(within(receiptsCard()).getByRole('button', { name: 'Link' }))
|
||||
await user.click(within(receiptsCard()).getByRole('button', { name: 'hotel-confirmation.pdf' }))
|
||||
// Now on the expense: listed like a saved receipt, and gone from what can be linked.
|
||||
expect(within(receiptsCard()).getByRole('button', { name: 'hotel-confirmation.pdf' })).toBeInTheDocument()
|
||||
expect(within(receiptsCard()).queryByText('No receipts attached')).toBeNull()
|
||||
expect(within(receiptsCard()).queryByRole('button', { name: 'Link' })).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
import { FileText, Link2, Paperclip, Plus, Receipt, Trash2 } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
|
||||
import { useTranslation } from '../../i18n';
|
||||
import type { BudgetItemReceipt, TripFile } from '../../types';
|
||||
import { DialogSection, fs } from '../shared/DialogShell';
|
||||
import { Tooltip } from '../shared/Tooltip';
|
||||
|
||||
const ROW =
|
||||
'flex items-center justify-between gap-2 rounded-[10px] border border-edge-faint bg-surface-secondary px-3 py-2';
|
||||
const PILL =
|
||||
'inline-flex cursor-pointer items-center gap-1 rounded-full px-2.5 py-1 font-semibold text-content-muted hover:text-content';
|
||||
|
||||
/**
|
||||
* The Receipts & Invoices block of the desktop expense dialog: the receipts on
|
||||
* the expense, the files picked to upload with the save, a picker for new ones
|
||||
* and, while the trip has files the expense does not carry, a list to link one
|
||||
* of those instead (#2839), so a booking's confirmation is not uploaded twice.
|
||||
*/
|
||||
export function ExpenseReceiptsSection({
|
||||
className,
|
||||
receipts,
|
||||
pendingFiles,
|
||||
uploading,
|
||||
linkable,
|
||||
onPick,
|
||||
onLink,
|
||||
onPreview,
|
||||
onRemove,
|
||||
onRemovePending,
|
||||
}: {
|
||||
className: string;
|
||||
receipts: BudgetItemReceipt[];
|
||||
pendingFiles: File[];
|
||||
uploading: boolean;
|
||||
linkable: TripFile[];
|
||||
onPick: (files: FileList | null) => void;
|
||||
onLink: (file: TripFile) => void;
|
||||
onPreview: (index: number) => void;
|
||||
onRemove: (receiptId: number) => void;
|
||||
onRemovePending: (index: number) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [linking, setLinking] = useState(false);
|
||||
const canLink = linkable.length > 0;
|
||||
|
||||
return (
|
||||
<DialogSection
|
||||
label={t('costs.receiptsTitle')}
|
||||
className={className}
|
||||
action={
|
||||
<span className="flex items-center gap-1.5">
|
||||
{canLink && (
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={linking}
|
||||
onClick={() => setLinking((v) => !v)}
|
||||
className={`${PILL} ${linking ? 'bg-surface-card shadow-sm' : 'bg-surface-tertiary'}`}
|
||||
style={fs(11.5)}
|
||||
>
|
||||
<Link2 size={12} /> {t('files.link')}
|
||||
</button>
|
||||
)}
|
||||
<label className={`${PILL} bg-surface-tertiary`} style={fs(11.5)}>
|
||||
<input
|
||||
type="file"
|
||||
multiple
|
||||
accept="image/*,application/pdf"
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
onPick(e.target.files);
|
||||
e.target.value = '';
|
||||
}}
|
||||
/>
|
||||
<Plus size={12} /> {t('costs.attach')}
|
||||
</label>
|
||||
</span>
|
||||
}
|
||||
>
|
||||
{linking && canLink && (
|
||||
<div className="mb-2 flex max-h-[180px] flex-col gap-1 overflow-y-auto rounded-[10px] border border-edge-faint bg-surface-card p-1.5">
|
||||
{linkable.map((file) => (
|
||||
<button
|
||||
key={file.id}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
onLink(file);
|
||||
setLinking(false);
|
||||
}}
|
||||
className="flex items-center gap-2 rounded-[8px] px-2.5 py-1.5 text-start text-content hover:bg-surface-tertiary"
|
||||
style={fs(12.5, 'body')}
|
||||
>
|
||||
<FileText size={13} className="flex-shrink-0 text-content-faint" />
|
||||
<span className="truncate">{file.original_name}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{uploading && (
|
||||
<div className="mb-2 text-content-faint" style={fs(12)}>
|
||||
{t('common.saving')}...
|
||||
</div>
|
||||
)}
|
||||
{receipts.length === 0 && pendingFiles.length === 0 ? (
|
||||
<div className="py-1 text-content-faint" style={fs(12.5, 'body')}>
|
||||
{t('costs.noReceipts')}
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{receipts.map((r, index) => (
|
||||
<div key={r.id} className={ROW}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onPreview(index)}
|
||||
className="inline-flex min-w-0 items-center gap-2 text-start text-content hover:underline"
|
||||
style={fs(13, 'body')}
|
||||
>
|
||||
<Receipt size={14} className="flex-shrink-0 text-content-faint" />
|
||||
<span className="truncate">{r.original_name}</span>
|
||||
</button>
|
||||
<Tooltip label={t('costs.deleteReceipt')}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onRemove(r.id)}
|
||||
aria-label={t('costs.deleteReceipt')}
|
||||
className="flex p-1 text-content-muted hover:text-danger"
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
))}
|
||||
{pendingFiles.map((file, index) => (
|
||||
<div key={index} className={ROW}>
|
||||
<div className="inline-flex min-w-0 items-center gap-2" style={fs(13, 'body')}>
|
||||
<Paperclip size={14} className="flex-shrink-0 text-content-faint" />
|
||||
<span className="truncate text-content">{file.name}</span>
|
||||
</div>
|
||||
<Tooltip label={t('costs.deleteReceipt')}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onRemovePending(index)}
|
||||
aria-label={t('costs.deleteReceipt')}
|
||||
className="flex p-1 text-content-muted hover:text-danger"
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</DialogSection>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// FE-BUDGET-RCPTLINK-001 to FE-BUDGET-RCPTLINK-003
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { buildTripFile } from '../../../tests/helpers/factories';
|
||||
import { linkableReceiptFiles, receiptOfFile } from './receiptLinks';
|
||||
|
||||
const names = (files: { original_name: string }[]) => files.map((f) => f.original_name);
|
||||
|
||||
describe('receipt links (#2839)', () => {
|
||||
const menu = buildTripFile({ id: 1, original_name: 'menu.jpg' });
|
||||
const confirmation = buildTripFile({ id: 2, original_name: 'hotel-confirmation.pdf', reservation_id: 7 });
|
||||
const linked = buildTripFile({ id: 3, original_name: 'hotel-invoice.pdf', linked_reservation_ids: [9, 7] });
|
||||
const binned = buildTripFile({ id: 4, original_name: 'old.pdf', deleted_at: '2026-01-01 10:00:00' });
|
||||
|
||||
it('FE-BUDGET-RCPTLINK-001: offers the live files the expense does not carry yet', () => {
|
||||
const files = linkableReceiptFiles([menu, confirmation, linked, binned], [receiptOfFile(linked)], null);
|
||||
expect(names(files)).toEqual(['menu.jpg', 'hotel-confirmation.pdf']);
|
||||
});
|
||||
|
||||
it("FE-BUDGET-RCPTLINK-002: the booking's own files lead, by its column or a link row", () => {
|
||||
expect(names(linkableReceiptFiles([menu, confirmation, linked], [], 7))).toEqual([
|
||||
'hotel-confirmation.pdf',
|
||||
'hotel-invoice.pdf',
|
||||
'menu.jpg',
|
||||
]);
|
||||
expect(names(linkableReceiptFiles([menu, confirmation], [], 8))).toEqual(['menu.jpg', 'hotel-confirmation.pdf']);
|
||||
});
|
||||
|
||||
it('FE-BUDGET-RCPTLINK-003: a file reads as a receipt row under its own id and download path', () => {
|
||||
expect(receiptOfFile(confirmation)).toEqual({
|
||||
id: 2,
|
||||
filename: 'test.pdf',
|
||||
original_name: 'hotel-confirmation.pdf',
|
||||
file_size: null,
|
||||
mime_type: 'application/pdf',
|
||||
url: '/api/trips/1/files/2/download',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { BudgetItemReceipt, TripFile } from '../../types';
|
||||
|
||||
/** A file of the booking: its own column names it, or one of its link rows does. */
|
||||
function onBooking(file: TripFile, reservationId: number): boolean {
|
||||
return Number(file.reservation_id) === reservationId || (file.linked_reservation_ids || []).includes(reservationId);
|
||||
}
|
||||
|
||||
/**
|
||||
* The trip's files an expense could take as a receipt (#2839): the ones not in
|
||||
* the bin and not on the expense yet. A booking's confirmation is so often its
|
||||
* invoice as well that the files of the booking the expense belongs to lead.
|
||||
*/
|
||||
export function linkableReceiptFiles(
|
||||
files: readonly TripFile[],
|
||||
receipts: readonly BudgetItemReceipt[],
|
||||
reservationId: number | null | undefined
|
||||
): TripFile[] {
|
||||
const taken = new Set(receipts.map((r) => r.id));
|
||||
const live = files.filter((f) => !f.deleted_at && !taken.has(f.id));
|
||||
if (!reservationId) return live;
|
||||
return [...live.filter((f) => onBooking(f, reservationId)), ...live.filter((f) => !onBooking(f, reservationId))];
|
||||
}
|
||||
|
||||
/**
|
||||
* A trip file as the receipt row the editor lists. Nothing is written yet: the
|
||||
* save sends its id with the others in `receipt_file_ids`, which links it.
|
||||
*/
|
||||
export function receiptOfFile(file: TripFile): BudgetItemReceipt {
|
||||
return {
|
||||
id: file.id,
|
||||
filename: file.filename,
|
||||
original_name: file.original_name,
|
||||
file_size: file.file_size ?? null,
|
||||
mime_type: file.mime_type,
|
||||
url: file.url,
|
||||
};
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { buildBudgetItem, buildTrip } from '../../../tests/helpers/factories';
|
||||
import { buildBudgetItem, buildTrip, buildTripFile } from '../../../tests/helpers/factories';
|
||||
import { resetAllStores } from '../../../tests/helpers/store';
|
||||
import { clearExchangeRateCache } from '../../hooks/useExchangeRates';
|
||||
import { useTripStore, type TripStoreState } from '../../store/tripStore';
|
||||
@@ -21,7 +21,7 @@ vi.mock('./receiptUploads', () => ({
|
||||
),
|
||||
}));
|
||||
|
||||
// FE-BUDGET-EXPFORM-001 to FE-BUDGET-EXPFORM-025
|
||||
// FE-BUDGET-EXPFORM-001 to FE-BUDGET-EXPFORM-026
|
||||
|
||||
const PEOPLE: TripMember[] = [
|
||||
{ id: 1, username: 'alice', avatar_url: null },
|
||||
@@ -475,6 +475,27 @@ describe('useExpenseForm: saving', () => {
|
||||
expect(result.current.pendingReceiptFiles).toEqual([]);
|
||||
});
|
||||
|
||||
it("FE-BUDGET-EXPFORM-026: a trip file linked as a receipt goes out with the save, the booking's files first (#2839)", async () => {
|
||||
const menu = buildTripFile({ id: 21, original_name: 'menu.jpg' });
|
||||
const confirmation = buildTripFile({ id: 22, original_name: 'confirmation.pdf', reservation_id: 4 });
|
||||
const binned = buildTripFile({ id: 23, original_name: 'old.pdf', deleted_at: '2026-01-01 10:00:00' });
|
||||
useTripStore.setState({ files: [menu, confirmation, binned] } as unknown as Partial<TripStoreState>);
|
||||
const { result } = setup({ prefill: { reservationId: 4 } });
|
||||
expect(result.current.linkableFiles.map((f) => f.id)).toEqual([22, 21]);
|
||||
|
||||
act(() => result.current.handleLinkReceipt(confirmation));
|
||||
act(() => result.current.handleLinkReceipt(confirmation));
|
||||
expect(result.current.receipts.map((r) => r.id)).toEqual([22]);
|
||||
expect(result.current.linkableFiles.map((f) => f.id)).toEqual([21]);
|
||||
|
||||
fill(result, 'Hotel', '200');
|
||||
await save(result);
|
||||
expect(addBudgetItem).toHaveBeenCalledWith(
|
||||
7,
|
||||
expect.objectContaining({ receipt_file_ids: [22], reservation_id: 4 })
|
||||
);
|
||||
});
|
||||
|
||||
it('FE-BUDGET-EXPFORM-017: a ticket split sends everyone a line names, ticked or not (#1382)', async () => {
|
||||
const { result } = setup();
|
||||
act(() => {
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useEffect, useEffectEvent, useMemo, useState } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import { isEffectivelyOffline } from '../../sync/networkMode';
|
||||
import type { BudgetItem, BudgetItemReceipt } from '../../types';
|
||||
import type { BudgetItem, BudgetItemReceipt, TripFile } from '../../types';
|
||||
import { amountToInputString } from '../../utils/formatters';
|
||||
import { localToday } from '../Planner/today';
|
||||
import { useToast } from '../shared/Toast';
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
import { catMeta } from './costsCategories';
|
||||
import { currencyOptions } from './costsModel';
|
||||
import { useExpenseFx } from './expenseFx';
|
||||
import { linkableReceiptFiles, receiptOfFile } from './receiptLinks';
|
||||
import { saveWithReceipts } from './receiptUploads';
|
||||
import { usePercentSplit } from './usePercentSplit';
|
||||
|
||||
@@ -71,6 +72,7 @@ export function useExpenseForm({
|
||||
const toast = useToast();
|
||||
const addBudgetItem = useTripStore((s) => s.addBudgetItem);
|
||||
const updateBudgetItem = useTripStore((s) => s.updateBudgetItem);
|
||||
const tripFiles = useTripStore((s) => s.files);
|
||||
const sym = (c: string) => SYMBOLS[c] || c + ' ';
|
||||
const nameOf = (p: TripMember) => (p.id === me ? t('costs.you') : p.username);
|
||||
// A saved expense without a currency opens in the trip's own (#2525).
|
||||
@@ -168,6 +170,16 @@ export function useExpenseForm({
|
||||
setPendingReceiptFiles((prev) => [...prev, ...Array.from(files)]);
|
||||
};
|
||||
|
||||
// A file the trip already has, such as the booking's confirmation, taken as a
|
||||
// receipt (#2839). It joins the list and the save links it, uploaded nothing.
|
||||
const linkableFiles = useMemo(
|
||||
() => linkableReceiptFiles(tripFiles, receipts, editing ? editing.reservation_id : prefill?.reservationId),
|
||||
[tripFiles, receipts, editing, prefill]
|
||||
);
|
||||
const handleLinkReceipt = (file: TripFile) => {
|
||||
setReceipts((prev) => (prev.some((r) => r.id === file.id) ? prev : [...prev, receiptOfFile(file)]));
|
||||
};
|
||||
|
||||
const handleRemoveReceipt = (receiptId: number) => {
|
||||
setReceipts((prev) => prev.filter((r) => r.id !== receiptId));
|
||||
};
|
||||
@@ -408,11 +420,11 @@ export function useExpenseForm({
|
||||
};
|
||||
try {
|
||||
setUploadingReceipt(pendingReceiptFiles.length > 0);
|
||||
await saveWithReceipts(tripId, pendingReceiptFiles, editing ? editing.id : null, (ids) =>
|
||||
editing
|
||||
? updateBudgetItem(tripId, editing.id, { ...data, receipt_file_ids: [...receipts.map((r) => r.id), ...ids] })
|
||||
: addBudgetItem(tripId, { ...data, receipt_file_ids: ids })
|
||||
);
|
||||
// The receipts listed (saved or linked from the trip's files) and the new uploads.
|
||||
await saveWithReceipts(tripId, pendingReceiptFiles, editing ? editing.id : null, (ids) => {
|
||||
const withReceipts = { ...data, receipt_file_ids: [...receipts.map((r) => r.id), ...ids] };
|
||||
return editing ? updateBudgetItem(tripId, editing.id, withReceipts) : addBudgetItem(tripId, withReceipts);
|
||||
});
|
||||
// Only cleared once the save went through, so a retry after a failure
|
||||
// does not upload a second copy of every file.
|
||||
setPendingReceiptFiles([]);
|
||||
@@ -483,6 +495,8 @@ export function useExpenseForm({
|
||||
pendingReceiptFiles,
|
||||
uploadingReceipt,
|
||||
handleReceiptFileSelect,
|
||||
linkableFiles,
|
||||
handleLinkReceipt,
|
||||
handleRemoveReceipt,
|
||||
handleRemovePendingReceipt,
|
||||
previewReceipts,
|
||||
|
||||
Reference in New Issue
Block a user