🔍 Code Extractor

function reset_document_training

Maturity: 58

Resets all training records for a specific controlled document, typically used when a document is republished or updated, requiring users to retrain.

File:
/tf/active/vicechatdev/CDocs/controllers/training_controller.py
Lines:
622 - 697
Complexity:
moderate

Purpose

This function manages the reset of training requirements for a controlled document. It verifies document existence, checks user permissions (only document owner or users with MANAGE_ALL_TRAINING can reset), clears all training records, logs the action in the audit trail, and notifies all affected users via email. This is critical in quality management systems where document changes require re-certification of trained personnel.

Source Code

def reset_document_training(
    user: DocUser,
    document_uid: str
) -> Dict[str, Any]:
    """
    Reset all training for a document (used when document is republished).
    
    Args:
        user: User performing reset
        document_uid: UID of document
        
    Returns:
        Dictionary with operation status
    """
    try:
        # Verify document exists
        document = ControlledDocument(uid=document_uid)
        if not document:
            raise ResourceNotFoundError(f"Document not found: {document_uid}")
        
        # Check permissions
        if (document.owner_uid != user.uid and 
            not permissions.user_has_permission(user, "MANAGE_ALL_TRAINING")):
            raise PermissionError("Only document owner can reset training")
        
        # Reset training
        doc_training = DocumentTraining(document_uid=document_uid)
        success = doc_training.reset_all_training()
        
        if not success:
            raise BusinessRuleError("Failed to reset training")
        
        # Get affected users for notifications
        assigned_users = doc_training.get_assigned_users()
        
        # Log event
        audit_trail.log_event(
            event_type="TRAINING_RESET",
            user=user,
            resource_uid=document_uid,
            resource_type="ControlledDocument",
            details={
                "doc_number": document.doc_number,
                "affected_users": len(assigned_users)
            }
        )
        
        # Notify affected users
        for user_data in assigned_users:
            notifications.send_notification(
                notification_type="TRAINING_RESET",
                users=[user_data["user_uid"]],
                resource_uid=document_uid,
                resource_type="ControlledDocument",
                message=f"Training requirement reset for document {document.doc_number}",
                details={
                    "document_uid": document_uid,
                    "doc_number": document.doc_number,
                    "title": document.title,
                    "reset_by": user.name
                },
                send_email=True,
                email_template="training_reset"
            )
        
        return {
            "success": True,
            "message": f"Training reset for {len(assigned_users)} user(s)",
            "affected_users": len(assigned_users)
        }
        
    except (ResourceNotFoundError, PermissionError, BusinessRuleError) as e:
        raise
    except Exception as e:
        logger.error(f"Error resetting training: {e}")
        raise BusinessRuleError(f"Failed to reset training: {e}")

Parameters

Name Type Default Kind
user DocUser - positional_or_keyword
document_uid str - positional_or_keyword

Parameter Details

user: DocUser object representing the user performing the reset operation. Must be either the document owner or have MANAGE_ALL_TRAINING permission. Used for permission checks, audit logging, and notification attribution.

document_uid: String containing the unique identifier (UID) of the controlled document whose training records should be reset. Must correspond to an existing ControlledDocument in the system.

Return Value

Type: Dict[str, Any]

Returns a dictionary with three keys: 'success' (boolean, always True if no exception raised), 'message' (string describing the operation result including number of affected users), and 'affected_users' (integer count of users whose training was reset). Raises ResourceNotFoundError if document doesn't exist, PermissionError if user lacks authorization, or BusinessRuleError if reset operation fails.

Dependencies

  • typing
  • datetime
  • logging
  • traceback
  • CDocs.config
  • CDocs.models.document
  • CDocs.models.user_extensions
  • CDocs.models.training
  • CDocs.utils
  • CDocs.db
  • CDocs.controllers

Required Imports

from typing import Dict, Any
from CDocs.models.user_extensions import DocUser
from CDocs.models.document import ControlledDocument
from CDocs.models.training import DocumentTraining
from CDocs.config import permissions
from CDocs.utils import audit_trail, notifications
from CDocs.controllers import log_controller_action, require_permission, transaction
from CDocs.controllers import PermissionError, ResourceNotFoundError, BusinessRuleError
import logging

Usage Example

from CDocs.models.user_extensions import DocUser
from CDocs.controllers.training_controller import reset_document_training

# Assume user and document_uid are already obtained
current_user = DocUser(uid='user123')
document_id = 'DOC-2024-001'

try:
    result = reset_document_training(
        user=current_user,
        document_uid=document_id
    )
    print(f"Success: {result['message']}")
    print(f"Affected users: {result['affected_users']}")
except ResourceNotFoundError as e:
    print(f"Document not found: {e}")
except PermissionError as e:
    print(f"Permission denied: {e}")
except BusinessRuleError as e:
    print(f"Operation failed: {e}")

Best Practices

  • This function is decorated with @transaction, so it runs within a database transaction that will rollback on any exception
  • Always handle the three specific exception types (ResourceNotFoundError, PermissionError, BusinessRuleError) separately for proper error reporting
  • The function requires 'MANAGE_TRAINING' permission via decorator, but also checks for document ownership or 'MANAGE_ALL_TRAINING' permission internally
  • Email notifications are sent to all affected users, so ensure email system is properly configured before use
  • The function logs audit events automatically, making it suitable for regulated environments requiring compliance tracking
  • Use this function only when document content changes significantly enough to require retraining (e.g., republishing, major revisions)
  • The operation affects all users assigned to the document's training, so communicate with stakeholders before executing
  • Consider the impact on training completion metrics and reporting before resetting training records

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function disable_document_training 80.5% similar

    Disables the training requirement for a specific controlled document, verifying user permissions and logging the action to the audit trail.

    From: /tf/active/vicechatdev/CDocs/controllers/training_controller.py
  • function enable_document_training 73.3% similar

    Enables training requirements for a controlled document, setting validity period, quiz requirements, and instructions for users who need to complete training on the document.

    From: /tf/active/vicechatdev/CDocs/controllers/training_controller.py
  • function complete_user_training 71.6% similar

    Marks a user's training as complete for a specific controlled document, validating quiz requirements and setting expiration dates.

    From: /tf/active/vicechatdev/CDocs/controllers/training_controller.py
  • function get_document_training_info 70.6% similar

    Retrieves comprehensive training information for a specific controlled document, including training configuration, assigned users, completion status, and statistics.

    From: /tf/active/vicechatdev/CDocs/controllers/training_controller.py
  • function get_document_training_assignments 70.3% similar

    Retrieves training assignments and configuration for a specific controlled document, including assigned users and training requirements.

    From: /tf/active/vicechatdev/CDocs/controllers/training_controller.py
← Back to Browse