"""Users logic.""" import logging from models import ows_users from utils import document as document_utils import util # noqa def prepare_docs(event): """Construct Cloudsearch documents for the user corpus. Args: event (dict): event with user data from Maxwell's Returns: list: cloudsearch documents ready for upload """ json_docs = [] item = {} event_type = event.get('type') if not event_type or event.get('_metadata'): logging.warning( 'An event with incompatible format received: %s', event) return json_docs if event_type == 'delete' and event.get('table') != 'vend_contact': doc_type = 'add' event_type = 'insert' if event_type != 'delete': doc_type = 'add' table_id_mapping = { 'vend_contact': 'id', 'contact': 'contact_id', 'subaccount': 'subaccount_id', 'vend_contact_roles': 'vend_contact_id', } table_url_param_mapping = { 'vend_contact': 'user_id', 'contact': 'contact_id', 'subaccount': 'subaccount_id', 'vend_contact_roles': 'user_id', } json_docs = ows_users.get_user_document( table_url_param_mapping[event.get('table')], event['data'][table_id_mapping[event.get('table')]]) all_documents = [] for item in json_docs: single_document = prepare_single_doc(doc_type, item['user_id'], item) all_documents.append(single_document) return all_documents doc_type = 'delete' return [prepare_single_doc(doc_type, event['data']['id'], item)] def prepare_single_doc(doc_type, user_id, item): """Construct Cloudsearch document for the user corpus. Args: doc_type (string): type of doc to upload user_id (int): id of the doc to upload item (dict): data in document to upload Returns: dict: cloudsearch document ready for upload """ return document_utils.prepare_for_upload( util.parse_spec_file('users'), { 'type': doc_type, 'id': f'user{user_id}', 'fields': item})