Files
crewli-old/apps/app/src/composables/api/useFormFailures.ts
bert.hausmans 192353f4bc feat(form-builder): admin UI completion — server filters, KPIs, resource expansion (WS-6 sessie 3c)
Closes the four production gaps that emerged from sessie 3b's admin UI.
What we ship here is final: no further rework planned before production.

Backend
- IndexFailuresRequest validates state/search/failed_at_from/failed_at_to/
  listener_class. orgIndex + platformIndex apply them via a single
  applyIndexFilters() helper. Search runs case-insensitive `LIKE` on
  exception_message; SQL wildcards in user input are escaped.
- New /kpis aggregate endpoint per scope (orgKpis, platformKpis) returns
  open / resolved_30d / dismissed_30d / total_submissions in O(1) COUNTs.
  Replaces sessie 3b's client-side bucketing of an oversized list.
- Resource expansion: organisation_name, form_schema_label,
  resolved_by_user_name, dismissed_by_user_name, exception_trace,
  retry_history[]. Eager-loading via indexEagerLoads()/detailEagerLoads()
  prevents N+1 (verified by query-count assertion in test).
- New 2026_04_28_181000 migration adds exception_trace (longtext nullable)
  to form_submission_action_failures. ApplyBindingsOnFormSubmit listener
  now captures $e->getTraceAsString() at failure time.
- New FormSubmissionActionFailureRetryAttemptResource exposes per-attempt
  data (timestamp, actor name, outcome, exception details) inside
  retry_history[]. Index payloads omit the field via whenLoaded() to keep
  list responses lean.

Frontend (apps/app)
- Types updated to mirror the expanded resource shape and the new KPI
  endpoint contract. FormFailuresKpis is now { open, resolved_30d,
  dismissed_30d, total_submissions } (server-aggregate).
- useFormFailures composable forwards all 5 server filters via
  buildIndexParams() (strips empty/whitespace). useFormFailuresKpis hits
  the dedicated /kpis endpoint per scope.
- FormFailuresTable replaces client-side bucketing with server-side
  filtering, adds listener_class + date-range filter inputs, and renames
  the 4th KPI tile to "Submissions" (was "Totaal").
- FormFailureDetail renders organisation_name + form_schema_label in the
  header, surfaces an expandable stack-trace card, names the resolved/
  dismissed actor in the timeline, and replaces the "v1 placeholder"
  retry-history card with a full per-attempt timeline.

ESLint config gap (apps/app)
- New .eslintrc.cjs adapted from the Vuexy reference, minus Vuexy-internal
  rules. `pnpm lint` now runs successfully (was previously broken — the
  package.json script referenced a missing config). The 80 baseline
  violations across the codebase are pre-existing and out of scope for
  this session.

Tests + gates
- 24 new backend tests across filter, kpis, and resource-shape suites.
  Backend: 1462 → 1486 passing, 0 → 0 failing. Larastan clean. Rector
  dry-run unchanged at 354 (pre-Task-1 baseline from f18b55b).
- 3 new vitest tests in apps/app (filter wiring, KPI endpoint, KPI tile
  values from /kpis). Vitest: 38 → 41 passing. tsc clean. Portal
  unchanged (113 vitest, tsc clean).
- 5 backfill rollback tests bumped --step counts +1 for the new migration.
- Ws6FoundationMigrationTest down/up chain now includes exception_trace
  before the parent table is restored.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-29 00:14:20 +02:00

211 lines
6.7 KiB
TypeScript

