All files / src/features/legal/api legal.hooks.ts

84.61% Statements 11/13
100% Branches 4/4
77.77% Functions 7/9
81.81% Lines 9/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61              7x                       30x                       11x   4x   8x 7x           11x                   11x   11x            
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
 
import { LEGAL_DOCUMENTS, type LegalDocument, type LegalDocumentId } from '@/shared/legal'
 
import { fetchLegalAcceptances, recordLegalAcceptance } from './legal.api'
import type { LegalAcceptance } from './legal.schemas'
 
export const legalAcceptancesQueryKey = ['legal', 'acceptances'] as const
 
/**
 * The documents that are actually in force right now.
 *
 * While every document is a draft this is empty, and that emptiness is what
 * makes the whole gate inert: no request goes out, nothing is asked, nothing
 * blocks. Asking someone to accept a draft would be asking them to agree to
 * text nobody has stood behind — the API could record it, but recording a
 * consent that means nothing is worse than having none.
 */
export function documentsInForce(): LegalDocument[] {
  return Object.values(LEGAL_DOCUMENTS).filter((document) => document.status === 'in-force')
}
 
/**
 * Of the in-force documents, the ones this user has not accepted **at the
 * current version**.
 *
 * Version-aware on purpose: an acceptance of 1.0.0 does not satisfy 2.0.0. That
 * is the same rule the API enforces on its unique key, and it is what makes a
 * text change re-ask rather than silently inherit an old agreement.
 */
export function documentsAwaitingAcceptance(acceptances: LegalAcceptance[] | undefined): LegalDocument[] {
  if (!acceptances) return []
 
  return documentsInForce().filter(
    (document) =>
      !acceptances.some(
        (acceptance) => acceptance.documentId === document.id && acceptance.version === document.version,
      ),
  )
}
 
export function useLegalAcceptances() {
  return useQuery({
    queryKey: legalAcceptancesQueryKey,
    queryFn: fetchLegalAcceptances,
    // No document in force means there is nothing this answer could change, so
    // the request is not made at all.
    enabled: documentsInForce().length > 0,
  })
}
 
export function useRecordLegalAcceptance() {
  const queryClient = useQueryClient()
 
  return useMutation({
    mutationFn: (documentId: LegalDocumentId) =>
      recordLegalAcceptance({ documentId, version: LEGAL_DOCUMENTS[documentId].version }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: legalAcceptancesQueryKey }),
  })
}