mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 09:54:14 +00:00
feat(places): link an expense to a place, the way bookings already do (#1917)
* feat(places): link an expense to a place, the way bookings already do Recording what a museum ticket or a guided tour cost meant leaving the place, opening the Costs tab and typing it in again — while a booking has had a Costs block in its own form all along. The place form now carries that block. Same component, same flow: with nothing linked it offers Create expense, which saves the place and then opens the Costs editor for a new expense pointing at it; once linked it shows the expense with edit and remove. budget_items gains place_id beside the reservation_id it already had, with the same nullable FK and the same ON DELETE SET NULL. Desktop and phone both, and the mobile editor carries the link through its own save path rather than the desktop one. The expense belongs to the place, not to a day assignment, so a place sitting on five days is not five tickets. Hanging it off the assignment would have meant adding a place to three days quietly creating three expenses and removing a day quietly deleting one. Deleting a place takes its expense with it in the same transaction and announces it, on every path that deletes a place: REST, both MCP tools and the plugin RPC. Closes #1298 * test(places): teach the RPC stubs about linkedExpenseIds The delete paths read the linked expense before the place is gone, so the two hand-built PlacesService stubs threw on the new method instead of reaching the hook, the remove and the broadcast — four failures out of one missing line.
This commit is contained in:
@@ -1393,6 +1393,26 @@ describe('CostsPanel — expense modal', () => {
|
||||
expect(posted).toMatchObject({ name: 'Hotel Astoria', category: 'accommodation', total_price: 240, reservation_id: 12 })
|
||||
expect(onSaved).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-W5COSTS-038b: a prefill from a place links the expense to that place (#1298)', async () => {
|
||||
const user = userEvent.setup()
|
||||
let posted: Record<string, unknown> | null = null
|
||||
server.use(http.post('/api/trips/1/budget', async ({ request }) => {
|
||||
posted = await request.json() as Record<string, unknown>
|
||||
return HttpResponse.json({ item: dinner() })
|
||||
}))
|
||||
render(
|
||||
<ExpenseModal tripId={1} base="EUR" people={tripMembers} me={1} editing={null}
|
||||
prefill={{ name: 'Louvre', category: 'activities', amount: 34, placeId: 7 }}
|
||||
onClose={() => {}} onSaved={vi.fn()} />
|
||||
)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Add expense' }))
|
||||
|
||||
await waitFor(() => expect(posted).toBeTruthy());
|
||||
expect(posted).toMatchObject({ name: 'Louvre', category: 'activities', total_price: 34, place_id: 7 })
|
||||
expect(posted).not.toHaveProperty('reservation_id')
|
||||
})
|
||||
})
|
||||
|
||||
describe('CostsPanel — remaining paths', () => {
|
||||
|
||||
@@ -1000,6 +1000,8 @@ export interface ExpensePrefill {
|
||||
category?: string
|
||||
amount?: number
|
||||
reservationId?: number
|
||||
/** Set when the expense is being created from a place (#1298). */
|
||||
placeId?: number
|
||||
}
|
||||
|
||||
export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClose, onSaved }: {
|
||||
@@ -1252,6 +1254,7 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
|
||||
note: note.trim() || null,
|
||||
ticket_json: splitMode === 'ticket' ? writeTicketItems(ticketItems) : null,
|
||||
...(!editing && prefill?.reservationId ? { reservation_id: prefill.reservationId } : {}),
|
||||
...(!editing && prefill?.placeId ? { place_id: prefill.placeId } : {}),
|
||||
}
|
||||
try {
|
||||
if (editing) await updateBudgetItem(tripId, editing.id, data)
|
||||
|
||||
@@ -7,13 +7,21 @@ import { catMeta } from '../Budget/costsCategories'
|
||||
import type { BudgetItem } from '../../types'
|
||||
|
||||
/**
|
||||
* The Costs block inside a booking modal. Replaces the old inline price + budget
|
||||
* category fields: when no expense is linked yet it offers a "create expense"
|
||||
* button (the modal saves the booking first, then opens the full Costs editor);
|
||||
* once linked it shows the expense with edit / remove actions.
|
||||
* The Costs block inside a booking modal — and, since #1298, inside the place
|
||||
* form, which links its expense the same way. Replaces the old inline price +
|
||||
* budget category fields: when no expense is linked yet it offers a "create
|
||||
* expense" button (the modal saves its own record first, then opens the full
|
||||
* Costs editor); once linked it shows the expense with edit / remove actions.
|
||||
*
|
||||
* Exactly one of reservationId / placeId is set — they are the two sides of the
|
||||
* same link, and the block behaves identically on both.
|
||||
*/
|
||||
export function BookingCostsSection({ reservationId, pendingExpense, onCreate, onEdit, onRemove }: {
|
||||
export function BookingCostsSection({ reservationId, placeId = null, hintKey = 'reservations.createExpenseHint', pendingExpense, onCreate, onEdit, onRemove }: {
|
||||
reservationId: number | null
|
||||
/** Set instead of reservationId when the block sits in the place form (#1298). */
|
||||
placeId?: number | null
|
||||
/** What gets saved before the editor opens — "the booking" or "the place". */
|
||||
hintKey?: string
|
||||
/** A cost parsed from an import that will be linked on save — previewed before the booking exists. */
|
||||
pendingExpense?: { total_price: number; currency?: string | null; category: string } | null
|
||||
onCreate: () => void
|
||||
@@ -25,7 +33,11 @@ export function BookingCostsSection({ reservationId, pendingExpense, onCreate, o
|
||||
const trip = useTripStore(s => s.trip)
|
||||
const displayCurrency = useSettingsStore(s => s.settings.default_currency)
|
||||
const base = (displayCurrency || trip?.currency || 'EUR').toUpperCase()
|
||||
const linked = reservationId ? budgetItems.find(i => i.reservation_id === reservationId) : null
|
||||
const linked = reservationId
|
||||
? budgetItems.find(i => i.reservation_id === reservationId)
|
||||
: placeId
|
||||
? budgetItems.find(i => i.place_id === placeId)
|
||||
: null
|
||||
|
||||
const labelCls = 'block text-[11px] font-semibold uppercase tracking-[0.08em] text-content-faint mb-[6px]'
|
||||
|
||||
@@ -40,7 +52,7 @@ export function BookingCostsSection({ reservationId, pendingExpense, onCreate, o
|
||||
<span style={{ width: 26, height: 26, borderRadius: 7, display: 'grid', placeItems: 'center', background: meta.color + '22', color: meta.color, flexShrink: 0 }}><Icon size={14} /></span>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div className="text-content" style={{ fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 600 }}>{t(meta.labelKey)}</div>
|
||||
<div className="text-content-faint" style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))' }}>{t('reservations.createExpenseHint')}</div>
|
||||
<div className="text-content-faint" style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))' }}>{t(hintKey)}</div>
|
||||
</div>
|
||||
<span className="text-content" style={{ fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 700, flexShrink: 0 }}>{formatMoney(pendingExpense.total_price, pendingExpense.currency || base, locale)}</span>
|
||||
</div>
|
||||
@@ -76,7 +88,7 @@ export function BookingCostsSection({ reservationId, pendingExpense, onCreate, o
|
||||
style={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, padding: '11px 13px', borderRadius: 10, fontSize: 'calc(13.5px * var(--fs-scale-body, 1))', fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}>
|
||||
<Plus size={15} /> {t('reservations.createExpense')}
|
||||
</button>
|
||||
<div className="text-content-faint" style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', marginTop: 6 }}>{t('reservations.createExpenseHint')}</div>
|
||||
<div className="text-content-faint" style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', marginTop: 6 }}>{t(hintKey)}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import type { BudgetItem } from '../../types'
|
||||
|
||||
/**
|
||||
* A request from a booking modal to open the Costs expense editor — either to
|
||||
* edit the already-linked expense, or to create a new one prefilled from the
|
||||
* booking (the modal saves the booking first so `reservationId` is known).
|
||||
* A request from a booking modal — or from the place form (#1298) — to open the
|
||||
* Costs expense editor: either to edit the already-linked expense, or to create
|
||||
* a new one prefilled from the record. The modal saves itself first, so the
|
||||
* `reservationId` / `placeId` it names already exists.
|
||||
*/
|
||||
export interface BookingExpenseRequest {
|
||||
editItem?: BudgetItem
|
||||
prefill?: { reservationId?: number; name?: string; category?: string; amount?: number }
|
||||
prefill?: { reservationId?: number; placeId?: number; name?: string; category?: string; amount?: number }
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-COMP-PLACEFORM-001 to FE-COMP-PLACEFORM-036, FE-PLANNER-PLACEFORM-016 to FE-PLANNER-PLACEFORM-062
|
||||
// FE-COMP-PLACEFORM-001 to FE-COMP-PLACEFORM-036, FE-PLANNER-PLACEFORM-016 to FE-PLANNER-PLACEFORM-067, plus FE-PLANNER-PLACEFORM-068 to -072
|
||||
import { render, screen, waitFor, fireEvent, within } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
@@ -1467,4 +1467,94 @@ describe('PlaceFormModal remaining branches', () => {
|
||||
expect(websiteInput().value).toBe('https://stored.example');
|
||||
});
|
||||
});
|
||||
|
||||
// ── Linked expense (#1298) — the same block bookings have ──────────────────
|
||||
|
||||
describe('Costs section', () => {
|
||||
const withBudget = () => seedStore(useAddonStore, {
|
||||
addons: [{ id: 'budget', name: 'Budget', type: 'budget', icon: '', enabled: true }],
|
||||
loaded: true,
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLACEFORM-068: the block only appears while the Budget addon is on', () => {
|
||||
const { unmount } = render(<PlaceFormModal {...defaultProps} />);
|
||||
expect(screen.queryByRole('button', { name: /Create expense/i })).not.toBeInTheDocument();
|
||||
unmount();
|
||||
|
||||
withBudget();
|
||||
render(<PlaceFormModal {...defaultProps} />);
|
||||
expect(screen.getByRole('button', { name: /Create expense/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLACEFORM-069: creating an expense saves the place first, then opens the editor', async () => {
|
||||
withBudget();
|
||||
const onSave = vi.fn().mockResolvedValue({ id: 42 });
|
||||
const onOpenExpense = vi.fn();
|
||||
render(<PlaceFormModal {...defaultProps} onSave={onSave} onOpenExpense={onOpenExpense} />);
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText(/e\.g\. Eiffel Tower/i), { target: { value: 'Louvre' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: /Create expense/i }));
|
||||
|
||||
await waitFor(() => expect(onOpenExpense).toHaveBeenCalled());
|
||||
expect(onSave).toHaveBeenCalled();
|
||||
expect(onSave.mock.invocationCallOrder[0]).toBeLessThan(onOpenExpense.mock.invocationCallOrder[0]);
|
||||
expect(onOpenExpense).toHaveBeenCalledWith({
|
||||
prefill: { placeId: 42, name: 'Louvre', category: 'activities' },
|
||||
});
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLACEFORM-070: a save that yields no id opens no editor', async () => {
|
||||
withBudget();
|
||||
const onSave = vi.fn().mockResolvedValue(undefined);
|
||||
const onOpenExpense = vi.fn();
|
||||
render(<PlaceFormModal {...defaultProps} onSave={onSave} onOpenExpense={onOpenExpense} />);
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText(/e\.g\. Eiffel Tower/i), { target: { value: 'Louvre' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: /Create expense/i }));
|
||||
|
||||
await waitFor(() => expect(onSave).toHaveBeenCalled());
|
||||
expect(onOpenExpense).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLACEFORM-070b: a nameless click drops the intent instead of arming the next save', async () => {
|
||||
withBudget();
|
||||
const onSave = vi.fn().mockResolvedValue({ id: 42 });
|
||||
const onOpenExpense = vi.fn();
|
||||
render(<PlaceFormModal {...defaultProps} onSave={onSave} onOpenExpense={onOpenExpense} />);
|
||||
|
||||
// No name yet — the save is refused and the intent must not survive it.
|
||||
fireEvent.click(screen.getByRole('button', { name: /Create expense/i }));
|
||||
await waitFor(() => expect(onSave).not.toHaveBeenCalled());
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText(/e\.g\. Eiffel Tower/i), { target: { value: 'Louvre' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: /^Add$/i }));
|
||||
|
||||
await waitFor(() => expect(onSave).toHaveBeenCalled());
|
||||
expect(onOpenExpense).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLACEFORM-071: an already-linked expense is shown with its amount instead of the button', () => {
|
||||
withBudget();
|
||||
seedStore(useTripStore, {
|
||||
trip: buildTrip({ id: 1 }),
|
||||
budgetItems: [{ id: 8, trip_id: 1, name: 'Louvre tickets', total_price: 34, category: 'activities', place_id: 7 }],
|
||||
});
|
||||
render(<PlaceFormModal {...defaultProps} place={{ id: 7, name: 'Louvre' } as never} />);
|
||||
|
||||
expect(screen.getByText('Louvre tickets')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: /Create expense/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLACEFORM-072: an expense linked to another place is not claimed', () => {
|
||||
withBudget();
|
||||
seedStore(useTripStore, {
|
||||
trip: buildTrip({ id: 1 }),
|
||||
budgetItems: [{ id: 8, trip_id: 1, name: 'Orsay tickets', total_price: 16, category: 'activities', place_id: 99 }],
|
||||
});
|
||||
render(<PlaceFormModal {...defaultProps} place={{ id: 7, name: 'Louvre' } as never} />);
|
||||
|
||||
expect(screen.queryByText('Orsay tickets')).not.toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /Create expense/i })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -16,7 +16,9 @@ import { useTranslation } from '../../i18n'
|
||||
import CustomTimePicker from '../shared/CustomTimePicker'
|
||||
import { DEFAULT_FORM, isGoogleMapsUrl, mergeResult, type PlaceFormData, type ResultField } from './PlaceFormModal.helpers'
|
||||
import { getApiErrorMessage } from '../../utils/apiError'
|
||||
import type { Place, Category, Assignment } from '../../types'
|
||||
import { BookingCostsSection } from './BookingCostsSection'
|
||||
import type { BookingExpenseRequest } from './BookingCostsSection.types'
|
||||
import type { Place, Category, Assignment, BudgetItem } from '../../types'
|
||||
import { NumericInput } from '../shared/NumericInput'
|
||||
|
||||
// The submit payload mirrors the form, but lat/lng are parsed to numbers and
|
||||
@@ -31,7 +33,7 @@ export interface PlaceSubmitData extends Omit<PlaceFormData, 'lat' | 'lng' | 'ca
|
||||
interface PlaceFormModalProps {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
onSave: (data: PlaceSubmitData, files?: File[]) => Promise<void> | void
|
||||
onSave: (data: PlaceSubmitData, files?: File[]) => Promise<{ id: number } | void> | void
|
||||
place: Place | null
|
||||
prefillCoords?: { lat: number; lng: number; name?: string; address?: string; website?: string; phone?: string; osm_id?: string } | null
|
||||
tripId: number
|
||||
@@ -43,6 +45,9 @@ interface PlaceFormModalProps {
|
||||
* picker column when the Collections addon is enabled. Sourced from the trip
|
||||
* planner's matchMedia('(max-width:767px)'). */
|
||||
isMobile?: boolean
|
||||
/** Opens the Costs editor for this place's linked expense (#1298) — the same
|
||||
* seam the booking and transport modals use. */
|
||||
onOpenExpense?: (req: BookingExpenseRequest) => void
|
||||
}
|
||||
|
||||
|
||||
@@ -78,6 +83,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
|
||||
const {
|
||||
isOpen, onClose, onSave, place, prefillCoords, tripId, categories,
|
||||
onCategoryCreated, assignmentId, dayAssignments = [], isMobile = false,
|
||||
onOpenExpense,
|
||||
} = props
|
||||
const [form, setForm] = useState(DEFAULT_FORM)
|
||||
const [mapsSearch, setMapsSearch] = useState('')
|
||||
@@ -108,6 +114,11 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
|
||||
const tripObj = useTripStore((s) => s.trip)
|
||||
const canUploadFiles = can('file_upload', tripObj)
|
||||
const collectionsEnabled = useAddonStore((s) => s.isEnabled('collections'))
|
||||
const isBudgetEnabled = useAddonStore((s) => s.isEnabled('budget'))
|
||||
const deleteBudgetItem = useTripStore((s) => s.deleteBudgetItem)
|
||||
// Set right before submit when the user clicked create/edit expense — the
|
||||
// place has to exist before an expense can point at it (see ReservationModal).
|
||||
const expenseIntentRef = useRef<{ editItem?: BudgetItem; create?: boolean } | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (place) {
|
||||
@@ -430,9 +441,12 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
|
||||
|
||||
const hasTimeError = place && form.place_time && form.end_time && form.place_time.length >= 5 && form.end_time.length >= 5 && form.end_time <= form.place_time
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault()
|
||||
const handleSubmit = async (e?: { preventDefault?: () => void }) => {
|
||||
e?.preventDefault?.()
|
||||
if (!form.name.trim()) {
|
||||
// Nothing was saved, so an expense intent from a previous click is stale —
|
||||
// otherwise the next plain Save would open a Costs editor out of nowhere.
|
||||
expenseIntentRef.current = null
|
||||
toast.error(t('places.nameRequired'))
|
||||
return
|
||||
}
|
||||
@@ -449,13 +463,23 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
|
||||
}
|
||||
setIsSaving(true)
|
||||
try {
|
||||
await onSave({
|
||||
const saved = await onSave({
|
||||
...form,
|
||||
lat: form.lat ? parseFloat(form.lat) : null,
|
||||
lng: form.lng ? parseFloat(form.lng) : null,
|
||||
category_id: form.category_id || null,
|
||||
_pendingFiles: pendingFiles.length > 0 ? pendingFiles : undefined,
|
||||
})
|
||||
// Open the Costs editor for the saved place when the user asked to
|
||||
// create/edit its linked expense — gated on an id, so a create that the
|
||||
// server refused never opens an editor pointing at nothing (#1298).
|
||||
const intent = expenseIntentRef.current
|
||||
expenseIntentRef.current = null
|
||||
const savedId = (saved && 'id' in saved ? saved.id : null) ?? place?.id ?? null
|
||||
if (intent && onOpenExpense && savedId) {
|
||||
if (intent.editItem) onOpenExpense({ editItem: intent.editItem })
|
||||
else onOpenExpense({ prefill: { placeId: savedId, name: form.name.trim(), category: 'activities' } })
|
||||
}
|
||||
onClose()
|
||||
} catch (err: unknown) {
|
||||
toast.error(err instanceof Error ? err.message : t('places.saveError'))
|
||||
@@ -464,6 +488,12 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
|
||||
}
|
||||
}
|
||||
|
||||
const handleCreateExpense = () => { expenseIntentRef.current = { create: true }; void handleSubmit() }
|
||||
const handleEditExpense = (item: BudgetItem) => { expenseIntentRef.current = { editItem: item }; void handleSubmit() }
|
||||
const handleRemoveExpense = async (item: BudgetItem) => {
|
||||
try { await deleteBudgetItem(Number(tripId), item.id) } catch { toast.error(t('common.unknownError')) }
|
||||
}
|
||||
|
||||
return {
|
||||
isOpen,
|
||||
onClose,
|
||||
@@ -527,6 +557,10 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
|
||||
handleSubmit,
|
||||
duplicateWarning,
|
||||
detailsSelection,
|
||||
isBudgetEnabled,
|
||||
handleCreateExpense,
|
||||
handleEditExpense,
|
||||
handleRemoveExpense,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -593,6 +627,10 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
|
||||
handleSubmit,
|
||||
duplicateWarning,
|
||||
detailsSelection,
|
||||
isBudgetEnabled,
|
||||
handleCreateExpense,
|
||||
handleEditExpense,
|
||||
handleRemoveExpense,
|
||||
} = S
|
||||
// Desktop + Collections addon → the saved-place picker on the right. Mobile
|
||||
// always keeps the original single-column form untouched.
|
||||
@@ -917,6 +955,19 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Costs — create / view the expense linked to this place (#1298).
|
||||
Same block, same flow as a booking: save first, then the editor. */}
|
||||
{isBudgetEnabled && (
|
||||
<BookingCostsSection
|
||||
placeId={place?.id ?? null}
|
||||
reservationId={null}
|
||||
hintKey="places.createExpenseHint"
|
||||
onCreate={handleCreateExpense}
|
||||
onEdit={handleEditExpense}
|
||||
onRemove={handleRemoveExpense}
|
||||
/>
|
||||
)}
|
||||
|
||||
</form>
|
||||
{twoColumn && (
|
||||
<CollectionPicker bias={locationBias} onSelect={handleSelectMapsResult} t={t} />
|
||||
|
||||
Reference in New Issue
Block a user