model

package
v0.0.0-...-30b4b00 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 5, 2026 License: AGPL-3.0 Imports: 43 Imported by: 0

Documentation

Overview

Copyright (C) 2023-2026 FastToken

This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.

For commercial licensing, please contact hello@fasttoken.example.com

Index

Constants

View Source
const (
	WalletTxnTypeRecharge = "recharge"
	WalletTxnTypeGrant    = "grant"
	WalletTxnTypeRecycle  = "recycle"
	WalletTxnTypeConsume  = "consume"
	WalletTxnTypeRefund   = "refund"
)

企业钱包流水类型

View Source
const (
	LogTypeUnknown = 0
	LogTypeTopup   = 1
	LogTypeConsume = 2
	LogTypeManage  = 3
	LogTypeSystem  = 4
	LogTypeError   = 5
	LogTypeRefund  = 6
)

don't use iota, avoid change log type value

View Source
const (
	NameRuleExact = iota
	NameRulePrefix
	NameRuleContains
	NameRuleSuffix
)
View Source
const (
	SkillStatusDraft      = "draft"
	SkillStatusPublished  = "published"
	SkillStatusDeprecated = "deprecated"
)

技能发布状态枚举。仅 SkillStatusPublished 对普通用户可见。

View Source
const (
	TaskStatusNotStart   TaskStatus = "NOT_START"
	TaskStatusSubmitted             = "SUBMITTED"
	TaskStatusQueued                = "QUEUED"
	TaskStatusInProgress            = "IN_PROGRESS"
	TaskStatusFailure               = "FAILURE"
	TaskStatusSuccess               = "SUCCESS"
	TaskStatusUnknown               = "UNKNOWN"
)
View Source
const (
	WalletTypeWallet     = "wallet"
	WalletTypeEnterprise = "enterprise"
)

充值入账目标钱包类型

View Source
const (
	GiftStatusActive  = "active"  // 可用
	GiftStatusUsed    = "used"    // 已使用
	GiftStatusExpired = "expired" // 已过期
)
View Source
const (
	PaymentMethodAlipay = "alipay"
	PaymentMethodWechat = "wxpay"
)
View Source
const (
	PaymentProviderEpay   = "epay"
	PaymentProviderAlipay = "alipay"
	PaymentProviderWechat = "wxpay"
)
View Source
const (
	BatchUpdateTypeUserQuota = iota
	BatchUpdateTypeTokenQuota
	BatchUpdateTypeUsedQuota
	BatchUpdateTypeChannelUsedQuota
	BatchUpdateTypeRequestCount
	BatchUpdateTypeCount // if you add a new type, you need to add a new map and a new lock
)
View Source
const TopUpExpireSeconds = 2 * 60 * 60 // 2 hours

TopUpExpireSeconds 充值订单超时时间(秒)。 微信 Native 支付订单默认 2 小时有效期,支付宝电脑网站支付通常 1-2 小时。

View Source
const UserNameMaxLength = 50

Variables

View Source
var (
	ErrInvalidCredentials   = errors.New("invalid credentials")
	ErrUserEmptyCredentials = errors.New("empty credentials")
	ErrUserNotFound         = errors.New("user not found")
)

User auth errors

View Source
var (
	ErrTokenNotProvided = errors.New("token not provided")
	ErrTokenInvalid     = errors.New("token invalid")
)

Token auth errors

View Source
var (
	ErrPaymentMethodMismatch = errors.New("payment method mismatch")
	ErrTopUpNotFound         = errors.New("topup not found")
	ErrTopUpStatusInvalid    = errors.New("topup status invalid")
)
View Source
var CacheQuotaData = make(map[string]*QuotaData)
View Source
var CacheQuotaDataLock = sync.Mutex{}
View Source
var DB *gorm.DB
View Source
var ErrActivityAlreadyGranted = errors.New("activity already granted")
View Source
var (
	ErrDatabase = errors.New("database error")
)

Common errors

View Source
var ErrGiftLimitExceeded = errors.New("gift issue limit exceeded")

ErrGiftLimitExceeded 表示赠品已达发放上限,拒绝继续发放。

View Source
var ErrRedeemFailed = errors.New("redeem.failed")

Redemption errors

View Source
var LOG_DB *gorm.DB

Functions

func AdminUpdateGiftStatus

func AdminUpdateGiftStatus(id int, status string) error

AdminUpdateGiftStatus 管理员更新礼物状态

func ApplyChannelGroupFilter

func ApplyChannelGroupFilter(query *gorm.DB, group string) *gorm.DB

func ApproveEnterprise

func ApproveEnterprise(id int, approvedBy int) error

func BatchAddUsersToEnterprise

func BatchAddUsersToEnterprise(enterpriseId int, userIds []int, role string) error

BatchAddUsersToEnterprise 批量添加用户到企业

func BatchCreateInvitationCodes

func BatchCreateInvitationCodes(codes []*InvitationCode) error

func BatchDeleteChannels

func BatchDeleteChannels(ids []int) error

func BatchDeleteTokens

func BatchDeleteTokens(ids []int, userId int) (int, error)

BatchDeleteTokens 删除指定用户的一组令牌,返回成功删除数量

func BatchExpireMemberships

func BatchExpireMemberships() (int64, error)

BatchExpireMemberships 批量过期会员(定时任务调用)

func BatchInsertChannels

func BatchInsertChannels(channels []Channel) error

func BatchRemoveUsersFromEnterprise

func BatchRemoveUsersFromEnterprise(enterpriseId int, userIds []int) error

BatchRemoveUsersFromEnterprise 批量从企业移除用户

func BatchSetChannelTag

func BatchSetChannelTag(ids []int, tag *string) error

func BulkUpsertI18nMessages

func BulkUpsertI18nMessages(locale string, m map[string]string) error

BulkUpsertI18nMessages 批量覆盖某 locale 的文案(事务写入 + 热更新缓存)。

func CacheUpdateChannel

func CacheUpdateChannel(channel *Channel)

func CacheUpdateChannelStatus

func CacheUpdateChannelStatus(id int, status int)

func CalculateDiscountedPrice

func CalculateDiscountedPrice(originalPrice float64, membershipLevel string, membershipExpire int64) (float64, bool)

CalculateDiscountedPrice 计算折扣后价格(通用函数) 参数:

  • originalPrice: 原价
  • membershipLevel: 会员等级
  • membershipExpire: 会员过期时间(Unix时间戳,0=永不过期)

返回:

  • 折扣后价格
  • 是否应用了折扣

func CalculateModelCallDiscount

func CalculateModelCallDiscount(userId int, originalPrice float64) (float64, bool, error)

CalculateModelCallDiscount 计算模型调用折扣(用于计费) 在 controller/channel-api.go 的计费逻辑中调用

func CheckSetup

func CheckSetup()

func CheckUserExistOrDeleted

func CheckUserExistOrDeleted(username string, email string) (bool, error)

func CleanExpiredSMSCodes

func CleanExpiredSMSCodes() error

CleanExpiredSMSCodes 清理过期的验证码(定时任务调用)

func CleanupChannelPollingLocks

func CleanupChannelPollingLocks()

CleanupChannelPollingLocks removes locks for channels that no longer exist This is optional and can be called periodically to prevent memory leaks

func CloseDB

func CloseDB() error

func ConsumeEUQuota

func ConsumeEUQuota(id int, amount int) error

ConsumeEUQuota 消费成员企业余额:扣 quota 同时累加 used_quota(单条 SQL 原子完成)。 条件更新保证余额不足时不产生任何变更并返回错误。

func CountAllChannels

func CountAllChannels() (int64, error)

CountAllChannels returns total channels in DB

func CountAllTags

func CountAllTags() (int64, error)

CountAllTags returns number of non-empty distinct tags

func CountAllTasks

func CountAllTasks(queryParams TaskQueryParams) int64

CountAllTasks returns total midjourney tasks for admin query

func CountAllUserTask

func CountAllUserTask(userId int, queryParams TaskQueryParams) int64

CountAllUserTask returns total midjourney tasks for user

func CountChannelTags

func CountChannelTags(query *gorm.DB) (int64, error)

func CountChannelsByType

func CountChannelsByType(channelType int) (int64, error)

Count channels of specific type

func CountChannelsGroupByType

func CountChannelsGroupByType() (map[int64]int64, error)

Return map[type]count for all channels

func CountUserTokens

func CountUserTokens(userId int) (int64, error)

CountUserTokens returns total number of tokens for the given user, used for pagination

func CreateActivity

func CreateActivity(a *Activity) error

func CreateEnterprise

func CreateEnterprise(e *Enterprise) error

func CreateEnterpriseUser

func CreateEnterpriseUser(eu *EnterpriseUser) error

func CreateGroupRatio

func CreateGroupRatio(gr *GroupRatio) error

CreateGroupRatio creates a new group ratio record.

func CreateInvitationCode

func CreateInvitationCode(ic *InvitationCode) error

func CreatePasskeyCredential

func CreatePasskeyCredential(cred *PasskeyCredential) error

CreatePasskeyCredential creates a new passkey credential

func CreateSkill

func CreateSkill(s *Skill) error

CreateSkill 插入一条技能记录。 唯一键冲突(PostgreSQL 23505)会原样向上返回,由 handler 通过 IsDuplicateKeyError 转 409。

func CreateUserOAuthBinding

func CreateUserOAuthBinding(binding *UserOAuthBinding) error

CreateUserOAuthBinding creates a new OAuth binding

func CreateUserOAuthBindingWithTx

func CreateUserOAuthBindingWithTx(tx *gorm.DB, binding *UserOAuthBinding) error

CreateUserOAuthBindingWithTx creates a new OAuth binding within a transaction

func CreateUserWebhook

func CreateUserWebhook(wh *UserWebhook) error

CreateUserWebhook creates a new webhook.

func DecreaseEUQuota

func DecreaseEUQuota(id int, amount int) error

DecreaseEUQuota 扣减成员企业余额(条件更新防负/防超卖)

func DecreaseTokenQuota

func DecreaseTokenQuota(id int, key string, quota int) (err error)

func DecreaseUserQuota

func DecreaseUserQuota(id int, quota int, force bool) error

DecreaseUserQuota decreases user's quota. When force is false, a conditional update (WHERE quota >= ?) prevents the balance from going negative and guards against concurrent oversell. When force is true (e.g. admin manual adjustment/write-off), the check is skipped.

func DecrementInviterAffCount

func DecrementInviterAffCount(inviterId int) error

DecrementInviterAffCount 在邀请关系解除或退款冲销时,将邀请人的 已邀请(注册)人数减 1。修复此前 aff_count 只增不减、导致推荐计划 统计虚高(退款后邀请人数不减)的缺陷。 使用条件表达式保证不会出现负数;inviterId<=0 时直接跳过。

func DeleteActivity

func DeleteActivity(id int) error

func DeleteChannelByStatus

func DeleteChannelByStatus(status int64) (int64, error)

func DeleteDisabledChannel

func DeleteDisabledChannel() (int64, error)

func DeleteEnterprise

func DeleteEnterprise(id int) error

func DeleteEnterpriseUser

func DeleteEnterpriseUser(id int) error

func DeleteGroupRatio

func DeleteGroupRatio(id int) error

DeleteGroupRatio deletes a group ratio record by id.

func DeleteInvalidRedemptions

func DeleteInvalidRedemptions() (int64, error)

func DeleteInvitationCode

func DeleteInvitationCode(id int) error

func DeleteOldLog

func DeleteOldLog(ctx context.Context, targetTimestamp int64, limit int) (int64, error)

func DeletePasskeyCredential

func DeletePasskeyCredential(id uint, userId int) error

DeletePasskeyCredential deletes a passkey credential by ID and user ID (ownership check)

func DeletePasskeyCredentialsByUserId

func DeletePasskeyCredentialsByUserId(userId int) error

DeletePasskeyCredentialsByUserId deletes all passkey credentials for a user

func DeletePerfMetricsBefore

func DeletePerfMetricsBefore(cutoffTs int64) error

func DeletePrefillGroupByID

func DeletePrefillGroupByID(id int) error

DeleteByID 根据 ID 删除组

func DeleteRedemptionById

func DeleteRedemptionById(id int) (err error)

func DeleteTokenById

func DeleteTokenById(id int, userId int) (err error)

func DeleteUiSkin

func DeleteUiSkin(key string) error

DeleteUiSkin 删除皮肤并热更新缓存。

func DeleteUserById

func DeleteUserById(id int) error

func DeleteUserOAuthBinding

func DeleteUserOAuthBinding(userId, providerId int) error

DeleteUserOAuthBinding deletes an OAuth binding

func DeleteUserWebhook

func DeleteUserWebhook(id int, userId int) error

DeleteUserWebhook deletes a webhook by id, ensuring it belongs to the user.

func DeltaUpdateUserQuota

func DeltaUpdateUserQuota(id int, delta int) error

DeltaUpdateUserQuota updates user's quota by delta

func DisableChannelByTag

func DisableChannelByTag(tag string) error

func DisableModelLimits

func DisableModelLimits(tokenId int) error

func DispatchActivityEvent

func DispatchActivityEvent(eventType string, userID int, payload map[string]any) error

DispatchActivityEvent 沿指定事件类型分发所有启用的活动并统一发放。 payload 至少包含 "user_id";topup 事件额外含 "money"(float64) 与 "trade_no"(string)。

func EditChannelByTag

func EditChannelByTag(tag string, newTag *string, modelMapping *string, models *string, group *string, priority *int64, weight *uint, paramOverride *string, headerOverride *string) error

func EnableChannelByTag

func EnableChannelByTag(tag string) error

func EvaluateTopupGiftBonus

func EvaluateTopupGiftBonus(money float64) float64

func ExpireOldCodes

func ExpireOldCodes() (int64, error)

ExpireOldCodes 过期旧的邀请码(定时任务调用)

func ExpireStaleTopUps

func ExpireStaleTopUps() (int64, error)

func ExpireUserMembership

func ExpireUserMembership(userId int) error

ExpireUserMembership 过期用户会员(降级到白银)

func FixAbility

func FixAbility() (int, int, error)

func GenerateInvitationCodeFunc

func GenerateInvitationCodeFunc() string

GenerateInvitationCodeFunc 生成邀请码

func GenerateTaskID

func GenerateTaskID() string

GenerateTaskID 生成对外暴露的 task_xxxx 格式 ID

func GetBoundChannelsByModelsMap

func GetBoundChannelsByModelsMap(modelNames []string) (map[string][]BoundChannel, error)

func GetChannelPollingLock

func GetChannelPollingLock(channelId int) *sync.Mutex

GetChannelPollingLock returns or creates a mutex for the given channel ID

func GetDBTimestamp

func GetDBTimestamp() int64

GetDBTimestamp returns a UNIX timestamp from database time. Falls back to application time on error.

func GetDefaultUiSkin

func GetDefaultUiSkin() string

GetDefaultUiSkin 返回当前默认皮肤 key(运营可在后台改默认)。

func GetDefaultUserGroup

func GetDefaultUserGroup() string

GetDefaultUserGroup returns default group for new users

func GetDefaultUserQuota

func GetDefaultUserQuota() int

GetDefaultUserQuota returns default quota for new users

func GetDefaultUserSetting

func GetDefaultUserSetting() string

GetDefaultUserSetting returns default setting JSON for new users

func GetEUQuota

func GetEUQuota(enterpriseId int, userId int) (int, error)

GetEUQuota 读取成员企业余额

func GetEUQuotaById

func GetEUQuotaById(id int) (int, error)

GetEUQuotaById 按 enterprise_user 主键读取成员企业余额(选路热路径,只取单列)

func GetEnabledModels

func GetEnabledModels() []string

func GetEnterpriseStats

func GetEnterpriseStats(enterpriseId int) (map[string]interface{}, error)

GetEnterpriseStats 获取企业统计信息

func GetGroupEnabledModels

func GetGroupEnabledModels(group string) []string

func GetGroupRatio

func GetGroupRatio(groupName string, modelName string) float64

GetGroupRatio returns the ratio for a specific group and model combination. Returns 0 if no matching record is found (caller should treat 0 as "no override").

func GetI18nLocales

func GetI18nLocales() []string

GetI18nLocales 返回已有覆盖文案的 locale 列表(管理员本地化页用)。

func GetI18nOverrides

func GetI18nOverrides(locale string) map[string]string

GetI18nOverrides 返回指定 locale 的覆盖文案;locale 为空返回 nil。

func GetIntOption

func GetIntOption(key string, def int) int

GetIntOption 从选项表读取整数配置;缺失或非法时返回默认值。 用于把写死的魔法数/开关外部化为可热改的配置项(配置即数据)。

func GetMaxUserId

func GetMaxUserId() int

GetMaxUserId returns max user ID

func GetMissingModels

func GetMissingModels() ([]string, error)

GetMissingModels returns model names that are referenced in the system

func GetModelEnableGroups

func GetModelEnableGroups(modelName string) []string

func GetModelQuotaTypes

func GetModelQuotaTypes(modelName string) []int

GetModelQuotaTypes 返回指定模型的计费类型集合(来自缓存)

func GetModelSupportEndpointTypes

func GetModelSupportEndpointTypes(model string) []constant.EndpointType

func GetPaginatedChannelTags

func GetPaginatedChannelTags(query *gorm.DB, offset int, limit int) ([]*string, error)

func GetPaginatedTags

func GetPaginatedTags(offset int, limit int) ([]*string, error)

func GetPasskeyCredentialCount

func GetPasskeyCredentialCount(userId int) (int64, error)

GetPasskeyCredentialCount returns the number of passkey credentials for a user

func GetPreferredModelOwnerChannelTypes

func GetPreferredModelOwnerChannelTypes(modelNames []string, groups []string) (map[string]int, error)

func GetSupportedEndpointMap

func GetSupportedEndpointMap() map[string]common.EndpointInfo

GetSupportedEndpointMap 返回全局端点到路径的映射

func GetSystemSetting

func GetSystemSetting(key string, defaultValue string) string

GetSystemSetting returns system setting as string

func GetSystemSettingBool

func GetSystemSettingBool(key string, defaultValue bool) bool

GetSystemSettingBool returns system setting as bool

func GetSystemSettingIntOrDefault

func GetSystemSettingIntOrDefault(key string, defaultValue int) int

GetSystemSettingIntOrDefault returns a system setting as int. TODO: implement from database. Currently always returns defaultValue. WARNING: This is a placeholder - all callers will receive the hardcoded default.

func GetSystemSettingOrDefault

func GetSystemSettingOrDefault(key, defaultValue string) string

GetSystemSettingOrDefault returns system setting with default

func GetTopupGiftBonusMap

func GetTopupGiftBonusMap(amountOptions []int) map[int]int

GetTopupGiftBonusMap 供前端展示「面额 -> 赠送额」映射。

func GetUserByPasskeyCredentialID

func GetUserByPasskeyCredentialID(credentialID []byte) (*User, *PasskeyCredential, error)

GetUserByPasskeyCredentialID finds a user by their WebAuthn credential ID

func GetUserCheckinStats

func GetUserCheckinStats(userId int, month string) (map[string]interface{}, error)

GetUserCheckinStats 获取用户签到统计信息

func GetUserEmail

func GetUserEmail(id int) (string, error)

func GetUserEnterpriseId

func GetUserEnterpriseId(userId int) int

GetUserEnterpriseId 返回用户关联的企业 ID(无关联则返回 0)。 单列索引查询,开销极低,供 Phase 1 多租户隔离逻辑使用。

func GetUserGroup

func GetUserGroup(id int, fromDB bool) (string, error)

func GetUserIdByAffCode

func GetUserIdByAffCode(affCode string) (int, error)

GetUserIdByAffCode returns user ID by aff code

func GetUserIdByEmail

func GetUserIdByEmail(email string) int

func GetUserLanguage

func GetUserLanguage(userId int) string

GetUserLanguage returns the user's language preference from cache Uses the existing GetUserCache mechanism for efficiency

func GetUserQuota

func GetUserQuota(id int, fromDB bool) (int, error)

GetUserQuota returns user's quota

func GetUserSetting

func GetUserSetting(id int, fromDB bool) (dto.UserSetting, error)

func GetUserUsedQuota

func GetUserUsedQuota(id int) (int, error)

GetUserUsedQuota returns user's used quota

func GetUsernameById

func GetUsernameById(id int, fromDB bool) (string, error)

GetUsernameById returns the username of a user by ID

func GetVendorModelCounts

func GetVendorModelCounts() (map[int64]int64, error)

func GrantQuotaToUser

func GrantQuotaToUser(userID, quota int, dedupeKey string, activityID int) error

GrantQuotaToUser 在严格幂等(dedupe_key 唯一约束)下给用户发放配额。

func HardDeleteUserById

func HardDeleteUserById(id int) error

func HasCheckedInToday

func HasCheckedInToday(userId int) (bool, error)

HasCheckedInToday 检查用户今天是否已签到

func HasPasskeyCredential

func HasPasskeyCredential(userId int) (bool, error)

HasPasskeyCredential checks if a user has any passkey credential

func HigherMembershipLevel

func HigherMembershipLevel(a, b string) string

HigherMembershipLevel 返回两个等级中较高的;空值处理:a 为空返回 b,b 为空返回 a。 用于企业认证审批时「只升不降」地合并用户会员等级。

func IncrSkillDownloads

func IncrSkillDownloads(id int64) error

IncrSkillDownloads 下载计数原子 +1。使用 UpdateColumn 避免触发 GORM 的自动时间戳更新。

func IncreaseEUQuota

func IncreaseEUQuota(id int, amount int) error

IncreaseEUQuota 增加成员企业余额(条件更新防负)

func IncreaseTokenQuota

func IncreaseTokenQuota(tokenId int, key string, quota int) (err error)

func IncreaseUserQuota

func IncreaseUserQuota(id int, delta int, force bool) error

IncreaseUserQuota increases user's quota by delta

func InferDefaultVendor

func InferDefaultVendor(modelName string) (string, bool)

InferDefaultVendor tries to infer a vendor name from a model name using the built-in pattern rules. It returns the inferred vendor name and true if a pattern matched, otherwise ("", false).

func InferDefaultVendorIcon

func InferDefaultVendorIcon(vendorName string) string

InferDefaultVendorIcon returns the default icon key for a vendor name, or an empty string if no default icon is defined.

func InitBatchUpdater

func InitBatchUpdater()

func InitChannelCache

func InitChannelCache()

func InitConfigData

func InitConfigData()

InitConfigData 在 InitOptionMap 之后调用:把编译期默认值 seed 进数据库(仅首次), 并把数据库中的定价/文案加载进内存,使数据库成为运行时唯一真相源。

func InitDB

func InitDB() (err error)

func InitLogDB

func InitLogDB() (err error)

func InitOptionMap

func InitOptionMap()

func InvalidatePricingCache

func InvalidatePricingCache()

func InvalidateUserCache

func InvalidateUserCache(userId int) error

InvalidateUserCache is the exported version of invalidateUserCache. 供 controller 等上层包在用户状态变更(如禁用、删除、角色变更)后主动清理缓存。

func InvalidateUserTokensCache

func InvalidateUserTokensCache(userId int) error

InvalidateUserTokensCache 清理指定用户所有令牌在 Redis 中的缓存, 配合 InvalidateUserCache 使用,可在用户被禁用/删除时立即阻断其令牌的请求。 下一次请求将从数据库重新加载令牌及用户状态,从而立即识别出被禁用的用户。

func IsAdmin

func IsAdmin(userId int) bool

IsAdmin checks if user is admin

func IsChannelEnabledForAnyGroupModel

func IsChannelEnabledForAnyGroupModel(groups []string, modelName string, channelID int) bool

func IsChannelEnabledForGroupModel

func IsChannelEnabledForGroupModel(group string, modelName string, channelID int) bool

func IsDuplicateKeyError

func IsDuplicateKeyError(err error) bool

IsDuplicateKeyError 判断是否为唯一约束冲突(幂等重试场景)

func IsEmailAlreadyTaken

func IsEmailAlreadyTaken(email string) bool

func IsMembershipActive

func IsMembershipActive(user *User) bool

IsMembershipActive 检查用户会员是否有效

func IsModelNameDuplicated

func IsModelNameDuplicated(id int, name string) (bool, error)

func IsPhoneRegistered

func IsPhoneRegistered(phone string) (bool, error)

IsPhoneRegistered 检查手机号是否已注册

func IsPrefillGroupNameDuplicated

func IsPrefillGroupNameDuplicated(id int, name string) (bool, error)

IsPrefillGroupNameDuplicated 检查组名称是否重复(排除自身 ID)

func IsProviderUserIdTaken

func IsProviderUserIdTaken(providerId int, providerUserId string) bool

IsProviderUserIdTaken checks if a provider user ID is already bound to any user

func IsValidSkillStatus

func IsValidSkillStatus(status string) bool

IsValidSkillStatus 校验状态是否为合法枚举值。

func IsVendorNameDuplicated

func IsVendorNameDuplicated(id int, name string) (bool, error)

IsVendorNameDuplicated 检查供应商名称是否重复(排除自身 ID)

func IsWeChatIdAlreadyTaken

func IsWeChatIdAlreadyTaken(wechatId string) bool

func IssueGiftWithLimit

func IssueGiftWithLimit(gift *UserGift, maxIssued int) error

IssueGiftWithLimit 在严格限额下发放一个赠品:事务内对 gift_key 计数 +1, 若已达上限(issued >= maxIssued)则整体回滚并拒绝。这是 UserGiftCounter 的限额发放核心, 保证同一 gift_key 不超发(修复此前手动发放易超发的问题)。 幂等:gift.TradeNo 唯一约束保证同一笔关联订单不会重复发放,冲突时可安全重试。

func LoadModelPricingIntoRatioSetting

func LoadModelPricingIntoRatioSetting() error

LoadModelPricingIntoRatioSetting 把数据库中的定价加载回 ratio_setting 内存 map(覆盖编译期默认值)。

func LoadOptionsFromDatabase

func LoadOptionsFromDatabase() error

func LogQuotaData

func LogQuotaData(userId int, username string, modelName string, quota int, createdAt int64, tokenUsed int)

func ManualCompleteTopUp

func ManualCompleteTopUp(tradeNo string, callerIp string) error

ManualCompleteTopUp 管理员手动完成订单并给用户充值

func MaskTokenKey

func MaskTokenKey(key string) string

func MjBulkUpdate

func MjBulkUpdate(mjIds []string, params map[string]any) error

func MjBulkUpdateByTaskIds

func MjBulkUpdateByTaskIds(taskIDs []int, params map[string]any) error

func NormalizeChannelGroupFilter

func NormalizeChannelGroupFilter(group string) string

func NormalizeEmail

func NormalizeEmail(email string) string

NormalizeEmail returns a trimmed lowercase email for consistent comparison/storage

func OwnerOrTenantWhere

func OwnerOrTenantWhere(prefix string) string

OwnerOrTenantWhere 返回 Phase 1 租户可见性谓词。 语义:本人拥有的资源 OR 所属企业的共享资源。 个人用户 entId=0 时后半恒假,等价于 user_id = ?(向后兼容)。 prefix 用于多表查询时限定列名,如 "logs.";单表传 ""。

注意:返回值自带最外层括号。与其他条件用 AND 组合时不要拆括号, 否则 SQL 运算符优先级会让 AND 先与右侧结合,造成跨租户越权放行。 占位符顺序固定为 (userId, entId)。

func PerfMetricStartTime

func PerfMetricStartTime(hours int) int64

func PingDB

func PingDB() error

func ProcessReferralRebate

func ProcessReferralRebate(topUp *TopUp, callerIp string) error

ProcessReferralRebate 处理推荐返利:充值成功后给邀请人(及可选被推荐人)发放配额。 幂等:以 trade_no 唯一约束保证同一笔订单只返一次。

func RechargeAlipay

func RechargeAlipay(tradeNo string, callerIp string) (err error)

RechargeAlipay processes a successful Alipay payment and credits the user's quota.

func RechargeWechat

func RechargeWechat(tradeNo string, callerIp string) (err error)

RechargeWechat processes a successful Wechat Pay payment and credits the user's quota.

func RecordConsumeLog

func RecordConsumeLog(c *gin.Context, userId int, params RecordConsumeLogParams)

func RecordConsumeLogAsync

func RecordConsumeLogAsync(username, requestId, upstreamRequestId, clientIP string, userId int, params RecordConsumeLogParams)

RecordConsumeLogAsync 异步写入消费日志(不依赖 gin.Context,用于 worker pool)

func RecordEUUsedQuota

func RecordEUUsedQuota(id int, amount int) error

RecordEUUsedQuota 累加成员已用企业额度

func RecordErrorLog

func RecordErrorLog(c *gin.Context, userId int, channelId int, modelName string, tokenName string, content string, tokenId int, useTimeSeconds int,
	isStream bool, group string, other map[string]interface{})

func RecordExist

func RecordExist(err error) (bool, error)

func RecordLog

func RecordLog(userId int, logType int, content string)

func RecordLogWithAdminInfo

func RecordLogWithAdminInfo(userId int, logType int, content string, adminInfo map[string]interface{})

RecordLogWithAdminInfo 记录操作日志,并将管理员相关信息存入 Other.admin_info,

func RecordTaskBillingLog

func RecordTaskBillingLog(params RecordTaskBillingLogParams)

func RecordTopupLog

func RecordTopupLog(userId int, content string, callerIp string, paymentMethod string, callbackPaymentMethod string)

func Redeem

func Redeem(key string, userId int) (quota int, err error)

func RefreshPricing

func RefreshPricing()

RefreshPricing 强制立即重新计算与定价相关的缓存。 该方法用于需要最新数据的内部管理 API, 因此会绕过默认的 1 分钟延迟刷新。

func RefundEUQuota

func RefundEUQuota(id int, amount int) error

RefundEUQuota 退还成员企业余额:加回 quota 同时回冲 used_quota。 used_quota 不足时仅回冲到 0,避免出现负值。

func RefundTopUp

func RefundTopUp(tradeNo string, callerIp string) error

RefundTopUp 管理员退款:反向冲销一笔已成功充值订单的主配额(本金+赠送已折入 Amount)与推荐返利,并标记订单为已退款。

设计要点:

  • 仅处理成功订单;已退款订单幂等返回 nil,可安全重试。
  • 主配额 = TopUp.Amount × QuotaPerUnit(与 RechargeAlipay/RechargeWechat 入账口径完全一致, 赠送额度在充值下单时已折入 Amount,因此一笔冲销即同时退还本金与赠送)。
  • 使用行锁(FOR UPDATE) + CASE WHEN quota-? < 0 THEN 0 ELSE quota-? END 防止并发下出现负数配额(跨方言可移植,兼容 Postgres/MySQL/sqlite)。
  • 仅做平台内配额冲销,不触碰支付网关的实际退款(那是独立的财务操作)。

func RejectEnterprise

func RejectEnterprise(id int, reason string) error

func ReloadAll

func ReloadAll() error

ReloadAll 免重启热加载所有配置驱动的状态: 选项表(含倍率覆盖)→ 数据库定价表 → 本地化覆盖 → 失效定价缓存。 供管理员「重载配置」端点调用。

func ReloadI18nCache

func ReloadI18nCache() error

ReloadI18nCache 从数据库全量加载覆盖文案到内存。

func ReloadUiSkinsCache

func ReloadUiSkinsCache() error

ReloadUiSkinsCache 从数据库全量加载皮肤到内存,并按 priority 排序;同时记录默认皮肤。

func RemoveUserFromEnterprise

func RemoveUserFromEnterprise(enterpriseId int, userId int) error

RemoveUserFromEnterprise 从企业移除用户

