File size: 5,597 Bytes
1fea92e
 
 
 
 
d45da3a
89f6f6b
1fea92e
 
 
 
 
6358d4a
 
 
 
1fea92e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89f6f6b
1fea92e
 
 
 
 
 
 
 
 
 
89f6f6b
1fea92e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89f6f6b
1fea92e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import pandas as pd
from pymongo import MongoClient
from dependency import get_manager, load_db
from bson.objectid import ObjectId
from datetime import datetime
import time 

cookie_manager = get_manager()
auth_state = cookie_manager.get(cookie='auth_state')
st.write(auth_state)

if st.session_state.auth_state:
    st.write('you are authenticated...')

if not auth_state == "authenticated" and st.session_state.auth_state == False:
    st.warning("You are not authorized to access this page. Please login.")
    st.stop()

# Connect to MongoDB
client = load_db()
db = client["chat_support"]
faq_collection = db["faq"]
st.title("Manage FAQs")
print('load faqs...')

# Display existing FAQs
faq_all = pd.DataFrame(list(faq_collection.find()))

with st.sidebar:
    st.subheader("Add New FAQ")
    with st.form("new_faq_form", clear_on_submit=True):
        new_title = st.text_input("Title")
        new_questions = st.text_area("Questions (one per line)")
        new_answer = st.text_area("Answer")
        add_faq = st.form_submit_button("Add FAQ")
        if add_faq:
            print('add new faq...')
            new_questions_list = new_questions.split("\n")
            faq_collection.insert_one({
                "title": new_title,
                "questions": new_questions_list,
                "answer": new_answer,
                "time_updated": int(round(time.time() * 1000))
            })
            st.success("New FAQ added successfully!")

# Search functionality
search_term = st.text_input("Search FAQs", "")
if search_term:
    faq_data = faq_all[faq_all['questions'].apply(lambda x: any(search_term.lower() in q.lower() for q in x))]
else:
    faq_data = faq_all

st.write(f'filtered {len(faq_data)} out of {len(faq_all)}')
# id = ObjectId('5e26c9f62da44968cc46444c')
# result = faq_collection.update_one(
#         {"_id": id},
#         {"$set": {
#             "title": 'cara menambahkan produks',
#         }}
#     )
# print('updated: ', result.modified_count, 'id: ', type(id))

def edit_faq(index):
    row = faq_data.loc[index]
    with st.form(f"edit_form_{index}", clear_on_submit=True):
        st.write("Edit FAQ Form")
        new_title = st.text_input("Title", value=row['title'], key=f"title_{index}")
        new_questions = st.text_area("Questions (one per line)", value="\n".join(row['questions']), key=f"questions_{index}")
        new_answer = st.text_area("Answer", value=row['answer'], key=f"answer_{index}")
        confirm_edit = st.form_submit_button("Confirm Edit",  on_click=save_edit, args=(index,))


def save_edit(index):    
    print('save at index: ', index)
    row = faq_data.loc[index]    
    faq_id = row['_id']
    # print('save....', row['_id'], faq_id['$oid'])
    print('typeOf faq_id ',type(faq_id))

    # Get the current state of the input fields
    edit_form = st.form(f"edit_form_{index}")
    print('form: ', edit_form)
    new_title = st.session_state.get(f"title_{index}", row['title'])
    new_questions = st.session_state.get(f"questions_{index}", "\n".join(row['questions']))
    new_answer = st.session_state.get(f"answer_{index}", row['answer'])
    # new_title = edit_form.form_state.widget_states['title'].value
    # new_questions = edit_form.form_state.widget_states['questions'].value.split("\n")
    # new_answer = edit_form.form_state.widget_states['answer'].value
    
    # Convert the _id to ObjectId
    # if isinstance(faq_id, ObjectId):
    #     faq_id = faq_id
    #     print('isinstance')
    # else:
    #     faq_id = ObjectId(faq_id['$oid'])
    #     print('isnot isinstance')

    result = faq_collection.update_one(
        {"_id": faq_id},
        {"$set": {
            "title": new_title,
            "questions": new_questions.split("\n"),
            "answer": new_answer,
            "time_updated": int(round(time.time() * 1000))
        }}
    )
    print('updated: ', result.modified_count, new_title)
    st.success("FAQ updated successfully!")

# Add new FAQ

# with st.form("new_faq_form"):
#     new_title = st.text_input("Title")
#     new_questions = st.text_area("Questions (one per line)")
#     new_answer = st.text_area("Answer")
#     add_faq = st.form_submit_button("Add FAQ")

#     if add_faq:
#         new_questions_list = new_questions.split("\n")
#         faq_collection.insert_one({
#             "title": new_title,
#             "questions": new_questions_list,
#             "answer": new_answer,
#             "time_updated": pd.Timestamp.now().value
#         })
#         st.success("New FAQ added successfully!")

for index, row in faq_data.iterrows():
    with st.expander(row['title']):
        st.write("**Questions:**")
        for question in row['questions']:
            st.write(f"- {question}")
        st.write(f"\n**Answer:** {row['answer']}")
        # edit_faq_button = st.button("Edit FAQ", key=f"edit_{index}", on_click=edit_faq, args=(index,))
        edit_faq_button = st.button("Edit FAQ", key=f"edit_{index}")
        if edit_faq_button:
            with st.form(f"edit_form_{index}", clear_on_submit=True):
                st.write("Edit FAQ Form")
                new_title = st.text_input("Title", value=row['title'], key=f"title_{index}")
                new_questions = st.text_area("Questions (one per line)", value="\n".join(row['questions']), key=f"questions_{index}")
                new_answer = st.text_area("Answer", value=row['answer'], key=f"answer_{index}")
                confirm_edit = st.form_submit_button("Confirm Edit",  on_click=save_edit, args=(index,))
# Add code to create a new FAQ entry