import { useMutation, useQuery, useQueryClient } from '@tanstack/vue-query'
import type { MaybeRef } from 'vue'
import { computed, unref } from 'vue'
import { apiClient } from '@/lib/axios'
import type {
DismissFailurePayload,
FormFailure,
FormFailuresKpis,
FormFailuresListParams,
ResolveFailurePayload,
} from '@/types/form-failures'
/**
* TanStack Vue Query composables for the FormSubmissionActionFailure
* admin endpoints.
*
* Routes (matching api/routes/api.php):
* - Platform (super_admin): /api/v1/admin/form-failures
* - Org (org_admin): /api/v1/organisations/{org}/form-failures
*
* Both scopes share the same controller methods + resource shape; the
* scope argument selects the URL prefix and the cache key family. The
* org-scope variant additionally requires `orgId`.
*
* Sessie 3c — index now accepts server-side filters (state/search/
* failed_at_from/failed_at_to/listener_class) and a separate `/kpis`
* endpoint replaces the client-side bucketing of an oversized list.
*/
interface PaginatedResponse<T> {
data: T[]
links: Record<string, string | null>
meta: {
current_page: number
per_page: number
total: number
last_page: number
}
}
interface SingleResponse<T> {
data: T
}
export type FormFailureScope = 'platform' | 'org'
function basePath(scope: FormFailureScope, orgId?: MaybeRef<string | undefined>): string {
if (scope === 'platform')
return '/admin/form-failures'
const id = unref(orgId)
if (!id)
throw new Error('useFormFailures: org scope requires orgId')
return `/organisations/${id}/form-failures`
}
function listKey(scope: FormFailureScope, orgId: MaybeRef<string | undefined>, params: MaybeRef<FormFailuresListParams>): unknown[] {
return ['form-failures', scope, unref(orgId) ?? null, unref(params)]
}
/**
* Strip empty/undefined keys so the URL stays clean and the React Query
* key family doesn't fragment over stable (vs. dirty) inputs.
*/
function buildIndexParams(p: FormFailuresListParams): Record<string, string | number> {
const out: Record<string, string | number> = {}
if (p.page !== undefined)
out.page = p.page
if (p.per_page !== undefined)
out.per_page = p.per_page
if (p.state !== undefined && p.state !== null)
out.state = p.state
if (p.listener_class && p.listener_class.trim() !== '')
out.listener_class = p.listener_class
if (p.failed_at_from && p.failed_at_from.trim() !== '')
out.failed_at_from = p.failed_at_from
if (p.failed_at_to && p.failed_at_to.trim() !== '')
out.failed_at_to = p.failed_at_to
if (p.search && p.search.trim() !== '')
out.search = p.search.trim()
return out
}
export function useFormFailures(
params: MaybeRef<FormFailuresListParams>,
scope: FormFailureScope,
orgId?: MaybeRef<string | undefined>,
) {
return useQuery({
queryKey: computed(() => listKey(scope, orgId, params)),
queryFn: async () => {
const p = unref(params)
const { data } = await apiClient.get<PaginatedResponse<FormFailure>>(basePath(scope, orgId), {
params: buildIndexParams(p),
})
return data
},
enabled: () => scope === 'platform' || !!unref(orgId),
})
}
/**
* Server-side KPI aggregate. Single COUNT-per-metric query — independent
* of tenant volume. Replaces sessie 3b's client-side bucketing.
*/
export function useFormFailuresKpis(scope: FormFailureScope, orgId?: MaybeRef<string | undefined>) {
return useQuery({
queryKey: ['form-failures-kpis', scope, computed(() => unref(orgId) ?? null)],
queryFn: async (): Promise<FormFailuresKpis> => {
const { data } = await apiClient.get<SingleResponse<FormFailuresKpis>>(
`${basePath(scope, orgId)}/kpis`,
)
return data.data
},
enabled: () => scope === 'platform' || !!unref(orgId),
})
}
export function useFormFailure(
failureId: MaybeRef<string>,
scope: FormFailureScope,
orgId?: MaybeRef<string | undefined>,
) {
return useQuery({
queryKey: computed(() => ['form-failure', scope, unref(orgId) ?? null, unref(failureId)]),
queryFn: async () => {
const { data } = await apiClient.get<SingleResponse<FormFailure>>(
`${basePath(scope, orgId)}/${unref(failureId)}`,
)
return data.data
},
enabled: () => !!unref(failureId) && (scope === 'platform' || !!unref(orgId)),
})
}
function invalidateFamily(qc: ReturnType<typeof useQueryClient>, scope: FormFailureScope, orgId?: MaybeRef<string | undefined>): void {
qc.invalidateQueries({ queryKey: ['form-failures', scope] })
qc.invalidateQueries({ queryKey: ['form-failures-kpis', scope] })
qc.invalidateQueries({ queryKey: ['form-failure', scope] })
// Pipeline retry succeeds → submission state may also change.
qc.invalidateQueries({ queryKey: ['form-submissions'] })
// Touch orgId to silence "unused" lint when scope === 'platform'.
void unref(orgId)
}
export function useRetryFailure(scope: FormFailureScope, orgId?: MaybeRef<string | undefined>) {
const qc = useQueryClient()
return useMutation({
mutationFn: async (failureId: string) => {
const { data } = await apiClient.post<SingleResponse<FormFailure>>(
`${basePath(scope, orgId)}/${failureId}/retry`,
)
return data.data
},
onSuccess: () => invalidateFamily(qc, scope, orgId),
})
}
export function useResolveFailure(scope: FormFailureScope, orgId?: MaybeRef<string | undefined>) {
const qc = useQueryClient()
return useMutation({
mutationFn: async ({ failureId, payload }: { failureId: string; payload: ResolveFailurePayload }) => {
// Omit `note` from the body when empty/undefined — the backend
// FormRequest treats an absent key and a null value identically,
// but keeping the payload tight avoids audit-log noise.
const body: Record<string, string> = {}
if (payload.note && payload.note.trim() !== '')
body.note = payload.note.trim()
const { data } = await apiClient.post<SingleResponse<FormFailure>>(
`${basePath(scope, orgId)}/${failureId}/resolve`,
body,
)
return data.data
},
onSuccess: () => invalidateFamily(qc, scope, orgId),
})
}
export function useDismissFailure(scope: FormFailureScope, orgId?: MaybeRef<string | undefined>) {
const qc = useQueryClient()
return useMutation({
mutationFn: async ({ failureId, payload }: { failureId: string; payload: DismissFailurePayload }) => {
const body: Record<string, string> = { reason_type: payload.reason_type }
if (payload.note && payload.note.trim() !== '')
body.note = payload.note.trim()
const { data } = await apiClient.post<SingleResponse<FormFailure>>(
`${basePath(scope, orgId)}/${failureId}/dismiss`,
body,
)
return data.data
},
onSuccess: () => invalidateFamily(qc, scope, orgId),
})
}