func ResetUserPasswordByEmail

func ResetUserPasswordByEmail(email string, password string) error

ResetUserPasswordByEmail resets password by email (case-insensitive)

func RevokeAffiliateRebate

func RevokeAffiliateRebate(tradeNo string) error

RevokeAffiliateRebate 撤销一笔充值订单的推荐返利(退款冲销)。

这是 ProcessReferralRebate 的幂等反向操作:原子地删除返利记录,并同步回退 邀请人的 aff_quota / aff_history / aff_recharge_total,以及通过 DecrementInviterAffCount 递减 aff_count。修复此前“邀请关系解除 / 退款后,推荐计划统计不更新”的缺陷—— 之前依赖手动 SQL 删 affiliate_logs,常常漏改字段(如 aff_count 只增不减), 导致推荐计划展示的邀请人数、待确认金额与实际不一致。

幂等:若对应返利记录已不存在,直接返回 nil,可安全重试。

func RootUserExists

func RootUserExists() bool

RootUserExists checks if root user exists

func SaveQuotaDataCache

func SaveQuotaDataCache()

func SearchTags

func SearchTags(keyword string, group string, model string, idSort bool) ([]*string, error)

func SeedDefaultActivities

func SeedDefaultActivities() error

func SeedDefaultUiSkins

func SeedDefaultUiSkins() error

SeedDefaultUiSkins 首次部署时把内置 4 套皮肤 seed 进库(css 留空=走 bundled)。幂等。

func SeedModelPricingFromDefaults

func SeedModelPricingFromDefaults() error

SeedModelPricingFromDefaults 仅在表为空时,把当前编译期默认值写入数据库。

func SkillNameVersionExists

func SkillNameVersionExists(name string, version string) (bool, error)

SkillNameVersionExists 判断「名称 + 版本」是否已被占用。 返回 (exists, err):仅当 err == nil 时 exists 有效。

func SumUsedToken

func SumUsedToken(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string) (token int)

func SyncChannelCache

func SyncChannelCache(frequency int)

func SyncOptions

func SyncOptions(frequency int)

func TaskBulkUpdate

func TaskBulkUpdate(taskIds []string, params map[string]any) error

TaskBulkUpdate performs an unconditional bulk UPDATE by upstream task_id strings. Same caveats as TaskBulkUpdateByID — no CAS guard.

func TaskBulkUpdateByID

func TaskBulkUpdateByID(ids []int64, params map[string]any) error

TaskBulkUpdateByID performs an unconditional bulk UPDATE by primary key IDs. WARNING: This function has NO CAS (Compare-And-Swap) guard — it will overwrite any concurrent status changes. DO NOT use in billing/quota lifecycle flows (e.g., timeout, success, failure transitions that trigger refunds or settlements). For status transitions that involve billing, use Task.UpdateWithStatus() instead.

func TaskCountAllTasks

func TaskCountAllTasks(queryParams SyncTaskQueryParams) int64

TaskCountAllTasks returns total tasks that match the given query params (admin usage)

func TaskCountAllUserTask

func TaskCountAllUserTask(userId int, queryParams SyncTaskQueryParams) int64

TaskCountAllUserTask returns total tasks for given user

func TenantScope

func TenantScope(tenantId *int64) func(db *gorm.DB) *gorm.DB

TenantScope returns a GORM Scope that filters by tenant_id. If tenantId is nil or 0, no filter is applied (admin/global query).

func TenantWhereArgs

func TenantWhereArgs(tenantId *int64) []interface{}

func TenantWhereClause

func TenantWhereClause(tenantId *int64) string

TenantWhereClause generates a WHERE clause for tenant_id filtering.

func TranslateFromDB

func TranslateFromDB(key, locale string) (string, bool)

TranslateFromDB 供 i18n 包回调:按 (key, locale) 从内存覆盖缓存取翻译。 key 即中文源文(与前端 t('中文') 同一套 key 体系)。

func UpdateAbilityByTag

func UpdateAbilityByTag(tag string, newTag *string, priority *int64, weight *uint) error

func UpdateAbilityStatus

func UpdateAbilityStatus(channelId int, status bool) error

func UpdateAbilityStatusByTag

func UpdateAbilityStatusByTag(tag string, status bool) error

func UpdateActivity

func UpdateActivity(a *Activity) error

func UpdateChannelStatus

func UpdateChannelStatus(channelId int, usingKey string, status int, reason string) bool

func UpdateChannelUsedQuota

func UpdateChannelUsedQuota(id int, quota int)

func UpdateEnterprise

func UpdateEnterprise(e *Enterprise) error

func UpdateEnterpriseMembership

func UpdateEnterpriseMembership(id int, level string) error

func UpdateEnterpriseUser

func UpdateEnterpriseUser(eu *EnterpriseUser) error

func UpdateGroupRatio

func UpdateGroupRatio(gr *GroupRatio) error

UpdateGroupRatio updates an existing group ratio record.

func UpdateInvitationCode

func UpdateInvitationCode(ic *InvitationCode) error

func UpdateOption

func UpdateOption(key string, value string) error

func UpdateOptionsBulk

func UpdateOptionsBulk(values map[string]string) error

UpdateOptionsBulk persists multiple key/value pairs in a single database transaction, then dispatches them through updateOptionMap in one pass. If any DB write fails the whole transaction rolls back and no in-memory state is touched — safe for callers that must commit a set of related options atomically (e.g. payment gateway binding).

func UpdatePasskeyCredentialSignCount

func UpdatePasskeyCredentialSignCount(id uint, signCount uint32) error

UpdatePasskeyCredentialSignCount updates the sign count and last used time

func UpdatePendingTopUpStatus

func UpdatePendingTopUpStatus(tradeNo string, expectedPaymentProvider string, targetStatus string) error

func UpdateProgress

func UpdateProgress(id int, progress string) error

func UpdateQuotaData

func UpdateQuotaData()

func UpdateUserGroupCache

func UpdateUserGroupCache(userId int, group string) error

func UpdateUserLastLoginAt

func UpdateUserLastLoginAt(id int)

func UpdateUserMembership

func UpdateUserMembership(userId int, level MembershipLevel, expireDays int) error

UpdateUserMembership 更新用户会员等级

func UpdateUserOAuthBinding

func UpdateUserOAuthBinding(userId, providerId int, providerUserId string) error

UpdateUserOAuthBinding updates or creates an OAuth binding

func UpdateUserRole

func UpdateUserRole(enterpriseId int, userId int, role string) error

UpdateUserRole 更新用户在企业中的角色

func UpdateUserStatus

func UpdateUserStatus(enterpriseId int, userId int, status string) error

UpdateUserStatus 更新用户状态(active/inactive)

func UpdateUserUsedQuotaAndRequestCount

func UpdateUserUsedQuotaAndRequestCount(id int, quota int)

func UpdateUserWebhook

func UpdateUserWebhook(wh *UserWebhook) error

UpdateUserWebhook updates an existing webhook.

func UpsertI18nMessage

func UpsertI18nMessage(key, locale, value string) error

UpsertI18nMessage 覆盖单条文案并热更新缓存。

func UpsertModelPrice

func UpsertModelPrice(p *ModelPricing) error

UpsertModelPrice 覆盖单个模型的定价并热更新(写库 + 重载 ratio_setting + 失效定价缓存)。

func UpsertPerfMetric

func UpsertPerfMetric(metric *PerfMetric) error

func UpsertUiSkin

func UpsertUiSkin(s *UiSkin) error

UpsertUiSkin 创建或更新皮肤并热更新缓存(运营可加第 5 套免部署)。

func UseInvitationCode

func UseInvitationCode(userId int, code string) error

UseInvitationCode 使用邀请码(认证企业会员)

func ValidateMembershipLevel

func ValidateMembershipLevel(level string) bool

ValidateMembershipLevel 验证会员等级是否合法

func VerifySMSVerificationCode

func VerifySMSVerificationCode(phone string, code string, purpose SMSPurpose) (bool, error)

VerifySMSVerificationCode 验证短信验证码(原子操作,无并发竞态)

Types

type Ability

type Ability struct {
	Group     string  `json:"group" gorm:"type:varchar(64);primaryKey;autoIncrement:false"`
	Model     string  `json:"model" gorm:"type:varchar(255);primaryKey;autoIncrement:false"`
	ChannelId int     `json:"channel_id" gorm:"primaryKey;autoIncrement:false;index"`
	Enabled   bool    `json:"enabled"`
	Priority  *int64  `json:"priority" gorm:"bigint;default:0;index"`
	Weight    uint    `json:"weight" gorm:"default:0;index"`
	Tag       *string `json:"tag" gorm:"index"`
}

func GetAllEnableAbilities

func GetAllEnableAbilities() []Ability

type AbilityWithChannel

type AbilityWithChannel struct {
	Ability
	ChannelType int `json:"channel_type"`
}

func GetAllEnableAbilityWithChannels

func GetAllEnableAbilityWithChannels() ([]AbilityWithChannel, error)

type Activity

type Activity struct {
	Id          int        `json:"id" gorm:"primaryKey;autoIncrement"`
	ParentId    *int       `json:"parent_id" gorm:"index"`
	Type        string     `json:"type" gorm:"type:varchar(50);index"`
	Name        string     `json:"name" gorm:"type:varchar(255)"`
	Enabled     bool       `json:"enabled"`
	Priority    int        `json:"priority"`
	StartTime   *time.Time `json:"start_time"`
	EndTime     *time.Time `json:"end_time"`
	Eligibility string     `json:"eligibility" gorm:"type:text"` // JSON: ActivityEligibility
	Reward      string     `json:"reward" gorm:"type:text"`      // JSON: ActivityReward
	Limit       string     `json:"limit" gorm:"type:text"`       // JSON: ActivityLimit
	Config      string     `json:"config" gorm:"type:text"`      // JSON: 任意扩展配置
	CreatedAt   time.Time  `json:"created_at"`
	UpdatedAt   time.Time  `json:"updated_at"`
}

Activity 是通用活动框架的一行记录。 采用自引用 parent_id 实现「总框架(父活动/campaign 容器)+ 子活动(具体发奖方式)」的层级结构:

  • 父活动(parent_id 为空):仅作容器,管理总体开关/档期/包裹,不直接发奖;
  • 子活动(parent_id 指向父):每条是一种具体发奖方式(type 区分)。

type 取值:topup_gift(充值赠送等值配额)/ signup_bonus(注册赠送)/ referral_reward(推荐奖励)/

lottery(抽奖)/ direct_quota(直接送配额)/ coupon(优惠券)……可无限扩展,无需改码。

func ListActivities

func ListActivities() ([]Activity, error)

func (Activity) TableName

func (Activity) TableName() string

type ActivityEligibility

type ActivityEligibility struct {
	MinAmount     float64  `json:"min_amount"`      // 精确命中金额(元);仅 topup_gift 使用
	UserGroups    []string `json:"user_groups"`     // 限定用户分组;空=不限
	Channels      []string `json:"channels"`        // 限定渠道;空=不限
	FirstTimeOnly bool     `json:"first_time_only"` // 仅首次触发
}

type ActivityGrant

type ActivityGrant struct {
	Id         int       `json:"id" gorm:"primaryKey;autoIncrement"`
	ActivityId int       `json:"activity_id" gorm:"index"`
	UserId     int       `json:"user_id" gorm:"index"`
	Amount     int       `json:"amount"` // 发放的配额(配额单位)
	DedupeKey  string    `json:"dedupe_key" gorm:"uniqueIndex;type:varchar(255)"`
	CreatedAt  time.Time `json:"created_at"`
}

ActivityGrant 是活动发放的明细台账(幂等由 dedupe_key 唯一约束保证)。

func (ActivityGrant) TableName

func (ActivityGrant) TableName() string

type ActivityLimit

type ActivityLimit struct {
	PerUser int `json:"per_user"` // 每用户最多发放次数;0=不限
	Total   int `json:"total"`    // 全局最多发放次数;0=不限
	Daily   int `json:"daily"`    // 每用户每日最多;0=不限
}

type ActivityReward

type ActivityReward struct {
	QuotaBonusRate float64 `json:"quota_bonus_rate"` // topup_gift:赠送=金额×此比例(元)
	QuotaFixed     int     `json:"quota_fixed"`      // 固定赠送配额(配额单位)
	GiftType       string  `json:"gift_type"`        // 实物赠品类型;空=不送实物
	GiftKey        string  `json:"gift_key"`
	GiftName       string  `json:"gift_name"`
	Coupon         string  `json:"coupon"`
}

type AdminUserGiftResp

type AdminUserGiftResp struct {
	Id          int    `json:"id"`
	UserId      int    `json:"user_id"`
	UserEmail   string `json:"user_email"`
	Username    string `json:"username"`
	GiftType    string `json:"gift_type"`
	GiftName    string `json:"gift_name"`
	TradeNo     string `json:"trade_no"`
	Status      string `json:"status"`
	Description string `json:"description"`
	CreateTime  int64  `json:"create_time"`
	UpdateTime  int64  `json:"update_time"`
}

ExpireStaleTopUps 将超过有效期的 Pending 订单标记为 Expired。 返回过期的订单数量。仅处理 Alipay 和 Wechat 支付订单(Epay 订阅订单除外)。 AdminUserGiftResp 管理端礼物列表响应(含用户信息)

func AdminGetAllGifts

func AdminGetAllGifts(status string, page, pageSize int) ([]AdminUserGiftResp, int64, error)

AdminGetAllGifts 管理员查询所有礼物记录(支持按状态筛选+分页)

type AffiliateLog

type AffiliateLog struct {
	Id             int     `json:"id" gorm:"primaryKey;autoIncrement"`
	InviterId      int     `json:"inviter_id" gorm:"index"`
	RefereeId      int     `json:"referee_id" gorm:"index"`
	TradeNo        string  `json:"trade_no" gorm:"uniqueIndex;type:varchar(255)"` // 幂等键:同一笔订单只返一次
	RechargeAmount int     `json:"recharge_amount"`                               // 被推荐人实付(元)
	Tier           int     `json:"tier"`
	Rate           float64 `json:"rate" gorm:"type:decimal(6,4)"`
	RebateQuota    int     `json:"rebate_quota"`  // 实际返给邀请人的配额
	RefereeQuota   int     `json:"referee_quota"` // 双方各得时返给被推荐人的配额
	CreatedAt      int64   `json:"created_at" gorm:"index"`
}

AffiliateLog 推荐返利记录(审计 / 对账 / 防重复)

type BoundChannel

type BoundChannel struct {
	Name string `json:"name"`
	Type int    `json:"type"`
}

type Channel

type Channel struct {
	Id                 int     `json:"id"`
	Type               int     `json:"type" gorm:"default:0"`
	Key                string  `json:"key" gorm:"not null"`
	OpenAIOrganization *string `json:"openai_organization"`
	TestModel          *string `json:"test_model"`
	Status             int     `json:"status" gorm:"default:1"`
	Name               string  `json:"name" gorm:"index"`
	Weight             *uint   `json:"weight" gorm:"default:0"`
	CreatedTime        int64   `json:"created_time" gorm:"bigint"`
	TestTime           int64   `json:"test_time" gorm:"bigint"`
	ResponseTime       int     `json:"response_time"` // in milliseconds
	BaseURL            *string `json:"base_url" gorm:"column:base_url;default:''"`
	Other              string  `json:"other"`
	Balance            float64 `json:"balance"` // in USD
	BalanceUpdatedTime int64   `json:"balance_updated_time" gorm:"bigint"`
	Models             string  `json:"models"`
	Group              string  `json:"group" gorm:"type:varchar(64);default:'default'"`
	UsedQuota          int64   `json:"used_quota" gorm:"bigint;default:0"`
	ModelMapping       *string `json:"model_mapping" gorm:"type:text"`
	//MaxInputTokens     *int    `json:"max_input_tokens" gorm:"default:0"`
	StatusCodeMapping *string `json:"status_code_mapping" gorm:"type:varchar(1024);default:''"`
	Priority          *int64  `json:"priority" gorm:"bigint;default:0"`
	AutoBan           *int    `json:"auto_ban" gorm:"default:1"`
	OtherInfo         string  `json:"other_info"`
	Tag               *string `json:"tag" gorm:"index"`
	Setting           *string `json:"setting" gorm:"type:text"` // 渠道额外设置
	ParamOverride     *string `json:"param_override" gorm:"type:text"`
	HeaderOverride    *string `json:"header_override" gorm:"type:text"`
	Remark            *string `json:"remark" gorm:"type:varchar(255)" validate:"max=255"`
	// add after v0.8.5
	ChannelInfo ChannelInfo `json:"channel_info" gorm:"type:json"`

	OtherSettings string `json:"settings" gorm:"column:settings"` // 其他设置,存储azure版本等不需要检索的信息,详见dto.ChannelOtherSettings

	// Tenant isolation (Phase 1 multi-tenancy)
	TenantId int `json:"tenant_id" gorm:"default:0;index"`

	// cache info
	Keys []string `json:"-" gorm:"-"`
}

