-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.py
More file actions
1838 lines (1734 loc) · 74.4 KB
/
Copy pathserver.py
File metadata and controls
1838 lines (1734 loc) · 74.4 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
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ============================================================================
# VANNA AI - Real Estate System (RES) Data Analysis
# Kết nối cùng database PostgreSQL với Spring Boot Backend
# ============================================================================
import os
from dotenv import load_dotenv
from vanna import Agent, AgentConfig
from vanna.core.registry import ToolRegistry
from vanna.core.user import User, UserResolver
from vanna.servers.fastapi import VannaFastAPIServer
from vanna.integrations.openai import OpenAILlmService
from vanna.tools import RunSqlTool, VisualizeDataTool
from vanna.tools.agent_memory import SaveQuestionToolArgsTool, SearchSavedCorrectToolUsesTool
from vanna.integrations.local.agent_memory import DemoAgentMemory
from vanna.integrations.postgres import PostgresRunner
# Load environment variables
load_dotenv()
# ============================================================================
# Simple Anonymous User Resolver
# ============================================================================
class AnonymousUserResolver(UserResolver):
"""Simple user resolver that returns an anonymous user for all requests"""
async def resolve_user(self, request_context):
return User(id="anonymous", email="anonymous@localhost", group_memberships=[])
# ============================================================================
# Configuration
# ============================================================================
# LLM Service
llm = OpenAILlmService(
model="o3",
api_key=os.getenv("OPENAI_API_KEY"),
)
# Database Runner - Kết nối cùng PostgreSQL với Backend
db_runner = PostgresRunner(
host=os.getenv("POSTGRES_HOST", os.getenv("POSTGRESQL_HOST", "localhost")),
port=int(os.getenv("POSTGRES_PORT", os.getenv("POSTGRESQL_PORT", "5432"))),
database=os.getenv("POSTGRES_DB", os.getenv("POSTGRESQL_DB", "postgres")),
user=os.getenv("POSTGRES_USER", os.getenv("POSTGRESQL_USER", "postgres")),
password=os.getenv("POSTGRES_PASSWORD", os.getenv("POSTGRESQL_PASSWORD", "secret"))
)
# Agent Memory
agent_memory = DemoAgentMemory(max_items=1000)
# User Resolver
user_resolver = AnonymousUserResolver()
# ============================================================================
# Tool Registry
# ============================================================================
tools = ToolRegistry()
# Database query tool
tools.register_local_tool(
RunSqlTool(sql_runner=db_runner),
access_groups=[]
)
# Visualization tool
tools.register_local_tool(
VisualizeDataTool(),
access_groups=[]
)
# Memory tools - Agent tự động học từ successful queries
tools.register_local_tool(
SaveQuestionToolArgsTool(),
access_groups=[]
)
tools.register_local_tool(
SearchSavedCorrectToolUsesTool(),
access_groups=[]
)
# ============================================================================
# Custom System Prompt - Real Estate System Schema
# ============================================================================
CUSTOM_SYSTEM_PROMPT = """
Bạn là trợ lý AI thông minh chuyên phân tích dữ liệu cho hệ thống Bất Động Sản (Real Estate System).
# QUAN TRỌNG
- Luôn trả lời bằng tiếng Việt
- Dữ liệu tiền theo VNĐ (ví dụ: 1500000000 = 1.5 tỷ VNĐ)
- Diện tích theo m² (mét vuông)
- Sử dụng PostgreSQL syntax
## DATABASE SCHEMA
### 1. USERS & AUTHENTICATION
#### Bảng users (Người dùng)
```sql
CREATE TABLE users (
user_id UUID PRIMARY KEY,
role VARCHAR(50) NOT NULL, -- ADMIN, SALESAGENT, CUSTOMER, PROPERTY_OWNER, ACCOUNTANT
email VARCHAR(255) NOT NULL UNIQUE,
phone_number VARCHAR(20) NOT NULL UNIQUE,
zalo_contact VARCHAR(50),
ward_id UUID REFERENCES wards(ward_id),
password VARCHAR(255) NOT NULL,
first_name VARCHAR(100) NOT NULL,
last_name VARCHAR(100) NOT NULL,
avatar_url TEXT,
status SMALLINT NOT NULL, -- 0=ACTIVE, 1=SUSPENDED, 2=PENDING_APPROVAL, 3=DELETED, 4=REJECTED
identification_number VARCHAR(20),
day_of_birth DATE,
gender VARCHAR(10),
nation VARCHAR(50),
bank_account_number VARCHAR(30),
bank_account_name VARCHAR(150),
bank_bin VARCHAR(20),
issue_date DATE,
issuing_authority VARCHAR(255),
front_id_picture_path TEXT,
back_id_picture_path TEXT,
last_login_at TIMESTAMP,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL
);
```
#### Bảng customers (Khách hàng)
```sql
CREATE TABLE customers (
customer_id UUID PRIMARY KEY REFERENCES users(user_id),
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL
);
```
#### Bảng sale_agents (Nhân viên môi giới)
```sql
CREATE TABLE sale_agents (
sale_agent_id UUID PRIMARY KEY REFERENCES users(user_id),
employee_code VARCHAR(50) NOT NULL UNIQUE,
max_properties INT NOT NULL,
hired_date TIMESTAMP NOT NULL,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL
);
```
#### Bảng property_owners (Chủ sở hữu BĐS)
```sql
CREATE TABLE property_owners (
owner_id UUID PRIMARY KEY REFERENCES users(user_id),
approved_at TIMESTAMP,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL
);
```
### 2. LOCATION (Địa điểm)
#### Bảng cities (Thành phố)
```sql
CREATE TABLE cities (
city_id UUID PRIMARY KEY,
city_name VARCHAR(100),
description TEXT,
img_url TEXT,
total_area NUMERIC(15,2),
avg_land_price NUMERIC(15,2),
population INT,
is_active BOOLEAN,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL
);
```
#### Bảng districts (Quận/Huyện)
```sql
CREATE TABLE districts (
district_id UUID PRIMARY KEY,
city_id UUID NOT NULL REFERENCES cities(city_id),
district_name VARCHAR(100),
img_url TEXT,
description TEXT,
total_area NUMERIC(15,2),
avg_land_price NUMERIC(15,2),
population INT,
is_active BOOLEAN,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL
);
```
#### Bảng wards (Phường/Xã)
```sql
CREATE TABLE wards (
ward_id UUID PRIMARY KEY,
district_id UUID NOT NULL REFERENCES districts(district_id),
ward_name VARCHAR(100) NOT NULL,
img_url TEXT,
description TEXT NOT NULL,
total_area NUMERIC(15,2) NOT NULL,
avg_land_price NUMERIC(15,2),
population INT NOT NULL,
is_active BOOLEAN,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL
);
```
### 3. PROPERTIES (Bất động sản)
#### Bảng property_types (Loại BĐS)
```sql
CREATE TABLE property_types (
property_type_id UUID PRIMARY KEY,
type_name VARCHAR(50) NOT NULL UNIQUE, -- Căn hộ, Nhà phố, Biệt thự, Đất nền, Shophouse...
avatar_url TEXT,
description TEXT,
is_active BOOLEAN,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL
);
```
#### Bảng properties (Bất động sản)
```sql
CREATE TABLE properties (
property_id UUID PRIMARY KEY,
owner_id UUID NOT NULL REFERENCES property_owners(owner_id),
assigned_agent_id UUID REFERENCES sale_agents(sale_agent_id),
service_fee_amount NUMERIC(15,2) NOT NULL,
service_fee_collected_amount NUMERIC(15,2) NOT NULL,
property_type_id UUID NOT NULL REFERENCES property_types(property_type_id),
ward_id UUID NOT NULL REFERENCES wards(ward_id),
title VARCHAR(200) NOT NULL,
description TEXT NOT NULL,
transaction_type VARCHAR(20) NOT NULL, -- SALE, RENTAL, INVESTMENT
full_address TEXT,
area NUMERIC(10,2) NOT NULL, -- Diện tích (m²)
rooms INT,
bathrooms INT,
floors INT,
bedrooms INT,
house_orientation VARCHAR(20), -- NORTH, SOUTH, EAST, WEST, NORTH_EAST, NORTH_WEST, SOUTH_EAST, SOUTH_WEST
balcony_orientation VARCHAR(20),
year_built INT,
price_amount NUMERIC(15,2) NOT NULL, -- Giá (VNĐ)
price_per_square_meter NUMERIC(15,2),
commission_rate NUMERIC(5,4) NOT NULL, -- Tỷ lệ hoa hồng
amenities TEXT, -- Tiện ích
status VARCHAR(20), -- PENDING, REJECTED, APPROVED, SOLD, RENTED, AVAILABLE, UNAVAILABLE, REMOVED, DELETED
view_count INT,
approved_at TIMESTAMP,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL
);
```
#### Bảng media (Ảnh/Video BĐS)
```sql
CREATE TABLE media (
media_id UUID PRIMARY KEY,
property_id UUID REFERENCES properties(property_id),
report_id UUID REFERENCES violation_reports(violation_id),
media_type VARCHAR(20) NOT NULL, -- IMAGE, VIDEO, DOCUMENT
file_name VARCHAR(255) NOT NULL,
file_path VARCHAR(500) NOT NULL,
mime_type VARCHAR(100) NOT NULL,
document_type VARCHAR(50),
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL
);
```
### 4. APPOINTMENTS (Lịch hẹn xem nhà)
```sql
CREATE TABLE appointment (
appointment_id UUID PRIMARY KEY,
property_id UUID NOT NULL REFERENCES properties(property_id),
customer_id UUID NOT NULL REFERENCES customers(customer_id),
agent_id UUID REFERENCES sale_agents(sale_agent_id),
requested_date TIMESTAMP NOT NULL,
confirmed_date TIMESTAMP,
status SMALLINT, -- 0=PENDING, 1=CONFIRMED, 2=COMPLETED, 3=CANCELLED
customer_requirements TEXT,
agent_notes TEXT,
viewing_outcome TEXT,
customer_interest_level VARCHAR(20),
cancelled_at TIMESTAMP,
cancelled_by VARCHAR(20), -- ADMIN, SALESAGENT, CUSTOMER, PROPERTY_OWNER
cancelled_reason TEXT,
rating SMALLINT, -- 1-5
comment TEXT,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL
);
```
### 5. CONTRACTS (Hợp đồng)
```sql
CREATE TABLE contract (
contract_id UUID PRIMARY KEY,
property_id UUID NOT NULL REFERENCES properties(property_id),
customer_id UUID NOT NULL REFERENCES customers(customer_id),
agent_id UUID NOT NULL REFERENCES sale_agents(sale_agent_id),
contract_type VARCHAR(20) NOT NULL, -- PURCHASE, RENTAL, INVESTMENT
contract_number VARCHAR(50) NOT NULL UNIQUE,
start_date DATE NOT NULL,
end_date DATE NOT NULL,
special_terms TEXT NOT NULL,
status VARCHAR(20) NOT NULL, -- DRAFT, PENDING_SIGNING, ACTIVE, COMPLETED, CANCELLED
cancellation_reason TEXT,
cancellation_penalty NUMERIC(15,2),
cancelled_by VARCHAR(20),
contract_payment_type VARCHAR(20) NOT NULL, -- MORTGAGE, MONTHLY_RENT, PAID_IN_FULL
total_contract_amount NUMERIC(15,2) NOT NULL,
deposit_amount NUMERIC(15,2) NOT NULL,
remaining_amount NUMERIC(15,2) NOT NULL,
advance_payment_amount NUMERIC(15,2) NOT NULL,
installment_amount INT NOT NULL,
progress_milestone NUMERIC(15,2) NOT NULL,
final_payment_amount NUMERIC(15,2) NOT NULL,
late_payment_penalty_rate NUMERIC(5,4) NOT NULL,
special_conditions TEXT NOT NULL,
signed_at TIMESTAMP NOT NULL,
completed_at TIMESTAMP NOT NULL,
rating SMALLINT,
comment TEXT,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL
);
```
### 6. PAYMENTS (Thanh toán)
```sql
CREATE TABLE payments (
payment_id UUID PRIMARY KEY,
contract_id UUID REFERENCES contract(contract_id),
property_id UUID REFERENCES properties(property_id),
sale_agent_id UUID REFERENCES sale_agents(sale_agent_id),
payment_type VARCHAR(20) NOT NULL, -- DEPOSIT, ADVANCE, INSTALLMENT, FULL_PAY, MONTHLY, PENALTY, REFUND, MONEY_SALE, MONEY_RENTAL, SALARY, SERVICE_FEE
amount NUMERIC(15,2) NOT NULL,
due_date DATE NOT NULL,
paid_date DATE,
installment_number INT,
payment_method VARCHAR(50),
transaction_reference VARCHAR(100),
status SMALLINT, -- 0=PENDING, 1=SUCCESS, 2=FAILED, 3=SYSTEM_PENDING, 4=SYSTEM_SUCCESS, 5=SYSTEM_FAILED
penalty_amount NUMERIC(15,2),
notes TEXT,
payos_order_code BIGINT UNIQUE,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL
);
```
### ⚠️ LƯU Ý QUAN TRỌNG VỀ PAYMENTS:
- **status là SMALLINT**: 0=PENDING, 1=SUCCESS, 2=FAILED, 3=SYSTEM_PENDING, 4=SYSTEM_SUCCESS, 5=SYSTEM_FAILED
- **payment_type là STRING**: DEPOSIT, ADVANCE, INSTALLMENT, FULL_PAY, MONTHLY, PENALTY, REFUND, MONEY_SALE, MONEY_RENTAL, SALARY, SERVICE_FEE
- **Ý nghĩa các payment_type:**
- SALARY: Tiền lương trả cho nhân viên môi giới
- DEPOSIT: Tiền đặt cọc từ khách hàng
- ADVANCE: Tiền thanh toán trước/tạm ứng
- INSTALLMENT: Tiền trả góp theo kỳ
- FULL_PAY: Thanh toán toàn bộ một lần
- MONTHLY: Tiền thuê hàng tháng
- PENALTY: Tiền phạt vi phạm hợp đồng
- REFUND: Tiền hoàn trả
- MONEY_SALE: Tiền chủ nhà nhận được từ việc bán BĐS
- MONEY_RENTAL: Tiền chủ nhà nhận được từ cho thuê BĐS
- SERVICE_FEE: Phí dịch vụ chủ nhà trả cho hệ thống
### 7. DOCUMENTS (Giấy tờ pháp lý)
#### Bảng document_types
```sql
CREATE TABLE document_types (
document_type_id UUID PRIMARY KEY,
name VARCHAR(100),
description TEXT,
is_compulsory BOOLEAN,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL
);
```
#### Bảng identification_documents
```sql
CREATE TABLE identification_documents (
document_id UUID PRIMARY KEY,
document_type_id UUID NOT NULL REFERENCES document_types(document_type_id),
property_id UUID REFERENCES properties(property_id),
document_number VARCHAR(20) NOT NULL,
document_name VARCHAR(255) NOT NULL,
file_path VARCHAR(500) NOT NULL,
issue_date DATE,
expiry_date DATE,
issuing_authority VARCHAR(100),
verification_status VARCHAR(20), -- PENDING, VERIFIED, REJECTED
verified_at TIMESTAMP,
rejection_reason TEXT,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL
);
```
### 8. NOTIFICATIONS (Thông báo)
```sql
CREATE TABLE notifications (
notification_id UUID PRIMARY KEY,
recipient_id UUID NOT NULL REFERENCES users(user_id),
type VARCHAR(30), -- APPOINTMENT_REMINDER, CONTRACT_UPDATE, PAYMENT_DUE, VIOLATION_WARNING, SYSTEM_ALERT
title VARCHAR(200) NOT NULL,
message TEXT NOT NULL,
related_entity_type VARCHAR(20), -- PROPERTY, CONTRACT, PAYMENT, APPOINTMENT, USER
related_entity_id VARCHAR(100),
delivery_status VARCHAR(20), -- PENDING, SENT, READ, FAILED
is_read BOOLEAN,
img_url TEXT NOT NULL,
read_at TIMESTAMP,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL
);
```
### 9. VIOLATION REPORTS (Báo cáo vi phạm)
```sql
CREATE TABLE violation_reports (
violation_id UUID PRIMARY KEY,
user_id UUID REFERENCES users(user_id),
related_entity_type VARCHAR(20) NOT NULL, -- CUSTOMER, PROPERTY, SALES_AGENT, PROPERTY_OWNER
related_entity_id UUID NOT NULL,
violation_type VARCHAR(50) NOT NULL, -- FRAUDULENT_LISTING, MISREPRESENTATION_OF_PROPERTY, SPAM_OR_DUPLICATE_LISTING, INAPPROPRIATE_CONTENT, NON_COMPLIANCE_WITH_TERMS, FAILURE_TO_DISCLOSE_INFORMATION, HARASSMENT, SCAM_ATTEMPT
description TEXT NOT NULL,
status VARCHAR(20), -- PENDING, REPORTED, UNDER_REVIEW, RESOLVED, DISMISSED
resolution_notes TEXT,
resolved_at TIMESTAMP,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL
);
```
## HƯỚNG DẪN TẠO SQL
1. **Luôn dùng PostgreSQL syntax**
2. **UUID là kiểu dữ liệu cho các ID**
3. **Ghép họ tên:** `CONCAT(last_name, ' ', first_name) AS full_name`
4. **Format tiền VNĐ:** Giữ nguyên số, giải thích khi trả lời (ví dụ: 1.5 tỷ)
5. **Join bảng vị trí:** properties → wards → districts → cities
6. **Join bảng user liên quan:** customers/sale_agents/property_owners → users
## ⚠️ QUAN TRỌNG: STATUS MAPPING
Một số bảng dùng SMALLINT cho status (lưu dạng số), một số dùng VARCHAR (lưu dạng string):
### Bảng dùng SMALLINT (số):
- **users.status**: 0=ACTIVE, 1=SUSPENDED, 2=PENDING_APPROVAL, 3=DELETED, 4=REJECTED
- **appointment.status**: 0=PENDING, 1=CONFIRMED, 2=COMPLETED, 3=CANCELLED
- **payments.status**: 0=PENDING, 1=SUCCESS, 2=FAILED, 3=SYSTEM_PENDING, 4=SYSTEM_SUCCESS, 5=SYSTEM_FAILED
### Bảng dùng VARCHAR (string):
- **properties.status**: 'PENDING', 'REJECTED', 'APPROVED', 'SOLD', 'RENTED', 'AVAILABLE', 'UNAVAILABLE', 'REMOVED', 'DELETED'
- **contract.status**: 'DRAFT', 'PENDING_SIGNING', 'ACTIVE', 'COMPLETED', 'CANCELLED'
- **violation_reports.status**: 'PENDING', 'REPORTED', 'UNDER_REVIEW', 'RESOLVED', 'DISMISSED'
## ⚠️ QUAN TRỌNG: CÁCH JOIN ĐỂ PHÂN TÍCH KHÁCH HÀNG CHI TIÊU
Để biết khách hàng chi tiêu bao nhiêu, cần join: **payments → contract → customers → users**
```sql
-- Ví dụ: Khách hàng chi tiêu nhiều nhất
SELECT CONCAT(u.last_name, ' ', u.first_name) AS customer_name,
u.email, u.gender, u.day_of_birth,
SUM(p.amount) AS total_spent
FROM payments p
JOIN contract ct ON p.contract_id = ct.contract_id
JOIN customers c ON ct.customer_id = c.customer_id
JOIN users u ON c.customer_id = u.user_id
WHERE p.status = 1 -- SUCCESS
GROUP BY c.customer_id, u.last_name, u.first_name, u.email, u.gender, u.day_of_birth
ORDER BY total_spent DESC;
```
Để biết khu vực khách hàng sinh sống, thêm join: **users → wards → districts → cities**
## EXAMPLE QUERIES
### Tổng số BĐS theo trạng thái
```sql
SELECT status, COUNT(*) as so_luong
FROM properties
GROUP BY status
ORDER BY so_luong DESC;
```
### Danh sách BĐS đang bán/cho thuê có giá cao nhất
```sql
SELECT p.title, p.price_amount, p.area, p.transaction_type,
pt.type_name, c.city_name, d.district_name
FROM properties p
JOIN property_types pt ON p.property_type_id = pt.property_type_id
JOIN wards w ON p.ward_id = w.ward_id
JOIN districts d ON w.district_id = d.district_id
JOIN cities c ON d.city_id = c.city_id
WHERE p.status = 'AVAILABLE'
ORDER BY p.price_amount DESC
LIMIT 10;
```
### Top 10 nhân viên môi giới có nhiều BĐS nhất
```sql
SELECT CONCAT(u.last_name, ' ', u.first_name) AS agent_name,
sa.employee_code,
COUNT(p.property_id) AS total_properties
FROM sale_agents sa
JOIN users u ON sa.sale_agent_id = u.user_id
LEFT JOIN properties p ON p.assigned_agent_id = sa.sale_agent_id
GROUP BY sa.sale_agent_id, u.last_name, u.first_name, sa.employee_code
ORDER BY total_properties DESC
LIMIT 10;
```
### Doanh thu theo tháng (từ payments thành công)
```sql
SELECT DATE_TRUNC('month', paid_date) AS thang,
SUM(amount) AS tong_doanh_thu
FROM payments
WHERE status = 1 AND paid_date IS NOT NULL
GROUP BY DATE_TRUNC('month', paid_date)
ORDER BY thang DESC;
```
### Số lượng lịch hẹn theo trạng thái
```sql
SELECT status, COUNT(*) AS so_luong
FROM appointment
GROUP BY status;
```
### Thống kê hợp đồng theo loại
```sql
SELECT contract_type, status, COUNT(*) AS so_luong,
SUM(total_contract_amount) AS tong_gia_tri
FROM contract
GROUP BY contract_type, status
ORDER BY contract_type, status;
```
### BĐS theo khu vực (thành phố)
```sql
SELECT c.city_name, COUNT(p.property_id) AS so_bds,
AVG(p.price_amount) AS gia_trung_binh,
AVG(p.area) AS dien_tich_tb
FROM properties p
JOIN wards w ON p.ward_id = w.ward_id
JOIN districts d ON w.district_id = d.district_id
JOIN cities c ON d.city_id = c.city_id
WHERE p.status IN ('AVAILABLE', 'APPROVED')
GROUP BY c.city_id, c.city_name
ORDER BY so_bds DESC;
```
### Khách hàng có nhiều lịch hẹn nhất
```sql
SELECT CONCAT(u.last_name, ' ', u.first_name) AS customer_name,
u.email, u.phone_number,
COUNT(a.appointment_id) AS total_appointments
FROM customers cu
JOIN users u ON cu.customer_id = u.user_id
LEFT JOIN appointment a ON a.customer_id = cu.customer_id
GROUP BY cu.customer_id, u.last_name, u.first_name, u.email, u.phone_number
ORDER BY total_appointments DESC
LIMIT 10;
```
### Chủ sở hữu có nhiều BĐS nhất
```sql
SELECT CONCAT(u.last_name, ' ', u.first_name) AS owner_name,
u.email, COUNT(p.property_id) AS total_properties,
SUM(p.price_amount) AS total_value
FROM property_owners po
JOIN users u ON po.owner_id = u.user_id
LEFT JOIN properties p ON p.owner_id = po.owner_id
GROUP BY po.owner_id, u.last_name, u.first_name, u.email
ORDER BY total_properties DESC
LIMIT 10;
```
### Rating trung bình của các nhân viên
```sql
SELECT CONCAT(u.last_name, ' ', u.first_name) AS agent_name,
sa.employee_code,
AVG(a.rating) AS avg_appointment_rating,
AVG(c.rating) AS avg_contract_rating,
COUNT(DISTINCT a.appointment_id) AS total_appointments,
COUNT(DISTINCT c.contract_id) AS total_contracts
FROM sale_agents sa
JOIN users u ON sa.sale_agent_id = u.user_id
LEFT JOIN appointment a ON a.agent_id = sa.sale_agent_id AND a.rating IS NOT NULL
LEFT JOIN contract c ON c.agent_id = sa.sale_agent_id AND c.rating IS NOT NULL
GROUP BY sa.sale_agent_id, u.last_name, u.first_name, sa.employee_code
HAVING AVG(a.rating) IS NOT NULL OR AVG(c.rating) IS NOT NULL
ORDER BY avg_appointment_rating DESC NULLS LAST;
```
## NHIỆM VỤ CỦA BẠN
1. Hiểu câu hỏi của người dùng về hệ thống bất động sản
2. Tạo SQL query chính xác dựa trên schema trên
3. Chạy query và trả về kết quả
4. Nếu cần, tạo visualization (biểu đồ) để minh họa
5. Giải thích kết quả bằng tiếng Việt dễ hiểu
### Gợi ý theo từ khóa:
- "BĐS/Bất động sản/Nhà/Căn hộ" → Bảng `properties`
- "Khách hàng" → Bảng `customers` JOIN `users`
- "Nhân viên/Môi giới/Agent" → Bảng `sale_agents` JOIN `users`
- "Chủ nhà/Chủ sở hữu" → Bảng `property_owners` JOIN `users`
- "Lịch hẹn/Xem nhà" → Bảng `appointment`
- "Hợp đồng" → Bảng `contract`
- "Thanh toán/Doanh thu" → Bảng `payments`
- "Thành phố/Quận/Phường" → Bảng `cities`, `districts`, `wards`
- "Vi phạm/Báo cáo" → Bảng `violation_reports`
"""
# Create agent with custom system prompt
agent = Agent(
llm_service=llm,
tool_registry=tools,
user_resolver=user_resolver,
agent_memory=agent_memory,
config=AgentConfig(
system_prompt=CUSTOM_SYSTEM_PROMPT,
max_tool_iterations=100,
temperature=0.1
)
)
# ============================================================================
# Pre-populate Agent Memory với training data
# ============================================================================
async def populate_memory():
"""Pre-populate agent memory with common query patterns for Real Estate System"""
from vanna.core.tool import ToolContext
from vanna.core.user import User
mock_user = User(id="system", email="system@vanna.ai", group_memberships=[])
mock_context = ToolContext(
user=mock_user,
agent_memory=agent_memory,
conversation_id="training",
message_id="training",
request_id="training-request"
)
# Training data - Common question-SQL pairs for Real Estate System
training_data = [
# ==================== PROPERTIES ====================
{
"question": "Có bao nhiêu bất động sản trong hệ thống?",
"sql": "SELECT COUNT(*) AS total_properties FROM properties;"
},
{
"question": "Thống kê BĐS theo trạng thái",
"sql": "SELECT status, COUNT(*) AS so_luong FROM properties GROUP BY status ORDER BY so_luong DESC;"
},
{
"question": "Top 10 BĐS giá cao nhất đang bán",
"sql": """SELECT p.title, p.price_amount, p.area, pt.type_name, c.city_name
FROM properties p
JOIN property_types pt ON p.property_type_id = pt.property_type_id
JOIN wards w ON p.ward_id = w.ward_id
JOIN districts d ON w.district_id = d.district_id
JOIN cities c ON d.city_id = c.city_id
WHERE p.status = 'AVAILABLE' AND p.transaction_type = 'SALE'
ORDER BY p.price_amount DESC LIMIT 10;"""
},
{
"question": "BĐS cho thuê có giá thấp nhất",
"sql": """SELECT p.title, p.price_amount, p.area, pt.type_name, c.city_name, d.district_name
FROM properties p
JOIN property_types pt ON p.property_type_id = pt.property_type_id
JOIN wards w ON p.ward_id = w.ward_id
JOIN districts d ON w.district_id = d.district_id
JOIN cities c ON d.city_id = c.city_id
WHERE p.status = 'AVAILABLE' AND p.transaction_type = 'RENTAL'
ORDER BY p.price_amount ASC LIMIT 10;"""
},
{
"question": "BĐS theo loại giao dịch",
"sql": "SELECT transaction_type, COUNT(*) AS so_luong, AVG(price_amount) AS gia_tb FROM properties GROUP BY transaction_type;"
},
{
"question": "BĐS theo hướng nhà",
"sql": "SELECT house_orientation, COUNT(*) AS so_luong FROM properties WHERE house_orientation IS NOT NULL GROUP BY house_orientation ORDER BY so_luong DESC;"
},
{
"question": "BĐS có diện tích lớn nhất",
"sql": "SELECT title, area, price_amount, full_address FROM properties ORDER BY area DESC LIMIT 10;"
},
{
"question": "BĐS mới đăng trong tháng này",
"sql": "SELECT title, price_amount, transaction_type, status, created_at FROM properties WHERE DATE_TRUNC('month', created_at) = DATE_TRUNC('month', CURRENT_DATE) ORDER BY created_at DESC;"
},
{
"question": "BĐS đã được duyệt",
"sql": "SELECT COUNT(*) AS approved_count FROM properties WHERE status = 'APPROVED' OR approved_at IS NOT NULL;"
},
{
"question": "Giá trung bình BĐS theo loại",
"sql": """SELECT pt.type_name, COUNT(p.property_id) AS so_bds, AVG(p.price_amount) AS gia_tb, AVG(p.area) AS dien_tich_tb
FROM properties p
JOIN property_types pt ON p.property_type_id = pt.property_type_id
GROUP BY pt.property_type_id, pt.type_name ORDER BY gia_tb DESC;"""
},
# ==================== PROPERTY TYPES ====================
{
"question": "Danh sách loại BĐS",
"sql": "SELECT type_name, description, is_active FROM property_types ORDER BY type_name;"
},
{
"question": "Loại BĐS nào phổ biến nhất?",
"sql": """SELECT pt.type_name, COUNT(p.property_id) AS so_bds
FROM property_types pt
LEFT JOIN properties p ON p.property_type_id = pt.property_type_id
GROUP BY pt.property_type_id, pt.type_name ORDER BY so_bds DESC;"""
},
# ==================== USERS ====================
{
"question": "Có bao nhiêu người dùng?",
"sql": "SELECT COUNT(*) AS total_users FROM users;"
},
{
"question": "Thống kê người dùng theo vai trò",
"sql": "SELECT role, COUNT(*) AS so_luong FROM users GROUP BY role ORDER BY so_luong DESC;"
},
{
"question": "Thống kê người dùng theo trạng thái",
"sql": "SELECT status, COUNT(*) AS so_luong FROM users GROUP BY status ORDER BY so_luong DESC;"
},
{
"question": "Người dùng đăng ký mới trong tháng",
"sql": "SELECT role, COUNT(*) AS so_luong FROM users WHERE DATE_TRUNC('month', created_at) = DATE_TRUNC('month', CURRENT_DATE) GROUP BY role;"
},
{
"question": "Người dùng theo giới tính",
"sql": "SELECT gender, COUNT(*) AS so_luong FROM users WHERE gender IS NOT NULL GROUP BY gender;"
},
# ==================== CUSTOMERS ====================
{
"question": "Có bao nhiêu khách hàng?",
"sql": "SELECT COUNT(*) AS total_customers FROM customers;"
},
{
"question": "Danh sách khách hàng",
"sql": """SELECT CONCAT(u.last_name, ' ', u.first_name) AS customer_name, u.email, u.phone_number, u.status
FROM customers cu
JOIN users u ON cu.customer_id = u.user_id
ORDER BY u.created_at DESC LIMIT 20;"""
},
{
"question": "Khách hàng có nhiều lịch hẹn nhất",
"sql": """SELECT CONCAT(u.last_name, ' ', u.first_name) AS customer_name, u.email, u.phone_number, COUNT(a.appointment_id) AS total_appointments
FROM customers cu
JOIN users u ON cu.customer_id = u.user_id
LEFT JOIN appointment a ON a.customer_id = cu.customer_id
GROUP BY cu.customer_id, u.last_name, u.first_name, u.email, u.phone_number
ORDER BY total_appointments DESC LIMIT 10;"""
},
{
"question": "Khách hàng có nhiều hợp đồng nhất",
"sql": """SELECT CONCAT(u.last_name, ' ', u.first_name) AS customer_name, u.email, COUNT(c.contract_id) AS total_contracts, SUM(c.total_contract_amount) AS total_value
FROM customers cu
JOIN users u ON cu.customer_id = u.user_id
LEFT JOIN contract c ON c.customer_id = cu.customer_id
GROUP BY cu.customer_id, u.last_name, u.first_name, u.email
ORDER BY total_contracts DESC LIMIT 10;"""
},
# === PHÂN TÍCH KHÁCH HÀNG CHI TIÊU ===
{
"question": "Khách hàng nào chi tiêu nhiều nhất?",
"sql": """SELECT CONCAT(u.last_name, ' ', u.first_name) AS customer_name, u.email, u.phone_number,
SUM(p.amount) AS total_spent, COUNT(DISTINCT ct.contract_id) AS so_hop_dong
FROM payments p
JOIN contract ct ON p.contract_id = ct.contract_id
JOIN customers c ON ct.customer_id = c.customer_id
JOIN users u ON c.customer_id = u.user_id
WHERE p.status = 1
GROUP BY c.customer_id, u.last_name, u.first_name, u.email, u.phone_number
ORDER BY total_spent DESC LIMIT 10;"""
},
{
"question": "Khách hàng chi tiêu nhiều tiền nhất",
"sql": """SELECT CONCAT(u.last_name, ' ', u.first_name) AS customer_name, u.email, u.phone_number,
SUM(p.amount) AS total_spent, COUNT(DISTINCT ct.contract_id) AS so_hop_dong
FROM payments p
JOIN contract ct ON p.contract_id = ct.contract_id
JOIN customers c ON ct.customer_id = c.customer_id
JOIN users u ON c.customer_id = u.user_id
WHERE p.status = 1
GROUP BY c.customer_id, u.last_name, u.first_name, u.email, u.phone_number
ORDER BY total_spent DESC LIMIT 10;"""
},
{
"question": "Top khách hàng VIP chi tiêu cao",
"sql": """SELECT CONCAT(u.last_name, ' ', u.first_name) AS customer_name, u.email, u.phone_number, u.gender,
EXTRACT(YEAR FROM CURRENT_DATE) - EXTRACT(YEAR FROM u.day_of_birth) AS tuoi,
SUM(p.amount) AS total_spent, COUNT(DISTINCT ct.contract_id) AS so_hop_dong
FROM payments p
JOIN contract ct ON p.contract_id = ct.contract_id
JOIN customers c ON ct.customer_id = c.customer_id
JOIN users u ON c.customer_id = u.user_id
WHERE p.status = 1
GROUP BY c.customer_id, u.last_name, u.first_name, u.email, u.phone_number, u.gender, u.day_of_birth
ORDER BY total_spent DESC LIMIT 20;"""
},
{
"question": "Phân tích khách hàng theo giới tính",
"sql": """SELECT u.gender AS gioi_tinh,
COUNT(DISTINCT c.customer_id) AS so_khach_hang,
SUM(p.amount) AS tong_chi_tieu,
AVG(p.amount) AS chi_tieu_tb
FROM payments p
JOIN contract ct ON p.contract_id = ct.contract_id
JOIN customers c ON ct.customer_id = c.customer_id
JOIN users u ON c.customer_id = u.user_id
WHERE p.status = 1 AND u.gender IS NOT NULL
GROUP BY u.gender
ORDER BY tong_chi_tieu DESC;"""
},
{
"question": "Khách hàng chi tiêu theo giới tính",
"sql": """SELECT u.gender AS gioi_tinh,
COUNT(DISTINCT c.customer_id) AS so_khach_hang,
SUM(p.amount) AS tong_chi_tieu,
AVG(p.amount) AS chi_tieu_tb
FROM payments p
JOIN contract ct ON p.contract_id = ct.contract_id
JOIN customers c ON ct.customer_id = c.customer_id
JOIN users u ON c.customer_id = u.user_id
WHERE p.status = 1 AND u.gender IS NOT NULL
GROUP BY u.gender
ORDER BY tong_chi_tieu DESC;"""
},
{
"question": "Phân tích khách hàng theo độ tuổi",
"sql": """SELECT
CASE
WHEN EXTRACT(YEAR FROM CURRENT_DATE) - EXTRACT(YEAR FROM u.day_of_birth) < 25 THEN 'Dưới 25 tuổi'
WHEN EXTRACT(YEAR FROM CURRENT_DATE) - EXTRACT(YEAR FROM u.day_of_birth) < 35 THEN '25-34 tuổi'
WHEN EXTRACT(YEAR FROM CURRENT_DATE) - EXTRACT(YEAR FROM u.day_of_birth) < 45 THEN '35-44 tuổi'
WHEN EXTRACT(YEAR FROM CURRENT_DATE) - EXTRACT(YEAR FROM u.day_of_birth) < 55 THEN '45-54 tuổi'
ELSE 'Trên 55 tuổi'
END AS nhom_tuoi,
COUNT(DISTINCT c.customer_id) AS so_khach_hang,
SUM(p.amount) AS tong_chi_tieu,
AVG(p.amount) AS chi_tieu_tb
FROM payments p
JOIN contract ct ON p.contract_id = ct.contract_id
JOIN customers c ON ct.customer_id = c.customer_id
JOIN users u ON c.customer_id = u.user_id
WHERE p.status = 1 AND u.day_of_birth IS NOT NULL
GROUP BY nhom_tuoi
ORDER BY tong_chi_tieu DESC;"""
},
{
"question": "Khách hàng chi tiêu theo độ tuổi",
"sql": """SELECT
CASE
WHEN EXTRACT(YEAR FROM CURRENT_DATE) - EXTRACT(YEAR FROM u.day_of_birth) < 25 THEN 'Dưới 25 tuổi'
WHEN EXTRACT(YEAR FROM CURRENT_DATE) - EXTRACT(YEAR FROM u.day_of_birth) < 35 THEN '25-34 tuổi'
WHEN EXTRACT(YEAR FROM CURRENT_DATE) - EXTRACT(YEAR FROM u.day_of_birth) < 45 THEN '35-44 tuổi'
WHEN EXTRACT(YEAR FROM CURRENT_DATE) - EXTRACT(YEAR FROM u.day_of_birth) < 55 THEN '45-54 tuổi'
ELSE 'Trên 55 tuổi'
END AS nhom_tuoi,
COUNT(DISTINCT c.customer_id) AS so_khach_hang,
SUM(p.amount) AS tong_chi_tieu,
AVG(p.amount) AS chi_tieu_tb
FROM payments p
JOIN contract ct ON p.contract_id = ct.contract_id
JOIN customers c ON ct.customer_id = c.customer_id
JOIN users u ON c.customer_id = u.user_id
WHERE p.status = 1 AND u.day_of_birth IS NOT NULL
GROUP BY nhom_tuoi
ORDER BY tong_chi_tieu DESC;"""
},
{
"question": "Phân tích khách hàng theo khu vực sinh sống",
"sql": """SELECT ci.city_name AS thanh_pho,
COUNT(DISTINCT c.customer_id) AS so_khach_hang,
SUM(p.amount) AS tong_chi_tieu,
AVG(p.amount) AS chi_tieu_tb
FROM payments p
JOIN contract ct ON p.contract_id = ct.contract_id
JOIN customers c ON ct.customer_id = c.customer_id
JOIN users u ON c.customer_id = u.user_id
JOIN wards w ON u.ward_id = w.ward_id
JOIN districts d ON w.district_id = d.district_id
JOIN cities ci ON d.city_id = ci.city_id
WHERE p.status = 1
GROUP BY ci.city_id, ci.city_name
ORDER BY tong_chi_tieu DESC;"""
},
{
"question": "Khách hàng chi tiêu theo thành phố",
"sql": """SELECT ci.city_name AS thanh_pho,
COUNT(DISTINCT c.customer_id) AS so_khach_hang,
SUM(p.amount) AS tong_chi_tieu,
AVG(p.amount) AS chi_tieu_tb
FROM payments p
JOIN contract ct ON p.contract_id = ct.contract_id
JOIN customers c ON ct.customer_id = c.customer_id
JOIN users u ON c.customer_id = u.user_id
JOIN wards w ON u.ward_id = w.ward_id
JOIN districts d ON w.district_id = d.district_id
JOIN cities ci ON d.city_id = ci.city_id
WHERE p.status = 1
GROUP BY ci.city_id, ci.city_name
ORDER BY tong_chi_tieu DESC;"""
},
{
"question": "Khách hàng chi tiêu theo quận huyện",
"sql": """SELECT ci.city_name AS thanh_pho, d.district_name AS quan_huyen,
COUNT(DISTINCT c.customer_id) AS so_khach_hang,
SUM(p.amount) AS tong_chi_tieu
FROM payments p
JOIN contract ct ON p.contract_id = ct.contract_id
JOIN customers c ON ct.customer_id = c.customer_id
JOIN users u ON c.customer_id = u.user_id
JOIN wards w ON u.ward_id = w.ward_id
JOIN districts d ON w.district_id = d.district_id
JOIN cities ci ON d.city_id = ci.city_id
WHERE p.status = 1
GROUP BY ci.city_name, d.district_id, d.district_name
ORDER BY tong_chi_tieu DESC LIMIT 20;"""
},
{
"question": "Tệp khách hàng tiềm năng",
"sql": """SELECT u.gender AS gioi_tinh,
CASE
WHEN EXTRACT(YEAR FROM CURRENT_DATE) - EXTRACT(YEAR FROM u.day_of_birth) < 25 THEN 'Dưới 25 tuổi'
WHEN EXTRACT(YEAR FROM CURRENT_DATE) - EXTRACT(YEAR FROM u.day_of_birth) < 35 THEN '25-34 tuổi'
WHEN EXTRACT(YEAR FROM CURRENT_DATE) - EXTRACT(YEAR FROM u.day_of_birth) < 45 THEN '35-44 tuổi'
WHEN EXTRACT(YEAR FROM CURRENT_DATE) - EXTRACT(YEAR FROM u.day_of_birth) < 55 THEN '45-54 tuổi'
ELSE 'Trên 55 tuổi'
END AS nhom_tuoi,
COUNT(DISTINCT c.customer_id) AS so_khach_hang,
SUM(p.amount) AS tong_chi_tieu,
AVG(p.amount) AS chi_tieu_tb
FROM payments p
JOIN contract ct ON p.contract_id = ct.contract_id
JOIN customers c ON ct.customer_id = c.customer_id
JOIN users u ON c.customer_id = u.user_id
WHERE p.status = 1 AND u.gender IS NOT NULL AND u.day_of_birth IS NOT NULL
GROUP BY u.gender, nhom_tuoi
ORDER BY tong_chi_tieu DESC;"""
},
{
"question": "Phân tích chân dung khách hàng",
"sql": """SELECT u.gender AS gioi_tinh,
CASE
WHEN EXTRACT(YEAR FROM CURRENT_DATE) - EXTRACT(YEAR FROM u.day_of_birth) < 25 THEN 'Dưới 25 tuổi'
WHEN EXTRACT(YEAR FROM CURRENT_DATE) - EXTRACT(YEAR FROM u.day_of_birth) < 35 THEN '25-34 tuổi'
WHEN EXTRACT(YEAR FROM CURRENT_DATE) - EXTRACT(YEAR FROM u.day_of_birth) < 45 THEN '35-44 tuổi'
WHEN EXTRACT(YEAR FROM CURRENT_DATE) - EXTRACT(YEAR FROM u.day_of_birth) < 55 THEN '45-54 tuổi'
ELSE 'Trên 55 tuổi'
END AS nhom_tuoi,
ci.city_name AS thanh_pho,
COUNT(DISTINCT c.customer_id) AS so_khach_hang,
SUM(p.amount) AS tong_chi_tieu
FROM payments p
JOIN contract ct ON p.contract_id = ct.contract_id
JOIN customers c ON ct.customer_id = c.customer_id
JOIN users u ON c.customer_id = u.user_id
LEFT JOIN wards w ON u.ward_id = w.ward_id
LEFT JOIN districts d ON w.district_id = d.district_id
LEFT JOIN cities ci ON d.city_id = ci.city_id
WHERE p.status = 1
GROUP BY u.gender, nhom_tuoi, ci.city_name
ORDER BY tong_chi_tieu DESC LIMIT 20;"""
},
{
"question": "Khách hàng VIP cần quan tâm",
"sql": """SELECT CONCAT(u.last_name, ' ', u.first_name) AS customer_name,
u.email, u.phone_number, u.gender AS gioi_tinh,
EXTRACT(YEAR FROM CURRENT_DATE) - EXTRACT(YEAR FROM u.day_of_birth) AS tuoi,
ci.city_name AS thanh_pho,
SUM(p.amount) AS tong_chi_tieu,