chat-faq / pages /manage_faqs.py
AnnasBlackHat's picture
fix time updated
89f6f6b
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