mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-22 13:10:29 +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:
@@ -4,7 +4,7 @@
|
||||
"src/components/Admin/AdminPluginsPanel.test.tsx": 2704,
|
||||
"src/components/Admin/AdminPluginsPanel.tsx": 1266,
|
||||
"src/components/Budget/CostsPanel.test.tsx": 2730,
|
||||
"src/components/Budget/CostsPanel.tsx": 1798,
|
||||
"src/components/Budget/CostsPanel.tsx": 1740,
|
||||
"src/components/Map/MapView.tsx": 1200,
|
||||
"src/components/Map/MapViewGL.test.tsx": 2919,
|
||||
"src/components/Map/MapViewGL.tsx": 2126,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { ArrowRight, Check, ChevronDown, Plus, Trash2, Wallet, Receipt, Paperclip } from 'lucide-react'
|
||||
import { ArrowRight, Check, ChevronDown, FileText, Link2, Plus, Trash2, Wallet, Receipt, Paperclip } from 'lucide-react'
|
||||
import MSheet from '../../../components/MSheet'
|
||||
import CustomSelect from '../../../../components/shared/CustomSelect'
|
||||
import { NumericInput } from '../../../../components/shared/NumericInput'
|
||||
@@ -66,6 +66,7 @@ export default function MCostSheet({ tripId, base, people, me, editing, prefill,
|
||||
ticketInfo, handleAddEmptyItem, handleUpdateItemName, handleUpdateItemPrice, handleRemoveItem, handleToggleItemParticipant,
|
||||
customAmounts, handleCustomAmountChange, splitUnits, splitSum, customBalanced, each, equalShares, placeholderShares,
|
||||
receipts, pendingReceiptFiles, uploadingReceipt, handleReceiptFileSelect, handleRemoveReceipt, handleRemovePendingReceipt,
|
||||
linkableFiles, handleLinkReceipt,
|
||||
previewReceipts, setPreviewReceipts, valid, saving, save,
|
||||
} = useExpenseForm({ tripId, base, people, me, editing, prefill, onSaved, oneSaveAtATime: true, keepSavingOnSuccess: true })
|
||||
|
||||
@@ -80,6 +81,8 @@ export default function MCostSheet({ tripId, base, people, me, editing, prefill,
|
||||
}
|
||||
|
||||
const [catOpen, setCatOpen] = useState(false)
|
||||
// The trip's files to link as a receipt (#2839), folded open under the receipts header.
|
||||
const [linkingReceipt, setLinkingReceipt] = useState(false)
|
||||
const [deleteArmed, setDeleteArmed] = useState(false)
|
||||
|
||||
const handleDelete = async () => {
|
||||
@@ -504,26 +507,56 @@ export default function MCostSheet({ tripId, base, people, me, editing, prefill,
|
||||
className={FIELD_AREA_CLS}
|
||||
/>
|
||||
|
||||
{/* RECEIPTS */}
|
||||
<div className="mb-[6px] mt-4 flex items-center justify-between">
|
||||
<Eyebrow className="uppercase">{t('costs.receiptsTitle') || t('costs.receipts')}</Eyebrow>
|
||||
<label className="flex cursor-pointer items-center gap-1 text-[0.75rem] font-semibold text-m-ink">
|
||||
<input
|
||||
type="file"
|
||||
multiple
|
||||
accept="image/*,application/pdf"
|
||||
className="hidden"
|
||||
onChange={e => {
|
||||
handleReceiptFileSelect(e.target.files)
|
||||
e.target.value = ''
|
||||
}}
|
||||
/>
|
||||
<span className="flex items-center gap-1 rounded-full border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-2.5 py-1 text-m-muted">
|
||||
<Plus size={12} /> {t('costs.attachReceipt')}
|
||||
</span>
|
||||
</label>
|
||||
{/* RECEIPTS. Where the header and both pills do not fit on one line, the
|
||||
pills move under it rather than squeezing the title. */}
|
||||
<div className="mb-[6px] mt-4 flex flex-wrap items-center justify-between gap-x-2 gap-y-[6px]">
|
||||
<Eyebrow className="uppercase">{t('costs.receiptsTitle')}</Eyebrow>
|
||||
<div className="ms-auto flex items-center gap-1.5">
|
||||
{linkableFiles.length > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={linkingReceipt}
|
||||
onClick={() => setLinkingReceipt(v => !v)}
|
||||
className={`flex items-center gap-1 rounded-full border px-2.5 py-1 text-caption font-semibold ${linkingReceipt ? 'border-transparent bg-m-act text-m-actfg' : 'border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] text-m-muted'}`}
|
||||
>
|
||||
<Link2 size={12} strokeWidth={2.2} /> {t('files.link')}
|
||||
</button>
|
||||
)}
|
||||
<label className="flex cursor-pointer items-center gap-1 text-[0.75rem] font-semibold text-m-ink">
|
||||
<input
|
||||
type="file"
|
||||
multiple
|
||||
accept="image/*,application/pdf"
|
||||
className="hidden"
|
||||
onChange={e => {
|
||||
handleReceiptFileSelect(e.target.files)
|
||||
e.target.value = ''
|
||||
}}
|
||||
/>
|
||||
<span className="flex items-center gap-1 rounded-full border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-2.5 py-1 text-m-muted">
|
||||
<Plus size={12} /> {t('costs.attachReceipt')}
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{linkingReceipt && linkableFiles.length > 0 && (
|
||||
<div className="mb-2 flex max-h-[200px] flex-col gap-1 overflow-y-auto overscroll-contain">
|
||||
{linkableFiles.map(file => (
|
||||
<button
|
||||
key={file.id}
|
||||
type="button"
|
||||
onClick={() => { handleLinkReceipt(file); setLinkingReceipt(false) }}
|
||||
className={`${ROW_CLS} text-start`}
|
||||
>
|
||||
<FileText size={14} className="flex-none text-m-faint" />
|
||||
<span dir="auto" className="min-w-0 flex-1 truncate text-body font-medium text-m-ink">{file.original_name}</span>
|
||||
<Link2 size={13} strokeWidth={2.2} className="flex-none text-m-faint" />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{uploadingReceipt && (
|
||||
<div className="mb-2 text-[0.75rem] text-m-faint">
|
||||
{t('common.saving')}...
|
||||
|
||||
@@ -5,12 +5,12 @@ import type { TripMember } from '../../../../src/components/Budget/BudgetPanelMe
|
||||
import { clearExchangeRateCache } from '../../../../src/hooks/useExchangeRates'
|
||||
import { useTripStore, type TripStoreState } from '../../../../src/store/tripStore'
|
||||
import type { BudgetItem, BudgetItemMember } from '../../../../src/types'
|
||||
import { buildBudgetItem, buildTrip } from '../../../helpers/factories'
|
||||
import { buildBudgetItem, buildTrip, buildTripFile } from '../../../helpers/factories'
|
||||
import { localToday } from '../../../../src/components/Planner/today'
|
||||
import { resetAllStores } from '../../../helpers/store'
|
||||
import { act, fireEvent, render, screen, waitFor } from '../../../helpers/render'
|
||||
|
||||
// FE-MOB-COSTSH-001 to FE-MOB-COSTSH-040
|
||||
// FE-MOB-COSTSH-001 to FE-MOB-COSTSH-041
|
||||
// The sheet reads its copy from useTranslation(), so assertions are English.
|
||||
// EUR formats de-DE style: displayed amounts and inputs use a comma.
|
||||
|
||||
@@ -775,4 +775,19 @@ describe('MCostSheet', () => {
|
||||
expect(screen.getByText('18,00 €')).toBeInTheDocument()
|
||||
expect(submit()).toBeEnabled()
|
||||
})
|
||||
|
||||
it('FE-MOB-COSTSH-041: a trip file is linked as a receipt and saved with the expense (#2839)', async () => {
|
||||
useTripStore.setState({ files: [buildTripFile({ id: 51, original_name: 'hotel-confirmation.pdf' })] } as unknown as Partial<TripStoreState>)
|
||||
renderSheet()
|
||||
fillBasics('Hotel', '200')
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Link' }))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'hotel-confirmation.pdf' }))
|
||||
// Listed with the receipts now, and nothing is left to link.
|
||||
expect(screen.getByRole('button', { name: 'hotel-confirmation.pdf' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Link' })).toBeNull()
|
||||
|
||||
fireEvent.click(submit())
|
||||
await waitFor(() => expect(addBudgetItem).toHaveBeenCalledTimes(1))
|
||||
expect(addBudgetItem.mock.calls[0][1]).toMatchObject({ receipt_file_ids: [51] })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -104,6 +104,8 @@ On the phone the booking, transport and place sheets carry the same block. Tap a
|
||||
|
||||
An expense can carry the receipt or invoice behind it. **Attach** in the **Receipts & Invoices** block of the expense dialog opens the file picker for images and PDFs, and several files can go on one expense. They are uploaded when the expense is saved, land in the trip's Files with a link to the expense, and are listed in the block from then on; click a name to view it. If the save fails after the upload, the uploaded files are taken back out again. Any that could not be removed are reported (*Save failed, and 1 uploaded receipt is still there. Remove it in the Files tab.*), so you can delete them there.
|
||||
|
||||
A file the trip already has can be the receipt too, so a booking confirmation that doubles as the invoice is not uploaded a second time. **Link**, beside **Attach** while the trip has files the expense does not carry yet, lists them: the files of the booking the expense belongs to come first, and a click puts one on the expense. Like an attached file it is linked when you save, and nothing is uploaded. The file keeps its other links, and **Remove receipt** only takes it off the expense again. The phone sheet has the same **Link** pill beside **Attach receipt / invoice**.
|
||||
|
||||
Receipts need a connection. If you are offline, the dialog says *Receipts need a connection to upload. Remove the new ones to save the expense offline, or save once you are back online.* An expense without new receipts can be saved offline.
|
||||
|
||||
A row with receipts shows a **Receipts** chip beside the name, with the count when there is more than one. Click it to open the viewer: it shows one receipt at a time, pages through them with the **arrow keys**, and offers a download for a PDF.
|
||||
|
||||
Reference in New Issue
Block a user