暂存一下,防止丢失
This commit is contained in:
218
internal/query/approval/query.go
Normal file
218
internal/query/approval/query.go
Normal file
@@ -0,0 +1,218 @@
|
||||
// Package approval 提供渠道无关审批实例的读取模型和权限投影。
|
||||
package approval
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/bytedance/sonic"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/middleware"
|
||||
)
|
||||
|
||||
// Viewer 是业务权限 Adapter 判定当前读取主体所需的最小身份。
|
||||
type Viewer struct {
|
||||
AccountID uint
|
||||
UserType int
|
||||
}
|
||||
|
||||
// BusinessReference 是通用审批实例指向的稳定业务引用。
|
||||
type BusinessReference struct {
|
||||
InstanceID uint
|
||||
BusinessType string
|
||||
BusinessID uint
|
||||
}
|
||||
|
||||
// BusinessProjection 是业务权限 Adapter 返回的安全摘要和处理状态。
|
||||
type BusinessProjection struct {
|
||||
Allowed bool
|
||||
Summary string
|
||||
ProcessingStatus int
|
||||
ProcessingStatusName string
|
||||
ProcessingSummary string
|
||||
}
|
||||
|
||||
// BusinessProjectionResolver 批量复核业务资源当前权限并投影处理摘要。
|
||||
type BusinessProjectionResolver interface {
|
||||
Resolve(ctx context.Context, viewer Viewer, references []BusinessReference) (map[uint]BusinessProjection, error)
|
||||
}
|
||||
|
||||
// ExtensionReference 是渠道 Adapter 读取本地扩展快照所需的最小引用。
|
||||
type ExtensionReference struct {
|
||||
InstanceID uint
|
||||
Provider string
|
||||
ExternalRef string
|
||||
}
|
||||
|
||||
// ChannelExtensionResolver 可为平台主体批量补充渠道专属本地快照。
|
||||
// 实现不得在 Query 请求中实时调用外部审批平台。
|
||||
type ChannelExtensionResolver interface {
|
||||
Resolve(ctx context.Context, viewer Viewer, references []ExtensionReference) (map[uint]any, error)
|
||||
}
|
||||
|
||||
// Projection 是通用审批 Query 对业务列表和详情输出的稳定读取模型。
|
||||
type Projection struct {
|
||||
ID uint `json:"id"`
|
||||
BusinessType string `json:"business_type"`
|
||||
BusinessID uint `json:"business_id"`
|
||||
BusinessSummary string `json:"business_summary"`
|
||||
SubmitterAccountID uint `json:"submitter_account_id"`
|
||||
SubmitterName string `json:"submitter_name"`
|
||||
Provider string `json:"provider"`
|
||||
Status int `json:"status"`
|
||||
StatusName string `json:"status_name"`
|
||||
StatusChangedAt time.Time `json:"status_changed_at"`
|
||||
ProcessingStatus int `json:"processing_status"`
|
||||
ProcessingStatusName string `json:"processing_status_name"`
|
||||
ProcessingSummary string `json:"processing_summary"`
|
||||
ChannelExtension any `json:"channel_extension,omitempty"`
|
||||
}
|
||||
|
||||
// Query 批量读取通用审批事实,并通过业务 Adapter 复核当前权限。
|
||||
type Query struct {
|
||||
db *gorm.DB
|
||||
businessResolver BusinessProjectionResolver
|
||||
extensionResolver ChannelExtensionResolver
|
||||
}
|
||||
|
||||
// NewQuery 创建通用审批 Query。
|
||||
func NewQuery(db *gorm.DB, businessResolver BusinessProjectionResolver, extensionResolver ChannelExtensionResolver) *Query {
|
||||
return &Query{db: db, businessResolver: businessResolver, extensionResolver: extensionResolver}
|
||||
}
|
||||
|
||||
// GetByID 读取单条通用审批投影;资源不存在、引用失效或无权限统一返回禁止访问。
|
||||
func (q *Query) GetByID(ctx context.Context, instanceID uint) (*Projection, error) {
|
||||
items, err := q.BatchByIDs(ctx, []uint{instanceID})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(items) != 1 {
|
||||
return nil, errors.New(errors.CodeForbidden, "无权限操作该资源或资源不存在")
|
||||
}
|
||||
return &items[0], nil
|
||||
}
|
||||
|
||||
// BatchByIDs 按调用方当前页实例 ID 批量返回有权读取的审批投影,并保持输入顺序。
|
||||
func (q *Query) BatchByIDs(ctx context.Context, instanceIDs []uint) ([]Projection, error) {
|
||||
ids, err := normalizeInstanceIDs(instanceIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return []Projection{}, nil
|
||||
}
|
||||
if q == nil || q.db == nil || q.businessResolver == nil {
|
||||
return nil, errors.New(errors.CodeInternalError, "通用审批 Query 未完整配置")
|
||||
}
|
||||
|
||||
var records []model.ApprovalInstance
|
||||
if err := q.db.WithContext(ctx).Where("id IN ?", ids).Find(&records).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询通用审批实例失败")
|
||||
}
|
||||
recordByID := make(map[uint]model.ApprovalInstance, len(records))
|
||||
references := make([]BusinessReference, 0, len(records))
|
||||
for _, record := range records {
|
||||
recordByID[record.ID] = record
|
||||
references = append(references, BusinessReference{
|
||||
InstanceID: record.ID, BusinessType: record.BusinessType, BusinessID: record.BusinessID,
|
||||
})
|
||||
}
|
||||
|
||||
viewer := Viewer{AccountID: middleware.GetUserIDFromContext(ctx), UserType: middleware.GetUserTypeFromContext(ctx)}
|
||||
if viewer.AccountID == 0 || viewer.UserType == 0 {
|
||||
return nil, errors.New(errors.CodeForbidden)
|
||||
}
|
||||
businessByID, err := q.businessResolver.Resolve(ctx, viewer, references)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
extensionByID, err := q.resolveExtensions(ctx, viewer, records, businessByID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
items := make([]Projection, 0, len(records))
|
||||
for _, id := range ids {
|
||||
record, exists := recordByID[id]
|
||||
business, allowed := businessByID[id]
|
||||
if !exists || !allowed || !business.Allowed {
|
||||
continue
|
||||
}
|
||||
items = append(items, project(record, business, extensionByID[id]))
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func (q *Query) resolveExtensions(
|
||||
ctx context.Context,
|
||||
viewer Viewer,
|
||||
records []model.ApprovalInstance,
|
||||
businessByID map[uint]BusinessProjection,
|
||||
) (map[uint]any, error) {
|
||||
if q.extensionResolver == nil || viewer.UserType == constants.UserTypeAgent || viewer.UserType == constants.UserTypeEnterprise {
|
||||
return map[uint]any{}, nil
|
||||
}
|
||||
if viewer.UserType != constants.UserTypeSuperAdmin && viewer.UserType != constants.UserTypePlatform {
|
||||
return map[uint]any{}, nil
|
||||
}
|
||||
references := make([]ExtensionReference, 0, len(records))
|
||||
for _, record := range records {
|
||||
business, exists := businessByID[record.ID]
|
||||
if !exists || !business.Allowed {
|
||||
continue
|
||||
}
|
||||
references = append(references, ExtensionReference{
|
||||
InstanceID: record.ID, Provider: record.Provider, ExternalRef: record.ExternalRef,
|
||||
})
|
||||
}
|
||||
if len(references) == 0 {
|
||||
return map[uint]any{}, nil
|
||||
}
|
||||
return q.extensionResolver.Resolve(ctx, viewer, references)
|
||||
}
|
||||
|
||||
func normalizeInstanceIDs(instanceIDs []uint) ([]uint, error) {
|
||||
if len(instanceIDs) > constants.ApprovalQueryMaxBatchSize {
|
||||
return nil, errors.New(errors.CodeInvalidParam, "单次最多查询 100 条审批摘要")
|
||||
}
|
||||
seen := make(map[uint]struct{}, len(instanceIDs))
|
||||
ids := make([]uint, 0, len(instanceIDs))
|
||||
for _, id := range instanceIDs {
|
||||
if id == 0 {
|
||||
return nil, errors.New(errors.CodeInvalidParam)
|
||||
}
|
||||
if _, exists := seen[id]; exists {
|
||||
continue
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
func project(record model.ApprovalInstance, business BusinessProjection, extension any) Projection {
|
||||
return Projection{
|
||||
ID: record.ID, BusinessType: record.BusinessType, BusinessID: record.BusinessID,
|
||||
BusinessSummary: business.Summary,
|
||||
SubmitterAccountID: record.SubmitterAccountID, SubmitterName: submitterName(record.SubmitterSnapshot),
|
||||
Provider: record.Provider, Status: record.Status, StatusName: constants.GetApprovalStatusName(record.Status),
|
||||
StatusChangedAt: record.StatusChangedAt,
|
||||
ProcessingStatus: business.ProcessingStatus, ProcessingStatusName: business.ProcessingStatusName,
|
||||
ProcessingSummary: business.ProcessingSummary, ChannelExtension: extension,
|
||||
}
|
||||
}
|
||||
|
||||
func submitterName(snapshot []byte) string {
|
||||
var value struct {
|
||||
AccountName string `json:"account_name"`
|
||||
}
|
||||
if sonic.Unmarshal(snapshot, &value) != nil || strings.TrimSpace(value.AccountName) == "" {
|
||||
return constants.ApprovalUnknownSubmitterName
|
||||
}
|
||||
return strings.TrimSpace(value.AccountName)
|
||||
}
|
||||
221
internal/query/notification/query.go
Normal file
221
internal/query/notification/query.go
Normal file
@@ -0,0 +1,221 @@
|
||||
// Package notification 提供当前接收人的 PostgreSQL 站内通知读取投影。
|
||||
package notification
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model/dto"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
)
|
||||
|
||||
// Query 提供后台账号未读数和基础列表查询。
|
||||
type Query struct {
|
||||
db *gorm.DB
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
// NewQuery 创建后台通知查询。
|
||||
func NewQuery(db *gorm.DB) *Query {
|
||||
return &Query{db: db, now: time.Now}
|
||||
}
|
||||
|
||||
// UnreadCount 从 PostgreSQL 查询当前后台账号的准确未读数。
|
||||
func (q *Query) UnreadCount(ctx context.Context, recipientID uint) (*dto.NotificationUnreadCountResponse, error) {
|
||||
if recipientID == 0 {
|
||||
return nil, errors.New(errors.CodeInvalidParam)
|
||||
}
|
||||
var count int64
|
||||
now := q.now().UTC()
|
||||
err := q.db.WithContext(ctx).Model(&model.Notification{}).
|
||||
Where("recipient_kind = ? AND recipient_id = ? AND is_read = ? AND (expires_at IS NULL OR expires_at > ?)",
|
||||
constants.NotificationRecipientKindAccount, recipientID, false, now).
|
||||
Count(&count).Error
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询通知未读数失败")
|
||||
}
|
||||
return newUnreadCountResponse(count), nil
|
||||
}
|
||||
|
||||
// List 按创建时间和 ID 倒序查询当前后台账号的未过期通知。
|
||||
func (q *Query) List(ctx context.Context, recipientID uint, request dto.NotificationListRequest) (*dto.NotificationListResponse, error) {
|
||||
if recipientID == 0 {
|
||||
return nil, errors.New(errors.CodeInvalidParam)
|
||||
}
|
||||
page, pageSize, offset, err := normalizeNotificationPagination(request.Page, request.PageSize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !isNotificationCategory(request.Category) || !isNotificationSeverity(request.Severity) || len(request.Type) > 100 || strings.TrimSpace(request.Type) != request.Type {
|
||||
return nil, errors.New(errors.CodeInvalidParam)
|
||||
}
|
||||
now := q.now().UTC()
|
||||
base := q.db.WithContext(ctx).Model(&model.Notification{}).
|
||||
Where("recipient_kind = ? AND recipient_id = ? AND (expires_at IS NULL OR expires_at > ?)",
|
||||
constants.NotificationRecipientKindAccount, recipientID, now)
|
||||
if request.Category != "" {
|
||||
base = base.Where("category = ?", request.Category)
|
||||
}
|
||||
if request.Type != "" {
|
||||
base = base.Where("type = ?", request.Type)
|
||||
}
|
||||
if request.Severity != "" {
|
||||
base = base.Where("severity = ?", request.Severity)
|
||||
}
|
||||
if request.IsRead != nil {
|
||||
base = base.Where("is_read = ?", *request.IsRead)
|
||||
}
|
||||
var total int64
|
||||
if err := base.Count(&total).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询通知总数失败")
|
||||
}
|
||||
var records []model.Notification
|
||||
if err := base.Order("created_at DESC, id DESC").Offset(offset).Limit(pageSize).Find(&records).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询通知列表失败")
|
||||
}
|
||||
items := make([]dto.NotificationItem, 0, len(records))
|
||||
for _, record := range records {
|
||||
items = append(items, dto.NotificationItem{
|
||||
ID: record.ID, Category: record.Category, Type: record.Type, Severity: record.Severity,
|
||||
Title: record.Title, Body: record.Body, RefType: record.RefType, RefID: record.RefID,
|
||||
RefKey: record.RefKey, IsRead: record.IsRead, ReadAt: record.ReadAt, CreatedAt: record.CreatedAt,
|
||||
})
|
||||
}
|
||||
return &dto.NotificationListResponse{Items: items, Total: total, Page: page, Size: pageSize}, nil
|
||||
}
|
||||
|
||||
// PersonalUnreadCount 查询当前个人客户可见业务通知的准确未读数。
|
||||
func (q *Query) PersonalUnreadCount(ctx context.Context, customerID uint) (*dto.NotificationUnreadCountResponse, error) {
|
||||
if customerID == 0 {
|
||||
return nil, errors.New(errors.CodeInvalidParam)
|
||||
}
|
||||
var count int64
|
||||
err := personalNotificationScope(q.db.WithContext(ctx).Model(&model.Notification{}), customerID, q.now().UTC()).
|
||||
Where("is_read = ?", false).
|
||||
Count(&count).Error
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询个人客户通知未读数失败")
|
||||
}
|
||||
return newUnreadCountResponse(count), nil
|
||||
}
|
||||
|
||||
// PersonalList 查询当前个人客户可见的未过期业务通知简化列表。
|
||||
func (q *Query) PersonalList(ctx context.Context, customerID uint, request dto.PersonalNotificationListRequest) (*dto.PersonalNotificationListResponse, error) {
|
||||
if customerID == 0 {
|
||||
return nil, errors.New(errors.CodeInvalidParam)
|
||||
}
|
||||
page, pageSize, offset, err := normalizeNotificationPagination(request.Page, request.PageSize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
base := personalNotificationScope(q.db.WithContext(ctx).Model(&model.Notification{}), customerID, q.now().UTC())
|
||||
var total int64
|
||||
if err := base.Count(&total).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询个人客户通知总数失败")
|
||||
}
|
||||
var records []model.Notification
|
||||
if err := base.Order("created_at DESC, id DESC").Offset(offset).Limit(pageSize).Find(&records).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询个人客户通知列表失败")
|
||||
}
|
||||
return &dto.PersonalNotificationListResponse{
|
||||
Items: notificationItems(records), Total: total, Page: page, Size: pageSize,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// UnreadSummary 使用单条 PostgreSQL 查询返回当前后台账号的固定分类汇总。
|
||||
func (q *Query) UnreadSummary(ctx context.Context, recipientID uint) (*dto.NotificationUnreadSummaryResponse, error) {
|
||||
if recipientID == 0 {
|
||||
return nil, errors.New(errors.CodeInvalidParam)
|
||||
}
|
||||
var summary dto.NotificationUnreadSummaryResponse
|
||||
err := q.db.WithContext(ctx).Model(&model.Notification{}).
|
||||
Select(`COUNT(*) AS total,
|
||||
COUNT(*) FILTER (WHERE category = ?) AS approval,
|
||||
COUNT(*) FILTER (WHERE category = ?) AS expiry,
|
||||
COUNT(*) FILTER (WHERE category = ?) AS sync,
|
||||
COUNT(*) FILTER (WHERE category = ?) AS system`,
|
||||
constants.NotificationCategoryApproval,
|
||||
constants.NotificationCategoryExpiry,
|
||||
constants.NotificationCategorySync,
|
||||
constants.NotificationCategorySystem).
|
||||
Where("recipient_kind = ? AND recipient_id = ? AND is_read = ? AND (expires_at IS NULL OR expires_at > ?)",
|
||||
constants.NotificationRecipientKindAccount, recipientID, false, q.now().UTC()).
|
||||
Scan(&summary).Error
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询通知未读汇总失败")
|
||||
}
|
||||
return &summary, nil
|
||||
}
|
||||
|
||||
func isNotificationCategory(category string) bool {
|
||||
switch category {
|
||||
case "", constants.NotificationCategoryApproval, constants.NotificationCategoryExpiry,
|
||||
constants.NotificationCategorySync, constants.NotificationCategorySystem:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func isNotificationSeverity(severity string) bool {
|
||||
switch severity {
|
||||
case "", constants.NotificationSeverityInfo, constants.NotificationSeverityWarning,
|
||||
constants.NotificationSeverityError, constants.NotificationSeverityCritical:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeNotificationPagination(page, pageSize int) (int, int, int, error) {
|
||||
if page <= 0 {
|
||||
page = 1
|
||||
}
|
||||
if page > constants.NotificationMaxPage {
|
||||
return 0, 0, 0, errors.New(errors.CodeInvalidParam)
|
||||
}
|
||||
if pageSize <= 0 {
|
||||
pageSize = constants.NotificationDefaultPageSize
|
||||
}
|
||||
if pageSize > constants.NotificationMaxPageSize {
|
||||
return 0, 0, 0, errors.New(errors.CodeInvalidParam)
|
||||
}
|
||||
return page, pageSize, (page - 1) * pageSize, nil
|
||||
}
|
||||
|
||||
func personalNotificationScope(db *gorm.DB, customerID uint, now time.Time) *gorm.DB {
|
||||
return db.Where(`recipient_kind = ? AND recipient_id = ?
|
||||
AND category IN ? AND type IN ? AND (expires_at IS NULL OR expires_at > ?)`,
|
||||
constants.NotificationRecipientKindPersonalCustomer,
|
||||
customerID,
|
||||
[]string{constants.NotificationCategoryApproval, constants.NotificationCategoryExpiry},
|
||||
[]string{constants.NotificationTypePackageExpiring},
|
||||
now,
|
||||
)
|
||||
}
|
||||
|
||||
func newUnreadCountResponse(count int64) *dto.NotificationUnreadCountResponse {
|
||||
displayCount := strconv.FormatInt(count, 10)
|
||||
if count > 99 {
|
||||
displayCount = "99+"
|
||||
}
|
||||
return &dto.NotificationUnreadCountResponse{Count: count, DisplayCount: displayCount}
|
||||
}
|
||||
|
||||
func notificationItems(records []model.Notification) []dto.NotificationItem {
|
||||
items := make([]dto.NotificationItem, 0, len(records))
|
||||
for _, record := range records {
|
||||
items = append(items, dto.NotificationItem{
|
||||
ID: record.ID, Category: record.Category, Type: record.Type, Severity: record.Severity,
|
||||
Title: record.Title, Body: record.Body, RefType: record.RefType, RefID: record.RefID,
|
||||
RefKey: record.RefKey, IsRead: record.IsRead, ReadAt: record.ReadAt, CreatedAt: record.CreatedAt,
|
||||
})
|
||||
}
|
||||
return items
|
||||
}
|
||||
156
internal/query/notification/target.go
Normal file
156
internal/query/notification/target.go
Normal file
@@ -0,0 +1,156 @@
|
||||
package notification
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math"
|
||||
"strconv"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model/dto"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/middleware"
|
||||
)
|
||||
|
||||
// Target 先校验通知属于当前账号,再解析白名单结构化目标并复核当前权限。
|
||||
func (q *Query) Target(ctx context.Context, recipientID, notificationID uint) (*dto.NotificationTargetResponse, error) {
|
||||
result := &dto.NotificationTargetResponse{}
|
||||
if recipientID == 0 || notificationID == 0 {
|
||||
return nil, errors.New(errors.CodeInvalidParam)
|
||||
}
|
||||
var record model.Notification
|
||||
err := q.db.WithContext(ctx).Select("ref_type", "ref_id", "ref_key").
|
||||
Where("id = ? AND recipient_kind = ? AND recipient_id = ? AND (expires_at IS NULL OR expires_at > ?)",
|
||||
notificationID, constants.NotificationRecipientKindAccount, recipientID, q.now().UTC()).Take(&record).Error
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return result, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询通知目标失败")
|
||||
}
|
||||
return q.resolveTarget(ctx, record)
|
||||
}
|
||||
|
||||
func (q *Query) resolveTarget(ctx context.Context, record model.Notification) (*dto.NotificationTargetResponse, error) {
|
||||
definition, exists := notificationTargetDefinitions()[record.RefType]
|
||||
if !exists {
|
||||
return &dto.NotificationTargetResponse{}, nil
|
||||
}
|
||||
result := &dto.NotificationTargetResponse{TargetType: definition.targetType}
|
||||
if definition.keyTarget {
|
||||
result.TargetKey = record.RefKey
|
||||
}
|
||||
if definition.idTarget {
|
||||
id, valid := parseNotificationTargetID(record.RefID)
|
||||
if !valid {
|
||||
return result, nil
|
||||
}
|
||||
result.TargetID = &id
|
||||
}
|
||||
available, err := definition.available(q, ctx, record, result.TargetID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result.Available = available
|
||||
return result, nil
|
||||
}
|
||||
|
||||
type targetDefinition struct {
|
||||
targetType string
|
||||
idTarget bool
|
||||
keyTarget bool
|
||||
available func(*Query, context.Context, model.Notification, *uint) (bool, error)
|
||||
}
|
||||
|
||||
func notificationTargetDefinitions() map[string]targetDefinition {
|
||||
return map[string]targetDefinition{
|
||||
constants.NotificationRefTypeRefund: {targetType: constants.NotificationTargetTypeRefundDetail, idTarget: true, available: refundTargetAvailable},
|
||||
constants.NotificationRefTypeAgentRecharge: {targetType: constants.NotificationTargetTypeAgentRechargeDetail, idTarget: true, available: unavailableFutureTarget},
|
||||
constants.NotificationRefTypeWeComApproval: {targetType: constants.NotificationTargetTypeWeComApprovalDetail, idTarget: true, available: unavailableFutureTarget},
|
||||
constants.NotificationRefTypeIotCard: {targetType: constants.NotificationTargetTypeIotCardDetail, idTarget: true, available: iotCardTargetAvailable},
|
||||
constants.NotificationRefTypeDevice: {targetType: constants.NotificationTargetTypeDeviceDetail, idTarget: true, available: deviceTargetAvailable},
|
||||
constants.NotificationRefTypeExpiringAsset: {targetType: constants.NotificationTargetTypeExpiringAssetList, idTarget: true, available: shopTargetAvailable},
|
||||
constants.NotificationRefTypeShopFund: {targetType: constants.NotificationTargetTypeShopFundSummary, idTarget: true, available: shopTargetAvailable},
|
||||
constants.NotificationRefTypeIntegrationLog: {targetType: constants.NotificationTargetTypeIntegrationLog, keyTarget: true, available: integrationTargetAvailable},
|
||||
constants.NotificationRefTypeCardSync: {targetType: constants.NotificationTargetTypeIntegrationLog, keyTarget: true, available: integrationTargetAvailable},
|
||||
constants.NotificationRefTypeSystemConfig: {targetType: constants.NotificationTargetTypeSystemConfig, keyTarget: true, available: systemConfigTargetAvailable},
|
||||
}
|
||||
}
|
||||
|
||||
func parseNotificationTargetID(value string) (uint, bool) {
|
||||
parsed, err := strconv.ParseUint(value, 10, 64)
|
||||
if err != nil || parsed == 0 || parsed > math.MaxInt64 {
|
||||
return 0, false
|
||||
}
|
||||
return uint(parsed), true
|
||||
}
|
||||
|
||||
func refundTargetAvailable(q *Query, ctx context.Context, _ model.Notification, id *uint) (bool, error) {
|
||||
query := q.db.WithContext(ctx).Model(&model.RefundRequest{}).Where("id = ?", *id)
|
||||
switch middleware.GetUserTypeFromContext(ctx) {
|
||||
case constants.UserTypeSuperAdmin, constants.UserTypePlatform:
|
||||
case constants.UserTypeAgent:
|
||||
query = query.Where("creator = ?", middleware.GetUserIDFromContext(ctx))
|
||||
default:
|
||||
return false, nil
|
||||
}
|
||||
return targetExists(query, "查询退款通知目标失败")
|
||||
}
|
||||
|
||||
func iotCardTargetAvailable(q *Query, ctx context.Context, _ model.Notification, id *uint) (bool, error) {
|
||||
if middleware.GetUserTypeFromContext(ctx) == constants.UserTypeEnterprise {
|
||||
return false, nil
|
||||
}
|
||||
query := middleware.ApplyShopFilter(ctx, q.db.WithContext(ctx).Model(&model.IotCard{})).Where("id = ?", *id)
|
||||
return targetExists(query, "查询物联网卡通知目标失败")
|
||||
}
|
||||
|
||||
func deviceTargetAvailable(q *Query, ctx context.Context, _ model.Notification, id *uint) (bool, error) {
|
||||
if middleware.GetUserTypeFromContext(ctx) == constants.UserTypeEnterprise {
|
||||
return false, nil
|
||||
}
|
||||
query := middleware.ApplyShopFilter(ctx, q.db.WithContext(ctx).Model(&model.Device{})).Where("id = ?", *id)
|
||||
return targetExists(query, "查询设备通知目标失败")
|
||||
}
|
||||
|
||||
func shopTargetAvailable(q *Query, ctx context.Context, _ model.Notification, id *uint) (bool, error) {
|
||||
if err := middleware.CanManageShop(ctx, *id); err != nil {
|
||||
return false, nil
|
||||
}
|
||||
query := middleware.ApplyShopIDFilter(ctx, q.db.WithContext(ctx).Model(&model.Shop{})).Where("id = ?", *id)
|
||||
return targetExists(query, "查询店铺通知目标失败")
|
||||
}
|
||||
|
||||
func integrationTargetAvailable(q *Query, ctx context.Context, record model.Notification, _ *uint) (bool, error) {
|
||||
userType := middleware.GetUserTypeFromContext(ctx)
|
||||
if userType != constants.UserTypeSuperAdmin && userType != constants.UserTypePlatform {
|
||||
return false, nil
|
||||
}
|
||||
if record.RefKey == "" {
|
||||
return false, nil
|
||||
}
|
||||
query := q.db.WithContext(ctx).Model(&model.IntegrationLog{}).Where("integration_id = ?", record.RefKey)
|
||||
return targetExists(query, "查询外部集成通知目标失败")
|
||||
}
|
||||
|
||||
func systemConfigTargetAvailable(q *Query, ctx context.Context, record model.Notification, _ *uint) (bool, error) {
|
||||
if middleware.GetUserTypeFromContext(ctx) != constants.UserTypeSuperAdmin || record.RefKey == "" {
|
||||
return false, nil
|
||||
}
|
||||
query := q.db.WithContext(ctx).Model(&model.SystemConfig{}).Where("config_key = ?", record.RefKey)
|
||||
return targetExists(query, "查询系统配置通知目标失败")
|
||||
}
|
||||
|
||||
func unavailableFutureTarget(_ *Query, _ context.Context, _ model.Notification, _ *uint) (bool, error) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func targetExists(query *gorm.DB, summary string) (bool, error) {
|
||||
var count int64
|
||||
if err := query.Count(&count).Error; err != nil {
|
||||
return false, errors.Wrap(errors.CodeDatabaseError, err, summary)
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
219
internal/query/shop/business_owner.go
Normal file
219
internal/query/shop/business_owner.go
Normal file
@@ -0,0 +1,219 @@
|
||||
// Package shop 提供店铺业务员归属与资金概况读取投影。
|
||||
package shop
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model/dto"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/middleware"
|
||||
)
|
||||
|
||||
// BusinessOwnerQuery 提供店铺业务员归属读取能力。
|
||||
type BusinessOwnerQuery struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewBusinessOwnerQuery 创建店铺业务员归属 Query。
|
||||
func NewBusinessOwnerQuery(db *gorm.DB) *BusinessOwnerQuery {
|
||||
return &BusinessOwnerQuery{db: db}
|
||||
}
|
||||
|
||||
// List 查询调用者数据范围内的店铺,并批量投影上级和业务员摘要。
|
||||
func (q *BusinessOwnerQuery) List(ctx context.Context, request dto.ShopListRequest) ([]*dto.ShopResponse, int64, error) {
|
||||
base := middleware.ApplyShopIDFilter(ctx, q.db.WithContext(ctx).Model(&model.Shop{}))
|
||||
base = applyShopFilters(base, request)
|
||||
var total int64
|
||||
if err := base.Count(&total).Error; err != nil {
|
||||
return nil, 0, errors.Wrap(errors.CodeDatabaseError, err, "查询店铺总数失败")
|
||||
}
|
||||
var shops []*model.Shop
|
||||
offset := (request.Page - 1) * request.PageSize
|
||||
if err := base.Order("created_at DESC, id DESC").Offset(offset).Limit(request.PageSize).Find(&shops).Error; err != nil {
|
||||
return nil, 0, errors.Wrap(errors.CodeDatabaseError, err, "查询店铺列表失败")
|
||||
}
|
||||
responses, err := q.project(ctx, shops)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return responses, total, nil
|
||||
}
|
||||
|
||||
// Detail 查询调用者数据范围内的一家店铺详情。
|
||||
func (q *BusinessOwnerQuery) Detail(ctx context.Context, shopID uint) (*dto.ShopResponse, error) {
|
||||
if shopID == 0 {
|
||||
return nil, errors.New(errors.CodeInvalidParam)
|
||||
}
|
||||
var shop model.Shop
|
||||
db := middleware.ApplyShopIDFilter(ctx, q.db.WithContext(ctx).Model(&model.Shop{}))
|
||||
if err := db.Where("id = ?", shopID).First(&shop).Error; err != nil {
|
||||
return nil, errors.New(errors.CodeForbidden, "无权限操作该资源或资源不存在")
|
||||
}
|
||||
responses, err := q.project(ctx, []*model.Shop{&shop})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return responses[0], nil
|
||||
}
|
||||
|
||||
// Candidates 查询当前可人工绑定的平台业务员最小投影。
|
||||
func (q *BusinessOwnerQuery) Candidates(ctx context.Context, request dto.ShopBusinessOwnerCandidateRequest) ([]dto.ShopBusinessOwnerCandidate, int64, int, int, error) {
|
||||
userType := middleware.GetUserTypeFromContext(ctx)
|
||||
if userType != constants.UserTypeSuperAdmin && userType != constants.UserTypePlatform {
|
||||
return nil, 0, 0, 0, errors.New(errors.CodeForbidden, "无权限查询业务员候选")
|
||||
}
|
||||
page, pageSize := request.Page, request.PageSize
|
||||
if page == 0 {
|
||||
page = constants.DefaultPage
|
||||
}
|
||||
if pageSize == 0 {
|
||||
pageSize = constants.DefaultPageSize
|
||||
}
|
||||
base := q.db.WithContext(ctx).Model(&model.Account{}).
|
||||
Where("user_type = ? AND status = ?", constants.UserTypePlatform, constants.StatusEnabled)
|
||||
if request.Keyword != "" {
|
||||
keyword := "%" + request.Keyword + "%"
|
||||
base = base.Where("username ILIKE ? OR phone ILIKE ?", keyword, keyword)
|
||||
}
|
||||
var total int64
|
||||
if err := base.Count(&total).Error; err != nil {
|
||||
return nil, 0, 0, 0, errors.Wrap(errors.CodeDatabaseError, err, "查询业务员候选总数失败")
|
||||
}
|
||||
var accounts []model.Account
|
||||
if err := base.Order("id ASC").Offset((page - 1) * pageSize).Limit(pageSize).Find(&accounts).Error; err != nil {
|
||||
return nil, 0, 0, 0, errors.Wrap(errors.CodeDatabaseError, err, "查询业务员候选失败")
|
||||
}
|
||||
items := make([]dto.ShopBusinessOwnerCandidate, 0, len(accounts))
|
||||
for _, account := range accounts {
|
||||
items = append(items, dto.ShopBusinessOwnerCandidate{
|
||||
ID: account.ID, Username: account.Username, PhoneSummary: maskPhone(account.Phone),
|
||||
})
|
||||
}
|
||||
return items, total, page, pageSize, nil
|
||||
}
|
||||
|
||||
func applyShopFilters(db *gorm.DB, request dto.ShopListRequest) *gorm.DB {
|
||||
if request.ShopName != "" {
|
||||
db = db.Where("shop_name LIKE ?", "%"+request.ShopName+"%")
|
||||
}
|
||||
if request.ShopCode != "" {
|
||||
db = db.Where("shop_code = ?", request.ShopCode)
|
||||
}
|
||||
if request.ContactPhone != "" {
|
||||
db = db.Where("contact_phone = ?", request.ContactPhone)
|
||||
}
|
||||
if request.BusinessOwnerAccountID != nil {
|
||||
db = db.Where("business_owner_account_id = ?", *request.BusinessOwnerAccountID)
|
||||
}
|
||||
if request.ParentID != nil {
|
||||
db = db.Where("parent_id = ?", *request.ParentID)
|
||||
}
|
||||
if request.Level != nil {
|
||||
db = db.Where("level = ?", *request.Level)
|
||||
}
|
||||
if request.Status != nil {
|
||||
db = db.Where("status = ?", *request.Status)
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
func (q *BusinessOwnerQuery) project(ctx context.Context, shops []*model.Shop) ([]*dto.ShopResponse, error) {
|
||||
parentIDs, ownerIDs := collectProjectionIDs(shops)
|
||||
parentNames, err := q.loadParentNames(ctx, parentIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
owners, err := q.loadBusinessOwners(ctx, ownerIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
responses := make([]*dto.ShopResponse, 0, len(shops))
|
||||
for _, shop := range shops {
|
||||
response := &dto.ShopResponse{
|
||||
ID: shop.ID, ShopName: shop.ShopName, ShopCode: shop.ShopCode, ParentID: shop.ParentID,
|
||||
BusinessOwnerAccountID: shop.BusinessOwnerAccountID, Level: shop.Level,
|
||||
ContactName: shop.ContactName, ContactPhone: shop.ContactPhone, Province: shop.Province,
|
||||
City: shop.City, District: shop.District, Address: shop.Address, Status: shop.Status,
|
||||
StatusName: constants.GetStatusName(shop.Status), CreatedAt: shop.CreatedAt.Format("2006-01-02 15:04:05"),
|
||||
UpdatedAt: shop.UpdatedAt.Format("2006-01-02 15:04:05"),
|
||||
}
|
||||
if shop.ParentID != nil {
|
||||
response.ParentShopName = parentNames[*shop.ParentID]
|
||||
}
|
||||
if shop.BusinessOwnerAccountID != nil {
|
||||
if owner, exists := owners[*shop.BusinessOwnerAccountID]; exists {
|
||||
response.BusinessOwnerUsername = owner.Username
|
||||
response.BusinessOwnerPhoneSummary = maskPhone(owner.Phone)
|
||||
response.BusinessOwnerAvailable = owner.UserType == constants.UserTypePlatform && owner.Status == constants.StatusEnabled && !owner.DeletedAt.Valid
|
||||
}
|
||||
}
|
||||
responses = append(responses, response)
|
||||
}
|
||||
return responses, nil
|
||||
}
|
||||
|
||||
func collectProjectionIDs(shops []*model.Shop) ([]uint, []uint) {
|
||||
parents := make(map[uint]struct{})
|
||||
owners := make(map[uint]struct{})
|
||||
for _, shop := range shops {
|
||||
if shop.ParentID != nil {
|
||||
parents[*shop.ParentID] = struct{}{}
|
||||
}
|
||||
if shop.BusinessOwnerAccountID != nil {
|
||||
owners[*shop.BusinessOwnerAccountID] = struct{}{}
|
||||
}
|
||||
}
|
||||
return mapKeys(parents), mapKeys(owners)
|
||||
}
|
||||
|
||||
func (q *BusinessOwnerQuery) loadParentNames(ctx context.Context, ids []uint) (map[uint]string, error) {
|
||||
result := make(map[uint]string, len(ids))
|
||||
if len(ids) == 0 {
|
||||
return result, nil
|
||||
}
|
||||
var shops []model.Shop
|
||||
db := middleware.ApplyShopIDFilter(ctx, q.db.WithContext(ctx).Model(&model.Shop{}))
|
||||
if err := db.Select("id", "shop_name").Where("id IN ?", ids).Find(&shops).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询上级店铺摘要失败")
|
||||
}
|
||||
for _, shop := range shops {
|
||||
result[shop.ID] = shop.ShopName
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (q *BusinessOwnerQuery) loadBusinessOwners(ctx context.Context, ids []uint) (map[uint]model.Account, error) {
|
||||
result := make(map[uint]model.Account, len(ids))
|
||||
if len(ids) == 0 {
|
||||
return result, nil
|
||||
}
|
||||
var accounts []model.Account
|
||||
if err := q.db.WithContext(ctx).Unscoped().Where("id IN ?", ids).Find(&accounts).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询业务员摘要失败")
|
||||
}
|
||||
for _, account := range accounts {
|
||||
result[account.ID] = account
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func mapKeys(values map[uint]struct{}) []uint {
|
||||
keys := make([]uint, 0, len(values))
|
||||
for key := range values {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
func maskPhone(phone string) string {
|
||||
phone = strings.TrimSpace(phone)
|
||||
if len(phone) < 7 {
|
||||
return ""
|
||||
}
|
||||
return phone[:3] + "****" + phone[len(phone)-4:]
|
||||
}
|
||||
294
internal/query/shop/fund_summary.go
Normal file
294
internal/query/shop/fund_summary.go
Normal file
@@ -0,0 +1,294 @@
|
||||
package shop
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math"
|
||||
"strings"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model/dto"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/middleware"
|
||||
)
|
||||
|
||||
// FundSummaryQuery 提供数据权限范围内的店铺资金概况读取投影。
|
||||
type FundSummaryQuery struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewFundSummaryQuery 创建店铺资金概况 Query。
|
||||
func NewFundSummaryQuery(db *gorm.DB) *FundSummaryQuery {
|
||||
return &FundSummaryQuery{db: db}
|
||||
}
|
||||
|
||||
// List 分页查询店铺,并以固定批次数投影主钱包、佣金、提现和主账号信息。
|
||||
func (q *FundSummaryQuery) List(ctx context.Context, req dto.ShopFundSummaryListReq) (*dto.ShopFundSummaryPageResult, error) {
|
||||
page, pageSize := normalizeFundSummaryPage(req.Page, req.PageSize)
|
||||
base := middleware.ApplyShopIDFilter(ctx, q.db.WithContext(ctx).Model(&model.Shop{}))
|
||||
base = applyFundSummaryFilters(base, req)
|
||||
|
||||
var total int64
|
||||
if err := base.Count(&total).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询店铺资金概况总数失败")
|
||||
}
|
||||
var shops []model.Shop
|
||||
if err := base.Order("created_at DESC, id DESC").Offset((page - 1) * pageSize).Limit(pageSize).Find(&shops).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询店铺资金概况列表失败")
|
||||
}
|
||||
if len(shops) == 0 {
|
||||
return &dto.ShopFundSummaryPageResult{Items: []dto.ShopFundSummaryItem{}, Total: total, Page: page, Size: pageSize}, nil
|
||||
}
|
||||
|
||||
shopIDs := make([]uint, 0, len(shops))
|
||||
for index := range shops {
|
||||
shopIDs = append(shopIDs, shops[index].ID)
|
||||
}
|
||||
wallets, err := q.loadWallets(ctx, shopIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
withdrawals, err := q.loadWithdrawals(ctx, shopIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
accounts, err := q.loadPrimaryAccounts(ctx, shopIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
items := make([]dto.ShopFundSummaryItem, 0, len(shops))
|
||||
for index := range shops {
|
||||
item, err := projectFundSummary(shops[index], wallets[shops[index].ID], withdrawals[shops[index].ID], accounts[shops[index].ID])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
return &dto.ShopFundSummaryPageResult{Items: items, Total: total, Page: page, Size: pageSize}, nil
|
||||
}
|
||||
|
||||
type fundWallets struct {
|
||||
main *model.AgentWallet
|
||||
commission *model.AgentWallet
|
||||
}
|
||||
|
||||
type withdrawalAmounts struct {
|
||||
approved int64
|
||||
pending int64
|
||||
}
|
||||
|
||||
type withdrawalAggregate struct {
|
||||
ShopID uint
|
||||
Status int
|
||||
Amount int64
|
||||
}
|
||||
|
||||
func normalizeFundSummaryPage(page, pageSize int) (int, int) {
|
||||
if page <= 0 {
|
||||
page = constants.DefaultPage
|
||||
}
|
||||
if pageSize <= 0 {
|
||||
pageSize = constants.DefaultPageSize
|
||||
}
|
||||
if pageSize > constants.MaxPageSize {
|
||||
pageSize = constants.MaxPageSize
|
||||
}
|
||||
return page, pageSize
|
||||
}
|
||||
|
||||
func applyFundSummaryFilters(db *gorm.DB, req dto.ShopFundSummaryListReq) *gorm.DB {
|
||||
if shopName := strings.TrimSpace(req.ShopName); shopName != "" {
|
||||
db = db.Where("shop_name ILIKE ?", "%"+shopName+"%")
|
||||
}
|
||||
if username := strings.TrimSpace(req.Username); username != "" {
|
||||
db = db.Where(`EXISTS (
|
||||
SELECT 1 FROM tb_account AS account_filter
|
||||
WHERE account_filter.shop_id = tb_shop.id
|
||||
AND account_filter.is_primary = TRUE
|
||||
AND account_filter.deleted_at IS NULL
|
||||
AND account_filter.username ILIKE ?
|
||||
)`, "%"+username+"%")
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
func (q *FundSummaryQuery) loadWallets(ctx context.Context, shopIDs []uint) (map[uint]fundWallets, error) {
|
||||
var records []model.AgentWallet
|
||||
if err := q.db.WithContext(ctx).
|
||||
Where("shop_id IN ? AND wallet_type IN ?", shopIDs, []string{constants.AgentWalletTypeMain, constants.AgentWalletTypeCommission}).
|
||||
Order("id ASC").Find(&records).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "批量查询店铺钱包失败")
|
||||
}
|
||||
result := make(map[uint]fundWallets, len(shopIDs))
|
||||
for index := range records {
|
||||
wallet := &records[index]
|
||||
pair := result[wallet.ShopID]
|
||||
switch wallet.WalletType {
|
||||
case constants.AgentWalletTypeMain:
|
||||
if pair.main == nil {
|
||||
pair.main = wallet
|
||||
}
|
||||
case constants.AgentWalletTypeCommission:
|
||||
if pair.commission == nil {
|
||||
pair.commission = wallet
|
||||
}
|
||||
}
|
||||
result[wallet.ShopID] = pair
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (q *FundSummaryQuery) loadWithdrawals(ctx context.Context, shopIDs []uint) (map[uint]withdrawalAmounts, error) {
|
||||
var records []withdrawalAggregate
|
||||
if err := q.db.WithContext(ctx).Model(&model.CommissionWithdrawalRequest{}).
|
||||
Select("shop_id, status, COALESCE(SUM(amount), 0) AS amount").
|
||||
Where("shop_id IN ? AND status IN ?", shopIDs, []int{constants.WithdrawalStatusApproved, constants.WithdrawalStatusPending}).
|
||||
Group("shop_id, status").Scan(&records).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "批量查询店铺提现汇总失败")
|
||||
}
|
||||
result := make(map[uint]withdrawalAmounts, len(shopIDs))
|
||||
for _, record := range records {
|
||||
amounts := result[record.ShopID]
|
||||
if record.Status == constants.WithdrawalStatusApproved {
|
||||
amounts.approved = record.Amount
|
||||
} else if record.Status == constants.WithdrawalStatusPending {
|
||||
amounts.pending = record.Amount
|
||||
}
|
||||
result[record.ShopID] = amounts
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (q *FundSummaryQuery) loadPrimaryAccounts(ctx context.Context, shopIDs []uint) (map[uint]*model.Account, error) {
|
||||
var records []model.Account
|
||||
if err := q.db.WithContext(ctx).
|
||||
Where("shop_id IN ? AND is_primary = ? AND deleted_at IS NULL", shopIDs, true).
|
||||
Order("id ASC").Find(&records).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "批量查询店铺主账号失败")
|
||||
}
|
||||
result := make(map[uint]*model.Account, len(shopIDs))
|
||||
for index := range records {
|
||||
account := &records[index]
|
||||
if account.ShopID != nil && result[*account.ShopID] == nil {
|
||||
result[*account.ShopID] = account
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func projectFundSummary(shop model.Shop, wallets fundWallets, withdrawals withdrawalAmounts, account *model.Account) (dto.ShopFundSummaryItem, error) {
|
||||
mainProjection, err := projectMainWallet(wallets.main)
|
||||
if err != nil {
|
||||
return dto.ShopFundSummaryItem{}, err
|
||||
}
|
||||
commissionProjection, err := projectCommissionWallet(wallets.commission, withdrawals)
|
||||
if err != nil {
|
||||
return dto.ShopFundSummaryItem{}, err
|
||||
}
|
||||
item := dto.ShopFundSummaryItem{
|
||||
ShopID: shop.ID, ShopName: shop.ShopName, ShopCode: shop.ShopCode,
|
||||
MainBalance: mainProjection.balance, MainFrozenBalance: mainProjection.frozen,
|
||||
CashAvailableBalance: mainProjection.cashAvailable, CreditEnabled: mainProjection.creditEnabled,
|
||||
CreditLimit: mainProjection.creditLimit, AvailableBalance: mainProjection.available,
|
||||
IsInDebt: mainProjection.isInDebt, DebtAmount: mainProjection.debtAmount, Version: mainProjection.version,
|
||||
TotalCommission: commissionProjection.total, WithdrawnCommission: withdrawals.approved,
|
||||
UnwithdrawCommission: commissionProjection.unwithdrawn, FrozenCommission: commissionProjection.frozen,
|
||||
WithdrawingCommission: withdrawals.pending, AvailableCommission: commissionProjection.available,
|
||||
CreatedAt: shop.CreatedAt.Format("2006-01-02 15:04:05"),
|
||||
}
|
||||
if account != nil {
|
||||
item.Username = account.Username
|
||||
item.Phone = account.Phone
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
type mainWalletProjection struct {
|
||||
balance int64
|
||||
frozen int64
|
||||
cashAvailable int64
|
||||
creditEnabled bool
|
||||
creditLimit int64
|
||||
available int64
|
||||
isInDebt bool
|
||||
debtAmount int64
|
||||
version int
|
||||
}
|
||||
|
||||
func projectMainWallet(wallet *model.AgentWallet) (mainWalletProjection, error) {
|
||||
if wallet == nil {
|
||||
return mainWalletProjection{}, nil
|
||||
}
|
||||
cashAvailable, ok := safeFundSub(wallet.Balance, wallet.FrozenBalance)
|
||||
if !ok {
|
||||
return mainWalletProjection{}, errors.New(errors.CodeInternalError, "计算主钱包现金可用金额时发生整数溢出")
|
||||
}
|
||||
effectiveCredit := int64(0)
|
||||
if wallet.CreditEnabled {
|
||||
effectiveCredit = wallet.CreditLimit
|
||||
}
|
||||
available, ok := safeFundAdd(cashAvailable, effectiveCredit)
|
||||
if !ok {
|
||||
return mainWalletProjection{}, errors.New(errors.CodeInternalError, "计算主钱包总可用金额时发生整数溢出")
|
||||
}
|
||||
debtAmount := int64(0)
|
||||
if wallet.Balance < 0 {
|
||||
if wallet.Balance == math.MinInt64 {
|
||||
return mainWalletProjection{}, errors.New(errors.CodeInternalError, "计算主钱包欠款金额时发生整数溢出")
|
||||
}
|
||||
debtAmount = -wallet.Balance
|
||||
}
|
||||
return mainWalletProjection{
|
||||
balance: wallet.Balance, frozen: wallet.FrozenBalance, cashAvailable: cashAvailable,
|
||||
creditEnabled: wallet.CreditEnabled, creditLimit: wallet.CreditLimit, available: available,
|
||||
isInDebt: wallet.Balance < 0, debtAmount: debtAmount, version: wallet.Version,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type commissionProjection struct {
|
||||
total int64
|
||||
unwithdrawn int64
|
||||
frozen int64
|
||||
available int64
|
||||
}
|
||||
|
||||
func projectCommissionWallet(wallet *model.AgentWallet, withdrawals withdrawalAmounts) (commissionProjection, error) {
|
||||
balance, frozen := int64(0), int64(0)
|
||||
if wallet != nil {
|
||||
balance = wallet.Balance
|
||||
frozen = wallet.FrozenBalance
|
||||
}
|
||||
unwithdrawn, ok := safeFundAdd(balance, frozen)
|
||||
if !ok {
|
||||
return commissionProjection{}, errors.New(errors.CodeInternalError, "计算未提现佣金时发生整数溢出")
|
||||
}
|
||||
total, ok := safeFundAdd(unwithdrawn, withdrawals.approved)
|
||||
if !ok {
|
||||
return commissionProjection{}, errors.New(errors.CodeInternalError, "计算累计佣金时发生整数溢出")
|
||||
}
|
||||
available, ok := safeFundSub(balance, withdrawals.pending)
|
||||
if !ok {
|
||||
return commissionProjection{}, errors.New(errors.CodeInternalError, "计算可提现佣金时发生整数溢出")
|
||||
}
|
||||
if available < 0 {
|
||||
available = 0
|
||||
}
|
||||
return commissionProjection{total: total, unwithdrawn: unwithdrawn, frozen: frozen, available: available}, nil
|
||||
}
|
||||
|
||||
func safeFundAdd(left, right int64) (int64, bool) {
|
||||
if (right > 0 && left > math.MaxInt64-right) || (right < 0 && left < math.MinInt64-right) {
|
||||
return 0, false
|
||||
}
|
||||
return left + right, true
|
||||
}
|
||||
|
||||
func safeFundSub(left, right int64) (int64, bool) {
|
||||
if (right > 0 && left < math.MinInt64+right) || (right < 0 && left > math.MaxInt64+right) {
|
||||
return 0, false
|
||||
}
|
||||
return left - right, true
|
||||
}
|
||||
Reference in New Issue
Block a user