diff --git a/backend/cmd/jwtgen/main.go b/backend/cmd/jwtgen/main.go index bc0016939..e7f1afa7c 100644 --- a/backend/cmd/jwtgen/main.go +++ b/backend/cmd/jwtgen/main.go @@ -33,7 +33,7 @@ func main() { }() userRepo := repository.NewUserRepository(client, sqlDB) - authService := service.NewAuthService(userRepo, nil, nil, cfg, nil, nil, nil, nil, nil, nil) + authService := service.NewAuthService(userRepo, nil, nil, cfg, nil, nil, nil, nil, nil, nil, nil) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go index 8e7aefe1a..80e5cd63f 100644 --- a/backend/cmd/server/wire_gen.go +++ b/backend/cmd/server/wire_gen.go @@ -67,7 +67,9 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { apiKeyAuthCacheInvalidator := service.ProvideAPIKeyAuthCacheInvalidator(apiKeyService) promoService := service.NewPromoService(promoCodeRepository, userRepository, billingCacheService, client, apiKeyAuthCacheInvalidator) subscriptionService := service.NewSubscriptionService(groupRepository, userSubscriptionRepository, billingCacheService, client, configConfig) - authService := service.NewAuthService(userRepository, redeemCodeRepository, refreshTokenCache, configConfig, settingService, emailService, turnstileService, emailQueueService, promoService, subscriptionService) + referralRepository := repository.NewReferralRepository(client) + referralService := service.NewReferralService(referralRepository, userRepository, settingService, billingCacheService, client) + authService := service.NewAuthService(userRepository, redeemCodeRepository, refreshTokenCache, configConfig, settingService, emailService, turnstileService, emailQueueService, promoService, referralService, subscriptionService) userService := service.NewUserService(userRepository, apiKeyAuthCacheInvalidator, billingCache) redeemCache := repository.NewRedeemCache(redisClient) redeemService := service.NewRedeemService(redeemCodeRepository, userRepository, subscriptionService, redeemCache, billingCacheService, client, apiKeyAuthCacheInvalidator) @@ -195,7 +197,8 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { errorPassthroughService := service.NewErrorPassthroughService(errorPassthroughRepository, errorPassthroughCache) errorPassthroughHandler := admin.NewErrorPassthroughHandler(errorPassthroughService) adminAPIKeyHandler := admin.NewAdminAPIKeyHandler(adminService) - adminHandlers := handler.ProvideAdminHandlers(dashboardHandler, adminUserHandler, groupHandler, accountHandler, adminAnnouncementHandler, dataManagementHandler, oAuthHandler, openAIOAuthHandler, geminiOAuthHandler, antigravityOAuthHandler, proxyHandler, adminRedeemHandler, promoHandler, settingHandler, opsHandler, systemHandler, adminSubscriptionHandler, adminUsageHandler, userAttributeHandler, errorPassthroughHandler, adminAPIKeyHandler) + adminReferralHandler := admin.NewReferralHandler(referralService) + adminHandlers := handler.ProvideAdminHandlers(dashboardHandler, adminUserHandler, groupHandler, accountHandler, adminAnnouncementHandler, dataManagementHandler, oAuthHandler, openAIOAuthHandler, geminiOAuthHandler, antigravityOAuthHandler, proxyHandler, adminRedeemHandler, promoHandler, settingHandler, opsHandler, systemHandler, adminSubscriptionHandler, adminUsageHandler, userAttributeHandler, errorPassthroughHandler, adminAPIKeyHandler, adminReferralHandler) usageRecordWorkerPool := service.NewUsageRecordWorkerPool(configConfig) userMsgQueueCache := repository.NewUserMsgQueueCache(redisClient) userMessageQueueService := service.ProvideUserMessageQueueService(userMsgQueueCache, rpmCache, configConfig) @@ -208,9 +211,10 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { soraGatewayHandler := handler.NewSoraGatewayHandler(gatewayService, soraGatewayService, concurrencyService, billingCacheService, usageRecordWorkerPool, configConfig) handlerSettingHandler := handler.ProvideSettingHandler(settingService, buildInfo) totpHandler := handler.NewTotpHandler(totpService) + referralHandler := handler.NewReferralHandler(referralService) idempotencyCoordinator := service.ProvideIdempotencyCoordinator(idempotencyRepository, configConfig) idempotencyCleanupService := service.ProvideIdempotencyCleanupService(idempotencyRepository, configConfig) - handlers := handler.ProvideHandlers(authHandler, userHandler, apiKeyHandler, usageHandler, redeemHandler, subscriptionHandler, announcementHandler, adminHandlers, gatewayHandler, openAIGatewayHandler, soraGatewayHandler, soraClientHandler, handlerSettingHandler, totpHandler, idempotencyCoordinator, idempotencyCleanupService) + handlers := handler.ProvideHandlers(authHandler, userHandler, apiKeyHandler, usageHandler, redeemHandler, subscriptionHandler, announcementHandler, adminHandlers, gatewayHandler, openAIGatewayHandler, soraGatewayHandler, soraClientHandler, handlerSettingHandler, totpHandler, referralHandler, idempotencyCoordinator, idempotencyCleanupService) jwtAuthMiddleware := middleware.NewJWTAuthMiddleware(authService, userService) adminAuthMiddleware := middleware.NewAdminAuthMiddleware(authService, userService, settingService) apiKeyAuthMiddleware := middleware.NewAPIKeyAuthMiddleware(apiKeyService, subscriptionService, configConfig) diff --git a/backend/ent/client.go b/backend/ent/client.go index 7ebbaa322..716c0dbaa 100644 --- a/backend/ent/client.go +++ b/backend/ent/client.go @@ -27,6 +27,7 @@ import ( "github.com/Wei-Shaw/sub2api/ent/promocodeusage" "github.com/Wei-Shaw/sub2api/ent/proxy" "github.com/Wei-Shaw/sub2api/ent/redeemcode" + "github.com/Wei-Shaw/sub2api/ent/referralrelation" "github.com/Wei-Shaw/sub2api/ent/securitysecret" "github.com/Wei-Shaw/sub2api/ent/setting" "github.com/Wei-Shaw/sub2api/ent/usagecleanuptask" @@ -35,6 +36,7 @@ import ( "github.com/Wei-Shaw/sub2api/ent/userallowedgroup" "github.com/Wei-Shaw/sub2api/ent/userattributedefinition" "github.com/Wei-Shaw/sub2api/ent/userattributevalue" + "github.com/Wei-Shaw/sub2api/ent/userreferralprofile" "github.com/Wei-Shaw/sub2api/ent/usersubscription" stdsql "database/sql" @@ -69,6 +71,8 @@ type Client struct { Proxy *ProxyClient // RedeemCode is the client for interacting with the RedeemCode builders. RedeemCode *RedeemCodeClient + // ReferralRelation is the client for interacting with the ReferralRelation builders. + ReferralRelation *ReferralRelationClient // SecuritySecret is the client for interacting with the SecuritySecret builders. SecuritySecret *SecuritySecretClient // Setting is the client for interacting with the Setting builders. @@ -85,6 +89,8 @@ type Client struct { UserAttributeDefinition *UserAttributeDefinitionClient // UserAttributeValue is the client for interacting with the UserAttributeValue builders. UserAttributeValue *UserAttributeValueClient + // UserReferralProfile is the client for interacting with the UserReferralProfile builders. + UserReferralProfile *UserReferralProfileClient // UserSubscription is the client for interacting with the UserSubscription builders. UserSubscription *UserSubscriptionClient } @@ -110,6 +116,7 @@ func (c *Client) init() { c.PromoCodeUsage = NewPromoCodeUsageClient(c.config) c.Proxy = NewProxyClient(c.config) c.RedeemCode = NewRedeemCodeClient(c.config) + c.ReferralRelation = NewReferralRelationClient(c.config) c.SecuritySecret = NewSecuritySecretClient(c.config) c.Setting = NewSettingClient(c.config) c.UsageCleanupTask = NewUsageCleanupTaskClient(c.config) @@ -118,6 +125,7 @@ func (c *Client) init() { c.UserAllowedGroup = NewUserAllowedGroupClient(c.config) c.UserAttributeDefinition = NewUserAttributeDefinitionClient(c.config) c.UserAttributeValue = NewUserAttributeValueClient(c.config) + c.UserReferralProfile = NewUserReferralProfileClient(c.config) c.UserSubscription = NewUserSubscriptionClient(c.config) } @@ -223,6 +231,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { PromoCodeUsage: NewPromoCodeUsageClient(cfg), Proxy: NewProxyClient(cfg), RedeemCode: NewRedeemCodeClient(cfg), + ReferralRelation: NewReferralRelationClient(cfg), SecuritySecret: NewSecuritySecretClient(cfg), Setting: NewSettingClient(cfg), UsageCleanupTask: NewUsageCleanupTaskClient(cfg), @@ -231,6 +240,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { UserAllowedGroup: NewUserAllowedGroupClient(cfg), UserAttributeDefinition: NewUserAttributeDefinitionClient(cfg), UserAttributeValue: NewUserAttributeValueClient(cfg), + UserReferralProfile: NewUserReferralProfileClient(cfg), UserSubscription: NewUserSubscriptionClient(cfg), }, nil } @@ -263,6 +273,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) PromoCodeUsage: NewPromoCodeUsageClient(cfg), Proxy: NewProxyClient(cfg), RedeemCode: NewRedeemCodeClient(cfg), + ReferralRelation: NewReferralRelationClient(cfg), SecuritySecret: NewSecuritySecretClient(cfg), Setting: NewSettingClient(cfg), UsageCleanupTask: NewUsageCleanupTaskClient(cfg), @@ -271,6 +282,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) UserAllowedGroup: NewUserAllowedGroupClient(cfg), UserAttributeDefinition: NewUserAttributeDefinitionClient(cfg), UserAttributeValue: NewUserAttributeValueClient(cfg), + UserReferralProfile: NewUserReferralProfileClient(cfg), UserSubscription: NewUserSubscriptionClient(cfg), }, nil } @@ -303,9 +315,10 @@ func (c *Client) Use(hooks ...Hook) { for _, n := range []interface{ Use(...Hook) }{ c.APIKey, c.Account, c.AccountGroup, c.Announcement, c.AnnouncementRead, c.ErrorPassthroughRule, c.Group, c.IdempotencyRecord, c.PromoCode, - c.PromoCodeUsage, c.Proxy, c.RedeemCode, c.SecuritySecret, c.Setting, - c.UsageCleanupTask, c.UsageLog, c.User, c.UserAllowedGroup, - c.UserAttributeDefinition, c.UserAttributeValue, c.UserSubscription, + c.PromoCodeUsage, c.Proxy, c.RedeemCode, c.ReferralRelation, c.SecuritySecret, + c.Setting, c.UsageCleanupTask, c.UsageLog, c.User, c.UserAllowedGroup, + c.UserAttributeDefinition, c.UserAttributeValue, c.UserReferralProfile, + c.UserSubscription, } { n.Use(hooks...) } @@ -317,9 +330,10 @@ func (c *Client) Intercept(interceptors ...Interceptor) { for _, n := range []interface{ Intercept(...Interceptor) }{ c.APIKey, c.Account, c.AccountGroup, c.Announcement, c.AnnouncementRead, c.ErrorPassthroughRule, c.Group, c.IdempotencyRecord, c.PromoCode, - c.PromoCodeUsage, c.Proxy, c.RedeemCode, c.SecuritySecret, c.Setting, - c.UsageCleanupTask, c.UsageLog, c.User, c.UserAllowedGroup, - c.UserAttributeDefinition, c.UserAttributeValue, c.UserSubscription, + c.PromoCodeUsage, c.Proxy, c.RedeemCode, c.ReferralRelation, c.SecuritySecret, + c.Setting, c.UsageCleanupTask, c.UsageLog, c.User, c.UserAllowedGroup, + c.UserAttributeDefinition, c.UserAttributeValue, c.UserReferralProfile, + c.UserSubscription, } { n.Intercept(interceptors...) } @@ -352,6 +366,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { return c.Proxy.mutate(ctx, m) case *RedeemCodeMutation: return c.RedeemCode.mutate(ctx, m) + case *ReferralRelationMutation: + return c.ReferralRelation.mutate(ctx, m) case *SecuritySecretMutation: return c.SecuritySecret.mutate(ctx, m) case *SettingMutation: @@ -368,6 +384,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { return c.UserAttributeDefinition.mutate(ctx, m) case *UserAttributeValueMutation: return c.UserAttributeValue.mutate(ctx, m) + case *UserReferralProfileMutation: + return c.UserReferralProfile.mutate(ctx, m) case *UserSubscriptionMutation: return c.UserSubscription.mutate(ctx, m) default: @@ -2346,6 +2364,171 @@ func (c *RedeemCodeClient) mutate(ctx context.Context, m *RedeemCodeMutation) (V } } +// ReferralRelationClient is a client for the ReferralRelation schema. +type ReferralRelationClient struct { + config +} + +// NewReferralRelationClient returns a client for the ReferralRelation from the given config. +func NewReferralRelationClient(c config) *ReferralRelationClient { + return &ReferralRelationClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `referralrelation.Hooks(f(g(h())))`. +func (c *ReferralRelationClient) Use(hooks ...Hook) { + c.hooks.ReferralRelation = append(c.hooks.ReferralRelation, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `referralrelation.Intercept(f(g(h())))`. +func (c *ReferralRelationClient) Intercept(interceptors ...Interceptor) { + c.inters.ReferralRelation = append(c.inters.ReferralRelation, interceptors...) +} + +// Create returns a builder for creating a ReferralRelation entity. +func (c *ReferralRelationClient) Create() *ReferralRelationCreate { + mutation := newReferralRelationMutation(c.config, OpCreate) + return &ReferralRelationCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of ReferralRelation entities. +func (c *ReferralRelationClient) CreateBulk(builders ...*ReferralRelationCreate) *ReferralRelationCreateBulk { + return &ReferralRelationCreateBulk{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 *ReferralRelationClient) MapCreateBulk(slice any, setFunc func(*ReferralRelationCreate, int)) *ReferralRelationCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &ReferralRelationCreateBulk{err: fmt.Errorf("calling to ReferralRelationClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*ReferralRelationCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &ReferralRelationCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for ReferralRelation. +func (c *ReferralRelationClient) Update() *ReferralRelationUpdate { + mutation := newReferralRelationMutation(c.config, OpUpdate) + return &ReferralRelationUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *ReferralRelationClient) UpdateOne(_m *ReferralRelation) *ReferralRelationUpdateOne { + mutation := newReferralRelationMutation(c.config, OpUpdateOne, withReferralRelation(_m)) + return &ReferralRelationUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *ReferralRelationClient) UpdateOneID(id int64) *ReferralRelationUpdateOne { + mutation := newReferralRelationMutation(c.config, OpUpdateOne, withReferralRelationID(id)) + return &ReferralRelationUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for ReferralRelation. +func (c *ReferralRelationClient) Delete() *ReferralRelationDelete { + mutation := newReferralRelationMutation(c.config, OpDelete) + return &ReferralRelationDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *ReferralRelationClient) DeleteOne(_m *ReferralRelation) *ReferralRelationDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *ReferralRelationClient) DeleteOneID(id int64) *ReferralRelationDeleteOne { + builder := c.Delete().Where(referralrelation.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &ReferralRelationDeleteOne{builder} +} + +// Query returns a query builder for ReferralRelation. +func (c *ReferralRelationClient) Query() *ReferralRelationQuery { + return &ReferralRelationQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeReferralRelation}, + inters: c.Interceptors(), + } +} + +// Get returns a ReferralRelation entity by its id. +func (c *ReferralRelationClient) Get(ctx context.Context, id int64) (*ReferralRelation, error) { + return c.Query().Where(referralrelation.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *ReferralRelationClient) GetX(ctx context.Context, id int64) *ReferralRelation { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryInviter queries the inviter edge of a ReferralRelation. +func (c *ReferralRelationClient) QueryInviter(_m *ReferralRelation) *UserQuery { + query := (&UserClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(referralrelation.Table, referralrelation.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, referralrelation.InviterTable, referralrelation.InviterColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryInvitee queries the invitee edge of a ReferralRelation. +func (c *ReferralRelationClient) QueryInvitee(_m *ReferralRelation) *UserQuery { + query := (&UserClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(referralrelation.Table, referralrelation.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, referralrelation.InviteeTable, referralrelation.InviteeColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *ReferralRelationClient) Hooks() []Hook { + return c.hooks.ReferralRelation +} + +// Interceptors returns the client interceptors. +func (c *ReferralRelationClient) Interceptors() []Interceptor { + return c.inters.ReferralRelation +} + +func (c *ReferralRelationClient) mutate(ctx context.Context, m *ReferralRelationMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&ReferralRelationCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&ReferralRelationUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&ReferralRelationUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&ReferralRelationDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown ReferralRelation mutation op: %q", m.Op()) + } +} + // SecuritySecretClient is a client for the SecuritySecret schema. type SecuritySecretClient struct { config @@ -3210,6 +3393,54 @@ func (c *UserClient) QueryPromoCodeUsages(_m *User) *PromoCodeUsageQuery { return query } +// QueryReferralProfile queries the referral_profile edge of a User. +func (c *UserClient) QueryReferralProfile(_m *User) *UserReferralProfileQuery { + query := (&UserReferralProfileClient{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(userreferralprofile.Table, userreferralprofile.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, user.ReferralProfileTable, user.ReferralProfileColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryReferralsGiven queries the referrals_given edge of a User. +func (c *UserClient) QueryReferralsGiven(_m *User) *ReferralRelationQuery { + query := (&ReferralRelationClient{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(referralrelation.Table, referralrelation.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, user.ReferralsGivenTable, user.ReferralsGivenColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryReferralReceived queries the referral_received edge of a User. +func (c *UserClient) QueryReferralReceived(_m *User) *ReferralRelationQuery { + query := (&ReferralRelationClient{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(referralrelation.Table, referralrelation.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, user.ReferralReceivedTable, user.ReferralReceivedColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + // QueryUserAllowedGroups queries the user_allowed_groups edge of a User. func (c *UserClient) QueryUserAllowedGroups(_m *User) *UserAllowedGroupQuery { query := (&UserAllowedGroupClient{config: c.config}).Query() @@ -3685,6 +3916,155 @@ func (c *UserAttributeValueClient) mutate(ctx context.Context, m *UserAttributeV } } +// UserReferralProfileClient is a client for the UserReferralProfile schema. +type UserReferralProfileClient struct { + config +} + +// NewUserReferralProfileClient returns a client for the UserReferralProfile from the given config. +func NewUserReferralProfileClient(c config) *UserReferralProfileClient { + return &UserReferralProfileClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `userreferralprofile.Hooks(f(g(h())))`. +func (c *UserReferralProfileClient) Use(hooks ...Hook) { + c.hooks.UserReferralProfile = append(c.hooks.UserReferralProfile, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `userreferralprofile.Intercept(f(g(h())))`. +func (c *UserReferralProfileClient) Intercept(interceptors ...Interceptor) { + c.inters.UserReferralProfile = append(c.inters.UserReferralProfile, interceptors...) +} + +// Create returns a builder for creating a UserReferralProfile entity. +func (c *UserReferralProfileClient) Create() *UserReferralProfileCreate { + mutation := newUserReferralProfileMutation(c.config, OpCreate) + return &UserReferralProfileCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of UserReferralProfile entities. +func (c *UserReferralProfileClient) CreateBulk(builders ...*UserReferralProfileCreate) *UserReferralProfileCreateBulk { + return &UserReferralProfileCreateBulk{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 *UserReferralProfileClient) MapCreateBulk(slice any, setFunc func(*UserReferralProfileCreate, int)) *UserReferralProfileCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &UserReferralProfileCreateBulk{err: fmt.Errorf("calling to UserReferralProfileClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*UserReferralProfileCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &UserReferralProfileCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for UserReferralProfile. +func (c *UserReferralProfileClient) Update() *UserReferralProfileUpdate { + mutation := newUserReferralProfileMutation(c.config, OpUpdate) + return &UserReferralProfileUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *UserReferralProfileClient) UpdateOne(_m *UserReferralProfile) *UserReferralProfileUpdateOne { + mutation := newUserReferralProfileMutation(c.config, OpUpdateOne, withUserReferralProfile(_m)) + return &UserReferralProfileUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *UserReferralProfileClient) UpdateOneID(id int64) *UserReferralProfileUpdateOne { + mutation := newUserReferralProfileMutation(c.config, OpUpdateOne, withUserReferralProfileID(id)) + return &UserReferralProfileUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for UserReferralProfile. +func (c *UserReferralProfileClient) Delete() *UserReferralProfileDelete { + mutation := newUserReferralProfileMutation(c.config, OpDelete) + return &UserReferralProfileDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *UserReferralProfileClient) DeleteOne(_m *UserReferralProfile) *UserReferralProfileDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *UserReferralProfileClient) DeleteOneID(id int64) *UserReferralProfileDeleteOne { + builder := c.Delete().Where(userreferralprofile.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &UserReferralProfileDeleteOne{builder} +} + +// Query returns a query builder for UserReferralProfile. +func (c *UserReferralProfileClient) Query() *UserReferralProfileQuery { + return &UserReferralProfileQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeUserReferralProfile}, + inters: c.Interceptors(), + } +} + +// Get returns a UserReferralProfile entity by its id. +func (c *UserReferralProfileClient) Get(ctx context.Context, id int64) (*UserReferralProfile, error) { + return c.Query().Where(userreferralprofile.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *UserReferralProfileClient) GetX(ctx context.Context, id int64) *UserReferralProfile { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryUser queries the user edge of a UserReferralProfile. +func (c *UserReferralProfileClient) QueryUser(_m *UserReferralProfile) *UserQuery { + query := (&UserClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(userreferralprofile.Table, userreferralprofile.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, userreferralprofile.UserTable, userreferralprofile.UserColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *UserReferralProfileClient) Hooks() []Hook { + return c.hooks.UserReferralProfile +} + +// Interceptors returns the client interceptors. +func (c *UserReferralProfileClient) Interceptors() []Interceptor { + return c.inters.UserReferralProfile +} + +func (c *UserReferralProfileClient) mutate(ctx context.Context, m *UserReferralProfileMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&UserReferralProfileCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&UserReferralProfileUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&UserReferralProfileUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&UserReferralProfileDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown UserReferralProfile mutation op: %q", m.Op()) + } +} + // UserSubscriptionClient is a client for the UserSubscription schema. type UserSubscriptionClient struct { config @@ -3889,16 +4269,16 @@ type ( hooks struct { APIKey, Account, AccountGroup, Announcement, AnnouncementRead, ErrorPassthroughRule, Group, IdempotencyRecord, PromoCode, PromoCodeUsage, - Proxy, RedeemCode, SecuritySecret, Setting, UsageCleanupTask, UsageLog, User, - UserAllowedGroup, UserAttributeDefinition, UserAttributeValue, - UserSubscription []ent.Hook + Proxy, RedeemCode, ReferralRelation, SecuritySecret, Setting, UsageCleanupTask, + UsageLog, User, UserAllowedGroup, UserAttributeDefinition, UserAttributeValue, + UserReferralProfile, UserSubscription []ent.Hook } inters struct { APIKey, Account, AccountGroup, Announcement, AnnouncementRead, ErrorPassthroughRule, Group, IdempotencyRecord, PromoCode, PromoCodeUsage, - Proxy, RedeemCode, SecuritySecret, Setting, UsageCleanupTask, UsageLog, User, - UserAllowedGroup, UserAttributeDefinition, UserAttributeValue, - UserSubscription []ent.Interceptor + Proxy, RedeemCode, ReferralRelation, SecuritySecret, Setting, UsageCleanupTask, + UsageLog, User, UserAllowedGroup, UserAttributeDefinition, UserAttributeValue, + UserReferralProfile, UserSubscription []ent.Interceptor } ) diff --git a/backend/ent/ent.go b/backend/ent/ent.go index 5197e4d84..75620da73 100644 --- a/backend/ent/ent.go +++ b/backend/ent/ent.go @@ -24,6 +24,7 @@ import ( "github.com/Wei-Shaw/sub2api/ent/promocodeusage" "github.com/Wei-Shaw/sub2api/ent/proxy" "github.com/Wei-Shaw/sub2api/ent/redeemcode" + "github.com/Wei-Shaw/sub2api/ent/referralrelation" "github.com/Wei-Shaw/sub2api/ent/securitysecret" "github.com/Wei-Shaw/sub2api/ent/setting" "github.com/Wei-Shaw/sub2api/ent/usagecleanuptask" @@ -32,6 +33,7 @@ import ( "github.com/Wei-Shaw/sub2api/ent/userallowedgroup" "github.com/Wei-Shaw/sub2api/ent/userattributedefinition" "github.com/Wei-Shaw/sub2api/ent/userattributevalue" + "github.com/Wei-Shaw/sub2api/ent/userreferralprofile" "github.com/Wei-Shaw/sub2api/ent/usersubscription" ) @@ -105,6 +107,7 @@ func checkColumn(t, c string) error { promocodeusage.Table: promocodeusage.ValidColumn, proxy.Table: proxy.ValidColumn, redeemcode.Table: redeemcode.ValidColumn, + referralrelation.Table: referralrelation.ValidColumn, securitysecret.Table: securitysecret.ValidColumn, setting.Table: setting.ValidColumn, usagecleanuptask.Table: usagecleanuptask.ValidColumn, @@ -113,6 +116,7 @@ func checkColumn(t, c string) error { userallowedgroup.Table: userallowedgroup.ValidColumn, userattributedefinition.Table: userattributedefinition.ValidColumn, userattributevalue.Table: userattributevalue.ValidColumn, + userreferralprofile.Table: userreferralprofile.ValidColumn, usersubscription.Table: usersubscription.ValidColumn, }) }) diff --git a/backend/ent/hook/hook.go b/backend/ent/hook/hook.go index 49d7f3c55..7e9c19d32 100644 --- a/backend/ent/hook/hook.go +++ b/backend/ent/hook/hook.go @@ -153,6 +153,18 @@ func (f RedeemCodeFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.RedeemCodeMutation", m) } +// The ReferralRelationFunc type is an adapter to allow the use of ordinary +// function as ReferralRelation mutator. +type ReferralRelationFunc func(context.Context, *ent.ReferralRelationMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f ReferralRelationFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.ReferralRelationMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.ReferralRelationMutation", m) +} + // The SecuritySecretFunc type is an adapter to allow the use of ordinary // function as SecuritySecret mutator. type SecuritySecretFunc func(context.Context, *ent.SecuritySecretMutation) (ent.Value, error) @@ -249,6 +261,18 @@ func (f UserAttributeValueFunc) Mutate(ctx context.Context, m ent.Mutation) (ent return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserAttributeValueMutation", m) } +// The UserReferralProfileFunc type is an adapter to allow the use of ordinary +// function as UserReferralProfile mutator. +type UserReferralProfileFunc func(context.Context, *ent.UserReferralProfileMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f UserReferralProfileFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.UserReferralProfileMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserReferralProfileMutation", m) +} + // The UserSubscriptionFunc type is an adapter to allow the use of ordinary // function as UserSubscription mutator. type UserSubscriptionFunc func(context.Context, *ent.UserSubscriptionMutation) (ent.Value, error) diff --git a/backend/ent/intercept/intercept.go b/backend/ent/intercept/intercept.go index e77464026..ac91d32ad 100644 --- a/backend/ent/intercept/intercept.go +++ b/backend/ent/intercept/intercept.go @@ -21,6 +21,7 @@ import ( "github.com/Wei-Shaw/sub2api/ent/promocodeusage" "github.com/Wei-Shaw/sub2api/ent/proxy" "github.com/Wei-Shaw/sub2api/ent/redeemcode" + "github.com/Wei-Shaw/sub2api/ent/referralrelation" "github.com/Wei-Shaw/sub2api/ent/securitysecret" "github.com/Wei-Shaw/sub2api/ent/setting" "github.com/Wei-Shaw/sub2api/ent/usagecleanuptask" @@ -29,6 +30,7 @@ import ( "github.com/Wei-Shaw/sub2api/ent/userallowedgroup" "github.com/Wei-Shaw/sub2api/ent/userattributedefinition" "github.com/Wei-Shaw/sub2api/ent/userattributevalue" + "github.com/Wei-Shaw/sub2api/ent/userreferralprofile" "github.com/Wei-Shaw/sub2api/ent/usersubscription" ) @@ -412,6 +414,33 @@ func (f TraverseRedeemCode) Traverse(ctx context.Context, q ent.Query) error { return fmt.Errorf("unexpected query type %T. expect *ent.RedeemCodeQuery", q) } +// The ReferralRelationFunc type is an adapter to allow the use of ordinary function as a Querier. +type ReferralRelationFunc func(context.Context, *ent.ReferralRelationQuery) (ent.Value, error) + +// Query calls f(ctx, q). +func (f ReferralRelationFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) { + if q, ok := q.(*ent.ReferralRelationQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *ent.ReferralRelationQuery", q) +} + +// The TraverseReferralRelation type is an adapter to allow the use of ordinary function as Traverser. +type TraverseReferralRelation func(context.Context, *ent.ReferralRelationQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseReferralRelation) Intercept(next ent.Querier) ent.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseReferralRelation) Traverse(ctx context.Context, q ent.Query) error { + if q, ok := q.(*ent.ReferralRelationQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *ent.ReferralRelationQuery", q) +} + // The SecuritySecretFunc type is an adapter to allow the use of ordinary function as a Querier. type SecuritySecretFunc func(context.Context, *ent.SecuritySecretQuery) (ent.Value, error) @@ -628,6 +657,33 @@ func (f TraverseUserAttributeValue) Traverse(ctx context.Context, q ent.Query) e return fmt.Errorf("unexpected query type %T. expect *ent.UserAttributeValueQuery", q) } +// The UserReferralProfileFunc type is an adapter to allow the use of ordinary function as a Querier. +type UserReferralProfileFunc func(context.Context, *ent.UserReferralProfileQuery) (ent.Value, error) + +// Query calls f(ctx, q). +func (f UserReferralProfileFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) { + if q, ok := q.(*ent.UserReferralProfileQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *ent.UserReferralProfileQuery", q) +} + +// The TraverseUserReferralProfile type is an adapter to allow the use of ordinary function as Traverser. +type TraverseUserReferralProfile func(context.Context, *ent.UserReferralProfileQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseUserReferralProfile) Intercept(next ent.Querier) ent.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseUserReferralProfile) Traverse(ctx context.Context, q ent.Query) error { + if q, ok := q.(*ent.UserReferralProfileQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *ent.UserReferralProfileQuery", q) +} + // The UserSubscriptionFunc type is an adapter to allow the use of ordinary function as a Querier. type UserSubscriptionFunc func(context.Context, *ent.UserSubscriptionQuery) (ent.Value, error) @@ -682,6 +738,8 @@ func NewQuery(q ent.Query) (Query, error) { return &query[*ent.ProxyQuery, predicate.Proxy, proxy.OrderOption]{typ: ent.TypeProxy, tq: q}, nil case *ent.RedeemCodeQuery: return &query[*ent.RedeemCodeQuery, predicate.RedeemCode, redeemcode.OrderOption]{typ: ent.TypeRedeemCode, tq: q}, nil + case *ent.ReferralRelationQuery: + return &query[*ent.ReferralRelationQuery, predicate.ReferralRelation, referralrelation.OrderOption]{typ: ent.TypeReferralRelation, tq: q}, nil case *ent.SecuritySecretQuery: return &query[*ent.SecuritySecretQuery, predicate.SecuritySecret, securitysecret.OrderOption]{typ: ent.TypeSecuritySecret, tq: q}, nil case *ent.SettingQuery: @@ -698,6 +756,8 @@ func NewQuery(q ent.Query) (Query, error) { return &query[*ent.UserAttributeDefinitionQuery, predicate.UserAttributeDefinition, userattributedefinition.OrderOption]{typ: ent.TypeUserAttributeDefinition, tq: q}, nil case *ent.UserAttributeValueQuery: return &query[*ent.UserAttributeValueQuery, predicate.UserAttributeValue, userattributevalue.OrderOption]{typ: ent.TypeUserAttributeValue, tq: q}, nil + case *ent.UserReferralProfileQuery: + return &query[*ent.UserReferralProfileQuery, predicate.UserReferralProfile, userreferralprofile.OrderOption]{typ: ent.TypeUserReferralProfile, tq: q}, nil case *ent.UserSubscriptionQuery: return &query[*ent.UserSubscriptionQuery, predicate.UserSubscription, usersubscription.OrderOption]{typ: ent.TypeUserSubscription, tq: q}, nil default: diff --git a/backend/ent/migrate/schema.go b/backend/ent/migrate/schema.go index 85e940723..cc857e213 100644 --- a/backend/ent/migrate/schema.go +++ b/backend/ent/migrate/schema.go @@ -642,6 +642,48 @@ var ( }, }, } + // ReferralRelationsColumns holds the columns for the "referral_relations" table. + ReferralRelationsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt64, Increment: true}, + {Name: "inviter_reward", Type: field.TypeFloat64, Default: 0, SchemaType: map[string]string{"postgres": "decimal(20,8)"}}, + {Name: "invitee_reward", Type: field.TypeFloat64, Default: 0, SchemaType: map[string]string{"postgres": "decimal(20,8)"}}, + {Name: "reward_granted", Type: field.TypeBool, Default: false}, + {Name: "created_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}}, + {Name: "inviter_id", Type: field.TypeInt64}, + {Name: "invitee_id", Type: field.TypeInt64}, + } + // ReferralRelationsTable holds the schema information for the "referral_relations" table. + ReferralRelationsTable = &schema.Table{ + Name: "referral_relations", + Columns: ReferralRelationsColumns, + PrimaryKey: []*schema.Column{ReferralRelationsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "referral_relations_users_referrals_given", + Columns: []*schema.Column{ReferralRelationsColumns[5]}, + RefColumns: []*schema.Column{UsersColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "referral_relations_users_referral_received", + Columns: []*schema.Column{ReferralRelationsColumns[6]}, + RefColumns: []*schema.Column{UsersColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "referralrelation_invitee_id", + Unique: true, + Columns: []*schema.Column{ReferralRelationsColumns[6]}, + }, + { + Name: "referralrelation_inviter_id", + Unique: false, + Columns: []*schema.Column{ReferralRelationsColumns[5]}, + }, + }, + } // SecuritySecretsColumns holds the columns for the "security_secrets" table. SecuritySecretsColumns = []*schema.Column{ {Name: "id", Type: field.TypeInt64, Increment: true}, @@ -995,6 +1037,39 @@ var ( }, }, } + // UserReferralProfilesColumns holds the columns for the "user_referral_profiles" table. + UserReferralProfilesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt64, Increment: true}, + {Name: "referral_code", Type: field.TypeString, Unique: true, Size: 8}, + {Name: "created_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}}, + {Name: "user_id", Type: field.TypeInt64}, + } + // UserReferralProfilesTable holds the schema information for the "user_referral_profiles" table. + UserReferralProfilesTable = &schema.Table{ + Name: "user_referral_profiles", + Columns: UserReferralProfilesColumns, + PrimaryKey: []*schema.Column{UserReferralProfilesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "user_referral_profiles_users_referral_profile", + Columns: []*schema.Column{UserReferralProfilesColumns[3]}, + RefColumns: []*schema.Column{UsersColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "userreferralprofile_user_id", + Unique: true, + Columns: []*schema.Column{UserReferralProfilesColumns[3]}, + }, + { + Name: "userreferralprofile_referral_code", + Unique: true, + Columns: []*schema.Column{UserReferralProfilesColumns[1]}, + }, + }, + } // UserSubscriptionsColumns holds the columns for the "user_subscriptions" table. UserSubscriptionsColumns = []*schema.Column{ {Name: "id", Type: field.TypeInt64, Increment: true}, @@ -1098,6 +1173,7 @@ var ( PromoCodeUsagesTable, ProxiesTable, RedeemCodesTable, + ReferralRelationsTable, SecuritySecretsTable, SettingsTable, UsageCleanupTasksTable, @@ -1106,6 +1182,7 @@ var ( UserAllowedGroupsTable, UserAttributeDefinitionsTable, UserAttributeValuesTable, + UserReferralProfilesTable, UserSubscriptionsTable, } ) @@ -1158,6 +1235,11 @@ func init() { RedeemCodesTable.Annotation = &entsql.Annotation{ Table: "redeem_codes", } + ReferralRelationsTable.ForeignKeys[0].RefTable = UsersTable + ReferralRelationsTable.ForeignKeys[1].RefTable = UsersTable + ReferralRelationsTable.Annotation = &entsql.Annotation{ + Table: "referral_relations", + } SecuritySecretsTable.Annotation = &entsql.Annotation{ Table: "security_secrets", } @@ -1191,6 +1273,10 @@ func init() { UserAttributeValuesTable.Annotation = &entsql.Annotation{ Table: "user_attribute_values", } + UserReferralProfilesTable.ForeignKeys[0].RefTable = UsersTable + UserReferralProfilesTable.Annotation = &entsql.Annotation{ + Table: "user_referral_profiles", + } UserSubscriptionsTable.ForeignKeys[0].RefTable = GroupsTable UserSubscriptionsTable.ForeignKeys[1].RefTable = UsersTable UserSubscriptionsTable.ForeignKeys[2].RefTable = UsersTable diff --git a/backend/ent/mutation.go b/backend/ent/mutation.go index 85e2ea716..c65a34120 100644 --- a/backend/ent/mutation.go +++ b/backend/ent/mutation.go @@ -25,6 +25,7 @@ import ( "github.com/Wei-Shaw/sub2api/ent/promocodeusage" "github.com/Wei-Shaw/sub2api/ent/proxy" "github.com/Wei-Shaw/sub2api/ent/redeemcode" + "github.com/Wei-Shaw/sub2api/ent/referralrelation" "github.com/Wei-Shaw/sub2api/ent/securitysecret" "github.com/Wei-Shaw/sub2api/ent/setting" "github.com/Wei-Shaw/sub2api/ent/usagecleanuptask" @@ -33,6 +34,7 @@ import ( "github.com/Wei-Shaw/sub2api/ent/userallowedgroup" "github.com/Wei-Shaw/sub2api/ent/userattributedefinition" "github.com/Wei-Shaw/sub2api/ent/userattributevalue" + "github.com/Wei-Shaw/sub2api/ent/userreferralprofile" "github.com/Wei-Shaw/sub2api/ent/usersubscription" "github.com/Wei-Shaw/sub2api/internal/domain" ) @@ -58,6 +60,7 @@ const ( TypePromoCodeUsage = "PromoCodeUsage" TypeProxy = "Proxy" TypeRedeemCode = "RedeemCode" + TypeReferralRelation = "ReferralRelation" TypeSecuritySecret = "SecuritySecret" TypeSetting = "Setting" TypeUsageCleanupTask = "UsageCleanupTask" @@ -66,6 +69,7 @@ const ( TypeUserAllowedGroup = "UserAllowedGroup" TypeUserAttributeDefinition = "UserAttributeDefinition" TypeUserAttributeValue = "UserAttributeValue" + TypeUserReferralProfile = "UserReferralProfile" TypeUserSubscription = "UserSubscription" ) @@ -15957,33 +15961,39 @@ func (m *RedeemCodeMutation) ResetEdge(name string) error { return fmt.Errorf("unknown RedeemCode edge %s", name) } -// SecuritySecretMutation represents an operation that mutates the SecuritySecret nodes in the graph. -type SecuritySecretMutation struct { +// ReferralRelationMutation represents an operation that mutates the ReferralRelation nodes in the graph. +type ReferralRelationMutation struct { config - op Op - typ string - id *int64 - created_at *time.Time - updated_at *time.Time - key *string - value *string - clearedFields map[string]struct{} - done bool - oldValue func(context.Context) (*SecuritySecret, error) - predicates []predicate.SecuritySecret + op Op + typ string + id *int64 + inviter_reward *float64 + addinviter_reward *float64 + invitee_reward *float64 + addinvitee_reward *float64 + reward_granted *bool + created_at *time.Time + clearedFields map[string]struct{} + inviter *int64 + clearedinviter bool + invitee *int64 + clearedinvitee bool + done bool + oldValue func(context.Context) (*ReferralRelation, error) + predicates []predicate.ReferralRelation } -var _ ent.Mutation = (*SecuritySecretMutation)(nil) +var _ ent.Mutation = (*ReferralRelationMutation)(nil) -// securitysecretOption allows management of the mutation configuration using functional options. -type securitysecretOption func(*SecuritySecretMutation) +// referralrelationOption allows management of the mutation configuration using functional options. +type referralrelationOption func(*ReferralRelationMutation) -// newSecuritySecretMutation creates new mutation for the SecuritySecret entity. -func newSecuritySecretMutation(c config, op Op, opts ...securitysecretOption) *SecuritySecretMutation { - m := &SecuritySecretMutation{ +// newReferralRelationMutation creates new mutation for the ReferralRelation entity. +func newReferralRelationMutation(c config, op Op, opts ...referralrelationOption) *ReferralRelationMutation { + m := &ReferralRelationMutation{ config: c, op: op, - typ: TypeSecuritySecret, + typ: TypeReferralRelation, clearedFields: make(map[string]struct{}), } for _, opt := range opts { @@ -15992,20 +16002,20 @@ func newSecuritySecretMutation(c config, op Op, opts ...securitysecretOption) *S return m } -// withSecuritySecretID sets the ID field of the mutation. -func withSecuritySecretID(id int64) securitysecretOption { - return func(m *SecuritySecretMutation) { +// withReferralRelationID sets the ID field of the mutation. +func withReferralRelationID(id int64) referralrelationOption { + return func(m *ReferralRelationMutation) { var ( err error once sync.Once - value *SecuritySecret + value *ReferralRelation ) - m.oldValue = func(ctx context.Context) (*SecuritySecret, error) { + m.oldValue = func(ctx context.Context) (*ReferralRelation, error) { once.Do(func() { if m.done { err = errors.New("querying old values post mutation is not allowed") } else { - value, err = m.Client().SecuritySecret.Get(ctx, id) + value, err = m.Client().ReferralRelation.Get(ctx, id) } }) return value, err @@ -16014,10 +16024,10 @@ func withSecuritySecretID(id int64) securitysecretOption { } } -// withSecuritySecret sets the old SecuritySecret of the mutation. -func withSecuritySecret(node *SecuritySecret) securitysecretOption { - return func(m *SecuritySecretMutation) { - m.oldValue = func(context.Context) (*SecuritySecret, error) { +// withReferralRelation sets the old ReferralRelation of the mutation. +func withReferralRelation(node *ReferralRelation) referralrelationOption { + return func(m *ReferralRelationMutation) { + m.oldValue = func(context.Context) (*ReferralRelation, error) { return node, nil } m.id = &node.ID @@ -16026,7 +16036,7 @@ func withSecuritySecret(node *SecuritySecret) securitysecretOption { // Client returns a new `ent.Client` from the mutation. If the mutation was // executed in a transaction (ent.Tx), a transactional client is returned. -func (m SecuritySecretMutation) Client() *Client { +func (m ReferralRelationMutation) Client() *Client { client := &Client{config: m.config} client.init() return client @@ -16034,7 +16044,7 @@ func (m SecuritySecretMutation) Client() *Client { // Tx returns an `ent.Tx` for mutations that were executed in transactions; // it returns an error otherwise. -func (m SecuritySecretMutation) Tx() (*Tx, error) { +func (m ReferralRelationMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { return nil, errors.New("ent: mutation is not running in a transaction") } @@ -16045,7 +16055,7 @@ func (m SecuritySecretMutation) Tx() (*Tx, error) { // ID returns the ID value in the mutation. Note that the ID is only available // if it was provided to the builder or after it was returned from the database. -func (m *SecuritySecretMutation) ID() (id int64, exists bool) { +func (m *ReferralRelationMutation) ID() (id int64, exists bool) { if m.id == nil { return } @@ -16056,7 +16066,7 @@ func (m *SecuritySecretMutation) ID() (id int64, exists bool) { // That means, if the mutation is applied within a transaction with an isolation level such // as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated // or updated by the mutation. -func (m *SecuritySecretMutation) IDs(ctx context.Context) ([]int64, error) { +func (m *ReferralRelationMutation) IDs(ctx context.Context) ([]int64, error) { switch { case m.op.Is(OpUpdateOne | OpDeleteOne): id, exists := m.ID() @@ -16065,165 +16075,331 @@ func (m *SecuritySecretMutation) IDs(ctx context.Context) ([]int64, error) { } fallthrough case m.op.Is(OpUpdate | OpDelete): - return m.Client().SecuritySecret.Query().Where(m.predicates...).IDs(ctx) + return m.Client().ReferralRelation.Query().Where(m.predicates...).IDs(ctx) default: return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } } -// SetCreatedAt sets the "created_at" field. -func (m *SecuritySecretMutation) SetCreatedAt(t time.Time) { - m.created_at = &t +// SetInviterID sets the "inviter_id" field. +func (m *ReferralRelationMutation) SetInviterID(i int64) { + m.inviter = &i } -// CreatedAt returns the value of the "created_at" field in the mutation. -func (m *SecuritySecretMutation) CreatedAt() (r time.Time, exists bool) { - v := m.created_at +// InviterID returns the value of the "inviter_id" field in the mutation. +func (m *ReferralRelationMutation) InviterID() (r int64, exists bool) { + v := m.inviter if v == nil { return } return *v, true } -// OldCreatedAt returns the old "created_at" field's value of the SecuritySecret entity. -// If the SecuritySecret object wasn't provided to the builder, the object is fetched from the database. +// OldInviterID returns the old "inviter_id" field's value of the ReferralRelation entity. +// If the ReferralRelation object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecuritySecretMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { +func (m *ReferralRelationMutation) OldInviterID(ctx context.Context) (v int64, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + return v, errors.New("OldInviterID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCreatedAt requires an ID field in the mutation") + return v, errors.New("OldInviterID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + return v, fmt.Errorf("querying old value for OldInviterID: %w", err) } - return oldValue.CreatedAt, nil + return oldValue.InviterID, nil } -// ResetCreatedAt resets all changes to the "created_at" field. -func (m *SecuritySecretMutation) ResetCreatedAt() { - m.created_at = nil +// ResetInviterID resets all changes to the "inviter_id" field. +func (m *ReferralRelationMutation) ResetInviterID() { + m.inviter = nil } -// SetUpdatedAt sets the "updated_at" field. -func (m *SecuritySecretMutation) SetUpdatedAt(t time.Time) { - m.updated_at = &t +// SetInviteeID sets the "invitee_id" field. +func (m *ReferralRelationMutation) SetInviteeID(i int64) { + m.invitee = &i } -// UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *SecuritySecretMutation) UpdatedAt() (r time.Time, exists bool) { - v := m.updated_at +// InviteeID returns the value of the "invitee_id" field in the mutation. +func (m *ReferralRelationMutation) InviteeID() (r int64, exists bool) { + v := m.invitee if v == nil { return } return *v, true } -// OldUpdatedAt returns the old "updated_at" field's value of the SecuritySecret entity. -// If the SecuritySecret object wasn't provided to the builder, the object is fetched from the database. +// OldInviteeID returns the old "invitee_id" field's value of the ReferralRelation entity. +// If the ReferralRelation object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecuritySecretMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { +func (m *ReferralRelationMutation) OldInviteeID(ctx context.Context) (v int64, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + return v, errors.New("OldInviteeID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUpdatedAt requires an ID field in the mutation") + return v, errors.New("OldInviteeID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + return v, fmt.Errorf("querying old value for OldInviteeID: %w", err) } - return oldValue.UpdatedAt, nil + return oldValue.InviteeID, nil } -// ResetUpdatedAt resets all changes to the "updated_at" field. -func (m *SecuritySecretMutation) ResetUpdatedAt() { - m.updated_at = nil +// ResetInviteeID resets all changes to the "invitee_id" field. +func (m *ReferralRelationMutation) ResetInviteeID() { + m.invitee = nil } -// SetKey sets the "key" field. -func (m *SecuritySecretMutation) SetKey(s string) { - m.key = &s +// SetInviterReward sets the "inviter_reward" field. +func (m *ReferralRelationMutation) SetInviterReward(f float64) { + m.inviter_reward = &f + m.addinviter_reward = nil } -// Key returns the value of the "key" field in the mutation. -func (m *SecuritySecretMutation) Key() (r string, exists bool) { - v := m.key +// InviterReward returns the value of the "inviter_reward" field in the mutation. +func (m *ReferralRelationMutation) InviterReward() (r float64, exists bool) { + v := m.inviter_reward if v == nil { return } return *v, true } -// OldKey returns the old "key" field's value of the SecuritySecret entity. -// If the SecuritySecret object wasn't provided to the builder, the object is fetched from the database. +// OldInviterReward returns the old "inviter_reward" field's value of the ReferralRelation entity. +// If the ReferralRelation object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecuritySecretMutation) OldKey(ctx context.Context) (v string, err error) { +func (m *ReferralRelationMutation) OldInviterReward(ctx context.Context) (v float64, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldKey is only allowed on UpdateOne operations") + return v, errors.New("OldInviterReward is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldKey requires an ID field in the mutation") + return v, errors.New("OldInviterReward requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldKey: %w", err) + return v, fmt.Errorf("querying old value for OldInviterReward: %w", err) } - return oldValue.Key, nil + return oldValue.InviterReward, nil } -// ResetKey resets all changes to the "key" field. -func (m *SecuritySecretMutation) ResetKey() { - m.key = nil +// AddInviterReward adds f to the "inviter_reward" field. +func (m *ReferralRelationMutation) AddInviterReward(f float64) { + if m.addinviter_reward != nil { + *m.addinviter_reward += f + } else { + m.addinviter_reward = &f + } } -// SetValue sets the "value" field. -func (m *SecuritySecretMutation) SetValue(s string) { - m.value = &s +// AddedInviterReward returns the value that was added to the "inviter_reward" field in this mutation. +func (m *ReferralRelationMutation) AddedInviterReward() (r float64, exists bool) { + v := m.addinviter_reward + if v == nil { + return + } + return *v, true } -// Value returns the value of the "value" field in the mutation. -func (m *SecuritySecretMutation) Value() (r string, exists bool) { - v := m.value +// ResetInviterReward resets all changes to the "inviter_reward" field. +func (m *ReferralRelationMutation) ResetInviterReward() { + m.inviter_reward = nil + m.addinviter_reward = nil +} + +// SetInviteeReward sets the "invitee_reward" field. +func (m *ReferralRelationMutation) SetInviteeReward(f float64) { + m.invitee_reward = &f + m.addinvitee_reward = nil +} + +// InviteeReward returns the value of the "invitee_reward" field in the mutation. +func (m *ReferralRelationMutation) InviteeReward() (r float64, exists bool) { + v := m.invitee_reward if v == nil { return } return *v, true } -// OldValue returns the old "value" field's value of the SecuritySecret entity. -// If the SecuritySecret object wasn't provided to the builder, the object is fetched from the database. +// OldInviteeReward returns the old "invitee_reward" field's value of the ReferralRelation entity. +// If the ReferralRelation object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecuritySecretMutation) OldValue(ctx context.Context) (v string, err error) { +func (m *ReferralRelationMutation) OldInviteeReward(ctx context.Context) (v float64, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldValue is only allowed on UpdateOne operations") + return v, errors.New("OldInviteeReward is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldValue requires an ID field in the mutation") + return v, errors.New("OldInviteeReward requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldValue: %w", err) + return v, fmt.Errorf("querying old value for OldInviteeReward: %w", err) } - return oldValue.Value, nil + return oldValue.InviteeReward, nil } -// ResetValue resets all changes to the "value" field. -func (m *SecuritySecretMutation) ResetValue() { - m.value = nil +// AddInviteeReward adds f to the "invitee_reward" field. +func (m *ReferralRelationMutation) AddInviteeReward(f float64) { + if m.addinvitee_reward != nil { + *m.addinvitee_reward += f + } else { + m.addinvitee_reward = &f + } } -// Where appends a list predicates to the SecuritySecretMutation builder. -func (m *SecuritySecretMutation) Where(ps ...predicate.SecuritySecret) { +// AddedInviteeReward returns the value that was added to the "invitee_reward" field in this mutation. +func (m *ReferralRelationMutation) AddedInviteeReward() (r float64, exists bool) { + v := m.addinvitee_reward + if v == nil { + return + } + return *v, true +} + +// ResetInviteeReward resets all changes to the "invitee_reward" field. +func (m *ReferralRelationMutation) ResetInviteeReward() { + m.invitee_reward = nil + m.addinvitee_reward = nil +} + +// SetRewardGranted sets the "reward_granted" field. +func (m *ReferralRelationMutation) SetRewardGranted(b bool) { + m.reward_granted = &b +} + +// RewardGranted returns the value of the "reward_granted" field in the mutation. +func (m *ReferralRelationMutation) RewardGranted() (r bool, exists bool) { + v := m.reward_granted + if v == nil { + return + } + return *v, true +} + +// OldRewardGranted returns the old "reward_granted" field's value of the ReferralRelation entity. +// If the ReferralRelation object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ReferralRelationMutation) OldRewardGranted(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRewardGranted is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRewardGranted requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRewardGranted: %w", err) + } + return oldValue.RewardGranted, nil +} + +// ResetRewardGranted resets all changes to the "reward_granted" field. +func (m *ReferralRelationMutation) ResetRewardGranted() { + m.reward_granted = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *ReferralRelationMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *ReferralRelationMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return + } + return *v, true +} + +// OldCreatedAt returns the old "created_at" field's value of the ReferralRelation entity. +// If the ReferralRelation object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ReferralRelationMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + } + return oldValue.CreatedAt, nil +} + +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *ReferralRelationMutation) ResetCreatedAt() { + m.created_at = nil +} + +// ClearInviter clears the "inviter" edge to the User entity. +func (m *ReferralRelationMutation) ClearInviter() { + m.clearedinviter = true + m.clearedFields[referralrelation.FieldInviterID] = struct{}{} +} + +// InviterCleared reports if the "inviter" edge to the User entity was cleared. +func (m *ReferralRelationMutation) InviterCleared() bool { + return m.clearedinviter +} + +// InviterIDs returns the "inviter" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// InviterID instead. It exists only for internal usage by the builders. +func (m *ReferralRelationMutation) InviterIDs() (ids []int64) { + if id := m.inviter; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetInviter resets all changes to the "inviter" edge. +func (m *ReferralRelationMutation) ResetInviter() { + m.inviter = nil + m.clearedinviter = false +} + +// ClearInvitee clears the "invitee" edge to the User entity. +func (m *ReferralRelationMutation) ClearInvitee() { + m.clearedinvitee = true + m.clearedFields[referralrelation.FieldInviteeID] = struct{}{} +} + +// InviteeCleared reports if the "invitee" edge to the User entity was cleared. +func (m *ReferralRelationMutation) InviteeCleared() bool { + return m.clearedinvitee +} + +// InviteeIDs returns the "invitee" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// InviteeID instead. It exists only for internal usage by the builders. +func (m *ReferralRelationMutation) InviteeIDs() (ids []int64) { + if id := m.invitee; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetInvitee resets all changes to the "invitee" edge. +func (m *ReferralRelationMutation) ResetInvitee() { + m.invitee = nil + m.clearedinvitee = false +} + +// Where appends a list predicates to the ReferralRelationMutation builder. +func (m *ReferralRelationMutation) Where(ps ...predicate.ReferralRelation) { m.predicates = append(m.predicates, ps...) } -// WhereP appends storage-level predicates to the SecuritySecretMutation builder. Using this method, +// WhereP appends storage-level predicates to the ReferralRelationMutation builder. Using this method, // users can use type-assertion to append predicates that do not depend on any generated package. -func (m *SecuritySecretMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.SecuritySecret, len(ps)) +func (m *ReferralRelationMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.ReferralRelation, len(ps)) for i := range ps { p[i] = ps[i] } @@ -16231,36 +16407,42 @@ func (m *SecuritySecretMutation) WhereP(ps ...func(*sql.Selector)) { } // Op returns the operation name. -func (m *SecuritySecretMutation) Op() Op { +func (m *ReferralRelationMutation) Op() Op { return m.op } // SetOp allows setting the mutation operation. -func (m *SecuritySecretMutation) SetOp(op Op) { +func (m *ReferralRelationMutation) SetOp(op Op) { m.op = op } -// Type returns the node type of this mutation (SecuritySecret). -func (m *SecuritySecretMutation) Type() string { +// Type returns the node type of this mutation (ReferralRelation). +func (m *ReferralRelationMutation) Type() string { return m.typ } // Fields returns all fields that were changed during this mutation. Note that in // order to get all numeric fields that were incremented/decremented, call // AddedFields(). -func (m *SecuritySecretMutation) Fields() []string { - fields := make([]string, 0, 4) - if m.created_at != nil { - fields = append(fields, securitysecret.FieldCreatedAt) +func (m *ReferralRelationMutation) Fields() []string { + fields := make([]string, 0, 6) + if m.inviter != nil { + fields = append(fields, referralrelation.FieldInviterID) } - if m.updated_at != nil { - fields = append(fields, securitysecret.FieldUpdatedAt) + if m.invitee != nil { + fields = append(fields, referralrelation.FieldInviteeID) } - if m.key != nil { - fields = append(fields, securitysecret.FieldKey) + if m.inviter_reward != nil { + fields = append(fields, referralrelation.FieldInviterReward) } - if m.value != nil { - fields = append(fields, securitysecret.FieldValue) + if m.invitee_reward != nil { + fields = append(fields, referralrelation.FieldInviteeReward) + } + if m.reward_granted != nil { + fields = append(fields, referralrelation.FieldRewardGranted) + } + if m.created_at != nil { + fields = append(fields, referralrelation.FieldCreatedAt) } return fields } @@ -16268,16 +16450,20 @@ func (m *SecuritySecretMutation) Fields() []string { // Field returns the value of a field with the given name. The second boolean // return value indicates that this field was not set, or was not defined in the // schema. -func (m *SecuritySecretMutation) Field(name string) (ent.Value, bool) { +func (m *ReferralRelationMutation) Field(name string) (ent.Value, bool) { switch name { - case securitysecret.FieldCreatedAt: + case referralrelation.FieldInviterID: + return m.InviterID() + case referralrelation.FieldInviteeID: + return m.InviteeID() + case referralrelation.FieldInviterReward: + return m.InviterReward() + case referralrelation.FieldInviteeReward: + return m.InviteeReward() + case referralrelation.FieldRewardGranted: + return m.RewardGranted() + case referralrelation.FieldCreatedAt: return m.CreatedAt() - case securitysecret.FieldUpdatedAt: - return m.UpdatedAt() - case securitysecret.FieldKey: - return m.Key() - case securitysecret.FieldValue: - return m.Value() } return nil, false } @@ -16285,192 +16471,288 @@ func (m *SecuritySecretMutation) Field(name string) (ent.Value, bool) { // OldField returns the old value of the field from the database. An error is // returned if the mutation operation is not UpdateOne, or the query to the // database failed. -func (m *SecuritySecretMutation) OldField(ctx context.Context, name string) (ent.Value, error) { +func (m *ReferralRelationMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { - case securitysecret.FieldCreatedAt: + case referralrelation.FieldInviterID: + return m.OldInviterID(ctx) + case referralrelation.FieldInviteeID: + return m.OldInviteeID(ctx) + case referralrelation.FieldInviterReward: + return m.OldInviterReward(ctx) + case referralrelation.FieldInviteeReward: + return m.OldInviteeReward(ctx) + case referralrelation.FieldRewardGranted: + return m.OldRewardGranted(ctx) + case referralrelation.FieldCreatedAt: return m.OldCreatedAt(ctx) - case securitysecret.FieldUpdatedAt: - return m.OldUpdatedAt(ctx) - case securitysecret.FieldKey: - return m.OldKey(ctx) - case securitysecret.FieldValue: - return m.OldValue(ctx) } - return nil, fmt.Errorf("unknown SecuritySecret field %s", name) + return nil, fmt.Errorf("unknown ReferralRelation field %s", name) } // SetField sets the value of a field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *SecuritySecretMutation) SetField(name string, value ent.Value) error { +func (m *ReferralRelationMutation) SetField(name string, value ent.Value) error { switch name { - case securitysecret.FieldCreatedAt: - v, ok := value.(time.Time) + case referralrelation.FieldInviterID: + v, ok := value.(int64) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetCreatedAt(v) + m.SetInviterID(v) return nil - case securitysecret.FieldUpdatedAt: - v, ok := value.(time.Time) + case referralrelation.FieldInviteeID: + v, ok := value.(int64) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetUpdatedAt(v) + m.SetInviteeID(v) return nil - case securitysecret.FieldKey: - v, ok := value.(string) + case referralrelation.FieldInviterReward: + v, ok := value.(float64) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetKey(v) + m.SetInviterReward(v) return nil - case securitysecret.FieldValue: - v, ok := value.(string) + case referralrelation.FieldInviteeReward: + v, ok := value.(float64) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetValue(v) + m.SetInviteeReward(v) return nil - } - return fmt.Errorf("unknown SecuritySecret field %s", name) + case referralrelation.FieldRewardGranted: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRewardGranted(v) + return nil + case referralrelation.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + } + return fmt.Errorf("unknown ReferralRelation field %s", name) } // AddedFields returns all numeric fields that were incremented/decremented during // this mutation. -func (m *SecuritySecretMutation) AddedFields() []string { - return nil +func (m *ReferralRelationMutation) AddedFields() []string { + var fields []string + if m.addinviter_reward != nil { + fields = append(fields, referralrelation.FieldInviterReward) + } + if m.addinvitee_reward != nil { + fields = append(fields, referralrelation.FieldInviteeReward) + } + return fields } // AddedField returns the numeric value that was incremented/decremented on a field // with the given name. The second boolean return value indicates that this field // was not set, or was not defined in the schema. -func (m *SecuritySecretMutation) AddedField(name string) (ent.Value, bool) { +func (m *ReferralRelationMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case referralrelation.FieldInviterReward: + return m.AddedInviterReward() + case referralrelation.FieldInviteeReward: + return m.AddedInviteeReward() + } return nil, false } // AddField adds the value to the field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *SecuritySecretMutation) AddField(name string, value ent.Value) error { +func (m *ReferralRelationMutation) AddField(name string, value ent.Value) error { switch name { + case referralrelation.FieldInviterReward: + v, ok := value.(float64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddInviterReward(v) + return nil + case referralrelation.FieldInviteeReward: + v, ok := value.(float64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddInviteeReward(v) + return nil } - return fmt.Errorf("unknown SecuritySecret numeric field %s", name) + return fmt.Errorf("unknown ReferralRelation numeric field %s", name) } // ClearedFields returns all nullable fields that were cleared during this // mutation. -func (m *SecuritySecretMutation) ClearedFields() []string { +func (m *ReferralRelationMutation) ClearedFields() []string { return nil } // FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. -func (m *SecuritySecretMutation) FieldCleared(name string) bool { +func (m *ReferralRelationMutation) FieldCleared(name string) bool { _, ok := m.clearedFields[name] return ok } // ClearField clears the value of the field with the given name. It returns an // error if the field is not defined in the schema. -func (m *SecuritySecretMutation) ClearField(name string) error { - return fmt.Errorf("unknown SecuritySecret nullable field %s", name) +func (m *ReferralRelationMutation) ClearField(name string) error { + return fmt.Errorf("unknown ReferralRelation nullable field %s", name) } // ResetField resets all changes in the mutation for the field with the given name. // It returns an error if the field is not defined in the schema. -func (m *SecuritySecretMutation) ResetField(name string) error { +func (m *ReferralRelationMutation) ResetField(name string) error { switch name { - case securitysecret.FieldCreatedAt: - m.ResetCreatedAt() + case referralrelation.FieldInviterID: + m.ResetInviterID() return nil - case securitysecret.FieldUpdatedAt: - m.ResetUpdatedAt() + case referralrelation.FieldInviteeID: + m.ResetInviteeID() return nil - case securitysecret.FieldKey: - m.ResetKey() + case referralrelation.FieldInviterReward: + m.ResetInviterReward() return nil - case securitysecret.FieldValue: - m.ResetValue() + case referralrelation.FieldInviteeReward: + m.ResetInviteeReward() + return nil + case referralrelation.FieldRewardGranted: + m.ResetRewardGranted() + return nil + case referralrelation.FieldCreatedAt: + m.ResetCreatedAt() return nil } - return fmt.Errorf("unknown SecuritySecret field %s", name) + return fmt.Errorf("unknown ReferralRelation field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. -func (m *SecuritySecretMutation) AddedEdges() []string { - edges := make([]string, 0, 0) +func (m *ReferralRelationMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.inviter != nil { + edges = append(edges, referralrelation.EdgeInviter) + } + if m.invitee != nil { + edges = append(edges, referralrelation.EdgeInvitee) + } return edges } // AddedIDs returns all IDs (to other nodes) that were added for the given edge // name in this mutation. -func (m *SecuritySecretMutation) AddedIDs(name string) []ent.Value { +func (m *ReferralRelationMutation) AddedIDs(name string) []ent.Value { + switch name { + case referralrelation.EdgeInviter: + if id := m.inviter; id != nil { + return []ent.Value{*id} + } + case referralrelation.EdgeInvitee: + if id := m.invitee; id != nil { + return []ent.Value{*id} + } + } return nil } // RemovedEdges returns all edge names that were removed in this mutation. -func (m *SecuritySecretMutation) RemovedEdges() []string { - edges := make([]string, 0, 0) +func (m *ReferralRelationMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) return edges } // RemovedIDs returns all IDs (to other nodes) that were removed for the edge with // the given name in this mutation. -func (m *SecuritySecretMutation) RemovedIDs(name string) []ent.Value { +func (m *ReferralRelationMutation) RemovedIDs(name string) []ent.Value { return nil } // ClearedEdges returns all edge names that were cleared in this mutation. -func (m *SecuritySecretMutation) ClearedEdges() []string { - edges := make([]string, 0, 0) +func (m *ReferralRelationMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedinviter { + edges = append(edges, referralrelation.EdgeInviter) + } + if m.clearedinvitee { + edges = append(edges, referralrelation.EdgeInvitee) + } return edges } // EdgeCleared returns a boolean which indicates if the edge with the given name // was cleared in this mutation. -func (m *SecuritySecretMutation) EdgeCleared(name string) bool { +func (m *ReferralRelationMutation) EdgeCleared(name string) bool { + switch name { + case referralrelation.EdgeInviter: + return m.clearedinviter + case referralrelation.EdgeInvitee: + return m.clearedinvitee + } return false } // ClearEdge clears the value of the edge with the given name. It returns an error // if that edge is not defined in the schema. -func (m *SecuritySecretMutation) ClearEdge(name string) error { - return fmt.Errorf("unknown SecuritySecret unique edge %s", name) +func (m *ReferralRelationMutation) ClearEdge(name string) error { + switch name { + case referralrelation.EdgeInviter: + m.ClearInviter() + return nil + case referralrelation.EdgeInvitee: + m.ClearInvitee() + return nil + } + return fmt.Errorf("unknown ReferralRelation unique edge %s", name) } // ResetEdge resets all changes to the edge with the given name in this mutation. // It returns an error if the edge is not defined in the schema. -func (m *SecuritySecretMutation) ResetEdge(name string) error { - return fmt.Errorf("unknown SecuritySecret edge %s", name) +func (m *ReferralRelationMutation) ResetEdge(name string) error { + switch name { + case referralrelation.EdgeInviter: + m.ResetInviter() + return nil + case referralrelation.EdgeInvitee: + m.ResetInvitee() + return nil + } + return fmt.Errorf("unknown ReferralRelation edge %s", name) } -// SettingMutation represents an operation that mutates the Setting nodes in the graph. -type SettingMutation struct { +// SecuritySecretMutation represents an operation that mutates the SecuritySecret nodes in the graph. +type SecuritySecretMutation struct { config op Op typ string id *int64 + created_at *time.Time + updated_at *time.Time key *string value *string - updated_at *time.Time clearedFields map[string]struct{} done bool - oldValue func(context.Context) (*Setting, error) - predicates []predicate.Setting + oldValue func(context.Context) (*SecuritySecret, error) + predicates []predicate.SecuritySecret } -var _ ent.Mutation = (*SettingMutation)(nil) +var _ ent.Mutation = (*SecuritySecretMutation)(nil) -// settingOption allows management of the mutation configuration using functional options. -type settingOption func(*SettingMutation) +// securitysecretOption allows management of the mutation configuration using functional options. +type securitysecretOption func(*SecuritySecretMutation) -// newSettingMutation creates new mutation for the Setting entity. -func newSettingMutation(c config, op Op, opts ...settingOption) *SettingMutation { - m := &SettingMutation{ +// newSecuritySecretMutation creates new mutation for the SecuritySecret entity. +func newSecuritySecretMutation(c config, op Op, opts ...securitysecretOption) *SecuritySecretMutation { + m := &SecuritySecretMutation{ config: c, op: op, - typ: TypeSetting, + typ: TypeSecuritySecret, clearedFields: make(map[string]struct{}), } for _, opt := range opts { @@ -16479,20 +16761,20 @@ func newSettingMutation(c config, op Op, opts ...settingOption) *SettingMutation return m } -// withSettingID sets the ID field of the mutation. -func withSettingID(id int64) settingOption { - return func(m *SettingMutation) { +// withSecuritySecretID sets the ID field of the mutation. +func withSecuritySecretID(id int64) securitysecretOption { + return func(m *SecuritySecretMutation) { var ( err error once sync.Once - value *Setting + value *SecuritySecret ) - m.oldValue = func(ctx context.Context) (*Setting, error) { + m.oldValue = func(ctx context.Context) (*SecuritySecret, error) { once.Do(func() { if m.done { err = errors.New("querying old values post mutation is not allowed") } else { - value, err = m.Client().Setting.Get(ctx, id) + value, err = m.Client().SecuritySecret.Get(ctx, id) } }) return value, err @@ -16501,10 +16783,10 @@ func withSettingID(id int64) settingOption { } } -// withSetting sets the old Setting of the mutation. -func withSetting(node *Setting) settingOption { - return func(m *SettingMutation) { - m.oldValue = func(context.Context) (*Setting, error) { +// withSecuritySecret sets the old SecuritySecret of the mutation. +func withSecuritySecret(node *SecuritySecret) securitysecretOption { + return func(m *SecuritySecretMutation) { + m.oldValue = func(context.Context) (*SecuritySecret, error) { return node, nil } m.id = &node.ID @@ -16513,7 +16795,7 @@ func withSetting(node *Setting) settingOption { // Client returns a new `ent.Client` from the mutation. If the mutation was // executed in a transaction (ent.Tx), a transactional client is returned. -func (m SettingMutation) Client() *Client { +func (m SecuritySecretMutation) Client() *Client { client := &Client{config: m.config} client.init() return client @@ -16521,7 +16803,7 @@ func (m SettingMutation) Client() *Client { // Tx returns an `ent.Tx` for mutations that were executed in transactions; // it returns an error otherwise. -func (m SettingMutation) Tx() (*Tx, error) { +func (m SecuritySecretMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { return nil, errors.New("ent: mutation is not running in a transaction") } @@ -16532,7 +16814,7 @@ func (m SettingMutation) Tx() (*Tx, error) { // ID returns the ID value in the mutation. Note that the ID is only available // if it was provided to the builder or after it was returned from the database. -func (m *SettingMutation) ID() (id int64, exists bool) { +func (m *SecuritySecretMutation) ID() (id int64, exists bool) { if m.id == nil { return } @@ -16543,7 +16825,7 @@ func (m *SettingMutation) ID() (id int64, exists bool) { // That means, if the mutation is applied within a transaction with an isolation level such // as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated // or updated by the mutation. -func (m *SettingMutation) IDs(ctx context.Context) ([]int64, error) { +func (m *SecuritySecretMutation) IDs(ctx context.Context) ([]int64, error) { switch { case m.op.Is(OpUpdateOne | OpDeleteOne): id, exists := m.ID() @@ -16552,163 +16834,202 @@ func (m *SettingMutation) IDs(ctx context.Context) ([]int64, error) { } fallthrough case m.op.Is(OpUpdate | OpDelete): - return m.Client().Setting.Query().Where(m.predicates...).IDs(ctx) + return m.Client().SecuritySecret.Query().Where(m.predicates...).IDs(ctx) default: return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } } -// SetKey sets the "key" field. -func (m *SettingMutation) SetKey(s string) { - m.key = &s +// SetCreatedAt sets the "created_at" field. +func (m *SecuritySecretMutation) SetCreatedAt(t time.Time) { + m.created_at = &t } -// Key returns the value of the "key" field in the mutation. -func (m *SettingMutation) Key() (r string, exists bool) { - v := m.key +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *SecuritySecretMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at if v == nil { return } return *v, true } -// OldKey returns the old "key" field's value of the Setting entity. -// If the Setting object wasn't provided to the builder, the object is fetched from the database. +// OldCreatedAt returns the old "created_at" field's value of the SecuritySecret entity. +// If the SecuritySecret object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SettingMutation) OldKey(ctx context.Context) (v string, err error) { +func (m *SecuritySecretMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldKey is only allowed on UpdateOne operations") + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldKey requires an ID field in the mutation") + return v, errors.New("OldCreatedAt requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldKey: %w", err) + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) } - return oldValue.Key, nil + return oldValue.CreatedAt, nil } -// ResetKey resets all changes to the "key" field. -func (m *SettingMutation) ResetKey() { - m.key = nil +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *SecuritySecretMutation) ResetCreatedAt() { + m.created_at = nil } -// SetValue sets the "value" field. -func (m *SettingMutation) SetValue(s string) { - m.value = &s +// SetUpdatedAt sets the "updated_at" field. +func (m *SecuritySecretMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t } -// Value returns the value of the "value" field in the mutation. -func (m *SettingMutation) Value() (r string, exists bool) { - v := m.value +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *SecuritySecretMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at if v == nil { return } return *v, true } -// OldValue returns the old "value" field's value of the Setting entity. -// If the Setting object wasn't provided to the builder, the object is fetched from the database. +// OldUpdatedAt returns the old "updated_at" field's value of the SecuritySecret entity. +// If the SecuritySecret object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SettingMutation) OldValue(ctx context.Context) (v string, err error) { +func (m *SecuritySecretMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldValue is only allowed on UpdateOne operations") + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldValue requires an ID field in the mutation") + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldValue: %w", err) + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) } - return oldValue.Value, nil + return oldValue.UpdatedAt, nil } -// ResetValue resets all changes to the "value" field. -func (m *SettingMutation) ResetValue() { - m.value = nil +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *SecuritySecretMutation) ResetUpdatedAt() { + m.updated_at = nil } -// SetUpdatedAt sets the "updated_at" field. -func (m *SettingMutation) SetUpdatedAt(t time.Time) { - m.updated_at = &t +// SetKey sets the "key" field. +func (m *SecuritySecretMutation) SetKey(s string) { + m.key = &s } -// UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *SettingMutation) UpdatedAt() (r time.Time, exists bool) { - v := m.updated_at +// Key returns the value of the "key" field in the mutation. +func (m *SecuritySecretMutation) Key() (r string, exists bool) { + v := m.key if v == nil { return } return *v, true } -// OldUpdatedAt returns the old "updated_at" field's value of the Setting entity. -// If the Setting object wasn't provided to the builder, the object is fetched from the database. +// OldKey returns the old "key" field's value of the SecuritySecret entity. +// If the SecuritySecret object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SettingMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { +func (m *SecuritySecretMutation) OldKey(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + return v, errors.New("OldKey is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUpdatedAt requires an ID field in the mutation") + return v, errors.New("OldKey requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + return v, fmt.Errorf("querying old value for OldKey: %w", err) } - return oldValue.UpdatedAt, nil + return oldValue.Key, nil } -// ResetUpdatedAt resets all changes to the "updated_at" field. -func (m *SettingMutation) ResetUpdatedAt() { - m.updated_at = nil +// ResetKey resets all changes to the "key" field. +func (m *SecuritySecretMutation) ResetKey() { + m.key = nil } -// Where appends a list predicates to the SettingMutation builder. -func (m *SettingMutation) Where(ps ...predicate.Setting) { - m.predicates = append(m.predicates, ps...) +// SetValue sets the "value" field. +func (m *SecuritySecretMutation) SetValue(s string) { + m.value = &s } -// WhereP appends storage-level predicates to the SettingMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *SettingMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.Setting, len(ps)) - for i := range ps { - p[i] = ps[i] +// Value returns the value of the "value" field in the mutation. +func (m *SecuritySecretMutation) Value() (r string, exists bool) { + v := m.value + if v == nil { + return } - m.Where(p...) + return *v, true +} + +// OldValue returns the old "value" field's value of the SecuritySecret entity. +// If the SecuritySecret object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SecuritySecretMutation) OldValue(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldValue is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldValue requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldValue: %w", err) + } + return oldValue.Value, nil +} + +// ResetValue resets all changes to the "value" field. +func (m *SecuritySecretMutation) ResetValue() { + m.value = nil +} + +// Where appends a list predicates to the SecuritySecretMutation builder. +func (m *SecuritySecretMutation) Where(ps ...predicate.SecuritySecret) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the SecuritySecretMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *SecuritySecretMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.SecuritySecret, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) } // Op returns the operation name. -func (m *SettingMutation) Op() Op { +func (m *SecuritySecretMutation) Op() Op { return m.op } // SetOp allows setting the mutation operation. -func (m *SettingMutation) SetOp(op Op) { +func (m *SecuritySecretMutation) SetOp(op Op) { m.op = op } -// Type returns the node type of this mutation (Setting). -func (m *SettingMutation) Type() string { +// Type returns the node type of this mutation (SecuritySecret). +func (m *SecuritySecretMutation) Type() string { return m.typ } // Fields returns all fields that were changed during this mutation. Note that in // order to get all numeric fields that were incremented/decremented, call // AddedFields(). -func (m *SettingMutation) Fields() []string { - fields := make([]string, 0, 3) +func (m *SecuritySecretMutation) Fields() []string { + fields := make([]string, 0, 4) + if m.created_at != nil { + fields = append(fields, securitysecret.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, securitysecret.FieldUpdatedAt) + } if m.key != nil { - fields = append(fields, setting.FieldKey) + fields = append(fields, securitysecret.FieldKey) } if m.value != nil { - fields = append(fields, setting.FieldValue) - } - if m.updated_at != nil { - fields = append(fields, setting.FieldUpdatedAt) + fields = append(fields, securitysecret.FieldValue) } return fields } @@ -16716,14 +17037,16 @@ func (m *SettingMutation) Fields() []string { // Field returns the value of a field with the given name. The second boolean // return value indicates that this field was not set, or was not defined in the // schema. -func (m *SettingMutation) Field(name string) (ent.Value, bool) { +func (m *SecuritySecretMutation) Field(name string) (ent.Value, bool) { switch name { - case setting.FieldKey: + case securitysecret.FieldCreatedAt: + return m.CreatedAt() + case securitysecret.FieldUpdatedAt: + return m.UpdatedAt() + case securitysecret.FieldKey: return m.Key() - case setting.FieldValue: + case securitysecret.FieldValue: return m.Value() - case setting.FieldUpdatedAt: - return m.UpdatedAt() } return nil, false } @@ -16731,192 +17054,192 @@ func (m *SettingMutation) Field(name string) (ent.Value, bool) { // OldField returns the old value of the field from the database. An error is // returned if the mutation operation is not UpdateOne, or the query to the // database failed. -func (m *SettingMutation) OldField(ctx context.Context, name string) (ent.Value, error) { +func (m *SecuritySecretMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { - case setting.FieldKey: + case securitysecret.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case securitysecret.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case securitysecret.FieldKey: return m.OldKey(ctx) - case setting.FieldValue: + case securitysecret.FieldValue: return m.OldValue(ctx) - case setting.FieldUpdatedAt: - return m.OldUpdatedAt(ctx) } - return nil, fmt.Errorf("unknown Setting field %s", name) + return nil, fmt.Errorf("unknown SecuritySecret field %s", name) } // SetField sets the value of a field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *SettingMutation) SetField(name string, value ent.Value) error { +func (m *SecuritySecretMutation) SetField(name string, value ent.Value) error { switch name { - case setting.FieldKey: - v, ok := value.(string) + case securitysecret.FieldCreatedAt: + v, ok := value.(time.Time) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetKey(v) + m.SetCreatedAt(v) return nil - case setting.FieldValue: + case securitysecret.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + case securitysecret.FieldKey: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetValue(v) + m.SetKey(v) return nil - case setting.FieldUpdatedAt: - v, ok := value.(time.Time) + case securitysecret.FieldValue: + v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetUpdatedAt(v) + m.SetValue(v) return nil } - return fmt.Errorf("unknown Setting field %s", name) + return fmt.Errorf("unknown SecuritySecret field %s", name) } // AddedFields returns all numeric fields that were incremented/decremented during // this mutation. -func (m *SettingMutation) AddedFields() []string { +func (m *SecuritySecretMutation) AddedFields() []string { return nil } // AddedField returns the numeric value that was incremented/decremented on a field // with the given name. The second boolean return value indicates that this field // was not set, or was not defined in the schema. -func (m *SettingMutation) AddedField(name string) (ent.Value, bool) { +func (m *SecuritySecretMutation) AddedField(name string) (ent.Value, bool) { return nil, false } // AddField adds the value to the field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *SettingMutation) AddField(name string, value ent.Value) error { +func (m *SecuritySecretMutation) AddField(name string, value ent.Value) error { switch name { } - return fmt.Errorf("unknown Setting numeric field %s", name) + return fmt.Errorf("unknown SecuritySecret numeric field %s", name) } // ClearedFields returns all nullable fields that were cleared during this // mutation. -func (m *SettingMutation) ClearedFields() []string { +func (m *SecuritySecretMutation) ClearedFields() []string { return nil } // FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. -func (m *SettingMutation) FieldCleared(name string) bool { +func (m *SecuritySecretMutation) FieldCleared(name string) bool { _, ok := m.clearedFields[name] return ok } // ClearField clears the value of the field with the given name. It returns an // error if the field is not defined in the schema. -func (m *SettingMutation) ClearField(name string) error { - return fmt.Errorf("unknown Setting nullable field %s", name) +func (m *SecuritySecretMutation) ClearField(name string) error { + return fmt.Errorf("unknown SecuritySecret nullable field %s", name) } // ResetField resets all changes in the mutation for the field with the given name. // It returns an error if the field is not defined in the schema. -func (m *SettingMutation) ResetField(name string) error { +func (m *SecuritySecretMutation) ResetField(name string) error { switch name { - case setting.FieldKey: + case securitysecret.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case securitysecret.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case securitysecret.FieldKey: m.ResetKey() return nil - case setting.FieldValue: + case securitysecret.FieldValue: m.ResetValue() return nil - case setting.FieldUpdatedAt: - m.ResetUpdatedAt() - return nil } - return fmt.Errorf("unknown Setting field %s", name) + return fmt.Errorf("unknown SecuritySecret field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. -func (m *SettingMutation) AddedEdges() []string { +func (m *SecuritySecretMutation) AddedEdges() []string { edges := make([]string, 0, 0) return edges } // AddedIDs returns all IDs (to other nodes) that were added for the given edge // name in this mutation. -func (m *SettingMutation) AddedIDs(name string) []ent.Value { +func (m *SecuritySecretMutation) AddedIDs(name string) []ent.Value { return nil } // RemovedEdges returns all edge names that were removed in this mutation. -func (m *SettingMutation) RemovedEdges() []string { +func (m *SecuritySecretMutation) RemovedEdges() []string { edges := make([]string, 0, 0) return edges } // RemovedIDs returns all IDs (to other nodes) that were removed for the edge with // the given name in this mutation. -func (m *SettingMutation) RemovedIDs(name string) []ent.Value { +func (m *SecuritySecretMutation) RemovedIDs(name string) []ent.Value { return nil } // ClearedEdges returns all edge names that were cleared in this mutation. -func (m *SettingMutation) ClearedEdges() []string { +func (m *SecuritySecretMutation) ClearedEdges() []string { edges := make([]string, 0, 0) return edges } // EdgeCleared returns a boolean which indicates if the edge with the given name // was cleared in this mutation. -func (m *SettingMutation) EdgeCleared(name string) bool { +func (m *SecuritySecretMutation) EdgeCleared(name string) bool { return false } // ClearEdge clears the value of the edge with the given name. It returns an error // if that edge is not defined in the schema. -func (m *SettingMutation) ClearEdge(name string) error { - return fmt.Errorf("unknown Setting unique edge %s", name) +func (m *SecuritySecretMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown SecuritySecret unique edge %s", name) } // ResetEdge resets all changes to the edge with the given name in this mutation. // It returns an error if the edge is not defined in the schema. -func (m *SettingMutation) ResetEdge(name string) error { - return fmt.Errorf("unknown Setting edge %s", name) +func (m *SecuritySecretMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown SecuritySecret edge %s", name) } -// UsageCleanupTaskMutation represents an operation that mutates the UsageCleanupTask nodes in the graph. -type UsageCleanupTaskMutation struct { +// SettingMutation represents an operation that mutates the Setting nodes in the graph. +type SettingMutation struct { config - op Op - typ string - id *int64 - created_at *time.Time - updated_at *time.Time - status *string - filters *json.RawMessage - appendfilters json.RawMessage - created_by *int64 - addcreated_by *int64 - deleted_rows *int64 - adddeleted_rows *int64 - error_message *string - canceled_by *int64 - addcanceled_by *int64 - canceled_at *time.Time - started_at *time.Time - finished_at *time.Time - clearedFields map[string]struct{} - done bool - oldValue func(context.Context) (*UsageCleanupTask, error) - predicates []predicate.UsageCleanupTask + op Op + typ string + id *int64 + key *string + value *string + updated_at *time.Time + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*Setting, error) + predicates []predicate.Setting } -var _ ent.Mutation = (*UsageCleanupTaskMutation)(nil) +var _ ent.Mutation = (*SettingMutation)(nil) -// usagecleanuptaskOption allows management of the mutation configuration using functional options. -type usagecleanuptaskOption func(*UsageCleanupTaskMutation) +// settingOption allows management of the mutation configuration using functional options. +type settingOption func(*SettingMutation) -// newUsageCleanupTaskMutation creates new mutation for the UsageCleanupTask entity. -func newUsageCleanupTaskMutation(c config, op Op, opts ...usagecleanuptaskOption) *UsageCleanupTaskMutation { - m := &UsageCleanupTaskMutation{ +// newSettingMutation creates new mutation for the Setting entity. +func newSettingMutation(c config, op Op, opts ...settingOption) *SettingMutation { + m := &SettingMutation{ config: c, op: op, - typ: TypeUsageCleanupTask, + typ: TypeSetting, clearedFields: make(map[string]struct{}), } for _, opt := range opts { @@ -16925,20 +17248,20 @@ func newUsageCleanupTaskMutation(c config, op Op, opts ...usagecleanuptaskOption return m } -// withUsageCleanupTaskID sets the ID field of the mutation. -func withUsageCleanupTaskID(id int64) usagecleanuptaskOption { - return func(m *UsageCleanupTaskMutation) { +// withSettingID sets the ID field of the mutation. +func withSettingID(id int64) settingOption { + return func(m *SettingMutation) { var ( err error once sync.Once - value *UsageCleanupTask + value *Setting ) - m.oldValue = func(ctx context.Context) (*UsageCleanupTask, error) { + m.oldValue = func(ctx context.Context) (*Setting, error) { once.Do(func() { if m.done { err = errors.New("querying old values post mutation is not allowed") } else { - value, err = m.Client().UsageCleanupTask.Get(ctx, id) + value, err = m.Client().Setting.Get(ctx, id) } }) return value, err @@ -16947,10 +17270,10 @@ func withUsageCleanupTaskID(id int64) usagecleanuptaskOption { } } -// withUsageCleanupTask sets the old UsageCleanupTask of the mutation. -func withUsageCleanupTask(node *UsageCleanupTask) usagecleanuptaskOption { - return func(m *UsageCleanupTaskMutation) { - m.oldValue = func(context.Context) (*UsageCleanupTask, error) { +// withSetting sets the old Setting of the mutation. +func withSetting(node *Setting) settingOption { + return func(m *SettingMutation) { + m.oldValue = func(context.Context) (*Setting, error) { return node, nil } m.id = &node.ID @@ -16959,7 +17282,7 @@ func withUsageCleanupTask(node *UsageCleanupTask) usagecleanuptaskOption { // Client returns a new `ent.Client` from the mutation. If the mutation was // executed in a transaction (ent.Tx), a transactional client is returned. -func (m UsageCleanupTaskMutation) Client() *Client { +func (m SettingMutation) Client() *Client { client := &Client{config: m.config} client.init() return client @@ -16967,7 +17290,7 @@ func (m UsageCleanupTaskMutation) Client() *Client { // Tx returns an `ent.Tx` for mutations that were executed in transactions; // it returns an error otherwise. -func (m UsageCleanupTaskMutation) Tx() (*Tx, error) { +func (m SettingMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { return nil, errors.New("ent: mutation is not running in a transaction") } @@ -16978,7 +17301,7 @@ func (m UsageCleanupTaskMutation) Tx() (*Tx, error) { // ID returns the ID value in the mutation. Note that the ID is only available // if it was provided to the builder or after it was returned from the database. -func (m *UsageCleanupTaskMutation) ID() (id int64, exists bool) { +func (m *SettingMutation) ID() (id int64, exists bool) { if m.id == nil { return } @@ -16989,7 +17312,7 @@ func (m *UsageCleanupTaskMutation) ID() (id int64, exists bool) { // That means, if the mutation is applied within a transaction with an isolation level such // as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated // or updated by the mutation. -func (m *UsageCleanupTaskMutation) IDs(ctx context.Context) ([]int64, error) { +func (m *SettingMutation) IDs(ctx context.Context) ([]int64, error) { switch { case m.op.Is(OpUpdateOne | OpDeleteOne): id, exists := m.ID() @@ -16998,3107 +17321,3553 @@ func (m *UsageCleanupTaskMutation) IDs(ctx context.Context) ([]int64, error) { } fallthrough case m.op.Is(OpUpdate | OpDelete): - return m.Client().UsageCleanupTask.Query().Where(m.predicates...).IDs(ctx) + return m.Client().Setting.Query().Where(m.predicates...).IDs(ctx) default: return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } } -// SetCreatedAt sets the "created_at" field. -func (m *UsageCleanupTaskMutation) SetCreatedAt(t time.Time) { - m.created_at = &t +// SetKey sets the "key" field. +func (m *SettingMutation) SetKey(s string) { + m.key = &s } -// CreatedAt returns the value of the "created_at" field in the mutation. -func (m *UsageCleanupTaskMutation) CreatedAt() (r time.Time, exists bool) { - v := m.created_at +// Key returns the value of the "key" field in the mutation. +func (m *SettingMutation) Key() (r string, exists bool) { + v := m.key if v == nil { return } return *v, true } -// OldCreatedAt returns the old "created_at" field's value of the UsageCleanupTask entity. -// If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database. +// OldKey returns the old "key" field's value of the Setting entity. +// If the Setting object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageCleanupTaskMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { +func (m *SettingMutation) OldKey(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + return v, errors.New("OldKey is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCreatedAt requires an ID field in the mutation") + return v, errors.New("OldKey requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + return v, fmt.Errorf("querying old value for OldKey: %w", err) } - return oldValue.CreatedAt, nil + return oldValue.Key, nil } -// ResetCreatedAt resets all changes to the "created_at" field. -func (m *UsageCleanupTaskMutation) ResetCreatedAt() { - m.created_at = nil +// ResetKey resets all changes to the "key" field. +func (m *SettingMutation) ResetKey() { + m.key = nil } -// SetUpdatedAt sets the "updated_at" field. -func (m *UsageCleanupTaskMutation) SetUpdatedAt(t time.Time) { - m.updated_at = &t +// SetValue sets the "value" field. +func (m *SettingMutation) SetValue(s string) { + m.value = &s } -// UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *UsageCleanupTaskMutation) UpdatedAt() (r time.Time, exists bool) { - v := m.updated_at +// Value returns the value of the "value" field in the mutation. +func (m *SettingMutation) Value() (r string, exists bool) { + v := m.value if v == nil { return } return *v, true } -// OldUpdatedAt returns the old "updated_at" field's value of the UsageCleanupTask entity. -// If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database. +// OldValue returns the old "value" field's value of the Setting entity. +// If the Setting object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageCleanupTaskMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { +func (m *SettingMutation) OldValue(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + return v, errors.New("OldValue is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUpdatedAt requires an ID field in the mutation") + return v, errors.New("OldValue requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + return v, fmt.Errorf("querying old value for OldValue: %w", err) } - return oldValue.UpdatedAt, nil + return oldValue.Value, nil } -// ResetUpdatedAt resets all changes to the "updated_at" field. -func (m *UsageCleanupTaskMutation) ResetUpdatedAt() { - m.updated_at = nil +// ResetValue resets all changes to the "value" field. +func (m *SettingMutation) ResetValue() { + m.value = nil } -// SetStatus sets the "status" field. -func (m *UsageCleanupTaskMutation) SetStatus(s string) { - m.status = &s +// SetUpdatedAt sets the "updated_at" field. +func (m *SettingMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t } -// Status returns the value of the "status" field in the mutation. -func (m *UsageCleanupTaskMutation) Status() (r string, exists bool) { - v := m.status +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *SettingMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at if v == nil { return } return *v, true } -// OldStatus returns the old "status" field's value of the UsageCleanupTask entity. -// If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database. +// OldUpdatedAt returns the old "updated_at" field's value of the Setting entity. +// If the Setting object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageCleanupTaskMutation) OldStatus(ctx context.Context) (v string, err error) { +func (m *SettingMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldStatus is only allowed on UpdateOne operations") + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldStatus requires an ID field in the mutation") + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldStatus: %w", err) - } - return oldValue.Status, nil -} - -// ResetStatus resets all changes to the "status" field. -func (m *UsageCleanupTaskMutation) ResetStatus() { - m.status = nil -} - -// SetFilters sets the "filters" field. -func (m *UsageCleanupTaskMutation) SetFilters(jm json.RawMessage) { - m.filters = &jm - m.appendfilters = nil -} - -// Filters returns the value of the "filters" field in the mutation. -func (m *UsageCleanupTaskMutation) Filters() (r json.RawMessage, exists bool) { - v := m.filters - if v == nil { - return + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) } - return *v, true + return oldValue.UpdatedAt, nil } -// OldFilters returns the old "filters" field's value of the UsageCleanupTask entity. -// If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageCleanupTaskMutation) OldFilters(ctx context.Context) (v json.RawMessage, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldFilters is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldFilters requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldFilters: %w", err) - } - return oldValue.Filters, nil +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *SettingMutation) ResetUpdatedAt() { + m.updated_at = nil } -// AppendFilters adds jm to the "filters" field. -func (m *UsageCleanupTaskMutation) AppendFilters(jm json.RawMessage) { - m.appendfilters = append(m.appendfilters, jm...) +// Where appends a list predicates to the SettingMutation builder. +func (m *SettingMutation) Where(ps ...predicate.Setting) { + m.predicates = append(m.predicates, ps...) } -// AppendedFilters returns the list of values that were appended to the "filters" field in this mutation. -func (m *UsageCleanupTaskMutation) AppendedFilters() (json.RawMessage, bool) { - if len(m.appendfilters) == 0 { - return nil, false +// WhereP appends storage-level predicates to the SettingMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *SettingMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Setting, len(ps)) + for i := range ps { + p[i] = ps[i] } - return m.appendfilters, true + m.Where(p...) } -// ResetFilters resets all changes to the "filters" field. -func (m *UsageCleanupTaskMutation) ResetFilters() { - m.filters = nil - m.appendfilters = nil +// Op returns the operation name. +func (m *SettingMutation) Op() Op { + return m.op } -// SetCreatedBy sets the "created_by" field. -func (m *UsageCleanupTaskMutation) SetCreatedBy(i int64) { - m.created_by = &i - m.addcreated_by = nil +// SetOp allows setting the mutation operation. +func (m *SettingMutation) SetOp(op Op) { + m.op = op } -// CreatedBy returns the value of the "created_by" field in the mutation. -func (m *UsageCleanupTaskMutation) CreatedBy() (r int64, exists bool) { - v := m.created_by - if v == nil { - return - } - return *v, true +// Type returns the node type of this mutation (Setting). +func (m *SettingMutation) Type() string { + return m.typ } -// OldCreatedBy returns the old "created_by" field's value of the UsageCleanupTask entity. -// If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageCleanupTaskMutation) OldCreatedBy(ctx context.Context) (v int64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCreatedBy is only allowed on UpdateOne operations") +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *SettingMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.key != nil { + fields = append(fields, setting.FieldKey) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCreatedBy requires an ID field in the mutation") + if m.value != nil { + fields = append(fields, setting.FieldValue) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldCreatedBy: %w", err) + if m.updated_at != nil { + fields = append(fields, setting.FieldUpdatedAt) } - return oldValue.CreatedBy, nil + return fields } -// AddCreatedBy adds i to the "created_by" field. -func (m *UsageCleanupTaskMutation) AddCreatedBy(i int64) { - if m.addcreated_by != nil { - *m.addcreated_by += i - } else { - m.addcreated_by = &i +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *SettingMutation) Field(name string) (ent.Value, bool) { + switch name { + case setting.FieldKey: + return m.Key() + case setting.FieldValue: + return m.Value() + case setting.FieldUpdatedAt: + return m.UpdatedAt() } + return nil, false } -// AddedCreatedBy returns the value that was added to the "created_by" field in this mutation. -func (m *UsageCleanupTaskMutation) AddedCreatedBy() (r int64, exists bool) { - v := m.addcreated_by - if v == nil { - return +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *SettingMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case setting.FieldKey: + return m.OldKey(ctx) + case setting.FieldValue: + return m.OldValue(ctx) + case setting.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) } - return *v, true + return nil, fmt.Errorf("unknown Setting field %s", name) } -// ResetCreatedBy resets all changes to the "created_by" field. -func (m *UsageCleanupTaskMutation) ResetCreatedBy() { - m.created_by = nil - m.addcreated_by = nil +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *SettingMutation) SetField(name string, value ent.Value) error { + switch name { + case setting.FieldKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetKey(v) + return nil + case setting.FieldValue: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetValue(v) + return nil + case setting.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + } + return fmt.Errorf("unknown Setting field %s", name) } -// SetDeletedRows sets the "deleted_rows" field. -func (m *UsageCleanupTaskMutation) SetDeletedRows(i int64) { - m.deleted_rows = &i - m.adddeleted_rows = nil -} - -// DeletedRows returns the value of the "deleted_rows" field in the mutation. -func (m *UsageCleanupTaskMutation) DeletedRows() (r int64, exists bool) { - v := m.deleted_rows - if v == nil { - return - } - return *v, true -} - -// OldDeletedRows returns the old "deleted_rows" field's value of the UsageCleanupTask entity. -// If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageCleanupTaskMutation) OldDeletedRows(ctx context.Context) (v int64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldDeletedRows is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldDeletedRows requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldDeletedRows: %w", err) - } - return oldValue.DeletedRows, nil +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *SettingMutation) AddedFields() []string { + return nil } -// AddDeletedRows adds i to the "deleted_rows" field. -func (m *UsageCleanupTaskMutation) AddDeletedRows(i int64) { - if m.adddeleted_rows != nil { - *m.adddeleted_rows += i - } else { - m.adddeleted_rows = &i - } +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *SettingMutation) AddedField(name string) (ent.Value, bool) { + return nil, false } -// AddedDeletedRows returns the value that was added to the "deleted_rows" field in this mutation. -func (m *UsageCleanupTaskMutation) AddedDeletedRows() (r int64, exists bool) { - v := m.adddeleted_rows - if v == nil { - return +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *SettingMutation) AddField(name string, value ent.Value) error { + switch name { } - return *v, true + return fmt.Errorf("unknown Setting numeric field %s", name) } -// ResetDeletedRows resets all changes to the "deleted_rows" field. -func (m *UsageCleanupTaskMutation) ResetDeletedRows() { - m.deleted_rows = nil - m.adddeleted_rows = nil +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *SettingMutation) ClearedFields() []string { + return nil } -// SetErrorMessage sets the "error_message" field. -func (m *UsageCleanupTaskMutation) SetErrorMessage(s string) { - m.error_message = &s +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *SettingMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok } -// ErrorMessage returns the value of the "error_message" field in the mutation. -func (m *UsageCleanupTaskMutation) ErrorMessage() (r string, exists bool) { - v := m.error_message - if v == nil { - return - } - return *v, true +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *SettingMutation) ClearField(name string) error { + return fmt.Errorf("unknown Setting nullable field %s", name) } -// OldErrorMessage returns the old "error_message" field's value of the UsageCleanupTask entity. -// If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageCleanupTaskMutation) OldErrorMessage(ctx context.Context) (v *string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldErrorMessage is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldErrorMessage requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldErrorMessage: %w", err) +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *SettingMutation) ResetField(name string) error { + switch name { + case setting.FieldKey: + m.ResetKey() + return nil + case setting.FieldValue: + m.ResetValue() + return nil + case setting.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil } - return oldValue.ErrorMessage, nil + return fmt.Errorf("unknown Setting field %s", name) } -// ClearErrorMessage clears the value of the "error_message" field. -func (m *UsageCleanupTaskMutation) ClearErrorMessage() { - m.error_message = nil - m.clearedFields[usagecleanuptask.FieldErrorMessage] = struct{}{} +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *SettingMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges } -// ErrorMessageCleared returns if the "error_message" field was cleared in this mutation. -func (m *UsageCleanupTaskMutation) ErrorMessageCleared() bool { - _, ok := m.clearedFields[usagecleanuptask.FieldErrorMessage] - return ok +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *SettingMutation) AddedIDs(name string) []ent.Value { + return nil } -// ResetErrorMessage resets all changes to the "error_message" field. -func (m *UsageCleanupTaskMutation) ResetErrorMessage() { - m.error_message = nil - delete(m.clearedFields, usagecleanuptask.FieldErrorMessage) +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *SettingMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges } -// SetCanceledBy sets the "canceled_by" field. -func (m *UsageCleanupTaskMutation) SetCanceledBy(i int64) { - m.canceled_by = &i - m.addcanceled_by = nil +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *SettingMutation) RemovedIDs(name string) []ent.Value { + return nil } -// CanceledBy returns the value of the "canceled_by" field in the mutation. -func (m *UsageCleanupTaskMutation) CanceledBy() (r int64, exists bool) { - v := m.canceled_by - if v == nil { - return - } - return *v, true +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *SettingMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges } -// OldCanceledBy returns the old "canceled_by" field's value of the UsageCleanupTask entity. -// If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageCleanupTaskMutation) OldCanceledBy(ctx context.Context) (v *int64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCanceledBy is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCanceledBy requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldCanceledBy: %w", err) - } - return oldValue.CanceledBy, nil +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *SettingMutation) EdgeCleared(name string) bool { + return false } -// AddCanceledBy adds i to the "canceled_by" field. -func (m *UsageCleanupTaskMutation) AddCanceledBy(i int64) { - if m.addcanceled_by != nil { - *m.addcanceled_by += i - } else { - m.addcanceled_by = &i - } +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *SettingMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown Setting unique edge %s", name) } -// AddedCanceledBy returns the value that was added to the "canceled_by" field in this mutation. -func (m *UsageCleanupTaskMutation) AddedCanceledBy() (r int64, exists bool) { - v := m.addcanceled_by - if v == nil { - return - } - return *v, true +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *SettingMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown Setting edge %s", name) } -// ClearCanceledBy clears the value of the "canceled_by" field. -func (m *UsageCleanupTaskMutation) ClearCanceledBy() { - m.canceled_by = nil - m.addcanceled_by = nil - m.clearedFields[usagecleanuptask.FieldCanceledBy] = struct{}{} +// UsageCleanupTaskMutation represents an operation that mutates the UsageCleanupTask nodes in the graph. +type UsageCleanupTaskMutation struct { + config + op Op + typ string + id *int64 + created_at *time.Time + updated_at *time.Time + status *string + filters *json.RawMessage + appendfilters json.RawMessage + created_by *int64 + addcreated_by *int64 + deleted_rows *int64 + adddeleted_rows *int64 + error_message *string + canceled_by *int64 + addcanceled_by *int64 + canceled_at *time.Time + started_at *time.Time + finished_at *time.Time + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*UsageCleanupTask, error) + predicates []predicate.UsageCleanupTask } -// CanceledByCleared returns if the "canceled_by" field was cleared in this mutation. -func (m *UsageCleanupTaskMutation) CanceledByCleared() bool { - _, ok := m.clearedFields[usagecleanuptask.FieldCanceledBy] - return ok -} +var _ ent.Mutation = (*UsageCleanupTaskMutation)(nil) -// ResetCanceledBy resets all changes to the "canceled_by" field. -func (m *UsageCleanupTaskMutation) ResetCanceledBy() { - m.canceled_by = nil - m.addcanceled_by = nil - delete(m.clearedFields, usagecleanuptask.FieldCanceledBy) -} +// usagecleanuptaskOption allows management of the mutation configuration using functional options. +type usagecleanuptaskOption func(*UsageCleanupTaskMutation) -// SetCanceledAt sets the "canceled_at" field. -func (m *UsageCleanupTaskMutation) SetCanceledAt(t time.Time) { - m.canceled_at = &t +// newUsageCleanupTaskMutation creates new mutation for the UsageCleanupTask entity. +func newUsageCleanupTaskMutation(c config, op Op, opts ...usagecleanuptaskOption) *UsageCleanupTaskMutation { + m := &UsageCleanupTaskMutation{ + config: c, + op: op, + typ: TypeUsageCleanupTask, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m } -// CanceledAt returns the value of the "canceled_at" field in the mutation. -func (m *UsageCleanupTaskMutation) CanceledAt() (r time.Time, exists bool) { - v := m.canceled_at +// withUsageCleanupTaskID sets the ID field of the mutation. +func withUsageCleanupTaskID(id int64) usagecleanuptaskOption { + return func(m *UsageCleanupTaskMutation) { + var ( + err error + once sync.Once + value *UsageCleanupTask + ) + m.oldValue = func(ctx context.Context) (*UsageCleanupTask, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().UsageCleanupTask.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withUsageCleanupTask sets the old UsageCleanupTask of the mutation. +func withUsageCleanupTask(node *UsageCleanupTask) usagecleanuptaskOption { + return func(m *UsageCleanupTaskMutation) { + m.oldValue = func(context.Context) (*UsageCleanupTask, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m UsageCleanupTaskMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m UsageCleanupTaskMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *UsageCleanupTaskMutation) ID() (id int64, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *UsageCleanupTaskMutation) IDs(ctx context.Context) ([]int64, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int64{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().UsageCleanupTask.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetCreatedAt sets the "created_at" field. +func (m *UsageCleanupTaskMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *UsageCleanupTaskMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at if v == nil { return } return *v, true } -// OldCanceledAt returns the old "canceled_at" field's value of the UsageCleanupTask entity. +// OldCreatedAt returns the old "created_at" field's value of the UsageCleanupTask entity. // If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageCleanupTaskMutation) OldCanceledAt(ctx context.Context) (v *time.Time, err error) { +func (m *UsageCleanupTaskMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCanceledAt is only allowed on UpdateOne operations") + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCanceledAt requires an ID field in the mutation") + return v, errors.New("OldCreatedAt requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldCanceledAt: %w", err) + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) } - return oldValue.CanceledAt, nil -} - -// ClearCanceledAt clears the value of the "canceled_at" field. -func (m *UsageCleanupTaskMutation) ClearCanceledAt() { - m.canceled_at = nil - m.clearedFields[usagecleanuptask.FieldCanceledAt] = struct{}{} -} - -// CanceledAtCleared returns if the "canceled_at" field was cleared in this mutation. -func (m *UsageCleanupTaskMutation) CanceledAtCleared() bool { - _, ok := m.clearedFields[usagecleanuptask.FieldCanceledAt] - return ok + return oldValue.CreatedAt, nil } -// ResetCanceledAt resets all changes to the "canceled_at" field. -func (m *UsageCleanupTaskMutation) ResetCanceledAt() { - m.canceled_at = nil - delete(m.clearedFields, usagecleanuptask.FieldCanceledAt) +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *UsageCleanupTaskMutation) ResetCreatedAt() { + m.created_at = nil } -// SetStartedAt sets the "started_at" field. -func (m *UsageCleanupTaskMutation) SetStartedAt(t time.Time) { - m.started_at = &t +// SetUpdatedAt sets the "updated_at" field. +func (m *UsageCleanupTaskMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t } -// StartedAt returns the value of the "started_at" field in the mutation. -func (m *UsageCleanupTaskMutation) StartedAt() (r time.Time, exists bool) { - v := m.started_at +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *UsageCleanupTaskMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at if v == nil { return } return *v, true } -// OldStartedAt returns the old "started_at" field's value of the UsageCleanupTask entity. +// OldUpdatedAt returns the old "updated_at" field's value of the UsageCleanupTask entity. // If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageCleanupTaskMutation) OldStartedAt(ctx context.Context) (v *time.Time, err error) { +func (m *UsageCleanupTaskMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldStartedAt is only allowed on UpdateOne operations") + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldStartedAt requires an ID field in the mutation") + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldStartedAt: %w", err) + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) } - return oldValue.StartedAt, nil -} - -// ClearStartedAt clears the value of the "started_at" field. -func (m *UsageCleanupTaskMutation) ClearStartedAt() { - m.started_at = nil - m.clearedFields[usagecleanuptask.FieldStartedAt] = struct{}{} -} - -// StartedAtCleared returns if the "started_at" field was cleared in this mutation. -func (m *UsageCleanupTaskMutation) StartedAtCleared() bool { - _, ok := m.clearedFields[usagecleanuptask.FieldStartedAt] - return ok + return oldValue.UpdatedAt, nil } -// ResetStartedAt resets all changes to the "started_at" field. -func (m *UsageCleanupTaskMutation) ResetStartedAt() { - m.started_at = nil - delete(m.clearedFields, usagecleanuptask.FieldStartedAt) +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *UsageCleanupTaskMutation) ResetUpdatedAt() { + m.updated_at = nil } -// SetFinishedAt sets the "finished_at" field. -func (m *UsageCleanupTaskMutation) SetFinishedAt(t time.Time) { - m.finished_at = &t +// SetStatus sets the "status" field. +func (m *UsageCleanupTaskMutation) SetStatus(s string) { + m.status = &s } -// FinishedAt returns the value of the "finished_at" field in the mutation. -func (m *UsageCleanupTaskMutation) FinishedAt() (r time.Time, exists bool) { - v := m.finished_at +// Status returns the value of the "status" field in the mutation. +func (m *UsageCleanupTaskMutation) Status() (r string, exists bool) { + v := m.status if v == nil { return } return *v, true } -// OldFinishedAt returns the old "finished_at" field's value of the UsageCleanupTask entity. +// OldStatus returns the old "status" field's value of the UsageCleanupTask entity. // If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageCleanupTaskMutation) OldFinishedAt(ctx context.Context) (v *time.Time, err error) { +func (m *UsageCleanupTaskMutation) OldStatus(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldFinishedAt is only allowed on UpdateOne operations") + return v, errors.New("OldStatus is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldFinishedAt requires an ID field in the mutation") + return v, errors.New("OldStatus requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldFinishedAt: %w", err) + return v, fmt.Errorf("querying old value for OldStatus: %w", err) } - return oldValue.FinishedAt, nil -} - -// ClearFinishedAt clears the value of the "finished_at" field. -func (m *UsageCleanupTaskMutation) ClearFinishedAt() { - m.finished_at = nil - m.clearedFields[usagecleanuptask.FieldFinishedAt] = struct{}{} + return oldValue.Status, nil } -// FinishedAtCleared returns if the "finished_at" field was cleared in this mutation. -func (m *UsageCleanupTaskMutation) FinishedAtCleared() bool { - _, ok := m.clearedFields[usagecleanuptask.FieldFinishedAt] - return ok +// ResetStatus resets all changes to the "status" field. +func (m *UsageCleanupTaskMutation) ResetStatus() { + m.status = nil } -// ResetFinishedAt resets all changes to the "finished_at" field. -func (m *UsageCleanupTaskMutation) ResetFinishedAt() { - m.finished_at = nil - delete(m.clearedFields, usagecleanuptask.FieldFinishedAt) +// SetFilters sets the "filters" field. +func (m *UsageCleanupTaskMutation) SetFilters(jm json.RawMessage) { + m.filters = &jm + m.appendfilters = nil } -// Where appends a list predicates to the UsageCleanupTaskMutation builder. -func (m *UsageCleanupTaskMutation) Where(ps ...predicate.UsageCleanupTask) { - m.predicates = append(m.predicates, ps...) +// Filters returns the value of the "filters" field in the mutation. +func (m *UsageCleanupTaskMutation) Filters() (r json.RawMessage, exists bool) { + v := m.filters + if v == nil { + return + } + return *v, true } -// WhereP appends storage-level predicates to the UsageCleanupTaskMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *UsageCleanupTaskMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.UsageCleanupTask, len(ps)) - for i := range ps { - p[i] = ps[i] +// OldFilters returns the old "filters" field's value of the UsageCleanupTask entity. +// If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UsageCleanupTaskMutation) OldFilters(ctx context.Context) (v json.RawMessage, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFilters is only allowed on UpdateOne operations") } - m.Where(p...) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFilters requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFilters: %w", err) + } + return oldValue.Filters, nil } -// Op returns the operation name. -func (m *UsageCleanupTaskMutation) Op() Op { - return m.op +// AppendFilters adds jm to the "filters" field. +func (m *UsageCleanupTaskMutation) AppendFilters(jm json.RawMessage) { + m.appendfilters = append(m.appendfilters, jm...) } -// SetOp allows setting the mutation operation. -func (m *UsageCleanupTaskMutation) SetOp(op Op) { - m.op = op +// AppendedFilters returns the list of values that were appended to the "filters" field in this mutation. +func (m *UsageCleanupTaskMutation) AppendedFilters() (json.RawMessage, bool) { + if len(m.appendfilters) == 0 { + return nil, false + } + return m.appendfilters, true } -// Type returns the node type of this mutation (UsageCleanupTask). -func (m *UsageCleanupTaskMutation) Type() string { - return m.typ +// ResetFilters resets all changes to the "filters" field. +func (m *UsageCleanupTaskMutation) ResetFilters() { + m.filters = nil + m.appendfilters = nil } -// Fields returns all fields that were changed during this mutation. Note that in -// order to get all numeric fields that were incremented/decremented, call -// AddedFields(). -func (m *UsageCleanupTaskMutation) Fields() []string { - fields := make([]string, 0, 11) - if m.created_at != nil { - fields = append(fields, usagecleanuptask.FieldCreatedAt) +// SetCreatedBy sets the "created_by" field. +func (m *UsageCleanupTaskMutation) SetCreatedBy(i int64) { + m.created_by = &i + m.addcreated_by = nil +} + +// CreatedBy returns the value of the "created_by" field in the mutation. +func (m *UsageCleanupTaskMutation) CreatedBy() (r int64, exists bool) { + v := m.created_by + if v == nil { + return } - if m.updated_at != nil { - fields = append(fields, usagecleanuptask.FieldUpdatedAt) + return *v, true +} + +// OldCreatedBy returns the old "created_by" field's value of the UsageCleanupTask entity. +// If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UsageCleanupTaskMutation) OldCreatedBy(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedBy is only allowed on UpdateOne operations") } - if m.status != nil { - fields = append(fields, usagecleanuptask.FieldStatus) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedBy requires an ID field in the mutation") } - if m.filters != nil { - fields = append(fields, usagecleanuptask.FieldFilters) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedBy: %w", err) } - if m.created_by != nil { - fields = append(fields, usagecleanuptask.FieldCreatedBy) + return oldValue.CreatedBy, nil +} + +// AddCreatedBy adds i to the "created_by" field. +func (m *UsageCleanupTaskMutation) AddCreatedBy(i int64) { + if m.addcreated_by != nil { + *m.addcreated_by += i + } else { + m.addcreated_by = &i } - if m.deleted_rows != nil { - fields = append(fields, usagecleanuptask.FieldDeletedRows) +} + +// AddedCreatedBy returns the value that was added to the "created_by" field in this mutation. +func (m *UsageCleanupTaskMutation) AddedCreatedBy() (r int64, exists bool) { + v := m.addcreated_by + if v == nil { + return } - if m.error_message != nil { - fields = append(fields, usagecleanuptask.FieldErrorMessage) + return *v, true +} + +// ResetCreatedBy resets all changes to the "created_by" field. +func (m *UsageCleanupTaskMutation) ResetCreatedBy() { + m.created_by = nil + m.addcreated_by = nil +} + +// SetDeletedRows sets the "deleted_rows" field. +func (m *UsageCleanupTaskMutation) SetDeletedRows(i int64) { + m.deleted_rows = &i + m.adddeleted_rows = nil +} + +// DeletedRows returns the value of the "deleted_rows" field in the mutation. +func (m *UsageCleanupTaskMutation) DeletedRows() (r int64, exists bool) { + v := m.deleted_rows + if v == nil { + return } - if m.canceled_by != nil { - fields = append(fields, usagecleanuptask.FieldCanceledBy) + return *v, true +} + +// OldDeletedRows returns the old "deleted_rows" field's value of the UsageCleanupTask entity. +// If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UsageCleanupTaskMutation) OldDeletedRows(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDeletedRows is only allowed on UpdateOne operations") } - if m.canceled_at != nil { - fields = append(fields, usagecleanuptask.FieldCanceledAt) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDeletedRows requires an ID field in the mutation") } - if m.started_at != nil { - fields = append(fields, usagecleanuptask.FieldStartedAt) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDeletedRows: %w", err) } - if m.finished_at != nil { - fields = append(fields, usagecleanuptask.FieldFinishedAt) + return oldValue.DeletedRows, nil +} + +// AddDeletedRows adds i to the "deleted_rows" field. +func (m *UsageCleanupTaskMutation) AddDeletedRows(i int64) { + if m.adddeleted_rows != nil { + *m.adddeleted_rows += i + } else { + m.adddeleted_rows = &i } - return fields } -// Field returns the value of a field with the given name. The second boolean -// return value indicates that this field was not set, or was not defined in the -// schema. -func (m *UsageCleanupTaskMutation) Field(name string) (ent.Value, bool) { - switch name { - case usagecleanuptask.FieldCreatedAt: - return m.CreatedAt() - case usagecleanuptask.FieldUpdatedAt: - return m.UpdatedAt() - case usagecleanuptask.FieldStatus: - return m.Status() - case usagecleanuptask.FieldFilters: - return m.Filters() - case usagecleanuptask.FieldCreatedBy: - return m.CreatedBy() - case usagecleanuptask.FieldDeletedRows: - return m.DeletedRows() - case usagecleanuptask.FieldErrorMessage: - return m.ErrorMessage() - case usagecleanuptask.FieldCanceledBy: - return m.CanceledBy() - case usagecleanuptask.FieldCanceledAt: - return m.CanceledAt() - case usagecleanuptask.FieldStartedAt: - return m.StartedAt() - case usagecleanuptask.FieldFinishedAt: - return m.FinishedAt() +// AddedDeletedRows returns the value that was added to the "deleted_rows" field in this mutation. +func (m *UsageCleanupTaskMutation) AddedDeletedRows() (r int64, exists bool) { + v := m.adddeleted_rows + if v == nil { + return } - return nil, false + return *v, true } -// OldField returns the old value of the field from the database. An error is -// returned if the mutation operation is not UpdateOne, or the query to the -// database failed. -func (m *UsageCleanupTaskMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case usagecleanuptask.FieldCreatedAt: - return m.OldCreatedAt(ctx) - case usagecleanuptask.FieldUpdatedAt: - return m.OldUpdatedAt(ctx) - case usagecleanuptask.FieldStatus: - return m.OldStatus(ctx) - case usagecleanuptask.FieldFilters: - return m.OldFilters(ctx) - case usagecleanuptask.FieldCreatedBy: - return m.OldCreatedBy(ctx) - case usagecleanuptask.FieldDeletedRows: - return m.OldDeletedRows(ctx) - case usagecleanuptask.FieldErrorMessage: - return m.OldErrorMessage(ctx) - case usagecleanuptask.FieldCanceledBy: - return m.OldCanceledBy(ctx) - case usagecleanuptask.FieldCanceledAt: - return m.OldCanceledAt(ctx) - case usagecleanuptask.FieldStartedAt: - return m.OldStartedAt(ctx) - case usagecleanuptask.FieldFinishedAt: - return m.OldFinishedAt(ctx) +// ResetDeletedRows resets all changes to the "deleted_rows" field. +func (m *UsageCleanupTaskMutation) ResetDeletedRows() { + m.deleted_rows = nil + m.adddeleted_rows = nil +} + +// SetErrorMessage sets the "error_message" field. +func (m *UsageCleanupTaskMutation) SetErrorMessage(s string) { + m.error_message = &s +} + +// ErrorMessage returns the value of the "error_message" field in the mutation. +func (m *UsageCleanupTaskMutation) ErrorMessage() (r string, exists bool) { + v := m.error_message + if v == nil { + return } - return nil, fmt.Errorf("unknown UsageCleanupTask field %s", name) + return *v, true } -// SetField sets the value of a field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *UsageCleanupTaskMutation) SetField(name string, value ent.Value) error { - switch name { - case usagecleanuptask.FieldCreatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCreatedAt(v) - return nil - case usagecleanuptask.FieldUpdatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUpdatedAt(v) - return nil - case usagecleanuptask.FieldStatus: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetStatus(v) - return nil - case usagecleanuptask.FieldFilters: - v, ok := value.(json.RawMessage) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetFilters(v) - return nil - case usagecleanuptask.FieldCreatedBy: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCreatedBy(v) - return nil - case usagecleanuptask.FieldDeletedRows: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetDeletedRows(v) - return nil - case usagecleanuptask.FieldErrorMessage: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetErrorMessage(v) - return nil - case usagecleanuptask.FieldCanceledBy: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCanceledBy(v) - return nil - case usagecleanuptask.FieldCanceledAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCanceledAt(v) - return nil - case usagecleanuptask.FieldStartedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetStartedAt(v) - return nil - case usagecleanuptask.FieldFinishedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetFinishedAt(v) - return nil - } - return fmt.Errorf("unknown UsageCleanupTask field %s", name) -} - -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *UsageCleanupTaskMutation) AddedFields() []string { - var fields []string - if m.addcreated_by != nil { - fields = append(fields, usagecleanuptask.FieldCreatedBy) +// OldErrorMessage returns the old "error_message" field's value of the UsageCleanupTask entity. +// If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UsageCleanupTaskMutation) OldErrorMessage(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldErrorMessage is only allowed on UpdateOne operations") } - if m.adddeleted_rows != nil { - fields = append(fields, usagecleanuptask.FieldDeletedRows) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldErrorMessage requires an ID field in the mutation") } - if m.addcanceled_by != nil { - fields = append(fields, usagecleanuptask.FieldCanceledBy) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldErrorMessage: %w", err) } - return fields + return oldValue.ErrorMessage, nil } -// AddedField returns the numeric value that was incremented/decremented on a field -// with the given name. The second boolean return value indicates that this field -// was not set, or was not defined in the schema. -func (m *UsageCleanupTaskMutation) AddedField(name string) (ent.Value, bool) { - switch name { - case usagecleanuptask.FieldCreatedBy: - return m.AddedCreatedBy() - case usagecleanuptask.FieldDeletedRows: - return m.AddedDeletedRows() - case usagecleanuptask.FieldCanceledBy: - return m.AddedCanceledBy() - } - return nil, false +// ClearErrorMessage clears the value of the "error_message" field. +func (m *UsageCleanupTaskMutation) ClearErrorMessage() { + m.error_message = nil + m.clearedFields[usagecleanuptask.FieldErrorMessage] = struct{}{} } -// AddField adds the value to the field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *UsageCleanupTaskMutation) AddField(name string, value ent.Value) error { - switch name { - case usagecleanuptask.FieldCreatedBy: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddCreatedBy(v) - return nil - case usagecleanuptask.FieldDeletedRows: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddDeletedRows(v) - return nil - case usagecleanuptask.FieldCanceledBy: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddCanceledBy(v) - return nil - } - return fmt.Errorf("unknown UsageCleanupTask numeric field %s", name) +// ErrorMessageCleared returns if the "error_message" field was cleared in this mutation. +func (m *UsageCleanupTaskMutation) ErrorMessageCleared() bool { + _, ok := m.clearedFields[usagecleanuptask.FieldErrorMessage] + return ok } -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *UsageCleanupTaskMutation) ClearedFields() []string { - var fields []string - if m.FieldCleared(usagecleanuptask.FieldErrorMessage) { - fields = append(fields, usagecleanuptask.FieldErrorMessage) - } - if m.FieldCleared(usagecleanuptask.FieldCanceledBy) { - fields = append(fields, usagecleanuptask.FieldCanceledBy) +// ResetErrorMessage resets all changes to the "error_message" field. +func (m *UsageCleanupTaskMutation) ResetErrorMessage() { + m.error_message = nil + delete(m.clearedFields, usagecleanuptask.FieldErrorMessage) +} + +// SetCanceledBy sets the "canceled_by" field. +func (m *UsageCleanupTaskMutation) SetCanceledBy(i int64) { + m.canceled_by = &i + m.addcanceled_by = nil +} + +// CanceledBy returns the value of the "canceled_by" field in the mutation. +func (m *UsageCleanupTaskMutation) CanceledBy() (r int64, exists bool) { + v := m.canceled_by + if v == nil { + return } - if m.FieldCleared(usagecleanuptask.FieldCanceledAt) { - fields = append(fields, usagecleanuptask.FieldCanceledAt) + return *v, true +} + +// OldCanceledBy returns the old "canceled_by" field's value of the UsageCleanupTask entity. +// If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UsageCleanupTaskMutation) OldCanceledBy(ctx context.Context) (v *int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCanceledBy is only allowed on UpdateOne operations") } - if m.FieldCleared(usagecleanuptask.FieldStartedAt) { - fields = append(fields, usagecleanuptask.FieldStartedAt) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCanceledBy requires an ID field in the mutation") } - if m.FieldCleared(usagecleanuptask.FieldFinishedAt) { - fields = append(fields, usagecleanuptask.FieldFinishedAt) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCanceledBy: %w", err) } - return fields -} - -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *UsageCleanupTaskMutation) FieldCleared(name string) bool { - _, ok := m.clearedFields[name] - return ok + return oldValue.CanceledBy, nil } -// ClearField clears the value of the field with the given name. It returns an -// error if the field is not defined in the schema. -func (m *UsageCleanupTaskMutation) ClearField(name string) error { - switch name { - case usagecleanuptask.FieldErrorMessage: - m.ClearErrorMessage() - return nil - case usagecleanuptask.FieldCanceledBy: - m.ClearCanceledBy() - return nil - case usagecleanuptask.FieldCanceledAt: - m.ClearCanceledAt() - return nil - case usagecleanuptask.FieldStartedAt: - m.ClearStartedAt() - return nil - case usagecleanuptask.FieldFinishedAt: - m.ClearFinishedAt() - return nil +// AddCanceledBy adds i to the "canceled_by" field. +func (m *UsageCleanupTaskMutation) AddCanceledBy(i int64) { + if m.addcanceled_by != nil { + *m.addcanceled_by += i + } else { + m.addcanceled_by = &i } - return fmt.Errorf("unknown UsageCleanupTask nullable field %s", name) } -// ResetField resets all changes in the mutation for the field with the given name. -// It returns an error if the field is not defined in the schema. -func (m *UsageCleanupTaskMutation) ResetField(name string) error { - switch name { - case usagecleanuptask.FieldCreatedAt: - m.ResetCreatedAt() - return nil - case usagecleanuptask.FieldUpdatedAt: - m.ResetUpdatedAt() - return nil - case usagecleanuptask.FieldStatus: - m.ResetStatus() - return nil - case usagecleanuptask.FieldFilters: - m.ResetFilters() - return nil - case usagecleanuptask.FieldCreatedBy: - m.ResetCreatedBy() - return nil - case usagecleanuptask.FieldDeletedRows: - m.ResetDeletedRows() - return nil - case usagecleanuptask.FieldErrorMessage: - m.ResetErrorMessage() - return nil - case usagecleanuptask.FieldCanceledBy: - m.ResetCanceledBy() - return nil - case usagecleanuptask.FieldCanceledAt: - m.ResetCanceledAt() - return nil - case usagecleanuptask.FieldStartedAt: - m.ResetStartedAt() - return nil - case usagecleanuptask.FieldFinishedAt: - m.ResetFinishedAt() - return nil +// AddedCanceledBy returns the value that was added to the "canceled_by" field in this mutation. +func (m *UsageCleanupTaskMutation) AddedCanceledBy() (r int64, exists bool) { + v := m.addcanceled_by + if v == nil { + return } - return fmt.Errorf("unknown UsageCleanupTask field %s", name) + return *v, true } -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *UsageCleanupTaskMutation) AddedEdges() []string { - edges := make([]string, 0, 0) - return edges +// ClearCanceledBy clears the value of the "canceled_by" field. +func (m *UsageCleanupTaskMutation) ClearCanceledBy() { + m.canceled_by = nil + m.addcanceled_by = nil + m.clearedFields[usagecleanuptask.FieldCanceledBy] = struct{}{} } -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *UsageCleanupTaskMutation) AddedIDs(name string) []ent.Value { - return nil +// CanceledByCleared returns if the "canceled_by" field was cleared in this mutation. +func (m *UsageCleanupTaskMutation) CanceledByCleared() bool { + _, ok := m.clearedFields[usagecleanuptask.FieldCanceledBy] + return ok } -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *UsageCleanupTaskMutation) RemovedEdges() []string { - edges := make([]string, 0, 0) - return edges +// ResetCanceledBy resets all changes to the "canceled_by" field. +func (m *UsageCleanupTaskMutation) ResetCanceledBy() { + m.canceled_by = nil + m.addcanceled_by = nil + delete(m.clearedFields, usagecleanuptask.FieldCanceledBy) } -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *UsageCleanupTaskMutation) RemovedIDs(name string) []ent.Value { - return nil +// SetCanceledAt sets the "canceled_at" field. +func (m *UsageCleanupTaskMutation) SetCanceledAt(t time.Time) { + m.canceled_at = &t } -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *UsageCleanupTaskMutation) ClearedEdges() []string { - edges := make([]string, 0, 0) - return edges +// CanceledAt returns the value of the "canceled_at" field in the mutation. +func (m *UsageCleanupTaskMutation) CanceledAt() (r time.Time, exists bool) { + v := m.canceled_at + if v == nil { + return + } + return *v, true } -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *UsageCleanupTaskMutation) EdgeCleared(name string) bool { - return false +// OldCanceledAt returns the old "canceled_at" field's value of the UsageCleanupTask entity. +// If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UsageCleanupTaskMutation) OldCanceledAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCanceledAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCanceledAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCanceledAt: %w", err) + } + return oldValue.CanceledAt, nil } -// ClearEdge clears the value of the edge with the given name. It returns an error -// if that edge is not defined in the schema. -func (m *UsageCleanupTaskMutation) ClearEdge(name string) error { - return fmt.Errorf("unknown UsageCleanupTask unique edge %s", name) +// ClearCanceledAt clears the value of the "canceled_at" field. +func (m *UsageCleanupTaskMutation) ClearCanceledAt() { + m.canceled_at = nil + m.clearedFields[usagecleanuptask.FieldCanceledAt] = struct{}{} } -// ResetEdge resets all changes to the edge with the given name in this mutation. -// It returns an error if the edge is not defined in the schema. -func (m *UsageCleanupTaskMutation) ResetEdge(name string) error { - return fmt.Errorf("unknown UsageCleanupTask edge %s", name) +// CanceledAtCleared returns if the "canceled_at" field was cleared in this mutation. +func (m *UsageCleanupTaskMutation) CanceledAtCleared() bool { + _, ok := m.clearedFields[usagecleanuptask.FieldCanceledAt] + return ok } -// UsageLogMutation represents an operation that mutates the UsageLog nodes in the graph. -type UsageLogMutation struct { - config - op Op - typ string - id *int64 - request_id *string - model *string - input_tokens *int - addinput_tokens *int - output_tokens *int - addoutput_tokens *int - cache_creation_tokens *int - addcache_creation_tokens *int - cache_read_tokens *int - addcache_read_tokens *int - cache_creation_5m_tokens *int - addcache_creation_5m_tokens *int - cache_creation_1h_tokens *int - addcache_creation_1h_tokens *int - input_cost *float64 - addinput_cost *float64 - output_cost *float64 - addoutput_cost *float64 - cache_creation_cost *float64 - addcache_creation_cost *float64 - cache_read_cost *float64 - addcache_read_cost *float64 - total_cost *float64 - addtotal_cost *float64 - actual_cost *float64 - addactual_cost *float64 - rate_multiplier *float64 - addrate_multiplier *float64 - account_rate_multiplier *float64 - addaccount_rate_multiplier *float64 - billing_type *int8 - addbilling_type *int8 - stream *bool - duration_ms *int - addduration_ms *int - first_token_ms *int - addfirst_token_ms *int - user_agent *string - ip_address *string - image_count *int - addimage_count *int - image_size *string - media_type *string - cache_ttl_overridden *bool - created_at *time.Time - clearedFields map[string]struct{} - user *int64 - cleareduser bool - api_key *int64 - clearedapi_key bool - account *int64 - clearedaccount bool - group *int64 - clearedgroup bool - subscription *int64 - clearedsubscription bool - done bool - oldValue func(context.Context) (*UsageLog, error) - predicates []predicate.UsageLog +// ResetCanceledAt resets all changes to the "canceled_at" field. +func (m *UsageCleanupTaskMutation) ResetCanceledAt() { + m.canceled_at = nil + delete(m.clearedFields, usagecleanuptask.FieldCanceledAt) } -var _ ent.Mutation = (*UsageLogMutation)(nil) - -// usagelogOption allows management of the mutation configuration using functional options. -type usagelogOption func(*UsageLogMutation) - -// newUsageLogMutation creates new mutation for the UsageLog entity. -func newUsageLogMutation(c config, op Op, opts ...usagelogOption) *UsageLogMutation { - m := &UsageLogMutation{ - config: c, - op: op, - typ: TypeUsageLog, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) - } - return m +// SetStartedAt sets the "started_at" field. +func (m *UsageCleanupTaskMutation) SetStartedAt(t time.Time) { + m.started_at = &t } -// withUsageLogID sets the ID field of the mutation. -func withUsageLogID(id int64) usagelogOption { - return func(m *UsageLogMutation) { - var ( - err error - once sync.Once - value *UsageLog - ) - m.oldValue = func(ctx context.Context) (*UsageLog, error) { - once.Do(func() { - if m.done { - err = errors.New("querying old values post mutation is not allowed") - } else { - value, err = m.Client().UsageLog.Get(ctx, id) - } - }) - return value, err - } - m.id = &id +// StartedAt returns the value of the "started_at" field in the mutation. +func (m *UsageCleanupTaskMutation) StartedAt() (r time.Time, exists bool) { + v := m.started_at + if v == nil { + return } + return *v, true } -// withUsageLog sets the old UsageLog of the mutation. -func withUsageLog(node *UsageLog) usagelogOption { - return func(m *UsageLogMutation) { - m.oldValue = func(context.Context) (*UsageLog, error) { - return node, nil - } - m.id = &node.ID +// OldStartedAt returns the old "started_at" field's value of the UsageCleanupTask entity. +// If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UsageCleanupTaskMutation) OldStartedAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStartedAt is only allowed on UpdateOne operations") } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStartedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStartedAt: %w", err) + } + return oldValue.StartedAt, nil } -// Client returns a new `ent.Client` from the mutation. If the mutation was -// executed in a transaction (ent.Tx), a transactional client is returned. -func (m UsageLogMutation) Client() *Client { - client := &Client{config: m.config} - client.init() - return client -} - -// Tx returns an `ent.Tx` for mutations that were executed in transactions; -// it returns an error otherwise. -func (m UsageLogMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, errors.New("ent: mutation is not running in a transaction") - } - tx := &Tx{config: m.config} - tx.init() - return tx, nil +// ClearStartedAt clears the value of the "started_at" field. +func (m *UsageCleanupTaskMutation) ClearStartedAt() { + m.started_at = nil + m.clearedFields[usagecleanuptask.FieldStartedAt] = struct{}{} } -// ID returns the ID value in the mutation. Note that the ID is only available -// if it was provided to the builder or after it was returned from the database. -func (m *UsageLogMutation) ID() (id int64, exists bool) { - if m.id == nil { - return - } - return *m.id, true +// StartedAtCleared returns if the "started_at" field was cleared in this mutation. +func (m *UsageCleanupTaskMutation) StartedAtCleared() bool { + _, ok := m.clearedFields[usagecleanuptask.FieldStartedAt] + return ok } -// IDs queries the database and returns the entity ids that match the mutation's predicate. -// That means, if the mutation is applied within a transaction with an isolation level such -// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated -// or updated by the mutation. -func (m *UsageLogMutation) IDs(ctx context.Context) ([]int64, error) { - switch { - case m.op.Is(OpUpdateOne | OpDeleteOne): - id, exists := m.ID() - if exists { - return []int64{id}, nil - } - fallthrough - case m.op.Is(OpUpdate | OpDelete): - return m.Client().UsageLog.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) - } +// ResetStartedAt resets all changes to the "started_at" field. +func (m *UsageCleanupTaskMutation) ResetStartedAt() { + m.started_at = nil + delete(m.clearedFields, usagecleanuptask.FieldStartedAt) } -// SetUserID sets the "user_id" field. -func (m *UsageLogMutation) SetUserID(i int64) { - m.user = &i +// SetFinishedAt sets the "finished_at" field. +func (m *UsageCleanupTaskMutation) SetFinishedAt(t time.Time) { + m.finished_at = &t } -// UserID returns the value of the "user_id" field in the mutation. -func (m *UsageLogMutation) UserID() (r int64, exists bool) { - v := m.user +// FinishedAt returns the value of the "finished_at" field in the mutation. +func (m *UsageCleanupTaskMutation) FinishedAt() (r time.Time, exists bool) { + v := m.finished_at if v == nil { return } return *v, true } -// OldUserID returns the old "user_id" field's value of the UsageLog entity. -// If the UsageLog object wasn't provided to the builder, the object is fetched from the database. +// OldFinishedAt returns the old "finished_at" field's value of the UsageCleanupTask entity. +// If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldUserID(ctx context.Context) (v int64, err error) { +func (m *UsageCleanupTaskMutation) OldFinishedAt(ctx context.Context) (v *time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUserID is only allowed on UpdateOne operations") + return v, errors.New("OldFinishedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUserID requires an ID field in the mutation") + return v, errors.New("OldFinishedAt requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldUserID: %w", err) + return v, fmt.Errorf("querying old value for OldFinishedAt: %w", err) } - return oldValue.UserID, nil + return oldValue.FinishedAt, nil } -// ResetUserID resets all changes to the "user_id" field. -func (m *UsageLogMutation) ResetUserID() { - m.user = nil +// ClearFinishedAt clears the value of the "finished_at" field. +func (m *UsageCleanupTaskMutation) ClearFinishedAt() { + m.finished_at = nil + m.clearedFields[usagecleanuptask.FieldFinishedAt] = struct{}{} } -// SetAPIKeyID sets the "api_key_id" field. -func (m *UsageLogMutation) SetAPIKeyID(i int64) { - m.api_key = &i +// FinishedAtCleared returns if the "finished_at" field was cleared in this mutation. +func (m *UsageCleanupTaskMutation) FinishedAtCleared() bool { + _, ok := m.clearedFields[usagecleanuptask.FieldFinishedAt] + return ok } -// APIKeyID returns the value of the "api_key_id" field in the mutation. -func (m *UsageLogMutation) APIKeyID() (r int64, exists bool) { - v := m.api_key - if v == nil { - return - } - return *v, true +// ResetFinishedAt resets all changes to the "finished_at" field. +func (m *UsageCleanupTaskMutation) ResetFinishedAt() { + m.finished_at = nil + delete(m.clearedFields, usagecleanuptask.FieldFinishedAt) } -// OldAPIKeyID returns the old "api_key_id" field's value of the UsageLog entity. -// If the UsageLog object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldAPIKeyID(ctx context.Context) (v int64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldAPIKeyID is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldAPIKeyID requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldAPIKeyID: %w", err) +// Where appends a list predicates to the UsageCleanupTaskMutation builder. +func (m *UsageCleanupTaskMutation) Where(ps ...predicate.UsageCleanupTask) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the UsageCleanupTaskMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *UsageCleanupTaskMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.UsageCleanupTask, len(ps)) + for i := range ps { + p[i] = ps[i] } - return oldValue.APIKeyID, nil + m.Where(p...) } -// ResetAPIKeyID resets all changes to the "api_key_id" field. -func (m *UsageLogMutation) ResetAPIKeyID() { - m.api_key = nil +// Op returns the operation name. +func (m *UsageCleanupTaskMutation) Op() Op { + return m.op } -// SetAccountID sets the "account_id" field. -func (m *UsageLogMutation) SetAccountID(i int64) { - m.account = &i +// SetOp allows setting the mutation operation. +func (m *UsageCleanupTaskMutation) SetOp(op Op) { + m.op = op } -// AccountID returns the value of the "account_id" field in the mutation. -func (m *UsageLogMutation) AccountID() (r int64, exists bool) { - v := m.account - if v == nil { - return - } - return *v, true +// Type returns the node type of this mutation (UsageCleanupTask). +func (m *UsageCleanupTaskMutation) Type() string { + return m.typ } -// OldAccountID returns the old "account_id" field's value of the UsageLog entity. -// If the UsageLog object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldAccountID(ctx context.Context) (v int64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldAccountID is only allowed on UpdateOne operations") +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *UsageCleanupTaskMutation) Fields() []string { + fields := make([]string, 0, 11) + if m.created_at != nil { + fields = append(fields, usagecleanuptask.FieldCreatedAt) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldAccountID requires an ID field in the mutation") + if m.updated_at != nil { + fields = append(fields, usagecleanuptask.FieldUpdatedAt) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldAccountID: %w", err) + if m.status != nil { + fields = append(fields, usagecleanuptask.FieldStatus) } - return oldValue.AccountID, nil -} - -// ResetAccountID resets all changes to the "account_id" field. -func (m *UsageLogMutation) ResetAccountID() { - m.account = nil -} - -// SetRequestID sets the "request_id" field. -func (m *UsageLogMutation) SetRequestID(s string) { - m.request_id = &s -} - -// RequestID returns the value of the "request_id" field in the mutation. -func (m *UsageLogMutation) RequestID() (r string, exists bool) { - v := m.request_id - if v == nil { - return + if m.filters != nil { + fields = append(fields, usagecleanuptask.FieldFilters) } - return *v, true -} - -// OldRequestID returns the old "request_id" field's value of the UsageLog entity. -// If the UsageLog object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldRequestID(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldRequestID is only allowed on UpdateOne operations") + if m.created_by != nil { + fields = append(fields, usagecleanuptask.FieldCreatedBy) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldRequestID requires an ID field in the mutation") + if m.deleted_rows != nil { + fields = append(fields, usagecleanuptask.FieldDeletedRows) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldRequestID: %w", err) + if m.error_message != nil { + fields = append(fields, usagecleanuptask.FieldErrorMessage) } - return oldValue.RequestID, nil -} - -// ResetRequestID resets all changes to the "request_id" field. -func (m *UsageLogMutation) ResetRequestID() { - m.request_id = nil -} - -// SetModel sets the "model" field. -func (m *UsageLogMutation) SetModel(s string) { - m.model = &s -} - -// Model returns the value of the "model" field in the mutation. -func (m *UsageLogMutation) Model() (r string, exists bool) { - v := m.model - if v == nil { - return + if m.canceled_by != nil { + fields = append(fields, usagecleanuptask.FieldCanceledBy) } - return *v, true -} - -// OldModel returns the old "model" field's value of the UsageLog entity. -// If the UsageLog object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldModel(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldModel is only allowed on UpdateOne operations") + if m.canceled_at != nil { + fields = append(fields, usagecleanuptask.FieldCanceledAt) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldModel requires an ID field in the mutation") + if m.started_at != nil { + fields = append(fields, usagecleanuptask.FieldStartedAt) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldModel: %w", err) + if m.finished_at != nil { + fields = append(fields, usagecleanuptask.FieldFinishedAt) } - return oldValue.Model, nil -} - -// ResetModel resets all changes to the "model" field. -func (m *UsageLogMutation) ResetModel() { - m.model = nil + return fields } -// SetGroupID sets the "group_id" field. -func (m *UsageLogMutation) SetGroupID(i int64) { - m.group = &i +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *UsageCleanupTaskMutation) Field(name string) (ent.Value, bool) { + switch name { + case usagecleanuptask.FieldCreatedAt: + return m.CreatedAt() + case usagecleanuptask.FieldUpdatedAt: + return m.UpdatedAt() + case usagecleanuptask.FieldStatus: + return m.Status() + case usagecleanuptask.FieldFilters: + return m.Filters() + case usagecleanuptask.FieldCreatedBy: + return m.CreatedBy() + case usagecleanuptask.FieldDeletedRows: + return m.DeletedRows() + case usagecleanuptask.FieldErrorMessage: + return m.ErrorMessage() + case usagecleanuptask.FieldCanceledBy: + return m.CanceledBy() + case usagecleanuptask.FieldCanceledAt: + return m.CanceledAt() + case usagecleanuptask.FieldStartedAt: + return m.StartedAt() + case usagecleanuptask.FieldFinishedAt: + return m.FinishedAt() + } + return nil, false } -// GroupID returns the value of the "group_id" field in the mutation. -func (m *UsageLogMutation) GroupID() (r int64, exists bool) { - v := m.group - if v == nil { - return +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *UsageCleanupTaskMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case usagecleanuptask.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case usagecleanuptask.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case usagecleanuptask.FieldStatus: + return m.OldStatus(ctx) + case usagecleanuptask.FieldFilters: + return m.OldFilters(ctx) + case usagecleanuptask.FieldCreatedBy: + return m.OldCreatedBy(ctx) + case usagecleanuptask.FieldDeletedRows: + return m.OldDeletedRows(ctx) + case usagecleanuptask.FieldErrorMessage: + return m.OldErrorMessage(ctx) + case usagecleanuptask.FieldCanceledBy: + return m.OldCanceledBy(ctx) + case usagecleanuptask.FieldCanceledAt: + return m.OldCanceledAt(ctx) + case usagecleanuptask.FieldStartedAt: + return m.OldStartedAt(ctx) + case usagecleanuptask.FieldFinishedAt: + return m.OldFinishedAt(ctx) } - return *v, true + return nil, fmt.Errorf("unknown UsageCleanupTask field %s", name) } -// OldGroupID returns the old "group_id" field's value of the UsageLog entity. -// If the UsageLog object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldGroupID(ctx context.Context) (v *int64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldGroupID is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldGroupID requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldGroupID: %w", err) +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *UsageCleanupTaskMutation) SetField(name string, value ent.Value) error { + switch name { + case usagecleanuptask.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case usagecleanuptask.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + case usagecleanuptask.FieldStatus: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatus(v) + return nil + case usagecleanuptask.FieldFilters: + v, ok := value.(json.RawMessage) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFilters(v) + return nil + case usagecleanuptask.FieldCreatedBy: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedBy(v) + return nil + case usagecleanuptask.FieldDeletedRows: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeletedRows(v) + return nil + case usagecleanuptask.FieldErrorMessage: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetErrorMessage(v) + return nil + case usagecleanuptask.FieldCanceledBy: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCanceledBy(v) + return nil + case usagecleanuptask.FieldCanceledAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCanceledAt(v) + return nil + case usagecleanuptask.FieldStartedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStartedAt(v) + return nil + case usagecleanuptask.FieldFinishedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFinishedAt(v) + return nil } - return oldValue.GroupID, nil -} - -// ClearGroupID clears the value of the "group_id" field. -func (m *UsageLogMutation) ClearGroupID() { - m.group = nil - m.clearedFields[usagelog.FieldGroupID] = struct{}{} -} - -// GroupIDCleared returns if the "group_id" field was cleared in this mutation. -func (m *UsageLogMutation) GroupIDCleared() bool { - _, ok := m.clearedFields[usagelog.FieldGroupID] - return ok + return fmt.Errorf("unknown UsageCleanupTask field %s", name) } -// ResetGroupID resets all changes to the "group_id" field. -func (m *UsageLogMutation) ResetGroupID() { - m.group = nil - delete(m.clearedFields, usagelog.FieldGroupID) +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *UsageCleanupTaskMutation) AddedFields() []string { + var fields []string + if m.addcreated_by != nil { + fields = append(fields, usagecleanuptask.FieldCreatedBy) + } + if m.adddeleted_rows != nil { + fields = append(fields, usagecleanuptask.FieldDeletedRows) + } + if m.addcanceled_by != nil { + fields = append(fields, usagecleanuptask.FieldCanceledBy) + } + return fields } -// SetSubscriptionID sets the "subscription_id" field. -func (m *UsageLogMutation) SetSubscriptionID(i int64) { - m.subscription = &i +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *UsageCleanupTaskMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case usagecleanuptask.FieldCreatedBy: + return m.AddedCreatedBy() + case usagecleanuptask.FieldDeletedRows: + return m.AddedDeletedRows() + case usagecleanuptask.FieldCanceledBy: + return m.AddedCanceledBy() + } + return nil, false } -// SubscriptionID returns the value of the "subscription_id" field in the mutation. -func (m *UsageLogMutation) SubscriptionID() (r int64, exists bool) { - v := m.subscription - if v == nil { - return +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *UsageCleanupTaskMutation) AddField(name string, value ent.Value) error { + switch name { + case usagecleanuptask.FieldCreatedBy: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddCreatedBy(v) + return nil + case usagecleanuptask.FieldDeletedRows: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddDeletedRows(v) + return nil + case usagecleanuptask.FieldCanceledBy: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddCanceledBy(v) + return nil } - return *v, true + return fmt.Errorf("unknown UsageCleanupTask numeric field %s", name) } -// OldSubscriptionID returns the old "subscription_id" field's value of the UsageLog entity. -// If the UsageLog object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldSubscriptionID(ctx context.Context) (v *int64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldSubscriptionID is only allowed on UpdateOne operations") +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *UsageCleanupTaskMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(usagecleanuptask.FieldErrorMessage) { + fields = append(fields, usagecleanuptask.FieldErrorMessage) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldSubscriptionID requires an ID field in the mutation") + if m.FieldCleared(usagecleanuptask.FieldCanceledBy) { + fields = append(fields, usagecleanuptask.FieldCanceledBy) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldSubscriptionID: %w", err) + if m.FieldCleared(usagecleanuptask.FieldCanceledAt) { + fields = append(fields, usagecleanuptask.FieldCanceledAt) } - return oldValue.SubscriptionID, nil -} - -// ClearSubscriptionID clears the value of the "subscription_id" field. -func (m *UsageLogMutation) ClearSubscriptionID() { - m.subscription = nil - m.clearedFields[usagelog.FieldSubscriptionID] = struct{}{} + if m.FieldCleared(usagecleanuptask.FieldStartedAt) { + fields = append(fields, usagecleanuptask.FieldStartedAt) + } + if m.FieldCleared(usagecleanuptask.FieldFinishedAt) { + fields = append(fields, usagecleanuptask.FieldFinishedAt) + } + return fields } -// SubscriptionIDCleared returns if the "subscription_id" field was cleared in this mutation. -func (m *UsageLogMutation) SubscriptionIDCleared() bool { - _, ok := m.clearedFields[usagelog.FieldSubscriptionID] +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *UsageCleanupTaskMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] return ok } -// ResetSubscriptionID resets all changes to the "subscription_id" field. -func (m *UsageLogMutation) ResetSubscriptionID() { - m.subscription = nil - delete(m.clearedFields, usagelog.FieldSubscriptionID) -} - -// SetInputTokens sets the "input_tokens" field. -func (m *UsageLogMutation) SetInputTokens(i int) { - m.input_tokens = &i - m.addinput_tokens = nil -} - -// InputTokens returns the value of the "input_tokens" field in the mutation. -func (m *UsageLogMutation) InputTokens() (r int, exists bool) { - v := m.input_tokens - if v == nil { - return +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *UsageCleanupTaskMutation) ClearField(name string) error { + switch name { + case usagecleanuptask.FieldErrorMessage: + m.ClearErrorMessage() + return nil + case usagecleanuptask.FieldCanceledBy: + m.ClearCanceledBy() + return nil + case usagecleanuptask.FieldCanceledAt: + m.ClearCanceledAt() + return nil + case usagecleanuptask.FieldStartedAt: + m.ClearStartedAt() + return nil + case usagecleanuptask.FieldFinishedAt: + m.ClearFinishedAt() + return nil } - return *v, true + return fmt.Errorf("unknown UsageCleanupTask nullable field %s", name) } -// OldInputTokens returns the old "input_tokens" field's value of the UsageLog entity. -// If the UsageLog object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldInputTokens(ctx context.Context) (v int, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldInputTokens is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldInputTokens requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldInputTokens: %w", err) +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *UsageCleanupTaskMutation) ResetField(name string) error { + switch name { + case usagecleanuptask.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case usagecleanuptask.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case usagecleanuptask.FieldStatus: + m.ResetStatus() + return nil + case usagecleanuptask.FieldFilters: + m.ResetFilters() + return nil + case usagecleanuptask.FieldCreatedBy: + m.ResetCreatedBy() + return nil + case usagecleanuptask.FieldDeletedRows: + m.ResetDeletedRows() + return nil + case usagecleanuptask.FieldErrorMessage: + m.ResetErrorMessage() + return nil + case usagecleanuptask.FieldCanceledBy: + m.ResetCanceledBy() + return nil + case usagecleanuptask.FieldCanceledAt: + m.ResetCanceledAt() + return nil + case usagecleanuptask.FieldStartedAt: + m.ResetStartedAt() + return nil + case usagecleanuptask.FieldFinishedAt: + m.ResetFinishedAt() + return nil } - return oldValue.InputTokens, nil + return fmt.Errorf("unknown UsageCleanupTask field %s", name) } -// AddInputTokens adds i to the "input_tokens" field. -func (m *UsageLogMutation) AddInputTokens(i int) { - if m.addinput_tokens != nil { - *m.addinput_tokens += i - } else { - m.addinput_tokens = &i - } +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *UsageCleanupTaskMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges } -// AddedInputTokens returns the value that was added to the "input_tokens" field in this mutation. -func (m *UsageLogMutation) AddedInputTokens() (r int, exists bool) { - v := m.addinput_tokens - if v == nil { - return - } - return *v, true +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *UsageCleanupTaskMutation) AddedIDs(name string) []ent.Value { + return nil } -// ResetInputTokens resets all changes to the "input_tokens" field. -func (m *UsageLogMutation) ResetInputTokens() { - m.input_tokens = nil - m.addinput_tokens = nil +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *UsageCleanupTaskMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges } -// SetOutputTokens sets the "output_tokens" field. -func (m *UsageLogMutation) SetOutputTokens(i int) { - m.output_tokens = &i - m.addoutput_tokens = nil +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *UsageCleanupTaskMutation) RemovedIDs(name string) []ent.Value { + return nil } -// OutputTokens returns the value of the "output_tokens" field in the mutation. -func (m *UsageLogMutation) OutputTokens() (r int, exists bool) { - v := m.output_tokens - if v == nil { - return - } - return *v, true +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *UsageCleanupTaskMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges } -// OldOutputTokens returns the old "output_tokens" field's value of the UsageLog entity. -// If the UsageLog object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldOutputTokens(ctx context.Context) (v int, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldOutputTokens is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldOutputTokens requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldOutputTokens: %w", err) - } - return oldValue.OutputTokens, nil +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *UsageCleanupTaskMutation) EdgeCleared(name string) bool { + return false } -// AddOutputTokens adds i to the "output_tokens" field. -func (m *UsageLogMutation) AddOutputTokens(i int) { - if m.addoutput_tokens != nil { - *m.addoutput_tokens += i - } else { - m.addoutput_tokens = &i - } +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *UsageCleanupTaskMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown UsageCleanupTask unique edge %s", name) } -// AddedOutputTokens returns the value that was added to the "output_tokens" field in this mutation. -func (m *UsageLogMutation) AddedOutputTokens() (r int, exists bool) { - v := m.addoutput_tokens - if v == nil { - return - } - return *v, true +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *UsageCleanupTaskMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown UsageCleanupTask edge %s", name) } -// ResetOutputTokens resets all changes to the "output_tokens" field. -func (m *UsageLogMutation) ResetOutputTokens() { - m.output_tokens = nil - m.addoutput_tokens = nil +// UsageLogMutation represents an operation that mutates the UsageLog nodes in the graph. +type UsageLogMutation struct { + config + op Op + typ string + id *int64 + request_id *string + model *string + input_tokens *int + addinput_tokens *int + output_tokens *int + addoutput_tokens *int + cache_creation_tokens *int + addcache_creation_tokens *int + cache_read_tokens *int + addcache_read_tokens *int + cache_creation_5m_tokens *int + addcache_creation_5m_tokens *int + cache_creation_1h_tokens *int + addcache_creation_1h_tokens *int + input_cost *float64 + addinput_cost *float64 + output_cost *float64 + addoutput_cost *float64 + cache_creation_cost *float64 + addcache_creation_cost *float64 + cache_read_cost *float64 + addcache_read_cost *float64 + total_cost *float64 + addtotal_cost *float64 + actual_cost *float64 + addactual_cost *float64 + rate_multiplier *float64 + addrate_multiplier *float64 + account_rate_multiplier *float64 + addaccount_rate_multiplier *float64 + billing_type *int8 + addbilling_type *int8 + stream *bool + duration_ms *int + addduration_ms *int + first_token_ms *int + addfirst_token_ms *int + user_agent *string + ip_address *string + image_count *int + addimage_count *int + image_size *string + media_type *string + cache_ttl_overridden *bool + created_at *time.Time + clearedFields map[string]struct{} + user *int64 + cleareduser bool + api_key *int64 + clearedapi_key bool + account *int64 + clearedaccount bool + group *int64 + clearedgroup bool + subscription *int64 + clearedsubscription bool + done bool + oldValue func(context.Context) (*UsageLog, error) + predicates []predicate.UsageLog } -// SetCacheCreationTokens sets the "cache_creation_tokens" field. -func (m *UsageLogMutation) SetCacheCreationTokens(i int) { - m.cache_creation_tokens = &i - m.addcache_creation_tokens = nil -} +var _ ent.Mutation = (*UsageLogMutation)(nil) -// CacheCreationTokens returns the value of the "cache_creation_tokens" field in the mutation. -func (m *UsageLogMutation) CacheCreationTokens() (r int, exists bool) { - v := m.cache_creation_tokens - if v == nil { - return - } - return *v, true -} +// usagelogOption allows management of the mutation configuration using functional options. +type usagelogOption func(*UsageLogMutation) -// OldCacheCreationTokens returns the old "cache_creation_tokens" field's value of the UsageLog entity. -// If the UsageLog object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldCacheCreationTokens(ctx context.Context) (v int, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCacheCreationTokens is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCacheCreationTokens requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldCacheCreationTokens: %w", err) +// newUsageLogMutation creates new mutation for the UsageLog entity. +func newUsageLogMutation(c config, op Op, opts ...usagelogOption) *UsageLogMutation { + m := &UsageLogMutation{ + config: c, + op: op, + typ: TypeUsageLog, + clearedFields: make(map[string]struct{}), } - return oldValue.CacheCreationTokens, nil -} - -// AddCacheCreationTokens adds i to the "cache_creation_tokens" field. -func (m *UsageLogMutation) AddCacheCreationTokens(i int) { - if m.addcache_creation_tokens != nil { - *m.addcache_creation_tokens += i - } else { - m.addcache_creation_tokens = &i + for _, opt := range opts { + opt(m) } + return m } -// AddedCacheCreationTokens returns the value that was added to the "cache_creation_tokens" field in this mutation. -func (m *UsageLogMutation) AddedCacheCreationTokens() (r int, exists bool) { - v := m.addcache_creation_tokens - if v == nil { +// withUsageLogID sets the ID field of the mutation. +func withUsageLogID(id int64) usagelogOption { + return func(m *UsageLogMutation) { + var ( + err error + once sync.Once + value *UsageLog + ) + m.oldValue = func(ctx context.Context) (*UsageLog, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().UsageLog.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withUsageLog sets the old UsageLog of the mutation. +func withUsageLog(node *UsageLog) usagelogOption { + return func(m *UsageLogMutation) { + m.oldValue = func(context.Context) (*UsageLog, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m UsageLogMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m UsageLogMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *UsageLogMutation) ID() (id int64, exists bool) { + if m.id == nil { return } - return *v, true + return *m.id, true } -// ResetCacheCreationTokens resets all changes to the "cache_creation_tokens" field. -func (m *UsageLogMutation) ResetCacheCreationTokens() { - m.cache_creation_tokens = nil - m.addcache_creation_tokens = nil +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *UsageLogMutation) IDs(ctx context.Context) ([]int64, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int64{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().UsageLog.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } } -// SetCacheReadTokens sets the "cache_read_tokens" field. -func (m *UsageLogMutation) SetCacheReadTokens(i int) { - m.cache_read_tokens = &i - m.addcache_read_tokens = nil +// SetUserID sets the "user_id" field. +func (m *UsageLogMutation) SetUserID(i int64) { + m.user = &i } -// CacheReadTokens returns the value of the "cache_read_tokens" field in the mutation. -func (m *UsageLogMutation) CacheReadTokens() (r int, exists bool) { - v := m.cache_read_tokens +// UserID returns the value of the "user_id" field in the mutation. +func (m *UsageLogMutation) UserID() (r int64, exists bool) { + v := m.user if v == nil { return } return *v, true } -// OldCacheReadTokens returns the old "cache_read_tokens" field's value of the UsageLog entity. +// OldUserID returns the old "user_id" field's value of the UsageLog entity. // If the UsageLog object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldCacheReadTokens(ctx context.Context) (v int, err error) { +func (m *UsageLogMutation) OldUserID(ctx context.Context) (v int64, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCacheReadTokens is only allowed on UpdateOne operations") + return v, errors.New("OldUserID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCacheReadTokens requires an ID field in the mutation") + return v, errors.New("OldUserID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldCacheReadTokens: %w", err) - } - return oldValue.CacheReadTokens, nil -} - -// AddCacheReadTokens adds i to the "cache_read_tokens" field. -func (m *UsageLogMutation) AddCacheReadTokens(i int) { - if m.addcache_read_tokens != nil { - *m.addcache_read_tokens += i - } else { - m.addcache_read_tokens = &i - } -} - -// AddedCacheReadTokens returns the value that was added to the "cache_read_tokens" field in this mutation. -func (m *UsageLogMutation) AddedCacheReadTokens() (r int, exists bool) { - v := m.addcache_read_tokens - if v == nil { - return + return v, fmt.Errorf("querying old value for OldUserID: %w", err) } - return *v, true + return oldValue.UserID, nil } -// ResetCacheReadTokens resets all changes to the "cache_read_tokens" field. -func (m *UsageLogMutation) ResetCacheReadTokens() { - m.cache_read_tokens = nil - m.addcache_read_tokens = nil +// ResetUserID resets all changes to the "user_id" field. +func (m *UsageLogMutation) ResetUserID() { + m.user = nil } -// SetCacheCreation5mTokens sets the "cache_creation_5m_tokens" field. -func (m *UsageLogMutation) SetCacheCreation5mTokens(i int) { - m.cache_creation_5m_tokens = &i - m.addcache_creation_5m_tokens = nil +// SetAPIKeyID sets the "api_key_id" field. +func (m *UsageLogMutation) SetAPIKeyID(i int64) { + m.api_key = &i } -// CacheCreation5mTokens returns the value of the "cache_creation_5m_tokens" field in the mutation. -func (m *UsageLogMutation) CacheCreation5mTokens() (r int, exists bool) { - v := m.cache_creation_5m_tokens +// APIKeyID returns the value of the "api_key_id" field in the mutation. +func (m *UsageLogMutation) APIKeyID() (r int64, exists bool) { + v := m.api_key if v == nil { return } return *v, true } -// OldCacheCreation5mTokens returns the old "cache_creation_5m_tokens" field's value of the UsageLog entity. +// OldAPIKeyID returns the old "api_key_id" field's value of the UsageLog entity. // If the UsageLog object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldCacheCreation5mTokens(ctx context.Context) (v int, err error) { +func (m *UsageLogMutation) OldAPIKeyID(ctx context.Context) (v int64, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCacheCreation5mTokens is only allowed on UpdateOne operations") + return v, errors.New("OldAPIKeyID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCacheCreation5mTokens requires an ID field in the mutation") + return v, errors.New("OldAPIKeyID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldCacheCreation5mTokens: %w", err) - } - return oldValue.CacheCreation5mTokens, nil -} - -// AddCacheCreation5mTokens adds i to the "cache_creation_5m_tokens" field. -func (m *UsageLogMutation) AddCacheCreation5mTokens(i int) { - if m.addcache_creation_5m_tokens != nil { - *m.addcache_creation_5m_tokens += i - } else { - m.addcache_creation_5m_tokens = &i - } -} - -// AddedCacheCreation5mTokens returns the value that was added to the "cache_creation_5m_tokens" field in this mutation. -func (m *UsageLogMutation) AddedCacheCreation5mTokens() (r int, exists bool) { - v := m.addcache_creation_5m_tokens - if v == nil { - return + return v, fmt.Errorf("querying old value for OldAPIKeyID: %w", err) } - return *v, true + return oldValue.APIKeyID, nil } -// ResetCacheCreation5mTokens resets all changes to the "cache_creation_5m_tokens" field. -func (m *UsageLogMutation) ResetCacheCreation5mTokens() { - m.cache_creation_5m_tokens = nil - m.addcache_creation_5m_tokens = nil +// ResetAPIKeyID resets all changes to the "api_key_id" field. +func (m *UsageLogMutation) ResetAPIKeyID() { + m.api_key = nil } -// SetCacheCreation1hTokens sets the "cache_creation_1h_tokens" field. -func (m *UsageLogMutation) SetCacheCreation1hTokens(i int) { - m.cache_creation_1h_tokens = &i - m.addcache_creation_1h_tokens = nil +// SetAccountID sets the "account_id" field. +func (m *UsageLogMutation) SetAccountID(i int64) { + m.account = &i } -// CacheCreation1hTokens returns the value of the "cache_creation_1h_tokens" field in the mutation. -func (m *UsageLogMutation) CacheCreation1hTokens() (r int, exists bool) { - v := m.cache_creation_1h_tokens +// AccountID returns the value of the "account_id" field in the mutation. +func (m *UsageLogMutation) AccountID() (r int64, exists bool) { + v := m.account if v == nil { return } return *v, true } -// OldCacheCreation1hTokens returns the old "cache_creation_1h_tokens" field's value of the UsageLog entity. +// OldAccountID returns the old "account_id" field's value of the UsageLog entity. // If the UsageLog object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldCacheCreation1hTokens(ctx context.Context) (v int, err error) { +func (m *UsageLogMutation) OldAccountID(ctx context.Context) (v int64, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCacheCreation1hTokens is only allowed on UpdateOne operations") + return v, errors.New("OldAccountID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCacheCreation1hTokens requires an ID field in the mutation") + return v, errors.New("OldAccountID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldCacheCreation1hTokens: %w", err) - } - return oldValue.CacheCreation1hTokens, nil -} - -// AddCacheCreation1hTokens adds i to the "cache_creation_1h_tokens" field. -func (m *UsageLogMutation) AddCacheCreation1hTokens(i int) { - if m.addcache_creation_1h_tokens != nil { - *m.addcache_creation_1h_tokens += i - } else { - m.addcache_creation_1h_tokens = &i - } -} - -// AddedCacheCreation1hTokens returns the value that was added to the "cache_creation_1h_tokens" field in this mutation. -func (m *UsageLogMutation) AddedCacheCreation1hTokens() (r int, exists bool) { - v := m.addcache_creation_1h_tokens - if v == nil { - return + return v, fmt.Errorf("querying old value for OldAccountID: %w", err) } - return *v, true + return oldValue.AccountID, nil } -// ResetCacheCreation1hTokens resets all changes to the "cache_creation_1h_tokens" field. -func (m *UsageLogMutation) ResetCacheCreation1hTokens() { - m.cache_creation_1h_tokens = nil - m.addcache_creation_1h_tokens = nil +// ResetAccountID resets all changes to the "account_id" field. +func (m *UsageLogMutation) ResetAccountID() { + m.account = nil } -// SetInputCost sets the "input_cost" field. -func (m *UsageLogMutation) SetInputCost(f float64) { - m.input_cost = &f - m.addinput_cost = nil +// SetRequestID sets the "request_id" field. +func (m *UsageLogMutation) SetRequestID(s string) { + m.request_id = &s } -// InputCost returns the value of the "input_cost" field in the mutation. -func (m *UsageLogMutation) InputCost() (r float64, exists bool) { - v := m.input_cost +// RequestID returns the value of the "request_id" field in the mutation. +func (m *UsageLogMutation) RequestID() (r string, exists bool) { + v := m.request_id if v == nil { return } return *v, true } -// OldInputCost returns the old "input_cost" field's value of the UsageLog entity. +// OldRequestID returns the old "request_id" field's value of the UsageLog entity. // If the UsageLog object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldInputCost(ctx context.Context) (v float64, err error) { +func (m *UsageLogMutation) OldRequestID(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldInputCost is only allowed on UpdateOne operations") + return v, errors.New("OldRequestID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldInputCost requires an ID field in the mutation") + return v, errors.New("OldRequestID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldInputCost: %w", err) + return v, fmt.Errorf("querying old value for OldRequestID: %w", err) } - return oldValue.InputCost, nil + return oldValue.RequestID, nil } -// AddInputCost adds f to the "input_cost" field. -func (m *UsageLogMutation) AddInputCost(f float64) { - if m.addinput_cost != nil { - *m.addinput_cost += f - } else { - m.addinput_cost = &f - } +// ResetRequestID resets all changes to the "request_id" field. +func (m *UsageLogMutation) ResetRequestID() { + m.request_id = nil } -// AddedInputCost returns the value that was added to the "input_cost" field in this mutation. -func (m *UsageLogMutation) AddedInputCost() (r float64, exists bool) { - v := m.addinput_cost +// SetModel sets the "model" field. +func (m *UsageLogMutation) SetModel(s string) { + m.model = &s +} + +// Model returns the value of the "model" field in the mutation. +func (m *UsageLogMutation) Model() (r string, exists bool) { + v := m.model if v == nil { return } return *v, true } -// ResetInputCost resets all changes to the "input_cost" field. -func (m *UsageLogMutation) ResetInputCost() { - m.input_cost = nil - m.addinput_cost = nil +// OldModel returns the old "model" field's value of the UsageLog entity. +// If the UsageLog object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UsageLogMutation) OldModel(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldModel is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldModel requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldModel: %w", err) + } + return oldValue.Model, nil } -// SetOutputCost sets the "output_cost" field. -func (m *UsageLogMutation) SetOutputCost(f float64) { - m.output_cost = &f - m.addoutput_cost = nil +// ResetModel resets all changes to the "model" field. +func (m *UsageLogMutation) ResetModel() { + m.model = nil } -// OutputCost returns the value of the "output_cost" field in the mutation. -func (m *UsageLogMutation) OutputCost() (r float64, exists bool) { - v := m.output_cost +// SetGroupID sets the "group_id" field. +func (m *UsageLogMutation) SetGroupID(i int64) { + m.group = &i +} + +// GroupID returns the value of the "group_id" field in the mutation. +func (m *UsageLogMutation) GroupID() (r int64, exists bool) { + v := m.group if v == nil { return } return *v, true } -// OldOutputCost returns the old "output_cost" field's value of the UsageLog entity. +// OldGroupID returns the old "group_id" field's value of the UsageLog entity. // If the UsageLog object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldOutputCost(ctx context.Context) (v float64, err error) { +func (m *UsageLogMutation) OldGroupID(ctx context.Context) (v *int64, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldOutputCost is only allowed on UpdateOne operations") + return v, errors.New("OldGroupID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldOutputCost requires an ID field in the mutation") + return v, errors.New("OldGroupID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldOutputCost: %w", err) + return v, fmt.Errorf("querying old value for OldGroupID: %w", err) } - return oldValue.OutputCost, nil + return oldValue.GroupID, nil } -// AddOutputCost adds f to the "output_cost" field. -func (m *UsageLogMutation) AddOutputCost(f float64) { - if m.addoutput_cost != nil { - *m.addoutput_cost += f - } else { - m.addoutput_cost = &f - } +// ClearGroupID clears the value of the "group_id" field. +func (m *UsageLogMutation) ClearGroupID() { + m.group = nil + m.clearedFields[usagelog.FieldGroupID] = struct{}{} } -// AddedOutputCost returns the value that was added to the "output_cost" field in this mutation. -func (m *UsageLogMutation) AddedOutputCost() (r float64, exists bool) { - v := m.addoutput_cost - if v == nil { - return - } - return *v, true +// GroupIDCleared returns if the "group_id" field was cleared in this mutation. +func (m *UsageLogMutation) GroupIDCleared() bool { + _, ok := m.clearedFields[usagelog.FieldGroupID] + return ok } -// ResetOutputCost resets all changes to the "output_cost" field. -func (m *UsageLogMutation) ResetOutputCost() { - m.output_cost = nil - m.addoutput_cost = nil +// ResetGroupID resets all changes to the "group_id" field. +func (m *UsageLogMutation) ResetGroupID() { + m.group = nil + delete(m.clearedFields, usagelog.FieldGroupID) } -// SetCacheCreationCost sets the "cache_creation_cost" field. -func (m *UsageLogMutation) SetCacheCreationCost(f float64) { - m.cache_creation_cost = &f - m.addcache_creation_cost = nil +// SetSubscriptionID sets the "subscription_id" field. +func (m *UsageLogMutation) SetSubscriptionID(i int64) { + m.subscription = &i } -// CacheCreationCost returns the value of the "cache_creation_cost" field in the mutation. -func (m *UsageLogMutation) CacheCreationCost() (r float64, exists bool) { - v := m.cache_creation_cost +// SubscriptionID returns the value of the "subscription_id" field in the mutation. +func (m *UsageLogMutation) SubscriptionID() (r int64, exists bool) { + v := m.subscription if v == nil { return } return *v, true } -// OldCacheCreationCost returns the old "cache_creation_cost" field's value of the UsageLog entity. +// OldSubscriptionID returns the old "subscription_id" field's value of the UsageLog entity. // If the UsageLog object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldCacheCreationCost(ctx context.Context) (v float64, err error) { +func (m *UsageLogMutation) OldSubscriptionID(ctx context.Context) (v *int64, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCacheCreationCost is only allowed on UpdateOne operations") + return v, errors.New("OldSubscriptionID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCacheCreationCost requires an ID field in the mutation") + return v, errors.New("OldSubscriptionID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldCacheCreationCost: %w", err) + return v, fmt.Errorf("querying old value for OldSubscriptionID: %w", err) } - return oldValue.CacheCreationCost, nil + return oldValue.SubscriptionID, nil } -// AddCacheCreationCost adds f to the "cache_creation_cost" field. -func (m *UsageLogMutation) AddCacheCreationCost(f float64) { - if m.addcache_creation_cost != nil { - *m.addcache_creation_cost += f - } else { - m.addcache_creation_cost = &f - } +// ClearSubscriptionID clears the value of the "subscription_id" field. +func (m *UsageLogMutation) ClearSubscriptionID() { + m.subscription = nil + m.clearedFields[usagelog.FieldSubscriptionID] = struct{}{} } -// AddedCacheCreationCost returns the value that was added to the "cache_creation_cost" field in this mutation. -func (m *UsageLogMutation) AddedCacheCreationCost() (r float64, exists bool) { - v := m.addcache_creation_cost - if v == nil { - return - } - return *v, true +// SubscriptionIDCleared returns if the "subscription_id" field was cleared in this mutation. +func (m *UsageLogMutation) SubscriptionIDCleared() bool { + _, ok := m.clearedFields[usagelog.FieldSubscriptionID] + return ok } -// ResetCacheCreationCost resets all changes to the "cache_creation_cost" field. -func (m *UsageLogMutation) ResetCacheCreationCost() { - m.cache_creation_cost = nil - m.addcache_creation_cost = nil +// ResetSubscriptionID resets all changes to the "subscription_id" field. +func (m *UsageLogMutation) ResetSubscriptionID() { + m.subscription = nil + delete(m.clearedFields, usagelog.FieldSubscriptionID) } -// SetCacheReadCost sets the "cache_read_cost" field. -func (m *UsageLogMutation) SetCacheReadCost(f float64) { - m.cache_read_cost = &f - m.addcache_read_cost = nil +// SetInputTokens sets the "input_tokens" field. +func (m *UsageLogMutation) SetInputTokens(i int) { + m.input_tokens = &i + m.addinput_tokens = nil } -// CacheReadCost returns the value of the "cache_read_cost" field in the mutation. -func (m *UsageLogMutation) CacheReadCost() (r float64, exists bool) { - v := m.cache_read_cost +// InputTokens returns the value of the "input_tokens" field in the mutation. +func (m *UsageLogMutation) InputTokens() (r int, exists bool) { + v := m.input_tokens if v == nil { return } return *v, true } -// OldCacheReadCost returns the old "cache_read_cost" field's value of the UsageLog entity. +// OldInputTokens returns the old "input_tokens" field's value of the UsageLog entity. // If the UsageLog object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldCacheReadCost(ctx context.Context) (v float64, err error) { +func (m *UsageLogMutation) OldInputTokens(ctx context.Context) (v int, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCacheReadCost is only allowed on UpdateOne operations") + return v, errors.New("OldInputTokens is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCacheReadCost requires an ID field in the mutation") + return v, errors.New("OldInputTokens requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldCacheReadCost: %w", err) + return v, fmt.Errorf("querying old value for OldInputTokens: %w", err) } - return oldValue.CacheReadCost, nil + return oldValue.InputTokens, nil } -// AddCacheReadCost adds f to the "cache_read_cost" field. -func (m *UsageLogMutation) AddCacheReadCost(f float64) { - if m.addcache_read_cost != nil { - *m.addcache_read_cost += f +// AddInputTokens adds i to the "input_tokens" field. +func (m *UsageLogMutation) AddInputTokens(i int) { + if m.addinput_tokens != nil { + *m.addinput_tokens += i } else { - m.addcache_read_cost = &f + m.addinput_tokens = &i } } -// AddedCacheReadCost returns the value that was added to the "cache_read_cost" field in this mutation. -func (m *UsageLogMutation) AddedCacheReadCost() (r float64, exists bool) { - v := m.addcache_read_cost +// AddedInputTokens returns the value that was added to the "input_tokens" field in this mutation. +func (m *UsageLogMutation) AddedInputTokens() (r int, exists bool) { + v := m.addinput_tokens if v == nil { return } return *v, true } -// ResetCacheReadCost resets all changes to the "cache_read_cost" field. -func (m *UsageLogMutation) ResetCacheReadCost() { - m.cache_read_cost = nil - m.addcache_read_cost = nil +// ResetInputTokens resets all changes to the "input_tokens" field. +func (m *UsageLogMutation) ResetInputTokens() { + m.input_tokens = nil + m.addinput_tokens = nil } -// SetTotalCost sets the "total_cost" field. -func (m *UsageLogMutation) SetTotalCost(f float64) { - m.total_cost = &f - m.addtotal_cost = nil +// SetOutputTokens sets the "output_tokens" field. +func (m *UsageLogMutation) SetOutputTokens(i int) { + m.output_tokens = &i + m.addoutput_tokens = nil } -// TotalCost returns the value of the "total_cost" field in the mutation. -func (m *UsageLogMutation) TotalCost() (r float64, exists bool) { - v := m.total_cost +// OutputTokens returns the value of the "output_tokens" field in the mutation. +func (m *UsageLogMutation) OutputTokens() (r int, exists bool) { + v := m.output_tokens if v == nil { return } return *v, true } -// OldTotalCost returns the old "total_cost" field's value of the UsageLog entity. +// OldOutputTokens returns the old "output_tokens" field's value of the UsageLog entity. // If the UsageLog object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldTotalCost(ctx context.Context) (v float64, err error) { +func (m *UsageLogMutation) OldOutputTokens(ctx context.Context) (v int, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldTotalCost is only allowed on UpdateOne operations") + return v, errors.New("OldOutputTokens is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldTotalCost requires an ID field in the mutation") + return v, errors.New("OldOutputTokens requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldTotalCost: %w", err) + return v, fmt.Errorf("querying old value for OldOutputTokens: %w", err) } - return oldValue.TotalCost, nil + return oldValue.OutputTokens, nil } -// AddTotalCost adds f to the "total_cost" field. -func (m *UsageLogMutation) AddTotalCost(f float64) { - if m.addtotal_cost != nil { - *m.addtotal_cost += f +// AddOutputTokens adds i to the "output_tokens" field. +func (m *UsageLogMutation) AddOutputTokens(i int) { + if m.addoutput_tokens != nil { + *m.addoutput_tokens += i } else { - m.addtotal_cost = &f + m.addoutput_tokens = &i } } -// AddedTotalCost returns the value that was added to the "total_cost" field in this mutation. -func (m *UsageLogMutation) AddedTotalCost() (r float64, exists bool) { - v := m.addtotal_cost +// AddedOutputTokens returns the value that was added to the "output_tokens" field in this mutation. +func (m *UsageLogMutation) AddedOutputTokens() (r int, exists bool) { + v := m.addoutput_tokens if v == nil { return } return *v, true } -// ResetTotalCost resets all changes to the "total_cost" field. -func (m *UsageLogMutation) ResetTotalCost() { - m.total_cost = nil - m.addtotal_cost = nil +// ResetOutputTokens resets all changes to the "output_tokens" field. +func (m *UsageLogMutation) ResetOutputTokens() { + m.output_tokens = nil + m.addoutput_tokens = nil } -// SetActualCost sets the "actual_cost" field. -func (m *UsageLogMutation) SetActualCost(f float64) { - m.actual_cost = &f - m.addactual_cost = nil +// SetCacheCreationTokens sets the "cache_creation_tokens" field. +func (m *UsageLogMutation) SetCacheCreationTokens(i int) { + m.cache_creation_tokens = &i + m.addcache_creation_tokens = nil } -// ActualCost returns the value of the "actual_cost" field in the mutation. -func (m *UsageLogMutation) ActualCost() (r float64, exists bool) { - v := m.actual_cost +// CacheCreationTokens returns the value of the "cache_creation_tokens" field in the mutation. +func (m *UsageLogMutation) CacheCreationTokens() (r int, exists bool) { + v := m.cache_creation_tokens if v == nil { return } return *v, true } -// OldActualCost returns the old "actual_cost" field's value of the UsageLog entity. +// OldCacheCreationTokens returns the old "cache_creation_tokens" field's value of the UsageLog entity. // If the UsageLog object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldActualCost(ctx context.Context) (v float64, err error) { +func (m *UsageLogMutation) OldCacheCreationTokens(ctx context.Context) (v int, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldActualCost is only allowed on UpdateOne operations") + return v, errors.New("OldCacheCreationTokens is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldActualCost requires an ID field in the mutation") + return v, errors.New("OldCacheCreationTokens requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldActualCost: %w", err) + return v, fmt.Errorf("querying old value for OldCacheCreationTokens: %w", err) } - return oldValue.ActualCost, nil + return oldValue.CacheCreationTokens, nil } -// AddActualCost adds f to the "actual_cost" field. -func (m *UsageLogMutation) AddActualCost(f float64) { - if m.addactual_cost != nil { - *m.addactual_cost += f +// AddCacheCreationTokens adds i to the "cache_creation_tokens" field. +func (m *UsageLogMutation) AddCacheCreationTokens(i int) { + if m.addcache_creation_tokens != nil { + *m.addcache_creation_tokens += i } else { - m.addactual_cost = &f + m.addcache_creation_tokens = &i } } -// AddedActualCost returns the value that was added to the "actual_cost" field in this mutation. -func (m *UsageLogMutation) AddedActualCost() (r float64, exists bool) { - v := m.addactual_cost +// AddedCacheCreationTokens returns the value that was added to the "cache_creation_tokens" field in this mutation. +func (m *UsageLogMutation) AddedCacheCreationTokens() (r int, exists bool) { + v := m.addcache_creation_tokens if v == nil { return } return *v, true } -// ResetActualCost resets all changes to the "actual_cost" field. -func (m *UsageLogMutation) ResetActualCost() { - m.actual_cost = nil - m.addactual_cost = nil +// ResetCacheCreationTokens resets all changes to the "cache_creation_tokens" field. +func (m *UsageLogMutation) ResetCacheCreationTokens() { + m.cache_creation_tokens = nil + m.addcache_creation_tokens = nil } -// SetRateMultiplier sets the "rate_multiplier" field. -func (m *UsageLogMutation) SetRateMultiplier(f float64) { - m.rate_multiplier = &f - m.addrate_multiplier = nil +// SetCacheReadTokens sets the "cache_read_tokens" field. +func (m *UsageLogMutation) SetCacheReadTokens(i int) { + m.cache_read_tokens = &i + m.addcache_read_tokens = nil } -// RateMultiplier returns the value of the "rate_multiplier" field in the mutation. -func (m *UsageLogMutation) RateMultiplier() (r float64, exists bool) { - v := m.rate_multiplier +// CacheReadTokens returns the value of the "cache_read_tokens" field in the mutation. +func (m *UsageLogMutation) CacheReadTokens() (r int, exists bool) { + v := m.cache_read_tokens if v == nil { return } return *v, true } -// OldRateMultiplier returns the old "rate_multiplier" field's value of the UsageLog entity. +// OldCacheReadTokens returns the old "cache_read_tokens" field's value of the UsageLog entity. // If the UsageLog object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldRateMultiplier(ctx context.Context) (v float64, err error) { +func (m *UsageLogMutation) OldCacheReadTokens(ctx context.Context) (v int, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldRateMultiplier is only allowed on UpdateOne operations") + return v, errors.New("OldCacheReadTokens is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldRateMultiplier requires an ID field in the mutation") + return v, errors.New("OldCacheReadTokens requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldRateMultiplier: %w", err) + return v, fmt.Errorf("querying old value for OldCacheReadTokens: %w", err) } - return oldValue.RateMultiplier, nil + return oldValue.CacheReadTokens, nil } -// AddRateMultiplier adds f to the "rate_multiplier" field. -func (m *UsageLogMutation) AddRateMultiplier(f float64) { - if m.addrate_multiplier != nil { - *m.addrate_multiplier += f +// AddCacheReadTokens adds i to the "cache_read_tokens" field. +func (m *UsageLogMutation) AddCacheReadTokens(i int) { + if m.addcache_read_tokens != nil { + *m.addcache_read_tokens += i } else { - m.addrate_multiplier = &f + m.addcache_read_tokens = &i } } -// AddedRateMultiplier returns the value that was added to the "rate_multiplier" field in this mutation. -func (m *UsageLogMutation) AddedRateMultiplier() (r float64, exists bool) { - v := m.addrate_multiplier +// AddedCacheReadTokens returns the value that was added to the "cache_read_tokens" field in this mutation. +func (m *UsageLogMutation) AddedCacheReadTokens() (r int, exists bool) { + v := m.addcache_read_tokens if v == nil { return } return *v, true } -// ResetRateMultiplier resets all changes to the "rate_multiplier" field. -func (m *UsageLogMutation) ResetRateMultiplier() { - m.rate_multiplier = nil - m.addrate_multiplier = nil +// ResetCacheReadTokens resets all changes to the "cache_read_tokens" field. +func (m *UsageLogMutation) ResetCacheReadTokens() { + m.cache_read_tokens = nil + m.addcache_read_tokens = nil } -// SetAccountRateMultiplier sets the "account_rate_multiplier" field. -func (m *UsageLogMutation) SetAccountRateMultiplier(f float64) { - m.account_rate_multiplier = &f - m.addaccount_rate_multiplier = nil +// SetCacheCreation5mTokens sets the "cache_creation_5m_tokens" field. +func (m *UsageLogMutation) SetCacheCreation5mTokens(i int) { + m.cache_creation_5m_tokens = &i + m.addcache_creation_5m_tokens = nil } -// AccountRateMultiplier returns the value of the "account_rate_multiplier" field in the mutation. -func (m *UsageLogMutation) AccountRateMultiplier() (r float64, exists bool) { - v := m.account_rate_multiplier +// CacheCreation5mTokens returns the value of the "cache_creation_5m_tokens" field in the mutation. +func (m *UsageLogMutation) CacheCreation5mTokens() (r int, exists bool) { + v := m.cache_creation_5m_tokens if v == nil { return } return *v, true } -// OldAccountRateMultiplier returns the old "account_rate_multiplier" field's value of the UsageLog entity. +// OldCacheCreation5mTokens returns the old "cache_creation_5m_tokens" field's value of the UsageLog entity. // If the UsageLog object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldAccountRateMultiplier(ctx context.Context) (v *float64, err error) { +func (m *UsageLogMutation) OldCacheCreation5mTokens(ctx context.Context) (v int, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldAccountRateMultiplier is only allowed on UpdateOne operations") + return v, errors.New("OldCacheCreation5mTokens is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldAccountRateMultiplier requires an ID field in the mutation") + return v, errors.New("OldCacheCreation5mTokens requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldAccountRateMultiplier: %w", err) + return v, fmt.Errorf("querying old value for OldCacheCreation5mTokens: %w", err) } - return oldValue.AccountRateMultiplier, nil + return oldValue.CacheCreation5mTokens, nil } -// AddAccountRateMultiplier adds f to the "account_rate_multiplier" field. -func (m *UsageLogMutation) AddAccountRateMultiplier(f float64) { - if m.addaccount_rate_multiplier != nil { - *m.addaccount_rate_multiplier += f +// AddCacheCreation5mTokens adds i to the "cache_creation_5m_tokens" field. +func (m *UsageLogMutation) AddCacheCreation5mTokens(i int) { + if m.addcache_creation_5m_tokens != nil { + *m.addcache_creation_5m_tokens += i } else { - m.addaccount_rate_multiplier = &f + m.addcache_creation_5m_tokens = &i } } -// AddedAccountRateMultiplier returns the value that was added to the "account_rate_multiplier" field in this mutation. -func (m *UsageLogMutation) AddedAccountRateMultiplier() (r float64, exists bool) { - v := m.addaccount_rate_multiplier +// AddedCacheCreation5mTokens returns the value that was added to the "cache_creation_5m_tokens" field in this mutation. +func (m *UsageLogMutation) AddedCacheCreation5mTokens() (r int, exists bool) { + v := m.addcache_creation_5m_tokens if v == nil { return } return *v, true } -// ClearAccountRateMultiplier clears the value of the "account_rate_multiplier" field. -func (m *UsageLogMutation) ClearAccountRateMultiplier() { - m.account_rate_multiplier = nil - m.addaccount_rate_multiplier = nil - m.clearedFields[usagelog.FieldAccountRateMultiplier] = struct{}{} -} - -// AccountRateMultiplierCleared returns if the "account_rate_multiplier" field was cleared in this mutation. -func (m *UsageLogMutation) AccountRateMultiplierCleared() bool { - _, ok := m.clearedFields[usagelog.FieldAccountRateMultiplier] - return ok -} - -// ResetAccountRateMultiplier resets all changes to the "account_rate_multiplier" field. -func (m *UsageLogMutation) ResetAccountRateMultiplier() { - m.account_rate_multiplier = nil - m.addaccount_rate_multiplier = nil - delete(m.clearedFields, usagelog.FieldAccountRateMultiplier) +// ResetCacheCreation5mTokens resets all changes to the "cache_creation_5m_tokens" field. +func (m *UsageLogMutation) ResetCacheCreation5mTokens() { + m.cache_creation_5m_tokens = nil + m.addcache_creation_5m_tokens = nil } -// SetBillingType sets the "billing_type" field. -func (m *UsageLogMutation) SetBillingType(i int8) { - m.billing_type = &i - m.addbilling_type = nil +// SetCacheCreation1hTokens sets the "cache_creation_1h_tokens" field. +func (m *UsageLogMutation) SetCacheCreation1hTokens(i int) { + m.cache_creation_1h_tokens = &i + m.addcache_creation_1h_tokens = nil } -// BillingType returns the value of the "billing_type" field in the mutation. -func (m *UsageLogMutation) BillingType() (r int8, exists bool) { - v := m.billing_type +// CacheCreation1hTokens returns the value of the "cache_creation_1h_tokens" field in the mutation. +func (m *UsageLogMutation) CacheCreation1hTokens() (r int, exists bool) { + v := m.cache_creation_1h_tokens if v == nil { return } return *v, true } -// OldBillingType returns the old "billing_type" field's value of the UsageLog entity. +// OldCacheCreation1hTokens returns the old "cache_creation_1h_tokens" field's value of the UsageLog entity. // If the UsageLog object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldBillingType(ctx context.Context) (v int8, err error) { +func (m *UsageLogMutation) OldCacheCreation1hTokens(ctx context.Context) (v int, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldBillingType is only allowed on UpdateOne operations") + return v, errors.New("OldCacheCreation1hTokens is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldBillingType requires an ID field in the mutation") + return v, errors.New("OldCacheCreation1hTokens requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldBillingType: %w", err) + return v, fmt.Errorf("querying old value for OldCacheCreation1hTokens: %w", err) } - return oldValue.BillingType, nil + return oldValue.CacheCreation1hTokens, nil } -// AddBillingType adds i to the "billing_type" field. -func (m *UsageLogMutation) AddBillingType(i int8) { - if m.addbilling_type != nil { - *m.addbilling_type += i +// AddCacheCreation1hTokens adds i to the "cache_creation_1h_tokens" field. +func (m *UsageLogMutation) AddCacheCreation1hTokens(i int) { + if m.addcache_creation_1h_tokens != nil { + *m.addcache_creation_1h_tokens += i } else { - m.addbilling_type = &i + m.addcache_creation_1h_tokens = &i } } -// AddedBillingType returns the value that was added to the "billing_type" field in this mutation. -func (m *UsageLogMutation) AddedBillingType() (r int8, exists bool) { - v := m.addbilling_type +// AddedCacheCreation1hTokens returns the value that was added to the "cache_creation_1h_tokens" field in this mutation. +func (m *UsageLogMutation) AddedCacheCreation1hTokens() (r int, exists bool) { + v := m.addcache_creation_1h_tokens if v == nil { return } return *v, true } -// ResetBillingType resets all changes to the "billing_type" field. -func (m *UsageLogMutation) ResetBillingType() { - m.billing_type = nil - m.addbilling_type = nil +// ResetCacheCreation1hTokens resets all changes to the "cache_creation_1h_tokens" field. +func (m *UsageLogMutation) ResetCacheCreation1hTokens() { + m.cache_creation_1h_tokens = nil + m.addcache_creation_1h_tokens = nil } -// SetStream sets the "stream" field. -func (m *UsageLogMutation) SetStream(b bool) { - m.stream = &b +// SetInputCost sets the "input_cost" field. +func (m *UsageLogMutation) SetInputCost(f float64) { + m.input_cost = &f + m.addinput_cost = nil } -// Stream returns the value of the "stream" field in the mutation. -func (m *UsageLogMutation) Stream() (r bool, exists bool) { - v := m.stream +// InputCost returns the value of the "input_cost" field in the mutation. +func (m *UsageLogMutation) InputCost() (r float64, exists bool) { + v := m.input_cost if v == nil { return } return *v, true } -// OldStream returns the old "stream" field's value of the UsageLog entity. +// OldInputCost returns the old "input_cost" field's value of the UsageLog entity. // If the UsageLog object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldStream(ctx context.Context) (v bool, err error) { +func (m *UsageLogMutation) OldInputCost(ctx context.Context) (v float64, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldStream is only allowed on UpdateOne operations") + return v, errors.New("OldInputCost is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldStream requires an ID field in the mutation") + return v, errors.New("OldInputCost requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldStream: %w", err) + return v, fmt.Errorf("querying old value for OldInputCost: %w", err) } - return oldValue.Stream, nil -} - -// ResetStream resets all changes to the "stream" field. -func (m *UsageLogMutation) ResetStream() { - m.stream = nil + return oldValue.InputCost, nil } -// SetDurationMs sets the "duration_ms" field. -func (m *UsageLogMutation) SetDurationMs(i int) { - m.duration_ms = &i - m.addduration_ms = nil +// AddInputCost adds f to the "input_cost" field. +func (m *UsageLogMutation) AddInputCost(f float64) { + if m.addinput_cost != nil { + *m.addinput_cost += f + } else { + m.addinput_cost = &f + } } -// DurationMs returns the value of the "duration_ms" field in the mutation. -func (m *UsageLogMutation) DurationMs() (r int, exists bool) { - v := m.duration_ms +// AddedInputCost returns the value that was added to the "input_cost" field in this mutation. +func (m *UsageLogMutation) AddedInputCost() (r float64, exists bool) { + v := m.addinput_cost if v == nil { return } return *v, true } -// OldDurationMs returns the old "duration_ms" field's value of the UsageLog entity. +// ResetInputCost resets all changes to the "input_cost" field. +func (m *UsageLogMutation) ResetInputCost() { + m.input_cost = nil + m.addinput_cost = nil +} + +// SetOutputCost sets the "output_cost" field. +func (m *UsageLogMutation) SetOutputCost(f float64) { + m.output_cost = &f + m.addoutput_cost = nil +} + +// OutputCost returns the value of the "output_cost" field in the mutation. +func (m *UsageLogMutation) OutputCost() (r float64, exists bool) { + v := m.output_cost + if v == nil { + return + } + return *v, true +} + +// OldOutputCost returns the old "output_cost" field's value of the UsageLog entity. // If the UsageLog object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldDurationMs(ctx context.Context) (v *int, err error) { +func (m *UsageLogMutation) OldOutputCost(ctx context.Context) (v float64, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldDurationMs is only allowed on UpdateOne operations") + return v, errors.New("OldOutputCost is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldDurationMs requires an ID field in the mutation") + return v, errors.New("OldOutputCost requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldDurationMs: %w", err) + return v, fmt.Errorf("querying old value for OldOutputCost: %w", err) } - return oldValue.DurationMs, nil + return oldValue.OutputCost, nil } -// AddDurationMs adds i to the "duration_ms" field. -func (m *UsageLogMutation) AddDurationMs(i int) { - if m.addduration_ms != nil { - *m.addduration_ms += i +// AddOutputCost adds f to the "output_cost" field. +func (m *UsageLogMutation) AddOutputCost(f float64) { + if m.addoutput_cost != nil { + *m.addoutput_cost += f } else { - m.addduration_ms = &i + m.addoutput_cost = &f } } -// AddedDurationMs returns the value that was added to the "duration_ms" field in this mutation. -func (m *UsageLogMutation) AddedDurationMs() (r int, exists bool) { - v := m.addduration_ms +// AddedOutputCost returns the value that was added to the "output_cost" field in this mutation. +func (m *UsageLogMutation) AddedOutputCost() (r float64, exists bool) { + v := m.addoutput_cost if v == nil { return } return *v, true } -// ClearDurationMs clears the value of the "duration_ms" field. -func (m *UsageLogMutation) ClearDurationMs() { - m.duration_ms = nil - m.addduration_ms = nil - m.clearedFields[usagelog.FieldDurationMs] = struct{}{} -} - -// DurationMsCleared returns if the "duration_ms" field was cleared in this mutation. -func (m *UsageLogMutation) DurationMsCleared() bool { - _, ok := m.clearedFields[usagelog.FieldDurationMs] - return ok -} - -// ResetDurationMs resets all changes to the "duration_ms" field. -func (m *UsageLogMutation) ResetDurationMs() { - m.duration_ms = nil - m.addduration_ms = nil - delete(m.clearedFields, usagelog.FieldDurationMs) +// ResetOutputCost resets all changes to the "output_cost" field. +func (m *UsageLogMutation) ResetOutputCost() { + m.output_cost = nil + m.addoutput_cost = nil } -// SetFirstTokenMs sets the "first_token_ms" field. -func (m *UsageLogMutation) SetFirstTokenMs(i int) { - m.first_token_ms = &i - m.addfirst_token_ms = nil +// SetCacheCreationCost sets the "cache_creation_cost" field. +func (m *UsageLogMutation) SetCacheCreationCost(f float64) { + m.cache_creation_cost = &f + m.addcache_creation_cost = nil } -// FirstTokenMs returns the value of the "first_token_ms" field in the mutation. -func (m *UsageLogMutation) FirstTokenMs() (r int, exists bool) { - v := m.first_token_ms +// CacheCreationCost returns the value of the "cache_creation_cost" field in the mutation. +func (m *UsageLogMutation) CacheCreationCost() (r float64, exists bool) { + v := m.cache_creation_cost if v == nil { return } return *v, true } -// OldFirstTokenMs returns the old "first_token_ms" field's value of the UsageLog entity. +// OldCacheCreationCost returns the old "cache_creation_cost" field's value of the UsageLog entity. // If the UsageLog object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldFirstTokenMs(ctx context.Context) (v *int, err error) { +func (m *UsageLogMutation) OldCacheCreationCost(ctx context.Context) (v float64, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldFirstTokenMs is only allowed on UpdateOne operations") + return v, errors.New("OldCacheCreationCost is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldFirstTokenMs requires an ID field in the mutation") + return v, errors.New("OldCacheCreationCost requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldFirstTokenMs: %w", err) + return v, fmt.Errorf("querying old value for OldCacheCreationCost: %w", err) } - return oldValue.FirstTokenMs, nil + return oldValue.CacheCreationCost, nil } -// AddFirstTokenMs adds i to the "first_token_ms" field. -func (m *UsageLogMutation) AddFirstTokenMs(i int) { - if m.addfirst_token_ms != nil { - *m.addfirst_token_ms += i +// AddCacheCreationCost adds f to the "cache_creation_cost" field. +func (m *UsageLogMutation) AddCacheCreationCost(f float64) { + if m.addcache_creation_cost != nil { + *m.addcache_creation_cost += f } else { - m.addfirst_token_ms = &i + m.addcache_creation_cost = &f } } -// AddedFirstTokenMs returns the value that was added to the "first_token_ms" field in this mutation. -func (m *UsageLogMutation) AddedFirstTokenMs() (r int, exists bool) { - v := m.addfirst_token_ms +// AddedCacheCreationCost returns the value that was added to the "cache_creation_cost" field in this mutation. +func (m *UsageLogMutation) AddedCacheCreationCost() (r float64, exists bool) { + v := m.addcache_creation_cost if v == nil { return } return *v, true } -// ClearFirstTokenMs clears the value of the "first_token_ms" field. -func (m *UsageLogMutation) ClearFirstTokenMs() { - m.first_token_ms = nil - m.addfirst_token_ms = nil - m.clearedFields[usagelog.FieldFirstTokenMs] = struct{}{} -} - -// FirstTokenMsCleared returns if the "first_token_ms" field was cleared in this mutation. -func (m *UsageLogMutation) FirstTokenMsCleared() bool { - _, ok := m.clearedFields[usagelog.FieldFirstTokenMs] - return ok -} - -// ResetFirstTokenMs resets all changes to the "first_token_ms" field. -func (m *UsageLogMutation) ResetFirstTokenMs() { - m.first_token_ms = nil - m.addfirst_token_ms = nil - delete(m.clearedFields, usagelog.FieldFirstTokenMs) +// ResetCacheCreationCost resets all changes to the "cache_creation_cost" field. +func (m *UsageLogMutation) ResetCacheCreationCost() { + m.cache_creation_cost = nil + m.addcache_creation_cost = nil } -// SetUserAgent sets the "user_agent" field. -func (m *UsageLogMutation) SetUserAgent(s string) { - m.user_agent = &s +// SetCacheReadCost sets the "cache_read_cost" field. +func (m *UsageLogMutation) SetCacheReadCost(f float64) { + m.cache_read_cost = &f + m.addcache_read_cost = nil } -// UserAgent returns the value of the "user_agent" field in the mutation. -func (m *UsageLogMutation) UserAgent() (r string, exists bool) { - v := m.user_agent +// CacheReadCost returns the value of the "cache_read_cost" field in the mutation. +func (m *UsageLogMutation) CacheReadCost() (r float64, exists bool) { + v := m.cache_read_cost if v == nil { return } return *v, true } -// OldUserAgent returns the old "user_agent" field's value of the UsageLog entity. +// OldCacheReadCost returns the old "cache_read_cost" field's value of the UsageLog entity. // If the UsageLog object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldUserAgent(ctx context.Context) (v *string, err error) { +func (m *UsageLogMutation) OldCacheReadCost(ctx context.Context) (v float64, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUserAgent is only allowed on UpdateOne operations") + return v, errors.New("OldCacheReadCost is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUserAgent requires an ID field in the mutation") + return v, errors.New("OldCacheReadCost requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldUserAgent: %w", err) + return v, fmt.Errorf("querying old value for OldCacheReadCost: %w", err) } - return oldValue.UserAgent, nil + return oldValue.CacheReadCost, nil } -// ClearUserAgent clears the value of the "user_agent" field. -func (m *UsageLogMutation) ClearUserAgent() { - m.user_agent = nil - m.clearedFields[usagelog.FieldUserAgent] = struct{}{} +// AddCacheReadCost adds f to the "cache_read_cost" field. +func (m *UsageLogMutation) AddCacheReadCost(f float64) { + if m.addcache_read_cost != nil { + *m.addcache_read_cost += f + } else { + m.addcache_read_cost = &f + } } -// UserAgentCleared returns if the "user_agent" field was cleared in this mutation. -func (m *UsageLogMutation) UserAgentCleared() bool { - _, ok := m.clearedFields[usagelog.FieldUserAgent] - return ok +// AddedCacheReadCost returns the value that was added to the "cache_read_cost" field in this mutation. +func (m *UsageLogMutation) AddedCacheReadCost() (r float64, exists bool) { + v := m.addcache_read_cost + if v == nil { + return + } + return *v, true } -// ResetUserAgent resets all changes to the "user_agent" field. -func (m *UsageLogMutation) ResetUserAgent() { - m.user_agent = nil - delete(m.clearedFields, usagelog.FieldUserAgent) +// ResetCacheReadCost resets all changes to the "cache_read_cost" field. +func (m *UsageLogMutation) ResetCacheReadCost() { + m.cache_read_cost = nil + m.addcache_read_cost = nil } -// SetIPAddress sets the "ip_address" field. -func (m *UsageLogMutation) SetIPAddress(s string) { - m.ip_address = &s +// SetTotalCost sets the "total_cost" field. +func (m *UsageLogMutation) SetTotalCost(f float64) { + m.total_cost = &f + m.addtotal_cost = nil } -// IPAddress returns the value of the "ip_address" field in the mutation. -func (m *UsageLogMutation) IPAddress() (r string, exists bool) { - v := m.ip_address +// TotalCost returns the value of the "total_cost" field in the mutation. +func (m *UsageLogMutation) TotalCost() (r float64, exists bool) { + v := m.total_cost if v == nil { return } return *v, true } -// OldIPAddress returns the old "ip_address" field's value of the UsageLog entity. +// OldTotalCost returns the old "total_cost" field's value of the UsageLog entity. // If the UsageLog object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldIPAddress(ctx context.Context) (v *string, err error) { +func (m *UsageLogMutation) OldTotalCost(ctx context.Context) (v float64, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldIPAddress is only allowed on UpdateOne operations") + return v, errors.New("OldTotalCost is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldIPAddress requires an ID field in the mutation") + return v, errors.New("OldTotalCost requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldIPAddress: %w", err) + return v, fmt.Errorf("querying old value for OldTotalCost: %w", err) } - return oldValue.IPAddress, nil -} - -// ClearIPAddress clears the value of the "ip_address" field. -func (m *UsageLogMutation) ClearIPAddress() { - m.ip_address = nil - m.clearedFields[usagelog.FieldIPAddress] = struct{}{} -} - -// IPAddressCleared returns if the "ip_address" field was cleared in this mutation. -func (m *UsageLogMutation) IPAddressCleared() bool { - _, ok := m.clearedFields[usagelog.FieldIPAddress] - return ok -} - -// ResetIPAddress resets all changes to the "ip_address" field. -func (m *UsageLogMutation) ResetIPAddress() { - m.ip_address = nil - delete(m.clearedFields, usagelog.FieldIPAddress) + return oldValue.TotalCost, nil } -// SetImageCount sets the "image_count" field. -func (m *UsageLogMutation) SetImageCount(i int) { - m.image_count = &i - m.addimage_count = nil +// AddTotalCost adds f to the "total_cost" field. +func (m *UsageLogMutation) AddTotalCost(f float64) { + if m.addtotal_cost != nil { + *m.addtotal_cost += f + } else { + m.addtotal_cost = &f + } } -// ImageCount returns the value of the "image_count" field in the mutation. -func (m *UsageLogMutation) ImageCount() (r int, exists bool) { - v := m.image_count +// AddedTotalCost returns the value that was added to the "total_cost" field in this mutation. +func (m *UsageLogMutation) AddedTotalCost() (r float64, exists bool) { + v := m.addtotal_cost if v == nil { return } return *v, true } -// OldImageCount returns the old "image_count" field's value of the UsageLog entity. -// If the UsageLog object wasn't provided to the builder, the object is fetched from the database. +// ResetTotalCost resets all changes to the "total_cost" field. +func (m *UsageLogMutation) ResetTotalCost() { + m.total_cost = nil + m.addtotal_cost = nil +} + +// SetActualCost sets the "actual_cost" field. +func (m *UsageLogMutation) SetActualCost(f float64) { + m.actual_cost = &f + m.addactual_cost = nil +} + +// ActualCost returns the value of the "actual_cost" field in the mutation. +func (m *UsageLogMutation) ActualCost() (r float64, exists bool) { + v := m.actual_cost + if v == nil { + return + } + return *v, true +} + +// OldActualCost returns the old "actual_cost" field's value of the UsageLog entity. +// If the UsageLog object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldImageCount(ctx context.Context) (v int, err error) { +func (m *UsageLogMutation) OldActualCost(ctx context.Context) (v float64, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldImageCount is only allowed on UpdateOne operations") + return v, errors.New("OldActualCost is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldImageCount requires an ID field in the mutation") + return v, errors.New("OldActualCost requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldImageCount: %w", err) + return v, fmt.Errorf("querying old value for OldActualCost: %w", err) } - return oldValue.ImageCount, nil + return oldValue.ActualCost, nil } -// AddImageCount adds i to the "image_count" field. -func (m *UsageLogMutation) AddImageCount(i int) { - if m.addimage_count != nil { - *m.addimage_count += i +// AddActualCost adds f to the "actual_cost" field. +func (m *UsageLogMutation) AddActualCost(f float64) { + if m.addactual_cost != nil { + *m.addactual_cost += f } else { - m.addimage_count = &i + m.addactual_cost = &f } } -// AddedImageCount returns the value that was added to the "image_count" field in this mutation. -func (m *UsageLogMutation) AddedImageCount() (r int, exists bool) { - v := m.addimage_count +// AddedActualCost returns the value that was added to the "actual_cost" field in this mutation. +func (m *UsageLogMutation) AddedActualCost() (r float64, exists bool) { + v := m.addactual_cost if v == nil { return } return *v, true } -// ResetImageCount resets all changes to the "image_count" field. -func (m *UsageLogMutation) ResetImageCount() { - m.image_count = nil - m.addimage_count = nil +// ResetActualCost resets all changes to the "actual_cost" field. +func (m *UsageLogMutation) ResetActualCost() { + m.actual_cost = nil + m.addactual_cost = nil } -// SetImageSize sets the "image_size" field. -func (m *UsageLogMutation) SetImageSize(s string) { - m.image_size = &s +// SetRateMultiplier sets the "rate_multiplier" field. +func (m *UsageLogMutation) SetRateMultiplier(f float64) { + m.rate_multiplier = &f + m.addrate_multiplier = nil } -// ImageSize returns the value of the "image_size" field in the mutation. -func (m *UsageLogMutation) ImageSize() (r string, exists bool) { - v := m.image_size +// RateMultiplier returns the value of the "rate_multiplier" field in the mutation. +func (m *UsageLogMutation) RateMultiplier() (r float64, exists bool) { + v := m.rate_multiplier if v == nil { return } return *v, true } -// OldImageSize returns the old "image_size" field's value of the UsageLog entity. +// OldRateMultiplier returns the old "rate_multiplier" field's value of the UsageLog entity. // If the UsageLog object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldImageSize(ctx context.Context) (v *string, err error) { +func (m *UsageLogMutation) OldRateMultiplier(ctx context.Context) (v float64, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldImageSize is only allowed on UpdateOne operations") + return v, errors.New("OldRateMultiplier is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldImageSize requires an ID field in the mutation") + return v, errors.New("OldRateMultiplier requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldImageSize: %w", err) + return v, fmt.Errorf("querying old value for OldRateMultiplier: %w", err) } - return oldValue.ImageSize, nil + return oldValue.RateMultiplier, nil } -// ClearImageSize clears the value of the "image_size" field. -func (m *UsageLogMutation) ClearImageSize() { - m.image_size = nil - m.clearedFields[usagelog.FieldImageSize] = struct{}{} +// AddRateMultiplier adds f to the "rate_multiplier" field. +func (m *UsageLogMutation) AddRateMultiplier(f float64) { + if m.addrate_multiplier != nil { + *m.addrate_multiplier += f + } else { + m.addrate_multiplier = &f + } } -// ImageSizeCleared returns if the "image_size" field was cleared in this mutation. -func (m *UsageLogMutation) ImageSizeCleared() bool { - _, ok := m.clearedFields[usagelog.FieldImageSize] - return ok +// AddedRateMultiplier returns the value that was added to the "rate_multiplier" field in this mutation. +func (m *UsageLogMutation) AddedRateMultiplier() (r float64, exists bool) { + v := m.addrate_multiplier + if v == nil { + return + } + return *v, true } -// ResetImageSize resets all changes to the "image_size" field. -func (m *UsageLogMutation) ResetImageSize() { - m.image_size = nil - delete(m.clearedFields, usagelog.FieldImageSize) +// ResetRateMultiplier resets all changes to the "rate_multiplier" field. +func (m *UsageLogMutation) ResetRateMultiplier() { + m.rate_multiplier = nil + m.addrate_multiplier = nil } -// SetMediaType sets the "media_type" field. -func (m *UsageLogMutation) SetMediaType(s string) { - m.media_type = &s +// SetAccountRateMultiplier sets the "account_rate_multiplier" field. +func (m *UsageLogMutation) SetAccountRateMultiplier(f float64) { + m.account_rate_multiplier = &f + m.addaccount_rate_multiplier = nil } -// MediaType returns the value of the "media_type" field in the mutation. -func (m *UsageLogMutation) MediaType() (r string, exists bool) { - v := m.media_type +// AccountRateMultiplier returns the value of the "account_rate_multiplier" field in the mutation. +func (m *UsageLogMutation) AccountRateMultiplier() (r float64, exists bool) { + v := m.account_rate_multiplier if v == nil { return } return *v, true } -// OldMediaType returns the old "media_type" field's value of the UsageLog entity. +// OldAccountRateMultiplier returns the old "account_rate_multiplier" field's value of the UsageLog entity. // If the UsageLog object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldMediaType(ctx context.Context) (v *string, err error) { +func (m *UsageLogMutation) OldAccountRateMultiplier(ctx context.Context) (v *float64, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldMediaType is only allowed on UpdateOne operations") + return v, errors.New("OldAccountRateMultiplier is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldMediaType requires an ID field in the mutation") + return v, errors.New("OldAccountRateMultiplier requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldMediaType: %w", err) + return v, fmt.Errorf("querying old value for OldAccountRateMultiplier: %w", err) } - return oldValue.MediaType, nil + return oldValue.AccountRateMultiplier, nil } -// ClearMediaType clears the value of the "media_type" field. -func (m *UsageLogMutation) ClearMediaType() { - m.media_type = nil - m.clearedFields[usagelog.FieldMediaType] = struct{}{} +// AddAccountRateMultiplier adds f to the "account_rate_multiplier" field. +func (m *UsageLogMutation) AddAccountRateMultiplier(f float64) { + if m.addaccount_rate_multiplier != nil { + *m.addaccount_rate_multiplier += f + } else { + m.addaccount_rate_multiplier = &f + } } -// MediaTypeCleared returns if the "media_type" field was cleared in this mutation. -func (m *UsageLogMutation) MediaTypeCleared() bool { - _, ok := m.clearedFields[usagelog.FieldMediaType] +// AddedAccountRateMultiplier returns the value that was added to the "account_rate_multiplier" field in this mutation. +func (m *UsageLogMutation) AddedAccountRateMultiplier() (r float64, exists bool) { + v := m.addaccount_rate_multiplier + if v == nil { + return + } + return *v, true +} + +// ClearAccountRateMultiplier clears the value of the "account_rate_multiplier" field. +func (m *UsageLogMutation) ClearAccountRateMultiplier() { + m.account_rate_multiplier = nil + m.addaccount_rate_multiplier = nil + m.clearedFields[usagelog.FieldAccountRateMultiplier] = struct{}{} +} + +// AccountRateMultiplierCleared returns if the "account_rate_multiplier" field was cleared in this mutation. +func (m *UsageLogMutation) AccountRateMultiplierCleared() bool { + _, ok := m.clearedFields[usagelog.FieldAccountRateMultiplier] return ok } -// ResetMediaType resets all changes to the "media_type" field. -func (m *UsageLogMutation) ResetMediaType() { - m.media_type = nil - delete(m.clearedFields, usagelog.FieldMediaType) +// ResetAccountRateMultiplier resets all changes to the "account_rate_multiplier" field. +func (m *UsageLogMutation) ResetAccountRateMultiplier() { + m.account_rate_multiplier = nil + m.addaccount_rate_multiplier = nil + delete(m.clearedFields, usagelog.FieldAccountRateMultiplier) } -// SetCacheTTLOverridden sets the "cache_ttl_overridden" field. -func (m *UsageLogMutation) SetCacheTTLOverridden(b bool) { - m.cache_ttl_overridden = &b +// SetBillingType sets the "billing_type" field. +func (m *UsageLogMutation) SetBillingType(i int8) { + m.billing_type = &i + m.addbilling_type = nil } -// CacheTTLOverridden returns the value of the "cache_ttl_overridden" field in the mutation. -func (m *UsageLogMutation) CacheTTLOverridden() (r bool, exists bool) { - v := m.cache_ttl_overridden +// BillingType returns the value of the "billing_type" field in the mutation. +func (m *UsageLogMutation) BillingType() (r int8, exists bool) { + v := m.billing_type if v == nil { return } return *v, true } -// OldCacheTTLOverridden returns the old "cache_ttl_overridden" field's value of the UsageLog entity. +// OldBillingType returns the old "billing_type" field's value of the UsageLog entity. // If the UsageLog object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldCacheTTLOverridden(ctx context.Context) (v bool, err error) { +func (m *UsageLogMutation) OldBillingType(ctx context.Context) (v int8, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCacheTTLOverridden is only allowed on UpdateOne operations") + return v, errors.New("OldBillingType is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCacheTTLOverridden requires an ID field in the mutation") + return v, errors.New("OldBillingType requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldCacheTTLOverridden: %w", err) + return v, fmt.Errorf("querying old value for OldBillingType: %w", err) } - return oldValue.CacheTTLOverridden, nil + return oldValue.BillingType, nil } -// ResetCacheTTLOverridden resets all changes to the "cache_ttl_overridden" field. -func (m *UsageLogMutation) ResetCacheTTLOverridden() { - m.cache_ttl_overridden = nil +// AddBillingType adds i to the "billing_type" field. +func (m *UsageLogMutation) AddBillingType(i int8) { + if m.addbilling_type != nil { + *m.addbilling_type += i + } else { + m.addbilling_type = &i + } } -// SetCreatedAt sets the "created_at" field. -func (m *UsageLogMutation) SetCreatedAt(t time.Time) { - m.created_at = &t +// AddedBillingType returns the value that was added to the "billing_type" field in this mutation. +func (m *UsageLogMutation) AddedBillingType() (r int8, exists bool) { + v := m.addbilling_type + if v == nil { + return + } + return *v, true } -// CreatedAt returns the value of the "created_at" field in the mutation. -func (m *UsageLogMutation) CreatedAt() (r time.Time, exists bool) { - v := m.created_at +// ResetBillingType resets all changes to the "billing_type" field. +func (m *UsageLogMutation) ResetBillingType() { + m.billing_type = nil + m.addbilling_type = nil +} + +// SetStream sets the "stream" field. +func (m *UsageLogMutation) SetStream(b bool) { + m.stream = &b +} + +// Stream returns the value of the "stream" field in the mutation. +func (m *UsageLogMutation) Stream() (r bool, exists bool) { + v := m.stream if v == nil { return } return *v, true } -// OldCreatedAt returns the old "created_at" field's value of the UsageLog entity. +// OldStream returns the old "stream" field's value of the UsageLog entity. // If the UsageLog object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UsageLogMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { +func (m *UsageLogMutation) OldStream(ctx context.Context) (v bool, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + return v, errors.New("OldStream is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCreatedAt requires an ID field in the mutation") + return v, errors.New("OldStream requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + return v, fmt.Errorf("querying old value for OldStream: %w", err) } - return oldValue.CreatedAt, nil + return oldValue.Stream, nil } -// ResetCreatedAt resets all changes to the "created_at" field. -func (m *UsageLogMutation) ResetCreatedAt() { - m.created_at = nil +// ResetStream resets all changes to the "stream" field. +func (m *UsageLogMutation) ResetStream() { + m.stream = nil } -// ClearUser clears the "user" edge to the User entity. -func (m *UsageLogMutation) ClearUser() { - m.cleareduser = true - m.clearedFields[usagelog.FieldUserID] = struct{}{} +// SetDurationMs sets the "duration_ms" field. +func (m *UsageLogMutation) SetDurationMs(i int) { + m.duration_ms = &i + m.addduration_ms = nil } -// UserCleared reports if the "user" edge to the User entity was cleared. -func (m *UsageLogMutation) UserCleared() bool { - return m.cleareduser +// DurationMs returns the value of the "duration_ms" field in the mutation. +func (m *UsageLogMutation) DurationMs() (r int, exists bool) { + v := m.duration_ms + if v == nil { + return + } + return *v, true } -// UserIDs returns the "user" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// UserID instead. It exists only for internal usage by the builders. -func (m *UsageLogMutation) UserIDs() (ids []int64) { - if id := m.user; id != nil { - ids = append(ids, *id) +// OldDurationMs returns the old "duration_ms" field's value of the UsageLog entity. +// If the UsageLog object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UsageLogMutation) OldDurationMs(ctx context.Context) (v *int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDurationMs is only allowed on UpdateOne operations") } - return + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDurationMs requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDurationMs: %w", err) + } + return oldValue.DurationMs, nil } -// ResetUser resets all changes to the "user" edge. -func (m *UsageLogMutation) ResetUser() { - m.user = nil - m.cleareduser = false +// AddDurationMs adds i to the "duration_ms" field. +func (m *UsageLogMutation) AddDurationMs(i int) { + if m.addduration_ms != nil { + *m.addduration_ms += i + } else { + m.addduration_ms = &i + } } -// ClearAPIKey clears the "api_key" edge to the APIKey entity. -func (m *UsageLogMutation) ClearAPIKey() { - m.clearedapi_key = true - m.clearedFields[usagelog.FieldAPIKeyID] = struct{}{} +// AddedDurationMs returns the value that was added to the "duration_ms" field in this mutation. +func (m *UsageLogMutation) AddedDurationMs() (r int, exists bool) { + v := m.addduration_ms + if v == nil { + return + } + return *v, true } -// APIKeyCleared reports if the "api_key" edge to the APIKey entity was cleared. -func (m *UsageLogMutation) APIKeyCleared() bool { - return m.clearedapi_key +// ClearDurationMs clears the value of the "duration_ms" field. +func (m *UsageLogMutation) ClearDurationMs() { + m.duration_ms = nil + m.addduration_ms = nil + m.clearedFields[usagelog.FieldDurationMs] = struct{}{} } -// APIKeyIDs returns the "api_key" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// APIKeyID instead. It exists only for internal usage by the builders. -func (m *UsageLogMutation) APIKeyIDs() (ids []int64) { - if id := m.api_key; id != nil { - ids = append(ids, *id) - } - return +// DurationMsCleared returns if the "duration_ms" field was cleared in this mutation. +func (m *UsageLogMutation) DurationMsCleared() bool { + _, ok := m.clearedFields[usagelog.FieldDurationMs] + return ok } -// ResetAPIKey resets all changes to the "api_key" edge. -func (m *UsageLogMutation) ResetAPIKey() { - m.api_key = nil - m.clearedapi_key = false +// ResetDurationMs resets all changes to the "duration_ms" field. +func (m *UsageLogMutation) ResetDurationMs() { + m.duration_ms = nil + m.addduration_ms = nil + delete(m.clearedFields, usagelog.FieldDurationMs) } -// ClearAccount clears the "account" edge to the Account entity. -func (m *UsageLogMutation) ClearAccount() { - m.clearedaccount = true - m.clearedFields[usagelog.FieldAccountID] = struct{}{} +// SetFirstTokenMs sets the "first_token_ms" field. +func (m *UsageLogMutation) SetFirstTokenMs(i int) { + m.first_token_ms = &i + m.addfirst_token_ms = nil } -// AccountCleared reports if the "account" edge to the Account entity was cleared. -func (m *UsageLogMutation) AccountCleared() bool { - return m.clearedaccount +// FirstTokenMs returns the value of the "first_token_ms" field in the mutation. +func (m *UsageLogMutation) FirstTokenMs() (r int, exists bool) { + v := m.first_token_ms + if v == nil { + return + } + return *v, true } -// AccountIDs returns the "account" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// AccountID instead. It exists only for internal usage by the builders. -func (m *UsageLogMutation) AccountIDs() (ids []int64) { - if id := m.account; id != nil { - ids = append(ids, *id) +// OldFirstTokenMs returns the old "first_token_ms" field's value of the UsageLog entity. +// If the UsageLog object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UsageLogMutation) OldFirstTokenMs(ctx context.Context) (v *int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFirstTokenMs is only allowed on UpdateOne operations") } - return + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFirstTokenMs requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFirstTokenMs: %w", err) + } + return oldValue.FirstTokenMs, nil } -// ResetAccount resets all changes to the "account" edge. -func (m *UsageLogMutation) ResetAccount() { - m.account = nil - m.clearedaccount = false +// AddFirstTokenMs adds i to the "first_token_ms" field. +func (m *UsageLogMutation) AddFirstTokenMs(i int) { + if m.addfirst_token_ms != nil { + *m.addfirst_token_ms += i + } else { + m.addfirst_token_ms = &i + } } -// ClearGroup clears the "group" edge to the Group entity. -func (m *UsageLogMutation) ClearGroup() { - m.clearedgroup = true - m.clearedFields[usagelog.FieldGroupID] = struct{}{} +// AddedFirstTokenMs returns the value that was added to the "first_token_ms" field in this mutation. +func (m *UsageLogMutation) AddedFirstTokenMs() (r int, exists bool) { + v := m.addfirst_token_ms + if v == nil { + return + } + return *v, true } -// GroupCleared reports if the "group" edge to the Group entity was cleared. -func (m *UsageLogMutation) GroupCleared() bool { - return m.GroupIDCleared() || m.clearedgroup +// ClearFirstTokenMs clears the value of the "first_token_ms" field. +func (m *UsageLogMutation) ClearFirstTokenMs() { + m.first_token_ms = nil + m.addfirst_token_ms = nil + m.clearedFields[usagelog.FieldFirstTokenMs] = struct{}{} } -// GroupIDs returns the "group" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// GroupID instead. It exists only for internal usage by the builders. -func (m *UsageLogMutation) GroupIDs() (ids []int64) { - if id := m.group; id != nil { - ids = append(ids, *id) - } - return +// FirstTokenMsCleared returns if the "first_token_ms" field was cleared in this mutation. +func (m *UsageLogMutation) FirstTokenMsCleared() bool { + _, ok := m.clearedFields[usagelog.FieldFirstTokenMs] + return ok } -// ResetGroup resets all changes to the "group" edge. -func (m *UsageLogMutation) ResetGroup() { - m.group = nil - m.clearedgroup = false +// ResetFirstTokenMs resets all changes to the "first_token_ms" field. +func (m *UsageLogMutation) ResetFirstTokenMs() { + m.first_token_ms = nil + m.addfirst_token_ms = nil + delete(m.clearedFields, usagelog.FieldFirstTokenMs) } -// ClearSubscription clears the "subscription" edge to the UserSubscription entity. -func (m *UsageLogMutation) ClearSubscription() { - m.clearedsubscription = true - m.clearedFields[usagelog.FieldSubscriptionID] = struct{}{} +// SetUserAgent sets the "user_agent" field. +func (m *UsageLogMutation) SetUserAgent(s string) { + m.user_agent = &s } -// SubscriptionCleared reports if the "subscription" edge to the UserSubscription entity was cleared. -func (m *UsageLogMutation) SubscriptionCleared() bool { - return m.SubscriptionIDCleared() || m.clearedsubscription +// UserAgent returns the value of the "user_agent" field in the mutation. +func (m *UsageLogMutation) UserAgent() (r string, exists bool) { + v := m.user_agent + if v == nil { + return + } + return *v, true } -// SubscriptionIDs returns the "subscription" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// SubscriptionID instead. It exists only for internal usage by the builders. -func (m *UsageLogMutation) SubscriptionIDs() (ids []int64) { - if id := m.subscription; id != nil { - ids = append(ids, *id) +// OldUserAgent returns the old "user_agent" field's value of the UsageLog entity. +// If the UsageLog object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UsageLogMutation) OldUserAgent(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUserAgent is only allowed on UpdateOne operations") } - return + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUserAgent requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUserAgent: %w", err) + } + return oldValue.UserAgent, nil } -// ResetSubscription resets all changes to the "subscription" edge. -func (m *UsageLogMutation) ResetSubscription() { - m.subscription = nil - m.clearedsubscription = false +// ClearUserAgent clears the value of the "user_agent" field. +func (m *UsageLogMutation) ClearUserAgent() { + m.user_agent = nil + m.clearedFields[usagelog.FieldUserAgent] = struct{}{} } -// Where appends a list predicates to the UsageLogMutation builder. -func (m *UsageLogMutation) Where(ps ...predicate.UsageLog) { - m.predicates = append(m.predicates, ps...) +// UserAgentCleared returns if the "user_agent" field was cleared in this mutation. +func (m *UsageLogMutation) UserAgentCleared() bool { + _, ok := m.clearedFields[usagelog.FieldUserAgent] + return ok } -// WhereP appends storage-level predicates to the UsageLogMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *UsageLogMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.UsageLog, len(ps)) - for i := range ps { - p[i] = ps[i] - } - m.Where(p...) +// ResetUserAgent resets all changes to the "user_agent" field. +func (m *UsageLogMutation) ResetUserAgent() { + m.user_agent = nil + delete(m.clearedFields, usagelog.FieldUserAgent) } -// Op returns the operation name. -func (m *UsageLogMutation) Op() Op { - return m.op +// SetIPAddress sets the "ip_address" field. +func (m *UsageLogMutation) SetIPAddress(s string) { + m.ip_address = &s } -// SetOp allows setting the mutation operation. -func (m *UsageLogMutation) SetOp(op Op) { - m.op = op -} - -// Type returns the node type of this mutation (UsageLog). -func (m *UsageLogMutation) Type() string { - return m.typ +// IPAddress returns the value of the "ip_address" field in the mutation. +func (m *UsageLogMutation) IPAddress() (r string, exists bool) { + v := m.ip_address + if v == nil { + return + } + return *v, true } -// Fields returns all fields that were changed during this mutation. Note that in -// order to get all numeric fields that were incremented/decremented, call -// AddedFields(). -func (m *UsageLogMutation) Fields() []string { - fields := make([]string, 0, 32) - if m.user != nil { - fields = append(fields, usagelog.FieldUserID) +// OldIPAddress returns the old "ip_address" field's value of the UsageLog entity. +// If the UsageLog object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UsageLogMutation) OldIPAddress(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIPAddress is only allowed on UpdateOne operations") } - if m.api_key != nil { - fields = append(fields, usagelog.FieldAPIKeyID) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIPAddress requires an ID field in the mutation") } - if m.account != nil { - fields = append(fields, usagelog.FieldAccountID) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIPAddress: %w", err) } - if m.request_id != nil { - fields = append(fields, usagelog.FieldRequestID) + return oldValue.IPAddress, nil +} + +// ClearIPAddress clears the value of the "ip_address" field. +func (m *UsageLogMutation) ClearIPAddress() { + m.ip_address = nil + m.clearedFields[usagelog.FieldIPAddress] = struct{}{} +} + +// IPAddressCleared returns if the "ip_address" field was cleared in this mutation. +func (m *UsageLogMutation) IPAddressCleared() bool { + _, ok := m.clearedFields[usagelog.FieldIPAddress] + return ok +} + +// ResetIPAddress resets all changes to the "ip_address" field. +func (m *UsageLogMutation) ResetIPAddress() { + m.ip_address = nil + delete(m.clearedFields, usagelog.FieldIPAddress) +} + +// SetImageCount sets the "image_count" field. +func (m *UsageLogMutation) SetImageCount(i int) { + m.image_count = &i + m.addimage_count = nil +} + +// ImageCount returns the value of the "image_count" field in the mutation. +func (m *UsageLogMutation) ImageCount() (r int, exists bool) { + v := m.image_count + if v == nil { + return } - if m.model != nil { - fields = append(fields, usagelog.FieldModel) + return *v, true +} + +// OldImageCount returns the old "image_count" field's value of the UsageLog entity. +// If the UsageLog object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UsageLogMutation) OldImageCount(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldImageCount is only allowed on UpdateOne operations") } - if m.group != nil { - fields = append(fields, usagelog.FieldGroupID) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldImageCount requires an ID field in the mutation") } - if m.subscription != nil { - fields = append(fields, usagelog.FieldSubscriptionID) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldImageCount: %w", err) } - if m.input_tokens != nil { - fields = append(fields, usagelog.FieldInputTokens) + return oldValue.ImageCount, nil +} + +// AddImageCount adds i to the "image_count" field. +func (m *UsageLogMutation) AddImageCount(i int) { + if m.addimage_count != nil { + *m.addimage_count += i + } else { + m.addimage_count = &i } - if m.output_tokens != nil { - fields = append(fields, usagelog.FieldOutputTokens) +} + +// AddedImageCount returns the value that was added to the "image_count" field in this mutation. +func (m *UsageLogMutation) AddedImageCount() (r int, exists bool) { + v := m.addimage_count + if v == nil { + return } - if m.cache_creation_tokens != nil { - fields = append(fields, usagelog.FieldCacheCreationTokens) + return *v, true +} + +// ResetImageCount resets all changes to the "image_count" field. +func (m *UsageLogMutation) ResetImageCount() { + m.image_count = nil + m.addimage_count = nil +} + +// SetImageSize sets the "image_size" field. +func (m *UsageLogMutation) SetImageSize(s string) { + m.image_size = &s +} + +// ImageSize returns the value of the "image_size" field in the mutation. +func (m *UsageLogMutation) ImageSize() (r string, exists bool) { + v := m.image_size + if v == nil { + return } - if m.cache_read_tokens != nil { - fields = append(fields, usagelog.FieldCacheReadTokens) + return *v, true +} + +// OldImageSize returns the old "image_size" field's value of the UsageLog entity. +// If the UsageLog object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UsageLogMutation) OldImageSize(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldImageSize is only allowed on UpdateOne operations") } - if m.cache_creation_5m_tokens != nil { - fields = append(fields, usagelog.FieldCacheCreation5mTokens) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldImageSize requires an ID field in the mutation") } - if m.cache_creation_1h_tokens != nil { - fields = append(fields, usagelog.FieldCacheCreation1hTokens) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldImageSize: %w", err) } - if m.input_cost != nil { - fields = append(fields, usagelog.FieldInputCost) + return oldValue.ImageSize, nil +} + +// ClearImageSize clears the value of the "image_size" field. +func (m *UsageLogMutation) ClearImageSize() { + m.image_size = nil + m.clearedFields[usagelog.FieldImageSize] = struct{}{} +} + +// ImageSizeCleared returns if the "image_size" field was cleared in this mutation. +func (m *UsageLogMutation) ImageSizeCleared() bool { + _, ok := m.clearedFields[usagelog.FieldImageSize] + return ok +} + +// ResetImageSize resets all changes to the "image_size" field. +func (m *UsageLogMutation) ResetImageSize() { + m.image_size = nil + delete(m.clearedFields, usagelog.FieldImageSize) +} + +// SetMediaType sets the "media_type" field. +func (m *UsageLogMutation) SetMediaType(s string) { + m.media_type = &s +} + +// MediaType returns the value of the "media_type" field in the mutation. +func (m *UsageLogMutation) MediaType() (r string, exists bool) { + v := m.media_type + if v == nil { + return } - if m.output_cost != nil { - fields = append(fields, usagelog.FieldOutputCost) + return *v, true +} + +// OldMediaType returns the old "media_type" field's value of the UsageLog entity. +// If the UsageLog object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UsageLogMutation) OldMediaType(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMediaType is only allowed on UpdateOne operations") } - if m.cache_creation_cost != nil { - fields = append(fields, usagelog.FieldCacheCreationCost) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMediaType requires an ID field in the mutation") } - if m.cache_read_cost != nil { - fields = append(fields, usagelog.FieldCacheReadCost) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMediaType: %w", err) } - if m.total_cost != nil { - fields = append(fields, usagelog.FieldTotalCost) + return oldValue.MediaType, nil +} + +// ClearMediaType clears the value of the "media_type" field. +func (m *UsageLogMutation) ClearMediaType() { + m.media_type = nil + m.clearedFields[usagelog.FieldMediaType] = struct{}{} +} + +// MediaTypeCleared returns if the "media_type" field was cleared in this mutation. +func (m *UsageLogMutation) MediaTypeCleared() bool { + _, ok := m.clearedFields[usagelog.FieldMediaType] + return ok +} + +// ResetMediaType resets all changes to the "media_type" field. +func (m *UsageLogMutation) ResetMediaType() { + m.media_type = nil + delete(m.clearedFields, usagelog.FieldMediaType) +} + +// SetCacheTTLOverridden sets the "cache_ttl_overridden" field. +func (m *UsageLogMutation) SetCacheTTLOverridden(b bool) { + m.cache_ttl_overridden = &b +} + +// CacheTTLOverridden returns the value of the "cache_ttl_overridden" field in the mutation. +func (m *UsageLogMutation) CacheTTLOverridden() (r bool, exists bool) { + v := m.cache_ttl_overridden + if v == nil { + return } - if m.actual_cost != nil { - fields = append(fields, usagelog.FieldActualCost) + return *v, true +} + +// OldCacheTTLOverridden returns the old "cache_ttl_overridden" field's value of the UsageLog entity. +// If the UsageLog object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UsageLogMutation) OldCacheTTLOverridden(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCacheTTLOverridden is only allowed on UpdateOne operations") } - if m.rate_multiplier != nil { - fields = append(fields, usagelog.FieldRateMultiplier) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCacheTTLOverridden requires an ID field in the mutation") } - if m.account_rate_multiplier != nil { - fields = append(fields, usagelog.FieldAccountRateMultiplier) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCacheTTLOverridden: %w", err) } - if m.billing_type != nil { - fields = append(fields, usagelog.FieldBillingType) - } - if m.stream != nil { - fields = append(fields, usagelog.FieldStream) - } - if m.duration_ms != nil { - fields = append(fields, usagelog.FieldDurationMs) - } - if m.first_token_ms != nil { - fields = append(fields, usagelog.FieldFirstTokenMs) + return oldValue.CacheTTLOverridden, nil +} + +// ResetCacheTTLOverridden resets all changes to the "cache_ttl_overridden" field. +func (m *UsageLogMutation) ResetCacheTTLOverridden() { + m.cache_ttl_overridden = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *UsageLogMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *UsageLogMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return } - if m.user_agent != nil { - fields = append(fields, usagelog.FieldUserAgent) + return *v, true +} + +// OldCreatedAt returns the old "created_at" field's value of the UsageLog entity. +// If the UsageLog object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UsageLogMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") } - if m.ip_address != nil { - fields = append(fields, usagelog.FieldIPAddress) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedAt requires an ID field in the mutation") } - if m.image_count != nil { - fields = append(fields, usagelog.FieldImageCount) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) } - if m.image_size != nil { - fields = append(fields, usagelog.FieldImageSize) + return oldValue.CreatedAt, nil +} + +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *UsageLogMutation) ResetCreatedAt() { + m.created_at = nil +} + +// ClearUser clears the "user" edge to the User entity. +func (m *UsageLogMutation) ClearUser() { + m.cleareduser = true + m.clearedFields[usagelog.FieldUserID] = struct{}{} +} + +// UserCleared reports if the "user" edge to the User entity was cleared. +func (m *UsageLogMutation) UserCleared() bool { + return m.cleareduser +} + +// UserIDs returns the "user" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// UserID instead. It exists only for internal usage by the builders. +func (m *UsageLogMutation) UserIDs() (ids []int64) { + if id := m.user; id != nil { + ids = append(ids, *id) } - if m.media_type != nil { - fields = append(fields, usagelog.FieldMediaType) + return +} + +// ResetUser resets all changes to the "user" edge. +func (m *UsageLogMutation) ResetUser() { + m.user = nil + m.cleareduser = false +} + +// ClearAPIKey clears the "api_key" edge to the APIKey entity. +func (m *UsageLogMutation) ClearAPIKey() { + m.clearedapi_key = true + m.clearedFields[usagelog.FieldAPIKeyID] = struct{}{} +} + +// APIKeyCleared reports if the "api_key" edge to the APIKey entity was cleared. +func (m *UsageLogMutation) APIKeyCleared() bool { + return m.clearedapi_key +} + +// APIKeyIDs returns the "api_key" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// APIKeyID instead. It exists only for internal usage by the builders. +func (m *UsageLogMutation) APIKeyIDs() (ids []int64) { + if id := m.api_key; id != nil { + ids = append(ids, *id) } - if m.cache_ttl_overridden != nil { - fields = append(fields, usagelog.FieldCacheTTLOverridden) + return +} + +// ResetAPIKey resets all changes to the "api_key" edge. +func (m *UsageLogMutation) ResetAPIKey() { + m.api_key = nil + m.clearedapi_key = false +} + +// ClearAccount clears the "account" edge to the Account entity. +func (m *UsageLogMutation) ClearAccount() { + m.clearedaccount = true + m.clearedFields[usagelog.FieldAccountID] = struct{}{} +} + +// AccountCleared reports if the "account" edge to the Account entity was cleared. +func (m *UsageLogMutation) AccountCleared() bool { + return m.clearedaccount +} + +// AccountIDs returns the "account" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// AccountID instead. It exists only for internal usage by the builders. +func (m *UsageLogMutation) AccountIDs() (ids []int64) { + if id := m.account; id != nil { + ids = append(ids, *id) } - if m.created_at != nil { - fields = append(fields, usagelog.FieldCreatedAt) + return +} + +// ResetAccount resets all changes to the "account" edge. +func (m *UsageLogMutation) ResetAccount() { + m.account = nil + m.clearedaccount = false +} + +// ClearGroup clears the "group" edge to the Group entity. +func (m *UsageLogMutation) ClearGroup() { + m.clearedgroup = true + m.clearedFields[usagelog.FieldGroupID] = struct{}{} +} + +// GroupCleared reports if the "group" edge to the Group entity was cleared. +func (m *UsageLogMutation) GroupCleared() bool { + return m.GroupIDCleared() || m.clearedgroup +} + +// GroupIDs returns the "group" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// GroupID instead. It exists only for internal usage by the builders. +func (m *UsageLogMutation) GroupIDs() (ids []int64) { + if id := m.group; id != nil { + ids = append(ids, *id) } - return fields + return } -// Field returns the value of a field with the given name. The second boolean -// return value indicates that this field was not set, or was not defined in the -// schema. -func (m *UsageLogMutation) Field(name string) (ent.Value, bool) { - switch name { - case usagelog.FieldUserID: - return m.UserID() - case usagelog.FieldAPIKeyID: - return m.APIKeyID() - case usagelog.FieldAccountID: - return m.AccountID() - case usagelog.FieldRequestID: - return m.RequestID() - case usagelog.FieldModel: - return m.Model() - case usagelog.FieldGroupID: - return m.GroupID() - case usagelog.FieldSubscriptionID: - return m.SubscriptionID() - case usagelog.FieldInputTokens: - return m.InputTokens() - case usagelog.FieldOutputTokens: - return m.OutputTokens() - case usagelog.FieldCacheCreationTokens: - return m.CacheCreationTokens() - case usagelog.FieldCacheReadTokens: - return m.CacheReadTokens() - case usagelog.FieldCacheCreation5mTokens: - return m.CacheCreation5mTokens() - case usagelog.FieldCacheCreation1hTokens: - return m.CacheCreation1hTokens() - case usagelog.FieldInputCost: - return m.InputCost() - case usagelog.FieldOutputCost: - return m.OutputCost() - case usagelog.FieldCacheCreationCost: - return m.CacheCreationCost() - case usagelog.FieldCacheReadCost: - return m.CacheReadCost() - case usagelog.FieldTotalCost: - return m.TotalCost() - case usagelog.FieldActualCost: - return m.ActualCost() - case usagelog.FieldRateMultiplier: - return m.RateMultiplier() - case usagelog.FieldAccountRateMultiplier: - return m.AccountRateMultiplier() - case usagelog.FieldBillingType: - return m.BillingType() - case usagelog.FieldStream: - return m.Stream() - case usagelog.FieldDurationMs: - return m.DurationMs() - case usagelog.FieldFirstTokenMs: - return m.FirstTokenMs() - case usagelog.FieldUserAgent: - return m.UserAgent() - case usagelog.FieldIPAddress: - return m.IPAddress() - case usagelog.FieldImageCount: - return m.ImageCount() - case usagelog.FieldImageSize: - return m.ImageSize() - case usagelog.FieldMediaType: - return m.MediaType() - case usagelog.FieldCacheTTLOverridden: - return m.CacheTTLOverridden() - case usagelog.FieldCreatedAt: - return m.CreatedAt() +// ResetGroup resets all changes to the "group" edge. +func (m *UsageLogMutation) ResetGroup() { + m.group = nil + m.clearedgroup = false +} + +// ClearSubscription clears the "subscription" edge to the UserSubscription entity. +func (m *UsageLogMutation) ClearSubscription() { + m.clearedsubscription = true + m.clearedFields[usagelog.FieldSubscriptionID] = struct{}{} +} + +// SubscriptionCleared reports if the "subscription" edge to the UserSubscription entity was cleared. +func (m *UsageLogMutation) SubscriptionCleared() bool { + return m.SubscriptionIDCleared() || m.clearedsubscription +} + +// SubscriptionIDs returns the "subscription" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SubscriptionID instead. It exists only for internal usage by the builders. +func (m *UsageLogMutation) SubscriptionIDs() (ids []int64) { + if id := m.subscription; id != nil { + ids = append(ids, *id) } - return nil, false + return +} + +// ResetSubscription resets all changes to the "subscription" edge. +func (m *UsageLogMutation) ResetSubscription() { + m.subscription = nil + m.clearedsubscription = false +} + +// Where appends a list predicates to the UsageLogMutation builder. +func (m *UsageLogMutation) Where(ps ...predicate.UsageLog) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the UsageLogMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *UsageLogMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.UsageLog, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *UsageLogMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *UsageLogMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (UsageLog). +func (m *UsageLogMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *UsageLogMutation) Fields() []string { + fields := make([]string, 0, 32) + if m.user != nil { + fields = append(fields, usagelog.FieldUserID) + } + if m.api_key != nil { + fields = append(fields, usagelog.FieldAPIKeyID) + } + if m.account != nil { + fields = append(fields, usagelog.FieldAccountID) + } + if m.request_id != nil { + fields = append(fields, usagelog.FieldRequestID) + } + if m.model != nil { + fields = append(fields, usagelog.FieldModel) + } + if m.group != nil { + fields = append(fields, usagelog.FieldGroupID) + } + if m.subscription != nil { + fields = append(fields, usagelog.FieldSubscriptionID) + } + if m.input_tokens != nil { + fields = append(fields, usagelog.FieldInputTokens) + } + if m.output_tokens != nil { + fields = append(fields, usagelog.FieldOutputTokens) + } + if m.cache_creation_tokens != nil { + fields = append(fields, usagelog.FieldCacheCreationTokens) + } + if m.cache_read_tokens != nil { + fields = append(fields, usagelog.FieldCacheReadTokens) + } + if m.cache_creation_5m_tokens != nil { + fields = append(fields, usagelog.FieldCacheCreation5mTokens) + } + if m.cache_creation_1h_tokens != nil { + fields = append(fields, usagelog.FieldCacheCreation1hTokens) + } + if m.input_cost != nil { + fields = append(fields, usagelog.FieldInputCost) + } + if m.output_cost != nil { + fields = append(fields, usagelog.FieldOutputCost) + } + if m.cache_creation_cost != nil { + fields = append(fields, usagelog.FieldCacheCreationCost) + } + if m.cache_read_cost != nil { + fields = append(fields, usagelog.FieldCacheReadCost) + } + if m.total_cost != nil { + fields = append(fields, usagelog.FieldTotalCost) + } + if m.actual_cost != nil { + fields = append(fields, usagelog.FieldActualCost) + } + if m.rate_multiplier != nil { + fields = append(fields, usagelog.FieldRateMultiplier) + } + if m.account_rate_multiplier != nil { + fields = append(fields, usagelog.FieldAccountRateMultiplier) + } + if m.billing_type != nil { + fields = append(fields, usagelog.FieldBillingType) + } + if m.stream != nil { + fields = append(fields, usagelog.FieldStream) + } + if m.duration_ms != nil { + fields = append(fields, usagelog.FieldDurationMs) + } + if m.first_token_ms != nil { + fields = append(fields, usagelog.FieldFirstTokenMs) + } + if m.user_agent != nil { + fields = append(fields, usagelog.FieldUserAgent) + } + if m.ip_address != nil { + fields = append(fields, usagelog.FieldIPAddress) + } + if m.image_count != nil { + fields = append(fields, usagelog.FieldImageCount) + } + if m.image_size != nil { + fields = append(fields, usagelog.FieldImageSize) + } + if m.media_type != nil { + fields = append(fields, usagelog.FieldMediaType) + } + if m.cache_ttl_overridden != nil { + fields = append(fields, usagelog.FieldCacheTTLOverridden) + } + if m.created_at != nil { + fields = append(fields, usagelog.FieldCreatedAt) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *UsageLogMutation) Field(name string) (ent.Value, bool) { + switch name { + case usagelog.FieldUserID: + return m.UserID() + case usagelog.FieldAPIKeyID: + return m.APIKeyID() + case usagelog.FieldAccountID: + return m.AccountID() + case usagelog.FieldRequestID: + return m.RequestID() + case usagelog.FieldModel: + return m.Model() + case usagelog.FieldGroupID: + return m.GroupID() + case usagelog.FieldSubscriptionID: + return m.SubscriptionID() + case usagelog.FieldInputTokens: + return m.InputTokens() + case usagelog.FieldOutputTokens: + return m.OutputTokens() + case usagelog.FieldCacheCreationTokens: + return m.CacheCreationTokens() + case usagelog.FieldCacheReadTokens: + return m.CacheReadTokens() + case usagelog.FieldCacheCreation5mTokens: + return m.CacheCreation5mTokens() + case usagelog.FieldCacheCreation1hTokens: + return m.CacheCreation1hTokens() + case usagelog.FieldInputCost: + return m.InputCost() + case usagelog.FieldOutputCost: + return m.OutputCost() + case usagelog.FieldCacheCreationCost: + return m.CacheCreationCost() + case usagelog.FieldCacheReadCost: + return m.CacheReadCost() + case usagelog.FieldTotalCost: + return m.TotalCost() + case usagelog.FieldActualCost: + return m.ActualCost() + case usagelog.FieldRateMultiplier: + return m.RateMultiplier() + case usagelog.FieldAccountRateMultiplier: + return m.AccountRateMultiplier() + case usagelog.FieldBillingType: + return m.BillingType() + case usagelog.FieldStream: + return m.Stream() + case usagelog.FieldDurationMs: + return m.DurationMs() + case usagelog.FieldFirstTokenMs: + return m.FirstTokenMs() + case usagelog.FieldUserAgent: + return m.UserAgent() + case usagelog.FieldIPAddress: + return m.IPAddress() + case usagelog.FieldImageCount: + return m.ImageCount() + case usagelog.FieldImageSize: + return m.ImageSize() + case usagelog.FieldMediaType: + return m.MediaType() + case usagelog.FieldCacheTTLOverridden: + return m.CacheTTLOverridden() + case usagelog.FieldCreatedAt: + return m.CreatedAt() + } + return nil, false } // OldField returns the old value of the field from the database. An error is @@ -20648,1679 +21417,2843 @@ func (m *UsageLogMutation) AddField(name string, value ent.Value) error { return fmt.Errorf("unknown UsageLog numeric field %s", name) } -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *UsageLogMutation) ClearedFields() []string { - var fields []string - if m.FieldCleared(usagelog.FieldGroupID) { - fields = append(fields, usagelog.FieldGroupID) +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *UsageLogMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(usagelog.FieldGroupID) { + fields = append(fields, usagelog.FieldGroupID) + } + if m.FieldCleared(usagelog.FieldSubscriptionID) { + fields = append(fields, usagelog.FieldSubscriptionID) + } + if m.FieldCleared(usagelog.FieldAccountRateMultiplier) { + fields = append(fields, usagelog.FieldAccountRateMultiplier) + } + if m.FieldCleared(usagelog.FieldDurationMs) { + fields = append(fields, usagelog.FieldDurationMs) + } + if m.FieldCleared(usagelog.FieldFirstTokenMs) { + fields = append(fields, usagelog.FieldFirstTokenMs) + } + if m.FieldCleared(usagelog.FieldUserAgent) { + fields = append(fields, usagelog.FieldUserAgent) + } + if m.FieldCleared(usagelog.FieldIPAddress) { + fields = append(fields, usagelog.FieldIPAddress) + } + if m.FieldCleared(usagelog.FieldImageSize) { + fields = append(fields, usagelog.FieldImageSize) + } + if m.FieldCleared(usagelog.FieldMediaType) { + fields = append(fields, usagelog.FieldMediaType) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *UsageLogMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *UsageLogMutation) ClearField(name string) error { + switch name { + case usagelog.FieldGroupID: + m.ClearGroupID() + return nil + case usagelog.FieldSubscriptionID: + m.ClearSubscriptionID() + return nil + case usagelog.FieldAccountRateMultiplier: + m.ClearAccountRateMultiplier() + return nil + case usagelog.FieldDurationMs: + m.ClearDurationMs() + return nil + case usagelog.FieldFirstTokenMs: + m.ClearFirstTokenMs() + return nil + case usagelog.FieldUserAgent: + m.ClearUserAgent() + return nil + case usagelog.FieldIPAddress: + m.ClearIPAddress() + return nil + case usagelog.FieldImageSize: + m.ClearImageSize() + return nil + case usagelog.FieldMediaType: + m.ClearMediaType() + return nil + } + return fmt.Errorf("unknown UsageLog nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *UsageLogMutation) ResetField(name string) error { + switch name { + case usagelog.FieldUserID: + m.ResetUserID() + return nil + case usagelog.FieldAPIKeyID: + m.ResetAPIKeyID() + return nil + case usagelog.FieldAccountID: + m.ResetAccountID() + return nil + case usagelog.FieldRequestID: + m.ResetRequestID() + return nil + case usagelog.FieldModel: + m.ResetModel() + return nil + case usagelog.FieldGroupID: + m.ResetGroupID() + return nil + case usagelog.FieldSubscriptionID: + m.ResetSubscriptionID() + return nil + case usagelog.FieldInputTokens: + m.ResetInputTokens() + return nil + case usagelog.FieldOutputTokens: + m.ResetOutputTokens() + return nil + case usagelog.FieldCacheCreationTokens: + m.ResetCacheCreationTokens() + return nil + case usagelog.FieldCacheReadTokens: + m.ResetCacheReadTokens() + return nil + case usagelog.FieldCacheCreation5mTokens: + m.ResetCacheCreation5mTokens() + return nil + case usagelog.FieldCacheCreation1hTokens: + m.ResetCacheCreation1hTokens() + return nil + case usagelog.FieldInputCost: + m.ResetInputCost() + return nil + case usagelog.FieldOutputCost: + m.ResetOutputCost() + return nil + case usagelog.FieldCacheCreationCost: + m.ResetCacheCreationCost() + return nil + case usagelog.FieldCacheReadCost: + m.ResetCacheReadCost() + return nil + case usagelog.FieldTotalCost: + m.ResetTotalCost() + return nil + case usagelog.FieldActualCost: + m.ResetActualCost() + return nil + case usagelog.FieldRateMultiplier: + m.ResetRateMultiplier() + return nil + case usagelog.FieldAccountRateMultiplier: + m.ResetAccountRateMultiplier() + return nil + case usagelog.FieldBillingType: + m.ResetBillingType() + return nil + case usagelog.FieldStream: + m.ResetStream() + return nil + case usagelog.FieldDurationMs: + m.ResetDurationMs() + return nil + case usagelog.FieldFirstTokenMs: + m.ResetFirstTokenMs() + return nil + case usagelog.FieldUserAgent: + m.ResetUserAgent() + return nil + case usagelog.FieldIPAddress: + m.ResetIPAddress() + return nil + case usagelog.FieldImageCount: + m.ResetImageCount() + return nil + case usagelog.FieldImageSize: + m.ResetImageSize() + return nil + case usagelog.FieldMediaType: + m.ResetMediaType() + return nil + case usagelog.FieldCacheTTLOverridden: + m.ResetCacheTTLOverridden() + return nil + case usagelog.FieldCreatedAt: + m.ResetCreatedAt() + return nil + } + return fmt.Errorf("unknown UsageLog field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *UsageLogMutation) AddedEdges() []string { + edges := make([]string, 0, 5) + if m.user != nil { + edges = append(edges, usagelog.EdgeUser) + } + if m.api_key != nil { + edges = append(edges, usagelog.EdgeAPIKey) + } + if m.account != nil { + edges = append(edges, usagelog.EdgeAccount) + } + if m.group != nil { + edges = append(edges, usagelog.EdgeGroup) + } + if m.subscription != nil { + edges = append(edges, usagelog.EdgeSubscription) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *UsageLogMutation) AddedIDs(name string) []ent.Value { + switch name { + case usagelog.EdgeUser: + if id := m.user; id != nil { + return []ent.Value{*id} + } + case usagelog.EdgeAPIKey: + if id := m.api_key; id != nil { + return []ent.Value{*id} + } + case usagelog.EdgeAccount: + if id := m.account; id != nil { + return []ent.Value{*id} + } + case usagelog.EdgeGroup: + if id := m.group; id != nil { + return []ent.Value{*id} + } + case usagelog.EdgeSubscription: + if id := m.subscription; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *UsageLogMutation) RemovedEdges() []string { + edges := make([]string, 0, 5) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *UsageLogMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *UsageLogMutation) ClearedEdges() []string { + edges := make([]string, 0, 5) + if m.cleareduser { + edges = append(edges, usagelog.EdgeUser) + } + if m.clearedapi_key { + edges = append(edges, usagelog.EdgeAPIKey) + } + if m.clearedaccount { + edges = append(edges, usagelog.EdgeAccount) + } + if m.clearedgroup { + edges = append(edges, usagelog.EdgeGroup) + } + if m.clearedsubscription { + edges = append(edges, usagelog.EdgeSubscription) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *UsageLogMutation) EdgeCleared(name string) bool { + switch name { + case usagelog.EdgeUser: + return m.cleareduser + case usagelog.EdgeAPIKey: + return m.clearedapi_key + case usagelog.EdgeAccount: + return m.clearedaccount + case usagelog.EdgeGroup: + return m.clearedgroup + case usagelog.EdgeSubscription: + return m.clearedsubscription + } + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *UsageLogMutation) ClearEdge(name string) error { + switch name { + case usagelog.EdgeUser: + m.ClearUser() + return nil + case usagelog.EdgeAPIKey: + m.ClearAPIKey() + return nil + case usagelog.EdgeAccount: + m.ClearAccount() + return nil + case usagelog.EdgeGroup: + m.ClearGroup() + return nil + case usagelog.EdgeSubscription: + m.ClearSubscription() + return nil + } + return fmt.Errorf("unknown UsageLog unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *UsageLogMutation) ResetEdge(name string) error { + switch name { + case usagelog.EdgeUser: + m.ResetUser() + return nil + case usagelog.EdgeAPIKey: + m.ResetAPIKey() + return nil + case usagelog.EdgeAccount: + m.ResetAccount() + return nil + case usagelog.EdgeGroup: + m.ResetGroup() + return nil + case usagelog.EdgeSubscription: + m.ResetSubscription() + return nil + } + return fmt.Errorf("unknown UsageLog edge %s", name) +} + +// UserMutation represents an operation that mutates the User nodes in the graph. +type UserMutation struct { + config + op Op + typ string + id *int64 + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + email *string + password_hash *string + role *string + balance *float64 + addbalance *float64 + concurrency *int + addconcurrency *int + status *string + username *string + notes *string + totp_secret_encrypted *string + totp_enabled *bool + totp_enabled_at *time.Time + sora_storage_quota_bytes *int64 + addsora_storage_quota_bytes *int64 + sora_storage_used_bytes *int64 + addsora_storage_used_bytes *int64 + clearedFields map[string]struct{} + api_keys map[int64]struct{} + removedapi_keys map[int64]struct{} + clearedapi_keys bool + redeem_codes map[int64]struct{} + removedredeem_codes map[int64]struct{} + clearedredeem_codes bool + subscriptions map[int64]struct{} + removedsubscriptions map[int64]struct{} + clearedsubscriptions bool + assigned_subscriptions map[int64]struct{} + removedassigned_subscriptions map[int64]struct{} + clearedassigned_subscriptions bool + announcement_reads map[int64]struct{} + removedannouncement_reads map[int64]struct{} + clearedannouncement_reads bool + allowed_groups map[int64]struct{} + removedallowed_groups map[int64]struct{} + clearedallowed_groups bool + usage_logs map[int64]struct{} + removedusage_logs map[int64]struct{} + clearedusage_logs bool + attribute_values map[int64]struct{} + removedattribute_values map[int64]struct{} + clearedattribute_values bool + promo_code_usages map[int64]struct{} + removedpromo_code_usages map[int64]struct{} + clearedpromo_code_usages bool + referral_profile map[int64]struct{} + removedreferral_profile map[int64]struct{} + clearedreferral_profile bool + referrals_given map[int64]struct{} + removedreferrals_given map[int64]struct{} + clearedreferrals_given bool + referral_received map[int64]struct{} + removedreferral_received map[int64]struct{} + clearedreferral_received bool + done bool + oldValue func(context.Context) (*User, error) + predicates []predicate.User +} + +var _ ent.Mutation = (*UserMutation)(nil) + +// userOption allows management of the mutation configuration using functional options. +type userOption func(*UserMutation) + +// newUserMutation creates new mutation for the User entity. +func newUserMutation(c config, op Op, opts ...userOption) *UserMutation { + m := &UserMutation{ + config: c, + op: op, + typ: TypeUser, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withUserID sets the ID field of the mutation. +func withUserID(id int64) userOption { + return func(m *UserMutation) { + var ( + err error + once sync.Once + value *User + ) + m.oldValue = func(ctx context.Context) (*User, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().User.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withUser sets the old User of the mutation. +func withUser(node *User) userOption { + return func(m *UserMutation) { + m.oldValue = func(context.Context) (*User, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m UserMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m UserMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *UserMutation) ID() (id int64, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *UserMutation) IDs(ctx context.Context) ([]int64, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int64{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().User.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetCreatedAt sets the "created_at" field. +func (m *UserMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *UserMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return + } + return *v, true +} + +// OldCreatedAt returns the old "created_at" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + } + return oldValue.CreatedAt, nil +} + +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *UserMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *UserMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *UserMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at + if v == nil { + return + } + return *v, true +} + +// OldUpdatedAt returns the old "updated_at" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + } + return oldValue.UpdatedAt, nil +} + +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *UserMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *UserMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *UserMutation) DeletedAt() (r time.Time, exists bool) { + v := m.deleted_at + if v == nil { + return + } + return *v, true +} + +// OldDeletedAt returns the old "deleted_at" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldDeletedAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDeletedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDeletedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDeletedAt: %w", err) + } + return oldValue.DeletedAt, nil +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (m *UserMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[user.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *UserMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[user.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *UserMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, user.FieldDeletedAt) +} + +// SetEmail sets the "email" field. +func (m *UserMutation) SetEmail(s string) { + m.email = &s +} + +// Email returns the value of the "email" field in the mutation. +func (m *UserMutation) Email() (r string, exists bool) { + v := m.email + if v == nil { + return + } + return *v, true +} + +// OldEmail returns the old "email" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldEmail(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEmail is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEmail requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEmail: %w", err) + } + return oldValue.Email, nil +} + +// ResetEmail resets all changes to the "email" field. +func (m *UserMutation) ResetEmail() { + m.email = nil +} + +// SetPasswordHash sets the "password_hash" field. +func (m *UserMutation) SetPasswordHash(s string) { + m.password_hash = &s +} + +// PasswordHash returns the value of the "password_hash" field in the mutation. +func (m *UserMutation) PasswordHash() (r string, exists bool) { + v := m.password_hash + if v == nil { + return } - if m.FieldCleared(usagelog.FieldSubscriptionID) { - fields = append(fields, usagelog.FieldSubscriptionID) + return *v, true +} + +// OldPasswordHash returns the old "password_hash" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldPasswordHash(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPasswordHash is only allowed on UpdateOne operations") } - if m.FieldCleared(usagelog.FieldAccountRateMultiplier) { - fields = append(fields, usagelog.FieldAccountRateMultiplier) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPasswordHash requires an ID field in the mutation") } - if m.FieldCleared(usagelog.FieldDurationMs) { - fields = append(fields, usagelog.FieldDurationMs) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPasswordHash: %w", err) } - if m.FieldCleared(usagelog.FieldFirstTokenMs) { - fields = append(fields, usagelog.FieldFirstTokenMs) + return oldValue.PasswordHash, nil +} + +// ResetPasswordHash resets all changes to the "password_hash" field. +func (m *UserMutation) ResetPasswordHash() { + m.password_hash = nil +} + +// SetRole sets the "role" field. +func (m *UserMutation) SetRole(s string) { + m.role = &s +} + +// Role returns the value of the "role" field in the mutation. +func (m *UserMutation) Role() (r string, exists bool) { + v := m.role + if v == nil { + return } - if m.FieldCleared(usagelog.FieldUserAgent) { - fields = append(fields, usagelog.FieldUserAgent) + return *v, true +} + +// OldRole returns the old "role" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldRole(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRole is only allowed on UpdateOne operations") } - if m.FieldCleared(usagelog.FieldIPAddress) { - fields = append(fields, usagelog.FieldIPAddress) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRole requires an ID field in the mutation") } - if m.FieldCleared(usagelog.FieldImageSize) { - fields = append(fields, usagelog.FieldImageSize) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRole: %w", err) } - if m.FieldCleared(usagelog.FieldMediaType) { - fields = append(fields, usagelog.FieldMediaType) + return oldValue.Role, nil +} + +// ResetRole resets all changes to the "role" field. +func (m *UserMutation) ResetRole() { + m.role = nil +} + +// SetBalance sets the "balance" field. +func (m *UserMutation) SetBalance(f float64) { + m.balance = &f + m.addbalance = nil +} + +// Balance returns the value of the "balance" field in the mutation. +func (m *UserMutation) Balance() (r float64, exists bool) { + v := m.balance + if v == nil { + return } - return fields + return *v, true } -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *UsageLogMutation) FieldCleared(name string) bool { - _, ok := m.clearedFields[name] - return ok +// OldBalance returns the old "balance" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldBalance(ctx context.Context) (v float64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBalance is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBalance requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBalance: %w", err) + } + return oldValue.Balance, nil } -// ClearField clears the value of the field with the given name. It returns an -// error if the field is not defined in the schema. -func (m *UsageLogMutation) ClearField(name string) error { - switch name { - case usagelog.FieldGroupID: - m.ClearGroupID() - return nil - case usagelog.FieldSubscriptionID: - m.ClearSubscriptionID() - return nil - case usagelog.FieldAccountRateMultiplier: - m.ClearAccountRateMultiplier() - return nil - case usagelog.FieldDurationMs: - m.ClearDurationMs() - return nil - case usagelog.FieldFirstTokenMs: - m.ClearFirstTokenMs() - return nil - case usagelog.FieldUserAgent: - m.ClearUserAgent() - return nil - case usagelog.FieldIPAddress: - m.ClearIPAddress() - return nil - case usagelog.FieldImageSize: - m.ClearImageSize() - return nil - case usagelog.FieldMediaType: - m.ClearMediaType() - return nil +// AddBalance adds f to the "balance" field. +func (m *UserMutation) AddBalance(f float64) { + if m.addbalance != nil { + *m.addbalance += f + } else { + m.addbalance = &f } - return fmt.Errorf("unknown UsageLog nullable field %s", name) } -// ResetField resets all changes in the mutation for the field with the given name. -// It returns an error if the field is not defined in the schema. -func (m *UsageLogMutation) ResetField(name string) error { - switch name { - case usagelog.FieldUserID: - m.ResetUserID() - return nil - case usagelog.FieldAPIKeyID: - m.ResetAPIKeyID() - return nil - case usagelog.FieldAccountID: - m.ResetAccountID() - return nil - case usagelog.FieldRequestID: - m.ResetRequestID() - return nil - case usagelog.FieldModel: - m.ResetModel() - return nil - case usagelog.FieldGroupID: - m.ResetGroupID() - return nil - case usagelog.FieldSubscriptionID: - m.ResetSubscriptionID() - return nil - case usagelog.FieldInputTokens: - m.ResetInputTokens() - return nil - case usagelog.FieldOutputTokens: - m.ResetOutputTokens() - return nil - case usagelog.FieldCacheCreationTokens: - m.ResetCacheCreationTokens() - return nil - case usagelog.FieldCacheReadTokens: - m.ResetCacheReadTokens() - return nil - case usagelog.FieldCacheCreation5mTokens: - m.ResetCacheCreation5mTokens() - return nil - case usagelog.FieldCacheCreation1hTokens: - m.ResetCacheCreation1hTokens() - return nil - case usagelog.FieldInputCost: - m.ResetInputCost() - return nil - case usagelog.FieldOutputCost: - m.ResetOutputCost() - return nil - case usagelog.FieldCacheCreationCost: - m.ResetCacheCreationCost() - return nil - case usagelog.FieldCacheReadCost: - m.ResetCacheReadCost() - return nil - case usagelog.FieldTotalCost: - m.ResetTotalCost() - return nil - case usagelog.FieldActualCost: - m.ResetActualCost() - return nil - case usagelog.FieldRateMultiplier: - m.ResetRateMultiplier() - return nil - case usagelog.FieldAccountRateMultiplier: - m.ResetAccountRateMultiplier() - return nil - case usagelog.FieldBillingType: - m.ResetBillingType() - return nil - case usagelog.FieldStream: - m.ResetStream() - return nil - case usagelog.FieldDurationMs: - m.ResetDurationMs() - return nil - case usagelog.FieldFirstTokenMs: - m.ResetFirstTokenMs() - return nil - case usagelog.FieldUserAgent: - m.ResetUserAgent() - return nil - case usagelog.FieldIPAddress: - m.ResetIPAddress() - return nil - case usagelog.FieldImageCount: - m.ResetImageCount() - return nil - case usagelog.FieldImageSize: - m.ResetImageSize() - return nil - case usagelog.FieldMediaType: - m.ResetMediaType() - return nil - case usagelog.FieldCacheTTLOverridden: - m.ResetCacheTTLOverridden() - return nil - case usagelog.FieldCreatedAt: - m.ResetCreatedAt() - return nil +// AddedBalance returns the value that was added to the "balance" field in this mutation. +func (m *UserMutation) AddedBalance() (r float64, exists bool) { + v := m.addbalance + if v == nil { + return } - return fmt.Errorf("unknown UsageLog field %s", name) + return *v, true } -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *UsageLogMutation) AddedEdges() []string { - edges := make([]string, 0, 5) - if m.user != nil { - edges = append(edges, usagelog.EdgeUser) +// ResetBalance resets all changes to the "balance" field. +func (m *UserMutation) ResetBalance() { + m.balance = nil + m.addbalance = nil +} + +// SetConcurrency sets the "concurrency" field. +func (m *UserMutation) SetConcurrency(i int) { + m.concurrency = &i + m.addconcurrency = nil +} + +// Concurrency returns the value of the "concurrency" field in the mutation. +func (m *UserMutation) Concurrency() (r int, exists bool) { + v := m.concurrency + if v == nil { + return } - if m.api_key != nil { - edges = append(edges, usagelog.EdgeAPIKey) + return *v, true +} + +// OldConcurrency returns the old "concurrency" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldConcurrency(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldConcurrency is only allowed on UpdateOne operations") } - if m.account != nil { - edges = append(edges, usagelog.EdgeAccount) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldConcurrency requires an ID field in the mutation") } - if m.group != nil { - edges = append(edges, usagelog.EdgeGroup) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldConcurrency: %w", err) } - if m.subscription != nil { - edges = append(edges, usagelog.EdgeSubscription) + return oldValue.Concurrency, nil +} + +// AddConcurrency adds i to the "concurrency" field. +func (m *UserMutation) AddConcurrency(i int) { + if m.addconcurrency != nil { + *m.addconcurrency += i + } else { + m.addconcurrency = &i } - return edges } -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *UsageLogMutation) AddedIDs(name string) []ent.Value { - switch name { - case usagelog.EdgeUser: - if id := m.user; id != nil { - return []ent.Value{*id} - } - case usagelog.EdgeAPIKey: - if id := m.api_key; id != nil { - return []ent.Value{*id} - } - case usagelog.EdgeAccount: - if id := m.account; id != nil { - return []ent.Value{*id} - } - case usagelog.EdgeGroup: - if id := m.group; id != nil { - return []ent.Value{*id} - } - case usagelog.EdgeSubscription: - if id := m.subscription; id != nil { - return []ent.Value{*id} - } +// AddedConcurrency returns the value that was added to the "concurrency" field in this mutation. +func (m *UserMutation) AddedConcurrency() (r int, exists bool) { + v := m.addconcurrency + if v == nil { + return } - return nil + return *v, true } -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *UsageLogMutation) RemovedEdges() []string { - edges := make([]string, 0, 5) - return edges +// ResetConcurrency resets all changes to the "concurrency" field. +func (m *UserMutation) ResetConcurrency() { + m.concurrency = nil + m.addconcurrency = nil } -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *UsageLogMutation) RemovedIDs(name string) []ent.Value { - return nil +// SetStatus sets the "status" field. +func (m *UserMutation) SetStatus(s string) { + m.status = &s } -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *UsageLogMutation) ClearedEdges() []string { - edges := make([]string, 0, 5) - if m.cleareduser { - edges = append(edges, usagelog.EdgeUser) +// Status returns the value of the "status" field in the mutation. +func (m *UserMutation) Status() (r string, exists bool) { + v := m.status + if v == nil { + return } - if m.clearedapi_key { - edges = append(edges, usagelog.EdgeAPIKey) + return *v, true +} + +// OldStatus returns the old "status" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldStatus(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStatus is only allowed on UpdateOne operations") } - if m.clearedaccount { - edges = append(edges, usagelog.EdgeAccount) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStatus requires an ID field in the mutation") } - if m.clearedgroup { - edges = append(edges, usagelog.EdgeGroup) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStatus: %w", err) } - if m.clearedsubscription { - edges = append(edges, usagelog.EdgeSubscription) + return oldValue.Status, nil +} + +// ResetStatus resets all changes to the "status" field. +func (m *UserMutation) ResetStatus() { + m.status = nil +} + +// SetUsername sets the "username" field. +func (m *UserMutation) SetUsername(s string) { + m.username = &s +} + +// Username returns the value of the "username" field in the mutation. +func (m *UserMutation) Username() (r string, exists bool) { + v := m.username + if v == nil { + return } - return edges + return *v, true } -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *UsageLogMutation) EdgeCleared(name string) bool { - switch name { - case usagelog.EdgeUser: - return m.cleareduser - case usagelog.EdgeAPIKey: - return m.clearedapi_key - case usagelog.EdgeAccount: - return m.clearedaccount - case usagelog.EdgeGroup: - return m.clearedgroup - case usagelog.EdgeSubscription: - return m.clearedsubscription +// OldUsername returns the old "username" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldUsername(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUsername is only allowed on UpdateOne operations") } - return false + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUsername requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUsername: %w", err) + } + return oldValue.Username, nil } -// ClearEdge clears the value of the edge with the given name. It returns an error -// if that edge is not defined in the schema. -func (m *UsageLogMutation) ClearEdge(name string) error { - switch name { - case usagelog.EdgeUser: - m.ClearUser() - return nil - case usagelog.EdgeAPIKey: - m.ClearAPIKey() - return nil - case usagelog.EdgeAccount: - m.ClearAccount() - return nil - case usagelog.EdgeGroup: - m.ClearGroup() - return nil - case usagelog.EdgeSubscription: - m.ClearSubscription() - return nil +// ResetUsername resets all changes to the "username" field. +func (m *UserMutation) ResetUsername() { + m.username = nil +} + +// SetNotes sets the "notes" field. +func (m *UserMutation) SetNotes(s string) { + m.notes = &s +} + +// Notes returns the value of the "notes" field in the mutation. +func (m *UserMutation) Notes() (r string, exists bool) { + v := m.notes + if v == nil { + return + } + return *v, true +} + +// OldNotes returns the old "notes" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldNotes(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldNotes is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldNotes requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldNotes: %w", err) + } + return oldValue.Notes, nil +} + +// ResetNotes resets all changes to the "notes" field. +func (m *UserMutation) ResetNotes() { + m.notes = nil +} + +// SetTotpSecretEncrypted sets the "totp_secret_encrypted" field. +func (m *UserMutation) SetTotpSecretEncrypted(s string) { + m.totp_secret_encrypted = &s +} + +// TotpSecretEncrypted returns the value of the "totp_secret_encrypted" field in the mutation. +func (m *UserMutation) TotpSecretEncrypted() (r string, exists bool) { + v := m.totp_secret_encrypted + if v == nil { + return } - return fmt.Errorf("unknown UsageLog unique edge %s", name) + return *v, true } -// ResetEdge resets all changes to the edge with the given name in this mutation. -// It returns an error if the edge is not defined in the schema. -func (m *UsageLogMutation) ResetEdge(name string) error { - switch name { - case usagelog.EdgeUser: - m.ResetUser() - return nil - case usagelog.EdgeAPIKey: - m.ResetAPIKey() - return nil - case usagelog.EdgeAccount: - m.ResetAccount() - return nil - case usagelog.EdgeGroup: - m.ResetGroup() - return nil - case usagelog.EdgeSubscription: - m.ResetSubscription() - return nil +// OldTotpSecretEncrypted returns the old "totp_secret_encrypted" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldTotpSecretEncrypted(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTotpSecretEncrypted is only allowed on UpdateOne operations") } - return fmt.Errorf("unknown UsageLog edge %s", name) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTotpSecretEncrypted requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTotpSecretEncrypted: %w", err) + } + return oldValue.TotpSecretEncrypted, nil } -// UserMutation represents an operation that mutates the User nodes in the graph. -type UserMutation struct { - config - op Op - typ string - id *int64 - created_at *time.Time - updated_at *time.Time - deleted_at *time.Time - email *string - password_hash *string - role *string - balance *float64 - addbalance *float64 - concurrency *int - addconcurrency *int - status *string - username *string - notes *string - totp_secret_encrypted *string - totp_enabled *bool - totp_enabled_at *time.Time - sora_storage_quota_bytes *int64 - addsora_storage_quota_bytes *int64 - sora_storage_used_bytes *int64 - addsora_storage_used_bytes *int64 - clearedFields map[string]struct{} - api_keys map[int64]struct{} - removedapi_keys map[int64]struct{} - clearedapi_keys bool - redeem_codes map[int64]struct{} - removedredeem_codes map[int64]struct{} - clearedredeem_codes bool - subscriptions map[int64]struct{} - removedsubscriptions map[int64]struct{} - clearedsubscriptions bool - assigned_subscriptions map[int64]struct{} - removedassigned_subscriptions map[int64]struct{} - clearedassigned_subscriptions bool - announcement_reads map[int64]struct{} - removedannouncement_reads map[int64]struct{} - clearedannouncement_reads bool - allowed_groups map[int64]struct{} - removedallowed_groups map[int64]struct{} - clearedallowed_groups bool - usage_logs map[int64]struct{} - removedusage_logs map[int64]struct{} - clearedusage_logs bool - attribute_values map[int64]struct{} - removedattribute_values map[int64]struct{} - clearedattribute_values bool - promo_code_usages map[int64]struct{} - removedpromo_code_usages map[int64]struct{} - clearedpromo_code_usages bool - done bool - oldValue func(context.Context) (*User, error) - predicates []predicate.User +// ClearTotpSecretEncrypted clears the value of the "totp_secret_encrypted" field. +func (m *UserMutation) ClearTotpSecretEncrypted() { + m.totp_secret_encrypted = nil + m.clearedFields[user.FieldTotpSecretEncrypted] = struct{}{} } -var _ ent.Mutation = (*UserMutation)(nil) +// TotpSecretEncryptedCleared returns if the "totp_secret_encrypted" field was cleared in this mutation. +func (m *UserMutation) TotpSecretEncryptedCleared() bool { + _, ok := m.clearedFields[user.FieldTotpSecretEncrypted] + return ok +} -// userOption allows management of the mutation configuration using functional options. -type userOption func(*UserMutation) +// ResetTotpSecretEncrypted resets all changes to the "totp_secret_encrypted" field. +func (m *UserMutation) ResetTotpSecretEncrypted() { + m.totp_secret_encrypted = nil + delete(m.clearedFields, user.FieldTotpSecretEncrypted) +} -// newUserMutation creates new mutation for the User entity. -func newUserMutation(c config, op Op, opts ...userOption) *UserMutation { - m := &UserMutation{ - config: c, - op: op, - typ: TypeUser, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) - } - return m +// SetTotpEnabled sets the "totp_enabled" field. +func (m *UserMutation) SetTotpEnabled(b bool) { + m.totp_enabled = &b } -// withUserID sets the ID field of the mutation. -func withUserID(id int64) userOption { - return func(m *UserMutation) { - var ( - err error - once sync.Once - value *User - ) - m.oldValue = func(ctx context.Context) (*User, error) { - once.Do(func() { - if m.done { - err = errors.New("querying old values post mutation is not allowed") - } else { - value, err = m.Client().User.Get(ctx, id) - } - }) - return value, err - } - m.id = &id +// TotpEnabled returns the value of the "totp_enabled" field in the mutation. +func (m *UserMutation) TotpEnabled() (r bool, exists bool) { + v := m.totp_enabled + if v == nil { + return } + return *v, true } -// withUser sets the old User of the mutation. -func withUser(node *User) userOption { - return func(m *UserMutation) { - m.oldValue = func(context.Context) (*User, error) { - return node, nil - } - m.id = &node.ID +// OldTotpEnabled returns the old "totp_enabled" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldTotpEnabled(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTotpEnabled is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTotpEnabled requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTotpEnabled: %w", err) } + return oldValue.TotpEnabled, nil } -// Client returns a new `ent.Client` from the mutation. If the mutation was -// executed in a transaction (ent.Tx), a transactional client is returned. -func (m UserMutation) Client() *Client { - client := &Client{config: m.config} - client.init() - return client +// ResetTotpEnabled resets all changes to the "totp_enabled" field. +func (m *UserMutation) ResetTotpEnabled() { + m.totp_enabled = nil } -// Tx returns an `ent.Tx` for mutations that were executed in transactions; -// it returns an error otherwise. -func (m UserMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, errors.New("ent: mutation is not running in a transaction") - } - tx := &Tx{config: m.config} - tx.init() - return tx, nil +// SetTotpEnabledAt sets the "totp_enabled_at" field. +func (m *UserMutation) SetTotpEnabledAt(t time.Time) { + m.totp_enabled_at = &t } -// ID returns the ID value in the mutation. Note that the ID is only available -// if it was provided to the builder or after it was returned from the database. -func (m *UserMutation) ID() (id int64, exists bool) { - if m.id == nil { +// TotpEnabledAt returns the value of the "totp_enabled_at" field in the mutation. +func (m *UserMutation) TotpEnabledAt() (r time.Time, exists bool) { + v := m.totp_enabled_at + if v == nil { return } - return *m.id, true + return *v, true } -// IDs queries the database and returns the entity ids that match the mutation's predicate. -// That means, if the mutation is applied within a transaction with an isolation level such -// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated -// or updated by the mutation. -func (m *UserMutation) IDs(ctx context.Context) ([]int64, error) { - switch { - case m.op.Is(OpUpdateOne | OpDeleteOne): - id, exists := m.ID() - if exists { - return []int64{id}, nil - } - fallthrough - case m.op.Is(OpUpdate | OpDelete): - return m.Client().User.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) +// OldTotpEnabledAt returns the old "totp_enabled_at" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldTotpEnabledAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTotpEnabledAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTotpEnabledAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTotpEnabledAt: %w", err) } + return oldValue.TotpEnabledAt, nil } -// SetCreatedAt sets the "created_at" field. -func (m *UserMutation) SetCreatedAt(t time.Time) { - m.created_at = &t +// ClearTotpEnabledAt clears the value of the "totp_enabled_at" field. +func (m *UserMutation) ClearTotpEnabledAt() { + m.totp_enabled_at = nil + m.clearedFields[user.FieldTotpEnabledAt] = struct{}{} +} + +// TotpEnabledAtCleared returns if the "totp_enabled_at" field was cleared in this mutation. +func (m *UserMutation) TotpEnabledAtCleared() bool { + _, ok := m.clearedFields[user.FieldTotpEnabledAt] + return ok +} + +// ResetTotpEnabledAt resets all changes to the "totp_enabled_at" field. +func (m *UserMutation) ResetTotpEnabledAt() { + m.totp_enabled_at = nil + delete(m.clearedFields, user.FieldTotpEnabledAt) +} + +// SetSoraStorageQuotaBytes sets the "sora_storage_quota_bytes" field. +func (m *UserMutation) SetSoraStorageQuotaBytes(i int64) { + m.sora_storage_quota_bytes = &i + m.addsora_storage_quota_bytes = nil } -// CreatedAt returns the value of the "created_at" field in the mutation. -func (m *UserMutation) CreatedAt() (r time.Time, exists bool) { - v := m.created_at +// SoraStorageQuotaBytes returns the value of the "sora_storage_quota_bytes" field in the mutation. +func (m *UserMutation) SoraStorageQuotaBytes() (r int64, exists bool) { + v := m.sora_storage_quota_bytes if v == nil { return } return *v, true } -// OldCreatedAt returns the old "created_at" field's value of the User entity. +// OldSoraStorageQuotaBytes returns the old "sora_storage_quota_bytes" field's value of the User entity. // If the User object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { +func (m *UserMutation) OldSoraStorageQuotaBytes(ctx context.Context) (v int64, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + return v, errors.New("OldSoraStorageQuotaBytes is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCreatedAt requires an ID field in the mutation") + return v, errors.New("OldSoraStorageQuotaBytes requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + return v, fmt.Errorf("querying old value for OldSoraStorageQuotaBytes: %w", err) } - return oldValue.CreatedAt, nil + return oldValue.SoraStorageQuotaBytes, nil } -// ResetCreatedAt resets all changes to the "created_at" field. -func (m *UserMutation) ResetCreatedAt() { - m.created_at = nil +// AddSoraStorageQuotaBytes adds i to the "sora_storage_quota_bytes" field. +func (m *UserMutation) AddSoraStorageQuotaBytes(i int64) { + if m.addsora_storage_quota_bytes != nil { + *m.addsora_storage_quota_bytes += i + } else { + m.addsora_storage_quota_bytes = &i + } } -// SetUpdatedAt sets the "updated_at" field. -func (m *UserMutation) SetUpdatedAt(t time.Time) { - m.updated_at = &t +// AddedSoraStorageQuotaBytes returns the value that was added to the "sora_storage_quota_bytes" field in this mutation. +func (m *UserMutation) AddedSoraStorageQuotaBytes() (r int64, exists bool) { + v := m.addsora_storage_quota_bytes + if v == nil { + return + } + return *v, true } -// UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *UserMutation) UpdatedAt() (r time.Time, exists bool) { - v := m.updated_at +// ResetSoraStorageQuotaBytes resets all changes to the "sora_storage_quota_bytes" field. +func (m *UserMutation) ResetSoraStorageQuotaBytes() { + m.sora_storage_quota_bytes = nil + m.addsora_storage_quota_bytes = nil +} + +// SetSoraStorageUsedBytes sets the "sora_storage_used_bytes" field. +func (m *UserMutation) SetSoraStorageUsedBytes(i int64) { + m.sora_storage_used_bytes = &i + m.addsora_storage_used_bytes = nil +} + +// SoraStorageUsedBytes returns the value of the "sora_storage_used_bytes" field in the mutation. +func (m *UserMutation) SoraStorageUsedBytes() (r int64, exists bool) { + v := m.sora_storage_used_bytes if v == nil { return } return *v, true } -// OldUpdatedAt returns the old "updated_at" field's value of the User entity. +// OldSoraStorageUsedBytes returns the old "sora_storage_used_bytes" field's value of the User entity. // If the User object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { +func (m *UserMutation) OldSoraStorageUsedBytes(ctx context.Context) (v int64, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + return v, errors.New("OldSoraStorageUsedBytes is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUpdatedAt requires an ID field in the mutation") + return v, errors.New("OldSoraStorageUsedBytes requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + return v, fmt.Errorf("querying old value for OldSoraStorageUsedBytes: %w", err) } - return oldValue.UpdatedAt, nil -} - -// ResetUpdatedAt resets all changes to the "updated_at" field. -func (m *UserMutation) ResetUpdatedAt() { - m.updated_at = nil + return oldValue.SoraStorageUsedBytes, nil } -// SetDeletedAt sets the "deleted_at" field. -func (m *UserMutation) SetDeletedAt(t time.Time) { - m.deleted_at = &t +// AddSoraStorageUsedBytes adds i to the "sora_storage_used_bytes" field. +func (m *UserMutation) AddSoraStorageUsedBytes(i int64) { + if m.addsora_storage_used_bytes != nil { + *m.addsora_storage_used_bytes += i + } else { + m.addsora_storage_used_bytes = &i + } } -// DeletedAt returns the value of the "deleted_at" field in the mutation. -func (m *UserMutation) DeletedAt() (r time.Time, exists bool) { - v := m.deleted_at +// AddedSoraStorageUsedBytes returns the value that was added to the "sora_storage_used_bytes" field in this mutation. +func (m *UserMutation) AddedSoraStorageUsedBytes() (r int64, exists bool) { + v := m.addsora_storage_used_bytes if v == nil { return } return *v, true } -// OldDeletedAt returns the old "deleted_at" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserMutation) OldDeletedAt(ctx context.Context) (v *time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldDeletedAt is only allowed on UpdateOne operations") +// ResetSoraStorageUsedBytes resets all changes to the "sora_storage_used_bytes" field. +func (m *UserMutation) ResetSoraStorageUsedBytes() { + m.sora_storage_used_bytes = nil + m.addsora_storage_used_bytes = nil +} + +// AddAPIKeyIDs adds the "api_keys" edge to the APIKey entity by ids. +func (m *UserMutation) AddAPIKeyIDs(ids ...int64) { + if m.api_keys == nil { + m.api_keys = make(map[int64]struct{}) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldDeletedAt requires an ID field in the mutation") + for i := range ids { + m.api_keys[ids[i]] = struct{}{} } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldDeletedAt: %w", err) +} + +// ClearAPIKeys clears the "api_keys" edge to the APIKey entity. +func (m *UserMutation) ClearAPIKeys() { + m.clearedapi_keys = true +} + +// APIKeysCleared reports if the "api_keys" edge to the APIKey entity was cleared. +func (m *UserMutation) APIKeysCleared() bool { + return m.clearedapi_keys +} + +// RemoveAPIKeyIDs removes the "api_keys" edge to the APIKey entity by IDs. +func (m *UserMutation) RemoveAPIKeyIDs(ids ...int64) { + if m.removedapi_keys == nil { + m.removedapi_keys = make(map[int64]struct{}) + } + for i := range ids { + delete(m.api_keys, ids[i]) + m.removedapi_keys[ids[i]] = struct{}{} + } +} + +// RemovedAPIKeys returns the removed IDs of the "api_keys" edge to the APIKey entity. +func (m *UserMutation) RemovedAPIKeysIDs() (ids []int64) { + for id := range m.removedapi_keys { + ids = append(ids, id) + } + return +} + +// APIKeysIDs returns the "api_keys" edge IDs in the mutation. +func (m *UserMutation) APIKeysIDs() (ids []int64) { + for id := range m.api_keys { + ids = append(ids, id) + } + return +} + +// ResetAPIKeys resets all changes to the "api_keys" edge. +func (m *UserMutation) ResetAPIKeys() { + m.api_keys = nil + m.clearedapi_keys = false + m.removedapi_keys = nil +} + +// AddRedeemCodeIDs adds the "redeem_codes" edge to the RedeemCode entity by ids. +func (m *UserMutation) AddRedeemCodeIDs(ids ...int64) { + if m.redeem_codes == nil { + m.redeem_codes = make(map[int64]struct{}) + } + for i := range ids { + m.redeem_codes[ids[i]] = struct{}{} + } +} + +// ClearRedeemCodes clears the "redeem_codes" edge to the RedeemCode entity. +func (m *UserMutation) ClearRedeemCodes() { + m.clearedredeem_codes = true +} + +// RedeemCodesCleared reports if the "redeem_codes" edge to the RedeemCode entity was cleared. +func (m *UserMutation) RedeemCodesCleared() bool { + return m.clearedredeem_codes +} + +// RemoveRedeemCodeIDs removes the "redeem_codes" edge to the RedeemCode entity by IDs. +func (m *UserMutation) RemoveRedeemCodeIDs(ids ...int64) { + if m.removedredeem_codes == nil { + m.removedredeem_codes = make(map[int64]struct{}) + } + for i := range ids { + delete(m.redeem_codes, ids[i]) + m.removedredeem_codes[ids[i]] = struct{}{} + } +} + +// RemovedRedeemCodes returns the removed IDs of the "redeem_codes" edge to the RedeemCode entity. +func (m *UserMutation) RemovedRedeemCodesIDs() (ids []int64) { + for id := range m.removedredeem_codes { + ids = append(ids, id) + } + return +} + +// RedeemCodesIDs returns the "redeem_codes" edge IDs in the mutation. +func (m *UserMutation) RedeemCodesIDs() (ids []int64) { + for id := range m.redeem_codes { + ids = append(ids, id) + } + return +} + +// ResetRedeemCodes resets all changes to the "redeem_codes" edge. +func (m *UserMutation) ResetRedeemCodes() { + m.redeem_codes = nil + m.clearedredeem_codes = false + m.removedredeem_codes = nil +} + +// AddSubscriptionIDs adds the "subscriptions" edge to the UserSubscription entity by ids. +func (m *UserMutation) AddSubscriptionIDs(ids ...int64) { + if m.subscriptions == nil { + m.subscriptions = make(map[int64]struct{}) + } + for i := range ids { + m.subscriptions[ids[i]] = struct{}{} + } +} + +// ClearSubscriptions clears the "subscriptions" edge to the UserSubscription entity. +func (m *UserMutation) ClearSubscriptions() { + m.clearedsubscriptions = true +} + +// SubscriptionsCleared reports if the "subscriptions" edge to the UserSubscription entity was cleared. +func (m *UserMutation) SubscriptionsCleared() bool { + return m.clearedsubscriptions +} + +// RemoveSubscriptionIDs removes the "subscriptions" edge to the UserSubscription entity by IDs. +func (m *UserMutation) RemoveSubscriptionIDs(ids ...int64) { + if m.removedsubscriptions == nil { + m.removedsubscriptions = make(map[int64]struct{}) + } + for i := range ids { + delete(m.subscriptions, ids[i]) + m.removedsubscriptions[ids[i]] = struct{}{} + } +} + +// RemovedSubscriptions returns the removed IDs of the "subscriptions" edge to the UserSubscription entity. +func (m *UserMutation) RemovedSubscriptionsIDs() (ids []int64) { + for id := range m.removedsubscriptions { + ids = append(ids, id) + } + return +} + +// SubscriptionsIDs returns the "subscriptions" edge IDs in the mutation. +func (m *UserMutation) SubscriptionsIDs() (ids []int64) { + for id := range m.subscriptions { + ids = append(ids, id) } - return oldValue.DeletedAt, nil + return } -// ClearDeletedAt clears the value of the "deleted_at" field. -func (m *UserMutation) ClearDeletedAt() { - m.deleted_at = nil - m.clearedFields[user.FieldDeletedAt] = struct{}{} +// ResetSubscriptions resets all changes to the "subscriptions" edge. +func (m *UserMutation) ResetSubscriptions() { + m.subscriptions = nil + m.clearedsubscriptions = false + m.removedsubscriptions = nil } -// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. -func (m *UserMutation) DeletedAtCleared() bool { - _, ok := m.clearedFields[user.FieldDeletedAt] - return ok +// AddAssignedSubscriptionIDs adds the "assigned_subscriptions" edge to the UserSubscription entity by ids. +func (m *UserMutation) AddAssignedSubscriptionIDs(ids ...int64) { + if m.assigned_subscriptions == nil { + m.assigned_subscriptions = make(map[int64]struct{}) + } + for i := range ids { + m.assigned_subscriptions[ids[i]] = struct{}{} + } } -// ResetDeletedAt resets all changes to the "deleted_at" field. -func (m *UserMutation) ResetDeletedAt() { - m.deleted_at = nil - delete(m.clearedFields, user.FieldDeletedAt) +// ClearAssignedSubscriptions clears the "assigned_subscriptions" edge to the UserSubscription entity. +func (m *UserMutation) ClearAssignedSubscriptions() { + m.clearedassigned_subscriptions = true } -// SetEmail sets the "email" field. -func (m *UserMutation) SetEmail(s string) { - m.email = &s +// AssignedSubscriptionsCleared reports if the "assigned_subscriptions" edge to the UserSubscription entity was cleared. +func (m *UserMutation) AssignedSubscriptionsCleared() bool { + return m.clearedassigned_subscriptions } -// Email returns the value of the "email" field in the mutation. -func (m *UserMutation) Email() (r string, exists bool) { - v := m.email - if v == nil { - return +// RemoveAssignedSubscriptionIDs removes the "assigned_subscriptions" edge to the UserSubscription entity by IDs. +func (m *UserMutation) RemoveAssignedSubscriptionIDs(ids ...int64) { + if m.removedassigned_subscriptions == nil { + m.removedassigned_subscriptions = make(map[int64]struct{}) + } + for i := range ids { + delete(m.assigned_subscriptions, ids[i]) + m.removedassigned_subscriptions[ids[i]] = struct{}{} } - return *v, true } -// OldEmail returns the old "email" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserMutation) OldEmail(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldEmail is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldEmail requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldEmail: %w", err) +// RemovedAssignedSubscriptions returns the removed IDs of the "assigned_subscriptions" edge to the UserSubscription entity. +func (m *UserMutation) RemovedAssignedSubscriptionsIDs() (ids []int64) { + for id := range m.removedassigned_subscriptions { + ids = append(ids, id) } - return oldValue.Email, nil + return } -// ResetEmail resets all changes to the "email" field. -func (m *UserMutation) ResetEmail() { - m.email = nil +// AssignedSubscriptionsIDs returns the "assigned_subscriptions" edge IDs in the mutation. +func (m *UserMutation) AssignedSubscriptionsIDs() (ids []int64) { + for id := range m.assigned_subscriptions { + ids = append(ids, id) + } + return } -// SetPasswordHash sets the "password_hash" field. -func (m *UserMutation) SetPasswordHash(s string) { - m.password_hash = &s +// ResetAssignedSubscriptions resets all changes to the "assigned_subscriptions" edge. +func (m *UserMutation) ResetAssignedSubscriptions() { + m.assigned_subscriptions = nil + m.clearedassigned_subscriptions = false + m.removedassigned_subscriptions = nil } -// PasswordHash returns the value of the "password_hash" field in the mutation. -func (m *UserMutation) PasswordHash() (r string, exists bool) { - v := m.password_hash - if v == nil { - return +// AddAnnouncementReadIDs adds the "announcement_reads" edge to the AnnouncementRead entity by ids. +func (m *UserMutation) AddAnnouncementReadIDs(ids ...int64) { + if m.announcement_reads == nil { + m.announcement_reads = make(map[int64]struct{}) + } + for i := range ids { + m.announcement_reads[ids[i]] = struct{}{} } - return *v, true } -// OldPasswordHash returns the old "password_hash" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserMutation) OldPasswordHash(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldPasswordHash is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldPasswordHash requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldPasswordHash: %w", err) - } - return oldValue.PasswordHash, nil +// ClearAnnouncementReads clears the "announcement_reads" edge to the AnnouncementRead entity. +func (m *UserMutation) ClearAnnouncementReads() { + m.clearedannouncement_reads = true } -// ResetPasswordHash resets all changes to the "password_hash" field. -func (m *UserMutation) ResetPasswordHash() { - m.password_hash = nil +// AnnouncementReadsCleared reports if the "announcement_reads" edge to the AnnouncementRead entity was cleared. +func (m *UserMutation) AnnouncementReadsCleared() bool { + return m.clearedannouncement_reads } -// SetRole sets the "role" field. -func (m *UserMutation) SetRole(s string) { - m.role = &s +// RemoveAnnouncementReadIDs removes the "announcement_reads" edge to the AnnouncementRead entity by IDs. +func (m *UserMutation) RemoveAnnouncementReadIDs(ids ...int64) { + if m.removedannouncement_reads == nil { + m.removedannouncement_reads = make(map[int64]struct{}) + } + for i := range ids { + delete(m.announcement_reads, ids[i]) + m.removedannouncement_reads[ids[i]] = struct{}{} + } } -// Role returns the value of the "role" field in the mutation. -func (m *UserMutation) Role() (r string, exists bool) { - v := m.role - if v == nil { - return +// RemovedAnnouncementReads returns the removed IDs of the "announcement_reads" edge to the AnnouncementRead entity. +func (m *UserMutation) RemovedAnnouncementReadsIDs() (ids []int64) { + for id := range m.removedannouncement_reads { + ids = append(ids, id) } - return *v, true + return } -// OldRole returns the old "role" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserMutation) OldRole(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldRole is only allowed on UpdateOne operations") +// AnnouncementReadsIDs returns the "announcement_reads" edge IDs in the mutation. +func (m *UserMutation) AnnouncementReadsIDs() (ids []int64) { + for id := range m.announcement_reads { + ids = append(ids, id) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldRole requires an ID field in the mutation") + return +} + +// ResetAnnouncementReads resets all changes to the "announcement_reads" edge. +func (m *UserMutation) ResetAnnouncementReads() { + m.announcement_reads = nil + m.clearedannouncement_reads = false + m.removedannouncement_reads = nil +} + +// AddAllowedGroupIDs adds the "allowed_groups" edge to the Group entity by ids. +func (m *UserMutation) AddAllowedGroupIDs(ids ...int64) { + if m.allowed_groups == nil { + m.allowed_groups = make(map[int64]struct{}) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldRole: %w", err) + for i := range ids { + m.allowed_groups[ids[i]] = struct{}{} } - return oldValue.Role, nil } -// ResetRole resets all changes to the "role" field. -func (m *UserMutation) ResetRole() { - m.role = nil +// ClearAllowedGroups clears the "allowed_groups" edge to the Group entity. +func (m *UserMutation) ClearAllowedGroups() { + m.clearedallowed_groups = true } -// SetBalance sets the "balance" field. -func (m *UserMutation) SetBalance(f float64) { - m.balance = &f - m.addbalance = nil +// AllowedGroupsCleared reports if the "allowed_groups" edge to the Group entity was cleared. +func (m *UserMutation) AllowedGroupsCleared() bool { + return m.clearedallowed_groups } -// Balance returns the value of the "balance" field in the mutation. -func (m *UserMutation) Balance() (r float64, exists bool) { - v := m.balance - if v == nil { - return +// RemoveAllowedGroupIDs removes the "allowed_groups" edge to the Group entity by IDs. +func (m *UserMutation) RemoveAllowedGroupIDs(ids ...int64) { + if m.removedallowed_groups == nil { + m.removedallowed_groups = make(map[int64]struct{}) + } + for i := range ids { + delete(m.allowed_groups, ids[i]) + m.removedallowed_groups[ids[i]] = struct{}{} } - return *v, true } -// OldBalance returns the old "balance" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserMutation) OldBalance(ctx context.Context) (v float64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldBalance is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldBalance requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldBalance: %w", err) +// RemovedAllowedGroups returns the removed IDs of the "allowed_groups" edge to the Group entity. +func (m *UserMutation) RemovedAllowedGroupsIDs() (ids []int64) { + for id := range m.removedallowed_groups { + ids = append(ids, id) } - return oldValue.Balance, nil + return } -// AddBalance adds f to the "balance" field. -func (m *UserMutation) AddBalance(f float64) { - if m.addbalance != nil { - *m.addbalance += f - } else { - m.addbalance = &f +// AllowedGroupsIDs returns the "allowed_groups" edge IDs in the mutation. +func (m *UserMutation) AllowedGroupsIDs() (ids []int64) { + for id := range m.allowed_groups { + ids = append(ids, id) } + return } -// AddedBalance returns the value that was added to the "balance" field in this mutation. -func (m *UserMutation) AddedBalance() (r float64, exists bool) { - v := m.addbalance - if v == nil { - return +// ResetAllowedGroups resets all changes to the "allowed_groups" edge. +func (m *UserMutation) ResetAllowedGroups() { + m.allowed_groups = nil + m.clearedallowed_groups = false + m.removedallowed_groups = nil +} + +// AddUsageLogIDs adds the "usage_logs" edge to the UsageLog entity by ids. +func (m *UserMutation) AddUsageLogIDs(ids ...int64) { + if m.usage_logs == nil { + m.usage_logs = make(map[int64]struct{}) + } + for i := range ids { + m.usage_logs[ids[i]] = struct{}{} } - return *v, true } -// ResetBalance resets all changes to the "balance" field. -func (m *UserMutation) ResetBalance() { - m.balance = nil - m.addbalance = nil +// ClearUsageLogs clears the "usage_logs" edge to the UsageLog entity. +func (m *UserMutation) ClearUsageLogs() { + m.clearedusage_logs = true } -// SetConcurrency sets the "concurrency" field. -func (m *UserMutation) SetConcurrency(i int) { - m.concurrency = &i - m.addconcurrency = nil +// UsageLogsCleared reports if the "usage_logs" edge to the UsageLog entity was cleared. +func (m *UserMutation) UsageLogsCleared() bool { + return m.clearedusage_logs } -// Concurrency returns the value of the "concurrency" field in the mutation. -func (m *UserMutation) Concurrency() (r int, exists bool) { - v := m.concurrency - if v == nil { - return +// RemoveUsageLogIDs removes the "usage_logs" edge to the UsageLog entity by IDs. +func (m *UserMutation) RemoveUsageLogIDs(ids ...int64) { + if m.removedusage_logs == nil { + m.removedusage_logs = make(map[int64]struct{}) + } + for i := range ids { + delete(m.usage_logs, ids[i]) + m.removedusage_logs[ids[i]] = struct{}{} } - return *v, true } -// OldConcurrency returns the old "concurrency" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserMutation) OldConcurrency(ctx context.Context) (v int, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldConcurrency is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldConcurrency requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldConcurrency: %w", err) +// RemovedUsageLogs returns the removed IDs of the "usage_logs" edge to the UsageLog entity. +func (m *UserMutation) RemovedUsageLogsIDs() (ids []int64) { + for id := range m.removedusage_logs { + ids = append(ids, id) } - return oldValue.Concurrency, nil + return } -// AddConcurrency adds i to the "concurrency" field. -func (m *UserMutation) AddConcurrency(i int) { - if m.addconcurrency != nil { - *m.addconcurrency += i - } else { - m.addconcurrency = &i +// UsageLogsIDs returns the "usage_logs" edge IDs in the mutation. +func (m *UserMutation) UsageLogsIDs() (ids []int64) { + for id := range m.usage_logs { + ids = append(ids, id) } + return } -// AddedConcurrency returns the value that was added to the "concurrency" field in this mutation. -func (m *UserMutation) AddedConcurrency() (r int, exists bool) { - v := m.addconcurrency - if v == nil { - return - } - return *v, true +// ResetUsageLogs resets all changes to the "usage_logs" edge. +func (m *UserMutation) ResetUsageLogs() { + m.usage_logs = nil + m.clearedusage_logs = false + m.removedusage_logs = nil } -// ResetConcurrency resets all changes to the "concurrency" field. -func (m *UserMutation) ResetConcurrency() { - m.concurrency = nil - m.addconcurrency = nil +// AddAttributeValueIDs adds the "attribute_values" edge to the UserAttributeValue entity by ids. +func (m *UserMutation) AddAttributeValueIDs(ids ...int64) { + if m.attribute_values == nil { + m.attribute_values = make(map[int64]struct{}) + } + for i := range ids { + m.attribute_values[ids[i]] = struct{}{} + } } -// SetStatus sets the "status" field. -func (m *UserMutation) SetStatus(s string) { - m.status = &s +// ClearAttributeValues clears the "attribute_values" edge to the UserAttributeValue entity. +func (m *UserMutation) ClearAttributeValues() { + m.clearedattribute_values = true } -// Status returns the value of the "status" field in the mutation. -func (m *UserMutation) Status() (r string, exists bool) { - v := m.status - if v == nil { - return - } - return *v, true +// AttributeValuesCleared reports if the "attribute_values" edge to the UserAttributeValue entity was cleared. +func (m *UserMutation) AttributeValuesCleared() bool { + return m.clearedattribute_values } -// OldStatus returns the old "status" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserMutation) OldStatus(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldStatus is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldStatus requires an ID field in the mutation") +// RemoveAttributeValueIDs removes the "attribute_values" edge to the UserAttributeValue entity by IDs. +func (m *UserMutation) RemoveAttributeValueIDs(ids ...int64) { + if m.removedattribute_values == nil { + m.removedattribute_values = make(map[int64]struct{}) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldStatus: %w", err) + for i := range ids { + delete(m.attribute_values, ids[i]) + m.removedattribute_values[ids[i]] = struct{}{} } - return oldValue.Status, nil } -// ResetStatus resets all changes to the "status" field. -func (m *UserMutation) ResetStatus() { - m.status = nil +// RemovedAttributeValues returns the removed IDs of the "attribute_values" edge to the UserAttributeValue entity. +func (m *UserMutation) RemovedAttributeValuesIDs() (ids []int64) { + for id := range m.removedattribute_values { + ids = append(ids, id) + } + return } -// SetUsername sets the "username" field. -func (m *UserMutation) SetUsername(s string) { - m.username = &s +// AttributeValuesIDs returns the "attribute_values" edge IDs in the mutation. +func (m *UserMutation) AttributeValuesIDs() (ids []int64) { + for id := range m.attribute_values { + ids = append(ids, id) + } + return } -// Username returns the value of the "username" field in the mutation. -func (m *UserMutation) Username() (r string, exists bool) { - v := m.username - if v == nil { - return - } - return *v, true +// ResetAttributeValues resets all changes to the "attribute_values" edge. +func (m *UserMutation) ResetAttributeValues() { + m.attribute_values = nil + m.clearedattribute_values = false + m.removedattribute_values = nil } -// OldUsername returns the old "username" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserMutation) OldUsername(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUsername is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUsername requires an ID field in the mutation") +// AddPromoCodeUsageIDs adds the "promo_code_usages" edge to the PromoCodeUsage entity by ids. +func (m *UserMutation) AddPromoCodeUsageIDs(ids ...int64) { + if m.promo_code_usages == nil { + m.promo_code_usages = make(map[int64]struct{}) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldUsername: %w", err) + for i := range ids { + m.promo_code_usages[ids[i]] = struct{}{} } - return oldValue.Username, nil } -// ResetUsername resets all changes to the "username" field. -func (m *UserMutation) ResetUsername() { - m.username = nil +// ClearPromoCodeUsages clears the "promo_code_usages" edge to the PromoCodeUsage entity. +func (m *UserMutation) ClearPromoCodeUsages() { + m.clearedpromo_code_usages = true } -// SetNotes sets the "notes" field. -func (m *UserMutation) SetNotes(s string) { - m.notes = &s +// PromoCodeUsagesCleared reports if the "promo_code_usages" edge to the PromoCodeUsage entity was cleared. +func (m *UserMutation) PromoCodeUsagesCleared() bool { + return m.clearedpromo_code_usages } -// Notes returns the value of the "notes" field in the mutation. -func (m *UserMutation) Notes() (r string, exists bool) { - v := m.notes - if v == nil { - return +// RemovePromoCodeUsageIDs removes the "promo_code_usages" edge to the PromoCodeUsage entity by IDs. +func (m *UserMutation) RemovePromoCodeUsageIDs(ids ...int64) { + if m.removedpromo_code_usages == nil { + m.removedpromo_code_usages = make(map[int64]struct{}) + } + for i := range ids { + delete(m.promo_code_usages, ids[i]) + m.removedpromo_code_usages[ids[i]] = struct{}{} } - return *v, true } -// OldNotes returns the old "notes" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserMutation) OldNotes(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldNotes is only allowed on UpdateOne operations") +// RemovedPromoCodeUsages returns the removed IDs of the "promo_code_usages" edge to the PromoCodeUsage entity. +func (m *UserMutation) RemovedPromoCodeUsagesIDs() (ids []int64) { + for id := range m.removedpromo_code_usages { + ids = append(ids, id) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldNotes requires an ID field in the mutation") + return +} + +// PromoCodeUsagesIDs returns the "promo_code_usages" edge IDs in the mutation. +func (m *UserMutation) PromoCodeUsagesIDs() (ids []int64) { + for id := range m.promo_code_usages { + ids = append(ids, id) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldNotes: %w", err) + return +} + +// ResetPromoCodeUsages resets all changes to the "promo_code_usages" edge. +func (m *UserMutation) ResetPromoCodeUsages() { + m.promo_code_usages = nil + m.clearedpromo_code_usages = false + m.removedpromo_code_usages = nil +} + +// AddReferralProfileIDs adds the "referral_profile" edge to the UserReferralProfile entity by ids. +func (m *UserMutation) AddReferralProfileIDs(ids ...int64) { + if m.referral_profile == nil { + m.referral_profile = make(map[int64]struct{}) + } + for i := range ids { + m.referral_profile[ids[i]] = struct{}{} } - return oldValue.Notes, nil } -// ResetNotes resets all changes to the "notes" field. -func (m *UserMutation) ResetNotes() { - m.notes = nil +// ClearReferralProfile clears the "referral_profile" edge to the UserReferralProfile entity. +func (m *UserMutation) ClearReferralProfile() { + m.clearedreferral_profile = true } -// SetTotpSecretEncrypted sets the "totp_secret_encrypted" field. -func (m *UserMutation) SetTotpSecretEncrypted(s string) { - m.totp_secret_encrypted = &s +// ReferralProfileCleared reports if the "referral_profile" edge to the UserReferralProfile entity was cleared. +func (m *UserMutation) ReferralProfileCleared() bool { + return m.clearedreferral_profile } -// TotpSecretEncrypted returns the value of the "totp_secret_encrypted" field in the mutation. -func (m *UserMutation) TotpSecretEncrypted() (r string, exists bool) { - v := m.totp_secret_encrypted - if v == nil { - return +// RemoveReferralProfileIDs removes the "referral_profile" edge to the UserReferralProfile entity by IDs. +func (m *UserMutation) RemoveReferralProfileIDs(ids ...int64) { + if m.removedreferral_profile == nil { + m.removedreferral_profile = make(map[int64]struct{}) + } + for i := range ids { + delete(m.referral_profile, ids[i]) + m.removedreferral_profile[ids[i]] = struct{}{} } - return *v, true } -// OldTotpSecretEncrypted returns the old "totp_secret_encrypted" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserMutation) OldTotpSecretEncrypted(ctx context.Context) (v *string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldTotpSecretEncrypted is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldTotpSecretEncrypted requires an ID field in the mutation") +// RemovedReferralProfile returns the removed IDs of the "referral_profile" edge to the UserReferralProfile entity. +func (m *UserMutation) RemovedReferralProfileIDs() (ids []int64) { + for id := range m.removedreferral_profile { + ids = append(ids, id) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldTotpSecretEncrypted: %w", err) + return +} + +// ReferralProfileIDs returns the "referral_profile" edge IDs in the mutation. +func (m *UserMutation) ReferralProfileIDs() (ids []int64) { + for id := range m.referral_profile { + ids = append(ids, id) } - return oldValue.TotpSecretEncrypted, nil + return } -// ClearTotpSecretEncrypted clears the value of the "totp_secret_encrypted" field. -func (m *UserMutation) ClearTotpSecretEncrypted() { - m.totp_secret_encrypted = nil - m.clearedFields[user.FieldTotpSecretEncrypted] = struct{}{} +// ResetReferralProfile resets all changes to the "referral_profile" edge. +func (m *UserMutation) ResetReferralProfile() { + m.referral_profile = nil + m.clearedreferral_profile = false + m.removedreferral_profile = nil } -// TotpSecretEncryptedCleared returns if the "totp_secret_encrypted" field was cleared in this mutation. -func (m *UserMutation) TotpSecretEncryptedCleared() bool { - _, ok := m.clearedFields[user.FieldTotpSecretEncrypted] - return ok +// AddReferralsGivenIDs adds the "referrals_given" edge to the ReferralRelation entity by ids. +func (m *UserMutation) AddReferralsGivenIDs(ids ...int64) { + if m.referrals_given == nil { + m.referrals_given = make(map[int64]struct{}) + } + for i := range ids { + m.referrals_given[ids[i]] = struct{}{} + } } -// ResetTotpSecretEncrypted resets all changes to the "totp_secret_encrypted" field. -func (m *UserMutation) ResetTotpSecretEncrypted() { - m.totp_secret_encrypted = nil - delete(m.clearedFields, user.FieldTotpSecretEncrypted) +// ClearReferralsGiven clears the "referrals_given" edge to the ReferralRelation entity. +func (m *UserMutation) ClearReferralsGiven() { + m.clearedreferrals_given = true } -// SetTotpEnabled sets the "totp_enabled" field. -func (m *UserMutation) SetTotpEnabled(b bool) { - m.totp_enabled = &b +// ReferralsGivenCleared reports if the "referrals_given" edge to the ReferralRelation entity was cleared. +func (m *UserMutation) ReferralsGivenCleared() bool { + return m.clearedreferrals_given } -// TotpEnabled returns the value of the "totp_enabled" field in the mutation. -func (m *UserMutation) TotpEnabled() (r bool, exists bool) { - v := m.totp_enabled - if v == nil { - return +// RemoveReferralsGivenIDs removes the "referrals_given" edge to the ReferralRelation entity by IDs. +func (m *UserMutation) RemoveReferralsGivenIDs(ids ...int64) { + if m.removedreferrals_given == nil { + m.removedreferrals_given = make(map[int64]struct{}) + } + for i := range ids { + delete(m.referrals_given, ids[i]) + m.removedreferrals_given[ids[i]] = struct{}{} } - return *v, true } -// OldTotpEnabled returns the old "totp_enabled" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserMutation) OldTotpEnabled(ctx context.Context) (v bool, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldTotpEnabled is only allowed on UpdateOne operations") +// RemovedReferralsGiven returns the removed IDs of the "referrals_given" edge to the ReferralRelation entity. +func (m *UserMutation) RemovedReferralsGivenIDs() (ids []int64) { + for id := range m.removedreferrals_given { + ids = append(ids, id) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldTotpEnabled requires an ID field in the mutation") + return +} + +// ReferralsGivenIDs returns the "referrals_given" edge IDs in the mutation. +func (m *UserMutation) ReferralsGivenIDs() (ids []int64) { + for id := range m.referrals_given { + ids = append(ids, id) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldTotpEnabled: %w", err) + return +} + +// ResetReferralsGiven resets all changes to the "referrals_given" edge. +func (m *UserMutation) ResetReferralsGiven() { + m.referrals_given = nil + m.clearedreferrals_given = false + m.removedreferrals_given = nil +} + +// AddReferralReceivedIDs adds the "referral_received" edge to the ReferralRelation entity by ids. +func (m *UserMutation) AddReferralReceivedIDs(ids ...int64) { + if m.referral_received == nil { + m.referral_received = make(map[int64]struct{}) + } + for i := range ids { + m.referral_received[ids[i]] = struct{}{} } - return oldValue.TotpEnabled, nil } -// ResetTotpEnabled resets all changes to the "totp_enabled" field. -func (m *UserMutation) ResetTotpEnabled() { - m.totp_enabled = nil +// ClearReferralReceived clears the "referral_received" edge to the ReferralRelation entity. +func (m *UserMutation) ClearReferralReceived() { + m.clearedreferral_received = true } -// SetTotpEnabledAt sets the "totp_enabled_at" field. -func (m *UserMutation) SetTotpEnabledAt(t time.Time) { - m.totp_enabled_at = &t +// ReferralReceivedCleared reports if the "referral_received" edge to the ReferralRelation entity was cleared. +func (m *UserMutation) ReferralReceivedCleared() bool { + return m.clearedreferral_received } -// TotpEnabledAt returns the value of the "totp_enabled_at" field in the mutation. -func (m *UserMutation) TotpEnabledAt() (r time.Time, exists bool) { - v := m.totp_enabled_at - if v == nil { - return +// RemoveReferralReceivedIDs removes the "referral_received" edge to the ReferralRelation entity by IDs. +func (m *UserMutation) RemoveReferralReceivedIDs(ids ...int64) { + if m.removedreferral_received == nil { + m.removedreferral_received = make(map[int64]struct{}) + } + for i := range ids { + delete(m.referral_received, ids[i]) + m.removedreferral_received[ids[i]] = struct{}{} } - return *v, true } -// OldTotpEnabledAt returns the old "totp_enabled_at" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserMutation) OldTotpEnabledAt(ctx context.Context) (v *time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldTotpEnabledAt is only allowed on UpdateOne operations") +// RemovedReferralReceived returns the removed IDs of the "referral_received" edge to the ReferralRelation entity. +func (m *UserMutation) RemovedReferralReceivedIDs() (ids []int64) { + for id := range m.removedreferral_received { + ids = append(ids, id) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldTotpEnabledAt requires an ID field in the mutation") + return +} + +// ReferralReceivedIDs returns the "referral_received" edge IDs in the mutation. +func (m *UserMutation) ReferralReceivedIDs() (ids []int64) { + for id := range m.referral_received { + ids = append(ids, id) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldTotpEnabledAt: %w", err) + return +} + +// ResetReferralReceived resets all changes to the "referral_received" edge. +func (m *UserMutation) ResetReferralReceived() { + m.referral_received = nil + m.clearedreferral_received = false + m.removedreferral_received = nil +} + +// Where appends a list predicates to the UserMutation builder. +func (m *UserMutation) Where(ps ...predicate.User) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the UserMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *UserMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.User, len(ps)) + for i := range ps { + p[i] = ps[i] } - return oldValue.TotpEnabledAt, nil + m.Where(p...) } -// ClearTotpEnabledAt clears the value of the "totp_enabled_at" field. -func (m *UserMutation) ClearTotpEnabledAt() { - m.totp_enabled_at = nil - m.clearedFields[user.FieldTotpEnabledAt] = struct{}{} +// Op returns the operation name. +func (m *UserMutation) Op() Op { + return m.op } -// TotpEnabledAtCleared returns if the "totp_enabled_at" field was cleared in this mutation. -func (m *UserMutation) TotpEnabledAtCleared() bool { - _, ok := m.clearedFields[user.FieldTotpEnabledAt] - return ok +// SetOp allows setting the mutation operation. +func (m *UserMutation) SetOp(op Op) { + m.op = op } -// ResetTotpEnabledAt resets all changes to the "totp_enabled_at" field. -func (m *UserMutation) ResetTotpEnabledAt() { - m.totp_enabled_at = nil - delete(m.clearedFields, user.FieldTotpEnabledAt) +// Type returns the node type of this mutation (User). +func (m *UserMutation) Type() string { + return m.typ } -// SetSoraStorageQuotaBytes sets the "sora_storage_quota_bytes" field. -func (m *UserMutation) SetSoraStorageQuotaBytes(i int64) { - m.sora_storage_quota_bytes = &i - m.addsora_storage_quota_bytes = nil +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *UserMutation) Fields() []string { + fields := make([]string, 0, 16) + if m.created_at != nil { + fields = append(fields, user.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, user.FieldUpdatedAt) + } + if m.deleted_at != nil { + fields = append(fields, user.FieldDeletedAt) + } + if m.email != nil { + fields = append(fields, user.FieldEmail) + } + if m.password_hash != nil { + fields = append(fields, user.FieldPasswordHash) + } + if m.role != nil { + fields = append(fields, user.FieldRole) + } + if m.balance != nil { + fields = append(fields, user.FieldBalance) + } + if m.concurrency != nil { + fields = append(fields, user.FieldConcurrency) + } + if m.status != nil { + fields = append(fields, user.FieldStatus) + } + if m.username != nil { + fields = append(fields, user.FieldUsername) + } + if m.notes != nil { + fields = append(fields, user.FieldNotes) + } + if m.totp_secret_encrypted != nil { + fields = append(fields, user.FieldTotpSecretEncrypted) + } + if m.totp_enabled != nil { + fields = append(fields, user.FieldTotpEnabled) + } + if m.totp_enabled_at != nil { + fields = append(fields, user.FieldTotpEnabledAt) + } + if m.sora_storage_quota_bytes != nil { + fields = append(fields, user.FieldSoraStorageQuotaBytes) + } + if m.sora_storage_used_bytes != nil { + fields = append(fields, user.FieldSoraStorageUsedBytes) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *UserMutation) Field(name string) (ent.Value, bool) { + switch name { + case user.FieldCreatedAt: + return m.CreatedAt() + case user.FieldUpdatedAt: + return m.UpdatedAt() + case user.FieldDeletedAt: + return m.DeletedAt() + case user.FieldEmail: + return m.Email() + case user.FieldPasswordHash: + return m.PasswordHash() + case user.FieldRole: + return m.Role() + case user.FieldBalance: + return m.Balance() + case user.FieldConcurrency: + return m.Concurrency() + case user.FieldStatus: + return m.Status() + case user.FieldUsername: + return m.Username() + case user.FieldNotes: + return m.Notes() + case user.FieldTotpSecretEncrypted: + return m.TotpSecretEncrypted() + case user.FieldTotpEnabled: + return m.TotpEnabled() + case user.FieldTotpEnabledAt: + return m.TotpEnabledAt() + case user.FieldSoraStorageQuotaBytes: + return m.SoraStorageQuotaBytes() + case user.FieldSoraStorageUsedBytes: + return m.SoraStorageUsedBytes() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *UserMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case user.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case user.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case user.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case user.FieldEmail: + return m.OldEmail(ctx) + case user.FieldPasswordHash: + return m.OldPasswordHash(ctx) + case user.FieldRole: + return m.OldRole(ctx) + case user.FieldBalance: + return m.OldBalance(ctx) + case user.FieldConcurrency: + return m.OldConcurrency(ctx) + case user.FieldStatus: + return m.OldStatus(ctx) + case user.FieldUsername: + return m.OldUsername(ctx) + case user.FieldNotes: + return m.OldNotes(ctx) + case user.FieldTotpSecretEncrypted: + return m.OldTotpSecretEncrypted(ctx) + case user.FieldTotpEnabled: + return m.OldTotpEnabled(ctx) + case user.FieldTotpEnabledAt: + return m.OldTotpEnabledAt(ctx) + case user.FieldSoraStorageQuotaBytes: + return m.OldSoraStorageQuotaBytes(ctx) + case user.FieldSoraStorageUsedBytes: + return m.OldSoraStorageUsedBytes(ctx) + } + return nil, fmt.Errorf("unknown User field %s", name) } -// SoraStorageQuotaBytes returns the value of the "sora_storage_quota_bytes" field in the mutation. -func (m *UserMutation) SoraStorageQuotaBytes() (r int64, exists bool) { - v := m.sora_storage_quota_bytes - if v == nil { - return +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *UserMutation) SetField(name string, value ent.Value) error { + switch name { + case user.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case user.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + case user.FieldDeletedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeletedAt(v) + return nil + case user.FieldEmail: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEmail(v) + return nil + case user.FieldPasswordHash: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPasswordHash(v) + return nil + case user.FieldRole: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRole(v) + return nil + case user.FieldBalance: + v, ok := value.(float64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBalance(v) + return nil + case user.FieldConcurrency: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetConcurrency(v) + return nil + case user.FieldStatus: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatus(v) + return nil + case user.FieldUsername: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUsername(v) + return nil + case user.FieldNotes: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNotes(v) + return nil + case user.FieldTotpSecretEncrypted: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTotpSecretEncrypted(v) + return nil + case user.FieldTotpEnabled: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTotpEnabled(v) + return nil + case user.FieldTotpEnabledAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTotpEnabledAt(v) + return nil + case user.FieldSoraStorageQuotaBytes: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSoraStorageQuotaBytes(v) + return nil + case user.FieldSoraStorageUsedBytes: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSoraStorageUsedBytes(v) + return nil } - return *v, true + return fmt.Errorf("unknown User field %s", name) } -// OldSoraStorageQuotaBytes returns the old "sora_storage_quota_bytes" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserMutation) OldSoraStorageQuotaBytes(ctx context.Context) (v int64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldSoraStorageQuotaBytes is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldSoraStorageQuotaBytes requires an ID field in the mutation") +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *UserMutation) AddedFields() []string { + var fields []string + if m.addbalance != nil { + fields = append(fields, user.FieldBalance) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldSoraStorageQuotaBytes: %w", err) + if m.addconcurrency != nil { + fields = append(fields, user.FieldConcurrency) } - return oldValue.SoraStorageQuotaBytes, nil -} - -// AddSoraStorageQuotaBytes adds i to the "sora_storage_quota_bytes" field. -func (m *UserMutation) AddSoraStorageQuotaBytes(i int64) { if m.addsora_storage_quota_bytes != nil { - *m.addsora_storage_quota_bytes += i - } else { - m.addsora_storage_quota_bytes = &i - } -} - -// AddedSoraStorageQuotaBytes returns the value that was added to the "sora_storage_quota_bytes" field in this mutation. -func (m *UserMutation) AddedSoraStorageQuotaBytes() (r int64, exists bool) { - v := m.addsora_storage_quota_bytes - if v == nil { - return + fields = append(fields, user.FieldSoraStorageQuotaBytes) } - return *v, true -} - -// ResetSoraStorageQuotaBytes resets all changes to the "sora_storage_quota_bytes" field. -func (m *UserMutation) ResetSoraStorageQuotaBytes() { - m.sora_storage_quota_bytes = nil - m.addsora_storage_quota_bytes = nil -} - -// SetSoraStorageUsedBytes sets the "sora_storage_used_bytes" field. -func (m *UserMutation) SetSoraStorageUsedBytes(i int64) { - m.sora_storage_used_bytes = &i - m.addsora_storage_used_bytes = nil -} - -// SoraStorageUsedBytes returns the value of the "sora_storage_used_bytes" field in the mutation. -func (m *UserMutation) SoraStorageUsedBytes() (r int64, exists bool) { - v := m.sora_storage_used_bytes - if v == nil { - return + if m.addsora_storage_used_bytes != nil { + fields = append(fields, user.FieldSoraStorageUsedBytes) } - return *v, true + return fields } -// OldSoraStorageUsedBytes returns the old "sora_storage_used_bytes" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserMutation) OldSoraStorageUsedBytes(ctx context.Context) (v int64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldSoraStorageUsedBytes is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldSoraStorageUsedBytes requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldSoraStorageUsedBytes: %w", err) +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *UserMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case user.FieldBalance: + return m.AddedBalance() + case user.FieldConcurrency: + return m.AddedConcurrency() + case user.FieldSoraStorageQuotaBytes: + return m.AddedSoraStorageQuotaBytes() + case user.FieldSoraStorageUsedBytes: + return m.AddedSoraStorageUsedBytes() } - return oldValue.SoraStorageUsedBytes, nil + return nil, false } -// AddSoraStorageUsedBytes adds i to the "sora_storage_used_bytes" field. -func (m *UserMutation) AddSoraStorageUsedBytes(i int64) { - if m.addsora_storage_used_bytes != nil { - *m.addsora_storage_used_bytes += i - } else { - m.addsora_storage_used_bytes = &i +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *UserMutation) AddField(name string, value ent.Value) error { + switch name { + case user.FieldBalance: + v, ok := value.(float64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddBalance(v) + return nil + case user.FieldConcurrency: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddConcurrency(v) + return nil + case user.FieldSoraStorageQuotaBytes: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddSoraStorageQuotaBytes(v) + return nil + case user.FieldSoraStorageUsedBytes: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddSoraStorageUsedBytes(v) + return nil } + return fmt.Errorf("unknown User numeric field %s", name) } -// AddedSoraStorageUsedBytes returns the value that was added to the "sora_storage_used_bytes" field in this mutation. -func (m *UserMutation) AddedSoraStorageUsedBytes() (r int64, exists bool) { - v := m.addsora_storage_used_bytes - if v == nil { - return +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *UserMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(user.FieldDeletedAt) { + fields = append(fields, user.FieldDeletedAt) } - return *v, true -} - -// ResetSoraStorageUsedBytes resets all changes to the "sora_storage_used_bytes" field. -func (m *UserMutation) ResetSoraStorageUsedBytes() { - m.sora_storage_used_bytes = nil - m.addsora_storage_used_bytes = nil -} - -// AddAPIKeyIDs adds the "api_keys" edge to the APIKey entity by ids. -func (m *UserMutation) AddAPIKeyIDs(ids ...int64) { - if m.api_keys == nil { - m.api_keys = make(map[int64]struct{}) + if m.FieldCleared(user.FieldTotpSecretEncrypted) { + fields = append(fields, user.FieldTotpSecretEncrypted) } - for i := range ids { - m.api_keys[ids[i]] = struct{}{} + if m.FieldCleared(user.FieldTotpEnabledAt) { + fields = append(fields, user.FieldTotpEnabledAt) } + return fields } -// ClearAPIKeys clears the "api_keys" edge to the APIKey entity. -func (m *UserMutation) ClearAPIKeys() { - m.clearedapi_keys = true -} - -// APIKeysCleared reports if the "api_keys" edge to the APIKey entity was cleared. -func (m *UserMutation) APIKeysCleared() bool { - return m.clearedapi_keys +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *UserMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok } -// RemoveAPIKeyIDs removes the "api_keys" edge to the APIKey entity by IDs. -func (m *UserMutation) RemoveAPIKeyIDs(ids ...int64) { - if m.removedapi_keys == nil { - m.removedapi_keys = make(map[int64]struct{}) - } - for i := range ids { - delete(m.api_keys, ids[i]) - m.removedapi_keys[ids[i]] = struct{}{} +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *UserMutation) ClearField(name string) error { + switch name { + case user.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case user.FieldTotpSecretEncrypted: + m.ClearTotpSecretEncrypted() + return nil + case user.FieldTotpEnabledAt: + m.ClearTotpEnabledAt() + return nil } + return fmt.Errorf("unknown User nullable field %s", name) } -// RemovedAPIKeys returns the removed IDs of the "api_keys" edge to the APIKey entity. -func (m *UserMutation) RemovedAPIKeysIDs() (ids []int64) { - for id := range m.removedapi_keys { - ids = append(ids, id) +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *UserMutation) ResetField(name string) error { + switch name { + case user.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case user.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case user.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case user.FieldEmail: + m.ResetEmail() + return nil + case user.FieldPasswordHash: + m.ResetPasswordHash() + return nil + case user.FieldRole: + m.ResetRole() + return nil + case user.FieldBalance: + m.ResetBalance() + return nil + case user.FieldConcurrency: + m.ResetConcurrency() + return nil + case user.FieldStatus: + m.ResetStatus() + return nil + case user.FieldUsername: + m.ResetUsername() + return nil + case user.FieldNotes: + m.ResetNotes() + return nil + case user.FieldTotpSecretEncrypted: + m.ResetTotpSecretEncrypted() + return nil + case user.FieldTotpEnabled: + m.ResetTotpEnabled() + return nil + case user.FieldTotpEnabledAt: + m.ResetTotpEnabledAt() + return nil + case user.FieldSoraStorageQuotaBytes: + m.ResetSoraStorageQuotaBytes() + return nil + case user.FieldSoraStorageUsedBytes: + m.ResetSoraStorageUsedBytes() + return nil } - return + return fmt.Errorf("unknown User field %s", name) } -// APIKeysIDs returns the "api_keys" edge IDs in the mutation. -func (m *UserMutation) APIKeysIDs() (ids []int64) { - for id := range m.api_keys { - ids = append(ids, id) +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *UserMutation) AddedEdges() []string { + edges := make([]string, 0, 12) + if m.api_keys != nil { + edges = append(edges, user.EdgeAPIKeys) } - return -} - -// ResetAPIKeys resets all changes to the "api_keys" edge. -func (m *UserMutation) ResetAPIKeys() { - m.api_keys = nil - m.clearedapi_keys = false - m.removedapi_keys = nil -} - -// AddRedeemCodeIDs adds the "redeem_codes" edge to the RedeemCode entity by ids. -func (m *UserMutation) AddRedeemCodeIDs(ids ...int64) { - if m.redeem_codes == nil { - m.redeem_codes = make(map[int64]struct{}) + if m.redeem_codes != nil { + edges = append(edges, user.EdgeRedeemCodes) } - for i := range ids { - m.redeem_codes[ids[i]] = struct{}{} + if m.subscriptions != nil { + edges = append(edges, user.EdgeSubscriptions) } + if m.assigned_subscriptions != nil { + edges = append(edges, user.EdgeAssignedSubscriptions) + } + if m.announcement_reads != nil { + edges = append(edges, user.EdgeAnnouncementReads) + } + if m.allowed_groups != nil { + edges = append(edges, user.EdgeAllowedGroups) + } + if m.usage_logs != nil { + edges = append(edges, user.EdgeUsageLogs) + } + if m.attribute_values != nil { + edges = append(edges, user.EdgeAttributeValues) + } + if m.promo_code_usages != nil { + edges = append(edges, user.EdgePromoCodeUsages) + } + if m.referral_profile != nil { + edges = append(edges, user.EdgeReferralProfile) + } + if m.referrals_given != nil { + edges = append(edges, user.EdgeReferralsGiven) + } + if m.referral_received != nil { + edges = append(edges, user.EdgeReferralReceived) + } + return edges } -// ClearRedeemCodes clears the "redeem_codes" edge to the RedeemCode entity. -func (m *UserMutation) ClearRedeemCodes() { - m.clearedredeem_codes = true -} - -// RedeemCodesCleared reports if the "redeem_codes" edge to the RedeemCode entity was cleared. -func (m *UserMutation) RedeemCodesCleared() bool { - return m.clearedredeem_codes -} - -// RemoveRedeemCodeIDs removes the "redeem_codes" edge to the RedeemCode entity by IDs. -func (m *UserMutation) RemoveRedeemCodeIDs(ids ...int64) { - if m.removedredeem_codes == nil { - m.removedredeem_codes = make(map[int64]struct{}) - } - for i := range ids { - delete(m.redeem_codes, ids[i]) - m.removedredeem_codes[ids[i]] = struct{}{} +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *UserMutation) AddedIDs(name string) []ent.Value { + switch name { + case user.EdgeAPIKeys: + ids := make([]ent.Value, 0, len(m.api_keys)) + for id := range m.api_keys { + ids = append(ids, id) + } + return ids + case user.EdgeRedeemCodes: + ids := make([]ent.Value, 0, len(m.redeem_codes)) + for id := range m.redeem_codes { + ids = append(ids, id) + } + return ids + case user.EdgeSubscriptions: + ids := make([]ent.Value, 0, len(m.subscriptions)) + for id := range m.subscriptions { + ids = append(ids, id) + } + return ids + case user.EdgeAssignedSubscriptions: + ids := make([]ent.Value, 0, len(m.assigned_subscriptions)) + for id := range m.assigned_subscriptions { + ids = append(ids, id) + } + return ids + case user.EdgeAnnouncementReads: + ids := make([]ent.Value, 0, len(m.announcement_reads)) + for id := range m.announcement_reads { + ids = append(ids, id) + } + return ids + case user.EdgeAllowedGroups: + ids := make([]ent.Value, 0, len(m.allowed_groups)) + for id := range m.allowed_groups { + ids = append(ids, id) + } + return ids + case user.EdgeUsageLogs: + ids := make([]ent.Value, 0, len(m.usage_logs)) + for id := range m.usage_logs { + ids = append(ids, id) + } + return ids + case user.EdgeAttributeValues: + ids := make([]ent.Value, 0, len(m.attribute_values)) + for id := range m.attribute_values { + ids = append(ids, id) + } + return ids + case user.EdgePromoCodeUsages: + ids := make([]ent.Value, 0, len(m.promo_code_usages)) + for id := range m.promo_code_usages { + ids = append(ids, id) + } + return ids + case user.EdgeReferralProfile: + ids := make([]ent.Value, 0, len(m.referral_profile)) + for id := range m.referral_profile { + ids = append(ids, id) + } + return ids + case user.EdgeReferralsGiven: + ids := make([]ent.Value, 0, len(m.referrals_given)) + for id := range m.referrals_given { + ids = append(ids, id) + } + return ids + case user.EdgeReferralReceived: + ids := make([]ent.Value, 0, len(m.referral_received)) + for id := range m.referral_received { + ids = append(ids, id) + } + return ids } + return nil } -// RemovedRedeemCodes returns the removed IDs of the "redeem_codes" edge to the RedeemCode entity. -func (m *UserMutation) RemovedRedeemCodesIDs() (ids []int64) { - for id := range m.removedredeem_codes { - ids = append(ids, id) +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *UserMutation) RemovedEdges() []string { + edges := make([]string, 0, 12) + if m.removedapi_keys != nil { + edges = append(edges, user.EdgeAPIKeys) } - return -} - -// RedeemCodesIDs returns the "redeem_codes" edge IDs in the mutation. -func (m *UserMutation) RedeemCodesIDs() (ids []int64) { - for id := range m.redeem_codes { - ids = append(ids, id) + if m.removedredeem_codes != nil { + edges = append(edges, user.EdgeRedeemCodes) } - return -} - -// ResetRedeemCodes resets all changes to the "redeem_codes" edge. -func (m *UserMutation) ResetRedeemCodes() { - m.redeem_codes = nil - m.clearedredeem_codes = false - m.removedredeem_codes = nil -} - -// AddSubscriptionIDs adds the "subscriptions" edge to the UserSubscription entity by ids. -func (m *UserMutation) AddSubscriptionIDs(ids ...int64) { - if m.subscriptions == nil { - m.subscriptions = make(map[int64]struct{}) + if m.removedsubscriptions != nil { + edges = append(edges, user.EdgeSubscriptions) } - for i := range ids { - m.subscriptions[ids[i]] = struct{}{} + if m.removedassigned_subscriptions != nil { + edges = append(edges, user.EdgeAssignedSubscriptions) } -} - -// ClearSubscriptions clears the "subscriptions" edge to the UserSubscription entity. -func (m *UserMutation) ClearSubscriptions() { - m.clearedsubscriptions = true -} - -// SubscriptionsCleared reports if the "subscriptions" edge to the UserSubscription entity was cleared. -func (m *UserMutation) SubscriptionsCleared() bool { - return m.clearedsubscriptions -} - -// RemoveSubscriptionIDs removes the "subscriptions" edge to the UserSubscription entity by IDs. -func (m *UserMutation) RemoveSubscriptionIDs(ids ...int64) { - if m.removedsubscriptions == nil { - m.removedsubscriptions = make(map[int64]struct{}) + if m.removedannouncement_reads != nil { + edges = append(edges, user.EdgeAnnouncementReads) } - for i := range ids { - delete(m.subscriptions, ids[i]) - m.removedsubscriptions[ids[i]] = struct{}{} + if m.removedallowed_groups != nil { + edges = append(edges, user.EdgeAllowedGroups) } -} - -// RemovedSubscriptions returns the removed IDs of the "subscriptions" edge to the UserSubscription entity. -func (m *UserMutation) RemovedSubscriptionsIDs() (ids []int64) { - for id := range m.removedsubscriptions { - ids = append(ids, id) + if m.removedusage_logs != nil { + edges = append(edges, user.EdgeUsageLogs) } - return -} - -// SubscriptionsIDs returns the "subscriptions" edge IDs in the mutation. -func (m *UserMutation) SubscriptionsIDs() (ids []int64) { - for id := range m.subscriptions { - ids = append(ids, id) + if m.removedattribute_values != nil { + edges = append(edges, user.EdgeAttributeValues) } - return -} - -// ResetSubscriptions resets all changes to the "subscriptions" edge. -func (m *UserMutation) ResetSubscriptions() { - m.subscriptions = nil - m.clearedsubscriptions = false - m.removedsubscriptions = nil -} - -// AddAssignedSubscriptionIDs adds the "assigned_subscriptions" edge to the UserSubscription entity by ids. -func (m *UserMutation) AddAssignedSubscriptionIDs(ids ...int64) { - if m.assigned_subscriptions == nil { - m.assigned_subscriptions = make(map[int64]struct{}) + if m.removedpromo_code_usages != nil { + edges = append(edges, user.EdgePromoCodeUsages) } - for i := range ids { - m.assigned_subscriptions[ids[i]] = struct{}{} + if m.removedreferral_profile != nil { + edges = append(edges, user.EdgeReferralProfile) } -} - -// ClearAssignedSubscriptions clears the "assigned_subscriptions" edge to the UserSubscription entity. -func (m *UserMutation) ClearAssignedSubscriptions() { - m.clearedassigned_subscriptions = true -} - -// AssignedSubscriptionsCleared reports if the "assigned_subscriptions" edge to the UserSubscription entity was cleared. -func (m *UserMutation) AssignedSubscriptionsCleared() bool { - return m.clearedassigned_subscriptions -} - -// RemoveAssignedSubscriptionIDs removes the "assigned_subscriptions" edge to the UserSubscription entity by IDs. -func (m *UserMutation) RemoveAssignedSubscriptionIDs(ids ...int64) { - if m.removedassigned_subscriptions == nil { - m.removedassigned_subscriptions = make(map[int64]struct{}) + if m.removedreferrals_given != nil { + edges = append(edges, user.EdgeReferralsGiven) } - for i := range ids { - delete(m.assigned_subscriptions, ids[i]) - m.removedassigned_subscriptions[ids[i]] = struct{}{} + if m.removedreferral_received != nil { + edges = append(edges, user.EdgeReferralReceived) } + return edges } -// RemovedAssignedSubscriptions returns the removed IDs of the "assigned_subscriptions" edge to the UserSubscription entity. -func (m *UserMutation) RemovedAssignedSubscriptionsIDs() (ids []int64) { - for id := range m.removedassigned_subscriptions { - ids = append(ids, id) +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *UserMutation) RemovedIDs(name string) []ent.Value { + switch name { + case user.EdgeAPIKeys: + ids := make([]ent.Value, 0, len(m.removedapi_keys)) + for id := range m.removedapi_keys { + ids = append(ids, id) + } + return ids + case user.EdgeRedeemCodes: + ids := make([]ent.Value, 0, len(m.removedredeem_codes)) + for id := range m.removedredeem_codes { + ids = append(ids, id) + } + return ids + case user.EdgeSubscriptions: + ids := make([]ent.Value, 0, len(m.removedsubscriptions)) + for id := range m.removedsubscriptions { + ids = append(ids, id) + } + return ids + case user.EdgeAssignedSubscriptions: + ids := make([]ent.Value, 0, len(m.removedassigned_subscriptions)) + for id := range m.removedassigned_subscriptions { + ids = append(ids, id) + } + return ids + case user.EdgeAnnouncementReads: + ids := make([]ent.Value, 0, len(m.removedannouncement_reads)) + for id := range m.removedannouncement_reads { + ids = append(ids, id) + } + return ids + case user.EdgeAllowedGroups: + ids := make([]ent.Value, 0, len(m.removedallowed_groups)) + for id := range m.removedallowed_groups { + ids = append(ids, id) + } + return ids + case user.EdgeUsageLogs: + ids := make([]ent.Value, 0, len(m.removedusage_logs)) + for id := range m.removedusage_logs { + ids = append(ids, id) + } + return ids + case user.EdgeAttributeValues: + ids := make([]ent.Value, 0, len(m.removedattribute_values)) + for id := range m.removedattribute_values { + ids = append(ids, id) + } + return ids + case user.EdgePromoCodeUsages: + ids := make([]ent.Value, 0, len(m.removedpromo_code_usages)) + for id := range m.removedpromo_code_usages { + ids = append(ids, id) + } + return ids + case user.EdgeReferralProfile: + ids := make([]ent.Value, 0, len(m.removedreferral_profile)) + for id := range m.removedreferral_profile { + ids = append(ids, id) + } + return ids + case user.EdgeReferralsGiven: + ids := make([]ent.Value, 0, len(m.removedreferrals_given)) + for id := range m.removedreferrals_given { + ids = append(ids, id) + } + return ids + case user.EdgeReferralReceived: + ids := make([]ent.Value, 0, len(m.removedreferral_received)) + for id := range m.removedreferral_received { + ids = append(ids, id) + } + return ids } - return + return nil } -// AssignedSubscriptionsIDs returns the "assigned_subscriptions" edge IDs in the mutation. -func (m *UserMutation) AssignedSubscriptionsIDs() (ids []int64) { - for id := range m.assigned_subscriptions { - ids = append(ids, id) +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *UserMutation) ClearedEdges() []string { + edges := make([]string, 0, 12) + if m.clearedapi_keys { + edges = append(edges, user.EdgeAPIKeys) } - return -} - -// ResetAssignedSubscriptions resets all changes to the "assigned_subscriptions" edge. -func (m *UserMutation) ResetAssignedSubscriptions() { - m.assigned_subscriptions = nil - m.clearedassigned_subscriptions = false - m.removedassigned_subscriptions = nil -} - -// AddAnnouncementReadIDs adds the "announcement_reads" edge to the AnnouncementRead entity by ids. -func (m *UserMutation) AddAnnouncementReadIDs(ids ...int64) { - if m.announcement_reads == nil { - m.announcement_reads = make(map[int64]struct{}) + if m.clearedredeem_codes { + edges = append(edges, user.EdgeRedeemCodes) } - for i := range ids { - m.announcement_reads[ids[i]] = struct{}{} + if m.clearedsubscriptions { + edges = append(edges, user.EdgeSubscriptions) } -} - -// ClearAnnouncementReads clears the "announcement_reads" edge to the AnnouncementRead entity. -func (m *UserMutation) ClearAnnouncementReads() { - m.clearedannouncement_reads = true -} - -// AnnouncementReadsCleared reports if the "announcement_reads" edge to the AnnouncementRead entity was cleared. -func (m *UserMutation) AnnouncementReadsCleared() bool { - return m.clearedannouncement_reads -} - -// RemoveAnnouncementReadIDs removes the "announcement_reads" edge to the AnnouncementRead entity by IDs. -func (m *UserMutation) RemoveAnnouncementReadIDs(ids ...int64) { - if m.removedannouncement_reads == nil { - m.removedannouncement_reads = make(map[int64]struct{}) + if m.clearedassigned_subscriptions { + edges = append(edges, user.EdgeAssignedSubscriptions) } - for i := range ids { - delete(m.announcement_reads, ids[i]) - m.removedannouncement_reads[ids[i]] = struct{}{} + if m.clearedannouncement_reads { + edges = append(edges, user.EdgeAnnouncementReads) } -} - -// RemovedAnnouncementReads returns the removed IDs of the "announcement_reads" edge to the AnnouncementRead entity. -func (m *UserMutation) RemovedAnnouncementReadsIDs() (ids []int64) { - for id := range m.removedannouncement_reads { - ids = append(ids, id) + if m.clearedallowed_groups { + edges = append(edges, user.EdgeAllowedGroups) } - return -} - -// AnnouncementReadsIDs returns the "announcement_reads" edge IDs in the mutation. -func (m *UserMutation) AnnouncementReadsIDs() (ids []int64) { - for id := range m.announcement_reads { - ids = append(ids, id) + if m.clearedusage_logs { + edges = append(edges, user.EdgeUsageLogs) } - return -} - -// ResetAnnouncementReads resets all changes to the "announcement_reads" edge. -func (m *UserMutation) ResetAnnouncementReads() { - m.announcement_reads = nil - m.clearedannouncement_reads = false - m.removedannouncement_reads = nil -} - -// AddAllowedGroupIDs adds the "allowed_groups" edge to the Group entity by ids. -func (m *UserMutation) AddAllowedGroupIDs(ids ...int64) { - if m.allowed_groups == nil { - m.allowed_groups = make(map[int64]struct{}) + if m.clearedattribute_values { + edges = append(edges, user.EdgeAttributeValues) } - for i := range ids { - m.allowed_groups[ids[i]] = struct{}{} + if m.clearedpromo_code_usages { + edges = append(edges, user.EdgePromoCodeUsages) } -} - -// ClearAllowedGroups clears the "allowed_groups" edge to the Group entity. -func (m *UserMutation) ClearAllowedGroups() { - m.clearedallowed_groups = true -} - -// AllowedGroupsCleared reports if the "allowed_groups" edge to the Group entity was cleared. -func (m *UserMutation) AllowedGroupsCleared() bool { - return m.clearedallowed_groups -} - -// RemoveAllowedGroupIDs removes the "allowed_groups" edge to the Group entity by IDs. -func (m *UserMutation) RemoveAllowedGroupIDs(ids ...int64) { - if m.removedallowed_groups == nil { - m.removedallowed_groups = make(map[int64]struct{}) + if m.clearedreferral_profile { + edges = append(edges, user.EdgeReferralProfile) } - for i := range ids { - delete(m.allowed_groups, ids[i]) - m.removedallowed_groups[ids[i]] = struct{}{} + if m.clearedreferrals_given { + edges = append(edges, user.EdgeReferralsGiven) } -} - -// RemovedAllowedGroups returns the removed IDs of the "allowed_groups" edge to the Group entity. -func (m *UserMutation) RemovedAllowedGroupsIDs() (ids []int64) { - for id := range m.removedallowed_groups { - ids = append(ids, id) + if m.clearedreferral_received { + edges = append(edges, user.EdgeReferralReceived) } - return + return edges } -// AllowedGroupsIDs returns the "allowed_groups" edge IDs in the mutation. -func (m *UserMutation) AllowedGroupsIDs() (ids []int64) { - for id := range m.allowed_groups { - ids = append(ids, id) +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *UserMutation) EdgeCleared(name string) bool { + switch name { + case user.EdgeAPIKeys: + return m.clearedapi_keys + case user.EdgeRedeemCodes: + return m.clearedredeem_codes + case user.EdgeSubscriptions: + return m.clearedsubscriptions + case user.EdgeAssignedSubscriptions: + return m.clearedassigned_subscriptions + case user.EdgeAnnouncementReads: + return m.clearedannouncement_reads + case user.EdgeAllowedGroups: + return m.clearedallowed_groups + case user.EdgeUsageLogs: + return m.clearedusage_logs + case user.EdgeAttributeValues: + return m.clearedattribute_values + case user.EdgePromoCodeUsages: + return m.clearedpromo_code_usages + case user.EdgeReferralProfile: + return m.clearedreferral_profile + case user.EdgeReferralsGiven: + return m.clearedreferrals_given + case user.EdgeReferralReceived: + return m.clearedreferral_received } - return + return false } -// ResetAllowedGroups resets all changes to the "allowed_groups" edge. -func (m *UserMutation) ResetAllowedGroups() { - m.allowed_groups = nil - m.clearedallowed_groups = false - m.removedallowed_groups = nil +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *UserMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown User unique edge %s", name) } -// AddUsageLogIDs adds the "usage_logs" edge to the UsageLog entity by ids. -func (m *UserMutation) AddUsageLogIDs(ids ...int64) { - if m.usage_logs == nil { - m.usage_logs = make(map[int64]struct{}) - } - for i := range ids { - m.usage_logs[ids[i]] = struct{}{} +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *UserMutation) ResetEdge(name string) error { + switch name { + case user.EdgeAPIKeys: + m.ResetAPIKeys() + return nil + case user.EdgeRedeemCodes: + m.ResetRedeemCodes() + return nil + case user.EdgeSubscriptions: + m.ResetSubscriptions() + return nil + case user.EdgeAssignedSubscriptions: + m.ResetAssignedSubscriptions() + return nil + case user.EdgeAnnouncementReads: + m.ResetAnnouncementReads() + return nil + case user.EdgeAllowedGroups: + m.ResetAllowedGroups() + return nil + case user.EdgeUsageLogs: + m.ResetUsageLogs() + return nil + case user.EdgeAttributeValues: + m.ResetAttributeValues() + return nil + case user.EdgePromoCodeUsages: + m.ResetPromoCodeUsages() + return nil + case user.EdgeReferralProfile: + m.ResetReferralProfile() + return nil + case user.EdgeReferralsGiven: + m.ResetReferralsGiven() + return nil + case user.EdgeReferralReceived: + m.ResetReferralReceived() + return nil } + return fmt.Errorf("unknown User edge %s", name) } -// ClearUsageLogs clears the "usage_logs" edge to the UsageLog entity. -func (m *UserMutation) ClearUsageLogs() { - m.clearedusage_logs = true +// UserAllowedGroupMutation represents an operation that mutates the UserAllowedGroup nodes in the graph. +type UserAllowedGroupMutation struct { + config + op Op + typ string + created_at *time.Time + clearedFields map[string]struct{} + user *int64 + cleareduser bool + group *int64 + clearedgroup bool + done bool + oldValue func(context.Context) (*UserAllowedGroup, error) + predicates []predicate.UserAllowedGroup } -// UsageLogsCleared reports if the "usage_logs" edge to the UsageLog entity was cleared. -func (m *UserMutation) UsageLogsCleared() bool { - return m.clearedusage_logs -} +var _ ent.Mutation = (*UserAllowedGroupMutation)(nil) -// RemoveUsageLogIDs removes the "usage_logs" edge to the UsageLog entity by IDs. -func (m *UserMutation) RemoveUsageLogIDs(ids ...int64) { - if m.removedusage_logs == nil { - m.removedusage_logs = make(map[int64]struct{}) - } - for i := range ids { - delete(m.usage_logs, ids[i]) - m.removedusage_logs[ids[i]] = struct{}{} - } -} +// userallowedgroupOption allows management of the mutation configuration using functional options. +type userallowedgroupOption func(*UserAllowedGroupMutation) -// RemovedUsageLogs returns the removed IDs of the "usage_logs" edge to the UsageLog entity. -func (m *UserMutation) RemovedUsageLogsIDs() (ids []int64) { - for id := range m.removedusage_logs { - ids = append(ids, id) +// newUserAllowedGroupMutation creates new mutation for the UserAllowedGroup entity. +func newUserAllowedGroupMutation(c config, op Op, opts ...userallowedgroupOption) *UserAllowedGroupMutation { + m := &UserAllowedGroupMutation{ + config: c, + op: op, + typ: TypeUserAllowedGroup, + clearedFields: make(map[string]struct{}), } - return -} - -// UsageLogsIDs returns the "usage_logs" edge IDs in the mutation. -func (m *UserMutation) UsageLogsIDs() (ids []int64) { - for id := range m.usage_logs { - ids = append(ids, id) + for _, opt := range opts { + opt(m) } - return + return m } -// ResetUsageLogs resets all changes to the "usage_logs" edge. -func (m *UserMutation) ResetUsageLogs() { - m.usage_logs = nil - m.clearedusage_logs = false - m.removedusage_logs = nil +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m UserAllowedGroupMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client } -// AddAttributeValueIDs adds the "attribute_values" edge to the UserAttributeValue entity by ids. -func (m *UserMutation) AddAttributeValueIDs(ids ...int64) { - if m.attribute_values == nil { - m.attribute_values = make(map[int64]struct{}) - } - for i := range ids { - m.attribute_values[ids[i]] = struct{}{} +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m UserAllowedGroupMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") } + tx := &Tx{config: m.config} + tx.init() + return tx, nil } -// ClearAttributeValues clears the "attribute_values" edge to the UserAttributeValue entity. -func (m *UserMutation) ClearAttributeValues() { - m.clearedattribute_values = true +// SetUserID sets the "user_id" field. +func (m *UserAllowedGroupMutation) SetUserID(i int64) { + m.user = &i } -// AttributeValuesCleared reports if the "attribute_values" edge to the UserAttributeValue entity was cleared. -func (m *UserMutation) AttributeValuesCleared() bool { - return m.clearedattribute_values +// UserID returns the value of the "user_id" field in the mutation. +func (m *UserAllowedGroupMutation) UserID() (r int64, exists bool) { + v := m.user + if v == nil { + return + } + return *v, true } -// RemoveAttributeValueIDs removes the "attribute_values" edge to the UserAttributeValue entity by IDs. -func (m *UserMutation) RemoveAttributeValueIDs(ids ...int64) { - if m.removedattribute_values == nil { - m.removedattribute_values = make(map[int64]struct{}) - } - for i := range ids { - delete(m.attribute_values, ids[i]) - m.removedattribute_values[ids[i]] = struct{}{} - } +// ResetUserID resets all changes to the "user_id" field. +func (m *UserAllowedGroupMutation) ResetUserID() { + m.user = nil } -// RemovedAttributeValues returns the removed IDs of the "attribute_values" edge to the UserAttributeValue entity. -func (m *UserMutation) RemovedAttributeValuesIDs() (ids []int64) { - for id := range m.removedattribute_values { - ids = append(ids, id) - } - return +// SetGroupID sets the "group_id" field. +func (m *UserAllowedGroupMutation) SetGroupID(i int64) { + m.group = &i } -// AttributeValuesIDs returns the "attribute_values" edge IDs in the mutation. -func (m *UserMutation) AttributeValuesIDs() (ids []int64) { - for id := range m.attribute_values { - ids = append(ids, id) +// GroupID returns the value of the "group_id" field in the mutation. +func (m *UserAllowedGroupMutation) GroupID() (r int64, exists bool) { + v := m.group + if v == nil { + return } - return + return *v, true } -// ResetAttributeValues resets all changes to the "attribute_values" edge. -func (m *UserMutation) ResetAttributeValues() { - m.attribute_values = nil - m.clearedattribute_values = false - m.removedattribute_values = nil +// ResetGroupID resets all changes to the "group_id" field. +func (m *UserAllowedGroupMutation) ResetGroupID() { + m.group = nil } -// AddPromoCodeUsageIDs adds the "promo_code_usages" edge to the PromoCodeUsage entity by ids. -func (m *UserMutation) AddPromoCodeUsageIDs(ids ...int64) { - if m.promo_code_usages == nil { - m.promo_code_usages = make(map[int64]struct{}) - } - for i := range ids { - m.promo_code_usages[ids[i]] = struct{}{} +// SetCreatedAt sets the "created_at" field. +func (m *UserAllowedGroupMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *UserAllowedGroupMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return } + return *v, true } -// ClearPromoCodeUsages clears the "promo_code_usages" edge to the PromoCodeUsage entity. -func (m *UserMutation) ClearPromoCodeUsages() { - m.clearedpromo_code_usages = true +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *UserAllowedGroupMutation) ResetCreatedAt() { + m.created_at = nil } -// PromoCodeUsagesCleared reports if the "promo_code_usages" edge to the PromoCodeUsage entity was cleared. -func (m *UserMutation) PromoCodeUsagesCleared() bool { - return m.clearedpromo_code_usages +// ClearUser clears the "user" edge to the User entity. +func (m *UserAllowedGroupMutation) ClearUser() { + m.cleareduser = true + m.clearedFields[userallowedgroup.FieldUserID] = struct{}{} } -// RemovePromoCodeUsageIDs removes the "promo_code_usages" edge to the PromoCodeUsage entity by IDs. -func (m *UserMutation) RemovePromoCodeUsageIDs(ids ...int64) { - if m.removedpromo_code_usages == nil { - m.removedpromo_code_usages = make(map[int64]struct{}) - } - for i := range ids { - delete(m.promo_code_usages, ids[i]) - m.removedpromo_code_usages[ids[i]] = struct{}{} - } +// UserCleared reports if the "user" edge to the User entity was cleared. +func (m *UserAllowedGroupMutation) UserCleared() bool { + return m.cleareduser } -// RemovedPromoCodeUsages returns the removed IDs of the "promo_code_usages" edge to the PromoCodeUsage entity. -func (m *UserMutation) RemovedPromoCodeUsagesIDs() (ids []int64) { - for id := range m.removedpromo_code_usages { - ids = append(ids, id) +// UserIDs returns the "user" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// UserID instead. It exists only for internal usage by the builders. +func (m *UserAllowedGroupMutation) UserIDs() (ids []int64) { + if id := m.user; id != nil { + ids = append(ids, *id) } return } -// PromoCodeUsagesIDs returns the "promo_code_usages" edge IDs in the mutation. -func (m *UserMutation) PromoCodeUsagesIDs() (ids []int64) { - for id := range m.promo_code_usages { - ids = append(ids, id) +// ResetUser resets all changes to the "user" edge. +func (m *UserAllowedGroupMutation) ResetUser() { + m.user = nil + m.cleareduser = false +} + +// ClearGroup clears the "group" edge to the Group entity. +func (m *UserAllowedGroupMutation) ClearGroup() { + m.clearedgroup = true + m.clearedFields[userallowedgroup.FieldGroupID] = struct{}{} +} + +// GroupCleared reports if the "group" edge to the Group entity was cleared. +func (m *UserAllowedGroupMutation) GroupCleared() bool { + return m.clearedgroup +} + +// GroupIDs returns the "group" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// GroupID instead. It exists only for internal usage by the builders. +func (m *UserAllowedGroupMutation) GroupIDs() (ids []int64) { + if id := m.group; id != nil { + ids = append(ids, *id) } return } -// ResetPromoCodeUsages resets all changes to the "promo_code_usages" edge. -func (m *UserMutation) ResetPromoCodeUsages() { - m.promo_code_usages = nil - m.clearedpromo_code_usages = false - m.removedpromo_code_usages = nil +// ResetGroup resets all changes to the "group" edge. +func (m *UserAllowedGroupMutation) ResetGroup() { + m.group = nil + m.clearedgroup = false } -// Where appends a list predicates to the UserMutation builder. -func (m *UserMutation) Where(ps ...predicate.User) { +// Where appends a list predicates to the UserAllowedGroupMutation builder. +func (m *UserAllowedGroupMutation) Where(ps ...predicate.UserAllowedGroup) { m.predicates = append(m.predicates, ps...) } -// WhereP appends storage-level predicates to the UserMutation builder. Using this method, +// WhereP appends storage-level predicates to the UserAllowedGroupMutation builder. Using this method, // users can use type-assertion to append predicates that do not depend on any generated package. -func (m *UserMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.User, len(ps)) +func (m *UserAllowedGroupMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.UserAllowedGroup, len(ps)) for i := range ps { p[i] = ps[i] } @@ -22328,72 +24261,33 @@ func (m *UserMutation) WhereP(ps ...func(*sql.Selector)) { } // Op returns the operation name. -func (m *UserMutation) Op() Op { +func (m *UserAllowedGroupMutation) Op() Op { return m.op } // SetOp allows setting the mutation operation. -func (m *UserMutation) SetOp(op Op) { +func (m *UserAllowedGroupMutation) SetOp(op Op) { m.op = op } -// Type returns the node type of this mutation (User). -func (m *UserMutation) Type() string { +// Type returns the node type of this mutation (UserAllowedGroup). +func (m *UserAllowedGroupMutation) Type() string { return m.typ } // Fields returns all fields that were changed during this mutation. Note that in // order to get all numeric fields that were incremented/decremented, call // AddedFields(). -func (m *UserMutation) Fields() []string { - fields := make([]string, 0, 16) - if m.created_at != nil { - fields = append(fields, user.FieldCreatedAt) - } - if m.updated_at != nil { - fields = append(fields, user.FieldUpdatedAt) - } - if m.deleted_at != nil { - fields = append(fields, user.FieldDeletedAt) - } - if m.email != nil { - fields = append(fields, user.FieldEmail) - } - if m.password_hash != nil { - fields = append(fields, user.FieldPasswordHash) - } - if m.role != nil { - fields = append(fields, user.FieldRole) - } - if m.balance != nil { - fields = append(fields, user.FieldBalance) - } - if m.concurrency != nil { - fields = append(fields, user.FieldConcurrency) - } - if m.status != nil { - fields = append(fields, user.FieldStatus) - } - if m.username != nil { - fields = append(fields, user.FieldUsername) - } - if m.notes != nil { - fields = append(fields, user.FieldNotes) - } - if m.totp_secret_encrypted != nil { - fields = append(fields, user.FieldTotpSecretEncrypted) - } - if m.totp_enabled != nil { - fields = append(fields, user.FieldTotpEnabled) - } - if m.totp_enabled_at != nil { - fields = append(fields, user.FieldTotpEnabledAt) +func (m *UserAllowedGroupMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.user != nil { + fields = append(fields, userallowedgroup.FieldUserID) } - if m.sora_storage_quota_bytes != nil { - fields = append(fields, user.FieldSoraStorageQuotaBytes) + if m.group != nil { + fields = append(fields, userallowedgroup.FieldGroupID) } - if m.sora_storage_used_bytes != nil { - fields = append(fields, user.FieldSoraStorageUsedBytes) + if m.created_at != nil { + fields = append(fields, userallowedgroup.FieldCreatedAt) } return fields } @@ -22401,238 +24295,67 @@ func (m *UserMutation) Fields() []string { // Field returns the value of a field with the given name. The second boolean // return value indicates that this field was not set, or was not defined in the // schema. -func (m *UserMutation) Field(name string) (ent.Value, bool) { - switch name { - case user.FieldCreatedAt: - return m.CreatedAt() - case user.FieldUpdatedAt: - return m.UpdatedAt() - case user.FieldDeletedAt: - return m.DeletedAt() - case user.FieldEmail: - return m.Email() - case user.FieldPasswordHash: - return m.PasswordHash() - case user.FieldRole: - return m.Role() - case user.FieldBalance: - return m.Balance() - case user.FieldConcurrency: - return m.Concurrency() - case user.FieldStatus: - return m.Status() - case user.FieldUsername: - return m.Username() - case user.FieldNotes: - return m.Notes() - case user.FieldTotpSecretEncrypted: - return m.TotpSecretEncrypted() - case user.FieldTotpEnabled: - return m.TotpEnabled() - case user.FieldTotpEnabledAt: - return m.TotpEnabledAt() - case user.FieldSoraStorageQuotaBytes: - return m.SoraStorageQuotaBytes() - case user.FieldSoraStorageUsedBytes: - return m.SoraStorageUsedBytes() - } - return nil, false -} - -// OldField returns the old value of the field from the database. An error is -// returned if the mutation operation is not UpdateOne, or the query to the -// database failed. -func (m *UserMutation) OldField(ctx context.Context, name string) (ent.Value, error) { +func (m *UserAllowedGroupMutation) Field(name string) (ent.Value, bool) { switch name { - case user.FieldCreatedAt: - return m.OldCreatedAt(ctx) - case user.FieldUpdatedAt: - return m.OldUpdatedAt(ctx) - case user.FieldDeletedAt: - return m.OldDeletedAt(ctx) - case user.FieldEmail: - return m.OldEmail(ctx) - case user.FieldPasswordHash: - return m.OldPasswordHash(ctx) - case user.FieldRole: - return m.OldRole(ctx) - case user.FieldBalance: - return m.OldBalance(ctx) - case user.FieldConcurrency: - return m.OldConcurrency(ctx) - case user.FieldStatus: - return m.OldStatus(ctx) - case user.FieldUsername: - return m.OldUsername(ctx) - case user.FieldNotes: - return m.OldNotes(ctx) - case user.FieldTotpSecretEncrypted: - return m.OldTotpSecretEncrypted(ctx) - case user.FieldTotpEnabled: - return m.OldTotpEnabled(ctx) - case user.FieldTotpEnabledAt: - return m.OldTotpEnabledAt(ctx) - case user.FieldSoraStorageQuotaBytes: - return m.OldSoraStorageQuotaBytes(ctx) - case user.FieldSoraStorageUsedBytes: - return m.OldSoraStorageUsedBytes(ctx) + case userallowedgroup.FieldUserID: + return m.UserID() + case userallowedgroup.FieldGroupID: + return m.GroupID() + case userallowedgroup.FieldCreatedAt: + return m.CreatedAt() } - return nil, fmt.Errorf("unknown User field %s", name) + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *UserAllowedGroupMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + return nil, errors.New("edge schema UserAllowedGroup does not support getting old values") } // SetField sets the value of a field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *UserMutation) SetField(name string, value ent.Value) error { +func (m *UserAllowedGroupMutation) SetField(name string, value ent.Value) error { switch name { - case user.FieldCreatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCreatedAt(v) - return nil - case user.FieldUpdatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUpdatedAt(v) - return nil - case user.FieldDeletedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetDeletedAt(v) - return nil - case user.FieldEmail: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetEmail(v) - return nil - case user.FieldPasswordHash: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetPasswordHash(v) - return nil - case user.FieldRole: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetRole(v) - return nil - case user.FieldBalance: - v, ok := value.(float64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetBalance(v) - return nil - case user.FieldConcurrency: - v, ok := value.(int) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetConcurrency(v) - return nil - case user.FieldStatus: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetStatus(v) - return nil - case user.FieldUsername: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUsername(v) - return nil - case user.FieldNotes: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetNotes(v) - return nil - case user.FieldTotpSecretEncrypted: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetTotpSecretEncrypted(v) - return nil - case user.FieldTotpEnabled: - v, ok := value.(bool) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetTotpEnabled(v) - return nil - case user.FieldTotpEnabledAt: - v, ok := value.(time.Time) + case userallowedgroup.FieldUserID: + v, ok := value.(int64) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetTotpEnabledAt(v) + m.SetUserID(v) return nil - case user.FieldSoraStorageQuotaBytes: + case userallowedgroup.FieldGroupID: v, ok := value.(int64) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetSoraStorageQuotaBytes(v) + m.SetGroupID(v) return nil - case user.FieldSoraStorageUsedBytes: - v, ok := value.(int64) + case userallowedgroup.FieldCreatedAt: + v, ok := value.(time.Time) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetSoraStorageUsedBytes(v) + m.SetCreatedAt(v) return nil } - return fmt.Errorf("unknown User field %s", name) + return fmt.Errorf("unknown UserAllowedGroup field %s", name) } // AddedFields returns all numeric fields that were incremented/decremented during // this mutation. -func (m *UserMutation) AddedFields() []string { +func (m *UserAllowedGroupMutation) AddedFields() []string { var fields []string - if m.addbalance != nil { - fields = append(fields, user.FieldBalance) - } - if m.addconcurrency != nil { - fields = append(fields, user.FieldConcurrency) - } - if m.addsora_storage_quota_bytes != nil { - fields = append(fields, user.FieldSoraStorageQuotaBytes) - } - if m.addsora_storage_used_bytes != nil { - fields = append(fields, user.FieldSoraStorageUsedBytes) - } return fields } // AddedField returns the numeric value that was incremented/decremented on a field // with the given name. The second boolean return value indicates that this field // was not set, or was not defined in the schema. -func (m *UserMutation) AddedField(name string) (ent.Value, bool) { +func (m *UserAllowedGroupMutation) AddedField(name string) (ent.Value, bool) { switch name { - case user.FieldBalance: - return m.AddedBalance() - case user.FieldConcurrency: - return m.AddedConcurrency() - case user.FieldSoraStorageQuotaBytes: - return m.AddedSoraStorageQuotaBytes() - case user.FieldSoraStorageUsedBytes: - return m.AddedSoraStorageUsedBytes() } return nil, false } @@ -22640,1552 +24363,1654 @@ func (m *UserMutation) AddedField(name string) (ent.Value, bool) { // AddField adds the value to the field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *UserMutation) AddField(name string, value ent.Value) error { +func (m *UserAllowedGroupMutation) AddField(name string, value ent.Value) error { switch name { - case user.FieldBalance: - v, ok := value.(float64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddBalance(v) - return nil - case user.FieldConcurrency: - v, ok := value.(int) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddConcurrency(v) - return nil - case user.FieldSoraStorageQuotaBytes: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddSoraStorageQuotaBytes(v) - return nil - case user.FieldSoraStorageUsedBytes: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddSoraStorageUsedBytes(v) - return nil } - return fmt.Errorf("unknown User numeric field %s", name) + return fmt.Errorf("unknown UserAllowedGroup numeric field %s", name) } // ClearedFields returns all nullable fields that were cleared during this // mutation. -func (m *UserMutation) ClearedFields() []string { - var fields []string - if m.FieldCleared(user.FieldDeletedAt) { - fields = append(fields, user.FieldDeletedAt) - } - if m.FieldCleared(user.FieldTotpSecretEncrypted) { - fields = append(fields, user.FieldTotpSecretEncrypted) - } - if m.FieldCleared(user.FieldTotpEnabledAt) { - fields = append(fields, user.FieldTotpEnabledAt) - } - return fields +func (m *UserAllowedGroupMutation) ClearedFields() []string { + return nil } // FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. -func (m *UserMutation) FieldCleared(name string) bool { +func (m *UserAllowedGroupMutation) FieldCleared(name string) bool { _, ok := m.clearedFields[name] return ok } // ClearField clears the value of the field with the given name. It returns an // error if the field is not defined in the schema. -func (m *UserMutation) ClearField(name string) error { - switch name { - case user.FieldDeletedAt: - m.ClearDeletedAt() - return nil - case user.FieldTotpSecretEncrypted: - m.ClearTotpSecretEncrypted() - return nil - case user.FieldTotpEnabledAt: - m.ClearTotpEnabledAt() - return nil - } - return fmt.Errorf("unknown User nullable field %s", name) +func (m *UserAllowedGroupMutation) ClearField(name string) error { + return fmt.Errorf("unknown UserAllowedGroup nullable field %s", name) } // ResetField resets all changes in the mutation for the field with the given name. // It returns an error if the field is not defined in the schema. -func (m *UserMutation) ResetField(name string) error { +func (m *UserAllowedGroupMutation) ResetField(name string) error { switch name { - case user.FieldCreatedAt: - m.ResetCreatedAt() - return nil - case user.FieldUpdatedAt: - m.ResetUpdatedAt() - return nil - case user.FieldDeletedAt: - m.ResetDeletedAt() - return nil - case user.FieldEmail: - m.ResetEmail() - return nil - case user.FieldPasswordHash: - m.ResetPasswordHash() - return nil - case user.FieldRole: - m.ResetRole() - return nil - case user.FieldBalance: - m.ResetBalance() - return nil - case user.FieldConcurrency: - m.ResetConcurrency() - return nil - case user.FieldStatus: - m.ResetStatus() - return nil - case user.FieldUsername: - m.ResetUsername() - return nil - case user.FieldNotes: - m.ResetNotes() - return nil - case user.FieldTotpSecretEncrypted: - m.ResetTotpSecretEncrypted() - return nil - case user.FieldTotpEnabled: - m.ResetTotpEnabled() - return nil - case user.FieldTotpEnabledAt: - m.ResetTotpEnabledAt() + case userallowedgroup.FieldUserID: + m.ResetUserID() return nil - case user.FieldSoraStorageQuotaBytes: - m.ResetSoraStorageQuotaBytes() + case userallowedgroup.FieldGroupID: + m.ResetGroupID() return nil - case user.FieldSoraStorageUsedBytes: - m.ResetSoraStorageUsedBytes() + case userallowedgroup.FieldCreatedAt: + m.ResetCreatedAt() return nil } - return fmt.Errorf("unknown User field %s", name) + return fmt.Errorf("unknown UserAllowedGroup field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. -func (m *UserMutation) AddedEdges() []string { - edges := make([]string, 0, 9) - if m.api_keys != nil { - edges = append(edges, user.EdgeAPIKeys) - } - if m.redeem_codes != nil { - edges = append(edges, user.EdgeRedeemCodes) - } - if m.subscriptions != nil { - edges = append(edges, user.EdgeSubscriptions) - } - if m.assigned_subscriptions != nil { - edges = append(edges, user.EdgeAssignedSubscriptions) - } - if m.announcement_reads != nil { - edges = append(edges, user.EdgeAnnouncementReads) - } - if m.allowed_groups != nil { - edges = append(edges, user.EdgeAllowedGroups) - } - if m.usage_logs != nil { - edges = append(edges, user.EdgeUsageLogs) - } - if m.attribute_values != nil { - edges = append(edges, user.EdgeAttributeValues) +func (m *UserAllowedGroupMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.user != nil { + edges = append(edges, userallowedgroup.EdgeUser) } - if m.promo_code_usages != nil { - edges = append(edges, user.EdgePromoCodeUsages) + if m.group != nil { + edges = append(edges, userallowedgroup.EdgeGroup) } return edges } // AddedIDs returns all IDs (to other nodes) that were added for the given edge // name in this mutation. -func (m *UserMutation) AddedIDs(name string) []ent.Value { +func (m *UserAllowedGroupMutation) AddedIDs(name string) []ent.Value { switch name { - case user.EdgeAPIKeys: - ids := make([]ent.Value, 0, len(m.api_keys)) - for id := range m.api_keys { - ids = append(ids, id) - } - return ids - case user.EdgeRedeemCodes: - ids := make([]ent.Value, 0, len(m.redeem_codes)) - for id := range m.redeem_codes { - ids = append(ids, id) - } - return ids - case user.EdgeSubscriptions: - ids := make([]ent.Value, 0, len(m.subscriptions)) - for id := range m.subscriptions { - ids = append(ids, id) - } - return ids - case user.EdgeAssignedSubscriptions: - ids := make([]ent.Value, 0, len(m.assigned_subscriptions)) - for id := range m.assigned_subscriptions { - ids = append(ids, id) - } - return ids - case user.EdgeAnnouncementReads: - ids := make([]ent.Value, 0, len(m.announcement_reads)) - for id := range m.announcement_reads { - ids = append(ids, id) - } - return ids - case user.EdgeAllowedGroups: - ids := make([]ent.Value, 0, len(m.allowed_groups)) - for id := range m.allowed_groups { - ids = append(ids, id) - } - return ids - case user.EdgeUsageLogs: - ids := make([]ent.Value, 0, len(m.usage_logs)) - for id := range m.usage_logs { - ids = append(ids, id) - } - return ids - case user.EdgeAttributeValues: - ids := make([]ent.Value, 0, len(m.attribute_values)) - for id := range m.attribute_values { - ids = append(ids, id) + case userallowedgroup.EdgeUser: + if id := m.user; id != nil { + return []ent.Value{*id} } - return ids - case user.EdgePromoCodeUsages: - ids := make([]ent.Value, 0, len(m.promo_code_usages)) - for id := range m.promo_code_usages { - ids = append(ids, id) + case userallowedgroup.EdgeGroup: + if id := m.group; id != nil { + return []ent.Value{*id} } - return ids } return nil } // RemovedEdges returns all edge names that were removed in this mutation. -func (m *UserMutation) RemovedEdges() []string { - edges := make([]string, 0, 9) - if m.removedapi_keys != nil { - edges = append(edges, user.EdgeAPIKeys) - } - if m.removedredeem_codes != nil { - edges = append(edges, user.EdgeRedeemCodes) - } - if m.removedsubscriptions != nil { - edges = append(edges, user.EdgeSubscriptions) - } - if m.removedassigned_subscriptions != nil { - edges = append(edges, user.EdgeAssignedSubscriptions) - } - if m.removedannouncement_reads != nil { - edges = append(edges, user.EdgeAnnouncementReads) - } - if m.removedallowed_groups != nil { - edges = append(edges, user.EdgeAllowedGroups) +func (m *UserAllowedGroupMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *UserAllowedGroupMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *UserAllowedGroupMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.cleareduser { + edges = append(edges, userallowedgroup.EdgeUser) } - if m.removedusage_logs != nil { - edges = append(edges, user.EdgeUsageLogs) + if m.clearedgroup { + edges = append(edges, userallowedgroup.EdgeGroup) } - if m.removedattribute_values != nil { - edges = append(edges, user.EdgeAttributeValues) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *UserAllowedGroupMutation) EdgeCleared(name string) bool { + switch name { + case userallowedgroup.EdgeUser: + return m.cleareduser + case userallowedgroup.EdgeGroup: + return m.clearedgroup } - if m.removedpromo_code_usages != nil { - edges = append(edges, user.EdgePromoCodeUsages) + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *UserAllowedGroupMutation) ClearEdge(name string) error { + switch name { + case userallowedgroup.EdgeUser: + m.ClearUser() + return nil + case userallowedgroup.EdgeGroup: + m.ClearGroup() + return nil } - return edges + return fmt.Errorf("unknown UserAllowedGroup unique edge %s", name) } -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *UserMutation) RemovedIDs(name string) []ent.Value { +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *UserAllowedGroupMutation) ResetEdge(name string) error { switch name { - case user.EdgeAPIKeys: - ids := make([]ent.Value, 0, len(m.removedapi_keys)) - for id := range m.removedapi_keys { - ids = append(ids, id) - } - return ids - case user.EdgeRedeemCodes: - ids := make([]ent.Value, 0, len(m.removedredeem_codes)) - for id := range m.removedredeem_codes { - ids = append(ids, id) - } - return ids - case user.EdgeSubscriptions: - ids := make([]ent.Value, 0, len(m.removedsubscriptions)) - for id := range m.removedsubscriptions { - ids = append(ids, id) - } - return ids - case user.EdgeAssignedSubscriptions: - ids := make([]ent.Value, 0, len(m.removedassigned_subscriptions)) - for id := range m.removedassigned_subscriptions { - ids = append(ids, id) - } - return ids - case user.EdgeAnnouncementReads: - ids := make([]ent.Value, 0, len(m.removedannouncement_reads)) - for id := range m.removedannouncement_reads { - ids = append(ids, id) - } - return ids - case user.EdgeAllowedGroups: - ids := make([]ent.Value, 0, len(m.removedallowed_groups)) - for id := range m.removedallowed_groups { - ids = append(ids, id) - } - return ids - case user.EdgeUsageLogs: - ids := make([]ent.Value, 0, len(m.removedusage_logs)) - for id := range m.removedusage_logs { - ids = append(ids, id) - } - return ids - case user.EdgeAttributeValues: - ids := make([]ent.Value, 0, len(m.removedattribute_values)) - for id := range m.removedattribute_values { - ids = append(ids, id) - } - return ids - case user.EdgePromoCodeUsages: - ids := make([]ent.Value, 0, len(m.removedpromo_code_usages)) - for id := range m.removedpromo_code_usages { - ids = append(ids, id) - } - return ids + case userallowedgroup.EdgeUser: + m.ResetUser() + return nil + case userallowedgroup.EdgeGroup: + m.ResetGroup() + return nil + } + return fmt.Errorf("unknown UserAllowedGroup edge %s", name) +} + +// UserAttributeDefinitionMutation represents an operation that mutates the UserAttributeDefinition nodes in the graph. +type UserAttributeDefinitionMutation struct { + config + op Op + typ string + id *int64 + created_at *time.Time + updated_at *time.Time + deleted_at *time.Time + key *string + name *string + description *string + _type *string + options *[]map[string]interface{} + appendoptions []map[string]interface{} + required *bool + validation *map[string]interface{} + placeholder *string + display_order *int + adddisplay_order *int + enabled *bool + clearedFields map[string]struct{} + values map[int64]struct{} + removedvalues map[int64]struct{} + clearedvalues bool + done bool + oldValue func(context.Context) (*UserAttributeDefinition, error) + predicates []predicate.UserAttributeDefinition +} + +var _ ent.Mutation = (*UserAttributeDefinitionMutation)(nil) + +// userattributedefinitionOption allows management of the mutation configuration using functional options. +type userattributedefinitionOption func(*UserAttributeDefinitionMutation) + +// newUserAttributeDefinitionMutation creates new mutation for the UserAttributeDefinition entity. +func newUserAttributeDefinitionMutation(c config, op Op, opts ...userattributedefinitionOption) *UserAttributeDefinitionMutation { + m := &UserAttributeDefinitionMutation{ + config: c, + op: op, + typ: TypeUserAttributeDefinition, + clearedFields: make(map[string]struct{}), } - return nil + for _, opt := range opts { + opt(m) + } + return m } -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *UserMutation) ClearedEdges() []string { - edges := make([]string, 0, 9) - if m.clearedapi_keys { - edges = append(edges, user.EdgeAPIKeys) +// withUserAttributeDefinitionID sets the ID field of the mutation. +func withUserAttributeDefinitionID(id int64) userattributedefinitionOption { + return func(m *UserAttributeDefinitionMutation) { + var ( + err error + once sync.Once + value *UserAttributeDefinition + ) + m.oldValue = func(ctx context.Context) (*UserAttributeDefinition, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().UserAttributeDefinition.Get(ctx, id) + } + }) + return value, err + } + m.id = &id } - if m.clearedredeem_codes { - edges = append(edges, user.EdgeRedeemCodes) +} + +// withUserAttributeDefinition sets the old UserAttributeDefinition of the mutation. +func withUserAttributeDefinition(node *UserAttributeDefinition) userattributedefinitionOption { + return func(m *UserAttributeDefinitionMutation) { + m.oldValue = func(context.Context) (*UserAttributeDefinition, error) { + return node, nil + } + m.id = &node.ID } - if m.clearedsubscriptions { - edges = append(edges, user.EdgeSubscriptions) +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m UserAttributeDefinitionMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m UserAttributeDefinitionMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") } - if m.clearedassigned_subscriptions { - edges = append(edges, user.EdgeAssignedSubscriptions) + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *UserAttributeDefinitionMutation) ID() (id int64, exists bool) { + if m.id == nil { + return } - if m.clearedannouncement_reads { - edges = append(edges, user.EdgeAnnouncementReads) + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *UserAttributeDefinitionMutation) IDs(ctx context.Context) ([]int64, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int64{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().UserAttributeDefinition.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } - if m.clearedallowed_groups { - edges = append(edges, user.EdgeAllowedGroups) +} + +// SetCreatedAt sets the "created_at" field. +func (m *UserAttributeDefinitionMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *UserAttributeDefinitionMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return } - if m.clearedusage_logs { - edges = append(edges, user.EdgeUsageLogs) + return *v, true +} + +// OldCreatedAt returns the old "created_at" field's value of the UserAttributeDefinition entity. +// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserAttributeDefinitionMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") } - if m.clearedattribute_values { - edges = append(edges, user.EdgeAttributeValues) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedAt requires an ID field in the mutation") } - if m.clearedpromo_code_usages { - edges = append(edges, user.EdgePromoCodeUsages) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) } - return edges + return oldValue.CreatedAt, nil } -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *UserMutation) EdgeCleared(name string) bool { - switch name { - case user.EdgeAPIKeys: - return m.clearedapi_keys - case user.EdgeRedeemCodes: - return m.clearedredeem_codes - case user.EdgeSubscriptions: - return m.clearedsubscriptions - case user.EdgeAssignedSubscriptions: - return m.clearedassigned_subscriptions - case user.EdgeAnnouncementReads: - return m.clearedannouncement_reads - case user.EdgeAllowedGroups: - return m.clearedallowed_groups - case user.EdgeUsageLogs: - return m.clearedusage_logs - case user.EdgeAttributeValues: - return m.clearedattribute_values - case user.EdgePromoCodeUsages: - return m.clearedpromo_code_usages - } - return false +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *UserAttributeDefinitionMutation) ResetCreatedAt() { + m.created_at = nil } -// ClearEdge clears the value of the edge with the given name. It returns an error -// if that edge is not defined in the schema. -func (m *UserMutation) ClearEdge(name string) error { - switch name { +// SetUpdatedAt sets the "updated_at" field. +func (m *UserAttributeDefinitionMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *UserAttributeDefinitionMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at + if v == nil { + return } - return fmt.Errorf("unknown User unique edge %s", name) + return *v, true } -// ResetEdge resets all changes to the edge with the given name in this mutation. -// It returns an error if the edge is not defined in the schema. -func (m *UserMutation) ResetEdge(name string) error { - switch name { - case user.EdgeAPIKeys: - m.ResetAPIKeys() - return nil - case user.EdgeRedeemCodes: - m.ResetRedeemCodes() - return nil - case user.EdgeSubscriptions: - m.ResetSubscriptions() - return nil - case user.EdgeAssignedSubscriptions: - m.ResetAssignedSubscriptions() - return nil - case user.EdgeAnnouncementReads: - m.ResetAnnouncementReads() - return nil - case user.EdgeAllowedGroups: - m.ResetAllowedGroups() - return nil - case user.EdgeUsageLogs: - m.ResetUsageLogs() - return nil - case user.EdgeAttributeValues: - m.ResetAttributeValues() - return nil - case user.EdgePromoCodeUsages: - m.ResetPromoCodeUsages() - return nil +// OldUpdatedAt returns the old "updated_at" field's value of the UserAttributeDefinition entity. +// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserAttributeDefinitionMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") } - return fmt.Errorf("unknown User edge %s", name) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + } + return oldValue.UpdatedAt, nil } -// UserAllowedGroupMutation represents an operation that mutates the UserAllowedGroup nodes in the graph. -type UserAllowedGroupMutation struct { - config - op Op - typ string - created_at *time.Time - clearedFields map[string]struct{} - user *int64 - cleareduser bool - group *int64 - clearedgroup bool - done bool - oldValue func(context.Context) (*UserAllowedGroup, error) - predicates []predicate.UserAllowedGroup +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *UserAttributeDefinitionMutation) ResetUpdatedAt() { + m.updated_at = nil } -var _ ent.Mutation = (*UserAllowedGroupMutation)(nil) +// SetDeletedAt sets the "deleted_at" field. +func (m *UserAttributeDefinitionMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} -// userallowedgroupOption allows management of the mutation configuration using functional options. -type userallowedgroupOption func(*UserAllowedGroupMutation) +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *UserAttributeDefinitionMutation) DeletedAt() (r time.Time, exists bool) { + v := m.deleted_at + if v == nil { + return + } + return *v, true +} -// newUserAllowedGroupMutation creates new mutation for the UserAllowedGroup entity. -func newUserAllowedGroupMutation(c config, op Op, opts ...userallowedgroupOption) *UserAllowedGroupMutation { - m := &UserAllowedGroupMutation{ - config: c, - op: op, - typ: TypeUserAllowedGroup, - clearedFields: make(map[string]struct{}), +// OldDeletedAt returns the old "deleted_at" field's value of the UserAttributeDefinition entity. +// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserAttributeDefinitionMutation) OldDeletedAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDeletedAt is only allowed on UpdateOne operations") } - for _, opt := range opts { - opt(m) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDeletedAt requires an ID field in the mutation") } - return m + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDeletedAt: %w", err) + } + return oldValue.DeletedAt, nil } -// Client returns a new `ent.Client` from the mutation. If the mutation was -// executed in a transaction (ent.Tx), a transactional client is returned. -func (m UserAllowedGroupMutation) Client() *Client { - client := &Client{config: m.config} - client.init() - return client +// ClearDeletedAt clears the value of the "deleted_at" field. +func (m *UserAttributeDefinitionMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[userattributedefinition.FieldDeletedAt] = struct{}{} } -// Tx returns an `ent.Tx` for mutations that were executed in transactions; -// it returns an error otherwise. -func (m UserAllowedGroupMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, errors.New("ent: mutation is not running in a transaction") - } - tx := &Tx{config: m.config} - tx.init() - return tx, nil +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *UserAttributeDefinitionMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[userattributedefinition.FieldDeletedAt] + return ok } -// SetUserID sets the "user_id" field. -func (m *UserAllowedGroupMutation) SetUserID(i int64) { - m.user = &i +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *UserAttributeDefinitionMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, userattributedefinition.FieldDeletedAt) } -// UserID returns the value of the "user_id" field in the mutation. -func (m *UserAllowedGroupMutation) UserID() (r int64, exists bool) { - v := m.user +// SetKey sets the "key" field. +func (m *UserAttributeDefinitionMutation) SetKey(s string) { + m.key = &s +} + +// Key returns the value of the "key" field in the mutation. +func (m *UserAttributeDefinitionMutation) Key() (r string, exists bool) { + v := m.key if v == nil { return } return *v, true } -// ResetUserID resets all changes to the "user_id" field. -func (m *UserAllowedGroupMutation) ResetUserID() { - m.user = nil +// OldKey returns the old "key" field's value of the UserAttributeDefinition entity. +// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserAttributeDefinitionMutation) OldKey(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldKey is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldKey requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldKey: %w", err) + } + return oldValue.Key, nil } -// SetGroupID sets the "group_id" field. -func (m *UserAllowedGroupMutation) SetGroupID(i int64) { - m.group = &i +// ResetKey resets all changes to the "key" field. +func (m *UserAttributeDefinitionMutation) ResetKey() { + m.key = nil } -// GroupID returns the value of the "group_id" field in the mutation. -func (m *UserAllowedGroupMutation) GroupID() (r int64, exists bool) { - v := m.group +// SetName sets the "name" field. +func (m *UserAttributeDefinitionMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *UserAttributeDefinitionMutation) Name() (r string, exists bool) { + v := m.name if v == nil { return } return *v, true } -// ResetGroupID resets all changes to the "group_id" field. -func (m *UserAllowedGroupMutation) ResetGroupID() { - m.group = nil +// OldName returns the old "name" field's value of the UserAttributeDefinition entity. +// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserAttributeDefinitionMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil } -// SetCreatedAt sets the "created_at" field. -func (m *UserAllowedGroupMutation) SetCreatedAt(t time.Time) { - m.created_at = &t +// ResetName resets all changes to the "name" field. +func (m *UserAttributeDefinitionMutation) ResetName() { + m.name = nil } -// CreatedAt returns the value of the "created_at" field in the mutation. -func (m *UserAllowedGroupMutation) CreatedAt() (r time.Time, exists bool) { - v := m.created_at +// SetDescription sets the "description" field. +func (m *UserAttributeDefinitionMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *UserAttributeDefinitionMutation) Description() (r string, exists bool) { + v := m.description if v == nil { return } return *v, true } -// ResetCreatedAt resets all changes to the "created_at" field. -func (m *UserAllowedGroupMutation) ResetCreatedAt() { - m.created_at = nil +// OldDescription returns the old "description" field's value of the UserAttributeDefinition entity. +// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserAttributeDefinitionMutation) OldDescription(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil } -// ClearUser clears the "user" edge to the User entity. -func (m *UserAllowedGroupMutation) ClearUser() { - m.cleareduser = true - m.clearedFields[userallowedgroup.FieldUserID] = struct{}{} +// ResetDescription resets all changes to the "description" field. +func (m *UserAttributeDefinitionMutation) ResetDescription() { + m.description = nil } -// UserCleared reports if the "user" edge to the User entity was cleared. -func (m *UserAllowedGroupMutation) UserCleared() bool { - return m.cleareduser +// SetType sets the "type" field. +func (m *UserAttributeDefinitionMutation) SetType(s string) { + m._type = &s } -// UserIDs returns the "user" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// UserID instead. It exists only for internal usage by the builders. -func (m *UserAllowedGroupMutation) UserIDs() (ids []int64) { - if id := m.user; id != nil { - ids = append(ids, *id) +// GetType returns the value of the "type" field in the mutation. +func (m *UserAttributeDefinitionMutation) GetType() (r string, exists bool) { + v := m._type + if v == nil { + return } - return + return *v, true } -// ResetUser resets all changes to the "user" edge. -func (m *UserAllowedGroupMutation) ResetUser() { - m.user = nil - m.cleareduser = false +// OldType returns the old "type" field's value of the UserAttributeDefinition entity. +// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserAttributeDefinitionMutation) OldType(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldType: %w", err) + } + return oldValue.Type, nil } -// ClearGroup clears the "group" edge to the Group entity. -func (m *UserAllowedGroupMutation) ClearGroup() { - m.clearedgroup = true - m.clearedFields[userallowedgroup.FieldGroupID] = struct{}{} +// ResetType resets all changes to the "type" field. +func (m *UserAttributeDefinitionMutation) ResetType() { + m._type = nil } -// GroupCleared reports if the "group" edge to the Group entity was cleared. -func (m *UserAllowedGroupMutation) GroupCleared() bool { - return m.clearedgroup +// SetOptions sets the "options" field. +func (m *UserAttributeDefinitionMutation) SetOptions(value []map[string]interface{}) { + m.options = &value + m.appendoptions = nil } -// GroupIDs returns the "group" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// GroupID instead. It exists only for internal usage by the builders. -func (m *UserAllowedGroupMutation) GroupIDs() (ids []int64) { - if id := m.group; id != nil { - ids = append(ids, *id) +// Options returns the value of the "options" field in the mutation. +func (m *UserAttributeDefinitionMutation) Options() (r []map[string]interface{}, exists bool) { + v := m.options + if v == nil { + return } - return + return *v, true } -// ResetGroup resets all changes to the "group" edge. -func (m *UserAllowedGroupMutation) ResetGroup() { - m.group = nil - m.clearedgroup = false +// OldOptions returns the old "options" field's value of the UserAttributeDefinition entity. +// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserAttributeDefinitionMutation) OldOptions(ctx context.Context) (v []map[string]interface{}, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldOptions is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldOptions requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldOptions: %w", err) + } + return oldValue.Options, nil } -// Where appends a list predicates to the UserAllowedGroupMutation builder. -func (m *UserAllowedGroupMutation) Where(ps ...predicate.UserAllowedGroup) { - m.predicates = append(m.predicates, ps...) +// AppendOptions adds value to the "options" field. +func (m *UserAttributeDefinitionMutation) AppendOptions(value []map[string]interface{}) { + m.appendoptions = append(m.appendoptions, value...) } -// WhereP appends storage-level predicates to the UserAllowedGroupMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *UserAllowedGroupMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.UserAllowedGroup, len(ps)) - for i := range ps { - p[i] = ps[i] +// AppendedOptions returns the list of values that were appended to the "options" field in this mutation. +func (m *UserAttributeDefinitionMutation) AppendedOptions() ([]map[string]interface{}, bool) { + if len(m.appendoptions) == 0 { + return nil, false } - m.Where(p...) + return m.appendoptions, true } -// Op returns the operation name. -func (m *UserAllowedGroupMutation) Op() Op { - return m.op +// ResetOptions resets all changes to the "options" field. +func (m *UserAttributeDefinitionMutation) ResetOptions() { + m.options = nil + m.appendoptions = nil } -// SetOp allows setting the mutation operation. -func (m *UserAllowedGroupMutation) SetOp(op Op) { - m.op = op +// SetRequired sets the "required" field. +func (m *UserAttributeDefinitionMutation) SetRequired(b bool) { + m.required = &b } -// Type returns the node type of this mutation (UserAllowedGroup). -func (m *UserAllowedGroupMutation) Type() string { - return m.typ +// Required returns the value of the "required" field in the mutation. +func (m *UserAttributeDefinitionMutation) Required() (r bool, exists bool) { + v := m.required + if v == nil { + return + } + return *v, true } -// Fields returns all fields that were changed during this mutation. Note that in -// order to get all numeric fields that were incremented/decremented, call -// AddedFields(). -func (m *UserAllowedGroupMutation) Fields() []string { - fields := make([]string, 0, 3) - if m.user != nil { - fields = append(fields, userallowedgroup.FieldUserID) +// OldRequired returns the old "required" field's value of the UserAttributeDefinition entity. +// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserAttributeDefinitionMutation) OldRequired(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRequired is only allowed on UpdateOne operations") } - if m.group != nil { - fields = append(fields, userallowedgroup.FieldGroupID) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRequired requires an ID field in the mutation") } - if m.created_at != nil { - fields = append(fields, userallowedgroup.FieldCreatedAt) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRequired: %w", err) } - return fields + return oldValue.Required, nil } -// Field returns the value of a field with the given name. The second boolean -// return value indicates that this field was not set, or was not defined in the -// schema. -func (m *UserAllowedGroupMutation) Field(name string) (ent.Value, bool) { - switch name { - case userallowedgroup.FieldUserID: - return m.UserID() - case userallowedgroup.FieldGroupID: - return m.GroupID() - case userallowedgroup.FieldCreatedAt: - return m.CreatedAt() - } - return nil, false +// ResetRequired resets all changes to the "required" field. +func (m *UserAttributeDefinitionMutation) ResetRequired() { + m.required = nil } -// OldField returns the old value of the field from the database. An error is -// returned if the mutation operation is not UpdateOne, or the query to the -// database failed. -func (m *UserAllowedGroupMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - return nil, errors.New("edge schema UserAllowedGroup does not support getting old values") +// SetValidation sets the "validation" field. +func (m *UserAttributeDefinitionMutation) SetValidation(value map[string]interface{}) { + m.validation = &value } -// SetField sets the value of a field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *UserAllowedGroupMutation) SetField(name string, value ent.Value) error { - switch name { - case userallowedgroup.FieldUserID: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUserID(v) - return nil - case userallowedgroup.FieldGroupID: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetGroupID(v) - return nil - case userallowedgroup.FieldCreatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCreatedAt(v) - return nil +// Validation returns the value of the "validation" field in the mutation. +func (m *UserAttributeDefinitionMutation) Validation() (r map[string]interface{}, exists bool) { + v := m.validation + if v == nil { + return } - return fmt.Errorf("unknown UserAllowedGroup field %s", name) + return *v, true } -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *UserAllowedGroupMutation) AddedFields() []string { - var fields []string - return fields +// OldValidation returns the old "validation" field's value of the UserAttributeDefinition entity. +// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserAttributeDefinitionMutation) OldValidation(ctx context.Context) (v map[string]interface{}, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldValidation is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldValidation requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldValidation: %w", err) + } + return oldValue.Validation, nil } -// AddedField returns the numeric value that was incremented/decremented on a field -// with the given name. The second boolean return value indicates that this field -// was not set, or was not defined in the schema. -func (m *UserAllowedGroupMutation) AddedField(name string) (ent.Value, bool) { - switch name { - } - return nil, false +// ResetValidation resets all changes to the "validation" field. +func (m *UserAttributeDefinitionMutation) ResetValidation() { + m.validation = nil } -// AddField adds the value to the field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *UserAllowedGroupMutation) AddField(name string, value ent.Value) error { - switch name { +// SetPlaceholder sets the "placeholder" field. +func (m *UserAttributeDefinitionMutation) SetPlaceholder(s string) { + m.placeholder = &s +} + +// Placeholder returns the value of the "placeholder" field in the mutation. +func (m *UserAttributeDefinitionMutation) Placeholder() (r string, exists bool) { + v := m.placeholder + if v == nil { + return } - return fmt.Errorf("unknown UserAllowedGroup numeric field %s", name) + return *v, true } -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *UserAllowedGroupMutation) ClearedFields() []string { - return nil +// OldPlaceholder returns the old "placeholder" field's value of the UserAttributeDefinition entity. +// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserAttributeDefinitionMutation) OldPlaceholder(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPlaceholder is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPlaceholder requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPlaceholder: %w", err) + } + return oldValue.Placeholder, nil } -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *UserAllowedGroupMutation) FieldCleared(name string) bool { - _, ok := m.clearedFields[name] - return ok +// ResetPlaceholder resets all changes to the "placeholder" field. +func (m *UserAttributeDefinitionMutation) ResetPlaceholder() { + m.placeholder = nil } -// ClearField clears the value of the field with the given name. It returns an -// error if the field is not defined in the schema. -func (m *UserAllowedGroupMutation) ClearField(name string) error { - return fmt.Errorf("unknown UserAllowedGroup nullable field %s", name) +// SetDisplayOrder sets the "display_order" field. +func (m *UserAttributeDefinitionMutation) SetDisplayOrder(i int) { + m.display_order = &i + m.adddisplay_order = nil } -// ResetField resets all changes in the mutation for the field with the given name. -// It returns an error if the field is not defined in the schema. -func (m *UserAllowedGroupMutation) ResetField(name string) error { - switch name { - case userallowedgroup.FieldUserID: - m.ResetUserID() - return nil - case userallowedgroup.FieldGroupID: - m.ResetGroupID() - return nil - case userallowedgroup.FieldCreatedAt: - m.ResetCreatedAt() - return nil +// DisplayOrder returns the value of the "display_order" field in the mutation. +func (m *UserAttributeDefinitionMutation) DisplayOrder() (r int, exists bool) { + v := m.display_order + if v == nil { + return } - return fmt.Errorf("unknown UserAllowedGroup field %s", name) + return *v, true } -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *UserAllowedGroupMutation) AddedEdges() []string { - edges := make([]string, 0, 2) - if m.user != nil { - edges = append(edges, userallowedgroup.EdgeUser) +// OldDisplayOrder returns the old "display_order" field's value of the UserAttributeDefinition entity. +// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserAttributeDefinitionMutation) OldDisplayOrder(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDisplayOrder is only allowed on UpdateOne operations") } - if m.group != nil { - edges = append(edges, userallowedgroup.EdgeGroup) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDisplayOrder requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDisplayOrder: %w", err) + } + return oldValue.DisplayOrder, nil +} + +// AddDisplayOrder adds i to the "display_order" field. +func (m *UserAttributeDefinitionMutation) AddDisplayOrder(i int) { + if m.adddisplay_order != nil { + *m.adddisplay_order += i + } else { + m.adddisplay_order = &i } - return edges } -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *UserAllowedGroupMutation) AddedIDs(name string) []ent.Value { - switch name { - case userallowedgroup.EdgeUser: - if id := m.user; id != nil { - return []ent.Value{*id} - } - case userallowedgroup.EdgeGroup: - if id := m.group; id != nil { - return []ent.Value{*id} - } +// AddedDisplayOrder returns the value that was added to the "display_order" field in this mutation. +func (m *UserAttributeDefinitionMutation) AddedDisplayOrder() (r int, exists bool) { + v := m.adddisplay_order + if v == nil { + return } - return nil + return *v, true } -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *UserAllowedGroupMutation) RemovedEdges() []string { - edges := make([]string, 0, 2) - return edges +// ResetDisplayOrder resets all changes to the "display_order" field. +func (m *UserAttributeDefinitionMutation) ResetDisplayOrder() { + m.display_order = nil + m.adddisplay_order = nil } -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *UserAllowedGroupMutation) RemovedIDs(name string) []ent.Value { - return nil +// SetEnabled sets the "enabled" field. +func (m *UserAttributeDefinitionMutation) SetEnabled(b bool) { + m.enabled = &b } -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *UserAllowedGroupMutation) ClearedEdges() []string { - edges := make([]string, 0, 2) - if m.cleareduser { - edges = append(edges, userallowedgroup.EdgeUser) - } - if m.clearedgroup { - edges = append(edges, userallowedgroup.EdgeGroup) +// Enabled returns the value of the "enabled" field in the mutation. +func (m *UserAttributeDefinitionMutation) Enabled() (r bool, exists bool) { + v := m.enabled + if v == nil { + return } - return edges + return *v, true } -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *UserAllowedGroupMutation) EdgeCleared(name string) bool { - switch name { - case userallowedgroup.EdgeUser: - return m.cleareduser - case userallowedgroup.EdgeGroup: - return m.clearedgroup +// OldEnabled returns the old "enabled" field's value of the UserAttributeDefinition entity. +// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserAttributeDefinitionMutation) OldEnabled(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEnabled is only allowed on UpdateOne operations") } - return false + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEnabled requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEnabled: %w", err) + } + return oldValue.Enabled, nil } -// ClearEdge clears the value of the edge with the given name. It returns an error -// if that edge is not defined in the schema. -func (m *UserAllowedGroupMutation) ClearEdge(name string) error { - switch name { - case userallowedgroup.EdgeUser: - m.ClearUser() - return nil - case userallowedgroup.EdgeGroup: - m.ClearGroup() - return nil - } - return fmt.Errorf("unknown UserAllowedGroup unique edge %s", name) +// ResetEnabled resets all changes to the "enabled" field. +func (m *UserAttributeDefinitionMutation) ResetEnabled() { + m.enabled = nil } -// ResetEdge resets all changes to the edge with the given name in this mutation. -// It returns an error if the edge is not defined in the schema. -func (m *UserAllowedGroupMutation) ResetEdge(name string) error { - switch name { - case userallowedgroup.EdgeUser: - m.ResetUser() - return nil - case userallowedgroup.EdgeGroup: - m.ResetGroup() - return nil +// AddValueIDs adds the "values" edge to the UserAttributeValue entity by ids. +func (m *UserAttributeDefinitionMutation) AddValueIDs(ids ...int64) { + if m.values == nil { + m.values = make(map[int64]struct{}) + } + for i := range ids { + m.values[ids[i]] = struct{}{} } - return fmt.Errorf("unknown UserAllowedGroup edge %s", name) } -// UserAttributeDefinitionMutation represents an operation that mutates the UserAttributeDefinition nodes in the graph. -type UserAttributeDefinitionMutation struct { - config - op Op - typ string - id *int64 - created_at *time.Time - updated_at *time.Time - deleted_at *time.Time - key *string - name *string - description *string - _type *string - options *[]map[string]interface{} - appendoptions []map[string]interface{} - required *bool - validation *map[string]interface{} - placeholder *string - display_order *int - adddisplay_order *int - enabled *bool - clearedFields map[string]struct{} - values map[int64]struct{} - removedvalues map[int64]struct{} - clearedvalues bool - done bool - oldValue func(context.Context) (*UserAttributeDefinition, error) - predicates []predicate.UserAttributeDefinition +// ClearValues clears the "values" edge to the UserAttributeValue entity. +func (m *UserAttributeDefinitionMutation) ClearValues() { + m.clearedvalues = true } -var _ ent.Mutation = (*UserAttributeDefinitionMutation)(nil) - -// userattributedefinitionOption allows management of the mutation configuration using functional options. -type userattributedefinitionOption func(*UserAttributeDefinitionMutation) +// ValuesCleared reports if the "values" edge to the UserAttributeValue entity was cleared. +func (m *UserAttributeDefinitionMutation) ValuesCleared() bool { + return m.clearedvalues +} -// newUserAttributeDefinitionMutation creates new mutation for the UserAttributeDefinition entity. -func newUserAttributeDefinitionMutation(c config, op Op, opts ...userattributedefinitionOption) *UserAttributeDefinitionMutation { - m := &UserAttributeDefinitionMutation{ - config: c, - op: op, - typ: TypeUserAttributeDefinition, - clearedFields: make(map[string]struct{}), +// RemoveValueIDs removes the "values" edge to the UserAttributeValue entity by IDs. +func (m *UserAttributeDefinitionMutation) RemoveValueIDs(ids ...int64) { + if m.removedvalues == nil { + m.removedvalues = make(map[int64]struct{}) } - for _, opt := range opts { - opt(m) + for i := range ids { + delete(m.values, ids[i]) + m.removedvalues[ids[i]] = struct{}{} } - return m } -// withUserAttributeDefinitionID sets the ID field of the mutation. -func withUserAttributeDefinitionID(id int64) userattributedefinitionOption { - return func(m *UserAttributeDefinitionMutation) { - var ( - err error - once sync.Once - value *UserAttributeDefinition - ) - m.oldValue = func(ctx context.Context) (*UserAttributeDefinition, error) { - once.Do(func() { - if m.done { - err = errors.New("querying old values post mutation is not allowed") - } else { - value, err = m.Client().UserAttributeDefinition.Get(ctx, id) - } - }) - return value, err - } - m.id = &id +// RemovedValues returns the removed IDs of the "values" edge to the UserAttributeValue entity. +func (m *UserAttributeDefinitionMutation) RemovedValuesIDs() (ids []int64) { + for id := range m.removedvalues { + ids = append(ids, id) } + return } -// withUserAttributeDefinition sets the old UserAttributeDefinition of the mutation. -func withUserAttributeDefinition(node *UserAttributeDefinition) userattributedefinitionOption { - return func(m *UserAttributeDefinitionMutation) { - m.oldValue = func(context.Context) (*UserAttributeDefinition, error) { - return node, nil - } - m.id = &node.ID +// ValuesIDs returns the "values" edge IDs in the mutation. +func (m *UserAttributeDefinitionMutation) ValuesIDs() (ids []int64) { + for id := range m.values { + ids = append(ids, id) } + return } -// Client returns a new `ent.Client` from the mutation. If the mutation was -// executed in a transaction (ent.Tx), a transactional client is returned. -func (m UserAttributeDefinitionMutation) Client() *Client { - client := &Client{config: m.config} - client.init() - return client +// ResetValues resets all changes to the "values" edge. +func (m *UserAttributeDefinitionMutation) ResetValues() { + m.values = nil + m.clearedvalues = false + m.removedvalues = nil } -// Tx returns an `ent.Tx` for mutations that were executed in transactions; -// it returns an error otherwise. -func (m UserAttributeDefinitionMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, errors.New("ent: mutation is not running in a transaction") - } - tx := &Tx{config: m.config} - tx.init() - return tx, nil +// Where appends a list predicates to the UserAttributeDefinitionMutation builder. +func (m *UserAttributeDefinitionMutation) Where(ps ...predicate.UserAttributeDefinition) { + m.predicates = append(m.predicates, ps...) } -// ID returns the ID value in the mutation. Note that the ID is only available -// if it was provided to the builder or after it was returned from the database. -func (m *UserAttributeDefinitionMutation) ID() (id int64, exists bool) { - if m.id == nil { - return +// WhereP appends storage-level predicates to the UserAttributeDefinitionMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *UserAttributeDefinitionMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.UserAttributeDefinition, len(ps)) + for i := range ps { + p[i] = ps[i] } - return *m.id, true + m.Where(p...) } -// IDs queries the database and returns the entity ids that match the mutation's predicate. -// That means, if the mutation is applied within a transaction with an isolation level such -// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated -// or updated by the mutation. -func (m *UserAttributeDefinitionMutation) IDs(ctx context.Context) ([]int64, error) { - switch { - case m.op.Is(OpUpdateOne | OpDeleteOne): - id, exists := m.ID() - if exists { - return []int64{id}, nil - } - fallthrough - case m.op.Is(OpUpdate | OpDelete): - return m.Client().UserAttributeDefinition.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) - } +// Op returns the operation name. +func (m *UserAttributeDefinitionMutation) Op() Op { + return m.op } -// SetCreatedAt sets the "created_at" field. -func (m *UserAttributeDefinitionMutation) SetCreatedAt(t time.Time) { - m.created_at = &t +// SetOp allows setting the mutation operation. +func (m *UserAttributeDefinitionMutation) SetOp(op Op) { + m.op = op } -// CreatedAt returns the value of the "created_at" field in the mutation. -func (m *UserAttributeDefinitionMutation) CreatedAt() (r time.Time, exists bool) { - v := m.created_at - if v == nil { - return - } - return *v, true +// Type returns the node type of this mutation (UserAttributeDefinition). +func (m *UserAttributeDefinitionMutation) Type() string { + return m.typ } -// OldCreatedAt returns the old "created_at" field's value of the UserAttributeDefinition entity. -// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserAttributeDefinitionMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *UserAttributeDefinitionMutation) Fields() []string { + fields := make([]string, 0, 13) + if m.created_at != nil { + fields = append(fields, userattributedefinition.FieldCreatedAt) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCreatedAt requires an ID field in the mutation") + if m.updated_at != nil { + fields = append(fields, userattributedefinition.FieldUpdatedAt) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + if m.deleted_at != nil { + fields = append(fields, userattributedefinition.FieldDeletedAt) } - return oldValue.CreatedAt, nil -} - -// ResetCreatedAt resets all changes to the "created_at" field. -func (m *UserAttributeDefinitionMutation) ResetCreatedAt() { - m.created_at = nil + if m.key != nil { + fields = append(fields, userattributedefinition.FieldKey) + } + if m.name != nil { + fields = append(fields, userattributedefinition.FieldName) + } + if m.description != nil { + fields = append(fields, userattributedefinition.FieldDescription) + } + if m._type != nil { + fields = append(fields, userattributedefinition.FieldType) + } + if m.options != nil { + fields = append(fields, userattributedefinition.FieldOptions) + } + if m.required != nil { + fields = append(fields, userattributedefinition.FieldRequired) + } + if m.validation != nil { + fields = append(fields, userattributedefinition.FieldValidation) + } + if m.placeholder != nil { + fields = append(fields, userattributedefinition.FieldPlaceholder) + } + if m.display_order != nil { + fields = append(fields, userattributedefinition.FieldDisplayOrder) + } + if m.enabled != nil { + fields = append(fields, userattributedefinition.FieldEnabled) + } + return fields } -// SetUpdatedAt sets the "updated_at" field. -func (m *UserAttributeDefinitionMutation) SetUpdatedAt(t time.Time) { - m.updated_at = &t +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *UserAttributeDefinitionMutation) Field(name string) (ent.Value, bool) { + switch name { + case userattributedefinition.FieldCreatedAt: + return m.CreatedAt() + case userattributedefinition.FieldUpdatedAt: + return m.UpdatedAt() + case userattributedefinition.FieldDeletedAt: + return m.DeletedAt() + case userattributedefinition.FieldKey: + return m.Key() + case userattributedefinition.FieldName: + return m.Name() + case userattributedefinition.FieldDescription: + return m.Description() + case userattributedefinition.FieldType: + return m.GetType() + case userattributedefinition.FieldOptions: + return m.Options() + case userattributedefinition.FieldRequired: + return m.Required() + case userattributedefinition.FieldValidation: + return m.Validation() + case userattributedefinition.FieldPlaceholder: + return m.Placeholder() + case userattributedefinition.FieldDisplayOrder: + return m.DisplayOrder() + case userattributedefinition.FieldEnabled: + return m.Enabled() + } + return nil, false } -// UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *UserAttributeDefinitionMutation) UpdatedAt() (r time.Time, exists bool) { - v := m.updated_at - if v == nil { - return +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *UserAttributeDefinitionMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case userattributedefinition.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case userattributedefinition.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case userattributedefinition.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case userattributedefinition.FieldKey: + return m.OldKey(ctx) + case userattributedefinition.FieldName: + return m.OldName(ctx) + case userattributedefinition.FieldDescription: + return m.OldDescription(ctx) + case userattributedefinition.FieldType: + return m.OldType(ctx) + case userattributedefinition.FieldOptions: + return m.OldOptions(ctx) + case userattributedefinition.FieldRequired: + return m.OldRequired(ctx) + case userattributedefinition.FieldValidation: + return m.OldValidation(ctx) + case userattributedefinition.FieldPlaceholder: + return m.OldPlaceholder(ctx) + case userattributedefinition.FieldDisplayOrder: + return m.OldDisplayOrder(ctx) + case userattributedefinition.FieldEnabled: + return m.OldEnabled(ctx) } - return *v, true + return nil, fmt.Errorf("unknown UserAttributeDefinition field %s", name) } -// OldUpdatedAt returns the old "updated_at" field's value of the UserAttributeDefinition entity. -// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserAttributeDefinitionMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUpdatedAt requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *UserAttributeDefinitionMutation) SetField(name string, value ent.Value) error { + switch name { + case userattributedefinition.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case userattributedefinition.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + case userattributedefinition.FieldDeletedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeletedAt(v) + return nil + case userattributedefinition.FieldKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetKey(v) + return nil + case userattributedefinition.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case userattributedefinition.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case userattributedefinition.FieldType: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetType(v) + return nil + case userattributedefinition.FieldOptions: + v, ok := value.([]map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOptions(v) + return nil + case userattributedefinition.FieldRequired: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRequired(v) + return nil + case userattributedefinition.FieldValidation: + v, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetValidation(v) + return nil + case userattributedefinition.FieldPlaceholder: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPlaceholder(v) + return nil + case userattributedefinition.FieldDisplayOrder: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDisplayOrder(v) + return nil + case userattributedefinition.FieldEnabled: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEnabled(v) + return nil } - return oldValue.UpdatedAt, nil -} - -// ResetUpdatedAt resets all changes to the "updated_at" field. -func (m *UserAttributeDefinitionMutation) ResetUpdatedAt() { - m.updated_at = nil + return fmt.Errorf("unknown UserAttributeDefinition field %s", name) } -// SetDeletedAt sets the "deleted_at" field. -func (m *UserAttributeDefinitionMutation) SetDeletedAt(t time.Time) { - m.deleted_at = &t +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *UserAttributeDefinitionMutation) AddedFields() []string { + var fields []string + if m.adddisplay_order != nil { + fields = append(fields, userattributedefinition.FieldDisplayOrder) + } + return fields } -// DeletedAt returns the value of the "deleted_at" field in the mutation. -func (m *UserAttributeDefinitionMutation) DeletedAt() (r time.Time, exists bool) { - v := m.deleted_at - if v == nil { - return +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *UserAttributeDefinitionMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case userattributedefinition.FieldDisplayOrder: + return m.AddedDisplayOrder() } - return *v, true + return nil, false } -// OldDeletedAt returns the old "deleted_at" field's value of the UserAttributeDefinition entity. -// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserAttributeDefinitionMutation) OldDeletedAt(ctx context.Context) (v *time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldDeletedAt is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldDeletedAt requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldDeletedAt: %w", err) +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *UserAttributeDefinitionMutation) AddField(name string, value ent.Value) error { + switch name { + case userattributedefinition.FieldDisplayOrder: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddDisplayOrder(v) + return nil } - return oldValue.DeletedAt, nil + return fmt.Errorf("unknown UserAttributeDefinition numeric field %s", name) } -// ClearDeletedAt clears the value of the "deleted_at" field. -func (m *UserAttributeDefinitionMutation) ClearDeletedAt() { - m.deleted_at = nil - m.clearedFields[userattributedefinition.FieldDeletedAt] = struct{}{} +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *UserAttributeDefinitionMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(userattributedefinition.FieldDeletedAt) { + fields = append(fields, userattributedefinition.FieldDeletedAt) + } + return fields } -// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. -func (m *UserAttributeDefinitionMutation) DeletedAtCleared() bool { - _, ok := m.clearedFields[userattributedefinition.FieldDeletedAt] +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *UserAttributeDefinitionMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] return ok } -// ResetDeletedAt resets all changes to the "deleted_at" field. -func (m *UserAttributeDefinitionMutation) ResetDeletedAt() { - m.deleted_at = nil - delete(m.clearedFields, userattributedefinition.FieldDeletedAt) -} - -// SetKey sets the "key" field. -func (m *UserAttributeDefinitionMutation) SetKey(s string) { - m.key = &s -} - -// Key returns the value of the "key" field in the mutation. -func (m *UserAttributeDefinitionMutation) Key() (r string, exists bool) { - v := m.key - if v == nil { - return +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *UserAttributeDefinitionMutation) ClearField(name string) error { + switch name { + case userattributedefinition.FieldDeletedAt: + m.ClearDeletedAt() + return nil } - return *v, true + return fmt.Errorf("unknown UserAttributeDefinition nullable field %s", name) } -// OldKey returns the old "key" field's value of the UserAttributeDefinition entity. -// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserAttributeDefinitionMutation) OldKey(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldKey is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldKey requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldKey: %w", err) +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *UserAttributeDefinitionMutation) ResetField(name string) error { + switch name { + case userattributedefinition.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case userattributedefinition.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case userattributedefinition.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case userattributedefinition.FieldKey: + m.ResetKey() + return nil + case userattributedefinition.FieldName: + m.ResetName() + return nil + case userattributedefinition.FieldDescription: + m.ResetDescription() + return nil + case userattributedefinition.FieldType: + m.ResetType() + return nil + case userattributedefinition.FieldOptions: + m.ResetOptions() + return nil + case userattributedefinition.FieldRequired: + m.ResetRequired() + return nil + case userattributedefinition.FieldValidation: + m.ResetValidation() + return nil + case userattributedefinition.FieldPlaceholder: + m.ResetPlaceholder() + return nil + case userattributedefinition.FieldDisplayOrder: + m.ResetDisplayOrder() + return nil + case userattributedefinition.FieldEnabled: + m.ResetEnabled() + return nil } - return oldValue.Key, nil -} - -// ResetKey resets all changes to the "key" field. -func (m *UserAttributeDefinitionMutation) ResetKey() { - m.key = nil -} - -// SetName sets the "name" field. -func (m *UserAttributeDefinitionMutation) SetName(s string) { - m.name = &s + return fmt.Errorf("unknown UserAttributeDefinition field %s", name) } -// Name returns the value of the "name" field in the mutation. -func (m *UserAttributeDefinitionMutation) Name() (r string, exists bool) { - v := m.name - if v == nil { - return +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *UserAttributeDefinitionMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.values != nil { + edges = append(edges, userattributedefinition.EdgeValues) } - return *v, true + return edges } -// OldName returns the old "name" field's value of the UserAttributeDefinition entity. -// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserAttributeDefinitionMutation) OldName(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldName is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldName requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldName: %w", err) +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *UserAttributeDefinitionMutation) AddedIDs(name string) []ent.Value { + switch name { + case userattributedefinition.EdgeValues: + ids := make([]ent.Value, 0, len(m.values)) + for id := range m.values { + ids = append(ids, id) + } + return ids } - return oldValue.Name, nil -} - -// ResetName resets all changes to the "name" field. -func (m *UserAttributeDefinitionMutation) ResetName() { - m.name = nil -} - -// SetDescription sets the "description" field. -func (m *UserAttributeDefinitionMutation) SetDescription(s string) { - m.description = &s + return nil } -// Description returns the value of the "description" field in the mutation. -func (m *UserAttributeDefinitionMutation) Description() (r string, exists bool) { - v := m.description - if v == nil { - return +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *UserAttributeDefinitionMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + if m.removedvalues != nil { + edges = append(edges, userattributedefinition.EdgeValues) } - return *v, true + return edges } -// OldDescription returns the old "description" field's value of the UserAttributeDefinition entity. -// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserAttributeDefinitionMutation) OldDescription(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldDescription is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldDescription requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldDescription: %w", err) +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *UserAttributeDefinitionMutation) RemovedIDs(name string) []ent.Value { + switch name { + case userattributedefinition.EdgeValues: + ids := make([]ent.Value, 0, len(m.removedvalues)) + for id := range m.removedvalues { + ids = append(ids, id) + } + return ids } - return oldValue.Description, nil + return nil } -// ResetDescription resets all changes to the "description" field. -func (m *UserAttributeDefinitionMutation) ResetDescription() { - m.description = nil +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *UserAttributeDefinitionMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedvalues { + edges = append(edges, userattributedefinition.EdgeValues) + } + return edges } -// SetType sets the "type" field. -func (m *UserAttributeDefinitionMutation) SetType(s string) { - m._type = &s +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *UserAttributeDefinitionMutation) EdgeCleared(name string) bool { + switch name { + case userattributedefinition.EdgeValues: + return m.clearedvalues + } + return false } -// GetType returns the value of the "type" field in the mutation. -func (m *UserAttributeDefinitionMutation) GetType() (r string, exists bool) { - v := m._type - if v == nil { - return +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *UserAttributeDefinitionMutation) ClearEdge(name string) error { + switch name { } - return *v, true + return fmt.Errorf("unknown UserAttributeDefinition unique edge %s", name) } -// OldType returns the old "type" field's value of the UserAttributeDefinition entity. -// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserAttributeDefinitionMutation) OldType(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldType is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldType requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldType: %w", err) +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *UserAttributeDefinitionMutation) ResetEdge(name string) error { + switch name { + case userattributedefinition.EdgeValues: + m.ResetValues() + return nil } - return oldValue.Type, nil + return fmt.Errorf("unknown UserAttributeDefinition edge %s", name) } -// ResetType resets all changes to the "type" field. -func (m *UserAttributeDefinitionMutation) ResetType() { - m._type = nil +// UserAttributeValueMutation represents an operation that mutates the UserAttributeValue nodes in the graph. +type UserAttributeValueMutation struct { + config + op Op + typ string + id *int64 + created_at *time.Time + updated_at *time.Time + value *string + clearedFields map[string]struct{} + user *int64 + cleareduser bool + definition *int64 + cleareddefinition bool + done bool + oldValue func(context.Context) (*UserAttributeValue, error) + predicates []predicate.UserAttributeValue } -// SetOptions sets the "options" field. -func (m *UserAttributeDefinitionMutation) SetOptions(value []map[string]interface{}) { - m.options = &value - m.appendoptions = nil -} +var _ ent.Mutation = (*UserAttributeValueMutation)(nil) -// Options returns the value of the "options" field in the mutation. -func (m *UserAttributeDefinitionMutation) Options() (r []map[string]interface{}, exists bool) { - v := m.options - if v == nil { - return +// userattributevalueOption allows management of the mutation configuration using functional options. +type userattributevalueOption func(*UserAttributeValueMutation) + +// newUserAttributeValueMutation creates new mutation for the UserAttributeValue entity. +func newUserAttributeValueMutation(c config, op Op, opts ...userattributevalueOption) *UserAttributeValueMutation { + m := &UserAttributeValueMutation{ + config: c, + op: op, + typ: TypeUserAttributeValue, + clearedFields: make(map[string]struct{}), } - return *v, true + for _, opt := range opts { + opt(m) + } + return m } -// OldOptions returns the old "options" field's value of the UserAttributeDefinition entity. -// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserAttributeDefinitionMutation) OldOptions(ctx context.Context) (v []map[string]interface{}, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldOptions is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldOptions requires an ID field in the mutation") +// withUserAttributeValueID sets the ID field of the mutation. +func withUserAttributeValueID(id int64) userattributevalueOption { + return func(m *UserAttributeValueMutation) { + var ( + err error + once sync.Once + value *UserAttributeValue + ) + m.oldValue = func(ctx context.Context) (*UserAttributeValue, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().UserAttributeValue.Get(ctx, id) + } + }) + return value, err + } + m.id = &id } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldOptions: %w", err) +} + +// withUserAttributeValue sets the old UserAttributeValue of the mutation. +func withUserAttributeValue(node *UserAttributeValue) userattributevalueOption { + return func(m *UserAttributeValueMutation) { + m.oldValue = func(context.Context) (*UserAttributeValue, error) { + return node, nil + } + m.id = &node.ID } - return oldValue.Options, nil } -// AppendOptions adds value to the "options" field. -func (m *UserAttributeDefinitionMutation) AppendOptions(value []map[string]interface{}) { - m.appendoptions = append(m.appendoptions, value...) +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m UserAttributeValueMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client } -// AppendedOptions returns the list of values that were appended to the "options" field in this mutation. -func (m *UserAttributeDefinitionMutation) AppendedOptions() ([]map[string]interface{}, bool) { - if len(m.appendoptions) == 0 { - return nil, false +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m UserAttributeValueMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") } - return m.appendoptions, true + tx := &Tx{config: m.config} + tx.init() + return tx, nil } -// ResetOptions resets all changes to the "options" field. -func (m *UserAttributeDefinitionMutation) ResetOptions() { - m.options = nil - m.appendoptions = nil +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *UserAttributeValueMutation) ID() (id int64, exists bool) { + if m.id == nil { + return + } + return *m.id, true } -// SetRequired sets the "required" field. -func (m *UserAttributeDefinitionMutation) SetRequired(b bool) { - m.required = &b +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *UserAttributeValueMutation) IDs(ctx context.Context) ([]int64, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int64{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().UserAttributeValue.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } } -// Required returns the value of the "required" field in the mutation. -func (m *UserAttributeDefinitionMutation) Required() (r bool, exists bool) { - v := m.required +// SetCreatedAt sets the "created_at" field. +func (m *UserAttributeValueMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *UserAttributeValueMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at if v == nil { return } return *v, true } -// OldRequired returns the old "required" field's value of the UserAttributeDefinition entity. -// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database. +// OldCreatedAt returns the old "created_at" field's value of the UserAttributeValue entity. +// If the UserAttributeValue object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserAttributeDefinitionMutation) OldRequired(ctx context.Context) (v bool, err error) { +func (m *UserAttributeValueMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldRequired is only allowed on UpdateOne operations") + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldRequired requires an ID field in the mutation") + return v, errors.New("OldCreatedAt requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldRequired: %w", err) + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) } - return oldValue.Required, nil + return oldValue.CreatedAt, nil } -// ResetRequired resets all changes to the "required" field. -func (m *UserAttributeDefinitionMutation) ResetRequired() { - m.required = nil +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *UserAttributeValueMutation) ResetCreatedAt() { + m.created_at = nil } -// SetValidation sets the "validation" field. -func (m *UserAttributeDefinitionMutation) SetValidation(value map[string]interface{}) { - m.validation = &value +// SetUpdatedAt sets the "updated_at" field. +func (m *UserAttributeValueMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t } -// Validation returns the value of the "validation" field in the mutation. -func (m *UserAttributeDefinitionMutation) Validation() (r map[string]interface{}, exists bool) { - v := m.validation +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *UserAttributeValueMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at if v == nil { return } return *v, true } -// OldValidation returns the old "validation" field's value of the UserAttributeDefinition entity. -// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database. +// OldUpdatedAt returns the old "updated_at" field's value of the UserAttributeValue entity. +// If the UserAttributeValue object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserAttributeDefinitionMutation) OldValidation(ctx context.Context) (v map[string]interface{}, err error) { +func (m *UserAttributeValueMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldValidation is only allowed on UpdateOne operations") + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldValidation requires an ID field in the mutation") + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldValidation: %w", err) + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) } - return oldValue.Validation, nil + return oldValue.UpdatedAt, nil } - -// ResetValidation resets all changes to the "validation" field. -func (m *UserAttributeDefinitionMutation) ResetValidation() { - m.validation = nil + +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *UserAttributeValueMutation) ResetUpdatedAt() { + m.updated_at = nil } -// SetPlaceholder sets the "placeholder" field. -func (m *UserAttributeDefinitionMutation) SetPlaceholder(s string) { - m.placeholder = &s +// SetUserID sets the "user_id" field. +func (m *UserAttributeValueMutation) SetUserID(i int64) { + m.user = &i } -// Placeholder returns the value of the "placeholder" field in the mutation. -func (m *UserAttributeDefinitionMutation) Placeholder() (r string, exists bool) { - v := m.placeholder +// UserID returns the value of the "user_id" field in the mutation. +func (m *UserAttributeValueMutation) UserID() (r int64, exists bool) { + v := m.user if v == nil { return } return *v, true } -// OldPlaceholder returns the old "placeholder" field's value of the UserAttributeDefinition entity. -// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database. +// OldUserID returns the old "user_id" field's value of the UserAttributeValue entity. +// If the UserAttributeValue object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserAttributeDefinitionMutation) OldPlaceholder(ctx context.Context) (v string, err error) { +func (m *UserAttributeValueMutation) OldUserID(ctx context.Context) (v int64, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldPlaceholder is only allowed on UpdateOne operations") + return v, errors.New("OldUserID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldPlaceholder requires an ID field in the mutation") + return v, errors.New("OldUserID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldPlaceholder: %w", err) + return v, fmt.Errorf("querying old value for OldUserID: %w", err) } - return oldValue.Placeholder, nil + return oldValue.UserID, nil } -// ResetPlaceholder resets all changes to the "placeholder" field. -func (m *UserAttributeDefinitionMutation) ResetPlaceholder() { - m.placeholder = nil +// ResetUserID resets all changes to the "user_id" field. +func (m *UserAttributeValueMutation) ResetUserID() { + m.user = nil } -// SetDisplayOrder sets the "display_order" field. -func (m *UserAttributeDefinitionMutation) SetDisplayOrder(i int) { - m.display_order = &i - m.adddisplay_order = nil +// SetAttributeID sets the "attribute_id" field. +func (m *UserAttributeValueMutation) SetAttributeID(i int64) { + m.definition = &i } -// DisplayOrder returns the value of the "display_order" field in the mutation. -func (m *UserAttributeDefinitionMutation) DisplayOrder() (r int, exists bool) { - v := m.display_order +// AttributeID returns the value of the "attribute_id" field in the mutation. +func (m *UserAttributeValueMutation) AttributeID() (r int64, exists bool) { + v := m.definition if v == nil { return } return *v, true } -// OldDisplayOrder returns the old "display_order" field's value of the UserAttributeDefinition entity. -// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database. +// OldAttributeID returns the old "attribute_id" field's value of the UserAttributeValue entity. +// If the UserAttributeValue object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserAttributeDefinitionMutation) OldDisplayOrder(ctx context.Context) (v int, err error) { +func (m *UserAttributeValueMutation) OldAttributeID(ctx context.Context) (v int64, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldDisplayOrder is only allowed on UpdateOne operations") + return v, errors.New("OldAttributeID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldDisplayOrder requires an ID field in the mutation") + return v, errors.New("OldAttributeID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldDisplayOrder: %w", err) - } - return oldValue.DisplayOrder, nil -} - -// AddDisplayOrder adds i to the "display_order" field. -func (m *UserAttributeDefinitionMutation) AddDisplayOrder(i int) { - if m.adddisplay_order != nil { - *m.adddisplay_order += i - } else { - m.adddisplay_order = &i - } -} - -// AddedDisplayOrder returns the value that was added to the "display_order" field in this mutation. -func (m *UserAttributeDefinitionMutation) AddedDisplayOrder() (r int, exists bool) { - v := m.adddisplay_order - if v == nil { - return + return v, fmt.Errorf("querying old value for OldAttributeID: %w", err) } - return *v, true + return oldValue.AttributeID, nil } -// ResetDisplayOrder resets all changes to the "display_order" field. -func (m *UserAttributeDefinitionMutation) ResetDisplayOrder() { - m.display_order = nil - m.adddisplay_order = nil +// ResetAttributeID resets all changes to the "attribute_id" field. +func (m *UserAttributeValueMutation) ResetAttributeID() { + m.definition = nil } -// SetEnabled sets the "enabled" field. -func (m *UserAttributeDefinitionMutation) SetEnabled(b bool) { - m.enabled = &b +// SetValue sets the "value" field. +func (m *UserAttributeValueMutation) SetValue(s string) { + m.value = &s } -// Enabled returns the value of the "enabled" field in the mutation. -func (m *UserAttributeDefinitionMutation) Enabled() (r bool, exists bool) { - v := m.enabled +// Value returns the value of the "value" field in the mutation. +func (m *UserAttributeValueMutation) Value() (r string, exists bool) { + v := m.value if v == nil { return } return *v, true } -// OldEnabled returns the old "enabled" field's value of the UserAttributeDefinition entity. -// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database. +// OldValue returns the old "value" field's value of the UserAttributeValue entity. +// If the UserAttributeValue object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserAttributeDefinitionMutation) OldEnabled(ctx context.Context) (v bool, err error) { +func (m *UserAttributeValueMutation) OldValue(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldEnabled is only allowed on UpdateOne operations") + return v, errors.New("OldValue is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldEnabled requires an ID field in the mutation") + return v, errors.New("OldValue requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldEnabled: %w", err) + return v, fmt.Errorf("querying old value for OldValue: %w", err) } - return oldValue.Enabled, nil + return oldValue.Value, nil } -// ResetEnabled resets all changes to the "enabled" field. -func (m *UserAttributeDefinitionMutation) ResetEnabled() { - m.enabled = nil +// ResetValue resets all changes to the "value" field. +func (m *UserAttributeValueMutation) ResetValue() { + m.value = nil } -// AddValueIDs adds the "values" edge to the UserAttributeValue entity by ids. -func (m *UserAttributeDefinitionMutation) AddValueIDs(ids ...int64) { - if m.values == nil { - m.values = make(map[int64]struct{}) - } - for i := range ids { - m.values[ids[i]] = struct{}{} +// ClearUser clears the "user" edge to the User entity. +func (m *UserAttributeValueMutation) ClearUser() { + m.cleareduser = true + m.clearedFields[userattributevalue.FieldUserID] = struct{}{} +} + +// UserCleared reports if the "user" edge to the User entity was cleared. +func (m *UserAttributeValueMutation) UserCleared() bool { + return m.cleareduser +} + +// UserIDs returns the "user" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// UserID instead. It exists only for internal usage by the builders. +func (m *UserAttributeValueMutation) UserIDs() (ids []int64) { + if id := m.user; id != nil { + ids = append(ids, *id) } + return } -// ClearValues clears the "values" edge to the UserAttributeValue entity. -func (m *UserAttributeDefinitionMutation) ClearValues() { - m.clearedvalues = true +// ResetUser resets all changes to the "user" edge. +func (m *UserAttributeValueMutation) ResetUser() { + m.user = nil + m.cleareduser = false } -// ValuesCleared reports if the "values" edge to the UserAttributeValue entity was cleared. -func (m *UserAttributeDefinitionMutation) ValuesCleared() bool { - return m.clearedvalues +// SetDefinitionID sets the "definition" edge to the UserAttributeDefinition entity by id. +func (m *UserAttributeValueMutation) SetDefinitionID(id int64) { + m.definition = &id } -// RemoveValueIDs removes the "values" edge to the UserAttributeValue entity by IDs. -func (m *UserAttributeDefinitionMutation) RemoveValueIDs(ids ...int64) { - if m.removedvalues == nil { - m.removedvalues = make(map[int64]struct{}) - } - for i := range ids { - delete(m.values, ids[i]) - m.removedvalues[ids[i]] = struct{}{} - } +// ClearDefinition clears the "definition" edge to the UserAttributeDefinition entity. +func (m *UserAttributeValueMutation) ClearDefinition() { + m.cleareddefinition = true + m.clearedFields[userattributevalue.FieldAttributeID] = struct{}{} } -// RemovedValues returns the removed IDs of the "values" edge to the UserAttributeValue entity. -func (m *UserAttributeDefinitionMutation) RemovedValuesIDs() (ids []int64) { - for id := range m.removedvalues { - ids = append(ids, id) +// DefinitionCleared reports if the "definition" edge to the UserAttributeDefinition entity was cleared. +func (m *UserAttributeValueMutation) DefinitionCleared() bool { + return m.cleareddefinition +} + +// DefinitionID returns the "definition" edge ID in the mutation. +func (m *UserAttributeValueMutation) DefinitionID() (id int64, exists bool) { + if m.definition != nil { + return *m.definition, true } return } -// ValuesIDs returns the "values" edge IDs in the mutation. -func (m *UserAttributeDefinitionMutation) ValuesIDs() (ids []int64) { - for id := range m.values { - ids = append(ids, id) +// DefinitionIDs returns the "definition" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// DefinitionID instead. It exists only for internal usage by the builders. +func (m *UserAttributeValueMutation) DefinitionIDs() (ids []int64) { + if id := m.definition; id != nil { + ids = append(ids, *id) } return } -// ResetValues resets all changes to the "values" edge. -func (m *UserAttributeDefinitionMutation) ResetValues() { - m.values = nil - m.clearedvalues = false - m.removedvalues = nil +// ResetDefinition resets all changes to the "definition" edge. +func (m *UserAttributeValueMutation) ResetDefinition() { + m.definition = nil + m.cleareddefinition = false } -// Where appends a list predicates to the UserAttributeDefinitionMutation builder. -func (m *UserAttributeDefinitionMutation) Where(ps ...predicate.UserAttributeDefinition) { +// Where appends a list predicates to the UserAttributeValueMutation builder. +func (m *UserAttributeValueMutation) Where(ps ...predicate.UserAttributeValue) { m.predicates = append(m.predicates, ps...) } -// WhereP appends storage-level predicates to the UserAttributeDefinitionMutation builder. Using this method, +// WhereP appends storage-level predicates to the UserAttributeValueMutation builder. Using this method, // users can use type-assertion to append predicates that do not depend on any generated package. -func (m *UserAttributeDefinitionMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.UserAttributeDefinition, len(ps)) +func (m *UserAttributeValueMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.UserAttributeValue, len(ps)) for i := range ps { p[i] = ps[i] } @@ -24193,63 +26018,39 @@ func (m *UserAttributeDefinitionMutation) WhereP(ps ...func(*sql.Selector)) { } // Op returns the operation name. -func (m *UserAttributeDefinitionMutation) Op() Op { +func (m *UserAttributeValueMutation) Op() Op { return m.op } // SetOp allows setting the mutation operation. -func (m *UserAttributeDefinitionMutation) SetOp(op Op) { - m.op = op -} - -// Type returns the node type of this mutation (UserAttributeDefinition). -func (m *UserAttributeDefinitionMutation) Type() string { - return m.typ -} - -// Fields returns all fields that were changed during this mutation. Note that in -// order to get all numeric fields that were incremented/decremented, call -// AddedFields(). -func (m *UserAttributeDefinitionMutation) Fields() []string { - fields := make([]string, 0, 13) - if m.created_at != nil { - fields = append(fields, userattributedefinition.FieldCreatedAt) - } - if m.updated_at != nil { - fields = append(fields, userattributedefinition.FieldUpdatedAt) - } - if m.deleted_at != nil { - fields = append(fields, userattributedefinition.FieldDeletedAt) - } - if m.key != nil { - fields = append(fields, userattributedefinition.FieldKey) - } - if m.name != nil { - fields = append(fields, userattributedefinition.FieldName) - } - if m.description != nil { - fields = append(fields, userattributedefinition.FieldDescription) - } - if m._type != nil { - fields = append(fields, userattributedefinition.FieldType) - } - if m.options != nil { - fields = append(fields, userattributedefinition.FieldOptions) - } - if m.required != nil { - fields = append(fields, userattributedefinition.FieldRequired) +func (m *UserAttributeValueMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (UserAttributeValue). +func (m *UserAttributeValueMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *UserAttributeValueMutation) Fields() []string { + fields := make([]string, 0, 5) + if m.created_at != nil { + fields = append(fields, userattributevalue.FieldCreatedAt) } - if m.validation != nil { - fields = append(fields, userattributedefinition.FieldValidation) + if m.updated_at != nil { + fields = append(fields, userattributevalue.FieldUpdatedAt) } - if m.placeholder != nil { - fields = append(fields, userattributedefinition.FieldPlaceholder) + if m.user != nil { + fields = append(fields, userattributevalue.FieldUserID) } - if m.display_order != nil { - fields = append(fields, userattributedefinition.FieldDisplayOrder) + if m.definition != nil { + fields = append(fields, userattributevalue.FieldAttributeID) } - if m.enabled != nil { - fields = append(fields, userattributedefinition.FieldEnabled) + if m.value != nil { + fields = append(fields, userattributevalue.FieldValue) } return fields } @@ -24257,34 +26058,18 @@ func (m *UserAttributeDefinitionMutation) Fields() []string { // Field returns the value of a field with the given name. The second boolean // return value indicates that this field was not set, or was not defined in the // schema. -func (m *UserAttributeDefinitionMutation) Field(name string) (ent.Value, bool) { +func (m *UserAttributeValueMutation) Field(name string) (ent.Value, bool) { switch name { - case userattributedefinition.FieldCreatedAt: + case userattributevalue.FieldCreatedAt: return m.CreatedAt() - case userattributedefinition.FieldUpdatedAt: + case userattributevalue.FieldUpdatedAt: return m.UpdatedAt() - case userattributedefinition.FieldDeletedAt: - return m.DeletedAt() - case userattributedefinition.FieldKey: - return m.Key() - case userattributedefinition.FieldName: - return m.Name() - case userattributedefinition.FieldDescription: - return m.Description() - case userattributedefinition.FieldType: - return m.GetType() - case userattributedefinition.FieldOptions: - return m.Options() - case userattributedefinition.FieldRequired: - return m.Required() - case userattributedefinition.FieldValidation: - return m.Validation() - case userattributedefinition.FieldPlaceholder: - return m.Placeholder() - case userattributedefinition.FieldDisplayOrder: - return m.DisplayOrder() - case userattributedefinition.FieldEnabled: - return m.Enabled() + case userattributevalue.FieldUserID: + return m.UserID() + case userattributevalue.FieldAttributeID: + return m.AttributeID() + case userattributevalue.FieldValue: + return m.Value() } return nil, false } @@ -24292,155 +26077,78 @@ func (m *UserAttributeDefinitionMutation) Field(name string) (ent.Value, bool) { // OldField returns the old value of the field from the database. An error is // returned if the mutation operation is not UpdateOne, or the query to the // database failed. -func (m *UserAttributeDefinitionMutation) OldField(ctx context.Context, name string) (ent.Value, error) { +func (m *UserAttributeValueMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { - case userattributedefinition.FieldCreatedAt: + case userattributevalue.FieldCreatedAt: return m.OldCreatedAt(ctx) - case userattributedefinition.FieldUpdatedAt: + case userattributevalue.FieldUpdatedAt: return m.OldUpdatedAt(ctx) - case userattributedefinition.FieldDeletedAt: - return m.OldDeletedAt(ctx) - case userattributedefinition.FieldKey: - return m.OldKey(ctx) - case userattributedefinition.FieldName: - return m.OldName(ctx) - case userattributedefinition.FieldDescription: - return m.OldDescription(ctx) - case userattributedefinition.FieldType: - return m.OldType(ctx) - case userattributedefinition.FieldOptions: - return m.OldOptions(ctx) - case userattributedefinition.FieldRequired: - return m.OldRequired(ctx) - case userattributedefinition.FieldValidation: - return m.OldValidation(ctx) - case userattributedefinition.FieldPlaceholder: - return m.OldPlaceholder(ctx) - case userattributedefinition.FieldDisplayOrder: - return m.OldDisplayOrder(ctx) - case userattributedefinition.FieldEnabled: - return m.OldEnabled(ctx) + case userattributevalue.FieldUserID: + return m.OldUserID(ctx) + case userattributevalue.FieldAttributeID: + return m.OldAttributeID(ctx) + case userattributevalue.FieldValue: + return m.OldValue(ctx) } - return nil, fmt.Errorf("unknown UserAttributeDefinition field %s", name) + return nil, fmt.Errorf("unknown UserAttributeValue field %s", name) } // SetField sets the value of a field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *UserAttributeDefinitionMutation) SetField(name string, value ent.Value) error { +func (m *UserAttributeValueMutation) SetField(name string, value ent.Value) error { switch name { - case userattributedefinition.FieldCreatedAt: + case userattributevalue.FieldCreatedAt: v, ok := value.(time.Time) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetCreatedAt(v) return nil - case userattributedefinition.FieldUpdatedAt: + case userattributevalue.FieldUpdatedAt: v, ok := value.(time.Time) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetUpdatedAt(v) return nil - case userattributedefinition.FieldDeletedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetDeletedAt(v) - return nil - case userattributedefinition.FieldKey: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetKey(v) - return nil - case userattributedefinition.FieldName: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetName(v) - return nil - case userattributedefinition.FieldDescription: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetDescription(v) - return nil - case userattributedefinition.FieldType: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetType(v) - return nil - case userattributedefinition.FieldOptions: - v, ok := value.([]map[string]interface{}) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetOptions(v) - return nil - case userattributedefinition.FieldRequired: - v, ok := value.(bool) + case userattributevalue.FieldUserID: + v, ok := value.(int64) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetRequired(v) + m.SetUserID(v) return nil - case userattributedefinition.FieldValidation: - v, ok := value.(map[string]interface{}) + case userattributevalue.FieldAttributeID: + v, ok := value.(int64) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetValidation(v) + m.SetAttributeID(v) return nil - case userattributedefinition.FieldPlaceholder: + case userattributevalue.FieldValue: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetPlaceholder(v) - return nil - case userattributedefinition.FieldDisplayOrder: - v, ok := value.(int) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetDisplayOrder(v) - return nil - case userattributedefinition.FieldEnabled: - v, ok := value.(bool) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetEnabled(v) + m.SetValue(v) return nil } - return fmt.Errorf("unknown UserAttributeDefinition field %s", name) + return fmt.Errorf("unknown UserAttributeValue field %s", name) } // AddedFields returns all numeric fields that were incremented/decremented during // this mutation. -func (m *UserAttributeDefinitionMutation) AddedFields() []string { +func (m *UserAttributeValueMutation) AddedFields() []string { var fields []string - if m.adddisplay_order != nil { - fields = append(fields, userattributedefinition.FieldDisplayOrder) - } return fields } // AddedField returns the numeric value that was incremented/decremented on a field // with the given name. The second boolean return value indicates that this field // was not set, or was not defined in the schema. -func (m *UserAttributeDefinitionMutation) AddedField(name string) (ent.Value, bool) { +func (m *UserAttributeValueMutation) AddedField(name string) (ent.Value, bool) { switch name { - case userattributedefinition.FieldDisplayOrder: - return m.AddedDisplayOrder() } return nil, false } @@ -24448,208 +26156,173 @@ func (m *UserAttributeDefinitionMutation) AddedField(name string) (ent.Value, bo // AddField adds the value to the field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *UserAttributeDefinitionMutation) AddField(name string, value ent.Value) error { +func (m *UserAttributeValueMutation) AddField(name string, value ent.Value) error { switch name { - case userattributedefinition.FieldDisplayOrder: - v, ok := value.(int) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddDisplayOrder(v) - return nil } - return fmt.Errorf("unknown UserAttributeDefinition numeric field %s", name) + return fmt.Errorf("unknown UserAttributeValue numeric field %s", name) } // ClearedFields returns all nullable fields that were cleared during this // mutation. -func (m *UserAttributeDefinitionMutation) ClearedFields() []string { - var fields []string - if m.FieldCleared(userattributedefinition.FieldDeletedAt) { - fields = append(fields, userattributedefinition.FieldDeletedAt) - } - return fields +func (m *UserAttributeValueMutation) ClearedFields() []string { + return nil } // FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *UserAttributeDefinitionMutation) FieldCleared(name string) bool { - _, ok := m.clearedFields[name] - return ok -} - -// ClearField clears the value of the field with the given name. It returns an -// error if the field is not defined in the schema. -func (m *UserAttributeDefinitionMutation) ClearField(name string) error { - switch name { - case userattributedefinition.FieldDeletedAt: - m.ClearDeletedAt() - return nil - } - return fmt.Errorf("unknown UserAttributeDefinition nullable field %s", name) -} - -// ResetField resets all changes in the mutation for the field with the given name. -// It returns an error if the field is not defined in the schema. -func (m *UserAttributeDefinitionMutation) ResetField(name string) error { - switch name { - case userattributedefinition.FieldCreatedAt: - m.ResetCreatedAt() - return nil - case userattributedefinition.FieldUpdatedAt: - m.ResetUpdatedAt() - return nil - case userattributedefinition.FieldDeletedAt: - m.ResetDeletedAt() - return nil - case userattributedefinition.FieldKey: - m.ResetKey() - return nil - case userattributedefinition.FieldName: - m.ResetName() - return nil - case userattributedefinition.FieldDescription: - m.ResetDescription() - return nil - case userattributedefinition.FieldType: - m.ResetType() - return nil - case userattributedefinition.FieldOptions: - m.ResetOptions() - return nil - case userattributedefinition.FieldRequired: - m.ResetRequired() +// cleared in this mutation. +func (m *UserAttributeValueMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *UserAttributeValueMutation) ClearField(name string) error { + return fmt.Errorf("unknown UserAttributeValue nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *UserAttributeValueMutation) ResetField(name string) error { + switch name { + case userattributevalue.FieldCreatedAt: + m.ResetCreatedAt() return nil - case userattributedefinition.FieldValidation: - m.ResetValidation() + case userattributevalue.FieldUpdatedAt: + m.ResetUpdatedAt() return nil - case userattributedefinition.FieldPlaceholder: - m.ResetPlaceholder() + case userattributevalue.FieldUserID: + m.ResetUserID() return nil - case userattributedefinition.FieldDisplayOrder: - m.ResetDisplayOrder() + case userattributevalue.FieldAttributeID: + m.ResetAttributeID() return nil - case userattributedefinition.FieldEnabled: - m.ResetEnabled() + case userattributevalue.FieldValue: + m.ResetValue() return nil } - return fmt.Errorf("unknown UserAttributeDefinition field %s", name) + return fmt.Errorf("unknown UserAttributeValue field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. -func (m *UserAttributeDefinitionMutation) AddedEdges() []string { - edges := make([]string, 0, 1) - if m.values != nil { - edges = append(edges, userattributedefinition.EdgeValues) +func (m *UserAttributeValueMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.user != nil { + edges = append(edges, userattributevalue.EdgeUser) + } + if m.definition != nil { + edges = append(edges, userattributevalue.EdgeDefinition) } return edges } // AddedIDs returns all IDs (to other nodes) that were added for the given edge // name in this mutation. -func (m *UserAttributeDefinitionMutation) AddedIDs(name string) []ent.Value { +func (m *UserAttributeValueMutation) AddedIDs(name string) []ent.Value { switch name { - case userattributedefinition.EdgeValues: - ids := make([]ent.Value, 0, len(m.values)) - for id := range m.values { - ids = append(ids, id) + case userattributevalue.EdgeUser: + if id := m.user; id != nil { + return []ent.Value{*id} + } + case userattributevalue.EdgeDefinition: + if id := m.definition; id != nil { + return []ent.Value{*id} } - return ids } return nil } // RemovedEdges returns all edge names that were removed in this mutation. -func (m *UserAttributeDefinitionMutation) RemovedEdges() []string { - edges := make([]string, 0, 1) - if m.removedvalues != nil { - edges = append(edges, userattributedefinition.EdgeValues) - } +func (m *UserAttributeValueMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) return edges } // RemovedIDs returns all IDs (to other nodes) that were removed for the edge with // the given name in this mutation. -func (m *UserAttributeDefinitionMutation) RemovedIDs(name string) []ent.Value { - switch name { - case userattributedefinition.EdgeValues: - ids := make([]ent.Value, 0, len(m.removedvalues)) - for id := range m.removedvalues { - ids = append(ids, id) - } - return ids - } +func (m *UserAttributeValueMutation) RemovedIDs(name string) []ent.Value { return nil } // ClearedEdges returns all edge names that were cleared in this mutation. -func (m *UserAttributeDefinitionMutation) ClearedEdges() []string { - edges := make([]string, 0, 1) - if m.clearedvalues { - edges = append(edges, userattributedefinition.EdgeValues) +func (m *UserAttributeValueMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.cleareduser { + edges = append(edges, userattributevalue.EdgeUser) + } + if m.cleareddefinition { + edges = append(edges, userattributevalue.EdgeDefinition) } return edges } // EdgeCleared returns a boolean which indicates if the edge with the given name // was cleared in this mutation. -func (m *UserAttributeDefinitionMutation) EdgeCleared(name string) bool { +func (m *UserAttributeValueMutation) EdgeCleared(name string) bool { switch name { - case userattributedefinition.EdgeValues: - return m.clearedvalues + case userattributevalue.EdgeUser: + return m.cleareduser + case userattributevalue.EdgeDefinition: + return m.cleareddefinition } return false } // ClearEdge clears the value of the edge with the given name. It returns an error // if that edge is not defined in the schema. -func (m *UserAttributeDefinitionMutation) ClearEdge(name string) error { +func (m *UserAttributeValueMutation) ClearEdge(name string) error { switch name { + case userattributevalue.EdgeUser: + m.ClearUser() + return nil + case userattributevalue.EdgeDefinition: + m.ClearDefinition() + return nil } - return fmt.Errorf("unknown UserAttributeDefinition unique edge %s", name) + return fmt.Errorf("unknown UserAttributeValue unique edge %s", name) } // ResetEdge resets all changes to the edge with the given name in this mutation. // It returns an error if the edge is not defined in the schema. -func (m *UserAttributeDefinitionMutation) ResetEdge(name string) error { +func (m *UserAttributeValueMutation) ResetEdge(name string) error { switch name { - case userattributedefinition.EdgeValues: - m.ResetValues() + case userattributevalue.EdgeUser: + m.ResetUser() + return nil + case userattributevalue.EdgeDefinition: + m.ResetDefinition() return nil } - return fmt.Errorf("unknown UserAttributeDefinition edge %s", name) + return fmt.Errorf("unknown UserAttributeValue edge %s", name) } -// UserAttributeValueMutation represents an operation that mutates the UserAttributeValue nodes in the graph. -type UserAttributeValueMutation struct { +// UserReferralProfileMutation represents an operation that mutates the UserReferralProfile nodes in the graph. +type UserReferralProfileMutation struct { config - op Op - typ string - id *int64 - created_at *time.Time - updated_at *time.Time - value *string - clearedFields map[string]struct{} - user *int64 - cleareduser bool - definition *int64 - cleareddefinition bool - done bool - oldValue func(context.Context) (*UserAttributeValue, error) - predicates []predicate.UserAttributeValue + op Op + typ string + id *int64 + referral_code *string + created_at *time.Time + clearedFields map[string]struct{} + user *int64 + cleareduser bool + done bool + oldValue func(context.Context) (*UserReferralProfile, error) + predicates []predicate.UserReferralProfile } -var _ ent.Mutation = (*UserAttributeValueMutation)(nil) +var _ ent.Mutation = (*UserReferralProfileMutation)(nil) -// userattributevalueOption allows management of the mutation configuration using functional options. -type userattributevalueOption func(*UserAttributeValueMutation) +// userreferralprofileOption allows management of the mutation configuration using functional options. +type userreferralprofileOption func(*UserReferralProfileMutation) -// newUserAttributeValueMutation creates new mutation for the UserAttributeValue entity. -func newUserAttributeValueMutation(c config, op Op, opts ...userattributevalueOption) *UserAttributeValueMutation { - m := &UserAttributeValueMutation{ +// newUserReferralProfileMutation creates new mutation for the UserReferralProfile entity. +func newUserReferralProfileMutation(c config, op Op, opts ...userreferralprofileOption) *UserReferralProfileMutation { + m := &UserReferralProfileMutation{ config: c, op: op, - typ: TypeUserAttributeValue, + typ: TypeUserReferralProfile, clearedFields: make(map[string]struct{}), } for _, opt := range opts { @@ -24658,20 +26331,20 @@ func newUserAttributeValueMutation(c config, op Op, opts ...userattributevalueOp return m } -// withUserAttributeValueID sets the ID field of the mutation. -func withUserAttributeValueID(id int64) userattributevalueOption { - return func(m *UserAttributeValueMutation) { +// withUserReferralProfileID sets the ID field of the mutation. +func withUserReferralProfileID(id int64) userreferralprofileOption { + return func(m *UserReferralProfileMutation) { var ( err error once sync.Once - value *UserAttributeValue + value *UserReferralProfile ) - m.oldValue = func(ctx context.Context) (*UserAttributeValue, error) { + m.oldValue = func(ctx context.Context) (*UserReferralProfile, error) { once.Do(func() { if m.done { err = errors.New("querying old values post mutation is not allowed") } else { - value, err = m.Client().UserAttributeValue.Get(ctx, id) + value, err = m.Client().UserReferralProfile.Get(ctx, id) } }) return value, err @@ -24680,10 +26353,10 @@ func withUserAttributeValueID(id int64) userattributevalueOption { } } -// withUserAttributeValue sets the old UserAttributeValue of the mutation. -func withUserAttributeValue(node *UserAttributeValue) userattributevalueOption { - return func(m *UserAttributeValueMutation) { - m.oldValue = func(context.Context) (*UserAttributeValue, error) { +// withUserReferralProfile sets the old UserReferralProfile of the mutation. +func withUserReferralProfile(node *UserReferralProfile) userreferralprofileOption { + return func(m *UserReferralProfileMutation) { + m.oldValue = func(context.Context) (*UserReferralProfile, error) { return node, nil } m.id = &node.ID @@ -24692,7 +26365,7 @@ func withUserAttributeValue(node *UserAttributeValue) userattributevalueOption { // Client returns a new `ent.Client` from the mutation. If the mutation was // executed in a transaction (ent.Tx), a transactional client is returned. -func (m UserAttributeValueMutation) Client() *Client { +func (m UserReferralProfileMutation) Client() *Client { client := &Client{config: m.config} client.init() return client @@ -24700,122 +26373,50 @@ func (m UserAttributeValueMutation) Client() *Client { // Tx returns an `ent.Tx` for mutations that were executed in transactions; // it returns an error otherwise. -func (m UserAttributeValueMutation) Tx() (*Tx, error) { +func (m UserReferralProfileMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { return nil, errors.New("ent: mutation is not running in a transaction") } tx := &Tx{config: m.config} - tx.init() - return tx, nil -} - -// ID returns the ID value in the mutation. Note that the ID is only available -// if it was provided to the builder or after it was returned from the database. -func (m *UserAttributeValueMutation) ID() (id int64, exists bool) { - if m.id == nil { - return - } - return *m.id, true -} - -// IDs queries the database and returns the entity ids that match the mutation's predicate. -// That means, if the mutation is applied within a transaction with an isolation level such -// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated -// or updated by the mutation. -func (m *UserAttributeValueMutation) IDs(ctx context.Context) ([]int64, error) { - switch { - case m.op.Is(OpUpdateOne | OpDeleteOne): - id, exists := m.ID() - if exists { - return []int64{id}, nil - } - fallthrough - case m.op.Is(OpUpdate | OpDelete): - return m.Client().UserAttributeValue.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) - } -} - -// SetCreatedAt sets the "created_at" field. -func (m *UserAttributeValueMutation) SetCreatedAt(t time.Time) { - m.created_at = &t -} - -// CreatedAt returns the value of the "created_at" field in the mutation. -func (m *UserAttributeValueMutation) CreatedAt() (r time.Time, exists bool) { - v := m.created_at - if v == nil { - return - } - return *v, true -} - -// OldCreatedAt returns the old "created_at" field's value of the UserAttributeValue entity. -// If the UserAttributeValue object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserAttributeValueMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCreatedAt requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) - } - return oldValue.CreatedAt, nil -} - -// ResetCreatedAt resets all changes to the "created_at" field. -func (m *UserAttributeValueMutation) ResetCreatedAt() { - m.created_at = nil -} - -// SetUpdatedAt sets the "updated_at" field. -func (m *UserAttributeValueMutation) SetUpdatedAt(t time.Time) { - m.updated_at = &t -} - -// UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *UserAttributeValueMutation) UpdatedAt() (r time.Time, exists bool) { - v := m.updated_at - if v == nil { - return - } - return *v, true -} - -// OldUpdatedAt returns the old "updated_at" field's value of the UserAttributeValue entity. -// If the UserAttributeValue object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserAttributeValueMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUpdatedAt requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + tx.init() + return tx, nil +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *UserReferralProfileMutation) ID() (id int64, exists bool) { + if m.id == nil { + return } - return oldValue.UpdatedAt, nil + return *m.id, true } -// ResetUpdatedAt resets all changes to the "updated_at" field. -func (m *UserAttributeValueMutation) ResetUpdatedAt() { - m.updated_at = nil +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *UserReferralProfileMutation) IDs(ctx context.Context) ([]int64, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int64{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().UserReferralProfile.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } } // SetUserID sets the "user_id" field. -func (m *UserAttributeValueMutation) SetUserID(i int64) { +func (m *UserReferralProfileMutation) SetUserID(i int64) { m.user = &i } // UserID returns the value of the "user_id" field in the mutation. -func (m *UserAttributeValueMutation) UserID() (r int64, exists bool) { +func (m *UserReferralProfileMutation) UserID() (r int64, exists bool) { v := m.user if v == nil { return @@ -24823,10 +26424,10 @@ func (m *UserAttributeValueMutation) UserID() (r int64, exists bool) { return *v, true } -// OldUserID returns the old "user_id" field's value of the UserAttributeValue entity. -// If the UserAttributeValue object wasn't provided to the builder, the object is fetched from the database. +// OldUserID returns the old "user_id" field's value of the UserReferralProfile entity. +// If the UserReferralProfile object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserAttributeValueMutation) OldUserID(ctx context.Context) (v int64, err error) { +func (m *UserReferralProfileMutation) OldUserID(ctx context.Context) (v int64, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldUserID is only allowed on UpdateOne operations") } @@ -24841,97 +26442,97 @@ func (m *UserAttributeValueMutation) OldUserID(ctx context.Context) (v int64, er } // ResetUserID resets all changes to the "user_id" field. -func (m *UserAttributeValueMutation) ResetUserID() { +func (m *UserReferralProfileMutation) ResetUserID() { m.user = nil } -// SetAttributeID sets the "attribute_id" field. -func (m *UserAttributeValueMutation) SetAttributeID(i int64) { - m.definition = &i +// SetReferralCode sets the "referral_code" field. +func (m *UserReferralProfileMutation) SetReferralCode(s string) { + m.referral_code = &s } -// AttributeID returns the value of the "attribute_id" field in the mutation. -func (m *UserAttributeValueMutation) AttributeID() (r int64, exists bool) { - v := m.definition +// ReferralCode returns the value of the "referral_code" field in the mutation. +func (m *UserReferralProfileMutation) ReferralCode() (r string, exists bool) { + v := m.referral_code if v == nil { return } return *v, true } -// OldAttributeID returns the old "attribute_id" field's value of the UserAttributeValue entity. -// If the UserAttributeValue object wasn't provided to the builder, the object is fetched from the database. +// OldReferralCode returns the old "referral_code" field's value of the UserReferralProfile entity. +// If the UserReferralProfile object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserAttributeValueMutation) OldAttributeID(ctx context.Context) (v int64, err error) { +func (m *UserReferralProfileMutation) OldReferralCode(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldAttributeID is only allowed on UpdateOne operations") + return v, errors.New("OldReferralCode is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldAttributeID requires an ID field in the mutation") + return v, errors.New("OldReferralCode requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldAttributeID: %w", err) + return v, fmt.Errorf("querying old value for OldReferralCode: %w", err) } - return oldValue.AttributeID, nil + return oldValue.ReferralCode, nil } -// ResetAttributeID resets all changes to the "attribute_id" field. -func (m *UserAttributeValueMutation) ResetAttributeID() { - m.definition = nil +// ResetReferralCode resets all changes to the "referral_code" field. +func (m *UserReferralProfileMutation) ResetReferralCode() { + m.referral_code = nil } -// SetValue sets the "value" field. -func (m *UserAttributeValueMutation) SetValue(s string) { - m.value = &s +// SetCreatedAt sets the "created_at" field. +func (m *UserReferralProfileMutation) SetCreatedAt(t time.Time) { + m.created_at = &t } -// Value returns the value of the "value" field in the mutation. -func (m *UserAttributeValueMutation) Value() (r string, exists bool) { - v := m.value +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *UserReferralProfileMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at if v == nil { return } return *v, true } -// OldValue returns the old "value" field's value of the UserAttributeValue entity. -// If the UserAttributeValue object wasn't provided to the builder, the object is fetched from the database. +// OldCreatedAt returns the old "created_at" field's value of the UserReferralProfile entity. +// If the UserReferralProfile object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserAttributeValueMutation) OldValue(ctx context.Context) (v string, err error) { +func (m *UserReferralProfileMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldValue is only allowed on UpdateOne operations") + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldValue requires an ID field in the mutation") + return v, errors.New("OldCreatedAt requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldValue: %w", err) + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) } - return oldValue.Value, nil + return oldValue.CreatedAt, nil } -// ResetValue resets all changes to the "value" field. -func (m *UserAttributeValueMutation) ResetValue() { - m.value = nil +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *UserReferralProfileMutation) ResetCreatedAt() { + m.created_at = nil } // ClearUser clears the "user" edge to the User entity. -func (m *UserAttributeValueMutation) ClearUser() { +func (m *UserReferralProfileMutation) ClearUser() { m.cleareduser = true - m.clearedFields[userattributevalue.FieldUserID] = struct{}{} + m.clearedFields[userreferralprofile.FieldUserID] = struct{}{} } // UserCleared reports if the "user" edge to the User entity was cleared. -func (m *UserAttributeValueMutation) UserCleared() bool { +func (m *UserReferralProfileMutation) UserCleared() bool { return m.cleareduser } // UserIDs returns the "user" edge IDs in the mutation. // Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use // UserID instead. It exists only for internal usage by the builders. -func (m *UserAttributeValueMutation) UserIDs() (ids []int64) { +func (m *UserReferralProfileMutation) UserIDs() (ids []int64) { if id := m.user; id != nil { ids = append(ids, *id) } @@ -24939,60 +26540,20 @@ func (m *UserAttributeValueMutation) UserIDs() (ids []int64) { } // ResetUser resets all changes to the "user" edge. -func (m *UserAttributeValueMutation) ResetUser() { +func (m *UserReferralProfileMutation) ResetUser() { m.user = nil m.cleareduser = false } -// SetDefinitionID sets the "definition" edge to the UserAttributeDefinition entity by id. -func (m *UserAttributeValueMutation) SetDefinitionID(id int64) { - m.definition = &id -} - -// ClearDefinition clears the "definition" edge to the UserAttributeDefinition entity. -func (m *UserAttributeValueMutation) ClearDefinition() { - m.cleareddefinition = true - m.clearedFields[userattributevalue.FieldAttributeID] = struct{}{} -} - -// DefinitionCleared reports if the "definition" edge to the UserAttributeDefinition entity was cleared. -func (m *UserAttributeValueMutation) DefinitionCleared() bool { - return m.cleareddefinition -} - -// DefinitionID returns the "definition" edge ID in the mutation. -func (m *UserAttributeValueMutation) DefinitionID() (id int64, exists bool) { - if m.definition != nil { - return *m.definition, true - } - return -} - -// DefinitionIDs returns the "definition" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// DefinitionID instead. It exists only for internal usage by the builders. -func (m *UserAttributeValueMutation) DefinitionIDs() (ids []int64) { - if id := m.definition; id != nil { - ids = append(ids, *id) - } - return -} - -// ResetDefinition resets all changes to the "definition" edge. -func (m *UserAttributeValueMutation) ResetDefinition() { - m.definition = nil - m.cleareddefinition = false -} - -// Where appends a list predicates to the UserAttributeValueMutation builder. -func (m *UserAttributeValueMutation) Where(ps ...predicate.UserAttributeValue) { +// Where appends a list predicates to the UserReferralProfileMutation builder. +func (m *UserReferralProfileMutation) Where(ps ...predicate.UserReferralProfile) { m.predicates = append(m.predicates, ps...) } -// WhereP appends storage-level predicates to the UserAttributeValueMutation builder. Using this method, +// WhereP appends storage-level predicates to the UserReferralProfileMutation builder. Using this method, // users can use type-assertion to append predicates that do not depend on any generated package. -func (m *UserAttributeValueMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.UserAttributeValue, len(ps)) +func (m *UserReferralProfileMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.UserReferralProfile, len(ps)) for i := range ps { p[i] = ps[i] } @@ -25000,39 +26561,33 @@ func (m *UserAttributeValueMutation) WhereP(ps ...func(*sql.Selector)) { } // Op returns the operation name. -func (m *UserAttributeValueMutation) Op() Op { +func (m *UserReferralProfileMutation) Op() Op { return m.op } // SetOp allows setting the mutation operation. -func (m *UserAttributeValueMutation) SetOp(op Op) { +func (m *UserReferralProfileMutation) SetOp(op Op) { m.op = op } -// Type returns the node type of this mutation (UserAttributeValue). -func (m *UserAttributeValueMutation) Type() string { +// Type returns the node type of this mutation (UserReferralProfile). +func (m *UserReferralProfileMutation) Type() string { return m.typ } // Fields returns all fields that were changed during this mutation. Note that in // order to get all numeric fields that were incremented/decremented, call // AddedFields(). -func (m *UserAttributeValueMutation) Fields() []string { - fields := make([]string, 0, 5) - if m.created_at != nil { - fields = append(fields, userattributevalue.FieldCreatedAt) - } - if m.updated_at != nil { - fields = append(fields, userattributevalue.FieldUpdatedAt) - } +func (m *UserReferralProfileMutation) Fields() []string { + fields := make([]string, 0, 3) if m.user != nil { - fields = append(fields, userattributevalue.FieldUserID) + fields = append(fields, userreferralprofile.FieldUserID) } - if m.definition != nil { - fields = append(fields, userattributevalue.FieldAttributeID) + if m.referral_code != nil { + fields = append(fields, userreferralprofile.FieldReferralCode) } - if m.value != nil { - fields = append(fields, userattributevalue.FieldValue) + if m.created_at != nil { + fields = append(fields, userreferralprofile.FieldCreatedAt) } return fields } @@ -25040,18 +26595,14 @@ func (m *UserAttributeValueMutation) Fields() []string { // Field returns the value of a field with the given name. The second boolean // return value indicates that this field was not set, or was not defined in the // schema. -func (m *UserAttributeValueMutation) Field(name string) (ent.Value, bool) { +func (m *UserReferralProfileMutation) Field(name string) (ent.Value, bool) { switch name { - case userattributevalue.FieldCreatedAt: - return m.CreatedAt() - case userattributevalue.FieldUpdatedAt: - return m.UpdatedAt() - case userattributevalue.FieldUserID: + case userreferralprofile.FieldUserID: return m.UserID() - case userattributevalue.FieldAttributeID: - return m.AttributeID() - case userattributevalue.FieldValue: - return m.Value() + case userreferralprofile.FieldReferralCode: + return m.ReferralCode() + case userreferralprofile.FieldCreatedAt: + return m.CreatedAt() } return nil, false } @@ -25059,69 +26610,51 @@ func (m *UserAttributeValueMutation) Field(name string) (ent.Value, bool) { // OldField returns the old value of the field from the database. An error is // returned if the mutation operation is not UpdateOne, or the query to the // database failed. -func (m *UserAttributeValueMutation) OldField(ctx context.Context, name string) (ent.Value, error) { +func (m *UserReferralProfileMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { - case userattributevalue.FieldCreatedAt: - return m.OldCreatedAt(ctx) - case userattributevalue.FieldUpdatedAt: - return m.OldUpdatedAt(ctx) - case userattributevalue.FieldUserID: + case userreferralprofile.FieldUserID: return m.OldUserID(ctx) - case userattributevalue.FieldAttributeID: - return m.OldAttributeID(ctx) - case userattributevalue.FieldValue: - return m.OldValue(ctx) + case userreferralprofile.FieldReferralCode: + return m.OldReferralCode(ctx) + case userreferralprofile.FieldCreatedAt: + return m.OldCreatedAt(ctx) } - return nil, fmt.Errorf("unknown UserAttributeValue field %s", name) + return nil, fmt.Errorf("unknown UserReferralProfile field %s", name) } // SetField sets the value of a field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *UserAttributeValueMutation) SetField(name string, value ent.Value) error { +func (m *UserReferralProfileMutation) SetField(name string, value ent.Value) error { switch name { - case userattributevalue.FieldCreatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCreatedAt(v) - return nil - case userattributevalue.FieldUpdatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUpdatedAt(v) - return nil - case userattributevalue.FieldUserID: + case userreferralprofile.FieldUserID: v, ok := value.(int64) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetUserID(v) return nil - case userattributevalue.FieldAttributeID: - v, ok := value.(int64) + case userreferralprofile.FieldReferralCode: + v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetAttributeID(v) + m.SetReferralCode(v) return nil - case userattributevalue.FieldValue: - v, ok := value.(string) + case userreferralprofile.FieldCreatedAt: + v, ok := value.(time.Time) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetValue(v) + m.SetCreatedAt(v) return nil } - return fmt.Errorf("unknown UserAttributeValue field %s", name) + return fmt.Errorf("unknown UserReferralProfile field %s", name) } // AddedFields returns all numeric fields that were incremented/decremented during // this mutation. -func (m *UserAttributeValueMutation) AddedFields() []string { +func (m *UserReferralProfileMutation) AddedFields() []string { var fields []string return fields } @@ -25129,7 +26662,7 @@ func (m *UserAttributeValueMutation) AddedFields() []string { // AddedField returns the numeric value that was incremented/decremented on a field // with the given name. The second boolean return value indicates that this field // was not set, or was not defined in the schema. -func (m *UserAttributeValueMutation) AddedField(name string) (ent.Value, bool) { +func (m *UserReferralProfileMutation) AddedField(name string) (ent.Value, bool) { switch name { } return nil, false @@ -25138,144 +26671,120 @@ func (m *UserAttributeValueMutation) AddedField(name string) (ent.Value, bool) { // AddField adds the value to the field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *UserAttributeValueMutation) AddField(name string, value ent.Value) error { +func (m *UserReferralProfileMutation) AddField(name string, value ent.Value) error { switch name { } - return fmt.Errorf("unknown UserAttributeValue numeric field %s", name) + return fmt.Errorf("unknown UserReferralProfile numeric field %s", name) } // ClearedFields returns all nullable fields that were cleared during this // mutation. -func (m *UserAttributeValueMutation) ClearedFields() []string { +func (m *UserReferralProfileMutation) ClearedFields() []string { return nil } // FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. -func (m *UserAttributeValueMutation) FieldCleared(name string) bool { +func (m *UserReferralProfileMutation) FieldCleared(name string) bool { _, ok := m.clearedFields[name] return ok } // ClearField clears the value of the field with the given name. It returns an // error if the field is not defined in the schema. -func (m *UserAttributeValueMutation) ClearField(name string) error { - return fmt.Errorf("unknown UserAttributeValue nullable field %s", name) +func (m *UserReferralProfileMutation) ClearField(name string) error { + return fmt.Errorf("unknown UserReferralProfile nullable field %s", name) } // ResetField resets all changes in the mutation for the field with the given name. // It returns an error if the field is not defined in the schema. -func (m *UserAttributeValueMutation) ResetField(name string) error { +func (m *UserReferralProfileMutation) ResetField(name string) error { switch name { - case userattributevalue.FieldCreatedAt: - m.ResetCreatedAt() - return nil - case userattributevalue.FieldUpdatedAt: - m.ResetUpdatedAt() - return nil - case userattributevalue.FieldUserID: + case userreferralprofile.FieldUserID: m.ResetUserID() return nil - case userattributevalue.FieldAttributeID: - m.ResetAttributeID() + case userreferralprofile.FieldReferralCode: + m.ResetReferralCode() return nil - case userattributevalue.FieldValue: - m.ResetValue() + case userreferralprofile.FieldCreatedAt: + m.ResetCreatedAt() return nil } - return fmt.Errorf("unknown UserAttributeValue field %s", name) + return fmt.Errorf("unknown UserReferralProfile field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. -func (m *UserAttributeValueMutation) AddedEdges() []string { - edges := make([]string, 0, 2) +func (m *UserReferralProfileMutation) AddedEdges() []string { + edges := make([]string, 0, 1) if m.user != nil { - edges = append(edges, userattributevalue.EdgeUser) - } - if m.definition != nil { - edges = append(edges, userattributevalue.EdgeDefinition) + edges = append(edges, userreferralprofile.EdgeUser) } return edges } // AddedIDs returns all IDs (to other nodes) that were added for the given edge // name in this mutation. -func (m *UserAttributeValueMutation) AddedIDs(name string) []ent.Value { +func (m *UserReferralProfileMutation) AddedIDs(name string) []ent.Value { switch name { - case userattributevalue.EdgeUser: + case userreferralprofile.EdgeUser: if id := m.user; id != nil { return []ent.Value{*id} } - case userattributevalue.EdgeDefinition: - if id := m.definition; id != nil { - return []ent.Value{*id} - } } return nil } // RemovedEdges returns all edge names that were removed in this mutation. -func (m *UserAttributeValueMutation) RemovedEdges() []string { - edges := make([]string, 0, 2) +func (m *UserReferralProfileMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) return edges } // RemovedIDs returns all IDs (to other nodes) that were removed for the edge with // the given name in this mutation. -func (m *UserAttributeValueMutation) RemovedIDs(name string) []ent.Value { +func (m *UserReferralProfileMutation) RemovedIDs(name string) []ent.Value { return nil } // ClearedEdges returns all edge names that were cleared in this mutation. -func (m *UserAttributeValueMutation) ClearedEdges() []string { - edges := make([]string, 0, 2) +func (m *UserReferralProfileMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) if m.cleareduser { - edges = append(edges, userattributevalue.EdgeUser) - } - if m.cleareddefinition { - edges = append(edges, userattributevalue.EdgeDefinition) + edges = append(edges, userreferralprofile.EdgeUser) } return edges } // EdgeCleared returns a boolean which indicates if the edge with the given name // was cleared in this mutation. -func (m *UserAttributeValueMutation) EdgeCleared(name string) bool { +func (m *UserReferralProfileMutation) EdgeCleared(name string) bool { switch name { - case userattributevalue.EdgeUser: + case userreferralprofile.EdgeUser: return m.cleareduser - case userattributevalue.EdgeDefinition: - return m.cleareddefinition } return false } // ClearEdge clears the value of the edge with the given name. It returns an error // if that edge is not defined in the schema. -func (m *UserAttributeValueMutation) ClearEdge(name string) error { +func (m *UserReferralProfileMutation) ClearEdge(name string) error { switch name { - case userattributevalue.EdgeUser: + case userreferralprofile.EdgeUser: m.ClearUser() return nil - case userattributevalue.EdgeDefinition: - m.ClearDefinition() - return nil } - return fmt.Errorf("unknown UserAttributeValue unique edge %s", name) + return fmt.Errorf("unknown UserReferralProfile unique edge %s", name) } // ResetEdge resets all changes to the edge with the given name in this mutation. // It returns an error if the edge is not defined in the schema. -func (m *UserAttributeValueMutation) ResetEdge(name string) error { +func (m *UserReferralProfileMutation) ResetEdge(name string) error { switch name { - case userattributevalue.EdgeUser: + case userreferralprofile.EdgeUser: m.ResetUser() return nil - case userattributevalue.EdgeDefinition: - m.ResetDefinition() - return nil } - return fmt.Errorf("unknown UserAttributeValue edge %s", name) + return fmt.Errorf("unknown UserReferralProfile edge %s", name) } // UserSubscriptionMutation represents an operation that mutates the UserSubscription nodes in the graph. diff --git a/backend/ent/predicate/predicate.go b/backend/ent/predicate/predicate.go index 89d933fcd..803b09c56 100644 --- a/backend/ent/predicate/predicate.go +++ b/backend/ent/predicate/predicate.go @@ -42,6 +42,9 @@ type Proxy func(*sql.Selector) // RedeemCode is the predicate function for redeemcode builders. type RedeemCode func(*sql.Selector) +// ReferralRelation is the predicate function for referralrelation builders. +type ReferralRelation func(*sql.Selector) + // SecuritySecret is the predicate function for securitysecret builders. type SecuritySecret func(*sql.Selector) @@ -66,5 +69,8 @@ type UserAttributeDefinition func(*sql.Selector) // UserAttributeValue is the predicate function for userattributevalue builders. type UserAttributeValue func(*sql.Selector) +// UserReferralProfile is the predicate function for userreferralprofile builders. +type UserReferralProfile func(*sql.Selector) + // UserSubscription is the predicate function for usersubscription builders. type UserSubscription func(*sql.Selector) diff --git a/backend/ent/referralrelation.go b/backend/ent/referralrelation.go new file mode 100644 index 000000000..9fb4ff3dd --- /dev/null +++ b/backend/ent/referralrelation.go @@ -0,0 +1,210 @@ +// 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/referralrelation" + "github.com/Wei-Shaw/sub2api/ent/user" +) + +// ReferralRelation is the model entity for the ReferralRelation schema. +type ReferralRelation struct { + config `json:"-"` + // ID of the ent. + ID int64 `json:"id,omitempty"` + // 邀请人的 user_id + InviterID int64 `json:"inviter_id,omitempty"` + // 被邀请人的 user_id,唯一约束确保一人只能被邀请一次 + InviteeID int64 `json:"invitee_id,omitempty"` + // 发放给邀请人的余额奖励(创建时快照,不受后续配置变更影响) + InviterReward float64 `json:"inviter_reward,omitempty"` + // 发放给被邀请人的余额奖励(创建时快照) + InviteeReward float64 `json:"invitee_reward,omitempty"` + // 奖励是否已发放,防止重复发放(幂等标志) + RewardGranted bool `json:"reward_granted,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the ReferralRelationQuery when eager-loading is set. + Edges ReferralRelationEdges `json:"edges"` + selectValues sql.SelectValues +} + +// ReferralRelationEdges holds the relations/edges for other nodes in the graph. +type ReferralRelationEdges struct { + // Inviter holds the value of the inviter edge. + Inviter *User `json:"inviter,omitempty"` + // Invitee holds the value of the invitee edge. + Invitee *User `json:"invitee,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// InviterOrErr returns the Inviter value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ReferralRelationEdges) InviterOrErr() (*User, error) { + if e.Inviter != nil { + return e.Inviter, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: user.Label} + } + return nil, &NotLoadedError{edge: "inviter"} +} + +// InviteeOrErr returns the Invitee value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ReferralRelationEdges) InviteeOrErr() (*User, error) { + if e.Invitee != nil { + return e.Invitee, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: user.Label} + } + return nil, &NotLoadedError{edge: "invitee"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*ReferralRelation) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case referralrelation.FieldRewardGranted: + values[i] = new(sql.NullBool) + case referralrelation.FieldInviterReward, referralrelation.FieldInviteeReward: + values[i] = new(sql.NullFloat64) + case referralrelation.FieldID, referralrelation.FieldInviterID, referralrelation.FieldInviteeID: + values[i] = new(sql.NullInt64) + case referralrelation.FieldCreatedAt: + 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 ReferralRelation fields. +func (_m *ReferralRelation) 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 referralrelation.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 referralrelation.FieldInviterID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field inviter_id", values[i]) + } else if value.Valid { + _m.InviterID = value.Int64 + } + case referralrelation.FieldInviteeID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field invitee_id", values[i]) + } else if value.Valid { + _m.InviteeID = value.Int64 + } + case referralrelation.FieldInviterReward: + if value, ok := values[i].(*sql.NullFloat64); !ok { + return fmt.Errorf("unexpected type %T for field inviter_reward", values[i]) + } else if value.Valid { + _m.InviterReward = value.Float64 + } + case referralrelation.FieldInviteeReward: + if value, ok := values[i].(*sql.NullFloat64); !ok { + return fmt.Errorf("unexpected type %T for field invitee_reward", values[i]) + } else if value.Valid { + _m.InviteeReward = value.Float64 + } + case referralrelation.FieldRewardGranted: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field reward_granted", values[i]) + } else if value.Valid { + _m.RewardGranted = value.Bool + } + case referralrelation.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 + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the ReferralRelation. +// This includes values selected through modifiers, order, etc. +func (_m *ReferralRelation) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryInviter queries the "inviter" edge of the ReferralRelation entity. +func (_m *ReferralRelation) QueryInviter() *UserQuery { + return NewReferralRelationClient(_m.config).QueryInviter(_m) +} + +// QueryInvitee queries the "invitee" edge of the ReferralRelation entity. +func (_m *ReferralRelation) QueryInvitee() *UserQuery { + return NewReferralRelationClient(_m.config).QueryInvitee(_m) +} + +// Update returns a builder for updating this ReferralRelation. +// Note that you need to call ReferralRelation.Unwrap() before calling this method if this ReferralRelation +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *ReferralRelation) Update() *ReferralRelationUpdateOne { + return NewReferralRelationClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the ReferralRelation 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 *ReferralRelation) Unwrap() *ReferralRelation { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: ReferralRelation is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *ReferralRelation) String() string { + var builder strings.Builder + builder.WriteString("ReferralRelation(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("inviter_id=") + builder.WriteString(fmt.Sprintf("%v", _m.InviterID)) + builder.WriteString(", ") + builder.WriteString("invitee_id=") + builder.WriteString(fmt.Sprintf("%v", _m.InviteeID)) + builder.WriteString(", ") + builder.WriteString("inviter_reward=") + builder.WriteString(fmt.Sprintf("%v", _m.InviterReward)) + builder.WriteString(", ") + builder.WriteString("invitee_reward=") + builder.WriteString(fmt.Sprintf("%v", _m.InviteeReward)) + builder.WriteString(", ") + builder.WriteString("reward_granted=") + builder.WriteString(fmt.Sprintf("%v", _m.RewardGranted)) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// ReferralRelations is a parsable slice of ReferralRelation. +type ReferralRelations []*ReferralRelation diff --git a/backend/ent/referralrelation/referralrelation.go b/backend/ent/referralrelation/referralrelation.go new file mode 100644 index 000000000..d1d825c0d --- /dev/null +++ b/backend/ent/referralrelation/referralrelation.go @@ -0,0 +1,151 @@ +// Code generated by ent, DO NOT EDIT. + +package referralrelation + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the referralrelation type in the database. + Label = "referral_relation" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldInviterID holds the string denoting the inviter_id field in the database. + FieldInviterID = "inviter_id" + // FieldInviteeID holds the string denoting the invitee_id field in the database. + FieldInviteeID = "invitee_id" + // FieldInviterReward holds the string denoting the inviter_reward field in the database. + FieldInviterReward = "inviter_reward" + // FieldInviteeReward holds the string denoting the invitee_reward field in the database. + FieldInviteeReward = "invitee_reward" + // FieldRewardGranted holds the string denoting the reward_granted field in the database. + FieldRewardGranted = "reward_granted" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // EdgeInviter holds the string denoting the inviter edge name in mutations. + EdgeInviter = "inviter" + // EdgeInvitee holds the string denoting the invitee edge name in mutations. + EdgeInvitee = "invitee" + // Table holds the table name of the referralrelation in the database. + Table = "referral_relations" + // InviterTable is the table that holds the inviter relation/edge. + InviterTable = "referral_relations" + // InviterInverseTable is the table name for the User entity. + // It exists in this package in order to avoid circular dependency with the "user" package. + InviterInverseTable = "users" + // InviterColumn is the table column denoting the inviter relation/edge. + InviterColumn = "inviter_id" + // InviteeTable is the table that holds the invitee relation/edge. + InviteeTable = "referral_relations" + // InviteeInverseTable is the table name for the User entity. + // It exists in this package in order to avoid circular dependency with the "user" package. + InviteeInverseTable = "users" + // InviteeColumn is the table column denoting the invitee relation/edge. + InviteeColumn = "invitee_id" +) + +// Columns holds all SQL columns for referralrelation fields. +var Columns = []string{ + FieldID, + FieldInviterID, + FieldInviteeID, + FieldInviterReward, + FieldInviteeReward, + FieldRewardGranted, + FieldCreatedAt, +} + +// 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 ( + // InviterIDValidator is a validator for the "inviter_id" field. It is called by the builders before save. + InviterIDValidator func(int64) error + // InviteeIDValidator is a validator for the "invitee_id" field. It is called by the builders before save. + InviteeIDValidator func(int64) error + // DefaultInviterReward holds the default value on creation for the "inviter_reward" field. + DefaultInviterReward float64 + // DefaultInviteeReward holds the default value on creation for the "invitee_reward" field. + DefaultInviteeReward float64 + // DefaultRewardGranted holds the default value on creation for the "reward_granted" field. + DefaultRewardGranted bool + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time +) + +// OrderOption defines the ordering options for the ReferralRelation 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() +} + +// ByInviterID orders the results by the inviter_id field. +func ByInviterID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInviterID, opts...).ToFunc() +} + +// ByInviteeID orders the results by the invitee_id field. +func ByInviteeID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInviteeID, opts...).ToFunc() +} + +// ByInviterReward orders the results by the inviter_reward field. +func ByInviterReward(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInviterReward, opts...).ToFunc() +} + +// ByInviteeReward orders the results by the invitee_reward field. +func ByInviteeReward(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInviteeReward, opts...).ToFunc() +} + +// ByRewardGranted orders the results by the reward_granted field. +func ByRewardGranted(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRewardGranted, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByInviterField orders the results by inviter field. +func ByInviterField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newInviterStep(), sql.OrderByField(field, opts...)) + } +} + +// ByInviteeField orders the results by invitee field. +func ByInviteeField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newInviteeStep(), sql.OrderByField(field, opts...)) + } +} +func newInviterStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(InviterInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, InviterTable, InviterColumn), + ) +} +func newInviteeStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(InviteeInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, InviteeTable, InviteeColumn), + ) +} diff --git a/backend/ent/referralrelation/where.go b/backend/ent/referralrelation/where.go new file mode 100644 index 000000000..3df7558b7 --- /dev/null +++ b/backend/ent/referralrelation/where.go @@ -0,0 +1,317 @@ +// Code generated by ent, DO NOT EDIT. + +package referralrelation + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/Wei-Shaw/sub2api/ent/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id int64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldLTE(FieldID, id)) +} + +// InviterID applies equality check predicate on the "inviter_id" field. It's identical to InviterIDEQ. +func InviterID(v int64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldEQ(FieldInviterID, v)) +} + +// InviteeID applies equality check predicate on the "invitee_id" field. It's identical to InviteeIDEQ. +func InviteeID(v int64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldEQ(FieldInviteeID, v)) +} + +// InviterReward applies equality check predicate on the "inviter_reward" field. It's identical to InviterRewardEQ. +func InviterReward(v float64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldEQ(FieldInviterReward, v)) +} + +// InviteeReward applies equality check predicate on the "invitee_reward" field. It's identical to InviteeRewardEQ. +func InviteeReward(v float64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldEQ(FieldInviteeReward, v)) +} + +// RewardGranted applies equality check predicate on the "reward_granted" field. It's identical to RewardGrantedEQ. +func RewardGranted(v bool) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldEQ(FieldRewardGranted, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldEQ(FieldCreatedAt, v)) +} + +// InviterIDEQ applies the EQ predicate on the "inviter_id" field. +func InviterIDEQ(v int64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldEQ(FieldInviterID, v)) +} + +// InviterIDNEQ applies the NEQ predicate on the "inviter_id" field. +func InviterIDNEQ(v int64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldNEQ(FieldInviterID, v)) +} + +// InviterIDIn applies the In predicate on the "inviter_id" field. +func InviterIDIn(vs ...int64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldIn(FieldInviterID, vs...)) +} + +// InviterIDNotIn applies the NotIn predicate on the "inviter_id" field. +func InviterIDNotIn(vs ...int64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldNotIn(FieldInviterID, vs...)) +} + +// InviteeIDEQ applies the EQ predicate on the "invitee_id" field. +func InviteeIDEQ(v int64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldEQ(FieldInviteeID, v)) +} + +// InviteeIDNEQ applies the NEQ predicate on the "invitee_id" field. +func InviteeIDNEQ(v int64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldNEQ(FieldInviteeID, v)) +} + +// InviteeIDIn applies the In predicate on the "invitee_id" field. +func InviteeIDIn(vs ...int64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldIn(FieldInviteeID, vs...)) +} + +// InviteeIDNotIn applies the NotIn predicate on the "invitee_id" field. +func InviteeIDNotIn(vs ...int64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldNotIn(FieldInviteeID, vs...)) +} + +// InviterRewardEQ applies the EQ predicate on the "inviter_reward" field. +func InviterRewardEQ(v float64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldEQ(FieldInviterReward, v)) +} + +// InviterRewardNEQ applies the NEQ predicate on the "inviter_reward" field. +func InviterRewardNEQ(v float64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldNEQ(FieldInviterReward, v)) +} + +// InviterRewardIn applies the In predicate on the "inviter_reward" field. +func InviterRewardIn(vs ...float64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldIn(FieldInviterReward, vs...)) +} + +// InviterRewardNotIn applies the NotIn predicate on the "inviter_reward" field. +func InviterRewardNotIn(vs ...float64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldNotIn(FieldInviterReward, vs...)) +} + +// InviterRewardGT applies the GT predicate on the "inviter_reward" field. +func InviterRewardGT(v float64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldGT(FieldInviterReward, v)) +} + +// InviterRewardGTE applies the GTE predicate on the "inviter_reward" field. +func InviterRewardGTE(v float64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldGTE(FieldInviterReward, v)) +} + +// InviterRewardLT applies the LT predicate on the "inviter_reward" field. +func InviterRewardLT(v float64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldLT(FieldInviterReward, v)) +} + +// InviterRewardLTE applies the LTE predicate on the "inviter_reward" field. +func InviterRewardLTE(v float64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldLTE(FieldInviterReward, v)) +} + +// InviteeRewardEQ applies the EQ predicate on the "invitee_reward" field. +func InviteeRewardEQ(v float64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldEQ(FieldInviteeReward, v)) +} + +// InviteeRewardNEQ applies the NEQ predicate on the "invitee_reward" field. +func InviteeRewardNEQ(v float64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldNEQ(FieldInviteeReward, v)) +} + +// InviteeRewardIn applies the In predicate on the "invitee_reward" field. +func InviteeRewardIn(vs ...float64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldIn(FieldInviteeReward, vs...)) +} + +// InviteeRewardNotIn applies the NotIn predicate on the "invitee_reward" field. +func InviteeRewardNotIn(vs ...float64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldNotIn(FieldInviteeReward, vs...)) +} + +// InviteeRewardGT applies the GT predicate on the "invitee_reward" field. +func InviteeRewardGT(v float64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldGT(FieldInviteeReward, v)) +} + +// InviteeRewardGTE applies the GTE predicate on the "invitee_reward" field. +func InviteeRewardGTE(v float64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldGTE(FieldInviteeReward, v)) +} + +// InviteeRewardLT applies the LT predicate on the "invitee_reward" field. +func InviteeRewardLT(v float64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldLT(FieldInviteeReward, v)) +} + +// InviteeRewardLTE applies the LTE predicate on the "invitee_reward" field. +func InviteeRewardLTE(v float64) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldLTE(FieldInviteeReward, v)) +} + +// RewardGrantedEQ applies the EQ predicate on the "reward_granted" field. +func RewardGrantedEQ(v bool) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldEQ(FieldRewardGranted, v)) +} + +// RewardGrantedNEQ applies the NEQ predicate on the "reward_granted" field. +func RewardGrantedNEQ(v bool) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldNEQ(FieldRewardGranted, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.FieldLTE(FieldCreatedAt, v)) +} + +// HasInviter applies the HasEdge predicate on the "inviter" edge. +func HasInviter() predicate.ReferralRelation { + return predicate.ReferralRelation(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, InviterTable, InviterColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasInviterWith applies the HasEdge predicate on the "inviter" edge with a given conditions (other predicates). +func HasInviterWith(preds ...predicate.User) predicate.ReferralRelation { + return predicate.ReferralRelation(func(s *sql.Selector) { + step := newInviterStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasInvitee applies the HasEdge predicate on the "invitee" edge. +func HasInvitee() predicate.ReferralRelation { + return predicate.ReferralRelation(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, InviteeTable, InviteeColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasInviteeWith applies the HasEdge predicate on the "invitee" edge with a given conditions (other predicates). +func HasInviteeWith(preds ...predicate.User) predicate.ReferralRelation { + return predicate.ReferralRelation(func(s *sql.Selector) { + step := newInviteeStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.ReferralRelation) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.ReferralRelation) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.ReferralRelation) predicate.ReferralRelation { + return predicate.ReferralRelation(sql.NotPredicates(p)) +} diff --git a/backend/ent/referralrelation_create.go b/backend/ent/referralrelation_create.go new file mode 100644 index 000000000..488aadbaf --- /dev/null +++ b/backend/ent/referralrelation_create.go @@ -0,0 +1,839 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/Wei-Shaw/sub2api/ent/referralrelation" + "github.com/Wei-Shaw/sub2api/ent/user" +) + +// ReferralRelationCreate is the builder for creating a ReferralRelation entity. +type ReferralRelationCreate struct { + config + mutation *ReferralRelationMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetInviterID sets the "inviter_id" field. +func (_c *ReferralRelationCreate) SetInviterID(v int64) *ReferralRelationCreate { + _c.mutation.SetInviterID(v) + return _c +} + +// SetInviteeID sets the "invitee_id" field. +func (_c *ReferralRelationCreate) SetInviteeID(v int64) *ReferralRelationCreate { + _c.mutation.SetInviteeID(v) + return _c +} + +// SetInviterReward sets the "inviter_reward" field. +func (_c *ReferralRelationCreate) SetInviterReward(v float64) *ReferralRelationCreate { + _c.mutation.SetInviterReward(v) + return _c +} + +// SetNillableInviterReward sets the "inviter_reward" field if the given value is not nil. +func (_c *ReferralRelationCreate) SetNillableInviterReward(v *float64) *ReferralRelationCreate { + if v != nil { + _c.SetInviterReward(*v) + } + return _c +} + +// SetInviteeReward sets the "invitee_reward" field. +func (_c *ReferralRelationCreate) SetInviteeReward(v float64) *ReferralRelationCreate { + _c.mutation.SetInviteeReward(v) + return _c +} + +// SetNillableInviteeReward sets the "invitee_reward" field if the given value is not nil. +func (_c *ReferralRelationCreate) SetNillableInviteeReward(v *float64) *ReferralRelationCreate { + if v != nil { + _c.SetInviteeReward(*v) + } + return _c +} + +// SetRewardGranted sets the "reward_granted" field. +func (_c *ReferralRelationCreate) SetRewardGranted(v bool) *ReferralRelationCreate { + _c.mutation.SetRewardGranted(v) + return _c +} + +// SetNillableRewardGranted sets the "reward_granted" field if the given value is not nil. +func (_c *ReferralRelationCreate) SetNillableRewardGranted(v *bool) *ReferralRelationCreate { + if v != nil { + _c.SetRewardGranted(*v) + } + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *ReferralRelationCreate) SetCreatedAt(v time.Time) *ReferralRelationCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *ReferralRelationCreate) SetNillableCreatedAt(v *time.Time) *ReferralRelationCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetInviter sets the "inviter" edge to the User entity. +func (_c *ReferralRelationCreate) SetInviter(v *User) *ReferralRelationCreate { + return _c.SetInviterID(v.ID) +} + +// SetInvitee sets the "invitee" edge to the User entity. +func (_c *ReferralRelationCreate) SetInvitee(v *User) *ReferralRelationCreate { + return _c.SetInviteeID(v.ID) +} + +// Mutation returns the ReferralRelationMutation object of the builder. +func (_c *ReferralRelationCreate) Mutation() *ReferralRelationMutation { + return _c.mutation +} + +// Save creates the ReferralRelation in the database. +func (_c *ReferralRelationCreate) Save(ctx context.Context) (*ReferralRelation, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *ReferralRelationCreate) SaveX(ctx context.Context) *ReferralRelation { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ReferralRelationCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ReferralRelationCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *ReferralRelationCreate) defaults() { + if _, ok := _c.mutation.InviterReward(); !ok { + v := referralrelation.DefaultInviterReward + _c.mutation.SetInviterReward(v) + } + if _, ok := _c.mutation.InviteeReward(); !ok { + v := referralrelation.DefaultInviteeReward + _c.mutation.SetInviteeReward(v) + } + if _, ok := _c.mutation.RewardGranted(); !ok { + v := referralrelation.DefaultRewardGranted + _c.mutation.SetRewardGranted(v) + } + if _, ok := _c.mutation.CreatedAt(); !ok { + v := referralrelation.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *ReferralRelationCreate) check() error { + if _, ok := _c.mutation.InviterID(); !ok { + return &ValidationError{Name: "inviter_id", err: errors.New(`ent: missing required field "ReferralRelation.inviter_id"`)} + } + if v, ok := _c.mutation.InviterID(); ok { + if err := referralrelation.InviterIDValidator(v); err != nil { + return &ValidationError{Name: "inviter_id", err: fmt.Errorf(`ent: validator failed for field "ReferralRelation.inviter_id": %w`, err)} + } + } + if _, ok := _c.mutation.InviteeID(); !ok { + return &ValidationError{Name: "invitee_id", err: errors.New(`ent: missing required field "ReferralRelation.invitee_id"`)} + } + if v, ok := _c.mutation.InviteeID(); ok { + if err := referralrelation.InviteeIDValidator(v); err != nil { + return &ValidationError{Name: "invitee_id", err: fmt.Errorf(`ent: validator failed for field "ReferralRelation.invitee_id": %w`, err)} + } + } + if _, ok := _c.mutation.InviterReward(); !ok { + return &ValidationError{Name: "inviter_reward", err: errors.New(`ent: missing required field "ReferralRelation.inviter_reward"`)} + } + if _, ok := _c.mutation.InviteeReward(); !ok { + return &ValidationError{Name: "invitee_reward", err: errors.New(`ent: missing required field "ReferralRelation.invitee_reward"`)} + } + if _, ok := _c.mutation.RewardGranted(); !ok { + return &ValidationError{Name: "reward_granted", err: errors.New(`ent: missing required field "ReferralRelation.reward_granted"`)} + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "ReferralRelation.created_at"`)} + } + if len(_c.mutation.InviterIDs()) == 0 { + return &ValidationError{Name: "inviter", err: errors.New(`ent: missing required edge "ReferralRelation.inviter"`)} + } + if len(_c.mutation.InviteeIDs()) == 0 { + return &ValidationError{Name: "invitee", err: errors.New(`ent: missing required edge "ReferralRelation.invitee"`)} + } + return nil +} + +func (_c *ReferralRelationCreate) sqlSave(ctx context.Context) (*ReferralRelation, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int64(id) + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *ReferralRelationCreate) createSpec() (*ReferralRelation, *sqlgraph.CreateSpec) { + var ( + _node = &ReferralRelation{config: _c.config} + _spec = sqlgraph.NewCreateSpec(referralrelation.Table, sqlgraph.NewFieldSpec(referralrelation.FieldID, field.TypeInt64)) + ) + _spec.OnConflict = _c.conflict + if value, ok := _c.mutation.InviterReward(); ok { + _spec.SetField(referralrelation.FieldInviterReward, field.TypeFloat64, value) + _node.InviterReward = value + } + if value, ok := _c.mutation.InviteeReward(); ok { + _spec.SetField(referralrelation.FieldInviteeReward, field.TypeFloat64, value) + _node.InviteeReward = value + } + if value, ok := _c.mutation.RewardGranted(); ok { + _spec.SetField(referralrelation.FieldRewardGranted, field.TypeBool, value) + _node.RewardGranted = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(referralrelation.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if nodes := _c.mutation.InviterIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: referralrelation.InviterTable, + Columns: []string{referralrelation.InviterColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.InviterID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.InviteeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: referralrelation.InviteeTable, + Columns: []string{referralrelation.InviteeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.InviteeID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.ReferralRelation.Create(). +// SetInviterID(v). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.ReferralRelationUpsert) { +// SetInviterID(v+v). +// }). +// Exec(ctx) +func (_c *ReferralRelationCreate) OnConflict(opts ...sql.ConflictOption) *ReferralRelationUpsertOne { + _c.conflict = opts + return &ReferralRelationUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ReferralRelation.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ReferralRelationCreate) OnConflictColumns(columns ...string) *ReferralRelationUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ReferralRelationUpsertOne{ + create: _c, + } +} + +type ( + // ReferralRelationUpsertOne is the builder for "upsert"-ing + // one ReferralRelation node. + ReferralRelationUpsertOne struct { + create *ReferralRelationCreate + } + + // ReferralRelationUpsert is the "OnConflict" setter. + ReferralRelationUpsert struct { + *sql.UpdateSet + } +) + +// SetInviterID sets the "inviter_id" field. +func (u *ReferralRelationUpsert) SetInviterID(v int64) *ReferralRelationUpsert { + u.Set(referralrelation.FieldInviterID, v) + return u +} + +// UpdateInviterID sets the "inviter_id" field to the value that was provided on create. +func (u *ReferralRelationUpsert) UpdateInviterID() *ReferralRelationUpsert { + u.SetExcluded(referralrelation.FieldInviterID) + return u +} + +// SetInviteeID sets the "invitee_id" field. +func (u *ReferralRelationUpsert) SetInviteeID(v int64) *ReferralRelationUpsert { + u.Set(referralrelation.FieldInviteeID, v) + return u +} + +// UpdateInviteeID sets the "invitee_id" field to the value that was provided on create. +func (u *ReferralRelationUpsert) UpdateInviteeID() *ReferralRelationUpsert { + u.SetExcluded(referralrelation.FieldInviteeID) + return u +} + +// SetInviterReward sets the "inviter_reward" field. +func (u *ReferralRelationUpsert) SetInviterReward(v float64) *ReferralRelationUpsert { + u.Set(referralrelation.FieldInviterReward, v) + return u +} + +// UpdateInviterReward sets the "inviter_reward" field to the value that was provided on create. +func (u *ReferralRelationUpsert) UpdateInviterReward() *ReferralRelationUpsert { + u.SetExcluded(referralrelation.FieldInviterReward) + return u +} + +// AddInviterReward adds v to the "inviter_reward" field. +func (u *ReferralRelationUpsert) AddInviterReward(v float64) *ReferralRelationUpsert { + u.Add(referralrelation.FieldInviterReward, v) + return u +} + +// SetInviteeReward sets the "invitee_reward" field. +func (u *ReferralRelationUpsert) SetInviteeReward(v float64) *ReferralRelationUpsert { + u.Set(referralrelation.FieldInviteeReward, v) + return u +} + +// UpdateInviteeReward sets the "invitee_reward" field to the value that was provided on create. +func (u *ReferralRelationUpsert) UpdateInviteeReward() *ReferralRelationUpsert { + u.SetExcluded(referralrelation.FieldInviteeReward) + return u +} + +// AddInviteeReward adds v to the "invitee_reward" field. +func (u *ReferralRelationUpsert) AddInviteeReward(v float64) *ReferralRelationUpsert { + u.Add(referralrelation.FieldInviteeReward, v) + return u +} + +// SetRewardGranted sets the "reward_granted" field. +func (u *ReferralRelationUpsert) SetRewardGranted(v bool) *ReferralRelationUpsert { + u.Set(referralrelation.FieldRewardGranted, v) + return u +} + +// UpdateRewardGranted sets the "reward_granted" field to the value that was provided on create. +func (u *ReferralRelationUpsert) UpdateRewardGranted() *ReferralRelationUpsert { + u.SetExcluded(referralrelation.FieldRewardGranted) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create. +// Using this option is equivalent to using: +// +// client.ReferralRelation.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// ). +// Exec(ctx) +func (u *ReferralRelationUpsertOne) UpdateNewValues() *ReferralRelationUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(referralrelation.FieldCreatedAt) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ReferralRelation.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ReferralRelationUpsertOne) Ignore() *ReferralRelationUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *ReferralRelationUpsertOne) DoNothing() *ReferralRelationUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ReferralRelationCreate.OnConflict +// documentation for more info. +func (u *ReferralRelationUpsertOne) Update(set func(*ReferralRelationUpsert)) *ReferralRelationUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ReferralRelationUpsert{UpdateSet: update}) + })) + return u +} + +// SetInviterID sets the "inviter_id" field. +func (u *ReferralRelationUpsertOne) SetInviterID(v int64) *ReferralRelationUpsertOne { + return u.Update(func(s *ReferralRelationUpsert) { + s.SetInviterID(v) + }) +} + +// UpdateInviterID sets the "inviter_id" field to the value that was provided on create. +func (u *ReferralRelationUpsertOne) UpdateInviterID() *ReferralRelationUpsertOne { + return u.Update(func(s *ReferralRelationUpsert) { + s.UpdateInviterID() + }) +} + +// SetInviteeID sets the "invitee_id" field. +func (u *ReferralRelationUpsertOne) SetInviteeID(v int64) *ReferralRelationUpsertOne { + return u.Update(func(s *ReferralRelationUpsert) { + s.SetInviteeID(v) + }) +} + +// UpdateInviteeID sets the "invitee_id" field to the value that was provided on create. +func (u *ReferralRelationUpsertOne) UpdateInviteeID() *ReferralRelationUpsertOne { + return u.Update(func(s *ReferralRelationUpsert) { + s.UpdateInviteeID() + }) +} + +// SetInviterReward sets the "inviter_reward" field. +func (u *ReferralRelationUpsertOne) SetInviterReward(v float64) *ReferralRelationUpsertOne { + return u.Update(func(s *ReferralRelationUpsert) { + s.SetInviterReward(v) + }) +} + +// AddInviterReward adds v to the "inviter_reward" field. +func (u *ReferralRelationUpsertOne) AddInviterReward(v float64) *ReferralRelationUpsertOne { + return u.Update(func(s *ReferralRelationUpsert) { + s.AddInviterReward(v) + }) +} + +// UpdateInviterReward sets the "inviter_reward" field to the value that was provided on create. +func (u *ReferralRelationUpsertOne) UpdateInviterReward() *ReferralRelationUpsertOne { + return u.Update(func(s *ReferralRelationUpsert) { + s.UpdateInviterReward() + }) +} + +// SetInviteeReward sets the "invitee_reward" field. +func (u *ReferralRelationUpsertOne) SetInviteeReward(v float64) *ReferralRelationUpsertOne { + return u.Update(func(s *ReferralRelationUpsert) { + s.SetInviteeReward(v) + }) +} + +// AddInviteeReward adds v to the "invitee_reward" field. +func (u *ReferralRelationUpsertOne) AddInviteeReward(v float64) *ReferralRelationUpsertOne { + return u.Update(func(s *ReferralRelationUpsert) { + s.AddInviteeReward(v) + }) +} + +// UpdateInviteeReward sets the "invitee_reward" field to the value that was provided on create. +func (u *ReferralRelationUpsertOne) UpdateInviteeReward() *ReferralRelationUpsertOne { + return u.Update(func(s *ReferralRelationUpsert) { + s.UpdateInviteeReward() + }) +} + +// SetRewardGranted sets the "reward_granted" field. +func (u *ReferralRelationUpsertOne) SetRewardGranted(v bool) *ReferralRelationUpsertOne { + return u.Update(func(s *ReferralRelationUpsert) { + s.SetRewardGranted(v) + }) +} + +// UpdateRewardGranted sets the "reward_granted" field to the value that was provided on create. +func (u *ReferralRelationUpsertOne) UpdateRewardGranted() *ReferralRelationUpsertOne { + return u.Update(func(s *ReferralRelationUpsert) { + s.UpdateRewardGranted() + }) +} + +// Exec executes the query. +func (u *ReferralRelationUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for ReferralRelationCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ReferralRelationUpsertOne) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} + +// Exec executes the UPSERT query and returns the inserted/updated ID. +func (u *ReferralRelationUpsertOne) ID(ctx context.Context) (id int64, err error) { + node, err := u.create.Save(ctx) + if err != nil { + return id, err + } + return node.ID, nil +} + +// IDX is like ID, but panics if an error occurs. +func (u *ReferralRelationUpsertOne) IDX(ctx context.Context) int64 { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// ReferralRelationCreateBulk is the builder for creating many ReferralRelation entities in bulk. +type ReferralRelationCreateBulk struct { + config + err error + builders []*ReferralRelationCreate + conflict []sql.ConflictOption +} + +// Save creates the ReferralRelation entities in the database. +func (_c *ReferralRelationCreateBulk) Save(ctx context.Context) ([]*ReferralRelation, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*ReferralRelation, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*ReferralRelationMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = _c.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int64(id) + } + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *ReferralRelationCreateBulk) SaveX(ctx context.Context) []*ReferralRelation { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ReferralRelationCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ReferralRelationCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.ReferralRelation.CreateBulk(builders...). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.ReferralRelationUpsert) { +// SetInviterID(v+v). +// }). +// Exec(ctx) +func (_c *ReferralRelationCreateBulk) OnConflict(opts ...sql.ConflictOption) *ReferralRelationUpsertBulk { + _c.conflict = opts + return &ReferralRelationUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ReferralRelation.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ReferralRelationCreateBulk) OnConflictColumns(columns ...string) *ReferralRelationUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ReferralRelationUpsertBulk{ + create: _c, + } +} + +// ReferralRelationUpsertBulk is the builder for "upsert"-ing +// a bulk of ReferralRelation nodes. +type ReferralRelationUpsertBulk struct { + create *ReferralRelationCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.ReferralRelation.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// ). +// Exec(ctx) +func (u *ReferralRelationUpsertBulk) UpdateNewValues() *ReferralRelationUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + for _, b := range u.create.builders { + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(referralrelation.FieldCreatedAt) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ReferralRelation.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ReferralRelationUpsertBulk) Ignore() *ReferralRelationUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *ReferralRelationUpsertBulk) DoNothing() *ReferralRelationUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ReferralRelationCreateBulk.OnConflict +// documentation for more info. +func (u *ReferralRelationUpsertBulk) Update(set func(*ReferralRelationUpsert)) *ReferralRelationUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ReferralRelationUpsert{UpdateSet: update}) + })) + return u +} + +// SetInviterID sets the "inviter_id" field. +func (u *ReferralRelationUpsertBulk) SetInviterID(v int64) *ReferralRelationUpsertBulk { + return u.Update(func(s *ReferralRelationUpsert) { + s.SetInviterID(v) + }) +} + +// UpdateInviterID sets the "inviter_id" field to the value that was provided on create. +func (u *ReferralRelationUpsertBulk) UpdateInviterID() *ReferralRelationUpsertBulk { + return u.Update(func(s *ReferralRelationUpsert) { + s.UpdateInviterID() + }) +} + +// SetInviteeID sets the "invitee_id" field. +func (u *ReferralRelationUpsertBulk) SetInviteeID(v int64) *ReferralRelationUpsertBulk { + return u.Update(func(s *ReferralRelationUpsert) { + s.SetInviteeID(v) + }) +} + +// UpdateInviteeID sets the "invitee_id" field to the value that was provided on create. +func (u *ReferralRelationUpsertBulk) UpdateInviteeID() *ReferralRelationUpsertBulk { + return u.Update(func(s *ReferralRelationUpsert) { + s.UpdateInviteeID() + }) +} + +// SetInviterReward sets the "inviter_reward" field. +func (u *ReferralRelationUpsertBulk) SetInviterReward(v float64) *ReferralRelationUpsertBulk { + return u.Update(func(s *ReferralRelationUpsert) { + s.SetInviterReward(v) + }) +} + +// AddInviterReward adds v to the "inviter_reward" field. +func (u *ReferralRelationUpsertBulk) AddInviterReward(v float64) *ReferralRelationUpsertBulk { + return u.Update(func(s *ReferralRelationUpsert) { + s.AddInviterReward(v) + }) +} + +// UpdateInviterReward sets the "inviter_reward" field to the value that was provided on create. +func (u *ReferralRelationUpsertBulk) UpdateInviterReward() *ReferralRelationUpsertBulk { + return u.Update(func(s *ReferralRelationUpsert) { + s.UpdateInviterReward() + }) +} + +// SetInviteeReward sets the "invitee_reward" field. +func (u *ReferralRelationUpsertBulk) SetInviteeReward(v float64) *ReferralRelationUpsertBulk { + return u.Update(func(s *ReferralRelationUpsert) { + s.SetInviteeReward(v) + }) +} + +// AddInviteeReward adds v to the "invitee_reward" field. +func (u *ReferralRelationUpsertBulk) AddInviteeReward(v float64) *ReferralRelationUpsertBulk { + return u.Update(func(s *ReferralRelationUpsert) { + s.AddInviteeReward(v) + }) +} + +// UpdateInviteeReward sets the "invitee_reward" field to the value that was provided on create. +func (u *ReferralRelationUpsertBulk) UpdateInviteeReward() *ReferralRelationUpsertBulk { + return u.Update(func(s *ReferralRelationUpsert) { + s.UpdateInviteeReward() + }) +} + +// SetRewardGranted sets the "reward_granted" field. +func (u *ReferralRelationUpsertBulk) SetRewardGranted(v bool) *ReferralRelationUpsertBulk { + return u.Update(func(s *ReferralRelationUpsert) { + s.SetRewardGranted(v) + }) +} + +// UpdateRewardGranted sets the "reward_granted" field to the value that was provided on create. +func (u *ReferralRelationUpsertBulk) UpdateRewardGranted() *ReferralRelationUpsertBulk { + return u.Update(func(s *ReferralRelationUpsert) { + s.UpdateRewardGranted() + }) +} + +// Exec executes the query. +func (u *ReferralRelationUpsertBulk) Exec(ctx context.Context) error { + if u.create.err != nil { + return u.create.err + } + for i, b := range u.create.builders { + if len(b.conflict) != 0 { + return fmt.Errorf("ent: OnConflict was set for builder %d. Set it on the ReferralRelationCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for ReferralRelationCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ReferralRelationUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/ent/referralrelation_delete.go b/backend/ent/referralrelation_delete.go new file mode 100644 index 000000000..aea694d9c --- /dev/null +++ b/backend/ent/referralrelation_delete.go @@ -0,0 +1,88 @@ +// 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/referralrelation" +) + +// ReferralRelationDelete is the builder for deleting a ReferralRelation entity. +type ReferralRelationDelete struct { + config + hooks []Hook + mutation *ReferralRelationMutation +} + +// Where appends a list predicates to the ReferralRelationDelete builder. +func (_d *ReferralRelationDelete) Where(ps ...predicate.ReferralRelation) *ReferralRelationDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *ReferralRelationDelete) 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 *ReferralRelationDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *ReferralRelationDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(referralrelation.Table, sqlgraph.NewFieldSpec(referralrelation.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 +} + +// ReferralRelationDeleteOne is the builder for deleting a single ReferralRelation entity. +type ReferralRelationDeleteOne struct { + _d *ReferralRelationDelete +} + +// Where appends a list predicates to the ReferralRelationDelete builder. +func (_d *ReferralRelationDeleteOne) Where(ps ...predicate.ReferralRelation) *ReferralRelationDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *ReferralRelationDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{referralrelation.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ReferralRelationDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/ent/referralrelation_query.go b/backend/ent/referralrelation_query.go new file mode 100644 index 000000000..1ae4b2f0d --- /dev/null +++ b/backend/ent/referralrelation_query.go @@ -0,0 +1,717 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "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/referralrelation" + "github.com/Wei-Shaw/sub2api/ent/user" +) + +// ReferralRelationQuery is the builder for querying ReferralRelation entities. +type ReferralRelationQuery struct { + config + ctx *QueryContext + order []referralrelation.OrderOption + inters []Interceptor + predicates []predicate.ReferralRelation + withInviter *UserQuery + withInvitee *UserQuery + modifiers []func(*sql.Selector) + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the ReferralRelationQuery builder. +func (_q *ReferralRelationQuery) Where(ps ...predicate.ReferralRelation) *ReferralRelationQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *ReferralRelationQuery) Limit(limit int) *ReferralRelationQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *ReferralRelationQuery) Offset(offset int) *ReferralRelationQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *ReferralRelationQuery) Unique(unique bool) *ReferralRelationQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *ReferralRelationQuery) Order(o ...referralrelation.OrderOption) *ReferralRelationQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryInviter chains the current query on the "inviter" edge. +func (_q *ReferralRelationQuery) QueryInviter() *UserQuery { + query := (&UserClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(referralrelation.Table, referralrelation.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, referralrelation.InviterTable, referralrelation.InviterColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryInvitee chains the current query on the "invitee" edge. +func (_q *ReferralRelationQuery) QueryInvitee() *UserQuery { + query := (&UserClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(referralrelation.Table, referralrelation.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, referralrelation.InviteeTable, referralrelation.InviteeColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first ReferralRelation entity from the query. +// Returns a *NotFoundError when no ReferralRelation was found. +func (_q *ReferralRelationQuery) First(ctx context.Context) (*ReferralRelation, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{referralrelation.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *ReferralRelationQuery) FirstX(ctx context.Context) *ReferralRelation { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first ReferralRelation ID from the query. +// Returns a *NotFoundError when no ReferralRelation ID was found. +func (_q *ReferralRelationQuery) FirstID(ctx context.Context) (id int64, err error) { + var ids []int64 + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{referralrelation.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *ReferralRelationQuery) FirstIDX(ctx context.Context) int64 { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single ReferralRelation entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one ReferralRelation entity is found. +// Returns a *NotFoundError when no ReferralRelation entities are found. +func (_q *ReferralRelationQuery) Only(ctx context.Context) (*ReferralRelation, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{referralrelation.Label} + default: + return nil, &NotSingularError{referralrelation.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *ReferralRelationQuery) OnlyX(ctx context.Context) *ReferralRelation { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only ReferralRelation ID in the query. +// Returns a *NotSingularError when more than one ReferralRelation ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *ReferralRelationQuery) OnlyID(ctx context.Context) (id int64, err error) { + var ids []int64 + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{referralrelation.Label} + default: + err = &NotSingularError{referralrelation.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *ReferralRelationQuery) OnlyIDX(ctx context.Context) int64 { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of ReferralRelations. +func (_q *ReferralRelationQuery) All(ctx context.Context) ([]*ReferralRelation, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*ReferralRelation, *ReferralRelationQuery]() + return withInterceptors[[]*ReferralRelation](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *ReferralRelationQuery) AllX(ctx context.Context) []*ReferralRelation { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of ReferralRelation IDs. +func (_q *ReferralRelationQuery) IDs(ctx context.Context) (ids []int64, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(referralrelation.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *ReferralRelationQuery) IDsX(ctx context.Context) []int64 { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *ReferralRelationQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*ReferralRelationQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *ReferralRelationQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *ReferralRelationQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *ReferralRelationQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the ReferralRelationQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *ReferralRelationQuery) Clone() *ReferralRelationQuery { + if _q == nil { + return nil + } + return &ReferralRelationQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]referralrelation.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.ReferralRelation{}, _q.predicates...), + withInviter: _q.withInviter.Clone(), + withInvitee: _q.withInvitee.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithInviter tells the query-builder to eager-load the nodes that are connected to +// the "inviter" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ReferralRelationQuery) WithInviter(opts ...func(*UserQuery)) *ReferralRelationQuery { + query := (&UserClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withInviter = query + return _q +} + +// WithInvitee tells the query-builder to eager-load the nodes that are connected to +// the "invitee" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ReferralRelationQuery) WithInvitee(opts ...func(*UserQuery)) *ReferralRelationQuery { + query := (&UserClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withInvitee = query + return _q +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// InviterID int64 `json:"inviter_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.ReferralRelation.Query(). +// GroupBy(referralrelation.FieldInviterID). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (_q *ReferralRelationQuery) GroupBy(field string, fields ...string) *ReferralRelationGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &ReferralRelationGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = referralrelation.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// InviterID int64 `json:"inviter_id,omitempty"` +// } +// +// client.ReferralRelation.Query(). +// Select(referralrelation.FieldInviterID). +// Scan(ctx, &v) +func (_q *ReferralRelationQuery) Select(fields ...string) *ReferralRelationSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &ReferralRelationSelect{ReferralRelationQuery: _q} + sbuild.label = referralrelation.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ReferralRelationSelect configured with the given aggregations. +func (_q *ReferralRelationQuery) Aggregate(fns ...AggregateFunc) *ReferralRelationSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *ReferralRelationQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !referralrelation.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *ReferralRelationQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ReferralRelation, error) { + var ( + nodes = []*ReferralRelation{} + _spec = _q.querySpec() + loadedTypes = [2]bool{ + _q.withInviter != nil, + _q.withInvitee != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*ReferralRelation).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &ReferralRelation{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := _q.withInviter; query != nil { + if err := _q.loadInviter(ctx, query, nodes, nil, + func(n *ReferralRelation, e *User) { n.Edges.Inviter = e }); err != nil { + return nil, err + } + } + if query := _q.withInvitee; query != nil { + if err := _q.loadInvitee(ctx, query, nodes, nil, + func(n *ReferralRelation, e *User) { n.Edges.Invitee = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *ReferralRelationQuery) loadInviter(ctx context.Context, query *UserQuery, nodes []*ReferralRelation, init func(*ReferralRelation), assign func(*ReferralRelation, *User)) error { + ids := make([]int64, 0, len(nodes)) + nodeids := make(map[int64][]*ReferralRelation) + for i := range nodes { + fk := nodes[i].InviterID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(user.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "inviter_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ReferralRelationQuery) loadInvitee(ctx context.Context, query *UserQuery, nodes []*ReferralRelation, init func(*ReferralRelation), assign func(*ReferralRelation, *User)) error { + ids := make([]int64, 0, len(nodes)) + nodeids := make(map[int64][]*ReferralRelation) + for i := range nodes { + fk := nodes[i].InviteeID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(user.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "invitee_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *ReferralRelationQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *ReferralRelationQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(referralrelation.Table, referralrelation.Columns, sqlgraph.NewFieldSpec(referralrelation.FieldID, field.TypeInt64)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, referralrelation.FieldID) + for i := range fields { + if fields[i] != referralrelation.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withInviter != nil { + _spec.Node.AddColumnOnce(referralrelation.FieldInviterID) + } + if _q.withInvitee != nil { + _spec.Node.AddColumnOnce(referralrelation.FieldInviteeID) + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *ReferralRelationQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(referralrelation.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = referralrelation.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, m := range _q.modifiers { + m(selector) + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + 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 *ReferralRelationQuery) ForUpdate(opts ...sql.LockOption) *ReferralRelationQuery { + 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 *ReferralRelationQuery) ForShare(opts ...sql.LockOption) *ReferralRelationQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// ReferralRelationGroupBy is the group-by builder for ReferralRelation entities. +type ReferralRelationGroupBy struct { + selector + build *ReferralRelationQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *ReferralRelationGroupBy) Aggregate(fns ...AggregateFunc) *ReferralRelationGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *ReferralRelationGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*ReferralRelationQuery, *ReferralRelationGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *ReferralRelationGroupBy) sqlScan(ctx context.Context, root *ReferralRelationQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// ReferralRelationSelect is the builder for selecting fields of ReferralRelation entities. +type ReferralRelationSelect struct { + *ReferralRelationQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *ReferralRelationSelect) Aggregate(fns ...AggregateFunc) *ReferralRelationSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *ReferralRelationSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*ReferralRelationQuery, *ReferralRelationSelect](ctx, _s.ReferralRelationQuery, _s, _s.inters, v) +} + +func (_s *ReferralRelationSelect) sqlScan(ctx context.Context, root *ReferralRelationQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/backend/ent/referralrelation_update.go b/backend/ent/referralrelation_update.go new file mode 100644 index 000000000..b58de893f --- /dev/null +++ b/backend/ent/referralrelation_update.go @@ -0,0 +1,582 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "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/referralrelation" + "github.com/Wei-Shaw/sub2api/ent/user" +) + +// ReferralRelationUpdate is the builder for updating ReferralRelation entities. +type ReferralRelationUpdate struct { + config + hooks []Hook + mutation *ReferralRelationMutation +} + +// Where appends a list predicates to the ReferralRelationUpdate builder. +func (_u *ReferralRelationUpdate) Where(ps ...predicate.ReferralRelation) *ReferralRelationUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetInviterID sets the "inviter_id" field. +func (_u *ReferralRelationUpdate) SetInviterID(v int64) *ReferralRelationUpdate { + _u.mutation.SetInviterID(v) + return _u +} + +// SetNillableInviterID sets the "inviter_id" field if the given value is not nil. +func (_u *ReferralRelationUpdate) SetNillableInviterID(v *int64) *ReferralRelationUpdate { + if v != nil { + _u.SetInviterID(*v) + } + return _u +} + +// SetInviteeID sets the "invitee_id" field. +func (_u *ReferralRelationUpdate) SetInviteeID(v int64) *ReferralRelationUpdate { + _u.mutation.SetInviteeID(v) + return _u +} + +// SetNillableInviteeID sets the "invitee_id" field if the given value is not nil. +func (_u *ReferralRelationUpdate) SetNillableInviteeID(v *int64) *ReferralRelationUpdate { + if v != nil { + _u.SetInviteeID(*v) + } + return _u +} + +// SetInviterReward sets the "inviter_reward" field. +func (_u *ReferralRelationUpdate) SetInviterReward(v float64) *ReferralRelationUpdate { + _u.mutation.ResetInviterReward() + _u.mutation.SetInviterReward(v) + return _u +} + +// SetNillableInviterReward sets the "inviter_reward" field if the given value is not nil. +func (_u *ReferralRelationUpdate) SetNillableInviterReward(v *float64) *ReferralRelationUpdate { + if v != nil { + _u.SetInviterReward(*v) + } + return _u +} + +// AddInviterReward adds value to the "inviter_reward" field. +func (_u *ReferralRelationUpdate) AddInviterReward(v float64) *ReferralRelationUpdate { + _u.mutation.AddInviterReward(v) + return _u +} + +// SetInviteeReward sets the "invitee_reward" field. +func (_u *ReferralRelationUpdate) SetInviteeReward(v float64) *ReferralRelationUpdate { + _u.mutation.ResetInviteeReward() + _u.mutation.SetInviteeReward(v) + return _u +} + +// SetNillableInviteeReward sets the "invitee_reward" field if the given value is not nil. +func (_u *ReferralRelationUpdate) SetNillableInviteeReward(v *float64) *ReferralRelationUpdate { + if v != nil { + _u.SetInviteeReward(*v) + } + return _u +} + +// AddInviteeReward adds value to the "invitee_reward" field. +func (_u *ReferralRelationUpdate) AddInviteeReward(v float64) *ReferralRelationUpdate { + _u.mutation.AddInviteeReward(v) + return _u +} + +// SetRewardGranted sets the "reward_granted" field. +func (_u *ReferralRelationUpdate) SetRewardGranted(v bool) *ReferralRelationUpdate { + _u.mutation.SetRewardGranted(v) + return _u +} + +// SetNillableRewardGranted sets the "reward_granted" field if the given value is not nil. +func (_u *ReferralRelationUpdate) SetNillableRewardGranted(v *bool) *ReferralRelationUpdate { + if v != nil { + _u.SetRewardGranted(*v) + } + return _u +} + +// SetInviter sets the "inviter" edge to the User entity. +func (_u *ReferralRelationUpdate) SetInviter(v *User) *ReferralRelationUpdate { + return _u.SetInviterID(v.ID) +} + +// SetInvitee sets the "invitee" edge to the User entity. +func (_u *ReferralRelationUpdate) SetInvitee(v *User) *ReferralRelationUpdate { + return _u.SetInviteeID(v.ID) +} + +// Mutation returns the ReferralRelationMutation object of the builder. +func (_u *ReferralRelationUpdate) Mutation() *ReferralRelationMutation { + return _u.mutation +} + +// ClearInviter clears the "inviter" edge to the User entity. +func (_u *ReferralRelationUpdate) ClearInviter() *ReferralRelationUpdate { + _u.mutation.ClearInviter() + return _u +} + +// ClearInvitee clears the "invitee" edge to the User entity. +func (_u *ReferralRelationUpdate) ClearInvitee() *ReferralRelationUpdate { + _u.mutation.ClearInvitee() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *ReferralRelationUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ReferralRelationUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *ReferralRelationUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ReferralRelationUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ReferralRelationUpdate) check() error { + if v, ok := _u.mutation.InviterID(); ok { + if err := referralrelation.InviterIDValidator(v); err != nil { + return &ValidationError{Name: "inviter_id", err: fmt.Errorf(`ent: validator failed for field "ReferralRelation.inviter_id": %w`, err)} + } + } + if v, ok := _u.mutation.InviteeID(); ok { + if err := referralrelation.InviteeIDValidator(v); err != nil { + return &ValidationError{Name: "invitee_id", err: fmt.Errorf(`ent: validator failed for field "ReferralRelation.invitee_id": %w`, err)} + } + } + if _u.mutation.InviterCleared() && len(_u.mutation.InviterIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "ReferralRelation.inviter"`) + } + if _u.mutation.InviteeCleared() && len(_u.mutation.InviteeIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "ReferralRelation.invitee"`) + } + return nil +} + +func (_u *ReferralRelationUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(referralrelation.Table, referralrelation.Columns, sqlgraph.NewFieldSpec(referralrelation.FieldID, field.TypeInt64)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.InviterReward(); ok { + _spec.SetField(referralrelation.FieldInviterReward, field.TypeFloat64, value) + } + if value, ok := _u.mutation.AddedInviterReward(); ok { + _spec.AddField(referralrelation.FieldInviterReward, field.TypeFloat64, value) + } + if value, ok := _u.mutation.InviteeReward(); ok { + _spec.SetField(referralrelation.FieldInviteeReward, field.TypeFloat64, value) + } + if value, ok := _u.mutation.AddedInviteeReward(); ok { + _spec.AddField(referralrelation.FieldInviteeReward, field.TypeFloat64, value) + } + if value, ok := _u.mutation.RewardGranted(); ok { + _spec.SetField(referralrelation.FieldRewardGranted, field.TypeBool, value) + } + if _u.mutation.InviterCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: referralrelation.InviterTable, + Columns: []string{referralrelation.InviterColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.InviterIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: referralrelation.InviterTable, + Columns: []string{referralrelation.InviterColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.InviteeCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: referralrelation.InviteeTable, + Columns: []string{referralrelation.InviteeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.InviteeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: referralrelation.InviteeTable, + Columns: []string{referralrelation.InviteeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{referralrelation.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// ReferralRelationUpdateOne is the builder for updating a single ReferralRelation entity. +type ReferralRelationUpdateOne struct { + config + fields []string + hooks []Hook + mutation *ReferralRelationMutation +} + +// SetInviterID sets the "inviter_id" field. +func (_u *ReferralRelationUpdateOne) SetInviterID(v int64) *ReferralRelationUpdateOne { + _u.mutation.SetInviterID(v) + return _u +} + +// SetNillableInviterID sets the "inviter_id" field if the given value is not nil. +func (_u *ReferralRelationUpdateOne) SetNillableInviterID(v *int64) *ReferralRelationUpdateOne { + if v != nil { + _u.SetInviterID(*v) + } + return _u +} + +// SetInviteeID sets the "invitee_id" field. +func (_u *ReferralRelationUpdateOne) SetInviteeID(v int64) *ReferralRelationUpdateOne { + _u.mutation.SetInviteeID(v) + return _u +} + +// SetNillableInviteeID sets the "invitee_id" field if the given value is not nil. +func (_u *ReferralRelationUpdateOne) SetNillableInviteeID(v *int64) *ReferralRelationUpdateOne { + if v != nil { + _u.SetInviteeID(*v) + } + return _u +} + +// SetInviterReward sets the "inviter_reward" field. +func (_u *ReferralRelationUpdateOne) SetInviterReward(v float64) *ReferralRelationUpdateOne { + _u.mutation.ResetInviterReward() + _u.mutation.SetInviterReward(v) + return _u +} + +// SetNillableInviterReward sets the "inviter_reward" field if the given value is not nil. +func (_u *ReferralRelationUpdateOne) SetNillableInviterReward(v *float64) *ReferralRelationUpdateOne { + if v != nil { + _u.SetInviterReward(*v) + } + return _u +} + +// AddInviterReward adds value to the "inviter_reward" field. +func (_u *ReferralRelationUpdateOne) AddInviterReward(v float64) *ReferralRelationUpdateOne { + _u.mutation.AddInviterReward(v) + return _u +} + +// SetInviteeReward sets the "invitee_reward" field. +func (_u *ReferralRelationUpdateOne) SetInviteeReward(v float64) *ReferralRelationUpdateOne { + _u.mutation.ResetInviteeReward() + _u.mutation.SetInviteeReward(v) + return _u +} + +// SetNillableInviteeReward sets the "invitee_reward" field if the given value is not nil. +func (_u *ReferralRelationUpdateOne) SetNillableInviteeReward(v *float64) *ReferralRelationUpdateOne { + if v != nil { + _u.SetInviteeReward(*v) + } + return _u +} + +// AddInviteeReward adds value to the "invitee_reward" field. +func (_u *ReferralRelationUpdateOne) AddInviteeReward(v float64) *ReferralRelationUpdateOne { + _u.mutation.AddInviteeReward(v) + return _u +} + +// SetRewardGranted sets the "reward_granted" field. +func (_u *ReferralRelationUpdateOne) SetRewardGranted(v bool) *ReferralRelationUpdateOne { + _u.mutation.SetRewardGranted(v) + return _u +} + +// SetNillableRewardGranted sets the "reward_granted" field if the given value is not nil. +func (_u *ReferralRelationUpdateOne) SetNillableRewardGranted(v *bool) *ReferralRelationUpdateOne { + if v != nil { + _u.SetRewardGranted(*v) + } + return _u +} + +// SetInviter sets the "inviter" edge to the User entity. +func (_u *ReferralRelationUpdateOne) SetInviter(v *User) *ReferralRelationUpdateOne { + return _u.SetInviterID(v.ID) +} + +// SetInvitee sets the "invitee" edge to the User entity. +func (_u *ReferralRelationUpdateOne) SetInvitee(v *User) *ReferralRelationUpdateOne { + return _u.SetInviteeID(v.ID) +} + +// Mutation returns the ReferralRelationMutation object of the builder. +func (_u *ReferralRelationUpdateOne) Mutation() *ReferralRelationMutation { + return _u.mutation +} + +// ClearInviter clears the "inviter" edge to the User entity. +func (_u *ReferralRelationUpdateOne) ClearInviter() *ReferralRelationUpdateOne { + _u.mutation.ClearInviter() + return _u +} + +// ClearInvitee clears the "invitee" edge to the User entity. +func (_u *ReferralRelationUpdateOne) ClearInvitee() *ReferralRelationUpdateOne { + _u.mutation.ClearInvitee() + return _u +} + +// Where appends a list predicates to the ReferralRelationUpdate builder. +func (_u *ReferralRelationUpdateOne) Where(ps ...predicate.ReferralRelation) *ReferralRelationUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *ReferralRelationUpdateOne) Select(field string, fields ...string) *ReferralRelationUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated ReferralRelation entity. +func (_u *ReferralRelationUpdateOne) Save(ctx context.Context) (*ReferralRelation, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ReferralRelationUpdateOne) SaveX(ctx context.Context) *ReferralRelation { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *ReferralRelationUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ReferralRelationUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ReferralRelationUpdateOne) check() error { + if v, ok := _u.mutation.InviterID(); ok { + if err := referralrelation.InviterIDValidator(v); err != nil { + return &ValidationError{Name: "inviter_id", err: fmt.Errorf(`ent: validator failed for field "ReferralRelation.inviter_id": %w`, err)} + } + } + if v, ok := _u.mutation.InviteeID(); ok { + if err := referralrelation.InviteeIDValidator(v); err != nil { + return &ValidationError{Name: "invitee_id", err: fmt.Errorf(`ent: validator failed for field "ReferralRelation.invitee_id": %w`, err)} + } + } + if _u.mutation.InviterCleared() && len(_u.mutation.InviterIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "ReferralRelation.inviter"`) + } + if _u.mutation.InviteeCleared() && len(_u.mutation.InviteeIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "ReferralRelation.invitee"`) + } + return nil +} + +func (_u *ReferralRelationUpdateOne) sqlSave(ctx context.Context) (_node *ReferralRelation, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(referralrelation.Table, referralrelation.Columns, sqlgraph.NewFieldSpec(referralrelation.FieldID, field.TypeInt64)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "ReferralRelation.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, referralrelation.FieldID) + for _, f := range fields { + if !referralrelation.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != referralrelation.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.InviterReward(); ok { + _spec.SetField(referralrelation.FieldInviterReward, field.TypeFloat64, value) + } + if value, ok := _u.mutation.AddedInviterReward(); ok { + _spec.AddField(referralrelation.FieldInviterReward, field.TypeFloat64, value) + } + if value, ok := _u.mutation.InviteeReward(); ok { + _spec.SetField(referralrelation.FieldInviteeReward, field.TypeFloat64, value) + } + if value, ok := _u.mutation.AddedInviteeReward(); ok { + _spec.AddField(referralrelation.FieldInviteeReward, field.TypeFloat64, value) + } + if value, ok := _u.mutation.RewardGranted(); ok { + _spec.SetField(referralrelation.FieldRewardGranted, field.TypeBool, value) + } + if _u.mutation.InviterCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: referralrelation.InviterTable, + Columns: []string{referralrelation.InviterColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.InviterIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: referralrelation.InviterTable, + Columns: []string{referralrelation.InviterColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.InviteeCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: referralrelation.InviteeTable, + Columns: []string{referralrelation.InviteeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.InviteeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: referralrelation.InviteeTable, + Columns: []string{referralrelation.InviteeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &ReferralRelation{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{referralrelation.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/backend/ent/runtime/runtime.go b/backend/ent/runtime/runtime.go index 2c7467f67..cb0a4a390 100644 --- a/backend/ent/runtime/runtime.go +++ b/backend/ent/runtime/runtime.go @@ -17,6 +17,7 @@ import ( "github.com/Wei-Shaw/sub2api/ent/promocodeusage" "github.com/Wei-Shaw/sub2api/ent/proxy" "github.com/Wei-Shaw/sub2api/ent/redeemcode" + "github.com/Wei-Shaw/sub2api/ent/referralrelation" "github.com/Wei-Shaw/sub2api/ent/schema" "github.com/Wei-Shaw/sub2api/ent/securitysecret" "github.com/Wei-Shaw/sub2api/ent/setting" @@ -26,6 +27,7 @@ import ( "github.com/Wei-Shaw/sub2api/ent/userallowedgroup" "github.com/Wei-Shaw/sub2api/ent/userattributedefinition" "github.com/Wei-Shaw/sub2api/ent/userattributevalue" + "github.com/Wei-Shaw/sub2api/ent/userreferralprofile" "github.com/Wei-Shaw/sub2api/ent/usersubscription" ) @@ -667,6 +669,32 @@ func init() { redeemcodeDescValidityDays := redeemcodeFields[9].Descriptor() // redeemcode.DefaultValidityDays holds the default value on creation for the validity_days field. redeemcode.DefaultValidityDays = redeemcodeDescValidityDays.Default.(int) + referralrelationFields := schema.ReferralRelation{}.Fields() + _ = referralrelationFields + // referralrelationDescInviterID is the schema descriptor for inviter_id field. + referralrelationDescInviterID := referralrelationFields[0].Descriptor() + // referralrelation.InviterIDValidator is a validator for the "inviter_id" field. It is called by the builders before save. + referralrelation.InviterIDValidator = referralrelationDescInviterID.Validators[0].(func(int64) error) + // referralrelationDescInviteeID is the schema descriptor for invitee_id field. + referralrelationDescInviteeID := referralrelationFields[1].Descriptor() + // referralrelation.InviteeIDValidator is a validator for the "invitee_id" field. It is called by the builders before save. + referralrelation.InviteeIDValidator = referralrelationDescInviteeID.Validators[0].(func(int64) error) + // referralrelationDescInviterReward is the schema descriptor for inviter_reward field. + referralrelationDescInviterReward := referralrelationFields[2].Descriptor() + // referralrelation.DefaultInviterReward holds the default value on creation for the inviter_reward field. + referralrelation.DefaultInviterReward = referralrelationDescInviterReward.Default.(float64) + // referralrelationDescInviteeReward is the schema descriptor for invitee_reward field. + referralrelationDescInviteeReward := referralrelationFields[3].Descriptor() + // referralrelation.DefaultInviteeReward holds the default value on creation for the invitee_reward field. + referralrelation.DefaultInviteeReward = referralrelationDescInviteeReward.Default.(float64) + // referralrelationDescRewardGranted is the schema descriptor for reward_granted field. + referralrelationDescRewardGranted := referralrelationFields[4].Descriptor() + // referralrelation.DefaultRewardGranted holds the default value on creation for the reward_granted field. + referralrelation.DefaultRewardGranted = referralrelationDescRewardGranted.Default.(bool) + // referralrelationDescCreatedAt is the schema descriptor for created_at field. + referralrelationDescCreatedAt := referralrelationFields[5].Descriptor() + // referralrelation.DefaultCreatedAt holds the default value on creation for the created_at field. + referralrelation.DefaultCreatedAt = referralrelationDescCreatedAt.Default.(func() time.Time) securitysecretMixin := schema.SecuritySecret{}.Mixin() securitysecretMixinFields0 := securitysecretMixin[0].Fields() _ = securitysecretMixinFields0 @@ -1118,6 +1146,34 @@ func init() { userattributevalueDescValue := userattributevalueFields[2].Descriptor() // userattributevalue.DefaultValue holds the default value on creation for the value field. userattributevalue.DefaultValue = userattributevalueDescValue.Default.(string) + userreferralprofileFields := schema.UserReferralProfile{}.Fields() + _ = userreferralprofileFields + // userreferralprofileDescUserID is the schema descriptor for user_id field. + userreferralprofileDescUserID := userreferralprofileFields[0].Descriptor() + // userreferralprofile.UserIDValidator is a validator for the "user_id" field. It is called by the builders before save. + userreferralprofile.UserIDValidator = userreferralprofileDescUserID.Validators[0].(func(int64) error) + // userreferralprofileDescReferralCode is the schema descriptor for referral_code field. + userreferralprofileDescReferralCode := userreferralprofileFields[1].Descriptor() + // userreferralprofile.ReferralCodeValidator is a validator for the "referral_code" field. It is called by the builders before save. + userreferralprofile.ReferralCodeValidator = func() func(string) error { + validators := userreferralprofileDescReferralCode.Validators + fns := [...]func(string) error{ + validators[0].(func(string) error), + validators[1].(func(string) error), + } + return func(referral_code string) error { + for _, fn := range fns { + if err := fn(referral_code); err != nil { + return err + } + } + return nil + } + }() + // userreferralprofileDescCreatedAt is the schema descriptor for created_at field. + userreferralprofileDescCreatedAt := userreferralprofileFields[2].Descriptor() + // userreferralprofile.DefaultCreatedAt holds the default value on creation for the created_at field. + userreferralprofile.DefaultCreatedAt = userreferralprofileDescCreatedAt.Default.(func() time.Time) usersubscriptionMixin := schema.UserSubscription{}.Mixin() usersubscriptionMixinHooks1 := usersubscriptionMixin[1].Hooks() usersubscription.Hooks[0] = usersubscriptionMixinHooks1[0] diff --git a/backend/ent/schema/referral_relation.go b/backend/ent/schema/referral_relation.go new file mode 100644 index 000000000..a12a17c53 --- /dev/null +++ b/backend/ent/schema/referral_relation.go @@ -0,0 +1,79 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" +) + +// ReferralRelation holds the schema definition for the ReferralRelation entity. +// +// 用户邀请关系记录:记录邀请人(inviter)与被邀请人(invitee)的关联, +// 以及双方获得的奖励金额快照和奖励发放状态。 +// +// 关键约束:invitee_id 唯一,确保同一用户只能被邀请一次(幂等性保障)。 +// +// 删除策略:硬删除(关系一旦建立不应更改,如需审计请在删除前记录日志) +type ReferralRelation struct { + ent.Schema +} + +func (ReferralRelation) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Annotation{Table: "referral_relations"}, + } +} + +func (ReferralRelation) Fields() []ent.Field { + return []ent.Field{ + field.Int64("inviter_id"). + Positive(). + Comment("邀请人的 user_id"), + field.Int64("invitee_id"). + Positive(). + Comment("被邀请人的 user_id,唯一约束确保一人只能被邀请一次"), + field.Float("inviter_reward"). + SchemaType(map[string]string{dialect.Postgres: "decimal(20,8)"}). + Default(0). + Comment("发放给邀请人的余额奖励(创建时快照,不受后续配置变更影响)"), + field.Float("invitee_reward"). + SchemaType(map[string]string{dialect.Postgres: "decimal(20,8)"}). + Default(0). + Comment("发放给被邀请人的余额奖励(创建时快照)"), + field.Bool("reward_granted"). + Default(false). + Comment("奖励是否已发放,防止重复发放(幂等标志)"), + field.Time("created_at"). + Immutable(). + Default(time.Now). + SchemaType(map[string]string{dialect.Postgres: "timestamptz"}), + } +} + +func (ReferralRelation) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("inviter", User.Type). + Ref("referrals_given"). + Field("inviter_id"). + Unique(). + Required(), + edge.From("invitee", User.Type). + Ref("referral_received"). + Field("invitee_id"). + Unique(). + Required(), + } +} + +func (ReferralRelation) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("invitee_id").Unique(), // 幂等约束:同一被邀请人只能出现一次 + index.Fields("inviter_id"), // 按邀请人查询列表(分页高频) + } +} diff --git a/backend/ent/schema/user.go b/backend/ent/schema/user.go index 0a3b5d9ec..e214cc004 100644 --- a/backend/ent/schema/user.go +++ b/backend/ent/schema/user.go @@ -93,6 +93,12 @@ func (User) Edges() []ent.Edge { edge.To("usage_logs", UsageLog.Type), edge.To("attribute_values", UserAttributeValue.Type), edge.To("promo_code_usages", PromoCodeUsage.Type), + // 裂变推广:用户的专属邀请码 Profile(一对一) + edge.To("referral_profile", UserReferralProfile.Type), + // 裂变推广:该用户作为邀请人发起的邀请关系 + edge.To("referrals_given", ReferralRelation.Type), + // 裂变推广:该用户被邀请的关系记录(最多一条) + edge.To("referral_received", ReferralRelation.Type), } } diff --git a/backend/ent/schema/user_referral_profile.go b/backend/ent/schema/user_referral_profile.go new file mode 100644 index 000000000..ec9a2d207 --- /dev/null +++ b/backend/ent/schema/user_referral_profile.go @@ -0,0 +1,61 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" +) + +// UserReferralProfile holds the schema definition for the UserReferralProfile entity. +// +// 每个用户的专属邀请码 Profile,在用户注册时自动创建(懒加载)。 +// 与 User 表一对一关系,通过独立表实现,不修改现有 users 表。 +// +// 删除策略:硬删除(与 RedeemCode 相同,邀请码 Profile 删除无需保留历史) +type UserReferralProfile struct { + ent.Schema +} + +func (UserReferralProfile) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Annotation{Table: "user_referral_profiles"}, + } +} + +func (UserReferralProfile) Fields() []ent.Field { + return []ent.Field{ + field.Int64("user_id"). + Positive(), + field.String("referral_code"). + MaxLen(8). + NotEmpty(). + Unique(). + Comment("8位大写字母+数字的专属邀请码"), + field.Time("created_at"). + Immutable(). + Default(time.Now). + SchemaType(map[string]string{"postgres": "timestamptz"}), + } +} + +func (UserReferralProfile) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("user", User.Type). + Ref("referral_profile"). + Field("user_id"). + Unique(). + Required(), + } +} + +func (UserReferralProfile) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("user_id").Unique(), + index.Fields("referral_code").Unique(), + } +} diff --git a/backend/ent/tx.go b/backend/ent/tx.go index cd3b2296c..70e984df1 100644 --- a/backend/ent/tx.go +++ b/backend/ent/tx.go @@ -38,6 +38,8 @@ type Tx struct { Proxy *ProxyClient // RedeemCode is the client for interacting with the RedeemCode builders. RedeemCode *RedeemCodeClient + // ReferralRelation is the client for interacting with the ReferralRelation builders. + ReferralRelation *ReferralRelationClient // SecuritySecret is the client for interacting with the SecuritySecret builders. SecuritySecret *SecuritySecretClient // Setting is the client for interacting with the Setting builders. @@ -54,6 +56,8 @@ type Tx struct { UserAttributeDefinition *UserAttributeDefinitionClient // UserAttributeValue is the client for interacting with the UserAttributeValue builders. UserAttributeValue *UserAttributeValueClient + // UserReferralProfile is the client for interacting with the UserReferralProfile builders. + UserReferralProfile *UserReferralProfileClient // UserSubscription is the client for interacting with the UserSubscription builders. UserSubscription *UserSubscriptionClient @@ -199,6 +203,7 @@ func (tx *Tx) init() { tx.PromoCodeUsage = NewPromoCodeUsageClient(tx.config) tx.Proxy = NewProxyClient(tx.config) tx.RedeemCode = NewRedeemCodeClient(tx.config) + tx.ReferralRelation = NewReferralRelationClient(tx.config) tx.SecuritySecret = NewSecuritySecretClient(tx.config) tx.Setting = NewSettingClient(tx.config) tx.UsageCleanupTask = NewUsageCleanupTaskClient(tx.config) @@ -207,6 +212,7 @@ func (tx *Tx) init() { tx.UserAllowedGroup = NewUserAllowedGroupClient(tx.config) tx.UserAttributeDefinition = NewUserAttributeDefinitionClient(tx.config) tx.UserAttributeValue = NewUserAttributeValueClient(tx.config) + tx.UserReferralProfile = NewUserReferralProfileClient(tx.config) tx.UserSubscription = NewUserSubscriptionClient(tx.config) } diff --git a/backend/ent/user.go b/backend/ent/user.go index b3f933f6f..e64225700 100644 --- a/backend/ent/user.go +++ b/backend/ent/user.go @@ -75,11 +75,17 @@ type UserEdges struct { AttributeValues []*UserAttributeValue `json:"attribute_values,omitempty"` // PromoCodeUsages holds the value of the promo_code_usages edge. PromoCodeUsages []*PromoCodeUsage `json:"promo_code_usages,omitempty"` + // ReferralProfile holds the value of the referral_profile edge. + ReferralProfile []*UserReferralProfile `json:"referral_profile,omitempty"` + // ReferralsGiven holds the value of the referrals_given edge. + ReferralsGiven []*ReferralRelation `json:"referrals_given,omitempty"` + // ReferralReceived holds the value of the referral_received edge. + ReferralReceived []*ReferralRelation `json:"referral_received,omitempty"` // UserAllowedGroups holds the value of the user_allowed_groups edge. UserAllowedGroups []*UserAllowedGroup `json:"user_allowed_groups,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. - loadedTypes [10]bool + loadedTypes [13]bool } // APIKeysOrErr returns the APIKeys value or an error if the edge @@ -163,10 +169,37 @@ func (e UserEdges) PromoCodeUsagesOrErr() ([]*PromoCodeUsage, error) { return nil, &NotLoadedError{edge: "promo_code_usages"} } +// ReferralProfileOrErr returns the ReferralProfile value or an error if the edge +// was not loaded in eager-loading. +func (e UserEdges) ReferralProfileOrErr() ([]*UserReferralProfile, error) { + if e.loadedTypes[9] { + return e.ReferralProfile, nil + } + return nil, &NotLoadedError{edge: "referral_profile"} +} + +// ReferralsGivenOrErr returns the ReferralsGiven value or an error if the edge +// was not loaded in eager-loading. +func (e UserEdges) ReferralsGivenOrErr() ([]*ReferralRelation, error) { + if e.loadedTypes[10] { + return e.ReferralsGiven, nil + } + return nil, &NotLoadedError{edge: "referrals_given"} +} + +// ReferralReceivedOrErr returns the ReferralReceived value or an error if the edge +// was not loaded in eager-loading. +func (e UserEdges) ReferralReceivedOrErr() ([]*ReferralRelation, error) { + if e.loadedTypes[11] { + return e.ReferralReceived, nil + } + return nil, &NotLoadedError{edge: "referral_received"} +} + // UserAllowedGroupsOrErr returns the UserAllowedGroups value or an error if the edge // was not loaded in eager-loading. func (e UserEdges) UserAllowedGroupsOrErr() ([]*UserAllowedGroup, error) { - if e.loadedTypes[9] { + if e.loadedTypes[12] { return e.UserAllowedGroups, nil } return nil, &NotLoadedError{edge: "user_allowed_groups"} @@ -365,6 +398,21 @@ func (_m *User) QueryPromoCodeUsages() *PromoCodeUsageQuery { return NewUserClient(_m.config).QueryPromoCodeUsages(_m) } +// QueryReferralProfile queries the "referral_profile" edge of the User entity. +func (_m *User) QueryReferralProfile() *UserReferralProfileQuery { + return NewUserClient(_m.config).QueryReferralProfile(_m) +} + +// QueryReferralsGiven queries the "referrals_given" edge of the User entity. +func (_m *User) QueryReferralsGiven() *ReferralRelationQuery { + return NewUserClient(_m.config).QueryReferralsGiven(_m) +} + +// QueryReferralReceived queries the "referral_received" edge of the User entity. +func (_m *User) QueryReferralReceived() *ReferralRelationQuery { + return NewUserClient(_m.config).QueryReferralReceived(_m) +} + // QueryUserAllowedGroups queries the "user_allowed_groups" edge of the User entity. func (_m *User) QueryUserAllowedGroups() *UserAllowedGroupQuery { return NewUserClient(_m.config).QueryUserAllowedGroups(_m) diff --git a/backend/ent/user/user.go b/backend/ent/user/user.go index 155b91608..1d074d795 100644 --- a/backend/ent/user/user.go +++ b/backend/ent/user/user.go @@ -65,6 +65,12 @@ const ( EdgeAttributeValues = "attribute_values" // EdgePromoCodeUsages holds the string denoting the promo_code_usages edge name in mutations. EdgePromoCodeUsages = "promo_code_usages" + // EdgeReferralProfile holds the string denoting the referral_profile edge name in mutations. + EdgeReferralProfile = "referral_profile" + // EdgeReferralsGiven holds the string denoting the referrals_given edge name in mutations. + EdgeReferralsGiven = "referrals_given" + // EdgeReferralReceived holds the string denoting the referral_received edge name in mutations. + EdgeReferralReceived = "referral_received" // EdgeUserAllowedGroups holds the string denoting the user_allowed_groups edge name in mutations. EdgeUserAllowedGroups = "user_allowed_groups" // Table holds the table name of the user in the database. @@ -130,6 +136,27 @@ const ( PromoCodeUsagesInverseTable = "promo_code_usages" // PromoCodeUsagesColumn is the table column denoting the promo_code_usages relation/edge. PromoCodeUsagesColumn = "user_id" + // ReferralProfileTable is the table that holds the referral_profile relation/edge. + ReferralProfileTable = "user_referral_profiles" + // ReferralProfileInverseTable is the table name for the UserReferralProfile entity. + // It exists in this package in order to avoid circular dependency with the "userreferralprofile" package. + ReferralProfileInverseTable = "user_referral_profiles" + // ReferralProfileColumn is the table column denoting the referral_profile relation/edge. + ReferralProfileColumn = "user_id" + // ReferralsGivenTable is the table that holds the referrals_given relation/edge. + ReferralsGivenTable = "referral_relations" + // ReferralsGivenInverseTable is the table name for the ReferralRelation entity. + // It exists in this package in order to avoid circular dependency with the "referralrelation" package. + ReferralsGivenInverseTable = "referral_relations" + // ReferralsGivenColumn is the table column denoting the referrals_given relation/edge. + ReferralsGivenColumn = "inviter_id" + // ReferralReceivedTable is the table that holds the referral_received relation/edge. + ReferralReceivedTable = "referral_relations" + // ReferralReceivedInverseTable is the table name for the ReferralRelation entity. + // It exists in this package in order to avoid circular dependency with the "referralrelation" package. + ReferralReceivedInverseTable = "referral_relations" + // ReferralReceivedColumn is the table column denoting the referral_received relation/edge. + ReferralReceivedColumn = "invitee_id" // UserAllowedGroupsTable is the table that holds the user_allowed_groups relation/edge. UserAllowedGroupsTable = "user_allowed_groups" // UserAllowedGroupsInverseTable is the table name for the UserAllowedGroup entity. @@ -434,6 +461,48 @@ func ByPromoCodeUsages(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { } } +// ByReferralProfileCount orders the results by referral_profile count. +func ByReferralProfileCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newReferralProfileStep(), opts...) + } +} + +// ByReferralProfile orders the results by referral_profile terms. +func ByReferralProfile(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newReferralProfileStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByReferralsGivenCount orders the results by referrals_given count. +func ByReferralsGivenCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newReferralsGivenStep(), opts...) + } +} + +// ByReferralsGiven orders the results by referrals_given terms. +func ByReferralsGiven(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newReferralsGivenStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByReferralReceivedCount orders the results by referral_received count. +func ByReferralReceivedCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newReferralReceivedStep(), opts...) + } +} + +// ByReferralReceived orders the results by referral_received terms. +func ByReferralReceived(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newReferralReceivedStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + // ByUserAllowedGroupsCount orders the results by user_allowed_groups count. func ByUserAllowedGroupsCount(opts ...sql.OrderTermOption) OrderOption { return func(s *sql.Selector) { @@ -510,6 +579,27 @@ func newPromoCodeUsagesStep() *sqlgraph.Step { sqlgraph.Edge(sqlgraph.O2M, false, PromoCodeUsagesTable, PromoCodeUsagesColumn), ) } +func newReferralProfileStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ReferralProfileInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ReferralProfileTable, ReferralProfileColumn), + ) +} +func newReferralsGivenStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ReferralsGivenInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ReferralsGivenTable, ReferralsGivenColumn), + ) +} +func newReferralReceivedStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ReferralReceivedInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ReferralReceivedTable, ReferralReceivedColumn), + ) +} func newUserAllowedGroupsStep() *sqlgraph.Step { return sqlgraph.NewStep( sqlgraph.From(Table, FieldID), diff --git a/backend/ent/user/where.go b/backend/ent/user/where.go index e26afcf38..7ee54b298 100644 --- a/backend/ent/user/where.go +++ b/backend/ent/user/where.go @@ -1157,6 +1157,75 @@ func HasPromoCodeUsagesWith(preds ...predicate.PromoCodeUsage) predicate.User { }) } +// HasReferralProfile applies the HasEdge predicate on the "referral_profile" edge. +func HasReferralProfile() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ReferralProfileTable, ReferralProfileColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasReferralProfileWith applies the HasEdge predicate on the "referral_profile" edge with a given conditions (other predicates). +func HasReferralProfileWith(preds ...predicate.UserReferralProfile) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := newReferralProfileStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasReferralsGiven applies the HasEdge predicate on the "referrals_given" edge. +func HasReferralsGiven() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ReferralsGivenTable, ReferralsGivenColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasReferralsGivenWith applies the HasEdge predicate on the "referrals_given" edge with a given conditions (other predicates). +func HasReferralsGivenWith(preds ...predicate.ReferralRelation) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := newReferralsGivenStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasReferralReceived applies the HasEdge predicate on the "referral_received" edge. +func HasReferralReceived() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ReferralReceivedTable, ReferralReceivedColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasReferralReceivedWith applies the HasEdge predicate on the "referral_received" edge with a given conditions (other predicates). +func HasReferralReceivedWith(preds ...predicate.ReferralRelation) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := newReferralReceivedStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + // HasUserAllowedGroups applies the HasEdge predicate on the "user_allowed_groups" edge. func HasUserAllowedGroups() predicate.User { return predicate.User(func(s *sql.Selector) { diff --git a/backend/ent/user_create.go b/backend/ent/user_create.go index df0c6bcc1..59421efb2 100644 --- a/backend/ent/user_create.go +++ b/backend/ent/user_create.go @@ -16,9 +16,11 @@ import ( "github.com/Wei-Shaw/sub2api/ent/group" "github.com/Wei-Shaw/sub2api/ent/promocodeusage" "github.com/Wei-Shaw/sub2api/ent/redeemcode" + "github.com/Wei-Shaw/sub2api/ent/referralrelation" "github.com/Wei-Shaw/sub2api/ent/usagelog" "github.com/Wei-Shaw/sub2api/ent/user" "github.com/Wei-Shaw/sub2api/ent/userattributevalue" + "github.com/Wei-Shaw/sub2api/ent/userreferralprofile" "github.com/Wei-Shaw/sub2api/ent/usersubscription" ) @@ -373,6 +375,51 @@ func (_c *UserCreate) AddPromoCodeUsages(v ...*PromoCodeUsage) *UserCreate { return _c.AddPromoCodeUsageIDs(ids...) } +// AddReferralProfileIDs adds the "referral_profile" edge to the UserReferralProfile entity by IDs. +func (_c *UserCreate) AddReferralProfileIDs(ids ...int64) *UserCreate { + _c.mutation.AddReferralProfileIDs(ids...) + return _c +} + +// AddReferralProfile adds the "referral_profile" edges to the UserReferralProfile entity. +func (_c *UserCreate) AddReferralProfile(v ...*UserReferralProfile) *UserCreate { + ids := make([]int64, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddReferralProfileIDs(ids...) +} + +// AddReferralsGivenIDs adds the "referrals_given" edge to the ReferralRelation entity by IDs. +func (_c *UserCreate) AddReferralsGivenIDs(ids ...int64) *UserCreate { + _c.mutation.AddReferralsGivenIDs(ids...) + return _c +} + +// AddReferralsGiven adds the "referrals_given" edges to the ReferralRelation entity. +func (_c *UserCreate) AddReferralsGiven(v ...*ReferralRelation) *UserCreate { + ids := make([]int64, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddReferralsGivenIDs(ids...) +} + +// AddReferralReceivedIDs adds the "referral_received" edge to the ReferralRelation entity by IDs. +func (_c *UserCreate) AddReferralReceivedIDs(ids ...int64) *UserCreate { + _c.mutation.AddReferralReceivedIDs(ids...) + return _c +} + +// AddReferralReceived adds the "referral_received" edges to the ReferralRelation entity. +func (_c *UserCreate) AddReferralReceived(v ...*ReferralRelation) *UserCreate { + ids := make([]int64, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddReferralReceivedIDs(ids...) +} + // Mutation returns the UserMutation object of the builder. func (_c *UserCreate) Mutation() *UserMutation { return _c.mutation @@ -768,6 +815,54 @@ func (_c *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) { } _spec.Edges = append(_spec.Edges, edge) } + if nodes := _c.mutation.ReferralProfileIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ReferralProfileTable, + Columns: []string{user.ReferralProfileColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(userreferralprofile.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.ReferralsGivenIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ReferralsGivenTable, + Columns: []string{user.ReferralsGivenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(referralrelation.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.ReferralReceivedIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ReferralReceivedTable, + Columns: []string{user.ReferralReceivedColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(referralrelation.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } return _node, _spec } diff --git a/backend/ent/user_query.go b/backend/ent/user_query.go index 4b56e16f4..8171bbd02 100644 --- a/backend/ent/user_query.go +++ b/backend/ent/user_query.go @@ -19,10 +19,12 @@ import ( "github.com/Wei-Shaw/sub2api/ent/predicate" "github.com/Wei-Shaw/sub2api/ent/promocodeusage" "github.com/Wei-Shaw/sub2api/ent/redeemcode" + "github.com/Wei-Shaw/sub2api/ent/referralrelation" "github.com/Wei-Shaw/sub2api/ent/usagelog" "github.com/Wei-Shaw/sub2api/ent/user" "github.com/Wei-Shaw/sub2api/ent/userallowedgroup" "github.com/Wei-Shaw/sub2api/ent/userattributevalue" + "github.com/Wei-Shaw/sub2api/ent/userreferralprofile" "github.com/Wei-Shaw/sub2api/ent/usersubscription" ) @@ -42,6 +44,9 @@ type UserQuery struct { withUsageLogs *UsageLogQuery withAttributeValues *UserAttributeValueQuery withPromoCodeUsages *PromoCodeUsageQuery + withReferralProfile *UserReferralProfileQuery + withReferralsGiven *ReferralRelationQuery + withReferralReceived *ReferralRelationQuery withUserAllowedGroups *UserAllowedGroupQuery modifiers []func(*sql.Selector) // intermediate query (i.e. traversal path). @@ -278,6 +283,72 @@ func (_q *UserQuery) QueryPromoCodeUsages() *PromoCodeUsageQuery { return query } +// QueryReferralProfile chains the current query on the "referral_profile" edge. +func (_q *UserQuery) QueryReferralProfile() *UserReferralProfileQuery { + query := (&UserReferralProfileClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, selector), + sqlgraph.To(userreferralprofile.Table, userreferralprofile.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, user.ReferralProfileTable, user.ReferralProfileColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryReferralsGiven chains the current query on the "referrals_given" edge. +func (_q *UserQuery) QueryReferralsGiven() *ReferralRelationQuery { + query := (&ReferralRelationClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, selector), + sqlgraph.To(referralrelation.Table, referralrelation.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, user.ReferralsGivenTable, user.ReferralsGivenColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryReferralReceived chains the current query on the "referral_received" edge. +func (_q *UserQuery) QueryReferralReceived() *ReferralRelationQuery { + query := (&ReferralRelationClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, selector), + sqlgraph.To(referralrelation.Table, referralrelation.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, user.ReferralReceivedTable, user.ReferralReceivedColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + // QueryUserAllowedGroups chains the current query on the "user_allowed_groups" edge. func (_q *UserQuery) QueryUserAllowedGroups() *UserAllowedGroupQuery { query := (&UserAllowedGroupClient{config: _q.config}).Query() @@ -501,6 +572,9 @@ func (_q *UserQuery) Clone() *UserQuery { withUsageLogs: _q.withUsageLogs.Clone(), withAttributeValues: _q.withAttributeValues.Clone(), withPromoCodeUsages: _q.withPromoCodeUsages.Clone(), + withReferralProfile: _q.withReferralProfile.Clone(), + withReferralsGiven: _q.withReferralsGiven.Clone(), + withReferralReceived: _q.withReferralReceived.Clone(), withUserAllowedGroups: _q.withUserAllowedGroups.Clone(), // clone intermediate query. sql: _q.sql.Clone(), @@ -607,6 +681,39 @@ func (_q *UserQuery) WithPromoCodeUsages(opts ...func(*PromoCodeUsageQuery)) *Us return _q } +// WithReferralProfile tells the query-builder to eager-load the nodes that are connected to +// the "referral_profile" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *UserQuery) WithReferralProfile(opts ...func(*UserReferralProfileQuery)) *UserQuery { + query := (&UserReferralProfileClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withReferralProfile = query + return _q +} + +// WithReferralsGiven tells the query-builder to eager-load the nodes that are connected to +// the "referrals_given" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *UserQuery) WithReferralsGiven(opts ...func(*ReferralRelationQuery)) *UserQuery { + query := (&ReferralRelationClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withReferralsGiven = query + return _q +} + +// WithReferralReceived tells the query-builder to eager-load the nodes that are connected to +// the "referral_received" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *UserQuery) WithReferralReceived(opts ...func(*ReferralRelationQuery)) *UserQuery { + query := (&ReferralRelationClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withReferralReceived = query + return _q +} + // WithUserAllowedGroups tells the query-builder to eager-load the nodes that are connected to // the "user_allowed_groups" edge. The optional arguments are used to configure the query builder of the edge. func (_q *UserQuery) WithUserAllowedGroups(opts ...func(*UserAllowedGroupQuery)) *UserQuery { @@ -696,7 +803,7 @@ func (_q *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e var ( nodes = []*User{} _spec = _q.querySpec() - loadedTypes = [10]bool{ + loadedTypes = [13]bool{ _q.withAPIKeys != nil, _q.withRedeemCodes != nil, _q.withSubscriptions != nil, @@ -706,6 +813,9 @@ func (_q *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e _q.withUsageLogs != nil, _q.withAttributeValues != nil, _q.withPromoCodeUsages != nil, + _q.withReferralProfile != nil, + _q.withReferralsGiven != nil, + _q.withReferralReceived != nil, _q.withUserAllowedGroups != nil, } ) @@ -795,6 +905,27 @@ func (_q *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e return nil, err } } + if query := _q.withReferralProfile; query != nil { + if err := _q.loadReferralProfile(ctx, query, nodes, + func(n *User) { n.Edges.ReferralProfile = []*UserReferralProfile{} }, + func(n *User, e *UserReferralProfile) { n.Edges.ReferralProfile = append(n.Edges.ReferralProfile, e) }); err != nil { + return nil, err + } + } + if query := _q.withReferralsGiven; query != nil { + if err := _q.loadReferralsGiven(ctx, query, nodes, + func(n *User) { n.Edges.ReferralsGiven = []*ReferralRelation{} }, + func(n *User, e *ReferralRelation) { n.Edges.ReferralsGiven = append(n.Edges.ReferralsGiven, e) }); err != nil { + return nil, err + } + } + if query := _q.withReferralReceived; query != nil { + if err := _q.loadReferralReceived(ctx, query, nodes, + func(n *User) { n.Edges.ReferralReceived = []*ReferralRelation{} }, + func(n *User, e *ReferralRelation) { n.Edges.ReferralReceived = append(n.Edges.ReferralReceived, e) }); err != nil { + return nil, err + } + } if query := _q.withUserAllowedGroups; query != nil { if err := _q.loadUserAllowedGroups(ctx, query, nodes, func(n *User) { n.Edges.UserAllowedGroups = []*UserAllowedGroup{} }, @@ -1112,6 +1243,96 @@ func (_q *UserQuery) loadPromoCodeUsages(ctx context.Context, query *PromoCodeUs } return nil } +func (_q *UserQuery) loadReferralProfile(ctx context.Context, query *UserReferralProfileQuery, nodes []*User, init func(*User), assign func(*User, *UserReferralProfile)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int64]*User) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(userreferralprofile.FieldUserID) + } + query.Where(predicate.UserReferralProfile(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(user.ReferralProfileColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.UserID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "user_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *UserQuery) loadReferralsGiven(ctx context.Context, query *ReferralRelationQuery, nodes []*User, init func(*User), assign func(*User, *ReferralRelation)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int64]*User) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(referralrelation.FieldInviterID) + } + query.Where(predicate.ReferralRelation(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(user.ReferralsGivenColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.InviterID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "inviter_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *UserQuery) loadReferralReceived(ctx context.Context, query *ReferralRelationQuery, nodes []*User, init func(*User), assign func(*User, *ReferralRelation)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int64]*User) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(referralrelation.FieldInviteeID) + } + query.Where(predicate.ReferralRelation(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(user.ReferralReceivedColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.InviteeID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "invitee_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} func (_q *UserQuery) loadUserAllowedGroups(ctx context.Context, query *UserAllowedGroupQuery, nodes []*User, init func(*User), assign func(*User, *UserAllowedGroup)) error { fks := make([]driver.Value, 0, len(nodes)) nodeids := make(map[int64]*User) diff --git a/backend/ent/user_update.go b/backend/ent/user_update.go index f71f0cadf..70b9877b4 100644 --- a/backend/ent/user_update.go +++ b/backend/ent/user_update.go @@ -17,9 +17,11 @@ import ( "github.com/Wei-Shaw/sub2api/ent/predicate" "github.com/Wei-Shaw/sub2api/ent/promocodeusage" "github.com/Wei-Shaw/sub2api/ent/redeemcode" + "github.com/Wei-Shaw/sub2api/ent/referralrelation" "github.com/Wei-Shaw/sub2api/ent/usagelog" "github.com/Wei-Shaw/sub2api/ent/user" "github.com/Wei-Shaw/sub2api/ent/userattributevalue" + "github.com/Wei-Shaw/sub2api/ent/userreferralprofile" "github.com/Wei-Shaw/sub2api/ent/usersubscription" ) @@ -419,6 +421,51 @@ func (_u *UserUpdate) AddPromoCodeUsages(v ...*PromoCodeUsage) *UserUpdate { return _u.AddPromoCodeUsageIDs(ids...) } +// AddReferralProfileIDs adds the "referral_profile" edge to the UserReferralProfile entity by IDs. +func (_u *UserUpdate) AddReferralProfileIDs(ids ...int64) *UserUpdate { + _u.mutation.AddReferralProfileIDs(ids...) + return _u +} + +// AddReferralProfile adds the "referral_profile" edges to the UserReferralProfile entity. +func (_u *UserUpdate) AddReferralProfile(v ...*UserReferralProfile) *UserUpdate { + ids := make([]int64, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddReferralProfileIDs(ids...) +} + +// AddReferralsGivenIDs adds the "referrals_given" edge to the ReferralRelation entity by IDs. +func (_u *UserUpdate) AddReferralsGivenIDs(ids ...int64) *UserUpdate { + _u.mutation.AddReferralsGivenIDs(ids...) + return _u +} + +// AddReferralsGiven adds the "referrals_given" edges to the ReferralRelation entity. +func (_u *UserUpdate) AddReferralsGiven(v ...*ReferralRelation) *UserUpdate { + ids := make([]int64, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddReferralsGivenIDs(ids...) +} + +// AddReferralReceivedIDs adds the "referral_received" edge to the ReferralRelation entity by IDs. +func (_u *UserUpdate) AddReferralReceivedIDs(ids ...int64) *UserUpdate { + _u.mutation.AddReferralReceivedIDs(ids...) + return _u +} + +// AddReferralReceived adds the "referral_received" edges to the ReferralRelation entity. +func (_u *UserUpdate) AddReferralReceived(v ...*ReferralRelation) *UserUpdate { + ids := make([]int64, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddReferralReceivedIDs(ids...) +} + // Mutation returns the UserMutation object of the builder. func (_u *UserUpdate) Mutation() *UserMutation { return _u.mutation @@ -613,6 +660,69 @@ func (_u *UserUpdate) RemovePromoCodeUsages(v ...*PromoCodeUsage) *UserUpdate { return _u.RemovePromoCodeUsageIDs(ids...) } +// ClearReferralProfile clears all "referral_profile" edges to the UserReferralProfile entity. +func (_u *UserUpdate) ClearReferralProfile() *UserUpdate { + _u.mutation.ClearReferralProfile() + return _u +} + +// RemoveReferralProfileIDs removes the "referral_profile" edge to UserReferralProfile entities by IDs. +func (_u *UserUpdate) RemoveReferralProfileIDs(ids ...int64) *UserUpdate { + _u.mutation.RemoveReferralProfileIDs(ids...) + return _u +} + +// RemoveReferralProfile removes "referral_profile" edges to UserReferralProfile entities. +func (_u *UserUpdate) RemoveReferralProfile(v ...*UserReferralProfile) *UserUpdate { + ids := make([]int64, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveReferralProfileIDs(ids...) +} + +// ClearReferralsGiven clears all "referrals_given" edges to the ReferralRelation entity. +func (_u *UserUpdate) ClearReferralsGiven() *UserUpdate { + _u.mutation.ClearReferralsGiven() + return _u +} + +// RemoveReferralsGivenIDs removes the "referrals_given" edge to ReferralRelation entities by IDs. +func (_u *UserUpdate) RemoveReferralsGivenIDs(ids ...int64) *UserUpdate { + _u.mutation.RemoveReferralsGivenIDs(ids...) + return _u +} + +// RemoveReferralsGiven removes "referrals_given" edges to ReferralRelation entities. +func (_u *UserUpdate) RemoveReferralsGiven(v ...*ReferralRelation) *UserUpdate { + ids := make([]int64, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveReferralsGivenIDs(ids...) +} + +// ClearReferralReceived clears all "referral_received" edges to the ReferralRelation entity. +func (_u *UserUpdate) ClearReferralReceived() *UserUpdate { + _u.mutation.ClearReferralReceived() + return _u +} + +// RemoveReferralReceivedIDs removes the "referral_received" edge to ReferralRelation entities by IDs. +func (_u *UserUpdate) RemoveReferralReceivedIDs(ids ...int64) *UserUpdate { + _u.mutation.RemoveReferralReceivedIDs(ids...) + return _u +} + +// RemoveReferralReceived removes "referral_received" edges to ReferralRelation entities. +func (_u *UserUpdate) RemoveReferralReceived(v ...*ReferralRelation) *UserUpdate { + ids := make([]int64, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveReferralReceivedIDs(ids...) +} + // Save executes the query and returns the number of nodes affected by the update operation. func (_u *UserUpdate) Save(ctx context.Context) (int, error) { if err := _u.defaults(); err != nil { @@ -1180,6 +1290,141 @@ func (_u *UserUpdate) sqlSave(ctx context.Context) (_node int, err error) { } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if _u.mutation.ReferralProfileCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ReferralProfileTable, + Columns: []string{user.ReferralProfileColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(userreferralprofile.FieldID, field.TypeInt64), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedReferralProfileIDs(); len(nodes) > 0 && !_u.mutation.ReferralProfileCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ReferralProfileTable, + Columns: []string{user.ReferralProfileColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(userreferralprofile.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ReferralProfileIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ReferralProfileTable, + Columns: []string{user.ReferralProfileColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(userreferralprofile.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.ReferralsGivenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ReferralsGivenTable, + Columns: []string{user.ReferralsGivenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(referralrelation.FieldID, field.TypeInt64), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedReferralsGivenIDs(); len(nodes) > 0 && !_u.mutation.ReferralsGivenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ReferralsGivenTable, + Columns: []string{user.ReferralsGivenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(referralrelation.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ReferralsGivenIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ReferralsGivenTable, + Columns: []string{user.ReferralsGivenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(referralrelation.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.ReferralReceivedCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ReferralReceivedTable, + Columns: []string{user.ReferralReceivedColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(referralrelation.FieldID, field.TypeInt64), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedReferralReceivedIDs(); len(nodes) > 0 && !_u.mutation.ReferralReceivedCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ReferralReceivedTable, + Columns: []string{user.ReferralReceivedColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(referralrelation.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ReferralReceivedIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ReferralReceivedTable, + Columns: []string{user.ReferralReceivedColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(referralrelation.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{user.Label} @@ -1583,6 +1828,51 @@ func (_u *UserUpdateOne) AddPromoCodeUsages(v ...*PromoCodeUsage) *UserUpdateOne return _u.AddPromoCodeUsageIDs(ids...) } +// AddReferralProfileIDs adds the "referral_profile" edge to the UserReferralProfile entity by IDs. +func (_u *UserUpdateOne) AddReferralProfileIDs(ids ...int64) *UserUpdateOne { + _u.mutation.AddReferralProfileIDs(ids...) + return _u +} + +// AddReferralProfile adds the "referral_profile" edges to the UserReferralProfile entity. +func (_u *UserUpdateOne) AddReferralProfile(v ...*UserReferralProfile) *UserUpdateOne { + ids := make([]int64, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddReferralProfileIDs(ids...) +} + +// AddReferralsGivenIDs adds the "referrals_given" edge to the ReferralRelation entity by IDs. +func (_u *UserUpdateOne) AddReferralsGivenIDs(ids ...int64) *UserUpdateOne { + _u.mutation.AddReferralsGivenIDs(ids...) + return _u +} + +// AddReferralsGiven adds the "referrals_given" edges to the ReferralRelation entity. +func (_u *UserUpdateOne) AddReferralsGiven(v ...*ReferralRelation) *UserUpdateOne { + ids := make([]int64, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddReferralsGivenIDs(ids...) +} + +// AddReferralReceivedIDs adds the "referral_received" edge to the ReferralRelation entity by IDs. +func (_u *UserUpdateOne) AddReferralReceivedIDs(ids ...int64) *UserUpdateOne { + _u.mutation.AddReferralReceivedIDs(ids...) + return _u +} + +// AddReferralReceived adds the "referral_received" edges to the ReferralRelation entity. +func (_u *UserUpdateOne) AddReferralReceived(v ...*ReferralRelation) *UserUpdateOne { + ids := make([]int64, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddReferralReceivedIDs(ids...) +} + // Mutation returns the UserMutation object of the builder. func (_u *UserUpdateOne) Mutation() *UserMutation { return _u.mutation @@ -1777,6 +2067,69 @@ func (_u *UserUpdateOne) RemovePromoCodeUsages(v ...*PromoCodeUsage) *UserUpdate return _u.RemovePromoCodeUsageIDs(ids...) } +// ClearReferralProfile clears all "referral_profile" edges to the UserReferralProfile entity. +func (_u *UserUpdateOne) ClearReferralProfile() *UserUpdateOne { + _u.mutation.ClearReferralProfile() + return _u +} + +// RemoveReferralProfileIDs removes the "referral_profile" edge to UserReferralProfile entities by IDs. +func (_u *UserUpdateOne) RemoveReferralProfileIDs(ids ...int64) *UserUpdateOne { + _u.mutation.RemoveReferralProfileIDs(ids...) + return _u +} + +// RemoveReferralProfile removes "referral_profile" edges to UserReferralProfile entities. +func (_u *UserUpdateOne) RemoveReferralProfile(v ...*UserReferralProfile) *UserUpdateOne { + ids := make([]int64, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveReferralProfileIDs(ids...) +} + +// ClearReferralsGiven clears all "referrals_given" edges to the ReferralRelation entity. +func (_u *UserUpdateOne) ClearReferralsGiven() *UserUpdateOne { + _u.mutation.ClearReferralsGiven() + return _u +} + +// RemoveReferralsGivenIDs removes the "referrals_given" edge to ReferralRelation entities by IDs. +func (_u *UserUpdateOne) RemoveReferralsGivenIDs(ids ...int64) *UserUpdateOne { + _u.mutation.RemoveReferralsGivenIDs(ids...) + return _u +} + +// RemoveReferralsGiven removes "referrals_given" edges to ReferralRelation entities. +func (_u *UserUpdateOne) RemoveReferralsGiven(v ...*ReferralRelation) *UserUpdateOne { + ids := make([]int64, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveReferralsGivenIDs(ids...) +} + +// ClearReferralReceived clears all "referral_received" edges to the ReferralRelation entity. +func (_u *UserUpdateOne) ClearReferralReceived() *UserUpdateOne { + _u.mutation.ClearReferralReceived() + return _u +} + +// RemoveReferralReceivedIDs removes the "referral_received" edge to ReferralRelation entities by IDs. +func (_u *UserUpdateOne) RemoveReferralReceivedIDs(ids ...int64) *UserUpdateOne { + _u.mutation.RemoveReferralReceivedIDs(ids...) + return _u +} + +// RemoveReferralReceived removes "referral_received" edges to ReferralRelation entities. +func (_u *UserUpdateOne) RemoveReferralReceived(v ...*ReferralRelation) *UserUpdateOne { + ids := make([]int64, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveReferralReceivedIDs(ids...) +} + // Where appends a list predicates to the UserUpdate builder. func (_u *UserUpdateOne) Where(ps ...predicate.User) *UserUpdateOne { _u.mutation.Where(ps...) @@ -2374,6 +2727,141 @@ func (_u *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) { } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if _u.mutation.ReferralProfileCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ReferralProfileTable, + Columns: []string{user.ReferralProfileColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(userreferralprofile.FieldID, field.TypeInt64), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedReferralProfileIDs(); len(nodes) > 0 && !_u.mutation.ReferralProfileCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ReferralProfileTable, + Columns: []string{user.ReferralProfileColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(userreferralprofile.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ReferralProfileIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ReferralProfileTable, + Columns: []string{user.ReferralProfileColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(userreferralprofile.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.ReferralsGivenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ReferralsGivenTable, + Columns: []string{user.ReferralsGivenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(referralrelation.FieldID, field.TypeInt64), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedReferralsGivenIDs(); len(nodes) > 0 && !_u.mutation.ReferralsGivenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ReferralsGivenTable, + Columns: []string{user.ReferralsGivenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(referralrelation.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ReferralsGivenIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ReferralsGivenTable, + Columns: []string{user.ReferralsGivenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(referralrelation.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.ReferralReceivedCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ReferralReceivedTable, + Columns: []string{user.ReferralReceivedColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(referralrelation.FieldID, field.TypeInt64), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedReferralReceivedIDs(); len(nodes) > 0 && !_u.mutation.ReferralReceivedCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ReferralReceivedTable, + Columns: []string{user.ReferralReceivedColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(referralrelation.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ReferralReceivedIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ReferralReceivedTable, + Columns: []string{user.ReferralReceivedColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(referralrelation.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } _node = &User{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/backend/ent/userreferralprofile.go b/backend/ent/userreferralprofile.go new file mode 100644 index 000000000..05b03e63d --- /dev/null +++ b/backend/ent/userreferralprofile.go @@ -0,0 +1,157 @@ +// 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/user" + "github.com/Wei-Shaw/sub2api/ent/userreferralprofile" +) + +// UserReferralProfile is the model entity for the UserReferralProfile schema. +type UserReferralProfile struct { + config `json:"-"` + // ID of the ent. + ID int64 `json:"id,omitempty"` + // UserID holds the value of the "user_id" field. + UserID int64 `json:"user_id,omitempty"` + // 8位大写字母+数字的专属邀请码 + ReferralCode string `json:"referral_code,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the UserReferralProfileQuery when eager-loading is set. + Edges UserReferralProfileEdges `json:"edges"` + selectValues sql.SelectValues +} + +// UserReferralProfileEdges holds the relations/edges for other nodes in the graph. +type UserReferralProfileEdges struct { + // User holds the value of the user edge. + User *User `json:"user,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// UserOrErr returns the User value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e UserReferralProfileEdges) UserOrErr() (*User, error) { + if e.User != nil { + return e.User, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: user.Label} + } + return nil, &NotLoadedError{edge: "user"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*UserReferralProfile) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case userreferralprofile.FieldID, userreferralprofile.FieldUserID: + values[i] = new(sql.NullInt64) + case userreferralprofile.FieldReferralCode: + values[i] = new(sql.NullString) + case userreferralprofile.FieldCreatedAt: + 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 UserReferralProfile fields. +func (_m *UserReferralProfile) 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 userreferralprofile.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 userreferralprofile.FieldUserID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field user_id", values[i]) + } else if value.Valid { + _m.UserID = value.Int64 + } + case userreferralprofile.FieldReferralCode: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field referral_code", values[i]) + } else if value.Valid { + _m.ReferralCode = value.String + } + case userreferralprofile.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 + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the UserReferralProfile. +// This includes values selected through modifiers, order, etc. +func (_m *UserReferralProfile) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryUser queries the "user" edge of the UserReferralProfile entity. +func (_m *UserReferralProfile) QueryUser() *UserQuery { + return NewUserReferralProfileClient(_m.config).QueryUser(_m) +} + +// Update returns a builder for updating this UserReferralProfile. +// Note that you need to call UserReferralProfile.Unwrap() before calling this method if this UserReferralProfile +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *UserReferralProfile) Update() *UserReferralProfileUpdateOne { + return NewUserReferralProfileClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the UserReferralProfile 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 *UserReferralProfile) Unwrap() *UserReferralProfile { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: UserReferralProfile is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *UserReferralProfile) String() string { + var builder strings.Builder + builder.WriteString("UserReferralProfile(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("user_id=") + builder.WriteString(fmt.Sprintf("%v", _m.UserID)) + builder.WriteString(", ") + builder.WriteString("referral_code=") + builder.WriteString(_m.ReferralCode) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// UserReferralProfiles is a parsable slice of UserReferralProfile. +type UserReferralProfiles []*UserReferralProfile diff --git a/backend/ent/userreferralprofile/userreferralprofile.go b/backend/ent/userreferralprofile/userreferralprofile.go new file mode 100644 index 000000000..535dbd4f4 --- /dev/null +++ b/backend/ent/userreferralprofile/userreferralprofile.go @@ -0,0 +1,98 @@ +// Code generated by ent, DO NOT EDIT. + +package userreferralprofile + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the userreferralprofile type in the database. + Label = "user_referral_profile" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldUserID holds the string denoting the user_id field in the database. + FieldUserID = "user_id" + // FieldReferralCode holds the string denoting the referral_code field in the database. + FieldReferralCode = "referral_code" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // EdgeUser holds the string denoting the user edge name in mutations. + EdgeUser = "user" + // Table holds the table name of the userreferralprofile in the database. + Table = "user_referral_profiles" + // UserTable is the table that holds the user relation/edge. + UserTable = "user_referral_profiles" + // UserInverseTable is the table name for the User entity. + // It exists in this package in order to avoid circular dependency with the "user" package. + UserInverseTable = "users" + // UserColumn is the table column denoting the user relation/edge. + UserColumn = "user_id" +) + +// Columns holds all SQL columns for userreferralprofile fields. +var Columns = []string{ + FieldID, + FieldUserID, + FieldReferralCode, + FieldCreatedAt, +} + +// 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 ( + // UserIDValidator is a validator for the "user_id" field. It is called by the builders before save. + UserIDValidator func(int64) error + // ReferralCodeValidator is a validator for the "referral_code" field. It is called by the builders before save. + ReferralCodeValidator func(string) error + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time +) + +// OrderOption defines the ordering options for the UserReferralProfile 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() +} + +// ByUserID orders the results by the user_id field. +func ByUserID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUserID, opts...).ToFunc() +} + +// ByReferralCode orders the results by the referral_code field. +func ByReferralCode(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldReferralCode, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByUserField orders the results by user field. +func ByUserField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newUserStep(), sql.OrderByField(field, opts...)) + } +} +func newUserStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UserInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, UserTable, UserColumn), + ) +} diff --git a/backend/ent/userreferralprofile/where.go b/backend/ent/userreferralprofile/where.go new file mode 100644 index 000000000..5b0d08742 --- /dev/null +++ b/backend/ent/userreferralprofile/where.go @@ -0,0 +1,234 @@ +// Code generated by ent, DO NOT EDIT. + +package userreferralprofile + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/Wei-Shaw/sub2api/ent/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id int64) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int64) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int64) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int64) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int64) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int64) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int64) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int64) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int64) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldLTE(FieldID, id)) +} + +// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. +func UserID(v int64) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldEQ(FieldUserID, v)) +} + +// ReferralCode applies equality check predicate on the "referral_code" field. It's identical to ReferralCodeEQ. +func ReferralCode(v string) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldEQ(FieldReferralCode, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldEQ(FieldCreatedAt, v)) +} + +// UserIDEQ applies the EQ predicate on the "user_id" field. +func UserIDEQ(v int64) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldEQ(FieldUserID, v)) +} + +// UserIDNEQ applies the NEQ predicate on the "user_id" field. +func UserIDNEQ(v int64) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldNEQ(FieldUserID, v)) +} + +// UserIDIn applies the In predicate on the "user_id" field. +func UserIDIn(vs ...int64) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldIn(FieldUserID, vs...)) +} + +// UserIDNotIn applies the NotIn predicate on the "user_id" field. +func UserIDNotIn(vs ...int64) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldNotIn(FieldUserID, vs...)) +} + +// ReferralCodeEQ applies the EQ predicate on the "referral_code" field. +func ReferralCodeEQ(v string) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldEQ(FieldReferralCode, v)) +} + +// ReferralCodeNEQ applies the NEQ predicate on the "referral_code" field. +func ReferralCodeNEQ(v string) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldNEQ(FieldReferralCode, v)) +} + +// ReferralCodeIn applies the In predicate on the "referral_code" field. +func ReferralCodeIn(vs ...string) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldIn(FieldReferralCode, vs...)) +} + +// ReferralCodeNotIn applies the NotIn predicate on the "referral_code" field. +func ReferralCodeNotIn(vs ...string) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldNotIn(FieldReferralCode, vs...)) +} + +// ReferralCodeGT applies the GT predicate on the "referral_code" field. +func ReferralCodeGT(v string) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldGT(FieldReferralCode, v)) +} + +// ReferralCodeGTE applies the GTE predicate on the "referral_code" field. +func ReferralCodeGTE(v string) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldGTE(FieldReferralCode, v)) +} + +// ReferralCodeLT applies the LT predicate on the "referral_code" field. +func ReferralCodeLT(v string) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldLT(FieldReferralCode, v)) +} + +// ReferralCodeLTE applies the LTE predicate on the "referral_code" field. +func ReferralCodeLTE(v string) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldLTE(FieldReferralCode, v)) +} + +// ReferralCodeContains applies the Contains predicate on the "referral_code" field. +func ReferralCodeContains(v string) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldContains(FieldReferralCode, v)) +} + +// ReferralCodeHasPrefix applies the HasPrefix predicate on the "referral_code" field. +func ReferralCodeHasPrefix(v string) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldHasPrefix(FieldReferralCode, v)) +} + +// ReferralCodeHasSuffix applies the HasSuffix predicate on the "referral_code" field. +func ReferralCodeHasSuffix(v string) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldHasSuffix(FieldReferralCode, v)) +} + +// ReferralCodeEqualFold applies the EqualFold predicate on the "referral_code" field. +func ReferralCodeEqualFold(v string) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldEqualFold(FieldReferralCode, v)) +} + +// ReferralCodeContainsFold applies the ContainsFold predicate on the "referral_code" field. +func ReferralCodeContainsFold(v string) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldContainsFold(FieldReferralCode, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.FieldLTE(FieldCreatedAt, v)) +} + +// HasUser applies the HasEdge predicate on the "user" edge. +func HasUser() predicate.UserReferralProfile { + return predicate.UserReferralProfile(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, UserTable, UserColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates). +func HasUserWith(preds ...predicate.User) predicate.UserReferralProfile { + return predicate.UserReferralProfile(func(s *sql.Selector) { + step := newUserStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.UserReferralProfile) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.UserReferralProfile) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.UserReferralProfile) predicate.UserReferralProfile { + return predicate.UserReferralProfile(sql.NotPredicates(p)) +} diff --git a/backend/ent/userreferralprofile_create.go b/backend/ent/userreferralprofile_create.go new file mode 100644 index 000000000..e1349feb1 --- /dev/null +++ b/backend/ent/userreferralprofile_create.go @@ -0,0 +1,583 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/Wei-Shaw/sub2api/ent/user" + "github.com/Wei-Shaw/sub2api/ent/userreferralprofile" +) + +// UserReferralProfileCreate is the builder for creating a UserReferralProfile entity. +type UserReferralProfileCreate struct { + config + mutation *UserReferralProfileMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetUserID sets the "user_id" field. +func (_c *UserReferralProfileCreate) SetUserID(v int64) *UserReferralProfileCreate { + _c.mutation.SetUserID(v) + return _c +} + +// SetReferralCode sets the "referral_code" field. +func (_c *UserReferralProfileCreate) SetReferralCode(v string) *UserReferralProfileCreate { + _c.mutation.SetReferralCode(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *UserReferralProfileCreate) SetCreatedAt(v time.Time) *UserReferralProfileCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *UserReferralProfileCreate) SetNillableCreatedAt(v *time.Time) *UserReferralProfileCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUser sets the "user" edge to the User entity. +func (_c *UserReferralProfileCreate) SetUser(v *User) *UserReferralProfileCreate { + return _c.SetUserID(v.ID) +} + +// Mutation returns the UserReferralProfileMutation object of the builder. +func (_c *UserReferralProfileCreate) Mutation() *UserReferralProfileMutation { + return _c.mutation +} + +// Save creates the UserReferralProfile in the database. +func (_c *UserReferralProfileCreate) Save(ctx context.Context) (*UserReferralProfile, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *UserReferralProfileCreate) SaveX(ctx context.Context) *UserReferralProfile { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *UserReferralProfileCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *UserReferralProfileCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *UserReferralProfileCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := userreferralprofile.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *UserReferralProfileCreate) check() error { + if _, ok := _c.mutation.UserID(); !ok { + return &ValidationError{Name: "user_id", err: errors.New(`ent: missing required field "UserReferralProfile.user_id"`)} + } + if v, ok := _c.mutation.UserID(); ok { + if err := userreferralprofile.UserIDValidator(v); err != nil { + return &ValidationError{Name: "user_id", err: fmt.Errorf(`ent: validator failed for field "UserReferralProfile.user_id": %w`, err)} + } + } + if _, ok := _c.mutation.ReferralCode(); !ok { + return &ValidationError{Name: "referral_code", err: errors.New(`ent: missing required field "UserReferralProfile.referral_code"`)} + } + if v, ok := _c.mutation.ReferralCode(); ok { + if err := userreferralprofile.ReferralCodeValidator(v); err != nil { + return &ValidationError{Name: "referral_code", err: fmt.Errorf(`ent: validator failed for field "UserReferralProfile.referral_code": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "UserReferralProfile.created_at"`)} + } + if len(_c.mutation.UserIDs()) == 0 { + return &ValidationError{Name: "user", err: errors.New(`ent: missing required edge "UserReferralProfile.user"`)} + } + return nil +} + +func (_c *UserReferralProfileCreate) sqlSave(ctx context.Context) (*UserReferralProfile, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int64(id) + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *UserReferralProfileCreate) createSpec() (*UserReferralProfile, *sqlgraph.CreateSpec) { + var ( + _node = &UserReferralProfile{config: _c.config} + _spec = sqlgraph.NewCreateSpec(userreferralprofile.Table, sqlgraph.NewFieldSpec(userreferralprofile.FieldID, field.TypeInt64)) + ) + _spec.OnConflict = _c.conflict + if value, ok := _c.mutation.ReferralCode(); ok { + _spec.SetField(userreferralprofile.FieldReferralCode, field.TypeString, value) + _node.ReferralCode = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(userreferralprofile.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if nodes := _c.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: userreferralprofile.UserTable, + Columns: []string{userreferralprofile.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.UserID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.UserReferralProfile.Create(). +// SetUserID(v). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.UserReferralProfileUpsert) { +// SetUserID(v+v). +// }). +// Exec(ctx) +func (_c *UserReferralProfileCreate) OnConflict(opts ...sql.ConflictOption) *UserReferralProfileUpsertOne { + _c.conflict = opts + return &UserReferralProfileUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.UserReferralProfile.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *UserReferralProfileCreate) OnConflictColumns(columns ...string) *UserReferralProfileUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &UserReferralProfileUpsertOne{ + create: _c, + } +} + +type ( + // UserReferralProfileUpsertOne is the builder for "upsert"-ing + // one UserReferralProfile node. + UserReferralProfileUpsertOne struct { + create *UserReferralProfileCreate + } + + // UserReferralProfileUpsert is the "OnConflict" setter. + UserReferralProfileUpsert struct { + *sql.UpdateSet + } +) + +// SetUserID sets the "user_id" field. +func (u *UserReferralProfileUpsert) SetUserID(v int64) *UserReferralProfileUpsert { + u.Set(userreferralprofile.FieldUserID, v) + return u +} + +// UpdateUserID sets the "user_id" field to the value that was provided on create. +func (u *UserReferralProfileUpsert) UpdateUserID() *UserReferralProfileUpsert { + u.SetExcluded(userreferralprofile.FieldUserID) + return u +} + +// SetReferralCode sets the "referral_code" field. +func (u *UserReferralProfileUpsert) SetReferralCode(v string) *UserReferralProfileUpsert { + u.Set(userreferralprofile.FieldReferralCode, v) + return u +} + +// UpdateReferralCode sets the "referral_code" field to the value that was provided on create. +func (u *UserReferralProfileUpsert) UpdateReferralCode() *UserReferralProfileUpsert { + u.SetExcluded(userreferralprofile.FieldReferralCode) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create. +// Using this option is equivalent to using: +// +// client.UserReferralProfile.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// ). +// Exec(ctx) +func (u *UserReferralProfileUpsertOne) UpdateNewValues() *UserReferralProfileUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(userreferralprofile.FieldCreatedAt) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.UserReferralProfile.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *UserReferralProfileUpsertOne) Ignore() *UserReferralProfileUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *UserReferralProfileUpsertOne) DoNothing() *UserReferralProfileUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the UserReferralProfileCreate.OnConflict +// documentation for more info. +func (u *UserReferralProfileUpsertOne) Update(set func(*UserReferralProfileUpsert)) *UserReferralProfileUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&UserReferralProfileUpsert{UpdateSet: update}) + })) + return u +} + +// SetUserID sets the "user_id" field. +func (u *UserReferralProfileUpsertOne) SetUserID(v int64) *UserReferralProfileUpsertOne { + return u.Update(func(s *UserReferralProfileUpsert) { + s.SetUserID(v) + }) +} + +// UpdateUserID sets the "user_id" field to the value that was provided on create. +func (u *UserReferralProfileUpsertOne) UpdateUserID() *UserReferralProfileUpsertOne { + return u.Update(func(s *UserReferralProfileUpsert) { + s.UpdateUserID() + }) +} + +// SetReferralCode sets the "referral_code" field. +func (u *UserReferralProfileUpsertOne) SetReferralCode(v string) *UserReferralProfileUpsertOne { + return u.Update(func(s *UserReferralProfileUpsert) { + s.SetReferralCode(v) + }) +} + +// UpdateReferralCode sets the "referral_code" field to the value that was provided on create. +func (u *UserReferralProfileUpsertOne) UpdateReferralCode() *UserReferralProfileUpsertOne { + return u.Update(func(s *UserReferralProfileUpsert) { + s.UpdateReferralCode() + }) +} + +// Exec executes the query. +func (u *UserReferralProfileUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for UserReferralProfileCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *UserReferralProfileUpsertOne) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} + +// Exec executes the UPSERT query and returns the inserted/updated ID. +func (u *UserReferralProfileUpsertOne) ID(ctx context.Context) (id int64, err error) { + node, err := u.create.Save(ctx) + if err != nil { + return id, err + } + return node.ID, nil +} + +// IDX is like ID, but panics if an error occurs. +func (u *UserReferralProfileUpsertOne) IDX(ctx context.Context) int64 { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// UserReferralProfileCreateBulk is the builder for creating many UserReferralProfile entities in bulk. +type UserReferralProfileCreateBulk struct { + config + err error + builders []*UserReferralProfileCreate + conflict []sql.ConflictOption +} + +// Save creates the UserReferralProfile entities in the database. +func (_c *UserReferralProfileCreateBulk) Save(ctx context.Context) ([]*UserReferralProfile, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*UserReferralProfile, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*UserReferralProfileMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = _c.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int64(id) + } + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *UserReferralProfileCreateBulk) SaveX(ctx context.Context) []*UserReferralProfile { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *UserReferralProfileCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *UserReferralProfileCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.UserReferralProfile.CreateBulk(builders...). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.UserReferralProfileUpsert) { +// SetUserID(v+v). +// }). +// Exec(ctx) +func (_c *UserReferralProfileCreateBulk) OnConflict(opts ...sql.ConflictOption) *UserReferralProfileUpsertBulk { + _c.conflict = opts + return &UserReferralProfileUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.UserReferralProfile.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *UserReferralProfileCreateBulk) OnConflictColumns(columns ...string) *UserReferralProfileUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &UserReferralProfileUpsertBulk{ + create: _c, + } +} + +// UserReferralProfileUpsertBulk is the builder for "upsert"-ing +// a bulk of UserReferralProfile nodes. +type UserReferralProfileUpsertBulk struct { + create *UserReferralProfileCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.UserReferralProfile.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// ). +// Exec(ctx) +func (u *UserReferralProfileUpsertBulk) UpdateNewValues() *UserReferralProfileUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + for _, b := range u.create.builders { + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(userreferralprofile.FieldCreatedAt) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.UserReferralProfile.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *UserReferralProfileUpsertBulk) Ignore() *UserReferralProfileUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *UserReferralProfileUpsertBulk) DoNothing() *UserReferralProfileUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the UserReferralProfileCreateBulk.OnConflict +// documentation for more info. +func (u *UserReferralProfileUpsertBulk) Update(set func(*UserReferralProfileUpsert)) *UserReferralProfileUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&UserReferralProfileUpsert{UpdateSet: update}) + })) + return u +} + +// SetUserID sets the "user_id" field. +func (u *UserReferralProfileUpsertBulk) SetUserID(v int64) *UserReferralProfileUpsertBulk { + return u.Update(func(s *UserReferralProfileUpsert) { + s.SetUserID(v) + }) +} + +// UpdateUserID sets the "user_id" field to the value that was provided on create. +func (u *UserReferralProfileUpsertBulk) UpdateUserID() *UserReferralProfileUpsertBulk { + return u.Update(func(s *UserReferralProfileUpsert) { + s.UpdateUserID() + }) +} + +// SetReferralCode sets the "referral_code" field. +func (u *UserReferralProfileUpsertBulk) SetReferralCode(v string) *UserReferralProfileUpsertBulk { + return u.Update(func(s *UserReferralProfileUpsert) { + s.SetReferralCode(v) + }) +} + +// UpdateReferralCode sets the "referral_code" field to the value that was provided on create. +func (u *UserReferralProfileUpsertBulk) UpdateReferralCode() *UserReferralProfileUpsertBulk { + return u.Update(func(s *UserReferralProfileUpsert) { + s.UpdateReferralCode() + }) +} + +// Exec executes the query. +func (u *UserReferralProfileUpsertBulk) Exec(ctx context.Context) error { + if u.create.err != nil { + return u.create.err + } + for i, b := range u.create.builders { + if len(b.conflict) != 0 { + return fmt.Errorf("ent: OnConflict was set for builder %d. Set it on the UserReferralProfileCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for UserReferralProfileCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *UserReferralProfileUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/ent/userreferralprofile_delete.go b/backend/ent/userreferralprofile_delete.go new file mode 100644 index 000000000..20a914b92 --- /dev/null +++ b/backend/ent/userreferralprofile_delete.go @@ -0,0 +1,88 @@ +// 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/userreferralprofile" +) + +// UserReferralProfileDelete is the builder for deleting a UserReferralProfile entity. +type UserReferralProfileDelete struct { + config + hooks []Hook + mutation *UserReferralProfileMutation +} + +// Where appends a list predicates to the UserReferralProfileDelete builder. +func (_d *UserReferralProfileDelete) Where(ps ...predicate.UserReferralProfile) *UserReferralProfileDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *UserReferralProfileDelete) 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 *UserReferralProfileDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *UserReferralProfileDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(userreferralprofile.Table, sqlgraph.NewFieldSpec(userreferralprofile.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 +} + +// UserReferralProfileDeleteOne is the builder for deleting a single UserReferralProfile entity. +type UserReferralProfileDeleteOne struct { + _d *UserReferralProfileDelete +} + +// Where appends a list predicates to the UserReferralProfileDelete builder. +func (_d *UserReferralProfileDeleteOne) Where(ps ...predicate.UserReferralProfile) *UserReferralProfileDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *UserReferralProfileDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{userreferralprofile.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *UserReferralProfileDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/ent/userreferralprofile_query.go b/backend/ent/userreferralprofile_query.go new file mode 100644 index 000000000..156fdf4c0 --- /dev/null +++ b/backend/ent/userreferralprofile_query.go @@ -0,0 +1,643 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "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/user" + "github.com/Wei-Shaw/sub2api/ent/userreferralprofile" +) + +// UserReferralProfileQuery is the builder for querying UserReferralProfile entities. +type UserReferralProfileQuery struct { + config + ctx *QueryContext + order []userreferralprofile.OrderOption + inters []Interceptor + predicates []predicate.UserReferralProfile + withUser *UserQuery + modifiers []func(*sql.Selector) + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the UserReferralProfileQuery builder. +func (_q *UserReferralProfileQuery) Where(ps ...predicate.UserReferralProfile) *UserReferralProfileQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *UserReferralProfileQuery) Limit(limit int) *UserReferralProfileQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *UserReferralProfileQuery) Offset(offset int) *UserReferralProfileQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *UserReferralProfileQuery) Unique(unique bool) *UserReferralProfileQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *UserReferralProfileQuery) Order(o ...userreferralprofile.OrderOption) *UserReferralProfileQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryUser chains the current query on the "user" edge. +func (_q *UserReferralProfileQuery) QueryUser() *UserQuery { + query := (&UserClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(userreferralprofile.Table, userreferralprofile.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, userreferralprofile.UserTable, userreferralprofile.UserColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first UserReferralProfile entity from the query. +// Returns a *NotFoundError when no UserReferralProfile was found. +func (_q *UserReferralProfileQuery) First(ctx context.Context) (*UserReferralProfile, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{userreferralprofile.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *UserReferralProfileQuery) FirstX(ctx context.Context) *UserReferralProfile { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first UserReferralProfile ID from the query. +// Returns a *NotFoundError when no UserReferralProfile ID was found. +func (_q *UserReferralProfileQuery) FirstID(ctx context.Context) (id int64, err error) { + var ids []int64 + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{userreferralprofile.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *UserReferralProfileQuery) FirstIDX(ctx context.Context) int64 { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single UserReferralProfile entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one UserReferralProfile entity is found. +// Returns a *NotFoundError when no UserReferralProfile entities are found. +func (_q *UserReferralProfileQuery) Only(ctx context.Context) (*UserReferralProfile, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{userreferralprofile.Label} + default: + return nil, &NotSingularError{userreferralprofile.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *UserReferralProfileQuery) OnlyX(ctx context.Context) *UserReferralProfile { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only UserReferralProfile ID in the query. +// Returns a *NotSingularError when more than one UserReferralProfile ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *UserReferralProfileQuery) OnlyID(ctx context.Context) (id int64, err error) { + var ids []int64 + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{userreferralprofile.Label} + default: + err = &NotSingularError{userreferralprofile.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *UserReferralProfileQuery) OnlyIDX(ctx context.Context) int64 { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of UserReferralProfiles. +func (_q *UserReferralProfileQuery) All(ctx context.Context) ([]*UserReferralProfile, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*UserReferralProfile, *UserReferralProfileQuery]() + return withInterceptors[[]*UserReferralProfile](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *UserReferralProfileQuery) AllX(ctx context.Context) []*UserReferralProfile { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of UserReferralProfile IDs. +func (_q *UserReferralProfileQuery) IDs(ctx context.Context) (ids []int64, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(userreferralprofile.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *UserReferralProfileQuery) IDsX(ctx context.Context) []int64 { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *UserReferralProfileQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*UserReferralProfileQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *UserReferralProfileQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *UserReferralProfileQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *UserReferralProfileQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the UserReferralProfileQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *UserReferralProfileQuery) Clone() *UserReferralProfileQuery { + if _q == nil { + return nil + } + return &UserReferralProfileQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]userreferralprofile.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.UserReferralProfile{}, _q.predicates...), + withUser: _q.withUser.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithUser tells the query-builder to eager-load the nodes that are connected to +// the "user" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *UserReferralProfileQuery) WithUser(opts ...func(*UserQuery)) *UserReferralProfileQuery { + query := (&UserClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withUser = query + return _q +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// UserID int64 `json:"user_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.UserReferralProfile.Query(). +// GroupBy(userreferralprofile.FieldUserID). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (_q *UserReferralProfileQuery) GroupBy(field string, fields ...string) *UserReferralProfileGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &UserReferralProfileGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = userreferralprofile.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// UserID int64 `json:"user_id,omitempty"` +// } +// +// client.UserReferralProfile.Query(). +// Select(userreferralprofile.FieldUserID). +// Scan(ctx, &v) +func (_q *UserReferralProfileQuery) Select(fields ...string) *UserReferralProfileSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &UserReferralProfileSelect{UserReferralProfileQuery: _q} + sbuild.label = userreferralprofile.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a UserReferralProfileSelect configured with the given aggregations. +func (_q *UserReferralProfileQuery) Aggregate(fns ...AggregateFunc) *UserReferralProfileSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *UserReferralProfileQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !userreferralprofile.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *UserReferralProfileQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*UserReferralProfile, error) { + var ( + nodes = []*UserReferralProfile{} + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withUser != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*UserReferralProfile).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &UserReferralProfile{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := _q.withUser; query != nil { + if err := _q.loadUser(ctx, query, nodes, nil, + func(n *UserReferralProfile, e *User) { n.Edges.User = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *UserReferralProfileQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*UserReferralProfile, init func(*UserReferralProfile), assign func(*UserReferralProfile, *User)) error { + ids := make([]int64, 0, len(nodes)) + nodeids := make(map[int64][]*UserReferralProfile) + for i := range nodes { + fk := nodes[i].UserID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(user.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "user_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *UserReferralProfileQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *UserReferralProfileQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(userreferralprofile.Table, userreferralprofile.Columns, sqlgraph.NewFieldSpec(userreferralprofile.FieldID, field.TypeInt64)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, userreferralprofile.FieldID) + for i := range fields { + if fields[i] != userreferralprofile.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withUser != nil { + _spec.Node.AddColumnOnce(userreferralprofile.FieldUserID) + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *UserReferralProfileQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(userreferralprofile.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = userreferralprofile.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, m := range _q.modifiers { + m(selector) + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + 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 *UserReferralProfileQuery) ForUpdate(opts ...sql.LockOption) *UserReferralProfileQuery { + 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 *UserReferralProfileQuery) ForShare(opts ...sql.LockOption) *UserReferralProfileQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// UserReferralProfileGroupBy is the group-by builder for UserReferralProfile entities. +type UserReferralProfileGroupBy struct { + selector + build *UserReferralProfileQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *UserReferralProfileGroupBy) Aggregate(fns ...AggregateFunc) *UserReferralProfileGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *UserReferralProfileGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*UserReferralProfileQuery, *UserReferralProfileGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *UserReferralProfileGroupBy) sqlScan(ctx context.Context, root *UserReferralProfileQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// UserReferralProfileSelect is the builder for selecting fields of UserReferralProfile entities. +type UserReferralProfileSelect struct { + *UserReferralProfileQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *UserReferralProfileSelect) Aggregate(fns ...AggregateFunc) *UserReferralProfileSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *UserReferralProfileSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*UserReferralProfileQuery, *UserReferralProfileSelect](ctx, _s.UserReferralProfileQuery, _s, _s.inters, v) +} + +func (_s *UserReferralProfileSelect) sqlScan(ctx context.Context, root *UserReferralProfileQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/backend/ent/userreferralprofile_update.go b/backend/ent/userreferralprofile_update.go new file mode 100644 index 000000000..095746d05 --- /dev/null +++ b/backend/ent/userreferralprofile_update.go @@ -0,0 +1,360 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "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/user" + "github.com/Wei-Shaw/sub2api/ent/userreferralprofile" +) + +// UserReferralProfileUpdate is the builder for updating UserReferralProfile entities. +type UserReferralProfileUpdate struct { + config + hooks []Hook + mutation *UserReferralProfileMutation +} + +// Where appends a list predicates to the UserReferralProfileUpdate builder. +func (_u *UserReferralProfileUpdate) Where(ps ...predicate.UserReferralProfile) *UserReferralProfileUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetUserID sets the "user_id" field. +func (_u *UserReferralProfileUpdate) SetUserID(v int64) *UserReferralProfileUpdate { + _u.mutation.SetUserID(v) + return _u +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (_u *UserReferralProfileUpdate) SetNillableUserID(v *int64) *UserReferralProfileUpdate { + if v != nil { + _u.SetUserID(*v) + } + return _u +} + +// SetReferralCode sets the "referral_code" field. +func (_u *UserReferralProfileUpdate) SetReferralCode(v string) *UserReferralProfileUpdate { + _u.mutation.SetReferralCode(v) + return _u +} + +// SetNillableReferralCode sets the "referral_code" field if the given value is not nil. +func (_u *UserReferralProfileUpdate) SetNillableReferralCode(v *string) *UserReferralProfileUpdate { + if v != nil { + _u.SetReferralCode(*v) + } + return _u +} + +// SetUser sets the "user" edge to the User entity. +func (_u *UserReferralProfileUpdate) SetUser(v *User) *UserReferralProfileUpdate { + return _u.SetUserID(v.ID) +} + +// Mutation returns the UserReferralProfileMutation object of the builder. +func (_u *UserReferralProfileUpdate) Mutation() *UserReferralProfileMutation { + return _u.mutation +} + +// ClearUser clears the "user" edge to the User entity. +func (_u *UserReferralProfileUpdate) ClearUser() *UserReferralProfileUpdate { + _u.mutation.ClearUser() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *UserReferralProfileUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *UserReferralProfileUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *UserReferralProfileUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *UserReferralProfileUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *UserReferralProfileUpdate) check() error { + if v, ok := _u.mutation.UserID(); ok { + if err := userreferralprofile.UserIDValidator(v); err != nil { + return &ValidationError{Name: "user_id", err: fmt.Errorf(`ent: validator failed for field "UserReferralProfile.user_id": %w`, err)} + } + } + if v, ok := _u.mutation.ReferralCode(); ok { + if err := userreferralprofile.ReferralCodeValidator(v); err != nil { + return &ValidationError{Name: "referral_code", err: fmt.Errorf(`ent: validator failed for field "UserReferralProfile.referral_code": %w`, err)} + } + } + if _u.mutation.UserCleared() && len(_u.mutation.UserIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "UserReferralProfile.user"`) + } + return nil +} + +func (_u *UserReferralProfileUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(userreferralprofile.Table, userreferralprofile.Columns, sqlgraph.NewFieldSpec(userreferralprofile.FieldID, field.TypeInt64)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.ReferralCode(); ok { + _spec.SetField(userreferralprofile.FieldReferralCode, field.TypeString, value) + } + if _u.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: userreferralprofile.UserTable, + Columns: []string{userreferralprofile.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: userreferralprofile.UserTable, + Columns: []string{userreferralprofile.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{userreferralprofile.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// UserReferralProfileUpdateOne is the builder for updating a single UserReferralProfile entity. +type UserReferralProfileUpdateOne struct { + config + fields []string + hooks []Hook + mutation *UserReferralProfileMutation +} + +// SetUserID sets the "user_id" field. +func (_u *UserReferralProfileUpdateOne) SetUserID(v int64) *UserReferralProfileUpdateOne { + _u.mutation.SetUserID(v) + return _u +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (_u *UserReferralProfileUpdateOne) SetNillableUserID(v *int64) *UserReferralProfileUpdateOne { + if v != nil { + _u.SetUserID(*v) + } + return _u +} + +// SetReferralCode sets the "referral_code" field. +func (_u *UserReferralProfileUpdateOne) SetReferralCode(v string) *UserReferralProfileUpdateOne { + _u.mutation.SetReferralCode(v) + return _u +} + +// SetNillableReferralCode sets the "referral_code" field if the given value is not nil. +func (_u *UserReferralProfileUpdateOne) SetNillableReferralCode(v *string) *UserReferralProfileUpdateOne { + if v != nil { + _u.SetReferralCode(*v) + } + return _u +} + +// SetUser sets the "user" edge to the User entity. +func (_u *UserReferralProfileUpdateOne) SetUser(v *User) *UserReferralProfileUpdateOne { + return _u.SetUserID(v.ID) +} + +// Mutation returns the UserReferralProfileMutation object of the builder. +func (_u *UserReferralProfileUpdateOne) Mutation() *UserReferralProfileMutation { + return _u.mutation +} + +// ClearUser clears the "user" edge to the User entity. +func (_u *UserReferralProfileUpdateOne) ClearUser() *UserReferralProfileUpdateOne { + _u.mutation.ClearUser() + return _u +} + +// Where appends a list predicates to the UserReferralProfileUpdate builder. +func (_u *UserReferralProfileUpdateOne) Where(ps ...predicate.UserReferralProfile) *UserReferralProfileUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *UserReferralProfileUpdateOne) Select(field string, fields ...string) *UserReferralProfileUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated UserReferralProfile entity. +func (_u *UserReferralProfileUpdateOne) Save(ctx context.Context) (*UserReferralProfile, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *UserReferralProfileUpdateOne) SaveX(ctx context.Context) *UserReferralProfile { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *UserReferralProfileUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *UserReferralProfileUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *UserReferralProfileUpdateOne) check() error { + if v, ok := _u.mutation.UserID(); ok { + if err := userreferralprofile.UserIDValidator(v); err != nil { + return &ValidationError{Name: "user_id", err: fmt.Errorf(`ent: validator failed for field "UserReferralProfile.user_id": %w`, err)} + } + } + if v, ok := _u.mutation.ReferralCode(); ok { + if err := userreferralprofile.ReferralCodeValidator(v); err != nil { + return &ValidationError{Name: "referral_code", err: fmt.Errorf(`ent: validator failed for field "UserReferralProfile.referral_code": %w`, err)} + } + } + if _u.mutation.UserCleared() && len(_u.mutation.UserIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "UserReferralProfile.user"`) + } + return nil +} + +func (_u *UserReferralProfileUpdateOne) sqlSave(ctx context.Context) (_node *UserReferralProfile, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(userreferralprofile.Table, userreferralprofile.Columns, sqlgraph.NewFieldSpec(userreferralprofile.FieldID, field.TypeInt64)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "UserReferralProfile.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, userreferralprofile.FieldID) + for _, f := range fields { + if !userreferralprofile.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != userreferralprofile.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.ReferralCode(); ok { + _spec.SetField(userreferralprofile.FieldReferralCode, field.TypeString, value) + } + if _u.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: userreferralprofile.UserTable, + Columns: []string{userreferralprofile.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: userreferralprofile.UserTable, + Columns: []string{userreferralprofile.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &UserReferralProfile{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{userreferralprofile.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/backend/go.sum b/backend/go.sum index 32e389a76..deb82542b 100644 --- a/backend/go.sum +++ b/backend/go.sum @@ -203,6 +203,8 @@ github.com/icholy/digest v1.1.0 h1:HfGg9Irj7i+IX1o1QAmPfIBNu/Q5A5Tu3n/MED9k9H4= github.com/icholy/digest v1.1.0/go.mod h1:QNrsSGQ5v7v9cReDI0+eyjsXGUoRSUZQHeQ5C4XLa0Y= github.com/imroc/req/v3 v3.57.0 h1:LMTUjNRUybUkTPn8oJDq8Kg3JRBOBTcnDhKu7mzupKI= github.com/imroc/req/v3 v3.57.0/go.mod h1:JL62ey1nvSLq81HORNcosvlf7SxZStONNqOprg0Pz00= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= diff --git a/backend/internal/handler/admin/referral_handler.go b/backend/internal/handler/admin/referral_handler.go new file mode 100644 index 000000000..42c2b83cb --- /dev/null +++ b/backend/internal/handler/admin/referral_handler.go @@ -0,0 +1,32 @@ +package admin + +import ( + "github.com/Wei-Shaw/sub2api/internal/pkg/response" + "github.com/Wei-Shaw/sub2api/internal/service" + + "github.com/gin-gonic/gin" +) + +// ReferralHandler handles admin referral management endpoints +type ReferralHandler struct { + referralService *service.ReferralService +} + +// NewReferralHandler creates a new admin ReferralHandler +func NewReferralHandler(referralService *service.ReferralService) *ReferralHandler { + return &ReferralHandler{ + referralService: referralService, + } +} + +// GetPlatformStats handles getting platform-wide referral statistics +// GET /api/v1/admin/referral/stats +func (h *ReferralHandler) GetPlatformStats(c *gin.Context) { + stats, err := h.referralService.GetPlatformStats(c.Request.Context()) + if err != nil { + response.ErrorFrom(c, err) + return + } + + response.Success(c, stats) +} diff --git a/backend/internal/handler/admin/setting_handler.go b/backend/internal/handler/admin/setting_handler.go index e32c142f4..40ddb2cfb 100644 --- a/backend/internal/handler/admin/setting_handler.go +++ b/backend/internal/handler/admin/setting_handler.go @@ -123,6 +123,9 @@ func (h *SettingHandler) GetSettings(c *gin.Context) { OpsQueryModeDefault: settings.OpsQueryModeDefault, OpsMetricsIntervalSeconds: settings.OpsMetricsIntervalSeconds, MinClaudeCodeVersion: settings.MinClaudeCodeVersion, + ReferralEnabled: settings.ReferralEnabled, + ReferralInviterReward: settings.ReferralInviterReward, + ReferralInviteeReward: settings.ReferralInviteeReward, }) } @@ -193,6 +196,11 @@ type UpdateSettingsRequest struct { OpsMetricsIntervalSeconds *int `json:"ops_metrics_interval_seconds"` MinClaudeCodeVersion string `json:"min_claude_code_version"` + + // 裂变推广配置 + ReferralEnabled bool `json:"referral_enabled"` + ReferralInviterReward float64 `json:"referral_inviter_reward"` + ReferralInviteeReward float64 `json:"referral_invitee_reward"` } // UpdateSettings 更新系统设置 @@ -465,6 +473,9 @@ func (h *SettingHandler) UpdateSettings(c *gin.Context) { EnableIdentityPatch: req.EnableIdentityPatch, IdentityPatchPrompt: req.IdentityPatchPrompt, MinClaudeCodeVersion: req.MinClaudeCodeVersion, + ReferralEnabled: req.ReferralEnabled, + ReferralInviterReward: req.ReferralInviterReward, + ReferralInviteeReward: req.ReferralInviteeReward, OpsMonitoringEnabled: func() bool { if req.OpsMonitoringEnabled != nil { return *req.OpsMonitoringEnabled @@ -561,6 +572,9 @@ func (h *SettingHandler) UpdateSettings(c *gin.Context) { OpsQueryModeDefault: updatedSettings.OpsQueryModeDefault, OpsMetricsIntervalSeconds: updatedSettings.OpsMetricsIntervalSeconds, MinClaudeCodeVersion: updatedSettings.MinClaudeCodeVersion, + ReferralEnabled: updatedSettings.ReferralEnabled, + ReferralInviterReward: updatedSettings.ReferralInviterReward, + ReferralInviteeReward: updatedSettings.ReferralInviteeReward, }) } diff --git a/backend/internal/handler/auth_handler.go b/backend/internal/handler/auth_handler.go index 1ffa9d717..93c445364 100644 --- a/backend/internal/handler/auth_handler.go +++ b/backend/internal/handler/auth_handler.go @@ -45,7 +45,8 @@ type RegisterRequest struct { VerifyCode string `json:"verify_code"` TurnstileToken string `json:"turnstile_token"` PromoCode string `json:"promo_code"` // 注册优惠码 - InvitationCode string `json:"invitation_code"` // 邀请码 + InvitationCode string `json:"invitation_code"` // 邀请码(兑换码类型) + ReferralCode string `json:"referral_code"` // 裂变推广邀请码 } // SendVerifyCodeRequest 发送验证码请求 @@ -119,7 +120,7 @@ func (h *AuthHandler) Register(c *gin.Context) { return } - _, user, err := h.authService.RegisterWithVerification(c.Request.Context(), req.Email, req.Password, req.VerifyCode, req.PromoCode, req.InvitationCode) + _, user, err := h.authService.RegisterWithVerification(c.Request.Context(), req.Email, req.Password, req.VerifyCode, req.PromoCode, req.InvitationCode, req.ReferralCode) if err != nil { response.ErrorFrom(c, err) return diff --git a/backend/internal/handler/dto/settings.go b/backend/internal/handler/dto/settings.go index beb03e679..ac5e56ec4 100644 --- a/backend/internal/handler/dto/settings.go +++ b/backend/internal/handler/dto/settings.go @@ -77,6 +77,11 @@ type SystemSettings struct { OpsMetricsIntervalSeconds int `json:"ops_metrics_interval_seconds"` MinClaudeCodeVersion string `json:"min_claude_code_version"` + + // 裂变推广配置 + ReferralEnabled bool `json:"referral_enabled"` + ReferralInviterReward float64 `json:"referral_inviter_reward"` + ReferralInviteeReward float64 `json:"referral_invitee_reward"` } type DefaultSubscriptionSetting struct { @@ -107,6 +112,7 @@ type PublicSettings struct { LinuxDoOAuthEnabled bool `json:"linuxdo_oauth_enabled"` SoraClientEnabled bool `json:"sora_client_enabled"` Version string `json:"version"` + ReferralEnabled bool `json:"referral_enabled"` } // SoraS3Settings Sora S3 存储配置 DTO(响应用,不含敏感字段) diff --git a/backend/internal/handler/handler.go b/backend/internal/handler/handler.go index 1e1247fc8..e5692d238 100644 --- a/backend/internal/handler/handler.go +++ b/backend/internal/handler/handler.go @@ -27,6 +27,7 @@ type AdminHandlers struct { UserAttribute *admin.UserAttributeHandler ErrorPassthrough *admin.ErrorPassthroughHandler APIKey *admin.AdminAPIKeyHandler + Referral *admin.ReferralHandler } // Handlers contains all HTTP handlers @@ -45,6 +46,7 @@ type Handlers struct { SoraClient *SoraClientHandler Setting *SettingHandler Totp *TotpHandler + Referral *ReferralHandler } // BuildInfo contains build-time information diff --git a/backend/internal/handler/referral_handler.go b/backend/internal/handler/referral_handler.go new file mode 100644 index 000000000..2316d3c7c --- /dev/null +++ b/backend/internal/handler/referral_handler.go @@ -0,0 +1,67 @@ +package handler + +import ( + "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" + "github.com/Wei-Shaw/sub2api/internal/pkg/response" + middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + + "github.com/gin-gonic/gin" +) + +// ReferralHandler handles user referral/invitation endpoints +type ReferralHandler struct { + referralService *service.ReferralService +} + +// NewReferralHandler creates a new ReferralHandler +func NewReferralHandler(referralService *service.ReferralService) *ReferralHandler { + return &ReferralHandler{ + referralService: referralService, + } +} + +// GetMyReferralInfo handles getting the current user's referral info +// GET /api/v1/referral +func (h *ReferralHandler) GetMyReferralInfo(c *gin.Context) { + subject, ok := middleware2.GetAuthSubjectFromContext(c) + if !ok { + response.Unauthorized(c, "User not authenticated") + return + } + + // 使用请求的 Origin 作为站点基础 URL(用于构建邀请链接) + siteBaseURL := c.Request.Header.Get("Origin") + + info, err := h.referralService.GetMyReferralInfo(c.Request.Context(), subject.UserID, siteBaseURL) + if err != nil { + response.ErrorFrom(c, err) + return + } + + response.Success(c, info) +} + +// ListMyInvitees handles listing the current user's invited users +// GET /api/v1/referral/invitees +func (h *ReferralHandler) ListMyInvitees(c *gin.Context) { + subject, ok := middleware2.GetAuthSubjectFromContext(c) + if !ok { + response.Unauthorized(c, "User not authenticated") + return + } + + page, pageSize := response.ParsePagination(c) + params := pagination.PaginationParams{ + Page: page, + PageSize: pageSize, + } + + invitees, result, err := h.referralService.ListMyInvitees(c.Request.Context(), subject.UserID, params) + if err != nil { + response.ErrorFrom(c, err) + return + } + + response.Paginated(c, invitees, result.Total, params.Page, params.PageSize) +} diff --git a/backend/internal/handler/setting_handler.go b/backend/internal/handler/setting_handler.go index a48eaf318..58695a44d 100644 --- a/backend/internal/handler/setting_handler.go +++ b/backend/internal/handler/setting_handler.go @@ -54,5 +54,6 @@ func (h *SettingHandler) GetPublicSettings(c *gin.Context) { LinuxDoOAuthEnabled: settings.LinuxDoOAuthEnabled, SoraClientEnabled: settings.SoraClientEnabled, Version: h.version, + ReferralEnabled: settings.ReferralEnabled, }) } diff --git a/backend/internal/handler/wire.go b/backend/internal/handler/wire.go index 76f5a9796..b93773efb 100644 --- a/backend/internal/handler/wire.go +++ b/backend/internal/handler/wire.go @@ -30,6 +30,7 @@ func ProvideAdminHandlers( userAttributeHandler *admin.UserAttributeHandler, errorPassthroughHandler *admin.ErrorPassthroughHandler, apiKeyHandler *admin.AdminAPIKeyHandler, + referralHandler *admin.ReferralHandler, ) *AdminHandlers { return &AdminHandlers{ Dashboard: dashboardHandler, @@ -53,6 +54,7 @@ func ProvideAdminHandlers( UserAttribute: userAttributeHandler, ErrorPassthrough: errorPassthroughHandler, APIKey: apiKeyHandler, + Referral: referralHandler, } } @@ -82,6 +84,7 @@ func ProvideHandlers( soraClientHandler *SoraClientHandler, settingHandler *SettingHandler, totpHandler *TotpHandler, + referralHandler *ReferralHandler, _ *service.IdempotencyCoordinator, _ *service.IdempotencyCleanupService, ) *Handlers { @@ -100,6 +103,7 @@ func ProvideHandlers( SoraClient: soraClientHandler, Setting: settingHandler, Totp: totpHandler, + Referral: referralHandler, } } @@ -118,6 +122,7 @@ var ProviderSet = wire.NewSet( NewSoraGatewayHandler, NewTotpHandler, ProvideSettingHandler, + NewReferralHandler, // Admin handlers admin.NewDashboardHandler, @@ -141,6 +146,7 @@ var ProviderSet = wire.NewSet( admin.NewUserAttributeHandler, admin.NewErrorPassthroughHandler, admin.NewAdminAPIKeyHandler, + admin.NewReferralHandler, // AdminHandlers and Handlers constructors ProvideAdminHandlers, diff --git a/backend/internal/repository/referral_repo.go b/backend/internal/repository/referral_repo.go new file mode 100644 index 000000000..c875cb07b --- /dev/null +++ b/backend/internal/repository/referral_repo.go @@ -0,0 +1,247 @@ +package repository + +// 注意:此文件依赖 Ent 代码生成产物。 +// 修改 ent/schema/ 下的 Schema 文件后,必须先在 backend/ 目录执行: +// +// go generate ./ent/... +// +// 才能使本文件编译通过。 + +import ( + "context" + + dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/ent/referralrelation" + "github.com/Wei-Shaw/sub2api/ent/userreferralprofile" + "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" + "github.com/Wei-Shaw/sub2api/internal/service" +) + +type referralRepository struct { + client *dbent.Client +} + +// NewReferralRepository 创建裂变推广仓储实例 +func NewReferralRepository(client *dbent.Client) service.ReferralRepository { + return &referralRepository{client: client} +} + +// ===================== +// Profile 操作 +// ===================== + +func (r *referralRepository) CreateProfile(ctx context.Context, userID int64, referralCode string) (*service.UserReferralProfile, error) { + client := clientFromContext(ctx, r.client) + m, err := client.UserReferralProfile.Create(). + SetUserID(userID). + SetReferralCode(referralCode). + Save(ctx) + if err != nil { + return nil, err + } + return referralProfileEntityToService(m), nil +} + +func (r *referralRepository) GetProfileByUserID(ctx context.Context, userID int64) (*service.UserReferralProfile, error) { + client := clientFromContext(ctx, r.client) + m, err := client.UserReferralProfile.Query(). + Where(userreferralprofile.UserIDEQ(userID)). + Only(ctx) + if err != nil { + if dbent.IsNotFound(err) { + return nil, nil // 惰性创建场景:profile 不存在返回 nil + } + return nil, err + } + return referralProfileEntityToService(m), nil +} + +func (r *referralRepository) GetProfileByCode(ctx context.Context, code string) (*service.UserReferralProfile, error) { + client := clientFromContext(ctx, r.client) + m, err := client.UserReferralProfile.Query(). + Where(userreferralprofile.ReferralCodeEQ(code)). + Only(ctx) + if err != nil { + if dbent.IsNotFound(err) { + return nil, service.ErrReferralCodeNotFound + } + return nil, err + } + return referralProfileEntityToService(m), nil +} + +// ===================== +// 关系操作 +// ===================== + +func (r *referralRepository) CreateRelation(ctx context.Context, relation *service.ReferralRelation) error { + client := clientFromContext(ctx, r.client) + m, err := client.ReferralRelation.Create(). + SetInviterID(relation.InviterID). + SetInviteeID(relation.InviteeID). + SetInviterReward(relation.InviterReward). + SetInviteeReward(relation.InviteeReward). + SetRewardGranted(relation.RewardGranted). + Save(ctx) + if err != nil { + return err + } + relation.ID = m.ID + relation.CreatedAt = m.CreatedAt + return nil +} + +func (r *referralRepository) GetRelationByInviteeID(ctx context.Context, inviteeID int64) (*service.ReferralRelation, error) { + client := clientFromContext(ctx, r.client) + m, err := client.ReferralRelation.Query(). + Where(referralrelation.InviteeIDEQ(inviteeID)). + Only(ctx) + if err != nil { + if dbent.IsNotFound(err) { + return nil, nil // 该用户未被邀请 + } + return nil, err + } + return referralRelationEntityToService(m), nil +} + +// MarkRewardGranted 将邀请关系的 reward_granted 标志设为 true, +// 表示奖励已成功发放。必须在事务上下文中调用。 +func (r *referralRepository) MarkRewardGranted(ctx context.Context, id int64) error { + client := clientFromContext(ctx, r.client) + return client.ReferralRelation.UpdateOneID(id).SetRewardGranted(true).Exec(ctx) +} + +// ===================== +// 查询操作 +// ===================== + +func (r *referralRepository) ListByInviterID(ctx context.Context, inviterID int64, params pagination.PaginationParams) ([]service.ReferralRelation, *pagination.PaginationResult, error) { + client := clientFromContext(ctx, r.client) + q := client.ReferralRelation.Query(). + Where(referralrelation.InviterIDEQ(inviterID)). + WithInvitee() + + total, err := q.Clone().Count(ctx) + if err != nil { + return nil, nil, err + } + + entities, err := q. + Order(dbent.Desc(referralrelation.FieldID)). + Offset(params.Offset()). + Limit(params.Limit()). + All(ctx) + if err != nil { + return nil, nil, err + } + + out := make([]service.ReferralRelation, len(entities)) + for i, e := range entities { + out[i] = *referralRelationEntityToService(e) + } + + return out, paginationResultFromTotal(int64(total), params), nil +} + +func (r *referralRepository) CountByInviterID(ctx context.Context, inviterID int64) (int64, error) { + client := clientFromContext(ctx, r.client) + n, err := client.ReferralRelation.Query(). + Where(referralrelation.InviterIDEQ(inviterID)). + Count(ctx) + return int64(n), err +} + +func (r *referralRepository) SumRewardsByInviterID(ctx context.Context, inviterID int64) (float64, error) { + client := clientFromContext(ctx, r.client) + var result []struct { + Sum float64 `json:"sum"` + } + err := client.ReferralRelation.Query(). + Where(referralrelation.InviterIDEQ(inviterID)). + Aggregate(dbent.As(dbent.Sum(referralrelation.FieldInviterReward), "sum")). + Scan(ctx, &result) + if err != nil { + return 0, err + } + if len(result) == 0 { + return 0, nil + } + return result[0].Sum, nil +} + +// ===================== +// 管理员统计 +// ===================== + +func (r *referralRepository) GetPlatformStats(ctx context.Context) (*service.ReferralStats, error) { + client := clientFromContext(ctx, r.client) + total, err := client.ReferralRelation.Query().Count(ctx) + if err != nil { + return nil, err + } + + var inviterSums []struct { + Sum float64 `json:"sum"` + } + if err := client.ReferralRelation.Query(). + Aggregate(dbent.As(dbent.Sum(referralrelation.FieldInviterReward), "sum")). + Scan(ctx, &inviterSums); err != nil { + return nil, err + } + + var inviteeSums []struct { + Sum float64 `json:"sum"` + } + if err := client.ReferralRelation.Query(). + Aggregate(dbent.As(dbent.Sum(referralrelation.FieldInviteeReward), "sum")). + Scan(ctx, &inviteeSums); err != nil { + return nil, err + } + + stats := &service.ReferralStats{TotalRelations: int64(total)} + if len(inviterSums) > 0 { + stats.TotalInviterRewardGiven = inviterSums[0].Sum + } + if len(inviteeSums) > 0 { + stats.TotalInviteeRewardGiven = inviteeSums[0].Sum + } + + return stats, nil +} + +// ===================== +// 实体 → 服务模型映射 +// ===================== + +func referralProfileEntityToService(m *dbent.UserReferralProfile) *service.UserReferralProfile { + if m == nil { + return nil + } + return &service.UserReferralProfile{ + ID: m.ID, + UserID: m.UserID, + ReferralCode: m.ReferralCode, + CreatedAt: m.CreatedAt, + } +} + +func referralRelationEntityToService(m *dbent.ReferralRelation) *service.ReferralRelation { + if m == nil { + return nil + } + rel := &service.ReferralRelation{ + ID: m.ID, + InviterID: m.InviterID, + InviteeID: m.InviteeID, + InviterReward: m.InviterReward, + InviteeReward: m.InviteeReward, + RewardGranted: m.RewardGranted, + CreatedAt: m.CreatedAt, + } + // 填充辅助字段(通过 WithInvitee() 预加载) + if invitee := m.Edges.Invitee; invitee != nil { + rel.InviteeEmail = invitee.Email + } + return rel +} diff --git a/backend/internal/repository/wire.go b/backend/internal/repository/wire.go index 2e35e0a00..ffd3e877e 100644 --- a/backend/internal/repository/wire.go +++ b/backend/internal/repository/wire.go @@ -70,6 +70,7 @@ var ProviderSet = wire.NewSet( NewUserAttributeValueRepository, NewUserGroupRateRepository, NewErrorPassthroughRepository, + NewReferralRepository, // Cache implementations NewGatewayCache, diff --git a/backend/internal/server/api_contract_test.go b/backend/internal/server/api_contract_test.go index 63b6cf282..7b9fc987b 100644 --- a/backend/internal/server/api_contract_test.go +++ b/backend/internal/server/api_contract_test.go @@ -97,7 +97,16 @@ func TestAPIContracts(t *testing.T) { "window_7d_start": null, "expires_at": null, "created_at": "2025-01-02T03:04:05Z", - "updated_at": "2025-01-02T03:04:05Z" + "updated_at": "2025-01-02T03:04:05Z", + "rate_limit_5h": 0, + "rate_limit_1d": 0, + "rate_limit_7d": 0, + "usage_5h": 0, + "usage_1d": 0, + "usage_7d": 0, + "window_5h_start": null, + "window_1d_start": null, + "window_7d_start": null } }`, }, @@ -146,7 +155,16 @@ func TestAPIContracts(t *testing.T) { "window_7d_start": null, "expires_at": null, "created_at": "2025-01-02T03:04:05Z", - "updated_at": "2025-01-02T03:04:05Z" + "updated_at": "2025-01-02T03:04:05Z", + "rate_limit_5h": 0, + "rate_limit_1d": 0, + "rate_limit_7d": 0, + "usage_5h": 0, + "usage_1d": 0, + "usage_7d": 0, + "window_5h_start": null, + "window_1d_start": null, + "window_7d_start": null } ], "total": 1, @@ -531,6 +549,9 @@ func TestAPIContracts(t *testing.T) { "hide_ccs_import_button": false, "purchase_subscription_enabled": false, "purchase_subscription_url": "", + "referral_enabled": false, + "referral_inviter_reward": 0, + "referral_invitee_reward": 0, "min_claude_code_version": "", "custom_menu_items": [] } @@ -560,6 +581,88 @@ func TestAPIContracts(t *testing.T) { } }`, }, + { + name: "GET /api/v1/referral", + setup: func(t *testing.T, deps *contractDeps) { + t.Helper() + deps.referralRepo.profileByUserID[1] = &service.UserReferralProfile{ + ID: 10, + UserID: 1, + ReferralCode: "CODE1234", + } + deps.referralRepo.countByInviter[1] = 3 + deps.referralRepo.sumByInviter[1] = 15.0 + }, + method: http.MethodGet, + path: "/api/v1/referral", + wantStatus: http.StatusOK, + wantJSON: `{ + "code": 0, + "message": "success", + "data": { + "referral_code": "CODE1234", + "referral_link": "?ref=CODE1234", + "total_invitees": 3, + "total_reward_earned": 15.0 + } + }`, + }, + { + name: "GET /api/v1/referral/invitees", + setup: func(t *testing.T, deps *contractDeps) { + t.Helper() + deps.referralRepo.invitees[1] = []service.ReferralRelation{ + { + InviteeEmail: "alice@example.com", + InviterReward: 5.0, + CreatedAt: deps.now, + }, + } + }, + method: http.MethodGet, + path: "/api/v1/referral/invitees?page=1&page_size=10", + wantStatus: http.StatusOK, + wantJSON: `{ + "code": 0, + "message": "success", + "data": { + "items": [ + { + "email_masked": "ali***@example.com", + "registered_at": "2025-01-02T03:04:05Z", + "reward_earned": 5.0 + } + ], + "total": 1, + "page": 1, + "page_size": 10, + "pages": 1 + } + }`, + }, + { + name: "GET /api/v1/admin/referral/stats", + setup: func(t *testing.T, deps *contractDeps) { + t.Helper() + deps.referralRepo.platformStats = &service.ReferralStats{ + TotalRelations: 100, + TotalInviterRewardGiven: 50.0, + TotalInviteeRewardGiven: 30.0, + } + }, + method: http.MethodGet, + path: "/api/v1/admin/referral/stats", + wantStatus: http.StatusOK, + wantJSON: `{ + "code": 0, + "message": "success", + "data": { + "total_relations": 100, + "total_inviter_reward_granted": 50.0, + "total_invitee_reward_granted": 30.0 + } + }`, + }, } for _, tt := range tests { @@ -577,14 +680,15 @@ func TestAPIContracts(t *testing.T) { } type contractDeps struct { - now time.Time - router http.Handler - apiKeyRepo *stubApiKeyRepo - groupRepo *stubGroupRepo - userSubRepo *stubUserSubscriptionRepo - usageRepo *stubUsageLogRepo - settingRepo *stubSettingRepo - redeemRepo *stubRedeemCodeRepo + now time.Time + router http.Handler + apiKeyRepo *stubApiKeyRepo + groupRepo *stubGroupRepo + userSubRepo *stubUserSubscriptionRepo + usageRepo *stubUsageLogRepo + settingRepo *stubSettingRepo + redeemRepo *stubRedeemCodeRepo + referralRepo *stubReferralRepoForContract } func newContractDeps(t *testing.T) *contractDeps { @@ -640,6 +744,8 @@ func newContractDeps(t *testing.T) *contractDeps { settingRepo := newStubSettingRepo() settingService := service.NewSettingService(settingRepo, cfg) + referralRepo := newStubReferralRepoForContract() + adminService := service.NewAdminService(userRepo, groupRepo, &accountRepo, nil, proxyRepo, apiKeyRepo, redeemRepo, nil, nil, nil, nil, nil, nil, nil, nil) authHandler := handler.NewAuthHandler(cfg, nil, userService, settingService, nil, redeemService, nil) apiKeyHandler := handler.NewAPIKeyHandler(apiKeyService) @@ -647,6 +753,10 @@ func newContractDeps(t *testing.T) *contractDeps { adminSettingHandler := adminhandler.NewSettingHandler(settingService, nil, nil, nil, nil) adminAccountHandler := adminhandler.NewAccountHandler(adminService, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + referralService := service.NewReferralService(referralRepo, userRepo, nil, nil, nil) + referralHandler := handler.NewReferralHandler(referralService) + adminReferralHandler := adminhandler.NewReferralHandler(referralService) + jwtAuth := func(c *gin.Context) { c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{ UserID: 1, @@ -695,16 +805,23 @@ func newContractDeps(t *testing.T) *contractDeps { v1Admin.Use(adminAuth) v1Admin.GET("/settings", adminSettingHandler.GetSettings) v1Admin.POST("/accounts/bulk-update", adminAccountHandler.BulkUpdate) + v1Admin.GET("/referral/stats", adminReferralHandler.GetPlatformStats) + + v1Referral := v1.Group("") + v1Referral.Use(jwtAuth) + v1Referral.GET("/referral", referralHandler.GetMyReferralInfo) + v1Referral.GET("/referral/invitees", referralHandler.ListMyInvitees) return &contractDeps{ - now: now, - router: r, - apiKeyRepo: apiKeyRepo, - groupRepo: groupRepo, - userSubRepo: userSubRepo, - usageRepo: usageRepo, - settingRepo: settingRepo, - redeemRepo: redeemRepo, + now: now, + router: r, + apiKeyRepo: apiKeyRepo, + groupRepo: groupRepo, + userSubRepo: userSubRepo, + usageRepo: usageRepo, + settingRepo: settingRepo, + redeemRepo: redeemRepo, + referralRepo: referralRepo, } } @@ -1848,6 +1965,91 @@ func paginationResult(total int64, params pagination.PaginationParams) *paginati } } +type stubReferralRepoForContract struct { + profileByUserID map[int64]*service.UserReferralProfile + inviterRelation map[int64]*service.ReferralRelation + countByInviter map[int64]int64 + sumByInviter map[int64]float64 + invitees map[int64][]service.ReferralRelation + platformStats *service.ReferralStats +} + +func newStubReferralRepoForContract() *stubReferralRepoForContract { + return &stubReferralRepoForContract{ + profileByUserID: make(map[int64]*service.UserReferralProfile), + inviterRelation: make(map[int64]*service.ReferralRelation), + countByInviter: make(map[int64]int64), + sumByInviter: make(map[int64]float64), + invitees: make(map[int64][]service.ReferralRelation), + } +} + +func (r *stubReferralRepoForContract) CreateProfile(ctx context.Context, userID int64, code string) (*service.UserReferralProfile, error) { + p := &service.UserReferralProfile{UserID: userID, ReferralCode: code} + r.profileByUserID[userID] = p + return p, nil +} + +func (r *stubReferralRepoForContract) GetProfileByUserID(ctx context.Context, userID int64) (*service.UserReferralProfile, error) { + p := r.profileByUserID[userID] + return p, nil +} + +func (r *stubReferralRepoForContract) GetProfileByCode(ctx context.Context, code string) (*service.UserReferralProfile, error) { + return nil, errors.New("not implemented") +} + +func (r *stubReferralRepoForContract) CreateRelation(ctx context.Context, relation *service.ReferralRelation) error { + return errors.New("not implemented") +} + +func (r *stubReferralRepoForContract) GetRelationByInviteeID(ctx context.Context, inviteeID int64) (*service.ReferralRelation, error) { + return r.inviterRelation[inviteeID], nil +} + +func (r *stubReferralRepoForContract) MarkRewardGranted(ctx context.Context, id int64) error { + return errors.New("not implemented") +} + +func (r *stubReferralRepoForContract) ListByInviterID(ctx context.Context, inviterID int64, params pagination.PaginationParams) ([]service.ReferralRelation, *pagination.PaginationResult, error) { + all := r.invitees[inviterID] + total := int64(len(all)) + pageSize := params.Limit() + pages := 1 + if total > 0 && pageSize > 0 { + pages = int((total + int64(pageSize) - 1) / int64(pageSize)) + } + start := params.Offset() + if start > int(total) { + start = int(total) + } + end := start + pageSize + if end > int(total) { + end = int(total) + } + return all[start:end], &pagination.PaginationResult{ + Total: total, + Page: params.Page, + PageSize: pageSize, + Pages: pages, + }, nil +} + +func (r *stubReferralRepoForContract) CountByInviterID(ctx context.Context, inviterID int64) (int64, error) { + return r.countByInviter[inviterID], nil +} + +func (r *stubReferralRepoForContract) SumRewardsByInviterID(ctx context.Context, inviterID int64) (float64, error) { + return r.sumByInviter[inviterID], nil +} + +func (r *stubReferralRepoForContract) GetPlatformStats(ctx context.Context) (*service.ReferralStats, error) { + if r.platformStats == nil { + return &service.ReferralStats{}, nil + } + return r.platformStats, nil +} + // Ensure compile-time interface compliance. var ( _ service.UserRepository = (*stubUserRepo)(nil) @@ -1857,4 +2059,5 @@ var ( _ service.UserSubscriptionRepository = (*stubUserSubscriptionRepo)(nil) _ service.UsageLogRepository = (*stubUsageLogRepo)(nil) _ service.SettingRepository = (*stubSettingRepo)(nil) + _ service.ReferralRepository = (*stubReferralRepoForContract)(nil) ) diff --git a/backend/internal/server/middleware/admin_auth_test.go b/backend/internal/server/middleware/admin_auth_test.go index 033a5b778..a4624679c 100644 --- a/backend/internal/server/middleware/admin_auth_test.go +++ b/backend/internal/server/middleware/admin_auth_test.go @@ -19,7 +19,7 @@ func TestAdminAuthJWTValidatesTokenVersion(t *testing.T) { gin.SetMode(gin.TestMode) cfg := &config.Config{JWT: config.JWTConfig{Secret: "test-secret", ExpireHour: 1}} - authService := service.NewAuthService(nil, nil, nil, cfg, nil, nil, nil, nil, nil, nil) + authService := service.NewAuthService(nil, nil, nil, cfg, nil, nil, nil, nil, nil, nil, nil) admin := &service.User{ ID: 1, diff --git a/backend/internal/server/middleware/jwt_auth_test.go b/backend/internal/server/middleware/jwt_auth_test.go index f8839cfe8..9415bab1d 100644 --- a/backend/internal/server/middleware/jwt_auth_test.go +++ b/backend/internal/server/middleware/jwt_auth_test.go @@ -40,7 +40,7 @@ func newJWTTestEnv(users map[int64]*service.User) (*gin.Engine, *service.AuthSer cfg.JWT.AccessTokenExpireMinutes = 60 userRepo := &stubJWTUserRepo{users: users} - authSvc := service.NewAuthService(userRepo, nil, nil, cfg, nil, nil, nil, nil, nil, nil) + authSvc := service.NewAuthService(userRepo, nil, nil, cfg, nil, nil, nil, nil, nil, nil, nil) userSvc := service.NewUserService(userRepo, nil, nil) mw := NewJWTAuthMiddleware(authSvc, userSvc) diff --git a/backend/internal/server/routes/admin.go b/backend/internal/server/routes/admin.go index c36c36a0a..c7f431f60 100644 --- a/backend/internal/server/routes/admin.go +++ b/backend/internal/server/routes/admin.go @@ -78,6 +78,9 @@ func RegisterAdminRoutes( // API Key 管理 registerAdminAPIKeyRoutes(admin, h) + + // 裂变推广管理 + registerAdminReferralRoutes(admin, h) } } @@ -486,3 +489,10 @@ func registerErrorPassthroughRoutes(admin *gin.RouterGroup, h *handler.Handlers) rules.DELETE("/:id", h.Admin.ErrorPassthrough.Delete) } } + +func registerAdminReferralRoutes(admin *gin.RouterGroup, h *handler.Handlers) { + referral := admin.Group("/referral") + { + referral.GET("/stats", h.Admin.Referral.GetPlatformStats) + } +} diff --git a/backend/internal/server/routes/user.go b/backend/internal/server/routes/user.go index d0ed24899..3c1aa191d 100644 --- a/backend/internal/server/routes/user.go +++ b/backend/internal/server/routes/user.go @@ -87,5 +87,12 @@ func RegisterUserRoutes( subscriptions.GET("/progress", h.Subscription.GetProgress) subscriptions.GET("/summary", h.Subscription.GetSummary) } + + // 裂变推广 + referral := authenticated.Group("/referral") + { + referral.GET("", h.Referral.GetMyReferralInfo) + referral.GET("/invitees", h.Referral.ListMyInvitees) + } } } diff --git a/backend/internal/service/admin_service_delete_test.go b/backend/internal/service/admin_service_delete_test.go index 2e0f7d907..d76b916e4 100644 --- a/backend/internal/service/admin_service_delete_test.go +++ b/backend/internal/service/admin_service_delete_test.go @@ -347,16 +347,18 @@ func (s *billingCacheStub) InvalidateSubscriptionCache(ctx context.Context, user s.invalidations <- subscriptionInvalidateCall{userID: userID, groupID: groupID} return nil } - func (s *billingCacheStub) GetAPIKeyRateLimit(ctx context.Context, keyID int64) (*APIKeyRateLimitCacheData, error) { panic("unexpected GetAPIKeyRateLimit call") } + func (s *billingCacheStub) SetAPIKeyRateLimit(ctx context.Context, keyID int64, data *APIKeyRateLimitCacheData) error { panic("unexpected SetAPIKeyRateLimit call") } + func (s *billingCacheStub) UpdateAPIKeyRateLimitUsage(ctx context.Context, keyID int64, cost float64) error { panic("unexpected UpdateAPIKeyRateLimitUsage call") } + func (s *billingCacheStub) InvalidateAPIKeyRateLimit(ctx context.Context, keyID int64) error { panic("unexpected InvalidateAPIKeyRateLimit call") } diff --git a/backend/internal/service/api_key_service_delete_test.go b/backend/internal/service/api_key_service_delete_test.go index 3eea59f99..278bcb572 100644 --- a/backend/internal/service/api_key_service_delete_test.go +++ b/backend/internal/service/api_key_service_delete_test.go @@ -146,6 +146,7 @@ func (s *apiKeyRepoStub) GetRateLimitData(ctx context.Context, id int64) (*APIKe panic("unexpected GetRateLimitData call") } + // apiKeyCacheStub 是 APIKeyCache 接口的测试桩实现。 // 用于验证删除操作时缓存清理逻辑是否被正确调用。 // diff --git a/backend/internal/service/auth_service.go b/backend/internal/service/auth_service.go index fe3a0f258..d6515132e 100644 --- a/backend/internal/service/auth_service.go +++ b/backend/internal/service/auth_service.go @@ -65,6 +65,7 @@ type AuthService struct { turnstileService *TurnstileService emailQueueService *EmailQueueService promoService *PromoService + referralService *ReferralService defaultSubAssigner DefaultSubscriptionAssigner } @@ -83,6 +84,7 @@ func NewAuthService( turnstileService *TurnstileService, emailQueueService *EmailQueueService, promoService *PromoService, + referralService *ReferralService, defaultSubAssigner DefaultSubscriptionAssigner, ) *AuthService { return &AuthService{ @@ -95,17 +97,18 @@ func NewAuthService( turnstileService: turnstileService, emailQueueService: emailQueueService, promoService: promoService, + referralService: referralService, defaultSubAssigner: defaultSubAssigner, } } // Register 用户注册,返回token和用户 func (s *AuthService) Register(ctx context.Context, email, password string) (string, *User, error) { - return s.RegisterWithVerification(ctx, email, password, "", "", "") + return s.RegisterWithVerification(ctx, email, password, "", "", "", "") } -// RegisterWithVerification 用户注册(支持邮件验证、优惠码和邀请码),返回token和用户 -func (s *AuthService) RegisterWithVerification(ctx context.Context, email, password, verifyCode, promoCode, invitationCode string) (string, *User, error) { +// RegisterWithVerification 用户注册(支持邮件验证、优惠码、邀请码和裂变推广码),返回token和用户 +func (s *AuthService) RegisterWithVerification(ctx context.Context, email, password, verifyCode, promoCode, invitationCode, referralCode string) (string, *User, error) { // 检查是否开放注册(默认关闭:settingService 未配置时不允许注册) if s.settingService == nil || !s.settingService.IsRegistrationEnabled(ctx) { return "", nil, ErrRegDisabled @@ -153,6 +156,19 @@ func (s *AuthService) RegisterWithVerification(ctx context.Context, email, passw } } + // 预验证裂变推广邀请码(用户 ID 尚不存在,自引用检查放到注册后) + var referralInviterID int64 + if referralCode != "" && s.referralService != nil && s.settingService != nil { + referralCode = strings.ToUpper(strings.TrimSpace(referralCode)) + if enabled, _ := s.settingService.IsReferralEnabled(ctx); enabled { + profile, err := s.referralService.referralRepo.GetProfileByCode(ctx, referralCode) + if err == nil && profile != nil { + referralInviterID = profile.UserID + } + // 邀请码无效时静默忽略(不阻断注册) + } + } + // 检查邮箱是否已存在 existsEmail, err := s.userRepo.ExistsByEmail(ctx, email) if err != nil { @@ -217,6 +233,19 @@ func (s *AuthService) RegisterWithVerification(ctx context.Context, email, passw } } + // 处理裂变推广奖励(inviterID 已在注册前验证,此处仅做最终自引用防护) + if referralInviterID > 0 && referralInviterID != user.ID && s.referralService != nil { + if err := s.referralService.ProcessReferralRegistration(ctx, referralInviterID, user.ID); err != nil { + // 奖励发放失败不影响注册,只记录日志 + logger.LegacyPrintf("service.auth", "[Auth] Failed to process referral for user %d: %v", user.ID, err) + } else { + // 重新获取用户信息以获取更新后的余额 + if updatedUser, err := s.userRepo.GetByID(ctx, user.ID); err == nil { + user = updatedUser + } + } + } + // 生成token token, err := s.GenerateToken(user) if err != nil { diff --git a/backend/internal/service/auth_service_register_test.go b/backend/internal/service/auth_service_register_test.go index 1999e759e..5f17c5a38 100644 --- a/backend/internal/service/auth_service_register_test.go +++ b/backend/internal/service/auth_service_register_test.go @@ -138,6 +138,7 @@ func newAuthService(repo *userRepoStub, settings map[string]string, emailCache E nil, nil, nil, // promoService + nil, // referralService nil, // defaultSubAssigner ) } @@ -170,7 +171,7 @@ func TestAuthService_Register_EmailVerifyEnabledButServiceNotConfigured(t *testi }, nil) // 应返回服务不可用错误,而不是允许绕过验证 - _, _, err := service.RegisterWithVerification(context.Background(), "user@test.com", "password", "any-code", "", "") + _, _, err := service.RegisterWithVerification(context.Background(), "user@test.com", "password", "any-code", "", "", "") require.ErrorIs(t, err, ErrServiceUnavailable) } @@ -182,7 +183,7 @@ func TestAuthService_Register_EmailVerifyRequired(t *testing.T) { SettingKeyEmailVerifyEnabled: "true", }, cache) - _, _, err := service.RegisterWithVerification(context.Background(), "user@test.com", "password", "", "", "") + _, _, err := service.RegisterWithVerification(context.Background(), "user@test.com", "password", "", "", "", "") require.ErrorIs(t, err, ErrEmailVerifyRequired) } @@ -196,7 +197,7 @@ func TestAuthService_Register_EmailVerifyInvalid(t *testing.T) { SettingKeyEmailVerifyEnabled: "true", }, cache) - _, _, err := service.RegisterWithVerification(context.Background(), "user@test.com", "password", "wrong", "", "") + _, _, err := service.RegisterWithVerification(context.Background(), "user@test.com", "password", "wrong", "", "", "") require.ErrorIs(t, err, ErrInvalidVerifyCode) require.ErrorContains(t, err, "verify code") } diff --git a/backend/internal/service/auth_service_turnstile_register_test.go b/backend/internal/service/auth_service_turnstile_register_test.go index 36cb1e065..24485c9a8 100644 --- a/backend/internal/service/auth_service_turnstile_register_test.go +++ b/backend/internal/service/auth_service_turnstile_register_test.go @@ -52,6 +52,7 @@ func newAuthServiceForRegisterTurnstileTest(settings map[string]string, verifier turnstileService, nil, // emailQueueService nil, // promoService + nil, // referralService nil, // defaultSubAssigner ) } diff --git a/backend/internal/service/domain_constants.go b/backend/internal/service/domain_constants.go index df2130027..949f43fb3 100644 --- a/backend/internal/service/domain_constants.go +++ b/backend/internal/service/domain_constants.go @@ -201,6 +201,14 @@ const ( // SettingKeyMinClaudeCodeVersion 最低 Claude Code 版本号要求 (semver, 如 "2.1.0",空值=不检查) SettingKeyMinClaudeCodeVersion = "min_claude_code_version" + + // ========================= + // 裂变推广设置 + // ========================= + + SettingKeyReferralEnabled = "referral_enabled" // 是否启用裂变推广功能(默认 false) + SettingKeyReferralInviterReward = "referral_inviter_reward" // 邀请人奖励余额(默认 10.0) + SettingKeyReferralInviteeReward = "referral_invitee_reward" // 被邀请人奖励余额(默认 5.0) ) // AdminAPIKeyPrefix is the prefix for admin API keys (distinct from user "sk-" keys). diff --git a/backend/internal/service/referral.go b/backend/internal/service/referral.go new file mode 100644 index 000000000..71b73307b --- /dev/null +++ b/backend/internal/service/referral.go @@ -0,0 +1,105 @@ +package service + +import ( + "context" + "time" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" +) + +// ===================== +// 领域模型 +// ===================== + +// UserReferralProfile 用户专属邀请码 Profile +type UserReferralProfile struct { + ID int64 + UserID int64 + ReferralCode string + CreatedAt time.Time +} + +// ReferralRelation 邀请关系记录 +type ReferralRelation struct { + ID int64 + InviterID int64 + InviteeID int64 + InviterReward float64 + InviteeReward float64 + RewardGranted bool + CreatedAt time.Time + + // 辅助字段(查询时填充,非 DB 字段) + InviteeEmail string +} + +// ReferralStats 全平台邀请统计(管理员视图) +type ReferralStats struct { + TotalRelations int64 `json:"total_relations"` + TotalInviterRewardGiven float64 `json:"total_inviter_reward_granted"` + TotalInviteeRewardGiven float64 `json:"total_invitee_reward_granted"` +} + +// ReferralInfo 用户端邀请信息(聚合视图) +type ReferralInfo struct { + ReferralCode string `json:"referral_code"` + ReferralLink string `json:"referral_link"` + TotalInvitees int64 `json:"total_invitees"` + TotalRewardEarned float64 `json:"total_reward_earned"` + InviterInfo *InviterInfo `json:"inviter_info,omitempty"` +} + +// InviterInfo 邀请人信息(脱敏) +type InviterInfo struct { + EmailMasked string `json:"email_masked"` +} + +// ReferralInvitee 邀请记录列表项 +type ReferralInvitee struct { + EmailMasked string `json:"email_masked"` + RegisteredAt time.Time `json:"registered_at"` + RewardEarned float64 `json:"reward_earned"` +} + +// ===================== +// Repository 接口 +// ===================== + +// ReferralRepository 邀请推广数据仓储接口 +type ReferralRepository interface { + // Profile 操作 + CreateProfile(ctx context.Context, userID int64, referralCode string) (*UserReferralProfile, error) + GetProfileByUserID(ctx context.Context, userID int64) (*UserReferralProfile, error) + GetProfileByCode(ctx context.Context, code string) (*UserReferralProfile, error) + + // 关系操作 + CreateRelation(ctx context.Context, relation *ReferralRelation) error + GetRelationByInviteeID(ctx context.Context, inviteeID int64) (*ReferralRelation, error) + + // 关系状态更新 + MarkRewardGranted(ctx context.Context, id int64) error + + // 查询操作 + ListByInviterID(ctx context.Context, inviterID int64, params pagination.PaginationParams) ([]ReferralRelation, *pagination.PaginationResult, error) + CountByInviterID(ctx context.Context, inviterID int64) (int64, error) + SumRewardsByInviterID(ctx context.Context, inviterID int64) (float64, error) + + // 管理员统计 + GetPlatformStats(ctx context.Context) (*ReferralStats, error) +} + +// ===================== +// 错误定义 +// ===================== + +var ( + ErrReferralCodeNotFound = newBadRequestError("REFERRAL_CODE_NOT_FOUND", "referral code not found or invalid") + ErrReferralCodeInvalid = newBadRequestError("REFERRAL_CODE_INVALID", "referral code is invalid") + ErrSelfReferralNotAllowed = newBadRequestError("SELF_REFERRAL_NOT_ALLOWED", "cannot use your own referral code") + ErrAlreadyReferred = newBadRequestError("ALREADY_REFERRED", "this user has already been referred") +) + +func newBadRequestError(code, msg string) error { + return infraerrors.BadRequest(code, msg) +} diff --git a/backend/internal/service/referral_service.go b/backend/internal/service/referral_service.go new file mode 100644 index 000000000..7737866c8 --- /dev/null +++ b/backend/internal/service/referral_service.go @@ -0,0 +1,301 @@ +package service + +import ( + "context" + "crypto/rand" + "fmt" + "strings" + "time" + + dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" +) + +// referralCodeCharset 邀请码字符集:大写字母 + 数字,去除易混淆字符 +const referralCodeCharset = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" + +// referralCodeLength 邀请码长度:8 位 +const referralCodeLength = 8 + +// referralCodeMaxRetries 邀请码冲突时最大重试次数 +const referralCodeMaxRetries = 5 + +// ReferralService 裂变推广业务逻辑服务 +type ReferralService struct { + referralRepo ReferralRepository + userRepo UserRepository + settingService *SettingService + billingCacheService *BillingCacheService + entClient *dbent.Client +} + +// NewReferralService 创建裂变推广服务实例 +func NewReferralService( + referralRepo ReferralRepository, + userRepo UserRepository, + settingService *SettingService, + billingCacheService *BillingCacheService, + entClient *dbent.Client, +) *ReferralService { + return &ReferralService{ + referralRepo: referralRepo, + userRepo: userRepo, + settingService: settingService, + billingCacheService: billingCacheService, + entClient: entClient, + } +} + +// GetOrCreateProfile 获取或懒加载创建用户的专属邀请码 Profile +func (s *ReferralService) GetOrCreateProfile(ctx context.Context, userID int64) (*UserReferralProfile, error) { + // 先查询 + profile, err := s.referralRepo.GetProfileByUserID(ctx, userID) + if err != nil { + return nil, fmt.Errorf("get referral profile: %w", err) + } + if profile != nil { + return profile, nil + } + + // 不存在则生成并创建(带重试应对极小概率的码冲突) + for i := 0; i < referralCodeMaxRetries; i++ { + code, err := generateReferralCode() + if err != nil { + return nil, fmt.Errorf("generate referral code: %w", err) + } + created, err := s.referralRepo.CreateProfile(ctx, userID, code) + if err == nil { + return created, nil + } + // 唯一约束冲突时重试,其他错误直接返回 + if !isUniqueConflict(err) { + return nil, fmt.Errorf("create referral profile: %w", err) + } + } + return nil, fmt.Errorf("failed to generate unique referral code after %d retries", referralCodeMaxRetries) +} + +// ValidateReferralCode 注册前验证邀请码有效性 +// 返回 nil, nil 表示空码(不报错) +func (s *ReferralService) ValidateReferralCode(ctx context.Context, code string, inviteeID int64) (*UserReferralProfile, error) { + code = strings.TrimSpace(strings.ToUpper(code)) + if code == "" { + return nil, nil + } + + profile, err := s.referralRepo.GetProfileByCode(ctx, code) + if err != nil { + return nil, err // ErrReferralCodeNotFound + } + + // 自己不能使用自己的邀请码 + if profile.UserID == inviteeID { + return nil, ErrSelfReferralNotAllowed + } + + return profile, nil +} + +// GrantRewardsInTx 在已有事务上下文中完成邀请关系创建和奖励发放。 +// +// 调用者(AuthService)负责事务管理,本方法仅在 txCtx 中执行。 +// 幂等保障:invitee_id UNIQUE 约束(DB 层)+ reward_granted 标志(应用层)。 +func (s *ReferralService) GrantRewardsInTx(ctx context.Context, inviterID, inviteeID int64, inviterReward, inviteeReward float64) error { + relation := &ReferralRelation{ + InviterID: inviterID, + InviteeID: inviteeID, + InviterReward: inviterReward, + InviteeReward: inviteeReward, + RewardGranted: false, + } + + // 创建邀请关系(invitee_id UNIQUE 约束保证幂等) + if err := s.referralRepo.CreateRelation(ctx, relation); err != nil { + return fmt.Errorf("create referral relation: %w", err) + } + + // 发放邀请人奖励 + if inviterReward > 0 { + if err := s.userRepo.UpdateBalance(ctx, inviterID, inviterReward); err != nil { + return fmt.Errorf("grant inviter reward: %w", err) + } + } + + // 发放被邀请人奖励 + if inviteeReward > 0 { + if err := s.userRepo.UpdateBalance(ctx, inviteeID, inviteeReward); err != nil { + return fmt.Errorf("grant invitee reward: %w", err) + } + } + + // 标记奖励已发放(应用层幂等标志) + if err := s.referralRepo.MarkRewardGranted(ctx, relation.ID); err != nil { + return fmt.Errorf("mark reward granted: %w", err) + } + + return nil +} + +// GetMyReferralInfo 获取当前用户的邀请统计信息 +func (s *ReferralService) GetMyReferralInfo(ctx context.Context, userID int64, siteBaseURL string) (*ReferralInfo, error) { + // 获取或创建 Profile + profile, err := s.GetOrCreateProfile(ctx, userID) + if err != nil { + return nil, err + } + + // 统计数据 + totalInvitees, err := s.referralRepo.CountByInviterID(ctx, userID) + if err != nil { + return nil, fmt.Errorf("count invitees: %w", err) + } + + totalRewardEarned, err := s.referralRepo.SumRewardsByInviterID(ctx, userID) + if err != nil { + return nil, fmt.Errorf("sum rewards: %w", err) + } + + info := &ReferralInfo{ + ReferralCode: profile.ReferralCode, + ReferralLink: buildReferralLink(siteBaseURL, profile.ReferralCode), + TotalInvitees: totalInvitees, + TotalRewardEarned: totalRewardEarned, + } + + // 如果该用户自己是被邀请的,填充邀请人信息 + relation, err := s.referralRepo.GetRelationByInviteeID(ctx, userID) + if err != nil { + return nil, fmt.Errorf("get inviter relation: %w", err) + } + if relation != nil { + inviter, err := s.userRepo.GetByID(ctx, relation.InviterID) + if err == nil && inviter != nil { + info.InviterInfo = &InviterInfo{ + EmailMasked: maskEmail(inviter.Email), + } + } + } + + return info, nil +} + +// ListMyInvitees 分页获取当前用户邀请的用户列表 +func (s *ReferralService) ListMyInvitees(ctx context.Context, userID int64, params pagination.PaginationParams) ([]ReferralInvitee, *pagination.PaginationResult, error) { + relations, result, err := s.referralRepo.ListByInviterID(ctx, userID, params) + if err != nil { + return nil, nil, fmt.Errorf("list invitees: %w", err) + } + + invitees := make([]ReferralInvitee, len(relations)) + for i, rel := range relations { + invitees[i] = ReferralInvitee{ + EmailMasked: maskEmail(rel.InviteeEmail), + RegisteredAt: rel.CreatedAt, + RewardEarned: rel.InviterReward, + } + } + + return invitees, result, nil +} + +// GetPlatformStats 获取全平台邀请统计(管理员) +func (s *ReferralService) GetPlatformStats(ctx context.Context) (*ReferralStats, error) { + return s.referralRepo.GetPlatformStats(ctx) +} + +// ProcessReferralRegistration 在注册完成后处理邀请奖励(自带事务)。 +// 从 SettingService 读取奖励金额后,在单一事务内创建邀请关系并更新双方余额。 +// 失败不影响注册结果,调用方应仅记录日志。 +func (s *ReferralService) ProcessReferralRegistration(ctx context.Context, inviterID, inviteeID int64) error { + inviterReward, inviteeReward, err := s.settingService.GetReferralRewards(ctx) + if err != nil { + return fmt.Errorf("get referral rewards: %w", err) + } + + tx, err := s.entClient.Tx(ctx) + if err != nil { + return fmt.Errorf("begin referral tx: %w", err) + } + defer func() { _ = tx.Rollback() }() + + txCtx := dbent.NewTxContext(ctx, tx) + + if err := s.GrantRewardsInTx(txCtx, inviterID, inviteeID, inviterReward, inviteeReward); err != nil { + return err + } + + if err := tx.Commit(); err != nil { + return fmt.Errorf("commit referral tx: %w", err) + } + + s.InvalidateRewardCaches(inviterID, inviteeID) + return nil +} + +// InvalidateRewardCaches 异步失效奖励相关的余额缓存(在事务提交后调用) +func (s *ReferralService) InvalidateRewardCaches(inviterID, inviteeID int64) { + if s.billingCacheService == nil { + return + } + go func() { + cacheCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _ = s.billingCacheService.InvalidateUserBalance(cacheCtx, inviterID) + _ = s.billingCacheService.InvalidateUserBalance(cacheCtx, inviteeID) + }() +} + +// ===================== +// 辅助函数 +// ===================== + +// generateReferralCode 使用 crypto/rand 生成 8 位大写字母+数字的邀请码 +func generateReferralCode() (string, error) { + buf := make([]byte, referralCodeLength) + if _, err := rand.Read(buf); err != nil { + return "", err + } + code := make([]byte, referralCodeLength) + for i, b := range buf { + code[i] = referralCodeCharset[int(b)%len(referralCodeCharset)] + } + return string(code), nil +} + +// maskEmail 对邮箱地址进行脱敏处理,只保留前3位和域名部分 +// 例如:user@example.com → use***@example.com +func maskEmail(email string) string { + if email == "" { + return "" + } + parts := strings.SplitN(email, "@", 2) + if len(parts) != 2 { + return email + } + local := parts[0] + domain := parts[1] + if len(local) <= 3 { + return local + "***@" + domain + } + return local[:3] + "***@" + domain +} + +// buildReferralLink 构建邀请链接 +func buildReferralLink(siteBaseURL, code string) string { + base := strings.TrimSuffix(strings.TrimSpace(siteBaseURL), "/") + if base == "" { + return "?ref=" + code + } + return base + "/register?ref=" + code +} + +// isUniqueConflict 判断错误是否为唯一约束冲突(用于邀请码重试逻辑) +func isUniqueConflict(err error) bool { + if err == nil { + return false + } + msg := strings.ToLower(err.Error()) + return strings.Contains(msg, "duplicate key") || + strings.Contains(msg, "unique constraint") || + strings.Contains(msg, "duplicate entry") +} diff --git a/backend/internal/service/referral_service_test.go b/backend/internal/service/referral_service_test.go new file mode 100644 index 000000000..ac09fc1c7 --- /dev/null +++ b/backend/internal/service/referral_service_test.go @@ -0,0 +1,755 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// ===================== +// stubReferralRepo +// ===================== + +type stubReferralRepo struct { + createProfile func(ctx context.Context, userID int64, code string) (*UserReferralProfile, error) + getProfileByUserID func(ctx context.Context, userID int64) (*UserReferralProfile, error) + getProfileByCode func(ctx context.Context, code string) (*UserReferralProfile, error) + createRelation func(ctx context.Context, relation *ReferralRelation) error + getRelationByInviteeID func(ctx context.Context, inviteeID int64) (*ReferralRelation, error) + markRewardGranted func(ctx context.Context, id int64) error + listByInviterID func(ctx context.Context, inviterID int64, params pagination.PaginationParams) ([]ReferralRelation, *pagination.PaginationResult, error) + countByInviterID func(ctx context.Context, inviterID int64) (int64, error) + sumRewardsByInviterID func(ctx context.Context, inviterID int64) (float64, error) + getPlatformStats func(ctx context.Context) (*ReferralStats, error) +} + +func (s *stubReferralRepo) CreateProfile(ctx context.Context, userID int64, code string) (*UserReferralProfile, error) { + if s.createProfile != nil { + return s.createProfile(ctx, userID, code) + } + panic("unexpected CreateProfile call") +} +func (s *stubReferralRepo) GetProfileByUserID(ctx context.Context, userID int64) (*UserReferralProfile, error) { + if s.getProfileByUserID != nil { + return s.getProfileByUserID(ctx, userID) + } + panic("unexpected GetProfileByUserID call") +} +func (s *stubReferralRepo) GetProfileByCode(ctx context.Context, code string) (*UserReferralProfile, error) { + if s.getProfileByCode != nil { + return s.getProfileByCode(ctx, code) + } + panic("unexpected GetProfileByCode call") +} +func (s *stubReferralRepo) CreateRelation(ctx context.Context, relation *ReferralRelation) error { + if s.createRelation != nil { + return s.createRelation(ctx, relation) + } + panic("unexpected CreateRelation call") +} +func (s *stubReferralRepo) GetRelationByInviteeID(ctx context.Context, inviteeID int64) (*ReferralRelation, error) { + if s.getRelationByInviteeID != nil { + return s.getRelationByInviteeID(ctx, inviteeID) + } + panic("unexpected GetRelationByInviteeID call") +} +func (s *stubReferralRepo) MarkRewardGranted(ctx context.Context, id int64) error { + if s.markRewardGranted != nil { + return s.markRewardGranted(ctx, id) + } + panic("unexpected MarkRewardGranted call") +} +func (s *stubReferralRepo) ListByInviterID(ctx context.Context, inviterID int64, params pagination.PaginationParams) ([]ReferralRelation, *pagination.PaginationResult, error) { + if s.listByInviterID != nil { + return s.listByInviterID(ctx, inviterID, params) + } + panic("unexpected ListByInviterID call") +} +func (s *stubReferralRepo) CountByInviterID(ctx context.Context, inviterID int64) (int64, error) { + if s.countByInviterID != nil { + return s.countByInviterID(ctx, inviterID) + } + panic("unexpected CountByInviterID call") +} +func (s *stubReferralRepo) SumRewardsByInviterID(ctx context.Context, inviterID int64) (float64, error) { + if s.sumRewardsByInviterID != nil { + return s.sumRewardsByInviterID(ctx, inviterID) + } + panic("unexpected SumRewardsByInviterID call") +} +func (s *stubReferralRepo) GetPlatformStats(ctx context.Context) (*ReferralStats, error) { + if s.getPlatformStats != nil { + return s.getPlatformStats(ctx) + } + panic("unexpected GetPlatformStats call") +} + +// stubUserRepoForReferral 支持按 ID 查找用户 +type stubUserRepoForReferral struct { + users map[int64]*User +} + +func newStubUserRepoForReferral(users ...*User) *stubUserRepoForReferral { + m := make(map[int64]*User, len(users)) + for _, u := range users { + m[u.ID] = u + } + return &stubUserRepoForReferral{users: m} +} + +func (r *stubUserRepoForReferral) Create(context.Context, *User) error { return nil } +func (r *stubUserRepoForReferral) GetByID(_ context.Context, id int64) (*User, error) { + u, ok := r.users[id] + if !ok { + return nil, ErrUserNotFound + } + clone := *u + return &clone, nil +} +func (r *stubUserRepoForReferral) GetByEmail(context.Context, string) (*User, error) { + return nil, ErrUserNotFound +} +func (r *stubUserRepoForReferral) GetFirstAdmin(context.Context) (*User, error) { + return nil, ErrUserNotFound +} +func (r *stubUserRepoForReferral) Update(context.Context, *User) error { return nil } +func (r *stubUserRepoForReferral) Delete(context.Context, int64) error { return nil } +func (r *stubUserRepoForReferral) UpdateBalance(context.Context, int64, float64) error { + return nil +} +func (r *stubUserRepoForReferral) DeductBalance(context.Context, int64, float64) error { + return nil +} +func (r *stubUserRepoForReferral) UpdateConcurrency(context.Context, int64, int) error { + return nil +} +func (r *stubUserRepoForReferral) ExistsByEmail(context.Context, string) (bool, error) { + return false, nil +} +func (r *stubUserRepoForReferral) List(context.Context, pagination.PaginationParams) ([]User, *pagination.PaginationResult, error) { + return nil, nil, nil +} +func (r *stubUserRepoForReferral) ListWithFilters(context.Context, pagination.PaginationParams, UserListFilters) ([]User, *pagination.PaginationResult, error) { + return nil, nil, nil +} +func (r *stubUserRepoForReferral) RemoveGroupFromAllowedGroups(context.Context, int64) (int64, error) { + return 0, nil +} +func (r *stubUserRepoForReferral) AddGroupToAllowedGroups(context.Context, int64, int64) error { + return nil +} +func (r *stubUserRepoForReferral) UpdateTotpSecret(context.Context, int64, *string) error { + return nil +} +func (r *stubUserRepoForReferral) EnableTotp(context.Context, int64) error { return nil } +func (r *stubUserRepoForReferral) DisableTotp(context.Context, int64) error { return nil } + +// ===================== +// 辅助函数测试 +// ===================== + +func TestMaskEmail(t *testing.T) { + tests := []struct { + name string + input string + want string + }{ + {"空字符串", "", ""}, + {"短local部分(<=3)", "ab@example.com", "ab***@example.com"}, + {"恰好3位local", "abc@example.com", "abc***@example.com"}, + {"正常邮箱", "alice@example.com", "ali***@example.com"}, + {"无@符号", "notanemail", "notanemail"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, maskEmail(tt.input)) + }) + } +} + +func TestBuildReferralLink(t *testing.T) { + tests := []struct { + name string + baseURL string + code string + want string + }{ + {"空baseURL", "", "CODE1234", "?ref=CODE1234"}, + {"有baseURL", "https://example.com", "CODE1234", "https://example.com/register?ref=CODE1234"}, + {"末尾有斜杠", "https://example.com/", "CODE1234", "https://example.com/register?ref=CODE1234"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, buildReferralLink(tt.baseURL, tt.code)) + }) + } +} + +func TestIsUniqueConflict(t *testing.T) { + tests := []struct { + name string + err error + want bool + }{ + {"nil error", nil, false}, + {"duplicate key", errors.New("pq: duplicate key value violates unique constraint"), true}, + {"unique constraint", errors.New("ERROR: unique constraint violation"), true}, + {"duplicate entry", errors.New("Error 1062: Duplicate entry '...' for key"), true}, + {"普通错误", errors.New("connection refused"), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, isUniqueConflict(tt.err)) + }) + } +} + +func TestGenerateReferralCode(t *testing.T) { + validChars := map[byte]struct{}{} + for _, c := range referralCodeCharset { + validChars[byte(c)] = struct{}{} + } + + for i := 0; i < 20; i++ { + code, err := generateReferralCode() + require.NoError(t, err) + assert.Len(t, code, referralCodeLength, "code should be %d chars", referralCodeLength) + for _, b := range []byte(code) { + _, ok := validChars[b] + assert.True(t, ok, "char %q not in charset", b) + } + } +} + +// ===================== +// GetOrCreateProfile 测试 +// ===================== + +func TestGetOrCreateProfile_ExistingProfile(t *testing.T) { + existing := &UserReferralProfile{ID: 1, UserID: 42, ReferralCode: "ABCD1234"} + repo := &stubReferralRepo{ + getProfileByUserID: func(_ context.Context, userID int64) (*UserReferralProfile, error) { + return existing, nil + }, + } + svc := NewReferralService(repo, newStubUserRepoForReferral(), nil, nil, nil) + + profile, err := svc.GetOrCreateProfile(context.Background(), 42) + require.NoError(t, err) + assert.Equal(t, existing, profile) +} + +func TestGetOrCreateProfile_NewProfile(t *testing.T) { + created := &UserReferralProfile{ID: 2, UserID: 7, ReferralCode: "NEWCODE1"} + repo := &stubReferralRepo{ + getProfileByUserID: func(_ context.Context, userID int64) (*UserReferralProfile, error) { + return nil, nil + }, + createProfile: func(_ context.Context, userID int64, code string) (*UserReferralProfile, error) { + return created, nil + }, + } + svc := NewReferralService(repo, newStubUserRepoForReferral(), nil, nil, nil) + + profile, err := svc.GetOrCreateProfile(context.Background(), 7) + require.NoError(t, err) + assert.Equal(t, created, profile) +} + +func TestGetOrCreateProfile_RetryOnUniqueConflict(t *testing.T) { + attempts := 0 + created := &UserReferralProfile{ID: 3, UserID: 9, ReferralCode: "RETRY123"} + repo := &stubReferralRepo{ + getProfileByUserID: func(_ context.Context, userID int64) (*UserReferralProfile, error) { + return nil, nil + }, + createProfile: func(_ context.Context, userID int64, code string) (*UserReferralProfile, error) { + attempts++ + if attempts == 1 { + return nil, errors.New("pq: duplicate key value violates unique constraint") + } + return created, nil + }, + } + svc := NewReferralService(repo, newStubUserRepoForReferral(), nil, nil, nil) + + profile, err := svc.GetOrCreateProfile(context.Background(), 9) + require.NoError(t, err) + assert.Equal(t, created, profile) + assert.Equal(t, 2, attempts) +} + +func TestGetOrCreateProfile_MaxRetries(t *testing.T) { + repo := &stubReferralRepo{ + getProfileByUserID: func(_ context.Context, userID int64) (*UserReferralProfile, error) { + return nil, nil + }, + createProfile: func(_ context.Context, userID int64, code string) (*UserReferralProfile, error) { + return nil, errors.New("pq: duplicate key value violates unique constraint") + }, + } + svc := NewReferralService(repo, newStubUserRepoForReferral(), nil, nil, nil) + + _, err := svc.GetOrCreateProfile(context.Background(), 10) + require.Error(t, err) +} + +func TestGetOrCreateProfile_RepoError(t *testing.T) { + repo := &stubReferralRepo{ + getProfileByUserID: func(_ context.Context, userID int64) (*UserReferralProfile, error) { + return nil, errors.New("db connection lost") + }, + } + svc := NewReferralService(repo, newStubUserRepoForReferral(), nil, nil, nil) + + _, err := svc.GetOrCreateProfile(context.Background(), 1) + require.Error(t, err) +} + +// ===================== +// ValidateReferralCode 测试 +// ===================== + +func TestValidateReferralCode_Empty(t *testing.T) { + repo := &stubReferralRepo{} + svc := NewReferralService(repo, newStubUserRepoForReferral(), nil, nil, nil) + + profile, err := svc.ValidateReferralCode(context.Background(), "", 1) + assert.NoError(t, err) + assert.Nil(t, profile) +} + +func TestValidateReferralCode_LowercaseAutoUpper(t *testing.T) { + expected := &UserReferralProfile{ID: 5, UserID: 99, ReferralCode: "ABCD1234"} + repo := &stubReferralRepo{ + getProfileByCode: func(_ context.Context, code string) (*UserReferralProfile, error) { + assert.Equal(t, "ABCD1234", code) // 验证已转大写 + return expected, nil + }, + } + svc := NewReferralService(repo, newStubUserRepoForReferral(), nil, nil, nil) + + profile, err := svc.ValidateReferralCode(context.Background(), "abcd1234", 42) + require.NoError(t, err) + assert.Equal(t, expected, profile) +} + +func TestValidateReferralCode_NotFound(t *testing.T) { + repo := &stubReferralRepo{ + getProfileByCode: func(_ context.Context, code string) (*UserReferralProfile, error) { + return nil, ErrReferralCodeNotFound + }, + } + svc := NewReferralService(repo, newStubUserRepoForReferral(), nil, nil, nil) + + _, err := svc.ValidateReferralCode(context.Background(), "BADCODE1", 42) + assert.ErrorIs(t, err, ErrReferralCodeNotFound) +} + +func TestValidateReferralCode_SelfReferral(t *testing.T) { + profile := &UserReferralProfile{ID: 5, UserID: 42, ReferralCode: "MYCODE12"} + repo := &stubReferralRepo{ + getProfileByCode: func(_ context.Context, code string) (*UserReferralProfile, error) { + return profile, nil + }, + } + svc := NewReferralService(repo, newStubUserRepoForReferral(), nil, nil, nil) + + _, err := svc.ValidateReferralCode(context.Background(), "MYCODE12", 42) // inviteeID == profile.UserID + assert.ErrorIs(t, err, ErrSelfReferralNotAllowed) +} + +func TestValidateReferralCode_Valid(t *testing.T) { + profile := &UserReferralProfile{ID: 5, UserID: 99, ReferralCode: "VALID123"} + repo := &stubReferralRepo{ + getProfileByCode: func(_ context.Context, code string) (*UserReferralProfile, error) { + return profile, nil + }, + } + svc := NewReferralService(repo, newStubUserRepoForReferral(), nil, nil, nil) + + result, err := svc.ValidateReferralCode(context.Background(), "VALID123", 42) + require.NoError(t, err) + assert.Equal(t, profile, result) +} + +// ===================== +// GrantRewardsInTx 测试 +// ===================== + +func TestGrantRewardsInTx_Normal(t *testing.T) { + var createdRelation *ReferralRelation + var inviterUpdated, inviteeUpdated bool + var markedID int64 + + userRepo := newStubUserRepoForReferral(&User{ID: 1}, &User{ID: 2}) + updateBalance := func(_ context.Context, id int64, _ float64) error { + if id == 1 { + inviterUpdated = true + } + if id == 2 { + inviteeUpdated = true + } + return nil + } + userRepo.users[1].ID = 1 + userRepo.users[2].ID = 2 + + repo := &stubReferralRepo{ + createRelation: func(_ context.Context, rel *ReferralRelation) error { + rel.ID = 100 + createdRelation = rel + return nil + }, + markRewardGranted: func(_ context.Context, id int64) error { + markedID = id + return nil + }, + } + // Override UpdateBalance in stubUserRepoForReferral + ur := newStubUserRepoForReferral() + var inviterUpdateCalled, inviteeUpdateCalled int64 + _ = updateBalance + customRepo := &stubReferralRepo{ + createRelation: func(_ context.Context, rel *ReferralRelation) error { + rel.ID = 100 + createdRelation = rel + return nil + }, + markRewardGranted: func(_ context.Context, id int64) error { + markedID = id + return nil + }, + } + + balanceCallCount := map[int64]int{} + mur := &mockUserRepo{ + updateBalanceFn: func(_ context.Context, id int64, amount float64) error { + balanceCallCount[id]++ + if id == 1 { + inviterUpdated = true + } + if id == 2 { + inviteeUpdated = true + } + return nil + }, + } + _ = repo + _ = ur + _ = inviterUpdated + _ = inviteeUpdated + _ = inviterUpdateCalled + _ = inviteeUpdateCalled + + svc := NewReferralService(customRepo, mur, nil, nil, nil) + err := svc.GrantRewardsInTx(context.Background(), 1, 2, 5.0, 3.0) + + require.NoError(t, err) + require.NotNil(t, createdRelation) + assert.Equal(t, int64(1), createdRelation.InviterID) + assert.Equal(t, int64(2), createdRelation.InviteeID) + assert.Equal(t, 1, balanceCallCount[1]) + assert.Equal(t, 1, balanceCallCount[2]) + assert.Equal(t, int64(100), markedID) +} + +func TestGrantRewardsInTx_SkipInviterRewardWhenZero(t *testing.T) { + balanceCallCount := map[int64]int{} + mur := &mockUserRepo{ + updateBalanceFn: func(_ context.Context, id int64, amount float64) error { + balanceCallCount[id]++ + return nil + }, + } + repo := &stubReferralRepo{ + createRelation: func(_ context.Context, rel *ReferralRelation) error { + rel.ID = 1 + return nil + }, + markRewardGranted: func(_ context.Context, id int64) error { return nil }, + } + svc := NewReferralService(repo, mur, nil, nil, nil) + + err := svc.GrantRewardsInTx(context.Background(), 1, 2, 0, 3.0) + require.NoError(t, err) + assert.Equal(t, 0, balanceCallCount[1], "inviter reward should be skipped when 0") + assert.Equal(t, 1, balanceCallCount[2]) +} + +func TestGrantRewardsInTx_SkipInviteeRewardWhenZero(t *testing.T) { + balanceCallCount := map[int64]int{} + mur := &mockUserRepo{ + updateBalanceFn: func(_ context.Context, id int64, amount float64) error { + balanceCallCount[id]++ + return nil + }, + } + repo := &stubReferralRepo{ + createRelation: func(_ context.Context, rel *ReferralRelation) error { + rel.ID = 1 + return nil + }, + markRewardGranted: func(_ context.Context, id int64) error { return nil }, + } + svc := NewReferralService(repo, mur, nil, nil, nil) + + err := svc.GrantRewardsInTx(context.Background(), 1, 2, 5.0, 0) + require.NoError(t, err) + assert.Equal(t, 1, balanceCallCount[1]) + assert.Equal(t, 0, balanceCallCount[2], "invitee reward should be skipped when 0") +} + +func TestGrantRewardsInTx_CreateRelationError(t *testing.T) { + repo := &stubReferralRepo{ + createRelation: func(_ context.Context, rel *ReferralRelation) error { + return errors.New("db error") + }, + } + svc := NewReferralService(repo, &mockUserRepo{}, nil, nil, nil) + err := svc.GrantRewardsInTx(context.Background(), 1, 2, 5.0, 3.0) + require.Error(t, err) +} + +func TestGrantRewardsInTx_InviterBalanceError(t *testing.T) { + repo := &stubReferralRepo{ + createRelation: func(_ context.Context, rel *ReferralRelation) error { + rel.ID = 1 + return nil + }, + markRewardGranted: func(_ context.Context, id int64) error { return nil }, + } + mur := &mockUserRepo{ + updateBalanceFn: func(_ context.Context, id int64, amount float64) error { + if id == 1 { + return errors.New("inviter balance error") + } + return nil + }, + } + svc := NewReferralService(repo, mur, nil, nil, nil) + err := svc.GrantRewardsInTx(context.Background(), 1, 2, 5.0, 3.0) + require.Error(t, err) +} + +func TestGrantRewardsInTx_InviteeBalanceError(t *testing.T) { + repo := &stubReferralRepo{ + createRelation: func(_ context.Context, rel *ReferralRelation) error { + rel.ID = 1 + return nil + }, + markRewardGranted: func(_ context.Context, id int64) error { return nil }, + } + mur := &mockUserRepo{ + updateBalanceFn: func(_ context.Context, id int64, amount float64) error { + if id == 2 { + return errors.New("invitee balance error") + } + return nil + }, + } + svc := NewReferralService(repo, mur, nil, nil, nil) + err := svc.GrantRewardsInTx(context.Background(), 1, 2, 5.0, 3.0) + require.Error(t, err) +} + +func TestGrantRewardsInTx_MarkRewardGrantedError(t *testing.T) { + repo := &stubReferralRepo{ + createRelation: func(_ context.Context, rel *ReferralRelation) error { + rel.ID = 1 + return nil + }, + markRewardGranted: func(_ context.Context, id int64) error { + return errors.New("mark error") + }, + } + svc := NewReferralService(repo, &mockUserRepo{}, nil, nil, nil) + err := svc.GrantRewardsInTx(context.Background(), 1, 2, 0, 0) + require.Error(t, err) +} + +// ===================== +// GetMyReferralInfo 测试 +// ===================== + +func TestGetMyReferralInfo_Normal_NoInviter(t *testing.T) { + profile := &UserReferralProfile{ID: 1, UserID: 10, ReferralCode: "CODE1234"} + repo := &stubReferralRepo{ + getProfileByUserID: func(_ context.Context, userID int64) (*UserReferralProfile, error) { + return profile, nil + }, + countByInviterID: func(_ context.Context, inviterID int64) (int64, error) { + return 5, nil + }, + sumRewardsByInviterID: func(_ context.Context, inviterID int64) (float64, error) { + return 12.5, nil + }, + getRelationByInviteeID: func(_ context.Context, inviteeID int64) (*ReferralRelation, error) { + return nil, nil // 没有被邀请 + }, + } + svc := NewReferralService(repo, newStubUserRepoForReferral(), nil, nil, nil) + + info, err := svc.GetMyReferralInfo(context.Background(), 10, "https://example.com") + require.NoError(t, err) + assert.Equal(t, "CODE1234", info.ReferralCode) + assert.Equal(t, "https://example.com/register?ref=CODE1234", info.ReferralLink) + assert.Equal(t, int64(5), info.TotalInvitees) + assert.Equal(t, 12.5, info.TotalRewardEarned) + assert.Nil(t, info.InviterInfo) +} + +func TestGetMyReferralInfo_WithInviter(t *testing.T) { + profile := &UserReferralProfile{ID: 1, UserID: 20, ReferralCode: "MYCODE12"} + inviterUser := &User{ID: 99, Email: "inviter@example.com"} + repo := &stubReferralRepo{ + getProfileByUserID: func(_ context.Context, userID int64) (*UserReferralProfile, error) { + return profile, nil + }, + countByInviterID: func(_ context.Context, inviterID int64) (int64, error) { + return 0, nil + }, + sumRewardsByInviterID: func(_ context.Context, inviterID int64) (float64, error) { + return 0, nil + }, + getRelationByInviteeID: func(_ context.Context, inviteeID int64) (*ReferralRelation, error) { + return &ReferralRelation{ID: 1, InviterID: 99, InviteeID: inviteeID}, nil + }, + } + svc := NewReferralService(repo, newStubUserRepoForReferral(inviterUser), nil, nil, nil) + + info, err := svc.GetMyReferralInfo(context.Background(), 20, "") + require.NoError(t, err) + require.NotNil(t, info.InviterInfo) + assert.Equal(t, "inv***@example.com", info.InviterInfo.EmailMasked) +} + +func TestGetMyReferralInfo_ProfileError(t *testing.T) { + repo := &stubReferralRepo{ + getProfileByUserID: func(_ context.Context, userID int64) (*UserReferralProfile, error) { + return nil, errors.New("db error") + }, + } + svc := NewReferralService(repo, newStubUserRepoForReferral(), nil, nil, nil) + + _, err := svc.GetMyReferralInfo(context.Background(), 1, "") + require.Error(t, err) +} + +// ===================== +// ListMyInvitees 测试 +// ===================== + +func TestListMyInvitees_Normal(t *testing.T) { + now := time.Date(2025, 1, 2, 3, 4, 5, 0, time.UTC) + relations := []ReferralRelation{ + {InviteeEmail: "alice@example.com", InviterReward: 5.0, CreatedAt: now}, + {InviteeEmail: "bo@example.com", InviterReward: 3.0, CreatedAt: now}, + } + paginationResult := &pagination.PaginationResult{Total: 2, Page: 1, PageSize: 10, Pages: 1} + + repo := &stubReferralRepo{ + listByInviterID: func(_ context.Context, inviterID int64, params pagination.PaginationParams) ([]ReferralRelation, *pagination.PaginationResult, error) { + return relations, paginationResult, nil + }, + } + svc := NewReferralService(repo, newStubUserRepoForReferral(), nil, nil, nil) + + params := pagination.PaginationParams{Page: 1, PageSize: 10} + invitees, result, err := svc.ListMyInvitees(context.Background(), 1, params) + require.NoError(t, err) + require.Len(t, invitees, 2) + assert.Equal(t, "ali***@example.com", invitees[0].EmailMasked) + assert.Equal(t, "bo***@example.com", invitees[1].EmailMasked) + assert.Equal(t, 5.0, invitees[0].RewardEarned) + assert.Equal(t, now, invitees[0].RegisteredAt) + assert.Equal(t, paginationResult, result) +} + +func TestListMyInvitees_Empty(t *testing.T) { + repo := &stubReferralRepo{ + listByInviterID: func(_ context.Context, inviterID int64, params pagination.PaginationParams) ([]ReferralRelation, *pagination.PaginationResult, error) { + return []ReferralRelation{}, &pagination.PaginationResult{Total: 0, Page: 1, PageSize: 10, Pages: 1}, nil + }, + } + svc := NewReferralService(repo, newStubUserRepoForReferral(), nil, nil, nil) + + invitees, _, err := svc.ListMyInvitees(context.Background(), 1, pagination.PaginationParams{Page: 1, PageSize: 10}) + require.NoError(t, err) + assert.Empty(t, invitees) +} + +func TestListMyInvitees_RepoError(t *testing.T) { + repo := &stubReferralRepo{ + listByInviterID: func(_ context.Context, inviterID int64, params pagination.PaginationParams) ([]ReferralRelation, *pagination.PaginationResult, error) { + return nil, nil, errors.New("db error") + }, + } + svc := NewReferralService(repo, newStubUserRepoForReferral(), nil, nil, nil) + + _, _, err := svc.ListMyInvitees(context.Background(), 1, pagination.PaginationParams{Page: 1, PageSize: 10}) + require.Error(t, err) +} + +// ===================== +// GetPlatformStats 测试 +// ===================== + +func TestGetPlatformStats_Normal(t *testing.T) { + expected := &ReferralStats{TotalRelations: 100, TotalInviterRewardGiven: 50.0, TotalInviteeRewardGiven: 30.0} + repo := &stubReferralRepo{ + getPlatformStats: func(_ context.Context) (*ReferralStats, error) { + return expected, nil + }, + } + svc := NewReferralService(repo, newStubUserRepoForReferral(), nil, nil, nil) + + stats, err := svc.GetPlatformStats(context.Background()) + require.NoError(t, err) + assert.Equal(t, expected, stats) +} + +func TestGetPlatformStats_Error(t *testing.T) { + repo := &stubReferralRepo{ + getPlatformStats: func(_ context.Context) (*ReferralStats, error) { + return nil, errors.New("db error") + }, + } + svc := NewReferralService(repo, newStubUserRepoForReferral(), nil, nil, nil) + + _, err := svc.GetPlatformStats(context.Background()) + require.Error(t, err) +} + +// ===================== +// InvalidateRewardCaches 测试 +// ===================== + +func TestInvalidateRewardCaches_NilService(t *testing.T) { + repo := &stubReferralRepo{} + svc := NewReferralService(repo, newStubUserRepoForReferral(), nil, nil, nil) + // nil billingCacheService 时不 panic + assert.NotPanics(t, func() { + svc.InvalidateRewardCaches(1, 2) + }) +} + +func TestInvalidateRewardCaches_NonNil(t *testing.T) { + repo := &stubReferralRepo{} + // BillingCacheService with nil internal cache: InvalidateUserBalance returns nil immediately + billingCache := &BillingCacheService{cache: nil} + svc := NewReferralService(repo, newStubUserRepoForReferral(), nil, billingCache, nil) + + assert.NotPanics(t, func() { + svc.InvalidateRewardCaches(1, 2) + }) + // 等待异步 goroutine 完成 + time.Sleep(50 * time.Millisecond) +} diff --git a/backend/internal/service/setting_service.go b/backend/internal/service/setting_service.go index f7e4fb6be..29e4bae79 100644 --- a/backend/internal/service/setting_service.go +++ b/backend/internal/service/setting_service.go @@ -127,6 +127,7 @@ func (s *SettingService) GetPublicSettings(ctx context.Context) (*PublicSettings SettingKeySoraClientEnabled, SettingKeyCustomMenuItems, SettingKeyLinuxDoConnectEnabled, + SettingKeyReferralEnabled, } settings, err := s.settingRepo.GetMultiple(ctx, keys) @@ -167,6 +168,7 @@ func (s *SettingService) GetPublicSettings(ctx context.Context) (*PublicSettings SoraClientEnabled: settings[SettingKeySoraClientEnabled] == "true", CustomMenuItems: settings[SettingKeyCustomMenuItems], LinuxDoOAuthEnabled: linuxDoEnabled, + ReferralEnabled: settings[SettingKeyReferralEnabled] == "true", }, nil } @@ -438,6 +440,11 @@ func (s *SettingService) UpdateSettings(ctx context.Context, settings *SystemSet // Claude Code version check updates[SettingKeyMinClaudeCodeVersion] = settings.MinClaudeCodeVersion + // 裂变推广配置 + updates[SettingKeyReferralEnabled] = strconv.FormatBool(settings.ReferralEnabled) + updates[SettingKeyReferralInviterReward] = strconv.FormatFloat(settings.ReferralInviterReward, 'f', 2, 64) + updates[SettingKeyReferralInviteeReward] = strconv.FormatFloat(settings.ReferralInviteeReward, 'f', 2, 64) + err = s.settingRepo.SetMultiple(ctx, updates) if err == nil { // 先使 inflight singleflight 失效,再刷新缓存,缩小旧值覆盖新值的竞态窗口 @@ -661,6 +668,7 @@ func (s *SettingService) parseSettings(settings map[string]string) *SystemSettin PasswordResetEnabled: emailVerifyEnabled && settings[SettingKeyPasswordResetEnabled] == "true", InvitationCodeEnabled: settings[SettingKeyInvitationCodeEnabled] == "true", TotpEnabled: settings[SettingKeyTotpEnabled] == "true", + ReferralEnabled: settings[SettingKeyReferralEnabled] == "true", SMTPHost: settings[SettingKeySMTPHost], SMTPUsername: settings[SettingKeySMTPUsername], SMTPFrom: settings[SettingKeySMTPFrom], @@ -705,6 +713,16 @@ func (s *SettingService) parseSettings(settings map[string]string) *SystemSettin } result.DefaultSubscriptions = parseDefaultSubscriptions(settings[SettingKeyDefaultSubscriptions]) + // 裂变推广奖励配置(默认 0,需管理员显式配置) + result.ReferralInviterReward = 0 + if v, err := strconv.ParseFloat(settings[SettingKeyReferralInviterReward], 64); err == nil { + result.ReferralInviterReward = v + } + result.ReferralInviteeReward = 0 + if v, err := strconv.ParseFloat(settings[SettingKeyReferralInviteeReward], 64); err == nil { + result.ReferralInviteeReward = v + } + // 敏感信息直接返回,方便测试连接时使用 result.SMTPPassword = settings[SettingKeySMTPPassword] result.TurnstileSecretKey = settings[SettingKeyTurnstileSecretKey] @@ -1780,3 +1798,37 @@ func maxInt64(value int64, min int64) int64 { } return value } + +// IsReferralEnabled 检查裂变推广功能是否启用 +func (s *SettingService) IsReferralEnabled(ctx context.Context) (bool, error) { + val, err := s.settingRepo.GetValue(ctx, SettingKeyReferralEnabled) + if err != nil { + return false, nil // default: disabled + } + return val == "true", nil +} + +// GetReferralRewards 获取邀请奖励配置,返回 (inviterReward, inviteeReward)。 +// 配置缺失时返回默认值 0(需管理员显式配置后才发放奖励)。 +func (s *SettingService) GetReferralRewards(ctx context.Context) (inviterReward, inviteeReward float64, err error) { + settings, err := s.settingRepo.GetMultiple(ctx, []string{ + SettingKeyReferralInviterReward, + SettingKeyReferralInviteeReward, + }) + inviterReward = 0 + inviteeReward = 0 + if err != nil { + return 0, 0, fmt.Errorf("get referral reward settings: %w", err) + } + if v, ok := settings[SettingKeyReferralInviterReward]; ok { + if f, e := strconv.ParseFloat(v, 64); e == nil { + inviterReward = f + } + } + if v, ok := settings[SettingKeyReferralInviteeReward]; ok { + if f, e := strconv.ParseFloat(v, 64); e == nil { + inviteeReward = f + } + } + return inviterReward, inviteeReward, nil +} diff --git a/backend/internal/service/settings_view.go b/backend/internal/service/settings_view.go index 9f0de6000..41dfa4c3f 100644 --- a/backend/internal/service/settings_view.go +++ b/backend/internal/service/settings_view.go @@ -65,6 +65,11 @@ type SystemSettings struct { // Claude Code version check MinClaudeCodeVersion string + + // 裂变推广配置 + ReferralEnabled bool + ReferralInviterReward float64 + ReferralInviteeReward float64 } type DefaultSubscriptionSetting struct { @@ -97,6 +102,7 @@ type PublicSettings struct { LinuxDoOAuthEnabled bool Version string + ReferralEnabled bool } // SoraS3Settings Sora S3 存储配置 diff --git a/backend/internal/service/subscription_calculate_progress_test.go b/backend/internal/service/subscription_calculate_progress_test.go index 22018bcd6..2e86ae8f9 100644 --- a/backend/internal/service/subscription_calculate_progress_test.go +++ b/backend/internal/service/subscription_calculate_progress_test.go @@ -34,7 +34,7 @@ func TestCalculateProgress_BasicFields(t *testing.T) { assert.Equal(t, int64(100), progress.ID) assert.Equal(t, "Premium", progress.GroupName) assert.Equal(t, sub.ExpiresAt, progress.ExpiresAt) - assert.Equal(t, 29, progress.ExpiresInDays) // 约 30 天 + assert.True(t, progress.ExpiresInDays >= 29 && progress.ExpiresInDays <= 30, "ExpiresInDays should be approximately 30 days (got %d)", progress.ExpiresInDays) assert.Nil(t, progress.Daily, "无日限额时 Daily 应为 nil") assert.Nil(t, progress.Weekly, "无周限额时 Weekly 应为 nil") assert.Nil(t, progress.Monthly, "无月限额时 Monthly 应为 nil") diff --git a/backend/internal/service/user_service_test.go b/backend/internal/service/user_service_test.go index 05fe50560..7f6c748fa 100644 --- a/backend/internal/service/user_service_test.go +++ b/backend/internal/service/user_service_test.go @@ -47,8 +47,8 @@ func (m *mockUserRepo) RemoveGroupFromAllowedGroups(context.Context, int64) (int } func (m *mockUserRepo) AddGroupToAllowedGroups(context.Context, int64, int64) error { return nil } func (m *mockUserRepo) UpdateTotpSecret(context.Context, int64, *string) error { return nil } -func (m *mockUserRepo) EnableTotp(context.Context, int64) error { return nil } -func (m *mockUserRepo) DisableTotp(context.Context, int64) error { return nil } +func (m *mockUserRepo) EnableTotp(context.Context, int64) error { return nil } +func (m *mockUserRepo) DisableTotp(context.Context, int64) error { return nil } // --- mock: APIKeyAuthCacheInvalidator --- diff --git a/backend/internal/service/wire.go b/backend/internal/service/wire.go index 920ab1cc5..454276377 100644 --- a/backend/internal/service/wire.go +++ b/backend/internal/service/wire.go @@ -380,4 +380,5 @@ var ProviderSet = wire.NewSet( ProvideIdempotencyCoordinator, ProvideSystemOperationLockService, ProvideIdempotencyCleanupService, + NewReferralService, ) diff --git a/backend/migrations/066_add_referral_system.sql b/backend/migrations/066_add_referral_system.sql new file mode 100644 index 000000000..bbe5e661c --- /dev/null +++ b/backend/migrations/066_add_referral_system.sql @@ -0,0 +1,26 @@ +-- 用户邀请裂变推广机制 - 新增两张独立表,不修改任何现有表 +-- user_referral_profiles: 每个用户的专属邀请码(懒加载,注册时创建) +-- referral_relations: 邀请关系记录(含奖励金额快照和幂等标志) + +CREATE TABLE IF NOT EXISTS user_referral_profiles ( + id BIGSERIAL PRIMARY KEY, + user_id BIGINT NOT NULL REFERENCES users(id), + referral_code VARCHAR(8) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + CONSTRAINT uq_urp_user_id UNIQUE (user_id), + CONSTRAINT uq_urp_referral_code UNIQUE (referral_code) +); + +CREATE TABLE IF NOT EXISTS referral_relations ( + id BIGSERIAL PRIMARY KEY, + inviter_id BIGINT NOT NULL REFERENCES users(id), + invitee_id BIGINT NOT NULL REFERENCES users(id), + inviter_reward DECIMAL(20,8) NOT NULL DEFAULT 0, + invitee_reward DECIMAL(20,8) NOT NULL DEFAULT 0, + reward_granted BOOLEAN NOT NULL DEFAULT FALSE, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + CONSTRAINT uq_rr_invitee_id UNIQUE (invitee_id) +); + +-- 按邀请人查询邀请记录(分页列表高频查询) +CREATE INDEX IF NOT EXISTS idx_referral_relations_inviter_id ON referral_relations(inviter_id); diff --git a/backend/migrations/067_add_referral_indexes_notx.sql b/backend/migrations/067_add_referral_indexes_notx.sql new file mode 100644 index 000000000..17eace646 --- /dev/null +++ b/backend/migrations/067_add_referral_indexes_notx.sql @@ -0,0 +1,5 @@ +CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS idx_urp_user_id_concurrent + ON user_referral_profiles(user_id); + +CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS idx_urp_referral_code_concurrent + ON user_referral_profiles(referral_code); diff --git a/frontend/src/api/admin/settings.ts b/frontend/src/api/admin/settings.ts index 52855a040..c95517d4b 100644 --- a/frontend/src/api/admin/settings.ts +++ b/frontend/src/api/admin/settings.ts @@ -78,6 +78,11 @@ export interface SystemSettings { // Claude Code version check min_claude_code_version: string + + // 裂变推广配置 + referral_enabled: boolean + referral_inviter_reward: number + referral_invitee_reward: number } export interface UpdateSettingsRequest { @@ -128,6 +133,11 @@ export interface UpdateSettingsRequest { ops_query_mode_default?: 'auto' | 'raw' | 'preagg' | string ops_metrics_interval_seconds?: number min_claude_code_version?: string + + // 裂变推广配置 + referral_enabled?: boolean + referral_inviter_reward?: number + referral_invitee_reward?: number } /** diff --git a/frontend/src/api/index.ts b/frontend/src/api/index.ts index 070ce6485..117f25c37 100644 --- a/frontend/src/api/index.ts +++ b/frontend/src/api/index.ts @@ -17,6 +17,7 @@ export { redeemAPI, type RedeemHistoryItem } from './redeem' export { userGroupsAPI } from './groups' export { totpAPI } from './totp' export { default as announcementsAPI } from './announcements' +export { referralAPI } from './referral' // Admin APIs export { adminAPI } from './admin' diff --git a/frontend/src/api/referral.ts b/frontend/src/api/referral.ts new file mode 100644 index 000000000..31d65113e --- /dev/null +++ b/frontend/src/api/referral.ts @@ -0,0 +1,45 @@ +/** + * Referral API endpoints + * Handles user referral/invitation system + */ + +import { apiClient } from './client' +import type { ReferralInfo, ReferralInvitee, BasePaginationResponse, ReferralStats } from '@/types' + +/** + * Get current user's referral info (code, link, stats) + */ +export async function getMyReferralInfo(): Promise { + const { data } = await apiClient.get('/referral') + return data +} + +/** + * Get paginated list of users invited by current user + */ +export async function listMyInvitees( + page = 1, + pageSize = 20 +): Promise> { + const { data } = await apiClient.get>( + '/referral/invitees', + { params: { page, page_size: pageSize } } + ) + return data +} + +/** + * Admin: Get platform-wide referral statistics + */ +export async function getAdminReferralStats(): Promise { + const { data } = await apiClient.get('/admin/referral/stats') + return data +} + +export const referralAPI = { + getMyReferralInfo, + listMyInvitees, + getAdminReferralStats +} + +export default referralAPI diff --git a/frontend/src/components/layout/AppSidebar.vue b/frontend/src/components/layout/AppSidebar.vue index dcfc60bbb..560516953 100644 --- a/frontend/src/components/layout/AppSidebar.vue +++ b/frontend/src/components/layout/AppSidebar.vue @@ -492,6 +492,21 @@ const SoraIcon = { ) } +const ReferralIcon = { + render: () => + h( + 'svg', + { fill: 'none', viewBox: '0 0 24 24', stroke: 'currentColor', 'stroke-width': '1.5' }, + [ + h('path', { + 'stroke-linecap': 'round', + 'stroke-linejoin': 'round', + d: 'M7.217 10.907a2.25 2.25 0 1 0 0 2.186m0-2.186c.18.324.283.696.283 1.093s-.103.77-.283 1.093m0-2.186 9.566-5.314m-9.566 7.5 9.566 5.314m0 0a2.25 2.25 0 1 0 3.935 2.186 2.25 2.25 0 0 0-3.935-2.186zm0-12.814a2.25 2.25 0 1 0 3.933-2.185 2.25 2.25 0 0 0-3.933 2.185z' + }) + ] + ) +} + const ChevronDoubleRightIcon = { render: () => h( @@ -528,6 +543,9 @@ const userNavItems = computed((): NavItem[] => { ] : []), { path: '/redeem', label: t('nav.redeem'), icon: GiftIcon, hideInSimpleMode: true }, + ...(appStore.cachedPublicSettings?.referral_enabled + ? [{ path: '/referral', label: t('nav.referral'), icon: ReferralIcon }] + : []), { path: '/profile', label: t('nav.profile'), icon: UserIcon }, ...customMenuItemsForUser.value.map((item): NavItem => ({ path: `/custom/${item.id}`, @@ -559,6 +577,9 @@ const personalNavItems = computed((): NavItem[] => { ] : []), { path: '/redeem', label: t('nav.redeem'), icon: GiftIcon, hideInSimpleMode: true }, + ...(appStore.cachedPublicSettings?.referral_enabled + ? [{ path: '/referral', label: t('nav.referral'), icon: ReferralIcon }] + : []), { path: '/profile', label: t('nav.profile'), icon: UserIcon }, ...customMenuItemsForUser.value.map((item): NavItem => ({ path: `/custom/${item.id}`, diff --git a/frontend/src/i18n/locales/en.ts b/frontend/src/i18n/locales/en.ts index 41edeb6a0..38d724681 100644 --- a/frontend/src/i18n/locales/en.ts +++ b/frontend/src/i18n/locales/en.ts @@ -230,6 +230,7 @@ export default { noOptionsFound: 'No options found', noGroupsAvailable: 'No groups available', unknownError: 'Unknown error occurred', + retry: 'Retry', saving: 'Saving...', selectedCount: '({count} selected)', refresh: 'Refresh', @@ -282,7 +283,8 @@ export default { mySubscriptions: 'My Subscriptions', buySubscription: 'Recharge / Subscription', docs: 'Docs', - sora: 'Sora Studio' + sora: 'Sora Studio', + referral: 'Referral' }, // Auth @@ -695,6 +697,32 @@ export default { pleaseEnterCode: 'Please enter a redeem code' }, + // Referral + referral: { + title: 'Referral Program', + description: 'Invite friends to join and earn balance rewards for both of you', + myCode: 'Your Referral Code', + myLink: 'Your Referral Link', + copyCode: 'Copy Code', + copyLink: 'Copy Link', + codeCopied: 'Code copied!', + linkCopied: 'Link copied!', + copyFailed: 'Copy failed', + stats: 'Your Stats', + totalInvitees: 'Total Invitees', + totalRewardEarned: 'Total Reward Earned', + invitedBy: 'You were invited by', + inviteeList: 'Your Invitees', + noInvitees: 'You have not invited anyone yet. Share your referral link to get started!', + emailMasked: 'Email', + registeredAt: 'Registered At', + rewardEarned: 'Reward Earned', + howItWorks: 'How It Works', + step1: 'Share your referral link or code with friends', + step2: 'Your friend registers using your link or enters your code', + step3: 'Both you and your friend receive a balance reward' + }, + // Profile profile: { title: 'Profile Settings', @@ -3643,6 +3671,17 @@ export default { enabled: 'Enable Sora Client', enabledHint: 'When enabled, the Sora entry will be shown in the sidebar for users to access Sora features' }, + referral: { + title: 'Referral Program', + description: 'Configure the referral/invitation reward system', + enabled: 'Enable Referral Program', + enabledHint: 'When enabled, users can invite others and earn balance rewards', + inviterReward: 'Inviter Reward ($)', + inviterRewardHint: 'Balance credited to the user who sent the invitation when their invitee registers', + inviteeReward: 'Invitee Reward ($)', + inviteeRewardHint: 'Balance credited to the newly registered user who used an invitation link', + rewardPlaceholder: '0.00' + }, customMenu: { title: 'Custom Menu Pages', description: 'Add custom iframe pages to the sidebar navigation. Each page can be visible to regular users or administrators.', diff --git a/frontend/src/i18n/locales/zh.ts b/frontend/src/i18n/locales/zh.ts index 397ecbb2f..2fd857fa2 100644 --- a/frontend/src/i18n/locales/zh.ts +++ b/frontend/src/i18n/locales/zh.ts @@ -230,6 +230,7 @@ export default { noOptionsFound: '无匹配选项', noGroupsAvailable: '无可用分组', unknownError: '发生未知错误', + retry: '重试', saving: '保存中...', selectedCount: '(已选 {count} 个)', refresh: '刷新', @@ -282,7 +283,8 @@ export default { mySubscriptions: '我的订阅', buySubscription: '充值/订阅', docs: '文档', - sora: 'Sora 创作' + sora: 'Sora 创作', + referral: '邀请推广' }, // Auth @@ -701,6 +703,32 @@ export default { pleaseEnterCode: '请输入兑换码' }, + // Referral + referral: { + title: '邀请推广', + description: '邀请好友注册,双方均可获得余额奖励', + myCode: '您的邀请码', + myLink: '您的邀请链接', + copyCode: '复制邀请码', + copyLink: '复制邀请链接', + codeCopied: '邀请码已复制!', + linkCopied: '链接已复制!', + copyFailed: '复制失败', + stats: '邀请统计', + totalInvitees: '已邀请人数', + totalRewardEarned: '累计获得奖励', + invitedBy: '您的邀请人', + inviteeList: '已邀请用户', + noInvitees: '您还没有邀请任何人,分享您的邀请链接开始吧!', + emailMasked: '邮箱', + registeredAt: '注册时间', + rewardEarned: '获得奖励', + howItWorks: '如何使用', + step1: '分享您的邀请链接或邀请码给好友', + step2: '好友通过您的链接注册,或注册时填写您的邀请码', + step3: '双方均可获得余额奖励' + }, + // Profile profile: { title: '个人设置', @@ -3813,6 +3841,17 @@ export default { enabled: '启用 Sora 客户端', enabledHint: '开启后,侧边栏将显示 Sora 入口,用户可访问 Sora 功能' }, + referral: { + title: '邀请推广', + description: '配置邀请注册奖励机制', + enabled: '启用邀请推广', + enabledHint: '开启后,用户可通过邀请他人注册获得余额奖励', + inviterReward: '邀请人奖励($)', + inviterRewardHint: '被邀请人成功注册后,邀请人获得的余额奖励', + inviteeReward: '被邀请人奖励($)', + inviteeRewardHint: '通过邀请链接注册的新用户获得的余额奖励', + rewardPlaceholder: '0.00' + }, customMenu: { title: '自定义菜单页面', description: '添加自定义 iframe 页面到侧边栏导航。每个页面可以设置为普通用户或管理员可见。', diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts index 08f492d4d..dd924ffe7 100644 --- a/frontend/src/router/index.ts +++ b/frontend/src/router/index.ts @@ -155,6 +155,18 @@ const routes: RouteRecordRaw[] = [ descriptionKey: 'redeem.description' } }, + { + path: '/referral', + name: 'Referral', + component: () => import('@/views/user/ReferralView.vue'), + meta: { + requiresAuth: true, + requiresAdmin: false, + title: 'Referral', + titleKey: 'referral.title', + descriptionKey: 'referral.description' + } + }, { path: '/profile', name: 'Profile', diff --git a/frontend/src/stores/app.ts b/frontend/src/stores/app.ts index 37439a4c1..bb24fcca8 100644 --- a/frontend/src/stores/app.ts +++ b/frontend/src/stores/app.ts @@ -330,6 +330,7 @@ export const useAppStore = defineStore('app', () => { custom_menu_items: [], linuxdo_oauth_enabled: false, sora_client_enabled: false, + referral_enabled: false, version: siteVersion.value } } diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts index 6e5aa3020..383f2707a 100644 --- a/frontend/src/types/index.ts +++ b/frontend/src/types/index.ts @@ -63,6 +63,33 @@ export interface RegisterRequest { turnstile_token?: string promo_code?: string invitation_code?: string + referral_code?: string +} + +// ==================== Referral Types ==================== + +export interface ReferralInviterInfo { + email_masked: string +} + +export interface ReferralInfo { + referral_code: string + referral_link: string + total_invitees: number + total_reward_earned: number + inviter_info?: ReferralInviterInfo +} + +export interface ReferralInvitee { + email_masked: string + registered_at: string + reward_earned: number +} + +export interface ReferralStats { + total_relations: number + total_inviter_reward_given: number + total_invitee_reward_given: number } export interface SendVerifyCodeRequest { @@ -105,6 +132,7 @@ export interface PublicSettings { custom_menu_items: CustomMenuItem[] linuxdo_oauth_enabled: boolean sora_client_enabled: boolean + referral_enabled: boolean version: string } diff --git a/frontend/src/views/admin/SettingsView.vue b/frontend/src/views/admin/SettingsView.vue index 3a42a5b71..990ba91ac 100644 --- a/frontend/src/views/admin/SettingsView.vue +++ b/frontend/src/views/admin/SettingsView.vue @@ -1110,6 +1110,68 @@ + +
+
+

+ {{ t('admin.settings.referral.title') }} +

+

+ {{ t('admin.settings.referral.description') }} +

+
+
+ +
+
+ +

+ {{ t('admin.settings.referral.enabledHint') }} +

+
+ +
+ + +
+ + +

+ {{ t('admin.settings.referral.inviterRewardHint') }} +

+
+ + +
+ + +

+ {{ t('admin.settings.referral.inviteeRewardHint') }} +

+
+
+
+
@@ -1438,7 +1500,11 @@ const form = reactive({ ops_query_mode_default: 'auto', ops_metrics_interval_seconds: 60, // Claude Code version check - min_claude_code_version: '' + min_claude_code_version: '', + // 裂变推广配置 + referral_enabled: false, + referral_inviter_reward: 0, + referral_invitee_reward: 0 }) const defaultSubscriptionGroupOptions = computed(() => @@ -1623,7 +1689,10 @@ async function saveSettings() { fallback_model_antigravity: form.fallback_model_antigravity, enable_identity_patch: form.enable_identity_patch, identity_patch_prompt: form.identity_patch_prompt, - min_claude_code_version: form.min_claude_code_version + min_claude_code_version: form.min_claude_code_version, + referral_enabled: form.referral_enabled, + referral_inviter_reward: form.referral_inviter_reward, + referral_invitee_reward: form.referral_invitee_reward } const updated = await adminAPI.settings.updateSettings(payload) Object.assign(form, updated) diff --git a/frontend/src/views/auth/EmailVerifyView.vue b/frontend/src/views/auth/EmailVerifyView.vue index 7f797eb43..e0ca27a9a 100644 --- a/frontend/src/views/auth/EmailVerifyView.vue +++ b/frontend/src/views/auth/EmailVerifyView.vue @@ -202,6 +202,7 @@ const password = ref('') const initialTurnstileToken = ref('') const promoCode = ref('') const invitationCode = ref('') +const referralCode = ref('') const hasRegisterData = ref(false) // Public settings @@ -232,6 +233,7 @@ onMounted(async () => { initialTurnstileToken.value = registerData.turnstile_token || '' promoCode.value = registerData.promo_code || '' invitationCode.value = registerData.invitation_code || '' + referralCode.value = registerData.referral_code || '' hasRegisterData.value = !!(email.value && password.value) } catch { hasRegisterData.value = false @@ -387,7 +389,8 @@ async function handleVerify(): Promise { verify_code: verifyCode.value.trim(), turnstile_token: initialTurnstileToken.value || undefined, promo_code: promoCode.value || undefined, - invitation_code: invitationCode.value || undefined + invitation_code: invitationCode.value || undefined, + referral_code: referralCode.value || undefined }) // Clear session data diff --git a/frontend/src/views/auth/RegisterView.vue b/frontend/src/views/auth/RegisterView.vue index 53cfe0d16..be9e50061 100644 --- a/frontend/src/views/auth/RegisterView.vue +++ b/frontend/src/views/auth/RegisterView.vue @@ -148,6 +148,27 @@
+ +
+ +
+
+ +
+ +
+
+