Documentation
¶
Index ¶
- Constants
- Variables
- func AdminBindSubscription(userId int, planId int, sourceNote string) (string, error)
- func AdminDeleteUserSubscription(userSubscriptionId int) (string, error)
- func AdminInvalidateUserSubscription(userSubscriptionId int) (string, error)
- func ApplyBillingSettlementOnce(input BillingSettlementInput) (appliedFundingDelta int64, alreadyApplied bool, err error)
- func ApplyChannelGroupFilter(query *gorm.DB, group string) *gorm.DB
- func BatchDeleteChannels(ids []int) error
- func BatchDeleteTokens(ids []int, userId int) (int, error)
- func BatchInsertChannels(channels []Channel) error
- func BatchSetChannelTag(ids []int, tag *string) error
- func BindEmailToUser(user *User, email string) error
- func CacheUpdateChannel(channel *Channel)
- func CacheUpdateChannelStatus(id int, status int)
- func ChannelSupportsRequestPath(channel *Channel, requestPath string) bool
- func CheckSetup()
- func CheckUserExistOrDeleted(username string, email string) (bool, error)
- func CleanupChannelPollingLocks()
- func CleanupSubscriptionPreConsumeRecords(olderThanSeconds int64) (int64, error)
- func CloseDB() error
- func CompleteSubscriptionOrder(tradeNo string, providerPayload string, expectedPaymentProvider string, ...) error
- func CountAllChannels() (int64, error)
- func CountAllTags() (int64, error)
- func CountAllTasks(queryParams TaskQueryParams) int64
- func CountAllUserTask(userId int, queryParams TaskQueryParams) int64
- func CountChannelTags(query *gorm.DB) (int64, error)
- func CountChannelsByType(channelType int) (int64, error)
- func CountChannelsGroupByType() (map[int64]int64, error)
- func CountOldLog(ctx context.Context, targetTimestamp int64) (int64, error)
- func CountUserSubscriptionsByPlan(userId int, planId int) (int64, error)
- func CountUserTokens(userId int) (int64, error)
- func CountUsersByEmail(email string) (int64, error)
- func CreateBackupCodes(userId int, codes []string) error
- func CreateCustomOAuthProvider(provider *CustomOAuthProvider) error
- func CreateUserOAuthBinding(binding *UserOAuthBinding) error
- func CreateUserOAuthBindingWithTx(tx *gorm.DB, binding *UserOAuthBinding) error
- func DecreaseTokenQuota(id int, key string, quota int) (err error)
- func DecreaseUserQuota[T quotaDeltaInteger](id int, quota T, _ bool) (err error)
- func DeleteChannelByStatus(status int64) (int64, error)
- func DeleteCustomOAuthProvider(id int) error
- func DeleteDisabledChannel() (int64, error)
- func DeleteExpiredAuthFlows(now time.Time) error
- func DeleteInvalidRedemptions() (int64, error)
- func DeleteOldBillingLogReceipts(ctx context.Context, targetTimestamp int64, limit int) (int64, error)
- func DeleteOldBillingLogReceiptsBatch(ctx context.Context, targetTimestamp int64, limit int) (int64, error)
- func DeleteOldLog(ctx context.Context, targetTimestamp int64, limit int) (int64, error)
- func DeleteOldLogBatch(ctx context.Context, targetTimestamp int64, limit int) (int64, error)
- func DeletePasskeyByUserID(userID int) error
- func DeletePerfMetricsBefore(cutoffTs int64) error
- func DeletePrefillGroupByID(id int) error
- func DeleteRedemptionById(id int) (err error)
- func DeleteStaleSystemInstance(nodeName string, now int64) error
- func DeleteStaleSystemInstances(now int64) (int64, error)
- func DeleteTokenById(id int, userId int) (err error)
- func DeleteUserById(id int) (err error)
- func DeleteUserOAuthBinding(userId, providerId int) error
- func DeleteUserOAuthBindingsByUserId(userId int) error
- func DeltaUpdateUserQuota[T quotaDeltaInteger](id int, delta T) (err error)
- func DisableChannelByTag(tag string) error
- func DisableModelLimits(tokenId int) error
- func DisableTwoFA(userId int) error
- func EditChannelByTag(tag string, newTag *string, modelMapping *string, models *string, ...) error
- func EnableChannelByTag(tag string) error
- func EnsureEmailAvailable(email string, excludeUserID int) error
- func ExpireDueSubscriptions(limit int) (int, error)
- func ExpireSubscriptionOrder(tradeNo string, expectedPaymentProvider string) error
- func FinalizeMidjourneySubmission(midjourney *Midjourney, billingTask *Task, ...) (created bool, refundDuplicate bool, err error)
- func FinishSystemTask(taskID string, lockedBy string, status SystemTaskStatus, resultPayload any, ...) error
- func FixAbility() (int, int, error)
- func GenerateSystemTaskID() (string, error)
- func GenerateTaskID() string
- func GetBindingCountByProviderId(providerId int) (int64, error)
- func GetBoundChannelsByModelsMap(modelNames []string) (map[string][]BoundChannel, error)
- func GetChannelPollingLock(channelId int) *sync.Mutex
- func GetDBTimestamp() int64
- func GetEnabledModels() []string
- func GetGroupEnabledModels(group string) []string
- func GetMaxUserId() int
- func GetMissingModels() ([]string, error)
- func GetModelEnableGroups(modelName string) []string
- func GetModelQuotaTypes(modelName string) []int
- func GetModelSupportEndpointTypes(model string) []constant.EndpointType
- func GetPaginatedChannelTags(query *gorm.DB, offset int, limit int) ([]*string, error)
- func GetPaginatedTags(offset int, limit int) ([]*string, error)
- func GetPreferredModelOwnerChannelTypes(modelNames []string, groups []string) (map[string]int, error)
- func GetSupportedEndpointMap() map[string]common.EndpointInfo
- func GetTwoFAStats() (map[string]interface{}, error)
- func GetUnusedBackupCodeCount(userId int) (int, error)
- func GetUserCheckinStats(userId int, month string) (map[string]interface{}, error)
- func GetUserEmail(id int) (email string, err error)
- func GetUserGroup(id int, fromDB bool) (group string, err error)
- func GetUserIdByAffCode(affCode string) (int, error)
- func GetUserLanguage(userId int) string
- func GetUserQuota(id int, fromDB bool) (quota int64, err error)
- func GetUserSetting(id int, fromDB bool) (settingMap dto.UserSetting, err error)
- func GetUserUsedQuota(id int) (quota int64, err error)
- func GetUsernameById(id int, fromDB bool) (username string, err error)
- func GetVendorModelCounts() (map[int64]int64, error)
- func HardDeleteUserById(id int) error
- func HasActiveUserSubscription(userId int) (bool, error)
- func HasCheckedInToday(userId int) (bool, error)
- func IncreaseTokenQuota(tokenId int, key string, quota int) (err error)
- func IncreaseUserQuota[T quotaDeltaInteger](id int, quota T, _ bool) (err error)
- func InitBatchUpdater()
- func InitChannelCache()
- func InitDB() (err error)
- func InitLogDB() (err error)
- func InitOptionMap()
- func InvalidatePricingCache()
- func InvalidateSubscriptionPlanCache(planId int)
- func InvalidateUserCache(userId int) error
- func InvalidateUserTokensCache(userId int) error
- func IsAdmin(userId int) bool
- func IsChannelEnabledForAnyGroupModel(groups []string, modelName string, channelID int) bool
- func IsChannelEnabledForGroupModel(group string, modelName string, channelID int) bool
- func IsDiscordIdAlreadyTaken(discordId string) (bool, error)
- func IsEmailAlreadyTaken(email string) bool
- func IsEmailAvailable(email string, excludeUserID int) (bool, error)
- func IsGitHubIdAlreadyTaken(githubId string) (bool, error)
- func IsLinuxDOIdAlreadyTaken(linuxDOId string) (bool, error)
- func IsModelNameDuplicated(id int, name string) (bool, error)
- func IsOidcIdAlreadyTaken(oidcId string) (bool, error)
- func IsPrefillGroupNameDuplicated(id int, name string) (bool, error)
- func IsProviderUserIdTaken(providerId int, providerUserId string) (bool, error)
- func IsRegisteredOptionKey(key string) bool
- func IsSlugTaken(slug string, excludeId int) bool
- func IsTelegramIdAlreadyTaken(telegramId string) (bool, error)
- func IsTwoFAEnabled(userId int) bool
- func IsVendorNameDuplicated(id int, name string) (bool, error)
- func IsWeChatIdAlreadyTaken(wechatId string) (bool, error)
- func LogQuotaData(params QuotaDataLogParams)
- func ManualCompleteTopUp(tradeNo string, callerIp string) error
- func MarkTaskSubmitAmbiguous(taskID int64, reason string) error
- func MarkTaskSubmitFailed(taskID int64, reason string) error
- func MarkTaskSubmitFailedWithSettlement(taskID int64, reason string, input *BillingSettlementInput) error
- func MarkTaskSubmitNeedsReview(task *Task, reason string) error
- func MaskTokenKey(key string) string
- func MjBulkUpdate(mjIds []string, params map[string]any) error
- func MjBulkUpdateByTaskIds(taskIDs []int, params map[string]any) error
- func NormalizeChannelGroupFilter(group string) string
- func NormalizeEmail(email string) string
- func NormalizeResetPeriod(period string) string
- func OverrideUserQuota(id int, quota int64) error
- func PerfMetricStartTime(hours int) int64
- func PingDB() error
- func PingDBContext(ctx context.Context) error
- func PingDBUncached() error
- func PostConsumeUserSubscriptionDelta(userSubscriptionId int, delta int64) (int64, error)
- func ProcessBillingSettlementEffect(operationKey string) error
- func ProcessPendingBillingSettlementsOnce()
- func PurchaseSubscriptionWithBalance(userId int, planId int) error
- func Recharge(referenceId string, customerId string, callerIp string, ...) (err error)
- func RechargeCreem(referenceId string, customerEmail string, customerName string, callerIp string, ...) (err error)
- func RechargeEpay(tradeNo string, actualPaymentMethod string, callerIp string, ...) (err error)
- func RechargeWaffo(tradeNo string, callerIp string, validations ...PaymentValidation) (err error)
- func RechargeWaffoPancake(tradeNo string, validations ...PaymentValidation) (err error)
- func RecordConsumeLog(c *gin.Context, userId int, params RecordConsumeLogParams)
- func RecordErrorLog(c *gin.Context, userId int, channelId int, modelName string, tokenName string, ...)
- func RecordExist(err error) (bool, error)
- func RecordLog(userId int, logType int, content string)
- func RecordLogWithAdminInfo(userId int, logType int, content string, adminInfo map[string]interface{})
- func RecordLoginLog(userId int, username string, content string, ip string, action string, ...)
- func RecordOperationAuditLog(logUserId int, content string, ip string, action string, ...)
- func RecordTaskBillingLog(params RecordTaskBillingLogParams)
- func RecordTaskBillingLogOnce(operationKey string, params RecordTaskBillingLogParams) error
- func RecordTopupLog(userId int, content string, callerIp string, paymentMethod string, ...)
- func Redeem(key string, userId int) (quota int, err error)
- func RefreshPricing()
- func RefundSubscriptionPreConsume(requestId string) error
- func ResetDueSubscriptions(limit int) (int, error)
- func ResetUserPasswordByEmail(email string, password string) error
- func ResolveBillingPreConsumeSource(requestID string) (string, bool, error)
- func RootUserExists() bool
- func SaveQuotaDataCache(ctx context.Context) error
- func SearchTags(keyword string, group string, model string, idSort bool) ([]*string, error)
- func StartBillingSettlementTaskRunner()
- func StartCacheInvalidationTaskRunner()
- func StopBillingSettlementTaskRunner(ctx context.Context) error
- func StopCacheInvalidationTaskRunner(ctx context.Context) error
- func SumUsedToken(logType int, startTimestamp int64, endTimestamp int64, modelName string, ...) (token int)
- func SyncChannelCache(frequency int)
- func SyncOptions(frequency int)
- func TaskBulkUpdate(taskIds []string, params map[string]any) error
- func TaskBulkUpdateByID(ids []int64, params map[string]any) error
- func TaskCountAllTasks(queryParams SyncTaskQueryParams) int64
- func TaskCountAllUserTask(userId int, queryParams SyncTaskQueryParams) int64
- func UpdateAbilityByTag(tag string, newTag *string, priority *int64, weight *uint) error
- func UpdateAbilityStatus(channelId int, status bool) error
- func UpdateAbilityStatusByTag(tag string, status bool) error
- func UpdateChannelStatus(channelId int, usingKey string, status int, reason string) bool
- func UpdateChannelUsedQuota(id int, quota int)
- func UpdateCustomOAuthProvider(provider *CustomOAuthProvider) error
- func UpdateOption(key string, value string) error
- func UpdateOptionsBulk(values map[string]string) error
- func UpdatePendingTopUpStatus(tradeNo string, expectedPaymentProvider string, targetStatus string) error
- func UpdateProgress(id int, progress string) error
- func UpdateQuotaData()
- func UpdateSystemTaskState(taskID string, lockedBy string, state any, lockUntil int64) error
- func UpdateUserLastLoginAt(id int)
- func UpdateUserOAuthBinding(userId, providerId int, newProviderUserId string) error
- func UpdateUserSetting(userId int, setting dto.UserSetting) error
- func UpdateUserUsedQuotaAndRequestCount(id int, quota int)
- func UpsertPasskeyCredential(credential *PasskeyCredential) error
- func UpsertPerfMetric(metric *PerfMetric) error
- func UpsertSystemInstance(nodeName string, info any, startedAt int64, lastSeenAt int64) error
- func ValidateBackupCode(userId int, code string) (bool, error)
- func WaitPendingLogQuotaData()
- func WithNormalizedEmailWriteTx(email string, fn func(tx *gorm.DB) error) error
- func WithUserOAuthIdentityWriteTx(email string, fn func(tx *gorm.DB) error) error
- type Ability
- type AbilityWithChannel
- type AuthFlow
- type AuthFlowCreate
- type AuthFlowMatch
- type BillingLogReceipt
- type BillingPreConsumeSelection
- type BillingSettlement
- type BillingSettlementEffect
- type BillingSettlementInput
- type BoundChannel
- type CacheInvalidationTask
- type Channel
- func CacheGetChannel(id int) (*Channel, error)
- func GetAllChannels(startIdx int, num int, selectAll bool, idSort bool, ...) ([]*Channel, error)
- func GetChannel(group string, model string, retry int, requestPath string) (*Channel, error)
- func GetChannelById(id int, selectAll bool) (*Channel, error)
- func GetChannelExcluding(group string, model string, retry int, requestPath string, ...) (*Channel, error)
- func GetChannelsByIds(ids []int) ([]*Channel, error)
- func GetChannelsByTag(tag string, idSort bool, selectAll bool, sortOptions ...ChannelSortOptions) ([]*Channel, error)
- func GetChannelsByType(startIdx int, num int, idSort bool, channelType int) ([]*Channel, error)
- func GetRandomSatisfiedChannel(group string, model string, retry int, requestPath string) (*Channel, error)
- func GetRandomSatisfiedChannelExcluding(group string, model string, retry int, requestPath string, ...) (*Channel, error)
- func SearchChannels(keyword string, group string, model string, idSort bool, ...) ([]*Channel, error)
- func (channel *Channel) AddAbilities(tx *gorm.DB) error
- func (channel *Channel) Delete() error
- func (channel *Channel) DeleteAbilities() error
- func (channel *Channel) GetAutoBan() bool
- func (channel *Channel) GetBaseURL() string
- func (channel *Channel) GetGroups() []string
- func (channel *Channel) GetHeaderOverride() map[string]interface{}
- func (channel *Channel) GetKeys() []string
- func (channel *Channel) GetModelMapping() string
- func (channel *Channel) GetModels() []string
- func (channel *Channel) GetNextEnabledKey() (string, int, *types.MaxAPIError)
- func (channel *Channel) GetOtherInfo() map[string]interface{}
- func (channel *Channel) GetOtherSettings() dto.ChannelOtherSettings
- func (channel *Channel) GetParamOverride() map[string]interface{}
- func (channel *Channel) GetPriority() int64
- func (channel *Channel) GetSetting() dto.ChannelSettings
- func (channel *Channel) GetStatusCodeMapping() string
- func (channel *Channel) GetTag() string
- func (channel *Channel) GetWeight() int
- func (channel *Channel) Insert() error
- func (channel *Channel) ParseOtherSettings() (dto.ChannelOtherSettings, error)
- func (channel *Channel) Save() error
- func (channel *Channel) SaveChannelInfo() error
- func (channel *Channel) SaveWithoutKey() error
- func (channel *Channel) SetOtherInfo(otherInfo map[string]interface{})
- func (channel *Channel) SetOtherSettings(setting dto.ChannelOtherSettings)
- func (channel *Channel) SetSetting(setting dto.ChannelSettings)
- func (channel *Channel) SetTag(tag string)
- func (channel *Channel) Update() error
- func (channel *Channel) UpdateAbilities(tx *gorm.DB) error
- func (channel *Channel) UpdateBalance(balance float64)
- func (channel *Channel) UpdateFields(fields ...string) error
- func (channel *Channel) UpdateResponseTime(responseTime int64)
- func (channel *Channel) ValidateSettings() error
- type ChannelInfo
- type ChannelSortOptions
- type Checkin
- type CheckinRecord
- type CustomOAuthProvider
- type JSONValue
- type Log
- func GetAllLogs(params LogQueryParams) (logs []*Log, total int64, err error)
- func GetLogById(id int) (*Log, error)
- func GetLogByTokenId(tokenId int) (logs []*Log, err error)
- func GetUserLogById(userId int, id int) (*Log, error)
- func GetUserLogs(params LogQueryParams) (logs []*Log, total int64, err error)
- type LogQueryParams
- type Midjourney
- func GetAllTasks(startIdx int, num int, queryParams TaskQueryParams) []*Midjourney
- func GetAllUnFinishTasks() []*Midjourney
- func GetAllUserTask(userId int, startIdx int, num int, queryParams TaskQueryParams) []*Midjourney
- func GetByMJIds(userId int, mjIds []string) []*Midjourney
- func GetMjByuId(id int) *Midjourney
- func GetUniqueMidjourneyByMJID(mjID string) (*Midjourney, error)
- func GetUniqueMidjourneyByUserAndMJID(userID int, mjID string) (*Midjourney, error)
- func (midjourney *Midjourney) BeforeSave(*gorm.DB) error
- func (midjourney *Midjourney) Insert() error
- func (midjourney *Midjourney) Update() error
- func (midjourney *Midjourney) UpdateWithBillingTaskAndSettlement(fromStatus string, billingTask *Task, input *BillingSettlementInput) (bool, error)
- func (midjourney *Midjourney) UpdateWithStatus(fromStatus string) (bool, error)
- type MidjourneyBillingClaim
- type Model
- type Option
- type PasskeyCredential
- func (p *PasskeyCredential) ApplyValidatedCredential(credential *webauthn.Credential)
- func (p *PasskeyCredential) SetTransports(list []protocol.AuthenticatorTransport)
- func (p *PasskeyCredential) ToWebAuthnCredential() webauthn.Credential
- func (p *PasskeyCredential) TransportList() []protocol.AuthenticatorTransport
- type PaymentValidation
- type PerfMetric
- type PerfMetricSummary
- type PrefillGroup
- type Pricing
- type PricingVendor
- type Properties
- type QuotaData
- func GetAllQuotaDates(startTime int64, endTime int64, username string) (quotaData []*QuotaData, err error)
- func GetQuotaDataByUserId(userId int, startTime int64, endTime int64) (quotaData []*QuotaData, err error)
- func GetQuotaDataByUsername(username string, startTime int64, endTime int64) (quotaData []*QuotaData, err error)
- func GetQuotaDataGroupByUser(startTime int64, endTime int64) (quotaData []*QuotaData, err error)
- type QuotaDataLogParams
- type QuotaDataSnapshot
- type QuotaDataSnapshotRetry
- type RankingQuotaBucket
- type RankingQuotaTotal
- type RecordConsumeLogParams
- type RecordTaskBillingLogParams
- type Redemption
- type Setup
- type Stat
- type SubscriptionOrder
- type SubscriptionPlan
- type SubscriptionPlanInfo
- type SubscriptionPreConsumeRecord
- type SubscriptionPreConsumeResult
- func PreConsumeTokenAndUserSubscription(requestId string, userId int, tokenId int, tokenKey string, modelName string, ...) (*SubscriptionPreConsumeResult, error)
- func PreConsumeUserSubscription(requestId string, userId int, modelName string, quotaType int, amount int64) (*SubscriptionPreConsumeResult, error)
- type SubscriptionResetResult
- type SubscriptionSummary
- type SyncTaskQueryParams
- type SystemInstance
- type SystemInstanceResponse
- type SystemTask
- func ClaimSystemTask(id int64, taskType string, runnerID string, lockUntil int64) (*SystemTask, bool, error)
- func CreateSystemTask(taskType string, activeKey string, payload any, state any) (*SystemTask, error)
- func FindRunnableSystemTasks(taskType string, now int64, limit int) ([]*SystemTask, error)
- func GetActiveSystemTask(taskType string) (*SystemTask, error)
- func GetSystemTaskByTaskID(taskID string) (*SystemTask, error)
- func ListSystemTasks(limit int) ([]*SystemTask, error)
- type SystemTaskResponse
- type SystemTaskStatus
- type Task
- func GetAllUnFinishSyncTasks(limit int) []*Task
- func GetByOnlyTaskId(taskId string) (*Task, bool, error)
- func GetByTaskId(userId int, taskId string) (*Task, bool, error)
- func GetByTaskIds(userId int, taskIds []any) ([]*Task, error)
- func GetMidjourneyBillingTask(userID, channelID int, mjID string) (*Task, error)
- func GetTimedOutUnfinishedTasks(cutoffUnix int64, limit int) []*Task
- func InitTask(platform constant.TaskPlatform, relayInfo *commonRelay.RelayInfo) *Task
- func TaskGetAllTasks(startIdx int, num int, queryParams SyncTaskQueryParams) []*Task
- func TaskGetAllUserTask(userId int, startIdx int, num int, queryParams SyncTaskQueryParams) []*Task
- func (t *Task) BeforeSave(*gorm.DB) error
- func (t *Task) ClearDataForUpdate()
- func (t *Task) ClearPrivateDataForUpdate()
- func (t *Task) DeltaSettlementDisabledForChannel(channelType int, channelSettings ...dto.ChannelOtherSettings) bool
- func (t *Task) GetData(v any) error
- func (t *Task) GetResultURL() string
- func (t *Task) GetUpstreamTaskID() string
- func (t *Task) IncludePrivateDataInUpdate()
- func (Task *Task) Insert() error
- func (t *Task) SetData(data any)
- func (t *Task) Snapshot() taskSnapshot
- func (t *Task) ToOpenAIVideo() *dto.OpenAIVideo
- func (Task *Task) Update() error
- func (t *Task) UpdateQuota() error
- func (t *Task) UpdateWithSettlementIntent(input *BillingSettlementInput) error
- func (t *Task) UpdateWithStatus(fromStatus TaskStatus) (bool, error)
- func (t *Task) UpdateWithStatusAndSettlement(fromStatus TaskStatus, input BillingSettlementInput) (bool, error)
- type TaskBillingContext
- type TaskPrivateData
- type TaskQueryParams
- type TaskQuotaUsage
- type TaskRateCardPricing
- type TaskRateCardPricingRow
- type TaskStatus
- type Token
- func GetAllUserTokens(userId int, startIdx int, num int) ([]*Token, error)
- func GetTokenById(id int) (*Token, error)
- func GetTokenByIds(id int, userId int) (*Token, error)
- func GetTokenByKey(key string, fromDB bool) (token *Token, err error)
- func GetTokenKeysByIds(ids []int, userId int) ([]Token, error)
- func SearchUserTokens(userId int, keyword string, token string, offset int, limit int) (tokens []*Token, total int64, err error)
- func ValidateUserToken(key string) (token *Token, err error)
- func ValidateUserTokenForReadOnly(key string) (token *Token, err error)
- func (token *Token) Clean()
- func (token *Token) Delete() (err error)
- func (token *Token) GetFullKey() string
- func (token *Token) GetIpLimits() []string
- func (token *Token) GetMaskedKey() string
- func (token *Token) GetModelLimits() []string
- func (token *Token) GetModelLimitsMap() map[string]bool
- func (token *Token) GetStoredRoutingPolicy() (*TokenRoutingPolicy, error)
- func (token *Token) Insert() error
- func (token *Token) IsModelLimitsEnabled() bool
- func (token *Token) SelectUpdate() (err error)
- func (token *Token) SetRoutingPolicy(policy *TokenRoutingPolicy) error
- func (token *Token) Update() (err error)
- type TokenRoutingPolicy
- type TopUp
- func GetAllTopUps(pageInfo *common.PageInfo) (topups []*TopUp, total int64, err error)
- func GetTopUpById(id int) *TopUp
- func GetTopUpByTradeNo(tradeNo string) *TopUp
- func GetTopUpByTradeNoWithError(tradeNo string) (*TopUp, error)
- func GetUserTopUps(userId int, pageInfo *common.PageInfo) (topups []*TopUp, total int64, err error)
- func SearchAllTopUps(keyword string, pageInfo *common.PageInfo) (topups []*TopUp, total int64, err error)
- func SearchUserTopUps(userId int, keyword string, pageInfo *common.PageInfo) (topups []*TopUp, total int64, err error)
- type TwoFA
- func (t *TwoFA) Create() error
- func (t *TwoFA) Delete() error
- func (t *TwoFA) Enable() error
- func (t *TwoFA) IncrementFailedAttempts() error
- func (t *TwoFA) IsLocked() bool
- func (t *TwoFA) ResetFailedAttempts() error
- func (t *TwoFA) Update() error
- func (t *TwoFA) ValidateBackupCodeAndUpdateUsage(code string) (bool, error)
- func (t *TwoFA) ValidateTOTPAndUpdateUsage(code string) (bool, error)
- type TwoFABackupCode
- type User
- func GetAllUsers(pageInfo *common.PageInfo) (users []*User, total int64, err error)
- func GetRootUser() (user *User)
- func GetUniqueUserByEmail(email string) (*User, error)
- func GetUserById(id int, selectAll bool) (*User, error)
- func GetUserByOAuthBinding(providerId int, providerUserId string) (*User, error)
- func SearchUsers(keyword string, group string, role *int, status *int, quotaStatus string, ...) ([]*User, int64, error)
- func ValidateAccessToken(token string) (*User, error)
- func (user *User) BeforeSave(_ *gorm.DB) error
- func (user *User) ClearBinding(bindingType string) error
- func (user *User) Delete() error
- func (user *User) Edit(updatePassword bool) error
- func (user *User) FillUserByDiscordId() error
- func (user *User) FillUserByEmail() error
- func (user *User) FillUserByGitHubId() error
- func (user *User) FillUserById() error
- func (user *User) FillUserByLinuxDOId() error
- func (user *User) FillUserByOidcId() error
- func (user *User) FillUserByTelegramId() error
- func (user *User) FillUserByWeChatId() error
- func (user *User) FinalizeOAuthUserCreation(inviterId int)
- func (user *User) GetAccessToken() string
- func (user *User) GetSetting() dto.UserSetting
- func (user *User) HardDelete() error
- func (user *User) Insert(inviterId int) error
- func (user *User) InsertWithTx(tx *gorm.DB, inviterId int) error
- func (user *User) SetAccessToken(token string)
- func (user *User) SetSetting(setting dto.UserSetting)
- func (user *User) ToBaseUser() *UserBase
- func (user *User) TransferAffQuotaToQuota(quota int64) error
- func (user *User) Update(updatePassword bool) error
- func (user *User) UpdateFields(updatePassword bool, fields ...UserUpdateField) error
- func (user *User) UpdateFieldsWithTx(tx *gorm.DB, updatePassword bool, fields ...UserUpdateField) error
- func (user *User) UpdateGitHubId(newGitHubId string) error
- func (user *User) UpdateWithTx(tx *gorm.DB, updatePassword bool) error
- func (user *User) ValidateAndFill() (err error)
- func (user *User) ValidateOAuthIdentityLengths() error
- type UserBase
- type UserOAuthBinding
- type UserSubscription
- type UserUpdateField
- type Vendor
Constants ¶
const ( AuthFlowPurposeOAuth = "oauth" AuthFlowIntentLogin = "login" AuthFlowIntentBind = "bind" AuthFlowTokenBytes = 32 AuthFlowDefaultCleanupRetention = 24 * time.Hour )
const ( BillingSettlementSourceWallet = "wallet" BillingSettlementSourceSubscription = "subscription" BillingSettlementStatusPending = "pending" BillingSettlementStatusApplied = "applied" BillingSettlementStatusManual = "manual" BillingSettlementEffectPending = "pending" BillingSettlementEffectApplying = "applying" BillingSettlementEffectApplied = "applied" )
const ( LogTypeUnknown = 0 LogTypeTopup = 1 LogTypeConsume = 2 LogTypeManage = 3 LogTypeSystem = 4 LogTypeError = 5 LogTypeRefund = 6 LogTypeLogin = 7 )
don't use iota, avoid change log type value
const ( LogFilterRetry = "retry" LogFilterErrorRetry = "error_retry" LogFilterEmptyRetry = "empty_retry" )
const ( LogQuotaFilterAbnormal = "abnormal" LogQuotaFilterZero = "zero" LogQuotaFilterNegative = "negative" )
const ( NameRuleExact = iota NameRulePrefix NameRuleContains NameRuleSuffix )
const ( SubscriptionDurationYear = "year" SubscriptionDurationMonth = "month" SubscriptionDurationDay = "day" SubscriptionDurationHour = "hour" SubscriptionDurationCustom = "custom" )
Subscription duration units
const ( SubscriptionResetNever = "never" SubscriptionResetDaily = "daily" SubscriptionResetWeekly = "weekly" SubscriptionResetMonthly = "monthly" SubscriptionResetCustom = "custom" )
Subscription quota reset period
const ( SystemInstanceStatusOnline = "online" SystemInstanceStatusStale = "stale" SystemInstanceStaleAfterSeconds int64 = 90 )
const ( SystemTaskStatusPending SystemTaskStatus = "pending" SystemTaskStatusRunning SystemTaskStatus = "running" SystemTaskStatusSucceeded SystemTaskStatus = "succeeded" SystemTaskStatusFailed SystemTaskStatus = "failed" SystemTaskTypeLogCleanup = "log_cleanup" SystemTaskTypeChannelTest = "channel_test" SystemTaskTypeModelUpdate = "model_update" SystemTaskTypeMidjourneyPoll = "midjourney_poll" SystemTaskTypeAsyncTaskPoll = "async_task_poll" )
const ( TaskStatusNotStart TaskStatus = "NOT_START" TaskStatusSubmitted = "SUBMITTED" TaskStatusQueued = "QUEUED" TaskStatusInProgress = "IN_PROGRESS" TaskStatusFailure = "FAILURE" TaskStatusSuccess = "SUCCESS" TaskStatusUnknown = "UNKNOWN" )
const ( TokenRoutingPolicyVersion = 1 TokenRoutingModeSmart = "smart" TokenRoutingModeManual = "manual" )
const ( PaymentMethodStripe = "stripe" PaymentMethodCreem = "creem" PaymentMethodWaffo = "waffo" PaymentMethodWaffoPancake = "waffo_pancake" PaymentMethodBalance = "balance" )
const ( PaymentProviderEpay = "epay" PaymentProviderStripe = "stripe" PaymentProviderCreem = "creem" PaymentProviderWaffo = "waffo" PaymentProviderWaffoPancake = "waffo_pancake" PaymentProviderBalance = "balance" )
const ( UserQuotaStatusNegative = "negative" UserQuotaStatusZero = "zero" UserQuotaStatusPositive = "positive" )
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 )
const (
UserNameMaxLength = 20
)
Variables ¶
var ( ErrAuthFlowInvalid = errors.New("auth flow is invalid") ErrAuthFlowExpired = errors.New("auth flow has expired") ErrAuthFlowConsumed = errors.New("auth flow has already been consumed") )
var ( ErrBillingSettlementManualReview = errors.New("billing settlement requires manual review") ErrBillingSettlementTaskConflict = errors.New("billing settlement task quota conflict") ErrBillingSettlementOperationConflict = errors.New("billing settlement operation conflict") ErrSubscriptionSettlementUnbound = errors.New("subscription settlement is not bound to its pre-consume request") ErrSubscriptionSettlementPeriodChanged = errors.New("subscription settlement crossed a quota reset period") )
var ( ErrDatabase = errors.New("database error") ErrUserNotFound = errors.New("user not found") ErrUserDeleted = errors.New("user deleted") ErrTokenNotFound = errors.New("token not found") ErrUserQuotaInsufficient = errors.New("user quota is not enough") ErrTokenQuotaInsufficient = errors.New("token quota is not enough") )
Common errors
var ( ErrInvalidCredentials = errors.New("invalid credentials") ErrUserEmptyCredentials = errors.New("empty credentials") ErrEmailAlreadyTaken = errors.New("email already taken") ErrEmailNotFound = errors.New("email not found") ErrEmailAmbiguous = errors.New("email matches multiple users") )
User auth errors
var ( ErrTokenNotProvided = errors.New("token not provided") ErrTokenInvalid = errors.New("token invalid") )
Token auth errors
var ( ErrPasskeyNotFound = errors.New("passkey credential not found") ErrFriendlyPasskeyNotFound = errors.New("Passkey 验证失败,请重试或联系管理员") )
var ( ErrPaymentAmountMismatch = errors.New("payment amount mismatch") ErrPaymentCurrencyMismatch = errors.New("payment currency mismatch") )
var ( ErrSubscriptionOrderNotFound = errors.New("subscription order not found") ErrSubscriptionOrderStatusInvalid = errors.New("subscription order status invalid") ErrSubscriptionQuotaInsufficient = errors.New("subscription quota insufficient") )
var ( ErrSystemInstanceNotFound = errors.New("System instance not found.") ErrSystemInstanceOnline = errors.New("Instance is still online and cannot be deleted.") )
var ( ErrPaymentMethodMismatch = errors.New("payment method mismatch") ErrTopUpNotFound = errors.New("topup not found") ErrTopUpStatusInvalid = errors.New("topup status invalid") )
var CacheQuotaData = make(map[string]*QuotaData)
var CacheQuotaDataLock = sync.Mutex{}
var DB *gorm.DB
var ErrLogRetryMarkerBackfillIncomplete = errors.New("log retry marker backfill is not completed")
var ErrMidjourneyTaskAmbiguous = errors.New("midjourney task identity is ambiguous across channels")
var ErrRedeemFailed = errors.New("redeem.failed")
Redemption errors
var ErrSystemTaskLockLost = errors.New("system task lock lost")
var ErrTwoFANotEnabled = errors.New("2fa not enabled")
2FA errors
var ErrVendorHasModels = errors.New("vendor is still referenced by models")
var LOG_DB *gorm.DB
Functions ¶
func AdminBindSubscription ¶
Admin bind (no payment). Creates a UserSubscription from a plan.
func AdminDeleteUserSubscription ¶
AdminDeleteUserSubscription hard-deletes a user subscription.
func AdminInvalidateUserSubscription ¶
AdminInvalidateUserSubscription marks a user subscription as cancelled and ends it immediately.
func ApplyBillingSettlementOnce ¶
func ApplyBillingSettlementOnce(input BillingSettlementInput) (appliedFundingDelta int64, alreadyApplied bool, err error)
func BatchDeleteChannels ¶
func BatchDeleteTokens ¶
BatchDeleteTokens 删除指定用户的一组令牌,返回成功删除数量
func BatchInsertChannels ¶
func BatchSetChannelTag ¶
func BindEmailToUser ¶ added in v1.0.4
BindEmailToUser atomically checks email availability and assigns it to the user, preventing concurrent binds from sharing the same normalized address.
func CacheUpdateChannel ¶
func CacheUpdateChannel(channel *Channel)
func CheckSetup ¶
func CheckSetup()
func CheckUserExistOrDeleted ¶
CheckUserExistOrDeleted check if user exist or deleted, if not exist, return false, nil, if deleted or exist, return true, nil
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 CleanupSubscriptionPreConsumeRecords ¶
CleanupSubscriptionPreConsumeRecords removes only old replay tombstones whose linked billing settlements have reached terminal applied/manual states. olderThanSeconds is retained for the scheduled cleanup API; non-positive values disable deletion, and pending settlement rows are always preserved.
func CompleteSubscriptionOrder ¶
func CompleteSubscriptionOrder(tradeNo string, providerPayload string, expectedPaymentProvider string, actualPaymentMethod string, validations ...PaymentValidation) error
Complete a subscription order (idempotent). Creates a UserSubscription snapshot from the plan. expectedPaymentProvider guards against cross-gateway callback attacks (empty skips the check). actualPaymentMethod updates the order's PaymentMethod to reflect the real payment type used (empty skips update).
func CountAllChannels ¶
CountAllChannels returns total channels in DB
func CountAllTags ¶
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 CountChannelsByType ¶
Count channels of specific type
func CountChannelsGroupByType ¶
Return map[type]count for all channels
func CountOldLog ¶ added in v1.0.3
func CountUserTokens ¶
CountUserTokens returns total number of tokens for the given user, used for pagination
func CountUsersByEmail ¶ added in v1.0.4
func CreateBackupCodes ¶
CreateBackupCodes 创建备用码
func CreateCustomOAuthProvider ¶
func CreateCustomOAuthProvider(provider *CustomOAuthProvider) error
CreateCustomOAuthProvider creates a new custom OAuth provider
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 DecreaseUserQuota ¶
See IncreaseUserQuota for why the compatibility flag is ignored.
func DeleteChannelByStatus ¶
func DeleteCustomOAuthProvider ¶
DeleteCustomOAuthProvider deletes a custom OAuth provider by ID
func DeleteDisabledChannel ¶
func DeleteExpiredAuthFlows ¶
func DeleteOldLog ¶
func DeleteOldLogBatch ¶ added in v1.0.3
func DeletePasskeyByUserID ¶
func DeletePerfMetricsBefore ¶
func DeleteRedemptionById ¶
func DeleteStaleSystemInstance ¶ added in v1.0.3
func DeleteTokenById ¶
func DeleteUserById ¶
func DeleteUserOAuthBinding ¶
DeleteUserOAuthBinding deletes an OAuth binding
func DeleteUserOAuthBindingsByUserId ¶
DeleteUserOAuthBindingsByUserId deletes all OAuth bindings for a user
func DeltaUpdateUserQuota ¶
func DisableChannelByTag ¶
func DisableModelLimits ¶
func EditChannelByTag ¶
func EnableChannelByTag ¶
func EnsureEmailAvailable ¶ added in v1.0.4
func ExpireDueSubscriptions ¶
ExpireDueSubscriptions marks expired subscriptions and handles group downgrade.
func ExpireSubscriptionOrder ¶
func FinalizeMidjourneySubmission ¶
func FinalizeMidjourneySubmission(midjourney *Midjourney, billingTask *Task, settlementInput, duplicateRefundInput *BillingSettlementInput) (created bool, refundDuplicate bool, err error)
FinalizeMidjourneySubmission atomically claims the provider task ID, writes the legacy Midjourney row, advances the durable billing Task, and stages the matching settlement intent. It returns false when another local request (or a historical row) already owns the provider task; in that case the supplied duplicate refund intent is staged with the losing Task transition.
func FinishSystemTask ¶ added in v1.0.3
func FixAbility ¶
func GenerateSystemTaskID ¶ added in v1.0.3
func GetBindingCountByProviderId ¶
GetBindingCountByProviderId returns the number of bindings for a provider
func GetBoundChannelsByModelsMap ¶
func GetBoundChannelsByModelsMap(modelNames []string) (map[string][]BoundChannel, error)
func GetChannelPollingLock ¶
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 GetEnabledModels ¶
func GetEnabledModels() []string
func GetGroupEnabledModels ¶
func GetMaxUserId ¶
func GetMaxUserId() int
func GetMissingModels ¶
GetMissingModels returns model names that are referenced in the system
func GetModelEnableGroups ¶
func GetModelQuotaTypes ¶
GetModelQuotaTypes 返回指定模型的计费类型集合(来自缓存)
func GetModelSupportEndpointTypes ¶
func GetModelSupportEndpointTypes(model string) []constant.EndpointType
func GetPaginatedChannelTags ¶
func GetSupportedEndpointMap ¶
func GetSupportedEndpointMap() map[string]common.EndpointInfo
GetSupportedEndpointMap 返回全局端点到路径的映射
func GetTwoFAStats ¶
GetTwoFAStats 获取2FA统计信息(管理员使用)
func GetUnusedBackupCodeCount ¶
GetUnusedBackupCodeCount 获取未使用的备用码数量
func GetUserCheckinStats ¶
GetUserCheckinStats 获取用户签到统计信息
func GetUserEmail ¶
func GetUserGroup ¶
GetUserGroup gets group from Redis first, falls back to DB if needed
func GetUserIdByAffCode ¶
func GetUserLanguage ¶
GetUserLanguage returns the user's language preference from cache Uses the existing GetUserCache mechanism for efficiency
func GetUserQuota ¶
GetUserQuota gets quota from Redis first, falls back to DB if needed
func GetUserSetting ¶
func GetUserSetting(id int, fromDB bool) (settingMap dto.UserSetting, err error)
GetUserSetting gets setting from Redis first, falls back to DB if needed
func GetUserUsedQuota ¶
func GetUsernameById ¶
GetUsernameById gets username from Redis first, falls back to DB if needed
func GetVendorModelCounts ¶
func HardDeleteUserById ¶
func HasActiveUserSubscription ¶
HasActiveUserSubscription returns whether the user has any active subscription. This is a lightweight existence check to avoid heavy pre-consume transactions.
func HasCheckedInToday ¶
HasCheckedInToday 检查用户今天是否已签到
func IncreaseUserQuota ¶
The final boolean is retained for caller compatibility. Accounting mutations always write the database directly so conditional deductions remain atomic.
func InitBatchUpdater ¶
func InitBatchUpdater()
func InitChannelCache ¶
func InitChannelCache()
func InitOptionMap ¶
func InitOptionMap()
func InvalidatePricingCache ¶
func InvalidatePricingCache()
func InvalidateSubscriptionPlanCache ¶
func InvalidateSubscriptionPlanCache(planId int)
func InvalidateUserCache ¶
InvalidateUserCache is the exported version of invalidateUserCache. 供 controller 等上层包在用户状态变更(如禁用、删除、角色变更)后主动清理缓存。
func InvalidateUserTokensCache ¶
InvalidateUserTokensCache 清理指定用户所有令牌在 Redis 中的缓存, 配合 InvalidateUserCache 使用,可在用户被禁用/删除时立即阻断其令牌的请求。 下一次请求将从数据库重新加载令牌及用户状态,从而立即识别出被禁用的用户。
func IsDiscordIdAlreadyTaken ¶
func IsEmailAlreadyTaken ¶
func IsEmailAvailable ¶ added in v1.0.4
func IsGitHubIdAlreadyTaken ¶
func IsLinuxDOIdAlreadyTaken ¶
func IsOidcIdAlreadyTaken ¶
func IsPrefillGroupNameDuplicated ¶
IsPrefillGroupNameDuplicated 检查组名称是否重复(排除自身 ID)
func IsProviderUserIdTaken ¶
IsProviderUserIdTaken checks if a provider user ID is already bound to any user
func IsRegisteredOptionKey ¶
IsRegisteredOptionKey reports whether a key is part of the initialized system/configuration option registry. It intentionally excludes arbitrary rows that may exist in the options table from older deployments.
func IsSlugTaken ¶
IsSlugTaken checks if a slug is already taken by another provider Returns true on DB errors (fail-closed) to prevent slug conflicts
func IsVendorNameDuplicated ¶
IsVendorNameDuplicated 检查供应商名称是否重复(排除自身 ID)
func IsWeChatIdAlreadyTaken ¶
func LogQuotaData ¶
func LogQuotaData(params QuotaDataLogParams)
func ManualCompleteTopUp ¶
ManualCompleteTopUp 管理员手动完成订单并给用户充值
func MarkTaskSubmitAmbiguous ¶
func MarkTaskSubmitFailed ¶
func MarkTaskSubmitFailedWithSettlement ¶
func MarkTaskSubmitFailedWithSettlement(taskID int64, reason string, input *BillingSettlementInput) error
MarkTaskSubmitFailedWithSettlement commits a definite submit rejection and its durable pre-consume refund intent atomically. The task is terminal with a zero displayed quota while the settlement runner applies or retries the already-recorded balance mutation.
func MarkTaskSubmitNeedsReview ¶
MarkTaskSubmitNeedsReview preserves the pre-consumed quota and any upstream identity after the provider accepted a task but local durable finalization failed. Refunding this state would create an unbilled upstream task.
func MaskTokenKey ¶
func NormalizeEmail ¶ added in v1.0.4
func NormalizeResetPeriod ¶
func OverrideUserQuota ¶
func PerfMetricStartTime ¶
func PingDBContext ¶
func PingDBUncached ¶
func PingDBUncached() error
func PostConsumeUserSubscriptionDelta ¶
Update subscription used amount by delta (positive consume more, negative refund). It returns the actual applied delta because negative deltas are floored at zero.
func ProcessPendingBillingSettlementsOnce ¶
func ProcessPendingBillingSettlementsOnce()
func PurchaseSubscriptionWithBalance ¶
PurchaseSubscriptionWithBalance creates a subscription by deducting the user's wallet quota.
func Recharge ¶
func Recharge(referenceId string, customerId string, callerIp string, validations ...PaymentValidation) (err error)
func RechargeCreem ¶
func RechargeEpay ¶
func RechargeEpay(tradeNo string, actualPaymentMethod string, callerIp string, validations ...PaymentValidation) (err error)
func RechargeWaffo ¶
func RechargeWaffo(tradeNo string, callerIp string, validations ...PaymentValidation) (err error)
func RechargeWaffoPancake ¶
func RechargeWaffoPancake(tradeNo string, validations ...PaymentValidation) (err error)
func RecordConsumeLog ¶
func RecordConsumeLog(c *gin.Context, userId int, params RecordConsumeLogParams)
func RecordErrorLog ¶
func RecordExist ¶
func RecordLogWithAdminInfo ¶
func RecordLogWithAdminInfo(userId int, logType int, content string, adminInfo map[string]interface{})
RecordLogWithAdminInfo 记录操作日志,并将管理员相关信息存入 Other.admin_info,
func RecordLoginLog ¶ added in v1.0.3
func RecordOperationAuditLog ¶ added in v1.0.3
func RecordTaskBillingLog ¶
func RecordTaskBillingLog(params RecordTaskBillingLogParams)
func RecordTaskBillingLogOnce ¶
func RecordTaskBillingLogOnce(operationKey string, params RecordTaskBillingLogParams) error
func RecordTopupLog ¶
func RefreshPricing ¶
func RefreshPricing()
RefreshPricing 强制立即重新计算与定价相关的缓存。 该方法用于需要最新数据的内部管理 API, 因此会绕过默认的 1 分钟延迟刷新。
func RefundSubscriptionPreConsume ¶
RefundSubscriptionPreConsume is idempotent and refunds pre-consumed subscription quota by requestId.
func ResetDueSubscriptions ¶
ResetDueSubscriptions resets subscriptions whose next_reset_time has passed.
func ResolveBillingPreConsumeSource ¶
ResolveBillingPreConsumeSource returns the funding source already selected by a request's durable pre-consume record. A request must never move between a wallet settlement and a subscription pre-consume on replay.
func RootUserExists ¶
func RootUserExists() bool
func SaveQuotaDataCache ¶
func SearchTags ¶
func StartBillingSettlementTaskRunner ¶
func StartBillingSettlementTaskRunner()
StartBillingSettlementTaskRunner retries durable settlement intents after a process restart or a transient database failure. All balance mutations are still protected by ApplyBillingSettlementOnce's operation key.
func StartCacheInvalidationTaskRunner ¶
func StartCacheInvalidationTaskRunner()
func SumUsedToken ¶
func SyncChannelCache ¶
func SyncChannelCache(frequency int)
func SyncOptions ¶
func SyncOptions(frequency int)
func TaskBulkUpdate ¶
TaskBulkUpdate performs an unconditional bulk UPDATE by upstream task_id strings. Same caveats as TaskBulkUpdateByID — no CAS guard.
func TaskBulkUpdateByID ¶
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 UpdateAbilityByTag ¶
func UpdateAbilityStatus ¶
func UpdateChannelStatus ¶
func UpdateChannelUsedQuota ¶
func UpdateCustomOAuthProvider ¶
func UpdateCustomOAuthProvider(provider *CustomOAuthProvider) error
UpdateCustomOAuthProvider updates an existing custom OAuth provider
func UpdateOption ¶
func UpdateOptionsBulk ¶
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 UpdateProgress ¶
func UpdateQuotaData ¶
func UpdateQuotaData()
func UpdateSystemTaskState ¶ added in v1.0.3
func UpdateUserLastLoginAt ¶
func UpdateUserLastLoginAt(id int)
func UpdateUserOAuthBinding ¶
UpdateUserOAuthBinding updates an existing OAuth binding (e.g., rebind to different OAuth account)
func UpdateUserSetting ¶ added in v1.0.4
func UpdateUserSetting(userId int, setting dto.UserSetting) error
func UpsertPasskeyCredential ¶
func UpsertPasskeyCredential(credential *PasskeyCredential) error
func UpsertPerfMetric ¶
func UpsertPerfMetric(metric *PerfMetric) error
func UpsertSystemInstance ¶ added in v1.0.3
func ValidateBackupCode ¶
ValidateBackupCode 验证并使用备用码
func WaitPendingLogQuotaData ¶ added in v1.0.4
func WaitPendingLogQuotaData()
func WithNormalizedEmailWriteTx ¶ added in v1.0.4
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 ¶
func GetAllEnableAbilityWithChannels ¶
func GetAllEnableAbilityWithChannels() ([]AbilityWithChannel, error)
type AuthFlow ¶
type AuthFlow struct {
Id int64 `json:"id" gorm:"primaryKey"`
TokenHash string `json:"-" gorm:"type:char(64);not null;uniqueIndex"`
Purpose string `json:"purpose" gorm:"type:varchar(32);not null;index:idx_auth_flow_purpose_expiry"`
Provider string `json:"provider,omitempty" gorm:"type:varchar(64)"`
Intent string `json:"intent,omitempty" gorm:"type:varchar(16)"`
UserId int `json:"user_id,omitempty" gorm:"index"`
Payload string `json:"-" gorm:"type:text"`
CreatedAt time.Time `json:"created_at"`
ExpiresAt time.Time `json:"expires_at" gorm:"not null;index:idx_auth_flow_purpose_expiry"`
ConsumedAt *time.Time `json:"consumed_at,omitempty" gorm:"index"`
}
AuthFlow stores one-time authentication state. The opaque token is never persisted.
func ConsumeAuthFlow ¶
func ConsumeAuthFlow(token string, match AuthFlowMatch) (*AuthFlow, error)
func CreateAuthFlow ¶
func CreateAuthFlow(input AuthFlowCreate) (string, *AuthFlow, error)
func GetAuthFlow ¶
func GetAuthFlow(token string, match AuthFlowMatch) (*AuthFlow, error)
type AuthFlowCreate ¶
type AuthFlowMatch ¶
type BillingLogReceipt ¶
type BillingLogReceipt struct {
ID int64 `gorm:"primaryKey"`
OperationKey string `gorm:"type:varchar(191);uniqueIndex;not null"`
ClaimToken string `gorm:"type:varchar(36);not null;default:''"`
CreatedAt int64 `gorm:"not null"`
}
BillingLogReceipt keeps task-billing log idempotency off the high-volume logs table. The receipt and its log row are committed in one LOG_DB transaction.
type BillingPreConsumeSelection ¶
type BillingPreConsumeSelection struct {
ID int64 `gorm:"primaryKey"`
RequestID string `gorm:"type:varchar(64);uniqueIndex;not null"`
Source string `gorm:"type:varchar(32);not null"`
UserID int `gorm:"not null"`
TokenID int `gorm:"not null;default:0"`
ModelName string `gorm:"type:varchar(191);not null;default:''"`
RequestedQuota int64 `gorm:"not null;default:0"`
EffectiveQuota int64 `gorm:"not null;default:0"`
CreatedAt int64 `gorm:"not null"`
}
BillingPreConsumeSelection is the immutable funding-source decision for one request. Wallet and subscription mutations claim it inside their own balance transaction so concurrent attempts cannot commit against different sources.
type BillingSettlement ¶
type BillingSettlement struct {
ID int64 `gorm:"primaryKey"`
OperationKey string `gorm:"type:varchar(191);uniqueIndex;not null"`
Source string `gorm:"type:varchar(32);not null"`
UserID int `gorm:"not null;default:0"`
SubscriptionID int `gorm:"not null;default:0"`
TokenID int `gorm:"not null;default:0"`
FundingDelta int64 `gorm:"not null;default:0"`
AppliedFundingDelta int64 `gorm:"not null;default:0"`
TokenDelta int64 `gorm:"not null;default:0"`
AppliedTokenDelta int64 `gorm:"not null;default:0"`
TaskID int64 `gorm:"not null;default:0"`
TaskQuota int64 `gorm:"not null;default:0"`
TaskQuotaTarget int64 `gorm:"not null;default:0"`
Status string `gorm:"type:varchar(16);index;not null;default:'applied'"`
Attempts int `gorm:"not null;default:0"`
LastError string `gorm:"type:text"`
NextAttempt int64 `gorm:"index;not null;default:0"`
Revision int64 `gorm:"not null;default:1"`
SubscriptionPreConsumeRequestID string `gorm:"type:varchar(64);index"`
FinalizeSubscriptionPreConsume bool `gorm:"not null;default:false"`
AllowMissingToken bool `gorm:"not null;default:false"`
ManualOnFailure bool `gorm:"not null;default:false"`
PreConsumeRequestID string `gorm:"type:varchar(64);index"`
PreConsumeModelName string `gorm:"type:varchar(191);not null;default:''"`
PreConsumeRequestedQuota int64 `gorm:"not null;default:0"`
PreConsumeEffectiveQuota int64 `gorm:"not null;default:0"`
EffectPayload string `gorm:"type:text"`
EffectStatus string `gorm:"type:varchar(16);index"`
CreatedAt int64 `gorm:"not null"`
UpdatedAt int64 `gorm:"index;not null"`
}
BillingSettlement is the durable idempotency record for a balance mutation. The record and every related DB mutation are committed in one transaction.
type BillingSettlementEffect ¶
type BillingSettlementEffect struct {
LogType int `json:"log_type"`
Content string `json:"content"`
ChannelID int `json:"channel_id"`
ModelName string `json:"model_name"`
TokenID int `json:"token_id"`
Group string `json:"group"`
Other map[string]interface{} `json:"other"`
NodeName string `json:"node_name"`
UpdateUsage bool `json:"update_usage"`
Quota int64 `json:"quota,omitempty"`
}
type BillingSettlementInput ¶
type BillingSettlementInput struct {
OperationKey string
Source string
UserID int
SubscriptionID int
TokenID int
TokenKey string
FundingDelta int64
TokenDelta int64
TaskID int64
TaskQuota int64
TaskQuotaTarget int64
SubscriptionPreConsumeRequestID string
FinalizeSubscriptionPreConsume bool
// AllowMissingToken is only for terminal task refunds. A token may be
// deleted while its asynchronous task is still pending; that must not
// prevent the user funding balance from being refunded.
AllowMissingToken bool
ManualOnFailure bool
Effect *BillingSettlementEffect
PreConsumeRequestID string
PreConsumeModelName string
PreConsumeRequestedQuota int64
PreConsumeEffectiveQuota int64
}
type BoundChannel ¶
type CacheInvalidationTask ¶
type CacheInvalidationTask struct {
ID int64 `gorm:"primaryKey"`
Kind string `gorm:"type:varchar(16);uniqueIndex:idx_cache_invalidation_target,priority:1;not null"`
EntityKey string `gorm:"type:varchar(96);uniqueIndex:idx_cache_invalidation_target,priority:2;not null"`
VersionKey string `gorm:"type:varchar(96);not null"`
DeleteEntry bool `gorm:"uniqueIndex:idx_cache_invalidation_target,priority:3;not null;default:false"`
Attempts int `gorm:"not null;default:0"`
LastError string `gorm:"type:text"`
NextAttempt int64 `gorm:"index;not null;default:0"`
CreatedAt int64 `gorm:"not null"`
UpdatedAt int64 `gorm:"not null"`
Revision int64 `gorm:"not null;default:1"`
}
CacheInvalidationTask persists Redis invalidations so process restarts do not lose work queued after a committed database mutation.
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
// cache info
Keys []string `json:"-" gorm:"-"`
}
func CacheGetChannel ¶
func GetAllChannels ¶
func GetChannel ¶
func GetChannelExcluding ¶
func GetChannelExcluding(group string, model string, retry int, requestPath string, excludedChannelIDs map[int]struct{}) (*Channel, error)
GetChannelExcluding selects a channel while excluding channels already tried during the current request's retry sequence.
func GetChannelsByIds ¶
func GetChannelsByTag ¶
func GetChannelsByType ¶
Get channels of specified type with pagination
func GetRandomSatisfiedChannelExcluding ¶
func GetRandomSatisfiedChannelExcluding(group string, model string, retry int, requestPath string, excludedChannelIDs map[int]struct{}) (*Channel, error)
GetRandomSatisfiedChannelExcluding selects from the cache while excluding channels already attempted by the current relay request.
func SearchChannels ¶
func (*Channel) DeleteAbilities ¶
func (*Channel) GetAutoBan ¶
func (*Channel) GetBaseURL ¶
func (*Channel) GetHeaderOverride ¶
func (*Channel) GetModelMapping ¶
func (*Channel) GetNextEnabledKey ¶
func (channel *Channel) GetNextEnabledKey() (string, int, *types.MaxAPIError)
func (*Channel) GetOtherInfo ¶
func (*Channel) GetOtherSettings ¶
func (channel *Channel) GetOtherSettings() dto.ChannelOtherSettings
func (*Channel) GetParamOverride ¶
func (*Channel) GetPriority ¶
func (*Channel) GetSetting ¶
func (channel *Channel) GetSetting() dto.ChannelSettings
func (*Channel) GetStatusCodeMapping ¶
func (*Channel) ParseOtherSettings ¶
func (channel *Channel) ParseOtherSettings() (dto.ChannelOtherSettings, error)
func (*Channel) SaveChannelInfo ¶
func (*Channel) SaveWithoutKey ¶
func (*Channel) SetOtherInfo ¶
func (*Channel) SetOtherSettings ¶
func (channel *Channel) SetOtherSettings(setting dto.ChannelOtherSettings)
func (*Channel) SetSetting ¶
func (channel *Channel) SetSetting(setting dto.ChannelSettings)
func (*Channel) UpdateAbilities ¶
UpdateAbilities updates abilities of this channel. Make sure the channel is completed before calling this function.
func (*Channel) UpdateBalance ¶
func (*Channel) UpdateFields ¶
func (*Channel) UpdateResponseTime ¶
func (*Channel) ValidateSettings ¶
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
type ChannelSortOptions ¶
func NewChannelSortOptions ¶
func NewChannelSortOptions(sortBy string, sortOrder string, idSort bool) ChannelSortOptions
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 ¶
GetUserCheckinRecords 获取用户在指定日期范围内的签到记录
func UserCheckin ¶
UserCheckin 执行用户签到 MySQL 和 PostgreSQL 使用事务保证原子性 SQLite 不支持嵌套事务,使用顺序操作 + 手动回滚
type CheckinRecord ¶
type CheckinRecord struct {
CheckinDate string `json:"checkin_date"`
QuotaAwarded int `json:"quota_awarded"`
}
CheckinRecord 用于API返回的签到记录(不包含敏感字段)
type CustomOAuthProvider ¶
type CustomOAuthProvider struct {
Id int `json:"id" gorm:"primaryKey"`
Name string `json:"name" gorm:"type:varchar(64);not null"` // Display name, e.g., "GitHub Enterprise"
Slug string `json:"slug" gorm:"type:varchar(64);uniqueIndex;not null"` // URL identifier, e.g., "github-enterprise"
Icon string `json:"icon" gorm:"type:varchar(128);default:''"` // Icon name from @lobehub/icons
Enabled bool `json:"enabled" gorm:"default:false"` // Whether this provider is enabled
ClientId string `json:"client_id" gorm:"type:varchar(256)"` // OAuth client ID
ClientSecret string `json:"-" gorm:"type:varchar(512)"` // OAuth client secret (not returned to frontend)
AuthorizationEndpoint string `json:"authorization_endpoint" gorm:"type:varchar(512)"` // Authorization URL
TokenEndpoint string `json:"token_endpoint" gorm:"type:varchar(512)"` // Token exchange URL
UserInfoEndpoint string `json:"user_info_endpoint" gorm:"type:varchar(512)"` // User info URL
Scopes string `json:"scopes" gorm:"type:varchar(256);default:'openid profile email'"` // OAuth scopes
// Field mapping configuration (supports JSONPath via gjson)
UserIdField string `json:"user_id_field" gorm:"type:varchar(128);default:'sub'"` // User ID field path, e.g., "sub", "id", "data.user.id"
UsernameField string `json:"username_field" gorm:"type:varchar(128);default:'preferred_username'"` // Username field path
DisplayNameField string `json:"display_name_field" gorm:"type:varchar(128);default:'name'"` // Display name field path
EmailField string `json:"email_field" gorm:"type:varchar(128);default:'email'"` // Email field path
// Advanced options
WellKnown string `json:"well_known" gorm:"type:varchar(512)"` // OIDC discovery endpoint (optional)
AuthStyle int `json:"auth_style" gorm:"default:0"` // 0=auto, 1=params, 2=header (Basic Auth)
AccessPolicy string `json:"access_policy" gorm:"type:text"` // JSON policy for access control based on user info
AccessDeniedMessage string `json:"access_denied_message" gorm:"type:varchar(512)"` // Custom error message template when access is denied
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
CustomOAuthProvider stores configuration for custom OAuth providers
func GetAllCustomOAuthProviders ¶
func GetAllCustomOAuthProviders() ([]*CustomOAuthProvider, error)
GetAllCustomOAuthProviders returns all custom OAuth providers
func GetCustomOAuthProviderById ¶
func GetCustomOAuthProviderById(id int) (*CustomOAuthProvider, error)
GetCustomOAuthProviderById returns a custom OAuth provider by ID
func GetCustomOAuthProviderBySlug ¶
func GetCustomOAuthProviderBySlug(slug string) (*CustomOAuthProvider, error)
GetCustomOAuthProviderBySlug returns a custom OAuth provider by slug
func GetEnabledCustomOAuthProviders ¶
func GetEnabledCustomOAuthProviders() ([]*CustomOAuthProvider, error)
GetEnabledCustomOAuthProviders returns all enabled custom OAuth providers
func (CustomOAuthProvider) TableName ¶
func (CustomOAuthProvider) TableName() string
type JSONValue ¶
type JSONValue json.RawMessage
JSONValue 基于 json.RawMessage 实现,支持从数据库的 []byte 和 string 两种类型读取
func (JSONValue) MarshalJSON ¶
MarshalJSON 确保在对外编码时与 json.RawMessage 行为一致
func (*JSONValue) UnmarshalJSON ¶
UnmarshalJSON 确保在对外解码时与 json.RawMessage 行为一致
type Log ¶
type Log struct {
Id int `json:"id" gorm:"index:idx_created_at_id,priority:2;index:idx_user_id_id,priority:2"`
UserId int `json:"user_id" gorm:"index;index:idx_user_id_id,priority:1"`
CreatedAt int64 `` /* 140-byte string literal not displayed */
Type int `json:"type" gorm:"index:idx_created_at_type;index:idx_logs_type_quota_created_at,priority:1"`
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;index:idx_logs_quota;index:idx_logs_type_quota_created_at,priority:2"`
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"`
IsRetry bool `json:"is_retry" gorm:"default:false;index"`
IsErrorRetry bool `json:"is_error_retry" gorm:"default:false;index"`
IsEmptyRetry bool `json:"is_empty_retry" gorm:"default:false;index"`
LogId int `json:"log_id,omitempty" gorm:"-"`
}
func GetAllLogs ¶
func GetAllLogs(params LogQueryParams) (logs []*Log, total int64, err error)
func GetLogById ¶ added in v1.0.3
func GetLogByTokenId ¶
func GetUserLogs ¶
func GetUserLogs(params LogQueryParams) (logs []*Log, total int64, err error)
type LogQueryParams ¶ added in v1.0.4
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"`
}
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 GetByMJIds ¶
func GetByMJIds(userId int, mjIds []string) []*Midjourney
func GetMjByuId ¶
func GetMjByuId(id int) *Midjourney
func GetUniqueMidjourneyByMJID ¶
func GetUniqueMidjourneyByMJID(mjID string) (*Midjourney, error)
func GetUniqueMidjourneyByUserAndMJID ¶
func GetUniqueMidjourneyByUserAndMJID(userID int, mjID string) (*Midjourney, error)
func (*Midjourney) BeforeSave ¶
func (midjourney *Midjourney) BeforeSave(*gorm.DB) error
func (*Midjourney) Insert ¶
func (midjourney *Midjourney) Insert() error
func (*Midjourney) Update ¶
func (midjourney *Midjourney) Update() error
func (*Midjourney) UpdateWithBillingTaskAndSettlement ¶
func (midjourney *Midjourney) UpdateWithBillingTaskAndSettlement(fromStatus string, billingTask *Task, input *BillingSettlementInput) (bool, error)
UpdateWithBillingTaskAndSettlement commits a Midjourney state transition, its shadow Task transition, and an optional terminal settlement intent in one transaction. Balance application happens after commit or through the durable settlement runner.
func (*Midjourney) UpdateWithStatus ¶
func (midjourney *Midjourney) UpdateWithStatus(fromStatus string) (bool, error)
UpdateWithStatus performs a conditional UPDATE guarded by fromStatus (CAS). It delegates to UpdateWithBillingTaskAndSettlement, which uses an explicit update map to avoid GORM Save()'s INSERT fallback and zero-value skipping.
type MidjourneyBillingClaim ¶
type MidjourneyBillingClaim struct {
ID int64 `gorm:"primaryKey"`
ChannelID int `gorm:"uniqueIndex:idx_midjourney_billing_claim,priority:1;not null"`
MjID string `gorm:"type:varchar(180);uniqueIndex:idx_midjourney_billing_claim,priority:2;not null"`
UserID int `gorm:"index;not null"`
BillingTaskID int64 `gorm:"index;not null;default:0"`
BillingRequestID string `gorm:"type:varchar(64);index;not null;default:''"`
CreatedAt int64 `gorm:"not null"`
}
MidjourneyBillingClaim binds one provider task identity to the single local task that owns its pre-consumed quota. Historical Midjourney rows use a zero BillingTaskID tombstone so later duplicate submissions cannot be charged.
type Model ¶
type Model struct {
Id int `json:"id"`
ModelName string `json:"model_name" gorm:"size:128;not null"`
NameKey string `json:"-" gorm:"size:191;not null;default:''"`
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"`
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 SearchModels ¶
type PasskeyCredential ¶
type PasskeyCredential struct {
ID int `json:"id" gorm:"primaryKey"`
UserID int `json:"user_id" gorm:"uniqueIndex;not null"`
CredentialID string `json:"credential_id" gorm:"type:varchar(512);uniqueIndex;not null"` // base64 encoded
PublicKey string `json:"public_key" gorm:"type:text;not null"` // base64 encoded
AttestationType string `json:"attestation_type" gorm:"type:varchar(255)"`
AAGUID string `json:"aaguid" gorm:"type:varchar(512)"` // base64 encoded
SignCount uint32 `json:"sign_count" gorm:"default:0"`
CloneWarning bool `json:"clone_warning"`
UserPresent bool `json:"user_present"`
UserVerified bool `json:"user_verified"`
BackupEligible bool `json:"backup_eligible"`
BackupState bool `json:"backup_state"`
Transports string `json:"transports" gorm:"type:text"`
Attachment string `json:"attachment" gorm:"type:varchar(32)"`
LastUsedAt *time.Time `json:"last_used_at"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
}
func GetPasskeyByCredentialID ¶
func GetPasskeyByCredentialID(credentialID []byte) (*PasskeyCredential, error)
func GetPasskeyByUserID ¶
func GetPasskeyByUserID(userID int) (*PasskeyCredential, error)
func NewPasskeyCredentialFromWebAuthn ¶
func NewPasskeyCredentialFromWebAuthn(userID int, credential *webauthn.Credential) *PasskeyCredential
func (*PasskeyCredential) ApplyValidatedCredential ¶
func (p *PasskeyCredential) ApplyValidatedCredential(credential *webauthn.Credential)
func (*PasskeyCredential) SetTransports ¶
func (p *PasskeyCredential) SetTransports(list []protocol.AuthenticatorTransport)
func (*PasskeyCredential) ToWebAuthnCredential ¶
func (p *PasskeyCredential) ToWebAuthnCredential() webauthn.Credential
func (*PasskeyCredential) TransportList ¶
func (p *PasskeyCredential) TransportList() []protocol.AuthenticatorTransport
type PaymentValidation ¶
type PaymentValidation struct {
HasAmount bool
PaidAmountMinor int64
Currency string
ExpectedCurrency string
AllowDiscount bool
}
func PaymentValidationFromMajorString ¶
func PaymentValidationFromMajorString(amount string, currency string, expectedCurrency string, allowDiscount bool) PaymentValidation
func PaymentValidationFromMinorUnits ¶
func PaymentValidationFromMinorUnits(amountMinor int64, currency string, expectedCurrency string, allowDiscount bool) PaymentValidation
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 (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 获取全部组,可按类型过滤(为空则返回全部)
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"`
TaskRateCard *TaskRateCardPricing `json:"task_rate_card,omitempty"`
PricingVersion string `json:"pricing_version,omitempty"`
}
func GetPricing ¶
func GetPricing() []Pricing
type PricingVendor ¶
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
type QuotaData ¶
type QuotaData struct {
Id int `json:"id"`
AggregateKey *string `json:"-" gorm:"type:varchar(64)"`
SnapshotID *string `json:"-" gorm:"-:all"`
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"`
UseGroup string `json:"use_group" gorm:"index;size:64;default:''"`
TokenID int `json:"token_id" gorm:"index;default:0"`
ChannelID int `json:"channel_id" gorm:"index;default:0"`
NodeName string `json:"node_name" gorm:"index;size:64;default:''"`
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 GetQuotaDataByUserId ¶
func GetQuotaDataByUsername ¶
type QuotaDataLogParams ¶ added in v1.0.4
type QuotaDataSnapshot ¶ added in v1.0.4
type QuotaDataSnapshotRetry ¶ added in v1.0.4
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"`
}
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 (*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 Setup ¶
type Stat ¶
func SumUsedQuota ¶
func SumUsedQuota(params LogQueryParams) (stat Stat, err error)
type SubscriptionOrder ¶
type SubscriptionOrder struct {
Id int `json:"id"`
UserId int `json:"user_id" gorm:"index"`
PlanId int `json:"plan_id" gorm:"index"`
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:''"`
Status string `json:"status"`
CreateTime int64 `json:"create_time"`
CompleteTime int64 `json:"complete_time"`
ProviderPayload string `json:"provider_payload" gorm:"type:text"`
}
Subscription order (payment -> webhook -> create UserSubscription)
func GetSubscriptionOrderByTradeNo ¶
func GetSubscriptionOrderByTradeNo(tradeNo string) *SubscriptionOrder
func (*SubscriptionOrder) Insert ¶
func (o *SubscriptionOrder) Insert() error
func (*SubscriptionOrder) Update ¶
func (o *SubscriptionOrder) Update() error
type SubscriptionPlan ¶
type SubscriptionPlan struct {
Id int `json:"id"`
Title string `json:"title" gorm:"type:varchar(128);not null"`
Subtitle string `json:"subtitle" gorm:"type:varchar(255);default:''"`
// Display money amount (follow existing code style: float64 for money)
PriceAmount float64 `json:"price_amount" gorm:"type:decimal(10,6);not null;default:0"`
Currency string `json:"currency" gorm:"type:varchar(8);not null;default:'USD'"`
DurationUnit string `json:"duration_unit" gorm:"type:varchar(16);not null;default:'month'"`
DurationValue int `json:"duration_value" gorm:"type:int;not null;default:1"`
CustomSeconds int64 `json:"custom_seconds" gorm:"type:bigint;not null;default:0"`
Enabled bool `json:"enabled" gorm:"default:true"`
SortOrder int `json:"sort_order" gorm:"type:int;default:0"`
AllowBalancePay *bool `json:"allow_balance_pay" gorm:"default:true"`
StripePriceId string `json:"stripe_price_id" gorm:"type:varchar(128);default:''"`
CreemProductId string `json:"creem_product_id" gorm:"type:varchar(128);default:''"`
WaffoPancakeProductId string `json:"waffo_pancake_product_id" gorm:"type:varchar(128);default:''"`
// Max purchases per user (0 = unlimited)
MaxPurchasePerUser int `json:"max_purchase_per_user" gorm:"type:int;default:0"`
// Upgrade user group after purchase (empty = no change)
UpgradeGroup string `json:"upgrade_group" gorm:"type:varchar(64);default:''"`
// Total quota (amount in quota units, 0 = unlimited)
TotalAmount int64 `json:"total_amount" gorm:"type:bigint;not null;default:0"`
// Quota reset period for plan
QuotaResetPeriod string `json:"quota_reset_period" gorm:"type:varchar(16);default:'never'"`
QuotaResetCustomSeconds int64 `json:"quota_reset_custom_seconds" gorm:"type:bigint;default:0"`
CreatedAt int64 `json:"created_at" gorm:"bigint"`
UpdatedAt int64 `json:"updated_at" gorm:"bigint"`
}
Subscription plan
func GetSubscriptionPlanById ¶
func GetSubscriptionPlanById(id int) (*SubscriptionPlan, error)
func (*SubscriptionPlan) BeforeCreate ¶
func (p *SubscriptionPlan) BeforeCreate(tx *gorm.DB) error
func (*SubscriptionPlan) BeforeUpdate ¶
func (p *SubscriptionPlan) BeforeUpdate(tx *gorm.DB) error
func (*SubscriptionPlan) NormalizeDefaults ¶
func (p *SubscriptionPlan) NormalizeDefaults()
type SubscriptionPlanInfo ¶
func GetSubscriptionPlanInfoByUserSubscriptionId ¶
func GetSubscriptionPlanInfoByUserSubscriptionId(userSubscriptionId int) (*SubscriptionPlanInfo, error)
type SubscriptionPreConsumeRecord ¶
type SubscriptionPreConsumeRecord struct {
Id int `json:"id"`
RequestId string `json:"request_id" gorm:"type:varchar(64);uniqueIndex"`
UserId int `json:"user_id" gorm:"index"`
TokenId int `json:"token_id" gorm:"index"`
UserSubscriptionId int `json:"user_subscription_id" gorm:"index"`
SubscriptionLastResetTime int64 `json:"subscription_last_reset_time" gorm:"bigint;not null;default:0"`
ModelName string `json:"model_name" gorm:"type:varchar(191)"`
QuotaType int `json:"quota_type"`
PreConsumed int64 `json:"pre_consumed" gorm:"type:bigint;not null;default:0"`
Status string `json:"status" gorm:"type:varchar(32);index"` // consumed/refunded
CreatedAt int64 `json:"created_at" gorm:"bigint"`
UpdatedAt int64 `json:"updated_at" gorm:"bigint;index"`
}
SubscriptionPreConsumeRecord stores idempotent pre-consume operations per request.
func (*SubscriptionPreConsumeRecord) BeforeCreate ¶
func (r *SubscriptionPreConsumeRecord) BeforeCreate(tx *gorm.DB) error
func (*SubscriptionPreConsumeRecord) BeforeUpdate ¶
func (r *SubscriptionPreConsumeRecord) BeforeUpdate(tx *gorm.DB) error
type SubscriptionPreConsumeResult ¶
type SubscriptionPreConsumeResult struct {
UserSubscriptionId int
PreConsumed int64
AmountTotal int64
AmountUsedBefore int64
AmountUsedAfter int64
}
func PreConsumeTokenAndUserSubscription ¶
func PreConsumeTokenAndUserSubscription(requestId string, userId int, tokenId int, tokenKey string, modelName string, quotaType int, amount int64) (*SubscriptionPreConsumeResult, error)
PreConsumeTokenAndUserSubscription atomically reserves subscription and token quota. Existing request IDs are returned without applying the token mutation again.
func PreConsumeUserSubscription ¶
func PreConsumeUserSubscription(requestId string, userId int, modelName string, quotaType int, amount int64) (*SubscriptionPreConsumeResult, error)
PreConsumeUserSubscription pre-consumes from any active subscription total quota.
type SubscriptionResetResult ¶ added in v1.0.4
type SubscriptionResetResult struct {
PlanId int `json:"plan_id"`
MatchedCount int `json:"matched_count"`
ResetCount int `json:"reset_count"`
UserCount int `json:"user_count"`
AdvanceResetTime bool `json:"advance_reset_time"`
PlanTitle string `json:"-"`
AffectedUserIds []int `json:"-"`
}
func AdminResetPlanSubscriptions ¶ added in v1.0.4
func AdminResetPlanSubscriptions(planId int, advanceResetTime bool) (*SubscriptionResetResult, error)
func AdminResetUserSubscriptionsByPlan ¶ added in v1.0.4
func AdminResetUserSubscriptionsByPlan(userId int, planId int, advanceResetTime bool) (*SubscriptionResetResult, error)
type SubscriptionSummary ¶
type SubscriptionSummary struct {
Subscription *UserSubscription `json:"subscription"`
}
func GetAllActiveUserSubscriptions ¶
func GetAllActiveUserSubscriptions(userId int) ([]SubscriptionSummary, error)
GetAllActiveUserSubscriptions returns all active subscriptions for a user.
func GetAllUserSubscriptions ¶
func GetAllUserSubscriptions(userId int) ([]SubscriptionSummary, error)
GetAllUserSubscriptions returns all subscriptions (active and expired) for a user.
type SyncTaskQueryParams ¶
type SyncTaskQueryParams struct {
Platform constant.TaskPlatform
ChannelID string
TaskID string
UserID string
Action string
Status string
StartTimestamp int64
EndTimestamp int64
UserIDs []int
QuotaFilter string
}
SyncTaskQueryParams 用于包含所有搜索条件的结构体,可以根据需求添加更多字段
type SystemInstance ¶ added in v1.0.3
type SystemInstance struct {
NodeName string `json:"node_name" gorm:"type:varchar(128);primaryKey"`
Info string `json:"info" gorm:"type:text"`
StartedAt int64 `json:"started_at" gorm:"bigint;index"`
LastSeenAt int64 `json:"last_seen_at" gorm:"bigint;index"`
CreatedAt int64 `json:"created_at" gorm:"bigint;index"`
UpdatedAt int64 `json:"updated_at" gorm:"bigint;index"`
}
func ListSystemInstances ¶ added in v1.0.3
func ListSystemInstances() ([]*SystemInstance, error)
func (*SystemInstance) BeforeCreate ¶ added in v1.0.3
func (instance *SystemInstance) BeforeCreate(_ *gorm.DB) error
func (*SystemInstance) ToResponse ¶ added in v1.0.3
func (instance *SystemInstance) ToResponse(now int64) SystemInstanceResponse
type SystemInstanceResponse ¶ added in v1.0.3
type SystemTask ¶ added in v1.0.3
type SystemTask struct {
ID int64 `json:"id" gorm:"primaryKey"`
TaskID string `json:"task_id" gorm:"type:varchar(64);uniqueIndex"`
Type string `json:"type" gorm:"type:varchar(64);index"`
Status SystemTaskStatus `json:"status" gorm:"type:varchar(32);index"`
ActiveKey *string `json:"active_key,omitempty" gorm:"type:varchar(64);uniqueIndex"`
Payload string `json:"payload" gorm:"type:text"`
State string `json:"state" gorm:"type:text"`
Result string `json:"result" gorm:"type:text"`
Error string `json:"error" gorm:"type:text"`
LockedBy string `json:"locked_by" gorm:"type:varchar(128);index"`
LockedUntil int64 `json:"locked_until" gorm:"bigint;index"`
CreatedAt int64 `json:"created_at" gorm:"bigint;index"`
UpdatedAt int64 `json:"updated_at" gorm:"bigint;index"`
}
func ClaimSystemTask ¶ added in v1.0.3
func CreateSystemTask ¶ added in v1.0.3
func FindRunnableSystemTasks ¶ added in v1.0.3
func FindRunnableSystemTasks(taskType string, now int64, limit int) ([]*SystemTask, error)
func GetActiveSystemTask ¶ added in v1.0.3
func GetActiveSystemTask(taskType string) (*SystemTask, error)
func GetSystemTaskByTaskID ¶ added in v1.0.3
func GetSystemTaskByTaskID(taskID string) (*SystemTask, error)
func ListSystemTasks ¶ added in v1.0.3
func ListSystemTasks(limit int) ([]*SystemTask, error)
func (*SystemTask) BeforeCreate ¶ added in v1.0.3
func (task *SystemTask) BeforeCreate(_ *gorm.DB) error
func (*SystemTask) DecodePayload ¶ added in v1.0.3
func (task *SystemTask) DecodePayload(v any) error
func (*SystemTask) DecodeState ¶ added in v1.0.3
func (task *SystemTask) DecodeState(v any) error
func (*SystemTask) ToResponse ¶ added in v1.0.3
func (task *SystemTask) ToResponse() SystemTaskResponse
type SystemTaskResponse ¶ added in v1.0.3
type SystemTaskResponse struct {
ID int64 `json:"id"`
TaskID string `json:"task_id"`
Type string `json:"type"`
Status SystemTaskStatus `json:"status"`
ActiveKey string `json:"active_key,omitempty"`
Payload any `json:"payload"`
State any `json:"state"`
Result any `json:"result"`
Error string `json:"error"`
LockedBy string `json:"locked_by"`
LockedUntil int64 `json:"locked_until"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
}
type SystemTaskStatus ¶ added in v1.0.3
type SystemTaskStatus string
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"`
// contains filtered or unexported fields
}
func GetAllUnFinishSyncTasks ¶
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) ClearDataForUpdate ¶
func (t *Task) ClearDataForUpdate()
func (*Task) ClearPrivateDataForUpdate ¶
func (t *Task) ClearPrivateDataForUpdate()
func (*Task) DeltaSettlementDisabledForChannel ¶
func (t *Task) DeltaSettlementDisabledForChannel(channelType int, channelSettings ...dto.ChannelOtherSettings) bool
func (*Task) GetResultURL ¶
GetResultURL 获取任务结果 URL(视频地址等) 新数据存在 PrivateData.ResultURL 中;旧数据回退到 FailReason(历史兼容)
func (*Task) GetUpstreamTaskID ¶
GetUpstreamTaskID 获取上游真实 task ID(用于与 provider 通信) 旧数据没有 UpstreamTaskID 时,TaskID 本身就是上游 ID
func (*Task) IncludePrivateDataInUpdate ¶
func (t *Task) IncludePrivateDataInUpdate()
func (*Task) ToOpenAIVideo ¶
func (t *Task) ToOpenAIVideo() *dto.OpenAIVideo
func (*Task) UpdateQuota ¶ added in v1.0.4
func (*Task) UpdateWithSettlementIntent ¶
func (t *Task) UpdateWithSettlementIntent(input *BillingSettlementInput) error
UpdateWithSettlementIntent persists upstream task identity and the request's final billing intent in one transaction before the HTTP success response is released.
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 a column map 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.
func (*Task) UpdateWithStatusAndSettlement ¶
func (t *Task) UpdateWithStatusAndSettlement(fromStatus TaskStatus, input BillingSettlementInput) (bool, error)
UpdateWithStatusAndSettlement commits a terminal task transition and its durable settlement intent atomically. Balance mutations are applied after this transaction by ApplyBillingSettlementOnce or its retry runner.
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"` // 附加倍率(时长、分辨率等)
TaskBilling *types.TaskBillingResult `json:"task_billing,omitempty"`
OriginModelName string `json:"origin_model_name,omitempty"` // 模型名称,必须为OriginModelName
PerCallBilling bool `json:"per_call_billing,omitempty"` // 按次计费:跳过轮询阶段的差额结算
DeltaSettlementDisabled *bool `json:"delta_settlement_disabled,omitempty"` // 渠道关闭完成态差额结算时按提交快照跳过
}
TaskBillingContext 记录任务提交时的计费参数,以便轮询阶段可以重新计算额度。
type TaskPrivateData ¶
type TaskPrivateData struct {
Key string `json:"key,omitempty"`
UpstreamTaskID string `json:"upstream_task_id,omitempty"` // 上游真实 task ID
// AwaitingUpstreamID distinguishes a newly persisted placeholder from
// legacy rows where TaskID itself is the provider task identifier.
AwaitingUpstreamID bool `json:"awaiting_upstream_id,omitempty"`
ResultURL string `json:"result_url,omitempty"` // 任务成功后的结果 URL(视频地址等)
// 计费上下文:用于异步退款/差额结算(轮询阶段读取)
BillingSource string `json:"billing_source,omitempty"` // "wallet" 或 "subscription"
BillingRequestId string `json:"billing_request_id,omitempty"` // 原始预扣 request id,用于跨周期安全结算
SubscriptionId int `json:"subscription_id,omitempty"` // 订阅 ID,用于订阅退款
TokenId int `json:"token_id,omitempty"` // 令牌 ID,用于令牌额度退款
NodeName string `json:"node_name,omitempty"` // 发起任务的节点名,轮询结算阶段据此归属日志而非最后查询节点
BillingContext *TaskBillingContext `json:"billing_context,omitempty"` // 计费参数快照(用于轮询阶段重新计算)
}
func (*TaskPrivateData) Scan ¶
func (p *TaskPrivateData) Scan(val interface{}) error
type TaskQueryParams ¶
type TaskQueryParams struct {
ChannelID string
MjID string
StartTimestamp string
EndTimestamp string
QuotaFilter string
}
TaskQueryParams 用于包含所有搜索条件的结构体,可以根据需求添加更多字段
type TaskQuotaUsage ¶
type TaskRateCardPricing ¶
type TaskRateCardPricing struct {
RuleKey string `json:"rule_key,omitempty"`
Vendor string `json:"vendor,omitempty"`
Unit string `json:"unit,omitempty"`
QuantityField string `json:"quantity_field,omitempty"`
DefaultQuantity float64 `json:"default_quantity,omitempty"`
Strict bool `json:"strict"`
Defaults map[string]string `json:"defaults,omitempty"`
MinUnitPrice float64 `json:"min_unit_price"`
MaxUnitPrice float64 `json:"max_unit_price"`
Rows []TaskRateCardPricingRow `json:"rows"`
}
type TaskRateCardPricingRow ¶
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 int64 `json:"remain_quota" gorm:"type:bigint;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 int64 `json:"used_quota" gorm:"type:bigint;default:0"` // used quota
Group string `json:"group" gorm:"default:''"`
CrossGroupRetry bool `json:"cross_group_retry"` // 跨分组重试,仅auto分组有效
RoutingPolicyJSON *string `json:"-" gorm:"column:routing_policy;type:text"`
DeletedAt gorm.DeletedAt `gorm:"index"`
}
func GetTokenById ¶
func SearchUserTokens ¶
func ValidateUserToken ¶
func ValidateUserTokenForReadOnly ¶ added in v1.0.2
func (*Token) GetFullKey ¶
func (*Token) GetIpLimits ¶
func (*Token) GetMaskedKey ¶
func (*Token) GetModelLimits ¶
func (*Token) GetModelLimitsMap ¶
func (*Token) GetStoredRoutingPolicy ¶
func (token *Token) GetStoredRoutingPolicy() (*TokenRoutingPolicy, error)
func (*Token) IsModelLimitsEnabled ¶
func (*Token) SelectUpdate ¶
func (*Token) SetRoutingPolicy ¶
func (token *Token) SetRoutingPolicy(policy *TokenRoutingPolicy) error
type TokenRoutingPolicy ¶
type TokenRoutingPolicy struct {
Version int `json:"version"`
Mode string `json:"mode"`
Route string `json:"route,omitempty"`
Groups []string `json:"groups,omitempty"`
RetryOnFailure bool `json:"retry_on_failure"`
}
func (TokenRoutingPolicy) Clone ¶
func (policy TokenRoutingPolicy) Clone() TokenRoutingPolicy
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"`
}
func GetAllTopUps ¶
GetAllTopUps 获取全平台的充值记录(管理员使用,不限制时间窗口)
func GetTopUpById ¶
func GetTopUpByTradeNo ¶
func GetTopUpByTradeNoWithError ¶
GetTopUpByTradeNoWithError keeps database failures distinct from a missing order for payment callbacks, which must retry when the database is unhealthy.
func GetUserTopUps ¶
func SearchAllTopUps ¶
func SearchAllTopUps(keyword string, pageInfo *common.PageInfo) (topups []*TopUp, total int64, err error)
SearchAllTopUps 按订单号搜索全平台充值记录(管理员使用,不限制时间窗口)
type TwoFA ¶
type TwoFA struct {
Id int `json:"id" gorm:"primaryKey"`
UserId int `json:"user_id" gorm:"unique;not null;index"`
Secret string `json:"-" gorm:"type:varchar(255);not null"` // TOTP密钥,不返回给前端
IsEnabled bool `json:"is_enabled"`
FailedAttempts int `json:"failed_attempts" gorm:"default:0"`
LockedUntil *time.Time `json:"locked_until,omitempty"`
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
}
TwoFA 用户2FA设置表
func GetTwoFAByUserId ¶
GetTwoFAByUserId 根据用户ID获取2FA设置
func (*TwoFA) IncrementFailedAttempts ¶
IncrementFailedAttempts 增加失败尝试次数
func (*TwoFA) ResetFailedAttempts ¶
ResetFailedAttempts 重置失败尝试次数
func (*TwoFA) ValidateBackupCodeAndUpdateUsage ¶
ValidateBackupCodeAndUpdateUsage 验证备用码并更新使用记录
type TwoFABackupCode ¶
type TwoFABackupCode struct {
Id int `json:"id" gorm:"primaryKey"`
UserId int `json:"user_id" gorm:"not null;index"`
CodeHash string `json:"-" gorm:"type:varchar(255);not null"` // 备用码哈希
IsUsed bool `json:"is_used"`
UsedAt *time.Time `json:"used_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
}
TwoFABackupCode 备用码使用记录表
type User ¶
type User struct {
Id int `json:"id"`
Username string `json:"username" gorm:"unique;index" validate:"max=20"`
Password string `json:"password" gorm:"not null;" validate:"min=8,max=20"`
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"`
NormalizedEmail string `json:"-" gorm:"column:normalized_email;size:50;index"`
GitHubId string `json:"github_id" gorm:"column:github_id;size:512;index" validate:"max=512"`
DiscordId string `json:"discord_id" gorm:"column:discord_id;size:512;index" validate:"max=512"`
OidcId string `json:"oidc_id" gorm:"column:oidc_id;size:512;index" validate:"max=512"`
WeChatId string `json:"wechat_id" gorm:"column:wechat_id;size:512;index" validate:"max=512"`
TelegramId string `json:"telegram_id" gorm:"column:telegram_id;size:512;index" validate:"max=512"`
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 int64 `json:"quota" gorm:"type:bigint;default:0"`
UsedQuota int64 `json:"used_quota" gorm:"type:bigint;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 int64 `json:"aff_quota" gorm:"type:bigint;default:0;column:aff_quota"` // 邀请剩余额度
AffHistoryQuota int64 `json:"aff_history_quota" gorm:"type:bigint;default:0;column:aff_history"` // 邀请历史额度
InviterId int `json:"inviter_id" gorm:"type:int;column:inviter_id;index"`
DeletedAt gorm.DeletedAt `gorm:"index"`
LinuxDOId string `json:"linux_do_id" gorm:"column:linux_do_id;size:512;index" validate:"max=512"`
Setting string `json:"setting" gorm:"type:text;column:setting"`
Remark string `json:"remark,omitempty" gorm:"type:varchar(255)" validate:"max=255"`
StripeCustomer string `json:"stripe_customer" gorm:"type:varchar(64);column:stripe_customer;index"`
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 GetRootUser ¶
func GetRootUser() (user *User)
func GetUniqueUserByEmail ¶ added in v1.0.4
func GetUserByOAuthBinding ¶
GetUserByOAuthBinding finds a user by provider ID and provider user ID
func SearchUsers ¶
func ValidateAccessToken ¶
func (*User) ClearBinding ¶
func (*User) FillUserByDiscordId ¶
func (*User) FillUserByEmail ¶
func (*User) FillUserByGitHubId ¶
func (*User) FillUserById ¶
func (*User) FillUserByLinuxDOId ¶
func (*User) FillUserByOidcId ¶
func (*User) FillUserByTelegramId ¶
func (*User) FillUserByWeChatId ¶
func (*User) FinalizeOAuthUserCreation ¶
FinalizeOAuthUserCreation performs post-transaction tasks for OAuth user creation. This should be called after the transaction commits successfully.
func (*User) GetAccessToken ¶
func (*User) GetSetting ¶
func (user *User) GetSetting() dto.UserSetting
func (*User) HardDelete ¶
func (*User) InsertWithTx ¶
InsertWithTx inserts a new user within an existing transaction. Callers that own the outer transaction should use WithNormalizedEmailWriteTx so MySQL's connection-scoped email lock covers the final commit. This is used for OAuth registration where user creation and binding need to be atomic. Post-creation tasks (sidebar config, logs, inviter rewards) are handled after the transaction commits.
func (*User) SetAccessToken ¶
func (*User) SetSetting ¶
func (user *User) SetSetting(setting dto.UserSetting)
func (*User) ToBaseUser ¶
func (*User) TransferAffQuotaToQuota ¶
func (*User) UpdateFields ¶ added in v1.0.4
func (user *User) UpdateFields(updatePassword bool, fields ...UserUpdateField) error
func (*User) UpdateFieldsWithTx ¶ added in v1.0.4
func (*User) UpdateGitHubId ¶
UpdateGitHubId updates the user's GitHub ID (used for migration from login to numeric ID)
func (*User) UpdateWithTx ¶ added in v1.0.4
func (*User) ValidateAndFill ¶
ValidateAndFill check password & user status
func (*User) ValidateOAuthIdentityLengths ¶ added in v1.0.4
type UserBase ¶
type UserBase struct {
Id int `json:"id"`
Group string `json:"group"`
Email string `json:"email"`
Quota int64 `json:"quota"`
Role int `json:"role"`
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 ¶
GetUserCache gets complete user cache from hash
func (*UserBase) GetSetting ¶
func (user *UserBase) GetSetting() dto.UserSetting
func (*UserBase) WriteContext ¶
type UserOAuthBinding ¶
type UserOAuthBinding struct {
Id int `json:"id" gorm:"primaryKey"`
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 UserSubscription ¶
type UserSubscription struct {
Id int `json:"id"`
UserId int `json:"user_id" gorm:"index;index:idx_user_sub_active,priority:1"`
PlanId int `json:"plan_id" gorm:"index"`
AmountTotal int64 `json:"amount_total" gorm:"type:bigint;not null;default:0"`
AmountUsed int64 `json:"amount_used" gorm:"type:bigint;not null;default:0"`
StartTime int64 `json:"start_time" gorm:"bigint"`
EndTime int64 `json:"end_time" gorm:"bigint;index;index:idx_user_sub_active,priority:3"`
Status string `json:"status" gorm:"type:varchar(32);index;index:idx_user_sub_active,priority:2"` // active/expired/cancelled
Source string `json:"source" gorm:"type:varchar(32);default:'order'"` // order/admin
LastResetTime int64 `json:"last_reset_time" gorm:"type:bigint;default:0"`
NextResetTime int64 `json:"next_reset_time" gorm:"type:bigint;default:0;index"`
UpgradeGroup string `json:"upgrade_group" gorm:"type:varchar(64);default:''"`
PrevUserGroup string `json:"prev_user_group" gorm:"type:varchar(64);default:''"`
CreatedAt int64 `json:"created_at" gorm:"bigint"`
UpdatedAt int64 `json:"updated_at" gorm:"bigint"`
}
User subscription instance
func CreateUserSubscriptionFromPlanTx ¶
func CreateUserSubscriptionFromPlanTx(tx *gorm.DB, userId int, plan *SubscriptionPlan, source string) (*UserSubscription, error)
func (*UserSubscription) BeforeCreate ¶
func (s *UserSubscription) BeforeCreate(tx *gorm.DB) error
func (*UserSubscription) BeforeUpdate ¶
func (s *UserSubscription) BeforeUpdate(tx *gorm.DB) error
type UserUpdateField ¶ added in v1.0.4
type UserUpdateField string
const ( UserUpdateFieldUsername UserUpdateField = "username" UserUpdateFieldDisplayName UserUpdateField = "display_name" UserUpdateFieldRole UserUpdateField = "role" UserUpdateFieldStatus UserUpdateField = "status" UserUpdateFieldEmail UserUpdateField = "email" UserUpdateFieldGitHubId UserUpdateField = "github_id" UserUpdateFieldDiscordId UserUpdateField = "discord_id" UserUpdateFieldOidcId UserUpdateField = "oidc_id" UserUpdateFieldWeChatId UserUpdateField = "wechat_id" UserUpdateFieldTelegramId UserUpdateField = "telegram_id" UserUpdateFieldAccessToken UserUpdateField = "access_token" UserUpdateFieldGroup UserUpdateField = "group" UserUpdateFieldAffCode UserUpdateField = "aff_code" UserUpdateFieldAffCount UserUpdateField = "aff_count" UserUpdateFieldAffQuota UserUpdateField = "aff_quota" UserUpdateFieldAffHistoryQuota UserUpdateField = "aff_history" UserUpdateFieldInviterId UserUpdateField = "inviter_id" UserUpdateFieldLinuxDOId UserUpdateField = "linux_do_id" UserUpdateFieldSetting UserUpdateField = "setting" UserUpdateFieldRemark UserUpdateField = "remark" UserUpdateFieldStripeCustomer UserUpdateField = "stripe_customer" UserUpdateFieldLastLoginAt UserUpdateField = "last_login_at" )
type Vendor ¶
type Vendor struct {
Id int `json:"id"`
Name string `json:"name" gorm:"size:128;not null"`
NameKey string `json:"-" gorm:"size:191;not null;default:''"`
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"`
}
func GetAllVendors ¶
GetAllVendors 获取全部供应商(分页)
func SearchVendors ¶
SearchVendors 按关键字搜索供应商
Source Files
¶
- ability.go
- auth_flow.go
- billing_settlement.go
- cache_invalidation_task.go
- channel.go
- channel_cache.go
- channel_satisfy.go
- checkin.go
- custom_oauth_provider.go
- db_time.go
- errors.go
- locking.go
- log.go
- main.go
- metadata_name_key.go
- midjourney.go
- missing_models.go
- model_extra.go
- model_meta.go
- option.go
- passkey.go
- payment_validation.go
- perf_metric.go
- prefill_group.go
- pricing.go
- pricing_default.go
- pricing_refresh.go
- redemption.go
- setup.go
- subscription.go
- system_instance.go
- system_task.go
- task.go
- token.go
- token_cache.go
- token_routing.go
- topup.go
- twofa.go
- usedata.go
- usedata_rankings.go
- user.go
- user_cache.go
- user_oauth_binding.go
- utils.go
- vendor_meta.go