mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 01:28:55 +00:00
fix(files): file notes, links, stars and the trash changed offline wait in the queue and sync once the connection is back
Every file write went straight to the API, so offline a star snapped back
without a word and moving a file to the trash failed with "Failed to delete
file". Notes, the place or booking of a file, a further link, the star, the
trash move, restore, delete for good and emptying the trash now go through
fileRepo and the mutation queue like the other trip data: the local copy
changes at once, and an online write to a file that still has an older one
queued joins the queue behind it, since file writes carry no version token.
The desktop file manager, its assign dialog and the phone's files tab,
menu, link and trash sheets all write through it.
The single file answers carry no ids of further links, so a replayed edit,
star or restore keeps the ones the local copy holds, and the link answer
({ success, links }) writes no row.
What only works online says so instead of failing: an upload shows that it
needs a connection, a place saved with newly picked files is stopped with a
hint, and removing a further link (its row id is known only to the server)
asks to try again once online.
Refs #2601
This commit is contained in:
@@ -168,7 +168,7 @@ describe('FileManager', () => {
|
||||
const starBtn = screen.getByRole('button', { name: /star/i });
|
||||
await user.click(starBtn);
|
||||
|
||||
expect(filesApi.toggleStar).toHaveBeenCalledWith(1, 1);
|
||||
await waitFor(() => expect(filesApi.toggleStar).toHaveBeenCalledWith(1, 1));
|
||||
});
|
||||
|
||||
it('FE-COMP-FILEMANAGER-006: trash toggle loads and displays trashed files', async () => {
|
||||
@@ -207,7 +207,7 @@ describe('FileManager', () => {
|
||||
const restoreBtn = screen.getByRole('button', { name: /restore/i });
|
||||
await user.click(restoreBtn);
|
||||
|
||||
expect(filesApi.restore).toHaveBeenCalledWith(1, 5);
|
||||
await waitFor(() => expect(filesApi.restore).toHaveBeenCalledWith(1, 5));
|
||||
});
|
||||
|
||||
it('FE-COMP-FILEMANAGER-008: permanent delete calls filesApi.permanentDelete after confirm', async () => {
|
||||
|
||||
@@ -26,6 +26,7 @@ import { AssignModal } from './FileManagerAssignModal'
|
||||
const setAssignFileId = vi.fn()
|
||||
const handleAssign = vi.fn(async (_fileId: number, _data: unknown) => {})
|
||||
const refreshFiles = vi.fn(async () => {})
|
||||
const toastError = vi.fn()
|
||||
|
||||
const file = (overrides: Partial<TripFile> = {}) =>
|
||||
({ id: 7, original_name: 'ticket.pdf', description: '', url: '/uploads/files/ticket.pdf', ...overrides }) as unknown as TripFile
|
||||
@@ -47,6 +48,7 @@ function state(overrides: Partial<FileManagerState> = {}): FileManagerState {
|
||||
tripId: 3,
|
||||
handleAssign,
|
||||
refreshFiles,
|
||||
toast: { error: toastError },
|
||||
...overrides,
|
||||
} as unknown as FileManagerState
|
||||
}
|
||||
@@ -198,13 +200,14 @@ describe('AssignModal place list', () => {
|
||||
expect(refreshFiles).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-W5ASG-014: a failing link request is swallowed', async () => {
|
||||
it('FE-W5ASG-014: a failing link request shows the assign error and does not refresh', async () => {
|
||||
addLink.mockRejectedValueOnce(new Error('offline'))
|
||||
render(<AssignModal {...state({ places, files: [file({ place_id: 1 })] })} />)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Eiffel Tower' }))
|
||||
|
||||
await waitFor(() => expect(addLink).toHaveBeenCalled())
|
||||
await waitFor(() => expect(toastError).toHaveBeenCalledWith('files.toast.assignError'))
|
||||
expect(addLink).toHaveBeenCalled()
|
||||
expect(refreshFiles).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -236,16 +239,32 @@ describe('AssignModal place list', () => {
|
||||
expect(removeLink).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-W5ASG-018: a failing links lookup is swallowed', async () => {
|
||||
it('FE-W5ASG-018: a failing links lookup shows the assign error and does not refresh', async () => {
|
||||
getLinks.mockRejectedValueOnce(new Error('offline'))
|
||||
render(<AssignModal {...state({ places, files: [file({ place_id: 1, linked_place_ids: [2] })] })} />)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Eiffel Tower' }))
|
||||
|
||||
await waitFor(() => expect(getLinks).toHaveBeenCalled())
|
||||
await waitFor(() => expect(toastError).toHaveBeenCalledWith('files.toast.assignError'))
|
||||
expect(getLinks).toHaveBeenCalled()
|
||||
expect(refreshFiles).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-W5ASG-035: offline, removing a further link says it needs a connection', async () => {
|
||||
Object.defineProperty(navigator, 'onLine', { value: false, writable: true, configurable: true })
|
||||
const t = (key: string) => (key === 'files.linkNeedsConnection' ? 'Needs a connection' : key)
|
||||
try {
|
||||
render(<AssignModal {...state({ t, places, files: [file({ place_id: 1, linked_place_ids: [2] })] } as Partial<FileManagerState>)} />)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Eiffel Tower' }))
|
||||
|
||||
await waitFor(() => expect(toastError).toHaveBeenCalledWith('Needs a connection'))
|
||||
expect(getLinks).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
Object.defineProperty(navigator, 'onLine', { value: true, writable: true, configurable: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('FE-W5ASG-019: rows keep the linked highlight on mouse-out, free rows do not', () => {
|
||||
render(<AssignModal {...state({ places, files: [file({ place_id: 1 })] })} />)
|
||||
const linked = screen.getByRole('button', { name: 'Louvre' })
|
||||
|
||||
@@ -7,6 +7,7 @@ import { transportIcon } from './FileManager.helpers'
|
||||
import { planFileLinkToggle, runFileLinkRecordStep, type FileLinkField } from './fileActions'
|
||||
import { DialogHeader, DialogShell, DialogTile, NEUTRAL_TINT } from '../shared/DialogShell'
|
||||
import { EditorField, INPUT } from '../shared/dialogParts'
|
||||
import { translateApiError } from '../../i18n'
|
||||
|
||||
export function AssignModal(S: FileManagerState) {
|
||||
const { files, assignFileId, setAssignFileId, t, days, assignments, places, reservations, tripId, handleAssign, refreshFiles } = S
|
||||
@@ -22,8 +23,9 @@ export function AssignModal(S: FileManagerState) {
|
||||
try {
|
||||
await runFileLinkRecordStep(tripId, file.id, field, targetId, step.kind)
|
||||
refreshFiles()
|
||||
} catch {
|
||||
// A failed link record change stays quiet.
|
||||
} catch (err) {
|
||||
// Offline a link record cannot be removed, and the hint says so.
|
||||
S.toast.error(translateApiError(t, err, 'files.toast.assignError'))
|
||||
}
|
||||
}
|
||||
return (
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-FILES-ACTIONS-001 to FE-FILES-ACTIONS-020: the paste, link, field save and trash rules the
|
||||
// FE-FILES-ACTIONS-001 to FE-FILES-ACTIONS-021: the paste, link, field save and trash rules the
|
||||
// desktop file manager and the phone's files tab and sheets share, with what each view keeps.
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
@@ -244,3 +244,27 @@ describe('trashFileWithToast', () => {
|
||||
expect(fb.toast.error).toHaveBeenCalledWith('files.toast.deleteError');
|
||||
});
|
||||
});
|
||||
|
||||
describe('link toggles offline (#2601)', () => {
|
||||
afterEach(() => {
|
||||
Object.defineProperty(navigator, 'onLine', { value: true, writable: true, configurable: true });
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('FE-FILES-ACTIONS-021: the column and a new record wait in the queue, removing a record says it needs a connection', async () => {
|
||||
Object.defineProperty(navigator, 'onLine', { value: false, writable: true, configurable: true });
|
||||
const update = vi.spyOn(filesApi, 'update');
|
||||
const addLink = vi.spyOn(filesApi, 'addLink');
|
||||
const getLinks = vi.spyOn(filesApi, 'getLinks');
|
||||
|
||||
await toggleFileLink(1, buildTripFile({ id: 9, place_id: null }), 'place_id', 5);
|
||||
await toggleFileLink(1, buildTripFile({ id: 9, place_id: 1 }), 'place_id', 6);
|
||||
await expect(
|
||||
toggleFileLink(1, buildTripFile({ id: 9, place_id: 1, linked_place_ids: [6] }), 'place_id', 6)
|
||||
).rejects.toThrow('files.linkNeedsConnection');
|
||||
|
||||
expect(update).not.toHaveBeenCalled();
|
||||
expect(addLink).not.toHaveBeenCalled();
|
||||
expect(getLinks).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { filesApi } from '../../api/client';
|
||||
import { fileRepo } from '../../repo/fileRepo';
|
||||
import type { TranslationFn, TripFile } from '../../types';
|
||||
import type { useToast } from '../shared/Toast';
|
||||
|
||||
@@ -71,7 +71,11 @@ interface FileLinkRecord {
|
||||
reservation_id?: number | string | null;
|
||||
}
|
||||
|
||||
/** Runs an `addLink` or `removeLink` step against the server. */
|
||||
/**
|
||||
* Runs an `addLink` or `removeLink` step. Adding one waits in the offline queue;
|
||||
* removing one needs the server to name the link record, so offline it throws
|
||||
* the hint that says so.
|
||||
*/
|
||||
export async function runFileLinkRecordStep(
|
||||
tripId: number,
|
||||
fileId: number,
|
||||
@@ -81,18 +85,16 @@ export async function runFileLinkRecordStep(
|
||||
rules: FileLinkRules = {}
|
||||
): Promise<void> {
|
||||
if (step === 'addLink') {
|
||||
await filesApi.addLink(
|
||||
await fileRepo.addLink(
|
||||
tripId,
|
||||
fileId,
|
||||
field === 'place_id' ? { place_id: targetId } : { reservation_id: targetId }
|
||||
);
|
||||
return;
|
||||
}
|
||||
const linksRes = (await filesApi.getLinks(tripId, fileId)) as { links?: FileLinkRecord[] };
|
||||
const link = (linksRes.links || []).find((l) =>
|
||||
await fileRepo.removeLinkTo(tripId, fileId, (l: FileLinkRecord) =>
|
||||
rules.matchRecordsByNumber ? Number(l[field]) === targetId : l[field] === targetId
|
||||
);
|
||||
if (link) await filesApi.removeLink(tripId, fileId, link.id);
|
||||
}
|
||||
|
||||
/** Toggles one place or booking on a file, whichever of the server calls that takes. */
|
||||
@@ -104,7 +106,7 @@ export async function toggleFileLink(
|
||||
rules: FileLinkRules = {}
|
||||
): Promise<void> {
|
||||
const step = planFileLinkToggle(file, field, targetId, rules);
|
||||
if (step.kind === 'update') await filesApi.update(tripId, file.id, step.data);
|
||||
if (step.kind === 'update') await fileRepo.update(tripId, file.id, step.data);
|
||||
else await runFileLinkRecordStep(tripId, file.id, field, targetId, step.kind, rules);
|
||||
}
|
||||
|
||||
@@ -128,12 +130,12 @@ export const PHONE_FILE_UPDATE_RULES: FileUpdateRules = { awaitRefresh: true };
|
||||
export async function updateFileFields(
|
||||
tripId: number,
|
||||
fileId: number,
|
||||
data: Parameters<typeof filesApi.update>[2],
|
||||
data: Parameters<typeof fileRepo.update>[2],
|
||||
{ t, toast, refresh }: FileFeedback & { refresh: () => unknown },
|
||||
rules: FileUpdateRules = {}
|
||||
): Promise<void> {
|
||||
try {
|
||||
await filesApi.update(tripId, fileId, data);
|
||||
await fileRepo.update(tripId, fileId, data);
|
||||
if (rules.awaitRefresh) await refresh();
|
||||
else void refresh();
|
||||
} catch {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useState, useCallback, useEffect } from 'react'
|
||||
import { useDropzone } from 'react-dropzone'
|
||||
import { useToast } from '../shared/Toast'
|
||||
import { useTranslation, translateApiError } from '../../i18n'
|
||||
import { filesApi } from '../../api/client'
|
||||
import { fileRepo } from '../../repo/fileRepo'
|
||||
import type { Place, Reservation, TripFile, Day, AssignmentsMap } from '../../types'
|
||||
import { useCanDo } from '../../store/permissionsStore'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
@@ -66,7 +66,7 @@ export function useFileManager({ files = [], onUpload, onDelete, onUpdate, place
|
||||
|
||||
const handleStar = async (fileId: number) => {
|
||||
try {
|
||||
await filesApi.toggleStar(tripId, fileId)
|
||||
await fileRepo.toggleStar(tripId, fileId)
|
||||
refreshFiles()
|
||||
} catch { /* */ }
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
|
||||
import { filesApi } from '../../api/client';
|
||||
import type { useTranslation } from '../../i18n';
|
||||
import { fileRepo } from '../../repo/fileRepo';
|
||||
import type { TripFile } from '../../types';
|
||||
import type { useToast } from '../shared/Toast';
|
||||
|
||||
@@ -31,7 +31,7 @@ export function useFileTrash({ tripId, t, toast, onRestored, open }: FileTrashOp
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await filesApi.list(tripId, true);
|
||||
const data = await fileRepo.listTrash(tripId);
|
||||
setFiles(data.files || []);
|
||||
} catch {
|
||||
// An unreachable trash shows as empty.
|
||||
@@ -43,8 +43,8 @@ export function useFileTrash({ tripId, t, toast, onRestored, open }: FileTrashOp
|
||||
if (!open) return;
|
||||
let cancelled = false;
|
||||
setLoading(true);
|
||||
filesApi
|
||||
.list(tripId, true)
|
||||
fileRepo
|
||||
.listTrash(tripId)
|
||||
.then((data: { files?: TripFile[] }) => {
|
||||
if (!cancelled) setFiles(data.files || []);
|
||||
})
|
||||
@@ -59,7 +59,11 @@ export function useFileTrash({ tripId, t, toast, onRestored, open }: FileTrashOp
|
||||
|
||||
const restore = async (fileId: number) => {
|
||||
try {
|
||||
await filesApi.restore(tripId, fileId);
|
||||
await fileRepo.restore(
|
||||
tripId,
|
||||
fileId,
|
||||
files.find((f) => f.id === fileId)
|
||||
);
|
||||
setFiles((prev) => prev.filter((f) => f.id !== fileId));
|
||||
onRestored();
|
||||
toast.success(t('files.toast.restored'));
|
||||
@@ -70,7 +74,7 @@ export function useFileTrash({ tripId, t, toast, onRestored, open }: FileTrashOp
|
||||
|
||||
const permanentDelete = async (fileId: number) => {
|
||||
try {
|
||||
await filesApi.permanentDelete(tripId, fileId);
|
||||
await fileRepo.permanentDelete(tripId, fileId);
|
||||
setFiles((prev) => prev.filter((f) => f.id !== fileId));
|
||||
toast.success(t('files.toast.deleted'));
|
||||
} catch {
|
||||
@@ -80,7 +84,7 @@ export function useFileTrash({ tripId, t, toast, onRestored, open }: FileTrashOp
|
||||
|
||||
const emptyTrash = async () => {
|
||||
try {
|
||||
await filesApi.emptyTrash(tripId);
|
||||
await fileRepo.emptyTrash(tripId);
|
||||
setFiles([]);
|
||||
toast.success(t('files.toast.trashEmptied'));
|
||||
} catch {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { ChangeEvent, RefObject } from 'react'
|
||||
import { ExternalLink, FileText, Link2, X } from 'lucide-react'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { translateApiError, useTranslation } from '../../i18n'
|
||||
import { useToast } from '../shared/Toast'
|
||||
import { openFile } from '../../utils/fileDownload'
|
||||
import { BookingFileButtons } from './BookingFileButtons'
|
||||
@@ -50,7 +50,7 @@ export function BookingLinkAndFiles({
|
||||
const linkable = reservationId ? tripFiles.filter(f => !f.deleted_at && !attachedFiles.some(af => af.id === f.id)) : []
|
||||
const detach = async (file: TripFile) => {
|
||||
if (!tripId || !reservationId) return
|
||||
try { await unlinkFile(tripId, file, reservationId) } catch { toast.error(t('reservations.toast.updateError')) }
|
||||
try { await unlinkFile(tripId, file, reservationId) } catch (err) { toast.error(translateApiError(t, err, 'reservations.toast.updateError')) }
|
||||
onDetached(file.id)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user