Romanchello-bit commited on
Commit
f230cf2
·
1 Parent(s): b3996c4

Update leads_manager.py

Browse files
Files changed (1) hide show
  1. leads_manager.py +85 -40
leads_manager.py CHANGED
@@ -1,51 +1,96 @@
 
1
  import pandas as pd
2
- import os
 
3
  from datetime import datetime
4
 
5
- LEADS_FILE = "leads.csv"
 
6
 
7
- def init_db():
8
- """Створює файл, якщо його немає"""
9
- if not os.path.exists(LEADS_FILE):
10
- df = pd.DataFrame(columns=[
11
- "Date", "Client Name", "Company", "Type", "Context",
12
- "Outcome", "Final Step", "Summary"
13
- ])
14
- df.to_csv(LEADS_FILE, index=False)
15
 
16
- def save_lead(lead_data, outcome, final_step, chat_history):
17
- """Зберігає результат розмови"""
18
- init_db()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
- # Робимо просте самарі (останні 2 повідомлення або статус)
21
- summary = f"Ended at {final_step}. Total msgs: {len(chat_history)}"
 
 
 
 
 
 
 
 
 
 
22
 
23
- new_row = {
24
- "Date": datetime.now().strftime("%Y-%m-%d %H:%M"),
25
- "Client Name": lead_data.get("name", "Unknown"),
26
- "Company": lead_data.get("company", "-"),
27
- "Type": lead_data.get("type", "B2B"),
28
- "Context": lead_data.get("context", "Cold Call"),
29
- "Outcome": outcome,
30
- "Final Step": final_step,
31
- "Summary": summary
32
- }
 
33
 
34
- df = pd.read_csv(LEADS_FILE)
35
- df = pd.concat([df, pd.DataFrame([new_row])], ignore_index=True)
36
- df.to_csv(LEADS_FILE, index=False)
37
- return True
38
 
39
  def get_analytics():
40
- """Повертає статистику для дашборду"""
41
- init_db()
42
- df = pd.read_csv(LEADS_FILE)
43
- if df.empty:
44
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
- stats = {
47
- "total": len(df),
48
- "success_rate": round(len(df[df["Outcome"] == "Success"]) / len(df) * 100, 1),
49
- "top_fail_reasons": df[df["Outcome"] == "Fail"]["Final Step"].value_counts().head(3)
50
- }
51
- return df, stats
 
 
1
+ import streamlit as st
2
  import pandas as pd
3
+ import gspread
4
+ from oauth2client.service_account import ServiceAccountCredentials
5
  from datetime import datetime
6
 
7
+ # Назва твоєї таблиці в Google Sheets (має співпадати буква в букву!)
8
+ SHEET_NAME = "SellMe_Leads"
9
 
10
+ def connect_to_gsheet():
11
+ """Підключення до Google Sheets через Secrets"""
12
+ try:
13
+ # Створюємо об'єкт облікових даних із секретів Streamlit
14
+ # Streamlit автоматично конвертує TOML секцію [gcp_service_account] у словник
15
+ if "gcp_service_account" not in st.secrets:
16
+ return None
 
17
 
18
+ creds_dict = dict(st.secrets["gcp_service_account"])
19
+
20
+ # Виправляємо переноси рядків у приватному ключі (часта проблема при копіюванні)
21
+ creds_dict["private_key"] = creds_dict["private_key"].replace("\\n", "\n")
22
+
23
+ scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
24
+ creds = ServiceAccountCredentials.from_json_keyfile_dict(creds_dict, scope)
25
+ client = gspread.authorize(creds)
26
+
27
+ # Відкриваємо таблицю
28
+ sheet = client.open(SHEET_NAME).sheet1
29
+ return sheet
30
+ except Exception as e:
31
+ # st.error(f"❌ Помилка підключення до Google Sheets: {e}")
32
+ # При кожному рерані може бути помилка якщо немає секретів, краще тихо
33
+ return None
34
+
35
+ def save_lead_to_db(lead_info, chat_history, outcome):
36
+ """Зберігає ліда в Google Таблицю"""
37
+ sheet = connect_to_gsheet()
38
+ if not sheet:
39
+ return # Якщо немає зв'язку, виходимо
40
 
41
+ # Якщо таблиця порожня, додамо заголовки
42
+ try:
43
+ if not sheet.get_all_values():
44
+ sheet.append_row([
45
+ "Date", "Name", "Company", "Type", "Context",
46
+ "Pain Point", "Budget", "Outcome", "Summary"
47
+ ])
48
+ except:
49
+ pass # Таблиця може бути новою
50
+
51
+ # Формуємо рядок даних
52
+ summary_text = f"Msgs: {len(chat_history)}"
53
 
54
+ row = [
55
+ datetime.now().strftime("%Y-%m-%d %H:%M"),
56
+ lead_info.get("name", "-"),
57
+ lead_info.get("company", "-"),
58
+ lead_info.get("type", "-"),
59
+ lead_info.get("context", "-"),
60
+ "AI Pending", # Тут можна додати AI аналіз
61
+ "Unknown",
62
+ outcome,
63
+ summary_text
64
+ ]
65
 
66
+ # Додаємо рядок
67
+ sheet.append_row(row)
68
+ print("✅ Дані збережено в Google Sheets!")
 
69
 
70
  def get_analytics():
71
+ """Читає дані з Google Таблиці для дашборду"""
72
+ sheet = connect_to_gsheet()
73
+ if not sheet:
74
+ return None, None
75
+
76
+ # Отримуємо всі записи
77
+ try:
78
+ data = sheet.get_all_records()
79
+ df = pd.DataFrame(data)
80
+
81
+ if df.empty:
82
+ return None, None
83
+
84
+ stats = {
85
+ "total": len(df),
86
+ "success_rate": 0,
87
+ "top_fail_reasons": None
88
+ }
89
 
90
+ if "Outcome" in df.columns and not df.empty:
91
+ success_count = len(df[df["Outcome"] == "Success"])
92
+ stats["success_rate"] = round(success_count / len(df) * 100, 1)
93
+
94
+ return df, stats
95
+ except:
96
+ return None, None