function complete_user_training
Marks a user's training as complete for a specific controlled document, validating quiz requirements and setting expiration dates.
/tf/active/vicechatdev/CDocs/controllers/training_controller.py
262 - 346
complex
Purpose
This function handles the completion of mandatory training for controlled documents in a document management system. It verifies that the document exists, checks if training is required, validates quiz completion if necessary, updates the user's training status with an expiration date, logs the completion event to an audit trail, and notifies the document owner. It enforces business rules around training requirements and quiz passing before allowing completion.
Source Code
def complete_user_training(
user: DocUser,
document_uid: str,
quiz_passed: bool = True
) -> Dict[str, Any]:
"""
Mark user training as complete.
Args:
user: User completing training
document_uid: UID of document
quiz_passed: Whether user passed quiz (if required)
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}")
# Get training configuration
doc_training = DocumentTraining(document_uid=document_uid)
if not doc_training._data.get("training_required", False):
raise BusinessRuleError("Training is not required for this document")
# Check if quiz is required and passed
if doc_training._data.get("quiz_required", False) and not quiz_passed:
raise BusinessRuleError("Quiz must be passed to complete training")
# Get user training status
user_training = UserTraining(user.uid, document_uid)
if not user_training._data:
raise BusinessRuleError("User is not assigned to training for this document")
# Mark as trained
validity_days = doc_training._data.get("validity_days", 365)
success = user_training.mark_trained(validity_days)
if not success:
raise BusinessRuleError("Failed to mark training as complete")
# Log event
audit_trail.log_event(
event_type="TRAINING_COMPLETED",
user=user,
resource_uid=document_uid,
resource_type="ControlledDocument",
details={
"doc_number": document.doc_number,
"quiz_passed": quiz_passed,
"validity_days": validity_days
}
)
# Notify document owner
if document.owner_uid and document.owner_uid != user.uid:
notifications.send_notification(
notification_type="TRAINING_COMPLETED",
users=[document.owner_uid],
resource_uid=document_uid,
resource_type="ControlledDocument",
message=f"{user.name} completed training for {document.doc_number}",
details={
"document_uid": document_uid,
"doc_number": document.doc_number,
"title": document.title,
"trained_user": user.name
},
send_email=True,
email_template="training_completed"
)
return {
"success": True,
"message": "Training completed successfully",
"expires_on": user_training._data.get("expires_on")
}
except (ResourceNotFoundError, ValidationError, BusinessRuleError) as e:
raise
except Exception as e:
logger.error(f"Error completing training: {e}")
raise BusinessRuleError(f"Failed to complete training: {e}")
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
user |
DocUser | - | positional_or_keyword |
document_uid |
str | - | positional_or_keyword |
quiz_passed |
bool | True | positional_or_keyword |
Parameter Details
user: DocUser object representing the user completing the training. Must be a valid user instance with a uid attribute for identification and a name attribute for notifications.
document_uid: String containing the unique identifier (UID) of the controlled document for which training is being completed. Must correspond to an existing ControlledDocument in the system.
quiz_passed: Boolean flag indicating whether the user passed the required quiz (default: True). If the document's training configuration requires a quiz, this must be True for training to be marked complete. Set to False only when quiz is not required or to explicitly fail the completion.
Return Value
Type: Dict[str, Any]
Returns a dictionary with three keys: 'success' (boolean indicating operation success), 'message' (string with human-readable status message), and 'expires_on' (datetime or string indicating when the training certification expires based on the document's validity_days configuration). On error, raises one of several exception types instead of returning.
Dependencies
CDocs.configCDocs.models.documentCDocs.models.user_extensionsCDocs.models.trainingCDocs.utilsCDocs.dbCDocs.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, UserTraining
from CDocs.utils import audit_trail, notifications
from CDocs.controllers import log_controller_action, transaction, ResourceNotFoundError, ValidationError, BusinessRuleError
import logging
Usage Example
from CDocs.models.user_extensions import DocUser
from CDocs.controllers.training_controller import complete_user_training
# Get the user who completed training
user = DocUser(uid='user_123')
# Document UID for which training was completed
document_uid = 'doc_456'
# Complete training with quiz passed
try:
result = complete_user_training(
user=user,
document_uid=document_uid,
quiz_passed=True
)
print(f"Training completed: {result['message']}")
print(f"Expires on: {result['expires_on']}")
except ResourceNotFoundError as e:
print(f"Document not found: {e}")
except BusinessRuleError as e:
print(f"Business rule violation: {e}")
# Complete training when quiz is not required
result = complete_user_training(
user=user,
document_uid=document_uid
# quiz_passed defaults to True
)
Best Practices
- Always wrap calls to this function in try-except blocks to handle ResourceNotFoundError, ValidationError, and BusinessRuleError exceptions
- Ensure the user is properly assigned to training for the document before calling this function (check UserTraining assignment first)
- The function is decorated with @transaction, so database operations will be rolled back on error - no need for manual rollback
- The function is decorated with @log_controller_action, so all calls are automatically logged
- Set quiz_passed=False only when intentionally testing failure scenarios, as it will raise BusinessRuleError if quiz is required
- The document owner will receive an email notification unless they are the same user completing the training
- Training expiration is automatically calculated based on the document's validity_days configuration (defaults to 365 days)
- Audit trail events are logged with type 'TRAINING_COMPLETED' for compliance tracking
- Verify that email templates and notification infrastructure are properly configured before deploying to production
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function complete_user_training_by_uid 89.5% similar
-
function enable_document_training 81.9% similar
-
function disable_document_training 75.1% similar
-
function get_document_training_info 72.0% similar
-
function reset_document_training 71.6% similar