Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file removed __pycache__/ai_brain.cpython-310.pyc
Binary file not shown.
Binary file removed __pycache__/database.cpython-310.pyc
Binary file not shown.
81 changes: 75 additions & 6 deletions database.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import os
import mysql.connector
from mysql.connector import pooling
from datetime import datetime
from datetime import datetime, timedelta
from dotenv import load_dotenv

load_dotenv()
Expand Down Expand Up @@ -101,11 +101,21 @@ def init_db():
''')

# Migration: Tambahkan kolom if not exists (untuk database yang sudah ada)
try:
cursor.execute("ALTER TABLE users ADD COLUMN has_accepted_disclaimer TINYINT(1) DEFAULT 0")
conn.commit()
except:
pass # Kolom sudah ada
migration_columns = [
"ALTER TABLE users ADD COLUMN has_accepted_disclaimer TINYINT(1) DEFAULT 0",
"ALTER TABLE users ADD COLUMN streak_count INT DEFAULT 0",
"ALTER TABLE users ADD COLUMN last_streak_date DATE DEFAULT NULL"
]

for sql in migration_columns:
try:
cursor.execute(sql)
conn.commit()
except mysql.connector.Error as err:
if err.errno == 1060: # Column already exists
pass
else:
print(f"Migration error for '{sql}': {err}")

# Create chat_logs table
cursor.execute('''
Expand Down Expand Up @@ -710,3 +720,62 @@ def get_user_balance(user_id):
finally:
cursor.close()
conn.close()

def update_user_streak(user_id):
"""
Update streak harian user.
Returns: (new_streak, is_new_milestone)
"""
conn = get_connection()
try:
cursor = conn.cursor(dictionary=True)
cursor.execute("SELECT streak_count, last_streak_date FROM users WHERE user_id = %s", (user_id,))
user = cursor.fetchone()

if not user:
return 0, False

current_streak = user['streak_count'] or 0
last_date = user['last_streak_date']

# Jika last_date adalah string (tergantung driver/config), parse ke date object
if isinstance(last_date, str):
try:
last_date = datetime.strptime(last_date, "%Y-%m-%d").date()
except:
last_date = None

today = datetime.now().date()
yesterday = today - timedelta(days=1)

new_streak = current_streak
is_new_milestone = False

if last_date is None:
# Streak pertama kali
new_streak = 1
elif last_date == today:
# Sudah diupdate hari ini, biarkan
return current_streak, False
elif last_date == yesterday:
# Melanjutkan streak
new_streak = current_streak + 1
else:
# Streak terputus (melewati > 1 hari)
new_streak = 1

# Update ke DB
cursor.execute(
"UPDATE users SET streak_count = %s, last_streak_date = %s WHERE user_id = %s",
(new_streak, today, user_id)
)
conn.commit()

# Cek milestone (3, 7, 14, 30)
if new_streak in [3, 7, 14, 30]:
is_new_milestone = True

return new_streak, is_new_milestone
finally:
cursor.close()
conn.close()
Binary file removed finance_bot.db
Binary file not shown.
3 changes: 3 additions & 0 deletions handlers/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@ def send_profile(message):
first_seen = profile.get("first_seen")
last_active = profile.get("last_active")
msg_count = profile.get("message_count", 0)
streak = profile.get("streak_count", 0)
streak_icon = "🔥" if streak > 0 else "❄️"

# Format tanggal agar lebih rapi
fs_str = first_seen.strftime("%d %b %Y %H:%M") if first_seen else "-"
Expand All @@ -89,6 +91,7 @@ def send_profile(message):
f"🔹 *ID:* `{user_id}`\n\n"
f"📊 *Statistik Interaksi*\n"
f"💬 *Jumlah Pesan:* {msg_count} pesan dicatat\n"
f"{streak_icon} *Streak Harian:* {streak} hari berturut-turut\n"
f"📅 *Mulai Menggunakan:* {fs_str}\n"
f"⏱ *Terakhir Aktif:* {la_str}"
)
Expand Down
17 changes: 17 additions & 0 deletions handlers/nlp_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,23 @@ def handle_text(message):
reply = "✅ *Berhasil mencatat " + (f"{success_count} transaksi" if success_count > 1 else "transaksi") + ":*\n\n"
reply += "\n".join(summary_lines)
bot.reply_to(message, reply, parse_mode='Markdown')

# --- STREAK LOGIC ---
try:
new_streak, is_milestone = database.update_user_streak(user_id)
if is_milestone:
milestone_msgs = {
3: "🔥 *Mantap!* Ini hari ke-3 kamu konsisten mencatat. Pertahankan! 🚀",
7: "🏆 *Selamat!* Kamu sudah 7 hari berturut-turut mencatat. Kamu luar biasa! 🌟",
14: "✨ *Luar biasa!* 14 hari tanpa putus. Kamu benar-benar disiplin dalam mengelola keuangan! 💪",
30: "👑 *GOKIL!* 30 hari konsisten! Kamu adalah master keuangan. Lanjutkan terus perjalananmu! 🌈"
}
celebration = milestone_msgs.get(new_streak, "")
if celebration:
# Kirim pesan terpisah untuk apresiasi agar lebih berkesan
bot.send_message(message.chat.id, celebration, parse_mode='Markdown')
except Exception as streak_err:
print(f"Error updating streak: {streak_err}")
else:
bot.reply_to(message, "❌ Gagal mencatat transaksi. Pastikan format pesan sudah benar.")

Expand Down
Loading