161 lines
7.2 KiB
Python
161 lines
7.2 KiB
Python
from app.utils.logger import logger
|
||
from app.api.services.base_service import BaseService
|
||
from marshmallow import ValidationError
|
||
from app.extensions import db
|
||
from app.models import MembersProducts, Products, Members, ProductsContacts
|
||
from app.api.helpers.response_helper import ResponseHelper
|
||
from app.api.schemas.user import UserSchema
|
||
|
||
import datetime
|
||
import random
|
||
|
||
|
||
class ContactService(BaseService):
|
||
|
||
@staticmethod
|
||
def process_request(data):
|
||
try:
|
||
with (db.session.begin()):
|
||
logger.info(f"Incoming ContactService data ==>>>> {data}")
|
||
validated_data = ContactService.validate_data(data, UserSchema())
|
||
token = validated_data.get('token')
|
||
uid = validated_data.get('uid')
|
||
member_data = Members.get_member_by_uid(uid)
|
||
member_id = member_data.id
|
||
|
||
contacts_product_list = Products.get_contact_supported_product_list(member_id)
|
||
category_data = []
|
||
for t in contacts_product_list:
|
||
category_data.append({
|
||
'cid': t.product_id,
|
||
'category_uid': t.uid,
|
||
'description': t.name,
|
||
})
|
||
|
||
cat_list = ['A000002', 'A000004', 'A000001', 'A000003']
|
||
page = 1
|
||
limit = 20
|
||
|
||
dList = []
|
||
contacts_data , total_count= ProductsContacts.get_all_contacts(member_id, page=1, limit=20)
|
||
if contacts_data:
|
||
for t in contacts_data:
|
||
new_l = {
|
||
"uid": str(t.uid),
|
||
"title": t.title,
|
||
"category": t.product_id,
|
||
"added": t.added,
|
||
"sender": t.sender,
|
||
"message": t.message,
|
||
}
|
||
dList.append(new_l)
|
||
|
||
# membersSubList, total_count = MembersProducts.get_all_subscriptions(product_id, member_id, page, limit)
|
||
# # Convert loans to dictionary format
|
||
# member_sub_data = []
|
||
# for subs in membersSubList:
|
||
# member_sub_data.append({
|
||
# 'id': subs.id,
|
||
# 'member_id': subs.member_id,
|
||
# 'product_id': subs.product_id,
|
||
# 'internal_url': subs.internal_url,
|
||
# 'external_url': subs.external_url,
|
||
# 'dns_group': subs.dns_group,
|
||
# 'status': subs.status,
|
||
# 'updated': subs.updated,
|
||
# "added": subs.added,
|
||
# })
|
||
|
||
# sample_range = random.randint(20, 60)
|
||
# for x in range(sample_range):
|
||
# calDate = datetime.datetime.utcnow() + datetime.timedelta(minutes=180 * random.randint(1, 20))
|
||
# new_l = {
|
||
# "uid": "425611f2-c692-4404-b93d-76ca7a5ce7" + str(x),
|
||
# "title": "Contact Random Item on " + str(x),
|
||
# "category": cat_list[random.randint(0, 3)],
|
||
# "added": calDate,
|
||
# "sender": "Firstname Lastname" + str(random.randint(1, 4)),
|
||
# "message": ContactService.dummy_message()
|
||
# }
|
||
# dList.append(new_l)
|
||
total_pages = (total_count + limit - 1) // limit
|
||
response_data = {
|
||
"last_update": datetime.datetime.utcnow(),
|
||
"member_id": member_id,
|
||
"category": category_data,
|
||
"contacts": dList,
|
||
'pagination': {
|
||
'total_count': total_count,
|
||
'total_pages': total_pages,
|
||
'current_page': page,
|
||
'limit': limit,
|
||
'has_next': page < total_pages,
|
||
'has_prev': page > 1
|
||
}
|
||
}
|
||
|
||
return ResponseHelper.success(data=response_data)
|
||
|
||
except ValidationError as err:
|
||
|
||
logger.error(f"Validation Error: {getattr(err, 'messages', str(err))}")
|
||
db.session.rollback()
|
||
return ResponseHelper.unprocessable_entity(result_description="Validation exception")
|
||
|
||
except ValueError as err:
|
||
logger.error(f"{getattr(err, 'messages', str(err))}")
|
||
db.session.rollback()
|
||
return ResponseHelper.error(result_description=str(err))
|
||
|
||
except Exception as e:
|
||
logger.error(f"An error occurred: {str(e)}", exc_info=True)
|
||
db.session.rollback()
|
||
return ResponseHelper.internal_server_error()
|
||
|
||
@staticmethod
|
||
def dummy_message():
|
||
dmm = "Dmummy Message" + str(random.randint(100, 400))
|
||
mss = f"""
|
||
{dmm}I truly believe Augustine’s words are true and if you look at history you know it is true. There are many people in the world with amazing talents who realize only a small percentage of their potential. We all know people who live this truth.
|
||
|
||
We also know those epic stories, those modern-day legends surrounding the early failures of such supremely successful folks as Michael Jordan and Bill Gates. We can look a bit further back in time to Albert Einstein or even further back to Abraham Lincoln. What made each of these people so successful? Motivation.
|
||
|
||
We know this in our gut, but what can we do about it? How can we motivate ourselves? One of the most difficult aspects of achieving success is staying motivated over the long haul.
|
||
"""
|
||
return mss
|
||
|
||
@staticmethod
|
||
def process_save_contacts(data):
|
||
logger.info(f"Process_save_contacts IN -> : {data}", exc_info=True)
|
||
try:
|
||
|
||
message = data.get('message', '')
|
||
subscription_uid = data.get('subscription_uid', '')
|
||
title = data.get('title', '')
|
||
email = data.get('email', '')
|
||
sender = data.get('sender', '')
|
||
contact_result = None
|
||
memSubb = MembersProducts.get_member_product_by_subscription_uid(subscription_uid)
|
||
if memSubb:
|
||
member_id = memSubb.member_id,
|
||
product_id = memSubb.product_id
|
||
if message != '' and title != '' and email != '' and sender != '':
|
||
logger.info(f"Ready to save data: {data}", exc_info=True)
|
||
contact_result = ProductsContacts.add_product_contact(
|
||
member_id, product_id, subscription_uid, title, email, sender, message
|
||
)
|
||
# if contact_result and contact_result.uid != '':
|
||
#
|
||
response_data = {
|
||
"last_message": datetime.datetime.utcnow(),
|
||
"subscription_uid": subscription_uid,
|
||
"result": contact_result.uid if contact_result and contact_result.uid != '' else None,
|
||
}
|
||
|
||
return ResponseHelper.success(data=response_data)
|
||
|
||
except Exception as e:
|
||
logger.error(f"An error occurred: {str(e)}", exc_info=True)
|
||
return ResponseHelper.internal_server_error()
|
||
|