func CacheGetChannel

func CacheGetChannel(id int) (*Channel, error)

func GetAllChannels

func GetAllChannels(startIdx int, num int, selectAll bool, idSort bool, sortOptions ...ChannelSortOptions) ([]*Channel, error)

func GetChannel

func GetChannel(group string, model string, retry int) (*Channel, error)

func GetChannelById

func GetChannelById(id int, selectAll bool) (*Channel, error)

func GetChannelsByIds

func GetChannelsByIds(ids []int) ([]*Channel, error)

func GetChannelsByTag

func GetChannelsByTag(tag string, idSort bool, selectAll bool, sortOptions ...ChannelSortOptions) ([]*Channel, error)

func GetChannelsByType

func GetChannelsByType(startIdx int, num int, idSort bool, channelType int) ([]*Channel, error)

Get channels of specified type with pagination

func GetRandomSatisfiedChannel

func GetRandomSatisfiedChannel(group string, model string, retry int) (*Channel, error)

func SearchChannels

func SearchChannels(keyword string, group string, model string, idSort bool, sortOptions ...ChannelSortOptions) ([]*Channel, error)

func (*Channel) AddAbilities

func (channel *Channel) AddAbilities(tx *gorm.DB) error

func (*Channel) Delete

func (channel *Channel) Delete() error

func (*Channel) DeleteAbilities

func (channel *Channel) DeleteAbilities() error

func (*Channel) GetAutoBan

func (channel *Channel) GetAutoBan() bool

func (*Channel) GetBaseURL

func (channel *Channel) GetBaseURL() string

func (*Channel) GetGroups

func (channel *Channel) GetGroups() []string

func (*Channel) GetHeaderOverride

func (channel *Channel) GetHeaderOverride() map[string]interface{}

func (*Channel) GetKeys

func (channel *Channel) GetKeys() []string

func (*Channel) GetModelMapping

func (channel *Channel) GetModelMapping() string

func (*Channel) GetModels

func (channel *Channel) GetModels() []string

func (*Channel) GetNextEnabledKey

func (channel *Channel) GetNextEnabledKey() (string, int, *types.FastTokenError)

func (*Channel) GetOtherInfo

func (channel *Channel) GetOtherInfo() map[string]interface{}

func (*Channel) GetOtherSettings

func (channel *Channel) GetOtherSettings() dto.ChannelOtherSettings

func (*Channel) GetParamOverride

func (channel *Channel) GetParamOverride() map[string]interface{}

func (*Channel) GetPriority

func (channel *Channel) GetPriority() int64

func (*Channel) GetSetting

func (channel *Channel) GetSetting() dto.ChannelSettings

func (*Channel) GetStatusCodeMapping

func (channel *Channel) GetStatusCodeMapping() string

func (*Channel) GetTag

func (channel *Channel) GetTag() string

func (*Channel) GetWeight

func (channel *Channel) GetWeight() int

func (*Channel) Insert

func (channel *Channel) Insert() error

func (*Channel) Save

func (channel *Channel) Save() error

func (*Channel) SaveChannelInfo

func (channel *Channel) SaveChannelInfo() error

func (*Channel) SaveWithoutKey

func (channel *Channel) SaveWithoutKey() error

func (*Channel) SetOtherInfo

func (channel *Channel) SetOtherInfo(otherInfo map[string]interface{})

func (*Channel) SetOtherSettings

func (channel *Channel) SetOtherSettings(setting dto.ChannelOtherSettings)

func (*Channel) SetSetting

func (channel *Channel) SetSetting(setting dto.ChannelSettings)

func (*Channel) SetTag

func (channel *Channel) SetTag(tag string)

func (*Channel) Update

func (channel *Channel) Update() error

func (*Channel) UpdateAbilities

func (channel *Channel) UpdateAbilities(tx *gorm.DB) error

UpdateAbilities updates abilities of this channel. Make sure the channel is completed before calling this function.

func (*Channel) UpdateBalance

func (channel *Channel) UpdateBalance(balance float64)

func (*Channel) UpdateResponseTime

func (channel *Channel) UpdateResponseTime(responseTime int64)

func (*Channel) ValidateSettings

func (channel *Channel) ValidateSettings() error

type ChannelInfo

type ChannelInfo struct {
	IsMultiKey             bool                  `json:"is_multi_key"`                        // 是否多Key模式
	MultiKeySize           int                   `json:"multi_key_size"`                      // 多Key模式下的Key数量
	MultiKeyStatusList     map[int]int           `json:"multi_key_status_list"`               // key状态列表,key index -> status
	MultiKeyDisabledReason map[int]string        `json:"multi_key_disabled_reason,omitempty"` // key禁用原因列表,key index -> reason
	MultiKeyDisabledTime   map[int]int64         `json:"multi_key_disabled_time,omitempty"`   // key禁用时间列表,key index -> time
	MultiKeyPollingIndex   int                   `json:"multi_key_polling_index"`             // 多Key模式下轮询的key索引
	MultiKeyMode           constant.MultiKeyMode `json:"multi_key_mode"`
}

func CacheGetChannelInfo

func CacheGetChannelInfo(id int) (*ChannelInfo, error)

func (*ChannelInfo) Scan

func (c *ChannelInfo) Scan(value interface{}) error

Scan implements sql.Scanner interface

func (ChannelInfo) Value

func (c ChannelInfo) Value() (driver.Value, error)

Value implements driver.Valuer interface

type ChannelSortOptions

type ChannelSortOptions struct {
	SortBy    string
	SortOrder string
	IDSort    bool
}

func NewChannelSortOptions

func NewChannelSortOptions(sortBy string, sortOrder string, idSort bool) ChannelSortOptions

func (ChannelSortOptions) Apply

func (options ChannelSortOptions) Apply(query *gorm.DB) *gorm.DB

type Checkin

type Checkin struct {
	Id           int    `json:"id" gorm:"primaryKey;autoIncrement"`
	UserId       int    `json:"user_id" gorm:"not null;uniqueIndex:idx_user_checkin_date"`
	CheckinDate  string `json:"checkin_date" gorm:"type:varchar(10);not null;uniqueIndex:idx_user_checkin_date"` // 格式: YYYY-MM-DD
	QuotaAwarded int    `json:"quota_awarded" gorm:"not null"`
	CreatedAt    int64  `json:"created_at" gorm:"bigint"`
}

Checkin 签到记录

func GetUserCheckinRecords

func GetUserCheckinRecords(userId int, startDate, endDate string) ([]Checkin, error)

GetUserCheckinRecords 获取用户在指定日期范围内的签到记录

func UserCheckin

func UserCheckin(userId int) (*Checkin, error)

UserCheckin 执行用户签到 MySQL 和 PostgreSQL 使用事务保证原子性 SQLite 不支持嵌套事务,使用顺序操作 + 手动回滚

func (Checkin) TableName

func (Checkin) TableName() string

type CheckinRecord

type CheckinRecord struct {
	CheckinDate  string `json:"checkin_date"`
	QuotaAwarded int    `json:"quota_awarded"`
}

CheckinRecord 用于API返回的签到记录(不包含敏感字段)

type CustomOAuthProvider

type CustomOAuthProvider struct {
	ID           uint   `gorm:"primaryKey" json:"id"`
	Name         string `gorm:"type:varchar(50);uniqueIndex" json:"name"`
	DisplayName  string `gorm:"type:varchar(100)" json:"display_name"`
	ClientID     string `gorm:"type:varchar(255)" json:"client_id"`
	ClientSecret string `gorm:"type:varchar(255)" json:"client_secret"`
	AuthURL      string `gorm:"type:varchar(500)" json:"auth_url"`
	TokenURL     string `gorm:"type:varchar(500)" json:"token_url"`
	UserInfoURL  string `gorm:"type:varchar(500)" json:"user_info_url"`
	Scope        string `gorm:"type:varchar(255);default:openid,profile,email" json:"scope"`
	Enabled      bool   `gorm:"default:false" json:"enabled"`
}

CustomOAuthProvider 自定义 OAuth 提供商配置

type DiscountRate

type DiscountRate float64

DiscountRate 折扣率(0.98 = 9.8折,0.95 = 9.5折,0.9 = 9折)

const (
	// SilverDiscount 白银会员折扣(9.8折)
	SilverDiscount DiscountRate = 0.98

	// GoldDiscount 黄金会员折扣(9.5折)
	GoldDiscount DiscountRate = 0.95

	// PlatinumDiscount 铂金会员折扣(9折)
	PlatinumDiscount DiscountRate = 0.9

	// NoDiscount 无折扣
	NoDiscount DiscountRate = 1.0
)

func GetDiscountRate

func GetDiscountRate(level MembershipLevel) DiscountRate

GetDiscountRate 根据会员等级获取折扣率

func GetUserDiscountRate

func GetUserDiscountRate(userId int) (DiscountRate, error)

GetUserDiscountRate 获取用户折扣率(带过期检查)

type Enterprise

type Enterprise struct {
	Id              int    `json:"id" gorm:"primaryKey;autoIncrement"`
	Name            string `json:"name" gorm:"type:varchar(255);not null" validate:"required,max=255"`
	CreditCode      string `json:"credit_code" gorm:"type:varchar(50);uniqueIndex" validate:"required,max=50"`
	ContactName     string `json:"contact_name" gorm:"type:varchar(50)" validate:"max=50"`
	ContactPhone    string `json:"contact_phone" gorm:"type:varchar(20)" validate:"max=20"`
	ContactEmail    string `json:"contact_email" gorm:"type:varchar(100)" validate:"max=100,email"`
	UserId          int    `json:"user_id" gorm:"default:0;index"`                       // 提交认证的用户ID
	BusinessLicense string `json:"business_license" gorm:"type:varchar(512);default:''"` // 营业执照文件 URL(上传后返回)
	InvitationCode  string `json:"invitation_code" gorm:"type:varchar(64);default:''"`   // 企业认证邀请码
	Status          string `json:"status" gorm:"type:varchar(20);default:'pending';index" validate:"oneof=pending approved rejected"`
	MembershipLevel string `json:"membership_level" gorm:"type:varchar(20);default:'gold'" validate:"oneof=silver gold platinum"`
	ApprovedAt      int64  `json:"approved_at" gorm:"default:0"`
	ApprovedBy      int    `json:"approved_by" gorm:"default:0"`
	RejectReason    string `json:"reject_reason" gorm:"type:varchar(500);default:''"`
	CreatedAt       int64  `json:"created_at" gorm:"autoCreateTime"`
	UpdatedAt       int64  `json:"updated_at" gorm:"autoUpdateTime"`
}

func GetEnterpriseByCreditCode

func GetEnterpriseByCreditCode(creditCode string) (*Enterprise, error)

func GetEnterpriseById

func GetEnterpriseById(id int) (*Enterprise, error)

func GetUserEnterprise

func GetUserEnterprise(userId int) (*Enterprise, error)

GetUserEnterprise 获取用户所属企业

func GetUserEnterprises

func GetUserEnterprises(userId int) ([]Enterprise, error)

GetUserEnterprises 获取用户加入的所有企业

func ListEnterprises

func ListEnterprises(status string, page int, pageSize int) ([]Enterprise, int64, error)

func (*Enterprise) BeforeCreate

func (e *Enterprise) BeforeCreate(tx *gorm.DB) error

func (*Enterprise) BeforeUpdate

func (e *Enterprise) BeforeUpdate(tx *gorm.DB) error

func (*Enterprise) GetDiscountRate

func (e *Enterprise) GetDiscountRate() float64

GetDiscountRate 获取企业折扣率(与个人会员折扣同源:认证通过即 platinum 9折)

func (*Enterprise) IsApproved

func (e *Enterprise) IsApproved() bool

IsApproved 判断企业是否已审核通过

func (*Enterprise) IsExpired

func (e *Enterprise) IsExpired() bool

IsExpired 判断企业会员是否过期(如果设置了过期时间)

func (*Enterprise) TableName

func (e *Enterprise) TableName() string

type EnterpriseMembership

type EnterpriseMembership struct {
	EnterpriseUserId int
	EnterpriseId     int
	Quota            int
	Role             string
}

EnterpriseMembership 用户的有效企业成员身份快照(选路用,一次查询取全)

func GetActiveEnterpriseMembership

func GetActiveEnterpriseMembership(userId int) (*EnterpriseMembership, error)

GetActiveEnterpriseMembership 查询用户当前生效的企业成员身份。 用户不属于任何企业或成员状态非 active 时返回 (nil, nil),不视为错误。

type EnterpriseUser

type EnterpriseUser struct {
	Id           int    `json:"id" gorm:"primaryKey;autoIncrement"`
	EnterpriseId int    `json:"enterprise_id" gorm:"not null;index;uniqueIndex:idx_enterprise_user"`
	UserId       int    `json:"user_id" gorm:"not null;index;uniqueIndex:idx_enterprise_user"`
	Role         string `json:"role" gorm:"type:varchar(20);default:'member'" validate:"oneof=member admin"`
	Status       string `json:"status" gorm:"type:varchar(20);default:'active';index" validate:"oneof=active inactive"`
	Quota        int    `json:"quota" gorm:"default:0"`
	UsedQuota    int    `json:"used_quota" gorm:"default:0"`
	JoinedAt     int64  `json:"joined_at"`
	CreatedAt    int64  `json:"created_at" gorm:"autoCreateTime"`
	UpdatedAt    int64  `json:"updated_at" gorm:"autoUpdateTime"`
}

func GetEnterpriseUser

func GetEnterpriseUser(enterpriseId int, userId int) (*EnterpriseUser, error)

func GetEnterpriseUserById

func GetEnterpriseUserById(id int) (*EnterpriseUser, error)

func GetEnterpriseUsers

func GetEnterpriseUsers(enterpriseId int, page int, pageSize int) ([]EnterpriseUser, int64, error)

GetEnterpriseUsers 获取企业成员列表

func (*EnterpriseUser) BeforeCreate

func (eu *EnterpriseUser) BeforeCreate(tx *gorm.DB) error

func (*EnterpriseUser) BeforeUpdate

func (eu *EnterpriseUser) BeforeUpdate(tx *gorm.DB) error

func (*EnterpriseUser) IsActive

func (eu *EnterpriseUser) IsActive() bool

IsActive 判断是否活跃状态

func (*EnterpriseUser) IsAdmin

func (eu *EnterpriseUser) IsAdmin() bool

IsAdmin 判断是否为企业管理员

func (*EnterpriseUser) TableName

func (eu *EnterpriseUser) TableName() string

type EnterpriseWallet

