Commit d2fc14fb authored by long's avatar long
Browse files

feat: 实现注册优惠码功能

  - 支持创建/编辑/删除优惠码,设置赠送金额和使用限制
  - 注册页面实时验证优惠码并显示赠送金额
  - 支持 URL 参数自动填充 (?promo=CODE)
  - 添加优惠码验证接口速率限制
  - 使用数据库行锁防止并发超限
  - 新增后台优惠码管理页面,支持复制注册链接
parent 7d1fe818
...@@ -33,7 +33,7 @@ func main() { ...@@ -33,7 +33,7 @@ func main() {
}() }()
userRepo := repository.NewUserRepository(client, sqlDB) userRepo := repository.NewUserRepository(client, sqlDB)
authService := service.NewAuthService(userRepo, cfg, nil, nil, nil, nil) authService := service.NewAuthService(userRepo, cfg, nil, nil, nil, nil, nil)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel() defer cancel()
......
...@@ -51,13 +51,17 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { ...@@ -51,13 +51,17 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
turnstileVerifier := repository.NewTurnstileVerifier() turnstileVerifier := repository.NewTurnstileVerifier()
turnstileService := service.NewTurnstileService(settingService, turnstileVerifier) turnstileService := service.NewTurnstileService(settingService, turnstileVerifier)
emailQueueService := service.ProvideEmailQueueService(emailService) emailQueueService := service.ProvideEmailQueueService(emailService)
authService := service.NewAuthService(userRepository, configConfig, settingService, emailService, turnstileService, emailQueueService) promoCodeRepository := repository.NewPromoCodeRepository(client)
billingCache := repository.NewBillingCache(redisClient)
userSubscriptionRepository := repository.NewUserSubscriptionRepository(client)
billingCacheService := service.NewBillingCacheService(billingCache, userRepository, userSubscriptionRepository, configConfig)
promoService := service.NewPromoService(promoCodeRepository, userRepository, billingCacheService, client)
authService := service.NewAuthService(userRepository, configConfig, settingService, emailService, turnstileService, emailQueueService, promoService)
userService := service.NewUserService(userRepository) userService := service.NewUserService(userRepository)
authHandler := handler.NewAuthHandler(configConfig, authService, userService, settingService) authHandler := handler.NewAuthHandler(configConfig, authService, userService, settingService, promoService)
userHandler := handler.NewUserHandler(userService) userHandler := handler.NewUserHandler(userService)
apiKeyRepository := repository.NewAPIKeyRepository(client) apiKeyRepository := repository.NewAPIKeyRepository(client)
groupRepository := repository.NewGroupRepository(client, db) groupRepository := repository.NewGroupRepository(client, db)
userSubscriptionRepository := repository.NewUserSubscriptionRepository(client)
apiKeyCache := repository.NewAPIKeyCache(redisClient) apiKeyCache := repository.NewAPIKeyCache(redisClient)
apiKeyService := service.NewAPIKeyService(apiKeyRepository, userRepository, groupRepository, userSubscriptionRepository, apiKeyCache, configConfig) apiKeyService := service.NewAPIKeyService(apiKeyRepository, userRepository, groupRepository, userSubscriptionRepository, apiKeyCache, configConfig)
apiKeyHandler := handler.NewAPIKeyHandler(apiKeyService) apiKeyHandler := handler.NewAPIKeyHandler(apiKeyService)
...@@ -65,8 +69,6 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { ...@@ -65,8 +69,6 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
usageService := service.NewUsageService(usageLogRepository, userRepository, client) usageService := service.NewUsageService(usageLogRepository, userRepository, client)
usageHandler := handler.NewUsageHandler(usageService, apiKeyService) usageHandler := handler.NewUsageHandler(usageService, apiKeyService)
redeemCodeRepository := repository.NewRedeemCodeRepository(client) redeemCodeRepository := repository.NewRedeemCodeRepository(client)
billingCache := repository.NewBillingCache(redisClient)
billingCacheService := service.NewBillingCacheService(billingCache, userRepository, userSubscriptionRepository, configConfig)
subscriptionService := service.NewSubscriptionService(groupRepository, userSubscriptionRepository, billingCacheService) subscriptionService := service.NewSubscriptionService(groupRepository, userSubscriptionRepository, billingCacheService)
redeemCache := repository.NewRedeemCache(redisClient) redeemCache := repository.NewRedeemCache(redisClient)
redeemService := service.NewRedeemService(redeemCodeRepository, userRepository, subscriptionService, redeemCache, billingCacheService, client) redeemService := service.NewRedeemService(redeemCodeRepository, userRepository, subscriptionService, redeemCache, billingCacheService, client)
...@@ -112,6 +114,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { ...@@ -112,6 +114,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
antigravityOAuthHandler := admin.NewAntigravityOAuthHandler(antigravityOAuthService) antigravityOAuthHandler := admin.NewAntigravityOAuthHandler(antigravityOAuthService)
proxyHandler := admin.NewProxyHandler(adminService) proxyHandler := admin.NewProxyHandler(adminService)
adminRedeemHandler := admin.NewRedeemHandler(adminService) adminRedeemHandler := admin.NewRedeemHandler(adminService)
promoHandler := admin.NewPromoHandler(promoService)
settingHandler := admin.NewSettingHandler(settingService, emailService, turnstileService) settingHandler := admin.NewSettingHandler(settingService, emailService, turnstileService)
updateCache := repository.NewUpdateCache(redisClient) updateCache := repository.NewUpdateCache(redisClient)
gitHubReleaseClient := repository.ProvideGitHubReleaseClient(configConfig) gitHubReleaseClient := repository.ProvideGitHubReleaseClient(configConfig)
...@@ -124,7 +127,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { ...@@ -124,7 +127,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
userAttributeValueRepository := repository.NewUserAttributeValueRepository(client) userAttributeValueRepository := repository.NewUserAttributeValueRepository(client)
userAttributeService := service.NewUserAttributeService(userAttributeDefinitionRepository, userAttributeValueRepository) userAttributeService := service.NewUserAttributeService(userAttributeDefinitionRepository, userAttributeValueRepository)
userAttributeHandler := admin.NewUserAttributeHandler(userAttributeService) userAttributeHandler := admin.NewUserAttributeHandler(userAttributeService)
adminHandlers := handler.ProvideAdminHandlers(dashboardHandler, adminUserHandler, groupHandler, accountHandler, oAuthHandler, openAIOAuthHandler, geminiOAuthHandler, antigravityOAuthHandler, proxyHandler, adminRedeemHandler, settingHandler, systemHandler, adminSubscriptionHandler, adminUsageHandler, userAttributeHandler) adminHandlers := handler.ProvideAdminHandlers(dashboardHandler, adminUserHandler, groupHandler, accountHandler, oAuthHandler, openAIOAuthHandler, geminiOAuthHandler, antigravityOAuthHandler, proxyHandler, adminRedeemHandler, promoHandler, settingHandler, systemHandler, adminSubscriptionHandler, adminUsageHandler, userAttributeHandler)
pricingRemoteClient := repository.ProvidePricingRemoteClient(configConfig) pricingRemoteClient := repository.ProvidePricingRemoteClient(configConfig)
pricingService, err := service.ProvidePricingService(configConfig, pricingRemoteClient) pricingService, err := service.ProvidePricingService(configConfig, pricingRemoteClient)
if err != nil { if err != nil {
...@@ -145,7 +148,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { ...@@ -145,7 +148,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
jwtAuthMiddleware := middleware.NewJWTAuthMiddleware(authService, userService) jwtAuthMiddleware := middleware.NewJWTAuthMiddleware(authService, userService)
adminAuthMiddleware := middleware.NewAdminAuthMiddleware(authService, userService, settingService) adminAuthMiddleware := middleware.NewAdminAuthMiddleware(authService, userService, settingService)
apiKeyAuthMiddleware := middleware.NewAPIKeyAuthMiddleware(apiKeyService, subscriptionService, configConfig) apiKeyAuthMiddleware := middleware.NewAPIKeyAuthMiddleware(apiKeyService, subscriptionService, configConfig)
engine := server.ProvideRouter(configConfig, handlers, jwtAuthMiddleware, adminAuthMiddleware, apiKeyAuthMiddleware, apiKeyService, subscriptionService) engine := server.ProvideRouter(configConfig, handlers, jwtAuthMiddleware, adminAuthMiddleware, apiKeyAuthMiddleware, apiKeyService, subscriptionService, redisClient)
httpServer := server.ProvideHTTPServer(configConfig, engine) httpServer := server.ProvideHTTPServer(configConfig, engine)
tokenRefreshService := service.ProvideTokenRefreshService(accountRepository, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, configConfig) tokenRefreshService := service.ProvideTokenRefreshService(accountRepository, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, configConfig)
accountExpiryService := service.ProvideAccountExpiryService(accountRepository) accountExpiryService := service.ProvideAccountExpiryService(accountRepository)
......
...@@ -9,6 +9,7 @@ import ( ...@@ -9,6 +9,7 @@ import (
"math" "math"
"entgo.io/ent" "entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field" "entgo.io/ent/schema/field"
...@@ -31,6 +32,7 @@ type AccountQuery struct { ...@@ -31,6 +32,7 @@ type AccountQuery struct {
withProxy *ProxyQuery withProxy *ProxyQuery
withUsageLogs *UsageLogQuery withUsageLogs *UsageLogQuery
withAccountGroups *AccountGroupQuery withAccountGroups *AccountGroupQuery
modifiers []func(*sql.Selector)
// intermediate query (i.e. traversal path). // intermediate query (i.e. traversal path).
sql *sql.Selector sql *sql.Selector
path func(context.Context) (*sql.Selector, error) path func(context.Context) (*sql.Selector, error)
...@@ -495,6 +497,9 @@ func (_q *AccountQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Acco ...@@ -495,6 +497,9 @@ func (_q *AccountQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Acco
node.Edges.loadedTypes = loadedTypes node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values) return node.assignValues(columns, values)
} }
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
for i := range hooks { for i := range hooks {
hooks[i](ctx, _spec) hooks[i](ctx, _spec)
} }
...@@ -690,6 +695,9 @@ func (_q *AccountQuery) loadAccountGroups(ctx context.Context, query *AccountGro ...@@ -690,6 +695,9 @@ func (_q *AccountQuery) loadAccountGroups(ctx context.Context, query *AccountGro
func (_q *AccountQuery) sqlCount(ctx context.Context) (int, error) { func (_q *AccountQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec() _spec := _q.querySpec()
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
_spec.Node.Columns = _q.ctx.Fields _spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 { if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
...@@ -755,6 +763,9 @@ func (_q *AccountQuery) sqlQuery(ctx context.Context) *sql.Selector { ...@@ -755,6 +763,9 @@ func (_q *AccountQuery) sqlQuery(ctx context.Context) *sql.Selector {
if _q.ctx.Unique != nil && *_q.ctx.Unique { if _q.ctx.Unique != nil && *_q.ctx.Unique {
selector.Distinct() selector.Distinct()
} }
for _, m := range _q.modifiers {
m(selector)
}
for _, p := range _q.predicates { for _, p := range _q.predicates {
p(selector) p(selector)
} }
...@@ -772,6 +783,32 @@ func (_q *AccountQuery) sqlQuery(ctx context.Context) *sql.Selector { ...@@ -772,6 +783,32 @@ func (_q *AccountQuery) sqlQuery(ctx context.Context) *sql.Selector {
return selector return selector
} }
// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
// updated, deleted or "selected ... for update" by other sessions, until the transaction is
// either committed or rolled-back.
func (_q *AccountQuery) ForUpdate(opts ...sql.LockOption) *AccountQuery {
if _q.driver.Dialect() == dialect.Postgres {
_q.Unique(false)
}
_q.modifiers = append(_q.modifiers, func(s *sql.Selector) {
s.ForUpdate(opts...)
})
return _q
}
// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
// on any rows that are read. Other sessions can read the rows, but cannot modify them
// until your transaction commits.
func (_q *AccountQuery) ForShare(opts ...sql.LockOption) *AccountQuery {
if _q.driver.Dialect() == dialect.Postgres {
_q.Unique(false)
}
_q.modifiers = append(_q.modifiers, func(s *sql.Selector) {
s.ForShare(opts...)
})
return _q
}
// AccountGroupBy is the group-by builder for Account entities. // AccountGroupBy is the group-by builder for Account entities.
type AccountGroupBy struct { type AccountGroupBy struct {
selector selector
......
...@@ -8,6 +8,7 @@ import ( ...@@ -8,6 +8,7 @@ import (
"math" "math"
"entgo.io/ent" "entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/dialect/sql/sqlgraph"
"github.com/Wei-Shaw/sub2api/ent/account" "github.com/Wei-Shaw/sub2api/ent/account"
...@@ -25,6 +26,7 @@ type AccountGroupQuery struct { ...@@ -25,6 +26,7 @@ type AccountGroupQuery struct {
predicates []predicate.AccountGroup predicates []predicate.AccountGroup
withAccount *AccountQuery withAccount *AccountQuery
withGroup *GroupQuery withGroup *GroupQuery
modifiers []func(*sql.Selector)
// intermediate query (i.e. traversal path). // intermediate query (i.e. traversal path).
sql *sql.Selector sql *sql.Selector
path func(context.Context) (*sql.Selector, error) path func(context.Context) (*sql.Selector, error)
...@@ -347,6 +349,9 @@ func (_q *AccountGroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([] ...@@ -347,6 +349,9 @@ func (_q *AccountGroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]
node.Edges.loadedTypes = loadedTypes node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values) return node.assignValues(columns, values)
} }
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
for i := range hooks { for i := range hooks {
hooks[i](ctx, _spec) hooks[i](ctx, _spec)
} }
...@@ -432,6 +437,9 @@ func (_q *AccountGroupQuery) loadGroup(ctx context.Context, query *GroupQuery, n ...@@ -432,6 +437,9 @@ func (_q *AccountGroupQuery) loadGroup(ctx context.Context, query *GroupQuery, n
func (_q *AccountGroupQuery) sqlCount(ctx context.Context) (int, error) { func (_q *AccountGroupQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec() _spec := _q.querySpec()
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
_spec.Unique = false _spec.Unique = false
_spec.Node.Columns = nil _spec.Node.Columns = nil
return sqlgraph.CountNodes(ctx, _q.driver, _spec) return sqlgraph.CountNodes(ctx, _q.driver, _spec)
...@@ -495,6 +503,9 @@ func (_q *AccountGroupQuery) sqlQuery(ctx context.Context) *sql.Selector { ...@@ -495,6 +503,9 @@ func (_q *AccountGroupQuery) sqlQuery(ctx context.Context) *sql.Selector {
if _q.ctx.Unique != nil && *_q.ctx.Unique { if _q.ctx.Unique != nil && *_q.ctx.Unique {
selector.Distinct() selector.Distinct()
} }
for _, m := range _q.modifiers {
m(selector)
}
for _, p := range _q.predicates { for _, p := range _q.predicates {
p(selector) p(selector)
} }
...@@ -512,6 +523,32 @@ func (_q *AccountGroupQuery) sqlQuery(ctx context.Context) *sql.Selector { ...@@ -512,6 +523,32 @@ func (_q *AccountGroupQuery) sqlQuery(ctx context.Context) *sql.Selector {
return selector return selector
} }
// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
// updated, deleted or "selected ... for update" by other sessions, until the transaction is
// either committed or rolled-back.
func (_q *AccountGroupQuery) ForUpdate(opts ...sql.LockOption) *AccountGroupQuery {
if _q.driver.Dialect() == dialect.Postgres {
_q.Unique(false)
}
_q.modifiers = append(_q.modifiers, func(s *sql.Selector) {
s.ForUpdate(opts...)
})
return _q
}
// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
// on any rows that are read. Other sessions can read the rows, but cannot modify them
// until your transaction commits.
func (_q *AccountGroupQuery) ForShare(opts ...sql.LockOption) *AccountGroupQuery {
if _q.driver.Dialect() == dialect.Postgres {
_q.Unique(false)
}
_q.modifiers = append(_q.modifiers, func(s *sql.Selector) {
s.ForShare(opts...)
})
return _q
}
// AccountGroupGroupBy is the group-by builder for AccountGroup entities. // AccountGroupGroupBy is the group-by builder for AccountGroup entities.
type AccountGroupGroupBy struct { type AccountGroupGroupBy struct {
selector selector
......
...@@ -9,6 +9,7 @@ import ( ...@@ -9,6 +9,7 @@ import (
"math" "math"
"entgo.io/ent" "entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field" "entgo.io/ent/schema/field"
...@@ -29,6 +30,7 @@ type APIKeyQuery struct { ...@@ -29,6 +30,7 @@ type APIKeyQuery struct {
withUser *UserQuery withUser *UserQuery
withGroup *GroupQuery withGroup *GroupQuery
withUsageLogs *UsageLogQuery withUsageLogs *UsageLogQuery
modifiers []func(*sql.Selector)
// intermediate query (i.e. traversal path). // intermediate query (i.e. traversal path).
sql *sql.Selector sql *sql.Selector
path func(context.Context) (*sql.Selector, error) path func(context.Context) (*sql.Selector, error)
...@@ -458,6 +460,9 @@ func (_q *APIKeyQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*APIKe ...@@ -458,6 +460,9 @@ func (_q *APIKeyQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*APIKe
node.Edges.loadedTypes = loadedTypes node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values) return node.assignValues(columns, values)
} }
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
for i := range hooks { for i := range hooks {
hooks[i](ctx, _spec) hooks[i](ctx, _spec)
} }
...@@ -583,6 +588,9 @@ func (_q *APIKeyQuery) loadUsageLogs(ctx context.Context, query *UsageLogQuery, ...@@ -583,6 +588,9 @@ func (_q *APIKeyQuery) loadUsageLogs(ctx context.Context, query *UsageLogQuery,
func (_q *APIKeyQuery) sqlCount(ctx context.Context) (int, error) { func (_q *APIKeyQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec() _spec := _q.querySpec()
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
_spec.Node.Columns = _q.ctx.Fields _spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 { if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
...@@ -651,6 +659,9 @@ func (_q *APIKeyQuery) sqlQuery(ctx context.Context) *sql.Selector { ...@@ -651,6 +659,9 @@ func (_q *APIKeyQuery) sqlQuery(ctx context.Context) *sql.Selector {
if _q.ctx.Unique != nil && *_q.ctx.Unique { if _q.ctx.Unique != nil && *_q.ctx.Unique {
selector.Distinct() selector.Distinct()
} }
for _, m := range _q.modifiers {
m(selector)
}
for _, p := range _q.predicates { for _, p := range _q.predicates {
p(selector) p(selector)
} }
...@@ -668,6 +679,32 @@ func (_q *APIKeyQuery) sqlQuery(ctx context.Context) *sql.Selector { ...@@ -668,6 +679,32 @@ func (_q *APIKeyQuery) sqlQuery(ctx context.Context) *sql.Selector {
return selector return selector
} }
// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
// updated, deleted or "selected ... for update" by other sessions, until the transaction is
// either committed or rolled-back.
func (_q *APIKeyQuery) ForUpdate(opts ...sql.LockOption) *APIKeyQuery {
if _q.driver.Dialect() == dialect.Postgres {
_q.Unique(false)
}
_q.modifiers = append(_q.modifiers, func(s *sql.Selector) {
s.ForUpdate(opts...)
})
return _q
}
// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
// on any rows that are read. Other sessions can read the rows, but cannot modify them
// until your transaction commits.
func (_q *APIKeyQuery) ForShare(opts ...sql.LockOption) *APIKeyQuery {
if _q.driver.Dialect() == dialect.Postgres {
_q.Unique(false)
}
_q.modifiers = append(_q.modifiers, func(s *sql.Selector) {
s.ForShare(opts...)
})
return _q
}
// APIKeyGroupBy is the group-by builder for APIKey entities. // APIKeyGroupBy is the group-by builder for APIKey entities.
type APIKeyGroupBy struct { type APIKeyGroupBy struct {
selector selector
......
...@@ -19,6 +19,8 @@ import ( ...@@ -19,6 +19,8 @@ import (
"github.com/Wei-Shaw/sub2api/ent/accountgroup" "github.com/Wei-Shaw/sub2api/ent/accountgroup"
"github.com/Wei-Shaw/sub2api/ent/apikey" "github.com/Wei-Shaw/sub2api/ent/apikey"
"github.com/Wei-Shaw/sub2api/ent/group" "github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/promocode"
"github.com/Wei-Shaw/sub2api/ent/promocodeusage"
"github.com/Wei-Shaw/sub2api/ent/proxy" "github.com/Wei-Shaw/sub2api/ent/proxy"
"github.com/Wei-Shaw/sub2api/ent/redeemcode" "github.com/Wei-Shaw/sub2api/ent/redeemcode"
"github.com/Wei-Shaw/sub2api/ent/setting" "github.com/Wei-Shaw/sub2api/ent/setting"
...@@ -45,6 +47,10 @@ type Client struct { ...@@ -45,6 +47,10 @@ type Client struct {
AccountGroup *AccountGroupClient AccountGroup *AccountGroupClient
// Group is the client for interacting with the Group builders. // Group is the client for interacting with the Group builders.
Group *GroupClient Group *GroupClient
// PromoCode is the client for interacting with the PromoCode builders.
PromoCode *PromoCodeClient
// PromoCodeUsage is the client for interacting with the PromoCodeUsage builders.
PromoCodeUsage *PromoCodeUsageClient
// Proxy is the client for interacting with the Proxy builders. // Proxy is the client for interacting with the Proxy builders.
Proxy *ProxyClient Proxy *ProxyClient
// RedeemCode is the client for interacting with the RedeemCode builders. // RedeemCode is the client for interacting with the RedeemCode builders.
...@@ -78,6 +84,8 @@ func (c *Client) init() { ...@@ -78,6 +84,8 @@ func (c *Client) init() {
c.Account = NewAccountClient(c.config) c.Account = NewAccountClient(c.config)
c.AccountGroup = NewAccountGroupClient(c.config) c.AccountGroup = NewAccountGroupClient(c.config)
c.Group = NewGroupClient(c.config) c.Group = NewGroupClient(c.config)
c.PromoCode = NewPromoCodeClient(c.config)
c.PromoCodeUsage = NewPromoCodeUsageClient(c.config)
c.Proxy = NewProxyClient(c.config) c.Proxy = NewProxyClient(c.config)
c.RedeemCode = NewRedeemCodeClient(c.config) c.RedeemCode = NewRedeemCodeClient(c.config)
c.Setting = NewSettingClient(c.config) c.Setting = NewSettingClient(c.config)
...@@ -183,6 +191,8 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { ...@@ -183,6 +191,8 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) {
Account: NewAccountClient(cfg), Account: NewAccountClient(cfg),
AccountGroup: NewAccountGroupClient(cfg), AccountGroup: NewAccountGroupClient(cfg),
Group: NewGroupClient(cfg), Group: NewGroupClient(cfg),
PromoCode: NewPromoCodeClient(cfg),
PromoCodeUsage: NewPromoCodeUsageClient(cfg),
Proxy: NewProxyClient(cfg), Proxy: NewProxyClient(cfg),
RedeemCode: NewRedeemCodeClient(cfg), RedeemCode: NewRedeemCodeClient(cfg),
Setting: NewSettingClient(cfg), Setting: NewSettingClient(cfg),
...@@ -215,6 +225,8 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) ...@@ -215,6 +225,8 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)
Account: NewAccountClient(cfg), Account: NewAccountClient(cfg),
AccountGroup: NewAccountGroupClient(cfg), AccountGroup: NewAccountGroupClient(cfg),
Group: NewGroupClient(cfg), Group: NewGroupClient(cfg),
PromoCode: NewPromoCodeClient(cfg),
PromoCodeUsage: NewPromoCodeUsageClient(cfg),
Proxy: NewProxyClient(cfg), Proxy: NewProxyClient(cfg),
RedeemCode: NewRedeemCodeClient(cfg), RedeemCode: NewRedeemCodeClient(cfg),
Setting: NewSettingClient(cfg), Setting: NewSettingClient(cfg),
...@@ -253,9 +265,9 @@ func (c *Client) Close() error { ...@@ -253,9 +265,9 @@ func (c *Client) Close() error {
// In order to add hooks to a specific client, call: `client.Node.Use(...)`. // In order to add hooks to a specific client, call: `client.Node.Use(...)`.
func (c *Client) Use(hooks ...Hook) { func (c *Client) Use(hooks ...Hook) {
for _, n := range []interface{ Use(...Hook) }{ for _, n := range []interface{ Use(...Hook) }{
c.APIKey, c.Account, c.AccountGroup, c.Group, c.Proxy, c.RedeemCode, c.Setting, c.APIKey, c.Account, c.AccountGroup, c.Group, c.PromoCode, c.PromoCodeUsage,
c.UsageLog, c.User, c.UserAllowedGroup, c.UserAttributeDefinition, c.Proxy, c.RedeemCode, c.Setting, c.UsageLog, c.User, c.UserAllowedGroup,
c.UserAttributeValue, c.UserSubscription, c.UserAttributeDefinition, c.UserAttributeValue, c.UserSubscription,
} { } {
n.Use(hooks...) n.Use(hooks...)
} }
...@@ -265,9 +277,9 @@ func (c *Client) Use(hooks ...Hook) { ...@@ -265,9 +277,9 @@ func (c *Client) Use(hooks ...Hook) {
// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`. // In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`.
func (c *Client) Intercept(interceptors ...Interceptor) { func (c *Client) Intercept(interceptors ...Interceptor) {
for _, n := range []interface{ Intercept(...Interceptor) }{ for _, n := range []interface{ Intercept(...Interceptor) }{
c.APIKey, c.Account, c.AccountGroup, c.Group, c.Proxy, c.RedeemCode, c.Setting, c.APIKey, c.Account, c.AccountGroup, c.Group, c.PromoCode, c.PromoCodeUsage,
c.UsageLog, c.User, c.UserAllowedGroup, c.UserAttributeDefinition, c.Proxy, c.RedeemCode, c.Setting, c.UsageLog, c.User, c.UserAllowedGroup,
c.UserAttributeValue, c.UserSubscription, c.UserAttributeDefinition, c.UserAttributeValue, c.UserSubscription,
} { } {
n.Intercept(interceptors...) n.Intercept(interceptors...)
} }
...@@ -284,6 +296,10 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { ...@@ -284,6 +296,10 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
return c.AccountGroup.mutate(ctx, m) return c.AccountGroup.mutate(ctx, m)
case *GroupMutation: case *GroupMutation:
return c.Group.mutate(ctx, m) return c.Group.mutate(ctx, m)
case *PromoCodeMutation:
return c.PromoCode.mutate(ctx, m)
case *PromoCodeUsageMutation:
return c.PromoCodeUsage.mutate(ctx, m)
case *ProxyMutation: case *ProxyMutation:
return c.Proxy.mutate(ctx, m) return c.Proxy.mutate(ctx, m)
case *RedeemCodeMutation: case *RedeemCodeMutation:
...@@ -1068,6 +1084,320 @@ func (c *GroupClient) mutate(ctx context.Context, m *GroupMutation) (Value, erro ...@@ -1068,6 +1084,320 @@ func (c *GroupClient) mutate(ctx context.Context, m *GroupMutation) (Value, erro
} }
} }
// PromoCodeClient is a client for the PromoCode schema.
type PromoCodeClient struct {
config
}
// NewPromoCodeClient returns a client for the PromoCode from the given config.
func NewPromoCodeClient(c config) *PromoCodeClient {
return &PromoCodeClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `promocode.Hooks(f(g(h())))`.
func (c *PromoCodeClient) Use(hooks ...Hook) {
c.hooks.PromoCode = append(c.hooks.PromoCode, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `promocode.Intercept(f(g(h())))`.
func (c *PromoCodeClient) Intercept(interceptors ...Interceptor) {
c.inters.PromoCode = append(c.inters.PromoCode, interceptors...)
}
// Create returns a builder for creating a PromoCode entity.
func (c *PromoCodeClient) Create() *PromoCodeCreate {
mutation := newPromoCodeMutation(c.config, OpCreate)
return &PromoCodeCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of PromoCode entities.
func (c *PromoCodeClient) CreateBulk(builders ...*PromoCodeCreate) *PromoCodeCreateBulk {
return &PromoCodeCreateBulk{config: c.config, builders: builders}
}
// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
// a builder and applies setFunc on it.
func (c *PromoCodeClient) MapCreateBulk(slice any, setFunc func(*PromoCodeCreate, int)) *PromoCodeCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &PromoCodeCreateBulk{err: fmt.Errorf("calling to PromoCodeClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*PromoCodeCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &PromoCodeCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for PromoCode.
func (c *PromoCodeClient) Update() *PromoCodeUpdate {
mutation := newPromoCodeMutation(c.config, OpUpdate)
return &PromoCodeUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *PromoCodeClient) UpdateOne(_m *PromoCode) *PromoCodeUpdateOne {
mutation := newPromoCodeMutation(c.config, OpUpdateOne, withPromoCode(_m))
return &PromoCodeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *PromoCodeClient) UpdateOneID(id int64) *PromoCodeUpdateOne {
mutation := newPromoCodeMutation(c.config, OpUpdateOne, withPromoCodeID(id))
return &PromoCodeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for PromoCode.
func (c *PromoCodeClient) Delete() *PromoCodeDelete {
mutation := newPromoCodeMutation(c.config, OpDelete)
return &PromoCodeDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *PromoCodeClient) DeleteOne(_m *PromoCode) *PromoCodeDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *PromoCodeClient) DeleteOneID(id int64) *PromoCodeDeleteOne {
builder := c.Delete().Where(promocode.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &PromoCodeDeleteOne{builder}
}
// Query returns a query builder for PromoCode.
func (c *PromoCodeClient) Query() *PromoCodeQuery {
return &PromoCodeQuery{
config: c.config,
ctx: &QueryContext{Type: TypePromoCode},
inters: c.Interceptors(),
}
}
// Get returns a PromoCode entity by its id.
func (c *PromoCodeClient) Get(ctx context.Context, id int64) (*PromoCode, error) {
return c.Query().Where(promocode.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *PromoCodeClient) GetX(ctx context.Context, id int64) *PromoCode {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryUsageRecords queries the usage_records edge of a PromoCode.
func (c *PromoCodeClient) QueryUsageRecords(_m *PromoCode) *PromoCodeUsageQuery {
query := (&PromoCodeUsageClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(promocode.Table, promocode.FieldID, id),
sqlgraph.To(promocodeusage.Table, promocodeusage.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, promocode.UsageRecordsTable, promocode.UsageRecordsColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *PromoCodeClient) Hooks() []Hook {
return c.hooks.PromoCode
}
// Interceptors returns the client interceptors.
func (c *PromoCodeClient) Interceptors() []Interceptor {
return c.inters.PromoCode
}
func (c *PromoCodeClient) mutate(ctx context.Context, m *PromoCodeMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&PromoCodeCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&PromoCodeUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&PromoCodeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&PromoCodeDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown PromoCode mutation op: %q", m.Op())
}
}
// PromoCodeUsageClient is a client for the PromoCodeUsage schema.
type PromoCodeUsageClient struct {
config
}
// NewPromoCodeUsageClient returns a client for the PromoCodeUsage from the given config.
func NewPromoCodeUsageClient(c config) *PromoCodeUsageClient {
return &PromoCodeUsageClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `promocodeusage.Hooks(f(g(h())))`.
func (c *PromoCodeUsageClient) Use(hooks ...Hook) {
c.hooks.PromoCodeUsage = append(c.hooks.PromoCodeUsage, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `promocodeusage.Intercept(f(g(h())))`.
func (c *PromoCodeUsageClient) Intercept(interceptors ...Interceptor) {
c.inters.PromoCodeUsage = append(c.inters.PromoCodeUsage, interceptors...)
}
// Create returns a builder for creating a PromoCodeUsage entity.
func (c *PromoCodeUsageClient) Create() *PromoCodeUsageCreate {
mutation := newPromoCodeUsageMutation(c.config, OpCreate)
return &PromoCodeUsageCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of PromoCodeUsage entities.
func (c *PromoCodeUsageClient) CreateBulk(builders ...*PromoCodeUsageCreate) *PromoCodeUsageCreateBulk {
return &PromoCodeUsageCreateBulk{config: c.config, builders: builders}
}
// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
// a builder and applies setFunc on it.
func (c *PromoCodeUsageClient) MapCreateBulk(slice any, setFunc func(*PromoCodeUsageCreate, int)) *PromoCodeUsageCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &PromoCodeUsageCreateBulk{err: fmt.Errorf("calling to PromoCodeUsageClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*PromoCodeUsageCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &PromoCodeUsageCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for PromoCodeUsage.
func (c *PromoCodeUsageClient) Update() *PromoCodeUsageUpdate {
mutation := newPromoCodeUsageMutation(c.config, OpUpdate)
return &PromoCodeUsageUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *PromoCodeUsageClient) UpdateOne(_m *PromoCodeUsage) *PromoCodeUsageUpdateOne {
mutation := newPromoCodeUsageMutation(c.config, OpUpdateOne, withPromoCodeUsage(_m))
return &PromoCodeUsageUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *PromoCodeUsageClient) UpdateOneID(id int64) *PromoCodeUsageUpdateOne {
mutation := newPromoCodeUsageMutation(c.config, OpUpdateOne, withPromoCodeUsageID(id))
return &PromoCodeUsageUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for PromoCodeUsage.
func (c *PromoCodeUsageClient) Delete() *PromoCodeUsageDelete {
mutation := newPromoCodeUsageMutation(c.config, OpDelete)
return &PromoCodeUsageDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *PromoCodeUsageClient) DeleteOne(_m *PromoCodeUsage) *PromoCodeUsageDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *PromoCodeUsageClient) DeleteOneID(id int64) *PromoCodeUsageDeleteOne {
builder := c.Delete().Where(promocodeusage.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &PromoCodeUsageDeleteOne{builder}
}
// Query returns a query builder for PromoCodeUsage.
func (c *PromoCodeUsageClient) Query() *PromoCodeUsageQuery {
return &PromoCodeUsageQuery{
config: c.config,
ctx: &QueryContext{Type: TypePromoCodeUsage},
inters: c.Interceptors(),
}
}
// Get returns a PromoCodeUsage entity by its id.
func (c *PromoCodeUsageClient) Get(ctx context.Context, id int64) (*PromoCodeUsage, error) {
return c.Query().Where(promocodeusage.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *PromoCodeUsageClient) GetX(ctx context.Context, id int64) *PromoCodeUsage {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryPromoCode queries the promo_code edge of a PromoCodeUsage.
func (c *PromoCodeUsageClient) QueryPromoCode(_m *PromoCodeUsage) *PromoCodeQuery {
query := (&PromoCodeClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(promocodeusage.Table, promocodeusage.FieldID, id),
sqlgraph.To(promocode.Table, promocode.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, promocodeusage.PromoCodeTable, promocodeusage.PromoCodeColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryUser queries the user edge of a PromoCodeUsage.
func (c *PromoCodeUsageClient) QueryUser(_m *PromoCodeUsage) *UserQuery {
query := (&UserClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(promocodeusage.Table, promocodeusage.FieldID, id),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, promocodeusage.UserTable, promocodeusage.UserColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *PromoCodeUsageClient) Hooks() []Hook {
return c.hooks.PromoCodeUsage
}
// Interceptors returns the client interceptors.
func (c *PromoCodeUsageClient) Interceptors() []Interceptor {
return c.inters.PromoCodeUsage
}
func (c *PromoCodeUsageClient) mutate(ctx context.Context, m *PromoCodeUsageMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&PromoCodeUsageCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&PromoCodeUsageUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&PromoCodeUsageUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&PromoCodeUsageDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown PromoCodeUsage mutation op: %q", m.Op())
}
}
// ProxyClient is a client for the Proxy schema. // ProxyClient is a client for the Proxy schema.
type ProxyClient struct { type ProxyClient struct {
config config
...@@ -1950,6 +2280,22 @@ func (c *UserClient) QueryAttributeValues(_m *User) *UserAttributeValueQuery { ...@@ -1950,6 +2280,22 @@ func (c *UserClient) QueryAttributeValues(_m *User) *UserAttributeValueQuery {
return query return query
} }
// QueryPromoCodeUsages queries the promo_code_usages edge of a User.
func (c *UserClient) QueryPromoCodeUsages(_m *User) *PromoCodeUsageQuery {
query := (&PromoCodeUsageClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(user.Table, user.FieldID, id),
sqlgraph.To(promocodeusage.Table, promocodeusage.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, user.PromoCodeUsagesTable, user.PromoCodeUsagesColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryUserAllowedGroups queries the user_allowed_groups edge of a User. // QueryUserAllowedGroups queries the user_allowed_groups edge of a User.
func (c *UserClient) QueryUserAllowedGroups(_m *User) *UserAllowedGroupQuery { func (c *UserClient) QueryUserAllowedGroups(_m *User) *UserAllowedGroupQuery {
query := (&UserAllowedGroupClient{config: c.config}).Query() query := (&UserAllowedGroupClient{config: c.config}).Query()
...@@ -2627,14 +2973,14 @@ func (c *UserSubscriptionClient) mutate(ctx context.Context, m *UserSubscription ...@@ -2627,14 +2973,14 @@ func (c *UserSubscriptionClient) mutate(ctx context.Context, m *UserSubscription
// hooks and interceptors per client, for fast access. // hooks and interceptors per client, for fast access.
type ( type (
hooks struct { hooks struct {
APIKey, Account, AccountGroup, Group, Proxy, RedeemCode, Setting, UsageLog, APIKey, Account, AccountGroup, Group, PromoCode, PromoCodeUsage, Proxy,
User, UserAllowedGroup, UserAttributeDefinition, UserAttributeValue, RedeemCode, Setting, UsageLog, User, UserAllowedGroup, UserAttributeDefinition,
UserSubscription []ent.Hook UserAttributeValue, UserSubscription []ent.Hook
} }
inters struct { inters struct {
APIKey, Account, AccountGroup, Group, Proxy, RedeemCode, Setting, UsageLog, APIKey, Account, AccountGroup, Group, PromoCode, PromoCodeUsage, Proxy,
User, UserAllowedGroup, UserAttributeDefinition, UserAttributeValue, RedeemCode, Setting, UsageLog, User, UserAllowedGroup, UserAttributeDefinition,
UserSubscription []ent.Interceptor UserAttributeValue, UserSubscription []ent.Interceptor
} }
) )
......
...@@ -16,6 +16,8 @@ import ( ...@@ -16,6 +16,8 @@ import (
"github.com/Wei-Shaw/sub2api/ent/accountgroup" "github.com/Wei-Shaw/sub2api/ent/accountgroup"
"github.com/Wei-Shaw/sub2api/ent/apikey" "github.com/Wei-Shaw/sub2api/ent/apikey"
"github.com/Wei-Shaw/sub2api/ent/group" "github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/promocode"
"github.com/Wei-Shaw/sub2api/ent/promocodeusage"
"github.com/Wei-Shaw/sub2api/ent/proxy" "github.com/Wei-Shaw/sub2api/ent/proxy"
"github.com/Wei-Shaw/sub2api/ent/redeemcode" "github.com/Wei-Shaw/sub2api/ent/redeemcode"
"github.com/Wei-Shaw/sub2api/ent/setting" "github.com/Wei-Shaw/sub2api/ent/setting"
...@@ -89,6 +91,8 @@ func checkColumn(t, c string) error { ...@@ -89,6 +91,8 @@ func checkColumn(t, c string) error {
account.Table: account.ValidColumn, account.Table: account.ValidColumn,
accountgroup.Table: accountgroup.ValidColumn, accountgroup.Table: accountgroup.ValidColumn,
group.Table: group.ValidColumn, group.Table: group.ValidColumn,
promocode.Table: promocode.ValidColumn,
promocodeusage.Table: promocodeusage.ValidColumn,
proxy.Table: proxy.ValidColumn, proxy.Table: proxy.ValidColumn,
redeemcode.Table: redeemcode.ValidColumn, redeemcode.Table: redeemcode.ValidColumn,
setting.Table: setting.ValidColumn, setting.Table: setting.ValidColumn,
......
...@@ -2,4 +2,5 @@ ...@@ -2,4 +2,5 @@
package ent package ent
// 启用 sql/execquery 以生成 ExecContext/QueryContext 的透传接口,便于事务内执行原生 SQL。 // 启用 sql/execquery 以生成 ExecContext/QueryContext 的透传接口,便于事务内执行原生 SQL。
//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate --feature sql/upsert,intercept,sql/execquery --idtype int64 ./schema // 启用 sql/lock 以支持 FOR UPDATE 行锁。
//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate --feature sql/upsert,intercept,sql/execquery,sql/lock --idtype int64 ./schema
...@@ -9,6 +9,7 @@ import ( ...@@ -9,6 +9,7 @@ import (
"math" "math"
"entgo.io/ent" "entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field" "entgo.io/ent/schema/field"
...@@ -39,6 +40,7 @@ type GroupQuery struct { ...@@ -39,6 +40,7 @@ type GroupQuery struct {
withAllowedUsers *UserQuery withAllowedUsers *UserQuery
withAccountGroups *AccountGroupQuery withAccountGroups *AccountGroupQuery
withUserAllowedGroups *UserAllowedGroupQuery withUserAllowedGroups *UserAllowedGroupQuery
modifiers []func(*sql.Selector)
// intermediate query (i.e. traversal path). // intermediate query (i.e. traversal path).
sql *sql.Selector sql *sql.Selector
path func(context.Context) (*sql.Selector, error) path func(context.Context) (*sql.Selector, error)
...@@ -643,6 +645,9 @@ func (_q *GroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Group, ...@@ -643,6 +645,9 @@ func (_q *GroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Group,
node.Edges.loadedTypes = loadedTypes node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values) return node.assignValues(columns, values)
} }
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
for i := range hooks { for i := range hooks {
hooks[i](ctx, _spec) hooks[i](ctx, _spec)
} }
...@@ -1025,6 +1030,9 @@ func (_q *GroupQuery) loadUserAllowedGroups(ctx context.Context, query *UserAllo ...@@ -1025,6 +1030,9 @@ func (_q *GroupQuery) loadUserAllowedGroups(ctx context.Context, query *UserAllo
func (_q *GroupQuery) sqlCount(ctx context.Context) (int, error) { func (_q *GroupQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec() _spec := _q.querySpec()
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
_spec.Node.Columns = _q.ctx.Fields _spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 { if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
...@@ -1087,6 +1095,9 @@ func (_q *GroupQuery) sqlQuery(ctx context.Context) *sql.Selector { ...@@ -1087,6 +1095,9 @@ func (_q *GroupQuery) sqlQuery(ctx context.Context) *sql.Selector {
if _q.ctx.Unique != nil && *_q.ctx.Unique { if _q.ctx.Unique != nil && *_q.ctx.Unique {
selector.Distinct() selector.Distinct()
} }
for _, m := range _q.modifiers {
m(selector)
}
for _, p := range _q.predicates { for _, p := range _q.predicates {
p(selector) p(selector)
} }
...@@ -1104,6 +1115,32 @@ func (_q *GroupQuery) sqlQuery(ctx context.Context) *sql.Selector { ...@@ -1104,6 +1115,32 @@ func (_q *GroupQuery) sqlQuery(ctx context.Context) *sql.Selector {
return selector return selector
} }
// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
// updated, deleted or "selected ... for update" by other sessions, until the transaction is
// either committed or rolled-back.
func (_q *GroupQuery) ForUpdate(opts ...sql.LockOption) *GroupQuery {
if _q.driver.Dialect() == dialect.Postgres {
_q.Unique(false)
}
_q.modifiers = append(_q.modifiers, func(s *sql.Selector) {
s.ForUpdate(opts...)
})
return _q
}
// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
// on any rows that are read. Other sessions can read the rows, but cannot modify them
// until your transaction commits.
func (_q *GroupQuery) ForShare(opts ...sql.LockOption) *GroupQuery {
if _q.driver.Dialect() == dialect.Postgres {
_q.Unique(false)
}
_q.modifiers = append(_q.modifiers, func(s *sql.Selector) {
s.ForShare(opts...)
})
return _q
}
// GroupGroupBy is the group-by builder for Group entities. // GroupGroupBy is the group-by builder for Group entities.
type GroupGroupBy struct { type GroupGroupBy struct {
selector selector
......
...@@ -57,6 +57,30 @@ func (f GroupFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error ...@@ -57,6 +57,30 @@ func (f GroupFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.GroupMutation", m) return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.GroupMutation", m)
} }
// The PromoCodeFunc type is an adapter to allow the use of ordinary
// function as PromoCode mutator.
type PromoCodeFunc func(context.Context, *ent.PromoCodeMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f PromoCodeFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.PromoCodeMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.PromoCodeMutation", m)
}
// The PromoCodeUsageFunc type is an adapter to allow the use of ordinary
// function as PromoCodeUsage mutator.
type PromoCodeUsageFunc func(context.Context, *ent.PromoCodeUsageMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f PromoCodeUsageFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.PromoCodeUsageMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.PromoCodeUsageMutation", m)
}
// The ProxyFunc type is an adapter to allow the use of ordinary // The ProxyFunc type is an adapter to allow the use of ordinary
// function as Proxy mutator. // function as Proxy mutator.
type ProxyFunc func(context.Context, *ent.ProxyMutation) (ent.Value, error) type ProxyFunc func(context.Context, *ent.ProxyMutation) (ent.Value, error)
......
...@@ -13,6 +13,8 @@ import ( ...@@ -13,6 +13,8 @@ import (
"github.com/Wei-Shaw/sub2api/ent/apikey" "github.com/Wei-Shaw/sub2api/ent/apikey"
"github.com/Wei-Shaw/sub2api/ent/group" "github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/predicate" "github.com/Wei-Shaw/sub2api/ent/predicate"
"github.com/Wei-Shaw/sub2api/ent/promocode"
"github.com/Wei-Shaw/sub2api/ent/promocodeusage"
"github.com/Wei-Shaw/sub2api/ent/proxy" "github.com/Wei-Shaw/sub2api/ent/proxy"
"github.com/Wei-Shaw/sub2api/ent/redeemcode" "github.com/Wei-Shaw/sub2api/ent/redeemcode"
"github.com/Wei-Shaw/sub2api/ent/setting" "github.com/Wei-Shaw/sub2api/ent/setting"
...@@ -188,6 +190,60 @@ func (f TraverseGroup) Traverse(ctx context.Context, q ent.Query) error { ...@@ -188,6 +190,60 @@ func (f TraverseGroup) Traverse(ctx context.Context, q ent.Query) error {
return fmt.Errorf("unexpected query type %T. expect *ent.GroupQuery", q) return fmt.Errorf("unexpected query type %T. expect *ent.GroupQuery", q)
} }
// The PromoCodeFunc type is an adapter to allow the use of ordinary function as a Querier.
type PromoCodeFunc func(context.Context, *ent.PromoCodeQuery) (ent.Value, error)
// Query calls f(ctx, q).
func (f PromoCodeFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) {
if q, ok := q.(*ent.PromoCodeQuery); ok {
return f(ctx, q)
}
return nil, fmt.Errorf("unexpected query type %T. expect *ent.PromoCodeQuery", q)
}
// The TraversePromoCode type is an adapter to allow the use of ordinary function as Traverser.
type TraversePromoCode func(context.Context, *ent.PromoCodeQuery) error
// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
func (f TraversePromoCode) Intercept(next ent.Querier) ent.Querier {
return next
}
// Traverse calls f(ctx, q).
func (f TraversePromoCode) Traverse(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.PromoCodeQuery); ok {
return f(ctx, q)
}
return fmt.Errorf("unexpected query type %T. expect *ent.PromoCodeQuery", q)
}
// The PromoCodeUsageFunc type is an adapter to allow the use of ordinary function as a Querier.
type PromoCodeUsageFunc func(context.Context, *ent.PromoCodeUsageQuery) (ent.Value, error)
// Query calls f(ctx, q).
func (f PromoCodeUsageFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) {
if q, ok := q.(*ent.PromoCodeUsageQuery); ok {
return f(ctx, q)
}
return nil, fmt.Errorf("unexpected query type %T. expect *ent.PromoCodeUsageQuery", q)
}
// The TraversePromoCodeUsage type is an adapter to allow the use of ordinary function as Traverser.
type TraversePromoCodeUsage func(context.Context, *ent.PromoCodeUsageQuery) error
// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
func (f TraversePromoCodeUsage) Intercept(next ent.Querier) ent.Querier {
return next
}
// Traverse calls f(ctx, q).
func (f TraversePromoCodeUsage) Traverse(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.PromoCodeUsageQuery); ok {
return f(ctx, q)
}
return fmt.Errorf("unexpected query type %T. expect *ent.PromoCodeUsageQuery", q)
}
// The ProxyFunc type is an adapter to allow the use of ordinary function as a Querier. // The ProxyFunc type is an adapter to allow the use of ordinary function as a Querier.
type ProxyFunc func(context.Context, *ent.ProxyQuery) (ent.Value, error) type ProxyFunc func(context.Context, *ent.ProxyQuery) (ent.Value, error)
...@@ -442,6 +498,10 @@ func NewQuery(q ent.Query) (Query, error) { ...@@ -442,6 +498,10 @@ func NewQuery(q ent.Query) (Query, error) {
return &query[*ent.AccountGroupQuery, predicate.AccountGroup, accountgroup.OrderOption]{typ: ent.TypeAccountGroup, tq: q}, nil return &query[*ent.AccountGroupQuery, predicate.AccountGroup, accountgroup.OrderOption]{typ: ent.TypeAccountGroup, tq: q}, nil
case *ent.GroupQuery: case *ent.GroupQuery:
return &query[*ent.GroupQuery, predicate.Group, group.OrderOption]{typ: ent.TypeGroup, tq: q}, nil return &query[*ent.GroupQuery, predicate.Group, group.OrderOption]{typ: ent.TypeGroup, tq: q}, nil
case *ent.PromoCodeQuery:
return &query[*ent.PromoCodeQuery, predicate.PromoCode, promocode.OrderOption]{typ: ent.TypePromoCode, tq: q}, nil
case *ent.PromoCodeUsageQuery:
return &query[*ent.PromoCodeUsageQuery, predicate.PromoCodeUsage, promocodeusage.OrderOption]{typ: ent.TypePromoCodeUsage, tq: q}, nil
case *ent.ProxyQuery: case *ent.ProxyQuery:
return &query[*ent.ProxyQuery, predicate.Proxy, proxy.OrderOption]{typ: ent.TypeProxy, tq: q}, nil return &query[*ent.ProxyQuery, predicate.Proxy, proxy.OrderOption]{typ: ent.TypeProxy, tq: q}, nil
case *ent.RedeemCodeQuery: case *ent.RedeemCodeQuery:
......
...@@ -259,6 +259,82 @@ var ( ...@@ -259,6 +259,82 @@ var (
}, },
}, },
} }
// PromoCodesColumns holds the columns for the "promo_codes" table.
PromoCodesColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt64, Increment: true},
{Name: "code", Type: field.TypeString, Unique: true, Size: 32},
{Name: "bonus_amount", Type: field.TypeFloat64, Default: 0, SchemaType: map[string]string{"postgres": "decimal(20,8)"}},
{Name: "max_uses", Type: field.TypeInt, Default: 0},
{Name: "used_count", Type: field.TypeInt, Default: 0},
{Name: "status", Type: field.TypeString, Size: 20, Default: "active"},
{Name: "expires_at", Type: field.TypeTime, Nullable: true, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "notes", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "text"}},
{Name: "created_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "updated_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}},
}
// PromoCodesTable holds the schema information for the "promo_codes" table.
PromoCodesTable = &schema.Table{
Name: "promo_codes",
Columns: PromoCodesColumns,
PrimaryKey: []*schema.Column{PromoCodesColumns[0]},
Indexes: []*schema.Index{
{
Name: "promocode_status",
Unique: false,
Columns: []*schema.Column{PromoCodesColumns[5]},
},
{
Name: "promocode_expires_at",
Unique: false,
Columns: []*schema.Column{PromoCodesColumns[6]},
},
},
}
// PromoCodeUsagesColumns holds the columns for the "promo_code_usages" table.
PromoCodeUsagesColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt64, Increment: true},
{Name: "bonus_amount", Type: field.TypeFloat64, SchemaType: map[string]string{"postgres": "decimal(20,8)"}},
{Name: "used_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "promo_code_id", Type: field.TypeInt64},
{Name: "user_id", Type: field.TypeInt64},
}
// PromoCodeUsagesTable holds the schema information for the "promo_code_usages" table.
PromoCodeUsagesTable = &schema.Table{
Name: "promo_code_usages",
Columns: PromoCodeUsagesColumns,
PrimaryKey: []*schema.Column{PromoCodeUsagesColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "promo_code_usages_promo_codes_usage_records",
Columns: []*schema.Column{PromoCodeUsagesColumns[3]},
RefColumns: []*schema.Column{PromoCodesColumns[0]},
OnDelete: schema.NoAction,
},
{
Symbol: "promo_code_usages_users_promo_code_usages",
Columns: []*schema.Column{PromoCodeUsagesColumns[4]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.NoAction,
},
},
Indexes: []*schema.Index{
{
Name: "promocodeusage_promo_code_id",
Unique: false,
Columns: []*schema.Column{PromoCodeUsagesColumns[3]},
},
{
Name: "promocodeusage_user_id",
Unique: false,
Columns: []*schema.Column{PromoCodeUsagesColumns[4]},
},
{
Name: "promocodeusage_promo_code_id_user_id",
Unique: true,
Columns: []*schema.Column{PromoCodeUsagesColumns[3], PromoCodeUsagesColumns[4]},
},
},
}
// ProxiesColumns holds the columns for the "proxies" table. // ProxiesColumns holds the columns for the "proxies" table.
ProxiesColumns = []*schema.Column{ ProxiesColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt64, Increment: true}, {Name: "id", Type: field.TypeInt64, Increment: true},
...@@ -720,6 +796,8 @@ var ( ...@@ -720,6 +796,8 @@ var (
AccountsTable, AccountsTable,
AccountGroupsTable, AccountGroupsTable,
GroupsTable, GroupsTable,
PromoCodesTable,
PromoCodeUsagesTable,
ProxiesTable, ProxiesTable,
RedeemCodesTable, RedeemCodesTable,
SettingsTable, SettingsTable,
...@@ -750,6 +828,14 @@ func init() { ...@@ -750,6 +828,14 @@ func init() {
GroupsTable.Annotation = &entsql.Annotation{ GroupsTable.Annotation = &entsql.Annotation{
Table: "groups", Table: "groups",
} }
PromoCodesTable.Annotation = &entsql.Annotation{
Table: "promo_codes",
}
PromoCodeUsagesTable.ForeignKeys[0].RefTable = PromoCodesTable
PromoCodeUsagesTable.ForeignKeys[1].RefTable = UsersTable
PromoCodeUsagesTable.Annotation = &entsql.Annotation{
Table: "promo_code_usages",
}
ProxiesTable.Annotation = &entsql.Annotation{ ProxiesTable.Annotation = &entsql.Annotation{
Table: "proxies", Table: "proxies",
} }
......
This diff is collapsed.
...@@ -18,6 +18,12 @@ type AccountGroup func(*sql.Selector) ...@@ -18,6 +18,12 @@ type AccountGroup func(*sql.Selector)
// Group is the predicate function for group builders. // Group is the predicate function for group builders.
type Group func(*sql.Selector) type Group func(*sql.Selector)
// PromoCode is the predicate function for promocode builders.
type PromoCode func(*sql.Selector)
// PromoCodeUsage is the predicate function for promocodeusage builders.
type PromoCodeUsage func(*sql.Selector)
// Proxy is the predicate function for proxy builders. // Proxy is the predicate function for proxy builders.
type Proxy func(*sql.Selector) type Proxy func(*sql.Selector)
......
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"github.com/Wei-Shaw/sub2api/ent/promocode"
)
// PromoCode is the model entity for the PromoCode schema.
type PromoCode struct {
config `json:"-"`
// ID of the ent.
ID int64 `json:"id,omitempty"`
// 优惠码
Code string `json:"code,omitempty"`
// 赠送余额金额
BonusAmount float64 `json:"bonus_amount,omitempty"`
// 最大使用次数,0表示无限制
MaxUses int `json:"max_uses,omitempty"`
// 已使用次数
UsedCount int `json:"used_count,omitempty"`
// 状态: active, disabled
Status string `json:"status,omitempty"`
// 过期时间,null表示永不过期
ExpiresAt *time.Time `json:"expires_at,omitempty"`
// 备注
Notes *string `json:"notes,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt time.Time `json:"created_at,omitempty"`
// UpdatedAt holds the value of the "updated_at" field.
UpdatedAt time.Time `json:"updated_at,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the PromoCodeQuery when eager-loading is set.
Edges PromoCodeEdges `json:"edges"`
selectValues sql.SelectValues
}
// PromoCodeEdges holds the relations/edges for other nodes in the graph.
type PromoCodeEdges struct {
// UsageRecords holds the value of the usage_records edge.
UsageRecords []*PromoCodeUsage `json:"usage_records,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [1]bool
}
// UsageRecordsOrErr returns the UsageRecords value or an error if the edge
// was not loaded in eager-loading.
func (e PromoCodeEdges) UsageRecordsOrErr() ([]*PromoCodeUsage, error) {
if e.loadedTypes[0] {
return e.UsageRecords, nil
}
return nil, &NotLoadedError{edge: "usage_records"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*PromoCode) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case promocode.FieldBonusAmount:
values[i] = new(sql.NullFloat64)
case promocode.FieldID, promocode.FieldMaxUses, promocode.FieldUsedCount:
values[i] = new(sql.NullInt64)
case promocode.FieldCode, promocode.FieldStatus, promocode.FieldNotes:
values[i] = new(sql.NullString)
case promocode.FieldExpiresAt, promocode.FieldCreatedAt, promocode.FieldUpdatedAt:
values[i] = new(sql.NullTime)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the PromoCode fields.
func (_m *PromoCode) assignValues(columns []string, values []any) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case promocode.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
_m.ID = int64(value.Int64)
case promocode.FieldCode:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field code", values[i])
} else if value.Valid {
_m.Code = value.String
}
case promocode.FieldBonusAmount:
if value, ok := values[i].(*sql.NullFloat64); !ok {
return fmt.Errorf("unexpected type %T for field bonus_amount", values[i])
} else if value.Valid {
_m.BonusAmount = value.Float64
}
case promocode.FieldMaxUses:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field max_uses", values[i])
} else if value.Valid {
_m.MaxUses = int(value.Int64)
}
case promocode.FieldUsedCount:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field used_count", values[i])
} else if value.Valid {
_m.UsedCount = int(value.Int64)
}
case promocode.FieldStatus:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field status", values[i])
} else if value.Valid {
_m.Status = value.String
}
case promocode.FieldExpiresAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field expires_at", values[i])
} else if value.Valid {
_m.ExpiresAt = new(time.Time)
*_m.ExpiresAt = value.Time
}
case promocode.FieldNotes:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field notes", values[i])
} else if value.Valid {
_m.Notes = new(string)
*_m.Notes = value.String
}
case promocode.FieldCreatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field created_at", values[i])
} else if value.Valid {
_m.CreatedAt = value.Time
}
case promocode.FieldUpdatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field updated_at", values[i])
} else if value.Valid {
_m.UpdatedAt = value.Time
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the PromoCode.
// This includes values selected through modifiers, order, etc.
func (_m *PromoCode) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// QueryUsageRecords queries the "usage_records" edge of the PromoCode entity.
func (_m *PromoCode) QueryUsageRecords() *PromoCodeUsageQuery {
return NewPromoCodeClient(_m.config).QueryUsageRecords(_m)
}
// Update returns a builder for updating this PromoCode.
// Note that you need to call PromoCode.Unwrap() before calling this method if this PromoCode
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *PromoCode) Update() *PromoCodeUpdateOne {
return NewPromoCodeClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the PromoCode entity that was returned from a transaction after it was closed,
// so that all future queries will be executed through the driver which created the transaction.
func (_m *PromoCode) Unwrap() *PromoCode {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: PromoCode is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *PromoCode) String() string {
var builder strings.Builder
builder.WriteString("PromoCode(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("code=")
builder.WriteString(_m.Code)
builder.WriteString(", ")
builder.WriteString("bonus_amount=")
builder.WriteString(fmt.Sprintf("%v", _m.BonusAmount))
builder.WriteString(", ")
builder.WriteString("max_uses=")
builder.WriteString(fmt.Sprintf("%v", _m.MaxUses))
builder.WriteString(", ")
builder.WriteString("used_count=")
builder.WriteString(fmt.Sprintf("%v", _m.UsedCount))
builder.WriteString(", ")
builder.WriteString("status=")
builder.WriteString(_m.Status)
builder.WriteString(", ")
if v := _m.ExpiresAt; v != nil {
builder.WriteString("expires_at=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString(", ")
if v := _m.Notes; v != nil {
builder.WriteString("notes=")
builder.WriteString(*v)
}
builder.WriteString(", ")
builder.WriteString("created_at=")
builder.WriteString(_m.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(_m.UpdatedAt.Format(time.ANSIC))
builder.WriteByte(')')
return builder.String()
}
// PromoCodes is a parsable slice of PromoCode.
type PromoCodes []*PromoCode
// Code generated by ent, DO NOT EDIT.
package promocode
import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the promocode type in the database.
Label = "promo_code"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldCode holds the string denoting the code field in the database.
FieldCode = "code"
// FieldBonusAmount holds the string denoting the bonus_amount field in the database.
FieldBonusAmount = "bonus_amount"
// FieldMaxUses holds the string denoting the max_uses field in the database.
FieldMaxUses = "max_uses"
// FieldUsedCount holds the string denoting the used_count field in the database.
FieldUsedCount = "used_count"
// FieldStatus holds the string denoting the status field in the database.
FieldStatus = "status"
// FieldExpiresAt holds the string denoting the expires_at field in the database.
FieldExpiresAt = "expires_at"
// FieldNotes holds the string denoting the notes field in the database.
FieldNotes = "notes"
// FieldCreatedAt holds the string denoting the created_at field in the database.
FieldCreatedAt = "created_at"
// FieldUpdatedAt holds the string denoting the updated_at field in the database.
FieldUpdatedAt = "updated_at"
// EdgeUsageRecords holds the string denoting the usage_records edge name in mutations.
EdgeUsageRecords = "usage_records"
// Table holds the table name of the promocode in the database.
Table = "promo_codes"
// UsageRecordsTable is the table that holds the usage_records relation/edge.
UsageRecordsTable = "promo_code_usages"
// UsageRecordsInverseTable is the table name for the PromoCodeUsage entity.
// It exists in this package in order to avoid circular dependency with the "promocodeusage" package.
UsageRecordsInverseTable = "promo_code_usages"
// UsageRecordsColumn is the table column denoting the usage_records relation/edge.
UsageRecordsColumn = "promo_code_id"
)
// Columns holds all SQL columns for promocode fields.
var Columns = []string{
FieldID,
FieldCode,
FieldBonusAmount,
FieldMaxUses,
FieldUsedCount,
FieldStatus,
FieldExpiresAt,
FieldNotes,
FieldCreatedAt,
FieldUpdatedAt,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// CodeValidator is a validator for the "code" field. It is called by the builders before save.
CodeValidator func(string) error
// DefaultBonusAmount holds the default value on creation for the "bonus_amount" field.
DefaultBonusAmount float64
// DefaultMaxUses holds the default value on creation for the "max_uses" field.
DefaultMaxUses int
// DefaultUsedCount holds the default value on creation for the "used_count" field.
DefaultUsedCount int
// DefaultStatus holds the default value on creation for the "status" field.
DefaultStatus string
// StatusValidator is a validator for the "status" field. It is called by the builders before save.
StatusValidator func(string) error
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() time.Time
// UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
UpdateDefaultUpdatedAt func() time.Time
)
// OrderOption defines the ordering options for the PromoCode queries.
type OrderOption func(*sql.Selector)
// ByID orders the results by the id field.
func ByID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldID, opts...).ToFunc()
}
// ByCode orders the results by the code field.
func ByCode(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCode, opts...).ToFunc()
}
// ByBonusAmount orders the results by the bonus_amount field.
func ByBonusAmount(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldBonusAmount, opts...).ToFunc()
}
// ByMaxUses orders the results by the max_uses field.
func ByMaxUses(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldMaxUses, opts...).ToFunc()
}
// ByUsedCount orders the results by the used_count field.
func ByUsedCount(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUsedCount, opts...).ToFunc()
}
// ByStatus orders the results by the status field.
func ByStatus(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldStatus, opts...).ToFunc()
}
// ByExpiresAt orders the results by the expires_at field.
func ByExpiresAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldExpiresAt, opts...).ToFunc()
}
// ByNotes orders the results by the notes field.
func ByNotes(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldNotes, opts...).ToFunc()
}
// ByCreatedAt orders the results by the created_at field.
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
}
// ByUpdatedAt orders the results by the updated_at field.
func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()
}
// ByUsageRecordsCount orders the results by usage_records count.
func ByUsageRecordsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newUsageRecordsStep(), opts...)
}
}
// ByUsageRecords orders the results by usage_records terms.
func ByUsageRecords(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newUsageRecordsStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
func newUsageRecordsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(UsageRecordsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, UsageRecordsTable, UsageRecordsColumn),
)
}
This diff is collapsed.
This diff is collapsed.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/Wei-Shaw/sub2api/ent/predicate"
"github.com/Wei-Shaw/sub2api/ent/promocode"
)
// PromoCodeDelete is the builder for deleting a PromoCode entity.
type PromoCodeDelete struct {
config
hooks []Hook
mutation *PromoCodeMutation
}
// Where appends a list predicates to the PromoCodeDelete builder.
func (_d *PromoCodeDelete) Where(ps ...predicate.PromoCode) *PromoCodeDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *PromoCodeDelete) Exec(ctx context.Context) (int, error) {
return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks)
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *PromoCodeDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *PromoCodeDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(promocode.Table, sqlgraph.NewFieldSpec(promocode.FieldID, field.TypeInt64))
if ps := _d.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
_d.mutation.done = true
return affected, err
}
// PromoCodeDeleteOne is the builder for deleting a single PromoCode entity.
type PromoCodeDeleteOne struct {
_d *PromoCodeDelete
}
// Where appends a list predicates to the PromoCodeDelete builder.
func (_d *PromoCodeDeleteOne) Where(ps ...predicate.PromoCode) *PromoCodeDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *PromoCodeDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{promocode.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *PromoCodeDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}
This diff is collapsed.
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment