from __future__ import annotations import datetime from typing import Dict, List, Optional, Set, Union from pydantic import BaseModel, EmailStr, Field, PrivateAttr, ValidationError, validator from app.db_sql import get_account_id_w_for_type_id, redis_lookup_id_random, sql_enable_part, sql_insert, sql_limit_offset_part, sql_select, sql_update from app.lib_general import log, logging, logger_reset from app.methods.address_methods import create_address_obj, create_update_address_obj, create_update_address_obj_v4, update_address_obj from app.models.common_field_schema import default_num_bytes from app.models.contact_models import Contact_Base # ### BEGIN ### API Contact Methods ### load_contact_obj() ### @logger_reset def load_contact_obj( contact_id: int|str, enabled: str = 'enabled', # enabled, disabled, all limit: int = 100, offset: int = 0, by_alias: bool = True, exclude_unset: bool = True, model_as_dict: bool = False, inc_address: bool = False ) -> Contact_Base|dict|bool: log.setLevel(logging.WARNING) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL log.debug(locals()) if contact_id := redis_lookup_id_random(record_id_random=contact_id, table_name='contact'): pass else: return False if contact_rec := sql_select(table_name='v_contact', record_id=contact_id): pass else: return False try: contact_obj = Contact_Base(**contact_rec) log.debug(contact_obj) except ValidationError as e: log.error(e.json()) return False if inc_address: log.info('Need to include address data...') # NOTE: The address_id field needs to be removed from the contact table. # NOTE: This is not ideal and the view needs to be updated when possible and anything currently pointing to the original contact.address_id needs to be fixed. if address_id := contact_rec.get('address_id', None): pass # WARNING elif address_id := contact_rec.get('linked_address_id', None): pass # WARNING else: pass # WARNING # address_id = contact_rec.get('address_id', None) log.debug(address_id) from app.methods.address_methods import load_address_obj if address_result := load_address_obj( address_id = address_id, by_alias = by_alias, exclude_unset = exclude_unset, model_as_dict = model_as_dict, ): contact_obj.address = address_result else: contact_obj.address = {} # None if model_as_dict: return contact_obj.dict(by_alias=by_alias, exclude_unset=exclude_unset) # pylint: disable=no-member else: return contact_obj # ### END ### API Contact Methods ### load_contact_obj() ### # ### BEGIN ### API Contact Methods ### get_contact_rec_list() ### # Updated 2022-01-07 @logger_reset def get_contact_rec_list( for_type: str, # 'account' is a special case for_id: str, enabled: str = 'enabled', # enabled, disabled, all limit: int = 500, offset: int = 0, ) -> list|bool: log.setLevel(logging.WARNING) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL log.debug(locals()) if for_id := redis_lookup_id_random(record_id_random=for_id, table_name=for_type): pass else: return False if for_type == 'account': sql_for_type_id = f'`contact`.account_id = :for_id' else: sql_for_type_id = f'`contact`.for_type = :for_type AND `contact`.for_id = :for_id' data = {} data['for_type'] = for_type data['for_id'] = for_id sql_enabled, data['enable'] = sql_enable_part(table_name='contact', enabled=enabled) # Reasonably safe return str and bool sql_limit = sql_limit_offset_part(limit=limit, offset=offset) # Reasonably safe return str sql = f""" SELECT `contact`.id AS 'contact_id', `contact`.id_random AS 'contact_id_random' FROM `contact` AS `contact` WHERE {sql_for_type_id} {sql_enabled} ORDER BY `contact`.created_on DESC, `contact`.updated_on DESC {sql_limit}; """ log.debug(sql) if contact_rec_li_result := sql_select(data=data, sql=sql, as_list=True): contact_rec_li = contact_rec_li_result else: # [] or False contact_rec_li = contact_rec_li_result log.debug(contact_rec_li_result) return contact_rec_li # ### END ### API Contact Methods ### get_contact_rec_list() ### # ### BEGIN ### API Contact Methods ### get_account_id_w_contact_id() ### # Updated 2021-08-24 @logger_reset def get_account_id_w_contact_id( contact_id: int|str, ) -> bool|int|None: log.setLevel(logging.WARNING) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL log.debug(locals()) if contact_id := redis_lookup_id_random(record_id_random=contact_id, table_name='contact'): pass else: return False data = {} data['contact_id'] = contact_id sql = f""" SELECT `contact`.id AS 'contact_id', `contact`.id_random AS 'contact_id_random', `contact`.account_id AS account_id FROM `contact` AS `contact` WHERE `contact`.id = :contact_id LIMIT 1; """ if contact_data_result := sql_select(data=data, sql=sql): log.debug(contact_data_result) if account_id := contact_data_result.get('account_id', None): return account_id else: return False else: return None # ### END ### API Contact Methods ### get_account_id_w_contact_id() ### # ### BEGIN ### API Contact Methods ### create_update_contact_obj_v4() ### # NOTE: This will create or update a contact. # Rewrite and updated 2021-08-25 @logger_reset def create_update_contact_obj_v4( contact_dict_obj: Contact_Base|dict, contact_id: int|str = None, account_id: int|str = None, for_type: str = None, for_id: int|str = None, create_sub_obj: bool = False, fail_any: bool = False, # Fail if any thing goes wrong for sub objects return_outline: bool = False, ) -> int|bool: log.setLevel(logging.WARNING) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL log.debug(locals()) log.info('Checking requirements...') if contact_id: log.info(f'Contact ID passed. Update existing Contact. Contact ID: {contact_id}') if contact_id := redis_lookup_id_random(record_id_random=contact_id, table_name='contact'): pass else: log.error('Contact ID passed but is invalid. Failed requirement.') return False if account_id := redis_lookup_id_random(record_id_random=account_id, table_name='account'): pass else: log.error('Missing or invalid Account ID passed. Not required. Ignoring.') log.info(f'Account ID: {account_id}') log.info('Attempting to get Account ID from related object.') if account_id := get_account_id_w_for_type_id(for_type='contact', for_id=contact_id): pass else: log.error('Unable to get Account ID from related object.') False if for_id := redis_lookup_id_random(record_id_random=for_id, table_name=for_type): pass else: log.error('Missing or invalid For Type and For ID passed. Not required. Ignoring.') log.info(f'For Type: {for_type} and For ID: {for_id}') else: log.info('No Contact ID passed. Create new Contact. Required: Account ID, For Type, For ID') if for_id := redis_lookup_id_random(record_id_random=for_id, table_name=for_type): pass else: log.error('Missing or invalid For Type and For ID passed. Failed requirement.') log.info(f'For Type: {for_type} and For ID: {for_id}') return False if account_id := redis_lookup_id_random(record_id_random=account_id, table_name='account'): pass else: log.error('Missing or invalid Account ID passed. Failed requirement.') log.info(f'Account ID: {account_id}') if for_type and for_id: log.info('Attempting to get Account ID from related object.') if account_id := get_account_id_w_for_type_id(for_type=for_type, for_id=for_id): pass else: log.error('Unable to get Account ID from related object.') False else: return False log.debug(type(contact_dict_obj)) if isinstance(contact_dict_obj, dict): contact_dict = contact_dict_obj if contact_id: contact_dict['contact_id'] = contact_id if account_id: contact_dict['account_id'] = account_id if for_type: contact_dict['for_type'] = for_type if for_id: contact_dict['for_id'] = for_id try: contact_obj = Contact_Base(**contact_dict) log.setLevel(logging.INFO) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL log.debug(contact_obj) except ValidationError as e: log.error(e.json()) return False else: contact_obj = contact_dict_obj if contact_id: # NOTE: Can't update the ID alias if it was never set. contact_obj.id = contact_id if account_id: contact_obj.account_id = account_id if for_type: contact_obj.for_type = for_type if for_id: contact_obj.for_id = for_id contact_dict = contact_obj.dict(by_alias=False, exclude_defaults=False, exclude_unset=True, exclude={'address', 'created_on', 'updated_on'}) if contact_id: if contact_dict_up_result := sql_update(data=contact_dict, table_name='contact', rm_id_random=True): pass else: log.warning(f'Contact not updated. Contact ID: {contact_id}') log.debug(contact_dict_up_result) return False log.debug(contact_dict_up_result) else: if contact_dict_in_result := sql_insert(data=contact_dict, table_name='contact', rm_id_random=True, id_random_length=8): pass else: log.warning(f'Contact not created.') log.debug(contact_dict_in_result) return False log.debug(contact_dict_in_result) contact_id = contact_dict_in_result contact_outline = {} contact_outline['contact_id'] = contact_id # NOTE: Use object model version because of better type checking and validations if contact_obj.address: contact_outline['address_id'] = None address_obj = contact_obj.address if address_id := contact_obj.address_id: pass elif address_id := address_obj.id: pass else: address_id = None address_obj.id address_obj.for_type = 'contact' address_obj.for_id = contact_id create_update_address_obj_result = create_update_address_obj_v4( address_dict_obj = address_obj, address_id = address_id, account_id = account_id, for_type = 'contact', for_id = contact_id, fail_any = fail_any, return_outline = return_outline, ) if isinstance(create_update_address_obj_result, int): address_id = create_update_address_obj_result elif create_update_address_obj_result == True: pass else: log.warning(f'Create or Update failed while trying create_update_address_obj_v4(): {create_update_address_obj_result}') address_id = None contact_outline['address_id'] = address_id if return_outline: log.debug(f'Returning the Contact Outline: {contact_outline}') return contact_outline else: log.debug(f'Returning the Contact ID: {contact_id}') return contact_id # ### END ### API Contact Methods ### create_update_contact_obj_v4() ### # ### BEGIN ### API Contact Methods ### create_contact_obj() ### # NOTE: This will create a contact and then also create a linked address if contact_obj.address data is passed. # NOTE: In the future it should be required that account_id, for_type, and for_id should be passed separately. account_id might not be required *if* it can be looked up based on for_type and for_id. # Updated 2022-01-06 @logger_reset def create_contact_obj( account_id: int|str, contact_dict_obj: Contact_Base, for_type: str = None, for_id: int|str = None, address_id: int = None, create_sub_obj: bool = False, fail_any: bool = False, # Fail if any thing goes wrong for sub objects log_lvl: int = logging.WARNING, # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL ) -> int|bool: log.setLevel(log_lvl) # ### SECTION ### Secondary data validation # NOTE: Remove at future date. Is this check needed if we trust that the ID is checked ahead of time? if account_id := redis_lookup_id_random(record_id_random=account_id, table_name='account'): pass else: return False if for_id := redis_lookup_id_random(record_id_random=for_id, table_name=for_type): pass else: return False if address_id := redis_lookup_id_random(record_id_random=address_id, table_name='address'): pass elif address_id is None: pass else: return False log.info('Create dictionary or Pydantic object') log.debug(type(contact_dict_obj)) if isinstance(contact_dict_obj, dict): contact_dict = contact_dict_obj try: contact_obj = Contact_Base(**contact_dict) log.debug(contact_obj) except ValidationError as e: log.error(e.json()) return False else: contact_obj = contact_dict_obj contact_obj.account_id = account_id contact_dict = contact_obj.dict(by_alias=False, exclude_defaults=False, exclude_unset=True, exclude={'address', 'address_id', 'address_id_random', 'created_on', 'updated_on'}) # ### SECTION ### Process data # Look for an account_id in the contact_obj if account_id: pass elif account_id := contact_obj.account_id: pass contact_obj.account_id = account_id contact_dict['account_id'] = account_id contact_obj.for_type = for_type contact_obj.for_id = for_id contact_dict['for_type'] = for_type contact_dict['for_id'] = for_id # Look for an address_id in the contact_obj if one was not passed separately if address_id: pass # elif address_id := contact_obj.address.id: pass if contact_dict_in_result := sql_insert( data = contact_dict, table_name = 'contact', rm_id_random = True, id_random_length = default_num_bytes ): pass else: return False log.debug(contact_dict_in_result) contact_id = contact_dict_in_result if address_id and contact_obj.address: log.info('Updating Address object') if address_update_result := update_address_obj( address_id = address_id, address_dict_obj = contact_obj.address, for_type = 'contact', for_id = contact_id, ): pass else: return False elif contact_obj.address: log.info('Creating Address object') if address_create_result := create_address_obj( account_id = account_id, address_dict_obj = contact_obj.address, for_type = 'contact', for_id = contact_id, ): pass else: return False else: pass # if contact_obj.address: # address_obj_new = contact_obj.address # address_obj_new.for_type = 'contact' # address_obj_new.for_id = contact_id # create_address_obj_result = create_address_obj( # address_obj_new = address_obj_new, # account_id = account_id, # for_type = 'contact', # for_id = contact_id, # fail_any = fail_any, # ) # if isinstance(create_address_obj_result, int): # address_id = create_address_obj_result # # NOTE: This last update should no longer be needed now that the contact_obj.address_id is not supposed to be used. # # Need to update the contact with the new address_id # contact_obj_up = {} # REMOVE # contact_obj_up['id'] = contact_id # REMOVE # contact_obj_up['address_id'] = address_id # REMOVE # if contact_obj_up_result := sql_update(data=contact_obj_up, table_name='contact'): pass # REMOVE # else: # REMOVE # return False # REMOVE # log.debug(contact_obj_up_result) # REMOVE # else: # log.debug(f'No address_id was returned when tyring to create_address_obj(): {create_address_obj_result}') # address_id = None log.info(f'Returning the new contact_id: {contact_id}') return contact_id # ### END ### API Contact Methods ### create_contact_obj() ### # ### BEGIN ### API Contact Methods ### update_contact_obj() ### # NOTE: This will update a contact and then also create or update a linked address if contact_obj.address data is passed. # Updated 2022-01-06 @logger_reset def update_contact_obj( contact_id: int|str, # Ideally the int ID should be passed. This allows for updating of the id_random value. contact_dict_obj: Contact_Base, for_type: str = None, for_id: int|str = None, address_id: int = None, create_sub_obj: bool = False, fail_any: bool = False, # Fail if any thing goes wrong for sub objects return_dict: bool = False, log_lvl: int = logging.WARNING, # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL ) -> bool: log.setLevel(log_lvl) # ### SECTION ### Secondary data validation # NOTE: Remove at future date. Is this check needed if we trust that the ID is checked ahead of time? if contact_id := redis_lookup_id_random(record_id_random=contact_id, table_name='contact'): pass else: return False if address_id := redis_lookup_id_random(record_id_random=address_id, table_name='address'): pass elif address_id is None: pass else: return False log.info('Create dictionary or Pydantic object') log.debug(type(contact_dict_obj)) log.debug(contact_dict_obj) if isinstance(contact_dict_obj, dict): contact_dict = contact_dict_obj try: contact_obj = Contact_Base(**contact_dict) log.debug(contact_obj) except ValidationError as e: log.error(e.json()) return False else: contact_obj = contact_dict_obj contact_dict = contact_obj.dict(by_alias=False, exclude_defaults=False, exclude_unset=True, exclude={'address', 'address_id', 'address_id_random', 'created_on', 'updated_on'}) log.debug(contact_dict) # ### SECTION ### Process data contact_obj.id = contact_id # Is this needed? contact_dict['id'] = contact_id # Look for an account_id in the contact_obj if account_id := contact_obj.account_id: pass elif account_id := get_account_id_w_for_type_id(for_type='contact', for_id=contact_id): pass # If for_type and for_id are passed then the contact needs to be updated if for_type and for_id: contact_obj.for_type = for_type contact_obj.for_id = for_id contact_dict['for_type'] = for_type contact_dict['for_id'] = for_id # Look for an address_id in the contact_obj if one was not passed separately if address_id: pass elif address_id := contact_obj.address.id: pass log.debug(contact_obj.address.id) log.debug(contact_obj.address.id_random) if contact_dict_up_result := sql_update( data=contact_dict, table_name='contact', rm_id_random=True ): pass else: log.warning(f'Contact not updated.') log.debug(contact_dict_up_result) return False log.debug(contact_dict_up_result) if address_id and contact_obj.address: log.info('Updating Address object') if address_update_result := update_address_obj( address_id = address_id, address_dict_obj = contact_obj.address, for_type = 'contact', for_id = contact_id, ): pass else: return False elif contact_obj.address: log.info('Creating Address object') if address_create_result := create_address_obj( account_id = account_id, address_dict_obj = contact_obj.address, for_type = 'contact', for_id = contact_id, ): pass else: return False else: pass log.debug(contact_obj.dict(by_alias=False, exclude_unset=True)) return True # ### END ### API Contact Methods ### update_contact_obj() ### # ### BEGIN ### API Contact Methods ### create_update_contact_obj() ### @logger_reset def create_update_contact_obj( contact_id: int|str|None, # Ideally the int ID should be passed. This allows for updating of the id_random value. contact_obj: Contact_Base, process_address: bool = False, process_organization: bool = False, ) -> bool: log.setLevel(logging.INFO) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL log.debug(locals()) if contact_id: if contact_id := redis_lookup_id_random(record_id_random=contact_id, table_name='contact'): pass else: return False contact_obj.id = contact_id else: # Insert record now and update later contact_dict_in = contact_obj.dict(by_alias=False, exclude_unset=True, exclude={'address', 'contact', 'organization', 'user'}) log.debug(contact_dict_in) contact_in_result = sql_insert( data = contact_dict_in, table_name = 'contact', rm_id_random = True, id_random_length = default_num_bytes, ) log.debug(contact_in_result) if isinstance(contact_in_result, bool) and contact_in_result is True: return contact_in_result elif isinstance(contact_in_result, int): contact_id = contact_in_result contact_obj.id = contact_id else: return False # This should not happen. # Process address data if process_address and contact_obj.address: address_obj = contact_obj.address address_obj.for_type = 'contact' address_obj.for_id = contact_id address_id = contact_obj.address_id_random address_result = create_update_address_obj( address_id = address_id, address_obj = address_obj, ) log.debug(address_result) if isinstance(address_result, bool) and address_result is True: pass # Do not need to update contact object. elif isinstance(address_result, bool) and address_result is False: pass # Do not need to update contact object. elif isinstance(address_result, int): contact_obj.address_id = address_result else: log.warning('Something may have gone wrong while trying to create or update a address.') # Process contact data contact_dict_up = contact_obj.dict(by_alias=False, exclude_unset=True, exclude={'address'}) log.debug(contact_dict_up) # Update record contact_up_result = sql_update( data = contact_dict_up, table_name = 'contact', rm_id_random = True, ) log.debug(contact_up_result) if isinstance(contact_up_result, bool) and contact_up_result is True: return contact_id elif isinstance(contact_up_result, bool) and contact_up_result is False: return False elif isinstance(contact_up_result, int): return contact_up_result else: return False # ### END ### API Contact Methods ### create_update_contact_obj() ###