fix(search): 修复跨租户重复手机号查询报错

This commit is contained in:
yml
2026-11-29 20:07:57 +08:00
parent 2e0018b943
commit a1e6089aa5
15 changed files with 382 additions and 28 deletions
@@ -234,7 +234,7 @@ func (r *Repository) disbursementListBaseQuery(ctx context.Context, phoneKeyword
}
if phoneKeyword = strings.TrimSpace(phoneKeyword); isPhoneKeyword(phoneKeyword) {
withdrawal = withdrawal.Where("wr.user_id = (SELECT id FROM users WHERE phone = ?)", phoneKeyword)
withdrawal = withdrawal.Where("wr.user_id IN (SELECT id FROM users WHERE phone = ?)", phoneKeyword)
return db.Table("(?) AS d", withdrawal)
}
@@ -298,8 +298,8 @@ func (r *Repository) applyDisbursementFilters(db *gorm.DB, query DisbursementQue
if query.Keyword != "" {
keyword := strings.TrimSpace(query.Keyword)
if isPhoneKeyword(keyword) {
// 完整手机号只可能命中提现收款人,先经 users(phone) 唯一索引解析用户。
db = db.Where("d.source_type = ? AND d.user_id = (SELECT id FROM users WHERE phone = ?)", "withdrawal", keyword)
// 完整手机号只匹配提现收款人,先查询该手机号对应的所有租户和站点账号。
db = db.Where("d.source_type = ? AND d.user_id IN (SELECT id FROM users WHERE phone = ?)", "withdrawal", keyword)
} else {
like := "%" + keyword + "%"
db = db.Where(`(d.business_no LIKE ? OR d.payee_name LIKE ? OR d.payee_phone LIKE ?
@@ -0,0 +1,65 @@
package adminfinance
import (
"fmt"
"testing"
"hfb_sys/backend/internal/database"
"hfb_sys/backend/internal/model"
)
func TestDisbursementPhoneFilterWithDuplicateAccounts(t *testing.T) {
db := database.NewTestDB()
const phone = "13812345678"
users := []model.User{
{TenantID: 101, Phone: phone},
{TenantID: 202, Phone: phone},
{TenantID: 101, DistributionSiteID: 7, Phone: phone},
{TenantID: 101, Phone: "13912345678"},
}
if err := db.Create(&users).Error; err != nil {
t.Fatal(err)
}
withdrawals := make([]model.WithdrawalRequest, len(users))
for i, user := range users {
withdrawals[i] = model.WithdrawalRequest{
WithdrawNo: fmt.Sprintf("W-PHONE-%d", i), UserID: user.ID, TenantID: user.TenantID,
DistributionSiteID: user.DistributionSiteID, AccountType: "alipay",
AccountName: "测试", AccountNo: "test", Status: "pending",
AmountCent: 100, ActualAmountCent: 100,
}
}
if err := db.Create(&withdrawals).Error; err != nil {
t.Fatal(err)
}
repo := NewRepository(db)
for _, tc := range []struct {
name string
tenantID uint64
keyword string
want map[uint64]bool
}{
{"tenant A excludes site wallets", 101, phone, map[uint64]bool{withdrawals[0].ID: true}},
{"tenant B", 202, phone, map[uint64]bool{withdrawals[1].ID: true}},
{"platform matches every account", 0, phone, map[uint64]bool{withdrawals[0].ID: true, withdrawals[1].ID: true, withdrawals[2].ID: true}},
{"unknown phone", 101, "13712345678", map[uint64]bool{}},
} {
t.Run(tc.name, func(t *testing.T) {
got, err := repo.Disbursements(financeTenantContext(tc.tenantID), DisbursementQuery{
Keyword: tc.keyword, Page: 1, PageSize: 20,
})
if err != nil {
t.Fatal(err)
}
if got.Total != int64(len(tc.want)) || len(got.Items) != len(tc.want) ||
got.Summary.ReviewPendingAmountCent != int64(len(tc.want))*100 {
t.Fatalf("unexpected phone-filtered result: %+v", got)
}
for _, item := range got.Items {
if item.SourceType != "withdrawal" || !tc.want[item.WithdrawalID] {
t.Fatalf("unexpected withdrawal: %+v", item)
}
}
})
}
}
@@ -0,0 +1,78 @@
package chat
import (
"fmt"
"testing"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
)
func TestAdminConversationPhoneFilterWithDuplicateAccounts(t *testing.T) {
db := setupAdminListTestDB(t)
const phone = "13812345678"
users := []model.User{
{TenantID: 101, Phone: phone}, {TenantID: 202, Phone: phone},
{TenantID: 303, Phone: phone}, {TenantID: 101, Phone: "13912345678"},
}
if err := db.Create(&users).Error; err != nil {
t.Fatal(err)
}
wantByTenant := map[uint64]map[uint64]bool{101: {}, 202: {}}
for i := 0; i < 5; i++ {
tenantID := uint64(101)
ownerID, renterID := users[0].ID, users[3].ID
if i == 1 {
ownerID, renterID = users[3].ID, users[2].ID
} else if i == 2 || i == 3 {
ownerID = users[1].ID
} else if i == 4 {
ownerID = users[3].ID
}
if i == 3 {
tenantID = 202
}
listing := model.RentalListing{ListingNo: fmt.Sprintf("L-PHONE-%d", i),
OwnerID: ownerID, AccountID: uint64(i + 1), Status: "published"}
if err := db.Create(&listing).Error; err != nil {
t.Fatal(err)
}
conversation := model.ChatConversation{TenantID: tenantID,
Type: ConversationTypeListingGroup, ListingID: &listing.ID, Status: "active"}
if i != 2 {
order := model.RentalOrder{OrderNo: fmt.Sprintf("RO-PHONE-%d", i),
ListingID: listing.ID, AccountID: listing.AccountID, OwnerID: ownerID, RenterID: renterID,
BuyerTenantID: tenantID, Status: "renting"}
if err := db.Create(&order).Error; err != nil {
t.Fatal(err)
}
conversation.Type, conversation.OrderID = ConversationTypeOrderGroup, &order.ID
}
if err := db.Create(&conversation).Error; err != nil {
t.Fatal(err)
}
if i < 4 {
wantByTenant[tenantID][conversation.ID] = true
}
}
repo := NewRepository(db, nil, nil)
for tenantID, want := range wantByTenant {
t.Run(fmt.Sprint(tenantID), func(t *testing.T) {
ctx := tenancy.WithScope(t.Context(), tenancy.Scope{TenantID: tenantID})
got, err := repo.ListConversationsWithFilter(ctx, Principal{Type: "admin"},
1, 20, adminChatFilterAll, adminChatStageAll, phone)
if err != nil {
t.Fatal(err)
}
items := got.Items.([]ConversationDTO)
if got.Total != int64(len(want)) || len(items) != len(want) {
t.Fatalf("unexpected conversations: total=%d items=%+v", got.Total, items)
}
for _, item := range items {
if !want[item.ID] {
t.Fatalf("unexpected conversation: %+v", item)
}
}
})
}
}
+4 -4
View File
@@ -339,20 +339,20 @@ func (r *Repository) adminConversationBase(ctx context.Context, principal Princi
if keyword != "" {
upper := strings.ToUpper(keyword)
if isPhoneKeyword(keyword) {
// 先由 users(phone) 唯一索引解析用户,再分别从订单群和发布群定位会话。
// 手机号可对应多个租户或站点账号,先按手机号匹配用户集合,再分别从订单群和发布群定位会话。
// 保持原有语义:订单群匹配订单号主/租客,发布群仅匹配商品号主。
db = db.Joins(`JOIN (
SELECT c2.id AS conversation_id
FROM chat_conversations AS c2
JOIN rental_orders AS o2 ON o2.id = c2.order_id
WHERE o2.owner_id = (SELECT id FROM users WHERE phone = ?)
OR o2.renter_id = (SELECT id FROM users WHERE phone = ?)
WHERE o2.owner_id IN (SELECT id FROM users WHERE phone = ?)
OR o2.renter_id IN (SELECT id FROM users WHERE phone = ?)
UNION ALL
SELECT c2.id AS conversation_id
FROM chat_conversations AS c2
JOIN rental_listings AS l2 ON l2.id = c2.listing_id
WHERE c2.order_id IS NULL
AND l2.owner_id = (SELECT id FROM users WHERE phone = ?)
AND l2.owner_id IN (SELECT id FROM users WHERE phone = ?)
) AS matched_phone ON matched_phone.conversation_id = c.id`, keyword, keyword, keyword)
} else if strings.HasPrefix(upper, "RO") || strings.HasPrefix(upper, "ORD") {
db = db.Where("(explicit_lo.order_no = ? OR c.latest_order_no = ?)", keyword, keyword)
@@ -0,0 +1,53 @@
package dispute
import (
"fmt"
"testing"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
)
func TestAdminDisputePhoneFilterWithDuplicateAccounts(t *testing.T) {
db := setupDisputeTestDB(t)
const phone = "13812345678"
wantByTenant := map[uint64]map[uint64]bool{101: {}, 202: {}}
for i, tenantID := range []uint64{101, 101, 202, 101} {
owner, renter, order := createDisputeOrderFixture(t, db, model.RentalOrder{
OrderNo: fmt.Sprintf("RO-PHONE-%d", i), BuyerTenantID: tenantID,
SourceTenantID: 303, Status: "renting",
})
if i < 3 {
userID := owner.ID
if i == 1 {
userID = renter.ID
}
// 匹配账号可来自货源租户,不能把手机号子查询限定到买方租户。
if err := db.Model(&model.User{}).Where("id = ?", userID).
Updates(map[string]any{"tenant_id": 303 + i, "phone": phone}).Error; err != nil {
t.Fatal(err)
}
}
dispute := model.Dispute{OrderID: order.ID, InitiatorID: renter.ID,
InitiatorType: "user", TargetUserID: owner.ID, Type: "cannot_login", Status: "open"}
if err := db.Create(&dispute).Error; err != nil {
t.Fatal(err)
}
if i < 3 {
wantByTenant[tenantID][dispute.ID] = true
}
}
repo := NewRepository(db)
for tenantID, want := range wantByTenant {
t.Run(fmt.Sprint(tenantID), func(t *testing.T) {
ctx := tenancy.WithScope(t.Context(), tenancy.Scope{TenantID: tenantID})
got, err := repo.ListAdmin(ctx, AdminListQuery{Keyword: phone, Page: 1, PageSize: 1})
if err != nil {
t.Fatal(err)
}
if got.Total != int64(len(want)) || len(got.Items) != 1 || !want[got.Items[0].ID] {
t.Fatalf("phone filter returned unexpected disputes: %+v", got)
}
})
}
}
+2 -2
View File
@@ -151,9 +151,9 @@ func applyAdminListFilters(db *gorm.DB, query AdminListQuery) *gorm.DB {
if keyword := strings.TrimSpace(query.Keyword); keyword != "" {
upper := strings.ToUpper(keyword)
if isPhoneKeyword(keyword) {
// 先由 users(phone) 唯一索引解析用户,再走订单号主/租客索引。
// 手机号可对应多个租户或站点账号,匹配用户集合后再走订单号主/租客索引。
db = db.Where(
"(o.owner_id = (SELECT id FROM users WHERE phone = ?) OR o.renter_id = (SELECT id FROM users WHERE phone = ?))",
"(o.owner_id IN (SELECT id FROM users WHERE phone = ?) OR o.renter_id IN (SELECT id FROM users WHERE phone = ?))",
keyword,
keyword,
)
@@ -781,7 +781,7 @@ func TestApplyAdminListFiltersSmartRouting(t *testing.T) {
{
name: "11位手机号先解析用户再走订单角色索引",
query: AdminListQuery{Keyword: "13800138000"},
wantSQLFrag: "o.owner_id = (SELECT id FROM users WHERE phone = ?)",
wantSQLFrag: "o.owner_id IN (SELECT id FROM users WHERE phone = ?)",
},
{
name: "RO前缀订单号路由至rental_orders(order_no)",
@@ -0,0 +1,83 @@
package distribution
import (
"fmt"
"testing"
"hfb_sys/backend/internal/model"
)
func TestDistributionPhoneFiltersWithDuplicateAccounts(t *testing.T) {
db := distributionTestDB(t)
sites := []model.DistributionSite{
{SiteCode: "phone-a", SiteName: "A", Domain: "phone-a.test", Status: "active"},
{SiteCode: "phone-b", SiteName: "B", Domain: "phone-b.test", Status: "active"},
}
if err := db.Create(&sites).Error; err != nil {
t.Fatal(err)
}
const phone = "13812345678"
users := []model.User{
{Phone: phone}, {TenantID: 202, Phone: phone},
{DistributionSiteID: sites[1].ID, Phone: phone}, {Phone: "13912345678"},
}
if err := db.Create(&users).Error; err != nil {
t.Fatal(err)
}
wantOrders := map[uint64]map[uint64]bool{0: {}, sites[0].ID: {}, sites[1].ID: {}}
wantListings := map[uint64]map[uint64]bool{sites[0].ID: {}, sites[1].ID: {}}
for i, user := range users {
siteID := sites[0].ID
if i == 2 {
siteID = sites[1].ID
}
account := model.GameAccount{OwnerID: user.ID, Title: "手机号筛选测试"}
if err := db.Create(&account).Error; err != nil {
t.Fatal(err)
}
listing := model.RentalListing{ListingNo: fmt.Sprintf("L-PHONE-%d", i), AccountID: account.ID,
OwnerID: user.ID, DistributionSiteID: &siteID, Status: "published", ReviewStatus: "approved"}
if err := db.Create(&listing).Error; err != nil {
t.Fatal(err)
}
order := model.RentalOrder{OrderNo: fmt.Sprintf("RO-PHONE-%d", i), ListingID: listing.ID,
AccountID: account.ID, OwnerID: user.ID, RenterID: user.ID, Status: "renting",
DistributionSiteID: &siteID, DistributionMode: "site_self_sell"}
if err := db.Create(&order).Error; err != nil {
t.Fatal(err)
}
if i < 3 {
wantOrders[0][order.ID], wantOrders[siteID][order.ID] = true, true
wantListings[siteID][listing.ID] = true
}
}
repo := NewRepository(db)
for siteID, want := range wantOrders {
got, err := repo.ListOrders(t.Context(), DistributionOrderListQuery{SiteID: siteID, Keyword: phone, Page: 1, Size: 20})
if err != nil {
t.Fatal(err)
}
if got.Total != int64(len(want)) || len(got.Items) != len(want) {
t.Fatalf("site %d orders=%+v", siteID, got)
}
for _, item := range got.Items {
if !want[item.OrderID] {
t.Fatalf("unexpected order: %+v", item)
}
}
}
for siteID, want := range wantListings {
got, err := repo.ListReceivedListings(t.Context(), 0, siteID, ReceivedListingQuery{Keyword: phone, Page: 1, PageSize: 20})
if err != nil {
t.Fatal(err)
}
if got.Total != int64(len(want)) || len(got.Items) != len(want) {
t.Fatalf("site %d received listings=%+v", siteID, got)
}
for _, item := range got.Items {
if !want[item.ListingID] {
t.Fatalf("unexpected listing: %+v", item)
}
}
}
}
@@ -1151,7 +1151,7 @@ func (r *Repository) ListOrders(ctx context.Context, query DistributionOrderList
if strings.TrimSpace(query.Keyword) != "" {
keyword := strings.TrimSpace(query.Keyword)
if isPhoneKeyword(keyword) {
base = base.Where("ro.renter_id = (SELECT id FROM users WHERE phone = ?)", keyword)
base = base.Where("ro.renter_id IN (SELECT id FROM users WHERE phone = ?)", keyword)
} else {
kw := "%" + keyword + "%"
base = base.Where("(ro.order_no LIKE ? OR rl.listing_no LIKE ? OR ga.title LIKE ? OR u.phone LIKE ?)", kw, kw, kw, kw)
@@ -3055,7 +3055,7 @@ func (r *Repository) ListReceivedListings(ctx context.Context, adminID, siteID u
if q.Keyword != "" {
keyword := strings.TrimSpace(q.Keyword)
if isPhoneKeyword(keyword) {
base = base.Where("rl.owner_id = (SELECT id FROM users WHERE phone = ?)", keyword)
base = base.Where("rl.owner_id IN (SELECT id FROM users WHERE phone = ?)", keyword)
} else {
kw := "%" + keyword + "%"
base = base.Where("(rl.listing_no LIKE ? OR ga.title LIKE ? OR u.phone LIKE ? OR u.nickname LIKE ?)", kw, kw, kw, kw)
@@ -0,0 +1,67 @@
package invitation
import (
"fmt"
"testing"
"time"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
)
func TestAdminInvitationPhoneFiltersWithDuplicateAccounts(t *testing.T) {
db := setupTestDB(t)
const inviterPhone, inviteePhone = "13812345678", "13912345678"
for i, tenantID := range []uint64{101, 202, 101} {
siteID := uint64(0)
if i == 2 {
siteID = 7
}
users := []model.User{
{TenantID: tenantID, DistributionSiteID: siteID, Phone: inviterPhone},
{TenantID: tenantID, DistributionSiteID: siteID, Phone: inviteePhone},
}
if err := db.Create(&users).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&model.UserInvitation{InviterID: users[0].ID, InviteeID: users[1].ID,
DistributionSiteID: siteID, InviteCode: fmt.Sprintf("phone-%d", i), Status: StatusActive}).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&model.InvitationRebateLedger{OrderID: uint64(i + 1),
OrderNo: fmt.Sprintf("RO-PHONE-%d", i), Source: "rental_order",
InviterID: users[0].ID, InviteeID: users[1].ID, DistributionSiteID: siteID,
TradeRole: "buyer", Status: "settled", CycleStage: CycleFirstMonth,
RebateAmountCent: 100, SettledAt: time.Now()}).Error; err != nil {
t.Fatal(err)
}
}
repo := NewRepository(db)
for _, tenantID := range []uint64{0, 101, 202} {
t.Run(fmt.Sprint(tenantID), func(t *testing.T) {
ctx := tenancy.WithScope(t.Context(), tenancy.Scope{TenantID: tenantID})
want := map[uint64]int64{0: 3, 101: 2, 202: 1}[tenantID]
for _, query := range []AdminInvitationQuery{
{Phone: inviterPhone}, {Phone: inviteePhone},
{InviterPhone: inviterPhone}, {InviteePhone: inviteePhone},
} {
items, total, err := repo.ListAdminInvitations(ctx, query)
if err != nil || total != want || int64(len(items)) != want {
t.Fatalf("invitation phone filter %+v: total=%d items=%v err=%v", query, total, items, err)
}
}
for _, query := range []AdminRebateLedgerQuery{
{InviterPhone: inviterPhone}, {InviteePhone: inviteePhone},
} {
items, total, err := repo.ListAdminRebateLedgers(ctx, query)
if err != nil || total != want || int64(len(items)) != want {
t.Fatalf("ledger phone filter %+v: total=%d items=%v err=%v", query, total, items, err)
}
summary, err := repo.AdminRebateSummary(ctx, query)
if err != nil || summary.LedgerCount != want || summary.TotalRebateCent != want*100 {
t.Fatalf("phone-filtered rebate summary=%+v err=%v", summary, err)
}
}
})
}
}
@@ -919,7 +919,7 @@ func (r *Repository) ListAdminInvitations(ctx context.Context, query AdminInvita
if p := strings.TrimSpace(query.Phone); p != "" {
if isPhoneKeyword(p) {
db = db.Where(
"(ui.inviter_id = (SELECT id FROM users WHERE phone = ?) OR ui.invitee_id = (SELECT id FROM users WHERE phone = ?))",
"(ui.inviter_id IN (SELECT id FROM users WHERE phone = ?) OR ui.invitee_id IN (SELECT id FROM users WHERE phone = ?))",
p,
p,
)
@@ -930,14 +930,14 @@ func (r *Repository) ListAdminInvitations(ctx context.Context, query AdminInvita
}
if p := strings.TrimSpace(query.InviterPhone); p != "" {
if isPhoneKeyword(p) {
db = db.Where("ui.inviter_id = (SELECT id FROM users WHERE phone = ?)", p)
db = db.Where("ui.inviter_id IN (SELECT id FROM users WHERE phone = ?)", p)
} else {
db = db.Where("inviter.phone LIKE ?", "%"+p+"%")
}
}
if p := strings.TrimSpace(query.InviteePhone); p != "" {
if isPhoneKeyword(p) {
db = db.Where("ui.invitee_id = (SELECT id FROM users WHERE phone = ?)", p)
db = db.Where("ui.invitee_id IN (SELECT id FROM users WHERE phone = ?)", p)
} else {
db = db.Where("invitee.phone LIKE ?", "%"+p+"%")
}
@@ -1069,14 +1069,14 @@ func (r *Repository) adminRebateLedgerBase(ctx context.Context, query AdminRebat
}
if p := strings.TrimSpace(query.InviterPhone); p != "" {
if isPhoneKeyword(p) {
db = db.Where("irl.inviter_id = (SELECT id FROM users WHERE phone = ?)", p)
db = db.Where("irl.inviter_id IN (SELECT id FROM users WHERE phone = ?)", p)
} else {
db = db.Where("inviter.phone LIKE ?", "%"+p+"%")
}
}
if p := strings.TrimSpace(query.InviteePhone); p != "" {
if isPhoneKeyword(p) {
db = db.Where("irl.invitee_id = (SELECT id FROM users WHERE phone = ?)", p)
db = db.Where("irl.invitee_id IN (SELECT id FROM users WHERE phone = ?)", p)
} else {
db = db.Where("invitee.phone LIKE ?", "%"+p+"%")
}
@@ -23,8 +23,7 @@ export interface UpdateTenantSMSConfigPayload {
}
export async function fetchTenantSMSConfig() {
const { data } =
await apiClient.get<ApiResponse<TenantSMSConfig>>('/admin/tenant-sms-config')
const { data } = await apiClient.get<ApiResponse<TenantSMSConfig>>('/admin/tenant-sms-config')
return data.data
}
@@ -128,7 +128,11 @@ async function handleSave() {
type="password"
autocomplete="new-password"
show-password
:placeholder="config.has_secret ? `已保存 ${config.masked_secret},留空保持不变` : '请输入 AccessKey Secret'"
:placeholder="
config.has_secret
? `已保存 ${config.masked_secret},留空保持不变`
: '请输入 AccessKey Secret'
"
/>
</el-form-item>
</div>
@@ -22,10 +22,7 @@ import {
updateSystemConfig,
type SystemConfig,
} from '@/features/admin/api/systemConfigs'
import {
fetchTenantSMSConfig,
type TenantSMSConfig,
} from '@/features/admin/api/tenantSmsConfig'
import { fetchTenantSMSConfig, type TenantSMSConfig } from '@/features/admin/api/tenantSmsConfig'
import { parseRenterGrowthConfig } from '@/features/admin/api/renterGrowth'
import {
parseSmsBusinessTemplatesConfig,
+12 -4
View File
@@ -59,7 +59,7 @@ require_pattern "backend/internal/modules/pickup/repository.go" "if pageSize > 1
# 智能意图路由与单表唯一索引直达防线(防止多表跨表 OR/LIKE 导致 MySQL 放弃索引而退化为全表扫描)
require_pattern "backend/internal/modules/order/queries.go" "o.order_no = ?" "订单列表订单号唯一索引直达"
require_pattern "backend/internal/modules/order/queries.go" "l.listing_no = ?" "订单列表商品号唯一索引直达"
require_pattern "backend/internal/modules/order/queries.go" "o.owner_id = (SELECT id FROM users WHERE phone = ?)" "订单列表手机号解析用户索引直达"
require_pattern "backend/internal/modules/order/queries.go" "o.owner_id IN (SELECT id FROM users WHERE phone = ?)" "订单列表手机号解析用户索引直达"
require_pattern "backend/internal/modules/order/queries.go" "LEFT JOIN wallet_ledger AS wl" "订单列表号主实际收入取最终钱包入账"
require_pattern "backend/internal/modules/order/queries.go" "offline_settlement_amount_cent" "订单列表平台代管收入取线下结算金额"
require_pattern "backend/internal/modules/order/queries.go" "page == 1 && len(rows) < pageSize" "订单列表首页面单扫描短路"
@@ -69,7 +69,7 @@ require_pattern "backend/internal/modules/pickup/repository.go" "pickup_owner.id
require_pattern "backend/internal/modules/pickup/repository.go" "page == 1 && len(rows) < pageSize" "提号列表首页面单扫描短路"
require_pattern "backend/internal/modules/dispute/query.go" "o.order_no = ?" "纠纷列表订单号唯一索引直达"
require_pattern "backend/internal/modules/dispute/query.go" "o.owner_id = (SELECT id FROM users WHERE phone = ?)" "纠纷列表手机号解析用户索引直达"
require_pattern "backend/internal/modules/dispute/query.go" "o.owner_id IN (SELECT id FROM users WHERE phone = ?)" "纠纷列表手机号解析用户索引直达"
require_pattern "backend/internal/modules/dispute/query.go" "page == 1 && len(rows) < pageSize" "纠纷列表首页面单扫描短路"
require_pattern "backend/internal/modules/adminuser/repository.go" "u.phone = ?" "用户管理手机号唯一索引直达"
@@ -81,8 +81,16 @@ require_pattern "backend/internal/modules/listing/query.go" "page == 1 && len(ro
require_pattern "backend/internal/modules/chat/support.go" "l.listing_no = ?" "客服会话商品号唯一索引直达"
require_pattern "backend/internal/modules/chat/support.go" "matched_phone.conversation_id = c.id" "客服会话手机号经订单角色索引直达"
require_pattern "backend/internal/modules/adminfinance/disbursement_list.go" "d.source_type = ? AND d.user_id = (SELECT id FROM users WHERE phone = ?)" "出款列表手机号解析用户索引直达"
require_pattern "backend/internal/modules/adminfinance/disbursement_list.go" "wr.user_id = (SELECT id FROM users WHERE phone = ?)" "出款列表手机号在联合前裁剪来源"
require_pattern "backend/internal/modules/adminfinance/disbursement_list.go" "d.source_type = ? AND d.user_id IN (SELECT id FROM users WHERE phone = ?)" "出款列表手机号解析用户索引直达"
require_pattern "backend/internal/modules/adminfinance/disbursement_list.go" "wr.user_id IN (SELECT id FROM users WHERE phone = ?)" "出款列表手机号在联合前裁剪来源"
# 手机号仅在租户和站点内唯一,标量子查询遇到多个账号会触发 MySQL 1242。
# 扫描所有业务模块,避免新增入口绕过上面的关键查询检查。
if scalar_phone_queries="$(grep -RniE --include='*.go' --exclude='*_test.go' \
'=[[:space:]]*\([[:space:]]*SELECT[[:space:]]+id[[:space:]]+FROM[[:space:]]+users[[:space:]]+WHERE[[:space:]]+phone[[:space:]]*=' \
"${ROOT_DIR}/backend/internal/modules")"; then
failures+=("手机号查询禁止使用标量子查询,应匹配用户集合: ${scalar_phone_queries}")
fi
# 禁止核心列表重新引入跨表 6~10 路全扫描反模式
forbid_pattern "backend/internal/modules/dispute/query.go" "o.order_no LIKE ? OR l.listing_no LIKE ? OR a.title LIKE ? OR owner.phone LIKE ? OR renter.phone LIKE ? OR d.id = ?" "纠纷列表禁止6表无意图全表扫描"