🔍 Code Extractor

function get_document_types

Maturity: 54

Retrieves document type configurations from application settings, optionally filtering by a specific type code, and returns them as a list of dictionaries with detailed metadata.

File:
/tf/active/vicechatdev/CDocs/controllers/admin_controller.py
Lines:
393 - 429
Complexity:
simple

Purpose

This function serves as a centralized accessor for document type configurations in a document management system. It reads from settings.DOCUMENT_TYPES and settings.DOCUMENT_CONFIG to compile comprehensive information about each document type, including naming conventions, approval requirements, retention policies, and templates. It's designed to support document creation workflows, UI dropdowns, and administrative interfaces where document type information is needed.

Source Code

def get_document_types(type_code: Optional[str] = None) -> List[Dict[str, Any]]:
    """
    Get document types from settings.
    
    Args:
        type_code: Optional code to filter by specific document type
        
    Returns:
        List of dictionaries with document type information
    """
    doc_types = []
    
    try:
        for name, code in settings.DOCUMENT_TYPES.items():
            # If type_code specified, only return that specific type
            if type_code and code != type_code:
                continue
                
            config = settings.DOCUMENT_CONFIG.get(code, {})
            
            doc_types.append({
                'uid': code,  # Use code as UID
                'code': code,
                'name': name,
                'description': f'{name} document type',
                'prefix': config.get('prefix', code),
                'numbering_format': config.get('numbering_format', '{prefix}-{dept}-{number:03d}'),
                'requires_training': config.get('requires_training', False),
                'retention_years': config.get('retention_years', 5),
                'approval_levels': config.get('approval_levels', 1),
                'template': config.get('template')
            })
            
        return doc_types
    except Exception as e:
        logger.error(f"Error getting document types: {e}")
        return []

Parameters

Name Type Default Kind
type_code Optional[str] None positional_or_keyword

Parameter Details

type_code: Optional string parameter to filter results to a single document type. When provided, only the document type matching this code will be returned. When None (default), all available document types are returned. Expected to match a code value from settings.DOCUMENT_TYPES.

Return Value

Type: List[Dict[str, Any]]

Returns a List[Dict[str, Any]] where each dictionary represents a document type with the following keys: 'uid' (unique identifier, same as code), 'code' (document type code), 'name' (human-readable name), 'description' (auto-generated description), 'prefix' (document numbering prefix), 'numbering_format' (format string for document numbers), 'requires_training' (boolean indicating if training is required), 'retention_years' (integer for retention policy), 'approval_levels' (integer for approval workflow depth), and 'template' (optional template reference). Returns an empty list if an error occurs or no matching types are found.

Dependencies

  • logging
  • typing

Required Imports

from typing import Optional, List, Dict, Any
import logging
from CDocs.config import settings

Usage Example

# Get all document types
all_types = get_document_types()
for doc_type in all_types:
    print(f"{doc_type['name']}: {doc_type['code']}")

# Get a specific document type
sop_types = get_document_types(type_code='SOP')
if sop_types:
    sop = sop_types[0]
    print(f"SOP prefix: {sop['prefix']}")
    print(f"Requires training: {sop['requires_training']}")
    print(f"Retention: {sop['retention_years']} years")

# Example settings configuration needed:
# settings.DOCUMENT_TYPES = {
#     'Standard Operating Procedure': 'SOP',
#     'Work Instruction': 'WI'
# }
# settings.DOCUMENT_CONFIG = {
#     'SOP': {
#         'prefix': 'SOP',
#         'numbering_format': '{prefix}-{dept}-{number:03d}',
#         'requires_training': True,
#         'retention_years': 10,
#         'approval_levels': 2,
#         'template': 'sop_template.docx'
#     }
# }

Best Practices

  • Ensure settings.DOCUMENT_TYPES and settings.DOCUMENT_CONFIG are properly configured before calling this function
  • The function returns an empty list on error, so always check if the returned list is non-empty before accessing elements
  • When filtering by type_code, the function returns a list (not a single item), so use indexing or iteration to access the result
  • The function provides default values for missing configuration keys (e.g., retention_years defaults to 5), but it's better to explicitly define all configuration values in settings
  • Consider caching the results if this function is called frequently, as it iterates through settings on each call
  • The 'uid' and 'code' fields are identical by design; use 'uid' for database operations and 'code' for business logic
  • Monitor logs for errors as exceptions are caught and logged but return an empty list, which may mask configuration issues

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_document_type 78.4% similar

    Retrieves configuration details for a specific document type by looking it up in DOCUMENT_CONFIG or DOCUMENT_TYPES, returning a dictionary with document metadata or an empty dict if not found.

    From: /tf/active/vicechatdev/CDocs/settings_prod.py
  • function get_document_type_code 67.5% similar

    Retrieves a document type code from a dictionary lookup using the provided document type name, returning the name itself if no mapping exists.

    From: /tf/active/vicechatdev/CDocs/settings_prod.py
  • function get_document_type_name 65.7% similar

    Looks up and returns the full document type name corresponding to a given document type code by searching through a DOCUMENT_TYPES dictionary.

    From: /tf/active/vicechatdev/CDocs/settings_prod.py
  • function generate_document_number_v1 50.2% similar

    Generates a unique document number by combining document type code, department code, and using a settings-based generation function, with UUID fallback on error.

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function get_documents 49.8% 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
← Back to Browse