@prenta/admin 2.14.2 → 2.14.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  // @vitest-environment happy-dom
2
2
  import { beforeEach, describe, expect, it, vi } from 'vitest'
3
- import { fireEvent, render, screen, waitFor } from '@testing-library/react'
3
+ import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
4
4
 
5
5
  // Drive the global All Entries inbox through a mocked forms-service so the test
6
6
  // owns the data and can assert the cross-form table (Form column + form
@@ -74,10 +74,7 @@ vi.mock('../../lib/forms-service.js', () => ({
74
74
  downloadEntriesExport: (opts?: unknown) => downloadEntriesExport(opts),
75
75
  }))
76
76
 
77
- vi.mock('../../lib/forms-events.js', () => ({
78
- onFormsChanged: () => () => {},
79
- emitFormsChanged: vi.fn(),
80
- }))
77
+ const { emitFormsChanged } = await import('../../lib/forms-events.js')
81
78
 
82
79
  vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn(), loading: vi.fn() } }))
83
80
 
@@ -86,12 +83,167 @@ const { FormEntries } = await import('../../views/FormEntries.js')
86
83
  beforeEach(() => {
87
84
  Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1280 })
88
85
  fetchForms.mockClear()
89
- fetchEntries.mockClear()
86
+ fetchEntries.mockReset()
87
+ fetchEntries.mockResolvedValue({ entries: ENTRIES, total: ENTRIES.length, page: 1, pageSize: 25 })
88
+ updateEntry.mockReset()
89
+ updateEntry.mockResolvedValue({ data: ENTRIES[0] })
90
90
  fetchEntryCounts.mockClear()
91
91
  fetchEntry.mockClear()
92
92
  })
93
93
 
