Working on the cart and other related things

This commit is contained in:
Scott Idem
2021-05-10 18:29:53 -04:00
parent 8cbabf48fe
commit 9a46b755bf
36 changed files with 444 additions and 263 deletions

View File

@@ -1,5 +1,5 @@
from __future__ import annotations from __future__ import annotations
import secrets import redis, secrets
from timeit import default_timer as timer from timeit import default_timer as timer
from app.config import settings from app.config import settings
@@ -115,8 +115,8 @@ def sql_update(sql:str=None, data:dict=None, table_name:str=None, record_id:int=
if sql: if sql:
sql_update = text(sql) sql_update = text(sql)
elif table_name and data: elif table_name and data:
#if rm_id_random: if rm_id_random:
#data = lookup_id_random_pop(obj_data=data) data = lookup_id_random_pop(obj_data=data)
if not data.get('id_random', None) and id_random_length: if not data.get('id_random', None) and id_random_length:
data['id_random'] = secrets.token_urlsafe(id_random_length) data['id_random'] = secrets.token_urlsafe(id_random_length)
@@ -200,6 +200,7 @@ def sql_insert_or_update(sql:str=None, data:dict=None, table_name:str=None, rm_i
elif table_name and data: elif table_name and data:
if rm_id_random: if rm_id_random:
data = lookup_id_random_pop(obj_data=data) data = lookup_id_random_pop(obj_data=data)
pass
if not data.get('id_random', None) and id_random_length: if not data.get('id_random', None) and id_random_length:
data['id_random'] = secrets.token_urlsafe(id_random_length) data['id_random'] = secrets.token_urlsafe(id_random_length)
@@ -631,3 +632,210 @@ def sql_delete(
# NOTE: Need to deal with 0 rows affected when the WHERE clause was not satisfied and there was no error. # NOTE: Need to deal with 0 rows affected when the WHERE clause was not satisfied and there was no error.
return True # Successful return True # Successful
# ### BEGIN ### API Lib General ### redis_lookup_id_random() ###
# Just return the value if it is an integer
# Check if the id_random value is a string and the correct length
# Attempt to look up id_random key in Redis
# If success then return the ID number
# If not success and there is a table_name then check the database table passed
# If found in database table then store in Redis and return the ID number
def redis_lookup_id_random(record_id_random:int|str, table_name:str):
log.setLevel(logging.WARNING) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
log.debug(locals())
if isinstance(record_id_random, str) and len(record_id_random) >= 11 and len(record_id_random) <= 22: pass
elif isinstance(record_id_random, int): return record_id_random
else:
log.warning(f'Unexpected data type or string format: {str(type(record_id_random))} Expected type is a string 11 or 22 characters long.')
return False
if record_id_random and table_name:
# WARNING: The record_id_random string length should be checked just in case?
if len(record_id_random) < 11:
log.warning(f'The length of id_random is too short: {str(record_id_random)} ({len(record_id_random)} chars)')
return False
elif len(record_id_random) > 22:
log.warning(f'The length of id_random is too long {str(record_id_random)} ({len(record_id_random)} chars)')
return False
else:
pass
elif record_id_random:
log.warning('Missing id_random')
return False
elif table_name:
log.warning('Missing table_name to select from for id_random')
return False
else:
log.warning('Missing table_name and record_id_random')
return False
r = redis.Redis(host='localhost', port=6379, db=7, password=None, decode_responses=True)
key_name = 'record_id:'+record_id_random
record_id = r.get(key_name)
log.debug(f'Record ID? {str(record_id)}')
if record_id:
log.info('The record ID was found using the record_id_random value.')
log.info(f'TTL for: {key_name} : {str(record_id)} is {str(r.ttl(key_name))} seconds')
return int(record_id)
elif table_name:
data = { 'id_random': record_id_random }
sql = f"""
SELECT id
FROM `{table_name}` AS `table`
WHERE `table`.id_random = :id_random;
"""
if select_results := sql_select(sql=sql, data=data):
log.setLevel(logging.WARNING) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
log.debug(select_results)
log.debug(type(select_results))
if isinstance(select_results, dict):
log.info(f"""Record ID random found: {str(select_results['id'])}""")
if record_id := select_results.get('id'):
r.setex(key_name, datetime.timedelta(minutes=90), value=record_id)
return int(record_id)
else:
log.setLevel(logging.ERROR) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
log.error('The SQL result was not what was expected.')
return False
else:
log.setLevel(logging.ERROR) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
log.error('More than one record may have been found. There may be a duplicate id_random.')
log.error(select_results)
return False
else:
#log.setLevel(logging.INFO) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
log.info('Record ID random was not found')
return None
log.setLevel(logging.ERROR) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
log.error('We should not be here. Something unexpected happened.')
return False # Just in case
# ### BEGIN ### API Lib General ### redis_lookup_id_random() ###
# ### BEGIN ### API Lib General ### lookup_id_random_pop() ###
# Look up and resolve id_random values to their id
# Remove the unneeded *_id_random key from the dict
def lookup_id_random_pop(obj_data:dict):
log.setLevel(logging.WARNING) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
log.debug(locals())
if 'account_id_random' in obj_data:
obj_data['account_id'] = redis_lookup_id_random(record_id_random=obj_data['account_id_random'], table_name='account')
obj_data.pop('account_id_random')
if 'address_id_random' in obj_data:
obj_data['address_id'] = redis_lookup_id_random(record_id_random=obj_data['address_id_random'], table_name='address')
obj_data.pop('address_id_random')
if 'address_location_id_random' in obj_data:
obj_data['address_location_id'] = redis_lookup_id_random(record_id_random=obj_data['address_location_id_random'], table_name='address')
obj_data.pop('address_location_id_random')
if 'archive_id_random' in obj_data:
obj_data['archive_id'] = redis_lookup_id_random(record_id_random=obj_data['archive_id_random'], table_name='archive')
obj_data.pop('archive_id_random')
if 'contact_id_random' in obj_data:
obj_data['contact_id'] = redis_lookup_id_random(record_id_random=obj_data['contact_id_random'], table_name='contact')
obj_data.pop('contact_id_random')
if 'event_id_random' in obj_data:
obj_data['event_id'] = redis_lookup_id_random(record_id_random=obj_data.get('event_id_random', None), table_name='event')
obj_data.pop('event_id_random')
if 'event_exhibit_id_random' in obj_data:
obj_data['event_exhibit_id'] = redis_lookup_id_random(record_id_random=obj_data.get('event_exhibit_id_random', None), table_name='event_exhibit')
obj_data.pop('event_exhibit_id_random')
if 'hosted_file_id_random' in obj_data:
obj_data['hosted_file_id'] = redis_lookup_id_random(record_id_random=obj_data.get('hosted_file_id_random', None), table_name='hosted_file')
obj_data.pop('hosted_file_id_random')
if 'order_id_random' in obj_data:
obj_data['order_id'] = redis_lookup_id_random(record_id_random=obj_data.get('order_id_random', None), table_name='order')
obj_data.pop('order_id_random')
if 'order_line_id_random' in obj_data:
obj_data['order_line_id'] = redis_lookup_id_random(record_id_random=obj_data.get('order_line_id_random', None), table_name='order_line')
obj_data.pop('order_line_id_random')
if 'order_cart_id_random' in obj_data:
obj_data['order_cart_id'] = redis_lookup_id_random(record_id_random=obj_data.get('order_cart_id_random', None), table_name='order_cart')
obj_data.pop('order_cart_id_random')
if 'order_cart_line_id_random' in obj_data:
obj_data['order_cart_line_id'] = redis_lookup_id_random(record_id_random=obj_data.get('order_cart_line_id_random', None), table_name='order_cart_line')
obj_data.pop('order_cart_line_id_random')
if 'organization_id_random' in obj_data:
obj_data['organization_id'] = redis_lookup_id_random(record_id_random=obj_data.get('organization_id_random', None), table_name='organization')
obj_data.pop('organization_id_random')
if 'person_id_random' in obj_data:
obj_data['person_id'] = redis_lookup_id_random(record_id_random=obj_data['person_id_random'], table_name='person')
obj_data.pop('person_id_random')
if 'post_id_random' in obj_data:
obj_data['post_id'] = redis_lookup_id_random(record_id_random=obj_data.get('post_id_random', None), table_name='post')
obj_data.pop('post_id_random')
if 'product_id_random' in obj_data:
obj_data['product_id'] = redis_lookup_id_random(record_id_random=obj_data['product_id_random'], table_name='product')
obj_data.pop('product_id_random')
if 'user_id_random' in obj_data:
obj_data['user_id'] = redis_lookup_id_random(record_id_random=obj_data['user_id_random'], table_name='user')
obj_data.pop('user_id_random')
if 'for_type' in obj_data and 'for_id_random' in obj_data:
obj_data['for_id'] = redis_lookup_id_random(record_id_random=obj_data.get('for_id_random', None), table_name=obj_data.get('for_type', None))
obj_data.pop('for_id_random')
#log.setLevel(logging.DEBUG) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
log.debug(obj_data)
elif 'for_id_random' in obj_data:
# In case for_id_random was passed without for_type
log.warn('for_id_random was passed without for_type')
obj_data.pop('for_id_random')
if 'object_type' in obj_data and 'object_id_random' in obj_data:
obj_data['object_id'] = redis_lookup_id_random(record_id_random=obj_data.get('object_id_random', None), table_name=obj_data.get('object_type', None))
obj_data.pop('object_id_random')
#log.setLevel(logging.DEBUG) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
log.debug(obj_data)
elif 'object_id_random' in obj_data:
# In case object_id_random was passed without object_type
log.warn('object_id_random was passed without object_type')
obj_data.pop('object_id_random')
if 'to_object_type' in obj_data and 'to_object_id_random' in obj_data:
obj_data['to_object_id'] = redis_lookup_id_random(record_id_random=obj_data.get('to_object_id_random', None), table_name=obj_data.get('to_object_type', None))
obj_data.pop('to_object_id_random')
#log.setLevel(logging.DEBUG) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
log.debug(obj_data)
elif 'to_object_id_random' in obj_data:
# In case to_object_id_random was passed without to_object_type
log.warn('to_object_id_random was passed without to_object_type')
obj_data.pop('to_object_id_random')
if 'from_object_type' in obj_data and 'from_object_id_random' in obj_data:
obj_data['from_object_id'] = redis_lookup_id_random(record_id_random=obj_data.get('from_object_id_random', None), table_name=obj_data.get('from_object_type', None))
obj_data.pop('from_object_id_random')
#log.setLevel(logging.DEBUG) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
log.debug(obj_data)
elif 'from_object_id_random' in obj_data:
# In case from_object_id_random was passed without from_object_type
log.warn('from_object_id_random was passed without from_object_type')
obj_data.pop('from_object_id_random')
return obj_data
# ### END ### API Lib General ### lookup_id_random_pop() ###

View File

@@ -43,208 +43,6 @@ async def get_account_header(x_account_id:str = Header(...)):
# ### END ### API Lib General ### async get_account_header() ### # ### END ### API Lib General ### async get_account_header() ###
# ### BEGIN ### API Lib General ### redis_lookup_id_random() ###
# Just return the value if it is an integer
# Check if the id_random value is a string and the correct length
# Attempt to look up id_random key in Redis
# If success then return the ID number
# If not success and there is a table_name then check the database table passed
# If found in database table then store in Redis and return the ID number
def redis_lookup_id_random(record_id_random:int|str, table_name:str):
log.setLevel(logging.WARNING) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
log.debug(locals())
if isinstance(record_id_random, str) and len(record_id_random) >= 11 and len(record_id_random) <= 22: pass
elif isinstance(record_id_random, int): return record_id_random
else:
log.warning(f'Unexpected data type or string format: {str(type(record_id_random))} Expected type is a string 11 or 22 characters long.')
return False
if record_id_random and table_name:
# WARNING: The record_id_random string length should be checked just in case?
if len(record_id_random) < 11:
log.warning(f'The length of id_random is too short: {str(record_id_random)} ({len(record_id_random)} chars)')
return False
elif len(record_id_random) > 22:
log.warning(f'The length of id_random is too long {str(record_id_random)} ({len(record_id_random)} chars)')
return False
else:
pass
elif record_id_random:
log.warning('Missing id_random')
return False
elif table_name:
log.warning('Missing table_name to select from for id_random')
return False
else:
log.warning('Missing table_name and record_id_random')
return False
r = redis.Redis(host='localhost', port=6379, db=7, password=None, decode_responses=True)
key_name = 'record_id:'+record_id_random
record_id = r.get(key_name)
log.debug(f'Record ID? {str(record_id)}')
if record_id:
log.info('The record ID was found using the record_id_random value.')
log.info(f'TTL for: {key_name} : {str(record_id)} is {str(r.ttl(key_name))} seconds')
return int(record_id)
elif table_name:
data = { 'id_random': record_id_random }
sql = f"""
SELECT id
FROM `{table_name}` AS `table`
WHERE `table`.id_random = :id_random;
"""
if select_results := sql_select(sql=sql, data=data):
log.setLevel(logging.WARNING) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
log.debug(select_results)
log.debug(type(select_results))
if isinstance(select_results, dict):
log.info(f"""Record ID random found: {str(select_results['id'])}""")
if record_id := select_results.get('id'):
r.setex(key_name, datetime.timedelta(minutes=90), value=record_id)
return int(record_id)
else:
log.setLevel(logging.ERROR) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
log.error('The SQL result was not what was expected.')
return False
else:
log.setLevel(logging.ERROR) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
log.error('More than one record may have been found. There may be a duplicate id_random.')
log.error(select_results)
return False
else:
#log.setLevel(logging.INFO) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
log.info('Record ID random was not found')
return None
log.setLevel(logging.ERROR) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
log.error('We should not be here. Something unexpected happened.')
return False # Just in case
# ### BEGIN ### API Lib General ### redis_lookup_id_random() ###
# ### BEGIN ### API Lib General ### lookup_id_random_pop() ###
# Look up and resolve id_random values to their id
# Remove the unneeded *_id_random key from the dict
def lookup_id_random_pop(obj_data:dict):
log.setLevel(logging.WARNING) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
log.debug(locals())
if 'account_id_random' in obj_data:
obj_data['account_id'] = redis_lookup_id_random(record_id_random=obj_data['account_id_random'], table_name='account')
obj_data.pop('account_id_random')
if 'address_id_random' in obj_data:
obj_data['address_id'] = redis_lookup_id_random(record_id_random=obj_data['address_id_random'], table_name='address')
obj_data.pop('address_id_random')
if 'address_location_id_random' in obj_data:
obj_data['address_location_id'] = redis_lookup_id_random(record_id_random=obj_data['address_location_id_random'], table_name='address')
obj_data.pop('address_location_id_random')
if 'archive_id_random' in obj_data:
obj_data['archive_id'] = redis_lookup_id_random(record_id_random=obj_data['archive_id_random'], table_name='archive')
obj_data.pop('archive_id_random')
if 'contact_id_random' in obj_data:
obj_data['contact_id'] = redis_lookup_id_random(record_id_random=obj_data['contact_id_random'], table_name='contact')
obj_data.pop('contact_id_random')
if 'event_id_random' in obj_data:
obj_data['event_id'] = redis_lookup_id_random(record_id_random=obj_data.get('event_id_random', None), table_name='event')
obj_data.pop('event_id_random')
if 'event_exhibit_id_random' in obj_data:
obj_data['event_exhibit_id'] = redis_lookup_id_random(record_id_random=obj_data.get('event_exhibit_id_random', None), table_name='event_exhibit')
obj_data.pop('event_exhibit_id_random')
if 'hosted_file_id_random' in obj_data:
obj_data['hosted_file_id'] = redis_lookup_id_random(record_id_random=obj_data.get('hosted_file_id_random', None), table_name='hosted_file')
obj_data.pop('hosted_file_id_random')
if 'order_id_random' in obj_data:
obj_data['order_id'] = redis_lookup_id_random(record_id_random=obj_data.get('order_id_random', None), table_name='order')
obj_data.pop('order_id_random')
if 'order_line_id_random' in obj_data:
obj_data['order_line_id'] = redis_lookup_id_random(record_id_random=obj_data.get('order_line_id_random', None), table_name='order_line')
obj_data.pop('order_line_id_random')
if 'order_cart_id_random' in obj_data:
obj_data['order_cart_id'] = redis_lookup_id_random(record_id_random=obj_data.get('order_cart_id_random', None), table_name='order_cart')
obj_data.pop('order_cart_id_random')
if 'order_cart_line_id_random' in obj_data:
obj_data['order_cart_line_id'] = redis_lookup_id_random(record_id_random=obj_data.get('order_cart_line_id_random', None), table_name='order_cart_line')
obj_data.pop('order_cart_line_id_random')
if 'organization_id_random' in obj_data:
obj_data['organization_id'] = redis_lookup_id_random(record_id_random=obj_data.get('organization_id_random', None), table_name='organization')
obj_data.pop('organization_id_random')
if 'person_id_random' in obj_data:
obj_data['person_id'] = redis_lookup_id_random(record_id_random=obj_data['person_id_random'], table_name='person')
obj_data.pop('person_id_random')
if 'post_id_random' in obj_data:
obj_data['post_id'] = redis_lookup_id_random(record_id_random=obj_data.get('post_id_random', None), table_name='post')
obj_data.pop('post_id_random')
if 'product_id_random' in obj_data:
obj_data['product_id'] = redis_lookup_id_random(record_id_random=obj_data['product_id_random'], table_name='product')
obj_data.pop('product_id_random')
if 'user_id_random' in obj_data:
obj_data['user_id'] = redis_lookup_id_random(record_id_random=obj_data['user_id_random'], table_name='user')
obj_data.pop('user_id_random')
if 'for_type' in obj_data and 'for_id_random' in obj_data:
obj_data['for_id'] = redis_lookup_id_random(record_id_random=obj_data.get('for_id_random', None), table_name=obj_data.get('for_type', None))
obj_data.pop('for_id_random')
#log.setLevel(logging.DEBUG) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
log.debug(obj_data)
elif 'for_id_random' in obj_data:
# In case for_id_random was passed without for_type
log.warn('for_id_random was passed without for_type')
obj_data.pop('for_id_random')
if 'object_type' in obj_data and 'object_id_random' in obj_data:
obj_data['object_id'] = redis_lookup_id_random(record_id_random=obj_data.get('object_id_random', None), table_name=obj_data.get('object_type', None))
obj_data.pop('object_id_random')
#log.setLevel(logging.DEBUG) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
log.debug(obj_data)
elif 'object_id_random' in obj_data:
# In case object_id_random was passed without object_type
log.warn('object_id_random was passed without object_type')
obj_data.pop('object_id_random')
if 'to_object_type' in obj_data and 'to_object_id_random' in obj_data:
obj_data['to_object_id'] = redis_lookup_id_random(record_id_random=obj_data.get('to_object_id_random', None), table_name=obj_data.get('to_object_type', None))
obj_data.pop('to_object_id_random')
#log.setLevel(logging.DEBUG) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
log.debug(obj_data)
elif 'to_object_id_random' in obj_data:
# In case to_object_id_random was passed without to_object_type
log.warn('to_object_id_random was passed without to_object_type')
obj_data.pop('to_object_id_random')
if 'from_object_type' in obj_data and 'from_object_id_random' in obj_data:
obj_data['from_object_id'] = redis_lookup_id_random(record_id_random=obj_data.get('from_object_id_random', None), table_name=obj_data.get('from_object_type', None))
obj_data.pop('from_object_id_random')
#log.setLevel(logging.DEBUG) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
log.debug(obj_data)
elif 'from_object_id_random' in obj_data:
# In case from_object_id_random was passed without from_object_type
log.warn('from_object_id_random was passed without from_object_type')
obj_data.pop('from_object_id_random')
return obj_data
# ### END ### API Lib General ### lookup_id_random_pop() ###
def secure_hash_string(string:str): def secure_hash_string(string:str):

View File

@@ -4,6 +4,7 @@ import datetime, hashlib, logging, os, pytz, redis, secrets
from typing import Dict, List, Optional, Set, Union from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator
from ..db_sql import redis_lookup_id_random
from ..lib_general import * from ..lib_general import *
from .common_field_schema import base_fields, default_num_bytes from .common_field_schema import base_fields, default_num_bytes

View File

@@ -5,7 +5,7 @@ from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, PrivateAttr, ValidationError, validator
from ..lib_general import * from ..lib_general import *
from ..db_sql import sql_select from ..db_sql import redis_lookup_id_random, sql_select
from .membership_model import Membership_Cfg_Base from .membership_model import Membership_Cfg_Base

View File

@@ -4,6 +4,7 @@ import datetime, hashlib, logging, os, pytz, redis, secrets
from typing import Dict, List, Optional, Set, Union from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator
from ..db_sql import redis_lookup_id_random
from ..lib_general import * from ..lib_general import *
from .common_field_schema import base_fields, default_num_bytes from .common_field_schema import base_fields, default_num_bytes

View File

@@ -4,6 +4,7 @@ import datetime, hashlib, logging, os, pytz, redis, secrets
from typing import Dict, List, Optional, Set, Union from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator
from ..db_sql import redis_lookup_id_random
from ..lib_general import * from ..lib_general import *
from .common_field_schema import base_fields, default_num_bytes from .common_field_schema import base_fields, default_num_bytes

View File

@@ -4,6 +4,7 @@ import datetime, hashlib, logging, os, pytz, redis, secrets
from typing import Dict, List, Optional, Set, Union from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator
from ..db_sql import redis_lookup_id_random
from ..lib_general import * from ..lib_general import *
from .common_field_schema import base_fields, default_num_bytes from .common_field_schema import base_fields, default_num_bytes

View File

@@ -4,6 +4,7 @@ import datetime, hashlib, logging, os, pytz, redis, secrets
from typing import Dict, List, Optional, Set, Union from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator
from ..db_sql import redis_lookup_id_random
from ..lib_general import * from ..lib_general import *
from .common_field_schema import base_fields, default_num_bytes from .common_field_schema import base_fields, default_num_bytes

View File

@@ -4,6 +4,7 @@ import datetime, hashlib, logging, os, pytz, redis, secrets
from typing import Dict, List, Optional, Set, Union from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator
from ..db_sql import redis_lookup_id_random
from ..lib_general import * from ..lib_general import *
from .common_field_schema import base_fields, default_num_bytes from .common_field_schema import base_fields, default_num_bytes

View File

@@ -4,6 +4,7 @@ import datetime, hashlib, logging, os, pytz, redis, secrets
from typing import Dict, List, Optional, Set, Union from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator
from ..db_sql import redis_lookup_id_random
from ..lib_general import * from ..lib_general import *
from .common_field_schema import base_fields, default_num_bytes from .common_field_schema import base_fields, default_num_bytes

View File

@@ -4,6 +4,7 @@ import datetime, hashlib, logging, os, pytz, redis, secrets
from typing import Dict, List, Optional, Set, Union from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator
from ..db_sql import redis_lookup_id_random
from ..lib_general import * from ..lib_general import *
from .common_field_schema import base_fields, default_num_bytes from .common_field_schema import base_fields, default_num_bytes

View File

@@ -4,8 +4,8 @@ import datetime, hashlib, logging, os, pytz, redis, secrets
from typing import Dict, List, Optional, Set, Union from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator
from ..db_sql import redis_lookup_id_random
from ..lib_general import * from ..lib_general import *
from ..log import *
from .common_field_schema import base_fields, default_num_bytes from .common_field_schema import base_fields, default_num_bytes

View File

@@ -4,8 +4,8 @@ import datetime, hashlib, logging, os, pytz, redis, secrets
from typing import Dict, List, Optional, Set, Union from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator
from ..db_sql import redis_lookup_id_random
from ..lib_general import * from ..lib_general import *
from ..log import *
from .common_field_schema import base_fields, default_num_bytes from .common_field_schema import base_fields, default_num_bytes

View File

@@ -4,8 +4,8 @@ import datetime, hashlib, logging, os, pytz, redis, secrets
from typing import Dict, List, Optional, Set, Union from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator
from ..db_sql import redis_lookup_id_random
from ..lib_general import * from ..lib_general import *
from ..log import *
from .common_field_schema import base_fields, default_num_bytes from .common_field_schema import base_fields, default_num_bytes

View File

@@ -4,6 +4,7 @@ import datetime, hashlib, logging, os, pytz, redis, secrets
from typing import Dict, List, Optional, Set, Union from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator
from ..db_sql import redis_lookup_id_random
from ..lib_general import * from ..lib_general import *
from .common_field_schema import base_fields, default_num_bytes from .common_field_schema import base_fields, default_num_bytes

View File

@@ -4,6 +4,7 @@ import datetime, hashlib, logging, os, pytz, redis, secrets
from typing import Dict, List, Optional, Set, Union from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator
from ..db_sql import redis_lookup_id_random
from ..lib_general import * from ..lib_general import *
from .common_field_schema import base_fields, default_num_bytes from .common_field_schema import base_fields, default_num_bytes

View File

@@ -4,8 +4,8 @@ import datetime, hashlib, logging, os, pytz, redis, secrets
from typing import Dict, List, Optional, Set, Union from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator
from ..db_sql import redis_lookup_id_random
from ..lib_general import * from ..lib_general import *
from ..log import *
from .common_field_schema import base_fields, default_num_bytes from .common_field_schema import base_fields, default_num_bytes

View File

@@ -5,7 +5,7 @@ from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, PrivateAttr, ValidationError, validator
from ..lib_general import * from ..lib_general import *
from ..db_sql import sql_select from ..db_sql import redis_lookup_id_random, sql_select
#from .address_model import Address_Base #from .address_model import Address_Base
#from .contact_model import Contact_Base #from .contact_model import Contact_Base

View File

@@ -4,8 +4,8 @@ import datetime, hashlib, logging, os, pytz, redis, secrets
from typing import Dict, List, Optional, Set, Union from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator
from ..db_sql import redis_lookup_id_random
from ..lib_general import * from ..lib_general import *
from ..log import *
from .common_field_schema import base_fields, default_num_bytes from .common_field_schema import base_fields, default_num_bytes
from .address_model import Address_Base from .address_model import Address_Base

View File

@@ -5,11 +5,67 @@ from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, PrivateAttr, ValidationError, validator
from ..lib_general import * from ..lib_general import *
from ..db_sql import sql_select from ..db_sql import redis_lookup_id_random, sql_insert_or_update, sql_update, sql_select
from .order_cart_model import Order_Cart_Base from .order_cart_model import Order_Cart_Base
def update_order_cart_obj(order_cart_obj:Order_Cart_Base, repl_order_cart_line_li:bool=False):
if order_cart_obj.account_id_random and (order_cart_obj.person_id_random or order_cart_obj.user_id_random):
log.info(f'An account.id_random {order_cart_obj.account_id_random} was passed. And either a person.id_random {order_cart_obj.person_id_random} or user.id_random {order_cart_obj.user_id_random} was passed. We can update the order cart.')
else:
log.error('An account ID along with a person ID or user ID is required to create an order.')
return False
#if order_cart_id := redis_lookup_id_random(record_id_random=order_cart_id_random, table_name='order_cart'): pass
#else: return False
order_cart_id_random = order_cart_obj.id_random # id_random because can't ref the alias
# Calculate totals
order_cart_total_amount:int = 0
order_cart_total_quantity:int = 0
for order_cart_line_obj in order_cart_obj.order_cart_line_li:
order_cart_total_amount += order_cart_line_obj.quantity * order_cart_line_obj.amount
order_cart_total_quantity += order_cart_line_obj.quantity
order_cart_line_obj.order_cart_id_random = order_cart_id_random
order_cart_line_obj_data = order_cart_line_obj.dict(by_alias=False, exclude_defaults=False, exclude_unset=True, exclude={'order_cart_line_id_random', 'product_type_id', 'product_type', 'created_on', 'updated_on'})
#order_cart_line_obj_data['order_id'] = order_cart_id
if order_cart_line_obj_resp := sql_insert_or_update(data=order_cart_line_obj_data, table_name='order_cart_line', rm_id_random=True, id_random_length=8): pass
else:
log.error('Something went wrong while trying to insert or update an order cart line record.')
return False
#log.debug(order_cart_obj_new.dict(by_alias=False, exclude_defaults=False, exclude_unset=True, exclude={'order_cart_line_li', 'cfg', 'created_on', 'updated_on'}))
#order_cart_obj_data = order_cart_obj_new.dict(by_alias=False, exclude_defaults=False, exclude_unset=True, exclude={'order_cart_line_li', 'cfg', 'created_on', 'updated_on'})
order_cart_obj_new = {}
order_cart_obj_new['id_random'] = order_cart_id_random
order_cart_obj_new['account_id_random'] = order_cart_obj.account_id_random
order_cart_obj_new['person_id_random'] = order_cart_obj.person_id_random
order_cart_obj_new['user_id_random'] = order_cart_obj.person_id_random
order_cart_obj_new['order_id_random'] = order_cart_obj.order_id_random
order_cart_obj_new['total_amount'] = order_cart_total_amount
order_cart_obj_new['total_quantity'] = order_cart_total_quantity
order_cart_obj_new['notes'] = order_cart_obj.notes
if order_cart_obj_resp := sql_update(data=order_cart_obj_new, table_name='order_cart', rm_id_random=True): pass
else:
log.error('Something went wrong while trying to update an order cart record.')
return False
return False
# ### BEGIN ### API Order Cart Methods ### load_order_cart_obj() ### # ### BEGIN ### API Order Cart Methods ### load_order_cart_obj() ###
def load_order_cart_obj(order_cart_id:int|str, inc_order_cart_line_li:bool=False, inc_order_cart_cfg:bool=False) -> Order_Cart_Base: def load_order_cart_obj(order_cart_id:int|str, inc_order_cart_line_li:bool=False, inc_order_cart_cfg:bool=False) -> Order_Cart_Base:
log.setLevel(logging.DEBUG) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL log.setLevel(logging.DEBUG) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
@@ -26,7 +82,7 @@ def load_order_cart_obj(order_cart_id:int|str, inc_order_cart_line_li:bool=False
order_cart_line_data = {} order_cart_line_data = {}
order_cart_line_data['order_cart_id'] = order_cart_id order_cart_line_data['order_cart_id'] = order_cart_id
if order_cart_line_rec_li := sql_select(table_name='v_order_cart_line', data=order_cart_line_data, as_list=True): if order_cart_line_rec_li := sql_select(table_name='v_order_cart_line', data=order_cart_line_data, as_list=True):
order_cart_rec['order_cart_line_list'] = order_cart_line_rec_li order_cart_rec['order_cart_line_li'] = order_cart_line_rec_li
if inc_order_cart_cfg: if inc_order_cart_cfg:
if order_cart_cfg_rec := sql_select(table_name='v_account_cfg_detail', field_name='account_id', field_value=order_cart_rec.get('account_id', None)): if order_cart_cfg_rec := sql_select(table_name='v_account_cfg_detail', field_name='account_id', field_value=order_cart_rec.get('account_id', None)):

View File

@@ -4,8 +4,8 @@ import datetime, hashlib, logging, os, pytz, redis, secrets
from typing import Dict, List, Optional, Set, Union from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator
from ..db_sql import redis_lookup_id_random
from ..lib_general import * from ..lib_general import *
from ..log import *
from .common_field_schema import base_fields, default_num_bytes from .common_field_schema import base_fields, default_num_bytes
@@ -95,6 +95,92 @@ class Order_Cart_Line_Base(BaseModel):
fields = base_fields fields = base_fields
class Order_Cart_DB_Base(BaseModel):
log.setLevel(logging.WARNING)
log.debug(locals())
id_random: Optional[str] = Field(
**base_fields['order_cart_id_random'],
alias='order_cart_id_random',
default_factory=lambda:secrets.token_urlsafe(default_num_bytes),
)
id: Optional[int] = Field(
#alias='order_cart_id'
)
account_id_random: Optional[str]
account_id: Optional[int] # NOTE: This is not really optional
person_id_random: Optional[str]
person_id: Optional[int]
user_id_random: Optional[str]
user_id: Optional[int]
order_id_random: Optional[str]
order_id: Optional[int]
total_quantity: Optional[int] = Field(0, ge=0, lt=150)
total_amount: Optional[int] = Field(0, ge=0, lt=1500000)
notes: Optional[str]
_processed_at: datetime.datetime = PrivateAttr(default_factory=datetime.datetime.now)
#@validator('order_cart_id_random', always=True)
def order_cart_id_random_copy(cls, v, values, **kwargs):
log.setLevel(logging.WARNING)
log.debug(locals())
if values['id_random']:
return values['id_random']
return None
@validator('id', always=True)
def order_cart_id_lookup(cls, v, values, **kwargs):
log.setLevel(logging.WARNING)
log.debug(locals())
if values['id_random']:
return redis_lookup_id_random(record_id_random=values['id_random'], table_name='order_cart')
return None
@validator('account_id', always=True)
def account_id_lookup(cls, v, values, **kwargs):
log.setLevel(logging.WARNING)
log.debug(locals())
if values['account_id_random']:
return redis_lookup_id_random(record_id_random=values['account_id_random'], table_name='account')
return None
@validator('person_id', always=True)
def person_id_lookup(cls, v, values, **kwargs):
log.setLevel(logging.WARNING)
log.debug(locals())
if values['person_id_random']:
return redis_lookup_id_random(record_id_random=values['person_id_random'], table_name='person')
return None
@validator('user_id', always=True)
def user_id_lookup(cls, v, values, **kwargs):
log.setLevel(logging.WARNING)
log.debug(locals())
if values['user_id_random']:
return redis_lookup_id_random(record_id_random=values['user_id_random'], table_name='user')
return None
@validator('order_id', always=True)
def order_id_lookup(cls, v, values, **kwargs):
log.setLevel(logging.WARNING)
log.debug(locals())
if 'order_id_random' in values and values['order_id_random']:
return redis_lookup_id_random(record_id_random=values['order_id_random'], table_name='order')
return None
class Config:
underscore_attrs_are_private = True
fields = base_fields
class Order_Cart_Base(BaseModel): class Order_Cart_Base(BaseModel):
log.setLevel(logging.WARNING) log.setLevel(logging.WARNING)
log.debug(locals()) log.debug(locals())
@@ -124,7 +210,7 @@ class Order_Cart_Base(BaseModel):
created_on: Optional[datetime.datetime] = None created_on: Optional[datetime.datetime] = None
updated_on: Optional[datetime.datetime] = None updated_on: Optional[datetime.datetime] = None
order_cart_line_list: List[Order_Cart_Line_Base] = [] order_cart_line_li: List[Order_Cart_Line_Base] = []
cfg: Optional[Order_Cart_Cfg_Base] = Order_Cart_Cfg_Base() cfg: Optional[Order_Cart_Cfg_Base] = Order_Cart_Cfg_Base()
@@ -199,7 +285,7 @@ def save_order_cart_obj(order_cart_obj_new=None):
#log.debug(order_cart_obj_new.dict(by_alias=False, exclude_defaults=False, exclude_unset=True)) #log.debug(order_cart_obj_new.dict(by_alias=False, exclude_defaults=False, exclude_unset=True))
# Get the current order_cart_line list to compare with what was sent # Get the current order_cart_line li to compare with what was sent
data = {} data = {}
data['order_cart_id_random'] = order_cart_obj_new.id_random data['order_cart_id_random'] = order_cart_obj_new.id_random
if order_cart_line_rec_li_curr := sql_select(table_name='v_order_cart_line', data=data, rm_id_random=True, as_list=True): if order_cart_line_rec_li_curr := sql_select(table_name='v_order_cart_line', data=data, rm_id_random=True, as_list=True):
@@ -225,7 +311,7 @@ def save_order_cart_obj(order_cart_obj_new=None):
# Loop through the line list that was sent and compare with what was pulled from the DB # Loop through the line list that was sent and compare with what was pulled from the DB
# Only insert if a product ID does not match # Only insert if a product ID does not match
# Only update if a product ID does match # Only update if a product ID does match
for order_cart_line_obj_new in order_cart_obj_new.order_cart_line_list: for order_cart_line_obj_new in order_cart_obj_new.order_cart_line_li:
log.setLevel(logging.DEBUG) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL log.setLevel(logging.DEBUG) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
if not any(order_cart_line_obj_curr.product_id_random == order_cart_line_obj_new.product_id_random for order_cart_line_obj_curr in order_cart_line_obj_li_curr): if not any(order_cart_line_obj_curr.product_id_random == order_cart_line_obj_new.product_id_random for order_cart_line_obj_curr in order_cart_line_obj_li_curr):
# Need to append to current list # Need to append to current list
@@ -244,7 +330,7 @@ def save_order_cart_obj(order_cart_obj_new=None):
log.info(f'Not a match: {order_cart_line_obj_curr.product_id_random}') log.info(f'Not a match: {order_cart_line_obj_curr.product_id_random}')
# Save merged current and new list to the new order cart object # Save merged current and new list to the new order cart object
order_cart_obj_new.order_cart_line_list = order_cart_line_obj_li_curr order_cart_obj_new.order_cart_line_li = order_cart_line_obj_li_curr
log.debug(order_cart_obj_new) log.debug(order_cart_obj_new)
# Final loop through to get the new order totals # Final loop through to get the new order totals
@@ -258,8 +344,8 @@ def save_order_cart_obj(order_cart_obj_new=None):
order_cart_obj_new.total_amount = order_cart_total_amount order_cart_obj_new.total_amount = order_cart_total_amount
order_cart_obj_new.total_quantity = order_cart_total_quantity order_cart_obj_new.total_quantity = order_cart_total_quantity
log.debug(order_cart_obj_new.dict(by_alias=False, exclude_defaults=False, exclude_unset=True, exclude={'order_cart_id_random', 'order_cart_line_list', 'cfg', 'created_on', 'updated_on'})) log.debug(order_cart_obj_new.dict(by_alias=False, exclude_defaults=False, exclude_unset=True, exclude={'order_cart_id_random', 'order_cart_line_li', 'cfg', 'created_on', 'updated_on'}))
order_cart_obj_data = order_cart_obj_new.dict(by_alias=False, exclude_defaults=False, exclude_unset=True, exclude={'order_cart_id_random', 'order_cart_line_list', 'cfg', 'created_on', 'updated_on'}) order_cart_obj_data = order_cart_obj_new.dict(by_alias=False, exclude_defaults=False, exclude_unset=True, exclude={'order_cart_id_random', 'order_cart_line_li', 'cfg', 'created_on', 'updated_on'})
# SQL INSERT or UPDATE the order_cart record # SQL INSERT or UPDATE the order_cart record
log.info('SQL INSERT or UPDATE the order_cart record') log.info('SQL INSERT or UPDATE the order_cart record')
@@ -278,7 +364,7 @@ def save_order_cart_obj(order_cart_obj_new=None):
# Loop through the order_cart_line list to SQL INSERT or UPDATE the records # Loop through the order_cart_line list to SQL INSERT or UPDATE the records
log.info('Loop through the order_cart_line list to SQL INSERT or UPDATE the records') log.info('Loop through the order_cart_line list to SQL INSERT or UPDATE the records')
for order_cart_line_obj in order_cart_obj_new.order_cart_line_list: for order_cart_line_obj in order_cart_obj_new.order_cart_line_li:
log.debug(f"--- {order_cart_line_obj}") log.debug(f"--- {order_cart_line_obj}")
log.debug(order_cart_line_obj.dict(by_alias=False, exclude_defaults=False, exclude_unset=False, exclude={})) log.debug(order_cart_line_obj.dict(by_alias=False, exclude_defaults=False, exclude_unset=False, exclude={}))
@@ -310,7 +396,7 @@ def get_order_cart_obj(order_cart_id=None, inc_order_cart_line_li=None, inc_orde
order_cart_line_data = {} order_cart_line_data = {}
order_cart_line_data['order_cart_id'] = order_cart_id order_cart_line_data['order_cart_id'] = order_cart_id
if order_cart_line_rec_li := sql_select(table_name='v_order_cart_line', data=order_cart_line_data, as_list=True): if order_cart_line_rec_li := sql_select(table_name='v_order_cart_line', data=order_cart_line_data, as_list=True):
order_cart_rec['order_cart_line_list'] = order_cart_line_rec_li order_cart_rec['order_cart_line_li'] = order_cart_line_rec_li
if inc_order_cart_cfg: if inc_order_cart_cfg:
if order_cart_cfg_rec := sql_select(table_name='v_account_cfg_detail', field_name='account_id', field_value=order_cart_rec.get('account_id', None)): if order_cart_cfg_rec := sql_select(table_name='v_account_cfg_detail', field_name='account_id', field_value=order_cart_rec.get('account_id', None)):

View File

@@ -5,7 +5,7 @@ from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, PrivateAttr, ValidationError, validator
from ..lib_general import * from ..lib_general import *
from ..db_sql import sql_select from ..db_sql import redis_lookup_id_random, sql_select
from .order_model import Order_Base from .order_model import Order_Base
#from .person_model import Person_Base #from .person_model import Person_Base
@@ -13,7 +13,7 @@ from .order_model import Order_Base
# ### BEGIN ### API Order Model ### save_order_obj() ### # ### BEGIN ### API Order Model ### save_order_obj() ###
def save_order_obj(order_obj_new:Order_Base, repl_order_line_list:bool=False): def save_order_obj(order_obj_new:Order_Base, repl_order_line_li:bool=False):
log.setLevel(logging.WARNING) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL log.setLevel(logging.WARNING) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
log.debug(locals()) log.debug(locals())
@@ -51,12 +51,12 @@ def save_order_obj(order_obj_new:Order_Base, repl_order_line_list:bool=False):
#log.setLevel(logging.DEBUG) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL #log.setLevel(logging.DEBUG) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
log.debug(order_line_obj_li_curr) log.debug(order_line_obj_li_curr)
if repl_order_line_list: # This will remove any order line list items not sent with the new order information. if repl_order_line_li: # This will remove any order line list items not sent with the new order information.
log.info('Removing any order line list items not sent with the new order information...') log.info('Removing any order line list items not sent with the new order information...')
for index, order_line_obj_curr in enumerate(order_line_obj_li_curr): for index, order_line_obj_curr in enumerate(order_line_obj_li_curr):
log.info(f'Current: order line ID={order_line_obj_curr.id_random} and product ID= {order_line_obj_curr.product_id_random}') log.info(f'Current: order line ID={order_line_obj_curr.id_random} and product ID= {order_line_obj_curr.product_id_random}')
matched_product_id = False matched_product_id = False
for order_line_obj_new in order_obj_new.order_line_list: for order_line_obj_new in order_obj_new.order_line_li:
log.debug(f'Checking new: product ID={order_line_obj_new.product_id_random}') log.debug(f'Checking new: product ID={order_line_obj_new.product_id_random}')
if order_line_obj_curr.product_id_random == order_line_obj_new.product_id_random: if order_line_obj_curr.product_id_random == order_line_obj_new.product_id_random:
@@ -82,7 +82,7 @@ def save_order_obj(order_obj_new:Order_Base, repl_order_line_list:bool=False):
# Loop through the new line list that was sent and compare with the current line list that was pulled from the DB # Loop through the new line list that was sent and compare with the current line list that was pulled from the DB
# Only insert if a product ID does not match # Only insert if a product ID does not match
# Only update if a product ID does match # Only update if a product ID does match
for order_line_obj_new in order_obj_new.order_line_list: for order_line_obj_new in order_obj_new.order_line_li:
log.info(f'New: order line ID={order_line_obj_new.id_random} and product ID= {order_line_obj_new.product_id_random}') log.info(f'New: order line ID={order_line_obj_new.id_random} and product ID= {order_line_obj_new.product_id_random}')
matched_product_id = False matched_product_id = False
for index, order_line_obj_curr in enumerate(order_line_obj_li_curr): for index, order_line_obj_curr in enumerate(order_line_obj_li_curr):
@@ -105,14 +105,14 @@ def save_order_obj(order_obj_new:Order_Base, repl_order_line_list:bool=False):
order_line_obj_li_curr.append(order_line_obj_new) # These will be inserted/updated below order_line_obj_li_curr.append(order_line_obj_new) # These will be inserted/updated below
# Save merged current and new list to the new order object # Save merged current and new list to the new order object
order_obj_new.order_line_list = order_line_obj_li_curr order_obj_new.order_line_li = order_line_obj_li_curr
log.debug(order_obj_new) log.debug(order_obj_new)
# Final loop through to get the new order totals # Final loop through to get the new order totals
# Calculate totals # Calculate totals
order_total_amount:int = 0 order_total_amount:int = 0
order_total_quantity:int = 0 order_total_quantity:int = 0
for order_line_obj_new in order_obj_new.order_line_list: for order_line_obj_new in order_obj_new.order_line_li:
order_total_amount += order_line_obj_new.quantity * order_line_obj_new.amount order_total_amount += order_line_obj_new.quantity * order_line_obj_new.amount
order_total_quantity += order_line_obj_new.quantity order_total_quantity += order_line_obj_new.quantity
@@ -120,8 +120,8 @@ def save_order_obj(order_obj_new:Order_Base, repl_order_line_list:bool=False):
order_obj_new.total_quantity = order_total_quantity order_obj_new.total_quantity = order_total_quantity
order_obj_new.balance = order_total_amount - order_obj_new.total_paid order_obj_new.balance = order_total_amount - order_obj_new.total_paid
log.debug(order_obj_new.dict(by_alias=False, exclude_defaults=False, exclude_unset=True, exclude={'order_line_list', 'cfg', 'created_on', 'updated_on'})) log.debug(order_obj_new.dict(by_alias=False, exclude_defaults=False, exclude_unset=True, exclude={'order_line_li', 'cfg', 'created_on', 'updated_on'}))
order_obj_data = order_obj_new.dict(by_alias=False, exclude_defaults=False, exclude_unset=True, exclude={'order_line_list', 'cfg', 'created_on', 'updated_on'}) order_obj_data = order_obj_new.dict(by_alias=False, exclude_defaults=False, exclude_unset=True, exclude={'order_line_li', 'cfg', 'created_on', 'updated_on'})
# SQL INSERT or UPDATE the order record # SQL INSERT or UPDATE the order record
log.info('SQL INSERT or UPDATE the order record') log.info('SQL INSERT or UPDATE the order record')
@@ -141,7 +141,7 @@ def save_order_obj(order_obj_new:Order_Base, repl_order_line_list:bool=False):
# Loop through the order_line list to SQL INSERT or UPDATE the records # Loop through the order_line list to SQL INSERT or UPDATE the records
log.info('Loop through the order_line list to SQL INSERT or UPDATE the records') log.info('Loop through the order_line list to SQL INSERT or UPDATE the records')
for order_line_obj_new in order_obj_new.order_line_list: for order_line_obj_new in order_obj_new.order_line_li:
log.info(f"New order_line: order_line_id_random={order_line_obj_new.id_random}; product_id_random={order_line_obj_new.product_id_random}") log.info(f"New order_line: order_line_id_random={order_line_obj_new.id_random}; product_id_random={order_line_obj_new.product_id_random}")
log.debug(order_line_obj_new.dict(by_alias=False, exclude_defaults=False, exclude_unset=False, exclude={'order_line_id_random', 'product_type_id', 'product_type', 'created_on', 'updated_on'})) log.debug(order_line_obj_new.dict(by_alias=False, exclude_defaults=False, exclude_unset=False, exclude={'order_line_id_random', 'product_type_id', 'product_type', 'created_on', 'updated_on'}))
@@ -174,7 +174,7 @@ def load_order_obj(order_id:int|str, inc_order_line_li:bool=False, inc_order_cfg
order_line_data['order_id'] = order_id order_line_data['order_id'] = order_id
if order_line_rec_li := sql_select(table_name='v_order_line', data=order_line_data, as_list=True):#, field_name='order_id', field_value=order_id): if order_line_rec_li := sql_select(table_name='v_order_line', data=order_line_data, as_list=True):#, field_name='order_id', field_value=order_id):
log.debug(order_line_rec_li) log.debug(order_line_rec_li)
order_rec['order_line_list'] = order_line_rec_li order_rec['order_line_li'] = order_line_rec_li
if inc_order_cfg: if inc_order_cfg:
if order_cfg_rec := sql_select(table_name='v_account_cfg_detail', field_name='account_id', field_value=order_rec.get('account_id', None)): if order_cfg_rec := sql_select(table_name='v_account_cfg_detail', field_name='account_id', field_value=order_rec.get('account_id', None)):

View File

@@ -4,8 +4,8 @@ import datetime, hashlib, logging, os, pytz, redis, secrets
from typing import Dict, List, Optional, Set, Union from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator
from ..db_sql import redis_lookup_id_random
from ..lib_general import * from ..lib_general import *
from ..log import *
from .common_field_schema import base_fields, default_num_bytes from .common_field_schema import base_fields, default_num_bytes
#from .supporting_core_models import * #from .supporting_core_models import *
@@ -138,7 +138,7 @@ class Order_Base(BaseModel):
created_on: Optional[datetime.datetime] = None created_on: Optional[datetime.datetime] = None
updated_on: Optional[datetime.datetime] = None updated_on: Optional[datetime.datetime] = None
order_line_list: List[Order_Line_Base] = [] order_line_li: List[Order_Line_Base] = []
cfg: Optional[Order_Cfg_Base] = Order_Cfg_Base() cfg: Optional[Order_Cfg_Base] = Order_Cfg_Base()

View File

@@ -4,8 +4,8 @@ import datetime, hashlib, logging, os, pytz, redis, secrets
from typing import Dict, List, Optional, Set, Union from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator
from ..db_sql import redis_lookup_id_random
from ..lib_general import * from ..lib_general import *
from ..log import *
from .common_field_schema import base_fields, default_num_bytes from .common_field_schema import base_fields, default_num_bytes
#from .account_model import Account_Base #from .account_model import Account_Base

View File

@@ -4,8 +4,8 @@ import datetime, hashlib, logging, os, pytz, redis, secrets
from typing import Dict, List, Optional, Set, Union from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator
from ..db_sql import redis_lookup_id_random
from ..lib_general import * from ..lib_general import *
from ..log import *
from .common_field_schema import base_fields, default_num_bytes from .common_field_schema import base_fields, default_num_bytes

View File

@@ -5,7 +5,7 @@ from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, PrivateAttr, ValidationError, validator
from ..lib_general import * from ..lib_general import *
from ..db_sql import sql_select from ..db_sql import redis_lookup_id_random, sql_select
from .person_model import Person_Base from .person_model import Person_Base

View File

@@ -4,8 +4,8 @@ import datetime, hashlib, logging, os, pytz, redis, secrets
from typing import Dict, List, Optional, Set, Union from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator
from ..db_sql import redis_lookup_id_random
from ..lib_general import * from ..lib_general import *
from ..log import *
from .common_field_schema import base_fields, default_num_bytes from .common_field_schema import base_fields, default_num_bytes
# from .account_model import Account_Base # from .account_model import Account_Base

View File

@@ -4,8 +4,8 @@ import datetime, hashlib, logging, os, pytz, redis, secrets
from typing import Dict, List, Optional, Set, Union from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator
from ..db_sql import redis_lookup_id_random
from ..lib_general import * from ..lib_general import *
from ..log import *
from .common_field_schema import base_fields, default_num_bytes from .common_field_schema import base_fields, default_num_bytes

View File

@@ -4,8 +4,8 @@ import datetime, hashlib, logging, os, pytz, redis, secrets
from typing import Dict, List, Optional, Set, Union from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator
from ..db_sql import redis_lookup_id_random
from ..lib_general import * from ..lib_general import *
from ..log import *
from .common_field_schema import base_fields, default_num_bytes from .common_field_schema import base_fields, default_num_bytes

View File

@@ -4,6 +4,7 @@ import datetime, hashlib, logging, os, pytz, redis, secrets
from typing import Dict, List, Optional, Set, Union from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator
from ..db_sql import redis_lookup_id_random
from ..lib_general import * from ..lib_general import *
from app.config import settings from app.config import settings

View File

@@ -4,8 +4,8 @@ import datetime, hashlib, logging, os, pytz, redis, secrets
from typing import Dict, List, Optional, Set, Union from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator
from ..db_sql import redis_lookup_id_random
from ..lib_general import * from ..lib_general import *
from ..log import *
from .common_field_schema import base_fields, default_num_bytes from .common_field_schema import base_fields, default_num_bytes
#from .site_model import Site_Base as Site_Base_2 #from .site_model import Site_Base as Site_Base_2

View File

@@ -4,8 +4,8 @@ import datetime, hashlib, logging, os, pytz, redis, secrets
from typing import Dict, List, Optional, Set, Union from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator
from ..db_sql import redis_lookup_id_random
from ..lib_general import * from ..lib_general import *
from ..log import *
from .common_field_schema import base_fields, default_num_bytes from .common_field_schema import base_fields, default_num_bytes
from .site_domain_model import Site_Domain_Base as Site_Domain_Base_2 from .site_domain_model import Site_Domain_Base as Site_Domain_Base_2

View File

@@ -5,7 +5,7 @@ from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, PrivateAttr, ValidationError, validator
from ..lib_general import * from ..lib_general import *
from ..db_sql import sql_select from ..db_sql import redis_lookup_id_random, sql_select
from .user_model import User_Base, User_Out_Base, User_New_Base from .user_model import User_Base, User_Out_Base, User_New_Base
from .user_role_model import User_Role_Base from .user_role_model import User_Role_Base

View File

@@ -4,6 +4,7 @@ import datetime, hashlib, logging, os, pytz, redis, secrets
from typing import Dict, List, Optional, Set, Union from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator
from ..db_sql import redis_lookup_id_random
from ..lib_general import * from ..lib_general import *
from .common_field_schema import base_fields, default_num_bytes from .common_field_schema import base_fields, default_num_bytes

View File

@@ -4,6 +4,7 @@ import datetime, hashlib, logging, os, pytz, redis, secrets
from typing import Dict, List, Optional, Set, Union from typing import Dict, List, Optional, Set, Union
from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator
from ..db_sql import redis_lookup_id_random
from ..lib_general import * from ..lib_general import *
from .common_field_schema import base_fields, default_num_bytes from .common_field_schema import base_fields, default_num_bytes

View File

@@ -12,7 +12,7 @@ from app.db_sql import *
from .api_crud import delete_obj_template, get_obj_template, get_obj_li_template, patch_obj_template, post_obj_template from .api_crud import delete_obj_template, get_obj_template, get_obj_li_template, patch_obj_template, post_obj_template
from ..models.order_cart_model import Order_Cart_Base from ..models.order_cart_model import Order_Cart_Base
from ..models.order_cart_methods import load_order_cart_obj from ..models.order_cart_methods import update_order_cart_obj, load_order_cart_obj
from ..models.response_model import * from ..models.response_model import *
@@ -42,31 +42,51 @@ async def post_order_cart_obj(
return result return result
@router.patch('/{obj_id}', response_model=Resp_Body_Base) @router.patch('/{order_cart_id}', response_model=Resp_Body_Base)
async def patch_order_cart_obj( async def patch_order_cart_obj(
obj_id: str = Query(..., min_length=1, max_length=22), order_cart_id: str = Query(..., min_length=1, max_length=22),
obj: Order_Cart_Base = None, order_cart_obj: Order_Cart_Base = None,
x_account_id: Optional[str] = Header(..., ), x_account_id: Optional[str] = Header(..., ),
return_obj: Optional[bool] = True, return_obj: Optional[bool] = True,
inc_order_cart_line_li: Optional[bool] = True,
inc_order_cart_cfg: Optional[bool] = True,
by_alias: Optional[bool] = True, by_alias: Optional[bool] = True,
exclude_unset: Optional[bool] = True, exclude_unset: Optional[bool] = True,
): ):
log.setLevel(logging.WARNING) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL log.setLevel(logging.WARNING) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
log.debug(locals()) log.debug(locals())
obj_type = 'order_cart' order_cart_obj_up_result = update_order_cart_obj(order_cart_obj)
obj_data_dict = obj.dict(by_alias=False, exclude_unset=True) if isinstance(order_cart_obj_up_result, int):
obj_data_dict['id'] = redis_lookup_id_random(record_id_random=obj_id, table_name=obj_type) log.info(f'Order cart update and the result was an int: {order_cart_obj_up_result}')
obj_data_dict['id_random'] = obj_id pass
result = patch_obj_template( elif isinstance(order_cart_obj_up_result, bool) and order_cart_obj_up_result:
obj_type=obj_type, log.info(f'Order cart update and the result was an bool: {order_cart_obj_up_result}')
data=obj_data_dict, pass
obj_id=obj_id, elif isinstance(order_cart_obj_up_result, bool) and not order_cart_obj_up_result:
return_obj=True, log.error(f'Order cart update and the result was an bool: {order_cart_obj_up_result}')
by_alias=True, return mk_resp(data=False, status_code=500) # Internal Server Error
exclude_unset=True,
) if order_cart_obj := load_order_cart_obj(order_cart_id=order_cart_id, inc_order_cart_line_li=inc_order_cart_line_li, inc_order_cart_cfg=inc_order_cart_cfg):
return result data = order_cart_obj.dict(by_alias=True, exclude_unset=False)
return mk_resp(data=data)
else:
return mk_resp(data=False, status_code=404) # Not Found
# obj_type = 'order_cart'
# obj_data_dict = obj.dict(by_alias=False, exclude_unset=True)
# obj_data_dict['id'] = redis_lookup_id_random(record_id_random=obj_id, table_name=obj_type)
# obj_data_dict['id_random'] = obj_id
# result = patch_obj_template(
# obj_type=obj_type,
# data=obj_data_dict,
# obj_id=order_cart_id,
# return_obj=True,
# by_alias=True,
# exclude_unset=True,
# )
# return result
@router.get('/list', response_model=Resp_Body_Base) @router.get('/list', response_model=Resp_Body_Base)
@@ -202,4 +222,4 @@ async def delete_order_cart_obj(
obj_type=obj_type, obj_type=obj_type,
obj_id=obj_id, obj_id=obj_id,
) )
return result return result