type EnterpriseWallet struct {
	Id            int   `json:"id" gorm:"primaryKey;autoIncrement"`
	EnterpriseId  int   `json:"enterprise_id" gorm:"not null;uniqueIndex"`
	Balance       int   `json:"balance" gorm:"not null;default:0"`
	TotalGranted  int   `json:"total_granted" gorm:"not null;default:0"`
	TotalRecycled int   `json:"total_recycled" gorm:"not null;default:0"`
	CreatedAt     int64 `json:"created_at" gorm:"autoCreateTime"`
	UpdatedAt     int64 `json:"updated_at" gorm:"autoUpdateTime"`
}

EnterpriseWallet 企业主钱包:企业账户维度的资金池,由平台授信或企业自助充值入账, 经企业管理员派发到成员 enterprise_user.quota 后供消费。

func GetOrCreateEnterpriseWallet

func GetOrCreateEnterpriseWallet(enterpriseId int) (*EnterpriseWallet, error)

GetOrCreateEnterpriseWallet 获取或创建企业主钱包(首次访问时建一行)

func (*EnterpriseWallet) GrantToMember

func (w *EnterpriseWallet) GrantToMember(member *EnterpriseUser, amount int, operatorId int, tradeNo string) error

GrantToMember 从企业主钱包向成员派发额度:扣主钱包、增成员余额、写流水(单事务)。 条件更新保证余额不足时整个事务不产生任何变更。

func (*EnterpriseWallet) Recharge

func (w *EnterpriseWallet) Recharge(amount int, operatorId int, tradeNo string) error

Recharge 平台授信或企业自助充值:增加主钱包余额与累计授予额,并写流水(单事务)。 operatorId 为 0 表示系统/支付回调入账,非 0 表示平台管理员手工授信。

func (*EnterpriseWallet) RechargeByOperator

func (w *EnterpriseWallet) RechargeByOperator(amount int, operatorId int, remark string) error

RechargeByOperator 平台管理员手工授信充值,remark 落到流水的 TradeNo 字段作为备注。

func (*EnterpriseWallet) RechargeInTx

func (w *EnterpriseWallet) RechargeInTx(tx *gorm.DB, amount int, operatorId int, tradeNo string) error

RechargeInTx 在既有事务内完成企业主钱包充值入账(支付回调使用,避免嵌套事务)。 仅要求 w.EnterpriseId 有效;事务内自动创建钱包行(并发首建冲突时回读)。

func (*EnterpriseWallet) RecycleFromMember

func (w *EnterpriseWallet) RecycleFromMember(member *EnterpriseUser, amount int, operatorId int, tradeNo string) error

RecycleFromMember 从成员回收额度回企业主钱包:扣成员余额、增主钱包、写流水(单事务)。

func (*EnterpriseWallet) RefundInTx

func (w *EnterpriseWallet) RefundInTx(tx *gorm.DB, amount int, operatorId int, tradeNo string) error

RefundInTx 在既有事务内冲销企业主钱包余额(管理员退款用),并写流水。 与个人钱包退款口径一致:只做平台内配额冲销,不触碰支付网关的实际退款。

func (EnterpriseWallet) TableName

func (EnterpriseWallet) TableName() string

type EnterpriseWalletTxn

type EnterpriseWalletTxn struct {
	Id           int    `json:"id" gorm:"primaryKey;autoIncrement"`
	EnterpriseId int    `json:"enterprise_id" gorm:"not null;index"`
	UserId       int    `json:"user_id" gorm:"not null;default:0;index"`
	Type         string `json:"type" gorm:"type:varchar(20);not null"`
	Amount       int    `json:"amount" gorm:"not null"`
	BalanceAfter int    `json:"balance_after" gorm:"not null;default:0"`
	OperatorId   int    `json:"operator_id" gorm:"not null;default:0"`
	TradeNo      string `json:"trade_no" gorm:"type:varchar(64);not null;default:'';index"`
	CreatedAt    int64  `json:"created_at" gorm:"autoCreateTime"`
}

EnterpriseWalletTxn 企业资金流水(主钱包维度):充值/派发/回收/消费/退款。

func GetEnterpriseWalletTxns

func GetEnterpriseWalletTxns(enterpriseId int, page int, pageSize int) ([]EnterpriseWalletTxn, int64, error)

GetEnterpriseWalletTxns 分页查询企业钱包流水

func (EnterpriseWalletTxn) TableName

func (EnterpriseWalletTxn) TableName() string

type GroupRatio

type GroupRatio struct {
	Id        int     `json:"id" gorm:"primaryKey;autoIncrement"`
	GroupName string  `json:"group_name" gorm:"uniqueIndex:idx_group_model;type:varchar(64)"`
	ModelName string  `json:"model_name" gorm:"uniqueIndex:idx_group_model;type:varchar(128)"`
	Ratio     float64 `json:"ratio" gorm:"type:decimal(10,6);default:1.0"`
	Enabled   bool    `json:"enabled" gorm:"default:true"`
	CreatedAt int64   `json:"created_at"`
	UpdatedAt int64   `json:"updated_at"`
}

func GetAllGroupRatios

func GetAllGroupRatios() ([]GroupRatio, error)

GetAllGroupRatios returns all group ratio records.

func GetGroupRatioById

func GetGroupRatioById(id int) (*GroupRatio, error)

GetGroupRatioById returns a single group ratio by id.

func GetGroupRatiosByGroup

func GetGroupRatiosByGroup(groupName string) ([]GroupRatio, error)

GetGroupRatiosByGroup returns all ratios for a specific group, optionally filtered by model prefix.

func (*GroupRatio) BeforeCreate

func (gr *GroupRatio) BeforeCreate(tx *gorm.DB) error

func (*GroupRatio) BeforeUpdate

func (gr *GroupRatio) BeforeUpdate(tx *gorm.DB) error

func (*GroupRatio) TableName

func (gr *GroupRatio) TableName() string

type I18nMessage

type I18nMessage struct {
	Key       string    `json:"key" gorm:"primaryKey;type:varchar(255);not null"`
	Locale    string    `json:"locale" gorm:"primaryKey;type:varchar(20);not null"`
	Value     string    `json:"value" gorm:"type:text"`
	UpdatedAt time.Time `json:"updated_at"`
}

I18nMessage 是运行时可覆盖的本地化文案(配置即数据:改翻译不部署)。 主键为 (key, locale);当某 locale 下存在覆盖项时,前端/后端本地化时优先使用它。

func (I18nMessage) TableName

func (I18nMessage) TableName() string

type InvitationCode

type InvitationCode struct {
	Id           int    `json:"id" gorm:"primaryKey;autoIncrement"`
	Code         string `json:"code" gorm:"type:varchar(32);uniqueIndex;not null"`
	Type         string `json:"type" gorm:"type:varchar(20);not null" validate:"oneof=silver gold platinum"`
	EnterpriseId int    `json:"enterprise_id" gorm:"default:0;index"`
	CreatedBy    int    `json:"created_by" gorm:"not null;index"`
	UsedBy       int    `json:"used_by" gorm:"default:0;index"`
	UsedAt       int64  `json:"used_at" gorm:"default:0"`
	Status       string `json:"status" gorm:"type:varchar(20);default:'active';index" validate:"oneof=active used expired"`
	ExpiresAt    int64  `json:"expires_at" gorm:"default:0"`
	Remark       string `json:"remark" gorm:"type:varchar(500);default:''"`
	CreatedAt    int64  `json:"created_at" gorm:"autoCreateTime"`
	UpdatedAt    int64  `json:"updated_at" gorm:"autoUpdateTime"`
}

func GetInvitationCodeByCode

func GetInvitationCodeByCode(code string) (*InvitationCode, error)

func GetInvitationCodeById

func GetInvitationCodeById(id int) (*InvitationCode, error)

func GetUserInvitationCodes

func GetUserInvitationCodes(userId int, page int, pageSize int) ([]InvitationCode, int64, error)

GetUserInvitationCodes 获取用户创建的邀请码

func ListInvitationCodes

func ListInvitationCodes(createdBy int, status string, codeType string, page int, pageSize int) ([]InvitationCode, int64, error)

ListInvitationCodes 列出邀请码(支持筛选和分页)

func (*InvitationCode) BeforeCreate

func (ic *InvitationCode) BeforeCreate(tx *gorm.DB) error

func (*InvitationCode) BeforeUpdate

func (ic *InvitationCode) BeforeUpdate(tx *gorm.DB) error

func (*InvitationCode) IsValid

func (ic *InvitationCode) IsValid() bool

IsValid 判断邀请码是否有效

func (*InvitationCode) TableName

func (ic *InvitationCode) TableName() string

func (*InvitationCode) UseCode

func (ic *InvitationCode) UseCode(userId int) error

UseCode 使用邀请码

type InvitationCodeStats

type InvitationCodeStats struct {
	Total   int64            `json:"total"`
	Active  int64            `json:"active"`
	Used    int64            `json:"used"`
	Expired int64            `json:"expired"`
	ByType  map[string]int64 `json:"by_type"`
}

func GetInvitationCodeStats

func GetInvitationCodeStats(createdBy int) (*InvitationCodeStats, error)

type JSONValue

type JSONValue json.RawMessage

JSONValue 基于 json.RawMessage 实现,支持从数据库的 []byte 和 string 两种类型读取

func (JSONValue) MarshalJSON

func (j JSONValue) MarshalJSON() ([]byte, error)

MarshalJSON 确保在对外编码时与 json.RawMessage 行为一致

func (*JSONValue) Scan

func (j *JSONValue) Scan(value interface{}) error

Scan 实现 sql.Scanner 接口,兼容不同驱动返回的类型

func (*JSONValue) UnmarshalJSON

func (j *JSONValue) UnmarshalJSON(data []byte) error

UnmarshalJSON 确保在对外解码时与 json.RawMessage 行为一致

func (JSONValue) Value

func (j JSONValue) Value() (driver.Value, error)

Value 实现 driver.Valuer 接口,用于数据库写入

type Log

type Log struct {
	Id                int    `json:"id" gorm:"index:idx_created_at_id,priority:1;index:idx_user_id_id,priority:2"`
	UserId            int    `json:"user_id" gorm:"index;index:idx_user_id_id,priority:1"`
	CreatedAt         int64  `json:"created_at" gorm:"bigint;index:idx_created_at_id,priority:2;index:idx_created_at_type"`
	Type              int    `json:"type" gorm:"index:idx_created_at_type"`
	Content           string `json:"content"`
	Username          string `json:"username" gorm:"index;index:index_username_model_name,priority:2;default:''"`
	TokenName         string `json:"token_name" gorm:"index;default:''"`
	ModelName         string `json:"model_name" gorm:"index;index:index_username_model_name,priority:1;default:''"`
	Quota             int    `json:"quota" gorm:"default:0"`
	PromptTokens      int    `json:"prompt_tokens" gorm:"default:0"`
	CompletionTokens  int    `json:"completion_tokens" gorm:"default:0"`
	UseTime           int    `json:"use_time" gorm:"default:0"`
	IsStream          bool   `json:"is_stream"`
	ChannelId         int    `json:"channel" gorm:"index"`
	ChannelName       string `json:"channel_name" gorm:"->"`
	TokenId           int    `json:"token_id" gorm:"default:0;index"`
	Group             string `json:"group" gorm:"index"`
	Ip                string `json:"ip" gorm:"index;default:''"`
	RequestId         string `json:"request_id,omitempty" gorm:"type:varchar(64);index:idx_logs_request_id;default:''"`
	UpstreamRequestId string `json:"upstream_request_id,omitempty" gorm:"type:varchar(128);index:idx_logs_upstream_request_id;default:''"`
	Other             string `json:"other"`

	// Tenant isolation (Phase 1 multi-tenancy)
	TenantId int `json:"tenant_id" gorm:"default:0;index"`

	// 资金来源:wallet(个人钱包)/ enterprise_wallet(企业钱包);双钱包分账与退款原路返回用
	FundingSource string `json:"funding_source" gorm:"type:varchar(20);default:'wallet'"`
}

func GetAllLogs

func GetAllLogs(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string, startIdx int, num int, channel int, group string, requestId string, upstreamRequestId string) (logs []*Log, total int64, err error)

func GetLogByTokenId

func GetLogByTokenId(tokenId int) (logs []*Log, err error)

func GetUserLogs

func GetUserLogs(userId int, logType int, startTimestamp int64, endTimestamp int64, modelName string, tokenName string, startIdx int, num int, group string, requestId string, upstreamRequestId string) (logs []*Log, total int64, err error)

type MembershipLevel

type MembershipLevel string

MembershipLevel 会员等级

const (
	// MembershipSilver 白银会员
	MembershipSilver MembershipLevel = "silver"

	// MembershipGold 黄金会员
	MembershipGold MembershipLevel = "gold"

	// MembershipPlatinum 铂金会员
	MembershipPlatinum MembershipLevel = "platinum"
)

func GetUserMembershipLevel

func GetUserMembershipLevel(userId int) (MembershipLevel, error)

GetUserMembershipLevel 获取用户会员等级(带过期检查)

type MembershipStats

type MembershipStats struct {
	TotalMembers      int64            `json:"total_members"`
	ByLevel           map[string]int64 `json:"by_level"`
	ActiveMembers     int64            `json:"active_members"`
	ExpiredMembers    int64            `json:"expired_members"`
	WillExpireIn7Days int64            `json:"will_expire_in_7_days"`
}

MembershipStats 会员统计

func GetMembershipStats

func GetMembershipStats() (*MembershipStats, error)

GetMembershipStats 获取会员统计信息

type Midjourney

type Midjourney struct {
	Id          int    `json:"id"`
	Code        int    `json:"code"`
	UserId      int    `json:"user_id" gorm:"index"`
	Action      string `json:"action" gorm:"type:varchar(40);index"`
	MjId        string `json:"mj_id" gorm:"index"`
	Prompt      string `json:"prompt"`
	PromptEn    string `json:"prompt_en"`
	Description string `json:"description"`
	State       string `json:"state"`
	SubmitTime  int64  `json:"submit_time" gorm:"index"`
	StartTime   int64  `json:"start_time" gorm:"index"`
	FinishTime  int64  `json:"finish_time" gorm:"index"`
	ImageUrl    string `json:"image_url"`
	VideoUrl    string `json:"video_url"`
	VideoUrls   string `json:"video_urls"`
	Status      string `json:"status" gorm:"type:varchar(20);index"`
	Progress    string `json:"progress" gorm:"type:varchar(30);index"`
	FailReason  string `json:"fail_reason"`
	ChannelId   int    `json:"channel_id"`
	Quota       int    `json:"quota"`
	Buttons     string `json:"buttons"`
	Properties  string `json:"properties"`
	// 双钱包计费上下文:失败退款必须原路返回,不可跨钱包
	BillingSource    string `json:"billing_source" gorm:"type:varchar(20);default:'wallet'"`
	EnterpriseUserId int    `json:"enterprise_user_id" gorm:"default:0"`
}

func GetAllTasks

func GetAllTasks(startIdx int, num int, queryParams TaskQueryParams) []*Midjourney

func GetAllUnFinishTasks

func GetAllUnFinishTasks() []*Midjourney

func GetAllUserTask

func GetAllUserTask(userId int, startIdx int, num int, queryParams TaskQueryParams) []*Midjourney

func GetByMJId

func GetByMJId(userId int, mjId string) *Midjourney

func GetByMJIds

func GetByMJIds(userId int, mjIds []string) []*Midjourney

func GetByOnlyMJId

func GetByOnlyMJId(mjId string) *Midjourney

func GetMjByuId

func GetMjByuId(id int) *Midjourney

func (*Midjourney) Insert

func (midjourney *Midjourney) Insert() error

func (*Midjourney) Update

func (midjourney *Midjourney) Update() error

func (*Midjourney) UpdateWithStatus

func (midjourney *Midjourney) UpdateWithStatus(fromStatus string) (bool, error)

UpdateWithStatus performs a conditional UPDATE guarded by fromStatus (CAS). Returns (true, nil) if this caller won the update, (false, nil) if another process already moved the task out of fromStatus. UpdateWithStatus performs a conditional UPDATE guarded by fromStatus (CAS). Uses Model().Select("*").Updates() to avoid GORM Save()'s INSERT fallback.

