Skip to content

Commit f1542e5

Browse files
committed
Migrate to firestore, reformat getoverall
1 parent 03feb1f commit f1542e5

File tree

3 files changed

+80
-11
lines changed

3 files changed

+80
-11
lines changed

bot/firestore.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
from bot.firestore_config import db
2+
3+
4+
# New user setup
5+
def new_user_setup(telegram_id, sheet_id):
6+
user_ref = db.collection("users").document(str(telegram_id))
7+
user_ref.set({"sheet_id": sheet_id})
8+
9+
10+
# Check if user exists
11+
def check_if_user_exists(telegram_id):
12+
user_ref = db.collection("users").document(str(telegram_id))
13+
user_doc = user_ref.get()
14+
return user_doc.exists
15+
16+
17+
# Get user sheet id
18+
def get_user_sheet_id(telegram_id):
19+
user_ref = db.collection("users").document(str(telegram_id))
20+
user_doc = user_ref.get()
21+
if user_doc.exists:
22+
return user_doc.get("sheet_id")
23+
else:
24+
return None
25+
26+
27+
# Get all user IDs
28+
def get_all_user_id():
29+
users_ref = db.collection("users")
30+
user_ids = [int(user.id) for user in users_ref.stream()]
31+
return user_ids
32+
33+
34+
# Get all sheet IDs
35+
def get_all_sheet_id():
36+
users_ref = db.collection("users")
37+
sheet_ids = []
38+
for user in users_ref.stream():
39+
sheet_ids.append(user.get("sheet_id"))
40+
return sheet_ids

bot/firestore_config.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
from firebase_admin import firestore
2+
import firebase_admin
3+
from firebase_admin import credentials
4+
import os
5+
import json
6+
7+
firebase_json = json.loads(os.environ["FIREBASE_JSON"])
8+
9+
cred = credentials.Certificate(firebase_json)
10+
firebase_admin.initialize_app(cred)
11+
12+
db = firestore.client()

bot/telegram_bot.py

Lines changed: 28 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
from bot.common import EntryType
1717
from bot.common import ConversationState as CS
1818
import bot.google_sheet as gs
19-
import bot.firebase as db
19+
import bot.firestore as db
2020

2121
timezone = pytz.timezone("Asia/Singapore")
2222

@@ -37,6 +37,7 @@ def check_date_format(date_string):
3737
pattern = r"\b\d{1,2}\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\b"
3838
return bool(re.fullmatch(pattern, date_string, re.IGNORECASE))
3939

40+
4041
def check_month_format(month_string):
4142
pattern = r"^(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)$"
4243
return bool(re.fullmatch(pattern, month_string, re.IGNORECASE))
@@ -623,6 +624,7 @@ def get_day_transaction(update, context):
623624
update.message.reply_text(ERROR_TEXT)
624625
return ConversationHandler.END
625626

627+
626628
def get_overall(update, context):
627629
context.user_data.clear()
628630
telegram_id = update.effective_user.id
@@ -634,6 +636,7 @@ def get_overall(update, context):
634636
update.message.reply_text(ERROR_TEXT)
635637
return ConversationHandler.END
636638

639+
637640
def handle_get_transaction(update, context):
638641
sheet_id = context.user_data["sheet_id"]
639642
reply = update.message.text
@@ -662,28 +665,42 @@ def handle_get_transaction(update, context):
662665
except Exception as e:
663666
update.message.reply_text(ERROR_TEXT)
664667

668+
665669
def handle_get_overall(update, context):
666670
sheet_id = context.user_data["sheet_id"]
667671
month = update.message.text
668-
msg = ""
669672
try:
670673
if check_month_format(month):
671674
values = gs.get_overall(sheet_id, month)
672-
msg = "```\n"
673-
for row in values:
674-
if len(row) == 3:
675-
msg += "{:<20} {:<10} {:<10}\n".format(*row)
676-
elif len(row) == 2:
677-
msg += "{:<20} {:<10}\n".format(*row)
678-
msg += "```"
679-
update.message.reply_text(msg, parse_mode='Markdown')
675+
676+
final_income = values[0]
677+
msg = f"--- Final Income ---\n`{final_income[2]}`\n\n"
678+
679+
msg += "--- Spending ---\n"
680+
max_len = (
681+
max(len(row[0]) for row in values[1:-2]) + 1
682+
) # +1 for some extra space
683+
for row in values[1:-2]:
684+
if row[1].startswith("-"): # if value is negative
685+
msg += f"`{row[0].ljust(max_len)}{row[1]}`\n"
686+
else:
687+
msg += f"`{row[0].ljust(max_len)} {row[1]}`\n" # else keep the original space
688+
689+
total_spent = values[-2]
690+
msg += f"\n--- Total Spent ---\n`{total_spent[1]}`\n"
691+
692+
overall = values[-1]
693+
msg += f"\n--- Overall ---\n`{overall[2]}`\n"
694+
695+
update.message.reply_text(msg, parse_mode="Markdown")
680696
return ConversationHandler.END
681697
else:
682698
update.message.reply_text(GET_OVERALL_TEXT)
683699
return CS.HANDLE_GET_OVERALL
684700
except Exception as e:
685701
update.message.reply_text(ERROR_TEXT)
686702

703+
687704
def add_income(update, context):
688705
context.user_data.clear()
689706
telegram_id = update.effective_user.id
@@ -807,7 +824,7 @@ def setup_handlers(dispatcher):
807824
CommandHandler("addothers", add_others),
808825
CommandHandler("addincome", add_income),
809826
CommandHandler("getdaytransaction", get_day_transaction),
810-
CommandHandler("getoverall", get_overall)
827+
CommandHandler("getoverall", get_overall),
811828
],
812829
states={
813830
CS.SET_UP: [MessageHandler(Filters.text & ~Filters.command, set_up)],

0 commit comments

Comments
 (0)