document types

This commit is contained in:
2025-10-31 00:13:16 +01:00
parent 3941ec61d3
commit 813ce24aeb
19 changed files with 1714 additions and 43 deletions
+172
View File
@@ -37,6 +37,32 @@ const sortCorrespondents = (entries = []) =>
}))
.sort((a, b) => (a.name || '').localeCompare(b.name || ''));
const resolveDocumentType = (doc) => {
if (!doc) {
return null;
}
const type = doc.document_type;
const fallbackId = doc.document_type_id ?? null;
if (!type) {
return null;
}
if (typeof type === 'string') {
const name = type.trim();
if (!name) {
return null;
}
return { id: fallbackId, name };
}
if (typeof type === 'object') {
const name = (type.name || type.label || '').trim();
if (!name) {
return null;
}
return { id: type.id ?? fallbackId, name };
}
return null;
};
const CorrespondentPills = ({ entries = [], onRemove, showCount = false }) => (
<div className="correspondent-list">
{entries.length ? (
@@ -302,6 +328,11 @@ const DetailPanel = ({
correspondents = [],
onCorrespondentAdd,
onCorrespondentRemove,
documentTypes = [],
onDocumentTypeSet,
onDocumentTypeClear,
onBulkDocumentTypeSet,
onBulkDocumentTypeClear,
resolveApiPath,
onFolderNavigate = null,
resolveFolderPath = null,
@@ -590,6 +621,23 @@ const DetailPanel = ({
});
}, [availableCorrespondents]);
const documentTypeOptions = useMemo(() => {
const seen = new Set();
return (documentTypes || [])
.map((entry) => (entry?.name || '').trim())
.filter((name) => {
if (!name) return false;
const lower = name.toLowerCase();
if (seen.has(lower)) {
return false;
}
seen.add(lower);
return true;
});
}, [documentTypes]);
const singleDocumentType = useMemo(() => resolveDocumentType(singleDoc), [singleDoc]);
const singleCorrespondents = useMemo(() => {
if (!singleDoc) return [];
return sortCorrespondents(singleDoc.correspondents || []);
@@ -725,6 +773,42 @@ const DetailPanel = ({
.sort((a, b) => (a.name || '').localeCompare(b.name || ''));
}, [selectedDocuments]);
const bulkDocumentTypes = useMemo(() => {
if (!selectedDocuments.length) {
return [];
}
const map = new Map();
selectedDocuments.forEach((doc) => {
const type = resolveDocumentType(doc);
if (!type) return;
const key = type.id ?? type.name.toLowerCase();
if (!map.has(key)) {
map.set(key, { id: type.id ?? null, name: type.name, count: 0 });
}
map.get(key).count += 1;
});
return [...map.values()].sort((a, b) => (a.name || '').localeCompare(b.name || ''));
}, [selectedDocuments]);
const bulkDocumentTypeSummary = useMemo(() => {
if (!bulkDocumentTypes.length) {
return '';
}
return bulkDocumentTypes
.map((entry) => {
if (!entry?.name) {
return null;
}
const suffix = entry.count === selectedDocuments.length ? '' : ` (${entry.count})`;
return `${entry.name}${suffix}`;
})
.filter(Boolean)
.join(', ');
}, [bulkDocumentTypes, selectedDocuments.length]);
const handleBulkCorrespondentRemove = useCallback(
(entry) => {
if (!entry?.id) return;
@@ -1092,6 +1176,53 @@ const DetailPanel = ({
);
})}
</div>
<div className="detail-field">
<div className="detail-field__label">Document type</div>
<div className="detail-field__value">
{singleDocumentType?.name ? (
<span>{singleDocumentType.name}</span>
) : (
<span className="meta">None assigned.</span>
)}
{singleDocumentType && onDocumentTypeClear ? (
<button
type="button"
className="secondary"
onClick={() => onDocumentTypeClear?.({ documentId: singleDoc.id })}
>
Clear
</button>
) : null}
</div>
{onDocumentTypeSet ? (
<form
className="inline"
onSubmit={(event) => {
event.preventDefault();
const form = event.currentTarget;
const input = form.elements.documentType;
const value = input?.value?.trim();
if (!value) {
return;
}
onDocumentTypeSet?.({ document: singleDoc, name: value, input });
}}
>
<input
name="documentType"
placeholder="Assign or create type"
list="document-type-catalog-single"
defaultValue=""
/>
<button type="submit">Set</button>
<datalist id="document-type-catalog-single">
{documentTypeOptions.map((name) => (
<option key={name} value={name} />
))}
</datalist>
</form>
) : null}
</div>
<TagSection
title="Tags"
tags={tagsForDoc.map((tag) => ({
@@ -1216,6 +1347,47 @@ const DetailPanel = ({
datalistOptions={tags}
className="bulk-tags"
/>
<div className="detail-field">
<div className="detail-field__label">Document type</div>
<div className="detail-field__value">
<span>{bulkDocumentTypeSummary || 'None assigned.'}</span>
{onBulkDocumentTypeClear && bulkDocumentTypes.length > 0 ? (
<button
type="button"
className="secondary"
onClick={() => onBulkDocumentTypeClear?.({ documentIds })}
>
Clear
</button>
) : null}
</div>
{onBulkDocumentTypeSet ? (
<form
className="inline"
onSubmit={(event) => {
event.preventDefault();
const form = event.currentTarget;
const input = form.elements.documentType;
const value = input?.value?.trim();
if (!value) {
return;
}
onBulkDocumentTypeSet?.({ name: value, input, documentIds });
}}
>
<input
name="documentType"
placeholder="Assign or create type"
list="document-type-catalog-bulk"
defaultValue=""
/>
<button type="submit">Set</button>
<datalist id="document-type-catalog-bulk">
{documentTypeOptions.map((name) => (<option key={name} value={name} />))}
</datalist>
</form>
) : null}
</div>
<CorrespondentSection
title="Correspondents"
entries={bulkCorrespondents}
@@ -0,0 +1,233 @@
import React, { useCallback, useState } from 'react';
function DocumentTypesPanel({
documentTypes = [],
onRefresh,
onCreate,
onUpdate,
onDelete,
onNotify,
}) {
const [editingId, setEditingId] = useState(null);
const [draftName, setDraftName] = useState('');
const [createName, setCreateName] = useState('');
const [saving, setSaving] = useState(false);
const [creating, setCreating] = useState(false);
const [deletingId, setDeletingId] = useState(null);
const startEdit = useCallback((entry) => {
setEditingId(entry.id);
setDraftName(entry.name || '');
}, []);
const cancelEdit = useCallback(() => {
setEditingId(null);
setDraftName('');
setSaving(false);
}, []);
const handleSave = useCallback(async () => {
if (!editingId) return;
const trimmed = draftName.trim();
if (!trimmed) {
onNotify?.('Document type name cannot be empty.', 'error');
return;
}
setSaving(true);
try {
await onUpdate(editingId, { name: trimmed });
cancelEdit();
} catch (error) {
onNotify?.('Failed to update document type.', 'error');
console.error('[document-types] update failed', error);
setSaving(false);
}
}, [editingId, draftName, onUpdate, cancelEdit, onNotify]);
const handleDelete = useCallback(
async (entry) => {
if (!entry?.id) return;
setDeletingId(entry.id);
try {
await onDelete(entry.id);
if (editingId === entry.id) {
cancelEdit();
}
} catch (error) {
onNotify?.('Failed to delete document type.', 'error');
console.error('[document-types] delete failed', error);
} finally {
setDeletingId(null);
}
},
[onDelete, editingId, cancelEdit, onNotify],
);
const handleCreate = useCallback(
async (event) => {
event.preventDefault();
const trimmed = createName.trim();
if (!trimmed) {
onNotify?.('Document type name cannot be empty.', 'error');
return;
}
setCreating(true);
try {
await onCreate({ name: trimmed });
setCreateName('');
} catch (error) {
onNotify?.('Failed to create document type.', 'error');
console.error('[document-types] create failed', error);
} finally {
setCreating(false);
}
},
[createName, onCreate, onNotify],
);
const handleKeyDown = useCallback(
(event) => {
if (event.key === 'Enter') {
event.preventDefault();
handleSave();
} else if (event.key === 'Escape') {
event.preventDefault();
cancelEdit();
}
},
[handleSave, cancelEdit],
);
const renderUsage = useCallback((usage) => {
if (!usage) {
return '0';
}
const total = typeof usage.total === 'number' ? usage.total : 0;
return total.toString();
}, []);
return (
<section className="correspondents-panel">
<div className="panel-section__header">
<div className="panel-section__titles">
<h2>Document Types</h2>
<div className="panel-section__subtitle">{documentTypes.length} total</div>
</div>
<div className="header-actions correspondents-actions">
<form className="correspondents-actions__form" onSubmit={handleCreate}>
<input
type="text"
placeholder="New document type name"
value={createName}
onChange={(event) => setCreateName(event.target.value)}
disabled={creating}
/>
<button type="submit" disabled={creating || !createName.trim()}>
{creating ? 'Creating…' : 'Create'}
</button>
</form>
<button
className="secondary"
type="button"
onClick={onRefresh}
disabled={saving || creating || Boolean(deletingId)}
>
Refresh
</button>
</div>
</div>
<div className="panel-section__body tags-panel__body">
{documentTypes.length === 0 ? (
<div className="empty-state">No document types created yet.</div>
) : (
<div className="tags-table">
<table>
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col" className="numeric">
Usage
</th>
<th scope="col" className="actions">
Actions
</th>
</tr>
</thead>
<tbody>
{documentTypes.map((entry) => {
const isEditing = editingId === entry.id;
return (
<tr key={entry.id} className={isEditing ? 'editing' : ''}>
<td className="tags-table__label">
{isEditing ? (
<input
className="tags-table__label-input"
value={draftName}
onChange={(event) => setDraftName(event.target.value)}
onKeyDown={handleKeyDown}
disabled={saving}
autoFocus
/>
) : (
<span>{entry.name}</span>
)}
</td>
<td className="numeric">{renderUsage(entry.usage)}</td>
<td className="actions">
{isEditing ? (
<div className="tags-table__edit-controls">
<button
type="button"
className="secondary"
onClick={handleSave}
disabled={saving}
>
Save
</button>
<button
type="button"
className="secondary"
onClick={cancelEdit}
disabled={saving}
>
Cancel
</button>
</div>
) : (
<div className="tags-table__row-actions">
<button
type="button"
className="icon-button ghost"
onClick={() => startEdit(entry)}
title="Rename"
aria-label={`Rename document type ${entry.name}`}
>
Edit
</button>
<button
type="button"
className="icon-button danger"
onClick={() => handleDelete(entry)}
disabled={deletingId === entry.id}
title="Delete"
aria-label={`Delete document type ${entry.name}`}
>
Delete
</button>
</div>
)}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
</div>
</section>
);
}
export default DocumentTypesPanel;
+97
View File
@@ -56,6 +56,37 @@ const resolveCorrespondents = (doc) => {
return results;
};
const resolveDocumentType = (doc) => {
if (!doc) {
return null;
}
const type = doc.document_type;
const fallbackId = doc.document_type_id ?? null;
if (!type) {
return null;
}
if (typeof type === 'string') {
const name = type.trim();
if (!name) {
return null;
}
return { id: fallbackId, name };
}
if (typeof type === 'object') {
const name = (type.name || type.label || '').trim();
if (!name) {
return null;
}
return { id: type.id ?? fallbackId, name };
}
return null;
};
// Detects when an element becomes visible within a scroll container.
const useLazyVisibility = (rootRef, resetKey) => {
const targetRef = useRef(null);
@@ -231,6 +262,8 @@ const DocumentsTable = ({
getDownloadHref,
onTagClick,
onCorrespondentClick,
activeDocumentTypeIds = [],
onDocumentTypeClick,
isSearchLoading = false,
onDocumentTagDrop,
viewMode = 'list',
@@ -257,6 +290,10 @@ const DocumentsTable = ({
() => new Set(activeCorrespondentIds || []),
[activeCorrespondentIds],
);
const activeDocumentTypeIdSet = useMemo(
() => new Set(activeDocumentTypeIds || []),
[activeDocumentTypeIds],
);
const scrollRef = useRef(null);
const suppressDocumentClickRef = useRef(false);
const [, forceVisibilityTick] = useState(0);
@@ -628,6 +665,11 @@ const DocumentsTable = ({
const visibleTags = tagList.slice(0, 3);
const remainingTagCount = tagList.length > 3 ? tagList.length - 3 : 0;
const correspondents = resolveCorrespondents(doc);
const documentType = resolveDocumentType(doc);
const isDocumentTypeActive =
documentType?.id != null && activeDocumentTypeIdSet.has(documentType.id);
const canToggleDocumentType =
documentType?.id != null && typeof onDocumentTypeClick === 'function';
const cardClasses = ['document-card', 'document'];
if (isSelected) cardClasses.push('selected');
if (isDraggingDoc) cardClasses.push('is-dragging');
@@ -663,6 +705,32 @@ const DocumentsTable = ({
className="document-card__title"
title={doc.title || doc.original_name}
>
{documentType ? (
<span
className={`doc-type-label${
isDocumentTypeActive ? ' active' : ''
}`}
role={canToggleDocumentType ? 'button' : undefined}
tabIndex={canToggleDocumentType ? 0 : undefined}
onClick={(event) => {
event.stopPropagation();
if (canToggleDocumentType) {
onDocumentTypeClick?.(documentType.id, documentType);
}
}}
onKeyDown={(event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
event.stopPropagation();
if (canToggleDocumentType) {
onDocumentTypeClick?.(documentType.id, documentType);
}
}
}}
>
{documentType.name}
</span>
) : null}
{correspondents.length > 0 ? (
<span className="doc-correspondents">
{renderCorrespondentLinks(correspondents)}
@@ -854,6 +922,9 @@ const DocumentsTable = ({
if (isDraggingDoc) rowClasses.push('is-dragging');
const downloadHref = getDownloadHref?.(doc) || null;
const correspondents = resolveCorrespondents(doc);
const documentType = resolveDocumentType(doc);
const isRowDocumentTypeActive = documentType?.id != null && activeDocumentTypeIdSet.has(documentType.id);
const canToggleRowDocumentType = documentType?.id != null && typeof onDocumentTypeClick === 'function';
return (
<tr
@@ -883,6 +954,32 @@ const DocumentsTable = ({
<div className="doc-name">
<div className="doc-list__name-content">
<span className="doc-name__title">
{documentType ? (
<span
className={`doc-type-label${
isRowDocumentTypeActive ? ' active' : ''
}`}
role={canToggleRowDocumentType ? 'button' : undefined}
tabIndex={canToggleRowDocumentType ? 0 : undefined}
onClick={(event) => {
event.stopPropagation();
if (canToggleRowDocumentType) {
onDocumentTypeClick?.(documentType.id, documentType);
}
}}
onKeyDown={(event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
event.stopPropagation();
if (canToggleRowDocumentType) {
onDocumentTypeClick?.(documentType.id, documentType);
}
}
}}
>
{documentType.name}
</span>
) : null}
{correspondents.length > 0 ? (
<span className="doc-correspondents">
{renderCorrespondentLinks(correspondents)}
+489 -36
View File
@@ -27,6 +27,7 @@ import AssetManager, { getAssetFromVersion, resolveDocumentAssetUrl, createAsset
import useApiError from './hooks/useApiError';
import TagsPanel from './tags/TagsPanel';
import CorrespondentsPanel from './correspondents/CorrespondentsPanel';
import DocumentTypesPanel from './documentTypes/DocumentTypesPanel';
import TagManager from './tag_manager';
import Sidebar from './sidebar/Sidebar';
import SettingsModal from './settings/SettingsModal';
@@ -442,6 +443,7 @@ const AppLayout = () => {
const [loading, setLoading] = useState(false);
const [isTagsModalOpen, setTagsModalOpen] = useState(false);
const [isCorrespondentsModalOpen, setCorrespondentsModalOpen] = useState(false);
const [isDocumentTypesModalOpen, setDocumentTypesModalOpen] = useState(false);
const [isSettingsModalOpen, setSettingsModalOpen] = useState(false);
const [creatingFolder, setCreatingFolder] = useState(false);
const [folderNodes, setFolderNodes] = useState(() => {
@@ -531,6 +533,7 @@ const AppLayout = () => {
const previewInflightRef = useRef(new Map());
const [tags, setTags] = useState([]);
const [correspondents, setCorrespondents] = useState([]);
const [documentTypes, setDocumentTypes] = useState([]);
const [webdavTokens, setWebdavTokens] = useState([]);
const [webdavTokensLoading, setWebdavTokensLoading] = useState(false);
const [creatingWebdavToken, setCreatingWebdavToken] = useState(false);
@@ -539,6 +542,7 @@ const AppLayout = () => {
const [searchQuery, setSearchQuery] = useState('');
const [activeTagFilters, setActiveTagFilters] = useState([]);
const [activeCorrespondentFilters, setActiveCorrespondentFilters] = useState([]);
const [activeDocumentTypeFilters, setActiveDocumentTypeFilters] = useState([]);
const [searchLoading, setSearchLoading] = useState(false);
const documentsRouteMatch = useMatch('/documents');
const documentsFolderRouteMatch = useMatch('/documents/folder/:folderId');
@@ -564,6 +568,15 @@ const AppLayout = () => {
});
}, []);
const toggleDocumentTypeFilter = useCallback((documentTypeId) => {
setActiveDocumentTypeFilters((previous) => {
if (!documentTypeId) {
return [];
}
return previous.includes(documentTypeId) ? [] : [documentTypeId];
});
}, []);
const initialRefreshAttemptedRef = useRef(Boolean(token));
useEffect(() => {
@@ -599,6 +612,7 @@ const AppLayout = () => {
setSearchQuery('');
setActiveTagFilters([]);
setActiveCorrespondentFilters([]);
setActiveDocumentTypeFilters([]);
setSearchLoading(false);
}, []);
@@ -628,6 +642,17 @@ const AppLayout = () => {
}
const assetManager = assetManagerRef.current;
const extractDocumentFromResponse = useCallback(
(payload) => {
if (!payload) {
return null;
}
const hydratedDetail = assetManager.hydrateDetail(payload);
return hydratedDetail?.document || payload.document || payload;
},
[assetManager],
);
const tagManagerRef = useRef(null);
if (!tagManagerRef.current) {
tagManagerRef.current = new TagManager();
@@ -692,6 +717,7 @@ const AppLayout = () => {
setSearchResults(null);
setTags([]);
setCorrespondents([]);
setDocumentTypes([]);
setWebdavTokens([]);
setWebdavTokensLoading(false);
setCreatingWebdavToken(false);
@@ -699,6 +725,8 @@ const AppLayout = () => {
setWebdavTokenSecret(null);
setSearchQuery('');
setActiveTagFilters([]);
setActiveCorrespondentFilters([]);
setActiveDocumentTypeFilters([]);
setDropOverlayState({ active: false, folderName: DEFAULT_FOLDER_NAME });
setActivePreviewId(null);
setDetailPanelOpen(false);
@@ -735,6 +763,26 @@ const AppLayout = () => {
return map;
}, [correspondents]);
const documentTypeLookupByName = useMemo(() => {
const map = new Map();
documentTypes.forEach((entry) => {
if (entry?.name) {
map.set(entry.name.toLowerCase(), entry);
}
});
return map;
}, [documentTypes]);
const documentTypeLookupById = useMemo(() => {
const map = new Map();
documentTypes.forEach((entry) => {
if (entry?.id) {
map.set(entry.id, entry);
}
});
return map;
}, [documentTypes]);
const updateSelectionOrder = useCallback((nextSelection, interactedKeys = []) => {
const nextSet = new Set(nextSelection);
const previousOrder = selectionOrderRef.current.filter((id) => nextSet.has(id));
@@ -870,8 +918,9 @@ const AppLayout = () => {
() =>
searchQuery.trim().length > 0 ||
activeTagFilters.length > 0 ||
activeCorrespondentFilters.length > 0,
[searchQuery, activeTagFilters, activeCorrespondentFilters],
activeCorrespondentFilters.length > 0 ||
activeDocumentTypeFilters.length > 0,
[searchQuery, activeTagFilters, activeCorrespondentFilters, activeDocumentTypeFilters],
);
const applySelectedFolder = useCallback(
@@ -1696,6 +1745,22 @@ const AppLayout = () => {
}
}, [notifyApiError]);
const refreshDocumentTypes = useCallback(async () => {
const requestTenantId = tenantIdRef.current;
try {
const { data } = await api.get('/document-types');
if (tenantIdRef.current !== requestTenantId) {
return;
}
setDocumentTypes(data || []);
} catch (error) {
if (tenantIdRef.current !== requestTenantId) {
return;
}
notifyApiError(error, 'Unable to load document types.');
}
}, [notifyApiError]);
const refreshWebdavTokens = useCallback(async () => {
if (!token) {
return;
@@ -2049,6 +2114,308 @@ const AppLayout = () => {
],
);
const handleDocumentTypeUpdate = useCallback(
async (documentTypeId, changes) => {
if (!documentTypeId) {
throw new Error('Missing document type identifier.');
}
const payload = {};
if (typeof changes.name === 'string') {
const trimmed = changes.name.trim();
if (!trimmed) {
throw new Error('Document type name cannot be empty.');
}
payload.name = trimmed;
}
if (Object.keys(payload).length === 0) {
return false;
}
try {
await api.patch(`/document-types/${documentTypeId}`, payload);
await refreshDocumentTypes();
setStatusMessage('Document type updated.', 'success');
return true;
} catch (error) {
const message = error.response?.data?.error || 'Failed to update document type.';
notifyApiError(error, message);
throw new Error(message);
}
},
[refreshDocumentTypes, notifyApiError, setStatusMessage],
);
const handleDocumentTypeCreate = useCallback(
async ({ name }) => {
const trimmed = (name || '').trim();
if (!trimmed) {
throw new Error('Document type name is required.');
}
try {
const { data } = await api.post('/document-types', { name: trimmed });
await refreshDocumentTypes();
setStatusMessage('Document type created.', 'success');
return data;
} catch (error) {
const message = error.response?.data?.error || 'Failed to create document type.';
notifyApiError(error, message);
throw new Error(message);
}
},
[refreshDocumentTypes, notifyApiError, setStatusMessage],
);
const handleDocumentTypeDelete = useCallback(
async (documentTypeId) => {
if (!documentTypeId) {
throw new Error('Missing document type identifier.');
}
const deletedEntry = documentTypeLookupById.get(documentTypeId);
try {
await api.delete(`/document-types/${documentTypeId}`);
mapDocumentCaches((doc) => {
if (!doc) {
return doc;
}
const existingType = doc.document_type;
const existingTypeId =
doc.document_type_id ?? (typeof existingType === 'object' ? existingType?.id : null);
const existingTypeName =
typeof existingType === 'string'
? existingType
: existingType?.name || existingType?.label || '';
const shouldClear =
existingTypeId === documentTypeId ||
(!!deletedEntry?.name &&
existingTypeName &&
existingTypeName.toLowerCase() === deletedEntry.name.toLowerCase());
if (!shouldClear) {
return doc;
}
return { ...doc, document_type: null, document_type_id: null };
});
await refreshDocumentTypes();
setStatusMessage('Document type deleted.', 'success');
return true;
} catch (error) {
const message = error.response?.data?.error || 'Failed to delete document type.';
notifyApiError(error, message);
throw new Error(message);
}
},
[
refreshDocumentTypes,
notifyApiError,
setStatusMessage,
mapDocumentCaches,
documentTypeLookupById,
],
);
const handleDocumentTypeAssign = useCallback(
async ({ documentId, documentTypeId }, { notify = true } = {}) => {
if (!documentId) {
throw new Error('Missing document identifier.');
}
try {
const payload = { document_type_id: documentTypeId ?? null };
const { data } = await api.patch(`/documents/${documentId}`, payload);
const updatedDocument = extractDocumentFromResponse(data);
updateDocumentCaches(documentId, (doc) => {
if (updatedDocument) {
return { ...doc, ...updatedDocument };
}
const next = { ...doc };
if (documentTypeId) {
const entry = documentTypeLookupById.get(documentTypeId);
next.document_type = entry || { id: documentTypeId, name: entry?.name || '' };
} else {
next.document_type = null;
}
next.document_type_id = documentTypeId ?? null;
return next;
});
if (notify) {
setStatusMessage(
documentTypeId ? 'Document type updated.' : 'Document type cleared.',
'success',
);
}
return true;
} catch (error) {
const message = error.response?.data?.error || 'Failed to update document type.';
notifyApiError(error, message);
return false;
}
},
[
extractDocumentFromResponse,
updateDocumentCaches,
documentTypeLookupById,
notifyApiError,
setStatusMessage,
],
);
const handleDocumentTypeClear = useCallback(
async ({ documentId }, options = {}) =>
handleDocumentTypeAssign({ documentId, documentTypeId: null }, options),
[handleDocumentTypeAssign],
);
const handleDocumentTypeSet = useCallback(
async ({ document, name, input }) => {
if (!document?.id) {
throw new Error('Missing document for document type assignment.');
}
const trimmed = (name || '').trim();
if (!trimmed) {
setStatusMessage('Document type name is required.', 'error');
return;
}
let target = documentTypeLookupByName.get(trimmed.toLowerCase()) || null;
if (!target) {
try {
target = await handleDocumentTypeCreate({ name: trimmed });
} catch (error) {
return;
}
}
if (!target?.id) {
setStatusMessage('Unable to resolve document type.', 'error');
return;
}
const success = await handleDocumentTypeAssign(
{ documentId: document.id, documentTypeId: target.id },
{ notify: true },
);
if (success && input) {
input.value = '';
}
},
[
handleDocumentTypeCreate,
handleDocumentTypeAssign,
documentTypeLookupByName,
setStatusMessage,
],
);
const resolveTargetDocumentIds = useCallback(
(candidateIds) => {
const normalized = Array.isArray(candidateIds)
? candidateIds.filter(Boolean)
: [];
if (normalized.length) {
return Array.from(new Set(normalized));
}
return selectedDocumentIds;
},
[selectedDocumentIds],
);
const handleBulkDocumentTypeSet = useCallback(
async ({ name, input, documentIds }) => {
const trimmed = (name || '').trim();
if (!trimmed) {
setStatusMessage('Document type name is required.', 'error');
return;
}
const targets = resolveTargetDocumentIds(documentIds);
if (!targets.length) {
setStatusMessage('Select documents before assigning a document type.', 'error');
return;
}
let target = documentTypeLookupByName.get(trimmed.toLowerCase()) || null;
if (!target) {
try {
target = await handleDocumentTypeCreate({ name: trimmed });
} catch (error) {
return;
}
}
if (!target?.id) {
setStatusMessage('Unable to resolve document type.', 'error');
return;
}
try {
await Promise.all(
targets.map((documentId) =>
api.patch(`/documents/${documentId}`, { document_type_id: target.id }),
),
);
await refreshCurrentFolder();
const suffix = targets.length === 1 ? '' : 's';
setStatusMessage(
`Document type assigned to ${targets.length} document${suffix}.`,
'success',
);
if (input) {
input.value = '';
}
} catch (error) {
const message = error.response?.data?.error || 'Failed to assign document type.';
notifyApiError(error, message);
}
},
[
documentTypeLookupByName,
handleDocumentTypeCreate,
refreshCurrentFolder,
resolveTargetDocumentIds,
setStatusMessage,
notifyApiError,
],
);
const handleBulkDocumentTypeClear = useCallback(
async ({ documentIds }) => {
const targets = resolveTargetDocumentIds(documentIds);
if (!targets.length) {
setStatusMessage('Select documents before clearing the document type.', 'error');
return;
}
try {
await Promise.all(
targets.map((documentId) => api.patch(`/documents/${documentId}`, { document_type_id: null })),
);
await refreshCurrentFolder();
const suffix = targets.length === 1 ? '' : 's';
setStatusMessage(
`Document type cleared from ${targets.length} document${suffix}.`,
'success',
);
} catch (error) {
const message = error.response?.data?.error || 'Failed to clear document type.';
notifyApiError(error, message);
}
},
[resolveTargetDocumentIds, refreshCurrentFolder, setStatusMessage, notifyApiError],
);
const handleTagDelete = useCallback(
async (tagId) => {
if (!tagId) {
@@ -2249,7 +2616,7 @@ const AppLayout = () => {
const initializeAfterLogin = useCallback(async () => {
setLoading(true);
try {
await Promise.all([refreshTags(), refreshCorrespondents()]);
await Promise.all([refreshTags(), refreshCorrespondents(), refreshDocumentTypes()]);
const initialFolder = routeFolderId && routeFolderId !== 'root' ? routeFolderId : 'root';
await loadFolder(initialFolder, { showLoading: false });
} catch (error) {
@@ -2258,7 +2625,7 @@ const AppLayout = () => {
} finally {
setLoading(false);
}
}, [refreshTags, refreshCorrespondents, routeFolderId, loadFolder, notifyApiError]);
}, [refreshTags, refreshCorrespondents, refreshDocumentTypes, routeFolderId, loadFolder, notifyApiError]);
useEffect(() => {
if (!token) {
@@ -2289,19 +2656,6 @@ const AppLayout = () => {
selectFolder,
]);
const resolveTargetDocumentIds = useCallback(
(candidateIds) => {
const normalized = Array.isArray(candidateIds)
? candidateIds.filter(Boolean)
: [];
if (normalized.length) {
return Array.from(new Set(normalized));
}
return selectedDocumentIds;
},
[selectedDocumentIds],
);
const handleBulkCorrespondentAdd = useCallback(
async ({ name, input, documentIds }) => {
const trimmed = (name || '').trim();
@@ -3582,16 +3936,15 @@ const AppLayout = () => {
setLoading(true);
try {
const { data } = await api.patch(`/documents/${documentId}`, { title: trimmed });
const hydratedDetail = assetManager.hydrateDetail(data);
const hydratedDocument = hydratedDetail?.document || data.document || data;
const { data } = await api.patch(`/documents/${documentId}`, { title: trimmed });
const updatedDocument = extractDocumentFromResponse(data);
updateDocumentCaches(documentId, (doc) => {
if (hydratedDocument) {
return { ...doc, ...hydratedDocument };
}
return { ...doc, title: trimmed };
});
updateDocumentCaches(documentId, (doc) => {
if (updatedDocument) {
return { ...doc, ...updatedDocument };
}
return { ...doc, title: trimmed };
});
setStatusMessage('Document title updated.', 'success');
return true;
@@ -3603,7 +3956,7 @@ const AppLayout = () => {
setLoading(false);
}
},
[assetManager, notifyApiError, setStatusMessage, updateDocumentCaches],
[notifyApiError, setStatusMessage, updateDocumentCaches, extractDocumentFromResponse],
);
const applyTagRemovalToCaches = useCallback(
@@ -3967,6 +4320,7 @@ const AppLayout = () => {
const openTagsModal = useCallback(() => {
setCorrespondentsModalOpen(false);
setDocumentTypesModalOpen(false);
setTagsModalOpen(true);
}, []);
@@ -3977,12 +4331,23 @@ const AppLayout = () => {
const openCorrespondentsModal = useCallback(() => {
setTagsModalOpen(false);
setCorrespondentsModalOpen(true);
setDocumentTypesModalOpen(false);
}, []);
const closeCorrespondentsModal = useCallback(() => {
setCorrespondentsModalOpen(false);
}, []);
const openDocumentTypesModal = useCallback(() => {
setTagsModalOpen(false);
setCorrespondentsModalOpen(false);
setDocumentTypesModalOpen(true);
}, []);
const closeDocumentTypesModal = useCallback(() => {
setDocumentTypesModalOpen(false);
}, []);
const openSettingsModal = useCallback(() => {
setSettingsModalOpen(true);
}, []);
@@ -3994,11 +4359,12 @@ const AppLayout = () => {
useEffect(() => {
setTagsModalOpen(false);
setCorrespondentsModalOpen(false);
setDocumentTypesModalOpen(false);
setSettingsModalOpen(false);
}, [location.pathname]);
useEffect(() => {
if (!isTagsModalOpen && !isCorrespondentsModalOpen && !isSettingsModalOpen) {
if (!isTagsModalOpen && !isCorrespondentsModalOpen && !isDocumentTypesModalOpen && !isSettingsModalOpen) {
return;
}
const handleKeyDown = (event) => {
@@ -4008,6 +4374,8 @@ const AppLayout = () => {
closeTagsModal();
} else if (isCorrespondentsModalOpen) {
closeCorrespondentsModal();
} else if (isDocumentTypesModalOpen) {
closeDocumentTypesModal();
} else if (isSettingsModalOpen) {
closeSettingsModal();
}
@@ -4020,9 +4388,11 @@ const AppLayout = () => {
}, [
isTagsModalOpen,
isCorrespondentsModalOpen,
isDocumentTypesModalOpen,
isSettingsModalOpen,
closeTagsModal,
closeCorrespondentsModal,
closeDocumentTypesModal,
closeSettingsModal,
]);
@@ -4054,6 +4424,9 @@ const AppLayout = () => {
if (activeCorrespondentFilters.length) {
params.correspondents = activeCorrespondentFilters.join(',');
}
if (activeDocumentTypeFilters.length) {
params.document_types = activeDocumentTypeFilters.join(',');
}
const folderIdentifier = selectedFolder === 'root' ? null : selectedFolder;
if (folderIdentifier) {
params.folder_id = folderIdentifier;
@@ -4135,6 +4508,7 @@ const AppLayout = () => {
searchQuery,
activeTagFilters,
activeCorrespondentFilters,
activeDocumentTypeFilters,
selectedFolder,
notifyApiError,
assetManager,
@@ -4936,7 +5310,7 @@ const AppLayout = () => {
setWorkspaceMode('table');
navigate('/documents', { replace: true });
await Promise.all([refreshTags(), refreshCorrespondents()]);
await Promise.all([refreshTags(), refreshCorrespondents(), refreshDocumentTypes()]);
await loadFolder('root', { showLoading: false, preserveSearch: false });
const tenantLabel = data?.tenant?.name || data?.tenant?.id || 'tenant';
@@ -4957,6 +5331,7 @@ const AppLayout = () => {
navigate,
refreshTags,
refreshCorrespondents,
refreshDocumentTypes,
loadFolder,
],
);
@@ -5082,6 +5457,10 @@ const AppLayout = () => {
activeCorrespondentIds: activeCorrespondentFilters,
onToggleCorrespondentFilter: toggleCorrespondentFilter,
onCreateCorrespondent: (name) => handleCorrespondentCreate({ name }),
documentTypes,
activeDocumentTypeIds: activeDocumentTypeFilters,
onToggleDocumentTypeFilter: toggleDocumentTypeFilter,
onCreateDocumentType: (name) => handleDocumentTypeCreate({ name }),
appStatus,
loading,
previewActive,
@@ -5105,6 +5484,7 @@ const AppLayout = () => {
clearFilters,
correspondents,
currentTenantId,
documentTypes,
folderClickHandlers,
folderNodes,
handleFolderDelete,
@@ -5130,10 +5510,13 @@ const AppLayout = () => {
toggleTagFilter,
handleTagCreate,
handleCorrespondentCreate,
toggleDocumentTypeFilter,
handleDocumentTypeCreate,
handlePromptCreateFolder,
creatingFolder,
handleNeutralHueChange,
neutralHue,
activeDocumentTypeFilters,
],
);
@@ -5168,6 +5551,11 @@ const AppLayout = () => {
correspondents,
onCorrespondentAdd: handleCorrespondentAdd,
onCorrespondentRemove: handleCorrespondentRemove,
documentTypes,
onDocumentTypeSet: handleDocumentTypeSet,
onDocumentTypeClear: handleDocumentTypeClear,
onBulkDocumentTypeSet: handleBulkDocumentTypeSet,
onBulkDocumentTypeClear: handleBulkDocumentTypeClear,
resolveApiPath,
onFolderNavigate: selectFolder,
onClose: handleDetailPanelClose,
@@ -5182,11 +5570,15 @@ const AppLayout = () => {
getDocumentAsset,
handleBulkCorrespondentAdd,
handleBulkCorrespondentRemove,
handleBulkDocumentTypeSet,
handleBulkDocumentTypeClear,
handleBulkSelectionReanalyze,
handleBulkTagAddFromDetail,
handleBulkTagRemoveFromDetail,
handleCorrespondentAdd,
handleCorrespondentRemove,
handleDocumentTypeSet,
handleDocumentTypeClear,
handleDetailPanelClose,
handleDocumentTitleUpdate,
handleTagAdd,
@@ -5199,6 +5591,7 @@ const AppLayout = () => {
selectedPreviewEntry,
tags,
tagLookupById,
documentTypes,
],
);
@@ -5257,6 +5650,16 @@ const AppLayout = () => {
handleDocumentCorrespondentAttach,
handleCorrespondentRemove,
handleCorrespondentAdd,
documentTypes,
refreshDocumentTypes,
handleDocumentTypeUpdate,
handleDocumentTypeCreate,
handleDocumentTypeDelete,
handleDocumentTypeAssign,
handleDocumentTypeClear,
handleDocumentTypeSet,
handleBulkDocumentTypeSet,
handleBulkDocumentTypeClear,
previewActive,
previewWorkspaceDocument,
previewWorkspaceEntry,
@@ -5275,6 +5678,7 @@ const AppLayout = () => {
notifyApiError,
openTagsModal,
openCorrespondentsModal,
openDocumentTypesModal,
openSettingsModal,
detailPanelOpen,
setDetailPanelOpen,
@@ -5300,6 +5704,16 @@ const AppLayout = () => {
handleDocumentCorrespondentAttach,
handleCorrespondentRemove,
handleCorrespondentAdd,
documentTypes,
refreshDocumentTypes,
handleDocumentTypeUpdate,
handleDocumentTypeCreate,
handleDocumentTypeDelete,
handleDocumentTypeAssign,
handleDocumentTypeClear,
handleDocumentTypeSet,
handleBulkDocumentTypeSet,
handleBulkDocumentTypeClear,
previewActive,
previewWorkspaceDocument,
previewWorkspaceEntry,
@@ -5317,6 +5731,7 @@ const AppLayout = () => {
notifyApiError,
openTagsModal,
openCorrespondentsModal,
openDocumentTypesModal,
openSettingsModal,
detailPanelOpen,
setDetailPanelOpen,
@@ -5402,12 +5817,48 @@ const AppLayout = () => {
</button>
</div>
<div className="panel-modal__body">
<CorrespondentsPanel
correspondents={correspondents}
onRefresh={refreshCorrespondents}
onCreate={handleCorrespondentCreate}
onUpdate={handleCorrespondentUpdate}
onDelete={handleCorrespondentDelete}
<CorrespondentsPanel
correspondents={correspondents}
onRefresh={refreshCorrespondents}
onCreate={handleCorrespondentCreate}
onUpdate={handleCorrespondentUpdate}
onDelete={handleCorrespondentDelete}
onNotify={setStatusMessage}
/>
</div>
</div>
</div>
)}
{isDocumentTypesModalOpen && (
<div
className="modal-backdrop"
role="presentation"
onClick={closeDocumentTypesModal}
>
<div
className="modal modal--panel"
role="dialog"
aria-modal="true"
aria-labelledby="document-types-modal-title"
onClick={(event) => event.stopPropagation()}
>
<div className="panel-modal__header">
<h3 id="document-types-modal-title">Manage Document Types</h3>
<button
type="button"
className="secondary"
onClick={closeDocumentTypesModal}
>
Close
</button>
</div>
<div className="panel-modal__body">
<DocumentTypesPanel
documentTypes={documentTypes}
onRefresh={refreshDocumentTypes}
onCreate={handleDocumentTypeCreate}
onUpdate={handleDocumentTypeUpdate}
onDelete={handleDocumentTypeDelete}
onNotify={setStatusMessage}
/>
</div>
@@ -5450,6 +5901,7 @@ const DocumentsRoute = () => {
skeuoWorkspaceProps,
openTagsModal,
openCorrespondentsModal,
openDocumentTypesModal,
previewWorkspaceDocument,
previewWorkspaceEntry,
closeDocumentPreview,
@@ -5471,9 +5923,10 @@ const DocumentsRoute = () => {
...sidebarProps,
onManageTags: openTagsModal,
onManageCorrespondents: openCorrespondentsModal,
onManageDocumentTypes: openDocumentTypesModal,
onCollapse: collapseSidebar,
}),
[sidebarProps, openTagsModal, openCorrespondentsModal, collapseSidebar],
[sidebarProps, openTagsModal, openCorrespondentsModal, openDocumentTypesModal, collapseSidebar],
);
const breadcrumbs = documentsTableProps?.breadcrumbs || null;
+8 -1
View File
@@ -3,6 +3,8 @@ import { DownloadIcon, TextScanIcon, AnalyzeIcon, CloseIcon } from '../ui/icons'
import { describeDocumentSummary } from '../documents/documentSummary';
import { createDocumentActionState } from '../documents/documentActions';
const resolveDocumentTypeName = (doc) => doc?.document_type?.name;
const PreviewWorkspace = ({
document,
previewEntry,
@@ -19,6 +21,7 @@ const PreviewWorkspace = ({
const tags = Array.isArray(document.tags)
? document.tags.map((tag) => tag?.label).filter(Boolean).join(', ')
: '';
const documentTypeName = resolveDocumentTypeName(document);
const formatDateTime = (value) => {
if (!value) {
@@ -33,11 +36,15 @@ const PreviewWorkspace = ({
{ label: 'Archive Reference', value: document.archive_serial || '—' },
{ label: 'Issued On', value: formatDateTime(document.issued_at) },
{ label: 'Correspondent', value: correspondents || '—' },
{ label: 'Document Type', value: document.document_type || '—' },
{ label: 'Document Type', value: documentTypeName || '—' },
{
label: 'Filename',
value: document.archive_path || document.filename || '—',
},
{
label: 'Original Filename',
value: document.original_name || '—',
},
{ label: 'Tags', value: tags || '—' },
];
+85
View File
@@ -151,10 +151,15 @@ const Sidebar = ({
correspondents = [],
activeCorrespondentIds = [],
onToggleCorrespondentFilter,
documentTypes = [],
activeDocumentTypeIds = [],
onToggleDocumentTypeFilter,
onManageTags,
onManageCorrespondents,
onManageDocumentTypes,
onCreateTag,
onCreateCorrespondent,
onCreateDocumentType,
searchQuery = '',
onSearchChange,
onSearchSubmit,
@@ -180,10 +185,22 @@ const Sidebar = ({
() => new Set(activeCorrespondentIds || []),
[activeCorrespondentIds],
);
const sortedDocumentTypes = useMemo(
() =>
[...documentTypes].sort((a, b) =>
(a?.name || '').localeCompare(b?.name || '', undefined, { sensitivity: 'base' }),
),
[documentTypes],
);
const activeDocumentTypeSet = useMemo(
() => new Set(activeDocumentTypeIds || []),
[activeDocumentTypeIds],
);
const handleToggleTag = onToggleTagFilter || (() => {});
const activeTagSet = new Set(activeTagIds);
const handleManageTags = onManageTags || (() => {});
const handleManageCorrespondents = onManageCorrespondents || (() => {});
const handleManageDocumentTypes = onManageDocumentTypes || (() => {});
const handleCreateTag = useCallback(async () => {
const input = window.prompt('New tag name');
if (!input) {
@@ -216,6 +233,22 @@ const Sidebar = ({
}
}, [onCreateCorrespondent]);
const handleCreateDocumentType = useCallback(async () => {
const input = window.prompt('New document type name');
if (!input) {
return;
}
const trimmed = input.trim();
if (!trimmed) {
return;
}
try {
await onCreateDocumentType?.(trimmed);
} catch (error) {
console.error('[sidebar] failed to create document type', error);
}
}, [onCreateDocumentType]);
const handleCreateFolder = useCallback(() => {
if (creatingFolder) {
return;
@@ -592,6 +625,58 @@ const Sidebar = ({
})}
</ul>
</div>
<div className="sidebar-section">
<div className="sidebar-section__header">
<h3>Document Types</h3>
<div className="sidebar-section__actions">
<button
type="button"
className="icon-button"
onClick={handleCreateDocumentType}
aria-label="Create document type"
>
<PlusIcon size={16} />
</button>
<button
type="button"
className="icon-button"
onClick={handleManageDocumentTypes}
aria-label="Manage document types"
>
<SettingsIcon size={16} />
</button>
<span className="meta">{documentTypes.length}</span>
</div>
</div>
<ul className="sidebar-correspondent-list">
{sortedDocumentTypes.map((entry) => {
const isActive = activeDocumentTypeSet.has(entry.id);
const className = `sidebar-correspondent-item${isActive ? ' active' : ''}`;
const label = entry.name || 'Untitled';
const handleSelect = () => {
const nextId = isActive ? null : entry.id;
onToggleDocumentTypeFilter?.(nextId);
};
return (
<li key={entry.id}>
<span
className={className}
role="button"
onClick={handleSelect}
onKeyDown={(event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
handleSelect();
}
}}
>
{label}
</span>
</li>
);
})}
</ul>
</div>
{typeof neutralHue === 'number' || typeof neutralHue === 'string' ? (
<div className="sidebar-section">
<div className="sidebar-section__header">
+58
View File
@@ -2012,6 +2012,43 @@ button.danger:hover:not([disabled]) {
color: inherit;
}
.doc-type-label {
display: inline-flex;
align-items: center;
padding: 0.05rem 0.4rem;
margin-right: 0.35rem;
border-radius: 999px;
background: var(--surface-subtle);
color: var(--muted);
font-size: 0.75rem;
line-height: 1.2;
cursor: default;
gap: 0.25rem;
}
.doc-type-label[role='button'] {
cursor: pointer;
color: var(--accent);
background: color-mix(in oklch, var(--accent) 12%, transparent);
}
.doc-type-label[role='button']:hover,
.doc-type-label[role='button']:focus-visible {
color: var(--accent-strong, var(--accent));
background: color-mix(in oklch, var(--accent) 20%, transparent);
}
.doc-type-label[role='button']:focus-visible {
outline: 2px solid currentColor;
outline-offset: 2px;
}
.doc-type-label.active {
background: color-mix(in oklch, var(--accent) 28%, transparent);
color: var(--accent-strong, var(--accent));
font-weight: 600;
}
.doc-correspondent-link {
background: none;
background-color: transparent;
@@ -2492,6 +2529,27 @@ button.danger:hover:not([disabled]) {
margin: 0.4rem 0 0.6rem;
}
.detail-field {
margin: 0.9rem 0;
}
.detail-field__label {
font-weight: 600;
margin-bottom: 0.25rem;
}
.detail-field__value {
display: flex;
align-items: center;
gap: 0.5rem;
flex-wrap: wrap;
margin-bottom: 0.5rem;
}
.detail-field__value .meta {
color: var(--muted);
}
.detail-panel dl {
margin: 0;
}