type Model

type Model struct {
	Id           int            `json:"id"`
	ModelName    string         `json:"model_name" gorm:"size:128;not null;uniqueIndex:uk_model_name_delete_at,priority:1"`
	Description  string         `json:"description,omitempty" gorm:"type:text"`
	Icon         string         `json:"icon,omitempty" gorm:"type:varchar(128)"`
	Tags         string         `json:"tags,omitempty" gorm:"type:varchar(255)"`
	VendorID     int            `json:"vendor_id,omitempty" gorm:"index"`
	Endpoints    string         `json:"endpoints,omitempty" gorm:"type:text"`
	Status       int            `json:"status" gorm:"default:1"`
	SyncOfficial int            `json:"sync_official" gorm:"default:1"`
	CreatedTime  int64          `json:"created_time" gorm:"bigint"`
	UpdatedTime  int64          `json:"updated_time" gorm:"bigint"`
	DeletedAt    gorm.DeletedAt `json:"-" gorm:"index;uniqueIndex:uk_model_name_delete_at,priority:2"`

	BoundChannels []BoundChannel `json:"bound_channels,omitempty" gorm:"-"`
	EnableGroups  []string       `json:"enable_groups,omitempty" gorm:"-"`
	QuotaTypes    []int          `json:"quota_types,omitempty" gorm:"-"`
	NameRule      int            `json:"name_rule" gorm:"default:0"`

	MatchedModels []string `json:"matched_models,omitempty" gorm:"-"`
	MatchedCount  int      `json:"matched_count,omitempty" gorm:"-"`
}

func GetAllModels

func GetAllModels(offset int, limit int) ([]*Model, error)

func SearchModels

func SearchModels(keyword string, vendor string, offset int, limit int) ([]*Model, int64, error)

func (*Model) Delete

func (mi *Model) Delete() error

func (*Model) Insert

func (mi *Model) Insert() error

func (*Model) Update

func (mi *Model) Update() error

type ModelPricing

type ModelPricing struct {
	ModelName            string    `json:"model_name" gorm:"primaryKey;type:varchar(255)"`
	ModelPrice           *float64  `json:"model_price,omitempty"`
	ModelRatio           *float64  `json:"model_ratio,omitempty"`
	CompletionRatio      *float64  `json:"completion_ratio,omitempty"`
	CacheRatio           *float64  `json:"cache_ratio,omitempty"`
	CreateCacheRatio     *float64  `json:"create_cache_ratio,omitempty"`
	ImageRatio           *float64  `json:"image_ratio,omitempty"`
	AudioRatio           *float64  `json:"audio_ratio,omitempty"`
	AudioCompletionRatio *float64  `json:"audio_completion_ratio,omitempty"`
	UpdatedAt            time.Time `json:"updated_at"`
}

ModelPricing 是模型定价在数据库中的持久化表(配置即数据:改价不部署)。 首次运行从编译期默认值(ratio_setting 内存 map)seed 一次;之后数据库为唯一真相源, 启动时加载回 ratio_setting,管理员改价经 UpdateModelPricing 热更新。 各倍率字段可为 NULL:NULL 表示沿用编译期默认值。

func GetAllModelPricing

func GetAllModelPricing() ([]ModelPricing, error)

GetAllModelPricing 返回全部模型定价(供管理员查看/编辑)。

func (ModelPricing) TableName

func (ModelPricing) TableName() string

type Option

type Option struct {
	Key   string `json:"key" gorm:"primaryKey"`
	Value string `json:"value"`
}

func AllOption

func AllOption() ([]*Option, error)

type PasskeyCredential

type PasskeyCredential struct {
	ID              uint   `gorm:"primaryKey" json:"id"`
	UserID          int    `json:"user_id" gorm:"not null;index:idx_passkey_user_id"`
	CredentialID    string `json:"credential_id" gorm:"type:varchar(1024);uniqueIndex:ux_passkey_cred_id"`
	PublicKey       []byte `json:"-" gorm:"type:bytea"`
	AttestationType string `json:"attestation_type" gorm:"type:varchar(100)"`
	AAGUID          string `json:"aaguid" gorm:"type:varchar(36)"`
	SignCount       uint32 `json:"sign_count" gorm:"default:0"`
	BackupEligible  bool   `json:"backup_eligible" gorm:"default:false"`
	BackupState     bool   `json:"backup_state" gorm:"default:false"`
	Attachment      string `json:"attachment" gorm:"type:varchar(50)"`
	CreatedAt       int64  `json:"created_at" gorm:"autoCreateTime"`
	LastUsedAt      int64  `json:"last_used_at" gorm:"default:0"`
	DeviceName      string `json:"device_name" gorm:"type:varchar(255);default:''"`
}

PasskeyCredential stores a WebAuthn credential for passwordless authentication

func GetPasskeyCredentialByCredentialID

func GetPasskeyCredentialByCredentialID(credentialID string) (*PasskeyCredential, error)

GetPasskeyCredentialByCredentialID returns a credential by its WebAuthn credential ID

func GetPasskeyCredentialByID

func GetPasskeyCredentialByID(id uint) (*PasskeyCredential, error)

GetPasskeyCredentialByID returns a single passkey credential by its primary key

func GetPasskeyCredentialsByUserId

func GetPasskeyCredentialsByUserId(userId int) ([]*PasskeyCredential, error)

GetPasskeyCredentialsByUserId returns all passkey credentials for a user

func (PasskeyCredential) TableName

func (PasskeyCredential) TableName() string

func (*PasskeyCredential) ToWebAuthnCredential

func (pc *PasskeyCredential) ToWebAuthnCredential() webauthn.Credential

ToWebAuthnCredential converts a PasskeyCredential to a webauthn.Credential

type PerfMetric

type PerfMetric struct {
	Id             int    `json:"id" gorm:"primaryKey"`
	ModelName      string `json:"model_name" gorm:"size:128;uniqueIndex:idx_perf_model_group_bucket,priority:1"`
	Group          string `json:"group" gorm:"column:group;size:64;uniqueIndex:idx_perf_model_group_bucket,priority:2"`
	BucketTs       int64  `json:"bucket_ts" gorm:"uniqueIndex:idx_perf_model_group_bucket,priority:3;index:idx_perf_bucket_ts"`
	RequestCount   int64  `json:"-" gorm:"default:0"`
	SuccessCount   int64  `json:"-" gorm:"default:0"`
	TotalLatencyMs int64  `json:"-" gorm:"default:0"`
	TtftSumMs      int64  `json:"-" gorm:"default:0"`
	TtftCount      int64  `json:"-" gorm:"default:0"`
	OutputTokens   int64  `json:"-" gorm:"default:0"`
	GenerationMs   int64  `json:"-" gorm:"default:0"`
}

PerfMetric stores aggregated relay performance metrics for the model square.

func GetPerfMetrics

func GetPerfMetrics(modelName string, group string, startTs int64, endTs int64) ([]PerfMetric, error)

func (PerfMetric) TableName

func (PerfMetric) TableName() string

type PerfMetricSummary

type PerfMetricSummary struct {
	ModelName      string `json:"model_name"`
	RequestCount   int64  `json:"request_count"`
	SuccessCount   int64  `json:"success_count"`
	TotalLatencyMs int64  `json:"total_latency_ms"`
	OutputTokens   int64  `json:"output_tokens"`
	GenerationMs   int64  `json:"generation_ms"`
}

func GetPerfMetricsSummaryAll

func GetPerfMetricsSummaryAll(startTs int64, endTs int64, groups []string) ([]PerfMetricSummary, error)

type PrefillGroup

type PrefillGroup struct {
	Id          int            `json:"id"`
	Name        string         `json:"name" gorm:"size:64;not null;uniqueIndex:uk_prefill_name,where:deleted_at IS NULL"`
	Type        string         `json:"type" gorm:"size:32;index;not null"`
	Items       JSONValue      `json:"items" gorm:"type:json"`
	Description string         `json:"description,omitempty" gorm:"type:varchar(255)"`
	CreatedTime int64          `json:"created_time" gorm:"bigint"`
	UpdatedTime int64          `json:"updated_time" gorm:"bigint"`
	DeletedAt   gorm.DeletedAt `json:"-" gorm:"index"`
}

func GetAllPrefillGroups

func GetAllPrefillGroups(groupType string) ([]*PrefillGroup, error)

GetAllPrefillGroups 获取全部组,可按类型过滤(为空则返回全部)

func (*PrefillGroup) Insert

func (g *PrefillGroup) Insert() error

Insert 新建组

func (*PrefillGroup) Update

func (g *PrefillGroup) Update() error

Update 更新组

type Pricing

type Pricing struct {
	ModelName              string                  `json:"model_name"`
	Description            string                  `json:"description,omitempty"`
	Icon                   string                  `json:"icon,omitempty"`
	Tags                   string                  `json:"tags,omitempty"`
	VendorID               int                     `json:"vendor_id,omitempty"`
	QuotaType              int                     `json:"quota_type"`
	ModelRatio             float64                 `json:"model_ratio"`
	ModelPrice             float64                 `json:"model_price"`
	OwnerBy                string                  `json:"owner_by"`
	CompletionRatio        float64                 `json:"completion_ratio"`
	CacheRatio             *float64                `json:"cache_ratio,omitempty"`
	CreateCacheRatio       *float64                `json:"create_cache_ratio,omitempty"`
	ImageRatio             *float64                `json:"image_ratio,omitempty"`
	AudioRatio             *float64                `json:"audio_ratio,omitempty"`
	AudioCompletionRatio   *float64                `json:"audio_completion_ratio,omitempty"`
	EnableGroup            []string                `json:"enable_groups"`
	SupportedEndpointTypes []constant.EndpointType `json:"supported_endpoint_types"`
	BillingMode            string                  `json:"billing_mode,omitempty"`
	BillingExpr            string                  `json:"billing_expr,omitempty"`
	PricingVersion         string                  `json:"pricing_version,omitempty"`
}

func GetPricing

func GetPricing() []Pricing

type PricingVendor

