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_insert, 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() ### def load_contact_obj( contact_id: int|str, limit: int = 1000, by_alias: bool = True, exclude_unset: bool = True, model_as_dict: bool = False, enabled: str = 'enabled', # enabled, disabled, all 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 2021-12-13 @logger_reset def get_contact_rec_list( for_obj_type: str, for_obj_id: str, limit: int = 1000, enabled: str = 'enabled', # enabled, disabled, all ) -> list|bool: log.setLevel(logging.INFO) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL log.debug(locals()) if for_obj_id := redis_lookup_id_random(record_id_random=for_obj_id, table_name=for_obj_type): pass else: return False data = {} data[f'{for_obj_type}_id'] = for_obj_id # data['for_obj_type'] = for_obj_type sql_obj_type_id = f'`contact`.{for_obj_type}_id = :{for_obj_type}_id' # if enabled in ['enabled', 'disabled', 'all']: # if enabled == 'enabled': # data['enable'] = True # sql_enabled = f'AND `contact`.enable = :enable' # elif enabled == 'disabled': # data['enable'] = False # sql_enabled = f'AND `contact`.enable = :enable' # elif enabled == 'all': # sql_enabled = '' sql_enabled = '' if limit: data['limit'] = limit sql_limit = f'LIMIT :limit' else: sql_limit = '' sql = f""" SELECT `contact`.id AS 'contact_id', `contact`.id_random AS 'contact_id_random' FROM `contact` AS `contact` WHERE {sql_obj_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 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; """ log.setLevel(logging.WARNING) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL if contact_data_result := sql_select(data=data, sql=sql): log.setLevel(logging.WARNING) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL 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 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.DEBUG) # 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.DEBUG) # 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 def create_contact_obj( account_id: int|str, contact_dict_obj: Contact_Base, 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 ) -> int|bool: log.setLevel(logging.WARNING) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL log.debug(locals()) # ### 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 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'}) # log.debug(type(contact_dict_obj)) # if isinstance(contact_dict_obj, dict): # if account_id: # contact_dict_obj['account_id'] = account_id # if for_type: # contact_dict_obj['for_type'] = for_type # if for_id: # contact_dict_obj['for_id'] = for_id # try: # contact_obj = Contact_Base(**contact_dict_obj) # log.setLevel(logging.DEBUG) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL # log.debug(contact_obj) # except ValidationError as e: # log.error(e.json()) # return False # else: # 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'}) # ### SECTION ### Process data contact_obj.account_id = account_id contact_obj.for_type = for_type contact_obj.for_id = for_id contact_dict['account_id'] = account_id contact_dict['for_type'] = for_type contact_dict['for_id'] = for_id if contact_dict_in_result := sql_insert(data=contact_dict, table_name='contact', rm_id_random=True, id_random_length=8): pass else: return False log.debug(contact_dict_in_result) contact_id = contact_dict_in_result if address_id and contact.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.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.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 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, create_sub_obj: bool = False, fail_any: bool = False, # Fail if any thing goes wrong for sub objects return_dict: bool = False, ) -> bool: log.setLevel(logging.DEBUG) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL log.debug(locals()) # ### 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 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.setLevel(logging.DEBUG) # 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 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 contact_obj.id = contact_id # Is this needed? contact_dict['contact_id'] = contact_id account_id = get_account_id_w_contact_id(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.') log.debug(contact_dict_up_result) return False log.debug(contact_dict_up_result) if address_id and contact.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.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_up) # log.debug(contact_obj_up.dict(by_alias=True, exclude_unset=True)) log.debug(contact_obj.dict(by_alias=False, exclude_unset=True)) # log.debug(contact_obj_up.dict(by_alias=False, exclude_unset=False)) #contact_dict_up = contact_obj_up.dict(by_alias=False, exclude_unset=True) # if contact_obj_up.address: # log.setLevel(logging.DEBUG) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL # address_obj_unknown = contact_obj_up.address # log.debug(address_obj_unknown) # if isinstance(contact_obj_up.address, dict): # address_id = address_obj_unknown.get('address_id_random', None) # else: # address_id = address_obj_unknown.id # if address_id: # # from app.methods.address_methods import update_address_obj_v3 # if update_address_obj_result := update_address_obj( # address_id = address_id, # address_obj_up = address_obj_unknown, # create_sub_obj = create_sub_obj, # fail_any = fail_any, # ): # address_id = update_address_obj_result # log.info(f'Address updated. Address ID: {address_id}') # else: # log.warning(f'Address not updated. Contact ID: {contact_id}') # log.debug(update_address_obj_result) # address_id = None # if fail_any: return False # if isinstance(update_address_obj_result, int): # address_id = update_address_obj_result # log.info(f'Address updated. Address ID: {address_id}') # else: # log.warning(f'Address not updated. Contact ID: {contact_id}') # log.debug(update_address_obj_result) # address_id = None # if fail_any: return False # else: # log.info(f'No Address ID found.') # # from app.methods.address_methods import create_address_obj_v3 # if create_address_obj_result := create_address_obj( # account_id = account_id, # for_type = 'contact', # for_id = contact_id, # address_obj_new = address_obj_unknown, # fail_any = fail_any, # ): # if isinstance(create_address_obj_result, int): # address_id = create_address_obj_result # log.info(f'Address created. Address ID: {address_id}') # else: # log.warning(f'Address not created. Contact ID: {contact_id}') # log.debug(create_address_obj_result) # address_id = None # if fail_any: return False # else: # log.warning(f'Address not created. Contact ID: {contact_id}') # log.debug(create_address_obj_result) # address_id = None # if fail_any: return False # # return_dict['address_id'] = address_id # else: # log.info('Address not found or not in a dict.') # pass # if contact_obj_up.address_id and contact_obj_up.address: # address_id = contact_obj_up.address_id # address_obj_up = contact_obj_up.address # log.debug(address_id) # log.debug(address_obj_up) # if address_obj_up_result := update_address_obj( # address_id = address_id, # address_obj_up = address_obj_up, # create_sub_obj = create_sub_obj, # ): # log.debug(address_obj_up_result) # else: # log.debug(address_obj_up_result) # return False # elif contact_obj_up.address and not contact_obj_up.address.id: # # NOTE: This will blindly create a new address even if there was one associated but the contact.address_id was not found. # address_obj_in = contact_obj_up.address # log.debug(address_obj_in) # if address_obj_in_result := create_address_obj( # address_obj_new = address_obj_in, # account_id = account_id, # for_type = 'contact', # for_id = contact_id, # ): # # log.setLevel(logging.DEBUG) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL # log.debug(address_obj_in_result) # # NOTE: This last update should no longer be needed now that the contact.address_id is not supposed to be used. # # Need to update the contact with the new address_id # contact_obj_up.address_id = address_obj_in_result # REMOVE # else: # # log.setLevel(logging.DEBUG) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL # log.debug(address_obj_in_result) # return False # contact_dict_up = contact_obj_up.dict(by_alias=False, exclude_unset=True, exclude={'address'}) # log.debug(contact_dict_up) # if contact_obj_up_result := sql_update(data=contact_dict_up, table_name='contact', rm_id_random=True): # log.debug(contact_obj_up_result) # return True # else: # log.debug(contact_obj_up_result) # return False return True # ### END ### API Contact Methods ### update_contact_obj() ### # ### BEGIN ### API Contact Methods ### create_update_contact_obj() ### 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.DEBUG) # 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() ###