general cleanup

This commit is contained in:
CHIEFSOFT\ameye
2025-08-25 19:27:37 -04:00
parent 6625b9edc9
commit 8109d95422
19 changed files with 380 additions and 137 deletions
+60
View File
@@ -228,6 +228,66 @@ merms_panel=# select product_id,description from products;
A000005 | Get Open EMR for practice management
(5 rows)
CREATE TABLE products_templates (
id SERIAL,
uid uuid DEFAULT uuid_generate_v4(),
product_id VARCHAR(25) REFERENCES products(product_id),
name VARCHAR(55) UNIQUE NOT NULL,
status INT DEFAULT 0,
owner_uid VARCHAR(100),
provision_name VARCHAR(250),
added timestamp without time zone DEFAULT now()
);
ALTER TABLE ONLY products_templates
ADD CONSTRAINT products_templates_id_key UNIQUE (id);
ALTER TABLE products_templates OWNER TO merms_panel;
INSERT INTO products_templates(product_id,name,provision_name,status)
VALUES(
'A000001',
'Template A01',
'registry.chiefsoft.com/pweb/pweb-01-merms-pweb0004:latest',
1);
INSERT INTO products_templates(product_id,name,provision_name,status)
VALUES(
'A000001',
'Template A02',
'registry.chiefsoft.com/pweb/pweb-01-merms-pweb0005:latest',
1);
INSERT INTO products_templates(product_id,name,provision_name,status)
VALUES(
'A000001',
'Template A03',
'registry.chiefsoft.com/pweb/pweb-01-merms-pweb0006:latest',
1);
INSERT INTO products_templates(product_id,name,provision_name,status)
VALUES(
'A000002',
'Practice B01',
'registry.chiefsoft.com/pweb/pweb-01-merms-pweb0007:latest',
1
);
INSERT INTO products_templates(product_id,name,provision_name,status)
VALUES(
'A000002',
'Practice B02',
'registry.chiefsoft.com/pweb/pweb-01-merms-pweb0008:latest',
1
);
INSERT INTO products_templates(product_id,name,provision_name,status)
VALUES(
'A000002',
'',
''
);
CREATE TABLE members_products (
+8 -8
View File
@@ -1,12 +1,12 @@
from app.api.services.eligibility_check import EligibilityCheckService
from app.api.services.select_offer import SelectOfferService
from app.api.services.provide_loan import ProvideLoanService
from app.api.services.loan_status import LoanStatusService
from app.api.services.repayment import RepaymentService
from app.api.services.customer_consent import CustomerConsentService
from app.api.services.notification_callback import NotificationCallbackService
# from app.api.services.eligibility_check import EligibilityCheckService
# from app.api.services.select_offer import SelectOfferService
# from app.api.services.provide_loan import ProvideLoanService
# from app.api.services.loan_status import LoanStatusService
# from app.api.services.repayment import RepaymentService
# from app.api.services.customer_consent import CustomerConsentService
# from app.api.services.notification_callback import NotificationCallbackService
from app.api.services.authorization import AuthorizationService
from app.api.services.offer_analysis import OfferAnalysis
# from app.api.services.offer_analysis import OfferAnalysis
from app.api.services.login import LoginService
from app.api.services.register import RegisterService
from app.api.services.products import ProductsService
+1 -1
View File
@@ -2,7 +2,7 @@ from flask import session, jsonify
# from app.models.loan import Loan
from app.utils.logger import logger
from app.api.services.base_service import BaseService
from app.api.schemas.eligibility_check import EligibilityCheckSchema
#from app.api.schemas.eligibility_check import EligibilityCheckSchema
from marshmallow import ValidationError
from app.api.enums import TransactionType
# from app.api.integrations import SimbrellaIntegration
+1 -1
View File
@@ -1,4 +1,4 @@
from app.models import Customer, Account, Transaction
# from app.models import Customer, Account, Transaction
from app.api.enums import TransactionType
from flask import jsonify
from marshmallow import ValidationError
+1 -1
View File
@@ -9,7 +9,7 @@ from marshmallow import ValidationError
from app.extensions import db
from app.models import MembersProducts, Products, Members
from app.api.services.offer_analysis import OfferAnalysis
# from app.api.services.offer_analysis import OfferAnalysis
from app.api.helpers.response_helper import ResponseHelper
from werkzeug.security import generate_password_hash, check_password_hash
# from app.api.schemas.register import RegisterSchema
+2 -2
View File
@@ -1,9 +1,9 @@
from flask import request, jsonify
from app.api.helpers.response_helper import ResponseHelper
from app.api.services.base_service import BaseService
# from app.api.services.base_service import BaseService
from marshmallow import ValidationError
from app.utils.logger import logger
from app.api.schemas.customer_consent import CustomerConsentSchema
# from app.api.schemas.customer_consent import CustomerConsentSchema
from app.api.services.base_service import BaseService
from app.api.enums import TransactionType
from app.extensions import db
+96 -51
View File
@@ -3,7 +3,8 @@ 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, ProductsDetails, ProductsDetails, ProvisionActions, MembersProductsSettings
from app.models import MembersProducts, Products, Members, ProductsDetails, ProductsDetails, ProvisionActions, \
MembersProductsSettings, ProductsTemplates
from app.api.helpers.response_helper import ResponseHelper
from app.api.schemas.myproduct import MyProductSchema
from app.api.schemas.provision import ProvisionSchema
@@ -15,6 +16,7 @@ import jwt
import random
from app.config import Config
class MyProductsService(BaseService):
@staticmethod
@@ -22,28 +24,75 @@ class MyProductsService(BaseService):
pass
@staticmethod
def mpproduct_template_data():
# class MyProductSchema(Schema):
# token = fields.Str(required=True)
# uid = fields.Str(required=True)
# product_id = fields.Str(required=True)
def mpproduct_template_data(data):
try:
with db.session.begin():
logger.info(f"Incoming MyProduct data ==>>>> {data}")
validated_data = MyProductsService.validate_data(data, MyProductSchema())
token = validated_data.get('token')
uid = validated_data.get('uid')
member_data = Members.get_member_by_uid(uid)
member_id = member_data.id
template_data = {
'template_16' : { 'title': 'Template Name-16', 'template_id': '02af24fd-2b1a-46ed-af21-87018e726408', 'banner': 'file-icon/svg.png', 'active': '0' },
'template_22' : { 'title': 'Template Name-22', 'template_id': '8b296894-42e4-4f2e-abd1-7c2a38d6e07b', 'banner': 'file-icon/svg.png', 'active': '0' },
'template_47' : { 'title': 'Template Name-47', 'template_id': 'ef2ffa1c-9272-42cd-9d33-0e614047b4f8', 'banner': 'file-icon/svg.png', 'active': '0' },
'template_25' : { 'title': 'Template Name-25', 'template_id': 'b3a7ba31-dc47-4a40-a5cc-fd1ff27d6b78', 'banner': 'file-icon/svg.png', 'active': '1' },
'template_49' : { 'title': 'Template Name-49', 'template_id': '60959c69-6672-4f69-a006-eeb7d210e605', 'banner': 'file-icon/svg.png', 'active': '0' },
'template_27' : { 'title': 'Template Name-27', 'template_id': 'e4acb98a-c584-45f2-bece-af677dcf0a1f', 'banner': 'file-icon/svg.png', 'active': '0' },
'template_51' : { 'title': 'Template Name-51', 'template_id': '975ee42e-3169-4978-92d7-d28e7e2ac014', 'banner': 'file-icon/svg.png', 'active': '0' },
'template_9' : { 'title': 'Template Name-9', 'template_id': 'fc8f0738-6500-4775-9895-2047cd275302', 'banner': 'file-icon/svg.png', 'active': '0' },
}
product_id = validated_data.get('product_id')
response_data = {
"templates": template_data,
"last_update": datetime.datetime.utcnow(),
}
return ResponseHelper.success(data=response_data)
# class MyProductSchema(Schema):
# token = fields.Str(required=True)
# uid = fields.Str(required=True)
# product_id = fields.Str(required=True)
templates = ProductsTemplates.get_template_by_product_id(product_id)
template_data = {
'template_16': {'title': 'Template Name-16', 'template_id': '02af24fd-2b1a-46ed-af21-87018e726408',
'banner': 'file-icon/svg.png', 'active': '0'},
'template_22': {'title': 'Template Name-22', 'template_id': '8b296894-42e4-4f2e-abd1-7c2a38d6e07b',
'banner': 'file-icon/svg.png', 'active': '0'},
'template_47': {'title': 'Template Name-47', 'template_id': 'ef2ffa1c-9272-42cd-9d33-0e614047b4f8',
'banner': 'file-icon/svg.png', 'active': '0'},
'template_25': {'title': 'Template Name-25', 'template_id': 'b3a7ba31-dc47-4a40-a5cc-fd1ff27d6b78',
'banner': 'file-icon/svg.png', 'active': '1'},
'template_49': {'title': 'Template Name-49', 'template_id': '60959c69-6672-4f69-a006-eeb7d210e605',
'banner': 'file-icon/svg.png', 'active': '0'},
'template_27': {'title': 'Template Name-27', 'template_id': 'e4acb98a-c584-45f2-bece-af677dcf0a1f',
'banner': 'file-icon/svg.png', 'active': '0'},
'template_51': {'title': 'Template Name-51', 'template_id': '975ee42e-3169-4978-92d7-d28e7e2ac014',
'banner': 'file-icon/svg.png', 'active': '0'},
'template_9': {'title': 'Template Name-9', 'template_id': 'fc8f0738-6500-4775-9895-2047cd275302',
'banner': 'file-icon/svg.png', 'active': '0'},
}
template_data =[]
for t in templates:
template_data.append({
'id': t.id,
'template_uid': t.uid,
'title': t.name,
'active': 1,
'added': t.added.isoformat() if t.added else None
})
response_data = {
"product_id": product_id,
"templates": template_data,
"last_update": datetime.datetime.utcnow(),
}
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 process_provision(data):
@@ -67,16 +116,16 @@ class MyProductsService(BaseService):
}, 400
logger.info(f"GET HERE ******************************** : {data}", exc_info=True)
subscription = MembersProducts.get_member_product_by_product_member_id(member_id, product_id)
subscription = MembersProducts.get_member_product_by_product_member_id(member_id, product_id)
provision_activities = ProvisionActions.get_provision_action_by_product_uid(subscription.uid, 4)
provision_activities_data =[]
provision_activities_data = []
for t in provision_activities:
provision_activities_data.append({
'id': t.id,
'uid': t.uid,
'action': t.action,
'added': t.added.isoformat() if t.added else None,
'id': t.id,
'uid': t.uid,
'action': t.action,
'added': t.added.isoformat() if t.added else None,
})
response_data = {
@@ -105,8 +154,6 @@ class MyProductsService(BaseService):
db.session.rollback()
return ResponseHelper.internal_server_error()
@staticmethod
def process_subscription(data):
try:
@@ -129,9 +176,9 @@ class MyProductsService(BaseService):
}, 400
logger.info(f"GET HERE ******************************** : {data}", exc_info=True)
mumberSub = MembersProducts.get_member_product_by_product_member_id(member_id, product_id)
mumberSub = MembersProducts.get_member_product_by_product_member_id(member_id, product_id)
if mumberSub:
if mumberSub:
logger.error(f"Ready to add data to tables")
response_data = {
"subscription": mumberSub,
@@ -142,10 +189,10 @@ class MyProductsService(BaseService):
return ResponseHelper.success(data=response_data)
internal_url = str(random.randint(100000, 999999)) + ".devprov.mermsemr.com"
#INSERT_NEW_PRODUCT = "INSERT INTO members_products (member_id ,product_id,status,internal_url) VALUES (%s, %s, %s, %s)"
# INSERT_NEW_PRODUCT = "INSERT INTO members_products (member_id ,product_id,status,internal_url) VALUES (%s, %s, %s, %s)"
# val_insert = (member_id, product_id,6,internal_url)
status = 6
subscription = MembersProducts.create_subscription(member_id ,product_id,status,internal_url)
subscription = MembersProducts.create_subscription(member_id, product_id, status, internal_url)
response_data = {
"subscription_uid": subscription.uid,
@@ -173,8 +220,6 @@ class MyProductsService(BaseService):
db.session.rollback()
return ResponseHelper.internal_server_error()
@staticmethod
def process_settings(data):
try:
@@ -191,7 +236,6 @@ class MyProductsService(BaseService):
product_id = validated_data.get('product_id')
product_settings = validated_data.get('settings')
memberSubscription = MembersProducts.get_member_product_by_product_member_id(member_id, product_id)
if memberSubscription is not None:
logger.info(f"Incoming MyProduct data ==>>>> {memberSubscription}")
@@ -210,7 +254,8 @@ class MyProductsService(BaseService):
for key in settings.keys():
setting_value = settings[key]
subscription_uid = memberSubscription.uid
MembersProductsSettings.save_update_product_settings(member_id,subscription_uid,product_id,key, 'TXT', setting_value)
MembersProductsSettings.save_update_product_settings(member_id, subscription_uid, product_id, key,
'TXT', setting_value)
# Simulate processing
response_data = {
@@ -219,7 +264,8 @@ class MyProductsService(BaseService):
"uid": str(uid),
}
logger.error(f"Going for Thread ******************** ")
thread = Thread(target=MyProductsService.async_send_settings_refresh_to_kafka, args=(response_data, subscription_uid, "REFRESH_PRODUCT_SETTINGS"))
thread = Thread(target=MyProductsService.async_send_settings_refresh_to_kafka,
args=(response_data, subscription_uid, "REFRESH_PRODUCT_SETTINGS"))
thread.start()
logger.error(f"After the Thread ******************** ")
@@ -252,35 +298,34 @@ class MyProductsService(BaseService):
member_data = Members.get_member_by_uid(uid)
member_id = member_data.id
product_id = validated_data.get('product_id')
product_subscription_uid=''
product_subscription_uid = ''
product_subscription_external_url = ''
product_subscription_internal_url = ''
product_data = Products.get_product_by_product_id(product_id)
product_data = Products.get_product_by_product_id(product_id)
product_description = ProductsDetails.get_product_details_with_product_id(product_id)
productDataStatus = product_data.status
memberSubscription = MembersProducts.get_member_product_by_product_member_id(member_id, product_id)
memberSubscription = MembersProducts.get_member_product_by_product_member_id(member_id, product_id)
if memberSubscription is not None:
logger.info(f"Incoming MyProduct data ==>>>> {memberSubscription}")
productDataStatus = memberSubscription.status
product_subscription_uid = memberSubscription.uid
product_subscription_uid = memberSubscription.uid
product_subscription_external_url = memberSubscription.external_url
product_subscription_internal_url = memberSubscription.internal_url
# "banner": "banner.jpg",
myproduct_data = {
"myproudct": {
"banner": product_data.banner,
"description": product_description.details,
"sale_text" : product_description.sale_text,
"sale_text": product_description.sale_text,
"internal_url": product_subscription_internal_url,
"external_url": product_subscription_external_url,
"price_text": "90 days free and 3.95/Month",
"product_id": product_data.product_id,
"product_name": product_data.name,
"product_id": product_data.product_id,
"product_name": product_data.name,
"product_subscription_uid": product_subscription_uid,
"product_uid": product_data.uid,
"product_uid": product_data.uid,
"promotion_text": "Start Free Today !",
"subscription_uid": product_subscription_uid,
"status": productDataStatus,
@@ -336,12 +381,13 @@ class MyProductsService(BaseService):
if memberSubscription is not None:
logger.info(f"Incoming MyProduct data ==>>>> {memberSubscription}")
product_subscription_uid = memberSubscription.uid
settings_data_result = MembersProductsSettings.get_product_settings_by_product_id_and_member_id(product_id, member_id)
settings_data_result = MembersProductsSettings.get_product_settings_by_product_id_and_member_id(
product_id, member_id)
if settings_data_result is not None:
for t in settings_data_result:
settings_data.append({
'setting_key': t.settings_key,
'setting_value': t.setting_value,
'setting_key': t.settings_key,
'setting_value': t.setting_value,
})
# Simulate processing
@@ -368,4 +414,3 @@ class MyProductsService(BaseService):
logger.error(f"An error occurred: {str(e)}", exc_info=True)
db.session.rollback()
return ResponseHelper.internal_server_error()
+1 -1
View File
@@ -3,7 +3,7 @@ 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 Offer, MembersPending, Members
from app.models import MembersPending, Members
from app.api.helpers.response_helper import ResponseHelper
from werkzeug.security import generate_password_hash, check_password_hash
+15 -12
View File
@@ -1,16 +1,16 @@
from .customer import Customer
# from .customer import Customer
from .account import Account
from .loan import Loan
from .transaction import Transaction
from .repayment import Repayment
from .loan_charge import LoanCharge
from .offer import Offer
from .charge import Charge
from .rac_checks import RACCheck
from .loan_repayment_schedule import LoanRepaymentSchedule
from .transaction_offers import TransactionOffer
from .repayments_data import RepaymentsData
from .salary import Salary
# from .loan import Loan
# from .transaction import Transaction
# from .repayment import Repayment
# from .loan_charge import LoanCharge
# from .offer import Offer
# from .charge import Charge
# from .rac_checks import RACCheck
# from .loan_repayment_schedule import LoanRepaymentSchedule
# from .transaction_offers import TransactionOffer
# from .repayments_data import RepaymentsData
# from .salary import Salary
from .members import Members
from .products import Products
from .members_products import MembersProducts
@@ -24,6 +24,8 @@ from .members_products_settings import MembersProductsSettings
from .members_profile import MembersProfile
from .subscription_options import SubscriptionOptions
from .subscription_options_items import SubscriptionOptionsItems
from .products_templates import ProductsTemplates
@@ -32,6 +34,7 @@ __all__ = ['Members','Customer', 'Account', 'Products',
'MembersProducts', 'MembersActions', 'MembersPending', 'ProductsDetails',
'ProvisionActions', 'MembersProductsRefresh','MembersProductsSettings',
'PasswordReset','MembersProfile','SubscriptionOptions','SubscriptionOptionsItems',
'ProductsTemplates',
'Loan', 'Transaction', 'Repayment',
'LoanCharge', 'Offer', 'Charge', 'RACCheck', 'LoanRepaymentSchedule',
+6 -6
View File
@@ -15,12 +15,12 @@ class Account(db.Model):
created_at = db.Column(db.DateTime(timezone=True), server_default=func.now())
updated_at = db.Column(db.DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
customer = relationship(
"Customer",
primaryjoin="Customer.id == Account.customer_id",
foreign_keys=[customer_id],
back_populates="accounts",
)
# customer = relationship(
# "Customer",
# primaryjoin="Customer.id == Account.customer_id",
# foreign_keys=[customer_id],
# back_populates="accounts",
# )
@classmethod
def create_account(cls, id, customer_id, account_type, status='active'):
+6 -6
View File
@@ -15,12 +15,12 @@ class Charge(db.Model):
due = db.Column(db.Integer, nullable=False)
created_at = db.Column(db.DateTime(timezone=True), server_default=func.now())
updated_at = db.Column(db.DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
offer = relationship(
"Offer",
primaryjoin="Charge.offer_id == Offer.id",
foreign_keys=[offer_id],
back_populates="charges",
)
# offer = relationship(
# "Offer",
# primaryjoin="Charge.offer_id == Offer.id",
# foreign_keys=[offer_id],
# back_populates="charges",
# )
@classmethod
def add_charges(cls, offer_id, charges):
+18 -18
View File
@@ -16,26 +16,26 @@ class Customer(db.Model):
country_code = db.Column(db.String(3), nullable=False)
created_at = db.Column(db.DateTime(timezone=True), server_default=func.now())
updated_at = db.Column(db.DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
accounts = relationship(
"Account",
primaryjoin="Customer.id == Account.customer_id",
foreign_keys="Account.customer_id",
back_populates="customer",
)
# accounts = relationship(
# # "Account",
# # primaryjoin="Customer.id == Account.customer_id",
# # foreign_keys="Account.customer_id",
# # back_populates="customer",
# # )
loans = relationship(
"Loan",
primaryjoin="Customer.id == Loan.customer_id",
foreign_keys="Loan.customer_id",
back_populates="customer",
)
# loans = relationship(
# "Loan",
# primaryjoin="Customer.id == Loan.customer_id",
# foreign_keys="Loan.customer_id",
# back_populates="customer",
# )
transaction_offers = relationship(
"TransactionOffer",
primaryjoin="Customer.id == TransactionOffer.customer_id",
foreign_keys="TransactionOffer.customer_id",
back_populates="customer",
)
# transaction_offers = relationship(
# "TransactionOffer",
# primaryjoin="Customer.id == TransactionOffer.customer_id",
# foreign_keys="TransactionOffer.customer_id",
# back_populates="customer",
# )
@classmethod
def is_valid_customer(cls, customer_id):
+6 -6
View File
@@ -50,12 +50,12 @@ class Loan(db.Model):
verify_result = db.Column(db.String(10), nullable=True)
verify_description = db.Column(db.String(100), nullable=True)
customer = relationship(
"Customer",
primaryjoin="Customer.id == Loan.customer_id",
foreign_keys=[customer_id],
back_populates="loans",
)
# customer = relationship(
# "Customer",
# primaryjoin="Customer.id == Loan.customer_id",
# foreign_keys=[customer_id],
# back_populates="loans",
# )
loan_charges = relationship(
"LoanCharge",
+6 -6
View File
@@ -19,12 +19,12 @@ class LoanCharge(db.Model):
due_date = db.Column(db.DateTime, nullable=True)
created_at = db.Column(db.DateTime(timezone=True), server_default=func.now())
updated_at = db.Column(db.DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
loan = relationship(
"Loan",
primaryjoin="LoanCharge.loan_id == Loan.id",
foreign_keys=[loan_id],
back_populates="loan_charges",
)
# loan = relationship(
# "Loan",
# primaryjoin="LoanCharge.loan_id == Loan.id",
# foreign_keys=[loan_id],
# back_populates="loan_charges",
# )
@classmethod
def create_charges_for_loan(cls, loan_id, transaction_id, charges, referenced_amount = 0.0):
+6 -6
View File
@@ -20,12 +20,12 @@ class LoanRepaymentSchedule(db.Model):
created_at = db.Column(db.DateTime(timezone=True), server_default=func.now())
updated_at = db.Column(db.DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
loan = relationship(
"Loan",
primaryjoin="LoanRepaymentSchedule.loan_id == Loan.id",
foreign_keys=[loan_id],
back_populates="loan_repayment_schedules",
)
# loan = relationship(
# "Loan",
# primaryjoin="LoanRepaymentSchedule.loan_id == Loan.id",
# foreign_keys=[loan_id],
# back_populates="loan_repayment_schedules",
# )
@classmethod
+6 -6
View File
@@ -24,12 +24,12 @@ class Offer(db.Model):
created_at = db.Column(db.DateTime(timezone=True), server_default=func.now())
updated_at = db.Column(db.DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
charges = relationship(
"Charge",
primaryjoin="Offer.id == Charge.offer_id",
foreign_keys="Charge.offer_id",
back_populates="offer",
)
# charges = relationship(
# "Charge",
# primaryjoin="Offer.id == Charge.offer_id",
# foreign_keys="Charge.offer_id",
# back_populates="offer",
# )
@classmethod
def get_all_offers(cls):
+94
View File
@@ -0,0 +1,94 @@
from datetime import datetime, timezone
from app.extensions import db
from app.models.charge import Charge
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
class Offer(db.Model):
__tablename__ = 'payments'
id = db.Column(db.String, primary_key=True)
product_id = db.Column(db.String, nullable=False)
min_amount = db.Column(db.Float, nullable=False)
max_amount = db.Column(db.Float, nullable=False)
tenor = db.Column(db.Integer, nullable=False)
schedule = db.Column(db.Integer, nullable=True)
interest_rate = db.Column(db.Float, default=3.0)
management_rate = db.Column(db.Float, default=1.0)
insurance_rate = db.Column(db.Float, default=1.0)
vat_rate = db.Column(db.Float, default=7.5)
list_order = db.Column(db.Integer, nullable=True)
max_daily_loans = db.Column(db.Integer, nullable=True)
max_active_loans = db.Column(db.Integer, nullable=True)
max_life_loans = db.Column(db.Integer, nullable=True)
created_at = db.Column(db.DateTime(timezone=True), server_default=func.now())
updated_at = db.Column(db.DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
charges = relationship(
"Charge",
primaryjoin="Offer.id == Charge.offer_id",
foreign_keys="Charge.offer_id",
back_populates="offer",
)
@classmethod
def get_all_offers(cls):
"""
Return all offers in dictionary format.
"""
offers = cls.query.all()
if not offers:
raise ValueError(f"No available offers")
return offers
@classmethod
def is_valid_offer(cls, offer_id):
offer = cls.query.filter_by(id=str(offer_id)).first()
if not offer:
return False
return offer
@classmethod
def get_offer_by_id(cls, offer_id):
"""
Return an offer by its ID.
"""
offer = cls.query.filter_by(id=str(offer_id)).first()
if not offer:
raise ValueError(f"Offer with ID {offer_id} not found")
return offer
@classmethod
def get_offer_by_product_id(cls, product_id):
"""
Return an offer by its product ID.
"""
offer = cls.query.filter_by(product_id=str(product_id)).first()
if not offer:
raise ValueError(f"Offer with Product ID {product_id} not found")
return offer
def to_dict(self):
return {
"offerId": self.id,
"productId": self.product_id,
"minAmount": self.min_amount,
"maxAmount": self.max_amount,
"tenor": self.tenor,
"interest_rate": self.interest_rate,
"management_rate": self.management_rate,
"insurance_rate": self.insurance_rate,
"vat_rate": self.vat_rate,
"maxDailyLoans": self.max_daily_loans,
"maxActiveLoans": self.max_active_loans,
"maxLifeLoans": self.max_life_loans
}
def __repr__(self):
return f'<LoanOffer {self.id}>'
+41
View File
@@ -0,0 +1,41 @@
from datetime import datetime, timezone
from app.extensions import db
from app.models.charge import Charge
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
class ProductsTemplates(db.Model):
__tablename__ = 'products_templates'
id = db.Column(db.String, primary_key=True)
uid = db.Column(db.String, nullable=False)
product_id = db.Column(db.String, nullable=False)
name = db.Column(db.String, nullable=False)
status = db.Column(db.Integer, nullable=True, default=1)
owner_uid = db.Column(db.String, nullable=False)
provision_name = db.Column(db.String, nullable=False)
added = db.Column(db.DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
@classmethod
def get_template_by_product_id(cls, product_id):
templates = cls.query.filter_by(product_id=str(product_id)).all()
if not templates:
raise ValueError(f"Templates with Product ID {product_id} not found")
return templates
def to_dict(self):
return {
"id": self.id,
"uid": self.uid,
"product_id": self.product_id,
"name": self.name,
"status": self.status,
"owner_uid": self.owner_uid,
"provision_name": self.provision_name,
"provision_name": self.provision_name
}
def __repr__(self):
return f'<LoanOffer {self.id}>'
+6 -6
View File
@@ -24,12 +24,12 @@ class TransactionOffer(db.Model):
created_at = db.Column(db.DateTime(timezone=True), server_default=func.now())
updated_at = db.Column(db.DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
customer = relationship(
"Customer",
primaryjoin="Customer.id == TransactionOffer.customer_id",
foreign_keys=[customer_id],
back_populates="transaction_offers",
)
# customer = relationship(
# "Customer",
# primaryjoin="Customer.id == TransactionOffer.customer_id",
# foreign_keys=[customer_id],
# back_populates="transaction_offers",
# )
@classmethod
def is_valid_transaction_offer(cls, transaction_offer, customer_id, product_id):