"use client"; /** * Settings → Integrations → Document archives (#1038): connect Paperless-ngx or * Papra so the document picker can search it. * * Renders nothing unless the operator listed at least one origin in * `DOCUMENT_SOURCE_ORIGINS`, the documents module is on, and the person is in * their own record: a delegate never manages the owner's connection, and a * card that can only be refused advertises a feature that is not there. * * One form per system behind a switch. Save tests the connection before it is * stored and says why when it fails; the token field never shows the stored * token (the server never returns it), only that one is saved, and leaving it * empty keeps it. Results sit above the action row; nothing follows it * (UI standards §12). */ import { useMutation, useQueryClient } from "@tanstack/react-query"; import { Archive, Check, Loader2, Unlink } from "lucide-react"; import { useState } from "react"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger, } from "@/components/ui/alert-dialog"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { PasswordInput } from "@/components/ui/password-input"; import { SettingsCardActions } from "@/components/settings/_card-actions"; import { SettingsCardHeader } from "@/components/settings/_card-header"; import { SettingsCard } from "@/components/settings/settings-card"; import { WrittenOutcomeLine } from "@/components/outcome/written-outcome-line"; import { errorCodeOf, sourceErrorMessage, } from "@/components/documents/sources/source-errors"; import { systemName, useDocumentSourcesStatus, } from "@/components/documents/sources/use-document-sources"; import { apiDelete, apiPost, apiPut } from "@/lib/api/api-fetch"; import { DOCUMENT_PICKER_SYSTEMS, slugForSystem, type DocumentPickerSystem, type DocumentSourceConnectionDto, } from "@/lib/documents/sources/types"; import { useFormatters, useTranslations } from "@/lib/i18n/context"; import { invalidateKeys, queryKeys } from "@/lib/query-keys"; import { cn } from "@/lib/utils"; type Outcome = { tone: "success" | "error"; message: string } | null; export function DocumentSourcesCard() { const { t } = useTranslations(); const { eligible, query } = useDocumentSourcesStatus(); const [system, setSystem] = useState("PAPERLESS"); if (!eligible || !query.data?.available) return null; const connections = query.data.connections; const connectedCount = connections.length; return ( 0 ? ( {t("settings.documentSources.statusConnected")} ) : null } />

{t("settings.documentSources.explainer")}

{DOCUMENT_PICKER_SYSTEMS.map((option) => { const isConnected = connections.some((c) => c.system === option); return ( ); })}
c.system === system) ?? null} allowedOrigins={query.data.allowedOrigins} />
); } function SourceForm({ system, connection, allowedOrigins, }: { system: DocumentPickerSystem; connection: DocumentSourceConnectionDto | null; allowedOrigins: string[]; }) { const { t } = useTranslations(); const format = useFormatters(); const queryClient = useQueryClient(); const slug = slugForSystem(system); const isPapra = system === "PAPRA"; const [baseUrl, setBaseUrl] = useState(connection?.baseUrl ?? ""); const [organizationId, setOrganizationId] = useState( connection?.organizationId ?? "", ); const [token, setToken] = useState(""); const [outcome, setOutcome] = useState(null); const dirty = baseUrl.trim() !== (connection?.baseUrl ?? "") || (isPapra && organizationId.trim() !== (connection?.organizationId ?? "")) || token.trim() !== ""; const refresh = () => invalidateKeys(queryClient, [queryKeys.documentSources()]); const save = useMutation({ mutationFn: () => apiPut(`/api/documents/sources/${slug}`, { baseUrl: baseUrl.trim(), ...(isPapra ? { organizationId: organizationId.trim() } : {}), ...(token.trim() ? { token: token.trim() } : {}), }), onMutate: () => setOutcome(null), onSuccess: () => { setToken(""); setOutcome({ tone: "success", message: t("settings.documentSources.saved"), }); void refresh(); }, onError: (err) => setOutcome({ tone: "error", message: sourceErrorMessage(t, errorCodeOf(err)), }), }); const test = useMutation({ mutationFn: () => apiPost<{ ok: true; latencyMs: number }>( `/api/documents/sources/${slug}/test`, ), onMutate: () => setOutcome(null), onSuccess: (data) => { setOutcome({ tone: "success", message: t("settings.documentSources.testOk", { latency: data.latencyMs, }), }); void refresh(); }, onError: (err) => setOutcome({ tone: "error", message: sourceErrorMessage(t, errorCodeOf(err)), }), }); const disconnect = useMutation({ mutationFn: () => apiDelete(`/api/documents/sources/${slug}`), onSuccess: () => { setBaseUrl(""); setOrganizationId(""); setToken(""); setOutcome(null); void refresh(); }, onError: (err) => setOutcome({ tone: "error", message: sourceErrorMessage(t, errorCodeOf(err)), }), }); const busy = save.isPending || test.isPending || disconnect.isPending; const canSave = baseUrl.trim() !== "" && (!isPapra || organizationId.trim() !== "") && (connection !== null || token.trim() !== "") && dirty; return (
{ e.preventDefault(); if (canSave && !busy) save.mutate(); }} data-slot="document-sources-form" >

{connection ? connection.lastVerifiedAt ? t("settings.documentSources.connectedSince", { date: format.date(connection.lastVerifiedAt), }) : t("settings.documentSources.statusConnected") : t("settings.documentSources.statusNotConnected")}

{connection && !connection.originAllowed ? (

{t("settings.documentSources.originRemoved")}

) : null}
setBaseUrl(e.target.value)} placeholder={allowedOrigins[0] ?? "https://"} maxLength={2048} autoComplete="off" inputMode="url" spellCheck={false} autoCapitalize="none" />

{t("settings.documentSources.allowedOrigins", { origins: allowedOrigins.join(", "), })}

{isPapra ? (
setOrganizationId(e.target.value)} maxLength={128} autoComplete="off" spellCheck={false} autoCapitalize="none" />

{t("settings.documentSources.organizationHelp")}

) : null}
setToken(e.target.value)} placeholder={ connection ? t("settings.documentSources.tokenSaved") : undefined } maxLength={512} autoComplete="off" spellCheck={false} autoCapitalize="none" />

{isPapra ? t("settings.documentSources.tokenHelpPapra") : t("settings.documentSources.tokenHelpPaperless")}

{outcome ? ( ) : null} {connection ? ( {t("settings.documentSources.disconnectTitle", { name: systemName(system), })} {t("settings.documentSources.disconnectDescription")} {t("common.cancel")} disconnect.mutate()}> {t("settings.documentSources.disconnect")} ) : null} {connection ? ( ) : null} ); }