Files
yunzerwebsiteallinone/go/services/tenant_storage.go
T
2026-11-16 11:32:16 +08:00

279 lines
7.9 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package services
import (
"errors"
"fmt"
"math"
"strings"
"time"
"server/models"
"github.com/beego/beego/v2/client/orm"
)
// DefaultTenantStorageMB 租户默认附件空间(MB)。
// 未配置基础额度、也没买套餐时按 500MB 兜底。
const DefaultTenantStorageMB = 500
const bytesPerMB = 1024 * 1024
// StorageQuotaExceededError 附件空间不足
type StorageQuotaExceededError struct {
UsedBytes uint64
QuotaBytes uint64
RequiredBytes uint64
}
func (e *StorageQuotaExceededError) Error() string {
return fmt.Sprintf(
"附件空间不足:已用 %.2fMB / 共 %.2fMB,本次需要 %.2fMB,请购买扩容",
float64(e.UsedBytes)/bytesPerMB,
float64(e.QuotaBytes)/bytesPerMB,
float64(e.RequiredBytes)/bytesPerMB,
)
}
// TenantStorageInfo 租户附件空间使用情况
type TenantStorageInfo struct {
Tid uint64 `json:"tid"`
BaseQuotaMB int `json:"base_quota_mb"` // 基础额度(租户字段,默认 500)
PackageQuotaMB int `json:"package_quota_mb"` // 生效套餐容量(无套餐为 0)
QuotaMB int `json:"quota_mb"` // 实际可用 = max(基础, 套餐)
UsedBytes uint64 `json:"used_bytes"`
QuotaBytes uint64 `json:"quota_bytes"`
RemainingBytes uint64 `json:"remaining_bytes"`
UsedPercent float64 `json:"used_percent"`
PackageID uint64 `json:"package_id"`
PackageName string `json:"package_name"`
ExpireTime *time.Time `json:"expire_time"`
DaysRemaining int `json:"days_remaining"`
}
// SumTenantStorageUsed 统计租户已用附件空间(字节)。
//
// 注意:这里**不过滤 delete_time**。
// 软删除只是标记 delete_time(回收站),记录仍然存在、磁盘仍然占用;
// 只有「彻底删除」才会物理删行,此时统计自然减少 —— 即“彻底删除才释放空间”。
// 只统计租户端上传(source=backend)的文件:平台端上传不占租户额度。
func SumTenantStorageUsed(tid uint64) (uint64, error) {
if tid == 0 {
return 0, nil
}
var rows []orm.Params
_, err := models.Orm.Raw(
"SELECT COALESCE(SUM(size), 0) AS total FROM yz_system_files WHERE tid = ? AND source = ?",
tid, models.FileSourceBackend,
).Values(&rows)
if err != nil {
return 0, err
}
if len(rows) == 0 {
return 0, nil
}
return toUint64(rows[0]["total"]), nil
}
// toUint64 兼容驱动返回的 int64 / uint64 / []byte / string
func toUint64(v interface{}) uint64 {
switch n := v.(type) {
case int64:
if n < 0 {
return 0
}
return uint64(n)
case uint64:
return n
case int:
if n < 0 {
return 0
}
return uint64(n)
case []byte:
var out uint64
_, _ = fmt.Sscan(string(n), &out)
return out
case string:
var out uint64
_, _ = fmt.Sscan(n, &out)
return out
default:
return 0
}
}
// GetActiveStorageOrder 取租户当前生效的附件空间订单。
// 正常情况下同一时刻只有一条(购买不同规格时旧的会被置为 replaced),
// 这里按容量倒序取第一条,兼容历史数据。
func GetActiveStorageOrder(tid uint64) (*models.SystemTenantStorageOrder, error) {
if tid == 0 {
return nil, nil
}
now := time.Now()
var order models.SystemTenantStorageOrder
err := models.Orm.QueryTable(new(models.SystemTenantStorageOrder)).
Filter("tid", tid).
Filter("status", models.StorageOrderPaid).
Filter("delete_time__isnull", true).
Filter("end_time__gt", now).
OrderBy("-capacity_mb", "-id").
One(&order)
if err == orm.ErrNoRows {
return nil, nil
}
if err != nil {
return nil, err
}
return &order, nil
}
// GetTenantStorageInfo 查询租户附件空间使用情况
func GetTenantStorageInfo(tid uint64) (*TenantStorageInfo, error) {
info := &TenantStorageInfo{Tid: tid, BaseQuotaMB: DefaultTenantStorageMB}
var tenant models.SystemTenant
if err := models.Orm.QueryTable(new(models.SystemTenant)).
Filter("id", tid).
One(&tenant); err != nil {
return nil, err
}
if tenant.StorageQuotaMB > 0 {
info.BaseQuotaMB = tenant.StorageQuotaMB
}
order, err := GetActiveStorageOrder(tid)
if err != nil {
return nil, err
}
if order != nil {
info.PackageID = order.PackageID
info.PackageName = order.PackageName
info.PackageQuotaMB = order.CapacityMB
info.ExpireTime = order.EndTime
if order.EndTime != nil {
days := int(math.Ceil(order.EndTime.Sub(time.Now()).Hours() / 24))
if days < 0 {
days = 0
}
info.DaysRemaining = days
}
}
info.QuotaMB = info.BaseQuotaMB
if info.PackageQuotaMB > info.QuotaMB {
info.QuotaMB = info.PackageQuotaMB
}
used, err := SumTenantStorageUsed(tid)
if err != nil {
return nil, err
}
info.UsedBytes = used
info.QuotaBytes = uint64(info.QuotaMB) * bytesPerMB
if info.UsedBytes >= info.QuotaBytes {
info.RemainingBytes = 0
} else {
info.RemainingBytes = info.QuotaBytes - info.UsedBytes
}
if info.QuotaBytes > 0 {
info.UsedPercent = math.Round(float64(info.UsedBytes)/float64(info.QuotaBytes)*1000) / 10
}
return info, nil
}
// EnsureTenantStorageQuota 上传前校验:已用 + 本次大小不得超过可用额度。
// 超限返回 *StorageQuotaExceededError,调用方据此返回 403。
func EnsureTenantStorageQuota(tid uint64, addBytes uint64) error {
if tid == 0 || addBytes == 0 {
return nil
}
info, err := GetTenantStorageInfo(tid)
if err != nil {
return err
}
if info.QuotaBytes > 0 && info.UsedBytes+addBytes > info.QuotaBytes {
return &StorageQuotaExceededError{
UsedBytes: info.UsedBytes,
QuotaBytes: info.QuotaBytes,
RequiredBytes: addBytes,
}
}
return nil
}
// BuildStorageOrderNo 生成附件空间订单号
func BuildStorageOrderNo(tid uint64) string {
return fmt.Sprintf("ST%d%s%s", tid, time.Now().Format("20060102150405"), randomHex(4))
}
// ActivateStorageOrder 支付成功后激活附件空间订单。
//
// 规则(与产品确认一致):
// - 同一套餐续费:在现有到期时间上顺延,容量不变;
// - 购买不同规格:新套餐立即生效,旧的已支付订单置为 replaced(只保留一个);
// - 幂等:订单已是 paid 时直接返回。
func ActivateStorageOrder(orderNo, payNo string) error {
orderNo = strings.TrimSpace(orderNo)
if orderNo == "" {
return errors.New("订单号不能为空")
}
var order models.SystemTenantStorageOrder
err := models.Orm.QueryTable(new(models.SystemTenantStorageOrder)).
Filter("order_no", orderNo).
Filter("delete_time__isnull", true).
One(&order)
if err != nil {
return fmt.Errorf("附件空间订单 %s 不存在: %w", orderNo, err)
}
if order.Status == models.StorageOrderPaid {
return nil
}
if order.Status == models.StorageOrderCancelled || order.Status == models.StorageOrderReplaced {
return fmt.Errorf("订单 %s 状态为 %s,不能激活", orderNo, order.Status)
}
now := time.Now()
start := now
end := now.AddDate(0, 0, order.DurationDays)
// 同规格续费:从原到期时间顺延
var sameOrder models.SystemTenantStorageOrder
sameErr := models.Orm.QueryTable(new(models.SystemTenantStorageOrder)).
Filter("tid", order.Tid).
Filter("package_id", order.PackageID).
Filter("status", models.StorageOrderPaid).
Filter("end_time__gt", now).
Filter("order_no__ne", order.OrderNo).
OrderBy("-end_time").
One(&sameOrder)
if sameErr == nil && sameOrder.EndTime != nil && sameOrder.EndTime.After(now) {
start = *sameOrder.EndTime
end = start.AddDate(0, 0, order.DurationDays)
} else {
// 不同规格:旧的生效订单作废(只保留最大的一个)
_, _ = models.Orm.QueryTable(new(models.SystemTenantStorageOrder)).
Filter("tid", order.Tid).
Filter("status", models.StorageOrderPaid).
Filter("order_no__ne", order.OrderNo).
Update(orm.Params{
"status": models.StorageOrderReplaced,
"update_time": now,
})
}
order.Status = models.StorageOrderPaid
if payNo != "" {
order.PayNo = payNo
}
order.StartTime = &start
order.EndTime = &end
order.UpdateTime = &now
if _, err := models.Orm.Update(&order, "Status", "PayNo", "StartTime", "EndTime", "UpdateTime"); err != nil {
return err
}
return nil
}