# Path: core/validation/validation.py
# class TSValidationError(Exception):
#     pass
# 
# def validate_request(collection, json_in):
#     validator(requests_schema[collection], format_checker=jsonschema.FormatChecker()).validate(json_in)
# 
# def sanitize_objectify_json(json_in):
#     """Sanitize string and convert _ids to ObjectId in JSON"""
#     return recursive_replace(json_in, _replace_function_sanitize_objectify_json)
# 
# def stringify_objectid_cursor(cursor_in):
#     """Convert ObjectId to string in JSON"""
#     
#     stringified = []
#     for json_in in cursor_in:
#         stringified.append(recursive_replace(json_in, _replace_function_stringify_objectid_json))
#     return stringified
# 
# Path: core/api/crud.py
# def get(collection, criteria_projection_order):
# def remove(collection, criterias = []):
# def add(collection, documents_list):
# def update(collection, document):
# 
# Path: core/validation/permissions.py
# def get_role_approval_step(group):
# 
#     # Approvation roles 
#     approvation_roles = [ s['approver'] if 'approver' in s else '' for s in conf_approval_flow ]
# 
#     # Administrator can see every expence, return 0
#     if group == 'administrator':
#         return 0
#     # Roles that can approves can see only expences >= owned step.
#     elif group in approvation_roles[1:-1]:
#         return approvation_roles.index(group)
#     # Else, return draft step 
#     else:
#         return len(approvation_roles)-1
# 
# def check_datamine_permissions(action, document):
#     # Get datamine permissions
#     
#     try:
#         restrictions = cherrypy.session['_ts_user']['restrictions'][action]
#     except (KeyError, TypeError):
#         restrictions = None
#         
#     if not restrictions:
#         raise TSValidationError("Access to '%s' is restricted for current user" % (action))
#     elif restrictions != True:
#         validator(restrictions, format_checker=jsonschema.FormatChecker()).validate(document)
# 
# Path: core/notifications/notifications.py
# def _get_recipients_of_expences_responsibles(expence_user_id, project_id, expence_id, expence_type, recipients_roles ):
# def notify_expence(project_expence, expence_type, approver):
# def get_pending():
# 
# Path: core/config.py



from core.validation.validation import TSValidationError, validate_request, sanitize_objectify_json, stringify_objectid_cursor
from core.api.crud import db
from bson.objectid import ObjectId
from core.validation.permissions import get_role_approval_step, check_datamine_permissions
from core.notifications import notifications
from core.config import schema 
import cherrypy, logging
    
    approval_result = {}
    
    # Status
    approval_result['status'] = found_expence[expence_type]['status']
    
    # Approver data
    approver_data = dict((key,value) for key, value in cherrypy.session['_ts_user'].iteritems() if key in ('username', 'name', 'surname', 'email'))
    
    # Notifications
    notifications_result = notifications.notify_expence(found_expence, expence_type, approver_data)
    if notifications_result:
        approval_result['notifications'] = notifications_result
    
    return approval_result


def search_approvals(criteria):
    
    """
    Search expences
    
    POST /data/search_approvals/
    
    Expects { 'projects_id' : [ ], 'user_id': string, 'type': trips|expences|any, 'status': toapprove|approved|rejected|any  }
    Returns { 'error' : string, 'records' : [] }
    """
    
    validate_request('search_approvals', criteria)
    sanified_criteria = sanitize_objectify_json(criteria)

# Path: core/validation/validation.py
# class TSValidationError(Exception):
#     pass
# 
# def validate_request(collection, json_in):
#     validator(requests_schema[collection], format_checker=jsonschema.FormatChecker()).validate(json_in)
# 
# def sanitize_objectify_json(json_in):
#     """Sanitize string and convert _ids to ObjectId in JSON"""
#     return recursive_replace(json_in, _replace_function_sanitize_objectify_json)
# 
# def stringify_objectid_cursor(cursor_in):
#     """Convert ObjectId to string in JSON"""
#     
#     stringified = []
#     for json_in in cursor_in:
#         stringified.append(recursive_replace(json_in, _replace_function_stringify_objectid_json))
#     return stringified
# 
# Path: core/api/crud.py
# def get(collection, criteria_projection_order):
# def remove(collection, criterias = []):
# def add(collection, documents_list):
# def update(collection, document):
# 
# Path: core/validation/permissions.py
# def get_role_approval_step(group):
# 
#     # Approvation roles 
#     approvation_roles = [ s['approver'] if 'approver' in s else '' for s in conf_approval_flow ]
# 
#     # Administrator can see every expence, return 0
#     if group == 'administrator':
#         return 0
#     # Roles that can approves can see only expences >= owned step.
#     elif group in approvation_roles[1:-1]:
#         return approvation_roles.index(group)
#     # Else, return draft step 
#     else:
#         return len(approvation_roles)-1
# 
# def check_datamine_permissions(action, document):
#     # Get datamine permissions
#     
#     try:
#         restrictions = cherrypy.session['_ts_user']['restrictions'][action]
#     except (KeyError, TypeError):
#         restrictions = None
#         
#     if not restrictions:
#         raise TSValidationError("Access to '%s' is restricted for current user" % (action))
#     elif restrictions != True:
#         validator(restrictions, format_checker=jsonschema.FormatChecker()).validate(document)
# 
# Path: core/notifications/notifications.py
# def _get_recipients_of_expences_responsibles(expence_user_id, project_id, expence_id, expence_type, recipients_roles ):
# def notify_expence(project_expence, expence_type, approver):
# def get_pending():
# 
# Path: core/config.py



# Path: core/api/approvals.py
from core.validation.validation import TSValidationError, validate_request, sanitize_objectify_json, stringify_objectid_cursor
from core.api.crud import db
from bson.objectid import ObjectId
from core.validation.permissions import get_role_approval_step, check_datamine_permissions
from core.notifications import notifications
from core.config import schema 
import cherrypy, logging

    
    approval_result = {}
    
    # Status
    approval_result['status'] = found_expence[expence_type]['status']
    
    # Approver data
    approver_data = dict((key,value) for key, value in cherrypy.session['_ts_user'].iteritems() if key in ('username', 'name', 'surname', 'email'))
    
    # Notifications
    notifications_result = notifications.notify_expence(found_expence, expence_type, approver_data)
    if notifications_result:
        approval_result['notifications'] = notifications_result
    
    return approval_result


def search_approvals(criteria):
    
    """
    Search expences
    
    POST /data/search_approvals/
    
    Expects { 'projects_id' : [ ], 'user_id': string, 'type': trips|expences|any, 'status': toapprove|approved|rejected|any  }
    Returns { 'error' : string, 'records' : [] }
    """
    
    validate_request('search_approvals', criteria)
    sanified_criteria = sanitize_objectify_json(criteria)

    check_datamine_permissions('search_approvals', sanified_criteria)