-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
858 lines (741 loc) · 35.1 KB
/
main.py
File metadata and controls
858 lines (741 loc) · 35.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
from services.sepay import create_payment_for_user_async
# src/bot/handlers/main.py
import os
import tempfile
import io
from aiogram.types import BufferedInputFile
import zipfile
import contextlib
import datetime
import secrets
import asyncio
import json as _json
from aiogram import Router, F
from aiogram.filters import CommandStart
from aiogram.types import Message, CallbackQuery, FSInputFile, InlineKeyboardMarkup, InlineKeyboardButton
from aiogram.exceptions import TelegramBadRequest, TelegramNetworkError
from dataclasses import dataclass
from ..keyboards import main_menu, product_menu_dynamic, tdata_menu_dynamic, proxy_menu_dynamic, back_only_menu
from settings import PRICE_A, PRICE_B, PRICE_C, PRICE_D, PRICE_E, PRICE_F, PRICE_J
from settings import ADMIN_ID, ADMIN_GROUP_ID
from .state import PendingQty
from services.inventory import Inventory
from services.uistate import UIState
from services.db import DB
from services.cache import TTLCache
from services.simple_db import SimpleDB
import logging
from settings import ADMIN_ID
logger = logging.getLogger(f'shopbot.{__name__}')
logger.info('[BOOT] handlers.main loaded with fast-response patches')
router = Router()
pending_qty = PendingQty()
# Store pending SePay orders: order_code -> user_id
pending_sepay_orders: dict[str, int] = {}
# Manual deposit requests: order_code -> user_id
pending_manual_requests: dict[str, int] = {}
# Admin notification mapping: admin_notification_message_id -> order_code
pending_admin_confirm: dict[int, str] = {}
# global simple in-memory cache used for hot values (prices, small lists)
_local_cache = TTLCache(default_ttl=10)
# process-local simple sqlite DB (file can be changed to persistent path if desired)
_local_db = SimpleDB(path=':memory:')
async def _waiting_qty_message(m: Message) -> bool:
st = await pending_qty.get(m.from_user.id)
return st is not None
async def _balance_header(db: DB, user_id: int) -> str:
bal = await db.get_balance(user_id)
return (
"━━━━━━━━━━━━━━\n"
f"💠 Số Dư : <code>{bal:,}</code> <b>VND</b>\n"
"━━━━━━━━━━━━━━\n"
)
def _price_map() -> dict[str, int]:
return {
'A': PRICE_A,
'B': PRICE_B,
'C': PRICE_C,
'D': PRICE_D,
'E': PRICE_E,
}
# ---------- Models and helpers (DRY) ----------
@dataclass(frozen=True)
class SKUInfo:
code: str
name: str
fmt: str
group: str # 'SESSION' or 'TDATA'
SKU_INFOS: dict[str, SKUInfo] = {
'A': SKUInfo('A', '+84 NEW', 'SESSION (SPAM , LỌC DATA)', 'SESSION'),
'B': SKUInfo('B', '+84 NEW', 'SESSION (KÉO 3 MEM)', 'SESSION'),
'C': SKUInfo('C', '+84 NEW', 'TXT (KÉO 5 MEM)', 'SESSION'),
'D': SKUInfo('D', '🇻🇳 +84', 'NHẮN BOT ĐỂ LẤY OTP', 'TDATA'),
'E': SKUInfo('E', '🇰🇭 +855', 'NHẮN BOT ĐỂ LẤY OTP', 'TDATA'),
'F': SKUInfo('F', 'PROXY', 'ip:port:user:pass', 'PROXY'),
'J': SKUInfo('J', '🇻🇳 +84', 'TDATA FOLDER', 'TDATA'),
}
def sku_info(code: str) -> SKUInfo | None:
return SKU_INFOS.get(code)
def product_kind(code: str) -> str:
info = sku_info(code)
return info.group if info else ('SESSION' if code in ('A', 'B', 'C') else 'TDATA')
def sibling_codes(code: str) -> tuple[str, ...]:
info = sku_info(code)
if info:
grp = info.group
else:
grp = 'SESSION' if code in ('A', 'B', 'C') else 'TDATA'
if grp == 'SESSION':
return ('A', 'B', 'C')
if grp == 'TDATA':
return ('D', 'E', 'J')
if grp == 'PROXY':
return ('F',)
return (code,)
def siblings_with_stock(inv: Inventory, code: str) -> list[tuple[str, int]]:
out: list[tuple[str, int]] = []
for p in sibling_codes(code):
if p == code:
continue
cnt = inv.count(p)
# include siblings even if count is zero so the user can see alternatives
out.append((p, cnt))
return out
def build_suggestion_rows(inv: Inventory, code: str) -> list[list[InlineKeyboardButton]]:
rows: list[list[InlineKeyboardButton]] = []
# Always show the two sibling warehouses (A/B/C or D/E grouping)
for p, cnt in siblings_with_stock(inv, code):
rows.append([InlineKeyboardButton(text=f"Kho {p} (còn {cnt})", callback_data=f'prod:{p}')])
return rows
def base_action_kb(
suggestion_rows: list[list[InlineKeyboardButton]] | None = None,
popup_button: tuple[str, str] | None = None,
show_quick_picks: bool = False,
) -> InlineKeyboardMarkup:
inline_rows: list[list[InlineKeyboardButton]] = []
if popup_button:
inline_rows.append([InlineKeyboardButton(text=popup_button[0], callback_data=popup_button[1])])
if suggestion_rows:
inline_rows.extend(suggestion_rows)
# Optional quick pick rows for inventory groups A-E (only when requested)
if show_quick_picks:
inline_rows.append([
InlineKeyboardButton(text='Kho A', callback_data='prod:A'),
InlineKeyboardButton(text='Kho B', callback_data='prod:B'),
InlineKeyboardButton(text='Kho C', callback_data='prod:C'),
])
inline_rows.append([
InlineKeyboardButton(text='Kho D', callback_data='prod:D'),
InlineKeyboardButton(text='Kho E', callback_data='prod:E'),
])
# Đã loại bỏ nút nạp tiền bank, chỉ giữ lại QR SePay
inline_rows.append([InlineKeyboardButton(text='<< Back Menu', callback_data='back')])
return InlineKeyboardMarkup(inline_keyboard=inline_rows)
def render_home(inv: Inventory, user_id: int, balance_block: str):
"""Return (text, keyboard) for the first menu."""
text = (
"Chào mừng: <b>{name}</b> đến với <i>Shop Bảo Bối ! ☘️</i>\n"
"UserID: <code>{uid}</code> Nội dung CK\n"
f"{balance_block}"
"⚠️ Rút số dư hiện tại liên hệ @boi39 . Mình không hỗ trợ rửa tiền."
)
return text, main_menu()
async def _edit_or_replace_menu(message: Message | CallbackQuery, text: str, kb, ui: UIState, user_id: int):
"""Try edit current menu message; if not possible, send a new one and delete old menus.
Accepts either a Message (for edit) coming from a callback, or directly the CallbackQuery.message.
"""
# Normalize to Message instance
msg = message.message if hasattr(message, 'message') else message
try:
await msg.edit_text(text, reply_markup=kb, parse_mode='HTML')
await ui.set_menu_id(user_id, msg.message_id)
return
except Exception as e:
emsg = str(e).lower()
# Harmless case: nothing changed
if isinstance(e, TelegramBadRequest) and 'message is not modified' in emsg:
return
# Network flake: one quick retry then fallback
if isinstance(e, TelegramNetworkError):
try:
await msg.edit_text(text, reply_markup=kb, parse_mode='HTML')
await ui.set_menu_id(user_id, msg.message_id)
return
except Exception:
pass
# Fallback: send new menu, delete old ones if possible
try:
sent = await msg.answer(text, reply_markup=kb, parse_mode='HTML')
await ui.set_menu_id(user_id, sent.message_id)
except Exception:
# If even answering fails, give up quietly
return
# delete the message we tried to edit
with contextlib.suppress(Exception):
await msg.delete()
# also delete previously tracked menu message if it's different
old_id = await ui.get_menu_id(user_id)
if old_id and old_id != sent.message_id:
with contextlib.suppress(Exception):
await msg.bot.delete_message(chat_id=msg.chat.id, message_id=old_id)
def render_products(inv: Inventory, user_id: int, balance_block: str):
a = inv.count('A')
b = inv.count('B')
c = inv.count('C')
total = a + b + c
header = (
f"{balance_block}"
f"📦 Tổng kho : <b>{total}</b> Sản Phẩm\n"
f"━━━━━━━━━━━━━━━━━━━\n"
f"🌎 Quốc Gia |♨️ Số Lượng | 💳 Giá Tiền <b>VND</b>\n"
f"━━━━━━━━━━━━━━━━━━━\n"
f"📝 Định dạng : TData | Session | 2FA\n"
)
kb = product_menu_dynamic(inv)
return header, kb
def render_tdata(inv: Inventory, user_id: int, balance_block: str):
d = inv.count('D')
e = inv.count('E')
total = d + e
header = (
f"{balance_block}"
f"📦 TDATA MENU | Tổng kho: <b>{total}</b>\n"
f"━━━━━━━━━━━━━━━━━━\n"
f"🌎 Quốc Gia |♨️ Số Lượng | 💳 Giá Tiền <b>VND</b>\n"
f"━━━━━━━━━━━━━━━━━━\n"
f"📝 Định dạng : TData | Session | 2FA\n"
)
kb = tdata_menu_dynamic(inv)
return header, kb
def render_proxy(inv: Inventory, user_id: int, balance_block: str):
e = inv.count('E')
header = (
f"{balance_block}"
f"📦 PROXY SOCK 5 | Tổng kho: <code>999999</code>\n"
f"━━━━━━━━━━━━━━━━\n"
f"Hướng dẫn cài đặt PROXY cho GOOGLE CHROME\n"
f"https://t.me/vaodaymatim/206\n"
)
kb = proxy_menu_dynamic(inv)
return header, kb
def render_tos(inv: Inventory, user_id: int, balance_block: str):
"""Return (text, keyboard) for the warranty/terms screen."""
text = (
f"<code>{balance_block}</code>"
"🛡️ <b>Chính sách bảo hành</b> :\n"
"- Sau khi mua, vui lòng check live / kiểm tra nhanh tình trạng tài khoản.\n\n"
"❌ <b>Miễn Từ Trách Nhiệm </b>:\n"
"- Login cùng lúc ở nhiều nơi.\n"
"- Mua hôm trước, hôm sau mới dùng.\n\n"
"✅ <b>Bảo hành 1 đổi 1</b> nếu lỗi phát sinh ngay khi check live sau khi mua.\n\n"
"✅ <b>Khuyến nghị</b>:\n"
"- Test trước số lượng nhỏ khi mua đầu số mới.\n"
"- Đá phiên / đổi mật khẩu file ngay sau khi mua (SIM thuê từ web)."
)
return text, back_only_menu()
def _profile_keyboard() -> InlineKeyboardMarkup:
return InlineKeyboardMarkup(inline_keyboard=[
[InlineKeyboardButton(text='<< Back Menu', callback_data='back')]
])
async def render_profile(db: DB, user_id: int, username: str | None) -> tuple[str, InlineKeyboardMarkup]:
bal = await db.get_balance(user_id)
total_paid = await db.get_total_paid(user_id)
plan, expires_at = await db.get_premium(user_id)
use_display = f"@{username}" if username else "—"
plan_display = {
'1m': '1 tháng',
'3m': '3 tháng',
'6m': '6 tháng',
'12m': '12 tháng',
None: 'Chưa có',
}.get(plan, plan or 'Chưa có')
expire_display = expires_at or '—'
text = (
"👤 Hồ sơ của bạn\n"
"━━━━━━━━━━━━━━━━━━━━\n"
f"<pre>🦁 Use : {use_display}\n"
f"🆔 ID : {user_id}\n"
f"💰 Số dư : <code>{bal:,}</code> VND\n"
f"♻️ Đã nạp : <code>{total_paid:,}</code> VND\n"
f"🎁 Thưởng : <code>0</code> VND\n"
"\n"
f"💎 Gói Premium: {plan_display}\n"
f"📝 Ngày hết hạn: {expire_display}</pre>\n"
"━━━━━━━━━━━━━━━━━━━━\n"
"🆘 Gặp Bối: https://t.me/boibank6789"
)
return text, _profile_keyboard()
@router.callback_query(F.data == 'menu:deposit_sepay')
async def deposit_sepay(cq: CallbackQuery, db: DB, ui: UIState):
"""Create SePay QR and replace current menu with the QR view.
Behavior:
- Push 'home' so Back returns there
- Create payment via create_payment_for_user
- Send photo (QR) as the single visible menu message
- Update ui.menu_id and remove any previously tracked menu messages
"""
user_id = cq.from_user.id
# keep navigation consistent
await ui.push(user_id, 'home')
# Show a locally-stored QR image and manual bank transfer info.
# Generate a local order code and remember request for manual flow
order_code = secrets.token_hex(6).upper()
pending_manual_requests[order_code] = user_id
# Local QR path (user requested): adjust if different filename
qr_local_path = r"C:\Users\Administrator\Desktop\AUTOB\qr.png"
# Bank/QR display information (as provided)
SEPAY_ACCOUNT_NAME = 'HOANG GIA BAO'
SEPAY_BANK = 'VIB'
SEPAY_ACCOUNT = '074659603'
SEPAY_CONTENT_DISPLAY = f'BBS{user_id}'
body = (
f"💳 Thông tin chuyển khoản 💳\n"
f"━━━━━━━━━━━━━━━━\n"
f"🔸 Chủ tài khoản: <code>{SEPAY_ACCOUNT_NAME}</code>\n"
f"🔸 Ngân hàng : <code>{SEPAY_BANK}</code>\n"
f"🔸 Số tài khoản : <code>{SEPAY_ACCOUNT}</code>\n"
f"🔸 Nội dung : <code>{SEPAY_CONTENT_DISPLAY}</code>\n\n"
f"☎️ Sau 3 phút không thấy cộng tiền, nhắn cho @boi39\n"
f"⚠️ LƯU Ý: Giữ nguyên nội dung để hệ thống auto cộng tiền."
)
# Keyboard: confirm (manual) + back
kb = InlineKeyboardMarkup(inline_keyboard=[
[InlineKeyboardButton(text='✅ ĐÃ NẠP', callback_data=f'manual:confirm:{order_code}'), InlineKeyboardButton(text='🔁 QUAY LẠI', callback_data='back')]
])
# Try to send local QR image; if missing, send text body (do NOT display fixed amount)
try:
if os.path.exists(qr_local_path):
await cq.message.answer_photo(photo=FSInputFile(qr_local_path), caption=(f"{body}"), reply_markup=kb, parse_mode='HTML')
else:
await cq.message.answer((f"{body}"), reply_markup=kb, parse_mode='HTML')
await cq.answer("Hiện QR/Thông tin nạp đã hiển thị.")
except Exception:
logger.exception("Failed sending local sepay QR or info")
with contextlib.suppress(Exception):
await cq.answer("Không thể hiển thị mã QR ngay bây giờ.")
# Premium menu and handlers have been moved to src/bot/handlers/premium.py
@router.message(CommandStart())
async def start(m: Message, inv: Inventory, ui: UIState, db: DB):
"""/start: remove previous menu, reset state, and send a fresh first menu."""
user_id = m.from_user.id
logger.debug(f"/start by user={user_id} -> recreate first menu and reset state")
# 1) Delete existing menu message if tracked
menu_id = await ui.get_menu_id(user_id)
if menu_id is not None:
try:
await m.bot.delete_message(chat_id=m.chat.id, message_id=menu_id)
logger.debug(f"Deleted old menu message_id={menu_id}")
except TelegramBadRequest as e:
logger.debug(f"Delete old menu failed: {e!s}")
# 2) Clear all UI state (menu_id and back stack) and pending quantity state
await ui.clear(user_id)
await pending_qty.clear(user_id)
# 2.5) Attribute referral if present: /start ref<referrer_id>
try:
if m.text and ' ' in m.text:
param = m.text.split(' ', 1)[1].strip()
if param.startswith('ref'):
ref_id = int(param[3:])
await db.set_referrer(m.from_user.id, ref_id)
except Exception:
pass
# 3) Send a brand-new first menu
bal_block = await _balance_header(db, user_id)
text, kb = render_home(inv, user_id, bal_block)
text = text.replace('{name}', m.from_user.first_name or 'bạn').replace('{uid}', str(user_id))
sent = await m.answer(text, reply_markup=kb, parse_mode='HTML')
await ui.set_menu_id(user_id, sent.message_id)
logger.debug(f"Menu created fresh message_id={sent.message_id}")
# Admin commands moved to src/bot/handlers/admin.py
# 'menu:premium' is handled in handlers/premium.py
@router.callback_query(F.data == 'menu:session')
async def show_products(cq: CallbackQuery, inv: Inventory, ui: UIState, db: DB):
# push previous screen for back navigation - should go back to home
await ui.push(cq.from_user.id, 'home')
bal_block = await _balance_header(db, cq.from_user.id)
text, kb = render_products(inv, cq.from_user.id, bal_block)
logger.debug(f"Show products for user={cq.from_user.id}")
# quick ACK so Telegram UI is responsive
await cq.answer()
# perform heavier message edit/send in background to keep callback latency low
asyncio.create_task(_edit_or_replace_menu(cq, text, kb, ui, cq.from_user.id))
@router.callback_query(F.data == 'menu:tdata')
async def show_tdata(cq: CallbackQuery, inv: Inventory, ui: UIState, db: DB):
# push previous screen for back navigation - should go back to home
await ui.push(cq.from_user.id, 'home')
bal_block = await _balance_header(db, cq.from_user.id)
text, kb = render_tdata(inv, cq.from_user.id, bal_block)
await cq.answer()
asyncio.create_task(_edit_or_replace_menu(cq, text, kb, ui, cq.from_user.id))
@router.callback_query(F.data == 'menu:orders')
async def show_proxy(cq: CallbackQuery, inv: Inventory, ui: UIState, db: DB):
# push previous screen for back navigation
await ui.push(cq.from_user.id, 'home')
bal_block = await _balance_header(db, cq.from_user.id)
text, kb = render_proxy(inv, cq.from_user.id, bal_block)
await cq.answer()
asyncio.create_task(_edit_or_replace_menu(cq, text, kb, ui, cq.from_user.id))
@router.callback_query(F.data == 'menu:tos')
async def show_tos(cq: CallbackQuery, inv: Inventory, ui: UIState, db: DB):
# push previous screen for back navigation
await ui.push(cq.from_user.id, 'home')
bal_block = await _balance_header(db, cq.from_user.id)
text, kb = render_tos(inv, cq.from_user.id, bal_block)
await cq.answer()
asyncio.create_task(_edit_or_replace_menu(cq, text, kb, ui, cq.from_user.id))
@router.callback_query(F.data == 'ui:back')
async def ui_back_alias(cq: CallbackQuery, inv: Inventory, ui: UIState, db: DB):
"""Backward-compat: some old menus use ui:back; route to global back."""
await go_back(cq, inv, ui, db)
@router.callback_query(F.data.startswith('prod:'))
async def choose_qty(cq: CallbackQuery, inv: Inventory, ui: UIState, db: DB):
prod = cq.data.split(':', 1)[1]
# push previous screen depending on product group
prev_key = 'products' if prod in ('A', 'B', 'C') else 'tdata'
await ui.push(cq.from_user.id, prev_key)
logger.debug(f"Choose qty for product={prod} user={cq.from_user.id}")
stock = inv.count(prod)
bal_block = await _balance_header(db, cq.from_user.id)
# Price per SKU (VND) and display via SKU model
unit_price = _price_map().get(prod, 0)
info = sku_info(prod)
name_display = info.name if info else f"HÀNG {prod}"
fmt_display = info.fmt if info else "—"
# Special-case proxy product formatting per user request
if prod == 'F':
name_display = 'proxy SHOCK5'
fmt_display = 'ip:port:user:pass'
# Price display with dot thousands separator (e.g., 3.000)
price_str = f"{unit_price:,}".replace(',', '.')
# Show real stock from inventory for F
try:
stock_display = inv.count('F')
except Exception:
stock_display = 0
else:
price_str = f"{unit_price:,}"
stock_display = stock
text_msg = (
f"{bal_block}"
"📊 <b>Hóa đơn mua hàng</b>\n"
"━━━━━━━━━━━━━━━━\n"
f"🛜 Sản phẩm : {name_display}\n"
f"🎯 Định dạng : {fmt_display}\n"
f"📦 Trong kho : {stock_display}\n"
f"💸 Giá : <code>{price_str}</code> <b>VND</b>\n"
"━━━━━━━━━━━━━━━━\n"
"🎁 Nhập số lượng sản phẩm cần mua:"
)
# Hành động chuẩn (không hiển thị Kho A-E ở cửa sổ hóa đơn)
kb = base_action_kb(show_quick_picks=False)
# fast ACK and background edit to keep Telegram responsive
await cq.answer()
asyncio.create_task(_edit_or_replace_menu(cq, text_msg, kb, ui, cq.from_user.id))
# menu_id is already set inside _edit_or_replace_menu; avoid overwriting with a stale id
await pending_qty.set(cq.from_user.id, prod, cq.message.message_id)
await cq.answer()
@router.message(_waiting_qty_message, F.text.regexp(r'^\d+$'))
async def capture_qty(m: Message, inv: Inventory, db: DB):
st = await pending_qty.get(m.from_user.id)
# Filter ensures we're in the state and text is digits; double-check anyway
if not st:
return
try:
qty = int((m.text or '').strip())
if qty <= 0:
raise ValueError
except Exception:
logger.debug(f"Invalid qty input by user={m.from_user.id}: {m.text!r}")
await m.answer("Số lượng không hợp lệ. ")
return
# Directly check balance and fulfill without extra confirmation
unit = _price_map().get(st.product)
if unit is None:
await m.answer("Mặt hàng không hợp lệ.")
await pending_qty.clear(m.from_user.id)
return
available = inv.count(st.product)
# If stock is insufficient, notify immediately and propose alternatives
if qty > available:
sugg_rows = build_suggestion_rows(inv, st.product)
# Show suggestion buttons for sibling warehouses instead of a popup explanation
kb_insuff = base_action_kb(
suggestion_rows=sugg_rows,
show_quick_picks=False,
)
unit_price = _price_map().get(st.product) or 0
total_req = unit_price * qty
text_insuff = (
"❌ Số lượng trong kho không đủ.\n"
f"• Bạn yêu cầu: <code>{qty}</code>\n"
f"• Hiện còn: <code>{available}</code>\n"
f"• Đơn giá: <code>{unit_price:,}</code> VND\n"
f"• Thành tiền dự kiến: <code>{total_req:,}</code> VND\n"
"\n👉 Mời tham khảo kho hàng khác hoặc nhập số lượng nhỏ hơn !"
)
await m.answer(text_insuff, reply_markup=kb_insuff, parse_mode='HTML')
# Keep waiting state so user can enter a new quantity
return
total = unit * qty
bal = await db.get_balance(m.from_user.id)
if m.from_user.id != ADMIN_ID and bal < total:
need = total - bal
# Offer sibling warehouse suggestions as quick alternative purchase options
kb = base_action_kb(
suggestion_rows=build_suggestion_rows(inv, st.product),
show_quick_picks=False,
)
await m.answer(
(
"❌ Số dư không đủ để thanh toán.\n"
f"• Thành tiền : <code>{total:,}</code> VND\n"
f"• Số dư hiện tại : <code>{bal:,}</code> VND\n"
f"• Cần nạp thêm : <code>{need:,}</code> VND\n\n"
"Nhấn các nút gợi ý để chọn kho khác, hoặc nhập số lượng nhỏ hơn."
),
reply_markup=kb,
parse_mode='HTML'
)
# Giữ trạng thái chờ số lượng để người dùng nhập lại
return
# Deduct and allocate
deducted = False
if m.from_user.id != ADMIN_ID:
if not await db.deduct_balance(m.from_user.id, total):
# Balance changed concurrently
bal = await db.get_balance(m.from_user.id)
need = max(total - bal, 0)
kb = InlineKeyboardMarkup(inline_keyboard=[
[InlineKeyboardButton(text='💸 NẠP TIỀN QR', callback_data='menu:deposit_sepay')],
[InlineKeyboardButton(text='<< Back Menu', callback_data='back')],
])
await m.answer(
(
"❌ Số dư không đủ để thanh toán.\n"
f"• Thành tiền: <code>{total:,}</code> VND\n"
f"• Số dư hiện tại: <code>{bal:,}</code> VND\n"
f"• Cần nạp thêm: <code>{need:,}</code> VND"
),
reply_markup=kb,
parse_mode='HTML'
)
return
deducted = True
try:
# allocation may touch disk; run in thread to avoid blocking
_filename, data = await asyncio.to_thread(lambda: inv.allocate(st.product, qty))
logger.debug(f"Allocated product={st.product} qty={qty} for user={m.from_user.id}")
except ValueError as e:
if deducted:
await db.add_balance(m.from_user.id, total)
await m.answer(str(e))
return
# Build and send result
tmp_path = None
order_id = secrets.token_hex(8).upper()
order_id_display = f"BOI{order_id}"
# precise timestamp with timezone for accurate records
ts = datetime.datetime.now().astimezone().strftime('%d.%m.%Y %H:%M:%S %Z')
product_kind = 'SESSION' if st.product in ('A','B','C') else 'TDATA'
# Sending files can be slow; prepare and send in background while ACKing user immediately.
async def send_order_documents():
try:
if _filename.endswith('.zip'):
order_zip_name = f"{order_id}.zip"
caption = (
f"\n✅ <b>@BaoBoiSHOP trân thành cảm ơn !</b>\n"
"━━━━━━━━━━━━━━━━\n"
f"🆔 ID Đơn hàng : <code>{order_id_display}</code>\n"
f"📦 Sản phẩm : <code>{product_kind}</code>\n"
f"📌 Số lượng : <code>{qty} Tài Khoản</code>\n"
f"💰 Thanh toán : <code>{total:,}</code> VND\n"
f"🕒 Ngày mua : <code>{ts}</code>\n"
f"🔐 2FA (Mã bảo mật): <b>666888</b>\n"
)
await m.answer_document(
BufferedInputFile(data, filename=order_zip_name),
caption=caption,
parse_mode='HTML'
)
else:
zip_display = f"{order_id}.zip"
mem = io.BytesIO()
with zipfile.ZipFile(mem, mode='w', compression=zipfile.ZIP_STORED) as zf:
inner_name = _filename
bdata = data.encode('utf-8') if isinstance(data, str) else data
zf.writestr(inner_name, bdata)
mem.seek(0)
zip_bytes = mem.getvalue()
caption = (
"✅ <b>@ShopBaoBoi trân thành cảm ơn</b> !\n"
"━━━━━━━━━━━━━━━━\n"
f"🆔 ID Đơn hàng : <code>{order_id_display}</code>\n"
f"📦 Sản phẩm : <code>{product_kind}</code>\n"
f"📌 Số lượng : {qty} Tài Khoản\n"
f"💰 Thanh toán : <code>{total:,}</code> VND\n"
f"🕒 Ngày mua : <code>{ts}</code>\n"
f"🔐 2FA (Mã bảo mật): 666888\n"
)
await m.answer_document(
BufferedInputFile(zip_bytes, filename=zip_display),
caption=caption,
parse_mode='HTML'
)
except Exception:
logger.exception('Failed sending order documents in background')
# ACK quickly to the user before heavy I/O
await m.answer('Đơn hàng của bạn đang được xử lý. Vui lòng chờ trong giây lát...')
asyncio.create_task(send_order_documents())
# No temp files used; nothing to clean up
# Clean up state on success
await pending_qty.clear(m.from_user.id)
return
@router.callback_query(F.data == 'back')
async def go_back(cq: CallbackQuery, inv: Inventory, ui: UIState, db: DB):
prev = await ui.pop(cq.from_user.id)
logger.debug(f"Back pressed by user={cq.from_user.id}, prev={prev}")
# Only 'home' supported for now; if unknown, default to home
if prev == 'products':
bal_block = await _balance_header(db, cq.from_user.id)
text, kb = render_products(inv, cq.from_user.id, bal_block)
elif prev == 'tdata':
bal_block = await _balance_header(db, cq.from_user.id)
text, kb = render_tdata(inv, cq.from_user.id, bal_block)
elif prev == 'proxy':
bal_block = await _balance_header(db, cq.from_user.id)
text, kb = render_proxy(inv, cq.from_user.id, bal_block)
else: # 'home' or None
bal_block = await _balance_header(db, cq.from_user.id)
text, kb = render_home(inv, cq.from_user.id, bal_block)
text = text.replace('{name}', cq.from_user.first_name or 'bạn').replace('{uid}', str(cq.from_user.id))
await cq.answer()
asyncio.create_task(_edit_or_replace_menu(cq, text, kb, ui, cq.from_user.id))
@router.callback_query(F.data.startswith('sepay:confirm_manual:'))
async def sepay_manual_confirm(cq: CallbackQuery, db: DB):
# User asserts they've paid via manual bank transfer. We will call SePay API to verify
# the payment and credit their account automatically if confirmed.
data = cq.data.split(':', 2)
if len(data) < 3:
await cq.answer('Dữ liệu không hợp lệ.')
return
order_code = data[2]
user_id = cq.from_user.id
# Acknowledge immediately and run verification in background to keep callback latency low.
await cq.answer('Yêu cầu xác minh giao dịch đã được nhận. Đang xử lý...')
from services.sepay import verify_payment
async def verify_and_notify():
try:
ok, payload = await asyncio.to_thread(verify_payment, order_code)
if not ok:
await cq.message.answer('Không tìm thấy giao dịch phù hợp hoặc chưa được thanh toán. Vui lòng kiểm tra lại.')
return
amount = 0
if isinstance(payload, dict):
amount = int(payload.get('amount') or payload.get('total') or 0)
# Credit DB and mark payment
try:
await db.mark_payment_paid_and_credit(order_code, user_id, amount, _json.dumps(payload, ensure_ascii=False))
await cq.message.answer(f'Giao dịch xác nhận thành công. Số tiền {amount:,} VND đã được cộng vào tài khoản của bạn.')
except Exception:
logger.exception('Failed to credit user after SePay verification')
await cq.message.answer('Xảy ra lỗi khi ghi nhận giao dịch. Vui lòng liên hệ quản trị.')
except Exception:
logger.exception('SePay background verification failed')
with contextlib.suppress(Exception):
await cq.message.answer('Xảy ra lỗi khi kiểm tra giao dịch. Vui lòng thử lại sau.')
asyncio.create_task(verify_and_notify())
@router.callback_query(F.data.startswith('manual:confirm:'))
async def manual_confirm(cq: CallbackQuery, db: DB):
# User clicked "Đã nạp" for manual/local QR flow -> notify admin group for approval
parts = cq.data.split(':', 2)
if len(parts) < 3:
await cq.answer('Dữ liệu không hợp lệ.')
return
order_code = parts[2]
user_id = cq.from_user.id
# remember mapping so admin can approve
pending_manual_requests[order_code] = user_id
# Notify admin group
try:
text = (
f"[Manual Deposit] User <a href='tg://user?id={user_id}'>{user_id}</a> báo đã chuyển tiền.\n"
f"Order: <code>{order_code}</code>\n"
f"Vui lòng xác nhận số tiền trong nhóm bằng câu trả lời (reply) ở tin nhắn này, nội dung chỉ là số tiền (vd: 100000)."
)
sent = await cq.message.bot.send_message(chat_id=ADMIN_GROUP_ID, text=text, parse_mode='HTML')
# map admin message id to order_code for later reply handling
pending_admin_confirm[sent.message_id] = order_code
# Acknowledge callback silently (no visible notification to user)
with contextlib.suppress(Exception):
await cq.answer()
except Exception:
logger.exception('Failed to notify admin group for manual deposit')
await cq.answer('Không thể gửi yêu cầu đến quản trị. Vui lòng thử lại sau.')
@router.message(F.chat.id == ADMIN_GROUP_ID)
async def admin_reply_credit(m: Message, db: DB):
# This handler should only process admin replies inside the configured ADMIN_GROUP_ID
# If a normal user sends a username (during premium flow), we must NOT intercept it.
try:
# Fast checks to ignore unrelated messages quickly
if m.chat.id != ADMIN_GROUP_ID:
return
if not m.reply_to_message:
return
reply_id = m.reply_to_message.message_id
order_code = pending_admin_confirm.get(reply_id)
if not order_code:
return
# Only allow admin user IDs to confirm
if not (m.from_user and (m.from_user.id == ADMIN_ID)):
# silent ignore by returning without replying
return
# parse amount from admin message (digits only)
txt = (m.text or '').strip().replace(',', '').replace('.', '')
if not txt.isdigit():
await m.reply('Vui lòng trả lời bằng số tiền (ví dụ: 100000) để xác nhận.')
return
amount = int(txt)
# find user
user_id = pending_manual_requests.get(order_code)
if not user_id:
await m.reply('Không tìm thấy yêu cầu tương ứng (order).')
return
# credit DB and mark as paid
try:
await db.mark_payment_paid_and_credit(order_code, user_id, amount, _json.dumps({'admin_confirm': True, 'by': m.from_user.id}))
ts = datetime.datetime.now().astimezone().strftime('%d.%m.%Y %H:%M:%S %Z')
await m.reply(f'Đã cộng {amount:,} VND cho user {user_id} (order {order_code}).\nThời gian: {ts}')
# notify user with friendly VND-style receipt (fetch updated balance)
try:
new_bal = await db.get_balance(user_id)
except Exception:
new_bal = None
if new_bal is not None:
user_text = (
f"✅ Nạp thành công: {amount:,} VND\n"
f"💰 Số dư hiện tại: {new_bal:,} VND\n"
f"🕒 Thời gian: {ts}\n"
"Cảm ơn bạn đã ủng hộ!"
)
else:
user_text = f"✅ Nạp thành công: {amount:,} VND\nCảm ơn bạn đã ủng hộ!"
with contextlib.suppress(Exception):
await m.bot.send_message(chat_id=user_id, text=user_text)
# cleanup
pending_admin_confirm.pop(reply_id, None)
pending_manual_requests.pop(order_code, None)
except Exception:
logger.exception('Failed to credit user from admin confirmation')
await m.reply('Lỗi khi cộng tiền .')
except Exception:
logger.exception('admin_reply_credit failed')
@router.callback_query(F.data == 'menu:deposit_usdt')
async def show_profile_alias(cq: CallbackQuery, db: DB):
"""Alias for the 'HỒ SƠ' button to open the profile screen."""
user_id = cq.from_user.id
text, kb = await render_profile(db, user_id, cq.from_user.username)
# Replace current menu with profile
with contextlib.suppress(Exception):
await cq.message.edit_text(text, reply_markup=kb, parse_mode='HTML')
with contextlib.suppress(Exception):
await cq.answer()