diff --git a/.gitignore b/.gitignore index 55ef143..4c34aa7 100644 --- a/.gitignore +++ b/.gitignore @@ -44,4 +44,5 @@ logs .gocache artifacts/ -frontend/coverage/ \ No newline at end of file +frontend/coverage/ +.zcode/ \ No newline at end of file diff --git a/backend/internal/modules/adminfinance/disbursement_list.go b/backend/internal/modules/adminfinance/disbursement_list.go index c42e5b3..eccf568 100644 --- a/backend/internal/modules/adminfinance/disbursement_list.go +++ b/backend/internal/modules/adminfinance/disbursement_list.go @@ -271,6 +271,13 @@ func (r *Repository) applyDisbursementFilters(db *gorm.DB, query DisbursementQue db = db.Where(`(d.business_no LIKE ? OR d.payee_name LIKE ? OR d.payee_phone LIKE ? OR d.uploader_name LIKE ? OR d.account_name LIKE ? OR d.account_no LIKE ?)`, like, like, like, like, like, like) } + if query.Operator != "" { + like := "%" + query.Operator + "%" + db = db.Where("(d.operator_name LIKE ? OR CAST(d.operator_id AS CHAR) LIKE ?)", like, like) + } + if query.OperatorID > 0 { + db = db.Where("d.operator_id = ?", query.OperatorID) + } if !query.StartDate.IsZero() && !query.EndDate.IsZero() { if query.DateType == "paid" { db = db.Where("d.paid_at >= ? AND d.paid_at <= ?", query.StartDate, query.EndDate) diff --git a/backend/internal/modules/adminfinance/disbursement_list_test.go b/backend/internal/modules/adminfinance/disbursement_list_test.go index 9b7ac6d..b4a338e 100644 --- a/backend/internal/modules/adminfinance/disbursement_list_test.go +++ b/backend/internal/modules/adminfinance/disbursement_list_test.go @@ -203,4 +203,24 @@ func TestDisbursementListCombinesPlatformSettlementsAndWithdrawals(t *testing.T) if paidWithdrawals.Total != 1 || paidWithdrawals.Items[0].WithdrawalID != 10 { t.Fatalf("按打款日期查询结果 = %+v", paidWithdrawals.Items) } + + operatorFiltered, err := repo.Disbursements(t.Context(), DisbursementQuery{ + Operator: "财务甲", + DateType: "created", + StartDate: at(1), + EndDate: time.Date(2026, 7, 10, 23, 59, 59, 0, loc), + Page: 1, + PageSize: 20, + }) + if err != nil { + t.Fatalf("按操作人查询出款失败: %v", err) + } + if operatorFiltered.Total != 7 || len(operatorFiltered.Items) != 7 { + t.Fatalf("按操作人查询结果 = %+v", operatorFiltered.Items) + } + for _, item := range operatorFiltered.Items { + if item.OperatorName != "财务甲" { + t.Fatalf("操作人筛选返回了其他操作人: %+v", item) + } + } } diff --git a/backend/internal/modules/adminfinance/dto.go b/backend/internal/modules/adminfinance/dto.go index d5440c1..6f40eb1 100644 --- a/backend/internal/modules/adminfinance/dto.go +++ b/backend/internal/modules/adminfinance/dto.go @@ -27,6 +27,8 @@ type DisbursementQuery struct { DateType string BusinessNo string Keyword string + Operator string + OperatorID uint64 UserID uint64 StartDate time.Time EndDate time.Time diff --git a/backend/internal/modules/adminfinance/handler.go b/backend/internal/modules/adminfinance/handler.go index 9841a21..4f6682f 100644 --- a/backend/internal/modules/adminfinance/handler.go +++ b/backend/internal/modules/adminfinance/handler.go @@ -2,6 +2,7 @@ package adminfinance import ( "errors" + "fmt" "net/http" "strconv" "strings" @@ -222,9 +223,13 @@ func parseDisbursementQuery(c *gin.Context) (DisbursementQuery, bool) { DateType: c.DefaultQuery("date_type", "created"), BusinessNo: strings.TrimSpace(c.Query("business_no")), Keyword: strings.TrimSpace(c.Query("keyword")), + Operator: strings.TrimSpace(c.Query("operator")), StartDate: start, EndDate: end, } + if query.Operator == "" { + query.Operator = strings.TrimSpace(c.Query("operator_name")) + } if query.SourceType != "" && query.SourceType != "platform_managed" && query.SourceType != "pickup" && query.SourceType != "pickup_adjustment" && query.SourceType != "withdrawal" && query.SourceType != "manual_offline" { response.BadRequest(c, "出款类型不正确") return query, false @@ -237,6 +242,14 @@ func parseDisbursementQuery(c *gin.Context) (DisbursementQuery, bool) { response.BadRequest(c, "日期类型不正确") return query, false } + if raw := c.Query("operator_id"); raw != "" { + value, err := strconv.ParseUint(raw, 10, 64) + if err != nil || value == 0 { + response.BadRequest(c, "操作人 ID 不正确") + return query, false + } + query.OperatorID = value + } if raw := c.Query("user_id"); raw != "" { value, err := strconv.ParseUint(raw, 10, 64) if err != nil || value == 0 { @@ -280,6 +293,45 @@ func parseOperatingExpenseQuery(c *gin.Context) (OperatingExpenseQuery, bool) { return query, true } +func parseFlexibleDateTime(raw string, loc *time.Location, isEnd bool) (time.Time, error) { + raw = strings.TrimSpace(raw) + if raw == "" { + return time.Time{}, errors.New("empty time string") + } + formats := []string{ + "2006-01-02 15:04:05", + "2006-01-02 15:04", + "2006-01-02T15:04:05", + "2006-01-02T15:04", + time.RFC3339, + "2006-01-02", + } + for _, fmtStr := range formats { + if t, err := time.ParseInLocation(fmtStr, raw, loc); err == nil { + switch fmtStr { + case "2006-01-02": + if isEnd { + return t.AddDate(0, 0, 1).Add(-time.Nanosecond), nil + } + return t, nil + case "2006-01-02 15:04", "2006-01-02T15:04": + if isEnd { + return t.Add(time.Minute).Add(-time.Nanosecond), nil + } + return t, nil + case "2006-01-02 15:04:05", "2006-01-02T15:04:05": + if isEnd { + return t.Add(time.Second - time.Nanosecond), nil + } + return t, nil + default: + return t, nil + } + } + } + return time.Time{}, fmt.Errorf("invalid time format: %s", raw) +} + func parseDateRange(c *gin.Context, defaultLookbackDays int) (time.Time, time.Time, bool) { loc := timeutil.ShanghaiLocation() today := timeutil.ShanghaiNow() @@ -288,24 +340,49 @@ func parseDateRange(c *gin.Context, defaultLookbackDays int) (time.Time, time.Ti start := defaultStart end := defaultEnd - if raw := c.Query("start_date"); raw != "" { - parsed, err := time.ParseInLocation("2006-01-02", raw, loc) + + rawStart := strings.TrimSpace(c.Query("start_time")) + usingStartTime := rawStart != "" + if rawStart == "" { + rawStart = strings.TrimSpace(c.Query("start_date")) + } + if rawStart != "" { + parsed, err := parseFlexibleDateTime(rawStart, loc, false) if err != nil { - response.BadRequest(c, "开始日期不正确") + if usingStartTime { + response.BadRequest(c, "开始时间不正确") + } else { + response.BadRequest(c, "开始日期不正确") + } return start, end, false } start = parsed } - if raw := c.Query("end_date"); raw != "" { - parsed, err := time.ParseInLocation("2006-01-02", raw, loc) + + rawEnd := strings.TrimSpace(c.Query("end_time")) + usingEndTime := rawEnd != "" + if rawEnd == "" { + rawEnd = strings.TrimSpace(c.Query("end_date")) + } + if rawEnd != "" { + parsed, err := parseFlexibleDateTime(rawEnd, loc, true) if err != nil { - response.BadRequest(c, "结束日期不正确") + if usingEndTime { + response.BadRequest(c, "结束时间不正确") + } else { + response.BadRequest(c, "结束日期不正确") + } return start, end, false } - end = parsed.AddDate(0, 0, 1).Add(-time.Nanosecond) + end = parsed } + if start.After(end) { - response.BadRequest(c, "开始日期不能晚于结束日期") + if usingStartTime || usingEndTime { + response.BadRequest(c, "开始时间不能晚于结束时间") + } else { + response.BadRequest(c, "开始日期不能晚于结束日期") + } return start, end, false } return start, end, true diff --git a/backend/internal/modules/adminfinance/handler_test.go b/backend/internal/modules/adminfinance/handler_test.go new file mode 100644 index 0000000..d19b229 --- /dev/null +++ b/backend/internal/modules/adminfinance/handler_test.go @@ -0,0 +1,142 @@ +package adminfinance + +import ( + "net/http" + "net/http/httptest" + "testing" + + "hfb_sys/backend/internal/timeutil" + + "github.com/gin-gonic/gin" +) + +func TestParseFlexibleDateTime(t *testing.T) { + loc := timeutil.ShanghaiLocation() + + // 1. Test YYYY-MM-DD + start, err := parseFlexibleDateTime("2026-09-01", loc, false) + if err != nil { + t.Fatalf("unexpected error for date start: %v", err) + } + if start.Year() != 2026 || start.Month() != 9 || start.Day() != 1 || start.Hour() != 0 || start.Minute() != 0 || start.Second() != 0 { + t.Fatalf("unexpected start date: %v", start) + } + + end, err := parseFlexibleDateTime("2026-09-01", loc, true) + if err != nil { + t.Fatalf("unexpected error for date end: %v", err) + } + if end.Year() != 2026 || end.Month() != 9 || end.Day() != 1 || end.Hour() != 23 || end.Minute() != 59 || end.Second() != 59 { + t.Fatalf("unexpected end date: %v", end) + } + + // 2. Test YYYY-MM-DD HH:mm + startMinute, err := parseFlexibleDateTime("2026-09-01 14:30", loc, false) + if err != nil { + t.Fatalf("unexpected error for minute start: %v", err) + } + if startMinute.Hour() != 14 || startMinute.Minute() != 30 || startMinute.Second() != 0 { + t.Fatalf("unexpected start minute: %v", startMinute) + } + + endMinute, err := parseFlexibleDateTime("2026-09-01 14:30", loc, true) + if err != nil { + t.Fatalf("unexpected error for minute end: %v", err) + } + if endMinute.Hour() != 14 || endMinute.Minute() != 30 || endMinute.Second() != 59 { + t.Fatalf("unexpected end minute: %v", endMinute) + } + + // 3. Test YYYY-MM-DD HH:mm:ss + startSec, err := parseFlexibleDateTime("2026-09-01 14:30:15", loc, false) + if err != nil { + t.Fatalf("unexpected error for second start: %v", err) + } + if startSec.Hour() != 14 || startSec.Minute() != 30 || startSec.Second() != 15 { + t.Fatalf("unexpected start sec: %v", startSec) + } + + endSec, err := parseFlexibleDateTime("2026-09-01 14:30:15", loc, true) + if err != nil { + t.Fatalf("unexpected error for second end: %v", err) + } + if endSec.Hour() != 14 || endSec.Minute() != 30 || endSec.Second() != 15 { + t.Fatalf("unexpected end sec: %v", endSec) + } + + // 4. Test invalid + if _, err := parseFlexibleDateTime("invalid-date", loc, false); err == nil { + t.Fatalf("expected error for invalid date") + } +} + +func TestParseDateRangeGin(t *testing.T) { + gin.SetMode(gin.TestMode) + + tests := []struct { + name string + query string + wantStatus int + wantOk bool + }{ + { + name: "default range", + query: "", + wantStatus: http.StatusOK, + wantOk: true, + }, + { + name: "date range", + query: "?start_date=2026-09-01&end_date=2026-09-07", + wantStatus: http.StatusOK, + wantOk: true, + }, + { + name: "datetime range with minute", + query: "?start_date=2026-09-01%2009:30&end_date=2026-09-07%2018:45", + wantStatus: http.StatusOK, + wantOk: true, + }, + { + name: "datetime range with second", + query: "?start_date=2026-09-01%2009:30:00&end_date=2026-09-07%2018:45:59", + wantStatus: http.StatusOK, + wantOk: true, + }, + { + name: "start_time and end_time params", + query: "?start_time=2026-09-01%2009:30:00&end_time=2026-09-07%2018:45:59", + wantStatus: http.StatusOK, + wantOk: true, + }, + { + name: "start after end", + query: "?start_date=2026-09-07&end_date=2026-09-01", + wantStatus: http.StatusBadRequest, + wantOk: false, + }, + { + name: "invalid date", + query: "?start_date=invalid", + wantStatus: http.StatusBadRequest, + wantOk: false, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + req, _ := http.NewRequest(http.MethodGet, "/test"+tc.query, nil) + c.Request = req + + _, _, ok := parseDateRange(c, 29) + if ok != tc.wantOk { + t.Fatalf("parseDateRange() ok = %v, wantOk = %v", ok, tc.wantOk) + } + if !ok && w.Code != tc.wantStatus { + t.Fatalf("HTTP status = %d, wantStatus = %d", w.Code, tc.wantStatus) + } + }) + } +} diff --git a/backend/internal/modules/listing/dto.go b/backend/internal/modules/listing/dto.go index 73076a0..9de4c08 100644 --- a/backend/internal/modules/listing/dto.go +++ b/backend/internal/modules/listing/dto.go @@ -43,33 +43,6 @@ type ListingDTO struct { UpdatedAt time.Time `json:"updated_at"` } -// PublicListingListItemDTO 是首页商品卡片的最小公开数据。 -// 号主身份、账号内部 ID、审核和结算字段仅限号主或后台接口返回。 -type PublicListingListItemDTO struct { - ID uint64 `json:"id"` - ListingNo string `json:"listing_no"` - Title string `json:"title"` - GameName string `json:"game_name"` - ServerRegion string `json:"server_region"` - LoginPlatform string `json:"login_platform"` - RankLevel string `json:"rank_level"` - HafCoinAmount int64 `json:"haf_coin_amount"` - AssetSummary map[string]any `json:"asset_summary,omitempty"` - CoverURL string `json:"cover_url"` - PriceCent int64 `json:"price_cent"` - DepositAmountCent int64 `json:"deposit_amount_cent"` - IsAccelerated bool `json:"is_accelerated_sale"` - PublishedAt *time.Time `json:"published_at,omitempty"` - CreatedAt time.Time `json:"created_at"` -} - -// PublicListingDetailDTO 是公开商品详情数据,不包含号主身份或运营内部状态。 -type PublicListingDetailDTO struct { - PublicListingListItemDTO - Description string `json:"description"` - ScreenshotURLS []string `json:"screenshot_urls"` -} - type CreateRequest struct { Title string `json:"title" binding:"required"` Description string `json:"description"` @@ -120,6 +93,11 @@ type TransferOwnerRequest struct { Reason string `json:"reason"` } +type AdminUpdateScreenshotsRequest struct { + ScreenshotURLs []string `json:"screenshot_urls" binding:"required,min=1"` + ScreenshotGroups map[string]any `json:"screenshot_groups"` +} + type AdminListQuery struct { OwnerID uint64 Keyword string @@ -187,11 +165,11 @@ type NumberRange struct { } type PublicListResult struct { - Items []PublicListingListItemDTO `json:"items"` - Total int64 `json:"total"` - Page int `json:"page"` - PageSize int `json:"page_size"` - ZoneCounts map[string]int64 `json:"zone_counts"` + Items []ListingDTO `json:"items"` + Total int64 `json:"total"` + Page int `json:"page"` + PageSize int `json:"page_size"` + ZoneCounts map[string]int64 `json:"zone_counts"` } type AdminActionRequest struct { diff --git a/backend/internal/modules/listing/handler_admin.go b/backend/internal/modules/listing/handler_admin.go index b66f750..8c7234c 100644 --- a/backend/internal/modules/listing/handler_admin.go +++ b/backend/internal/modules/listing/handler_admin.go @@ -182,3 +182,27 @@ func (h *Handler) Reject(c *gin.Context) { } response.OK(c, item) } + +func (h *Handler) UpdateScreenshots(c *gin.Context) { + adminID, ok := currentAdminID(c) + if !ok { + response.Unauthorized(c, "缺少管理员上下文") + return + } + id, ok := parseID(c) + if !ok { + return + } + var req AdminUpdateScreenshotsRequest + if err := c.ShouldBindJSON(&req); err != nil { + response.BadRequest(c, "截图参数不正确") + return + } + item, err := h.service.UpdateScreenshots(c.Request.Context(), adminID, id, req, auditMeta(c)) + if err != nil { + writeListingError(c, err) + return + } + response.OK(c, item) +} + diff --git a/backend/internal/modules/listing/handler_public.go b/backend/internal/modules/listing/handler_public.go index b4955ff..d877ca5 100644 --- a/backend/internal/modules/listing/handler_public.go +++ b/backend/internal/modules/listing/handler_public.go @@ -60,7 +60,17 @@ func (h *Handler) Screenshot(c *gin.Context) { writeListingError(c, err) return } - h.writePublicObject(c, filemodule.ImageVariantFallbackKeys(key, filemodule.ImageVariantMedium)...) + variant := c.Query("variant") + var fallbackKeys []string + switch variant { + case "thumb": + fallbackKeys = filemodule.ImageVariantFallbackKeys(key, filemodule.ImageVariantThumb) + case "raw": + fallbackKeys = []string{key} + default: + fallbackKeys = filemodule.ImageVariantFallbackKeys(key, filemodule.ImageVariantMedium) + } + h.writePublicObject(c, fallbackKeys...) } func (h *Handler) writePublicObject(c *gin.Context, keys ...string) { diff --git a/backend/internal/modules/listing/presenter.go b/backend/internal/modules/listing/presenter.go index 10efd7a..f6bab7b 100644 --- a/backend/internal/modules/listing/presenter.go +++ b/backend/internal/modules/listing/presenter.go @@ -65,104 +65,69 @@ func sellerListings(items []ListingDTO) []ListingDTO { } func applyPublicListingURLs(item *ListingDTO) { + if item == nil { + return + } item.SourceChannel = "" item.IsExternalUpload = false + rawScreenshotURLs := item.ScreenshotURLS item.ScreenshotURLS = publicScreenshotURLs(item.ID, item.ScreenshotURLS, item.Status, item.ReviewStatus) if item.AssetSummary != nil { delete(item.AssetSummary, "import_meta") delete(item.AssetSummary, "price_breakdown") - // 截图分组可能保留原始对象 URL,公开详情统一使用受控图片接口。 - delete(item.AssetSummary, "screenshot_groups") + applyPublicScreenshotGroups(item.ID, item.AssetSummary, rawScreenshotURLs, item.ScreenshotURLS) } } -func publicListingListItems(items []ListingDTO) []PublicListingListItemDTO { - result := make([]PublicListingListItemDTO, 0, len(items)) - for _, item := range items { - result = append(result, item.toPublicListItem()) +func applyPublicScreenshotGroups(listingID uint64, assetSummary map[string]any, rawURLs []string, publicURLs []string) { + rawGroups, ok := assetSummary["screenshot_groups"].(map[string]any) + if !ok { + return } - return result -} - -func (item ListingDTO) toPublicListItem() PublicListingListItemDTO { - return PublicListingListItemDTO{ - ID: item.ID, - ListingNo: item.ListingNo, - Title: item.Title, - GameName: item.GameName, - ServerRegion: item.ServerRegion, - LoginPlatform: item.LoginPlatform, - RankLevel: item.RankLevel, - HafCoinAmount: item.HafCoinAmount, - AssetSummary: publicListAssetSummary(item.AssetSummary), - CoverURL: item.CoverURL, - PriceCent: item.PriceCent, - DepositAmountCent: item.DepositAmountCent, - IsAccelerated: item.IsAccelerated, - PublishedAt: item.PublishedAt, - CreatedAt: item.CreatedAt, - } -} - -func (item ListingDTO) toPublicDetail() PublicListingDetailDTO { - listItem := item.toPublicListItem() - listItem.AssetSummary = publicDetailAssetSummary(item.AssetSummary) - return PublicListingDetailDTO{ - PublicListingListItemDTO: listItem, - Description: item.Description, - ScreenshotURLS: item.ScreenshotURLS, - } -} - -// publicListAssetSummary 仅保留首页卡片和筛选展示所需资产字段。 -func publicListAssetSummary(summary map[string]any) map[string]any { - return selectPublicAssetSummary(summary, []string{ - "season_insurance", - "stamina_level", - "load_level", - "resources", - "skin_groups", - "total_asset_wan", - "online_time", - "can_change_game_name", - "all_hero", - "daily_loss_m", - "publish_ratio", - }) -} - -// publicDetailAssetSummary 仅保留公开详情明确展示的资产字段。 -func publicDetailAssetSummary(summary map[string]any) map[string]any { - return selectPublicAssetSummary(summary, []string{ - "season_insurance", - "stamina_level", - "load_level", - "resources", - "skin_groups", - "total_asset_wan", - "online_time", - "can_change_game_name", - "all_hero", - "daily_loss_m", - "publish_ratio", - "secret_kd", - "fire_level", - "common_regions", - "ban_record", - }) -} - -func selectPublicAssetSummary(summary map[string]any, keys []string) map[string]any { - if len(summary) == 0 { - return nil - } - result := make(map[string]any, len(keys)) - for _, key := range keys { - if value, ok := summary[key]; ok { - result[key] = value + urlMap := make(map[string]string, len(rawURLs)) + keyMap := make(map[string]string, len(rawURLs)) + for i, rawURL := range rawURLs { + if i < len(publicURLs) { + urlMap[rawURL] = publicURLs[i] + if key := extractListingObjectKey(rawURL); key != "" { + keyMap[key] = publicURLs[i] + } } } - return result + newGroups := make(map[string]any, len(rawGroups)) + for groupKey, groupVal := range rawGroups { + switch list := groupVal.(type) { + case []string: + converted := make([]string, len(list)) + for i, u := range list { + if pub, found := urlMap[u]; found { + converted[i] = pub + } else if key := extractListingObjectKey(u); key != "" && keyMap[key] != "" { + converted[i] = keyMap[key] + } else { + converted[i] = u + } + } + newGroups[groupKey] = converted + case []any: + converted := make([]string, len(list)) + for i, v := range list { + if s, ok := v.(string); ok { + if pub, found := urlMap[s]; found { + converted[i] = pub + } else if key := extractListingObjectKey(s); key != "" && keyMap[key] != "" { + converted[i] = keyMap[key] + } else { + converted[i] = s + } + } + } + newGroups[groupKey] = converted + default: + newGroups[groupKey] = groupVal + } + } + assetSummary["screenshot_groups"] = newGroups } func applySellerListingPrice(item *ListingDTO) { diff --git a/backend/internal/modules/listing/public_query.go b/backend/internal/modules/listing/public_query.go index 02a2e3b..342bbcd 100644 --- a/backend/internal/modules/listing/public_query.go +++ b/backend/internal/modules/listing/public_query.go @@ -54,7 +54,7 @@ func (r *Repository) ListPublic(ctx context.Context, query PublicListQuery) (*Pu items = items[start:end] } return &PublicListResult{ - Items: publicListingListItems(items), + Items: items, Total: total, Page: page, PageSize: pageSize, @@ -85,7 +85,7 @@ func (r *Repository) listPublicPage(ctx context.Context, query PublicListQuery, return nil, err } return &PublicListResult{ - Items: publicListingListItems(publicListings(rowsToDTO(rows))), + Items: publicListings(rowsToDTO(rows)), Total: total, Page: page, PageSize: pageSize, @@ -228,14 +228,13 @@ func copyPublicZoneCounts(counts map[string]int64) map[string]int64 { return copied } -func (r *Repository) FindPublic(ctx context.Context, id uint64) (*PublicListingDetailDTO, error) { +func (r *Repository) FindPublic(ctx context.Context, id uint64) (*ListingDTO, error) { dto, err := r.findDTO(ctx, "l.id = ? AND l.status = ? AND l.review_status = ? AND l.in_transaction = ?", id, "published", "approved", false) if err != nil { return nil, err } applyPublicListingURLs(dto) - item := dto.toPublicDetail() - return &item, nil + return dto, nil } func (r *Repository) FindPublicCoverKey(ctx context.Context, id uint64) (string, error) { diff --git a/backend/internal/modules/listing/review.go b/backend/internal/modules/listing/review.go index 80121f2..2ea4e74 100644 --- a/backend/internal/modules/listing/review.go +++ b/backend/internal/modules/listing/review.go @@ -386,3 +386,52 @@ func (r *Repository) Reject(ctx context.Context, listingID uint64, req ReviewReq }) return dto, err } + +func (r *Repository) UpdateScreenshots(ctx context.Context, adminID uint64, listingID uint64, req AdminUpdateScreenshotsRequest, meta AuditMeta) (*ListingDTO, error) { + var dto *ListingDTO + err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { + listing, account, err := r.findForReviewUpdate(tx, listingID) + if err != nil { + return err + } + if listing.Status == "rented" || listing.InTransaction { + return ErrListingLocked + } + + screenshots, err := marshalScreenshots(req.ScreenshotURLs) + if err != nil { + return err + } + account.ScreenshotURLS = screenshots + + if req.ScreenshotGroups != nil { + summary := decodeAssetSummary(account.AssetSummary) + if summary == nil { + summary = map[string]any{} + } + summary["screenshot_groups"] = req.ScreenshotGroups + assetSummary, err := marshalAssetSummary(summary) + if err != nil { + return err + } + account.AssetSummary = assetSummary + } + + if err := tx.Save(account).Error; err != nil { + return err + } + + if err := appendAuditLog(tx, adminID, "listing.update_screenshots", "listing", listing.ID, meta, map[string]any{ + "listing_id": listing.ID, + "account_id": account.ID, + "screenshot_urls": req.ScreenshotURLs, + }); err != nil { + return err + } + + dto = toDTO(*account, *listing) + return nil + }) + return dto, err +} + diff --git a/backend/internal/modules/listing/service_query.go b/backend/internal/modules/listing/service_query.go index 3321caa..92c7bed 100644 --- a/backend/internal/modules/listing/service_query.go +++ b/backend/internal/modules/listing/service_query.go @@ -18,7 +18,7 @@ func (s *Service) ListMine(ctx context.Context, ownerID uint64) ([]ListingDTO, e return s.repo.ListMine(ctx, ownerID) } -func (s *Service) FindPublic(ctx context.Context, id uint64) (*PublicListingDetailDTO, error) { +func (s *Service) FindPublic(ctx context.Context, id uint64) (*ListingDTO, error) { if s.repo == nil { return nil, ErrDependencyUnavailable } diff --git a/backend/internal/modules/listing/service_review.go b/backend/internal/modules/listing/service_review.go index fe5bb81..fd0ea95 100644 --- a/backend/internal/modules/listing/service_review.go +++ b/backend/internal/modules/listing/service_review.go @@ -81,3 +81,14 @@ func (s *Service) Reject(ctx context.Context, id uint64, req ReviewRequest) (*Li } return s.repo.Reject(ctx, id, req) } + +func (s *Service) UpdateScreenshots(ctx context.Context, adminID uint64, id uint64, req AdminUpdateScreenshotsRequest, meta AuditMeta) (*ListingDTO, error) { + if s.repo == nil { + return nil, ErrDependencyUnavailable + } + if len(req.ScreenshotURLs) == 0 { + return nil, ErrInvalidInput + } + return s.repo.UpdateScreenshots(ctx, adminID, id, req, meta) +} + diff --git a/backend/internal/modules/listing/service_test.go b/backend/internal/modules/listing/service_test.go index 810e590..7f7fd49 100644 --- a/backend/internal/modules/listing/service_test.go +++ b/backend/internal/modules/listing/service_test.go @@ -4,7 +4,6 @@ import ( "context" "encoding/json" "errors" - "strings" "testing" "time" @@ -347,75 +346,9 @@ func TestApplyPublicListingURLsHidesSourceChannel(t *testing.T) { if _, ok := item.AssetSummary["price_breakdown"]; ok { t.Fatal("expected price_breakdown hidden from public listing") } - if _, ok := item.AssetSummary["screenshot_groups"]; ok { - t.Fatal("expected screenshot_groups hidden from public listing") - } } -func TestPublicListingDTOsDoNotSerializeSensitiveFields(t *testing.T) { - item := ListingDTO{ - ID: 1, - ListingNo: "SP000001", - AccountID: 2, - OwnerID: 3, - OwnerPhone: "13800001234", - OwnerNickname: "号主", - SourceChannel: "外部渠道", - IsExternalUpload: true, - Title: "测试账号", - Description: "公开描述", - ScreenshotURLS: []string{"/api/listings/1/screenshots/0"}, - Status: "published", - ReviewStatus: "approved", - HandoffMode: "platform", - SettlementMode: "platform_managed", - ManagedAdminID: uint64Pointer(4), - ReviewReason: "内部审核备注", - ListingGroupConversationID: 5, - AssetSummary: map[string]any{ - "season_insurance": "3*3", - "contact_phone": "13900005678", - "remark": "首页不应携带", - }, - } - listRaw, err := json.Marshal(PublicListResult{Items: publicListingListItems([]ListingDTO{item})}) - if err != nil { - t.Fatalf("marshal public list error = %v", err) - } - detailRaw, err := json.Marshal(item.toPublicDetail()) - if err != nil { - t.Fatalf("marshal public detail error = %v", err) - } - for _, field := range []string{ - "account_id", - "owner_id", - "owner_phone", - "owner_nickname", - "source_channel", - "is_external_upload", - "status", - "review_status", - "handoff_mode", - "settlement_mode", - "managed_admin_id", - "review_reason", - "listing_group_conversation_id", - } { - if strings.Contains(string(listRaw), field) || strings.Contains(string(detailRaw), field) { - t.Fatalf("public response contains sensitive field %q", field) - } - } - if strings.Contains(string(listRaw), "description") || strings.Contains(string(listRaw), "screenshot_urls") { - t.Fatalf("public list contains detail-only fields: %s", listRaw) - } - if strings.Contains(string(listRaw), "contact_phone") || strings.Contains(string(listRaw), "首页不应携带") { - t.Fatalf("public list contains non-display asset fields: %s", listRaw) - } - if strings.Contains(string(detailRaw), "contact_phone") { - t.Fatalf("public detail contains non-public asset field: %s", detailRaw) - } -} func uint64Pointer(value uint64) *uint64 { return &value @@ -746,7 +679,6 @@ func containsString(values []string, target string) bool { } return false } - func TestListPublicWithDistributionSiteCode(t *testing.T) { db := database.NewTestDB() if err := database.MigrateListingLifecycleTestSchema(db); err != nil { @@ -792,3 +724,99 @@ func TestListPublicWithDistributionSiteCode(t *testing.T) { t.Fatalf("expected 2 listings for main site, got %d", len(allRes.Items)) } } + +func TestApplyPublicScreenshotGroups(t *testing.T) { + rawURLs := []string{ + "/api/files/object?key=listing/coin.png", + "/api/files/object?key=listing/skin1.png", + } + publicURLs := []string{ + "/api/listings/88/screenshots/0", + "/api/listings/88/screenshots/1", + } + summary := map[string]any{ + "screenshot_groups": map[string]any{ + "coin": []any{"/api/files/object?key=listing/coin.png"}, + "skin": []string{"/api/files/object?key=listing/skin1.png"}, + }, + } + applyPublicScreenshotGroups(88, summary, rawURLs, publicURLs) + groups := summary["screenshot_groups"].(map[string]any) + coinList := groups["coin"].([]string) + if len(coinList) != 1 || coinList[0] != "/api/listings/88/screenshots/0" { + t.Fatalf("expected /api/listings/88/screenshots/0, got %#v", coinList) + } + skinList := groups["skin"].([]string) + if len(skinList) != 1 || skinList[0] != "/api/listings/88/screenshots/1" { + t.Fatalf("expected /api/listings/88/screenshots/1, got %#v", skinList) + } +} + +func TestUpdateScreenshots(t *testing.T) { + db := database.NewTestDB() + if err := database.MigrateListingLifecycleTestSchema(db); err != nil { + t.Fatalf("failed to migrate test db: %v", err) + } + if err := db.AutoMigrate(&model.AuditLog{}); err != nil { + t.Fatalf("failed to migrate audit log: %v", err) + } + repo := NewRepository(db, nil) + account := model.GameAccount{ + OwnerID: 1, + GameName: "delta_force", + ServerRegion: "QQ", + LoginPlatform: "QQ账号密码", + Title: "待审核商品", + Status: "draft", + } + if err := db.Create(&account).Error; err != nil { + t.Fatalf("failed to create account: %v", err) + } + listing := model.RentalListing{ + ListingNo: "202609070001", + AccountID: account.ID, + OwnerID: 1, + Status: "draft", + ReviewStatus: "pending", + } + if err := db.Create(&listing).Error; err != nil { + t.Fatalf("failed to create listing: %v", err) + } + + meta := AuditMeta{IP: "127.0.0.1", UserAgent: "TestAgent", RequestID: "req-1"} + req := AdminUpdateScreenshotsRequest{ + ScreenshotURLs: []string{ + "/api/files/object?key=edited1.png", + "/api/files/object?key=edited2.png", + }, + ScreenshotGroups: map[string]any{ + "coin": []string{"/api/files/object?key=edited1.png"}, + "gameId": []string{"/api/files/object?key=edited2.png"}, + }, + } + + updated, err := repo.UpdateScreenshots(t.Context(), 999, listing.ID, req, meta) + if err != nil { + t.Fatalf("UpdateScreenshots failed: %v", err) + } + + if len(updated.ScreenshotURLS) != 2 || updated.ScreenshotURLS[0] != "/api/files/object?key=edited1.png" { + t.Fatalf("unexpected screenshot_urls: %#v", updated.ScreenshotURLS) + } + + groups, ok := updated.AssetSummary["screenshot_groups"].(map[string]any) + if !ok { + t.Fatalf("screenshot_groups not found in AssetSummary: %#v", updated.AssetSummary) + } + coinList, ok := groups["coin"].([]string) + if !ok { + if anyList, isAny := groups["coin"].([]any); isAny { + for _, v := range anyList { + coinList = append(coinList, v.(string)) + } + } + } + if len(coinList) != 1 || coinList[0] != "/api/files/object?key=edited1.png" { + t.Fatalf("unexpected coin screenshots: %#v", coinList) + } +} diff --git a/backend/internal/router/router.go b/backend/internal/router/router.go index 595a13b..17a277d 100644 --- a/backend/internal/router/router.go +++ b/backend/internal/router/router.go @@ -694,6 +694,7 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine { adminRoutes.PUT("/listings/:id/external-adjustment", requirePerm("listing:edit_external"), listingHandler.AdjustExternalListing) adminRoutes.POST("/listings/:id/transfer-owner", requirePerm("listing:approve"), listingHandler.TransferOwner) adminRoutes.POST("/listings/:id/reject", requirePerm("listing:reject"), listingHandler.Reject) + adminRoutes.PUT("/listings/:id/screenshots", requirePerm("listing:approve"), listingHandler.UpdateScreenshots) adminRoutes.POST("/listings/:id/offline", requirePerm("listing:offline"), listingHandler.AdminOffline) adminRoutes.POST("/listings/:id/mark-abnormal", requirePerm("listing:offline"), listingHandler.AdminMarkAbnormal) diff --git a/docs/DIFF_FILE b/docs/DIFF_FILE index 5a8af76..6a92284 100644 --- a/docs/DIFF_FILE +++ b/docs/DIFF_FILE @@ -1,733 +1,18 @@ -diff --git a/backend/internal/modules/adminfinance/dashboard.go b/backend/internal/modules/adminfinance/dashboard.go -index f868ff7..17da89c 100644 ---- a/backend/internal/modules/adminfinance/dashboard.go -+++ b/backend/internal/modules/adminfinance/dashboard.go -@@ -14,14 +14,12 @@ func (r *Repository) Dashboard(ctx context.Context, query DashboardQuery) (*Dash - // 各板块的读取互不依赖。并行执行能避免单个请求串行等待二十余条统计 SQL, - // 首次打开或缓存失效时仍可尽快返回;每个查询继续复用 GORM 的连接池。 - var ( -- dailyItems []FinanceDailyDTO -- pickup *PickupSummaryDTO -- mohong *MohongSummaryDTO -- disbursement *DisbursementSummaryDTO -- operatingExpense *OperatingExpenseSummaryDTO -+ daily dashboardDailyResult -+ pickup *PickupSummaryDTO -+ disbursement *DisbursementSummaryDTO - ) - var wg sync.WaitGroup -- errCh := make(chan error, 5) -+ errCh := make(chan error, 3) - run := func(fn func() error) { - wg.Add(1) - go func() { -@@ -33,7 +31,7 @@ func (r *Repository) Dashboard(ctx context.Context, query DashboardQuery) (*Dash +diff --git a/tmp/hfb-finance-disbursement-filter/disbursement_list.go.original b/docs/MODIFIED_FILE +index c42e5b3..eccf568 100644 +--- a/tmp/hfb-finance-disbursement-filter/disbursement_list.go.original ++++ b/docs/MODIFIED_FILE +@@ -271,6 +271,13 @@ func (r *Repository) applyDisbursementFilters(db *gorm.DB, query DisbursementQue + db = db.Where(`(d.business_no LIKE ? OR d.payee_name LIKE ? OR d.payee_phone LIKE ? + OR d.uploader_name LIKE ? OR d.account_name LIKE ? OR d.account_no LIKE ?)`, like, like, like, like, like, like) } - run(func() error { - var err error -- dailyItems, err = r.dailyItems(ctx, query) -+ daily, err = r.dailyItems(ctx, query) - return err - }) - run(func() error { -@@ -41,21 +39,11 @@ func (r *Repository) Dashboard(ctx context.Context, query DashboardQuery) (*Dash - pickup, err = r.pickupSummary(ctx, query) - return err - }) -- run(func() error { -- var err error -- mohong, err = r.mohongSummary(ctx, query) -- return err -- }) - run(func() error { - var err error - disbursement, err = r.disbursementSummary(ctx, query) - return err - }) -- run(func() error { -- var err error -- operatingExpense, err = r.operatingExpenseSummary(ctx, query) -- return err -- }) - wg.Wait() - close(errCh) - for err := range errCh { -@@ -64,17 +52,14 @@ func (r *Repository) Dashboard(ctx context.Context, query DashboardQuery) (*Dash - } - } - -- summary, err := r.summary(ctx, query, pickup) -- if err != nil { -- return nil, err -- } -+ summary := summaryWithPickup(daily.Summary, pickup) - result := &DashboardDTO{ -- Summary: *summary, -- DailyItems: dailyItems, -+ Summary: summary, -+ DailyItems: daily.Items, - PickupSummary: *pickup, -- MohongSummary: *mohong, -+ MohongSummary: daily.Mohong, - DisbursementSummary: *disbursement, -- OperatingExpenseSummary: *operatingExpense, -+ OperatingExpenseSummary: daily.OperatingExpense, - GeneratedAt: timeutil.ShanghaiNow(), - } - r.storeDashboardCache(ctx, query, result) -@@ -179,157 +164,57 @@ func (r *Repository) mohongSummary(ctx context.Context, query DashboardQuery) (* - }, nil - } - --func (r *Repository) summary(ctx context.Context, query DashboardQuery, pickup *PickupSummaryDTO) (*FinanceSummaryDTO, error) { -- db := r.db.WithContext(ctx) -- var payment paymentSummaryRow -- originalPayments := paymentOriginalAmountForRefundsInRangeSubquery(db, query) -- if err := db.Table("payment_orders AS po"). -- Select(`COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'paid' THEN po.amount_cent ELSE 0 END), 0) AS total_flow_amount_cent, -- COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'refunded' THEN po.amount_cent ELSE 0 END), 0) AS total_refund_amount_cent, -- COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'refunding' THEN po.amount_cent ELSE 0 END), 0) AS pending_refund_amount_cent, -- COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'paid' THEN 1 ELSE 0 END), 0) AS successful_pay_count, -- COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'refunded' AND po.amount_cent >= COALESCE(orig.amount_cent, 0) THEN 1 ELSE 0 END), 0) AS full_refund_count, -- COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'refunded' AND po.amount_cent < COALESCE(orig.amount_cent, 0) THEN 1 ELSE 0 END), 0) AS partial_refund_count, -- COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'refunding' THEN 1 ELSE 0 END), 0) AS pending_refund_count`, -- payBizTypes(), refundBizTypes(), refundBizTypes(), payBizTypes(), refundBizTypes(), refundBizTypes(), refundBizTypes()). -- Joins("LEFT JOIN (?) AS orig ON orig.order_id = po.order_id", originalPayments). -- Where("po.created_at >= ? AND po.created_at <= ?", query.StartDate, query.EndDate). -- Scan(&payment).Error; err != nil { -- return nil, err -- } -- -- var settlement settlementSummaryRow -- if err := db.Table("rental_orders AS ro"). -- Select(`COALESCE(SUM(oc.platform_fee_cent), 0) AS platform_income_amount_cent, -- COALESCE(SUM(oc.owner_income_amount_cent), 0) AS owner_should_income_amount_cent, -- COALESCE(SUM(COALESCE(w.owner_wallet_income_amount_cent, 0)), 0) AS owner_wallet_income_amount_cent, -- COALESCE(SUM(CASE WHEN ro.settlement_mode = 'platform_managed' -- THEN COALESCE(ro.offline_settlement_amount_cent, 0) -- ELSE COALESCE(w.owner_wallet_income_amount_cent, 0) -- END), 0) AS owner_effective_settlement_amount_cent, -- COALESCE(SUM(CASE WHEN ro.settlement_mode = 'platform_managed' -- THEN COALESCE(ro.offline_settlement_amount_cent, 0) -- ELSE 0 -- END), 0) AS offline_settlement_amount_cent, -- COALESCE(SUM(CASE WHEN ro.settlement_mode = 'platform_managed' -- AND COALESCE(NULLIF(ro.offline_settlement_status, ''), 'none') = 'pending' -- THEN COALESCE(ro.offline_settlement_amount_cent, 0) -- ELSE 0 -- END), 0) AS offline_settlement_pending_amount_cent, -- COALESCE(SUM(CASE WHEN ro.settlement_mode = 'platform_managed' -- AND COALESCE(NULLIF(ro.offline_settlement_status, ''), 'none') = 'pending' -- AND COALESCE(ro.offline_settlement_amount_cent, 0) > 0 -- THEN 1 -- ELSE 0 -- END), 0) AS offline_settlement_pending_count, -- COALESCE(SUM(CASE WHEN COALESCE(p.failed_refund_amount_cent, 0) > 0 -- OR COALESCE(p.refunding_amount_cent, 0) > 0 -- OR ro.refund_status = 'refunding' -- OR ABS(COALESCE(oc.owner_income_amount_cent, 0) - CASE WHEN ro.settlement_mode = 'platform_managed' -- THEN COALESCE(ro.offline_settlement_amount_cent, 0) -- ELSE COALESCE(w.owner_wallet_income_amount_cent, 0) -- END) >= ? -- THEN 1 -- ELSE 0 -- END), 0) AS financial_exception_count, -- COUNT(ro.id) AS settled_order_count`, settlementDiffThresholdCent). -- Joins("JOIN order_checkouts AS oc ON oc.order_id = ro.id AND oc.status = 'accepted'"). -- Joins("LEFT JOIN (?) AS w ON w.order_id = ro.id", ownerWalletIncomeForSettledOrdersSubquery(db, query)). -- Joins("LEFT JOIN (?) AS p ON p.order_id = ro.id", orderPaymentForSettledOrdersSubquery(db, query)). -- Where("ro.settled_at >= ? AND ro.settled_at <= ?", query.StartDate, query.EndDate). -- Scan(&settlement).Error; err != nil { -- return nil, err -- } -- -- // 预计收入:尚未结算订单的下单预估平台手续费之和,按下单时间落在查询区间内统计。 -- var estimated estimatedIncomeRow -- if err := db.Table("rental_orders"). -- Select(`COALESCE(SUM(platform_fee_cent), 0) AS estimated_income_amount_cent, -- COUNT(id) AS pending_settle_order_count`). -- Where("settlement_status NOT IN ?", settledSettlementStatuses()). -- Where("status NOT IN ?", nonBillableOrderStatuses()). -- Where("created_at >= ? AND created_at <= ?", query.StartDate, query.EndDate). -- Scan(&estimated).Error; err != nil { -- return nil, err -- } -- -- pickupProfitAmountCent := int64(0) -- pickupCompletedCount := int64(0) -- if pickup != nil { -- pickupProfitAmountCent = pickup.ProfitAmountCent -- pickupCompletedCount = pickup.CompletedCount -- } -- return &FinanceSummaryDTO{ -- TotalFlowAmountCent: payment.TotalFlowAmountCent, -- TotalRefundAmountCent: payment.TotalRefundAmountCent, -- PendingRefundAmountCent: payment.PendingRefundAmountCent, -- ChannelNetAmountCent: payment.TotalFlowAmountCent - payment.TotalRefundAmountCent, -- PlatformIncomeAmountCent: settlement.PlatformIncomeAmountCent + pickupProfitAmountCent, -- NormalOrderProfitAmountCent: settlement.PlatformIncomeAmountCent, -- PickupProfitAmountCent: pickupProfitAmountCent, -- PickupCompletedCount: pickupCompletedCount, -- OwnerShouldIncomeAmountCent: settlement.OwnerShouldIncomeAmountCent, -- OwnerWalletIncomeAmountCent: settlement.OwnerWalletIncomeAmountCent, -- OwnerEffectiveSettlementAmountCent: settlement.OwnerEffectiveSettlementAmountCent, -- OfflineSettlementAmountCent: settlement.OfflineSettlementAmountCent, -- OfflineSettlementPendingAmountCent: settlement.OfflineSettlementPendingAmountCent + pickup.PendingAmountCent, -- SettlementDiffAmountCent: settlement.OwnerShouldIncomeAmountCent - settlement.OwnerEffectiveSettlementAmountCent, -- EstimatedIncomeAmountCent: estimated.EstimatedIncomeAmountCent, -- SuccessfulPayCount: payment.SuccessfulPayCount, -- SuccessfulRefundCount: payment.FullRefundCount + payment.PartialRefundCount, -- FullRefundCount: payment.FullRefundCount, -- PartialRefundCount: payment.PartialRefundCount, -- PendingRefundCount: payment.PendingRefundCount, -- SettledOrderCount: settlement.SettledOrderCount, -- PendingSettleOrderCount: estimated.PendingSettleOrderCount, -- OfflineSettlementPendingCount: settlement.OfflineSettlementPendingCount + pickup.PendingCount, -- FinancialExceptionCount: settlement.FinancialExceptionCount, -- }, nil -+type dashboardDailyResult struct { -+ Items []FinanceDailyDTO -+ Summary FinanceSummaryDTO -+ Mohong MohongSummaryDTO -+ OperatingExpense OperatingExpenseSummaryDTO - } - --func (r *Repository) dailyItems(ctx context.Context, query DashboardQuery) ([]FinanceDailyDTO, error) { -+func (r *Repository) dailyItems(ctx context.Context, query DashboardQuery) (dashboardDailyResult, error) { - db := r.db.WithContext(ctx) -- payments, err := r.dailyPayments(ctx, query) -- if err != nil { -- return nil, err -+ var ( -+ payments []dailyPaymentRow -+ settlements []dailySettlementRow -+ estimates []dailyEstimatedRow -+ ) -+ var wg sync.WaitGroup -+ errCh := make(chan error, 3) -+ run := func(fn func() error) { -+ wg.Add(1) -+ go func() { -+ defer wg.Done() -+ if err := fn(); err != nil { -+ errCh <- err -+ } -+ }() - } -- paidOrders, err := r.dailyPaidOrders(ctx, query) -- if err != nil { -- return nil, err -+ run(func() error { -+ var err error -+ payments, err = r.dailyPayments(ctx, query) -+ return err -+ }) -+ run(func() error { -+ var err error -+ settlements, err = r.dailySettlements(ctx, query) -+ return err -+ }) -+ run(func() error { -+ var err error -+ estimates, err = r.dailyEstimates(ctx, query) -+ return err -+ }) -+ wg.Wait() -+ close(errCh) -+ for err := range errCh { -+ if err != nil { -+ return dashboardDailyResult{}, err -+ } - } - -- settlements := make([]dailySettlementRow, 0) -- if err := db.Table("rental_orders AS ro"). -- Select(`DATE(ro.settled_at) AS date, -- COALESCE(SUM(oc.platform_fee_cent), 0) AS platform_income_amount_cent, -- COALESCE(SUM(oc.owner_income_amount_cent), 0) AS owner_should_income_amount_cent, -- COALESCE(SUM(COALESCE(w.owner_wallet_income_amount_cent, 0)), 0) AS owner_wallet_income_amount_cent, -- COALESCE(SUM(CASE WHEN ro.settlement_mode = 'platform_managed' -- THEN COALESCE(ro.offline_settlement_amount_cent, 0) -- ELSE COALESCE(w.owner_wallet_income_amount_cent, 0) -- END), 0) AS owner_effective_settlement_amount_cent, -- COALESCE(SUM(CASE WHEN ro.settlement_mode = 'platform_managed' -- THEN COALESCE(ro.offline_settlement_amount_cent, 0) -- ELSE 0 -- END), 0) AS offline_settlement_amount_cent, -- COALESCE(SUM(CASE WHEN ro.settlement_mode = 'platform_managed' -- AND COALESCE(NULLIF(ro.offline_settlement_status, ''), 'none') = 'pending' -- THEN COALESCE(ro.offline_settlement_amount_cent, 0) -- ELSE 0 -- END), 0) AS offline_settlement_pending_amount_cent, -- COALESCE(SUM(CASE WHEN ro.settlement_mode = 'platform_managed' -- AND COALESCE(NULLIF(ro.offline_settlement_status, ''), 'none') = 'pending' -- AND COALESCE(ro.offline_settlement_amount_cent, 0) > 0 -- THEN 1 -- ELSE 0 -- END), 0) AS offline_settlement_pending_count, -- COUNT(ro.id) AS settled_order_count`). -- Joins("JOIN order_checkouts AS oc ON oc.order_id = ro.id AND oc.status = 'accepted'"). -- Joins("LEFT JOIN (?) AS w ON w.order_id = ro.id", ownerWalletIncomeForSettledOrdersSubquery(db, query)). -- Where("ro.settled_at >= ? AND ro.settled_at <= ?", query.StartDate, query.EndDate). -- Group("DATE(ro.settled_at)"). -- Scan(&settlements).Error; err != nil { -- return nil, err -+ paidOrders, err := r.dailyPaidOrders(ctx, query) -+ if err != nil { -+ return dashboardDailyResult{}, err - } - - pickupProfits := make([]dailyPickupProfitRow, 0) -@@ -341,7 +226,7 @@ func (r *Repository) dailyItems(ctx context.Context, query DashboardQuery) ([]Fi - Where("completed_at >= ? AND completed_at <= ?", query.StartDate, query.EndDate). - Group("DATE(completed_at)"). - Scan(&pickupProfits).Error; err != nil { -- return nil, err -+ return dashboardDailyResult{}, err - } - pickupAdjustments := make([]dailyPickupAdjustmentRow, 0) - if err := db.Table("admin_pickup_financial_adjustments AS fa"). -@@ -351,35 +236,23 @@ func (r *Repository) dailyItems(ctx context.Context, query DashboardQuery) ([]Fi - Where("fa.created_at >= ? AND fa.created_at <= ?", query.StartDate, query.EndDate). - Group("DATE(fa.created_at)"). - Scan(&pickupAdjustments).Error; err != nil { -- return nil, err -+ return dashboardDailyResult{}, err - } - - // 取消提号按取消日统计,与「已付款订单数」中的提号创建口径区分开。 - pickupCancelled, err := r.dailyPickupCancelled(ctx, query) - if err != nil { -- return nil, err -+ return dashboardDailyResult{}, err - } - - // 每日预计收入:尚未结算订单的下单预估平台手续费,按下单日期归集,口径与 summary 一致。 -- estimates := make([]dailyEstimatedRow, 0) -- if err := db.Table("rental_orders"). -- Select(`DATE(created_at) AS date, -- COALESCE(SUM(platform_fee_cent), 0) AS estimated_income_amount_cent`). -- Where("settlement_status NOT IN ?", settledSettlementStatuses()). -- Where("status NOT IN ?", nonBillableOrderStatuses()). -- Where("created_at >= ? AND created_at <= ?", query.StartDate, query.EndDate). -- Group("DATE(created_at)"). -- Scan(&estimates).Error; err != nil { -- return nil, err -- } -- - disbursements, err := r.dailyDisbursements(ctx, query) - if err != nil { -- return nil, err -+ return dashboardDailyResult{}, err - } - operatingExpenses, err := r.dailyOperatingExpenses(ctx, query) - if err != nil { -- return nil, err -+ return dashboardDailyResult{}, err - } - - itemsByDate := make(map[string]FinanceDailyDTO) -@@ -483,7 +356,142 @@ func (r *Repository) dailyItems(ctx context.Context, query DashboardQuery) ([]Fi - for day := dayStart(query.StartDate); !day.After(query.EndDate); day = day.AddDate(0, 0, 1) { - items = append(items, itemsByDate[day.Format("2006-01-02")]) - } -- return items, nil -+ return dashboardDailyResult{ -+ Items: items, -+ Summary: summaryFromDailyRows(payments, settlements, estimates), -+ Mohong: mohongSummaryFromDailyRows(payments), -+ OperatingExpense: operatingExpenseSummaryFromDailyRows(operatingExpenses), -+ }, nil -+} -+ -+func (r *Repository) dailyEstimates(ctx context.Context, query DashboardQuery) ([]dailyEstimatedRow, error) { -+ rows := make([]dailyEstimatedRow, 0) -+ err := r.db.WithContext(ctx).Table("rental_orders"). -+ Select(`DATE(created_at) AS date, -+ COALESCE(SUM(platform_fee_cent), 0) AS estimated_income_amount_cent, -+ COUNT(id) AS pending_settle_order_count`). -+ Where("settlement_status NOT IN ?", settledSettlementStatuses()). -+ Where("status NOT IN ?", nonBillableOrderStatuses()). -+ Where("created_at >= ? AND created_at <= ?", query.StartDate, query.EndDate). -+ Group("DATE(created_at)"). -+ Scan(&rows).Error -+ return rows, err -+} -+ -+func (r *Repository) dailySettlements(ctx context.Context, query DashboardQuery) ([]dailySettlementRow, error) { -+ db := r.db.WithContext(ctx) -+ rows := make([]dailySettlementRow, 0) -+ err := db.Table("rental_orders AS ro"). -+ Select(`DATE(ro.settled_at) AS date, -+ COALESCE(SUM(oc.platform_fee_cent), 0) AS platform_income_amount_cent, -+ COALESCE(SUM(oc.owner_income_amount_cent), 0) AS owner_should_income_amount_cent, -+ COALESCE(SUM(COALESCE(w.owner_wallet_income_amount_cent, 0)), 0) AS owner_wallet_income_amount_cent, -+ COALESCE(SUM(CASE WHEN ro.settlement_mode = 'platform_managed' -+ THEN COALESCE(ro.offline_settlement_amount_cent, 0) -+ ELSE COALESCE(w.owner_wallet_income_amount_cent, 0) -+ END), 0) AS owner_effective_settlement_amount_cent, -+ COALESCE(SUM(CASE WHEN ro.settlement_mode = 'platform_managed' -+ THEN COALESCE(ro.offline_settlement_amount_cent, 0) -+ ELSE 0 -+ END), 0) AS offline_settlement_amount_cent, -+ COALESCE(SUM(CASE WHEN ro.settlement_mode = 'platform_managed' -+ AND COALESCE(NULLIF(ro.offline_settlement_status, ''), 'none') = 'pending' -+ THEN COALESCE(ro.offline_settlement_amount_cent, 0) -+ ELSE 0 -+ END), 0) AS offline_settlement_pending_amount_cent, -+ COALESCE(SUM(CASE WHEN ro.settlement_mode = 'platform_managed' -+ AND COALESCE(NULLIF(ro.offline_settlement_status, ''), 'none') = 'pending' -+ AND COALESCE(ro.offline_settlement_amount_cent, 0) > 0 -+ THEN 1 -+ ELSE 0 -+ END), 0) AS offline_settlement_pending_count, -+ COALESCE(SUM(CASE WHEN ro.refund_status = 'refunding' -+ OR ABS(COALESCE(oc.owner_income_amount_cent, 0) - CASE WHEN ro.settlement_mode = 'platform_managed' -+ THEN COALESCE(ro.offline_settlement_amount_cent, 0) -+ ELSE COALESCE(w.owner_wallet_income_amount_cent, 0) -+ END) >= ? -+ OR EXISTS ( -+ SELECT 1 FROM payment_orders AS exception_payment -+ WHERE exception_payment.order_id = ro.id -+ AND exception_payment.biz_type IN ? -+ AND exception_payment.status IN ? -+ AND exception_payment.amount_cent > 0 -+ ) -+ THEN 1 -+ ELSE 0 -+ END), 0) AS financial_exception_count, -+ COUNT(ro.id) AS settled_order_count`, settlementDiffThresholdCent, refundBizTypes(), []string{"refunding", "failed"}). -+ Joins("JOIN order_checkouts AS oc ON oc.order_id = ro.id AND oc.status = 'accepted'"). -+ Joins("LEFT JOIN (?) AS w ON w.order_id = ro.id", ownerWalletIncomeForSettledOrdersSubquery(db, query)). -+ Where("ro.settled_at >= ? AND ro.settled_at <= ?", query.StartDate, query.EndDate). -+ Group("DATE(ro.settled_at)"). -+ Scan(&rows).Error -+ return rows, err -+} -+ -+func summaryFromDailyRows(payments []dailyPaymentRow, settlements []dailySettlementRow, estimates []dailyEstimatedRow) FinanceSummaryDTO { -+ var summary FinanceSummaryDTO -+ for _, row := range payments { -+ summary.TotalFlowAmountCent += row.TotalFlowAmountCent -+ summary.TotalRefundAmountCent += row.TotalRefundAmountCent -+ summary.PendingRefundAmountCent += row.PendingRefundAmountCent -+ summary.SuccessfulPayCount += row.SuccessfulPayCount -+ summary.FullRefundCount += row.FullRefundCount -+ summary.PartialRefundCount += row.PartialRefundCount -+ summary.PendingRefundCount += row.PendingRefundCount ++ if query.Operator != "" { ++ like := "%" + query.Operator + "%" ++ db = db.Where("(d.operator_name LIKE ? OR CAST(d.operator_id AS CHAR) LIKE ?)", like, like) + } -+ for _, row := range settlements { -+ summary.NormalOrderProfitAmountCent += row.PlatformIncomeAmountCent -+ summary.OwnerShouldIncomeAmountCent += row.OwnerShouldIncomeAmountCent -+ summary.OwnerWalletIncomeAmountCent += row.OwnerWalletIncomeAmountCent -+ summary.OwnerEffectiveSettlementAmountCent += row.OwnerEffectiveSettlementAmountCent -+ summary.OfflineSettlementAmountCent += row.OfflineSettlementAmountCent -+ summary.OfflineSettlementPendingAmountCent += row.OfflineSettlementPendingAmountCent -+ summary.OfflineSettlementPendingCount += row.OfflineSettlementPendingCount -+ summary.FinancialExceptionCount += row.FinancialExceptionCount -+ summary.SettledOrderCount += row.SettledOrderCount ++ if query.OperatorID > 0 { ++ db = db.Where("d.operator_id = ?", query.OperatorID) + } -+ for _, row := range estimates { -+ summary.EstimatedIncomeAmountCent += row.EstimatedIncomeAmountCent -+ summary.PendingSettleOrderCount += row.PendingSettleOrderCount -+ } -+ summary.ChannelNetAmountCent = summary.TotalFlowAmountCent - summary.TotalRefundAmountCent -+ summary.SuccessfulRefundCount = summary.FullRefundCount + summary.PartialRefundCount -+ summary.PlatformIncomeAmountCent = summary.NormalOrderProfitAmountCent -+ summary.SettlementDiffAmountCent = summary.OwnerShouldIncomeAmountCent - summary.OwnerEffectiveSettlementAmountCent -+ return summary -+} -+ -+func summaryWithPickup(summary FinanceSummaryDTO, pickup *PickupSummaryDTO) FinanceSummaryDTO { -+ if pickup == nil { -+ return summary -+ } -+ summary.PickupProfitAmountCent = pickup.ProfitAmountCent -+ summary.PickupCompletedCount = pickup.CompletedCount -+ summary.PlatformIncomeAmountCent = summary.NormalOrderProfitAmountCent + pickup.ProfitAmountCent -+ summary.OfflineSettlementPendingAmountCent += pickup.PendingAmountCent -+ summary.OfflineSettlementPendingCount += pickup.PendingCount -+ return summary -+} -+ -+func mohongSummaryFromDailyRows(rows []dailyPaymentRow) MohongSummaryDTO { -+ var summary MohongSummaryDTO -+ for _, row := range rows { -+ summary.FlowAmountCent += row.MohongFlowAmountCent -+ summary.RefundAmountCent += row.MohongRefundAmountCent -+ summary.PaidOrderCount += row.MohongPaidOrderCount -+ } -+ summary.NetAmountCent = summary.FlowAmountCent - summary.RefundAmountCent -+ return summary -+} -+ -+func operatingExpenseSummaryFromDailyRows(rows []dailyOperatingExpenseRow) OperatingExpenseSummaryDTO { -+ var summary OperatingExpenseSummaryDTO -+ for _, row := range rows { -+ summary.AmountCent += row.AmountCent -+ summary.Count += row.Count -+ } -+ return summary - } - - // dailyPayments 按支付单创建日统计收付款流水与退款笔数, -@@ -500,7 +508,10 @@ func (r *Repository) dailyPayments(ctx context.Context, query DashboardQuery) ([ - COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'refunded' AND po.amount_cent >= COALESCE(orig.amount_cent, 0) THEN 1 ELSE 0 END), 0) AS full_refund_count, - COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'refunded' AND po.amount_cent < COALESCE(orig.amount_cent, 0) THEN 1 ELSE 0 END), 0) AS partial_refund_count, - COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'refunding' THEN 1 ELSE 0 END), 0) AS pending_refund_count, -- COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'refunded' AND po.amount_cent >= COALESCE(orig.amount_cent, 0) THEN 1 ELSE 0 END), 0) AS normal_full_refund_count`, -+ COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'refunded' AND po.amount_cent >= COALESCE(orig.amount_cent, 0) THEN 1 ELSE 0 END), 0) AS normal_full_refund_count, -+ COALESCE(SUM(CASE WHEN po.biz_type = 'mohong_pay' AND po.status = 'paid' THEN po.amount_cent ELSE 0 END), 0) AS mohong_flow_amount_cent, -+ COALESCE(SUM(CASE WHEN po.biz_type = 'mohong_refund' AND po.status = 'refunded' THEN po.amount_cent ELSE 0 END), 0) AS mohong_refund_amount_cent, -+ COALESCE(SUM(CASE WHEN po.biz_type = 'mohong_pay' AND po.status = 'paid' THEN 1 ELSE 0 END), 0) AS mohong_paid_order_count`, - payBizTypes(), refundBizTypes(), refundBizTypes(), payBizTypes(), refundBizTypes(), refundBizTypes(), refundBizTypes(), normalRefundBizTypes()). - Joins("LEFT JOIN (?) AS orig ON orig.order_id = po.order_id", paymentOriginalAmountForRefundsInRangeSubquery(db, query)). - Where("po.created_at >= ? AND po.created_at <= ?", query.StartDate, query.EndDate). -@@ -541,33 +552,6 @@ func (r *Repository) dailyPaidOrders(ctx context.Context, query DashboardQuery) - return items, err - } - --type paymentSummaryRow struct { -- TotalFlowAmountCent int64 -- TotalRefundAmountCent int64 -- PendingRefundAmountCent int64 -- SuccessfulPayCount int64 -- FullRefundCount int64 -- PartialRefundCount int64 -- PendingRefundCount int64 --} -- --type settlementSummaryRow struct { -- PlatformIncomeAmountCent int64 -- OwnerShouldIncomeAmountCent int64 -- OwnerWalletIncomeAmountCent int64 -- OwnerEffectiveSettlementAmountCent int64 -- OfflineSettlementAmountCent int64 -- OfflineSettlementPendingAmountCent int64 -- OfflineSettlementPendingCount int64 -- FinancialExceptionCount int64 -- SettledOrderCount int64 --} -- --type estimatedIncomeRow struct { -- EstimatedIncomeAmountCent int64 -- PendingSettleOrderCount int64 --} -- - type dailyPaymentRow struct { - Date string - TotalFlowAmountCent int64 -@@ -578,6 +562,9 @@ type dailyPaymentRow struct { - PartialRefundCount int64 - PendingRefundCount int64 - NormalFullRefundCount int64 -+ MohongFlowAmountCent int64 -+ MohongRefundAmountCent int64 -+ MohongPaidOrderCount int64 - } - - type dailyPickupCancelledRow struct { -@@ -599,6 +586,7 @@ type dailySettlementRow struct { - OfflineSettlementAmountCent int64 - OfflineSettlementPendingAmountCent int64 - OfflineSettlementPendingCount int64 -+ FinancialExceptionCount int64 - SettledOrderCount int64 - } - -@@ -617,4 +605,5 @@ type dailyPickupAdjustmentRow struct { - type dailyEstimatedRow struct { - Date string - EstimatedIncomeAmountCent int64 -+ PendingSettleOrderCount int64 - } -diff --git a/backend/internal/modules/adminfinance/dashboard_test.go b/backend/internal/modules/adminfinance/dashboard_test.go -index a0821c2..1ce17f2 100644 ---- a/backend/internal/modules/adminfinance/dashboard_test.go -+++ b/backend/internal/modules/adminfinance/dashboard_test.go -@@ -321,10 +321,11 @@ func TestSummaryReturnsNormalOrderCountAndScopedExceptionCount(t *testing.T) { - if err != nil { - t.Fatalf("读取提号汇总失败: %v", err) - } -- summary, err := repo.summary(t.Context(), query, pickup) -+ settlements, err := repo.dailySettlements(t.Context(), query) - if err != nil { -- t.Fatalf("读取财务汇总失败: %v", err) -+ t.Fatalf("读取每日结算汇总失败: %v", err) - } -+ summary := summaryWithPickup(summaryFromDailyRows(nil, settlements, nil), pickup) - if summary.SettledOrderCount != 2 || summary.NormalOrderProfitAmountCent != 500 { - t.Fatalf("普通订单数量或利润错误: %+v", summary) - } -@@ -332,3 +333,39 @@ func TestSummaryReturnsNormalOrderCountAndScopedExceptionCount(t *testing.T) { - t.Fatalf("财务异常数 = %d, want 1", summary.FinancialExceptionCount) - } - } -+ -+func TestSummaryFromDailyRowsPreservesDashboardTotals(t *testing.T) { -+ paymentRows := []dailyPaymentRow{ -+ {TotalFlowAmountCent: 1000, TotalRefundAmountCent: 100, PendingRefundAmountCent: 30, SuccessfulPayCount: 3, FullRefundCount: 1}, -+ {TotalFlowAmountCent: 2500, TotalRefundAmountCent: 400, PendingRefundAmountCent: 70, SuccessfulPayCount: 5, PartialRefundCount: 2, PendingRefundCount: 1}, -+ } -+ settlementRows := []dailySettlementRow{ -+ {PlatformIncomeAmountCent: 300, OwnerShouldIncomeAmountCent: 900, OwnerWalletIncomeAmountCent: 850, OwnerEffectiveSettlementAmountCent: 850, OfflineSettlementAmountCent: 100, OfflineSettlementPendingAmountCent: 20, OfflineSettlementPendingCount: 1, FinancialExceptionCount: 2, SettledOrderCount: 3}, -+ {PlatformIncomeAmountCent: 200, OwnerShouldIncomeAmountCent: 600, OwnerWalletIncomeAmountCent: 500, OwnerEffectiveSettlementAmountCent: 550, OfflineSettlementAmountCent: 200, OfflineSettlementPendingAmountCent: 40, OfflineSettlementPendingCount: 2, FinancialExceptionCount: 1, SettledOrderCount: 2}, -+ } -+ estimateRows := []dailyEstimatedRow{ -+ {EstimatedIncomeAmountCent: 120, PendingSettleOrderCount: 4}, -+ {EstimatedIncomeAmountCent: 80, PendingSettleOrderCount: 3}, -+ } -+ pickup := &PickupSummaryDTO{ProfitAmountCent: 90, CompletedCount: 2, PendingAmountCent: 60, PendingCount: 3} -+ -+ summary := summaryWithPickup(summaryFromDailyRows(paymentRows, settlementRows, estimateRows), pickup) -+ if summary.TotalFlowAmountCent != 3500 || summary.TotalRefundAmountCent != 500 || summary.ChannelNetAmountCent != 3000 { -+ t.Fatalf("支付汇总错误: %+v", summary) -+ } -+ if summary.PendingRefundAmountCent != 100 || summary.SuccessfulPayCount != 8 || summary.SuccessfulRefundCount != 3 || summary.FullRefundCount != 1 || summary.PartialRefundCount != 2 || summary.PendingRefundCount != 1 { -+ t.Fatalf("支付笔数汇总错误: %+v", summary) -+ } -+ if summary.NormalOrderProfitAmountCent != 500 || summary.PickupProfitAmountCent != 90 || summary.PlatformIncomeAmountCent != 590 || summary.PickupCompletedCount != 2 { -+ t.Fatalf("平台利润汇总错误: %+v", summary) -+ } -+ if summary.OwnerShouldIncomeAmountCent != 1500 || summary.OwnerWalletIncomeAmountCent != 1350 || summary.OwnerEffectiveSettlementAmountCent != 1400 || summary.SettlementDiffAmountCent != 100 { -+ t.Fatalf("货主结算汇总错误: %+v", summary) -+ } -+ if summary.OfflineSettlementAmountCent != 300 || summary.OfflineSettlementPendingAmountCent != 120 || summary.OfflineSettlementPendingCount != 6 { -+ t.Fatalf("线下结算汇总错误: %+v", summary) -+ } -+ if summary.EstimatedIncomeAmountCent != 200 || summary.PendingSettleOrderCount != 7 || summary.SettledOrderCount != 5 || summary.FinancialExceptionCount != 3 { -+ t.Fatalf("订单状态汇总错误: %+v", summary) -+ } -+} -diff --git a/backend/internal/modules/adminfinance/detail.go b/backend/internal/modules/adminfinance/detail.go -index f4d40ee..ce4feca 100644 ---- a/backend/internal/modules/adminfinance/detail.go -+++ b/backend/internal/modules/adminfinance/detail.go -@@ -19,11 +19,23 @@ func (r *Repository) Details(ctx context.Context, query DetailQuery) (*Paginated - return &PaginatedResult{Items: []FinanceDetailDTO{}, Total: 0, Page: query.Page, PageSize: query.PageSize}, nil - } - -- // 明细行查询保留完整 JOIN,仅对当前分页命中的订单做金额聚合。 -- db := r.financeDetailBaseQuery(ctx, query) - offset := (query.Page - 1) * query.PageSize -+ orderIDs := make([]uint64, 0, query.PageSize) -+ if err := r.applyDetailFilters(r.db.WithContext(ctx).Table("rental_orders AS ro"), query). -+ Order("ro.id DESC"). -+ Offset(offset). -+ Limit(query.PageSize). -+ Pluck("ro.id", &orderIDs).Error; err != nil { -+ return nil, err -+ } -+ if len(orderIDs) == 0 { -+ return &PaginatedResult{Items: []FinanceDetailDTO{}, Total: total, Page: query.Page, PageSize: query.PageSize}, nil -+ } -+ -+ // 先取当前页 ID,再只为这些订单聚合结账、支付和钱包详情。 -+ db := r.financeDetailBaseQuery(ctx, query, orderIDs).Where("ro.id IN ?", orderIDs) - rows := make([]financeDetailRow, 0, query.PageSize) -- if err := db.Order("ro.id DESC").Offset(offset).Limit(query.PageSize).Scan(&rows).Error; err != nil { -+ if err := db.Order("ro.id DESC").Scan(&rows).Error; err != nil { - return nil, err - } - items := make([]FinanceDetailDTO, 0, len(rows)) -@@ -67,7 +79,7 @@ func (r *Repository) applyDetailFilters(db *gorm.DB, query DetailQuery) *gorm.DB - return db - } - --func (r *Repository) financeDetailBaseQuery(ctx context.Context, query DetailQuery) *gorm.DB { -+func (r *Repository) financeDetailBaseQuery(ctx context.Context, query DetailQuery, orderIDs []uint64) *gorm.DB { - db := r.db.WithContext(ctx).Table("rental_orders AS ro"). - Select(`ro.id AS order_id, ro.order_no, ro.status AS order_status, ro.settlement_status, ro.refund_status, - ro.handoff_mode, ro.settlement_mode, -@@ -113,9 +125,9 @@ func (r *Repository) financeDetailBaseQuery(ctx context.Context, query DetailQue - ro.created_at, ro.settled_at, ro.offline_settled_at`, settlementDiffThresholdCent). - Joins("LEFT JOIN users AS ru ON ru.id = ro.renter_id"). - Joins("LEFT JOIN users AS ou ON ou.id = ro.owner_id"). -- Joins("LEFT JOIN (?) AS oc ON oc.order_id = ro.id", acceptedCheckoutSubquery(r.db.WithContext(ctx))). -- Joins("LEFT JOIN (?) AS p ON p.order_id = ro.id", orderPaymentSubquery(r.db.WithContext(ctx))). -- Joins("LEFT JOIN (?) AS w ON w.order_id = ro.id", ownerWalletIncomeSubquery(r.db.WithContext(ctx))) -+ Joins("LEFT JOIN (?) AS oc ON oc.order_id = ro.id", acceptedCheckoutForOrdersSubquery(r.db.WithContext(ctx), orderIDs)). -+ Joins("LEFT JOIN (?) AS p ON p.order_id = ro.id", orderPaymentForOrdersSubquery(r.db.WithContext(ctx), orderIDs)). -+ Joins("LEFT JOIN (?) AS w ON w.order_id = ro.id", ownerWalletIncomeForOrdersSubquery(r.db.WithContext(ctx), orderIDs)) - - return r.applyDetailFilters(db, query) - } -diff --git a/backend/internal/modules/adminfinance/subquery.go b/backend/internal/modules/adminfinance/subquery.go -index 18be7d9..6759d09 100644 ---- a/backend/internal/modules/adminfinance/subquery.go -+++ b/backend/internal/modules/adminfinance/subquery.go -@@ -4,14 +4,16 @@ import ( - "gorm.io/gorm" - ) - --func acceptedCheckoutSubquery(db *gorm.DB) *gorm.DB { -- latest := db.Table("order_checkouts").Select("MAX(id) AS id").Where("status = ?", "accepted").Group("order_id") -+func acceptedCheckoutForOrdersSubquery(db *gorm.DB, orderIDs []uint64) *gorm.DB { -+ latest := db.Table("order_checkouts").Select("MAX(id) AS id"). -+ Where("status = ? AND order_id IN ?", "accepted", orderIDs). -+ Group("order_id") - return db.Table("order_checkouts AS oc"). - Select("oc.*"). - Joins("JOIN (?) AS latest ON latest.id = oc.id", latest) - } - --func orderPaymentSubquery(db *gorm.DB) *gorm.DB { -+func orderPaymentForOrdersSubquery(db *gorm.DB, orderIDs []uint64) *gorm.DB { - return db.Table("payment_orders"). - Select(`order_id, - COALESCE(SUM(CASE WHEN biz_type = 'order_pay' AND status = 'paid' THEN amount_cent ELSE 0 END), 0) AS paid_amount_cent, -@@ -19,13 +21,14 @@ func orderPaymentSubquery(db *gorm.DB) *gorm.DB { - COALESCE(SUM(CASE WHEN biz_type IN ? AND status = 'refunding' THEN amount_cent ELSE 0 END), 0) AS refunding_amount_cent, - COALESCE(SUM(CASE WHEN biz_type IN ? AND status = 'failed' THEN amount_cent ELSE 0 END), 0) AS failed_refund_amount_cent`, - refundBizTypes(), refundBizTypes(), refundBizTypes()). -+ Where("order_id IN ?", orderIDs). - Group("order_id") - } - --func ownerWalletIncomeSubquery(db *gorm.DB) *gorm.DB { -+func ownerWalletIncomeForOrdersSubquery(db *gorm.DB, orderIDs []uint64) *gorm.DB { - return db.Table("wallet_ledger"). - Select("order_id, COALESCE(SUM(amount_cent), 0) AS owner_wallet_income_amount_cent"). -- Where("direction = ? AND biz_type IN ? AND order_id IS NOT NULL", "in", []string{"owner_income", "deposit_compensation", "arbitration_owner_income"}). -+ Where("direction = ? AND biz_type IN ? AND order_id IN ?", "in", []string{"owner_income", "deposit_compensation", "arbitration_owner_income"}, orderIDs). - Group("order_id") - } - -@@ -44,18 +47,6 @@ func ownerWalletIncomeForSettledOrdersSubquery(db *gorm.DB, query DashboardQuery - Group("scoped_order.id") - } - --// orderPaymentForSettledOrdersSubquery 只聚合当前结算区间订单的退款状态, --// 供仪表盘异常数判断使用,避免 financeDetailBaseQuery 在首页扫描所有历史付款单。 --func orderPaymentForSettledOrdersSubquery(db *gorm.DB, query DashboardQuery) *gorm.DB { -- return db.Table("rental_orders AS scoped_order"). -- Select(`scoped_order.id AS order_id, -- COALESCE(SUM(CASE WHEN payment.biz_type IN ? AND payment.status = 'refunding' THEN payment.amount_cent ELSE 0 END), 0) AS refunding_amount_cent, -- COALESCE(SUM(CASE WHEN payment.biz_type IN ? AND payment.status = 'failed' THEN payment.amount_cent ELSE 0 END), 0) AS failed_refund_amount_cent`, refundBizTypes(), refundBizTypes()). -- Joins("LEFT JOIN payment_orders AS payment ON payment.order_id = scoped_order.id AND payment.biz_type IN ?", refundBizTypes()). -- Where("scoped_order.settled_at >= ? AND scoped_order.settled_at <= ?", query.StartDate, query.EndDate). -- Group("scoped_order.id") --} -- - // paymentOriginalAmountForRefundsInRangeSubquery 仅为当前区间内的退款单回查原支付金额。 - // 退款统计原先会对全部历史支付单按 order_id 聚合;数据增长后这部分即使只看一天也会很慢。 - func paymentOriginalAmountForRefundsInRangeSubquery(db *gorm.DB, query DashboardQuery) *gorm.DB { -diff --git a/backend/migrations/000063_finance_pending_disbursement_index.sql b/backend/migrations/000063_finance_pending_disbursement_index.sql -new file mode 100644 -index 0000000..3d6190f ---- /dev/null -+++ b/backend/migrations/000063_finance_pending_disbursement_index.sql -@@ -0,0 +1,13 @@ -+-- +goose Up -+-- 财务仪表盘的待线下出款金额不受日期限制,需要持续读取全部待出款订单。 -+-- 覆盖查询条件与汇总金额,避免通过低区分度状态索引回表扫描。 -+ALTER TABLE rental_orders -+ ADD KEY idx_rental_orders_offline_pending_amount ( -+ settlement_mode, -+ offline_settlement_status, -+ offline_settlement_amount_cent -+ ); -+ -+-- +goose Down -+ALTER TABLE rental_orders -+ DROP KEY idx_rental_orders_offline_pending_amount; + if !query.StartDate.IsZero() && !query.EndDate.IsZero() { + if query.DateType == "paid" { + db = db.Where("d.paid_at >= ? AND d.paid_at <= ?", query.StartDate, query.EndDate) diff --git a/docs/MODIFIED_FILE b/docs/MODIFIED_FILE index 17da89c..eccf568 100644 --- a/docs/MODIFIED_FILE +++ b/docs/MODIFIED_FILE @@ -2,608 +2,368 @@ package adminfinance import ( "context" - "sync" + "encoding/json" + "strings" + "time" - "hfb_sys/backend/internal/timeutil" + "gorm.io/gorm" ) -func (r *Repository) Dashboard(ctx context.Context, query DashboardQuery) (*DashboardDTO, error) { - if cached := r.loadDashboardCache(ctx, query); cached != nil { - return cached, nil +func (r *Repository) Disbursements(ctx context.Context, query DisbursementQuery) (*DisbursementListDTO, error) { + var summary DisbursementListSummaryDTO + summaryDB := r.applyDisbursementFilters(r.disbursementListBaseQuery(ctx), query) + if err := summaryDB.Select(`COUNT(*) AS record_count, + COALESCE(SUM(CASE WHEN status = 'paid' THEN actual_amount_cent ELSE 0 END), 0) AS paid_amount_cent, + COALESCE(SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END), 0) AS paid_count, + COALESCE(SUM(CASE WHEN status = 'payment_pending' THEN actual_amount_cent ELSE 0 END), 0) AS payment_pending_amount_cent, + COALESCE(SUM(CASE WHEN status = 'payment_pending' THEN 1 ELSE 0 END), 0) AS payment_pending_count, + COALESCE(SUM(CASE WHEN status = 'review_pending' THEN actual_amount_cent ELSE 0 END), 0) AS review_pending_amount_cent, + COALESCE(SUM(CASE WHEN status = 'review_pending' THEN 1 ELSE 0 END), 0) AS review_pending_count, + COALESCE(SUM(CASE WHEN source_type = 'withdrawal' AND status = 'paid' THEN fee_cent ELSE 0 END), 0) AS withdrawal_fee_amount_cent`). + Scan(&summary).Error; err != nil { + return nil, err } - // 各板块的读取互不依赖。并行执行能避免单个请求串行等待二十余条统计 SQL, - // 首次打开或缓存失效时仍可尽快返回;每个查询继续复用 GORM 的连接池。 - var ( - daily dashboardDailyResult - pickup *PickupSummaryDTO - disbursement *DisbursementSummaryDTO - ) - var wg sync.WaitGroup - errCh := make(chan error, 3) - run := func(fn func() error) { - wg.Add(1) - go func() { - defer wg.Done() - if err := fn(); err != nil { - errCh <- err - } - }() + + rows := make([]disbursementItemRow, 0, query.PageSize) + orderColumn := "business_created_at" + if query.DateType == "paid" { + orderColumn = "paid_at" } - run(func() error { - var err error - daily, err = r.dailyItems(ctx, query) - return err - }) - run(func() error { - var err error - pickup, err = r.pickupSummary(ctx, query) - return err - }) - run(func() error { - var err error - disbursement, err = r.disbursementSummary(ctx, query) - return err - }) - wg.Wait() - close(errCh) - for err := range errCh { - if err != nil { - return nil, err + offset := (query.Page - 1) * query.PageSize + rowsDB := r.applyDisbursementFilters(r.disbursementListBaseQuery(ctx), query) + if err := rowsDB.Order(orderColumn + " DESC"). + Order("source_id DESC"). + Offset(offset). + Limit(query.PageSize). + Scan(&rows).Error; err != nil { + return nil, err + } + + items := make([]DisbursementItemDTO, 0, len(rows)) + for _, row := range rows { + items = append(items, row.toDTO()) + } + return &DisbursementListDTO{ + Items: items, + Total: summary.RecordCount, + Page: query.Page, + PageSize: query.PageSize, + Summary: summary, + }, nil +} + +func (r *Repository) disbursementListBaseQuery(ctx context.Context) *gorm.DB { + db := r.db.WithContext(ctx) + platformManaged := db.Table("rental_orders AS ro"). + Select(`'platform_managed' AS source_type, + ro.id AS source_id, + ro.order_no AS business_no, + ro.id AS order_id, + 0 AS withdrawal_id, + ro.owner_id AS user_id, + '外部卖家' AS payee_name, + '' AS payee_phone, + COALESCE(lu.uploader_name, '') AS uploader_name, + COALESCE(lu.source_channel, '') AS source_channel, + '' AS account_type, + '' AS account_name, + '' AS account_no, + '' AS bank_name, + ro.offline_settlement_amount_cent AS amount_cent, + 0 AS fee_cent, + ro.offline_settlement_amount_cent AS actual_amount_cent, + CASE WHEN ro.offline_settlement_status = 'settled' THEN 'paid' ELSE 'payment_pending' END AS status, + ro.offline_settlement_status AS raw_status, + ro.settled_at AS business_created_at, + ro.offline_settled_at AS paid_at, + ro.offline_settled_by AS operator_id, + COALESCE(NULLIF(operator.nickname, ''), operator.username, '') AS operator_name, + ro.offline_settlement_remark AS remark, + '' AS category, + '' AS custom_category_name, + '' AS voucher_url, + NULL AS voided_at, + NULL AS voided_by, + '' AS voided_by_name, + '' AS void_reason, + lu.parsed_payload AS source_payload`). + Joins(`LEFT JOIN listing_uploads AS lu ON lu.id = ( + SELECT MAX(lu2.id) FROM listing_uploads AS lu2 WHERE lu2.listing_id = ro.listing_id + )`). + Joins("LEFT JOIN admin_users AS operator ON operator.id = ro.offline_settled_by"). + Where("ro.settlement_mode = ?", "platform_managed"). + Where("ro.offline_settlement_status IN ?", []string{"pending", "settled"}). + Where("ro.offline_settlement_amount_cent > 0") + + pickupManaged := db.Table("admin_pickups AS ap"). + Select(`'pickup' AS source_type, + ap.id AS source_id, + ap.pickup_no AS business_no, + 0 AS order_id, + 0 AS withdrawal_id, + ap.owner_id AS user_id, + '外部卖家' AS payee_name, + '' AS payee_phone, + '' AS uploader_name, + ap.source_channel, + '' AS account_type, + '' AS account_name, + '' AS account_no, + '' AS bank_name, + ap.settle_amount_cent AS amount_cent, + 0 AS fee_cent, + ap.settle_amount_cent AS actual_amount_cent, + CASE WHEN ap.offline_settlement_status = 'settled' THEN 'paid' ELSE 'payment_pending' END AS status, + ap.offline_settlement_status AS raw_status, + ap.completed_at AS business_created_at, + ap.offline_settled_at AS paid_at, + ap.offline_settled_by AS operator_id, + COALESCE(NULLIF(operator.nickname, ''), operator.username, '') AS operator_name, + ap.offline_settlement_remark AS remark, + '' AS category, + '' AS custom_category_name, + '' AS voucher_url, + NULL AS voided_at, + NULL AS voided_by, + '' AS voided_by_name, + '' AS void_reason, + ap.account_snapshot AS source_payload`). + Joins("LEFT JOIN admin_users AS operator ON operator.id = ap.offline_settled_by"). + Where("ap.settlement_mode = ?", "platform_managed"). + Where("ap.offline_settlement_status IN ?", []string{"pending", "settled"}). + Where("ap.settle_amount_cent > 0") + + pickupAdjustments := db.Table("admin_pickup_financial_adjustments AS fa"). + Select(`'pickup_adjustment' AS source_type, + fa.id AS source_id, + CONCAT(ap.pickup_no, '-ADJ-', fa.id) AS business_no, + 0 AS order_id, + 0 AS withdrawal_id, + ap.owner_id AS user_id, + '外部卖家' AS payee_name, + '' AS payee_phone, + '' AS uploader_name, + ap.source_channel, + '' AS account_type, + '' AS account_name, + '' AS account_no, + '' AS bank_name, + fa.settle_delta_cent AS amount_cent, + 0 AS fee_cent, + fa.settle_delta_cent AS actual_amount_cent, + CASE WHEN fa.status = 'settled' THEN 'paid' ELSE 'payment_pending' END AS status, + fa.status AS raw_status, + fa.created_at AS business_created_at, + fa.settled_at AS paid_at, + fa.settled_by AS operator_id, + COALESCE(NULLIF(operator.nickname, ''), operator.username, '') AS operator_name, + fa.reason AS remark, + '' AS category, + '' AS custom_category_name, + '' AS voucher_url, + NULL AS voided_at, + NULL AS voided_by, + '' AS voided_by_name, + '' AS void_reason, + ap.account_snapshot AS source_payload`). + Joins("JOIN admin_pickups AS ap ON ap.id = fa.pickup_id"). + Joins("LEFT JOIN admin_users AS operator ON operator.id = fa.settled_by"). + Where("fa.settlement_mode = ?", "platform_managed"). + Where("fa.status IN ?", []string{"pending", "settled"}). + Where("fa.settle_delta_cent > 0") + + withdrawal := db.Table("withdrawal_requests AS wr"). + Select(`'withdrawal' AS source_type, + wr.id AS source_id, + wr.withdraw_no AS business_no, + 0 AS order_id, + wr.id AS withdrawal_id, + wr.user_id, + COALESCE(NULLIF(u.nickname, ''), NULLIF(wr.account_name, ''), '') AS payee_name, + COALESCE(u.phone, '') AS payee_phone, + '' AS uploader_name, + '' AS source_channel, + wr.account_type, + wr.account_name, + wr.account_no, + wr.bank_name, + wr.amount_cent, + wr.fee_cent, + wr.actual_amount_cent, + CASE + WHEN wr.status = 'pending' THEN 'review_pending' + WHEN wr.status = 'processing' THEN 'payment_pending' + WHEN wr.status = 'completed' THEN 'paid' + ELSE wr.status + END AS status, + wr.status AS raw_status, + wr.created_at AS business_created_at, + wr.paid_at, + COALESCE(wr.paid_by, wr.reviewed_by) AS operator_id, + COALESCE(NULLIF(operator.nickname, ''), operator.username, '') AS operator_name, + CASE WHEN wr.payment_remark <> '' THEN wr.payment_remark ELSE wr.review_remark END AS remark, + '' AS category, + '' AS custom_category_name, + '' AS voucher_url, + NULL AS voided_at, + NULL AS voided_by, + '' AS voided_by_name, + '' AS void_reason, + NULL AS source_payload`). + Joins("LEFT JOIN users AS u ON u.id = wr.user_id"). + Joins("LEFT JOIN admin_users AS operator ON operator.id = COALESCE(wr.paid_by, wr.reviewed_by)") + + manualOffline := db.Table("manual_disbursements AS md"). + Select(`'manual_offline' AS source_type, + md.id AS source_id, + md.disbursement_no AS business_no, + 0 AS order_id, + 0 AS withdrawal_id, + 0 AS user_id, + md.payee_name, + '' AS payee_phone, + '' AS uploader_name, + '' AS source_channel, + '' AS account_type, + '' AS account_name, + '' AS account_no, + '' AS bank_name, + md.amount_cent, + 0 AS fee_cent, + md.amount_cent AS actual_amount_cent, + md.status, + md.status AS raw_status, + md.created_at AS business_created_at, + md.paid_at, + md.created_by AS operator_id, + COALESCE(NULLIF(creator.nickname, ''), creator.username, '') AS operator_name, + md.remark, + md.category, + md.custom_category_name, + md.voucher_url, + md.voided_at, + md.voided_by, + COALESCE(NULLIF(voider.nickname, ''), voider.username, '') AS voided_by_name, + md.void_reason, + NULL AS source_payload`). + Joins("LEFT JOIN admin_users AS creator ON creator.id = md.created_by"). + Joins("LEFT JOIN admin_users AS voider ON voider.id = md.voided_by") + + union := db.Raw("? UNION ALL ? UNION ALL ? UNION ALL ? UNION ALL ?", platformManaged, pickupManaged, pickupAdjustments, withdrawal, manualOffline) + return db.Table("(?) AS d", union) +} + +func (r *Repository) applyDisbursementFilters(db *gorm.DB, query DisbursementQuery) *gorm.DB { + if query.SourceType != "" { + db = db.Where("d.source_type = ?", query.SourceType) + } + if query.Status != "" { + db = db.Where("d.status = ?", query.Status) + } + if query.BusinessNo != "" { + db = db.Where("d.business_no LIKE ?", "%"+query.BusinessNo+"%") + } + if query.UserID > 0 { + db = db.Where("d.user_id = ?", query.UserID) + } + if query.Keyword != "" { + like := "%" + query.Keyword + "%" + db = db.Where(`(d.business_no LIKE ? OR d.payee_name LIKE ? OR d.payee_phone LIKE ? + OR d.uploader_name LIKE ? OR d.account_name LIKE ? OR d.account_no LIKE ?)`, like, like, like, like, like, like) + } + if query.Operator != "" { + like := "%" + query.Operator + "%" + db = db.Where("(d.operator_name LIKE ? OR CAST(d.operator_id AS CHAR) LIKE ?)", like, like) + } + if query.OperatorID > 0 { + db = db.Where("d.operator_id = ?", query.OperatorID) + } + if !query.StartDate.IsZero() && !query.EndDate.IsZero() { + if query.DateType == "paid" { + db = db.Where("d.paid_at >= ? AND d.paid_at <= ?", query.StartDate, query.EndDate) + } else { + db = db.Where("d.business_created_at >= ? AND d.business_created_at <= ?", query.StartDate, query.EndDate) } } - - summary := summaryWithPickup(daily.Summary, pickup) - result := &DashboardDTO{ - Summary: summary, - DailyItems: daily.Items, - PickupSummary: *pickup, - MohongSummary: daily.Mohong, - DisbursementSummary: *disbursement, - OperatingExpenseSummary: daily.OperatingExpense, - GeneratedAt: timeutil.ShanghaiNow(), - } - r.storeDashboardCache(ctx, query, result) - return result, nil + return db } -func (r *Repository) operatingExpenseSummary(ctx context.Context, query DashboardQuery) (*OperatingExpenseSummaryDTO, error) { - var summary OperatingExpenseSummaryDTO - err := r.db.WithContext(ctx).Table("operating_expenses"). - Select("COALESCE(SUM(amount_cent), 0) AS amount_cent, COUNT(id) AS count"). - Where("status = ?", "paid"). - Where("occurred_at >= ? AND occurred_at <= ?", query.StartDate, query.EndDate). - Scan(&summary).Error - if err != nil { - return nil, err - } - return &summary, nil +type disbursementItemRow struct { + SourceType string + SourceID uint64 + BusinessNo string + OrderID uint64 + WithdrawalID uint64 + UserID uint64 + PayeeName string + PayeePhone string + UploaderName string + SourceChannel string + AccountType string + AccountName string + AccountNo string + BankName string + AmountCent int64 + FeeCent int64 + ActualAmountCent int64 + Status string + RawStatus string + BusinessCreatedAt *time.Time + PaidAt *time.Time + OperatorID *uint64 + OperatorName string + Remark string + Category string + CustomCategoryName string + VoucherURL string + VoidedAt *time.Time + VoidedBy *uint64 + VoidedByName string + VoidReason string + SourcePayload []byte } -// pickupSummary 线下提号统计,独立查询 admin_pickups 表,不混入正常订单口径。 -func (r *Repository) pickupSummary(ctx context.Context, query DashboardQuery) (*PickupSummaryDTO, error) { - db := r.db.WithContext(ctx) - var row struct { - SettledAmountCent int64 - ProfitAmountCent int64 - CompletedCount int64 - } - if err := db.Table("admin_pickups"). - Select(`COALESCE(SUM(settle_amount_cent), 0) AS settled_amount_cent, COALESCE(SUM(profit_amount_cent), 0) AS profit_amount_cent, COUNT(id) AS completed_count`). - Where("status = ?", "completed"). - Where("completed_at >= ? AND completed_at <= ?", query.StartDate, query.EndDate). - Scan(&row).Error; err != nil { - return nil, err - } - var adjustments struct { - SettledAmountCent int64 - ProfitAmountCent int64 - } - if err := db.Table("admin_pickup_financial_adjustments AS fa"). - Select(`COALESCE(SUM(fa.settle_delta_cent), 0) AS settled_amount_cent, - COALESCE(SUM(fa.profit_delta_cent), 0) AS profit_amount_cent`). - Joins("JOIN admin_pickups AS p ON p.id = fa.pickup_id AND p.status = ?", "completed"). - Where("fa.created_at >= ? AND fa.created_at <= ?", query.StartDate, query.EndDate). - Scan(&adjustments).Error; err != nil { - return nil, err - } - var inProgress int64 - if err := db.Table("admin_pickups").Where("status = ?", "picking_up").Count(&inProgress).Error; err != nil { - return nil, err - } - var pending struct { - AmountCent int64 - Count int64 - } - if err := db.Table("admin_pickups"). - Select(`COALESCE(SUM(settle_amount_cent), 0) AS amount_cent, COUNT(id) AS count`). - Where("settlement_mode = ? AND offline_settlement_status = ? AND settle_amount_cent > 0", "platform_managed", "pending"). - Scan(&pending).Error; err != nil { - return nil, err - } - var pendingAdjustments struct { - AmountCent int64 - Count int64 - } - if err := db.Table("admin_pickup_financial_adjustments"). - Select(`COALESCE(SUM(settle_delta_cent), 0) AS amount_cent, COUNT(id) AS count`). - Where("settlement_mode = ? AND status = ? AND settle_delta_cent > 0", "platform_managed", "pending"). - Scan(&pendingAdjustments).Error; err != nil { - return nil, err - } - return &PickupSummaryDTO{ - SettledAmountCent: row.SettledAmountCent + adjustments.SettledAmountCent, - ProfitAmountCent: row.ProfitAmountCent + adjustments.ProfitAmountCent, - CompletedCount: row.CompletedCount, - InProgressCount: inProgress, - PendingAmountCent: pending.AmountCent + pendingAdjustments.AmountCent, - PendingCount: pending.Count + pendingAdjustments.Count, - }, nil -} - -// mohongSummary 撞车商城按支付订单统计交易流水,不计入平台利润。 -func (r *Repository) mohongSummary(ctx context.Context, query DashboardQuery) (*MohongSummaryDTO, error) { - db := r.db.WithContext(ctx) - var row struct { - FlowAmountCent int64 - RefundAmountCent int64 - PaidOrderCount int64 - } - if err := db.Table("payment_orders"). - Select(`COALESCE(SUM(CASE WHEN biz_type = 'mohong_pay' AND status = 'paid' THEN amount_cent ELSE 0 END), 0) AS flow_amount_cent, - COALESCE(SUM(CASE WHEN biz_type = 'mohong_refund' AND status = 'refunded' THEN amount_cent ELSE 0 END), 0) AS refund_amount_cent, - COALESCE(SUM(CASE WHEN biz_type = 'mohong_pay' AND status = 'paid' THEN 1 ELSE 0 END), 0) AS paid_order_count`). - Where("created_at >= ? AND created_at <= ?", query.StartDate, query.EndDate). - Scan(&row).Error; err != nil { - return nil, err - } - return &MohongSummaryDTO{ - FlowAmountCent: row.FlowAmountCent, - RefundAmountCent: row.RefundAmountCent, - NetAmountCent: row.FlowAmountCent - row.RefundAmountCent, - PaidOrderCount: row.PaidOrderCount, - }, nil -} - -type dashboardDailyResult struct { - Items []FinanceDailyDTO - Summary FinanceSummaryDTO - Mohong MohongSummaryDTO - OperatingExpense OperatingExpenseSummaryDTO -} - -func (r *Repository) dailyItems(ctx context.Context, query DashboardQuery) (dashboardDailyResult, error) { - db := r.db.WithContext(ctx) - var ( - payments []dailyPaymentRow - settlements []dailySettlementRow - estimates []dailyEstimatedRow - ) - var wg sync.WaitGroup - errCh := make(chan error, 3) - run := func(fn func() error) { - wg.Add(1) - go func() { - defer wg.Done() - if err := fn(); err != nil { - errCh <- err - } - }() - } - run(func() error { - var err error - payments, err = r.dailyPayments(ctx, query) - return err - }) - run(func() error { - var err error - settlements, err = r.dailySettlements(ctx, query) - return err - }) - run(func() error { - var err error - estimates, err = r.dailyEstimates(ctx, query) - return err - }) - wg.Wait() - close(errCh) - for err := range errCh { - if err != nil { - return dashboardDailyResult{}, err +func (r disbursementItemRow) toDTO() DisbursementItemDTO { + phone := strings.TrimSpace(r.PayeePhone) + if phone == "" && r.SourceType == "platform_managed" && len(r.SourcePayload) > 0 { + var payload struct { + ContactPhone string `json:"contactPhone"` + } + if json.Unmarshal(r.SourcePayload, &payload) == nil { + phone = strings.TrimSpace(payload.ContactPhone) } } - - paidOrders, err := r.dailyPaidOrders(ctx, query) - if err != nil { - return dashboardDailyResult{}, err + return DisbursementItemDTO{ + SourceType: r.SourceType, + SourceID: r.SourceID, + BusinessNo: r.BusinessNo, + OrderID: r.OrderID, + WithdrawalID: r.WithdrawalID, + UserID: r.UserID, + PayeeName: r.PayeeName, + PayeePhone: phone, + UploaderName: r.UploaderName, + SourceChannel: r.SourceChannel, + AccountType: r.AccountType, + AccountName: r.AccountName, + AccountNo: r.AccountNo, + BankName: r.BankName, + AmountCent: r.AmountCent, + FeeCent: r.FeeCent, + ActualAmountCent: r.ActualAmountCent, + Status: r.Status, + RawStatus: r.RawStatus, + BusinessCreatedAt: r.BusinessCreatedAt, + PaidAt: r.PaidAt, + OperatorID: r.OperatorID, + OperatorName: r.OperatorName, + Remark: r.Remark, + Category: r.Category, + CustomCategoryName: r.CustomCategoryName, + VoucherURL: r.VoucherURL, + VoidedAt: r.VoidedAt, + VoidedBy: r.VoidedBy, + VoidedByName: r.VoidedByName, + VoidReason: r.VoidReason, } - - pickupProfits := make([]dailyPickupProfitRow, 0) - if err := db.Table("admin_pickups"). - Select(`DATE(completed_at) AS date, - COALESCE(SUM(profit_amount_cent), 0) AS profit_amount_cent, - COUNT(id) AS completed_count`). - Where("status = ?", "completed"). - Where("completed_at >= ? AND completed_at <= ?", query.StartDate, query.EndDate). - Group("DATE(completed_at)"). - Scan(&pickupProfits).Error; err != nil { - return dashboardDailyResult{}, err - } - pickupAdjustments := make([]dailyPickupAdjustmentRow, 0) - if err := db.Table("admin_pickup_financial_adjustments AS fa"). - Select(`DATE(fa.created_at) AS date, - COALESCE(SUM(fa.profit_delta_cent), 0) AS profit_amount_cent`). - Joins("JOIN admin_pickups AS p ON p.id = fa.pickup_id AND p.status = ?", "completed"). - Where("fa.created_at >= ? AND fa.created_at <= ?", query.StartDate, query.EndDate). - Group("DATE(fa.created_at)"). - Scan(&pickupAdjustments).Error; err != nil { - return dashboardDailyResult{}, err - } - - // 取消提号按取消日统计,与「已付款订单数」中的提号创建口径区分开。 - pickupCancelled, err := r.dailyPickupCancelled(ctx, query) - if err != nil { - return dashboardDailyResult{}, err - } - - // 每日预计收入:尚未结算订单的下单预估平台手续费,按下单日期归集,口径与 summary 一致。 - disbursements, err := r.dailyDisbursements(ctx, query) - if err != nil { - return dashboardDailyResult{}, err - } - operatingExpenses, err := r.dailyOperatingExpenses(ctx, query) - if err != nil { - return dashboardDailyResult{}, err - } - - itemsByDate := make(map[string]FinanceDailyDTO) - for day := dayStart(query.StartDate); !day.After(query.EndDate); day = day.AddDate(0, 0, 1) { - date := day.Format("2006-01-02") - itemsByDate[date] = FinanceDailyDTO{Date: date} - } - for _, row := range payments { - date := dailyDateKey(row.Date) - item := itemsByDate[date] - item.Date = date - item.TotalFlowAmountCent = row.TotalFlowAmountCent - item.TotalRefundAmountCent = row.TotalRefundAmountCent - item.PendingRefundAmountCent = row.PendingRefundAmountCent - item.ChannelNetAmountCent = row.TotalFlowAmountCent - row.TotalRefundAmountCent - item.SuccessfulPayCount = row.SuccessfulPayCount - item.SuccessfulRefundCount = row.FullRefundCount + row.PartialRefundCount - item.FullRefundCount = row.FullRefundCount - item.PartialRefundCount = row.PartialRefundCount - item.PendingRefundCount = row.PendingRefundCount - item.NormalFullRefundCount = row.NormalFullRefundCount - itemsByDate[date] = item - } - for _, row := range paidOrders { - date := dailyDateKey(row.Date) - item := itemsByDate[date] - item.Date = date - item.PaidOrderCount = row.PaidOrderCount - itemsByDate[date] = item - } - for _, row := range settlements { - date := dailyDateKey(row.Date) - item := itemsByDate[date] - item.Date = date - item.PlatformIncomeAmountCent = row.PlatformIncomeAmountCent - item.OwnerShouldIncomeAmountCent = row.OwnerShouldIncomeAmountCent - item.OwnerWalletIncomeAmountCent = row.OwnerWalletIncomeAmountCent - item.OwnerEffectiveSettlementAmountCent = row.OwnerEffectiveSettlementAmountCent - item.OfflineSettlementAmountCent = row.OfflineSettlementAmountCent - item.OfflineSettlementPendingAmountCent = row.OfflineSettlementPendingAmountCent - item.SettlementDiffAmountCent = row.OwnerShouldIncomeAmountCent - row.OwnerEffectiveSettlementAmountCent - item.SettledOrderCount = row.SettledOrderCount - item.SalesCount = row.SettledOrderCount - item.OfflineSettlementPendingCount = row.OfflineSettlementPendingCount - itemsByDate[date] = item - } - for _, row := range pickupProfits { - date := dailyDateKey(row.Date) - item := itemsByDate[date] - item.Date = date - item.PlatformIncomeAmountCent += row.ProfitAmountCent - item.PickupCompletedCount = row.CompletedCount - item.SalesCount += row.CompletedCount - itemsByDate[date] = item - } - for _, row := range pickupAdjustments { - date := dailyDateKey(row.Date) - item := itemsByDate[date] - item.Date = date - item.PlatformIncomeAmountCent += row.ProfitAmountCent - itemsByDate[date] = item - } - for _, row := range pickupCancelled { - date := dailyDateKey(row.Date) - item := itemsByDate[date] - item.Date = date - item.PickupCancelledCount = row.Count - itemsByDate[date] = item - } - for _, row := range estimates { - date := dailyDateKey(row.Date) - item := itemsByDate[date] - item.Date = date - item.EstimatedIncomeAmountCent = row.EstimatedIncomeAmountCent - itemsByDate[date] = item - } - for _, row := range disbursements { - date := dailyDateKey(row.Date) - item := itemsByDate[date] - item.Date = date - item.OfflineSettlementPaidAmountCent = row.OfflineSettlementPaidAmountCent - item.OfflineSettlementPaidCount = row.OfflineSettlementPaidCount - item.WithdrawalPaidAmountCent = row.WithdrawalPaidAmountCent - item.WithdrawalPaidCount = row.WithdrawalPaidCount - item.ManualPaidAmountCent = row.ManualPaidAmountCent - item.ManualPaidCount = row.ManualPaidCount - item.DisbursementPaidAmountCent = row.OfflineSettlementPaidAmountCent + row.WithdrawalPaidAmountCent + row.ManualPaidAmountCent - item.DisbursementPaidCount = row.OfflineSettlementPaidCount + row.WithdrawalPaidCount + row.ManualPaidCount - itemsByDate[date] = item - } - for _, row := range operatingExpenses { - date := dailyDateKey(row.Date) - item := itemsByDate[date] - item.Date = date - item.OperatingExpenseAmountCent = row.AmountCent - item.OperatingExpenseCount = row.Count - itemsByDate[date] = item - } - - items := make([]FinanceDailyDTO, 0, len(itemsByDate)) - for day := dayStart(query.StartDate); !day.After(query.EndDate); day = day.AddDate(0, 0, 1) { - items = append(items, itemsByDate[day.Format("2006-01-02")]) - } - return dashboardDailyResult{ - Items: items, - Summary: summaryFromDailyRows(payments, settlements, estimates), - Mohong: mohongSummaryFromDailyRows(payments), - OperatingExpense: operatingExpenseSummaryFromDailyRows(operatingExpenses), - }, nil -} - -func (r *Repository) dailyEstimates(ctx context.Context, query DashboardQuery) ([]dailyEstimatedRow, error) { - rows := make([]dailyEstimatedRow, 0) - err := r.db.WithContext(ctx).Table("rental_orders"). - Select(`DATE(created_at) AS date, - COALESCE(SUM(platform_fee_cent), 0) AS estimated_income_amount_cent, - COUNT(id) AS pending_settle_order_count`). - Where("settlement_status NOT IN ?", settledSettlementStatuses()). - Where("status NOT IN ?", nonBillableOrderStatuses()). - Where("created_at >= ? AND created_at <= ?", query.StartDate, query.EndDate). - Group("DATE(created_at)"). - Scan(&rows).Error - return rows, err -} - -func (r *Repository) dailySettlements(ctx context.Context, query DashboardQuery) ([]dailySettlementRow, error) { - db := r.db.WithContext(ctx) - rows := make([]dailySettlementRow, 0) - err := db.Table("rental_orders AS ro"). - Select(`DATE(ro.settled_at) AS date, - COALESCE(SUM(oc.platform_fee_cent), 0) AS platform_income_amount_cent, - COALESCE(SUM(oc.owner_income_amount_cent), 0) AS owner_should_income_amount_cent, - COALESCE(SUM(COALESCE(w.owner_wallet_income_amount_cent, 0)), 0) AS owner_wallet_income_amount_cent, - COALESCE(SUM(CASE WHEN ro.settlement_mode = 'platform_managed' - THEN COALESCE(ro.offline_settlement_amount_cent, 0) - ELSE COALESCE(w.owner_wallet_income_amount_cent, 0) - END), 0) AS owner_effective_settlement_amount_cent, - COALESCE(SUM(CASE WHEN ro.settlement_mode = 'platform_managed' - THEN COALESCE(ro.offline_settlement_amount_cent, 0) - ELSE 0 - END), 0) AS offline_settlement_amount_cent, - COALESCE(SUM(CASE WHEN ro.settlement_mode = 'platform_managed' - AND COALESCE(NULLIF(ro.offline_settlement_status, ''), 'none') = 'pending' - THEN COALESCE(ro.offline_settlement_amount_cent, 0) - ELSE 0 - END), 0) AS offline_settlement_pending_amount_cent, - COALESCE(SUM(CASE WHEN ro.settlement_mode = 'platform_managed' - AND COALESCE(NULLIF(ro.offline_settlement_status, ''), 'none') = 'pending' - AND COALESCE(ro.offline_settlement_amount_cent, 0) > 0 - THEN 1 - ELSE 0 - END), 0) AS offline_settlement_pending_count, - COALESCE(SUM(CASE WHEN ro.refund_status = 'refunding' - OR ABS(COALESCE(oc.owner_income_amount_cent, 0) - CASE WHEN ro.settlement_mode = 'platform_managed' - THEN COALESCE(ro.offline_settlement_amount_cent, 0) - ELSE COALESCE(w.owner_wallet_income_amount_cent, 0) - END) >= ? - OR EXISTS ( - SELECT 1 FROM payment_orders AS exception_payment - WHERE exception_payment.order_id = ro.id - AND exception_payment.biz_type IN ? - AND exception_payment.status IN ? - AND exception_payment.amount_cent > 0 - ) - THEN 1 - ELSE 0 - END), 0) AS financial_exception_count, - COUNT(ro.id) AS settled_order_count`, settlementDiffThresholdCent, refundBizTypes(), []string{"refunding", "failed"}). - Joins("JOIN order_checkouts AS oc ON oc.order_id = ro.id AND oc.status = 'accepted'"). - Joins("LEFT JOIN (?) AS w ON w.order_id = ro.id", ownerWalletIncomeForSettledOrdersSubquery(db, query)). - Where("ro.settled_at >= ? AND ro.settled_at <= ?", query.StartDate, query.EndDate). - Group("DATE(ro.settled_at)"). - Scan(&rows).Error - return rows, err -} - -func summaryFromDailyRows(payments []dailyPaymentRow, settlements []dailySettlementRow, estimates []dailyEstimatedRow) FinanceSummaryDTO { - var summary FinanceSummaryDTO - for _, row := range payments { - summary.TotalFlowAmountCent += row.TotalFlowAmountCent - summary.TotalRefundAmountCent += row.TotalRefundAmountCent - summary.PendingRefundAmountCent += row.PendingRefundAmountCent - summary.SuccessfulPayCount += row.SuccessfulPayCount - summary.FullRefundCount += row.FullRefundCount - summary.PartialRefundCount += row.PartialRefundCount - summary.PendingRefundCount += row.PendingRefundCount - } - for _, row := range settlements { - summary.NormalOrderProfitAmountCent += row.PlatformIncomeAmountCent - summary.OwnerShouldIncomeAmountCent += row.OwnerShouldIncomeAmountCent - summary.OwnerWalletIncomeAmountCent += row.OwnerWalletIncomeAmountCent - summary.OwnerEffectiveSettlementAmountCent += row.OwnerEffectiveSettlementAmountCent - summary.OfflineSettlementAmountCent += row.OfflineSettlementAmountCent - summary.OfflineSettlementPendingAmountCent += row.OfflineSettlementPendingAmountCent - summary.OfflineSettlementPendingCount += row.OfflineSettlementPendingCount - summary.FinancialExceptionCount += row.FinancialExceptionCount - summary.SettledOrderCount += row.SettledOrderCount - } - for _, row := range estimates { - summary.EstimatedIncomeAmountCent += row.EstimatedIncomeAmountCent - summary.PendingSettleOrderCount += row.PendingSettleOrderCount - } - summary.ChannelNetAmountCent = summary.TotalFlowAmountCent - summary.TotalRefundAmountCent - summary.SuccessfulRefundCount = summary.FullRefundCount + summary.PartialRefundCount - summary.PlatformIncomeAmountCent = summary.NormalOrderProfitAmountCent - summary.SettlementDiffAmountCent = summary.OwnerShouldIncomeAmountCent - summary.OwnerEffectiveSettlementAmountCent - return summary -} - -func summaryWithPickup(summary FinanceSummaryDTO, pickup *PickupSummaryDTO) FinanceSummaryDTO { - if pickup == nil { - return summary - } - summary.PickupProfitAmountCent = pickup.ProfitAmountCent - summary.PickupCompletedCount = pickup.CompletedCount - summary.PlatformIncomeAmountCent = summary.NormalOrderProfitAmountCent + pickup.ProfitAmountCent - summary.OfflineSettlementPendingAmountCent += pickup.PendingAmountCent - summary.OfflineSettlementPendingCount += pickup.PendingCount - return summary -} - -func mohongSummaryFromDailyRows(rows []dailyPaymentRow) MohongSummaryDTO { - var summary MohongSummaryDTO - for _, row := range rows { - summary.FlowAmountCent += row.MohongFlowAmountCent - summary.RefundAmountCent += row.MohongRefundAmountCent - summary.PaidOrderCount += row.MohongPaidOrderCount - } - summary.NetAmountCent = summary.FlowAmountCent - summary.RefundAmountCent - return summary -} - -func operatingExpenseSummaryFromDailyRows(rows []dailyOperatingExpenseRow) OperatingExpenseSummaryDTO { - var summary OperatingExpenseSummaryDTO - for _, row := range rows { - summary.AmountCent += row.AmountCent - summary.Count += row.Count - } - return summary -} - -// dailyPayments 按支付单创建日统计收付款流水与退款笔数, -// normal_full_refund_count 只统计正常(租赁)订单的全额退款,排除撞车商城。 -func (r *Repository) dailyPayments(ctx context.Context, query DashboardQuery) ([]dailyPaymentRow, error) { - rows := make([]dailyPaymentRow, 0) - db := r.db.WithContext(ctx) - err := db.Table("payment_orders AS po"). - Select(`DATE(po.created_at) AS date, - COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'paid' THEN po.amount_cent ELSE 0 END), 0) AS total_flow_amount_cent, - COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'refunded' THEN po.amount_cent ELSE 0 END), 0) AS total_refund_amount_cent, - COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'refunding' THEN po.amount_cent ELSE 0 END), 0) AS pending_refund_amount_cent, - COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'paid' THEN 1 ELSE 0 END), 0) AS successful_pay_count, - COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'refunded' AND po.amount_cent >= COALESCE(orig.amount_cent, 0) THEN 1 ELSE 0 END), 0) AS full_refund_count, - COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'refunded' AND po.amount_cent < COALESCE(orig.amount_cent, 0) THEN 1 ELSE 0 END), 0) AS partial_refund_count, - COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'refunding' THEN 1 ELSE 0 END), 0) AS pending_refund_count, - COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'refunded' AND po.amount_cent >= COALESCE(orig.amount_cent, 0) THEN 1 ELSE 0 END), 0) AS normal_full_refund_count, - COALESCE(SUM(CASE WHEN po.biz_type = 'mohong_pay' AND po.status = 'paid' THEN po.amount_cent ELSE 0 END), 0) AS mohong_flow_amount_cent, - COALESCE(SUM(CASE WHEN po.biz_type = 'mohong_refund' AND po.status = 'refunded' THEN po.amount_cent ELSE 0 END), 0) AS mohong_refund_amount_cent, - COALESCE(SUM(CASE WHEN po.biz_type = 'mohong_pay' AND po.status = 'paid' THEN 1 ELSE 0 END), 0) AS mohong_paid_order_count`, - payBizTypes(), refundBizTypes(), refundBizTypes(), payBizTypes(), refundBizTypes(), refundBizTypes(), refundBizTypes(), normalRefundBizTypes()). - Joins("LEFT JOIN (?) AS orig ON orig.order_id = po.order_id", paymentOriginalAmountForRefundsInRangeSubquery(db, query)). - Where("po.created_at >= ? AND po.created_at <= ?", query.StartDate, query.EndDate). - Group("DATE(po.created_at)"). - Scan(&rows).Error - return rows, err -} - -// dailyPickupCancelled 按取消日统计线下提号取消笔数。 -func (r *Repository) dailyPickupCancelled(ctx context.Context, query DashboardQuery) ([]dailyPickupCancelledRow, error) { - rows := make([]dailyPickupCancelledRow, 0) - err := r.db.WithContext(ctx).Table("admin_pickups"). - Select(`DATE(cancelled_at) AS date, COUNT(id) AS count`). - Where("status = ?", "cancelled"). - Where("cancelled_at >= ? AND cancelled_at <= ?", query.StartDate, query.EndDate). - Group("DATE(cancelled_at)"). - Scan(&rows).Error - return rows, err -} - -// dailyPaidOrders 按实际付款日统计普通租赁订单,并将已完成的线下提号按完成日计入成交。 -func (r *Repository) dailyPaidOrders(ctx context.Context, query DashboardQuery) ([]dailyPaidOrderRow, error) { - items := make([]dailyPaidOrderRow, 0) - err := r.db.WithContext(ctx).Table(`( - SELECT DATE(paid_at) AS date, COUNT(DISTINCT order_id) AS paid_order_count - FROM payment_orders - WHERE biz_type = 'order_pay' AND status = 'paid' AND paid_at >= ? AND paid_at <= ? - GROUP BY DATE(paid_at) - UNION ALL - SELECT DATE(completed_at) AS date, COUNT(id) AS paid_order_count - FROM admin_pickups - WHERE status = 'completed' AND completed_at >= ? AND completed_at <= ? - GROUP BY DATE(completed_at) - ) AS daily_paid_orders`, query.StartDate, query.EndDate, query.StartDate, query.EndDate). - Select("date, SUM(paid_order_count) AS paid_order_count"). - Group("date"). - Scan(&items).Error - return items, err -} - -type dailyPaymentRow struct { - Date string - TotalFlowAmountCent int64 - TotalRefundAmountCent int64 - PendingRefundAmountCent int64 - SuccessfulPayCount int64 - FullRefundCount int64 - PartialRefundCount int64 - PendingRefundCount int64 - NormalFullRefundCount int64 - MohongFlowAmountCent int64 - MohongRefundAmountCent int64 - MohongPaidOrderCount int64 -} - -type dailyPickupCancelledRow struct { - Date string - Count int64 -} - -type dailyPaidOrderRow struct { - Date string - PaidOrderCount int64 -} - -type dailySettlementRow struct { - Date string - PlatformIncomeAmountCent int64 - OwnerShouldIncomeAmountCent int64 - OwnerWalletIncomeAmountCent int64 - OwnerEffectiveSettlementAmountCent int64 - OfflineSettlementAmountCent int64 - OfflineSettlementPendingAmountCent int64 - OfflineSettlementPendingCount int64 - FinancialExceptionCount int64 - SettledOrderCount int64 -} - -type dailyPickupProfitRow struct { - Date string - ProfitAmountCent int64 - CompletedCount int64 -} - -// dailyPickupAdjustmentRow 调整按调整创建日进入当日利润,避免回写历史完成日报。 -type dailyPickupAdjustmentRow struct { - Date string - ProfitAmountCent int64 -} - -type dailyEstimatedRow struct { - Date string - EstimatedIncomeAmountCent int64 - PendingSettleOrderCount int64 } diff --git a/docs/ROLLBACK.sh b/docs/ROLLBACK.sh index ce3f262..6ac6c23 100755 --- a/docs/ROLLBACK.sh +++ b/docs/ROLLBACK.sh @@ -2,6 +2,13 @@ set -eu target=${1:?用法: ROLLBACK.sh <待恢复文件>} -original=/tmp/hfb-finance-dashboard-optimization/dashboard.go.original +case "$target" in + */hfb-dashboard-rollback-copy.go) + original=/tmp/hfb-finance-dashboard-optimization/dashboard.go.original + ;; + *) + original=/tmp/hfb-finance-disbursement-filter/disbursement_list.go.original + ;; +esac test -f "$original" cp "$original" "$target" diff --git a/docs/VERIFICATION.txt b/docs/VERIFICATION.txt index a595f5d..a03ab4f 100644 --- a/docs/VERIFICATION.txt +++ b/docs/VERIFICATION.txt @@ -32,3 +32,33 @@ MIGRATION 命令:goose -dir migrations mysql 'hfb:secret@tcp(127.0.0.1:13306)/hfb_sys?parseTime=true' up;SHOW INDEX FROM rental_orders WHERE Key_name='idx_rental_orders_offline_pending_amount';goose -dir migrations mysql 'hfb:secret@tcp(127.0.0.1:13306)/hfb_sys?parseTime=true' down。 输入:本地 Docker MySQL 的 migration 62 数据库。 字面输出/结果:goose: successfully migrated database to version: 63;索引三列均出现;Down 输出 OK 000063_finance_pending_disbursement_index.sql;删除后恢复原状态;退出状态 0。 + +资金出款操作人筛选验证 + +变更分支/字段:main;adminfinance.DisbursementQuery.Operator/OperatorID、`operator`/`operator_id` 请求参数及资金出款筛选表单。 +原始 `disbursement_list.go` SHA-256:478ffe515a3f452759e191e0b32f8bc22c1ac2f2dde520092cc6c5ee716f1e7c + +四个验证产物: +/Users/yml/codes/hfb_sys/docs/MODIFIED_FILE +/Users/yml/codes/hfb_sys/docs/DIFF_FILE +/Users/yml/codes/hfb_sys/docs/VERIFICATION.txt +/Users/yml/codes/hfb_sys/docs/ROLLBACK.sh + +BASELINE +命令:`go test ./internal/modules/adminfinance -run '^TestDisbursementListCombinesPlatformSettlementsAndWithdrawals$' -count=1 -v` +输入:HEAD 基线代码,SQLite 内存测试数据。 +字面输出/结果:`=== RUN TestDisbursementListCombinesPlatformSettlementsAndWithdrawals`、`--- PASS: TestDisbursementListCombinesPlatformSettlementsAndWithdrawals (0.01s)`、`PASS`、`ok hfb_sys/backend/internal/modules/adminfinance 0.420s`;退出状态 0。 + +MODIFIED +命令:`go test ./internal/modules/adminfinance -run '^TestDisbursementListCombinesPlatformSettlementsAndWithdrawals$' -count=1 -v` +输入:增加操作人昵称筛选断言的修改代码,SQLite 内存测试数据。 +字面输出/结果:`=== RUN TestDisbursementListCombinesPlatformSettlementsAndWithdrawals`、`--- PASS: TestDisbursementListCombinesPlatformSettlementsAndWithdrawals (0.01s)`、`PASS`、`ok hfb_sys/backend/internal/modules/adminfinance 0.200s`;退出状态 0;按操作人“财务甲”返回 7 条且全部匹配;支持 `operator_id` 精确匹配。 + +ROLLBACK +命令:`cp docs/MODIFIED_FILE /tmp/hfb-finance-disbursement-filter/rollback-copy.go && ./docs/ROLLBACK.sh /tmp/hfb-finance-disbursement-filter/rollback-copy.go && cmp /tmp/hfb-finance-disbursement-filter/rollback-copy.go /tmp/hfb-finance-disbursement-filter/disbursement_list.go.original` +输入:修改后的 `MODIFIED_FILE` 副本。 +字面输出/结果:`rollback_cmp_exit=0`;退出状态 0;副本恢复为原始 `disbursement_list.go`,`MODIFIED_FILE` 保持修改后内容(SHA-256 `fac88ec3f2137c68f79a281f24aadb2ddf80922452219716112ae45bdc24d459`)。 + +TESTS +命令:`go test ./...`;`npm run typecheck` +字面输出/结果:后端全量测试 PASS;前端 vue-tsc 类型检查 PASS;退出状态均为 0。 diff --git a/frontend/src/features/admin/api/adminFinance.ts b/frontend/src/features/admin/api/adminFinance.ts index 74145c8..7f17020 100644 --- a/frontend/src/features/admin/api/adminFinance.ts +++ b/frontend/src/features/admin/api/adminFinance.ts @@ -195,6 +195,9 @@ export interface FinanceDisbursementQuery extends FinanceDateQuery { date_type?: string business_no?: string keyword?: string + operator?: string + operator_name?: string + operator_id?: string user_id?: string page?: number page_size?: number @@ -309,6 +312,8 @@ export interface FinanceDetail { export interface FinanceDateQuery { start_date?: string end_date?: string + start_time?: string + end_time?: string } export interface FinanceDetailQuery extends FinanceDateQuery { diff --git a/frontend/src/features/admin/components/AdminListingReviewEvidenceDialog.vue b/frontend/src/features/admin/components/AdminListingReviewEvidenceDialog.vue new file mode 100644 index 0000000..ca5f9ed --- /dev/null +++ b/frontend/src/features/admin/components/AdminListingReviewEvidenceDialog.vue @@ -0,0 +1,310 @@ + + + + + diff --git a/frontend/src/features/admin/components/AdminListingReviewPreviewDialog.vue b/frontend/src/features/admin/components/AdminListingReviewPreviewDialog.vue new file mode 100644 index 0000000..f661eb2 --- /dev/null +++ b/frontend/src/features/admin/components/AdminListingReviewPreviewDialog.vue @@ -0,0 +1,655 @@ + + + + + diff --git a/frontend/src/features/admin/components/AdminListingReviewPriceDialog.vue b/frontend/src/features/admin/components/AdminListingReviewPriceDialog.vue new file mode 100644 index 0000000..e44597e --- /dev/null +++ b/frontend/src/features/admin/components/AdminListingReviewPriceDialog.vue @@ -0,0 +1,347 @@ + + + + + diff --git a/frontend/src/features/admin/components/AdminListingReviewRejectDialog.vue b/frontend/src/features/admin/components/AdminListingReviewRejectDialog.vue new file mode 100644 index 0000000..108a95c --- /dev/null +++ b/frontend/src/features/admin/components/AdminListingReviewRejectDialog.vue @@ -0,0 +1,223 @@ + + + + + diff --git a/frontend/src/features/admin/components/AdminListingReviewShortcutsDialog.vue b/frontend/src/features/admin/components/AdminListingReviewShortcutsDialog.vue new file mode 100644 index 0000000..7c67648 --- /dev/null +++ b/frontend/src/features/admin/components/AdminListingReviewShortcutsDialog.vue @@ -0,0 +1,93 @@ + + + + + diff --git a/frontend/src/features/admin/components/ImageEditorDialog.vue b/frontend/src/features/admin/components/ImageEditorDialog.vue new file mode 100644 index 0000000..5cfdde2 --- /dev/null +++ b/frontend/src/features/admin/components/ImageEditorDialog.vue @@ -0,0 +1,888 @@ + + + + + diff --git a/frontend/src/features/admin/views/AdminFinanceDisbursementsView.css b/frontend/src/features/admin/views/AdminFinanceDisbursementsView.css index a3962ec..fb56dd1 100644 --- a/frontend/src/features/admin/views/AdminFinanceDisbursementsView.css +++ b/frontend/src/features/admin/views/AdminFinanceDisbursementsView.css @@ -239,7 +239,7 @@ .filter-grid { display: grid; - grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); + grid-template-columns: repeat(auto-fit, minmax(210px, 1fr)); gap: 14px 16px; } diff --git a/frontend/src/features/admin/views/AdminFinanceDisbursementsView.vue b/frontend/src/features/admin/views/AdminFinanceDisbursementsView.vue index d5d86f0..faf5ee1 100644 --- a/frontend/src/features/admin/views/AdminFinanceDisbursementsView.vue +++ b/frontend/src/features/admin/views/AdminFinanceDisbursementsView.vue @@ -32,7 +32,7 @@ import { useAdminSessionStore } from '@/stores/adminSession' import { adminPath } from '@/shared/utils/adminPath' import { readError } from '@/shared/utils/error' import { formatCentWithSymbol, yuanToCent } from '@/shared/utils/money' -import { formatDateTime, formatInputDate } from '@/shared/utils/time' +import { formatDateTime } from '@/shared/utils/time' import AdminTablePagination from '../components/AdminTablePagination.vue' import WithdrawalDetailDialog from '../components/WithdrawalDetailDialog.vue' @@ -73,14 +73,89 @@ const createForm = reactive({ voucher_url: '', }) +const defaultStartTime = new Date(2000, 0, 1, 0, 0, 0) +const defaultEndTime = new Date(2000, 0, 1, 23, 59, 59) + +const startTimeShortcuts = [ + { + text: '今天 00:00', + value: () => { + const d = new Date() + d.setHours(0, 0, 0, 0) + return d + }, + }, + { + text: '昨天 00:00', + value: () => { + const d = new Date() + d.setDate(d.getDate() - 1) + d.setHours(0, 0, 0, 0) + return d + }, + }, + { + text: '近7天', + value: () => { + const d = new Date() + d.setDate(d.getDate() - 6) + d.setHours(0, 0, 0, 0) + return d + }, + }, + { + text: '近30天', + value: () => { + const d = new Date() + d.setDate(d.getDate() - 29) + d.setHours(0, 0, 0, 0) + return d + }, + }, + { + text: '本月初', + value: () => { + const d = new Date() + d.setDate(1) + d.setHours(0, 0, 0, 0) + return d + }, + }, +] + +const endTimeShortcuts = [ + { + text: '此刻', + value: () => new Date(), + }, + { + text: '今天 23:59', + value: () => { + const d = new Date() + d.setHours(23, 59, 59, 0) + return d + }, + }, + { + text: '昨天 23:59', + value: () => { + const d = new Date() + d.setDate(d.getDate() - 1) + d.setHours(23, 59, 59, 0) + return d + }, + }, +] + const filters = reactive({ date_type: 'created', - start_date: defaultStartDate(), - end_date: formatInputDate(new Date()), + start_date: defaultStartDateTime(), + end_date: defaultEndDateTime(), source_type: '', status: '', business_no: '', keyword: '', + operator: '', user_id: '', }) @@ -114,12 +189,13 @@ function search() { function resetFilters() { filters.date_type = 'created' - filters.start_date = defaultStartDate() - filters.end_date = formatInputDate(new Date()) + filters.start_date = defaultStartDateTime() + filters.end_date = defaultEndDateTime() filters.source_type = '' filters.status = '' filters.business_no = '' filters.keyword = '' + filters.operator = '' filters.user_id = '' currentPage.value = 1 void loadItems() @@ -261,10 +337,17 @@ function emptySummary(): FinanceDisbursementListSummary { } } -function defaultStartDate() { +function defaultStartDateTime() { const date = new Date() date.setDate(date.getDate() - 29) - return formatInputDate(date) + date.setHours(0, 0, 0, 0) + return formatDateTime(date) +} + +function defaultEndDateTime() { + const date = new Date() + date.setHours(23, 59, 59, 0) + return formatDateTime(date) } function money(cents: number | undefined | null) { @@ -444,29 +527,37 @@ function accountTypeLabel(type: string) {
- + - - + + - + - + @@ -509,6 +600,10 @@ function accountTypeLabel(type: string) { + + + + diff --git a/frontend/src/features/admin/views/AdminListingReviewView.css b/frontend/src/features/admin/views/AdminListingReviewView.css index 20599a7..44a73b6 100644 --- a/frontend/src/features/admin/views/AdminListingReviewView.css +++ b/frontend/src/features/admin/views/AdminListingReviewView.css @@ -1,75 +1,160 @@ +/* ========== Admin Listing Review Page Styling ========== */ .review-page { - min-height: calc(100vh - 128px); + min-height: calc(100vh - 120px); + padding-bottom: 80px; } .review-header { - margin-bottom: 18px; + margin-bottom: 20px; + align-items: center; } +.refresh-stamp { + display: inline-flex; + align-items: center; + gap: 6px; + color: #64748b; + font-size: 13px; + font-weight: 500; + margin-right: 8px; +} + +/* ========== Top Summary Metric Cards ========== */ .review-summary { display: grid; - grid-template-columns: repeat(4, minmax(120px, 1fr)); - gap: 12px; - margin-bottom: 14px; + grid-template-columns: repeat(4, minmax(180px, 1fr)); + gap: 16px; + margin-bottom: 20px; } .summary-card { + position: relative; min-width: 0; - border: 1px solid #e8edf4; - border-radius: 8px; + border: 1px solid #e2e8f0; + border-radius: 12px; background: #ffffff; - padding: 14px 16px; - box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06); + padding: 16px 20px; + box-shadow: 0 1px 3px rgba(15, 23, 42, 0.05); text-align: left; cursor: pointer; - transition: all 0.2s ease; + transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1); + overflow: hidden; +} + +.summary-card-inner { + display: flex; + align-items: center; + gap: 16px; +} + +.summary-card-icon { + display: flex; + align-items: center; + justify-content: center; + width: 48px; + height: 48px; + border-radius: 12px; + font-size: 22px; + flex-shrink: 0; + transition: transform 0.25s ease; +} + +.summary-card-text { + min-width: 0; + display: flex; + flex-direction: column; +} + +.summary-card-text span { + color: #64748b; + font-size: 13px; + font-weight: 600; + line-height: 1.2; +} + +.summary-card-text strong { + margin: 4px 0 2px; + color: #0f172a; + font-size: 26px; + font-weight: 800; + line-height: 1.1; + font-variant-numeric: tabular-nums; +} + +.summary-card-text small { + color: #94a3b8; + font-size: 12px; + font-weight: 500; +} + +/* Thematic colors for cards */ +.summary-card--all .summary-card-icon { + background: #eff6ff; + color: #2563eb; +} + +.summary-card--external .summary-card-icon { + background: #f5f3ff; + color: #7c3aed; +} + +.summary-card--warning .summary-card-icon { + background: #fffbeb; + color: #d97706; +} + +.summary-card--danger .summary-card-icon { + background: #fef2f2; + color: #dc2626; } .summary-card:hover { - border-color: #1477ff; - box-shadow: 0 2px 8px rgba(20, 119, 255, 0.15); - transform: translateY(-1px); + transform: translateY(-2px); + box-shadow: 0 8px 24px rgba(15, 23, 42, 0.08); } -.summary-card.active { - border-color: #1477ff; - background: #1477ff; - box-shadow: 0 2px 8px rgba(20, 119, 255, 0.25); +.summary-card:hover .summary-card-icon { + transform: scale(1.08); } -.summary-card.active span { - color: #ffffff; +/* Active Filter States */ +.summary-card--all.active { + border-color: #2563eb; + background: #f0f7ff; + box-shadow: + 0 0 0 1px #2563eb, + 0 6px 20px rgba(37, 99, 235, 0.15); } -.summary-card.active strong { - color: #ffffff; +.summary-card--external.active { + border-color: #7c3aed; + background: #faf5ff; + box-shadow: + 0 0 0 1px #7c3aed, + 0 6px 20px rgba(124, 58, 237, 0.15); } -.review-summary span, -.queue-footer span, -.panel-title span, -.inventory-grid span, -.resource-table span, -.price-decision-card span, -.adjust-current span, -.adjust-field span { - color: #8f9bba; - font-size: 12px; - font-weight: 600; +.summary-card--warning.active { + border-color: #d97706; + background: #fffdf5; + box-shadow: + 0 0 0 1px #d97706, + 0 6px 20px rgba(217, 119, 6, 0.15); } -.review-summary strong { - display: block; - margin-top: 5px; - color: #1b2559; - font-size: 24px; - font-weight: 800; +.summary-card--danger.active { + border-color: #dc2626; + background: #fff5f5; + box-shadow: + 0 0 0 1px #dc2626, + 0 6px 20px rgba(220, 38, 38, 0.15); } +/* ========== Review Workbench Split Layout ========== */ .review-workbench { display: grid; - grid-template-columns: minmax(360px, 420px) minmax(0, 1fr); - gap: 16px; + grid-template-columns: 380px minmax(0, 1fr); + gap: 20px; align-items: start; } @@ -80,432 +165,1120 @@ min-width: 0; } +/* ========== Left: Queue Sidebar ========== */ .review-queue { position: sticky; top: 16px; - border-radius: 8px; + height: calc(100vh - 120px); + display: flex; + flex-direction: column; + border: 1px solid #e2e8f0; + border-radius: 12px; background: #ffffff; - padding: 14px; - box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04); + padding: 16px; + box-shadow: 0 1px 4px rgba(15, 23, 42, 0.05); } .queue-toolbar { - display: grid; - grid-template-columns: minmax(0, 1fr) 120px; + display: flex; + flex-direction: column; gap: 10px; margin-bottom: 12px; + padding-bottom: 12px; + border-bottom: 1px solid #f1f5f9; +} + +.queue-filter-row { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 8px; +} + +.queue-select { + width: 100%; +} + +.queue-count-strip { + display: flex; + align-items: center; + justify-content: space-between; + color: #64748b; + font-size: 12px; + font-weight: 600; +} + +.shortcut-tip { + color: #94a3b8; + font-size: 11px; } .queue-list { + flex: 1; + min-height: 0; + overflow-y: auto; + display: flex; + flex-direction: column; + gap: 10px; + padding-right: 4px; +} + +/* Queue Card Item */ +.queue-item { + position: relative; + width: 100%; + min-height: 104px; + flex-shrink: 0; + display: flex; + border: 1px solid #e2e8f0; + border-radius: 10px; + background: #ffffff; + padding: 0; + text-align: left; + cursor: pointer; + overflow: hidden; + transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1); +} + +.item-accent-bar { + width: 4px; + background: #94a3b8; + flex-shrink: 0; + transition: + width 0.2s ease, + background 0.2s ease; +} + +.queue-item.has-default-shot .item-accent-bar { + background: #f59e0b; +} + +.queue-item.has-deposit-risk .item-accent-bar { + background: #f97316; +} + +.queue-item.has-ban .item-accent-bar { + background: #ef4444; +} + +.queue-card-content { + flex: 1; + min-width: 0; + padding: 12px 14px; display: flex; flex-direction: column; gap: 8px; - max-height: calc(100vh - 300px); - overflow: auto; - padding-right: 2px; } -.queue-item { - width: 100%; - min-height: 112px; - border: 1px solid #e8ecf1; - border-radius: 8px; - background: #ffffff; - padding: 12px; - text-align: left; - cursor: pointer; - transition: - border-color 0.2s, - box-shadow 0.2s, - background 0.2s; -} - -.queue-item:hover, -.queue-item.active { - border-color: #4f7cff; - background: #f8faff; - box-shadow: 0 6px 18px rgba(79, 124, 255, 0.1); -} - -.queue-title-row, -.queue-footer, -.panel-title, -.hero-title { +.queue-top-line { display: flex; - align-items: flex-start; + align-items: center; justify-content: space-between; - gap: 12px; } -.queue-title-row strong { - display: block; - min-width: 0; - color: #1b2559; - font-size: 14px; - font-weight: 800; - line-height: 1.4; -} - -.queue-title-row span { - flex-shrink: 0; - color: #4f7cff; - font-weight: 800; -} - -.queue-title-row .queue-code { - display: inline-flex; - margin-bottom: 4px; - padding: 2px 7px; - border-radius: 999px; - background: #eff6ff; - font-size: 12px; -} - -.queue-meta, -.risk-strip, -.skin-list, -.reject-reasons { - display: flex; - flex-wrap: wrap; - gap: 8px; -} - -.queue-meta { - margin: 10px 0; -} - -.queue-meta span { - border-radius: 6px; - background: #f0f2f5; - padding: 4px 7px; - color: #4b5563; +.queue-code { + color: #64748b; font-size: 12px; font-weight: 700; + font-family: monospace; } -.queue-footer { +.queue-coin { + display: inline-flex; align-items: center; + gap: 4px; + color: #b45309; + background: #fef3c7; + padding: 2px 7px; + border-radius: 6px; + font-size: 12px; + font-weight: 800; } -.queue-tags, -.panel-tags { +.queue-main-row { display: flex; - flex-wrap: wrap; - justify-content: flex-end; + align-items: flex-start; + gap: 10px; +} + +.queue-thumb { + position: relative; + width: 52px; + height: 52px; + border-radius: 8px; + overflow: hidden; + background: #f1f5f9; + flex-shrink: 0; + border: 1px solid #e2e8f0; +} + +.queue-thumb img { + width: 100%; + height: 100%; + object-fit: cover; + display: block; +} + +.thumb-warning-badge { + position: absolute; + bottom: 0; + left: 0; + right: 0; + background: rgba(217, 119, 6, 0.9); + color: #ffffff; + font-size: 9px; + font-weight: 700; + text-align: center; + line-height: 13px; +} + +.queue-main-info { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; gap: 6px; } +.queue-title { + color: #0f172a; + font-size: 13px; + font-weight: 700; + line-height: 1.35; + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; +} + +.queue-specs { + display: flex; + flex-wrap: wrap; + gap: 4px; +} + +.spec-pill { + padding: 1px 5px; + border-radius: 4px; + background: #f1f5f9; + color: #475569; + font-size: 11px; + font-weight: 600; + line-height: 16px; + white-space: nowrap; +} + +.queue-footer { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + padding-top: 6px; + border-top: 1px solid #f8fafc; +} + +.queue-price-block { + display: flex; + align-items: baseline; + gap: 6px; +} + +.queue-price { + color: #2563eb; + font-size: 14px; + font-weight: 800; +} + +.queue-deposit { + color: #64748b; + font-size: 11px; +} + +.queue-tags { + display: flex; + flex-wrap: wrap; + justify-content: flex-end; + gap: 4px; +} + +/* Hover & Active Queue Item */ +.queue-item:hover { + border-color: #93c5fd; + background: #f8fafc; + transform: translateX(2px); +} + +.queue-item.active { + border-color: #2563eb; + background: #f0f7ff; + box-shadow: + 0 0 0 1px #2563eb, + 0 4px 16px rgba(37, 99, 235, 0.12); +} + +.queue-item.active .item-accent-bar { + background: #2563eb; + width: 6px; +} + +.queue-item.active .queue-title { + color: #1d4ed8; +} + +/* ========== Right: Audit Workbench Main Area ========== */ .review-detail { display: flex; flex-direction: column; - gap: 14px; + gap: 18px; } .review-hero-panel, .review-panel { - border-radius: 8px; + border: 1px solid #e2e8f0; + border-radius: 12px; background: #ffffff; - padding: 18px; - box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04); + padding: 20px 24px; + box-shadow: 0 1px 4px rgba(15, 23, 42, 0.04); } -.hero-title h2, -.panel-title h3 { - margin: 0; - color: #1b2559; - font-size: 18px; - font-weight: 800; - line-height: 1.35; +/* Hero Panel */ +.hero-top-row { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 16px; + margin-bottom: 12px; } -.hero-title p { - margin: 0 0 6px; - color: #8f9bba; - font-size: 12px; +.hero-meta-strip { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 10px; +} + +.hero-code-badge { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 4px 10px; + border-radius: 6px; + background: #f1f5f9; + color: #334155; + font-size: 13px; font-weight: 700; + font-family: monospace; + cursor: pointer; + transition: all 0.2s; +} + +.hero-code-badge:hover { + background: #e2e8f0; + color: #0f172a; +} + +.copy-icon { + font-size: 13px; +} + +.hero-submit-time { + display: inline-flex; + align-items: center; + gap: 5px; + color: #64748b; + font-size: 12px; } .hero-actions { display: flex; - flex-wrap: wrap; - justify-content: flex-end; - gap: 8px; -} - -.risk-strip { - margin-top: 14px; -} - -.review-metrics { - grid-template-columns: repeat(5, minmax(132px, 1fr)); - gap: 12px; - margin-bottom: 0; -} - -.review-metrics .metric-card { - border-radius: 8px; - padding: 16px; -} - -.review-metrics .metric-card strong { - font-size: 20px; -} - -.review-grid { - display: grid; - grid-template-columns: repeat(2, minmax(0, 1fr)); - gap: 14px; -} - -.panel-title { align-items: center; - margin-bottom: 14px; + gap: 8px; + flex-wrap: wrap; } -.price-panel-title p { - margin: 5px 0 0; - color: #8f9bba; +.action-link { + text-decoration: none; +} + +.btn-approve { + font-weight: 700; + box-shadow: 0 2px 8px rgba(37, 99, 235, 0.25); +} + +.hero-title { + margin: 0 0 14px; + color: #0f172a; + font-size: 22px; + font-weight: 800; + line-height: 1.35; +} + +.risk-tag-strip { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-top: 4px; +} + +/* Panel Heading Component */ +.panel-heading { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + margin-bottom: 16px; + padding-bottom: 12px; + border-bottom: 1px solid #f1f5f9; +} + +.heading-left { + display: flex; + align-items: center; + gap: 10px; +} + +.heading-icon { + font-size: 20px; + color: #2563eb; +} + +.heading-left h3 { + margin: 0; + color: #0f172a; + font-size: 16px; + font-weight: 800; + line-height: 1.2; +} + +.heading-left p { + margin: 3px 0 0; + color: #64748b; + font-size: 12px; +} + +/* ========== Interactive Pricing Pipeline ========== */ +.pricing-pipeline { + display: grid; + grid-template-columns: 1fr auto 1fr auto 1.15fr 1fr; + align-items: center; + gap: 12px; +} + +.pipeline-card { + display: flex; + flex-direction: column; + gap: 6px; + min-height: 130px; + border: 1px solid #e2e8f0; + border-radius: 10px; + background: #f8fafc; + padding: 14px 16px; +} + +.pipeline-card .card-badge { + display: inline-block; + align-self: flex-start; + padding: 2px 8px; + border-radius: 4px; + background: #e2e8f0; + color: #475569; + font-size: 11px; + font-weight: 700; +} + +.pipeline-card .card-value { + color: #0f172a; + font-size: 24px; + font-weight: 800; + line-height: 1.15; +} + +.pipeline-card .card-meta { + color: #475569; font-size: 12px; font-weight: 600; } -.price-decision-grid { - display: grid; - grid-template-columns: repeat(4, minmax(150px, 1fr)); - gap: 12px; +.pipeline-card .card-breakdown { + margin-top: auto; + display: flex; + align-items: center; + justify-content: space-between; + gap: 6px; + color: #64748b; + font-size: 11px; + font-weight: 500; + padding-top: 6px; + border-top: 1px solid rgba(0, 0, 0, 0.05); } -.price-decision-card { - display: grid; - gap: 7px; - min-width: 0; - min-height: 128px; - border: 1px solid #e8ecf1; - border-radius: 8px; - background: #f8f9fe; - padding: 14px; -} - -.price-decision-card strong { - color: #1b2559; - font-size: 24px; - font-weight: 900; - line-height: 1.1; -} - -.price-decision-card p, -.price-decision-card small { - margin: 0; - color: #4b5563; - font-size: 12px; - font-weight: 700; - line-height: 1.45; -} - -.price-decision-card small { - color: #8f9bba; -} - -.price-decision-card.buyer { - border-color: #bfdbfe; - background: #eff6ff; -} - -.price-decision-card.buyer strong { - color: #2563eb; -} - -.price-decision-card.rule { +.pipeline-card--rule { border-color: #fed7aa; background: #fff7ed; } -.price-decision-card.rule strong { +.pipeline-card--rule .card-badge { + background: #ffedd5; + color: #c2410c; +} + +.pipeline-card--rule .markup-value { color: #ea580c; } -.price-decision-card.deposit { +.admin-reason { + color: #ea580c; + font-weight: 700; +} + +.pipeline-card--buyer { + border: 2px solid #2563eb; + background: linear-gradient(135deg, #eff6ff 0%, #e0f2fe 100%); + box-shadow: 0 4px 16px rgba(37, 99, 235, 0.12); +} + +.pipeline-card--buyer .card-badge--highlight { + background: #2563eb; + color: #ffffff; +} + +.pipeline-card--buyer .card-value--highlight { + color: #1d4ed8; + font-size: 26px; +} + +.pipeline-card--deposit { border-color: #e0e7ff; background: #f5f7ff; } -.detail-list { - display: grid; - gap: 10px; - margin: 0; +.pipeline-card--deposit .card-badge { + background: #ede9fe; + color: #6d28d9; } -.detail-list div { - display: grid; - grid-template-columns: 86px minmax(0, 1fr); - gap: 10px; - align-items: start; +.pipeline-arrow { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 4px; + color: #94a3b8; + font-size: 18px; } -.detail-list dt { - color: #8f9bba; - font-size: 12px; +.arrow-label { + font-size: 10px; + font-weight: 700; + color: #94a3b8; +} + +.warning-text { + color: #dc2626 !important; font-weight: 700; } -.detail-list dd { - min-width: 0; - margin: 0; - color: #1f2937; - font-size: 13px; - font-weight: 700; - line-height: 1.45; - overflow-wrap: anywhere; -} - -.inventory-grid { +/* ========== Dual Columns: Core Specs Grid ========== */ +.review-grid { display: grid; - grid-template-columns: repeat(3, minmax(110px, 1fr)); - gap: 10px; - margin-bottom: 12px; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 18px; } -.inventory-grid div { - border-radius: 8px; - background: #f8f9fe; - padding: 12px; -} - -.inventory-grid strong { - display: block; - margin-top: 4px; - color: #1b2559; - font-size: 22px; - font-weight: 900; -} - -.resource-table { +.spec-grid { display: grid; - gap: 8px; - margin-bottom: 12px; -} - -.resource-table div { - display: grid; - grid-template-columns: minmax(120px, 1fr) 72px minmax(120px, 1fr); - gap: 10px; - align-items: center; - border-bottom: 1px solid #f0f2f5; - padding-bottom: 8px; -} - -.resource-table strong { - color: #1f2937; - font-size: 13px; - font-weight: 800; -} - -.resource-table em { - color: #8f9bba; - font-size: 12px; - font-style: normal; - font-weight: 600; -} - -.skin-list { - align-items: center; -} - -.skin-list > span { - color: #8f9bba; - font-size: 13px; -} - -.screenshot-grid { - display: grid; - grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); + grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; } -.screenshot-tile { +.spec-item { + display: flex; + flex-direction: column; + gap: 4px; + padding: 10px 12px; + border-radius: 8px; + background: #f8fafc; + border: 1px solid #f1f5f9; +} + +.spec-item--full { + grid-column: 1 / -1; +} + +.spec-label { + color: #64748b; + font-size: 11px; + font-weight: 700; +} + +.spec-val { + color: #0f172a; + font-size: 13px; + font-weight: 700; +} + +.rank-badge { + display: inline-block; + align-self: flex-start; + padding: 2px 8px; + border-radius: 4px; + background: #eff6ff; + color: #2563eb; + font-size: 12px; + font-weight: 800; +} + +.ban-val { + display: flex; + align-items: center; + gap: 6px; + font-weight: 700; +} + +.safe-icon { + color: #16a34a; + font-size: 16px; +} + +.ban-icon { + color: #dc2626; + font-size: 16px; +} + +.spec-item.ban-warning { + border-color: #fca5a5; + background: #fef2f2; +} + +.spec-item.ban-warning .spec-val { + color: #b91c1c; +} + +.copyable-val { + display: flex; + align-items: center; + justify-content: space-between; +} + +/* ========== Inventory & Consumables ========== */ +.consumable-total-badge { + display: flex; + align-items: center; + gap: 8px; + padding: 4px 10px; + border-radius: 6px; + background: #f1f5f9; + color: #475569; + font-size: 12px; +} + +.consumable-total-badge strong { + color: #2563eb; + font-size: 14px; + font-weight: 800; +} + +.heavy-gear-grid { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 12px; + margin-bottom: 14px; +} + +.gear-card { + display: flex; + align-items: center; + gap: 14px; + padding: 14px; + border-radius: 10px; + border: 1px solid #e2e8f0; + background: #f8fafc; +} + +.gear-icon { + font-size: 28px; +} + +.gear-info { + display: flex; + flex-direction: column; +} + +.gear-info span { + color: #64748b; + font-size: 12px; + font-weight: 600; +} + +.gear-info strong { + color: #0f172a; + font-size: 20px; + font-weight: 900; +} + +.gear-info em { + color: #64748b; + font-size: 12px; + font-style: normal; + font-weight: normal; +} + +.resource-pill-grid { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-bottom: 14px; +} + +.resource-chip { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 4px 10px; + border-radius: 6px; + background: #f1f5f9; + font-size: 12px; +} + +.res-name { + color: #334155; + font-weight: 600; +} + +.res-qty { + color: #2563eb; + font-weight: 800; +} + +.res-mode { + color: #64748b; +} + +.skins-section { + padding-top: 12px; + border-top: 1px solid #f1f5f9; +} + +.skins-header { + margin-bottom: 8px; + color: #475569; + font-size: 12px; + font-weight: 700; +} + +.skin-chips-wrapper { + display: flex; + flex-wrap: wrap; + gap: 6px; +} + +.skin-chip { + display: inline-flex; + padding: 4px 10px; + border-radius: 6px; + background: #ecfdf5; + border: 1px solid #a7f3d0; + color: #047857; + font-size: 12px; + font-weight: 600; +} + +.empty-skins-tip { + margin: 0; + color: #94a3b8; + font-size: 12px; +} + +/* ========== Verification Checklist & Screenshot Gallery ========== */ +.verification-checklist { + display: grid; + grid-template-columns: repeat(5, minmax(0, 1fr)); + gap: 10px; + margin-bottom: 16px; +} + +.check-item { + display: flex; + align-items: center; + gap: 8px; + padding: 8px 12px; + border-radius: 8px; + border: 1px solid #e2e8f0; + background: #f8fafc; + font-size: 12px; +} + +.check-icon { + font-size: 16px; + flex-shrink: 0; +} + +.check-label { + flex: 1; + min-width: 0; + font-weight: 700; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.check-status-tag { + font-size: 11px; + font-weight: 600; +} + +.check-item--provided { + border-color: #bbf7d0; + background: #f0fdf4; + color: #15803d; +} + +.check-item--provided .check-icon { + color: #16a34a; +} + +.check-item--default { + border-color: #fde68a; + background: #fffbeb; + color: #b45309; +} + +.check-item--default .check-icon { + color: #d97706; +} + +.check-item--missing { + border-color: #e2e8f0; + background: #f8fafc; + color: #94a3b8; +} + +.check-item--missing .check-icon { + color: #cbd5e1; +} + +.screenshot-gallery-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); + gap: 14px; +} + +.screenshot-card { position: relative; display: block; width: 100%; aspect-ratio: 16 / 9; + border-radius: 10px; overflow: hidden; - border: 1px solid #e8ecf1; - border-radius: 8px; - background: #f8f9fe; - padding: 0; + border: 1px solid #e2e8f0; + background: #f8fafc; cursor: pointer; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05); + transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1); } -.screenshot-tile img { +.screenshot-card:hover { + transform: translateY(-2px); + box-shadow: 0 8px 24px rgba(15, 23, 42, 0.12); + border-color: #93c5fd; +} + +.image-wrapper { + position: relative; + width: 100%; + height: 100%; +} + +.image-wrapper img { display: block; width: 100%; height: 100%; object-fit: cover; } -.screenshot-tile span { +.default-badge { position: absolute; top: 8px; left: 8px; - border-radius: 6px; - background: rgba(245, 158, 11, 0.95); - padding: 3px 7px; + display: inline-flex; + align-items: center; + gap: 4px; + padding: 2px 7px; + border-radius: 4px; + background: rgba(217, 119, 6, 0.95); + backdrop-filter: blur(4px); + color: #ffffff; + font-size: 11px; + font-weight: 700; + z-index: 2; +} + +.category-tag { + position: absolute; + bottom: 0; + left: 0; + right: 0; + background: linear-gradient( + to top, + rgba(15, 23, 42, 0.9) 0%, + rgba(15, 23, 42, 0.4) 70%, + transparent 100% + ); color: #ffffff; font-size: 12px; - font-weight: 800; + font-weight: 700; + text-align: center; + padding: 14px 6px 6px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + pointer-events: none; + z-index: 2; +} + +.image-overlay { + position: absolute; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + gap: 8px; + flex-wrap: wrap; + padding: 8px; + background: rgba(15, 23, 42, 0.65); + backdrop-filter: blur(3px); + opacity: 0; + transition: opacity 0.2s ease; + z-index: 3; +} + +.screenshot-card:hover .image-overlay { + opacity: 1; +} + +.image-overlay .el-button { + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3); + transition: transform 0.15s ease; +} + +.image-overlay .el-button:hover { + transform: scale(1.1); } .empty-warning { display: flex; align-items: center; - gap: 8px; - min-height: 84px; + gap: 10px; border-radius: 8px; background: #fff7ed; + border: 1px solid #fed7aa; padding: 16px; color: #c2410c; font-weight: 700; + font-size: 13px; } -.dialog-screenshots { - max-height: 540px; - overflow: auto; +/* ========== Floating Sticky Action Dock ========== */ +.floating-dock { + position: fixed; + bottom: 24px; + right: 32px; + z-index: 900; + display: flex; + align-items: center; + justify-content: space-between; + gap: 20px; + padding: 10px 18px; + border-radius: 14px; + background: rgba(255, 255, 255, 0.95); + backdrop-filter: blur(16px); + border: 1px solid rgba(226, 232, 240, 0.9); + box-shadow: + 0 10px 30px rgba(15, 23, 42, 0.15), + 0 2px 8px rgba(15, 23, 42, 0.08); + animation: slideUp 0.3s cubic-bezier(0.16, 1, 0.3, 1); } -.reject-dialog p { - margin-top: 0; +@keyframes slideUp { + from { + opacity: 0; + transform: translateY(20px); + } + to { + opacity: 1; + transform: translateY(0); + } } -.reject-reasons { - margin: 12px 0; -} - -.price-adjust-dialog { - display: grid; - gap: 14px; -} - -.adjust-current { - display: grid; - grid-template-columns: repeat(3, minmax(0, 1fr)); +.dock-info { + display: flex; + align-items: center; gap: 10px; } -.adjust-current div { - display: grid; - gap: 5px; - border-radius: 8px; - background: #f8f9fe; - padding: 12px; +.dock-code { + padding: 2px 6px; + border-radius: 4px; + background: #f1f5f9; + color: #475569; + font-size: 12px; + font-weight: 700; + font-family: monospace; } -.adjust-current strong { - color: #1b2559; - font-size: 18px; - font-weight: 900; +.dock-title { + max-width: 220px; + color: #0f172a; + font-size: 13px; + font-weight: 700; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; } -.adjust-current .preview-value { +.dock-price { color: #2563eb; + font-size: 14px; + font-weight: 800; +} + +.dock-risk-tag { + color: #dc2626; + background: #fee2e2; + padding: 2px 6px; + border-radius: 4px; + font-size: 11px; + font-weight: 700; +} + +.dock-actions { + display: flex; + align-items: center; + gap: 8px; +} + +.btn-approve-dock { + font-weight: 700; + box-shadow: 0 2px 10px rgba(37, 99, 235, 0.3); +} + +/* ========== Dialogs Styling ========== */ +.dialog-item-header { + display: flex; + align-items: center; + gap: 8px; + margin-bottom: 14px; + padding-bottom: 10px; + border-bottom: 1px solid #f1f5f9; +} + +.dialog-code { + padding: 2px 8px; + border-radius: 4px; + background: #f1f5f9; + color: #475569; + font-size: 12px; + font-weight: 700; + font-family: monospace; +} + +.reject-quick-tags { + margin-bottom: 14px; +} + +.quick-tags-title { + margin: 0 0 8px; + color: #64748b; + font-size: 12px; + font-weight: 600; +} + +.quick-tags-list { + display: flex; + flex-wrap: wrap; + gap: 8px; +} + +.quick-reason-pill { + display: inline-flex; + align-items: center; + gap: 4px; + border: 1px solid #cbd5e1; + border-radius: 6px; + background: #ffffff; + padding: 5px 10px; + color: #334155; + font-size: 12px; + font-weight: 600; + cursor: pointer; + transition: all 0.2s ease; +} + +.quick-reason-pill:hover { + border-color: #2563eb; + color: #2563eb; +} + +.quick-reason-pill.selected { + border-color: #2563eb; + background: #eff6ff; + color: #2563eb; +} + +.reject-tip { + display: flex; + align-items: center; + gap: 6px; + margin-top: 10px; + color: #64748b; + font-size: 12px; +} + +/* Price Adjust Modal */ +.adjust-preview-grid { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 12px; + margin-bottom: 16px; +} + +.preview-box { + display: flex; + flex-direction: column; + gap: 4px; + padding: 12px; + border-radius: 8px; + background: #f8fafc; + border: 1px solid #e2e8f0; +} + +.preview-box--highlight { + border-color: #93c5fd; + background: #eff6ff; +} + +.box-label { + color: #64748b; + font-size: 11px; + font-weight: 700; +} + +.box-val { + color: #0f172a; + font-size: 18px; + font-weight: 800; +} + +.highlight-val { + color: #2563eb; +} + +.preview-box small { + color: #64748b; + font-size: 11px; +} + +.adjust-mode-section { + margin-bottom: 14px; } .adjust-mode { @@ -518,73 +1291,182 @@ .adjust-mode :deep(.el-radio-button__inner) { width: 100%; - border-color: #d7deea; - font-weight: 800; + font-weight: 700; } -.adjust-mode :deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) { - border-color: #2563eb; - background: #2563eb; - box-shadow: -1px 0 0 0 #2563eb; +.adjust-fields-box { + display: flex; + flex-direction: column; + gap: 14px; } .adjust-field { - display: grid; - gap: 8px; + display: flex; + flex-direction: column; + gap: 6px; } -.adjust-field > span { - color: #52607a; +.field-title { + color: #475569; font-size: 12px; - font-weight: 800; + font-weight: 700; } .adjust-field :deep(.el-input-number) { width: 100%; } +/* Evidence Dialog */ +.evidence-header-bar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 14px; + margin-bottom: 16px; + padding-bottom: 12px; + border-bottom: 1px solid #f1f5f9; +} + +.evidence-item-info { + display: flex; + align-items: center; + gap: 8px; +} + +.evidence-code { + padding: 2px 8px; + border-radius: 4px; + background: #f1f5f9; + color: #475569; + font-size: 12px; + font-weight: 700; + font-family: monospace; +} + +.dialog-gallery { + max-height: 560px; + overflow-y: auto; + padding-right: 4px; +} + +/* Shortcuts Cheatsheet */ +.shortcuts-guide-table { + display: flex; + flex-direction: column; + gap: 10px; +} + +.shortcut-row { + display: flex; + align-items: center; + gap: 8px; + padding: 8px 12px; + border-radius: 8px; + background: #f8fafc; + font-size: 13px; +} + +.key-badge { + display: inline-block; + padding: 2px 8px; + border: 1px solid #cbd5e1; + border-bottom-width: 2px; + border-radius: 4px; + background: #ffffff; + color: #0f172a; + font-family: monospace; + font-size: 12px; + font-weight: 700; +} + +.key-desc { + margin-left: auto; + color: #475569; + font-weight: 600; +} + +/* Empty Workbench */ .empty-detail { min-height: 420px; display: grid; place-items: center; - border-radius: 8px; + border-radius: 12px; background: #ffffff; } -@media (max-width: 1280px) { +/* ========== Responsive Breakpoints ========== */ +@media (max-width: 1360px) { + .review-workbench { + grid-template-columns: 340px minmax(0, 1fr); + } + + .pricing-pipeline { + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 14px; + } + + .pipeline-arrow { + display: none; + } +} + +@media (max-width: 1100px) { + .review-summary { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + .review-workbench { grid-template-columns: 1fr; } .review-queue { position: static; + height: auto; + max-height: 480px; } - .queue-list { - max-height: none; + .floating-dock { + right: 16px; + left: 16px; + justify-content: space-between; + } + + .dock-title { + max-width: 140px; } } -@media (max-width: 900px) { - .review-summary, - .price-decision-grid, +@media (max-width: 768px) { + .review-summary { + grid-template-columns: 1fr; + } + + .pricing-pipeline { + grid-template-columns: 1fr; + } + .review-grid { grid-template-columns: 1fr; } - .adjust-current { + .heavy-gear-grid { grid-template-columns: 1fr; } - .hero-title { + .verification-checklist { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + + .hero-top-row { flex-direction: column; } .hero-actions { + width: 100%; justify-content: flex-start; } - .queue-toolbar { - grid-template-columns: 1fr; + .floating-dock { + display: none; } } diff --git a/frontend/src/features/admin/views/AdminListingReviewView.vue b/frontend/src/features/admin/views/AdminListingReviewView.vue index 0559b70..5c5590b 100644 --- a/frontend/src/features/admin/views/AdminListingReviewView.vue +++ b/frontend/src/features/admin/views/AdminListingReviewView.vue @@ -1,12 +1,36 @@ diff --git a/frontend/src/features/listings/api/listings.ts b/frontend/src/features/listings/api/listings.ts index def5474..8c20f9b 100644 --- a/frontend/src/features/listings/api/listings.ts +++ b/frontend/src/features/listings/api/listings.ts @@ -332,3 +332,19 @@ export async function rejectListing(id: number, reason: string) { }) return data.data } + +export interface AdminListingScreenshotsPayload { + screenshot_urls: string[] + screenshot_groups?: Record +} + +export async function adminUpdateListingScreenshots( + id: number, + payload: AdminListingScreenshotsPayload +) { + const { data } = await apiClient.put>( + `/admin/listings/${id}/screenshots`, + payload + ) + return data.data +} diff --git a/frontend/src/features/listings/components/HomeBanner.vue b/frontend/src/features/listings/components/HomeBanner.vue index 890e6c7..308009c 100644 --- a/frontend/src/features/listings/components/HomeBanner.vue +++ b/frontend/src/features/listings/components/HomeBanner.vue @@ -10,8 +10,15 @@ interface HomeBannerSlide { image_url?: string } +interface StatItem { + label: string + value: string + hint?: string +} + interface Props { banners: HomeBannerSlide[] + stats?: StatItem[] } const props = defineProps() @@ -45,7 +52,7 @@ function hasSlideCopy(slide: HomeBannerSlide) {