type PricingVendor struct {
	ID          int    `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Icon        string `json:"icon,omitempty"`
}

func GetVendors

func GetVendors() []PricingVendor

GetVendors 返回当前定价接口使用到的供应商信息

type Properties

type Properties struct {
	Input             string `json:"input"`
	UpstreamModelName string `json:"upstream_model_name,omitempty"`
	OriginModelName   string `json:"origin_model_name,omitempty"`
}

func (*Properties) Scan

func (m *Properties) Scan(val interface{}) error

func (Properties) Value

func (m Properties) Value() (driver.Value, error)

type QuotaData

type QuotaData struct {
	Id        int    `json:"id"`
	UserID    int    `json:"user_id" gorm:"index"`
	Username  string `json:"username" gorm:"index:idx_qdt_model_user_name,priority:2;size:64;default:''"`
	ModelName string `json:"model_name" gorm:"index:idx_qdt_model_user_name,priority:1;size:64;default:''"`
	CreatedAt int64  `json:"created_at" gorm:"bigint;index:idx_qdt_created_at,priority:2"`
	TokenUsed int    `json:"token_used" gorm:"default:0"`
	Count     int    `json:"count" gorm:"default:0"`
	Quota     int    `json:"quota" gorm:"default:0"`
}

QuotaData 柱状图数据

func GetAllQuotaDates

func GetAllQuotaDates(startTime int64, endTime int64, username string) (quotaData []*QuotaData, err error)

func GetQuotaDataByUserId

func GetQuotaDataByUserId(userId int, startTime int64, endTime int64) (quotaData []*QuotaData, err error)

func GetQuotaDataByUsername

func GetQuotaDataByUsername(username string, startTime int64, endTime int64) (quotaData []*QuotaData, err error)

func GetQuotaDataGroupByUser

func GetQuotaDataGroupByUser(startTime int64, endTime int64) (quotaData []*QuotaData, err error)

type RankingQuotaBucket

type RankingQuotaBucket struct {
	ModelName string `json:"model_name"`
	Bucket    int64  `json:"bucket"`
	Tokens    int64  `json:"tokens"`
}

func GetRankingQuotaBuckets

func GetRankingQuotaBuckets(startTime int64, endTime int64, bucketSize int64) ([]RankingQuotaBucket, error)

type RankingQuotaTotal

type RankingQuotaTotal struct {
	ModelName   string `json:"model_name"`
	TotalTokens int64  `json:"total_tokens"`
}

func GetRankingQuotaTotals

func GetRankingQuotaTotals(startTime int64, endTime int64) ([]RankingQuotaTotal, error)

type RecordConsumeLogParams

type RecordConsumeLogParams struct {
	ChannelId        int                    `json:"channel_id"`
	PromptTokens     int                    `json:"prompt_tokens"`
	CompletionTokens int                    `json:"completion_tokens"`
	ModelName        string                 `json:"model_name"`
	TokenName        string                 `json:"token_name"`
	Quota            int                    `json:"quota"`
	Content          string                 `json:"content"`
	TokenId          int                    `json:"token_id"`
	UseTimeSeconds   int                    `json:"use_time_seconds"`
	IsStream         bool                   `json:"is_stream"`
	Group            string                 `json:"group"`
	Other            map[string]interface{} `json:"other"`
	// TenantId 为 Phase 1 多租户透传字段。调用方可显式指定;
	// 留空(0)时由 RecordConsumeLog / RecordConsumeLogAsync 自行兜底解析。
	TenantId int `json:"tenant_id"`
	// FundingSource 资金来源标识:wallet / enterprise_wallet
	FundingSource string `json:"funding_source"`
}

type RecordTaskBillingLogParams

type RecordTaskBillingLogParams struct {
	UserId        int
	LogType       int
	Content       string
	ChannelId     int
	ModelName     string
	Quota         int
	TokenId       int
	Group         string
	Other         map[string]interface{}
	FundingSource string
}

type Redemption

type Redemption struct {
	Id           int            `json:"id"`
	UserId       int            `json:"user_id"`
	Key          string         `json:"key" gorm:"type:char(32);uniqueIndex"`
	Status       int            `json:"status" gorm:"default:1"`
	Name         string         `json:"name" gorm:"index"`
	Quota        int            `json:"quota" gorm:"default:100"`
	CreatedTime  int64          `json:"created_time" gorm:"bigint"`
	RedeemedTime int64          `json:"redeemed_time" gorm:"bigint"`
	Count        int            `json:"count" gorm:"-:all"` // only for api request
	UsedUserId   int            `json:"used_user_id"`
	DeletedAt    gorm.DeletedAt `gorm:"index"`
	ExpiredTime  int64          `json:"expired_time" gorm:"bigint"` // 过期时间,0 表示不过期
}

func GetAllRedemptions

func GetAllRedemptions(startIdx int, num int) (redemptions []*Redemption, total int64, err error)

func GetRedemptionById

func GetRedemptionById(id int) (*Redemption, error)

func SearchRedemptions

func SearchRedemptions(keyword string, startIdx int, num int) (redemptions []*Redemption, total int64, err error)

func (*Redemption) Delete

func (redemption *Redemption) Delete() error

func (*Redemption) Insert

func (redemption *Redemption) Insert() error

func (*Redemption) SelectUpdate

func (redemption *Redemption) SelectUpdate() error

func (*Redemption) Update

func (redemption *Redemption) Update() error

Update Make sure your token's fields is completed, because this will update non-zero values

type SMSPurpose

type SMSPurpose string

SMSPurpose 短信验证码用途

const (
	SMSPurposeRegister    SMSPurpose = "register"       // 注册
	SMSPurposeLogin       SMSPurpose = "login"          // 登录
	SMSPurposeResetPwd    SMSPurpose = "reset_password" // 重置密码
	SMSPurposeBindPhone   SMSPurpose = "bind_phone"     // 绑定手机号
	SMSPurposeUnbindPhone SMSPurpose = "unbind_phone"   // 解绑手机号
)

type SMSVerificationCode

type SMSVerificationCode struct {
	ID        uint       `gorm:"primaryKey" json:"id"`
	Phone     string     `gorm:"type:varchar(20);index" json:"phone"`
	Code      string     `gorm:"type:varchar(10)" json:"code"`
	Purpose   SMSPurpose `gorm:"type:varchar(20);index" json:"purpose"`
	ExpiresAt time.Time  `json:"expires_at"`
	Used      bool       `gorm:"default:false" json:"used"`
	CreatedAt time.Time  `json:"created_at"`
}

SMSVerificationCode 短信验证码表

func CreateSMSVerificationCode

func CreateSMSVerificationCode(phone string, code string, purpose SMSPurpose, expireMinutes int) (*SMSVerificationCode, error)

CreateSMSVerificationCode 创建短信验证码

func (SMSVerificationCode) TableName

func (SMSVerificationCode) TableName() string

TableName 指定表名

type Setup

type Setup struct {
	ID            uint   `json:"id" gorm:"primaryKey"`
	Version       string `json:"version" gorm:"type:varchar(50);not null"`
	InitializedAt int64  `json:"initialized_at" gorm:"type:bigint;not null"`
}

func GetSetup

func GetSetup() *Setup

type Skill

type Skill struct {
	Id          int64  `json:"id"           gorm:"primaryKey;autoIncrement"`
	Name        string `json:"name"         gorm:"type:varchar(128);not null;uniqueIndex:idx_skills_name_version,priority:1"`
	Version     string `json:"version"      gorm:"type:varchar(32);not null;uniqueIndex:idx_skills_name_version,priority:2"`
	Description string `json:"description"  gorm:"type:text;default:''"`
	Author      string `json:"author"       gorm:"type:varchar(128);default:''"`
	Category    string `json:"category"     gorm:"type:varchar(64);default:'general';index"`
	DownloadUrl string `json:"download_url" gorm:"type:varchar(512);not null"`
	Sha256      string `json:"sha256"       gorm:"type:varchar(64);not null"`
	SizeBytes   int64  `json:"size_bytes"   gorm:"default:0"`
	Downloads   int64  `json:"downloads"    gorm:"default:0"`
	Status      string `json:"status"       gorm:"type:varchar(20);default:'draft';index"`
	UserId      int    `json:"user_id"      gorm:"default:0"`
	TenantId    int    `json:"tenant_id"    gorm:"default:0;index"`
	CreatedAt   int64  `json:"created_at"   gorm:"default:0"`
	UpdatedAt   int64  `json:"updated_at"   gorm:"default:0"`
}

Skill Agent Marketplace L1 技能注册中心的目录表模型。

设计要点:

  • created_at/updated_at 为 bigint epoch 秒(common.GetTimestamp()),对齐仓库既有约定。
  • sha256 为 64 位小写十六进制摘要,客户端下载后本地比对,保障产物完整性。
  • user_id/tenant_id 为 L2「组织私有技能」预留,本期全部写 0(公开技能)。 撞 id 铁律:tenant_id 只写 enterprise_id,永不写 user_id。

func GetSkillById

func GetSkillById(id int64) (*Skill, error)

GetSkillById 按主键获取技能;不存在时返回 gorm.ErrRecordNotFound。

func GetSkillByNameVersion

func GetSkillByNameVersion(name string, version string) (*Skill, error)

GetSkillByNameVersion 按「名称 + 版本」唯一键获取技能;不存在时返回 gorm.ErrRecordNotFound。

func ListSkills

func ListSkills(category string, keyword string, status string, startIdx int, num int) (skills []*Skill, total int64, err error)

ListSkills 分页检索技能目录。

参数:

  • category:为空则不过滤分类
  • keyword:为空则不过滤;非空时对 name/description 做 LIKE,必须过 sanitizeLikePattern
  • status:为空则不过滤(管理员全量视图);普通用户由调用方强制传 SkillStatusPublished
  • startIdx / num:偏移与条数,num 受 SkillPageHardLimit 硬上限截断

返回:技能列表、匹配总数、错误。

func (Skill) TableName

func (Skill) TableName() string

TableName 固定表名,避免 GORM 复数化推断歧义。

type Stat

type Stat struct {
	Quota int `json:"quota"`
	Rpm   int `json:"rpm"`
	Tpm   int `json:"tpm"`
}

func SumUsedQuota

func SumUsedQuota(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string, channel int, group string) (stat Stat, err error)

func SumUsedQuotaSelf

func SumUsedQuotaSelf(userId int, logType int, startTimestamp int64, endTimestamp int64, modelName string, tokenName string, channel int, group string) (stat Stat, err error)

SumUsedQuotaSelf 统计当前用户(含其所属企业共享资源)的用量。 与 SumUsedQuota 的区别:按 user_id/tenant_id 过滤而非 username, 从而与 GetUserLogs 的租户可见性口径保持一致。 SumUsedQuota 同时服务管理员全局视图(GetLogsStat),不可原地改签名,故另起本函数。

type SyncTaskQueryParams

type SyncTaskQueryParams struct {
	Platform       constant.TaskPlatform
	ChannelID      string
	TaskID         string
	UserID         string
	Action         string
	Status         string
	StartTimestamp int64
	EndTimestamp   int64
	UserIDs        []int
}

SyncTaskQueryParams 用于包含所有搜索条件的结构体,可以根据需求添加更多字段

type Task

type Task struct {
	ID         int64                 `json:"id" gorm:"primary_key;AUTO_INCREMENT"`
	CreatedAt  int64                 `json:"created_at" gorm:"index"`
	UpdatedAt  int64                 `json:"updated_at"`
	TaskID     string                `json:"task_id" gorm:"type:varchar(191);index"` // 第三方id,不一定有/ song id\ Task id
	Platform   constant.TaskPlatform `json:"platform" gorm:"type:varchar(30);index"` // 平台
	UserId     int                   `json:"user_id" gorm:"index"`
	Group      string                `json:"group" gorm:"type:varchar(50)"` // 修正计费用
	ChannelId  int                   `json:"channel_id" gorm:"index"`
	Quota      int                   `json:"quota"`
	Action     string                `json:"action" gorm:"type:varchar(40);index"` // 任务类型, song, lyrics, description-mode
	Status     TaskStatus            `json:"status" gorm:"type:varchar(20);index"` // 任务状态
	FailReason string                `json:"fail_reason"`
	SubmitTime int64                 `json:"submit_time" gorm:"index"`
	StartTime  int64                 `json:"start_time" gorm:"index"`
	FinishTime int64                 `json:"finish_time" gorm:"index"`
	Progress   string                `json:"progress" gorm:"type:varchar(20);index"`
	Properties Properties            `json:"properties" gorm:"type:json"`
	Username   string                `json:"username,omitempty" gorm:"-"`
	// 禁止返回给用户,内部可能包含key等隐私信息
	PrivateData TaskPrivateData `json:"-" gorm:"column:private_data;type:json"`
	Data        json.RawMessage `json:"data" gorm:"type:json"`
}

func GetAllUnFinishSyncTasks

func GetAllUnFinishSyncTasks(limit int) []*Task

func GetByOnlyTaskId

func GetByOnlyTaskId(taskId string) (*Task, bool, error)

func GetByTaskId

func GetByTaskId(userId int, taskId string) (*Task, bool, error)

func GetByTaskIds

func GetByTaskIds(userId int, taskIds []any) ([]*Task, error)

func GetTimedOutUnfinishedTasks

func GetTimedOutUnfinishedTasks(cutoffUnix int64, limit int) []*Task

func InitTask

func InitTask(platform constant.TaskPlatform, relayInfo *commonRelay.RelayInfo) *Task

func TaskGetAllTasks

func TaskGetAllTasks(startIdx int, num int, queryParams SyncTaskQueryParams) []*Task

func TaskGetAllUserTask

func TaskGetAllUserTask(userId int, startIdx int, num int, queryParams SyncTaskQueryParams) []*Task

func (*Task) GetData

func (t *Task) GetData(v any) error

func (*Task) GetResultURL

func (t *Task) GetResultURL() string

GetResultURL 获取任务结果 URL(视频地址等) 新数据存在 PrivateData.ResultURL 中;旧数据回退到 FailReason(历史兼容)

func (*Task) GetUpstreamTaskID

func (t *Task) GetUpstreamTaskID() string

GetUpstreamTaskID 获取上游真实 task ID(用于与 provider 通信) 旧数据没有 UpstreamTaskID 时,TaskID 本身就是上游 ID

func (*Task) Insert

func (Task *Task) Insert() error

func (*Task) SetData

func (t *Task) SetData(data any)

func (*Task) Snapshot

func (t *Task) Snapshot() taskSnapshot

func (*Task) ToOpenAIVideo

func (t *Task) ToOpenAIVideo() *dto.OpenAIVideo

func (*Task) Update

func (Task *Task) Update() error

func (*Task) UpdateWithStatus

func (t *Task) UpdateWithStatus(fromStatus TaskStatus) (bool, error)

UpdateWithStatus performs a conditional UPDATE guarded by fromStatus (CAS). Returns (true, nil) if this caller won the update, (false, nil) if another process already moved the task out of fromStatus.

Uses Model().Select("*").Updates() instead of Save() because GORM's Save falls back to INSERT ON CONFLICT when the WHERE-guarded UPDATE matches zero rows, which silently bypasses the CAS guard.

type TaskBillingContext

type TaskBillingContext struct {
	ModelPrice      float64            `json:"model_price,omitempty"`       // 模型单价
	GroupRatio      float64            `json:"group_ratio,omitempty"`       // 分组倍率
	ModelRatio      float64            `json:"model_ratio,omitempty"`       // 模型倍率
	OtherRatios     map[string]float64 `json:"other_ratios,omitempty"`      // 附加倍率(时长、分辨率等)
	OriginModelName string             `json:"origin_model_name,omitempty"` // 模型名称,必须为OriginModelName
	PerCallBilling  bool               `json:"per_call_billing,omitempty"`  // 按次计费:跳过轮询阶段的差额结算
}

TaskBillingContext 记录任务提交时的计费参数,以便轮询阶段可以重新计算额度。

type TaskPrivateData

type TaskPrivateData struct {
	Key            string `json:"key,omitempty"`
	UpstreamTaskID string `json:"upstream_task_id,omitempty"` // 上游真实 task ID
	ResultURL      string `json:"result_url,omitempty"`       // 任务成功后的结果 URL(视频地址等)
	// 计费上下文:用于异步退款/差额结算(轮询阶段读取)
	BillingSource    string              `json:"billing_source,omitempty"`     // "wallet"(个人钱包)或 "enterprise"(企业钱包)
	EnterpriseUserId int                 `json:"enterprise_user_id,omitempty"` // enterprise_user.id,企业钱包退款原路返回
	SubscriptionId   int                 `json:"subscription_id,omitempty"`    // 订阅 ID,用于订阅退款
	TokenId          int                 `json:"token_id,omitempty"`           // 令牌 ID,用于令牌额度退款
	BillingContext   *TaskBillingContext `json:"billing_context,omitempty"`    // 计费参数快照(用于轮询阶段重新计算)
}

func (*TaskPrivateData) Scan

func (p *TaskPrivateData) Scan(val interface{}) error

func (TaskPrivateData) Value

func (p TaskPrivateData) Value() (driver.Value, error)

type TaskQueryParams

type TaskQueryParams struct {
	ChannelID      string
	MjID           string
	StartTimestamp string
	EndTimestamp   string
}

TaskQueryParams 用于包含所有搜索条件的结构体,可以根据需求添加更多字段

type TaskQuotaUsage

type TaskQuotaUsage struct {
	Mode  string  `json:"mode"`
	Count float64 `json:"count"`
}

type TaskStatus

type TaskStatus string

func (TaskStatus) ToVideoStatus

func (t TaskStatus) ToVideoStatus() string

type Token

type Token struct {
	Id                 int            `json:"id"`
	UserId             int            `json:"user_id" gorm:"index"`
	Key                string         `json:"key" gorm:"type:varchar(128);uniqueIndex"`
	Status             int            `json:"status" gorm:"default:1"`
	Name               string         `json:"name" gorm:"index" `
	CreatedTime        int64          `json:"created_time" gorm:"bigint"`
	AccessedTime       int64          `json:"accessed_time" gorm:"bigint"`
	ExpiredTime        int64          `json:"expired_time" gorm:"bigint;default:-1"` // -1 means never expired
	RemainQuota        int            `json:"remain_quota" gorm:"default:0"`
	UnlimitedQuota     bool           `json:"unlimited_quota"`
	ModelLimitsEnabled bool           `json:"model_limits_enabled"`
	ModelLimits        string         `json:"model_limits" gorm:"type:text"`
	AllowIps           *string        `json:"allow_ips" gorm:"default:''"`
	UsedQuota          int            `json:"used_quota" gorm:"default:0"` // used quota
	Group              string         `json:"group" gorm:"default:''"`
	CrossGroupRetry    bool           `json:"cross_group_retry"` // 跨分组重试,仅auto分组有效
	TenantId           int            `json:"tenant_id" gorm:"default:0;index"`
	DeletedAt          gorm.DeletedAt `gorm:"index"`
}

func GetAllTokensAdmin

func GetAllTokensAdmin(startIdx int, num int) (tokens []*Token, total int64, err error)

GetAllTokensAdmin 管理员导出用:返回全量 token(不含已软删除)。调用方需自行脱敏 Key。

func GetAllUserTokens

func GetAllUserTokens(userId int, startIdx int, num int) ([]*Token, error)

func GetTokenById

func GetTokenById(id int) (*Token, error)

func GetTokenByIds

func GetTokenByIds(id int, userId int) (*Token, error)

func GetTokenByKey

func GetTokenByKey(key string, fromDB bool) (token *Token, err error)

func GetTokenKeysByIds

func GetTokenKeysByIds(ids []int, userId int) ([]Token, error)

func SearchUserTokens

func SearchUserTokens(userId int, keyword string, token string, offset int, limit int) (tokens []*Token, total int64, err error)

func ValidateUserToken

func ValidateUserToken(key string) (token *Token, err error)

func (*Token) Clean

func (token *Token) Clean()

func (*Token) Delete

func (token *Token) Delete() (err error)

func (*Token) GetFullKey

func (token *Token) GetFullKey() string

func (*Token) GetIpLimits

func (token *Token) GetIpLimits() []string

func (*Token) GetMaskedKey

func (token *Token) GetMaskedKey() string

func (*Token) GetModelLimits

func (token *Token) GetModelLimits() []string

func (*Token) GetModelLimitsMap

func (token *Token) GetModelLimitsMap() map[string]bool

func (*Token) Insert

func (token *Token) Insert() error

func (*Token) IsModelLimitsEnabled

func (token *Token) IsModelLimitsEnabled() bool

func (*Token) SelectUpdate

func (token *Token) SelectUpdate() (err error)

func (*Token) Update

func (token *Token) Update() (err error)

Update Make sure your token's fields is completed, because this will update non-zero values

type TopUp

type TopUp struct {
	Id              int     `json:"id"`
	UserId          int     `json:"user_id" gorm:"index"`
	Amount          int64   `json:"amount"`
	Money           float64 `json:"money"`
	TradeNo         string  `json:"trade_no" gorm:"unique;type:varchar(255);index"`
	PaymentMethod   string  `json:"payment_method" gorm:"type:varchar(50)"`
	PaymentProvider string  `json:"payment_provider" gorm:"type:varchar(50);default:''"`
	CreateTime      int64   `json:"create_time"`
	CompleteTime    int64   `json:"complete_time"`
	Status          string  `json:"status"`

	// WalletType 充值入账目标钱包:wallet=个人钱包(默认),enterprise=企业主钱包
	WalletType string `json:"wallet_type" gorm:"type:varchar(20);default:'wallet';index"`

	// Tenant isolation (Phase 1 multi-tenancy)
	TenantId int `json:"tenant_id" gorm:"default:0;index"`
}

func GetAllTopUps

func GetAllTopUps(pageInfo *common.PageInfo) (topups []*TopUp, total int64, err error)

GetAllTopUps 获取全平台的充值记录(管理员使用,不限制时间窗口)

func GetPendingAlipayTopUps

func GetPendingAlipayTopUps() ([]*TopUp, error)

GetPendingAlipayTopUps 返回所有 pending 状态的支付宝充值订单,用于主动对账补单。

func GetPendingWechatTopUps

func GetPendingWechatTopUps() ([]*TopUp, error)

GetPendingWechatTopUps 返回所有 pending 状态的微信充值订单,用于主动对账补单。

func GetTopUpById

func GetTopUpById(id int) *TopUp

func GetTopUpByTradeNo

func GetTopUpByTradeNo(tradeNo string) *TopUp

func GetUserTopUps

func GetUserTopUps(userId int, pageInfo *common.PageInfo) (topups []*TopUp, total int64, err error)

func SearchAllTopUps

func SearchAllTopUps(keyword string, pageInfo *common.PageInfo) (topups []*TopUp, total int64, err error)

SearchAllTopUps 按订单号搜索全平台充值记录(管理员使用,不限制时间窗口)

func SearchUserTopUps

func SearchUserTopUps(userId int, keyword string, pageInfo *common.PageInfo) (topups []*TopUp, total int64, err error)

SearchUserTopUps 按订单号搜索某用户的充值记录

func (*TopUp) Insert

func (topUp *TopUp) Insert() error

func (*TopUp) Update

func (topUp *TopUp) Update() error

type UiSkin

type UiSkin struct {
	Key         string    `json:"key" gorm:"primaryKey;type:varchar(32);not null"`
	Name        string    `json:"name" gorm:"type:varchar(64);not null"`
	Description string    `json:"description" gorm:"type:text"`
	Css         string    `json:"css" gorm:"type:text"`
	Enabled     bool      `json:"enabled" gorm:"default:true"`
	IsDefault   bool      `json:"is_default" gorm:"default:false"`
	Priority    int       `json:"priority" gorm:"default:0"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

UiSkin 是运行时可配置的前端皮肤定义(配置即数据:运营在后台增删改皮肤免部署)。 key 为皮肤唯一标识(如 neo/aurora),与前端 styles/skins.css 的 [data-skin=key] 选择器对应; css 为该皮肤的完整 CSS 变量块——留空则回退到 bundled skins.css 的内置定义(保证零回归与无 FOUC)。

func GetAllUiSkins

func GetAllUiSkins() []*UiSkin

GetAllUiSkins 返回全部皮肤(后台管理用,含禁用项)。

func GetEnabledUiSkins

func GetEnabledUiSkins() []*UiSkin

GetEnabledUiSkins 返回前端可用的(enabled)皮肤列表,css 一并下发(内置皮肤 css 为空→前端回退 bundled)。

func (UiSkin) TableName

func (UiSkin) TableName() string

type User

type User struct {
	Id               int            `json:"id"`
	Username         string         `json:"username" gorm:"unique;index" validate:"max=50"`
	Password         string         `json:"password" gorm:"not null;" validate:"min=8,max=50"`
	OriginalPassword string         `json:"original_password" gorm:"-:all"` // this field is only for Password change verification, don't save it to database!
	DisplayName      string         `json:"display_name" gorm:"index" validate:"max=20"`
	Role             int            `json:"role" gorm:"type:int;default:1"`   // admin, common
	Status           int            `json:"status" gorm:"type:int;default:1"` // enabled, disabled
	Email            string         `json:"email" gorm:"index" validate:"max=50"`
	WeChatId         string         `json:"wechat_id" gorm:"column:wechat_id;index"`
	Phone            string         `json:"phone" gorm:"column:phone;index;default:''" validate:"omitempty,len=11"`
	VerificationCode string         `json:"verification_code" gorm:"-:all"`                         // this field is only for Email verification, don't save it to database!
	AccessToken      *string        `json:"-" gorm:"type:char(32);column:access_token;uniqueIndex"` // this token is for system management
	Quota            int            `json:"quota" gorm:"type:int;default:0"`
	UsedQuota        int            `json:"used_quota" gorm:"type:int;default:0;column:used_quota"` // used quota
	RequestCount     int            `json:"request_count" gorm:"type:int;default:0;"`               // request number
	Group            string         `json:"group" gorm:"type:varchar(64);default:'default'"`
	AffCode          string         `json:"aff_code" gorm:"type:varchar(32);column:aff_code;uniqueIndex"`
	AffCount         int            `json:"aff_count" gorm:"type:int;default:0;column:aff_count"`
	AffQuota         int            `json:"aff_quota" gorm:"type:int;default:0;column:aff_quota"`           // affiliate remaining quota
	AffHistoryQuota  int            `json:"aff_history_quota" gorm:"type:int;default:0;column:aff_history"` // affiliate history quota
	InviterId        int            `json:"inviter_id" gorm:"type:int;column:inviter_id;index"`
	AffRechargeTotal int            `json:"aff_recharge_total" gorm:"type:int;default:0;column:aff_recharge_total"` // 累计被推荐人实付总额(元)
	DeletedAt        gorm.DeletedAt `gorm:"index"`
	Setting          string         `json:"setting" gorm:"type:text;column:setting"`
	Remark           string         `json:"remark,omitempty" gorm:"type:varchar(255)" validate:"max=255"`
	// Membership related fields
	MembershipLevel  string `json:"membership_level" gorm:"type:varchar(20);default:'silver';index"` // silver/gold/platinum
	MembershipExpire int64  `json:"membership_expire" gorm:"default:0"`                              // membership expiration time (Unix timestamp, 0=never expire)
	InvitationCode   string `json:"invitation_code" gorm:"type:varchar(32);default:''"`              // invitation code used
	EnterpriseId     int    `json:"enterprise_id" gorm:"default:0;index"`                            // associated enterprise ID
	RegisterIp       string `json:"register_ip" gorm:"type:varchar(45);default:"`
	UID              string `json:"uid" gorm:"type:varchar(32);uniqueIndex;default:''"` // public unique identifier
	CreatedAt        int64  `json:"created_at" gorm:"autoCreateTime;column:created_at"`
	LastLoginAt      int64  `json:"last_login_at" gorm:"default:0;column:last_login_at"`
}

User if you add sensitive fields, don't forget to clean them in setupLogin function. Otherwise, the sensitive information will be saved on local storage in plain text!

func GetAllUsers

func GetAllUsers(pageInfo interface{}) ([]*User, int64, error)

GetAllUsers returns all users with pagination

func GetRootUser

func GetRootUser() (*User, error)

GetRootUser returns the root/admin user

func GetUserById

func GetUserById(id int, selectAll bool) (*User, error)

func GetUserByOAuthBinding

func GetUserByOAuthBinding(providerId int, providerUserId string) (*User, error)

GetUserByOAuthBinding finds a user by provider ID and provider user ID

func SearchUsers

func SearchUsers(keyword string, group string, role *int, status *int, startIdx int, num int) ([]*User, int64, error)

SearchUsers searches users by keyword with optional group, role, and status filters

func ValidateAccessToken

func ValidateAccessToken(token string) (*User, error)

func (*User) BeforeCreate

func (u *User) BeforeCreate(tx *gorm.DB) (err error)

BeforeCreate GORM hook: automatically generate unique aff_code and hash password before creating user

func (*User) ClearBinding

func (user *User) ClearBinding(bindingType string) error

ClearBinding clears the specified OAuth binding (wechat)

func (*User) Edit

func (user *User) Edit(updatePassword bool) error

func (*User) FillUserByEmail

func (user *User) FillUserByEmail() error

FillUserByEmail fills user by email (case-insensitive)

func (*User) FillUserById

func (user *User) FillUserById() error

FillUserById fills user by ID

func (*User) FillUserByIdentifier

func (user *User) FillUserByIdentifier(identifier string) error

FillUserByIdentifier tries to find user by UID, username, email, or phone (in that order)

func (*User) FillUserByPhone

func (user *User) FillUserByPhone() error

FillUserByPhone fills user by Phone (method on User)

func (*User) FillUserByWeChatId

func (user *User) FillUserByWeChatId() error

FillUserByWeChatId fills user by WeChat ID (method on User)

func (*User) GetAccessToken

func (user *User) GetAccessToken() string

func (*User) GetSetting

func (user *User) GetSetting() dto.UserSetting

func (*User) Insert

func (user *User) Insert(inviterId int) error

func (*User) InsertWithTx

func (user *User) InsertWithTx(tx *gorm.DB) error

InsertWithTx inserts user with transaction

func (*User) SetAccessToken

func (user *User) SetAccessToken(token string)

func (*User) SetSetting

func (user *User) SetSetting(setting dto.UserSetting)

func (*User) ToBaseUser

func (user *User) ToBaseUser() *UserBase

ToBaseUser converts User to UserBase for cache

func (*User) TransferAffQuotaToQuota

func (user *User) TransferAffQuotaToQuota(amount int) error

TransferAffQuotaToQuota transfers affiliate quota to main quota (stub)

func (*User) Update

func (user *User) Update(updatePassword bool) error

func (*User) UpdateWeChatId

func (user *User) UpdateWeChatId(wechatId string) error

UpdateWeChatId updates user's WeChat ID

func (*User) ValidateAndFill

func (user *User) ValidateAndFill() error

ValidateAndFill validates user credentials and fills user model (stub)

func (*User) ValidatePassword

func (user *User) ValidatePassword(password string) bool

ValidatePassword validates if the given password matches user's password

type UserBase

type UserBase struct {
	Id       int    `json:"id"`
	Group    string `json:"group"`
	Email    string `json:"email"`
	Quota    int    `json:"quota"`
	Status   int    `json:"status"`
	Username string `json:"username"`
	Setting  string `json:"setting"`
}

UserBase struct remains the same as it represents the cached data structure

func GetUserCache

func GetUserCache(userId int) (userCache *UserBase, err error)

GetUserCache gets complete user cache from hash

func (*UserBase) GetSetting

func (user *UserBase) GetSetting() dto.UserSetting

func (*UserBase) WriteContext

func (user *UserBase) WriteContext(c *gin.Context)

type UserGift

type UserGift struct {
	Id          int    `json:"id" gorm:"primaryKey;autoIncrement"`
	UserId      int    `json:"user_id" gorm:"index"`
	GiftType    string `json:"gift_type" gorm:"type:varchar(50);index"`         // 赠品类型:event_ticket, etc.
	GiftKey     string `json:"gift_key" gorm:"type:varchar(100);index"`         // 赠品标识(如 waic_2026_day20),用于限额计数与幂等
	GiftName    string `json:"gift_name" gorm:"type:varchar(255)"`              // 赠品名称
	TradeNo     string `json:"trade_no" gorm:"type:varchar(255);index"`         // 关联充值订单号
	Status      string `json:"status" gorm:"type:varchar(20);default:'active'"` // active, used, expired
	Description string `json:"description" gorm:"type:text"`                    // 备注说明
	CreateTime  int64  `json:"create_time"`
	UpdateTime  int64  `json:"update_time"`
}

UserGift 用户赠品记录(充值赠送AI大会门票等)

func GetUserGifts

func GetUserGifts(userId int) ([]UserGift, error)

type UserGiftCounter

type UserGiftCounter struct {
	GiftKey    string `json:"gift_key" gorm:"primaryKey;type:varchar(100)"`
	Issued     int    `json:"issued" gorm:"not null;default:0"`
	CreateTime int64  `json:"create_time"`
	UpdateTime int64  `json:"update_time"`
}

UserGiftCounter 赠品发放计数器(按 gift_key 严格限额,避免超发)。

type UserOAuthBinding

type UserOAuthBinding struct {
	ID             uint      `gorm:"primaryKey" json:"id"`
	UserID         int       `json:"user_id" gorm:"not null;uniqueIndex:ux_user_provider"`                                    // User ID - one binding per user per provider
	ProviderID     int       `json:"provider_id" gorm:"not null;uniqueIndex:ux_user_provider;uniqueIndex:ux_provider_userid"` // Custom OAuth provider ID
	ProviderUserID string    `json:"provider_user_id" gorm:"type:varchar(256);not null;uniqueIndex:ux_provider_userid"`       // User ID from OAuth provider - one OAuth account per provider
	CreatedAt      time.Time `json:"created_at"`
}

UserOAuthBinding stores the binding relationship between users and custom OAuth providers

func GetUserOAuthBinding

func GetUserOAuthBinding(userId, providerId int) (*UserOAuthBinding, error)

GetUserOAuthBinding returns a specific binding for a user and provider

func GetUserOAuthBindingsByUserId

func GetUserOAuthBindingsByUserId(userId int) ([]*UserOAuthBinding, error)

GetUserOAuthBindingsByUserId returns all OAuth bindings for a user

func (UserOAuthBinding) TableName

func (UserOAuthBinding) TableName() string

type UserWebhook

type UserWebhook struct {
	Id        int    `json:"id" gorm:"primaryKey;autoIncrement"`
	UserId    int    `json:"user_id" gorm:"index"`
	Url       string `json:"url" gorm:"type:varchar(512)"`
	Events    string `json:"events" gorm:"type:varchar(256)"` // comma-separated: "topup,quota_low"
	Secret    string `json:"secret" gorm:"type:varchar(64)"`  // for HMAC signature
	Enabled   bool   `json:"enabled" gorm:"default:true"`
	CreatedAt int64  `json:"created_at"`
	UpdatedAt int64  `json:"updated_at"`
}

func GetUserWebhookById

func GetUserWebhookById(id int, userId int) (*UserWebhook, error)

GetUserWebhookById returns a single webhook by id, ensuring it belongs to the user.

func GetUserWebhooks

func GetUserWebhooks(userId int) ([]UserWebhook, error)

GetUserWebhooks returns all webhooks for a user.

func GetUserWebhooksByEvent

func GetUserWebhooksByEvent(userId int, event string) ([]UserWebhook, error)

GetUserWebhooksByEvent returns all enabled webhooks for a user that match the given event.

func (*UserWebhook) BeforeCreate

func (uw *UserWebhook) BeforeCreate(tx *gorm.DB) error

func (*UserWebhook) BeforeUpdate

func (uw *UserWebhook) BeforeUpdate(tx *gorm.DB) error

func (*UserWebhook) HasEvent

func (uw *UserWebhook) HasEvent(event string) bool

HasEvent checks if this webhook is subscribed to the given event.

func (*UserWebhook) TableName

func (uw *UserWebhook) TableName() string

type Vendor

type Vendor struct {
	Id          int            `json:"id"`
	Name        string         `json:"name" gorm:"size:128;not null;uniqueIndex:uk_vendor_name_delete_at,priority:1"`
	Description string         `json:"description,omitempty" gorm:"type:text"`
	Icon        string         `json:"icon,omitempty" gorm:"type:varchar(128)"`
	Status      int            `json:"status" gorm:"default:1"`
	CreatedTime int64          `json:"created_time" gorm:"bigint"`
	UpdatedTime int64          `json:"updated_time" gorm:"bigint"`
	DeletedAt   gorm.DeletedAt `json:"-" gorm:"index;uniqueIndex:uk_vendor_name_delete_at,priority:2"`
}

func GetAllVendors

func GetAllVendors(offset int, limit int) ([]*Vendor, error)

GetAllVendors 获取全部供应商(分页)

func GetVendorByID

func GetVendorByID(id int) (*Vendor, error)

GetVendorByID 根据 ID 获取供应商

func SearchVendors

func SearchVendors(keyword string, offset int, limit int) ([]*Vendor, int64, error)

SearchVendors 按关键字搜索供应商

func (*Vendor) Delete

func (v *Vendor) Delete() error

Delete 软删除供应商

func (*Vendor) Insert

func (v *Vendor) Insert() error

Insert 创建新的供应商记录

func (*Vendor) Update

func (v *Vendor) Update() error

Update 更新供应商记录

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL