plan_maker_v3.0 / app.py
Ninad077's picture
Update app.py
fe8555c verified
# Importing necessary libraries
import os
import streamlit as st
import pandas as pd
from html2image import Html2Image
from io import BytesIO
from PIL import Image
from datetime import datetime
from utilities import (
initialize_session_state, save_user_data, generate_rule_id, generate_plan_id,
display_saved_records, load_theme_config, store_and_fetch_company_info,
get_feature_user_data, default_button_click, custom_button_click, uploader,
render_selectboxes, insert_into_bq
)
from html_templates import (
app_title, plan_info_header, button_styles, rule_info_header,
expected_billing_header, final_billing_header, side_logo
)
from placeholders import (
fee_type_options, fee_nature_options, variable_options, chargeable_on_options,
plan_validity_options, payment_method_options, fee_reversal_options, threshold_options
)
from mapping import new_mapping
from slab import generate_slab_data
initialize_session_state()
theme_settings = load_theme_config()
# Streamlit UI elements
st.sidebar.markdown(side_logo, unsafe_allow_html=True)
st.markdown(app_title, unsafe_allow_html=True)
st.write(" ")
# User input section
user_name = st.sidebar.text_input("Enter your name:")
selected_business_head = st.sidebar.selectbox(
"Business Head", ["", "Commerce India", "Reliance", "Commerce Global", "Government Projects", "Individual BH"],
help="Business Head is used for cost centre allocation"
)
company_id = st.sidebar.text_input("Company ID", help="Enter the company ID")
store_and_fetch_company_info(company_id)
st.sidebar.text_input("Company Name", value=st.session_state.get('company_name', ''), disabled=False)
currency = st.sidebar.radio("Currency", options=["INR", "USD"], help="Select the type of currency")
bundle_by = st.sidebar.radio("Bundle by", options=["Single value", "Feature specific"], help="Select the bundle")
# Feature specific options
if bundle_by == "Feature specific":
plan_name = st.sidebar.text_input("Plan Name", help="Enter the name of the plan")
plan_description = st.sidebar.text_area("Plan Description", max_chars=250, help="Describe the plan")
plan_start_date = st.sidebar.date_input("Plan Start Date", value=datetime.now(), help="Select the start date of the plan")
col1, col2 = st.sidebar.columns([0.25, 0.45])
with col1:
default_clicked = st.button("Default mapping")
with col2:
custom_clicked = st.button("Custom mapping")
if default_clicked:
default_button_click()
elif custom_clicked:
custom_button_click()
st.markdown(button_styles, unsafe_allow_html=True)
if st.session_state.get('button_clicked') == 'default':
st.session_state['new_mapping'] = new_mapping
st.session_state['mapping_mode'] = 'default'
st.sidebar.markdown(rule_info_header, unsafe_allow_html=True)
elif st.session_state.get('button_clicked') == 'custom':
st.markdown(button_styles, unsafe_allow_html=True)
uploaded_file = st.sidebar.file_uploader("Upload a file:", type=['csv', 'xlsx'], key='file_uploader')
st.sidebar.markdown(rule_info_header, unsafe_allow_html=True)
if uploaded_file is not None:
uploader(uploaded_file)
if st.session_state.get('mapping_mode'):
render_selectboxes(st.session_state, st.session_state.get('new_mapping'))
selected_fee_nature = st.selectbox("Fee Nature:", [""] + fee_nature_options, key="fee_nature_select", help="Fee nature is an option to consume the price in flat / % / slab")
######################################################## Slab based ###########################################################
if selected_fee_nature == "Slab based":
slab_data = generate_slab_data()
selected_payment_method = st.selectbox("Payment Method", [""] + payment_method_options, help="Payment method defines the mode of payment of the plan", key="py_vd_2")
os.environ['selected_payment_method'] = selected_payment_method
rule_id = None
plan_id = None
user_data = None
project_id = "fynd-db"
dataset_id = "finance_dwh"
table_id = "plan_v2"
service_account_info = {
"type": "service_account",
"project_id": "fynd-db",
"private_key_id": "48954327ef172acc3091a91881840dc353ff0413",
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCmIs0vgXflZmHD\n0IeHCiDEXavRb2GvRQqkCZGLy/EHFO7XLmpNrFzZHTSQach6HErARWTMsd2AMIA5\nHbmjEyt9deTOMUmICszkwNwpn6pzuoF2v4+fL2PQ4VBElLfCv4qbP9JGljvLsj5b\nC9UWe9rWgRrw2Z88LlVmFy3k4Om80Q57gW3hSYZpG4rBhC9+YRXjZ+Iq5SFEJQ+U\nj8ej7q6DnI8Prbvw/e13JH1pxm9AUQDm+sTsBmvjh4Ye02vKbfUP+pFOM0eC3Eoa\nOyG7unZnDuAaK9g87xVjd9HtD6MfaM0EHAEF1eyC4UqeiXTbVMwi7+0IGA2evEDZ\n3WRR2i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fUPqR8gKsVJgBGE04iwE/RmLpp9/XZRAoGAFtaa9JeHk9dmZiST3lev\ns5syeOK1cCj1+nJer/GPEjqWMKxbCULvoEYBp7RaoEXjfGi7P4Mc6YHnbljHc+sL\niJzHhxrv/HYZdlCdTU3IRWT0sNHzqZemfYnsVTSp+4y61sGDxioDYL4CLnMq5T2F\nqzfc2qp3s8ApVloY3giuqnI=\n-----END PRIVATE KEY-----\n",
"client_email": "plan-maker@fynd-db.iam.gserviceaccount.com",
"client_id": "114883060650442183907",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/plan-maker%40fynd-db.iam.gserviceaccount.com",
"universe_domain": "googleapis.com"
}
if st.button("Submit", key='submit_button'):
user_data = {
"Business_Head": selected_business_head,
"Company_ID": company_id.strip(),
"Company_Name": st.session_state.get('company_name', ''),
"Currency": currency,
"Bundle_by": bundle_by,
"Plan_Name": plan_name,
"Plan_Description": plan_description,
"Product_lines": st.session_state.get('ordering_channel', ''),
"Fulfilling_Location": st.session_state.get('fulfilling_location', ''),
"Application_ID": st.session_state.get('application_id', ''),
"Fee_Type": st.session_state.get('selected_fee_type', ''),
"Variable_Type": st.session_state.get('selected_variable_type', ''),
"Chargeable_on": st.session_state.get('selected_chargeable_on', ''),
"Fee_Nature": selected_fee_nature,
"Commercial_value": 0.0,
"Fee_reversal": os.getenv('fee_reversal',''),
"Reversal_%": os.getenv('reversal_per',''),
"Usage_limit": 0.0,
"Threshold_value": 0.0,
"Threshold_option": '',
"Plan_validity": '',
"Payment_Method": os.getenv('selected_payment_method',''),
"Expected_Billing": 0.0,
"Net_total_billing": 0,
"slab_data": slab_data if selected_fee_nature == "Slab based" else ""
}
# Save and display user data
save_user_data(user_data)
st.session_state.user_data = user_data
st.session_state.df = pd.DataFrame([user_data])
st.write(st.session_state.df)
if st.button("Export to BQ"):
if project_id and dataset_id and table_id and service_account_info:
user_data = st.session_state.user_data
# Generate rule_id and plan_id
rule_id = generate_rule_id(user_data)
plan_id = generate_plan_id(user_data)
# Update user_data with generated IDs
user_data['rule_id'] = rule_id
user_data['plan_id'] = plan_id
st.session_state['created_at'] = datetime.now().isoformat()
user_data = {
"Business_Head": selected_business_head,
"Company_ID": company_id.strip(),
"Company_Name": st.session_state.get('company_name', ''),
"Currency": currency,
"Bundle_by": bundle_by,
"Plan_Name": plan_name,
"Plan_Description": plan_description,
"Product_lines": st.session_state.get('ordering_channel', ''),
"Fulfilling_Location": st.session_state.get('fulfilling_location', ''),
"Application_ID": st.session_state.get('application_id', ''),
"Fee_Type": st.session_state.get('selected_fee_type', ''),
"Variable_Type": st.session_state.get('selected_variable_type', ''),
"Chargeable_on": st.session_state.get('selected_chargeable_on', ''),
"Fee_Nature": selected_fee_nature,
# Ensure environment values are safely converted to float, handling empty strings
"Commercial_value": 0.0,
"Fee_reversal": os.getenv('fee_reversal', ''),
"Reversal_%": float(os.getenv('reversal_per', '0.0') or 0.0),
"Usage_limit": 0.0,
"Threshold_value": 0.0,
"Threshold_option": '',
"Plan_validity": '',
"Payment_Method": os.getenv('selected_payment_method', ''),
"Expected_Billing": 0.0,
"Net_total_billing": 0,
"rule_id": rule_id,
"plan_id": plan_id,
"created_at": st.session_state.get('created_at', ''),
# Set slab_data based on the selected fee nature
"slab_data": slab_data if selected_fee_nature == "Slab based" else ""
}
# Save the user data locally and to session state
save_user_data(user_data)
# Display saved records
display_saved_records()
# Store created_at, rule_id, and plan_id in session state
st.session_state['created_at'] = datetime.now().isoformat()
st.session_state['rule_id'] = rule_id
st.session_state['plan_id'] = plan_id
insert_into_bq(user_data, project_id, dataset_id, table_id, service_account_info)
else:
st.error("One or more required variables are not defined.")
############################################################ Fixed or Flat #####################################################
elif selected_fee_nature in ["Fixed %", "Flat currency"]:
user_input_1 = st.number_input("Enter Commercial value:", min_value=0.0, help="Enter the Commercial value")
user_input_2 = float(user_input_1) if isinstance(user_input_1, (int, float)) else 0.0
user_input_3 = "{:.2f}".format(user_input_2)
os.environ['user_input_3'] = user_input_3
selected_fee_type = st.session_state.get('selected_fee_type', '')
selected_variable_type = st.session_state.get('selected_variable_type', '')
fee_reversal = st.multiselect("Fee Reversal", fee_reversal_options, help="Fee reversal is an option of reversing to be given to any fee on a particular service status") if selected_fee_type == "Transaction" and selected_variable_type == "Bag" else None
fee_reversal = "/".join(fee_reversal) if fee_reversal else ""
os.environ['fee_reversal'] = str(fee_reversal) if fee_reversal is not None else ''
reversal_per = st.number_input("Reversal %", min_value=0.0, help="Enter the reversal percentage") if selected_fee_type == "Transaction" and selected_variable_type == "Bag" else ""
os.environ['reversal_per'] = str(reversal_per) if reversal_per is not None else ''
usage_1 = st.number_input(f"Usage limit for {selected_variable_type}", min_value=0.0, help="Enter the usage limit")
usage_2 = float(usage_1)
usage_3 = "{:.2f}".format(usage_2)
os.environ['usage_3'] = usage_3
product_1 = usage_1 * user_input_1 if selected_fee_nature in ["Fixed %", "Flat currency"] else 0
product_2 = float(product_1)
product_3 = "{:.2f}".format(product_2)
threshold = st.selectbox("Threshold option:", [""] + threshold_options, help="If Minimum guarantee is set as threshold option then Expected billing will be the higher value b/w 'Commercial*Usage' & 'Threshold' and if it is set to Capping then Expected billing will be the lower value b/w 'Commercial*Usage' & 'Threshold'")
os.environ['threshold'] = threshold
capping_or_minimum_guarantee_1 = st.number_input(f"Threshold value for {selected_variable_type}", min_value=0.0, help="Enter the Capping/Minimum Guarantee value")
capping_or_minimum_guarantee_2 = float(capping_or_minimum_guarantee_1)
capping_or_minimum_guarantee_3 = "{:.2f}".format(capping_or_minimum_guarantee_2)
os.environ['capping_or_minimum_guarantee_3'] = capping_or_minimum_guarantee_3
initial_expected_billing = product_1
if threshold == 'Capping value':
expected_billing = min(product_1, capping_or_minimum_guarantee_1)
elif threshold == 'Minimum Guarantee':
expected_billing = max(product_1, capping_or_minimum_guarantee_1)
else:
expected_billing = initial_expected_billing
os.environ['expected_billing'] = str(expected_billing) if expected_billing is not None else ''
selected_plan_validity = st.selectbox("Plan Validity", [""] + plan_validity_options, help="Plan validity defines the periodicity of calculation for the above billing", key="plan_vd_2")
os.environ['selected_plan_validity'] = selected_plan_validity
expected_billing_header = f"""
<h1 style='
color: #a689f6;
font-size: 20px;
background-image: -webkit-linear-gradient(0deg, #a689f6 3%, #272191 33%, #413bb9 61%);
background-clip: text;
-webkit-background-clip: text;
text-fill-color: transparent;
-webkit-text-fill-color: transparent;
'>Expected Monthly Billing (excluding GST): {expected_billing}</h1>
"""
st.markdown(expected_billing_header, unsafe_allow_html=True)
if selected_plan_validity == 'One time':
final_billing = 1 * expected_billing
elif selected_plan_validity == 'Monthly':
final_billing = 1 * expected_billing
elif selected_plan_validity == 'Quarterly':
final_billing = 3 * expected_billing
elif selected_plan_validity == 'Bi-Annually':
final_billing = 6 * expected_billing
elif selected_plan_validity == 'Annually':
final_billing = 12 * expected_billing
else:
final_billing = 0
os.environ['final_billing']= str(final_billing) if final_billing is not None else ''
final_billing_header = f"""
<h1 style='
color: #a689f6;
font-size: 20px;
background-image: -webkit-linear-gradient(0deg, #a689f6 3%, #272191 33%, #413bb9 61%);
background-clip: text;
-webkit-background-clip: text;
text-fill-color: transparent;
-webkit-text-fill-color: transparent;
'>Net total billing (excluding GST): {final_billing}</h1>
"""
st.markdown(final_billing_header, unsafe_allow_html=True)
selected_payment_method = st.selectbox("Payment Method", [""] + payment_method_options, help="Payment method defines the mode of payment of the plan", key="py_vd_2")
os.environ['selected_payment_method'] = selected_payment_method
st.markdown(button_styles, unsafe_allow_html=True)
rule_id = None
plan_id = None
user_data = None
user_input_3 = float(os.getenv('user_input_3'))
usage_3 = float(os.getenv('usage_3'))
capping_or_minimum_guarantee_3 = float(os.getenv('capping_or_minimum_guarantee_3'))
threshold = (os.getenv('threshold'))
selected_plan_validity= os.getenv('selected_plan_validity')
expected_billing= os.getenv('expected_billing')
final_billing = os.getenv('final_billing')
project_id = "fynd-db"
dataset_id = "finance_dwh"
table_id = "plan_v2"
service_account_info = {
"type": "service_account",
"project_id": "fynd-db",
"private_key_id": "48954327ef172acc3091a91881840dc353ff0413",
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCmIs0vgXflZmHD\n0IeHCiDEXavRb2GvRQqkCZGLy/EHFO7XLmpNrFzZHTSQach6HErARWTMsd2AMIA5\nHbmjEyt9deTOMUmICszkwNwpn6pzuoF2v4+fL2PQ4VBElLfCv4qbP9JGljvLsj5b\nC9UWe9rWgRrw2Z88LlVmFy3k4Om80Q57gW3hSYZpG4rBhC9+YRXjZ+Iq5SFEJQ+U\nj8ej7q6DnI8Prbvw/e13JH1pxm9AUQDm+sTsBmvjh4Ye02vKbfUP+pFOM0eC3Eoa\nOyG7unZnDuAaK9g87xVjd9HtD6MfaM0EHAEF1eyC4UqeiXTbVMwi7+0IGA2evEDZ\n3WRR2i+lAgMBAAECggEAF7Vis7NVsVqFfCS/moFTAMLfWLF87r67EIK/DwSpHloZ\n5YJdsDz3ORKmZC98aRSthDfC9UUyt270dXItAj0jmTFgWB6HgE8OQ1zUbmo3MHG+\ntPwMWmqwY2gsBMV2Xefot1QJxYH+AYkrxeFv5NgC+FaPSiy8QSHZlQqcxYtlP8kY\nzv8QFMgZ3b0sixK+YcSjCRXHu/DznnS/ZU7XlTALxANa50hT11rVLq6zYDF40fqC\nOWCOZvupjMOnNimXCWn7q6D1F8S/IMYlnHArJpEb7SdbJnJzxUvJC2rrMSoY896r\nyFEVhlElWp5GfTopu0WnL7iaw3pukM1OtpanFAk29wKBgQDW+yMzL7RiQ5LdElVP\n7Ml5hs+t6cjrUJTgBI8Uf9qGxE+tMe7Ye1fyJfbYslbOYO9xIUUT1jJmU6jadNWX\nA7UT59/IjvAOBIYyMEdh6Xo+H6ggW8DeU1HSdvixnQdgi0c03E6OCbOKi9E/UzK/\nTK2RBJJLN4MCiNL0FzrhTuxyEwKBgQDF1cz9Sb2UbrL5hr8LdcEH0ctatNlhJcSN\nnMd0Fn+e1EAkip+Hs9HmTvNdty4gQE+yEq/Tj0cRHXmjzK2AYx0WYRAhWGNSTlTS\n4OJdjE6vsoPu7Ouz1R/i/egKniUifEXYSgyL+oPBUrqqsnk9lgGBkJipN3u1f9+K\niuUJJP/OZwKBgF6ZvqCcom0HPU5I7f+wu+vdVfA6yy45lHmLqAamSFw7cLBPI8Jh\nbI7jA9/Rgn9oipUmxcX34M/Eiq4u8Xp1qC4tP/16YMpaVU8qjY7ZdfB2b75lgdaT\npZLOxZsq9X8Xauso8uxv+nDCG/8YtmEV9d61u0acE+t+mA3PVxqkZ0m/AoGBAI5c\nY76AqeN+JVxaEm/0tIsj9Om46hR2URJ2lzB6YCuzINUqy9GjHJBWj9oITzD2FmNV\n/yCGIeW3CClOyCtzJyNLhYf5Sr+XjoKRQVN/+7+C/l2YL6Sg4Ok/PRMm6iH+u2QB\nJTY1d0pOdfUPqR8gKsVJgBGE04iwE/RmLpp9/XZRAoGAFtaa9JeHk9dmZiST3lev\ns5syeOK1cCj1+nJer/GPEjqWMKxbCULvoEYBp7RaoEXjfGi7P4Mc6YHnbljHc+sL\niJzHhxrv/HYZdlCdTU3IRWT0sNHzqZemfYnsVTSp+4y61sGDxioDYL4CLnMq5T2F\nqzfc2qp3s8ApVloY3giuqnI=\n-----END PRIVATE KEY-----\n",
"client_email": "plan-maker@fynd-db.iam.gserviceaccount.com",
"client_id": "114883060650442183907",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/plan-maker%40fynd-db.iam.gserviceaccount.com",
"universe_domain": "googleapis.com"
}
if st.button("Submit", key='submit_button'):
user_data = {
"Business_Head": selected_business_head,
"Company_ID": company_id.strip(),
"Company_Name": st.session_state.get('company_name', ''),
"Currency": currency,
"Bundle_by": bundle_by,
"Plan_Name": plan_name,
"Plan_Description": plan_description,
"Product_lines": st.session_state.get('ordering_channel', ''),
"Fulfilling_Location": st.session_state.get('fulfilling_location', ''),
"Application_ID": st.session_state.get('application_id', ''),
"Fee_Type": st.session_state.get('selected_fee_type', ''),
"Variable_Type": st.session_state.get('selected_variable_type', ''),
"Chargeable_on": st.session_state.get('selected_chargeable_on', ''),
"Fee_Nature": selected_fee_nature,
"Commercial_value": float(os.getenv('user_input_3', '0.0')) if user_input_3 else 0.0,
"Fee_reversal": os.getenv('fee_reversal',''),
"Reversal_%": os.getenv('reversal_per',''),
"Usage_limit": os.getenv('usage_3','') if usage_3 else 0.0,
"Threshold_value": os.getenv('capping_or_minimum_guarantee_3','') if capping_or_minimum_guarantee_3 else 0.0,
"Threshold_option": os.getenv('threshold','') if threshold else '',
"Plan_validity": os.getenv('selected_plan_validity','') if selected_plan_validity else '',
"Payment_Method": os.getenv('selected_payment_method',''),
"Expected_Billing": os.getenv('expected_billing','') if expected_billing else 0.0,
"Net_total_billing": os.getenv('final_billing','') if final_billing else 0,
"slab_data": slab_data if selected_fee_nature == "Slab based" else ""
}
# Save and display user data
save_user_data(user_data)
st.session_state.user_data = user_data
st.session_state.df = pd.DataFrame([user_data])
st.write(st.session_state.df)
# Display saved records
# display_saved_records()
# Insert into BigQuery
if st.button("Export to BQ"):
if project_id and dataset_id and table_id and service_account_info:
user_data = st.session_state.user_data
# Generate rule_id and plan_id
rule_id = generate_rule_id(user_data)
plan_id = generate_plan_id(user_data)
# Update user_data with generated IDs
user_data['rule_id'] = rule_id
user_data['plan_id'] = plan_id
st.session_state['created_at'] = datetime.now().isoformat()
user_data = {
"Business_Head": selected_business_head,
"Company_ID": company_id.strip(),
"Company_Name": st.session_state.get('company_name', ''),
"Currency": currency,
"Bundle_by": bundle_by,
"Plan_Name": plan_name,
"Plan_Description": plan_description,
"Product_lines": st.session_state.get('ordering_channel', ''),
"Fulfilling_Location": st.session_state.get('fulfilling_location', ''),
"Application_ID": st.session_state.get('application_id', ''),
"Fee_Type": st.session_state.get('selected_fee_type', ''),
"Variable_Type": st.session_state.get('selected_variable_type', ''),
"Chargeable_on": st.session_state.get('selected_chargeable_on', ''),
"Fee_Nature": selected_fee_nature,
# Ensure environment values are safely converted to float, handling empty strings
"Commercial_value": float(os.getenv('user_input_3', '0.0') or 0.0) if user_input_3 else 0.0,
"Fee_reversal": os.getenv('fee_reversal', ''),
"Reversal_%": float(os.getenv('reversal_per', '0.0') or 0.0),
"Usage_limit": float(os.getenv('usage_3', '0.0') or 0.0) if usage_3 else 0.0,
"Threshold_value": float(os.getenv('capping_or_minimum_guarantee_3', '0.0') or 0.0) if capping_or_minimum_guarantee_3 else 0.0,
"Threshold_option": os.getenv('threshold', '') if threshold else '',
"Plan_validity": os.getenv('selected_plan_validity', '') if selected_plan_validity else '',
"Payment_Method": os.getenv('selected_payment_method', ''),
# Convert expected_billing to float if it's a valid string or 0.0 if empty
"Expected_Billing": float(os.getenv('expected_billing', '0.0') or 0.0) if expected_billing else 0.0,
# Convert final_billing to int (default to 0 if empty)
# Safely convert 'final_billing' to a float first, then to an integer
"Net_total_billing": int(float(os.getenv('final_billing', '0.0') or 0.0)) if final_billing else 0,
"rule_id": rule_id,
"plan_id": plan_id,
"created_at": st.session_state.get('created_at', ''),
# Set slab_data based on the selected fee nature
"slab_data": slab_data if selected_fee_nature == "Slab based" else ""
}
# Save the user data locally and to session state
save_user_data(user_data)
# Display saved records
display_saved_records()
# Store created_at, rule_id, and plan_id in session state
st.session_state['created_at'] = datetime.now().isoformat()
st.session_state['rule_id'] = rule_id
st.session_state['plan_id'] = plan_id
insert_into_bq(user_data, project_id, dataset_id, table_id, service_account_info)
else:
st.error("One or more required variables are not defined.")
elif bundle_by == "Single value":
user_input_1 = st.sidebar.number_input("Enter Commercial value:")
user_input_2 = float(user_input_1)
st.session_state['user_input_3'] = "{:.2f}".format(user_input_2)
plan_name = st.sidebar.text_input("Plan Name", help="Enter the name of the plan")
plan_description = st.sidebar.text_area("Plan Description", max_chars=250, help="Describe the plan")
plan_start_date = st.sidebar.date_input("Plan Start Date", value=datetime.now(), help="Select the start date of the plan")
# Initialize session state variables if they don't exist
if 'new_mapping' not in st.session_state:
st.session_state['new_mapping'] = {}
if 'file_data' not in st.session_state:
st.session_state['file_data'] = None
if 'mapping_mode' not in st.session_state:
st.session_state['mapping_mode'] = None # None, 'default', 'custom'
if 'button_clicked' not in st.session_state:
st.session_state['button_clicked'] = None
# Function to handle custom button click
def custom_button_click():
st.session_state.button_clicked = 'custom'
# Function to handle default button click
def default_button_click():
st.session_state.button_clicked = 'default'
# Display buttons without immediate execution on click
col1, col2 = st.sidebar.columns([0.25, 0.45])
with col1:
default_clicked = st.button("Default mapping")
with col2:
custom_clicked = st.button("Custom mapping")
# Determine action based on button clicked
if default_clicked:
default_button_click()
elif custom_clicked:
custom_button_click()
st.markdown(button_styles, unsafe_allow_html=True)
# Default button mapping
if st.session_state.button_clicked == 'default':
st.session_state['new_mapping'] = new_mapping
st.session_state['mapping_mode'] = 'default'
st.sidebar.markdown(rule_info_header, unsafe_allow_html=True)
# Handle Custom Mapping
elif st.session_state.button_clicked == 'custom':
st.markdown(button_styles, unsafe_allow_html=True)
uploaded_file = st.sidebar.file_uploader("Upload a file:", type=['csv', 'xlsx'], key='file_uploader')
st.sidebar.markdown(rule_info_header, unsafe_allow_html=True)
if uploaded_file is not None:
uploader(uploaded_file)
if st.session_state.get('mapping_mode'):
render_selectboxes(st.session_state, st.session_state.get('new_mapping'))
selected_variable_type = st.session_state['selected_variable_type']
usage_1 = st.number_input(f"Usage limit for {selected_variable_type}", min_value=0.0, help="Enter the usage limit")
usage_2 = float(usage_1)
usage_3 = "{:.2f}".format(usage_2)
expected_billing = user_input_1
expected_billing_header = f"""
<h1 style='
color: #a689f6;
font-size: 20px;
background-image: -webkit-linear-gradient(0deg, #a689f6 3%, #272191 33%, #413bb9 61%);
background-clip: text;
-webkit-background-clip: text;
text-fill-color: transparent;
-webkit-text-fill-color: transparent;
'>Expected Monthly Billing (excluding GST): {expected_billing}</h1>
"""
st.markdown(expected_billing_header, unsafe_allow_html=True)
selected_plan_validity = st.selectbox("Plan Validity", [""] + plan_validity_options, help="Plan validity defines the periodicity of calculation for the above billing", key="plan_vd_2")
selected_payment_method = st.selectbox("Payment Method", [""] + payment_method_options, help="Payment method defines the mode of payment of the plan", key="py_vd_2")
initial_net_billing = 0
user_input_3 = st.session_state['user_input_3']
if selected_plan_validity == 'One time':
final_billing = 1 * expected_billing
elif selected_plan_validity == 'Monthly':
final_billing = 1 * expected_billing
elif selected_plan_validity == 'Quarterly':
final_billing = 3 * expected_billing
elif selected_plan_validity == 'Bi-Annually':
final_billing = 6 * expected_billing
elif selected_plan_validity == 'Annually':
final_billing = 12 * expected_billing
else:
final_billing = initial_net_billing
final_billing_header = f"""
<h1 style='
color: #a689f6;
font-size: 20px;
background-image: -webkit-linear-gradient(0deg, #a689f6 3%, #272191 33%, #413bb9 61%);
background-clip: text;
-webkit-background-clip: text;
text-fill-color: transparent;
-webkit-text-fill-color: transparent;
'>Net total billing (excluding GST): {final_billing}</h1>
"""
st.markdown(final_billing_header, unsafe_allow_html=True)
st.markdown(button_styles, unsafe_allow_html=True)
rule_id = None
plan_id = None
user_data = None
project_id = "fynd-db"
dataset_id = "finance_dwh"
table_id = "plan_v2"
service_account_info = {
"type": "service_account",
"project_id": "fynd-db",
"private_key_id": "48954327ef172acc3091a91881840dc353ff0413",
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCmIs0vgXflZmHD\n0IeHCiDEXavRb2GvRQqkCZGLy/EHFO7XLmpNrFzZHTSQach6HErARWTMsd2AMIA5\nHbmjEyt9deTOMUmICszkwNwpn6pzuoF2v4+fL2PQ4VBElLfCv4qbP9JGljvLsj5b\nC9UWe9rWgRrw2Z88LlVmFy3k4Om80Q57gW3hSYZpG4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+mA3PVxqkZ0m/AoGBAI5c\nY76AqeN+JVxaEm/0tIsj9Om46hR2URJ2lzB6YCuzINUqy9GjHJBWj9oITzD2FmNV\n/yCGIeW3CClOyCtzJyNLhYf5Sr+XjoKRQVN/+7+C/l2YL6Sg4Ok/PRMm6iH+u2QB\nJTY1d0pOdfUPqR8gKsVJgBGE04iwE/RmLpp9/XZRAoGAFtaa9JeHk9dmZiST3lev\ns5syeOK1cCj1+nJer/GPEjqWMKxbCULvoEYBp7RaoEXjfGi7P4Mc6YHnbljHc+sL\niJzHhxrv/HYZdlCdTU3IRWT0sNHzqZemfYnsVTSp+4y61sGDxioDYL4CLnMq5T2F\nqzfc2qp3s8ApVloY3giuqnI=\n-----END PRIVATE KEY-----\n",
"client_email": "plan-maker@fynd-db.iam.gserviceaccount.com",
"client_id": "114883060650442183907",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/plan-maker%40fynd-db.iam.gserviceaccount.com",
"universe_domain": "googleapis.com"
}
# Submit button
if st.button("Submit"):
# Save user data
user_data = {
"Business_Head": selected_business_head,
"Company_ID": company_id.strip() if company_id else None,
"Company_Name": st.session_state.get('company_name', ''),
"Currency": currency,
"Bundle_by": bundle_by,
"Plan_Name": plan_name,
"Plan_Description": plan_description,
"Product_lines": st.session_state.get('ordering_channel', ''),
"Fulfilling_Location": st.session_state.get('fulfilling_location', ''),
"Application_ID": st.session_state.get('application_id', ''),
"Fee_Type": st.session_state.get('selected_fee_type', ''),
"Variable_Type": selected_variable_type,
"Chargeable_on": st.session_state.get('selected_chargeable_on', ''),
"Fee_Nature": 0,
"Commercial_value": user_input_3,
"Fee_reversal": 0,
"Reversal_%": 0,
"Usage_limit": usage_3,
"Threshold_value": 0,
"Threshold_option": 0,
"Expected_Billing": user_input_3,
"Plan_Validity": selected_plan_validity,
"Payment_Method": selected_payment_method,
"Net_total_billing":int(final_billing),
"slab_data": ""
}
# Save and display user data
save_user_data(user_data)
st.session_state.user_data = user_data
st.session_state.df = pd.DataFrame([user_data])
st.write(st.session_state.df)
# Display saved records
# display_saved_records()
# Insert into BigQuery
if st.button("Export to BQ"):
if project_id and dataset_id and table_id and service_account_info:
user_data = st.session_state.user_data
# Generate rule_id and plan_id
rule_id = generate_rule_id(user_data)
plan_id = generate_plan_id(user_data)
# Update user_data with generated IDs
user_data['rule_id'] = rule_id
user_data['plan_id'] = plan_id
st.session_state['created_at'] = datetime.now().isoformat()
user_data = {
"Business_Head": selected_business_head,
"Company_ID": company_id.strip(),
"Company_Name": st.session_state.get('company_name', ''),
"Currency": currency,
"Bundle_by": bundle_by,
"Plan_Name": plan_name,
"Plan_Description": plan_description,
"Product_lines": st.session_state.get('ordering_channel', ''),
"Fulfilling_Location": st.session_state.get('fulfilling_location', ''),
"Application_ID": st.session_state.get('application_id', ''),
"Fee_Type": st.session_state.get('selected_fee_type', ''),
"Variable_Type": selected_variable_type,
"Chargeable_on": st.session_state.get('selected_chargeable_on', ''),
"Fee_Nature": 0,
"Commercial_value": user_input_3,
"Fee_reversal": 0,
"Reversal_%": 0,
"Usage_limit": usage_3,
"Threshold_value": 0,
"Threshold_option": 0,
"Expected_Billing": user_input_3,
"Plan_Validity": selected_plan_validity,
"Payment_Method": selected_payment_method,
"Net_total_billing":int(final_billing),
"rule_id": rule_id,
"plan_id": plan_id,
"created_at": st.session_state.get('created_at',''),
"slab_data": ""
}
# Save the user data locally and to session state
save_user_data(user_data)
# Display saved records
display_saved_records()
# Store created_at, rule_id, and plan_id in session state
st.session_state['created_at'] = datetime.now().isoformat()
st.session_state['rule_id'] = rule_id
st.session_state['plan_id'] = plan_id
insert_into_bq(user_data, project_id, dataset_id, table_id, service_account_info)
else:
st.error("One or more required variables are not defined.")