π‘οΈ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!
Add claim documents (issue #148)
Omega (QA)14966f2436b9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex da90970..73eeaf6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,4 +1,9 @@# Changelog+## 1.0.4 - Unreleased++- **Claim documents (issue #148):** claims can now carry documents β claim approval or rejection letters, photos of the defect, repair invoices, and similar evidence. Each claim shows a Documents section in the claims view: attach a file directly, or upload it to Paperless-ngx and link it, then view or remove it from the same place. Access follows the warranty's other documents: the owner and admins only, never shared through global view. Deleting a claim or its warranty removes the attached local files from disk; Paperless documents are unlinked, never deleted from Paperless.+ - _Files: `backend/migrations/052_create_claim_documents_table.sql`, `backend/warranties_routes.py`, `backend/file_routes.py`, `frontend/js/components/claims.js`, `frontend/style.css`, `locales/en/translation.json`_+## 1.0.3 - 2026-10-02- **Status page CSV export:** The Export button on the status dashboard was a placeholder that only showed a "not implemented" toast. It now downloads a CSV of the currently displayed (filtered and sorted) warranties, using the same column layout as the main page export so the file can be re-imported.diff --git a/backend/file_routes.py b/backend/file_routes.pyindex b8666b7..9fed308 100644--- a/backend/file_routes.py+++ b/backend/file_routes.py@@ -54,6 +54,23 @@ def _check_file_authorization(cur, db_search_path, user_id, is_admin):logger.info(f"[FILE_AUTH] Admin access granted for '{db_search_path}'")return True+ # Claim documents (issue #148): owner-only, like warranty "other+ # documents" they never participate in global view.+ if not results:+ cur.execute("""+ SELECT w.user_id+ FROM claim_documents d+ JOIN warranty_claims c ON d.claim_id = c.id+ JOIN warranties w ON c.warranty_id = w.id+ WHERE d.file_path = %s+ """, (db_search_path,))+ for (claim_owner_id,) in (cur.fetchall() or []):+ if claim_owner_id == user_id:+ logger.info(f"[FILE_AUTH] Claim document ownership confirmed for '{db_search_path}'")+ return True+ logger.warning(f"[FILE_AUTH] Unauthorized file access attempt: '{db_search_path}' by user {user_id}")+ return False+# Ownership authorizationfor warranty_id_db, warranty_user_id_db in (results or []):if warranty_user_id_db == user_id:@@ -275,7 +292,20 @@ def serve_paperless_document(paperless_id: int):""", (paperless_id, paperless_id, paperless_id, paperless_id))results = cur.fetchall()-++ # Claim documents (issue #148) link Paperless documents too;+ # they resolve to the owning warranty's user and stay+ # owner/admin-only (no global-view sharing, like claims).+ if not results:+ cur.execute("""+ SELECT w.id, w.user_id+ FROM claim_documents d+ JOIN warranty_claims c ON d.claim_id = c.id+ JOIN warranties w ON c.warranty_id = w.id+ WHERE d.paperless_document_id = %s+ """, (paperless_id,))+ results = cur.fetchall()+if not results:logger.warning(f"[PAPERLESS_FILE] No warranty found with Paperless document ID {paperless_id}")return jsonify({"message": "Document not found"}), 404diff --git a/backend/migrations/052_create_claim_documents_table.sql b/backend/migrations/052_create_claim_documents_table.sqlnew file mode 100644index 0000000..daf448f--- /dev/null+++ b/backend/migrations/052_create_claim_documents_table.sql@@ -0,0 +1,18 @@+-- Migration 052: claim_documents table (issue #148)+-- Documents attached to warranty claims: claim approval/rejection letters,+-- photos of the defect, repair invoices, and similar evidence. A document is+-- either a locally uploaded file (file_path set) or a Paperless-ngx document+-- (paperless_document_id set) β exactly one of the two.+CREATE TABLE IF NOT EXISTS claim_documents (+ id SERIAL PRIMARY KEY,+ claim_id INTEGER NOT NULL REFERENCES warranty_claims(id) ON DELETE CASCADE,+ original_filename VARCHAR(255) NOT NULL,+ file_path VARCHAR(500),+ paperless_document_id INTEGER,+ created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,+ CONSTRAINT claim_documents_exactly_one_source+ CHECK ((file_path IS NOT NULL) <> (paperless_document_id IS NOT NULL))+);+CREATE INDEX IF NOT EXISTS idx_claim_documents_claim_id ON claim_documents(claim_id);+CREATE INDEX IF NOT EXISTS idx_claim_documents_file_path ON claim_documents(file_path);+CREATE INDEX IF NOT EXISTS idx_claim_documents_paperless_id ON claim_documents(paperless_document_id);diff --git a/backend/warranties_routes.py b/backend/warranties_routes.pyindex ba4b95f..929515e 100644--- a/backend/warranties_routes.py+++ b/backend/warranties_routes.py@@ -617,7 +617,16 @@ def delete_warranty(warranty_id):manual_path = result[1]other_document_path = result[2]product_photo_path = result[3]-++ # Claim document files (issue #148) β the rows cascade on delete,+ # so collect their paths first+ cur.execute('''+ SELECT d.file_path FROM claim_documents d+ JOIN warranty_claims c ON d.claim_id = c.id+ WHERE c.warranty_id = %s AND d.file_path IS NOT NULL+ ''', (warranty_id,))+ claim_document_paths = [row[0] for row in cur.fetchall()]+# Delete the warranty from databasecur.execute('DELETE FROM warranties WHERE id = %s', (warranty_id,))deleted_rows = cur.rowcount@@ -647,6 +656,12 @@ def delete_warranty(warranty_id):if os.path.exists(full_path):os.remove(full_path)+ # Delete claim document files (rows already cascaded)+ for claim_doc_path in claim_document_paths:+ full_path = os.path.join('/data', claim_doc_path)+ if os.path.exists(full_path):+ os.remove(full_path)+return jsonify({"message": "Warranty deleted successfully"}), 200except Exception as e:@@ -2322,7 +2337,8 @@ def create_claim(warranty_id):'resolution': resolution,'resolution_date': parsed_resolution_date.isoformat() if parsed_resolution_date else None,'created_at': created_at.isoformat() if created_at else None,- 'updated_at': updated_at.isoformat() if updated_at else None+ 'updated_at': updated_at.isoformat() if updated_at else None,+ 'documents': []}logger.info(f"Created claim {claim_id} for warranty {warranty_id} by user {user_id}")@@ -2409,7 +2425,30 @@ def get_claims(warranty_id):'updated_at': row[9].isoformat() if row[9] else None}claims.append(claim)-++ # Embed each claim's documents (issue #148) in one extra query+ if claims:+ claim_ids = [c['id'] for c in claims]+ cur.execute("""+ SELECT id, claim_id, original_filename, file_path, paperless_document_id, created_at+ FROM claim_documents+ WHERE claim_id = ANY(%s)+ ORDER BY created_at, id+ """, (claim_ids,))+ docs_by_claim = {}+ for drow in cur.fetchall():+ doc = {+ 'id': drow[0],+ 'claim_id': drow[1],+ 'original_filename': drow[2],+ 'file_path': drow[3],+ 'paperless_document_id': drow[4],+ 'created_at': drow[5].isoformat() if drow[5] else None+ }+ docs_by_claim.setdefault(drow[1], []).append(doc)+ for claim in claims:+ claim['documents'] = docs_by_claim.get(claim['id'], [])+return jsonify(claims), 200except Exception as e:@@ -2562,17 +2601,28 @@ def delete_claim(warranty_id, claim_id):result = cur.fetchone()if not result:return jsonify({'error': 'Warranty or claim not found or access denied'}), 404-++ # Remember attached local files so they can be removed with the claim+ # (the claim_documents rows themselves cascade on delete)+ cur.execute("""+ SELECT file_path FROM claim_documents+ WHERE claim_id = %s AND file_path IS NOT NULL+ """, (claim_id,))+ document_files = [row[0] for row in cur.fetchall()]+# Delete the claimcur.execute("""- DELETE FROM warranty_claims+ DELETE FROM warranty_claimsWHERE id = %s AND warranty_id = %s""", (claim_id, warranty_id))-+if cur.rowcount == 0:return jsonify({'error': 'Claim not found'}), 404-+conn.commit()++ for doc_file in document_files:+ _remove_claim_document_file(doc_file)logger.info(f"Deleted claim {claim_id} for warranty {warranty_id} by user {user_id}")return jsonify({'message': 'Claim deleted successfully'}), 200@@ -2589,4 +2639,219 @@ def delete_claim(warranty_id, claim_id):if conn:release_db_connection(conn)-\ No newline at end of file+++# ============================+# Claim Documents (issue #148)+# ============================++def _serialize_claim_document(row):+ """Serialize a claim_documents row (id, claim_id, original_filename,+ file_path, paperless_document_id, created_at)."""+ return {+ 'id': row[0],+ 'claim_id': row[1],+ 'original_filename': row[2],+ 'file_path': row[3],+ 'paperless_document_id': row[4],+ 'created_at': row[5].isoformat() if row[5] else None+ }+++def _verify_claim_ownership(cur, warranty_id, claim_id, user_id):+ """True when the user owns the warranty the claim belongs to."""+ cur.execute("""+ SELECT w.id+ FROM warranties w+ JOIN warranty_claims c ON w.id = c.warranty_id+ WHERE w.id = %s AND c.id = %s AND w.user_id = %s+ """, (warranty_id, claim_id, user_id))+ return cur.fetchone() is not None+++def _remove_claim_document_file(file_path):+ """Best-effort removal of a locally stored claim document file."""+ if not file_path:+ return+ try:+ full_path = os.path.join(current_app.config['UPLOAD_FOLDER'], os.path.basename(file_path))+ if os.path.exists(full_path):+ os.remove(full_path)+ except OSError as e:+ logger.warning(f"Could not remove claim document file {file_path}: {e}")+++@warranties_bp.route('/warranties/<int:warranty_id>/claims/<int:claim_id>/documents', methods=['POST'])+@token_required+def add_claim_document(warranty_id, claim_id):+ """Attach a document to a claim: a local file upload, or a link to an+ existing Paperless-ngx document (paperless_document_id form field)."""+ conn = None+ cur = None++ try:+ user_id = request.user['id']+ conn = get_db_connection()+ cur = conn.cursor()++ if not _verify_claim_ownership(cur, warranty_id, claim_id, user_id):+ return jsonify({'error': 'Warranty or claim not found or access denied'}), 404++ paperless_document_id = None+ raw_pid = request.form.get('paperless_document_id')+ if raw_pid:+ try:+ paperless_document_id = int(raw_pid)+ except (TypeError, ValueError):+ return jsonify({'error': 'Invalid paperless_document_id'}), 400++ db_file_path = None+ original_filename = None++ if paperless_document_id is not None:+ # Link an existing Paperless document; the local file input is ignored.+ original_filename = (request.form.get('original_filename') or '').strip() \+ or f'Paperless document {paperless_document_id}'+ elif 'file' in request.files and request.files['file'].filename:+ upload = request.files['file']+ if not allowed_file(upload.filename):+ return jsonify({'error': 'File type not allowed',+ 'code': 'file_type_not_allowed'}), 400+ filename = unique_upload_filename(upload.filename, infix="claim_")+ full_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)+ try:+ upload.save(full_path)+ except OSError as e:+ logger.error(f"Error saving claim document {filename}: {e}")+ return jsonify({'error': 'Could not save the uploaded file'}), 500+ db_file_path = os.path.join('uploads', filename)+ original_filename = upload.filename+ else:+ return jsonify({'error': 'No file or paperless_document_id provided'}), 400++ if len(original_filename) > 255:+ original_filename = original_filename[:255]++ cur.execute("""+ INSERT INTO claim_documents+ (claim_id, original_filename, file_path, paperless_document_id)+ VALUES (%s, %s, %s, %s)+ RETURNING id, claim_id, original_filename, file_path, paperless_document_id, created_at+ """, (claim_id, original_filename, db_file_path, paperless_document_id))++ document = _serialize_claim_document(cur.fetchone())+ conn.commit()++ logger.info(f"Added document {document['id']} to claim {claim_id} by user {user_id}")+ return jsonify(document), 201++ except Exception as e:+ if conn:+ conn.rollback()+ logger.error(f"Error adding claim document: {e}")+ return jsonify({'error': 'Internal server error'}), 500++ finally:+ if cur:+ cur.close()+ if conn:+ release_db_connection(conn)+++@warranties_bp.route('/warranties/<int:warranty_id>/claims/<int:claim_id>/documents', methods=['GET'])+@token_required+def get_claim_documents(warranty_id, claim_id):+ """List a claim's documents. Read access follows the claims list:+ the warranty owner, admins, and global-view users may read."""+ conn = None+ cur = None++ try:+ user_id = request.user['id']+ is_admin = request.user.get('is_admin', False)+ conn = get_db_connection()+ cur = conn.cursor()++ # The claim must exist under this warranty+ cur.execute("""+ SELECT w.user_id FROM warranties w+ JOIN warranty_claims c ON w.id = c.warranty_id+ WHERE w.id = %s AND c.id = %s+ """, (warranty_id, claim_id))+ owner_row = cur.fetchone()+ if not owner_row:+ return jsonify({'error': 'Warranty or claim not found'}), 404++ if owner_row[0] != user_id and not is_admin:+ cur.execute("SELECT key, value FROM site_settings WHERE key IN ('global_view_enabled', 'global_view_admin_only')")+ settings = {row[0]: row[1] for row in cur.fetchall()}+ global_view_enabled = settings.get('global_view_enabled', 'true').lower() == 'true'+ admin_only = settings.get('global_view_admin_only', 'false').lower() == 'true'+ if not global_view_enabled or admin_only:+ return jsonify({'error': 'Warranty or claim not found or access denied'}), 404++ cur.execute("""+ SELECT id, claim_id, original_filename, file_path, paperless_document_id, created_at+ FROM claim_documents+ WHERE claim_id = %s+ ORDER BY created_at, id+ """, (claim_id,))++ return jsonify([_serialize_claim_document(row) for row in cur.fetchall()]), 200++ except Exception as e:+ logger.error(f"Error getting claim documents: {e}")+ return jsonify({'error': 'Internal server error'}), 500++ finally:+ if cur:+ cur.close()+ if conn:+ release_db_connection(conn)+++@warranties_bp.route('/warranties/<int:warranty_id>/claims/<int:claim_id>/documents/<int:document_id>', methods=['DELETE'])+@token_required+def delete_claim_document(warranty_id, claim_id, document_id):+ """Remove a document from a claim. Local files are deleted from disk;+ Paperless documents are only unlinked (never deleted from Paperless)."""+ conn = None+ cur = None++ try:+ user_id = request.user['id']+ conn = get_db_connection()+ cur = conn.cursor()++ if not _verify_claim_ownership(cur, warranty_id, claim_id, user_id):+ return jsonify({'error': 'Warranty or claim not found or access denied'}), 404++ cur.execute("""+ SELECT file_path FROM claim_documents+ WHERE id = %s AND claim_id = %s+ """, (document_id, claim_id))+ row = cur.fetchone()+ if not row:+ return jsonify({'error': 'Document not found'}), 404+ file_path = row[0]++ cur.execute("DELETE FROM claim_documents WHERE id = %s AND claim_id = %s",+ (document_id, claim_id))+ conn.commit()++ _remove_claim_document_file(file_path)++ logger.info(f"Deleted document {document_id} from claim {claim_id} by user {user_id}")+ return jsonify({'message': 'Document deleted successfully'}), 200++ except Exception as e:+ if conn:+ conn.rollback()+ logger.error(f"Error deleting claim document: {e}")+ return jsonify({'error': 'Internal server error'}), 500++ finally:+ if cur:+ cur.close()+ if conn:+ release_db_connection(conn)diff --git a/frontend/js/components/claims.js b/frontend/js/components/claims.jsindex 9b40c0a..df4bc1d 100644--- a/frontend/js/components/claims.js+++ b/frontend/js/components/claims.js@@ -83,6 +83,16 @@ function bindClaimsListDelegation() {function bindClaimsListBodyActions() {if (!dom.claimsListBody || dom.claimsListBody._claimsActionsBound) return;dom.claimsListBody.addEventListener('click', (event) => {+ // Viewing a document is allowed for read-only (global view) users too+ const viewBtn = event.target.closest('.claim-doc-view');+ if (viewBtn) {+ const claimId = parseInt(viewBtn.dataset.claimId, 10);+ const docId = parseInt(viewBtn.dataset.docId, 10);+ const claim = state.claims.find((c) => c.id === claimId);+ const doc = claim?.documents?.find((d) => d.id === docId);+ if (doc) openClaimDocument(doc);+ return;+ }if (!state.canEdit) return;const editBtn = event.target.closest('.edit-claim-btn');if (editBtn) {@@ -99,6 +109,25 @@ function bindClaimsListBodyActions() {if (window.confirm(confirmMessage)) {deleteClaim(claimId);}+ return;+ }+ const docDeleteBtn = event.target.closest('.claim-doc-delete');+ if (docDeleteBtn) {+ const claimId = parseInt(docDeleteBtn.dataset.claimId, 10);+ const docId = parseInt(docDeleteBtn.dataset.docId, 10);+ const confirmMessage = t('claims.confirm_delete_document', 'Remove this document from the claim?');+ if (window.confirm(confirmMessage)) {+ deleteClaimDocument(claimId, docId);+ }+ return;+ }+ const attachBtn = event.target.closest('.claim-doc-attach');+ if (attachBtn) {+ const claimId = parseInt(attachBtn.dataset.claimId, 10);+ const item = attachBtn.closest('.claim-item');+ const storageSelect = item?.querySelector('.claim-doc-storage');+ pendingAttach = { claimId, storage: storageSelect?.value || 'local' };+ getClaimDocFileInput().click();}});dom.claimsListBody._claimsActionsBound = true;@@ -146,6 +175,36 @@ function ensureAddClaimHandler() {dom.addClaimBtn._claimsAddBound = true;}+function documentsSectionHtml(claim, canEdit) {+ const docs = Array.isArray(claim.documents) ? claim.documents : [];+ const rows = docs+ .map((doc) => {+ const icon = doc.paperless_document_id ? 'fas fa-cloud' : 'fas fa-file-alt';+ const del = canEdit+ ? `<button type="button" class="claim-doc-delete" data-claim-id="${claim.id}" data-doc-id="${doc.id}" title="${t('actions.delete', 'Delete')}"><i class="fas fa-times"></i></button>`+ : '';+ return `<div class="claim-document">+ <button type="button" class="claim-doc-view" data-claim-id="${claim.id}" data-doc-id="${doc.id}"><i class="${icon}"></i> ${escapeHtml(doc.original_filename || 'Document')}</button>+ ${del}+ </div>`;+ })+ .join('');+ const addRow = canEdit+ ? `<div class="claim-documents-add">+ <select class="claim-doc-storage">+ <option value="local">${t('claims.storage_local', 'Upload file')}</option>+ <option value="paperless">${t('claims.storage_paperless', 'Upload to Paperless')}</option>+ </select>+ <button type="button" class="btn btn-sm btn-secondary claim-doc-attach" data-claim-id="${claim.id}"><i class="fas fa-paperclip"></i> ${t('claims.attach_document', 'Attach document')}</button>+ </div>`+ : '';+ return `<div class="claim-documents">+ <div class="claim-documents-header"><i class="fas fa-paperclip"></i> ${t('claims.documents', 'Documents')} (${docs.length})</div>+ ${rows ? `<div class="claim-documents-list">${rows}</div>` : ''}+ ${addRow}+ </div>`;+}+function renderClaims() {if (!dom.claimsListBody) return;if (!state.claims.length) {@@ -203,6 +262,7 @@ function renderClaims() {</div>${claim.description ? `<div class="claim-description">${escapeHtml(claim.description)}</div>` : ''}${claim.resolution ? `<div class="claim-resolution"><strong>${t('claims.resolution_label', 'Resolution')}:</strong> ${escapeHtml(claim.resolution)}</div>` : ''}+ ${documentsSectionHtml(claim, state.canEdit)}</div>`;})@@ -335,6 +395,190 @@ async function deleteClaim(claimId) {}}+// ============================+// Claim documents (issue #148)+// ============================++let pendingAttach = null;+let claimDocFileInput = null;++function getClaimDocFileInput() {+ if (!claimDocFileInput) {+ claimDocFileInput = document.createElement('input');+ claimDocFileInput.type = 'file';+ claimDocFileInput.accept = '.pdf,.png,.jpg,.jpeg,.zip,.rar,.webp,.gif';+ claimDocFileInput.style.display = 'none';+ claimDocFileInput.addEventListener('change', () => {+ const file = claimDocFileInput.files?.[0];+ const pending = pendingAttach;+ pendingAttach = null;+ claimDocFileInput.value = '';+ if (file && pending) {+ uploadClaimDocument(pending.claimId, file, pending.storage);+ }+ });+ document.body.appendChild(claimDocFileInput);+ }+ return claimDocFileInput;+}++async function openClaimDocument(doc) {+ if (doc.paperless_document_id) {+ const token = getToken();+ if (!token) {+ showToast(t('messages.authentication_required', 'Authentication required'), 'error');+ return;+ }+ try {+ const response = await fetch(`/api/paperless-file/${doc.paperless_document_id}`, {+ headers: { Authorization: `Bearer ${token}` },+ });+ if (!response.ok) throw new Error('download failed');+ const blob = await response.blob();+ const blobUrl = window.URL.createObjectURL(blob);+ window.open(blobUrl, '_blank');+ setTimeout(() => window.URL.revokeObjectURL(blobUrl), 10000);+ } catch (error) {+ console.error('[claims] paperless document open failed', error);+ showToast(t('claims.document_open_failed', 'Failed to open document'), 'error');+ }+ return;+ }+ if (doc.file_path && window.openSecureFile) {+ window.openSecureFile(doc.file_path);+ }+}++async function uploadClaimDocument(claimId, file, storage) {+ if (!state.currentWarrantyId) return;+ try {+ const token = getToken();+ if (!token) throw new Error(t('messages.authentication_required', 'Authentication required'));++ const formData = new FormData();+ if (storage === 'paperless') {+ // Upload to Paperless first, then link the returned document ID+ const paperlessForm = new FormData();+ paperlessForm.append('file', file);+ paperlessForm.append('document_type', 'claim_document');+ paperlessForm.append('title', `Warracker claim document - ${file.name}`);+ paperlessForm.append('tags', 'warracker,claim');+ const uploadResponse = await fetch('/api/paperless/upload', {+ method: 'POST',+ headers: { Authorization: `Bearer ${token}` },+ body: paperlessForm,+ });+ const uploadResult = await uploadResponse.json().catch(() => ({}));+ if (!uploadResponse.ok || !uploadResult.document_id) {+ throw new Error(uploadResult.error || t('claims.document_add_failed', 'Failed to attach document'));+ }+ formData.append('paperless_document_id', String(uploadResult.document_id));+ formData.append('original_filename', file.name);+ } else {+ formData.append('file', file);+ }++ const response = await fetch(+ `/api/warranties/${state.currentWarrantyId}/claims/${claimId}/documents`,+ {+ method: 'POST',+ headers: { Authorization: `Bearer ${token}` },+ body: formData,+ }+ );+ if (!response.ok) {+ const error = await response.json().catch(() => ({}));+ throw new Error(error.error || t('claims.document_add_failed', 'Failed to attach document'));+ }+ showToast(t('claims.document_added', 'Document attached'), 'success');+ await loadClaims(state.currentWarrantyId);+ } catch (error) {+ console.error('[claims] document upload failed', error);+ showToast(error.message || t('claims.document_add_failed', 'Failed to attach document'), 'error');+ }+}++async function deleteClaimDocument(claimId, docId) {+ if (!state.currentWarrantyId) return;+ try {+ const token = getToken();+ if (!token) throw new Error(t('messages.authentication_required', 'Authentication required'));+ const response = await fetch(+ `/api/warranties/${state.currentWarrantyId}/claims/${claimId}/documents/${docId}`,+ {+ method: 'DELETE',+ headers: { Authorization: `Bearer ${token}` },+ }+ );+ if (!response.ok) {+ const error = await response.json().catch(() => ({}));+ throw new Error(error.error || t('claims.document_delete_failed', 'Failed to remove document'));+ }+ showToast(t('claims.document_deleted', 'Document removed'), 'success');+ await loadClaims(state.currentWarrantyId);+ } catch (error) {+ console.error('[claims] document delete failed', error);+ showToast(error.message || t('claims.document_delete_failed', 'Failed to remove document'), 'error');+ }+}++function createDocumentsSection(claim, canEdit) {+ const section = el('div', 'claim-documents');+ const header = el('div', 'claim-documents-header');+ const clip = el('i', 'fas fa-paperclip');+ header.appendChild(clip);+ const docs = Array.isArray(claim.documents) ? claim.documents : [];+ header.appendChild(document.createTextNode(' ' + t('claims.documents', 'Documents') + ` (${docs.length})`));+ section.appendChild(header);++ if (docs.length) {+ const list = el('div', 'claim-documents-list');+ docs.forEach((doc) => {+ const row = el('div', 'claim-document');+ const viewBtn = el('button', 'claim-doc-view');+ viewBtn.type = 'button';+ viewBtn.dataset.claimId = String(claim.id);+ viewBtn.dataset.docId = String(doc.id);+ const icon = el('i', doc.paperless_document_id ? 'fas fa-cloud' : 'fas fa-file-alt');+ viewBtn.appendChild(icon);+ viewBtn.appendChild(document.createTextNode(' ' + (doc.original_filename || 'Document')));+ row.appendChild(viewBtn);+ if (canEdit) {+ const delBtn = el('button', 'claim-doc-delete');+ delBtn.type = 'button';+ delBtn.title = t('actions.delete', 'Delete');+ delBtn.dataset.claimId = String(claim.id);+ delBtn.dataset.docId = String(doc.id);+ delBtn.appendChild(el('i', 'fas fa-times'));+ row.appendChild(delBtn);+ }+ list.appendChild(row);+ });+ section.appendChild(list);+ }++ if (canEdit) {+ const addRow = el('div', 'claim-documents-add');+ const storageSelect = el('select', 'claim-doc-storage');+ const optLocal = el('option', null, t('claims.storage_local', 'Upload file'));+ optLocal.value = 'local';+ const optPaperless = el('option', null, t('claims.storage_paperless', 'Upload to Paperless'));+ optPaperless.value = 'paperless';+ storageSelect.appendChild(optLocal);+ storageSelect.appendChild(optPaperless);+ const attachBtn = el('button', 'btn btn-sm btn-secondary claim-doc-attach');+ attachBtn.type = 'button';+ attachBtn.dataset.claimId = String(claim.id);+ attachBtn.appendChild(el('i', 'fas fa-paperclip'));+ attachBtn.appendChild(document.createTextNode(' ' + t('claims.attach_document', 'Attach document')));+ addRow.appendChild(storageSelect);+ addRow.appendChild(attachBtn);+ section.appendChild(addRow);+ }++ return section;+}+export function closeClaimsModal() {if (dom.claimsModal) dom.claimsModal.classList.remove('active');state.currentWarrantyId = null;@@ -512,6 +756,8 @@ function createClaimItem(claim, canEdit, formatDateFn) {item.appendChild(res);}+ item.appendChild(createDocumentsSection(claim, canEdit));+return item;}diff --git a/frontend/style.css b/frontend/style.cssindex 3704ba3..6681132 100644--- a/frontend/style.css+++ b/frontend/style.css@@ -5420,6 +5420,72 @@ html.dark-mode .warracker-footer a:hover {border-left: 4px solid var(--secondary-color);}+/* Claim documents (issue #148) */+.claim-documents {+ margin-top: 10px;+ padding: 10px;+ background: var(--light-gray);+ border-radius: 4px;+ font-size: 0.9rem;+}++.claim-documents-header {+ font-weight: 600;+ color: var(--text-color);+ margin-bottom: 6px;+}++.claim-documents-list {+ display: flex;+ flex-direction: column;+ gap: 4px;+}++.claim-document {+ display: flex;+ align-items: center;+ gap: 6px;+}++.claim-doc-view {+ background: none;+ border: none;+ padding: 2px 4px;+ color: var(--primary-color);+ cursor: pointer;+ font-size: 0.9rem;+ text-align: left;+}++.claim-doc-view:hover {+ text-decoration: underline;+}++.claim-doc-delete {+ background: none;+ border: none;+ padding: 2px 4px;+ color: var(--danger-color);+ cursor: pointer;+ font-size: 0.8rem;+}++.claim-documents-add {+ display: flex;+ align-items: center;+ gap: 8px;+ margin-top: 8px;+}++.claim-doc-storage {+ padding: 4px 6px;+ font-size: 0.85rem;+ border: 1px solid var(--border-color);+ border-radius: 4px;+ background: var(--card-bg);+ color: var(--text-color);+}+/* Status badges */.claim-status-badge {padding: 3px 8px;diff --git a/locales/en/translation.json b/locales/en/translation.jsonindex 7cdf44a..d216ce9 100644--- a/locales/en/translation.json+++ b/locales/en/translation.json@@ -766,7 +766,17 @@"resolved_label": "Resolved","status_unknown": "Unknown","unknown_vendor": "Unknown Vendor",- "view_only": "View Only"+ "view_only": "View Only",+ "documents": "Documents",+ "attach_document": "Attach document",+ "document_added": "Document attached",+ "document_deleted": "Document removed",+ "document_add_failed": "Failed to attach document",+ "document_delete_failed": "Failed to remove document",+ "confirm_delete_document": "Remove this document from the claim?",+ "storage_local": "Upload file",+ "storage_paperless": "Upload to Paperless",+ "document_open_failed": "Failed to open document"},"paperless": {"uploading_documents": "Uploading documents...",@@ -798,4 +808,4 @@"pick_color": "Pick color","create_with_name": "Create \"{{name}}\""}-}\ No newline at end of file+}