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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
740b75a
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
# Importing necessary libraries
import streamlit as st
import pandas as pd
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, slab_data, 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

# Initializing session state and loading theme
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=True)

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")
        
        if selected_fee_nature == "Slab based":
            slab = st.selectbox("Slab:", [1, 2, 3], key="slab_select")
            max_value = st.text_input("Max value:", key = "max_value_input")
            user_input = st.text_input("Commercial Value:", key="user_input")
            usage = st.text_input("Usage:", key="usage_input")
            capping_or_minimum_guarantee = st.text_input("Capping/Min_Guarantee:", key="capping_or_minimum_guarantee_input")
            threshold = st.text_input("Threshold:", key="threshold_input")

            slab_data(slab, max_value, user_input, usage, capping_or_minimum_guarantee, threshold)

        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)

            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 None


            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 None

            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)

            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'")

            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)

            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

            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")

            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


            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")

        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\nC9UWe9rWgRrw2Z88LlVmFy3k4Om80Q57gW3hSYZpG4rBhC9+YRXjZ+Iq5SFEJQ+U\nj8ej7q6DnI8Prbvw/e13JH1pxm9AUQDm+sTsBmvjh4Ye02vKbfUP+pFOM0eC3Eoa\nOyG7unZnDuAaK9g87xVjd9HtD6MfaM0EHAEF1eyC4UqeiXTbVMwi7+0IGA2evEDZ\n3WRR2i+lAgMBAAECggEAF7Vis7NVsVqFfCS/moFTAMLfWLF87r67EIK/DwSpHloZ\n5YJdsDz3ORKmZC98aRSthDfC9UUyt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voEYBp7RaoEXjfGi7P4Mc6YHnbljHc+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": user_input_3,
                "Fee_reversal": fee_reversal,
                "Reversal_%": reversal_per,
                "Usage_limit": usage_3,
                "Threshold_value": capping_or_minimum_guarantee_3,
                "Threshold_option": threshold,
                "Plan_validity": selected_plan_validity,
                "Payment_Method": selected_payment_method,
                "Expected_Billing": expected_billing,
                "Net_total_billing": int(final_billing)
            }

            # 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("User Data Submitted")
            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,
                "Commercial_value": user_input_3,
                "Fee_reversal": fee_reversal,
                "Reversal_%": reversal_per,
                "Usage_limit": usage_3,
                "Threshold_value": capping_or_minimum_guarantee_3,
                "Threshold_option": threshold,
                "Plan_validity": selected_plan_validity,
                "Payment_Method": selected_payment_method,
                "Expected_Billing": expected_billing,
                "Net_total_billing": int(final_billing),
                "rule_id": rule_id,
                "plan_id": plan_id,
                "created_at": st.session_state.get('created_at','')
            }


                # 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+fL2P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/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"
        }


        # 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)
            }

            
        # 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("User Data Submitted")
            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','')
                }
                
                # 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.")