# Handling step type
elif data['type'] == 'step':
username = data['data']['username']
step_count = data['data']['step_count']
date_received = datetime.datetime.strptime(data['data']['date'], '%Y-%b-%d').date()
headers_dict = dict(request.headers)
# Get telegram_id from users table using username
c.execute('SELECT telegram_id FROM users WHERE username = %s', (username,))
row = c.fetchone()
if not row:
return {"status": False, "error": f"No user found with username {username}"}
telegram_id = row[0]
# Check if an entry exists for the user in steps_data
c.execute('SELECT date FROM steps_data WHERE telegram_id = %s', (telegram_id,))
row = c.fetchone()
# If there's an entry and the date doesn't match the current payload's date, reset today_steps to 0 and set the date to date_received
if row and row[0] != date_received:
c.execute('UPDATE steps_data SET today_steps = 0, date = %s WHERE telegram_id = %s', (date_received, telegram_id,))
# Insert or update steps_data for the date in the payload
c.execute('''
INSERT INTO steps_data (telegram_id, date, today_steps)
VALUES (%s, %s, %s)
ON DUPLICATE KEY UPDATE today_steps = today_steps + %s
''', (telegram_id, date_received, step_count, step_count))
# Update total steps in leaderboard
c.execute('UPDATE leaderboard SET total_steps = total_steps + %s WHERE telegram_id = %s', (step_count, telegram_id))
# Retrieve current balance
c.execute('SELECT balance FROM balances WHERE telegram_id = %s', (telegram_id,))
current_balance = c.fetchone()[0]
# Calculate the new balance
new_balance = current_balance + step_count * 2
# Ensure the daily balance itself doesn't exceed 20000
if new_balance > 20000:
new_balance = 20000
# Update balance
c.execute('UPDATE balances SET balance = %s WHERE telegram_id = %s', (new_balance, telegram_id))
conn.commit()
# await client.send_message(int(telegram_id), f'Steps updated by {step_count} \n Balance updated by {new_balance}')
return {"status": True, "type": "step", "data": data['data'], "header": headers_dict}
else:
return {"status": False, "error": "Unsupported type"}
except Exception as e:
return {"status": False, "error": str(e)}