Files
go-sms-V2/internal/service/settle/bill.go
T

494 lines
15 KiB
Go

// bill.go S2-D4:月结出账引擎——下家(SettleCustomer)/上家(SettleUpstream)
// 生成-确认-结账全链 + 阶梯应用 + 按天明细。
//
// 数据源(R2):下家=billing_consume_log(账号×业务×天);上家=stats_channel_daily
// (通道×天)按 channel 当前 upstream_id 归并(Q4:换绑历史不拆分,按生成时点)。
// 幂等(Q6):uk(account|upstream,period) UPSERT 重算覆盖;status=2 已结拒重算
// (ISC:039);金额=元,条→元换算只在 price.go(R6 单点)。
package settle
import (
"context"
"fmt"
"time"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"go-sms/internal/model/entity"
errs "go-sms/internal/pkg/errors"
)
// PeriodBounds "YYYY-MM" → [start, nextStart);非法格式 ISC:400。
func PeriodBounds(period string) (time.Time, time.Time, error) {
start, err := time.ParseInLocation("2006-01", period, time.Local)
if err != nil {
return time.Time{}, time.Time{}, errs.InvalidParam.WithMsg("period 须为 YYYY-MM")
}
return start, start.AddDate(0, 1, 0), nil
}
// GenerateResult 生成/重算统计。
type GenerateResult struct {
Generated int `json:"generated"` // 新建
Recalculated int `json:"recalculated"` // 覆盖重算(0/1 态)
Skipped int `json:"skipped"` // 已结(status=2)跳过
}
// GenerateCustomerBills 下家账期出账:遍历当月有消耗账号,逐业务逐日计价,
// 阶梯落档覆写(Q2);单账号粒度幂等,已结跳过。
func (s *Service) GenerateCustomerBills(ctx context.Context, period string) (*GenerateResult, error) {
lo, hi, err := PeriodBounds(period)
if err != nil {
return nil, err
}
res := &GenerateResult{}
var accountIDs []int64
if err := s.db.WithContext(ctx).Model(&entity.BillingConsumeLog{}).
Where("stat_date >= ? AND stat_date < ?", lo, hi).
Distinct().Pluck("account_id", &accountIDs).Error; err != nil {
return nil, err
}
for _, accountID := range accountIDs {
var exist entity.SettleCustomer
q := s.db.WithContext(ctx).Where("account_id = ? AND period = ?", accountID, period).First(&exist)
if q.Error == nil && exist.Status == 2 {
res.Skipped++
continue
}
var rows []entity.BillingConsumeLog
if err := s.db.WithContext(ctx).
Where("account_id = ? AND stat_date >= ? AND stat_date < ?", accountID, lo, hi).
Order("stat_date").Find(&rows).Error; err != nil {
return nil, err
}
var successTotal int64
var amount float64
for _, r := range rows {
successTotal += int64(r.SuccessCount)
price, _ := s.PriceAtAccount(ctx, accountID, r.Business, r.StatDate)
amount += float64(r.SuccessCount) * price
}
// 阶梯覆写:月成功总量落档,整月单价按档价(Q2)。
if p, ok := s.LadderPrice(ctx, "account", accountID, successTotal); ok {
amount = float64(successTotal) * p
}
bill := entity.SettleCustomer{
SettleNo: fmt.Sprintf("SC%s-%d", lo.Format("200601"), accountID),
AccountID: accountID,
Period: period,
SuccessCount: successTotal,
Amount: amount,
}
if err := s.db.WithContext(ctx).Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "account_id"}, {Name: "period"}},
DoUpdates: clause.AssignmentColumns([]string{"settle_no", "success_count", "amount"}),
}).Create(&bill).Error; err != nil {
return nil, err
}
if q.Error == nil {
res.Recalculated++
} else {
res.Generated++
}
}
return res, nil
}
// GenerateUpstreamBills 上家账期出账:通道按当前 upstream_id 归并(Q4),
// 计费条数随通道 billing_mode(Q3:all=submit/success_unknown=+unknown/空=success)。
func (s *Service) GenerateUpstreamBills(ctx context.Context, period string) (*GenerateResult, error) {
lo, hi, err := PeriodBounds(period)
if err != nil {
return nil, err
}
res := &GenerateResult{}
var channelIDs []int64
if err := s.db.WithContext(ctx).Model(&entity.StatsChannelDaily{}).
Where("stat_date >= ? AND stat_date < ?", lo, hi).
Distinct().Pluck("channel_id", &channelIDs).Error; err != nil {
return nil, err
}
var channels []entity.ChannelChannel
if err := s.db.WithContext(ctx).Find(&channels).Error; err != nil {
return nil, err
}
modeOf := map[int64]string{}
upstreamOf := map[int64]int64{}
for _, ch := range channels {
modeOf[ch.ID] = ch.BillingMode
upstreamOf[ch.ID] = ch.UpstreamID
}
type upAcc struct {
count int64
amount float64
}
ups := map[int64]*upAcc{}
for _, channelID := range channelIDs {
var rows []entity.StatsChannelDaily
if err := s.db.WithContext(ctx).
Where("channel_id = ? AND stat_date >= ? AND stat_date < ?", channelID, lo, hi).
Order("stat_date").Find(&rows).Error; err != nil {
return nil, err
}
uid := upstreamOf[channelID]
if uid == 0 {
continue // 未绑上家的通道不进上家账单
}
acc := ups[uid]
if acc == nil {
acc = &upAcc{}
ups[uid] = acc
}
for _, r := range rows {
bc := billableCount(modeOf[channelID], r)
acc.count += int64(bc)
price, _ := s.PriceAtChannel(ctx, channelID, r.StatDate)
acc.amount += float64(bc) * price
}
}
for uid, acc := range ups {
var exist entity.SettleUpstream
q := s.db.WithContext(ctx).Where("upstream_id = ? AND period = ?", uid, period).First(&exist)
if q.Error == nil && exist.Status == 2 {
res.Skipped++
continue
}
amount := acc.amount
if p, ok := s.LadderPrice(ctx, "upstream", uid, acc.count); ok {
amount = float64(acc.count) * p
}
bill := entity.SettleUpstream{
SettleNo: fmt.Sprintf("US%s-%d", lo.Format("200601"), uid),
UpstreamID: uid,
Period: period,
SuccessCount: acc.count,
Amount: amount,
}
if err := s.db.WithContext(ctx).Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "upstream_id"}, {Name: "period"}},
DoUpdates: clause.AssignmentColumns([]string{"settle_no", "success_count", "amount"}),
}).Create(&bill).Error; err != nil {
return nil, err
}
if q.Error == nil {
res.Recalculated++
} else {
res.Generated++
}
}
return res, nil
}
// billableCount 通道计费口径(Q3):all=submit;success_unknown=成功+未知;
// success/空=仅成功(保守缺省)。
func billableCount(mode string, r entity.StatsChannelDaily) int {
switch mode {
case "all":
return r.SubmitCount
case "success_unknown":
return r.SuccessCount + r.UnknownCount
default:
return r.SuccessCount
}
}
// ---- 确认/结账(Q6 状态机:0草稿→1已确认→2已结账;非法迁移 ISC:039) ----
// ConfirmCustomerBill 下家账单 0→1(人工核对锁账)。
func (s *Service) ConfirmCustomerBill(ctx context.Context, id int64) error {
res := s.db.WithContext(ctx).Model(&entity.SettleCustomer{}).
Where("id = ? AND status = 0", id).Update("status", 1)
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return settleStateConflict(ctx, s.db, "settle_customer", id)
}
return nil
}
// ConfirmUpstreamBill 上家同构。
func (s *Service) ConfirmUpstreamBill(ctx context.Context, id int64) error {
res := s.db.WithContext(ctx).Model(&entity.SettleUpstream{}).
Where("id = ? AND status = 0", id).Update("status", 1)
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return settleStateConflict(ctx, s.db, "settle_upstream", id)
}
return nil
}
// SettleCustomerBill 下家结账 1→2 + SettleRecord(direction=1)同事务。
func (s *Service) SettleCustomerBill(ctx context.Context, id int64, payType, operator, remark string) (*entity.SettleRecord, error) {
return s.settleBill(ctx, false, id, payType, operator, remark)
}
// SettleUpstreamBill 上家结账(direction=2)。
func (s *Service) SettleUpstreamBill(ctx context.Context, id int64, payType, operator, remark string) (*entity.SettleRecord, error) {
return s.settleBill(ctx, true, id, payType, operator, remark)
}
// settleBill 结账公共实现:1→2 CAS + settle_record 同事务(金额快照)。
func (s *Service) settleBill(ctx context.Context, upstream bool, id int64, payType, operator, remark string) (*entity.SettleRecord, error) {
var rec entity.SettleRecord
err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
direction := int8(1)
if upstream {
direction = 2
}
res := tx.Table("settle_customer").Where("id = ? AND status = 1", id).Update("status", 2)
if upstream {
res = tx.Table("settle_upstream").Where("id = ? AND status = 1", id).Update("status", 2)
}
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
table := "settle_customer"
if upstream {
table = "settle_upstream"
}
return settleStateConflict(ctx, tx, table, id)
}
var row struct {
SettleNo string
Amount float64
}
q := tx.Table("settle_customer").Where("id = ?", id)
if upstream {
q = tx.Table("settle_upstream").Where("id = ?", id)
}
if err := q.Select("settle_no", "amount").Scan(&row).Error; err != nil {
return err
}
rec = entity.SettleRecord{
SettleNo: row.SettleNo, Direction: direction, Amount: row.Amount,
PayType: payType, Operator: operator,
SettledAt: time.Now(), Remark: remark,
}
return tx.Create(&rec).Error
})
if err != nil {
return nil, err
}
return &rec, nil
}
// settleStateConflict 状态冲突 → ISC:039(不存在 → 404)。
func settleStateConflict(ctx context.Context, db *gorm.DB, table string, id int64) error {
var n int64
db.Table(table).Where("id = ?", id).Count(&n)
if n == 0 {
return errs.NotFound.WithMsg(fmt.Sprintf("结算单 %d 不存在", id))
}
return errs.OrderStatusConflict.WithMsg(fmt.Sprintf("结算单 %d 状态不允许该操作", id))
}
// ---- 查询与明细 ----
// BillQuery 账单列表条件(OwnerID:customer=account_id/upstream=upstream_id)。
type BillQuery struct {
Period string
OwnerID int64
Status *int8
Page int
PageSize int
}
// BillDayRow 账单按天明细行。
type BillDayRow struct {
Day string `json:"day"`
SuccessCount int64 `json:"success_count"`
Amount float64 `json:"amount"`
}
// ListCustomerBills 下家账单分页(id 倒序)。
func (s *Service) ListCustomerBills(ctx context.Context, q BillQuery) ([]entity.SettleCustomer, int64, error) {
db := s.db.WithContext(ctx).Model(&entity.SettleCustomer{})
if q.Period != "" {
db = db.Where("period = ?", q.Period)
}
if q.OwnerID > 0 {
db = db.Where("account_id = ?", q.OwnerID)
}
if q.Status != nil {
db = db.Where("status = ?", *q.Status)
}
var total int64
if err := db.Count(&total).Error; err != nil {
return nil, 0, err
}
if q.Page <= 0 {
q.Page = 1
}
if q.PageSize <= 0 || q.PageSize > 100 {
q.PageSize = 20
}
var list []entity.SettleCustomer
err := db.Order("id DESC").Limit(q.PageSize).Offset((q.Page - 1) * q.PageSize).Find(&list).Error
return list, total, err
}
// ListUpstreamBills 上家账单分页。
func (s *Service) ListUpstreamBills(ctx context.Context, q BillQuery) ([]entity.SettleUpstream, int64, error) {
db := s.db.WithContext(ctx).Model(&entity.SettleUpstream{})
if q.Period != "" {
db = db.Where("period = ?", q.Period)
}
if q.OwnerID > 0 {
db = db.Where("upstream_id = ?", q.OwnerID)
}
if q.Status != nil {
db = db.Where("status = ?", *q.Status)
}
var total int64
if err := db.Count(&total).Error; err != nil {
return nil, 0, err
}
if q.Page <= 0 {
q.Page = 1
}
if q.PageSize <= 0 || q.PageSize > 100 {
q.PageSize = 20
}
var list []entity.SettleUpstream
err := db.Order("id DESC").Limit(q.PageSize).Offset((q.Page - 1) * q.PageSize).Find(&list).Error
return list, total, err
}
// GetCustomerBill 下家账单单头。
func (s *Service) GetCustomerBill(ctx context.Context, id int64) (*entity.SettleCustomer, error) {
var b entity.SettleCustomer
if err := s.db.WithContext(ctx).First(&b, id).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return nil, errs.NotFound.WithMsg(fmt.Sprintf("结算单 %d 不存在", id))
}
return nil, err
}
return &b, nil
}
// GetUpstreamBill 上家账单单头。
func (s *Service) GetUpstreamBill(ctx context.Context, id int64) (*entity.SettleUpstream, error) {
var b entity.SettleUpstream
if err := s.db.WithContext(ctx).First(&b, id).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return nil, errs.NotFound.WithMsg(fmt.Sprintf("结算单 %d 不存在", id))
}
return nil, err
}
return &b, nil
}
// CustomerBillDays 下家账单按天明细(逐业务逐日计价加总,与出账同口径重算)。
func (s *Service) CustomerBillDays(ctx context.Context, bill *entity.SettleCustomer) ([]BillDayRow, error) {
lo, hi, err := PeriodBounds(bill.Period)
if err != nil {
return nil, err
}
var rows []entity.BillingConsumeLog
if err := s.db.WithContext(ctx).
Where("account_id = ? AND stat_date >= ? AND stat_date < ?", bill.AccountID, lo, hi).
Order("stat_date").Find(&rows).Error; err != nil {
return nil, err
}
byDay := map[string]*BillDayRow{}
var order []string
for _, r := range rows {
key := r.StatDate.Format("2006-01-02")
d, ok := byDay[key]
if !ok {
d = &BillDayRow{Day: key}
byDay[key] = d
order = append(order, key)
}
d.SuccessCount += int64(r.SuccessCount)
price, _ := s.PriceAtAccount(ctx, bill.AccountID, r.Business, r.StatDate)
d.Amount += float64(r.SuccessCount) * price
}
out := make([]BillDayRow, 0, len(order))
for _, k := range order {
out = append(out, *byDay[k])
}
return out, nil
}
// ---- 阶梯档位 CRUD(R5) ----
// ListLadders 档位列表(owner 过滤,tier_from 升序)。
func (s *Service) ListLadders(ctx context.Context, ownerType string, ownerID int64) ([]entity.SettleLadder, error) {
db := s.db.WithContext(ctx).Model(&entity.SettleLadder{})
if ownerType != "" {
db = db.Where("owner_type = ?", ownerType)
}
if ownerID > 0 {
db = db.Where("owner_id = ?", ownerID)
}
var list []entity.SettleLadder
err := db.Order("tier_from").Find(&list).Error
return list, err
}
// CreateLadder 新增档位(同 owner 同 tier_from 唯一,重复 ISC:400)。
func (s *Service) CreateLadder(ctx context.Context, l *entity.SettleLadder) error {
if l.OwnerType != "account" && l.OwnerType != "upstream" {
return errs.InvalidParam.WithMsg("owner_type 须为 account/upstream")
}
if l.TierFrom < 0 || l.Price <= 0 {
return errs.InvalidParam.WithMsg("tier_from 须≥0 且 price 须>0")
}
if err := s.db.WithContext(ctx).Create(l).Error; err != nil {
if isDuplicateKey(err) {
return errs.InvalidParam.WithMsg("该 owner 已存在同下限档位")
}
return err
}
return nil
}
// UpdateLadder 修改档位(price/tier_from;tier_from 冲突 ISC:400)。
func (s *Service) UpdateLadder(ctx context.Context, id int64, tierFrom *int64, price *float64) error {
updates := map[string]any{}
if tierFrom != nil {
if *tierFrom < 0 {
return errs.InvalidParam.WithMsg("tier_from 须≥0")
}
updates["tier_from"] = *tierFrom
}
if price != nil {
if *price <= 0 {
return errs.InvalidParam.WithMsg("price 须>0")
}
updates["price"] = *price
}
if len(updates) == 0 {
return nil
}
res := s.db.WithContext(ctx).Model(&entity.SettleLadder{}).Where("id = ?", id).Updates(updates)
if res.Error != nil {
if isDuplicateKey(res.Error) {
return errs.InvalidParam.WithMsg("该 owner 已存在同下限档位")
}
return res.Error
}
if res.RowsAffected == 0 {
return errs.NotFound.WithMsg(fmt.Sprintf("档位 %d 不存在", id))
}
return nil
}
// DeleteLadder 删除档位。
func (s *Service) DeleteLadder(ctx context.Context, id int64) error {
res := s.db.WithContext(ctx).Delete(&entity.SettleLadder{}, id)
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return errs.NotFound.WithMsg(fmt.Sprintf("档位 %d 不存在", id))
}
return nil
}