94
94
  describe('FormEntries (All Entries)', () => {
95
+ it('shows the new query error when a failed event refresh supersedes a filter load', async () => {
96
+ render(<FormEntries onNavigate={() => {}} />)
97
+ await screen.findByRole('article', { name: /Jordan Avery/ })
98
+ let finish!: (value: Awaited<ReturnType<typeof fetchEntries>>) => void
99
+ fetchEntries.mockImplementationOnce(
100
+ () =>
101
+ new Promise((resolve) => {
102
+ finish = resolve
103
+ }),
104
+ )
105
+ fireEvent.change(screen.getByLabelText('Filter by form'), { target: { value: 'f2' } })
106
+ await screen.findByRole('status', { name: 'Loading entries' })
107
+ fetchEntries.mockRejectedValueOnce(new Error('Filtered entries unavailable'))
108
+ act(() => emitFormsChanged())
109
+ expect(await screen.findByRole('alert')).toHaveProperty(
110
+ 'textContent',
111
+ expect.stringContaining('Filtered entries unavailable'),
112
+ )
113
+ expect(screen.queryByRole('article', { name: /Jordan Avery/ })).toBeNull()
114
+ await act(async () => finish({ entries: [ENTRIES[1]!], total: 1, page: 1, pageSize: 25 }))
115
+ expect(screen.getByRole('alert').textContent).toContain('Filtered entries unavailable')
116
+ expect(screen.queryByRole('article', { name: /Jordan Avery/ })).toBeNull()
117
+ fetchEntries.mockResolvedValueOnce({ entries: [ENTRIES[1]!], total: 1, page: 1, pageSize: 25 })
118
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
119
+ await screen.findByRole('article', { name: /Priya Nair/ })
120
+ expect(screen.queryByRole('alert')).toBeNull()
121
+ })
122
+
123
+ it('preserves optimistic changes across refreshes and overlapping writes to the same entry', async () => {
124
+ render(<FormEntries onNavigate={() => {}} />)
125
+ const row = await screen.findByRole('article', { name: /Jordan Avery/ })
126
+ let finishRefresh!: (value: Awaited<ReturnType<typeof fetchEntries>>) => void
127
+ fetchEntries.mockImplementationOnce(
128
+ () =>
129
+ new Promise((resolve) => {
130
+ finishRefresh = resolve
131
+ }),
132
+ )
133
+ act(() => emitFormsChanged())
134
+ let finishStar!: (value: Awaited<ReturnType<typeof updateEntry>>) => void
135
+ let finishUnstar!: (value: Awaited<ReturnType<typeof updateEntry>>) => void
136
+ updateEntry
137
+ .mockImplementationOnce(
138
+ () =>
139
+ new Promise((resolve) => {
140
+ finishStar = resolve
141
+ }),
142
+ )
143
+ .mockImplementationOnce(
144
+ () =>
145
+ new Promise((resolve) => {
146
+ finishUnstar = resolve
147
+ }),
148
+ )
149
+ fireEvent.click(within(row).getByRole('button', { name: 'Star' }))
150
+ expect(within(row).getByRole('button', { name: 'Unstar' })).toBeTruthy()
151
+ await act(async () => finishRefresh({ entries: ENTRIES, total: 2, page: 1, pageSize: 25 }))
152
+ expect(within(row).getByRole('button', { name: 'Unstar' })).toBeTruthy()
153
+ fireEvent.click(within(row).getByRole('button', { name: 'Unstar' }))
154
+ // A later write cannot reach the server before the earlier write completes.
155
+ expect(updateEntry).toHaveBeenCalledTimes(1)
156
+ const starred = { ...ENTRIES[0]!, starred: true }
157
+ fetchEntries.mockResolvedValueOnce({
158
+ entries: [starred, ENTRIES[1]!],
159
+ total: 2,
160
+ page: 1,
161
+ pageSize: 25,
162
+ })
163
+ await act(async () => finishStar({ data: starred }))
164
+ expect(updateEntry).toHaveBeenCalledTimes(2)
165
+ expect(updateEntry).toHaveBeenLastCalledWith('e1', { starred: false })
166
+ expect(within(row).getByRole('button', { name: 'Star' })).toBeTruthy()
167
+ await act(async () => finishUnstar({ data: ENTRIES[0] }))
168
+ expect(within(row).getByRole('button', { name: 'Star' })).toBeTruthy()
169
+ })
170
+
171
+ it('continues queued writes after a failed request without blocking other entries', async () => {
172
+ render(<FormEntries onNavigate={() => {}} />)
173
+ const row = await screen.findByRole('article', { name: /Jordan Avery/ })
174
+ const other = screen.getByRole('article', { name: /Priya Nair/ })
175
+ let failFirst!: (error: Error) => void
176
+ updateEntry.mockImplementationOnce(
177
+ () =>
178
+ new Promise((_resolve, reject) => {
179
+ failFirst = reject
180
+ }),
181
+ )
182
+ fireEvent.click(within(row).getByRole('button', { name: 'Star' }))
183
+ await waitFor(() => expect(updateEntry).toHaveBeenCalledTimes(1))
184
+ fireEvent.click(within(row).getByRole('button', { name: 'Unstar' }))
185
+ fireEvent.click(within(other).getByRole('button', { name: 'Star' }))
186
+ await waitFor(() => expect(updateEntry).toHaveBeenCalledWith('e2', { starred: true }))
187
+ expect(updateEntry).not.toHaveBeenCalledWith('e1', { starred: false })
188
+ await act(async () => failFirst(new Error('Connection interrupted')))
189
+ await waitFor(() => expect(updateEntry).toHaveBeenCalledWith('e1', { starred: false }))
190
+ const reloaded = await screen.findByRole('article', { name: /Jordan Avery/ })
191
+ expect(within(reloaded).getByRole('button', { name: 'Star' })).toBeTruthy()
192
+ })
193
+
194
+ it('keeps rows, scroll and checkbox selection mounted while marking an entry read', async () => {
195
+ render(<FormEntries onNavigate={() => {}} />)
196
+ const row = await screen.findByRole('article', { name: /Jordan Avery/ })
197
+ const list = screen.getByRole('region', { name: 'Form entries' })
198
+ list.scrollTop = 260
199
+ const checkbox = screen.getByRole('button', { name: 'Select Jordan Avery' })
200
+ fireEvent.click(checkbox)
201
+ let finish!: (value: Awaited<ReturnType<typeof fetchEntries>>) => void
202
+ fetchEntries.mockImplementationOnce(
203
+ () =>
204
+ new Promise((resolve) => {
205
+ finish = resolve
206
+ }),
207
+ )
208
+ const calls = fetchEntries.mock.calls.length
209
+ fireEvent.click(row)
210
+ await waitFor(() => expect(fetchEntries.mock.calls.length).toBe(calls + 1))
211
+ expect(screen.queryByRole('status', { name: 'Loading entries' })).toBeNull()
212
+ expect(screen.getByRole('article', { name: /Jordan Avery/ })).toBe(row)
213
+ expect(checkbox.getAttribute('aria-pressed')).toBe('true')
214
+ expect(list.scrollTop).toBe(260)
215
+ await act(async () =>
216
+ finish({
217
+ entries: ENTRIES.map((e) => ({ ...e, unread: false })),
218
+ total: 2,
219
+ page: 1,
220
+ pageSize: 25,
221
+ }),
222
+ )
223
+ expect(screen.getByRole('article', { name: /Jordan Avery/ })).toBe(row)
224
+ expect(checkbox.getAttribute('aria-pressed')).toBe('true')
225
+ expect(list.scrollTop).toBe(260)
226
+ })
227
+
228
+ it('ignores an old background response after the form filter changes', async () => {
229
+ render(<FormEntries onNavigate={() => {}} />)
230
+ await screen.findByRole('article', { name: /Jordan Avery/ })
231
+ let finish!: (value: Awaited<ReturnType<typeof fetchEntries>>) => void
232
+ fetchEntries.mockImplementationOnce(
233
+ () =>
234
+ new Promise((resolve) => {
235
+ finish = resolve
236
+ }),
237
+ )
238
+ act(() => emitFormsChanged())
239
+ fetchEntries.mockResolvedValueOnce({ entries: [ENTRIES[1]!], total: 1, page: 1, pageSize: 25 })
240
+ fireEvent.change(screen.getByLabelText('Filter by form'), { target: { value: 'f2' } })
241
+ await waitFor(() => expect(screen.queryByRole('article', { name: /Jordan Avery/ })).toBeNull())
242
+ await act(async () => finish({ entries: ENTRIES, total: 2, page: 1, pageSize: 25 }))
243
+ expect(screen.queryByRole('article', { name: /Jordan Avery/ })).toBeNull()
244
+ expect(screen.getByRole('article', { name: /Priya Nair/ })).toBeTruthy()
245
+ })
246
+
95
247
  it('renders cross-form entries with a Form column and filter', async () => {
96
248
  render(<FormEntries onNavigate={() => {}} />)
97
249
 
@@ -145,7 +297,8 @@ describe('FormEntries (All Entries)', () => {
145
297
  utmCampaign: 'spring-launch',
146
298
  })
147
299
  fetchEntry.mockResolvedValueOnce({ entry: attributed, fields: [] })
148
- fetchEntries.mockResolvedValueOnce({ entries: [attributed], total: 1, page: 1, pageSize: 25 })
300
+ updateEntry.mockResolvedValueOnce({ data: attributed })
301
+ fetchEntries.mockResolvedValue({ entries: [attributed], total: 1, page: 1, pageSize: 25 })
149
302
  render(<FormEntries onNavigate={() => {}} />)
150
303
  fireEvent.click(await screen.findByRole('article', { name: /Jordan Avery/ }))
151
304
 
@@ -318,6 +318,21 @@ export function EntriesInbox({
318
318
  const [total, setTotal] = useState(0)
319
319
  const [counts, setCounts] = useState<EntryCounts | null>(null)
320
320
  const [loading, setLoading] = useState(true)
321
+ const loadRequestRef = useRef(0)
322
+ const loadedQueryRef = useRef<string | null>(null)
323
+ // Track operations separately: overlapping writes to one entry must not
324
+ // remove each other's optimistic state when one request finishes.
325
+ const pendingPatchesRef = useRef(new Map<symbol, { id: string; patch: EntryPatch }>())
326
+ const applyPendingPatches = useCallback((rows: FormSubmission[]) => {
327
+ const patches = new Map<string, EntryPatch>()
328
+ for (const { id, patch } of pendingPatchesRef.current.values()) {
329
+ patches.set(id, { ...patches.get(id), ...patch })
330
+ }
331
+ return rows.map((entry) => {
332
+ const patch = patches.get(entry.id)
333
+ return patch ? { ...entry, ...patch } : entry
334
+ })
335
+ }, [])
321
336
  const [error, setError] = useState<string | null>(null)
322
337
  const [search, setSearch] = useState('')
323
338
  const [filter, setFilter] = useState<InboxFilter>(initial.filter)
@@ -590,45 +605,61 @@ export function EntriesInbox({
590
605
  [formId, onNavigate],
591
606
  )
592
607
 
593
- const load = useCallback(async () => {
594
- setLoading(true)
595
- setError(null)
596
- const params = filterParams(filter, currentUserId)
597
- try {
598
- const collected: FormSubmission[] = []
599
- const seen = new Set<string>()
600
- let reported = 0
601
- for (let page = 1; page <= 5; page++) {
602
- const result = await fetchEntries({
603
- formId: scopedFormId,
604
- search: search.trim() || undefined,
605
- page,
606
- pageSize: PAGE_SIZE,
607
- sortBy: 'submittedAt',
608
- sortDirection: 'desc',
609
- ...params,
610
- })
611
- reported = result.total
612
- const fresh = result.entries.filter((entry) => !seen.has(entry.id))
613
- for (const entry of fresh) seen.add(entry.id)
614
- collected.push(...fresh)
615
- if (
616
- collected.length >= reported ||
617
- fresh.length === 0 ||
618
- result.entries.length < PAGE_SIZE
619
- ) {
620
- break
608
+ const load = useCallback(
609
+ async (background = false) => {
610
+ const request = ++loadRequestRef.current
611
+ const query = JSON.stringify([filter, scopedFormId, search.trim(), currentUserId])
612
+ // An event may supersede a foreground load. Until this query has a
613
+ // successful dataset, its failures must remain foreground errors.
614
+ const keepRows = background && loadedQueryRef.current === query
615
+ if (!keepRows) setLoading(true)
616
+ setError(null)
617
+ const params = filterParams(filter, currentUserId)
618
+ try {
619
+ const collected: FormSubmission[] = []
620
+ const seen = new Set<string>()
621
+ let reported = 0
622
+ for (let page = 1; page <= 5; page++) {
623
+ const result = await fetchEntries({
624
+ formId: scopedFormId,
625
+ search: search.trim() || undefined,
626
+ page,
627
+ pageSize: PAGE_SIZE,
628
+ sortBy: 'submittedAt',
629
+ sortDirection: 'desc',
630
+ ...params,
631
+ })
632
+ if (request !== loadRequestRef.current) return
633
+ reported = result.total
634
+ const fresh = result.entries.filter((entry) => !seen.has(entry.id))
635
+ for (const entry of fresh) seen.add(entry.id)
636
+ collected.push(...fresh)
637
+ if (
638
+ collected.length >= reported ||
639
+ fresh.length === 0 ||
640
+ result.entries.length < PAGE_SIZE
641
+ ) {
642
+ break
643
+ }
621
644
  }
645
+ if (request !== loadRequestRef.current) return
646
+ setEntries(applyPendingPatches(collected))
647
+ loadedQueryRef.current = query
648
+ setTotal(reported)
649
+ setChecked((current) =>
650
+ keepRows ? new Set([...current].filter((id) => seen.has(id))) : new Set(),
651
+ )
652
+ } catch (err) {
653
+ if (request !== loadRequestRef.current) return
654
+ const message = err instanceof Error ? err.message : 'Failed to load entries'
655
+ if (keepRows) toast.error(message)
656
+ else setError(message)
657
+ } finally {
658
+ if (request === loadRequestRef.current) setLoading(false)
622
659
  }
623
- setEntries(collected)
624
- setTotal(reported)
625
- setChecked(new Set())
626
- } catch (err) {
627
- setError(err instanceof Error ? err.message : 'Failed to load entries')
628
- } finally {
629
- setLoading(false)
630
- }
631
- }, [filter, scopedFormId, search, currentUserId])
660
+ },
661
+ [filter, scopedFormId, search, currentUserId, applyPendingPatches],
662
+ )
632
663
 
633
664
  const loadCounts = useCallback(() => {
634
665
  void fetchEntryCounts({
@@ -639,9 +670,14 @@ export function EntriesInbox({
639
670
  .catch(() => {})
640
671
  }, [scopedFormId, currentUserId])
641
672
 
673
+ const cancelLoad = useCallback(() => {
674
+ loadRequestRef.current++
675
+ }, [])
676
+
642
677
  useEffect(() => {
643
678
  void load()
644
- }, [load])
679
+ return cancelLoad
680
+ }, [load, cancelLoad])
645
681
 
646
682
  useEffect(() => {
647
683
  loadCounts()
@@ -650,7 +686,8 @@ export function EntriesInbox({
650
686
  useEffect(
651
687
  () =>
652
688
  onFormsChanged(() => {
653
- void load()
689
+ // Read/star updates must not unmount rows or reset the inbox scroll position.
690
+ void load(true)
654
691
  loadCounts()
655
692
  }),
656
693
  [load, loadCounts],
@@ -754,6 +791,47 @@ export function EntriesInbox({
754
791
  writeQuery(filter, next)
755
792
  }
756
793
 
794
+ const entryWriteQueue = useRef(
795
+ new Map<string, Promise<Awaited<ReturnType<typeof updateEntry>>>>(),
796
+ )
797
+ const persistEntryPatch = useCallback(
798
+ (id: string, patch: EntryPatch) => {
799
+ const operation = Symbol()
800
+ pendingPatchesRef.current.set(operation, { id, patch })
801
+ setEntries((current) => applyPendingPatches(current))
802
+ // Serialize writes to one entry so the server and UI both retain click
803
+ // order. Other entries can still save independently.
804
+ const previous = entryWriteQueue.current.get(id) ?? Promise.resolve()
805
+ const queued = previous
806
+ .catch(() => undefined)
807
+ .then(async () => {
808
+ let result: Awaited<ReturnType<typeof updateEntry>>
809
+ try {
810
+ result = await updateEntry(id, patch)
811
+ } catch (error) {
812
+ result = { error: error instanceof Error ? error.message : 'Failed to update entry' }
813
+ }
814
+ pendingPatchesRef.current.delete(operation)
815
+ if (result.data) {
816
+ setEntries((current) =>
817
+ applyPendingPatches(
818
+ current.map((entry) =>
819
+ entry.id === id ? { ...entry, ...result.data, ...patch } : entry,
820
+ ),
821
+ ),
822
+ )
823
+ }
824
+ return result
825
+ })
826
+ .finally(() => {
827
+ if (entryWriteQueue.current.get(id) === queued) entryWriteQueue.current.delete(id)
828
+ })
829
+ entryWriteQueue.current.set(id, queued)
830
+ return queued
831
+ },
832
+ [applyPendingPatches],
833
+ )
834
+
757
835
  const patchOne = useCallback(
758
836
  async (
759
837
  id: string,
@@ -763,34 +841,23 @@ export function EntriesInbox({
763
841
  clearSelectionOnApply?: boolean,
764
842
  ) => {
765
843
  const prevActive = activeId
766
- setEntries((current) =>
767
- current.map((entry) => (entry.id === id ? { ...entry, ...patch } : entry)),
768
- )
769
844
  if (clearSelectionOnApply && activeId === id) setActiveId(null)
770
- const res = await updateEntry(id, patch)
845
+ const res = await persistEntryPatch(id, patch)
771
846
  if (res.error) {
772
847
  toast.error(res.error)
773
848
  void load()
774
849
  return
775
850
  }
776
- if (res.data) {
777
- setEntries((current) =>
778
- current.map((entry) => (entry.id === id ? { ...entry, ...res.data, ...patch } : entry)),
779
- )
780
- }
781
851
  if (message) {
782
852
  if (undoPatch) {
783
853
  showUndoToast(message, () => {
784
854
  void (async () => {
785
- const undoRes = await updateEntry(id, undoPatch)
855
+ const undoRes = await persistEntryPatch(id, undoPatch)
786
856
  if (undoRes.error) {
787
857
  toast.error(undoRes.error)
788
858
  void load()
789
859
  return
790
860
  }
791
- setEntries((current) =>
792
- current.map((entry) => (entry.id === id ? { ...entry, ...undoPatch } : entry)),
793
- )
794
861
  setActiveId(prevActive)
795
862
  showUndoToast('Undone')
796
863
  emitFormsChanged()
@@ -802,7 +869,7 @@ export function EntriesInbox({
802
869
  }
803
870
  emitFormsChanged()
804
871
  },
805
- [activeId, load, showUndoToast],
872
+ [activeId, load, showUndoToast, persistEntryPatch],
806
873
  )
807
874
 
808
875
  const handleTrashOrDelete = useCallback(