🔍 Code Extractor

function get_all_documents

Maturity: 53

Retrieves all controlled documents from a Neo4j graph database with their associated owner information, formatted for administrative management interfaces.

File:
/tf/active/vicechatdev/CDocs/controllers/admin_controller.py
Lines:
574 - 605
Complexity:
moderate

Purpose

This function queries a Neo4j database to fetch controlled documents along with their ownership details. It's designed for administrative dashboards or management interfaces where a comprehensive view of all documents is needed. The function handles various property name variations (case differences) and provides fallback values for missing data, ensuring robust data retrieval even with inconsistent database schemas. Results are ordered by modification date (most recent first) and limited to prevent overwhelming responses.

Source Code

def get_all_documents(limit: int = 100) -> List[Dict[str, Any]]:
    """Get all documents for admin management."""
    try:
        query = """
        MATCH (d:ControlledDocument)
        OPTIONAL MATCH (d)-[:OWNED_BY]->(u:DocUser)
        RETURN d, u.name as owner_name
        ORDER BY d.modifiedDate DESC
        LIMIT $limit
        """
        
        results = db.run_query(query, {'limit': limit})
        documents = []
        
        for record in results:
            doc_data = record['d']
            documents.append({
                'uid': doc_data.get('UID') or doc_data.get('uid'),  # Try both cases
                'title': doc_data.get('title') or 'Untitled',
                'type': doc_data.get('documentType') or doc_data.get('type') or 'Document',
                'status': doc_data.get('documentStatus') or doc_data.get('status') or 'draft',
                'version': doc_data.get('version') or '1.0',
                'ownerName': record.get('owner_name') or 'Unknown',
                'modifiedDate': doc_data.get('lastModifiedDate') or doc_data.get('modifiedDate') or 'Unknown',
                'createdDate': doc_data.get('createdDate') or 'Unknown'
            })
        
        return documents
        
    except Exception as e:
        logger.error(f"Error getting all documents: {e}")
        return []

Parameters

Name Type Default Kind
limit int 100 positional_or_keyword

Parameter Details

limit: Maximum number of documents to retrieve from the database. Defaults to 100. This parameter helps control query performance and response size. Should be a positive integer. Higher values may impact performance on large document collections.

Return Value

Type: List[Dict[str, Any]]

Returns a List of dictionaries, where each dictionary represents a document with standardized keys: 'uid' (unique identifier), 'title' (document name), 'type' (document category), 'status' (workflow state like 'draft'), 'version' (version number), 'ownerName' (name of document owner), 'modifiedDate' (last modification timestamp), and 'createdDate' (creation timestamp). Returns an empty list if an error occurs or no documents are found. All fields include fallback values to handle missing data gracefully.

Dependencies

  • logging
  • typing
  • CDocs.db
  • CDocs.models.document
  • CDocs.models.user_extensions
  • CDocs.db.schema_manager
  • CDocs.config

Required Imports

import logging
from typing import Dict, List, Any
from CDocs import db
from CDocs.models.document import ControlledDocument
from CDocs.models.user_extensions import DocUser

Usage Example

from typing import Dict, List, Any
from CDocs import db
import logging

logger = logging.getLogger(__name__)

# Get default 100 documents
documents = get_all_documents()
for doc in documents:
    print(f"Document: {doc['title']} (UID: {doc['uid']})")
    print(f"  Owner: {doc['ownerName']}")
    print(f"  Status: {doc['status']} v{doc['version']}")
    print(f"  Modified: {doc['modifiedDate']}")

# Get limited set of documents
recent_docs = get_all_documents(limit=10)
print(f"Retrieved {len(recent_docs)} most recent documents")

# Handle empty results
if not documents:
    print("No documents found or error occurred")

Best Practices

  • Always handle the empty list return case, as it indicates either no documents or an error condition
  • Check logs for error details when an empty list is returned unexpectedly
  • Use appropriate limit values based on your UI pagination needs to avoid performance issues
  • The function handles property name variations (case differences), but ensure your database schema is consistent for best performance
  • Consider implementing pagination in the calling code if dealing with large document collections
  • The function returns 'Unknown' for missing owner names and dates - handle these sentinel values appropriately in UI
  • Results are ordered by modification date DESC, so most recently modified documents appear first
  • The function uses OPTIONAL MATCH for owner relationships, so documents without owners are still returned

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_documents 79.2% similar

    Retrieves controlled documents from a Neo4j database with comprehensive filtering, permission-based access control, pagination, and full-text search capabilities.

    From: /tf/active/vicechatdev/CDocs/controllers/document_controller.py
  • function get_documents_v1 76.7% similar

    Retrieves filtered and paginated documents from a Neo4j graph database with permission-based access control, supporting multiple filter criteria and search functionality.

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function get_document_stats 71.6% similar

    Retrieves aggregated statistics about controlled documents from a Neo4j database, including status and type distributions for visualization in charts.

    From: /tf/active/vicechatdev/CDocs/controllers/admin_controller.py
  • function search_documents_v1 71.0% similar

    Searches for controlled documents in a Neo4j graph database based on multiple optional filter criteria including text query, document type, department, status, and owner.

    From: /tf/active/vicechatdev/CDocs/controllers/document_controller.py
  • function get_document_with_relationships 68.0% similar

    Retrieves a complete document from Neo4j graph database along with all its related entities including versions, reviews, approvals, and authors.

    From: /tf/active/vicechatdev/CDocs/db/db_operations.py
← Back to Browse