Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: in-app subscription purchase for SaaS (BYT-9094) (#19778)
ecmadao24fff41967f6
diff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yamlindex 1f85867047..6837e52686 100644--- a/backend/api/mcp/gen/openapi.yaml+++ b/backend/api/mcp/gen/openapi.yaml@@ -6004,7 +6004,7 @@ paths:content:application/json:schema:- $ref: '#/components/schemas/bytebase.v1.CancelPurchaseResponse'+ $ref: '#/components/schemas/bytebase.v1.PurchaseResponse'/bytebase.v1.SubscriptionService/CreatePurchase:post:tags:@@ -6042,7 +6042,7 @@ paths:content:application/json:schema:- $ref: '#/components/schemas/bytebase.v1.CreatePurchaseResponse'+ $ref: '#/components/schemas/bytebase.v1.PurchaseResponse'/bytebase.v1.SubscriptionService/GetPaymentInfo:post:tags:@@ -6088,7 +6088,6 @@ paths:GetSubscription returns the current subscription.If there is no license, we will return a free plan subscription without expiration time.If there is expired license, we will return a free plan subscription with the expiration time of the expired license.- Permissions required: NoneoperationId: bytebase.v1.SubscriptionService.GetSubscriptionparameters:- name: Connect-Protocol-Version@@ -6192,16 +6191,14 @@ paths:content:application/json:schema:- $ref: '#/components/schemas/bytebase.v1.UpdatePurchaseResponse'- /bytebase.v1.SubscriptionService/UpdateSubscription:+ $ref: '#/components/schemas/bytebase.v1.PurchaseResponse'+ /bytebase.v1.SubscriptionService/UploadLicense:post:tags:- bytebase.v1.SubscriptionService- summary: UpdateSubscription- description: |-- Updates the enterprise license subscription (self-hosted only).- Permissions required: bb.settings.set- operationId: bytebase.v1.SubscriptionService.UpdateSubscription+ summary: UploadLicense+ description: Uploads an enterprise license (self-hosted only).+ operationId: bytebase.v1.SubscriptionService.UploadLicenseparameters:- name: Connect-Protocol-Versionin: header@@ -6216,7 +6213,7 @@ paths:content:application/json:schema:- $ref: '#/components/schemas/bytebase.v1.UpdateSubscriptionRequest'+ $ref: '#/components/schemas/bytebase.v1.UploadLicenseRequest'required: trueresponses:default:@@ -6231,6 +6228,42 @@ paths:application/json:schema:$ref: '#/components/schemas/bytebase.v1.Subscription'+ /bytebase.v1.SubscriptionService/VerifyCheckoutSession:+ post:+ tags:+ - bytebase.v1.SubscriptionService+ summary: VerifyCheckoutSession+ description: VerifyCheckoutSession verifies a Stripe Checkout Session status (SaaS only).+ operationId: bytebase.v1.SubscriptionService.VerifyCheckoutSession+ parameters:+ - name: Connect-Protocol-Version+ in: header+ required: true+ schema:+ $ref: '#/components/schemas/connect-protocol-version'+ - name: Connect-Timeout-Ms+ in: header+ schema:+ $ref: '#/components/schemas/connect-timeout-header'+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/bytebase.v1.VerifyCheckoutSessionRequest'+ required: true+ responses:+ default:+ description: Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/connect.error'+ "200":+ description: Success+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/bytebase.v1.VerifyCheckoutSessionResponse'/bytebase.v1.UserService/BatchGetUsers:post:tags:@@ -8876,10 +8909,6 @@ components:type: objecttitle: CancelPurchaseRequestadditionalProperties: false- bytebase.v1.CancelPurchaseResponse:- type: object- title: CancelPurchaseResponse- additionalProperties: falsebytebase.v1.Changelog:type: objectproperties:@@ -9387,15 +9416,6 @@ components:format: int32title: CreatePurchaseRequestadditionalProperties: false- bytebase.v1.CreatePurchaseResponse:- type: object- properties:- paymentUrl:- type: string- title: payment_url- description: Stripe Checkout URL for the user to complete payment.- title: CreatePurchaseResponse- additionalProperties: falsebytebase.v1.CreateReleaseRequest:type: objectproperties:@@ -14257,6 +14277,10 @@ components:type: stringtitle: invoice_urldescription: Stripe Billing Portal URL for invoice management.+ cancelAtPeriodEnd:+ type: boolean+ title: cancel_at_period_end+ description: Whether the subscription is scheduled to cancel at the end of the current billing period.title: PaymentInfoadditionalProperties: falsebytebase.v1.PermissionDeniedDetail:@@ -15071,14 +15095,23 @@ components:bytebase.v1.PurchaseDiscount:type: objectproperties:- description:- type: string- title: description- promotionCode:- type: string- title: promotion_code+ type:+ title: type+ $ref: '#/components/schemas/bytebase.v1.PurchaseDiscount.Type'+ value:+ type: integer+ title: value+ format: int32title: PurchaseDiscountadditionalProperties: false+ bytebase.v1.PurchaseDiscount.Type:+ type: string+ title: Type+ enum:+ - TYPE_UNSPECIFIED+ - PERCENTAGE_OFF+ - FIXED_MONTH_OFF+ - FIXED_PRICE_OFFbytebase.v1.PurchasePlan:type: objectproperties:@@ -15132,6 +15165,21 @@ components:enum:- TYPE_UNSPECIFIED- USER+ bytebase.v1.PurchaseResponse:+ type: object+ properties:+ paymentUrl:+ type: string+ title: payment_url+ description: |-+ If set, redirect to this Stripe Checkout URL.+ If empty, the update was applied directly using the existing payment method.+ sessionId:+ type: string+ title: session_id+ description: Stripe Checkout Session ID. Used to verify the session after redirect.+ title: PurchaseResponse+ additionalProperties: falsebytebase.v1.QueryDataPolicy:type: objectproperties:@@ -17430,6 +17478,10 @@ components:type: booleantitle: hadescription: Whether high availability (multiple replicas) is enabled.+ etag:+ type: string+ title: etag+ description: Etag for optimistic concurrency on purchase updates. Only set in SaaS mode.title: SubscriptionadditionalProperties: falsebytebase.v1.SwitchWorkspaceRequest:@@ -19087,17 +19139,6 @@ components:title: etagtitle: UpdatePurchaseRequestadditionalProperties: false- bytebase.v1.UpdatePurchaseResponse:- type: object- properties:- paymentUrl:- type: string- title: payment_url- description: |-- If set, redirect to this Stripe Checkout URL.- If empty, the update was applied directly using the existing payment method.- title: UpdatePurchaseResponse- additionalProperties: falsebytebase.v1.UpdateReleaseRequest:type: objectproperties:@@ -19194,20 +19235,6 @@ components:title: UpdateSettingRequestadditionalProperties: falsedescription: The request message for updating or creating a setting.- bytebase.v1.UpdateSubscriptionRequest:- type: object- properties:- license:- type: string- title: license- allowMissing:- type: boolean- title: allow_missing- description: |-- If set to true, and the subscription is not found, a new subscription will be created.- In this situation, `update_mask` is ignored.- title: UpdateSubscriptionRequest- additionalProperties: falsebytebase.v1.UpdateUserRequest:type: objectproperties:@@ -19349,6 +19376,14 @@ components:$ref: '#/components/schemas/google.protobuf.FieldMask'title: UpdateWorkspaceRequestadditionalProperties: false+ bytebase.v1.UploadLicenseRequest:+ type: object+ properties:+ license:+ type: string+ title: license+ title: UploadLicenseRequest+ additionalProperties: falsebytebase.v1.User:type: objectproperties:@@ -19450,6 +19485,23 @@ components:- BITBUCKET- AZURE_DEVOPSdescription: Version control system type.+ bytebase.v1.VerifyCheckoutSessionRequest:+ type: object+ properties:+ sessionId:+ type: string+ title: session_id+ title: VerifyCheckoutSessionRequest+ additionalProperties: false+ bytebase.v1.VerifyCheckoutSessionResponse:+ type: object+ properties:+ status:+ type: string+ title: status+ description: 'Stripe Checkout Session status: "complete", "expired", or "open".'+ title: VerifyCheckoutSessionResponse+ additionalProperties: falsebytebase.v1.ViewMetadata:type: objectproperties:diff --git a/backend/api/stripe/webhook.go b/backend/api/stripe/webhook.goindex c37cd40d10..324a7efc27 100644--- a/backend/api/stripe/webhook.go+++ b/backend/api/stripe/webhook.go@@ -49,6 +49,7 @@ func (h *WebhookHandler) handleCallback(c *echo.Context) error {ctx := c.Request().Context()body, err := io.ReadAll(c.Request().Body)if err != nil {+ slog.Error("failed to read stripe webhook request body", log.BBError(err))return c.String(http.StatusBadRequest, "failed to read request body")}@@ -90,6 +91,11 @@ func (h *WebhookHandler) processEvent(ctx context.Context, event *stripego.Eventfunc (h *WebhookHandler) handleSubscriptionStatusChange(ctx context.Context, event *stripego.Event) error {var sub stripego.Subscriptionif err := json.Unmarshal(event.Data.Raw, &sub); err != nil {+ slog.Error("failed to unmarshal stripe subscription from webhook",+ log.BBError(err),+ slog.String("event_type", string(event.Type)),+ slog.String("event_id", event.ID),+ )return errors.Wrap(err, "failed to unmarshal subscription")}@@ -102,17 +108,29 @@ func (h *WebhookHandler) handleSubscriptionStatusChange(ctx context.Context, eveslog.Error("missing workspace in stripe subscription metadata",slog.String("stripe_subscription_id", sub.ID),slog.String("event_type", string(event.Type)),+ slog.String("event_id", event.ID),)return nil}status, err := mapStripeStatus(sub.Status)if err != nil {+ slog.Error("unsupported stripe subscription status",+ log.BBError(err),+ slog.String("workspace", workspace),+ slog.String("stripe_subscription_id", sub.ID),+ slog.String("stripe_status", string(sub.Status)),+ )return err}stripeCustomer, err := getStripeCustomer(sub.Customer)if err != nil {+ slog.Error("failed to get stripe customer",+ log.BBError(err),+ slog.String("workspace", workspace),+ slog.String("stripe_subscription_id", sub.ID),+ )return err}@@ -126,14 +144,53 @@ func (h *WebhookHandler) handleSubscriptionStatusChange(ctx context.Context, eveexisting, err := h.store.GetSubscriptionByWorkspace(ctx, workspace)if err != nil {+ slog.Error("failed to get subscription for workspace",+ log.BBError(err),+ slog.String("workspace", workspace),+ slog.String("stripe_subscription_id", sub.ID),+ )return errors.Wrapf(err, "failed to get subscription for workspace %s", workspace)}- if existing == nil {- slog.Error("no subscription found for workspace", slog.String("workspace", workspace))- return nil++ // Ignore stale destructive events from an old Stripe subscription.+ // During plan changes, the old subscription is canceled and a new one is created.+ // Webhooks may arrive out of order — if the new subscription's invoice.paid+ // arrived first, the stored StripeSubscriptionId already points to the new one.+ // A late-arriving cancel/pause event from the old subscription must not overwrite it.+ // However, we must allow created/updated/resumed events for the NEW subscription+ // (which has a different ID) to go through.+ if existing != nil && existing.Payload != nil &&+ existing.Payload.StripeSubscriptionId != "" &&+ existing.Payload.StripeSubscriptionId != sub.ID {+ // Only block events that would downgrade the subscription status.+ if event.Type == "customer.subscription.deleted" ||+ event.Type == "customer.subscription.paused" {+ slog.Info("ignoring stale destructive webhook for old stripe subscription",+ slog.String("workspace", workspace),+ slog.String("event_subscription_id", sub.ID),+ slog.String("current_subscription_id", existing.Payload.StripeSubscriptionId),+ slog.String("event_type", string(event.Type)),+ )+ return nil+ }+ }++ var payload *storepb.SubscriptionPayload+ if existing != nil && existing.Payload != nil {+ payload = existing.Payload+ } else {+ // First webhook for this workspace — build payload from Stripe metadata.+ payload, err = buildPayloadFromMetadata(sub.Metadata)+ if err != nil {+ slog.Error("failed to build payload from stripe metadata",+ log.BBError(err),+ slog.String("workspace", workspace),+ slog.String("stripe_subscription_id", sub.ID),+ )+ return errors.Wrapf(err, "failed to build payload from metadata for workspace %s", workspace)+ }}- payload := existing.Payloadpayload.Status = statuspayload.StripeSubscriptionId = sub.IDpayload.StripeCustomerId = stripeCustomer.ID@@ -143,21 +200,41 @@ func (h *WebhookHandler) handleSubscriptionStatusChange(ctx context.Context, evepayload.ExpiresAt = timestamppb.New(expiresAt)}- if _, err := h.store.UpdateSubscription(ctx, workspace, payload); err != nil {- return errors.Wrapf(err, "failed to update subscription for workspace %s", workspace)+ if _, err := h.store.UpsertSubscription(ctx, workspace, payload); err != nil {+ slog.Error("failed to upsert subscription",+ log.BBError(err),+ slog.String("workspace", workspace),+ slog.String("stripe_subscription_id", sub.ID),+ )+ return errors.Wrapf(err, "failed to upsert subscription for workspace %s", workspace)}- h.licenseService.InvalidateCache(workspace)+ if err := h.updateLicense(ctx, workspace, payload); err != nil {+ slog.Error("failed to update license after subscription change",+ log.BBError(err),+ slog.String("workspace", workspace),+ slog.String("stripe_subscription_id", sub.ID),+ )+ return errors.Wrapf(err, "failed to update license for workspace %s", workspace)+ }return nil}func (h *WebhookHandler) handleInvoicePaid(ctx context.Context, event *stripego.Event) error {var inv stripego.Invoiceif err := json.Unmarshal(event.Data.Raw, &inv); err != nil {+ slog.Error("failed to unmarshal stripe invoice from webhook",+ log.BBError(err),+ slog.String("event_id", event.ID),+ )return errors.Wrap(err, "failed to unmarshal invoice")}if len(inv.Lines.Data) == 0 {+ slog.Error("stripe invoice has no line items",+ slog.String("invoice_id", inv.ID),+ slog.String("event_id", event.ID),+ )return errors.Errorf("invoice %s has no line items", inv.ID)}@@ -168,31 +245,31 @@ func (h *WebhookHandler) handleInvoicePaid(ctx context.Context, event *stripego.workspace := metadata["workspace"]if workspace == "" {- slog.Error("missing workspace in invoice metadata", slog.String("invoice_id", inv.ID))+ slog.Error("missing workspace in invoice metadata",+ slog.String("invoice_id", inv.ID),+ slog.String("event_id", event.ID),+ )return nil}stripeCustomer, err := getStripeCustomer(inv.Customer)if err != nil {+ slog.Error("failed to get stripe customer from invoice",+ log.BBError(err),+ slog.String("workspace", workspace),+ slog.String("invoice_id", inv.ID),+ )return err}- // Parse metadata fields.- plan, err := parsePlan(metadata["plan"])- if err != nil {- return err- }- interval, err := parseInterval(metadata["interval"])+ payload, err := buildPayloadFromMetadata(metadata)if err != nil {- return err- }- instanceCount, err := strconv.Atoi(metadata["instance_count"])- if err != nil {- return errors.Wrapf(err, "failed to parse instance_count %q", metadata["instance_count"])- }- userCount, err := strconv.Atoi(metadata["user_count"])- if err != nil {- return errors.Wrapf(err, "failed to parse user_count %q", metadata["user_count"])+ slog.Error("failed to build payload from invoice metadata",+ log.BBError(err),+ slog.String("workspace", workspace),+ slog.String("invoice_id", inv.ID),+ )+ return errors.Wrapf(err, "failed to build payload from invoice metadata for workspace %s", workspace)}// Get Stripe subscription ID from invoice parent.@@ -201,6 +278,25 @@ func (h *WebhookHandler) handleInvoicePaid(ctx context.Context, event *stripego.stripeSubID = inv.Parent.SubscriptionDetails.Subscription.ID}+ // Ignore stale invoice.paid events from an old Stripe subscription.+ if stripeSubID != "" {+ existing, err := h.store.GetSubscriptionByWorkspace(ctx, workspace)+ if err != nil {+ return errors.Wrapf(err, "failed to get subscription for workspace %s", workspace)+ }+ if existing != nil && existing.Payload != nil &&+ existing.Payload.StripeSubscriptionId != "" &&+ existing.Payload.StripeSubscriptionId != stripeSubID {+ slog.Info("ignoring stale invoice.paid for old stripe subscription",+ slog.String("workspace", workspace),+ slog.String("event_subscription_id", stripeSubID),+ slog.String("current_subscription_id", existing.Payload.StripeSubscriptionId),+ slog.String("invoice_id", inv.ID),+ )+ return nil+ }+ }+lineData := inv.Lines.Data[0]startedAt := time.Unix(lineData.Period.Start, 0).UTC()expiresAt := time.Unix(lineData.Period.End, 0).UTC()@@ -208,39 +304,95 @@ func (h *WebhookHandler) handleInvoicePaid(ctx context.Context, event *stripego.slog.Info("stripe invoice paid",slog.String("workspace", workspace),slog.String("stripe_subscription_id", stripeSubID),- slog.String("plan", plan.String()),- slog.Int("seats", userCount),- slog.Int("instances", instanceCount),+ slog.String("invoice_id", inv.ID),+ slog.String("plan", payload.Plan.String()),+ slog.Int("seats", int(payload.Seat)),+ slog.Int("instances", int(payload.InstanceCount)),slog.Time("started_at", startedAt),slog.Time("expires_at", expiresAt),)- existing, err := h.store.GetSubscriptionByWorkspace(ctx, workspace)- if err != nil {- return errors.Wrapf(err, "failed to get subscription for workspace %s", workspace)- }- if existing == nil {- return errors.Errorf("no subscription found for workspace %s", workspace)+ payload.Status = storepb.SubscriptionPayload_ACTIVE+ payload.StartedAt = timestamppb.New(startedAt)+ payload.ExpiresAt = timestamppb.New(expiresAt)+ payload.StripeSubscriptionId = stripeSubID+ payload.StripeCustomerId = stripeCustomer.ID++ if _, err := h.store.UpsertSubscription(ctx, workspace, payload); err != nil {+ slog.Error("failed to upsert subscription from invoice",+ log.BBError(err),+ slog.String("workspace", workspace),+ slog.String("stripe_subscription_id", stripeSubID),+ slog.String("invoice_id", inv.ID),+ )+ return errors.Wrapf(err, "failed to upsert subscription for workspace %s", workspace)}- payload := &storepb.SubscriptionPayload{- Status: storepb.SubscriptionPayload_ACTIVE,- StartedAt: timestamppb.New(startedAt),- ExpiresAt: timestamppb.New(expiresAt),- Plan: plan,- Interval: interval,- Seat: int32(userCount),- InstanceCount: int32(instanceCount),- StripeSubscriptionId: stripeSubID,- StripeCustomerId: stripeCustomer.ID,+ if err := h.updateLicense(ctx, workspace, payload); err != nil {+ slog.Error("failed to update license after invoice paid",+ log.BBError(err),+ slog.String("workspace", workspace),+ slog.String("stripe_subscription_id", stripeSubID),+ slog.String("invoice_id", inv.ID),+ )+ return errors.Wrapf(err, "failed to update license for workspace %s", workspace)}+ return nil+}++// updateLicense generates a license JWT from the subscription payload and stores it.+// For non-ACTIVE subscriptions, stores an empty license (reverts to FREE plan).+func (h *WebhookHandler) updateLicense(ctx context.Context, workspace string, payload *storepb.SubscriptionPayload) error {+ var license string++ if payload.Status == storepb.SubscriptionPayload_ACTIVE {+ var expiresAt time.Time+ if payload.ExpiresAt != nil {+ expiresAt = payload.ExpiresAt.AsTime()+ }++ var err error+ license, err = h.licenseService.CreateLicense(&enterprise.LicenseParams{+ Plan: payload.Plan.String(),+ Seats: int(payload.Seat),+ Instances: int(payload.InstanceCount),+ WorkspaceID: workspace,+ ExpiresAt: expiresAt,+ })+ if err != nil {+ return errors.Wrap(err, "failed to create license JWT")+ }+ }++ return h.licenseService.StoreLicense(ctx, workspace, license)+}- if _, err := h.store.UpdateSubscription(ctx, workspace, payload); err != nil {- return errors.Wrapf(err, "failed to update subscription for workspace %s", workspace)+// buildPayloadFromMetadata constructs a SubscriptionPayload from Stripe metadata.+// Returns error if any required field is missing or invalid.+func buildPayloadFromMetadata(metadata map[string]string) (*storepb.SubscriptionPayload, error) {+ plan, err := parsePlan(metadata["plan"])+ if err != nil {+ return nil, errors.Wrap(err, "metadata missing valid plan")+ }+ interval, err := parseInterval(metadata["interval"])+ if err != nil {+ return nil, errors.Wrap(err, "metadata missing valid interval")+ }+ instanceCount, err := strconv.Atoi(metadata["instance_count"])+ if err != nil {+ return nil, errors.Wrapf(err, "metadata missing valid instance_count %q", metadata["instance_count"])+ }+ userCount, err := strconv.Atoi(metadata["user_count"])+ if err != nil {+ return nil, errors.Wrapf(err, "metadata missing valid user_count %q", metadata["user_count"])}- h.licenseService.InvalidateCache(workspace)- return nil+ return &storepb.SubscriptionPayload{+ Plan: plan,+ Interval: interval,+ InstanceCount: int32(instanceCount),+ Seat: int32(userCount),+ }, nil}func mapStripeStatus(status stripego.SubscriptionStatus) (storepb.SubscriptionPayload_Status, error) {diff --git a/backend/api/v1/acl_test.go b/backend/api/v1/acl_test.goindex 4736493a96..3ec3da743d 100644--- a/backend/api/v1/acl_test.go+++ b/backend/api/v1/acl_test.go@@ -63,7 +63,7 @@ func TestGetResourceFromRequest(t *testing.T) {want: []string{"instances/hello"},},{- request: &v1pb.UpdateSubscriptionRequest{+ request: &v1pb.UploadLicenseRequest{License: "123",},method: "/bytebase.v1.SubscriptionService/UpdateSubscription",diff --git a/backend/api/v1/subscription_service.go b/backend/api/v1/subscription_service.goindex 006b43ea29..a18c877a39 100644--- a/backend/api/v1/subscription_service.go+++ b/backend/api/v1/subscription_service.go@@ -9,7 +9,6 @@ import ("connectrpc.com/connect""github.com/pkg/errors"- "google.golang.org/protobuf/types/known/timestamppb""github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"@@ -46,13 +45,20 @@ func NewSubscriptionService(// GetSubscription gets the subscription.func (s *SubscriptionService) GetSubscription(ctx context.Context, _ *connect.Request[v1pb.GetSubscriptionRequest]) (*connect.Response[v1pb.Subscription], error) {- subscription := s.licenseService.LoadSubscription(ctx, common.GetWorkspaceIDFromContext(ctx))+ workspaceID := common.GetWorkspaceIDFromContext(ctx)+ subscription := s.licenseService.LoadSubscription(ctx, workspaceID)+ // Attach etag from subscription table for optimistic concurrency.+ if subscription.Plan != v1pb.PlanType_FREE {+ if existing, err := s.store.GetSubscriptionByWorkspace(ctx, workspaceID); err == nil && existing != nil {+ subscription.Etag = existing.Etag+ }+ }return connect.NewResponse(subscription), nil}-// UpdateSubscription updates the subscription license (self-hosted only).-func (s *SubscriptionService) UpdateSubscription(ctx context.Context, req *connect.Request[v1pb.UpdateSubscriptionRequest]) (*connect.Response[v1pb.Subscription], error) {- if s.profile.SaaS {+// UploadLicense uploads an enterprise license (self-hosted only).+func (s *SubscriptionService) UploadLicense(ctx context.Context, req *connect.Request[v1pb.UploadLicenseRequest]) (*connect.Response[v1pb.Subscription], error) {+ if s.profile.SaaS && s.profile.Mode == common.ReleaseModeProd {return nil, connect.NewError(connect.CodeUnimplemented, errors.New("use purchase APIs in SaaS mode"))}@@ -67,74 +73,35 @@ func (s *SubscriptionService) UpdateSubscription(ctx context.Context, req *connereturn connect.NewResponse(subscription), nil}-// CreatePurchase creates a new subscription purchase (SaaS only).-func (s *SubscriptionService) CreatePurchase(ctx context.Context, req *connect.Request[v1pb.CreatePurchaseRequest]) (*connect.Response[v1pb.CreatePurchaseResponse], error) {+// CreatePurchase creates a Stripe Checkout session (SaaS only).+// Stateless — no subscription record is created. The subscription is only+// created when the Stripe webhook confirms payment.+func (s *SubscriptionService) CreatePurchase(ctx context.Context, req *connect.Request[v1pb.CreatePurchaseRequest]) (*connect.Response[v1pb.PurchaseResponse], error) {if !s.profile.SaaS {return nil, connect.NewError(connect.CodeUnimplemented, errors.New("purchase is only available in SaaS mode"))}workspaceID := common.GetWorkspaceIDFromContext(ctx)- // Check no existing active subscription.+ // Block if workspace already has an active or paused subscription.existing, err := s.store.GetSubscriptionByWorkspace(ctx, workspaceID)if err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to get subscription"))}- if existing != nil && existing.Payload != nil && existing.Payload.Status == storepb.SubscriptionPayload_ACTIVE {- return nil, connect.NewError(connect.CodeAlreadyExists, errors.New("workspace already has an active subscription"))- }-- plan, interval, seats := convertV1PlanToStore(req.Msg.Plan), convertV1IntervalToStore(req.Msg.Interval), req.Msg.Seats- priceModel, err := pricing.NewPriceModel(plan, interval, seats)- if err != nil {- return nil, connect.NewError(connect.CodeInvalidArgument, err)- }-- planLimit := pricing.GetPlanLimit(plan)-- // Create or update subscription record with PENDING status.- payload := &storepb.SubscriptionPayload{- Status: storepb.SubscriptionPayload_PENDING,- Plan: plan,- Interval: interval,- Seat: seats,- InstanceCount: planLimit.InstanceCount,- StartedAt: timestamppb.Now(),- ExpiresAt: timestamppb.Now(),- }-- if existing != nil {- if _, err := s.store.UpdateSubscription(ctx, workspaceID, payload); err != nil {- return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to update subscription"))- }- } else {- if _, err := s.store.CreateSubscription(ctx, &store.SubscriptionMessage{- Workspace: workspaceID,- Payload: payload,- }); err != nil {- return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to create subscription"))+ if existing != nil && existing.Payload != nil {+ switch existing.Payload.Status {+ case storepb.SubscriptionPayload_ACTIVE:+ return nil, connect.NewError(connect.CodeAlreadyExists, errors.New("workspace already has an active subscription"))+ case storepb.SubscriptionPayload_PAUSED:+ return nil, connect.NewError(connect.CodeFailedPrecondition, errors.New("subscription is paused due to a payment issue, please resolve it via the billing portal in Payment Info"))}}- // Generate Stripe Checkout URL.- redirectURL := fmt.Sprintf("%s/setting/subscription", s.profile.ExternalURL)- paymentURL, err := stripeplugin.CreateCheckoutSession(&stripeplugin.CheckoutParams{- Workspace: workspaceID,- PriceModel: priceModel,- SuccessURL: fmt.Sprintf("%s?from=STRIPE", redirectURL),- CancelURL: redirectURL,- })- if err != nil {- return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to create checkout session"))- }-- return connect.NewResponse(&v1pb.CreatePurchaseResponse{- PaymentUrl: paymentURL,- }), nil+ return s.createCheckout(workspaceID, req.Msg.Plan, req.Msg.Interval, req.Msg.Seats)}// UpdatePurchase updates an existing subscription (SaaS only).-func (s *SubscriptionService) UpdatePurchase(ctx context.Context, req *connect.Request[v1pb.UpdatePurchaseRequest]) (*connect.Response[v1pb.UpdatePurchaseResponse], error) {+func (s *SubscriptionService) UpdatePurchase(ctx context.Context, req *connect.Request[v1pb.UpdatePurchaseRequest]) (*connect.Response[v1pb.PurchaseResponse], error) {if !s.profile.SaaS {return nil, connect.NewError(connect.CodeUnimplemented, errors.New("purchase is only available in SaaS mode"))}@@ -145,10 +112,14 @@ func (s *SubscriptionService) UpdatePurchase(ctx context.Context, req *connect.Rif err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to get subscription"))}- if existing == nil {- return nil, connect.NewError(connect.CodeNotFound, errors.New("no subscription found"))++ // No subscription or canceled — create a new checkout session.+ if existing == nil || existing.Payload == nil || existing.Payload.Status == storepb.SubscriptionPayload_CANCELED {+ return s.createCheckout(workspaceID, req.Msg.Plan, req.Msg.Interval, req.Msg.Seats)}- if req.Msg.Etag != "" && req.Msg.Etag != existing.Etag {++ // ACTIVE or PAUSED — cancel old Stripe subscription and create new one.+ if req.Msg.Etag != existing.Etag {return nil, connect.NewError(connect.CodeAborted, errors.New("subscription is out of date, please refresh and try again"))}@@ -158,67 +129,23 @@ func (s *SubscriptionService) UpdatePurchase(ctx context.Context, req *connect.Rreturn nil, connect.NewError(connect.CodeInvalidArgument, err)}- planLimit := pricing.GetPlanLimit(plan)-- // If subscription is not active (PENDING/CANCELED), reset to PENDING and generate new checkout URL.- if existing.Payload == nil || existing.Payload.Status != storepb.SubscriptionPayload_ACTIVE {- payload := &storepb.SubscriptionPayload{- Status: storepb.SubscriptionPayload_PENDING,- Plan: plan,- Interval: interval,- Seat: seats,- InstanceCount: planLimit.InstanceCount,- StartedAt: timestamppb.Now(),- ExpiresAt: timestamppb.Now(),- }- if _, err := s.store.UpdateSubscription(ctx, workspaceID, payload); err != nil {- return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to update subscription"))- }-- redirectURL := fmt.Sprintf("%s/setting/subscription", s.profile.ExternalURL)- paymentURL, err := stripeplugin.CreateCheckoutSession(&stripeplugin.CheckoutParams{- Workspace: workspaceID,- PriceModel: priceModel,- SuccessURL: fmt.Sprintf("%s?from=STRIPE", redirectURL),- CancelURL: redirectURL,- })- if err != nil {- return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to create checkout session"))- }- return connect.NewResponse(&v1pb.UpdatePurchaseResponse{PaymentUrl: paymentURL}), nil- }-- // Active subscription — cancel old Stripe subscription and create new one.+ // Cancel old Stripe subscription and create new one.+ // No need to clear metadata — the cancel webhook will set status=CANCELED,+ // and the invoice.paid webhook from the new subscription will upsert back to ACTIVE.oldPayload := existing.Payloadif oldPayload.StripeSubscriptionId == "" {return nil, connect.NewError(connect.CodeFailedPrecondition, errors.New("no Stripe subscription to update"))}- // Clear metadata on old subscription so webhook ignores the cancel event.- metadata := stripeplugin.GetMetadata(workspaceID, priceModel)- metadata["workspace"] = ""- if err := stripeplugin.UpdateSubscriptionMetadata(oldPayload.StripeSubscriptionId, metadata); err != nil {- return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to clear old subscription metadata"))- }-- // Cancel old subscription with forced refund.- if _, err := stripeplugin.CancelSubscription(oldPayload.StripeSubscriptionId, workspaceID, true); err != nil {- return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to cancel old subscription"))- }-- // Try to create new Stripe subscription directly using existing payment method.+ // Fetch old subscription to get customer ID and payment method before cancellation.oldStripeSub, err := stripeplugin.GetSubscription(oldPayload.StripeSubscriptionId, []string{"default_payment_method", "customer"})if err != nil {- slog.Error("failed to get old stripe subscription, falling back to checkout",- log.BBError(err),- slog.String("workspace", workspaceID),- )- return s.fallbackToCheckout(ctx, workspaceID, priceModel, plan, interval, seats, planLimit.InstanceCount)+ return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to get stripe subscription, please try again"))}customerID := oldStripeSub.Customer.IDif customerID == "" {- return s.fallbackToCheckout(ctx, workspaceID, priceModel, plan, interval, seats, planLimit.InstanceCount)+ return nil, connect.NewError(connect.CodeInternal, errors.New("missing customer ID from stripe subscription"))}var paymentMethodID string@@ -226,6 +153,12 @@ func (s *SubscriptionService) UpdatePurchase(ctx context.Context, req *connect.RpaymentMethodID = oldStripeSub.DefaultPaymentMethod.ID}+ // Cancel old subscription. The webhook may briefly set status=CANCELED,+ // but the invoice.paid from the new subscription will upsert back to ACTIVE.+ if _, err := stripeplugin.CancelSubscription(oldPayload.StripeSubscriptionId, workspaceID, true); err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to cancel old subscription"))+ }+newSub, err := stripeplugin.CreateSubscriptionDirect(&stripeplugin.DirectSubscriptionParams{CustomerID: customerID,PaymentMethodID: paymentMethodID,@@ -237,7 +170,7 @@ func (s *SubscriptionService) UpdatePurchase(ctx context.Context, req *connect.Rlog.BBError(err),slog.String("workspace", workspaceID),)- return s.fallbackToCheckout(ctx, workspaceID, priceModel, plan, interval, seats, planLimit.InstanceCount)+ return s.createCheckout(workspaceID, req.Msg.Plan, req.Msg.Interval, req.Msg.Seats)}slog.Info("created new stripe subscription for plan change",@@ -246,46 +179,36 @@ func (s *SubscriptionService) UpdatePurchase(ctx context.Context, req *connect.Rslog.String("new_stripe_sub", newSub.ID),)- return connect.NewResponse(&v1pb.UpdatePurchaseResponse{}), nil+ return connect.NewResponse(&v1pb.PurchaseResponse{}), nil}-func (s *SubscriptionService) fallbackToCheckout(- ctx context.Context,- workspaceID string,- priceModel *pricing.PriceModel,- plan storepb.SubscriptionPayload_Plan,- interval storepb.SubscriptionPayload_BillingInterval,- seats int32,- instanceCount int32,-) (*connect.Response[v1pb.UpdatePurchaseResponse], error) {- payload := &storepb.SubscriptionPayload{- Status: storepb.SubscriptionPayload_PENDING,- Plan: plan,- Interval: interval,- Seat: seats,- InstanceCount: instanceCount,- StartedAt: timestamppb.Now(),- ExpiresAt: timestamppb.Now(),- }- if _, err := s.store.UpdateSubscription(ctx, workspaceID, payload); err != nil {- return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to update subscription"))+// createCheckoutURL validates inputs and creates a Stripe Checkout session URL.+func (s *SubscriptionService) createCheckout(workspaceID string, v1Plan v1pb.PlanType, v1Interval v1pb.BillingInterval, seats int32) (*connect.Response[v1pb.PurchaseResponse], error) {+ plan, interval := convertV1PlanToStore(v1Plan), convertV1IntervalToStore(v1Interval)+ priceModel, err := pricing.NewPriceModel(plan, interval, seats)+ if err != nil {+ return nil, connect.NewError(connect.CodeInvalidArgument, err)}redirectURL := fmt.Sprintf("%s/setting/subscription", s.profile.ExternalURL)- paymentURL, err := stripeplugin.CreateCheckoutSession(&stripeplugin.CheckoutParams{- Workspace: workspaceID,- PriceModel: priceModel,- SuccessURL: fmt.Sprintf("%s?from=STRIPE", redirectURL),- CancelURL: redirectURL,+ result, err := stripeplugin.CreateCheckoutSession(&stripeplugin.CheckoutParams{+ Workspace: workspaceID,+ PriceModel: priceModel,+ SuccessURL: redirectURL + "?session_id={CHECKOUT_SESSION_ID}",+ CancelURL: redirectURL,+ PromotionCode: priceModel.GetPromotionCode(),})if err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to create checkout session"))}- return connect.NewResponse(&v1pb.UpdatePurchaseResponse{PaymentUrl: paymentURL}), nil+ return connect.NewResponse(&v1pb.PurchaseResponse{+ PaymentUrl: result.URL,+ SessionId: result.SessionID,+ }), nil}// CancelPurchase cancels an active subscription (SaaS only).-func (s *SubscriptionService) CancelPurchase(ctx context.Context, _ *connect.Request[v1pb.CancelPurchaseRequest]) (*connect.Response[v1pb.CancelPurchaseResponse], error) {+func (s *SubscriptionService) CancelPurchase(ctx context.Context, _ *connect.Request[v1pb.CancelPurchaseRequest]) (*connect.Response[v1pb.PurchaseResponse], error) {if !s.profile.SaaS {return nil, connect.NewError(connect.CodeUnimplemented, errors.New("purchase is only available in SaaS mode"))}@@ -312,18 +235,9 @@ func (s *SubscriptionService) CancelPurchase(ctx context.Context, _ *connect.Reqreturn nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to cancel subscription"))}- // Update status. For prorated (monthly), set CANCELED + expire immediately.- // For annual, the webhook will update the status when Stripe cancels at period end.- if prorate {- payload.Status = storepb.SubscriptionPayload_CANCELED- payload.ExpiresAt = timestamppb.New(time.Now().Add(-time.Second))- if _, err := s.store.UpdateSubscription(ctx, workspaceID, payload); err != nil {- slog.Error("failed to update subscription after cancellation", log.BBError(err))- }- s.licenseService.InvalidateCache(workspaceID)- }+ // Stripe webhook (customer.subscription.deleted) will update the subscription status and clear the license- return connect.NewResponse(&v1pb.CancelPurchaseResponse{}), nil+ return connect.NewResponse(&v1pb.PurchaseResponse{}), nil}// GetPaymentInfo returns payment details (SaaS only).@@ -355,13 +269,13 @@ func (s *SubscriptionService) GetPaymentInfo(ctx context.Context, _ *connect.Reqperiod := inv.Lines.Data[0].Periodinfo := &v1pb.PaymentInfo{- TotalPrice: strconv.FormatInt(inv.Total, 10),- Currency: string(sub.Currency),- PeriodStart: time.Unix(period.Start, 0).Format("2006-01-02"),- PeriodEnd: time.Unix(period.End, 0).Format("2006-01-02"),+ TotalPrice: strconv.FormatInt(inv.Total, 10),+ Currency: string(sub.Currency),+ PeriodStart: time.Unix(period.Start, 0).Format("2006-01-02"),+ PeriodEnd: time.Unix(period.End, 0).Format("2006-01-02"),+ CancelAtPeriodEnd: sub.CancelAtPeriodEnd,}- // Create billing portal session for invoice management.if payload.StripeCustomerId != "" {returnURL := fmt.Sprintf("%s/setting/subscription", s.profile.ExternalURL)portalURL, err := stripeplugin.CreateBillingPortalSession(payload.StripeCustomerId, returnURL)@@ -375,35 +289,102 @@ func (s *SubscriptionService) GetPaymentInfo(ctx context.Context, _ *connect.Reqreturn connect.NewResponse(info), nil}+// VerifyCheckoutSession verifies a Stripe Checkout Session status (SaaS only).+func (s *SubscriptionService) VerifyCheckoutSession(ctx context.Context, req *connect.Request[v1pb.VerifyCheckoutSessionRequest]) (*connect.Response[v1pb.VerifyCheckoutSessionResponse], error) {+ if !s.profile.SaaS {+ return nil, connect.NewError(connect.CodeUnimplemented, errors.New("purchase is only available in SaaS mode"))+ }++ if req.Msg.SessionId == "" {+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.New("session_id is required"))+ }++ info, err := stripeplugin.GetCheckoutSessionInfo(req.Msg.SessionId)+ if err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to verify checkout session"))+ }++ // Verify the checkout session belongs to the caller's workspace.+ if info.Workspace != "" && info.Workspace != common.GetWorkspaceIDFromContext(ctx) {+ return nil, connect.NewError(connect.CodePermissionDenied, errors.New("checkout session does not belong to this workspace"))+ }++ return connect.NewResponse(&v1pb.VerifyCheckoutSessionResponse{+ Status: info.Status,+ }), nil+}+// ListPurchasePlans returns available plans for self-service purchase.-func (*SubscriptionService) ListPurchasePlans(_ context.Context, _ *connect.Request[v1pb.ListPurchasePlansRequest]) (*connect.Response[v1pb.ListPurchasePlansResponse], error) {- plans := []*v1pb.PurchasePlan{- {- Type: v1pb.PlanType_TEAM,- SelfServicePurchase: true,- Additionals: []*v1pb.PurchasePlanAdditional{+func (s *SubscriptionService) ListPurchasePlans(_ context.Context, _ *connect.Request[v1pb.ListPurchasePlansRequest]) (*connect.Response[v1pb.ListPurchasePlansResponse], error) {+ // Non-SaaS: no purchase plans available.+ if !s.profile.SaaS {+ return connect.NewResponse(&v1pb.ListPurchasePlansResponse{}), nil+ }++ allPlans := []storepb.SubscriptionPayload_Plan{+ storepb.SubscriptionPayload_TEAM,+ storepb.SubscriptionPayload_ENTERPRISE,+ }++ var plans []*v1pb.PurchasePlan+ for _, p := range allPlans {+ limit := pricing.GetPlanLimit(p)+ if limit == nil {+ continue+ }++ plan := &v1pb.PurchasePlan{+ Type: convertStorePlanToV1(p),+ SelfServicePurchase: limit.SelfServicePurchase,+ }+ if limit.SelfServicePurchase {+ plan.Additionals = []*v1pb.PurchasePlanAdditional{{Type: v1pb.PurchasePlanAdditional_USER,- UnitPrice: 2000, // $20/user/month- FreeCount: 0,+ UnitPrice: int32(limit.PricePerSeatPerMonth),+ FreeCount: limit.FreeSeatCount,MinimumCount: 1,- MaximumCount: -1, // unlimited+ MaximumCount: limit.MaximumSeatCount,},- },- BillingMethods: []*v1pb.PurchaseBillingMethod{- {Interval: v1pb.BillingInterval_MONTH},- {Interval: v1pb.BillingInterval_YEAR},- },- },- {- Type: v1pb.PlanType_ENTERPRISE,- SelfServicePurchase: false,- },+ }+ }++ for _, bm := range limit.BillingMethods {+ method := &v1pb.PurchaseBillingMethod{+ Interval: convertStoreIntervalToV1(bm.Interval),+ Discount: bm.Discount,+ }+ plan.BillingMethods = append(plan.BillingMethods, method)+ }++ plans = append(plans, plan)}return connect.NewResponse(&v1pb.ListPurchasePlansResponse{Plans: plans}), nil}+func convertStorePlanToV1(plan storepb.SubscriptionPayload_Plan) v1pb.PlanType {+ switch plan {+ case storepb.SubscriptionPayload_TEAM:+ return v1pb.PlanType_TEAM+ case storepb.SubscriptionPayload_ENTERPRISE:+ return v1pb.PlanType_ENTERPRISE+ default:+ return v1pb.PlanType_FREE+ }+}++func convertStoreIntervalToV1(interval storepb.SubscriptionPayload_BillingInterval) v1pb.BillingInterval {+ switch interval {+ case storepb.SubscriptionPayload_MONTH:+ return v1pb.BillingInterval_MONTH+ case storepb.SubscriptionPayload_YEAR:+ return v1pb.BillingInterval_YEAR+ default:+ return v1pb.BillingInterval_BILLING_INTERVAL_UNSPECIFIED+ }+}+func convertV1PlanToStore(plan v1pb.PlanType) storepb.SubscriptionPayload_Plan {switch plan {case v1pb.PlanType_TEAM:diff --git a/backend/bin/server/cmd/profile.go b/backend/bin/server/cmd/profile.goindex ff5c1137c2..0d18a6ddb7 100644--- a/backend/bin/server/cmd/profile.go+++ b/backend/bin/server/cmd/profile.go@@ -24,8 +24,9 @@ func getBaseProfile(dataDir string) *config.Profile {GitCommit: gitcommit,PgURL: os.Getenv("PG_URL"),ReplicaID: uuid.NewString(),- StripeAPIKey: os.Getenv("STRIPE_API_KEY"),+ StripeAPISecret: os.Getenv("STRIPE_API_SECRET"),StripeWebhookSecret: os.Getenv("STRIPE_WEBHOOK_SECRET"),+ LicensePrivateKey: os.Getenv("LICENSE_PRIVATE_KEY"),}config.LastActiveTS.Store(time.Now().Unix())diff --git a/backend/component/config/profile.go b/backend/component/config/profile.goindex aa4ebf7a42..68cb8507e9 100644--- a/backend/component/config/profile.go+++ b/backend/component/config/profile.go@@ -22,8 +22,10 @@ type Profile struct {// When we are running in SaaS mode, some features are not allowed to edit by users.SaaS bool// Stripe configuration for SaaS subscription purchase. Only used when SaaS is true.- StripeAPIKey string+ StripeAPISecret stringStripeWebhookSecret string+ // LicensePrivateKey is the PEM-encoded RSA private key for signing license JWTs (SaaS only).+ LicensePrivateKey string// DataDir is the directory stores the data including Bytebase's own database, backups, etc.DataDir string// Demo mode.diff --git a/backend/enterprise/license.go b/backend/enterprise/license.goindex 2c5bd1d275..d8371d9e19 100644--- a/backend/enterprise/license.go+++ b/backend/enterprise/license.go@@ -5,6 +5,7 @@ import ("context""crypto/rsa""embed"+ "encoding/base64""encoding/json""fmt""io/fs"@@ -24,7 +25,6 @@ import ("github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"- storepb "github.com/bytebase/bytebase/backend/generated-go/store"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1""github.com/bytebase/bytebase/backend/store")@@ -79,6 +79,8 @@ func init() {type Config struct {// PublicKey is the parsed RSA public key.PublicKey *rsa.PublicKey+ // PrivateKey is the parsed RSA private key (only set in SaaS mode for license signing).+ PrivateKey *rsa.PrivateKey// Version is the JWT key version.Version string// Issuer is the license issuer, it should always be "bytebase".@@ -139,9 +141,9 @@ type LicenseService struct {replicaCache atomic.Pointer[replicaCacheState]}-// claims creates a struct that will be encoded to a JWT.+// Claims creates a struct that will be encoded to a JWT.// We add jwt.RegisteredClaims as an embedded type, to provide fields such as name.-type claims struct {+type Claims struct {ActiveInstances int `json:"instanceCount"`Instances int `json:"instance"`Seats int `json:"seat"`@@ -154,12 +156,27 @@ type claims struct {}// NewLicenseService will create a new enterprise license service.-func NewLicenseService(mode common.ReleaseMode, store *store.Store, saas bool) (*LicenseService, error) {+// privateKeyPEM is optional — only needed in SaaS mode for signing license JWTs.+func NewLicenseService(mode common.ReleaseMode, store *store.Store, saas bool, privateKeyPEM string) (*LicenseService, error) {config, err := NewConfig(mode)if err != nil {return nil, err}+ if privateKeyPEM != "" {+ // Support base64-encoded PEM (for env vars that can't contain newlines).+ decoded, err := base64.StdEncoding.DecodeString(privateKeyPEM)+ if err == nil {+ privateKeyPEM = string(decoded)+ }+ // If base64 decode fails, assume it's already raw PEM.+ privKey, err := jwt.ParseRSAPrivateKeyFromPEM([]byte(privateKeyPEM))+ if err != nil {+ return nil, errors.Wrap(err, "failed to parse license private key")+ }+ config.PrivateKey = privKey+ }+service := &LicenseService{store: store,config: config,@@ -199,13 +216,7 @@ func (s *LicenseService) LoadSubscription(ctx context.Context, workspaceID strinreturn sub, nil}- var subscription *v1pb.Subscription- // TODO(ed): find if be able to unify this- if s.saas {- subscription = s.loadSubscriptionFromPurchase(ctx, workspaceID)- } else {- subscription = s.loadSubscriptionFromDB(ctx, workspaceID)- }+ subscription := s.loadSubscriptionFromDB(ctx, workspaceID)// Only cache non-free subscriptions. Free plan may be a transient failure// (e.g. DB not ready during startup), and caching it would mask the real@@ -259,53 +270,6 @@ func (s *LicenseService) loadSubscriptionFromDB(ctx context.Context, workspaceIDreturn subscription}-// loadSubscriptionFromPurchase loads subscription from the subscription table (SaaS mode).-func (s *LicenseService) loadSubscriptionFromPurchase(ctx context.Context, workspaceID string) *v1pb.Subscription {- sub, err := s.store.GetSubscriptionByWorkspace(ctx, workspaceID)- if err != nil {- slog.Debug("failed to get subscription from purchase table", log.BBError(err))- return defaultFreeSubscription- }- if sub == nil || sub.Payload == nil {- return defaultFreeSubscription- }-- payload := sub.Payload- if payload.Status != storepb.SubscriptionPayload_ACTIVE {- return defaultFreeSubscription- }-- subscription := &v1pb.Subscription{- Plan: convertStorePlanToV1(payload.Plan),- Seats: payload.Seat,- Instances: payload.InstanceCount,- ActiveInstances: payload.InstanceCount,- }- if payload.ExpiresAt != nil {- subscription.ExpiresTime = payload.ExpiresAt- }-- if isExpired(subscription) {- return &v1pb.Subscription{- Plan: v1pb.PlanType_FREE,- ExpiresTime: subscription.ExpiresTime,- }- }-- return subscription-}--func convertStorePlanToV1(plan storepb.SubscriptionPayload_Plan) v1pb.PlanType {- switch plan {- case storepb.SubscriptionPayload_TEAM:- return v1pb.PlanType_TEAM- case storepb.SubscriptionPayload_ENTERPRISE:- return v1pb.PlanType_ENTERPRISE- default:- return v1pb.PlanType_FREE- }-}-func isExpired(sub *v1pb.Subscription) bool {if sub == nil {return false@@ -416,6 +380,43 @@ func (s *LicenseService) StoreLicense(ctx context.Context, workspaceID string, lreturn nil}+// LicenseParams contains the business fields for license generation.+type LicenseParams struct {+ Plan string+ Seats int+ Instances int+ WorkspaceID string+ ExpiresAt time.Time // zero value means no expiration+}++// CreateLicense signs a new license JWT from business params.+// Only available when private key is configured (SaaS mode).+// Handles JWT plumbing (issuer, audience, kid) internally.+func (s *LicenseService) CreateLicense(params *LicenseParams) (string, error) {+ if s.config.PrivateKey == nil {+ return "", errors.New("license signing not available: private key not configured")+ }++ c := &Claims{+ Plan: params.Plan,+ Seats: params.Seats,+ ActiveInstances: params.Instances,+ Instances: params.Instances,+ WorkspaceID: params.WorkspaceID,+ }+ c.Issuer = s.config.Issuer+ c.Audience = jwt.ClaimStrings{s.config.Audience}+ c.IssuedAt = jwt.NewNumericDate(time.Now())+ c.Subject = params.WorkspaceID+ if !params.ExpiresAt.IsZero() {+ c.ExpiresAt = jwt.NewNumericDate(params.ExpiresAt)+ }++ token := jwt.NewWithClaims(jwt.SigningMethodRS256, c)+ token.Header["kid"] = s.config.Version+ return token.SignedString(s.config.PrivateKey)+}+// InvalidateCache removes the cached subscription for a workspace,// forcing the next LoadSubscription call to reload from the database.func (s *LicenseService) InvalidateCache(workspaceID string) {@@ -448,7 +449,8 @@ func (s *LicenseService) GetAuditLogRetentionCutoff(ctx context.Context, workspaif days <= 0 {return nil // Either no access (0) or unlimited (-1)}- return new(time.Now().AddDate(0, 0, -days))+ cutoff := time.Now().AddDate(0, 0, -days)+ return &cutoff}// CountActiveReplicas returns the count of active replicas.@@ -501,7 +503,7 @@ func (s *LicenseService) CheckReplicaLimit(ctx context.Context) error {}func (s *LicenseService) parseLicense(license, workspaceID string) (*v1pb.Subscription, error) {- claim := &claims{}+ claim := &Claims{}token, err := jwt.ParseWithClaims(license, claim, func(token *jwt.Token) (any, error) {if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {return nil, common.Errorf(common.Invalid, "unexpected signing method: %v", token.Header["alg"])diff --git a/backend/enterprise/pricing/plan.go b/backend/enterprise/pricing/plan.goindex c26b2c921d..8c1add5564 100644--- a/backend/enterprise/pricing/plan.go+++ b/backend/enterprise/pricing/plan.go@@ -3,8 +3,16 @@ package pricingimport (storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1")+// BillingMethodConfig defines a billing method with optional discount.+type BillingMethodConfig struct {+ Interval storepb.SubscriptionPayload_BillingInterval+ PromotionCode string // Stripe promotion code (e.g., "FIRSTMONTH90")+ Discount *v1pb.PurchaseDiscount+}+// PlanLimitConfig defines pricing and limits for a plan.type PlanLimitConfig struct {Plan storepb.SubscriptionPayload_Plan@@ -13,6 +21,7 @@ type PlanLimitConfig struct {MaximumSeatCount int32 // -1 = unlimitedPricePerSeatPerMonth int64 // USD centsInstanceCount int32 // fixed instance count included in the plan+ BillingMethods []BillingMethodConfig}var planLimits = map[storepb.SubscriptionPayload_Plan]*PlanLimitConfig{@@ -23,6 +32,19 @@ var planLimits = map[storepb.SubscriptionPayload_Plan]*PlanLimitConfig{MaximumSeatCount: -1, // unlimitedPricePerSeatPerMonth: 2000, // $20/user/monthInstanceCount: 10,+ BillingMethods: []BillingMethodConfig{+ {+ Interval: storepb.SubscriptionPayload_MONTH,+ PromotionCode: "FISRTMONTH90",+ Discount: &v1pb.PurchaseDiscount{+ Type: v1pb.PurchaseDiscount_PERCENTAGE_OFF,+ Value: 90,+ },+ },+ {+ Interval: storepb.SubscriptionPayload_YEAR,+ },+ },},storepb.SubscriptionPayload_ENTERPRISE: {Plan: storepb.SubscriptionPayload_ENTERPRISE,diff --git a/backend/enterprise/pricing/pricing.go b/backend/enterprise/pricing/pricing.goindex 820683a26c..2f9039c9fc 100644--- a/backend/enterprise/pricing/pricing.go+++ b/backend/enterprise/pricing/pricing.go@@ -62,6 +62,16 @@ func (m *PriceModel) GetStripeInterval() string {return "month"}+// GetPromotionCode returns the promotion code for the current interval, or empty string.+func (m *PriceModel) GetPromotionCode() string {+ for _, bm := range m.Plan.BillingMethods {+ if bm.Interval == m.Interval {+ return bm.PromotionCode+ }+ }+ return ""+}+// GetPlanText returns a display name for the plan.func (m *PriceModel) GetPlanText() string {switch m.Plan.Plan {diff --git a/backend/generated-go/store/subscription.pb.go b/backend/generated-go/store/subscription.pb.goindex 77a5c3db92..c881841d55 100644--- a/backend/generated-go/store/subscription.pb.go+++ b/backend/generated-go/store/subscription.pb.go@@ -26,27 +26,24 @@ type SubscriptionPayload_Status int32const (SubscriptionPayload_STATUS_UNSPECIFIED SubscriptionPayload_Status = 0- SubscriptionPayload_PENDING SubscriptionPayload_Status = 1- SubscriptionPayload_ACTIVE SubscriptionPayload_Status = 2- SubscriptionPayload_PAUSED SubscriptionPayload_Status = 3- SubscriptionPayload_CANCELED SubscriptionPayload_Status = 4+ SubscriptionPayload_ACTIVE SubscriptionPayload_Status = 1+ SubscriptionPayload_PAUSED SubscriptionPayload_Status = 2+ SubscriptionPayload_CANCELED SubscriptionPayload_Status = 3)// Enum value maps for SubscriptionPayload_Status.var (SubscriptionPayload_Status_name = map[int32]string{0: "STATUS_UNSPECIFIED",- 1: "PENDING",- 2: "ACTIVE",- 3: "PAUSED",- 4: "CANCELED",+ 1: "ACTIVE",+ 2: "PAUSED",+ 3: "CANCELED",}SubscriptionPayload_Status_value = map[string]int32{"STATUS_UNSPECIFIED": 0,- "PENDING": 1,- "ACTIVE": 2,- "PAUSED": 3,- "CANCELED": 4,+ "ACTIVE": 1,+ "PAUSED": 2,+ "CANCELED": 3,})@@ -292,7 +289,7 @@ var File_store_subscription_proto protoreflect.FileDescriptorconst file_store_subscription_proto_rawDesc = "" +"\n" +- "\x18store/subscription.proto\x12\x0ebytebase.store\x1a\x1fgoogle/protobuf/timestamp.proto\"\xd4\x05\n" ++ "\x18store/subscription.proto\x12\x0ebytebase.store\x1a\x1fgoogle/protobuf/timestamp.proto\"\xc7\x05\n" +"\x13SubscriptionPayload\x12B\n" +"\x06status\x18\x01 \x01(\x0e2*.bytebase.store.SubscriptionPayload.StatusR\x06status\x129\n" +"\n" +@@ -304,15 +301,14 @@ const file_store_subscription_proto_rawDesc = "" +"\x04seat\x18\x06 \x01(\x05R\x04seat\x12%\n" +"\x0einstance_count\x18\a \x01(\x05R\rinstanceCount\x124\n" +"\x16stripe_subscription_id\x18\b \x01(\tR\x14stripeSubscriptionId\x12,\n" +- "\x12stripe_customer_id\x18\t \x01(\tR\x10stripeCustomerId\"S\n" ++ "\x12stripe_customer_id\x18\t \x01(\tR\x10stripeCustomerId\"F\n" +"\x06Status\x12\x16\n" +- "\x12STATUS_UNSPECIFIED\x10\x00\x12\v\n" +- "\aPENDING\x10\x01\x12\n" ++ "\x12STATUS_UNSPECIFIED\x10\x00\x12\n" +"\n" +- "\x06ACTIVE\x10\x02\x12\n" ++ "\x06ACTIVE\x10\x01\x12\n" +"\n" +- "\x06PAUSED\x10\x03\x12\f\n" +- "\bCANCELED\x10\x04\"6\n" ++ "\x06PAUSED\x10\x02\x12\f\n" ++ "\bCANCELED\x10\x03\"6\n" +"\x04Plan\x12\x14\n" +"\x10PLAN_UNSPECIFIED\x10\x00\x12\b\n" +"\x04TEAM\x10\x01\x12\x0e\n" +diff --git a/backend/generated-go/v1/subscription_service.pb.go b/backend/generated-go/v1/subscription_service.pb.goindex ac752ea0d0..222e132df2 100644--- a/backend/generated-go/v1/subscription_service.pb.go+++ b/backend/generated-go/v1/subscription_service.pb.go@@ -435,6 +435,58 @@ func (PurchasePlanAdditional_Type) EnumDescriptor() ([]byte, []int) {return file_v1_subscription_service_proto_rawDescGZIP(), []int{11, 0}}+type PurchaseDiscount_Type int32++const (+ PurchaseDiscount_TYPE_UNSPECIFIED PurchaseDiscount_Type = 0+ PurchaseDiscount_PERCENTAGE_OFF PurchaseDiscount_Type = 1+ PurchaseDiscount_FIXED_MONTH_OFF PurchaseDiscount_Type = 2+ PurchaseDiscount_FIXED_PRICE_OFF PurchaseDiscount_Type = 3+)++// Enum value maps for PurchaseDiscount_Type.+var (+ PurchaseDiscount_Type_name = map[int32]string{+ 0: "TYPE_UNSPECIFIED",+ 1: "PERCENTAGE_OFF",+ 2: "FIXED_MONTH_OFF",+ 3: "FIXED_PRICE_OFF",+ }+ PurchaseDiscount_Type_value = map[string]int32{+ "TYPE_UNSPECIFIED": 0,+ "PERCENTAGE_OFF": 1,+ "FIXED_MONTH_OFF": 2,+ "FIXED_PRICE_OFF": 3,+ }+)++func (x PurchaseDiscount_Type) Enum() *PurchaseDiscount_Type {+ p := new(PurchaseDiscount_Type)+ *p = x+ return p+}++func (x PurchaseDiscount_Type) String() string {+ return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))+}++func (PurchaseDiscount_Type) Descriptor() protoreflect.EnumDescriptor {+ return file_v1_subscription_service_proto_enumTypes[4].Descriptor()+}++func (PurchaseDiscount_Type) Type() protoreflect.EnumType {+ return &file_v1_subscription_service_proto_enumTypes[4]+}++func (x PurchaseDiscount_Type) Number() protoreflect.EnumNumber {+ return protoreflect.EnumNumber(x)+}++// Deprecated: Use PurchaseDiscount_Type.Descriptor instead.+func (PurchaseDiscount_Type) EnumDescriptor() ([]byte, []int) {+ return file_v1_subscription_service_proto_rawDescGZIP(), []int{13, 0}+}+type GetSubscriptionRequest struct {state protoimpl.MessageState `protogen:"open.v1"`unknownFields protoimpl.UnknownFields@@ -471,30 +523,27 @@ func (*GetSubscriptionRequest) Descriptor() ([]byte, []int) {return file_v1_subscription_service_proto_rawDescGZIP(), []int{0}}-type UpdateSubscriptionRequest struct {- state protoimpl.MessageState `protogen:"open.v1"`- License string `protobuf:"bytes,1,opt,name=license,proto3" json:"license,omitempty"`- // If set to true, and the subscription is not found, a new subscription will be created.- // In this situation, `update_mask` is ignored.- AllowMissing bool `protobuf:"varint,2,opt,name=allow_missing,json=allowMissing,proto3" json:"allow_missing,omitempty"`+type UploadLicenseRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ License string `protobuf:"bytes,1,opt,name=license,proto3" json:"license,omitempty"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache}-func (x *UpdateSubscriptionRequest) Reset() {- *x = UpdateSubscriptionRequest{}+func (x *UploadLicenseRequest) Reset() {+ *x = UploadLicenseRequest{}mi := &file_v1_subscription_service_proto_msgTypes[1]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}-func (x *UpdateSubscriptionRequest) String() string {+func (x *UploadLicenseRequest) String() string {return protoimpl.X.MessageStringOf(x)}-func (*UpdateSubscriptionRequest) ProtoMessage() {}+func (*UploadLicenseRequest) ProtoMessage() {}-func (x *UpdateSubscriptionRequest) ProtoReflect() protoreflect.Message {+func (x *UploadLicenseRequest) ProtoReflect() protoreflect.Message {mi := &file_v1_subscription_service_proto_msgTypes[1]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))@@ -506,25 +555,18 @@ func (x *UpdateSubscriptionRequest) ProtoReflect() protoreflect.Message {return mi.MessageOf(x)}-// Deprecated: Use UpdateSubscriptionRequest.ProtoReflect.Descriptor instead.-func (*UpdateSubscriptionRequest) Descriptor() ([]byte, []int) {+// Deprecated: Use UploadLicenseRequest.ProtoReflect.Descriptor instead.+func (*UploadLicenseRequest) Descriptor() ([]byte, []int) {return file_v1_subscription_service_proto_rawDescGZIP(), []int{1}}-func (x *UpdateSubscriptionRequest) GetLicense() string {+func (x *UploadLicenseRequest) GetLicense() string {if x != nil {return x.License}return ""}-func (x *UpdateSubscriptionRequest) GetAllowMissing() bool {- if x != nil {- return x.AllowMissing- }- return false-}-type CreatePurchaseRequest struct {state protoimpl.MessageState `protogen:"open.v1"`Plan PlanType `protobuf:"varint,1,opt,name=plan,proto3,enum=bytebase.v1.PlanType" json:"plan,omitempty"`@@ -585,28 +627,31 @@ func (x *CreatePurchaseRequest) GetSeats() int32 {return 0}-type CreatePurchaseResponse struct {+type PurchaseResponse struct {state protoimpl.MessageState `protogen:"open.v1"`- // Stripe Checkout URL for the user to complete payment.- PaymentUrl string `protobuf:"bytes,1,opt,name=payment_url,json=paymentUrl,proto3" json:"payment_url,omitempty"`+ // If set, redirect to this Stripe Checkout URL.+ // If empty, the update was applied directly using the existing payment method.+ PaymentUrl string `protobuf:"bytes,1,opt,name=payment_url,json=paymentUrl,proto3" json:"payment_url,omitempty"`+ // Stripe Checkout Session ID. Used to verify the session after redirect.+ SessionId string `protobuf:"bytes,2,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache}-func (x *CreatePurchaseResponse) Reset() {- *x = CreatePurchaseResponse{}+func (x *PurchaseResponse) Reset() {+ *x = PurchaseResponse{}mi := &file_v1_subscription_service_proto_msgTypes[3]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}-func (x *CreatePurchaseResponse) String() string {+func (x *PurchaseResponse) String() string {return protoimpl.X.MessageStringOf(x)}-func (*CreatePurchaseResponse) ProtoMessage() {}+func (*PurchaseResponse) ProtoMessage() {}-func (x *CreatePurchaseResponse) ProtoReflect() protoreflect.Message {+func (x *PurchaseResponse) ProtoReflect() protoreflect.Message {mi := &file_v1_subscription_service_proto_msgTypes[3]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))@@ -618,42 +663,46 @@ func (x *CreatePurchaseResponse) ProtoReflect() protoreflect.Message {return mi.MessageOf(x)}-// Deprecated: Use CreatePurchaseResponse.ProtoReflect.Descriptor instead.-func (*CreatePurchaseResponse) Descriptor() ([]byte, []int) {+// Deprecated: Use PurchaseResponse.ProtoReflect.Descriptor instead.+func (*PurchaseResponse) Descriptor() ([]byte, []int) {return file_v1_subscription_service_proto_rawDescGZIP(), []int{3}}-func (x *CreatePurchaseResponse) GetPaymentUrl() string {+func (x *PurchaseResponse) GetPaymentUrl() string {if x != nil {return x.PaymentUrl}return ""}-type UpdatePurchaseRequest struct {+func (x *PurchaseResponse) GetSessionId() string {+ if x != nil {+ return x.SessionId+ }+ return ""+}++type VerifyCheckoutSessionRequest struct {state protoimpl.MessageState `protogen:"open.v1"`- Plan PlanType `protobuf:"varint,1,opt,name=plan,proto3,enum=bytebase.v1.PlanType" json:"plan,omitempty"`- Interval BillingInterval `protobuf:"varint,2,opt,name=interval,proto3,enum=bytebase.v1.BillingInterval" json:"interval,omitempty"`- Seats int32 `protobuf:"varint,3,opt,name=seats,proto3" json:"seats,omitempty"`- Etag string `protobuf:"bytes,4,opt,name=etag,proto3" json:"etag,omitempty"`+ SessionId string `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache}-func (x *UpdatePurchaseRequest) Reset() {- *x = UpdatePurchaseRequest{}+func (x *VerifyCheckoutSessionRequest) Reset() {+ *x = VerifyCheckoutSessionRequest{}mi := &file_v1_subscription_service_proto_msgTypes[4]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}-func (x *UpdatePurchaseRequest) String() string {+func (x *VerifyCheckoutSessionRequest) String() string {return protoimpl.X.MessageStringOf(x)}-func (*UpdatePurchaseRequest) ProtoMessage() {}+func (*VerifyCheckoutSessionRequest) ProtoMessage() {}-func (x *UpdatePurchaseRequest) ProtoReflect() protoreflect.Message {+func (x *VerifyCheckoutSessionRequest) ProtoReflect() protoreflect.Message {mi := &file_v1_subscription_service_proto_msgTypes[4]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))@@ -665,62 +714,40 @@ func (x *UpdatePurchaseRequest) ProtoReflect() protoreflect.Message {return mi.MessageOf(x)}-// Deprecated: Use UpdatePurchaseRequest.ProtoReflect.Descriptor instead.-func (*UpdatePurchaseRequest) Descriptor() ([]byte, []int) {+// Deprecated: Use VerifyCheckoutSessionRequest.ProtoReflect.Descriptor instead.+func (*VerifyCheckoutSessionRequest) Descriptor() ([]byte, []int) {return file_v1_subscription_service_proto_rawDescGZIP(), []int{4}}-func (x *UpdatePurchaseRequest) GetPlan() PlanType {+func (x *VerifyCheckoutSessionRequest) GetSessionId() string {if x != nil {- return x.Plan- }- return PlanType_PLAN_TYPE_UNSPECIFIED-}--func (x *UpdatePurchaseRequest) GetInterval() BillingInterval {- if x != nil {- return x.Interval- }- return BillingInterval_BILLING_INTERVAL_UNSPECIFIED-}--func (x *UpdatePurchaseRequest) GetSeats() int32 {- if x != nil {- return x.Seats- }- return 0-}--func (x *UpdatePurchaseRequest) GetEtag() string {- if x != nil {- return x.Etag+ return x.SessionId}return ""}-type UpdatePurchaseResponse struct {+type VerifyCheckoutSessionResponse struct {state protoimpl.MessageState `protogen:"open.v1"`- // If set, redirect to this Stripe Checkout URL.- // If empty, the update was applied directly using the existing payment method.- PaymentUrl string `protobuf:"bytes,1,opt,name=payment_url,json=paymentUrl,proto3" json:"payment_url,omitempty"`+ // Stripe Checkout Session status: "complete", "expired", or "open".+ Status string `protobuf:"bytes,1,opt,name=status,proto3" json:"status,omitempty"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache}-func (x *UpdatePurchaseResponse) Reset() {- *x = UpdatePurchaseResponse{}+func (x *VerifyCheckoutSessionResponse) Reset() {+ *x = VerifyCheckoutSessionResponse{}mi := &file_v1_subscription_service_proto_msgTypes[5]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}-func (x *UpdatePurchaseResponse) String() string {+func (x *VerifyCheckoutSessionResponse) String() string {return protoimpl.X.MessageStringOf(x)}-func (*UpdatePurchaseResponse) ProtoMessage() {}+func (*VerifyCheckoutSessionResponse) ProtoMessage() {}-func (x *UpdatePurchaseResponse) ProtoReflect() protoreflect.Message {+func (x *VerifyCheckoutSessionResponse) ProtoReflect() protoreflect.Message {mi := &file_v1_subscription_service_proto_msgTypes[5]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))@@ -732,38 +759,42 @@ func (x *UpdatePurchaseResponse) ProtoReflect() protoreflect.Message {return mi.MessageOf(x)}-// Deprecated: Use UpdatePurchaseResponse.ProtoReflect.Descriptor instead.-func (*UpdatePurchaseResponse) Descriptor() ([]byte, []int) {+// Deprecated: Use VerifyCheckoutSessionResponse.ProtoReflect.Descriptor instead.+func (*VerifyCheckoutSessionResponse) Descriptor() ([]byte, []int) {return file_v1_subscription_service_proto_rawDescGZIP(), []int{5}}-func (x *UpdatePurchaseResponse) GetPaymentUrl() string {+func (x *VerifyCheckoutSessionResponse) GetStatus() string {if x != nil {- return x.PaymentUrl+ return x.Status}return ""}-type CancelPurchaseRequest struct {+type UpdatePurchaseRequest struct {state protoimpl.MessageState `protogen:"open.v1"`+ Plan PlanType `protobuf:"varint,1,opt,name=plan,proto3,enum=bytebase.v1.PlanType" json:"plan,omitempty"`+ Interval BillingInterval `protobuf:"varint,2,opt,name=interval,proto3,enum=bytebase.v1.BillingInterval" json:"interval,omitempty"`+ Seats int32 `protobuf:"varint,3,opt,name=seats,proto3" json:"seats,omitempty"`+ Etag string `protobuf:"bytes,4,opt,name=etag,proto3" json:"etag,omitempty"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache}-func (x *CancelPurchaseRequest) Reset() {- *x = CancelPurchaseRequest{}+func (x *UpdatePurchaseRequest) Reset() {+ *x = UpdatePurchaseRequest{}mi := &file_v1_subscription_service_proto_msgTypes[6]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}-func (x *CancelPurchaseRequest) String() string {+func (x *UpdatePurchaseRequest) String() string {return protoimpl.X.MessageStringOf(x)}-func (*CancelPurchaseRequest) ProtoMessage() {}+func (*UpdatePurchaseRequest) ProtoMessage() {}-func (x *CancelPurchaseRequest) ProtoReflect() protoreflect.Message {+func (x *UpdatePurchaseRequest) ProtoReflect() protoreflect.Message {mi := &file_v1_subscription_service_proto_msgTypes[6]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))@@ -775,31 +806,59 @@ func (x *CancelPurchaseRequest) ProtoReflect() protoreflect.Message {return mi.MessageOf(x)}-// Deprecated: Use CancelPurchaseRequest.ProtoReflect.Descriptor instead.-func (*CancelPurchaseRequest) Descriptor() ([]byte, []int) {+// Deprecated: Use UpdatePurchaseRequest.ProtoReflect.Descriptor instead.+func (*UpdatePurchaseRequest) Descriptor() ([]byte, []int) {return file_v1_subscription_service_proto_rawDescGZIP(), []int{6}}-type CancelPurchaseResponse struct {+func (x *UpdatePurchaseRequest) GetPlan() PlanType {+ if x != nil {+ return x.Plan+ }+ return PlanType_PLAN_TYPE_UNSPECIFIED+}++func (x *UpdatePurchaseRequest) GetInterval() BillingInterval {+ if x != nil {+ return x.Interval+ }+ return BillingInterval_BILLING_INTERVAL_UNSPECIFIED+}++func (x *UpdatePurchaseRequest) GetSeats() int32 {+ if x != nil {+ return x.Seats+ }+ return 0+}++func (x *UpdatePurchaseRequest) GetEtag() string {+ if x != nil {+ return x.Etag+ }+ return ""+}++type CancelPurchaseRequest struct {state protoimpl.MessageState `protogen:"open.v1"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache}-func (x *CancelPurchaseResponse) Reset() {- *x = CancelPurchaseResponse{}+func (x *CancelPurchaseRequest) Reset() {+ *x = CancelPurchaseRequest{}mi := &file_v1_subscription_service_proto_msgTypes[7]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}-func (x *CancelPurchaseResponse) String() string {+func (x *CancelPurchaseRequest) String() string {return protoimpl.X.MessageStringOf(x)}-func (*CancelPurchaseResponse) ProtoMessage() {}+func (*CancelPurchaseRequest) ProtoMessage() {}-func (x *CancelPurchaseResponse) ProtoReflect() protoreflect.Message {+func (x *CancelPurchaseRequest) ProtoReflect() protoreflect.Message {mi := &file_v1_subscription_service_proto_msgTypes[7]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))@@ -811,8 +870,8 @@ func (x *CancelPurchaseResponse) ProtoReflect() protoreflect.Message {return mi.MessageOf(x)}-// Deprecated: Use CancelPurchaseResponse.ProtoReflect.Descriptor instead.-func (*CancelPurchaseResponse) Descriptor() ([]byte, []int) {+// Deprecated: Use CancelPurchaseRequest.ProtoReflect.Descriptor instead.+func (*CancelPurchaseRequest) Descriptor() ([]byte, []int) {return file_v1_subscription_service_proto_rawDescGZIP(), []int{7}}@@ -859,9 +918,11 @@ type PaymentInfo struct {PeriodStart string `protobuf:"bytes,3,opt,name=period_start,json=periodStart,proto3" json:"period_start,omitempty"`PeriodEnd string `protobuf:"bytes,4,opt,name=period_end,json=periodEnd,proto3" json:"period_end,omitempty"`// Stripe Billing Portal URL for invoice management.- InvoiceUrl string `protobuf:"bytes,5,opt,name=invoice_url,json=invoiceUrl,proto3" json:"invoice_url,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache+ InvoiceUrl string `protobuf:"bytes,5,opt,name=invoice_url,json=invoiceUrl,proto3" json:"invoice_url,omitempty"`+ // Whether the subscription is scheduled to cancel at the end of the current billing period.+ CancelAtPeriodEnd bool `protobuf:"varint,6,opt,name=cancel_at_period_end,json=cancelAtPeriodEnd,proto3" json:"cancel_at_period_end,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache}func (x *PaymentInfo) Reset() {@@ -929,6 +990,13 @@ func (x *PaymentInfo) GetInvoiceUrl() string {return ""}+func (x *PaymentInfo) GetCancelAtPeriodEnd() bool {+ if x != nil {+ return x.CancelAtPeriodEnd+ }+ return false+}+type PurchasePlan struct {state protoimpl.MessageState `protogen:"open.v1"`Type PlanType `protobuf:"varint,1,opt,name=type,proto3,enum=bytebase.v1.PlanType" json:"type,omitempty"`@@ -1129,8 +1197,8 @@ func (x *PurchaseBillingMethod) GetDiscount() *PurchaseDiscount {type PurchaseDiscount struct {state protoimpl.MessageState `protogen:"open.v1"`- Description string `protobuf:"bytes,1,opt,name=description,proto3" json:"description,omitempty"`- PromotionCode string `protobuf:"bytes,2,opt,name=promotion_code,json=promotionCode,proto3" json:"promotion_code,omitempty"`+ Type PurchaseDiscount_Type `protobuf:"varint,1,opt,name=type,proto3,enum=bytebase.v1.PurchaseDiscount_Type" json:"type,omitempty"`+ Value int32 `protobuf:"varint,2,opt,name=value,proto3" json:"value,omitempty"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache}@@ -1165,18 +1233,18 @@ func (*PurchaseDiscount) Descriptor() ([]byte, []int) {return file_v1_subscription_service_proto_rawDescGZIP(), []int{13}}-func (x *PurchaseDiscount) GetDescription() string {+func (x *PurchaseDiscount) GetType() PurchaseDiscount_Type {if x != nil {- return x.Description+ return x.Type}- return ""+ return PurchaseDiscount_TYPE_UNSPECIFIED}-func (x *PurchaseDiscount) GetPromotionCode() string {+func (x *PurchaseDiscount) GetValue() int32 {if x != nil {- return x.PromotionCode+ return x.Value}- return ""+ return 0}type ListPurchasePlansRequest struct {@@ -1269,7 +1337,9 @@ type Subscription struct {Trialing bool `protobuf:"varint,6,opt,name=trialing,proto3" json:"trialing,omitempty"`OrgName string `protobuf:"bytes,7,opt,name=org_name,json=orgName,proto3" json:"org_name,omitempty"`// Whether high availability (multiple replicas) is enabled.- Ha bool `protobuf:"varint,8,opt,name=ha,proto3" json:"ha,omitempty"`+ Ha bool `protobuf:"varint,8,opt,name=ha,proto3" json:"ha,omitempty"`+ // Etag for optimistic concurrency on purchase updates. Only set in SaaS mode.+ Etag string `protobuf:"bytes,9,opt,name=etag,proto3" json:"etag,omitempty"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache}@@ -1360,6 +1430,13 @@ func (x *Subscription) GetHa() bool {return false}+func (x *Subscription) GetEtag() string {+ if x != nil {+ return x.Etag+ }+ return ""+}+// PlanConfig represents the configuration for all plans loaded from plan.yamltype PlanConfig struct {state protoimpl.MessageState `protogen:"open.v1"`@@ -1487,28 +1564,30 @@ var File_v1_subscription_service_proto protoreflect.FileDescriptorconst file_v1_subscription_service_proto_rawDesc = "" +"\n" +"\x1dv1/subscription_service.proto\x12\vbytebase.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x13v1/annotation.proto\"\x18\n" +- "\x16GetSubscriptionRequest\"Z\n" +- "\x19UpdateSubscriptionRequest\x12\x18\n" +- "\alicense\x18\x01 \x01(\tR\alicense\x12#\n" +- "\rallow_missing\x18\x02 \x01(\bR\fallowMissing\"\x92\x01\n" ++ "\x16GetSubscriptionRequest\"0\n" ++ "\x14UploadLicenseRequest\x12\x18\n" ++ "\alicense\x18\x01 \x01(\tR\alicense\"\x92\x01\n" +"\x15CreatePurchaseRequest\x12)\n" +"\x04plan\x18\x01 \x01(\x0e2\x15.bytebase.v1.PlanTypeR\x04plan\x128\n" +"\binterval\x18\x02 \x01(\x0e2\x1c.bytebase.v1.BillingIntervalR\binterval\x12\x14\n" +- "\x05seats\x18\x03 \x01(\x05R\x05seats\"9\n" +- "\x16CreatePurchaseResponse\x12\x1f\n" ++ "\x05seats\x18\x03 \x01(\x05R\x05seats\"R\n" ++ "\x10PurchaseResponse\x12\x1f\n" +"\vpayment_url\x18\x01 \x01(\tR\n" +- "paymentUrl\"\xa6\x01\n" ++ "paymentUrl\x12\x1d\n" ++ "\n" ++ "session_id\x18\x02 \x01(\tR\tsessionId\"=\n" ++ "\x1cVerifyCheckoutSessionRequest\x12\x1d\n" ++ "\n" ++ "session_id\x18\x01 \x01(\tR\tsessionId\"7\n" ++ "\x1dVerifyCheckoutSessionResponse\x12\x16\n" ++ "\x06status\x18\x01 \x01(\tR\x06status\"\xa6\x01\n" +"\x15UpdatePurchaseRequest\x12)\n" +"\x04plan\x18\x01 \x01(\x0e2\x15.bytebase.v1.PlanTypeR\x04plan\x128\n" +"\binterval\x18\x02 \x01(\x0e2\x1c.bytebase.v1.BillingIntervalR\binterval\x12\x14\n" +"\x05seats\x18\x03 \x01(\x05R\x05seats\x12\x12\n" +- "\x04etag\x18\x04 \x01(\tR\x04etag\"9\n" +- "\x16UpdatePurchaseResponse\x12\x1f\n" +- "\vpayment_url\x18\x01 \x01(\tR\n" +- "paymentUrl\"\x17\n" +- "\x15CancelPurchaseRequest\"\x18\n" +- "\x16CancelPurchaseResponse\"\x17\n" +- "\x15GetPaymentInfoRequest\"\xad\x01\n" ++ "\x04etag\x18\x04 \x01(\tR\x04etag\"\x17\n" ++ "\x15CancelPurchaseRequest\"\x17\n" ++ "\x15GetPaymentInfoRequest\"\xde\x01\n" +"\vPaymentInfo\x12\x1f\n" +"\vtotal_price\x18\x01 \x01(\tR\n" +"totalPrice\x12\x1a\n" +@@ -1517,7 +1596,8 @@ const file_v1_subscription_service_proto_rawDesc = "" +"\n" +"period_end\x18\x04 \x01(\tR\tperiodEnd\x12\x1f\n" +"\vinvoice_url\x18\x05 \x01(\tR\n" +- "invoiceUrl\"\x81\x02\n" ++ "invoiceUrl\x12/\n" ++ "\x14cancel_at_period_end\x18\x06 \x01(\bR\x11cancelAtPeriodEnd\"\x81\x02\n" +"\fPurchasePlan\x12)\n" +"\x04type\x18\x01 \x01(\x0e2\x15.bytebase.v1.PlanTypeR\x04type\x122\n" +"\x15self_service_purchase\x18\x02 \x01(\bR\x13selfServicePurchase\x12E\n" +@@ -1536,13 +1616,18 @@ const file_v1_subscription_service_proto_rawDesc = "" +"\x04USER\x10\x01\"\x8c\x01\n" +"\x15PurchaseBillingMethod\x128\n" +"\binterval\x18\x01 \x01(\x0e2\x1c.bytebase.v1.BillingIntervalR\binterval\x129\n" +- "\bdiscount\x18\x02 \x01(\v2\x1d.bytebase.v1.PurchaseDiscountR\bdiscount\"[\n" +- "\x10PurchaseDiscount\x12 \n" +- "\vdescription\x18\x01 \x01(\tR\vdescription\x12%\n" +- "\x0epromotion_code\x18\x02 \x01(\tR\rpromotionCode\"\x1a\n" ++ "\bdiscount\x18\x02 \x01(\v2\x1d.bytebase.v1.PurchaseDiscountR\bdiscount\"\xbc\x01\n" ++ "\x10PurchaseDiscount\x126\n" ++ "\x04type\x18\x01 \x01(\x0e2\".bytebase.v1.PurchaseDiscount.TypeR\x04type\x12\x14\n" ++ "\x05value\x18\x02 \x01(\x05R\x05value\"Z\n" ++ "\x04Type\x12\x14\n" ++ "\x10TYPE_UNSPECIFIED\x10\x00\x12\x12\n" ++ "\x0ePERCENTAGE_OFF\x10\x01\x12\x13\n" ++ "\x0fFIXED_MONTH_OFF\x10\x02\x12\x13\n" ++ "\x0fFIXED_PRICE_OFF\x10\x03\"\x1a\n" +"\x18ListPurchasePlansRequest\"L\n" +"\x19ListPurchasePlansResponse\x12/\n" +- "\x05plans\x18\x01 \x03(\v2\x19.bytebase.v1.PurchasePlanR\x05plans\"\xc6\x02\n" ++ "\x05plans\x18\x01 \x03(\v2\x19.bytebase.v1.PurchasePlanR\x05plans\"\xdf\x02\n" +"\fSubscription\x12.\n" +"\x04plan\x18\x01 \x01(\x0e2\x15.bytebase.v1.PlanTypeB\x03\xe0A\x03R\x04plan\x12\x19\n" +"\x05seats\x18\x02 \x01(\x05B\x03\xe0A\x03R\x05seats\x12!\n" +@@ -1551,7 +1636,8 @@ const file_v1_subscription_service_proto_rawDesc = "" +"\fexpires_time\x18\x05 \x01(\v2\x1a.google.protobuf.TimestampB\x03\xe0A\x03R\vexpiresTime\x12\x1f\n" +"\btrialing\x18\x06 \x01(\bB\x03\xe0A\x03R\btrialing\x12\x1e\n" +"\borg_name\x18\a \x01(\tB\x03\xe0A\x03R\aorgName\x12\x13\n" +- "\x02ha\x18\b \x01(\bB\x03\xe0A\x03R\x02ha\"\x87\x01\n" ++ "\x02ha\x18\b \x01(\bB\x03\xe0A\x03R\x02ha\x12\x17\n" ++ "\x04etag\x18\t \x01(\tB\x03\xe0A\x03R\x04etag\"\x87\x01\n" +"\n" +"PlanConfig\x122\n" +"\x05plans\x18\x01 \x03(\v2\x1c.bytebase.v1.PlanLimitConfigR\x05plans\x12E\n" +@@ -1644,15 +1730,16 @@ const file_v1_subscription_service_proto_rawDesc = "" +"\x12FEATURE_CUSTOM_MSA\x10D\x12\x1d\n" +"\x19FEATURE_COMMUNITY_SUPPORT\x10E\x12\x19\n" +"\x15FEATURE_EMAIL_SUPPORT\x10F\x12&\n" +- "\"FEATURE_DEDICATED_SUPPORT_WITH_SLA\x10G2\xaf\b\n" +- "\x13SubscriptionService\x12r\n" +- "\x0fGetSubscription\x12#.bytebase.v1.GetSubscriptionRequest\x1a\x19.bytebase.v1.Subscription\"\x1f\xdaA\x00\x80\xea0\x01\x82\xd3\xe4\x93\x02\x12\x12\x10/v1/subscription\x12\x99\x01\n" +- "\x12UpdateSubscription\x12&.bytebase.v1.UpdateSubscriptionRequest\x1a\x19.bytebase.v1.Subscription\"@\xdaA\x05patch\x8a\xea0\x0fbb.settings.set\x90\xea0\x01\x82\xd3\xe4\x93\x02\x1b:\alicense2\x10/v1/subscription\x12\x9d\x01\n" +- "\x0eCreatePurchase\x12\".bytebase.v1.CreatePurchaseRequest\x1a#.bytebase.v1.CreatePurchaseResponse\"B\x8a\xea0\x16bb.subscription.manage\x90\xea0\x01\x82\xd3\xe4\x93\x02\x1e:\x01*\"\x19/v1/subscription:purchase\x12\xa3\x01\n" +- "\x0eUpdatePurchase\x12\".bytebase.v1.UpdatePurchaseRequest\x1a#.bytebase.v1.UpdatePurchaseResponse\"H\x8a\xea0\x16bb.subscription.manage\x90\xea0\x01\x82\xd3\xe4\x93\x02$:\x01*\"\x1f/v1/subscription:updatePurchase\x12\xa3\x01\n" +- "\x0eCancelPurchase\x12\".bytebase.v1.CancelPurchaseRequest\x1a#.bytebase.v1.CancelPurchaseResponse\"H\x8a\xea0\x16bb.subscription.manage\x90\xea0\x01\x82\xd3\xe4\x93\x02$:\x01*\"\x1f/v1/subscription:cancelPurchase\x12\x92\x01\n" +- "\x0eGetPaymentInfo\x12\".bytebase.v1.GetPaymentInfoRequest\x1a\x18.bytebase.v1.PaymentInfo\"B\x8a\xea0\x16bb.subscription.manage\x90\xea0\x01\x82\xd3\xe4\x93\x02\x1e\x12\x1c/v1/subscription/paymentInfo\x12\x86\x01\n" +- "\x11ListPurchasePlans\x12%.bytebase.v1.ListPurchasePlansRequest\x1a&.bytebase.v1.ListPurchasePlansResponse\"\"\x80\xea0\x01\x82\xd3\xe4\x93\x02\x18\x12\x16/v1/subscription/plansB\xae\x01\n" ++ "\"FEATURE_DEDICATED_SUPPORT_WITH_SLA\x10G2\xd2\t\n" ++ "\x13SubscriptionService\x12n\n" ++ "\x0fGetSubscription\x12#.bytebase.v1.GetSubscriptionRequest\x1a\x19.bytebase.v1.Subscription\"\x1b\xdaA\x00\x82\xd3\xe4\x93\x02\x12\x12\x10/v1/subscription\x12\x90\x01\n" ++ "\rUploadLicense\x12!.bytebase.v1.UploadLicenseRequest\x1a\x19.bytebase.v1.Subscription\"A\x8a\xea0\x16bb.subscription.manage\x90\xea0\x01\x82\xd3\xe4\x93\x02\x1d:\x01*2\x18/v1/subscription/license\x12\x97\x01\n" ++ "\x0eCreatePurchase\x12\".bytebase.v1.CreatePurchaseRequest\x1a\x1d.bytebase.v1.PurchaseResponse\"B\x8a\xea0\x16bb.subscription.manage\x90\xea0\x01\x82\xd3\xe4\x93\x02\x1e:\x01*\"\x19/v1/subscription:purchase\x12\x9d\x01\n" ++ "\x0eUpdatePurchase\x12\".bytebase.v1.UpdatePurchaseRequest\x1a\x1d.bytebase.v1.PurchaseResponse\"H\x8a\xea0\x16bb.subscription.manage\x90\xea0\x01\x82\xd3\xe4\x93\x02$:\x01*\"\x1f/v1/subscription:updatePurchase\x12\x9d\x01\n" ++ "\x0eCancelPurchase\x12\".bytebase.v1.CancelPurchaseRequest\x1a\x1d.bytebase.v1.PurchaseResponse\"H\x8a\xea0\x16bb.subscription.manage\x90\xea0\x01\x82\xd3\xe4\x93\x02$:\x01*\"\x1f/v1/subscription:cancelPurchase\x12\x92\x01\n" ++ "\x0eGetPaymentInfo\x12\".bytebase.v1.GetPaymentInfoRequest\x1a\x18.bytebase.v1.PaymentInfo\"B\x8a\xea0\x16bb.subscription.manage\x90\xea0\x01\x82\xd3\xe4\x93\x02\x1e\x12\x1c/v1/subscription/paymentInfo\x12\xc3\x01\n" ++ "\x15VerifyCheckoutSession\x12).bytebase.v1.VerifyCheckoutSessionRequest\x1a*.bytebase.v1.VerifyCheckoutSessionResponse\"S\x8a\xea0\x16bb.subscription.manage\x90\xea0\x01\x82\xd3\xe4\x93\x02/\x12-/v1/subscription/checkoutSession/{session_id}\x12\x82\x01\n" ++ "\x11ListPurchasePlans\x12%.bytebase.v1.ListPurchasePlansRequest\x1a&.bytebase.v1.ListPurchasePlansResponse\"\x1e\x82\xd3\xe4\x93\x02\x18\x12\x16/v1/subscription/plansB\xae\x01\n" +"\x0fcom.bytebase.v1B\x18SubscriptionServiceProtoP\x01Z4github.com/bytebase/bytebase/backend/generated-go/v1\xa2\x02\x03BXX\xaa\x02\vBytebase.V1\xca\x02\vBytebase\\V1\xe2\x02\x17Bytebase\\V1\\GPBMetadata\xea\x02\fBytebase::V1b\x06proto3"var (@@ -1667,33 +1754,34 @@ func file_v1_subscription_service_proto_rawDescGZIP() []byte {return file_v1_subscription_service_proto_rawDescData}-var file_v1_subscription_service_proto_enumTypes = make([]protoimpl.EnumInfo, 4)+var file_v1_subscription_service_proto_enumTypes = make([]protoimpl.EnumInfo, 5)var file_v1_subscription_service_proto_msgTypes = make([]protoimpl.MessageInfo, 19)var file_v1_subscription_service_proto_goTypes = []any{- (BillingInterval)(0), // 0: bytebase.v1.BillingInterval- (PlanType)(0), // 1: bytebase.v1.PlanType- (PlanFeature)(0), // 2: bytebase.v1.PlanFeature- (PurchasePlanAdditional_Type)(0), // 3: bytebase.v1.PurchasePlanAdditional.Type- (*GetSubscriptionRequest)(nil), // 4: bytebase.v1.GetSubscriptionRequest- (*UpdateSubscriptionRequest)(nil), // 5: bytebase.v1.UpdateSubscriptionRequest- (*CreatePurchaseRequest)(nil), // 6: bytebase.v1.CreatePurchaseRequest- (*CreatePurchaseResponse)(nil), // 7: bytebase.v1.CreatePurchaseResponse- (*UpdatePurchaseRequest)(nil), // 8: bytebase.v1.UpdatePurchaseRequest- (*UpdatePurchaseResponse)(nil), // 9: bytebase.v1.UpdatePurchaseResponse- (*CancelPurchaseRequest)(nil), // 10: bytebase.v1.CancelPurchaseRequest- (*CancelPurchaseResponse)(nil), // 11: bytebase.v1.CancelPurchaseResponse- (*GetPaymentInfoRequest)(nil), // 12: bytebase.v1.GetPaymentInfoRequest- (*PaymentInfo)(nil), // 13: bytebase.v1.PaymentInfo- (*PurchasePlan)(nil), // 14: bytebase.v1.PurchasePlan- (*PurchasePlanAdditional)(nil), // 15: bytebase.v1.PurchasePlanAdditional- (*PurchaseBillingMethod)(nil), // 16: bytebase.v1.PurchaseBillingMethod- (*PurchaseDiscount)(nil), // 17: bytebase.v1.PurchaseDiscount- (*ListPurchasePlansRequest)(nil), // 18: bytebase.v1.ListPurchasePlansRequest- (*ListPurchasePlansResponse)(nil), // 19: bytebase.v1.ListPurchasePlansResponse- (*Subscription)(nil), // 20: bytebase.v1.Subscription- (*PlanConfig)(nil), // 21: bytebase.v1.PlanConfig- (*PlanLimitConfig)(nil), // 22: bytebase.v1.PlanLimitConfig- (*timestamppb.Timestamp)(nil), // 23: google.protobuf.Timestamp+ (BillingInterval)(0), // 0: bytebase.v1.BillingInterval+ (PlanType)(0), // 1: bytebase.v1.PlanType+ (PlanFeature)(0), // 2: bytebase.v1.PlanFeature+ (PurchasePlanAdditional_Type)(0), // 3: bytebase.v1.PurchasePlanAdditional.Type+ (PurchaseDiscount_Type)(0), // 4: bytebase.v1.PurchaseDiscount.Type+ (*GetSubscriptionRequest)(nil), // 5: bytebase.v1.GetSubscriptionRequest+ (*UploadLicenseRequest)(nil), // 6: bytebase.v1.UploadLicenseRequest+ (*CreatePurchaseRequest)(nil), // 7: bytebase.v1.CreatePurchaseRequest+ (*PurchaseResponse)(nil), // 8: bytebase.v1.PurchaseResponse+ (*VerifyCheckoutSessionRequest)(nil), // 9: bytebase.v1.VerifyCheckoutSessionRequest+ (*VerifyCheckoutSessionResponse)(nil), // 10: bytebase.v1.VerifyCheckoutSessionResponse+ (*UpdatePurchaseRequest)(nil), // 11: bytebase.v1.UpdatePurchaseRequest+ (*CancelPurchaseRequest)(nil), // 12: bytebase.v1.CancelPurchaseRequest+ (*GetPaymentInfoRequest)(nil), // 13: bytebase.v1.GetPaymentInfoRequest+ (*PaymentInfo)(nil), // 14: bytebase.v1.PaymentInfo+ (*PurchasePlan)(nil), // 15: bytebase.v1.PurchasePlan+ (*PurchasePlanAdditional)(nil), // 16: bytebase.v1.PurchasePlanAdditional+ (*PurchaseBillingMethod)(nil), // 17: bytebase.v1.PurchaseBillingMethod+ (*PurchaseDiscount)(nil), // 18: bytebase.v1.PurchaseDiscount+ (*ListPurchasePlansRequest)(nil), // 19: bytebase.v1.ListPurchasePlansRequest+ (*ListPurchasePlansResponse)(nil), // 20: bytebase.v1.ListPurchasePlansResponse+ (*Subscription)(nil), // 21: bytebase.v1.Subscription+ (*PlanConfig)(nil), // 22: bytebase.v1.PlanConfig+ (*PlanLimitConfig)(nil), // 23: bytebase.v1.PlanLimitConfig+ (*timestamppb.Timestamp)(nil), // 24: google.protobuf.Timestamp}var file_v1_subscription_service_proto_depIdxs = []int32{1, // 0: bytebase.v1.CreatePurchaseRequest.plan:type_name -> bytebase.v1.PlanType@@ -1701,37 +1789,40 @@ var file_v1_subscription_service_proto_depIdxs = []int32{1, // 2: bytebase.v1.UpdatePurchaseRequest.plan:type_name -> bytebase.v1.PlanType0, // 3: bytebase.v1.UpdatePurchaseRequest.interval:type_name -> bytebase.v1.BillingInterval1, // 4: bytebase.v1.PurchasePlan.type:type_name -> bytebase.v1.PlanType- 15, // 5: bytebase.v1.PurchasePlan.additionals:type_name -> bytebase.v1.PurchasePlanAdditional- 16, // 6: bytebase.v1.PurchasePlan.billing_methods:type_name -> bytebase.v1.PurchaseBillingMethod+ 16, // 5: bytebase.v1.PurchasePlan.additionals:type_name -> bytebase.v1.PurchasePlanAdditional+ 17, // 6: bytebase.v1.PurchasePlan.billing_methods:type_name -> bytebase.v1.PurchaseBillingMethod3, // 7: bytebase.v1.PurchasePlanAdditional.type:type_name -> bytebase.v1.PurchasePlanAdditional.Type0, // 8: bytebase.v1.PurchaseBillingMethod.interval:type_name -> bytebase.v1.BillingInterval- 17, // 9: bytebase.v1.PurchaseBillingMethod.discount:type_name -> bytebase.v1.PurchaseDiscount- 14, // 10: bytebase.v1.ListPurchasePlansResponse.plans:type_name -> bytebase.v1.PurchasePlan- 1, // 11: bytebase.v1.Subscription.plan:type_name -> bytebase.v1.PlanType- 23, // 12: bytebase.v1.Subscription.expires_time:type_name -> google.protobuf.Timestamp- 22, // 13: bytebase.v1.PlanConfig.plans:type_name -> bytebase.v1.PlanLimitConfig- 2, // 14: bytebase.v1.PlanConfig.instance_features:type_name -> bytebase.v1.PlanFeature- 1, // 15: bytebase.v1.PlanLimitConfig.type:type_name -> bytebase.v1.PlanType- 2, // 16: bytebase.v1.PlanLimitConfig.features:type_name -> bytebase.v1.PlanFeature- 4, // 17: bytebase.v1.SubscriptionService.GetSubscription:input_type -> bytebase.v1.GetSubscriptionRequest- 5, // 18: bytebase.v1.SubscriptionService.UpdateSubscription:input_type -> bytebase.v1.UpdateSubscriptionRequest- 6, // 19: bytebase.v1.SubscriptionService.CreatePurchase:input_type -> bytebase.v1.CreatePurchaseRequest- 8, // 20: bytebase.v1.SubscriptionService.UpdatePurchase:input_type -> bytebase.v1.UpdatePurchaseRequest- 10, // 21: bytebase.v1.SubscriptionService.CancelPurchase:input_type -> bytebase.v1.CancelPurchaseRequest- 12, // 22: bytebase.v1.SubscriptionService.GetPaymentInfo:input_type -> bytebase.v1.GetPaymentInfoRequest- 18, // 23: bytebase.v1.SubscriptionService.ListPurchasePlans:input_type -> bytebase.v1.ListPurchasePlansRequest- 20, // 24: bytebase.v1.SubscriptionService.GetSubscription:output_type -> bytebase.v1.Subscription- 20, // 25: bytebase.v1.SubscriptionService.UpdateSubscription:output_type -> bytebase.v1.Subscription- 7, // 26: bytebase.v1.SubscriptionService.CreatePurchase:output_type -> bytebase.v1.CreatePurchaseResponse- 9, // 27: bytebase.v1.SubscriptionService.UpdatePurchase:output_type -> bytebase.v1.UpdatePurchaseResponse- 11, // 28: bytebase.v1.SubscriptionService.CancelPurchase:output_type -> bytebase.v1.CancelPurchaseResponse- 13, // 29: bytebase.v1.SubscriptionService.GetPaymentInfo:output_type -> bytebase.v1.PaymentInfo- 19, // 30: bytebase.v1.SubscriptionService.ListPurchasePlans:output_type -> bytebase.v1.ListPurchasePlansResponse- 24, // [24:31] is the sub-list for method output_type- 17, // [17:24] is the sub-list for method input_type- 17, // [17:17] is the sub-list for extension type_name- 17, // [17:17] is the sub-list for extension extendee- 0, // [0:17] is the sub-list for field type_name+ 18, // 9: bytebase.v1.PurchaseBillingMethod.discount:type_name -> bytebase.v1.PurchaseDiscount+ 4, // 10: bytebase.v1.PurchaseDiscount.type:type_name -> bytebase.v1.PurchaseDiscount.Type+ 15, // 11: bytebase.v1.ListPurchasePlansResponse.plans:type_name -> bytebase.v1.PurchasePlan+ 1, // 12: bytebase.v1.Subscription.plan:type_name -> bytebase.v1.PlanType+ 24, // 13: bytebase.v1.Subscription.expires_time:type_name -> google.protobuf.Timestamp+ 23, // 14: bytebase.v1.PlanConfig.plans:type_name -> bytebase.v1.PlanLimitConfig+ 2, // 15: bytebase.v1.PlanConfig.instance_features:type_name -> bytebase.v1.PlanFeature+ 1, // 16: bytebase.v1.PlanLimitConfig.type:type_name -> bytebase.v1.PlanType+ 2, // 17: bytebase.v1.PlanLimitConfig.features:type_name -> bytebase.v1.PlanFeature+ 5, // 18: bytebase.v1.SubscriptionService.GetSubscription:input_type -> bytebase.v1.GetSubscriptionRequest+ 6, // 19: bytebase.v1.SubscriptionService.UploadLicense:input_type -> bytebase.v1.UploadLicenseRequest+ 7, // 20: bytebase.v1.SubscriptionService.CreatePurchase:input_type -> bytebase.v1.CreatePurchaseRequest+ 11, // 21: bytebase.v1.SubscriptionService.UpdatePurchase:input_type -> bytebase.v1.UpdatePurchaseRequest+ 12, // 22: bytebase.v1.SubscriptionService.CancelPurchase:input_type -> bytebase.v1.CancelPurchaseRequest+ 13, // 23: bytebase.v1.SubscriptionService.GetPaymentInfo:input_type -> bytebase.v1.GetPaymentInfoRequest+ 9, // 24: bytebase.v1.SubscriptionService.VerifyCheckoutSession:input_type -> bytebase.v1.VerifyCheckoutSessionRequest+ 19, // 25: bytebase.v1.SubscriptionService.ListPurchasePlans:input_type -> bytebase.v1.ListPurchasePlansRequest+ 21, // 26: bytebase.v1.SubscriptionService.GetSubscription:output_type -> bytebase.v1.Subscription+ 21, // 27: bytebase.v1.SubscriptionService.UploadLicense:output_type -> bytebase.v1.Subscription+ 8, // 28: bytebase.v1.SubscriptionService.CreatePurchase:output_type -> bytebase.v1.PurchaseResponse+ 8, // 29: bytebase.v1.SubscriptionService.UpdatePurchase:output_type -> bytebase.v1.PurchaseResponse+ 8, // 30: bytebase.v1.SubscriptionService.CancelPurchase:output_type -> bytebase.v1.PurchaseResponse+ 14, // 31: bytebase.v1.SubscriptionService.GetPaymentInfo:output_type -> bytebase.v1.PaymentInfo+ 10, // 32: bytebase.v1.SubscriptionService.VerifyCheckoutSession:output_type -> bytebase.v1.VerifyCheckoutSessionResponse+ 20, // 33: bytebase.v1.SubscriptionService.ListPurchasePlans:output_type -> bytebase.v1.ListPurchasePlansResponse+ 26, // [26:34] is the sub-list for method output_type+ 18, // [18:26] is the sub-list for method input_type+ 18, // [18:18] is the sub-list for extension type_name+ 18, // [18:18] is the sub-list for extension extendee+ 0, // [0:18] is the sub-list for field type_name}func init() { file_v1_subscription_service_proto_init() }@@ -1745,7 +1836,7 @@ func file_v1_subscription_service_proto_init() {File: protoimpl.DescBuilder{GoPackagePath: reflect.TypeOf(x{}).PkgPath(),RawDescriptor: unsafe.Slice(unsafe.StringData(file_v1_subscription_service_proto_rawDesc), len(file_v1_subscription_service_proto_rawDesc)),- NumEnums: 4,+ NumEnums: 5,NumMessages: 19,NumExtensions: 0,NumServices: 1,diff --git a/backend/generated-go/v1/subscription_service.pb.gw.go b/backend/generated-go/v1/subscription_service.pb.gw.goindex a4298f7509..ab94da9f2f 100644--- a/backend/generated-go/v1/subscription_service.pb.gw.go+++ b/backend/generated-go/v1/subscription_service.pb.gw.go@@ -56,44 +56,30 @@ func local_request_SubscriptionService_GetSubscription_0(ctx context.Context, mareturn msg, metadata, err}-var filter_SubscriptionService_UpdateSubscription_0 = &utilities.DoubleArray{Encoding: map[string]int{"license": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}}--func request_SubscriptionService_UpdateSubscription_0(ctx context.Context, marshaler runtime.Marshaler, client SubscriptionServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {+func request_SubscriptionService_UploadLicense_0(ctx context.Context, marshaler runtime.Marshaler, client SubscriptionServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {var (- protoReq UpdateSubscriptionRequest+ protoReq UploadLicenseRequestmetadata runtime.ServerMetadata)- if err := marshaler.NewDecoder(req.Body).Decode(&protoReq.License); err != nil && !errors.Is(err, io.EOF) {+ if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) {return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)}if req.Body != nil {_, _ = io.Copy(io.Discard, req.Body)}- if err := req.ParseForm(); err != nil {- return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)- }- if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_SubscriptionService_UpdateSubscription_0); err != nil {- return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)- }- msg, err := client.UpdateSubscription(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))+ msg, err := client.UploadLicense(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))return msg, metadata, err}-func local_request_SubscriptionService_UpdateSubscription_0(ctx context.Context, marshaler runtime.Marshaler, server SubscriptionServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {+func local_request_SubscriptionService_UploadLicense_0(ctx context.Context, marshaler runtime.Marshaler, server SubscriptionServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {var (- protoReq UpdateSubscriptionRequest+ protoReq UploadLicenseRequestmetadata runtime.ServerMetadata)- if err := marshaler.NewDecoder(req.Body).Decode(&protoReq.License); err != nil && !errors.Is(err, io.EOF) {- return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)- }- if err := req.ParseForm(); err != nil {- return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)- }- if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_SubscriptionService_UpdateSubscription_0); err != nil {+ if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) {return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)}- msg, err := server.UpdateSubscription(ctx, &protoReq)+ msg, err := server.UploadLicense(ctx, &protoReq)return msg, metadata, err}@@ -199,6 +185,45 @@ func local_request_SubscriptionService_GetPaymentInfo_0(ctx context.Context, marreturn msg, metadata, err}+func request_SubscriptionService_VerifyCheckoutSession_0(ctx context.Context, marshaler runtime.Marshaler, client SubscriptionServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {+ var (+ protoReq VerifyCheckoutSessionRequest+ metadata runtime.ServerMetadata+ err error+ )+ if req.Body != nil {+ _, _ = io.Copy(io.Discard, req.Body)+ }+ val, ok := pathParams["session_id"]+ if !ok {+ return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "session_id")+ }+ protoReq.SessionId, err = runtime.String(val)+ if err != nil {+ return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "session_id", err)+ }+ msg, err := client.VerifyCheckoutSession(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))+ return msg, metadata, err+}++func local_request_SubscriptionService_VerifyCheckoutSession_0(ctx context.Context, marshaler runtime.Marshaler, server SubscriptionServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {+ var (+ protoReq VerifyCheckoutSessionRequest+ metadata runtime.ServerMetadata+ err error+ )+ val, ok := pathParams["session_id"]+ if !ok {+ return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "session_id")+ }+ protoReq.SessionId, err = runtime.String(val)+ if err != nil {+ return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "session_id", err)+ }+ msg, err := server.VerifyCheckoutSession(ctx, &protoReq)+ return msg, metadata, err+}+func request_SubscriptionService_ListPurchasePlans_0(ctx context.Context, marshaler runtime.Marshaler, client SubscriptionServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {var (protoReq ListPurchasePlansRequest@@ -246,25 +271,25 @@ func RegisterSubscriptionServiceHandlerServer(ctx context.Context, mux *runtime.}forward_SubscriptionService_GetSubscription_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)})- mux.Handle(http.MethodPatch, pattern_SubscriptionService_UpdateSubscription_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {+ mux.Handle(http.MethodPatch, pattern_SubscriptionService_UploadLicense_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {ctx, cancel := context.WithCancel(req.Context())defer cancel()var stream runtime.ServerTransportStreamctx = grpc.NewContextWithServerTransportStream(ctx, &stream)inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)- annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/bytebase.v1.SubscriptionService/UpdateSubscription", runtime.WithHTTPPathPattern("/v1/subscription"))+ annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/bytebase.v1.SubscriptionService/UploadLicense", runtime.WithHTTPPathPattern("/v1/subscription/license"))if err != nil {runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)return}- resp, md, err := local_request_SubscriptionService_UpdateSubscription_0(annotatedContext, inboundMarshaler, server, req, pathParams)+ resp, md, err := local_request_SubscriptionService_UploadLicense_0(annotatedContext, inboundMarshaler, server, req, pathParams)md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)if err != nil {runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)return}- forward_SubscriptionService_UpdateSubscription_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)+ forward_SubscriptionService_UploadLicense_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)})mux.Handle(http.MethodPost, pattern_SubscriptionService_CreatePurchase_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {ctx, cancel := context.WithCancel(req.Context())@@ -346,6 +371,26 @@ func RegisterSubscriptionServiceHandlerServer(ctx context.Context, mux *runtime.}forward_SubscriptionService_GetPaymentInfo_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)})+ mux.Handle(http.MethodGet, pattern_SubscriptionService_VerifyCheckoutSession_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {+ ctx, cancel := context.WithCancel(req.Context())+ defer cancel()+ var stream runtime.ServerTransportStream+ ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)+ inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)+ annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/bytebase.v1.SubscriptionService/VerifyCheckoutSession", runtime.WithHTTPPathPattern("/v1/subscription/checkoutSession/{session_id}"))+ if err != nil {+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)+ return+ }+ resp, md, err := local_request_SubscriptionService_VerifyCheckoutSession_0(annotatedContext, inboundMarshaler, server, req, pathParams)+ md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)+ if err != nil {+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)+ return+ }+ forward_SubscriptionService_VerifyCheckoutSession_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)+ })mux.Handle(http.MethodGet, pattern_SubscriptionService_ListPurchasePlans_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {ctx, cancel := context.WithCancel(req.Context())defer cancel()@@ -423,22 +468,22 @@ func RegisterSubscriptionServiceHandlerClient(ctx context.Context, mux *runtime.}forward_SubscriptionService_GetSubscription_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)})- mux.Handle(http.MethodPatch, pattern_SubscriptionService_UpdateSubscription_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {+ mux.Handle(http.MethodPatch, pattern_SubscriptionService_UploadLicense_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {ctx, cancel := context.WithCancel(req.Context())defer cancel()inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)- annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/bytebase.v1.SubscriptionService/UpdateSubscription", runtime.WithHTTPPathPattern("/v1/subscription"))+ annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/bytebase.v1.SubscriptionService/UploadLicense", runtime.WithHTTPPathPattern("/v1/subscription/license"))if err != nil {runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)return}- resp, md, err := request_SubscriptionService_UpdateSubscription_0(annotatedContext, inboundMarshaler, client, req, pathParams)+ resp, md, err := request_SubscriptionService_UploadLicense_0(annotatedContext, inboundMarshaler, client, req, pathParams)annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)if err != nil {runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)return}- forward_SubscriptionService_UpdateSubscription_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)+ forward_SubscriptionService_UploadLicense_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)})mux.Handle(http.MethodPost, pattern_SubscriptionService_CreatePurchase_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {ctx, cancel := context.WithCancel(req.Context())@@ -508,6 +553,23 @@ func RegisterSubscriptionServiceHandlerClient(ctx context.Context, mux *runtime.}forward_SubscriptionService_GetPaymentInfo_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)})+ mux.Handle(http.MethodGet, pattern_SubscriptionService_VerifyCheckoutSession_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {+ ctx, cancel := context.WithCancel(req.Context())+ defer cancel()+ inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)+ annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/bytebase.v1.SubscriptionService/VerifyCheckoutSession", runtime.WithHTTPPathPattern("/v1/subscription/checkoutSession/{session_id}"))+ if err != nil {+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)+ return+ }+ resp, md, err := request_SubscriptionService_VerifyCheckoutSession_0(annotatedContext, inboundMarshaler, client, req, pathParams)+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)+ if err != nil {+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)+ return+ }+ forward_SubscriptionService_VerifyCheckoutSession_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)+ })mux.Handle(http.MethodGet, pattern_SubscriptionService_ListPurchasePlans_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {ctx, cancel := context.WithCancel(req.Context())defer cancel()@@ -529,21 +591,23 @@ func RegisterSubscriptionServiceHandlerClient(ctx context.Context, mux *runtime.}var (- pattern_SubscriptionService_GetSubscription_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "subscription"}, ""))- pattern_SubscriptionService_UpdateSubscription_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "subscription"}, ""))- pattern_SubscriptionService_CreatePurchase_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "subscription"}, "purchase"))- pattern_SubscriptionService_UpdatePurchase_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "subscription"}, "updatePurchase"))- pattern_SubscriptionService_CancelPurchase_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "subscription"}, "cancelPurchase"))- pattern_SubscriptionService_GetPaymentInfo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "subscription", "paymentInfo"}, ""))- pattern_SubscriptionService_ListPurchasePlans_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "subscription", "plans"}, ""))+ pattern_SubscriptionService_GetSubscription_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "subscription"}, ""))+ pattern_SubscriptionService_UploadLicense_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "subscription", "license"}, ""))+ pattern_SubscriptionService_CreatePurchase_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "subscription"}, "purchase"))+ pattern_SubscriptionService_UpdatePurchase_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "subscription"}, "updatePurchase"))+ pattern_SubscriptionService_CancelPurchase_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "subscription"}, "cancelPurchase"))+ pattern_SubscriptionService_GetPaymentInfo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "subscription", "paymentInfo"}, ""))+ pattern_SubscriptionService_VerifyCheckoutSession_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v1", "subscription", "checkoutSession", "session_id"}, ""))+ pattern_SubscriptionService_ListPurchasePlans_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "subscription", "plans"}, "")))var (- forward_SubscriptionService_GetSubscription_0 = runtime.ForwardResponseMessage- forward_SubscriptionService_UpdateSubscription_0 = runtime.ForwardResponseMessage- forward_SubscriptionService_CreatePurchase_0 = runtime.ForwardResponseMessage- forward_SubscriptionService_UpdatePurchase_0 = runtime.ForwardResponseMessage- forward_SubscriptionService_CancelPurchase_0 = runtime.ForwardResponseMessage- forward_SubscriptionService_GetPaymentInfo_0 = runtime.ForwardResponseMessage- forward_SubscriptionService_ListPurchasePlans_0 = runtime.ForwardResponseMessage+ forward_SubscriptionService_GetSubscription_0 = runtime.ForwardResponseMessage+ forward_SubscriptionService_UploadLicense_0 = runtime.ForwardResponseMessage+ forward_SubscriptionService_CreatePurchase_0 = runtime.ForwardResponseMessage+ forward_SubscriptionService_UpdatePurchase_0 = runtime.ForwardResponseMessage+ forward_SubscriptionService_CancelPurchase_0 = runtime.ForwardResponseMessage+ forward_SubscriptionService_GetPaymentInfo_0 = runtime.ForwardResponseMessage+ forward_SubscriptionService_VerifyCheckoutSession_0 = runtime.ForwardResponseMessage+ forward_SubscriptionService_ListPurchasePlans_0 = runtime.ForwardResponseMessage)diff --git a/backend/generated-go/v1/subscription_service_equal.pb.go b/backend/generated-go/v1/subscription_service_equal.pb.goindex f4ff1b073d..ea1b5f803a 100644--- a/backend/generated-go/v1/subscription_service_equal.pb.go+++ b/backend/generated-go/v1/subscription_service_equal.pb.go@@ -13,7 +13,7 @@ func (x *GetSubscriptionRequest) Equal(y *GetSubscriptionRequest) bool {return true}-func (x *UpdateSubscriptionRequest) Equal(y *UpdateSubscriptionRequest) bool {+func (x *UploadLicenseRequest) Equal(y *UploadLicenseRequest) bool {if x == y {return true}@@ -23,9 +23,6 @@ func (x *UpdateSubscriptionRequest) Equal(y *UpdateSubscriptionRequest) bool {if x.License != y.License {return false}- if x.AllowMissing != y.AllowMissing {- return false- }return true}@@ -48,7 +45,7 @@ func (x *CreatePurchaseRequest) Equal(y *CreatePurchaseRequest) bool {return true}-func (x *CreatePurchaseResponse) Equal(y *CreatePurchaseResponse) bool {+func (x *PurchaseResponse) Equal(y *PurchaseResponse) bool {if x == y {return true}@@ -58,55 +55,61 @@ func (x *CreatePurchaseResponse) Equal(y *CreatePurchaseResponse) bool {if x.PaymentUrl != y.PaymentUrl {return false}+ if x.SessionId != y.SessionId {+ return false+ }return true}-func (x *UpdatePurchaseRequest) Equal(y *UpdatePurchaseRequest) bool {+func (x *VerifyCheckoutSessionRequest) Equal(y *VerifyCheckoutSessionRequest) bool {if x == y {return true}if x == nil || y == nil {return x == nil && y == nil}- if x.Plan != y.Plan {- return false- }- if x.Interval != y.Interval {- return false- }- if x.Seats != y.Seats {- return false- }- if x.Etag != y.Etag {+ if x.SessionId != y.SessionId {return false}return true}-func (x *UpdatePurchaseResponse) Equal(y *UpdatePurchaseResponse) bool {+func (x *VerifyCheckoutSessionResponse) Equal(y *VerifyCheckoutSessionResponse) bool {if x == y {return true}if x == nil || y == nil {return x == nil && y == nil}- if x.PaymentUrl != y.PaymentUrl {+ if x.Status != y.Status {return false}return true}-func (x *CancelPurchaseRequest) Equal(y *CancelPurchaseRequest) bool {+func (x *UpdatePurchaseRequest) Equal(y *UpdatePurchaseRequest) bool {if x == y {return true}if x == nil || y == nil {return x == nil && y == nil}+ if x.Plan != y.Plan {+ return false+ }+ if x.Interval != y.Interval {+ return false+ }+ if x.Seats != y.Seats {+ return false+ }+ if x.Etag != y.Etag {+ return false+ }return true}-func (x *CancelPurchaseResponse) Equal(y *CancelPurchaseResponse) bool {+func (x *CancelPurchaseRequest) Equal(y *CancelPurchaseRequest) bool {if x == y {return true}@@ -148,6 +151,9 @@ func (x *PaymentInfo) Equal(y *PaymentInfo) bool {if x.InvoiceUrl != y.InvoiceUrl {return false}+ if x.CancelAtPeriodEnd != y.CancelAtPeriodEnd {+ return false+ }return true}@@ -231,10 +237,10 @@ func (x *PurchaseDiscount) Equal(y *PurchaseDiscount) bool {if x == nil || y == nil {return x == nil && y == nil}- if x.Description != y.Description {+ if x.Type != y.Type {return false}- if x.PromotionCode != y.PromotionCode {+ if x.Value != y.Value {return false}return true@@ -299,6 +305,9 @@ func (x *Subscription) Equal(y *Subscription) bool {if x.Ha != y.Ha {return false}+ if x.Etag != y.Etag {+ return false+ }return true}diff --git a/backend/generated-go/v1/subscription_service_grpc.pb.go b/backend/generated-go/v1/subscription_service_grpc.pb.goindex aaf65473c5..ee566cc5e7 100644--- a/backend/generated-go/v1/subscription_service_grpc.pb.go+++ b/backend/generated-go/v1/subscription_service_grpc.pb.go@@ -19,13 +19,14 @@ import (const _ = grpc.SupportPackageIsVersion9const (- SubscriptionService_GetSubscription_FullMethodName = "/bytebase.v1.SubscriptionService/GetSubscription"- SubscriptionService_UpdateSubscription_FullMethodName = "/bytebase.v1.SubscriptionService/UpdateSubscription"- SubscriptionService_CreatePurchase_FullMethodName = "/bytebase.v1.SubscriptionService/CreatePurchase"- SubscriptionService_UpdatePurchase_FullMethodName = "/bytebase.v1.SubscriptionService/UpdatePurchase"- SubscriptionService_CancelPurchase_FullMethodName = "/bytebase.v1.SubscriptionService/CancelPurchase"- SubscriptionService_GetPaymentInfo_FullMethodName = "/bytebase.v1.SubscriptionService/GetPaymentInfo"- SubscriptionService_ListPurchasePlans_FullMethodName = "/bytebase.v1.SubscriptionService/ListPurchasePlans"+ SubscriptionService_GetSubscription_FullMethodName = "/bytebase.v1.SubscriptionService/GetSubscription"+ SubscriptionService_UploadLicense_FullMethodName = "/bytebase.v1.SubscriptionService/UploadLicense"+ SubscriptionService_CreatePurchase_FullMethodName = "/bytebase.v1.SubscriptionService/CreatePurchase"+ SubscriptionService_UpdatePurchase_FullMethodName = "/bytebase.v1.SubscriptionService/UpdatePurchase"+ SubscriptionService_CancelPurchase_FullMethodName = "/bytebase.v1.SubscriptionService/CancelPurchase"+ SubscriptionService_GetPaymentInfo_FullMethodName = "/bytebase.v1.SubscriptionService/GetPaymentInfo"+ SubscriptionService_VerifyCheckoutSession_FullMethodName = "/bytebase.v1.SubscriptionService/VerifyCheckoutSession"+ SubscriptionService_ListPurchasePlans_FullMethodName = "/bytebase.v1.SubscriptionService/ListPurchasePlans")// SubscriptionServiceClient is the client API for SubscriptionService service.@@ -37,21 +38,21 @@ type SubscriptionServiceClient interface {// GetSubscription returns the current subscription.// If there is no license, we will return a free plan subscription without expiration time.// If there is expired license, we will return a free plan subscription with the expiration time of the expired license.- // Permissions required: NoneGetSubscription(ctx context.Context, in *GetSubscriptionRequest, opts ...grpc.CallOption) (*Subscription, error)- // Updates the enterprise license subscription (self-hosted only).- // Permissions required: bb.settings.set- UpdateSubscription(ctx context.Context, in *UpdateSubscriptionRequest, opts ...grpc.CallOption) (*Subscription, error)+ // Uploads an enterprise license (self-hosted only).+ UploadLicense(ctx context.Context, in *UploadLicenseRequest, opts ...grpc.CallOption) (*Subscription, error)// CreatePurchase creates a new subscription purchase (SaaS only).// Returns a Stripe Checkout URL for the user to complete payment.- CreatePurchase(ctx context.Context, in *CreatePurchaseRequest, opts ...grpc.CallOption) (*CreatePurchaseResponse, error)+ CreatePurchase(ctx context.Context, in *CreatePurchaseRequest, opts ...grpc.CallOption) (*PurchaseResponse, error)// UpdatePurchase updates an existing subscription (SaaS only).// May return a Stripe Checkout URL if payment method change is needed.- UpdatePurchase(ctx context.Context, in *UpdatePurchaseRequest, opts ...grpc.CallOption) (*UpdatePurchaseResponse, error)+ UpdatePurchase(ctx context.Context, in *UpdatePurchaseRequest, opts ...grpc.CallOption) (*PurchaseResponse, error)// CancelPurchase cancels an active subscription (SaaS only).- CancelPurchase(ctx context.Context, in *CancelPurchaseRequest, opts ...grpc.CallOption) (*CancelPurchaseResponse, error)+ CancelPurchase(ctx context.Context, in *CancelPurchaseRequest, opts ...grpc.CallOption) (*PurchaseResponse, error)// GetPaymentInfo returns payment details for the current subscription (SaaS only).GetPaymentInfo(ctx context.Context, in *GetPaymentInfoRequest, opts ...grpc.CallOption) (*PaymentInfo, error)+ // VerifyCheckoutSession verifies a Stripe Checkout Session status (SaaS only).+ VerifyCheckoutSession(ctx context.Context, in *VerifyCheckoutSessionRequest, opts ...grpc.CallOption) (*VerifyCheckoutSessionResponse, error)// ListPurchasePlans returns available plans for self-service purchase.ListPurchasePlans(ctx context.Context, in *ListPurchasePlansRequest, opts ...grpc.CallOption) (*ListPurchasePlansResponse, error)}@@ -74,19 +75,19 @@ func (c *subscriptionServiceClient) GetSubscription(ctx context.Context, in *Getreturn out, nil}-func (c *subscriptionServiceClient) UpdateSubscription(ctx context.Context, in *UpdateSubscriptionRequest, opts ...grpc.CallOption) (*Subscription, error) {+func (c *subscriptionServiceClient) UploadLicense(ctx context.Context, in *UploadLicenseRequest, opts ...grpc.CallOption) (*Subscription, error) {cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)out := new(Subscription)- err := c.cc.Invoke(ctx, SubscriptionService_UpdateSubscription_FullMethodName, in, out, cOpts...)+ err := c.cc.Invoke(ctx, SubscriptionService_UploadLicense_FullMethodName, in, out, cOpts...)if err != nil {return nil, err}return out, nil}-func (c *subscriptionServiceClient) CreatePurchase(ctx context.Context, in *CreatePurchaseRequest, opts ...grpc.CallOption) (*CreatePurchaseResponse, error) {+func (c *subscriptionServiceClient) CreatePurchase(ctx context.Context, in *CreatePurchaseRequest, opts ...grpc.CallOption) (*PurchaseResponse, error) {cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)- out := new(CreatePurchaseResponse)+ out := new(PurchaseResponse)err := c.cc.Invoke(ctx, SubscriptionService_CreatePurchase_FullMethodName, in, out, cOpts...)if err != nil {return nil, err@@ -94,9 +95,9 @@ func (c *subscriptionServiceClient) CreatePurchase(ctx context.Context, in *Creareturn out, nil}-func (c *subscriptionServiceClient) UpdatePurchase(ctx context.Context, in *UpdatePurchaseRequest, opts ...grpc.CallOption) (*UpdatePurchaseResponse, error) {+func (c *subscriptionServiceClient) UpdatePurchase(ctx context.Context, in *UpdatePurchaseRequest, opts ...grpc.CallOption) (*PurchaseResponse, error) {cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)- out := new(UpdatePurchaseResponse)+ out := new(PurchaseResponse)err := c.cc.Invoke(ctx, SubscriptionService_UpdatePurchase_FullMethodName, in, out, cOpts...)if err != nil {return nil, err@@ -104,9 +105,9 @@ func (c *subscriptionServiceClient) UpdatePurchase(ctx context.Context, in *Updareturn out, nil}-func (c *subscriptionServiceClient) CancelPurchase(ctx context.Context, in *CancelPurchaseRequest, opts ...grpc.CallOption) (*CancelPurchaseResponse, error) {+func (c *subscriptionServiceClient) CancelPurchase(ctx context.Context, in *CancelPurchaseRequest, opts ...grpc.CallOption) (*PurchaseResponse, error) {cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)- out := new(CancelPurchaseResponse)+ out := new(PurchaseResponse)err := c.cc.Invoke(ctx, SubscriptionService_CancelPurchase_FullMethodName, in, out, cOpts...)if err != nil {return nil, err@@ -124,6 +125,16 @@ func (c *subscriptionServiceClient) GetPaymentInfo(ctx context.Context, in *GetPreturn out, nil}+func (c *subscriptionServiceClient) VerifyCheckoutSession(ctx context.Context, in *VerifyCheckoutSessionRequest, opts ...grpc.CallOption) (*VerifyCheckoutSessionResponse, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(VerifyCheckoutSessionResponse)+ err := c.cc.Invoke(ctx, SubscriptionService_VerifyCheckoutSession_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}+func (c *subscriptionServiceClient) ListPurchasePlans(ctx context.Context, in *ListPurchasePlansRequest, opts ...grpc.CallOption) (*ListPurchasePlansResponse, error) {cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)out := new(ListPurchasePlansResponse)@@ -143,21 +154,21 @@ type SubscriptionServiceServer interface {// GetSubscription returns the current subscription.// If there is no license, we will return a free plan subscription without expiration time.// If there is expired license, we will return a free plan subscription with the expiration time of the expired license.- // Permissions required: NoneGetSubscription(context.Context, *GetSubscriptionRequest) (*Subscription, error)- // Updates the enterprise license subscription (self-hosted only).- // Permissions required: bb.settings.set- UpdateSubscription(context.Context, *UpdateSubscriptionRequest) (*Subscription, error)+ // Uploads an enterprise license (self-hosted only).+ UploadLicense(context.Context, *UploadLicenseRequest) (*Subscription, error)// CreatePurchase creates a new subscription purchase (SaaS only).// Returns a Stripe Checkout URL for the user to complete payment.- CreatePurchase(context.Context, *CreatePurchaseRequest) (*CreatePurchaseResponse, error)+ CreatePurchase(context.Context, *CreatePurchaseRequest) (*PurchaseResponse, error)// UpdatePurchase updates an existing subscription (SaaS only).// May return a Stripe Checkout URL if payment method change is needed.- UpdatePurchase(context.Context, *UpdatePurchaseRequest) (*UpdatePurchaseResponse, error)+ UpdatePurchase(context.Context, *UpdatePurchaseRequest) (*PurchaseResponse, error)// CancelPurchase cancels an active subscription (SaaS only).- CancelPurchase(context.Context, *CancelPurchaseRequest) (*CancelPurchaseResponse, error)+ CancelPurchase(context.Context, *CancelPurchaseRequest) (*PurchaseResponse, error)// GetPaymentInfo returns payment details for the current subscription (SaaS only).GetPaymentInfo(context.Context, *GetPaymentInfoRequest) (*PaymentInfo, error)+ // VerifyCheckoutSession verifies a Stripe Checkout Session status (SaaS only).+ VerifyCheckoutSession(context.Context, *VerifyCheckoutSessionRequest) (*VerifyCheckoutSessionResponse, error)// ListPurchasePlans returns available plans for self-service purchase.ListPurchasePlans(context.Context, *ListPurchasePlansRequest) (*ListPurchasePlansResponse, error)mustEmbedUnimplementedSubscriptionServiceServer()@@ -173,21 +184,24 @@ type UnimplementedSubscriptionServiceServer struct{}func (UnimplementedSubscriptionServiceServer) GetSubscription(context.Context, *GetSubscriptionRequest) (*Subscription, error) {return nil, status.Error(codes.Unimplemented, "method GetSubscription not implemented")}-func (UnimplementedSubscriptionServiceServer) UpdateSubscription(context.Context, *UpdateSubscriptionRequest) (*Subscription, error) {- return nil, status.Error(codes.Unimplemented, "method UpdateSubscription not implemented")+func (UnimplementedSubscriptionServiceServer) UploadLicense(context.Context, *UploadLicenseRequest) (*Subscription, error) {+ return nil, status.Error(codes.Unimplemented, "method UploadLicense not implemented")}-func (UnimplementedSubscriptionServiceServer) CreatePurchase(context.Context, *CreatePurchaseRequest) (*CreatePurchaseResponse, error) {+func (UnimplementedSubscriptionServiceServer) CreatePurchase(context.Context, *CreatePurchaseRequest) (*PurchaseResponse, error) {return nil, status.Error(codes.Unimplemented, "method CreatePurchase not implemented")}-func (UnimplementedSubscriptionServiceServer) UpdatePurchase(context.Context, *UpdatePurchaseRequest) (*UpdatePurchaseResponse, error) {+func (UnimplementedSubscriptionServiceServer) UpdatePurchase(context.Context, *UpdatePurchaseRequest) (*PurchaseResponse, error) {return nil, status.Error(codes.Unimplemented, "method UpdatePurchase not implemented")}-func (UnimplementedSubscriptionServiceServer) CancelPurchase(context.Context, *CancelPurchaseRequest) (*CancelPurchaseResponse, error) {+func (UnimplementedSubscriptionServiceServer) CancelPurchase(context.Context, *CancelPurchaseRequest) (*PurchaseResponse, error) {return nil, status.Error(codes.Unimplemented, "method CancelPurchase not implemented")}func (UnimplementedSubscriptionServiceServer) GetPaymentInfo(context.Context, *GetPaymentInfoRequest) (*PaymentInfo, error) {return nil, status.Error(codes.Unimplemented, "method GetPaymentInfo not implemented")}+func (UnimplementedSubscriptionServiceServer) VerifyCheckoutSession(context.Context, *VerifyCheckoutSessionRequest) (*VerifyCheckoutSessionResponse, error) {+ return nil, status.Error(codes.Unimplemented, "method VerifyCheckoutSession not implemented")+}func (UnimplementedSubscriptionServiceServer) ListPurchasePlans(context.Context, *ListPurchasePlansRequest) (*ListPurchasePlansResponse, error) {return nil, status.Error(codes.Unimplemented, "method ListPurchasePlans not implemented")}@@ -230,20 +244,20 @@ func _SubscriptionService_GetSubscription_Handler(srv interface{}, ctx context.Creturn interceptor(ctx, in, info, handler)}-func _SubscriptionService_UpdateSubscription_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {- in := new(UpdateSubscriptionRequest)+func _SubscriptionService_UploadLicense_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(UploadLicenseRequest)if err := dec(in); err != nil {return nil, err}if interceptor == nil {- return srv.(SubscriptionServiceServer).UpdateSubscription(ctx, in)+ return srv.(SubscriptionServiceServer).UploadLicense(ctx, in)}info := &grpc.UnaryServerInfo{Server: srv,- FullMethod: SubscriptionService_UpdateSubscription_FullMethodName,+ FullMethod: SubscriptionService_UploadLicense_FullMethodName,}handler := func(ctx context.Context, req interface{}) (interface{}, error) {- return srv.(SubscriptionServiceServer).UpdateSubscription(ctx, req.(*UpdateSubscriptionRequest))+ return srv.(SubscriptionServiceServer).UploadLicense(ctx, req.(*UploadLicenseRequest))}return interceptor(ctx, in, info, handler)}@@ -320,6 +334,24 @@ func _SubscriptionService_GetPaymentInfo_Handler(srv interface{}, ctx context.Coreturn interceptor(ctx, in, info, handler)}+func _SubscriptionService_VerifyCheckoutSession_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(VerifyCheckoutSessionRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(SubscriptionServiceServer).VerifyCheckoutSession(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: SubscriptionService_VerifyCheckoutSession_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(SubscriptionServiceServer).VerifyCheckoutSession(ctx, req.(*VerifyCheckoutSessionRequest))+ }+ return interceptor(ctx, in, info, handler)+}+func _SubscriptionService_ListPurchasePlans_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {in := new(ListPurchasePlansRequest)if err := dec(in); err != nil {@@ -350,8 +382,8 @@ var SubscriptionService_ServiceDesc = grpc.ServiceDesc{Handler: _SubscriptionService_GetSubscription_Handler,},{- MethodName: "UpdateSubscription",- Handler: _SubscriptionService_UpdateSubscription_Handler,+ MethodName: "UploadLicense",+ Handler: _SubscriptionService_UploadLicense_Handler,},{MethodName: "CreatePurchase",@@ -369,6 +401,10 @@ var SubscriptionService_ServiceDesc = grpc.ServiceDesc{MethodName: "GetPaymentInfo",Handler: _SubscriptionService_GetPaymentInfo_Handler,},+ {+ MethodName: "VerifyCheckoutSession",+ Handler: _SubscriptionService_VerifyCheckoutSession_Handler,+ },{MethodName: "ListPurchasePlans",Handler: _SubscriptionService_ListPurchasePlans_Handler,diff --git a/backend/generated-go/v1/v1connect/subscription_service.connect.go b/backend/generated-go/v1/v1connect/subscription_service.connect.goindex e794771b7d..7992c74213 100644--- a/backend/generated-go/v1/v1connect/subscription_service.connect.go+++ b/backend/generated-go/v1/v1connect/subscription_service.connect.go@@ -36,9 +36,9 @@ const (// SubscriptionServiceGetSubscriptionProcedure is the fully-qualified name of the// SubscriptionService's GetSubscription RPC.SubscriptionServiceGetSubscriptionProcedure = "/bytebase.v1.SubscriptionService/GetSubscription"- // SubscriptionServiceUpdateSubscriptionProcedure is the fully-qualified name of the- // SubscriptionService's UpdateSubscription RPC.- SubscriptionServiceUpdateSubscriptionProcedure = "/bytebase.v1.SubscriptionService/UpdateSubscription"+ // SubscriptionServiceUploadLicenseProcedure is the fully-qualified name of the+ // SubscriptionService's UploadLicense RPC.+ SubscriptionServiceUploadLicenseProcedure = "/bytebase.v1.SubscriptionService/UploadLicense"// SubscriptionServiceCreatePurchaseProcedure is the fully-qualified name of the// SubscriptionService's CreatePurchase RPC.SubscriptionServiceCreatePurchaseProcedure = "/bytebase.v1.SubscriptionService/CreatePurchase"@@ -51,6 +51,9 @@ const (// SubscriptionServiceGetPaymentInfoProcedure is the fully-qualified name of the// SubscriptionService's GetPaymentInfo RPC.SubscriptionServiceGetPaymentInfoProcedure = "/bytebase.v1.SubscriptionService/GetPaymentInfo"+ // SubscriptionServiceVerifyCheckoutSessionProcedure is the fully-qualified name of the+ // SubscriptionService's VerifyCheckoutSession RPC.+ SubscriptionServiceVerifyCheckoutSessionProcedure = "/bytebase.v1.SubscriptionService/VerifyCheckoutSession"// SubscriptionServiceListPurchasePlansProcedure is the fully-qualified name of the// SubscriptionService's ListPurchasePlans RPC.SubscriptionServiceListPurchasePlansProcedure = "/bytebase.v1.SubscriptionService/ListPurchasePlans"@@ -61,21 +64,21 @@ type SubscriptionServiceClient interface {// GetSubscription returns the current subscription.// If there is no license, we will return a free plan subscription without expiration time.// If there is expired license, we will return a free plan subscription with the expiration time of the expired license.- // Permissions required: NoneGetSubscription(context.Context, *connect.Request[v1.GetSubscriptionRequest]) (*connect.Response[v1.Subscription], error)- // Updates the enterprise license subscription (self-hosted only).- // Permissions required: bb.settings.set- UpdateSubscription(context.Context, *connect.Request[v1.UpdateSubscriptionRequest]) (*connect.Response[v1.Subscription], error)+ // Uploads an enterprise license (self-hosted only).+ UploadLicense(context.Context, *connect.Request[v1.UploadLicenseRequest]) (*connect.Response[v1.Subscription], error)// CreatePurchase creates a new subscription purchase (SaaS only).// Returns a Stripe Checkout URL for the user to complete payment.- CreatePurchase(context.Context, *connect.Request[v1.CreatePurchaseRequest]) (*connect.Response[v1.CreatePurchaseResponse], error)+ CreatePurchase(context.Context, *connect.Request[v1.CreatePurchaseRequest]) (*connect.Response[v1.PurchaseResponse], error)// UpdatePurchase updates an existing subscription (SaaS only).// May return a Stripe Checkout URL if payment method change is needed.- UpdatePurchase(context.Context, *connect.Request[v1.UpdatePurchaseRequest]) (*connect.Response[v1.UpdatePurchaseResponse], error)+ UpdatePurchase(context.Context, *connect.Request[v1.UpdatePurchaseRequest]) (*connect.Response[v1.PurchaseResponse], error)// CancelPurchase cancels an active subscription (SaaS only).- CancelPurchase(context.Context, *connect.Request[v1.CancelPurchaseRequest]) (*connect.Response[v1.CancelPurchaseResponse], error)+ CancelPurchase(context.Context, *connect.Request[v1.CancelPurchaseRequest]) (*connect.Response[v1.PurchaseResponse], error)// GetPaymentInfo returns payment details for the current subscription (SaaS only).GetPaymentInfo(context.Context, *connect.Request[v1.GetPaymentInfoRequest]) (*connect.Response[v1.PaymentInfo], error)+ // VerifyCheckoutSession verifies a Stripe Checkout Session status (SaaS only).+ VerifyCheckoutSession(context.Context, *connect.Request[v1.VerifyCheckoutSessionRequest]) (*connect.Response[v1.VerifyCheckoutSessionResponse], error)// ListPurchasePlans returns available plans for self-service purchase.ListPurchasePlans(context.Context, *connect.Request[v1.ListPurchasePlansRequest]) (*connect.Response[v1.ListPurchasePlansResponse], error)}@@ -97,25 +100,25 @@ func NewSubscriptionServiceClient(httpClient connect.HTTPClient, baseURL string,connect.WithSchema(subscriptionServiceMethods.ByName("GetSubscription")),connect.WithClientOptions(opts...),),- updateSubscription: connect.NewClient[v1.UpdateSubscriptionRequest, v1.Subscription](+ uploadLicense: connect.NewClient[v1.UploadLicenseRequest, v1.Subscription](httpClient,- baseURL+SubscriptionServiceUpdateSubscriptionProcedure,- connect.WithSchema(subscriptionServiceMethods.ByName("UpdateSubscription")),+ baseURL+SubscriptionServiceUploadLicenseProcedure,+ connect.WithSchema(subscriptionServiceMethods.ByName("UploadLicense")),connect.WithClientOptions(opts...),),- createPurchase: connect.NewClient[v1.CreatePurchaseRequest, v1.CreatePurchaseResponse](+ createPurchase: connect.NewClient[v1.CreatePurchaseRequest, v1.PurchaseResponse](httpClient,baseURL+SubscriptionServiceCreatePurchaseProcedure,connect.WithSchema(subscriptionServiceMethods.ByName("CreatePurchase")),connect.WithClientOptions(opts...),),- updatePurchase: connect.NewClient[v1.UpdatePurchaseRequest, v1.UpdatePurchaseResponse](+ updatePurchase: connect.NewClient[v1.UpdatePurchaseRequest, v1.PurchaseResponse](httpClient,baseURL+SubscriptionServiceUpdatePurchaseProcedure,connect.WithSchema(subscriptionServiceMethods.ByName("UpdatePurchase")),connect.WithClientOptions(opts...),),- cancelPurchase: connect.NewClient[v1.CancelPurchaseRequest, v1.CancelPurchaseResponse](+ cancelPurchase: connect.NewClient[v1.CancelPurchaseRequest, v1.PurchaseResponse](httpClient,baseURL+SubscriptionServiceCancelPurchaseProcedure,connect.WithSchema(subscriptionServiceMethods.ByName("CancelPurchase")),@@ -127,6 +130,12 @@ func NewSubscriptionServiceClient(httpClient connect.HTTPClient, baseURL string,connect.WithSchema(subscriptionServiceMethods.ByName("GetPaymentInfo")),connect.WithClientOptions(opts...),),+ verifyCheckoutSession: connect.NewClient[v1.VerifyCheckoutSessionRequest, v1.VerifyCheckoutSessionResponse](+ httpClient,+ baseURL+SubscriptionServiceVerifyCheckoutSessionProcedure,+ connect.WithSchema(subscriptionServiceMethods.ByName("VerifyCheckoutSession")),+ connect.WithClientOptions(opts...),+ ),listPurchasePlans: connect.NewClient[v1.ListPurchasePlansRequest, v1.ListPurchasePlansResponse](httpClient,baseURL+SubscriptionServiceListPurchasePlansProcedure,@@ -138,13 +147,14 @@ func NewSubscriptionServiceClient(httpClient connect.HTTPClient, baseURL string,// subscriptionServiceClient implements SubscriptionServiceClient.type subscriptionServiceClient struct {- getSubscription *connect.Client[v1.GetSubscriptionRequest, v1.Subscription]- updateSubscription *connect.Client[v1.UpdateSubscriptionRequest, v1.Subscription]- createPurchase *connect.Client[v1.CreatePurchaseRequest, v1.CreatePurchaseResponse]- updatePurchase *connect.Client[v1.UpdatePurchaseRequest, v1.UpdatePurchaseResponse]- cancelPurchase *connect.Client[v1.CancelPurchaseRequest, v1.CancelPurchaseResponse]- getPaymentInfo *connect.Client[v1.GetPaymentInfoRequest, v1.PaymentInfo]- listPurchasePlans *connect.Client[v1.ListPurchasePlansRequest, v1.ListPurchasePlansResponse]+ getSubscription *connect.Client[v1.GetSubscriptionRequest, v1.Subscription]+ uploadLicense *connect.Client[v1.UploadLicenseRequest, v1.Subscription]+ createPurchase *connect.Client[v1.CreatePurchaseRequest, v1.PurchaseResponse]+ updatePurchase *connect.Client[v1.UpdatePurchaseRequest, v1.PurchaseResponse]+ cancelPurchase *connect.Client[v1.CancelPurchaseRequest, v1.PurchaseResponse]+ getPaymentInfo *connect.Client[v1.GetPaymentInfoRequest, v1.PaymentInfo]+ verifyCheckoutSession *connect.Client[v1.VerifyCheckoutSessionRequest, v1.VerifyCheckoutSessionResponse]+ listPurchasePlans *connect.Client[v1.ListPurchasePlansRequest, v1.ListPurchasePlansResponse]}// GetSubscription calls bytebase.v1.SubscriptionService.GetSubscription.@@ -152,23 +162,23 @@ func (c *subscriptionServiceClient) GetSubscription(ctx context.Context, req *coreturn c.getSubscription.CallUnary(ctx, req)}-// UpdateSubscription calls bytebase.v1.SubscriptionService.UpdateSubscription.-func (c *subscriptionServiceClient) UpdateSubscription(ctx context.Context, req *connect.Request[v1.UpdateSubscriptionRequest]) (*connect.Response[v1.Subscription], error) {- return c.updateSubscription.CallUnary(ctx, req)+// UploadLicense calls bytebase.v1.SubscriptionService.UploadLicense.+func (c *subscriptionServiceClient) UploadLicense(ctx context.Context, req *connect.Request[v1.UploadLicenseRequest]) (*connect.Response[v1.Subscription], error) {+ return c.uploadLicense.CallUnary(ctx, req)}// CreatePurchase calls bytebase.v1.SubscriptionService.CreatePurchase.-func (c *subscriptionServiceClient) CreatePurchase(ctx context.Context, req *connect.Request[v1.CreatePurchaseRequest]) (*connect.Response[v1.CreatePurchaseResponse], error) {+func (c *subscriptionServiceClient) CreatePurchase(ctx context.Context, req *connect.Request[v1.CreatePurchaseRequest]) (*connect.Response[v1.PurchaseResponse], error) {return c.createPurchase.CallUnary(ctx, req)}// UpdatePurchase calls bytebase.v1.SubscriptionService.UpdatePurchase.-func (c *subscriptionServiceClient) UpdatePurchase(ctx context.Context, req *connect.Request[v1.UpdatePurchaseRequest]) (*connect.Response[v1.UpdatePurchaseResponse], error) {+func (c *subscriptionServiceClient) UpdatePurchase(ctx context.Context, req *connect.Request[v1.UpdatePurchaseRequest]) (*connect.Response[v1.PurchaseResponse], error) {return c.updatePurchase.CallUnary(ctx, req)}// CancelPurchase calls bytebase.v1.SubscriptionService.CancelPurchase.-func (c *subscriptionServiceClient) CancelPurchase(ctx context.Context, req *connect.Request[v1.CancelPurchaseRequest]) (*connect.Response[v1.CancelPurchaseResponse], error) {+func (c *subscriptionServiceClient) CancelPurchase(ctx context.Context, req *connect.Request[v1.CancelPurchaseRequest]) (*connect.Response[v1.PurchaseResponse], error) {return c.cancelPurchase.CallUnary(ctx, req)}@@ -177,6 +187,11 @@ func (c *subscriptionServiceClient) GetPaymentInfo(ctx context.Context, req *conreturn c.getPaymentInfo.CallUnary(ctx, req)}+// VerifyCheckoutSession calls bytebase.v1.SubscriptionService.VerifyCheckoutSession.+func (c *subscriptionServiceClient) VerifyCheckoutSession(ctx context.Context, req *connect.Request[v1.VerifyCheckoutSessionRequest]) (*connect.Response[v1.VerifyCheckoutSessionResponse], error) {+ return c.verifyCheckoutSession.CallUnary(ctx, req)+}+// ListPurchasePlans calls bytebase.v1.SubscriptionService.ListPurchasePlans.func (c *subscriptionServiceClient) ListPurchasePlans(ctx context.Context, req *connect.Request[v1.ListPurchasePlansRequest]) (*connect.Response[v1.ListPurchasePlansResponse], error) {return c.listPurchasePlans.CallUnary(ctx, req)@@ -187,21 +202,21 @@ type SubscriptionServiceHandler interface {// GetSubscription returns the current subscription.// If there is no license, we will return a free plan subscription without expiration time.// If there is expired license, we will return a free plan subscription with the expiration time of the expired license.- // Permissions required: NoneGetSubscription(context.Context, *connect.Request[v1.GetSubscriptionRequest]) (*connect.Response[v1.Subscription], error)- // Updates the enterprise license subscription (self-hosted only).- // Permissions required: bb.settings.set- UpdateSubscription(context.Context, *connect.Request[v1.UpdateSubscriptionRequest]) (*connect.Response[v1.Subscription], error)+ // Uploads an enterprise license (self-hosted only).+ UploadLicense(context.Context, *connect.Request[v1.UploadLicenseRequest]) (*connect.Response[v1.Subscription], error)// CreatePurchase creates a new subscription purchase (SaaS only).// Returns a Stripe Checkout URL for the user to complete payment.- CreatePurchase(context.Context, *connect.Request[v1.CreatePurchaseRequest]) (*connect.Response[v1.CreatePurchaseResponse], error)+ CreatePurchase(context.Context, *connect.Request[v1.CreatePurchaseRequest]) (*connect.Response[v1.PurchaseResponse], error)// UpdatePurchase updates an existing subscription (SaaS only).// May return a Stripe Checkout URL if payment method change is needed.- UpdatePurchase(context.Context, *connect.Request[v1.UpdatePurchaseRequest]) (*connect.Response[v1.UpdatePurchaseResponse], error)+ UpdatePurchase(context.Context, *connect.Request[v1.UpdatePurchaseRequest]) (*connect.Response[v1.PurchaseResponse], error)// CancelPurchase cancels an active subscription (SaaS only).- CancelPurchase(context.Context, *connect.Request[v1.CancelPurchaseRequest]) (*connect.Response[v1.CancelPurchaseResponse], error)+ CancelPurchase(context.Context, *connect.Request[v1.CancelPurchaseRequest]) (*connect.Response[v1.PurchaseResponse], error)// GetPaymentInfo returns payment details for the current subscription (SaaS only).GetPaymentInfo(context.Context, *connect.Request[v1.GetPaymentInfoRequest]) (*connect.Response[v1.PaymentInfo], error)+ // VerifyCheckoutSession verifies a Stripe Checkout Session status (SaaS only).+ VerifyCheckoutSession(context.Context, *connect.Request[v1.VerifyCheckoutSessionRequest]) (*connect.Response[v1.VerifyCheckoutSessionResponse], error)// ListPurchasePlans returns available plans for self-service purchase.ListPurchasePlans(context.Context, *connect.Request[v1.ListPurchasePlansRequest]) (*connect.Response[v1.ListPurchasePlansResponse], error)}@@ -219,10 +234,10 @@ func NewSubscriptionServiceHandler(svc SubscriptionServiceHandler, opts ...conneconnect.WithSchema(subscriptionServiceMethods.ByName("GetSubscription")),connect.WithHandlerOptions(opts...),)- subscriptionServiceUpdateSubscriptionHandler := connect.NewUnaryHandler(- SubscriptionServiceUpdateSubscriptionProcedure,- svc.UpdateSubscription,- connect.WithSchema(subscriptionServiceMethods.ByName("UpdateSubscription")),+ subscriptionServiceUploadLicenseHandler := connect.NewUnaryHandler(+ SubscriptionServiceUploadLicenseProcedure,+ svc.UploadLicense,+ connect.WithSchema(subscriptionServiceMethods.ByName("UploadLicense")),connect.WithHandlerOptions(opts...),)subscriptionServiceCreatePurchaseHandler := connect.NewUnaryHandler(@@ -249,6 +264,12 @@ func NewSubscriptionServiceHandler(svc SubscriptionServiceHandler, opts ...conneconnect.WithSchema(subscriptionServiceMethods.ByName("GetPaymentInfo")),connect.WithHandlerOptions(opts...),)+ subscriptionServiceVerifyCheckoutSessionHandler := connect.NewUnaryHandler(+ SubscriptionServiceVerifyCheckoutSessionProcedure,+ svc.VerifyCheckoutSession,+ connect.WithSchema(subscriptionServiceMethods.ByName("VerifyCheckoutSession")),+ connect.WithHandlerOptions(opts...),+ )subscriptionServiceListPurchasePlansHandler := connect.NewUnaryHandler(SubscriptionServiceListPurchasePlansProcedure,svc.ListPurchasePlans,@@ -259,8 +280,8 @@ func NewSubscriptionServiceHandler(svc SubscriptionServiceHandler, opts ...conneswitch r.URL.Path {case SubscriptionServiceGetSubscriptionProcedure:subscriptionServiceGetSubscriptionHandler.ServeHTTP(w, r)- case SubscriptionServiceUpdateSubscriptionProcedure:- subscriptionServiceUpdateSubscriptionHandler.ServeHTTP(w, r)+ case SubscriptionServiceUploadLicenseProcedure:+ subscriptionServiceUploadLicenseHandler.ServeHTTP(w, r)case SubscriptionServiceCreatePurchaseProcedure:subscriptionServiceCreatePurchaseHandler.ServeHTTP(w, r)case SubscriptionServiceUpdatePurchaseProcedure:@@ -269,6 +290,8 @@ func NewSubscriptionServiceHandler(svc SubscriptionServiceHandler, opts ...connesubscriptionServiceCancelPurchaseHandler.ServeHTTP(w, r)case SubscriptionServiceGetPaymentInfoProcedure:subscriptionServiceGetPaymentInfoHandler.ServeHTTP(w, r)+ case SubscriptionServiceVerifyCheckoutSessionProcedure:+ subscriptionServiceVerifyCheckoutSessionHandler.ServeHTTP(w, r)case SubscriptionServiceListPurchasePlansProcedure:subscriptionServiceListPurchasePlansHandler.ServeHTTP(w, r)default:@@ -284,19 +307,19 @@ func (UnimplementedSubscriptionServiceHandler) GetSubscription(context.Context,return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.SubscriptionService.GetSubscription is not implemented"))}-func (UnimplementedSubscriptionServiceHandler) UpdateSubscription(context.Context, *connect.Request[v1.UpdateSubscriptionRequest]) (*connect.Response[v1.Subscription], error) {- return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.SubscriptionService.UpdateSubscription is not implemented"))+func (UnimplementedSubscriptionServiceHandler) UploadLicense(context.Context, *connect.Request[v1.UploadLicenseRequest]) (*connect.Response[v1.Subscription], error) {+ return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.SubscriptionService.UploadLicense is not implemented"))}-func (UnimplementedSubscriptionServiceHandler) CreatePurchase(context.Context, *connect.Request[v1.CreatePurchaseRequest]) (*connect.Response[v1.CreatePurchaseResponse], error) {+func (UnimplementedSubscriptionServiceHandler) CreatePurchase(context.Context, *connect.Request[v1.CreatePurchaseRequest]) (*connect.Response[v1.PurchaseResponse], error) {return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.SubscriptionService.CreatePurchase is not implemented"))}-func (UnimplementedSubscriptionServiceHandler) UpdatePurchase(context.Context, *connect.Request[v1.UpdatePurchaseRequest]) (*connect.Response[v1.UpdatePurchaseResponse], error) {+func (UnimplementedSubscriptionServiceHandler) UpdatePurchase(context.Context, *connect.Request[v1.UpdatePurchaseRequest]) (*connect.Response[v1.PurchaseResponse], error) {return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.SubscriptionService.UpdatePurchase is not implemented"))}-func (UnimplementedSubscriptionServiceHandler) CancelPurchase(context.Context, *connect.Request[v1.CancelPurchaseRequest]) (*connect.Response[v1.CancelPurchaseResponse], error) {+func (UnimplementedSubscriptionServiceHandler) CancelPurchase(context.Context, *connect.Request[v1.CancelPurchaseRequest]) (*connect.Response[v1.PurchaseResponse], error) {return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.SubscriptionService.CancelPurchase is not implemented"))}@@ -304,6 +327,10 @@ func (UnimplementedSubscriptionServiceHandler) GetPaymentInfo(context.Context, *return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.SubscriptionService.GetPaymentInfo is not implemented"))}+func (UnimplementedSubscriptionServiceHandler) VerifyCheckoutSession(context.Context, *connect.Request[v1.VerifyCheckoutSessionRequest]) (*connect.Response[v1.VerifyCheckoutSessionResponse], error) {+ return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.SubscriptionService.VerifyCheckoutSession is not implemented"))+}+func (UnimplementedSubscriptionServiceHandler) ListPurchasePlans(context.Context, *connect.Request[v1.ListPurchasePlansRequest]) (*connect.Response[v1.ListPurchasePlansResponse], error) {return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.SubscriptionService.ListPurchasePlans is not implemented"))}diff --git a/backend/plugin/stripe/stripe.go b/backend/plugin/stripe/stripe.goindex eefd8d409b..b072884774 100644--- a/backend/plugin/stripe/stripe.go+++ b/backend/plugin/stripe/stripe.go@@ -38,8 +38,14 @@ type CheckoutParams struct {PromotionCode string // optional promotion code string}-// CreateCheckoutSession creates a Stripe Checkout Session and returns the checkout URL.-func CreateCheckoutSession(params *CheckoutParams) (string, error) {+// CheckoutResult contains the result of creating a checkout session.+type CheckoutResult struct {+ URL string+ SessionID string+}++// CreateCheckoutSession creates a Stripe Checkout Session and returns the URL and session ID.+func CreateCheckoutSession(params *CheckoutParams) (*CheckoutResult, error) {priceInCents := params.PriceModel.GetPrice()metadata := GetMetadata(params.Workspace, params.PriceModel)@@ -88,9 +94,33 @@ func CreateCheckoutSession(params *CheckoutParams) (string, error) {s, err := checkoutsession.New(checkoutParams)if err != nil {- return "", errors.Wrap(err, "failed to create checkout session")+ return nil, errors.Wrap(err, "failed to create checkout session")}- return s.URL, nil+ return &CheckoutResult{URL: s.URL, SessionID: s.ID}, nil+}++// CheckoutSessionInfo contains the status and workspace of a checkout session.+type CheckoutSessionInfo struct {+ Status string+ Workspace string+}++// GetCheckoutSessionInfo returns the status and workspace of a Stripe Checkout Session.+func GetCheckoutSessionInfo(sessionID string) (*CheckoutSessionInfo, error) {+ params := &stripego.CheckoutSessionParams{}+ params.AddExpand("subscription")+ s, err := checkoutsession.Get(sessionID, params)+ if err != nil {+ return nil, errors.Wrapf(err, "failed to get checkout session %s", sessionID)+ }+ var workspace string+ if s.Subscription != nil {+ workspace = s.Subscription.Metadata["workspace"]+ }+ return &CheckoutSessionInfo{+ Status: string(s.Status),+ Workspace: workspace,+ }, nil}// CancelSubscription cancels a Stripe subscription.@@ -194,14 +224,6 @@ func GetSubscription(stripeSubID string, expand []string) (*stripego.Subscriptioreturn sub, nil}-// UpdateSubscriptionMetadata updates the metadata on a Stripe subscription.-func UpdateSubscriptionMetadata(stripeSubID string, metadata map[string]string) error {- _, err := stripesubscription.Update(stripeSubID, &stripego.SubscriptionParams{- Metadata: metadata,- })- return errors.Wrapf(err, "failed to update stripe subscription metadata %s", stripeSubID)-}-// GetMetadata builds the metadata map for a Stripe subscription.func GetMetadata(workspace string, model *pricing.PriceModel) map[string]string {return map[string]string{diff --git a/backend/server/echo_routes.go b/backend/server/echo_routes.goindex a6cb67a0e0..2807c648ec 100644--- a/backend/server/echo_routes.go+++ b/backend/server/echo_routes.go@@ -83,9 +83,9 @@ func configureEchoRouters(scimGroup := hookGroup.Group(scimAPIPrefix)directorySyncServer.RegisterDirectorySyncRoutes(scimGroup)- // Stripe (SaaS only).- if profile.SaaS && profile.StripeAPIKey != "" {- stripeplugin.Init(profile.StripeAPIKey)+ // Stripe (SaaS only, requires both API key and webhook secret).+ if profile.SaaS && profile.StripeAPISecret != "" && profile.StripeWebhookSecret != "" {+ stripeplugin.Init(profile.StripeAPISecret)stripeGroup := hookGroup.Group("/stripe")stripeWebhookHandler.RegisterRoutes(stripeGroup)}diff --git a/backend/server/server.go b/backend/server/server.goindex 0024c908dd..f24eaaa0da 100644--- a/backend/server/server.go+++ b/backend/server/server.go@@ -155,7 +155,7 @@ func NewServer(ctx context.Context, profile *config.Profile) (*Server, error) {s.store = storessheetManager := sheet.NewManager()- s.licenseService, err = enterprise.NewLicenseService(profile.Mode, stores, profile.SaaS)+ s.licenseService, err = enterprise.NewLicenseService(profile.Mode, stores, profile.SaaS, profile.LicensePrivateKey)if err != nil {return nil, errors.Wrap(err, "failed to create license service")}diff --git a/backend/store/subscription.go b/backend/store/subscription.goindex bb7ffc88f3..2ee92d15cf 100644--- a/backend/store/subscription.go+++ b/backend/store/subscription.go@@ -22,22 +22,30 @@ type SubscriptionMessage struct {UpdatedAt time.Time}-// CreateSubscription creates a new subscription.-func (s *Store) CreateSubscription(ctx context.Context, create *SubscriptionMessage) (*SubscriptionMessage, error) {- payload, err := protojson.Marshal(create.Payload)+// UpsertSubscription creates or updates a subscription by workspace.+func (s *Store) UpsertSubscription(ctx context.Context, workspace string, payload *storepb.SubscriptionPayload) (*SubscriptionMessage, error) {+ p, err := protojson.Marshal(payload)if err != nil {return nil, errors.Wrapf(err, "failed to marshal payload")}+ sub := &SubscriptionMessage{+ Payload: &storepb.SubscriptionPayload{},+ }+ var payloadBytes []byteif err := s.GetDB().QueryRowContext(ctx,- `INSERT INTO subscription (workspace, payload) VALUES ($1, $2) RETURNING created_at, updated_at`,- create.Workspace, payload,- ).Scan(&create.CreatedAt, &create.UpdatedAt); err != nil {- return nil, errors.Wrapf(err, "failed to insert subscription")+ `INSERT INTO subscription (workspace, payload) VALUES ($1, $2)+ ON CONFLICT (workspace) DO UPDATE SET payload = $2, updated_at = now()+ RETURNING workspace, payload, created_at, updated_at`,+ workspace, p,+ ).Scan(&sub.Workspace, &payloadBytes, &sub.CreatedAt, &sub.UpdatedAt); err != nil {+ return nil, errors.Wrapf(err, "failed to upsert subscription")}- create.Etag = generateEtag(create.UpdatedAt)-- return create, nil+ if err := common.ProtojsonUnmarshaler.Unmarshal(payloadBytes, sub.Payload); err != nil {+ return nil, errors.Wrapf(err, "failed to unmarshal payload")+ }+ sub.Etag = fmt.Sprintf("%d", sub.UpdatedAt.UnixMilli())+ return sub, nil}// GetSubscriptionByWorkspace gets a subscription by workspace.@@ -62,28 +70,3 @@ func (s *Store) GetSubscriptionByWorkspace(ctx context.Context, workspace stringsub.Etag = generateEtag(sub.UpdatedAt)return sub, nil}--// UpdateSubscription updates a subscription by workspace.-func (s *Store) UpdateSubscription(ctx context.Context, workspace string, payload *storepb.SubscriptionPayload) (*SubscriptionMessage, error) {- p, err := protojson.Marshal(payload)- if err != nil {- return nil, errors.Wrapf(err, "failed to marshal payload")- }-- sub := &SubscriptionMessage{- Payload: &storepb.SubscriptionPayload{},- }- var payloadBytes []byte- if err := s.GetDB().QueryRowContext(ctx,- `UPDATE subscription SET payload = $1, updated_at = now() WHERE workspace = $2- RETURNING workspace, payload, created_at, updated_at`,- p, workspace,- ).Scan(&sub.Workspace, &payloadBytes, &sub.CreatedAt, &sub.UpdatedAt); err != nil {- return nil, errors.Wrapf(err, "failed to update subscription")- }- if err := common.ProtojsonUnmarshaler.Unmarshal(payloadBytes, sub.Payload); err != nil {- return nil, errors.Wrapf(err, "failed to unmarshal payload")- }- sub.Etag = fmt.Sprintf("%d", sub.UpdatedAt.UnixMilli())- return sub, nil-}diff --git a/backend/tests/subscription.go b/backend/tests/subscription.goindex 9d7ef78a8e..7d31c83a5a 100644--- a/backend/tests/subscription.go+++ b/backend/tests/subscription.go@@ -10,7 +10,7 @@ import ()func (ctl *controller) setLicense(ctx context.Context) error {- if _, err := ctl.subscriptionServiceClient.UpdateSubscription(ctx, connect.NewRequest(&v1pb.UpdateSubscriptionRequest{+ if _, err := ctl.subscriptionServiceClient.UploadLicense(ctx, connect.NewRequest(&v1pb.UploadLicenseRequest{License: "eyJhbGciOiJSUzI1NiIsImtpZCI6InYxIiwidHlwIjoiSldUIn0.eyJpbnN0YW5jZUNvdW50Ijo5OTksInRyaWFsaW5nIjpmYWxzZSwicGxhbiI6IkVOVEVSUFJJU0UiLCJvcmdOYW1lIjoiYmIiLCJhdWQiOiJiYi5saWNlbnNlIiwiZXhwIjo3OTc0OTc5MjAwLCJpYXQiOjE2NjM2Njc1NjEsImlzcyI6ImJ5dGViYXNlIiwic3ViIjoiMDAwMDEwMDAuIn0.JjYCMeAAMB9FlVeDFLdN3jvFcqtPsbEzaIm1YEDhUrfekthCbIOeX_DB2Bg2OUji3HSX5uDvG9AkK4Gtrc4gLMPI3D5mk3L-6wUKZ0L4REztS47LT4oxVhpqPQayYa9lKJB1YoHaqeMV4Z5FXeOXwuACoELznlwpT6pXo9xXm_I6QwQiO7-zD83XOTO4PRjByc-q3GKQu_64zJMIKiCW0I8a3GvrdSnO7jUuYU1KPmCuk0ZRq3I91m29LTo478BMST59HqCLj1GGuCKtR3SL_376XsZfUUM0iSAur5scg99zNGWRj-sUo05wbAadYx6V6TKaWrBUi_8_0RnJyP5gbA",})); err != nil {return errors.Wrap(err, "failed to set license")@@ -19,7 +19,7 @@ func (ctl *controller) setLicense(ctx context.Context) error {}func (ctl *controller) removeLicense(ctx context.Context) error {- if _, err := ctl.subscriptionServiceClient.UpdateSubscription(ctx, connect.NewRequest(&v1pb.UpdateSubscriptionRequest{+ if _, err := ctl.subscriptionServiceClient.UploadLicense(ctx, connect.NewRequest(&v1pb.UploadLicenseRequest{License: "",})); err != nil {return errors.Wrap(err, "failed to remove license")diff --git a/docs/plans/saas/08.in-app-purchase.md b/docs/plans/saas/08.in-app-purchase.mdindex 0b853c3aa0..01f14905bd 100644--- a/docs/plans/saas/08.in-app-purchase.md+++ b/docs/plans/saas/08.in-app-purchase.md@@ -10,573 +10,486 @@ Move the purchase workflow from the hub codebase into the Bytebase codebase so S**Out of scope**: GCP deployment, Paddle, self-host license download, Auth0, Mailchimp, Slack notifications, cloud workspace provisioning.-**Guiding principle**: Non-SaaS hides the purchase UI and rejects purchase APIs. The existing `UpdateSubscription` (manual JWT upload) remains for self-hosted.+**Guiding principle**: Non-SaaS hides the purchase UI and rejects purchase APIs. The existing `UploadLicense` (manual JWT upload) remains for self-hosted.----## Current State+## Workflow Overview-### Bytebase (this codebase)+The purchase system has three actors: the **frontend** (Vue SPA), the **backend** (gRPC API + Echo webhook handler), and **Stripe** (payment processor). All subscription state flows through Stripe webhooks — the backend never writes subscription records directly from API calls (except during webhook processing). This ensures Stripe remains the single source of truth for payment state.-- **License storage**: JWT string in `setting` table (workspace-scoped), key `(workspace, "bb.workspace.license")`.-- **License parsing**: `enterprise/license.go` — RSA256 JWT with claims `{seat, instanceCount, instance, plan, orgName, workspaceId, ha, trialing}`.-- **LicenseService**: `LoadSubscription(ctx, workspaceID)` → cached `*v1pb.Subscription`. `StoreLicense(ctx, workspaceID, jwt)` → validates + persists.-- **API**: `GetSubscription` (unauthenticated), `UpdateSubscription` (manual JWT upload, `bb.settings.set`).-- **Frontend**: `SettingWorkspaceSubscription.vue` — shows plan info, textarea for JWT upload (self-host only).-- **Webhook infra**: Echo routes under `/hook/` (SCIM already registered here).+### Architecture Diagram-### Hub (source of truth for purchase logic)--- **Subscription table**: `id, org, instance_count, seat, interval, status, expires_at, payload(JSONB)`.-- **Stripe checkout**: Creates `CheckoutSession` with dynamic `PriceData`, metadata `{sub_id, plan, interval, instance_count, user_count, source}`.-- **Stripe webhooks**: `customer.subscription.created/updated/paused/resumed/deleted`, `invoice.paid`.-- **Cancellation**: Monthly = immediate proration + refund across charges. Annual = cancel at period end.-- **Subscription update**: Cancel old Stripe sub → create new one with existing customer's payment method.-- **Pricing**: `PlanLimitConfig` per plan type, `PriceModel` calculates total from base + additionals.-- **License generation**: RS256 JWT with same claims structure as Bytebase parser expects.+```+┌─────────────────────────────────────────────────────────────────────────────────────┐+│ FRONTEND │+│ │+│ SettingWorkspaceSubscription.vue │+│ ├── Plan info, expiry, user stats (both modes) │+│ ├── [SaaS] SettingWorkspacePurchase.vue │+│ │ ├── PlanCard (FREE / Pro / Enterprise) │+│ │ ├── Seat counter, billing interval, terms checkbox │+│ │ ├── Subscribe / Update / Cancel buttons │+│ │ └── Pending payment spinner + polling │+│ └── [Self-hosted] License textarea upload │+│ │+│ Pinia Store: subscription.ts │+│ ├── createPurchase(plan, interval, seats) → paymentUrl │+│ ├── updatePurchase(plan, interval, seats, etag) → paymentUrl │+│ ├── cancelPurchase() │+│ ├── verifyCheckoutSession(sessionId) → status │+│ ├── fetchPaymentInfo() → PaymentInfo │+│ └── fetchPurchasePlans() → PurchasePlan[] │+└──────────────┬──────────────────────────────────────────────────┬────────────────────┘+ │ gRPC (ConnectRPC) │ HTTP redirect+ ▼ ▼+┌──────────────────────────────────┐ ┌────────────────────────────────────────┐+│ BACKEND │ │ STRIPE │+│ │ │ │+│ SubscriptionService (gRPC) │────────▶│ Checkout Session │+│ ├── CreatePurchase │ API │ ├── Dynamic PriceData │+│ ├── UpdatePurchase │ calls │ ├── Metadata (workspace, plan, ...) │+│ ├── CancelPurchase │ │ └── Success/Cancel redirect URLs │+│ ├── GetPaymentInfo │ │ │+│ ├── VerifyCheckoutSession │ │ Subscription lifecycle │+│ └── ListPurchasePlans │ │ ├── customer.subscription.created │+│ │ │ ├── customer.subscription.updated │+│ WebhookHandler (Echo) │◀────────│ ├── customer.subscription.deleted │+│ POST /hook/stripe/callback │ webhook │ ├── customer.subscription.paused │+│ ├── Signature verification │ │ ├── customer.subscription.resumed │+│ ├── handleSubscriptionStatus │ │ └── invoice.paid │+│ └── handleInvoicePaid │ │ │+│ │ └────────────────────────────────────────┘+│ Store layer │+│ ├── subscription table (PK=workspace) │+│ └── UpsertSubscription (INSERT ON CONFLICT DO UPDATE) │+│ │+│ LicenseService │+│ ├── CreateLicense (sign JWT) │+│ ├── StoreLicense (setting table)│+│ └── LoadSubscription (JWT → v1pb.Subscription, cached w/ singleflight) │+└──────────────────────────────────┘+```----## Design+## Data Model-### 1. Database: `subscription` Table+### `subscription` Table-Minimal table — `workspace` is the PK (one subscription per workspace). All subscription data lives in `payload` JSONB so the schema can evolve without DDL migrations. `etag` is derived from `updated_at` (same pattern as IAM policy).+One row per workspace. All subscription data in `payload` JSONB to evolve without DDL migrations.```sqlCREATE TABLE subscription (workspace text NOT NULL REFERENCES workspace(resource_id) PRIMARY KEY,- -- Stored as SubscriptionPayload (proto/store/store/subscription.proto)payload jsonb NOT NULL DEFAULT '{}',created_at timestamptz NOT NULL DEFAULT now(),updated_at timestamptz NOT NULL DEFAULT now());```-**Payload** (proto, stored as JSONB via `protojson.Marshal` → camelCase keys):+### `SubscriptionPayload` (proto → JSONB via `protojson.Marshal`, camelCase keys)```protobuf-// proto/store/store/subscription.protomessage SubscriptionPayload {- enum Status {- STATUS_UNSPECIFIED = 0;- PENDING = 1;- ACTIVE = 2;- PAUSED = 3;- CANCELED = 4;- }-- enum Plan {- PLAN_UNSPECIFIED = 0;- TEAM = 1;- ENTERPRISE = 2;- }-- enum BillingInterval {- BILLING_INTERVAL_UNSPECIFIED = 0;- MONTH = 1;- YEAR = 2;- }-- // Lifecycle+ enum Status { STATUS_UNSPECIFIED=0; PENDING=1; ACTIVE=2; PAUSED=3; CANCELED=4; }+ enum Plan { PLAN_UNSPECIFIED=0; TEAM=1; ENTERPRISE=2; }+ enum BillingInterval { BILLING_INTERVAL_UNSPECIFIED=0; MONTH=1; YEAR=2; }+Status status = 1;google.protobuf.Timestamp started_at = 2;google.protobuf.Timestamp expires_at = 3;-- // Billing detailsPlan plan = 4;BillingInterval interval = 5;int32 seat = 6;int32 instance_count = 7;-- // Stripe integrationstring stripe_subscription_id = 8;string stripe_customer_id = 9;}```-`Plan` and `BillingInterval` are local enums (store proto does not import v1 proto). `protojson.Marshal` serializes enums as string names (e.g., `"TEAM"`, `"MONTH"`) in JSONB.--### 2. Store Layer--New file: `backend/store/subscription.go`--```go-type SubscriptionMessage struct {- Workspace string- Payload *storepb.SubscriptionPayload- Etag string // derived from UpdatedAt (unix millis), not stored- CreatedAt time.Time- UpdatedAt time.Time-}--func (s *Store) CreateSubscription(ctx, create *SubscriptionMessage) (*SubscriptionMessage, error)-func (s *Store) GetSubscriptionByWorkspace(ctx, workspace string) (*SubscriptionMessage, error)-func (s *Store) UpdateSubscription(ctx, workspace string, payload *SubscriptionPayload) (*SubscriptionMessage, error)-```--- `workspace` is the PK — no separate ID, no find struct.-- `Etag` derived from `updated_at` via `generateEtag()` (same as IAM policy), not a stored column.-- `UpdateSubscription` always replaces the full payload atomically.--### 3. Proto Changes--Extend `proto/v1/v1/subscription_service.proto`:--```protobuf-service SubscriptionService {- // Existing- rpc GetSubscription(GetSubscriptionRequest) returns (Subscription) { ... }- rpc UpdateSubscription(UpdateSubscriptionRequest) returns (Subscription) { ... }-- // New — SaaS purchase flow- rpc CreatePurchase(CreatePurchaseRequest) returns (CreatePurchaseResponse) {- option (google.api.http) = {- post: "/v1/subscription:purchase"- body: "*"- };- option (bytebase.v1.permission) = "bb.settings.set";- option (bytebase.v1.auth_method) = IAM;- }-- rpc UpdatePurchase(UpdatePurchaseRequest) returns (UpdatePurchaseResponse) {- option (google.api.http) = {- post: "/v1/subscription:updatePurchase"- body: "*"- };- option (bytebase.v1.permission) = "bb.settings.set";- option (bytebase.v1.auth_method) = IAM;- }-- rpc CancelPurchase(CancelPurchaseRequest) returns (CancelPurchaseResponse) {- option (google.api.http) = {- post: "/v1/subscription:cancelPurchase"- body: "*"- };- option (bytebase.v1.permission) = "bb.settings.set";- option (bytebase.v1.auth_method) = IAM;- }-- rpc GetPaymentInfo(GetPaymentInfoRequest) returns (PaymentInfo) {- option (google.api.http) = {get: "/v1/subscription/paymentInfo"};- option (bytebase.v1.permission) = "bb.settings.set";- option (bytebase.v1.auth_method) = IAM;- }-- rpc ListPlans(ListPlansRequest) returns (ListPlansResponse) {- option (google.api.http) = {get: "/v1/subscription/plans"};- option (bytebase.v1.allow_without_credential) = true;- }-}--message CreatePurchaseRequest {- PlanType plan = 1;- BillingInterval interval = 2;- int32 seats = 3;-}--message CreatePurchaseResponse {- string payment_url = 1; // Stripe Checkout URL-}--message UpdatePurchaseRequest {- PlanType plan = 1;- BillingInterval interval = 2;- int32 seats = 3;- string etag = 4;-}--message UpdatePurchaseResponse {- // If payment_url is set, redirect to Stripe Checkout.- // If empty, the update was applied directly (existing payment method reused).- string payment_url = 1;-}--message CancelPurchaseRequest {- string etag = 1;-}--message CancelPurchaseResponse {}+### License Storage-message GetPaymentInfoRequest {}+The license JWT is stored separately in the `setting` table (key `bb.workspace.license`). The webhook handler generates a JWT from the subscription payload and stores it via `LicenseService.StoreLicense`. `LicenseService.LoadSubscription` parses the JWT to produce `v1pb.Subscription`, cached in an LRU with singleflight dedup.-message PaymentInfo {- string total_price = 1;- string currency = 2;- string period_start = 3;- string period_end = 4;- string invoice_url = 5; // Stripe Billing Portal URL-}--enum BillingInterval {- BILLING_INTERVAL_UNSPECIFIED = 0;- MONTH = 1;- YEAR = 2;-}+### Etag-message PurchasePlan {- PlanType type = 1;- bool self_service_purchase = 2;- repeated PurchasePlanAdditional additionals = 3;- repeated PurchaseBillingMethod billing_methods = 4;-}--message PurchasePlanAdditional {- enum Type {- TYPE_UNSPECIFIED = 0;- USER = 1;- }- Type type = 1;- int32 unit_price = 2; // cents per month- int32 free_count = 3;- int32 minimum_count = 4;- int32 maximum_count = 5; // -1 = unlimited-}+Derived from `updated_at` (unix millis), not a stored column. Used for optimistic concurrency in `UpdatePurchase`.-message PurchaseBillingMethod {- BillingInterval interval = 1;- PurchaseDiscount discount = 2;-}--message PurchaseDiscount {- string description = 1;- string promotion_code = 2;-}+----message ListPlansRequest {}+## Purchase Flow (New Subscription)-message ListPlansResponse {- repeated PurchasePlan plans = 1;-}+```+ User Frontend Backend Stripe+ │ │ │ │+ │ Select plan, seats │ │ │+ │ Accept terms │ │ │+ │ Click "Subscribe" │ │ │+ │ ───────────────────────▶│ │ │+ │ │ CreatePurchase(plan, │ │+ │ │ interval, seats) │ │+ │ │ ─────────────────────────▶│ │+ │ │ │ Check no active sub │+ │ │ │ Validate plan + pricing │+ │ │ │ CreateCheckoutSession() │+ │ │ │ ─────────────────────────▶│+ │ │ │ ◀── session URL ─────────│+ │ │ ◀── { paymentUrl } ──────│ │+ │ ◀── redirect ──────────│ │ │+ │ │ │ │+ │ ══════════════════ Stripe Checkout (hosted page) ═══════════════════════════════+ │ Enter card, complete │ │ │+ │ ───────────────────────────────────────────────────────────────────────────────▶│+ │ │ │ │+ │ ◀── redirect to /setting/subscription?session_id=cs_xxx ──────────────────────│+ │ ───────────────────────▶│ │ │+ │ │ VerifyCheckoutSession │ │+ │ │ (session_id) │ │+ │ │ ─────────────────────────▶│ GetCheckoutSessionStatus │+ │ │ │ ─────────────────────────▶│+ │ │ │ ◀── "complete" ──────────│+ │ │ ◀── "complete" ──────────│ │+ │ │ │ │+ │ Show spinner │ │ ┌─── Webhook ───────────│+ │ "Activating..." │ │ │ invoice.paid │+ │ │ │ │ │+ │ │ │ ▼ │+ │ │ │ Verify signature │+ │ │ │ Parse metadata │+ │ │ │ UpsertSubscription │+ │ │ │ (status=ACTIVE, │+ │ │ │ plan, seats, expiry) │+ │ │ │ CreateLicense (JWT) │+ │ │ │ StoreLicense │+ │ │ │ │+ │ │ Poll GetSubscription │ │+ │ │ (every 2s, max 30x, │ │+ │ │ no store update to │ │+ │ │ avoid FREE flash) │ │+ │ │ ─────────────────────────▶│ │+ │ │ ◀── plan=TEAM ───────────│ │+ │ │ Update store │ │+ │ Show active sub ◀──────│ │ │```-**Why separate `CreatePurchase`/`UpdatePurchase`/`CancelPurchase` from existing `UpdateSubscription`?**-- `UpdateSubscription` is the self-hosted JWT upload path (will be disabled in SaaS).-- Purchase RPCs are SaaS-only and involve Stripe interaction.-- Clean separation — no conditional logic mixing two unrelated flows.--### 4. Pricing Module--New package: `backend/enterprise/pricing/`--Port from hub with simplifications:+**Key details:**-```go-// backend/enterprise/pricing/plan.go+1. `CreatePurchase` is **stateless** — it only creates a Stripe Checkout Session and returns the URL. No subscription record is written.+2. The subscription record is created only when the `invoice.paid` webhook arrives from Stripe.+3. The frontend polls `GetSubscription` after redirect, using `cache=false` to avoid updating the Pinia store until the plan is confirmed (prevents UI flashing FREE → PAID).+4. `CreatePurchase` blocks if the workspace already has an ACTIVE or PAUSED subscription.-type PlanLimitConfig struct {- Type v1pb.PlanType- FreeSeatCount int- MaximumSeatCount int // -1 = unlimited- PricePerSeatPerMonth int64 // cents-}+----var planLimits = map[v1pb.PlanType]*PlanLimitConfig{- v1pb.PlanType_FREE: {- FreeSeatCount: 20,- MaximumSeatCount: 20,- PricePerSeatPerMonth: 0,- },- v1pb.PlanType_TEAM: {- FreeSeatCount: 0,- MaximumSeatCount: -1, // unlimited- PricePerSeatPerMonth: 2000, // $20/user/month in cents- },-}+## Update Flow (Plan/Seat Change)-// ListPlans returns purchase plans for the API.-func ListPlans() []*v1pb.PurchasePlan { ... }```--```go-// backend/enterprise/pricing/pricing.go--type PriceModel struct {- Plan *PlanLimitConfig- Interval v1pb.BillingInterval- Seats int32-}--// GetPrice returns total price in USD cents.-func (m *PriceModel) GetPrice() (int64, error) {- // seats × pricePerSeat × intervalMonths- // Apply discount for annual billing if configured-}--// GetStripeInterval converts to Stripe interval string.-func (m *PriceModel) GetStripeInterval() string { ... }+ User Frontend Backend Stripe+ │ │ │ │+ │ Change seats │ │ │+ │ Click "Update" │ │ │+ │ ───────────────────────▶│ │ │+ │ │ UpdatePurchase(plan, │ │+ │ │ interval, seats, etag) │ │+ │ │ ─────────────────────────▶│ │+ │ │ │ GetSubscriptionByWorkspace│+ │ │ │ (etag check if provided) │+ │ │ │ │+ │ │ │ ┌─ Has active sub? ──────┐+ │ │ │ │ YES │+ │ │ │ │ GetSubscription(old) │+ │ │ │ │ ─────────────────────▶ │+ │ │ │ │ ◀── old sub + PM ──── │+ │ │ │ │ │+ │ │ │ │ CancelSubscription │+ │ │ │ │ (old, prorate=true) │+ │ │ │ │ ─────────────────────▶ │+ │ │ │ │ │+ │ │ │ │ CreateSubscription │+ │ │ │ │ Direct(customer, │+ │ │ │ │ payment method, │+ │ │ │ │ new price) │+ │ │ │ │ ─────────────────────▶ │+ │ │ │ │ ◀── new sub ──────── │+ │ │ │ └───────────────────────┘+ │ │ │ │+ │ │ ◀── { paymentUrl: "" } ──│ (empty = direct success)│+ │ │ │ │+ │ Show spinner │ │ ┌─── Webhooks ──────────│+ │ "Activating..." │ │ │ sub.deleted (old) │+ │ │ │ │ invoice.paid (new) │+ │ │ │ ▼ │+ │ │ │ Stale event filter: │+ │ │ │ old sub.deleted ignored │+ │ │ │ if StripeSubscriptionId │+ │ │ │ already points to new │+ │ │ │ │+ │ │ Poll GetSubscription │ │+ │ │ (match seats to confirm) │ │+ │ │ ─────────────────────────▶│ │+ │ │ ◀── updated sub ─────────│ │+ │ Show updated sub ◀─────│ │ │```-**Dropped from hub**: `PricePerInstancePerMonth` (TEAM has fixed 10 instances), multi-currency support, Paddle price maps.--### 5. Stripe Plugin--New package: `backend/plugin/stripe/`--```go-// backend/plugin/stripe/stripe.go--// Init sets the Stripe API key from config. Called at server startup.-func Init(apiKey string) {- stripe.Key = apiKey-}+**Key details:**-// CreateCheckoutSession creates a Stripe Checkout Session for subscription purchase.-func CreateCheckoutSession(params *CheckoutParams) (string, error) { ... }+1. The backend reuses the existing customer and payment method from the old Stripe subscription.+2. The old subscription is canceled immediately (with proration), then a new one is created via `CreateSubscriptionDirect`.+3. If the direct creation fails (e.g., payment method expired), the backend falls back to creating a Stripe Checkout Session and returns a `paymentUrl`.+4. If `paymentUrl` is empty, the frontend polls until `sub.seats` matches the requested value.+5. Webhooks may arrive out of order. The stale event filter in `handleSubscriptionStatusChange` compares the event's `StripeSubscriptionId` against the stored one — if they differ, the event is from an old subscription and is ignored.-// CancelSubscription cancels a Stripe subscription.-// Monthly: immediate with proration. Annual: at period end.-func CancelSubscription(stripeSubID string, monthly bool, forceRefund bool) (*stripe.Subscription, error) { ... }+**Fallback paths in UpdatePurchase:**+- No existing subscription or CANCELED → falls through to `createCheckout` (same as new purchase).+- Active subscription but can't fetch old Stripe sub → falls back to `createCheckout`.+- Active subscription but no customer ID → falls back to `createCheckout`.+- Cancel succeeds but direct create fails → falls back to `createCheckout`.-// CreateSubscriptionDirect creates a new Stripe subscription using an existing customer's payment method.-func CreateSubscriptionDirect(params *DirectSubscriptionParams) (*stripe.Subscription, error) { ... }--// RefundFromSubscription refunds proration credit after cancellation.-func RefundFromSubscription(sub *stripe.Subscription, internalSubID string) error { ... }--// GetMetadata builds metadata map for Stripe subscription.-func GetMetadata(workspace string, plan string, interval string, seats int) map[string]string { ... }+----// FindLastPaidInvoice finds the last paid invoice for a subscription.-func FindLastPaidInvoice(sub *stripe.Subscription) (*stripe.Invoice, error) { ... }+## Cancel Flow-// GetPromotionByCode looks up an active promotion code.-func GetPromotionByCode(code string, price int64) *stripe.PromotionCode { ... }+```+ User Frontend Backend Stripe+ │ │ │ │+ │ Click "Cancel" │ │ │+ │ Confirm in dialog │ │ │+ │ ───────────────────────▶│ │ │+ │ │ CancelPurchase() │ │+ │ │ ─────────────────────────▶│ │+ │ │ │ GetSubscriptionByWorkspace│+ │ │ │ │+ │ │ │ ┌─ Monthly? ─────────────┐+ │ │ │ │ YES: Cancel immediately│+ │ │ │ │ CancelSubscription │+ │ │ │ │ (prorate=true) │+ │ │ │ │ + RefundFromSub │+ │ │ │ │ (proration credit │+ │ │ │ │ across charges) │+ │ │ │ ├─ Annual? ──────────────┤+ │ │ │ │ NO: Cancel at period │+ │ │ │ │ end (CancelAtPeriodEnd│+ │ │ │ │ = true) │+ │ │ │ └───────────────────────┘+ │ │ │ ─────────────────────────▶│+ │ │ │ │+ │ │ ◀── success ─────────────│ │+ │ │ fetchSubscription() │ │+ │ │ ─────────────────────────▶│ │+ │ Show updated plan ◀────│ │ │+ │ │ │ │+ │ │ │ ┌─── Webhook ───────────│+ │ │ │ │ sub.deleted │+ │ │ │ ▼ │+ │ │ │ UpsertSubscription │+ │ │ │ (status=CANCELED) │+ │ │ │ StoreLicense("") │+ │ │ │ → reverts to FREE │```-Direct port of hub's `plugin/stripe/stripe.go` with Paddle references removed.--### 6. Stripe Webhook Handler--New file: `backend/api/stripe/webhook.go`--Register via Echo routes alongside SCIM (in `echo_routes.go`):+**Cancellation rules:**-```go-// echo_routes.go-stripeWebhook := hookGroup.Group("/stripe")-stripeWebhookHandler.RegisterRoutes(stripeWebhook)-```+| Interval | Behavior | Refund |+|----------|----------|--------|+| Monthly | Immediate cancellation with proration | Proration credit refunded across recent charges (skips refunds < $1) |+| Annual | `CancelAtPeriodEnd = true` — subscription stays active until period end | None (user keeps access until expiry) |-Route: `POST /hook/stripe/callback`+**Refund mechanics (`RefundFromSubscription`):**+1. Find the draft invoice generated by Stripe's proration.+2. Sum negative line items (credits) to compute refund amount.+3. List the customer's recent charges and refund across them (partial refunds if one charge doesn't cover the full amount).-```go-type WebhookHandler struct {- store *store.Store- licenseService *enterprise.LicenseService- stripeSecret string // webhook signing secret-}+----func (h *WebhookHandler) HandleCallback(c echo.Context) error {- // 1. Verify Stripe signature- // 2. Parse event- // 3. Filter by metadata source- // 4. Route to handler by event type-}-```+## Webhook Processing-**Event handlers** (ported from hub `webhook/stripe.go`):+### Route-| Event | Handler |-|-------|---------|-| `customer.subscription.created` | Extract metadata, update subscription payload with Stripe IDs |-| `customer.subscription.updated` | Map Stripe status → `SubscriptionPayload.Status` |-| `customer.subscription.paused` | Set PAUSED, invalidate license cache |-| `customer.subscription.resumed` | Set ACTIVE, invalidate license cache |-| `customer.subscription.deleted` | Set CANCELED, invalidate license cache |-| `invoice.paid` | Update seats/interval from metadata, extend `expires_at`, set ACTIVE, invalidate license cache |+`POST /hook/stripe/callback` — registered in `echo_routes.go` under the `/hook` group, alongside SCIM. Only registered when `profile.SaaS && profile.StripeWebhookSecret != ""`.-**No JWT license generation needed.** The subscription table already has all the data (`plan`, `seat`, `instance_count`, `expires_at`). In SaaS mode, `LicenseService.LoadSubscription` reads directly from the subscription table and converts `SubscriptionPayload` → `v1pb.Subscription`. The webhook handler just updates the subscription table and invalidates the cache.+### Signature Verification-### 7. Configuration+Every incoming request is verified via `webhook.ConstructEvent(body, signature, secret)` using the `Stripe-Signature` header against the configured `STRIPE_WEBHOOK_SECRET`. Invalid signatures return 400.-Add to `backend/component/config/profile.go`:+### Event Routing-```go-type Profile struct {- // ... existing fields- StripeAPIKey string- StripeWebhookSecret string-}+```+processEvent(event)+├── customer.subscription.created ─┐+├── customer.subscription.updated │+├── customer.subscription.deleted ├──▶ handleSubscriptionStatusChange+├── customer.subscription.paused │+├── customer.subscription.resumed ─┘+├── invoice.paid ──────────────────────▶ handleInvoicePaid+└── (other) ───────────────────────────▶ ignored (return nil)```-Loaded from environment variables:-- `STRIPE_API_KEY` — Stripe secret key-- `STRIPE_WEBHOOK_SECRET` — Webhook signing secret+### Metadata Filtering-Only used when `profile.SaaS == true`. Non-SaaS ignores these.+Both handlers check `metadata["source"] == "bytebase"` to ignore Stripe events from unrelated checkout sessions. Events without this source marker are silently skipped.-### 8. API Service Changes+### `handleSubscriptionStatusChange`-Expand `backend/api/v1/subscription_service.go`:+1. Unmarshal `stripego.Subscription` from event data.+2. Filter by `source` metadata. Extract `workspace` from metadata.+3. Map Stripe status → internal status:+ - `active`, `trialing` → ACTIVE+ - `canceled` → CANCELED+ - `past_due`, `unpaid`, `paused`, `incomplete`, `incomplete_expired` → PAUSED+4. **Stale event guard**: If the stored `StripeSubscriptionId` differs from the event's subscription ID, ignore the event (prevents late-arriving cancel events from an old subscription from overwriting a newer one).+5. Upsert subscription payload with new status and Stripe IDs.+6. On `customer.subscription.created`: set `ExpiresAt` from the first item's `CurrentPeriodEnd`.+7. Update license: ACTIVE → sign and store JWT; non-ACTIVE → store empty string (reverts to FREE).-```go-type SubscriptionService struct {- v1connect.UnimplementedSubscriptionServiceHandler- profile *config.Profile- store *store.Store- licenseService *enterprise.LicenseService-}+### `handleInvoicePaid`-// GetSubscription — unchanged (returns current subscription from license cache).--// UpdateSubscription — self-hosted JWT upload (gated: rejected if profile.SaaS).--// CreatePurchase — SaaS only.-func (s *SubscriptionService) CreatePurchase(ctx, req) {- if !s.profile.SaaS {- return Unimplemented- }- workspaceID := common.GetWorkspaceIDFromContext(ctx)- // 1. Validate plan is self-service purchasable- // 2. Calculate price via pricing.GetPriceModel()- // 3. Check no existing active subscription- // 4. Create subscription record (status=PENDING)- // 5. Create Stripe Checkout Session- // 6. Return payment URL-}+1. Unmarshal `stripego.Invoice`. Extract metadata from `Lines.Data[0].Metadata`.+2. Build payload from metadata: plan, interval, instance_count, user_count.+3. Extract Stripe subscription ID from `inv.Parent.SubscriptionDetails.Subscription`.+4. Set `StartedAt` and `ExpiresAt` from the line item's period.+5. Upsert with `status=ACTIVE`.+6. Generate and store license JWT.-// UpdatePurchase — SaaS only.-func (s *SubscriptionService) UpdatePurchase(ctx, req) {- if !s.profile.SaaS {- return Unimplemented- }- // 1. Validate etag- // 2. If subscription is PENDING: activate with new settings, generate new checkout URL- // 3. If plan/interval/seats changed: cancel old Stripe sub → create new one- // 4. Return payment URL or empty (if direct creation succeeded)-}+This is the primary event that activates a subscription — it fires after successful payment for both new subscriptions and renewals.-// CancelPurchase — SaaS only.-func (s *SubscriptionService) CancelPurchase(ctx, req) {- if !s.profile.SaaS {- return Unimplemented- }- // 1. Validate etag- // 2. Monthly: cancel immediately with proration + refund- // 3. Annual: cancel at period end- // 4. Clear license-}+----// GetPaymentInfo — SaaS only.-func (s *SubscriptionService) GetPaymentInfo(ctx, req) {- // Fetch last paid invoice from Stripe- // Create Billing Portal session for invoice management-}+## License Lifecycle-// ListPlans — public.-func (s *SubscriptionService) ListPlans(ctx, req) {- return pricing.ListPlans()-}+```+Stripe webhook arrives+ │+ ▼+handleInvoicePaid / handleSubscriptionStatusChange+ │+ ├── status == ACTIVE+ │ │+ │ ▼+ │ LicenseService.CreateLicense(LicenseParams{+ │ Plan, Seats, Instances, WorkspaceID, ExpiresAt+ │ })+ │ │+ │ ▼+ │ Sign RS256 JWT (private key, SaaS only)+ │ │+ │ ▼+ │ LicenseService.StoreLicense(ctx, workspace, jwt)+ │ ├── Validate JWT (parse + verify signature)+ │ ├── UPDATE setting SET value = jwt WHERE workspace = ? AND name = 'bb.workspace.license'+ │ └── Invalidate LRU cache for workspace+ │+ └── status != ACTIVE+ │+ ▼+ LicenseService.StoreLicense(ctx, workspace, "")+ └── Empty license → LoadSubscription returns FREE plan```-### 9. LicenseService Changes--In SaaS mode, `LoadSubscription` reads from the `subscription` table instead of parsing a JWT from the `setting` table. No license JWT generation or private key needed.+`LoadSubscription` (called on every authenticated request for plan/feature checks):+1. Check LRU cache (TTL = 1 minute, size = 128).+2. On miss: singleflight-deduplicated DB read from `setting` table.+3. Parse JWT, verify signature, check expiry, map claims to `v1pb.Subscription`.+4. Only non-FREE subscriptions are cached (FREE might be a transient failure).-```go-func (s *LicenseService) LoadSubscription(ctx context.Context, workspaceID string) *v1pb.Subscription {- if s.saas {- // Read from subscription table, convert SubscriptionPayload → v1pb.Subscription- return s.loadSubscriptionFromPurchase(ctx, workspaceID)- }- // Self-hosted: existing JWT-based flow (unchanged)- return s.loadSubscriptionFromDB(ctx, workspaceID)-}-```+----The conversion is straightforward — map `SubscriptionPayload.Plan` → `v1pb.PlanType`, copy seats/instances/expiry. Cache invalidation works the same way (keyed by workspace ID).+## Frontend UX-### 10. Frontend Changes+### Page Structure-#### SettingWorkspaceSubscription.vue+`SettingWorkspaceSubscription.vue` is the main settings page. It renders:+- Plan info header (current plan, expiry, user count) — always shown.+- `SettingWorkspacePurchase.vue` — shown in SaaS mode (`actuatorStore.isSaaSMode`).+- License upload textarea — shown in self-hosted mode.-The page needs two modes:+### Purchase Page States```-if (SaaS mode):- Show: Plan card, seats config, billing interval toggle, purchase button- Show: Subscription status (PENDING/ACTIVE/PAUSED/CANCELED/EXPIRED)- Show: Payment info (price, period, invoice link)- Show: Cancel button- Hide: License textarea upload-else (self-hosted):- Show: Current plan info, license textarea upload (existing behavior)- Hide: Purchase UI+SettingWorkspacePurchase.vue+├── Pending Payment (spinner)+│ └── Shown during polling after Stripe redirect or direct update+│+├── Active Subscription Management+│ ├── Payment info (price, period, invoice link via Stripe Billing Portal)+│ ├── Cancel-pending warning (annual plan with CancelAtPeriodEnd)+│ └── Cancel button (opens confirmation dialog)+│+└── Plan Cards Grid (FREE / Pro / Enterprise)+ ├── FREE: static, no action for current plan+ ├── Pro (TEAM): seat counter, terms checkbox, subscribe/update button+ │ └── Discount badge if promotion available (e.g., "90% off first month")+ └── Enterprise: "Contact Us" button (not self-service)```-#### New Components+### Plan Data Source-- **`PurchasePlanCard.vue`** — Plan selection with seat counter, billing toggle. Port from hub's `PlanPricing.vue`, simplified (no instance counter, no deployment type selector, always CLOUD).-- **`SubscriptionManagement.vue`** — Shows active subscription details, payment info, cancel button. Port from hub's `DashboardSubscriptionManagement.vue`.-- **`PendingPayment.vue`** — Shown after Stripe redirect while polling for subscription activation.+Plan cards are driven by the `ListPurchasePlans` API response, not hardcoded. The API returns:+- `PurchasePlan.selfServicePurchase` — whether the plan supports checkout.+- `PurchasePlan.additionals[]` — configurable dimensions (USER type: unit price, min/max count).+- `PurchasePlan.billingMethods[]` — available intervals with optional discounts.-#### Frontend Store Extension+The FREE plan card is always added client-side (not returned by API).-Extend `frontend/src/store/modules/v1/subscription.ts`:+### Post-Checkout Polling-```typescript-// New actions (SaaS only)-async createPurchase(plan, interval, seats): Promise<{ paymentUrl: string }>-async updatePurchase(plan, interval, seats, etag): Promise<{ paymentUrl: string }>-async cancelPurchase(etag): Promise<void>-async fetchPaymentInfo(): Promise<PaymentInfo>-async fetchPlans(): Promise<PurchasePlan[]>+After Stripe redirects back with `?session_id=cs_xxx`:+1. Call `VerifyCheckoutSession(session_id)` to confirm Stripe reports `"complete"`.+2. Show pending payment spinner.+3. Poll `GetSubscription` every 2 seconds, up to 30 attempts (60 seconds max).+4. When plan changes from FREE → paid, update the store and dismiss spinner.+5. Clean up query params (`router.replace({ query: {} })`) to prevent re-polling on page refresh.-// New state-purchaseSubscription: Ref<PurchaseSubscription | undefined> // from subscription table-paymentInfo: Ref<PaymentInfo | undefined>-plans: Ref<PurchasePlan[]>-```+### Direct Update Polling-#### Stripe Checkout Redirect Flow--```-User clicks "Subscribe" → createPurchase() → backend returns paymentUrl- → window.location.href = paymentUrl (redirect to Stripe Checkout)- → Stripe success → redirect to /setting/subscription?from=STRIPE- → Frontend polls GetSubscription until plan becomes ACTIVE- → Show subscription management UI-```--The `?from=STRIPE` query param triggers the pending payment polling view (same pattern as hub).+When `UpdatePurchase` returns empty `paymentUrl` (direct subscription swap succeeded):+1. Show pending payment spinner.+2. Poll `GetSubscription` with `cache=false` (does not update Pinia store during polling to avoid UI flashing PAID → FREE → PAID as webhooks process).+3. Match `sub.seats === state.seats` to confirm the new subscription is active.+4. Update store only after confirmation.----## Implementation Plan+## API Reference-### Phase 1: Backend Foundation (done)+All purchase APIs require `bb.subscription.manage` permission (IAM). All are SaaS-only (return `Unimplemented` for non-SaaS).-1. **Database migration** — `0014##add_subscription_table.sql`. Minimal table: `workspace` PK + `payload` + timestamps.-2. **Store proto** — `proto/store/store/subscription.proto` with `SubscriptionPayload` (enums for `Status`, `Plan`, `BillingInterval`; fields for lifecycle, billing, Stripe IDs).-3. **Store layer** — `backend/store/subscription.go` with `CreateSubscription`, `GetSubscriptionByWorkspace`, `UpdateSubscription`.+| RPC | HTTP | Description |+|-----|------|-------------|+| `CreatePurchase` | `POST /v1/subscription:purchase` | Create Stripe Checkout Session for new subscription |+| `UpdatePurchase` | `POST /v1/subscription:updatePurchase` | Change plan/seats — cancel old sub + create new, or fallback to checkout |+| `CancelPurchase` | `POST /v1/subscription:cancelPurchase` | Cancel subscription (monthly=immediate, annual=period end) |+| `GetPaymentInfo` | `GET /v1/subscription/paymentInfo` | Payment details + Stripe Billing Portal URL |+| `VerifyCheckoutSession` | `GET /v1/subscription/checkoutSession/{session_id}` | Check if checkout completed |+| `ListPurchasePlans` | `GET /v1/subscription/plans` | Available plans with pricing (no auth) |+| `GetSubscription` | `GET /v1/subscription` | Current subscription (no auth) |+| `UploadLicense` | `PUT /v1/subscription/license` | Manual JWT upload (self-hosted only) |-### Phase 2: Pricing & Stripe+----4. **Pricing module** — `backend/enterprise/pricing/` with plan config and price calculation.-5. **Stripe plugin** — `backend/plugin/stripe/` with checkout session, cancellation, refund.+## Pricing-### Phase 3: API & Webhooks+Defined in `backend/enterprise/pricing/plan.go`:-6. **Proto definitions** — Add new RPCs and messages to `subscription_service.proto`.-7. **LicenseService SaaS path** — `LoadSubscription` reads from subscription table in SaaS mode. No JWT generation needed.-8. **Subscription service** — Implement `CreatePurchase`, `UpdatePurchase`, `CancelPurchase`, `GetPaymentInfo`, `ListPlans`.-9. **Stripe webhook** — `backend/api/stripe/webhook.go`, register in `echo_routes.go`.-10. **SaaS gate** — `UpdateSubscription` blocked in SaaS, purchase APIs blocked in non-SaaS.+| Plan | Self-Service | Price | Instances | Max Seats |+|------|-------------|-------|-----------|-----------|+| TEAM | Yes | $20/user/month | 10 (fixed) | Unlimited |+| ENTERPRISE | No (contact sales) | Custom | Custom | Custom |-### Phase 4: Frontend+`PriceModel.GetPrice()` calculates: `(seats - freeSeatCount) × pricePerSeat × intervalMonths`.+Annual billing multiplies the monthly price by 12 (no annual discount in the price itself; discounts are handled via Stripe promotion codes).++----11. **Subscription store** — Add purchase actions and state.-12. **Plan selection UI** — `PurchasePlanCard.vue` with seat counter and billing toggle.-13. **Subscription management** — Status display, payment info, cancel flow.-14. **Pending payment** — Polling view after Stripe redirect.-15. **Conditional rendering** — Show purchase UI in SaaS, license upload in self-hosted.+## Configuration-### Phase 5: Integration & Testing+Environment variables (only used when `profile.SaaS == true`):-16. **Stripe test mode** — End-to-end testing with Stripe test keys.-17. **Webhook testing** — Stripe CLI (`stripe listen --forward-to`) for local webhook testing.-18. **Edge cases** — Expired subscription, failed payment retry, concurrent updates (etag), plan changes mid-billing.+| Variable | Purpose |+|----------|---------|+| `STRIPE_API_SECRET` | Stripe secret key for API calls |+| `STRIPE_WEBHOOK_SECRET` | Webhook signing secret for signature verification |+| `BB_LICENSE_PRIVATE_KEY` | RSA private key (PEM or base64-encoded PEM) for signing license JWTs |---@@ -584,7 +497,7 @@ The `?from=STRIPE` query param triggers the pending payment polling view (same p| Aspect | Hub | Bytebase SaaS ||--------|-----|----------------|-| License source | JWT generated by hub, injected via GCP or downloaded | No JWT — `LoadSubscription` reads subscription table directly |+| License source | JWT generated by hub, injected via GCP or downloaded | JWT signed by backend (private key in env), stored in setting table || Instance pricing | Per-instance additional | Fixed 10 instances (TEAM) || Payment providers | Stripe + Paddle | Stripe only || Grace period | +7 days (self-host), +12h (cloud) | None needed (same-process read) |@@ -596,8 +509,10 @@ The `?from=STRIPE` query param triggers the pending payment polling view (same p## Security Considerations-1. **Stripe webhook signature verification** — Must validate `Stripe-Signature` header against `STRIPE_WEBHOOK_SECRET`. Reject unsigned requests.-2. **SaaS gate** — All purchase APIs must check `profile.SaaS` before proceeding. Non-SaaS deployments must never expose Stripe integration.-3. **Etag-based optimistic locking** — Prevents race conditions on subscription updates. Derived from `updated_at` timestamp.-4. **Metadata validation** — Webhook handler must verify `source` in metadata to filter out unrelated Stripe events.-5. **HTTPS only** — Stripe webhooks require HTTPS endpoints.+1. **Stripe webhook signature verification** — Validates `Stripe-Signature` header against `STRIPE_WEBHOOK_SECRET`. Rejects unsigned requests with 400.+2. **SaaS gate** — All purchase APIs check `profile.SaaS` and return `Unimplemented` for non-SaaS. Stripe routes are only registered when both API key and webhook secret are configured.+3. **IAM permission** — All purchase/cancel/payment APIs require `bb.subscription.manage` permission.+4. **Metadata filtering** — Webhook handler checks `source == "bytebase"` to filter out unrelated Stripe events.+5. **Stale event guard** — Subscription status webhooks compare `StripeSubscriptionId` to prevent late-arriving events from old subscriptions from overwriting newer state.+6. **Etag-based optimistic locking** — `UpdatePurchase` supports etag comparison to detect concurrent modifications.+7. **Private key isolation** — License signing key is only loaded in SaaS mode. Self-hosted deployments only have the public key (for verification).diff --git a/frontend/src/components/ProfileDropdown.vue b/frontend/src/components/ProfileDropdown.vueindex ea224e67e0..e52069f188 100644--- a/frontend/src/components/ProfileDropdown.vue+++ b/frontend/src/components/ProfileDropdown.vue@@ -92,7 +92,7 @@ const toggleLocale = (lang: string) => {};const switchPlan = (license: string) => {- subscriptionStore.patchSubscription(license);+ subscriptionStore.uploadLicense(license);showDropdown.value = false;};diff --git a/frontend/src/locales/dynamic/en-US.json b/frontend/src/locales/dynamic/en-US.jsonindex d0be6daeb6..ac2ddd652d 100644--- a/frontend/src/locales/dynamic/en-US.json+++ b/frontend/src/locales/dynamic/en-US.json@@ -320,6 +320,51 @@"title": "Dedicated support with SLA","desc": "Priority support with guaranteed response times."}+ },+ "purchase": {+ "free-description": "Designed for solo devs, side-projects, and experiments.",+ "pro-description": "Built for teams creating production-ready applications.",+ "enterprise-description": "Scale your business securely while staying compliant.",+ "features": {+ "free": {+ "limits": "Up to 20 users and 10 instances",+ "dcm": "Complete database change management",+ "git": "Git-based version control & schema migration",+ "sql-review": "SQL review with 200+ rules",+ "backup": "Automatic backups & one-click rollback",+ "sql-editor": "Web-based SQL editor with AI assistance",+ "schema": "Schema diagrams & data export",+ "iam": "Basic IAM and security features",+ "support": "Community support"+ },+ "pro": {+ "limits": "Unlimited users at $20/user/month, 10 instances",+ "everything": "Everything in Free, plus:",+ "batch-query": "Batch query capabilities",+ "read-only": "Instance read-only connections",+ "query-policy": "Query policies for governance",+ "sso": "Google & GitHub SSO",+ "groups": "User groups management",+ "db-groups": "Database groups",+ "audit-log": "Limited audit logging",+ "support": "Email support"+ },+ "enterprise": {+ "limits": "Custom limits based on needs",+ "everything": "Everything in Pro, plus:",+ "custom-limits": "Custom user & instance limits",+ "approval": "Risk assessment & approval workflows",+ "audit-log": "Full audit logging",+ "sso": "Enterprise SSO (Custom OAuth2, OIDC, LDAP)",+ "2fa": "2FA & advanced authentication policies",+ "masking": "Data masking & classification",+ "roles": "Custom roles & role request workflows",+ "scim": "SCIM user provisioning & directory sync",+ "secret": "External secret manager integration",+ "branding": "Custom branding & watermarking",+ "support": "Dedicated support with SLA"+ }+ }}},"resource": {diff --git a/frontend/src/locales/dynamic/es-ES.json b/frontend/src/locales/dynamic/es-ES.jsonindex 1544c07d1d..58577e85d8 100644--- a/frontend/src/locales/dynamic/es-ES.json+++ b/frontend/src/locales/dynamic/es-ES.json@@ -320,6 +320,51 @@"title": "Soporte dedicado con SLA","desc": "Soporte prioritario con tiempos de respuesta garantizados."}+ },+ "purchase": {+ "free-description": "Diseñado para desarrolladores individuales, proyectos paralelos y experimentos.",+ "pro-description": "Creado para equipos que construyen aplicaciones listas para producción.",+ "enterprise-description": "Escala tu negocio de forma segura y cumpliendo normativas.",+ "features": {+ "free": {+ "limits": "Hasta 20 usuarios y 10 instancias",+ "dcm": "Gestión completa de cambios de base de datos",+ "git": "Control de versiones y migración de esquema basado en Git",+ "sql-review": "Revisión SQL con más de 200 reglas",+ "backup": "Copias de seguridad automáticas y reversión con un clic",+ "sql-editor": "Editor SQL web con asistencia de IA",+ "schema": "Diagramas de esquema y exportación de datos",+ "iam": "Funciones básicas de IAM y seguridad",+ "support": "Soporte comunitario"+ },+ "pro": {+ "limits": "Usuarios ilimitados a $20/usuario/mes, 10 instancias",+ "everything": "Todo en Gratis, más:",+ "batch-query": "Capacidades de consulta por lotes",+ "read-only": "Conexiones de solo lectura de instancias",+ "query-policy": "Políticas de consulta para gobernanza",+ "sso": "SSO de Google y GitHub",+ "groups": "Gestión de grupos de usuarios",+ "db-groups": "Grupos de bases de datos",+ "audit-log": "Registro de auditoría limitado",+ "support": "Soporte por correo electrónico"+ },+ "enterprise": {+ "limits": "Límites personalizados según necesidades",+ "everything": "Todo en Pro, más:",+ "custom-limits": "Límites personalizados de usuarios e instancias",+ "approval": "Evaluación de riesgos y flujos de aprobación",+ "audit-log": "Registro de auditoría completo",+ "sso": "SSO empresarial (OAuth2, OIDC, LDAP personalizados)",+ "2fa": "2FA y políticas de autenticación avanzadas",+ "masking": "Enmascaramiento y clasificación de datos",+ "roles": "Roles personalizados y flujos de solicitud de roles",+ "scim": "Aprovisionamiento de usuarios SCIM y sincronización de directorio",+ "secret": "Integración con gestor de secretos externo",+ "branding": "Marca personalizada y marca de agua",+ "support": "Soporte dedicado con SLA"+ }+ }}},"resource": {diff --git a/frontend/src/locales/dynamic/ja-JP.json b/frontend/src/locales/dynamic/ja-JP.jsonindex bdeb9a7f3e..d98438213e 100644--- a/frontend/src/locales/dynamic/ja-JP.json+++ b/frontend/src/locales/dynamic/ja-JP.json@@ -320,6 +320,51 @@"title": "SLA付き専用サポート","desc": "保証された応答時間での優先サポート。"}+ },+ "purchase": {+ "free-description": "個人開発者、サイドプロジェクト、実験向け。",+ "pro-description": "本番対応アプリケーションを構築するチーム向け。",+ "enterprise-description": "コンプライアンスを維持しながら安全にビジネスを拡大。",+ "features": {+ "free": {+ "limits": "最大20ユーザー、10インスタンス",+ "dcm": "完全なデータベース変更管理",+ "git": "Gitベースのバージョン管理とスキーマ移行",+ "sql-review": "200以上のルールによるSQLレビュー",+ "backup": "自動バックアップとワンクリックロールバック",+ "sql-editor": "AI支援付きWebベースSQLエディタ",+ "schema": "スキーマ図とデータエクスポート",+ "iam": "基本的なIAMとセキュリティ機能",+ "support": "コミュニティサポート"+ },+ "pro": {+ "limits": "無制限ユーザー($20/ユーザー/月)、10インスタンス",+ "everything": "無料版のすべてに加えて:",+ "batch-query": "バッチクエリ機能",+ "read-only": "インスタンス読み取り専用接続",+ "query-policy": "ガバナンスのためのクエリポリシー",+ "sso": "Google & GitHub SSO",+ "groups": "ユーザーグループ管理",+ "db-groups": "データベースグループ",+ "audit-log": "限定的な監査ログ",+ "support": "メールサポート"+ },+ "enterprise": {+ "limits": "ニーズに基づくカスタム制限",+ "everything": "プロ版のすべてに加えて:",+ "custom-limits": "カスタムユーザーとインスタンス制限",+ "approval": "リスク評価と承認ワークフロー",+ "audit-log": "完全な監査ログ",+ "sso": "エンタープライズSSO(カスタムOAuth2、OIDC、LDAP)",+ "2fa": "二要素認証と高度な認証ポリシー",+ "masking": "データマスキングと分類",+ "roles": "カスタムロールとロール申請ワークフロー",+ "scim": "SCIMユーザープロビジョニングとディレクトリ同期",+ "secret": "外部シークレットマネージャー統合",+ "branding": "カスタムブランディングとウォーターマーク",+ "support": "SLA付き専用サポート"+ }+ }}},"resource": {diff --git a/frontend/src/locales/dynamic/vi-VN.json b/frontend/src/locales/dynamic/vi-VN.jsonindex 1a9f96e85d..c11e3113e9 100644--- a/frontend/src/locales/dynamic/vi-VN.json+++ b/frontend/src/locales/dynamic/vi-VN.json@@ -320,6 +320,51 @@"title": "Hỗ trợ chuyên dụng với SLA","desc": "Hỗ trợ ưu tiên với thời gian phản hồi được đảm bảo."}+ },+ "purchase": {+ "free-description": "Dành cho lập trình viên cá nhân, dự án phụ và thử nghiệm.",+ "pro-description": "Xây dựng cho các nhóm tạo ứng dụng sẵn sàng cho sản xuất.",+ "enterprise-description": "Mở rộng doanh nghiệp một cách an toàn và tuân thủ.",+ "features": {+ "free": {+ "limits": "Tối đa 20 người dùng và 10 phiên bản",+ "dcm": "Quản lý thay đổi cơ sở dữ liệu hoàn chỉnh",+ "git": "Kiểm soát phiên bản và di chuyển schema dựa trên Git",+ "sql-review": "Đánh giá SQL với hơn 200 quy tắc",+ "backup": "Sao lưu tự động và hoàn tác một cú nhấp",+ "sql-editor": "Trình soạn SQL trên web với hỗ trợ AI",+ "schema": "Sơ đồ schema và xuất dữ liệu",+ "iam": "Các tính năng IAM và bảo mật cơ bản",+ "support": "Hỗ trợ cộng đồng"+ },+ "pro": {+ "limits": "Người dùng không giới hạn với $20/người dùng/tháng, 10 phiên bản",+ "everything": "Tất cả trong Miễn phí, cộng thêm:",+ "batch-query": "Khả năng truy vấn hàng loạt",+ "read-only": "Kết nối chỉ đọc phiên bản",+ "query-policy": "Chính sách truy vấn cho quản trị",+ "sso": "Google & GitHub SSO",+ "groups": "Quản lý nhóm người dùng",+ "db-groups": "Nhóm cơ sở dữ liệu",+ "audit-log": "Nhật ký kiểm toán hạn chế",+ "support": "Hỗ trợ qua email"+ },+ "enterprise": {+ "limits": "Giới hạn tùy chỉnh theo nhu cầu",+ "everything": "Tất cả trong Pro, cộng thêm:",+ "custom-limits": "Giới hạn người dùng và phiên bản tùy chỉnh",+ "approval": "Đánh giá rủi ro và quy trình phê duyệt",+ "audit-log": "Nhật ký kiểm toán đầy đủ",+ "sso": "SSO doanh nghiệp (OAuth2, OIDC, LDAP tùy chỉnh)",+ "2fa": "Xác thực hai yếu tố và chính sách xác thực nâng cao",+ "masking": "Che dấu và phân loại dữ liệu",+ "roles": "Vai trò tùy chỉnh và quy trình yêu cầu vai trò",+ "scim": "Cung cấp người dùng SCIM và đồng bộ thư mục",+ "secret": "Tích hợp trình quản lý bí mật bên ngoài",+ "branding": "Thương hiệu tùy chỉnh và hình mờ",+ "support": "Hỗ trợ chuyên dụng với SLA"+ }+ }}},"resource": {diff --git a/frontend/src/locales/dynamic/zh-CN.json b/frontend/src/locales/dynamic/zh-CN.jsonindex 853168d219..e15d494a6b 100644--- a/frontend/src/locales/dynamic/zh-CN.json+++ b/frontend/src/locales/dynamic/zh-CN.json@@ -320,6 +320,51 @@"title": "专属支持与 SLA","desc": "具有保证响应时间的优先支持。"}+ },+ "purchase": {+ "free-description": "适用于个人开发者、副业项目和实验。",+ "pro-description": "适用于构建生产级应用的团队。",+ "enterprise-description": "安全合规地扩展您的业务。",+ "features": {+ "free": {+ "limits": "最多 20 个用户和 10 个实例",+ "dcm": "完整的数据库变更管理",+ "git": "基于 Git 的版本控制和 Schema 迁移",+ "sql-review": "200+ 条 SQL 审查规则",+ "backup": "自动备份和一键回滚",+ "sql-editor": "基于 Web 的 SQL 编辑器(含 AI 辅助)",+ "schema": "Schema 图表和数据导出",+ "iam": "基本 IAM 和安全功能",+ "support": "社区支持"+ },+ "pro": {+ "limits": "无限用户,$20/用户/月,10 个实例",+ "everything": "包含免费版所有功能,另外:",+ "batch-query": "批量查询功能",+ "read-only": "实例只读连接",+ "query-policy": "查询治理策略",+ "sso": "Google 和 GitHub SSO",+ "groups": "用户组管理",+ "db-groups": "数据库分组",+ "audit-log": "有限审计日志",+ "support": "邮件支持"+ },+ "enterprise": {+ "limits": "按需自定义限制",+ "everything": "包含专业版所有功能,另外:",+ "custom-limits": "自定义用户和实例限制",+ "approval": "风险评估和审批工作流",+ "audit-log": "完整审计日志",+ "sso": "企业级 SSO(自定义 OAuth2、OIDC、LDAP)",+ "2fa": "双因素认证和高级认证策略",+ "masking": "数据脱敏和分类",+ "roles": "自定义角色和角色申请工作流",+ "scim": "SCIM 用户配置和目录同步",+ "secret": "外部密钥管理器集成",+ "branding": "自定义品牌和水印",+ "support": "专属 SLA 支持"+ }+ }}},"resource": {diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 6f0bbfcca1..4c4207f385 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -2394,6 +2394,36 @@"title": "Enterprise"},"try": "Try it free"+ },+ "purchase": {+ "subscribe": "Subscribe now",+ "cancel": "Cancel Subscription",+ "cancel-confirm": "Are you sure you want to cancel your subscription?",+ "canceled": "Subscription canceled",+ "update": "Update Subscription",+ "cancel-pending": "Your subscription has been canceled and will end on {date}.",+ "discount": {+ "percentage-off": "first month {value}% off",+ "month-off": "{value} month free",+ "price-off": "${value} off"+ },+ "seats": "Users",+ "per-user-per-month": "/ user monthly",+ "custom": "Custom",+ "free-description": "Designed for solo devs, side-projects, and experiments.",+ "pro-description": "Built for teams creating production-ready applications.",+ "enterprise-description": "Scale your business securely while staying compliant.",+ "see-comparison": "See detailed feature comparison",+ "accept-terms-prefix": "I accept the",+ "terms-of-service": "Terms of Service",+ "and": "and",+ "privacy-policy": "Privacy policy",+ "pending-title": "Completing your purchase...",+ "pending-description": "Please wait while we confirm your payment. This usually takes a few seconds.",+ "payment-info": "Payment Info",+ "total-price": "Total Price",+ "billing-period": "Billing Period",+ "manage-invoices": "Manage Invoices"}},"sheet": {diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 8e206a4c64..e863c56d4d 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -2394,6 +2394,36 @@"title": "Empresa"},"try": "Pruébalo gratis."+ },+ "purchase": {+ "subscribe": "Suscribirse ahora",+ "cancel": "Cancelar suscripción",+ "cancel-confirm": "¿Está seguro de que desea cancelar su suscripción?",+ "canceled": "Suscripción cancelada",+ "update": "Actualizar suscripción",+ "cancel-pending": "Su suscripción ha sido cancelada y finalizará el {date}.",+ "discount": {+ "percentage-off": "primer mes {value}% de descuento",+ "month-off": "{value} mes gratis",+ "price-off": "${value} de descuento"+ },+ "seats": "Usuarios",+ "per-user-per-month": "/ usuario / mes",+ "custom": "Personalizado",+ "free-description": "Designed for solo devs, side-projects, and experiments.",+ "pro-description": "Built for teams creating production-ready applications.",+ "enterprise-description": "Scale your business securely while staying compliant.",+ "see-comparison": "Ver comparación detallada de funciones",+ "accept-terms-prefix": "Acepto los",+ "terms-of-service": "Términos de servicio",+ "and": "y",+ "privacy-policy": "Política de privacidad",+ "pending-title": "Completando su compra...",+ "pending-description": "Por favor espere mientras confirmamos su pago. Esto suele tardar unos segundos.",+ "payment-info": "Información de pago",+ "total-price": "Precio total",+ "billing-period": "Período de facturación",+ "manage-invoices": "Gestionar facturas"}},"sheet": {diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 32eb4ec370..e7ba68b9d6 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -2394,6 +2394,36 @@"title": "エンタープライズ"},"try": "無料でお試しください。"+ },+ "purchase": {+ "subscribe": "今すぐ購読",+ "cancel": "サブスクリプションをキャンセル",+ "cancel-confirm": "サブスクリプションをキャンセルしてもよろしいですか?",+ "canceled": "サブスクリプションがキャンセルされました",+ "update": "サブスクリプションを更新",+ "cancel-pending": "サブスクリプションはキャンセル済みで、{date} に終了します。",+ "discount": {+ "percentage-off": "初月 {value}% オフ",+ "month-off": "{value} ヶ月無料",+ "price-off": "${value} オフ"+ },+ "seats": "ユーザー数",+ "per-user-per-month": "/ ユーザー / 月",+ "custom": "カスタム",+ "free-description": "Designed for solo devs, side-projects, and experiments.",+ "pro-description": "Built for teams creating production-ready applications.",+ "enterprise-description": "Scale your business securely while staying compliant.",+ "see-comparison": "機能の詳細比較を見る",+ "accept-terms-prefix": "以下に同意します:",+ "terms-of-service": "利用規約",+ "and": "および",+ "privacy-policy": "プライバシーポリシー",+ "pending-title": "購入を完了しています...",+ "pending-description": "お支払いの確認中です。通常は数秒で完了します。",+ "payment-info": "支払い情報",+ "total-price": "合計金額",+ "billing-period": "請求期間",+ "manage-invoices": "請求書を管理"}},"sheet": {diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 0e5de2f5e4..40eb445cf3 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -2394,6 +2394,36 @@"title": "Doanh nghiệp"},"try": "Dùng thử miễn phí."+ },+ "purchase": {+ "subscribe": "Đăng ký ngay",+ "cancel": "Hủy đăng ký",+ "cancel-confirm": "Bạn có chắc chắn muốn hủy đăng ký không?",+ "canceled": "Đã hủy đăng ký",+ "update": "Cập nhật đăng ký",+ "cancel-pending": "Đăng ký đã bị hủy và sẽ kết thúc vào {date}.",+ "discount": {+ "percentage-off": "tháng đầu giảm {value}%",+ "month-off": "{value} tháng miễn phí",+ "price-off": "giảm ${value}"+ },+ "seats": "Người dùng",+ "per-user-per-month": "/ người dùng / tháng",+ "custom": "Tùy chỉnh",+ "free-description": "Designed for solo devs, side-projects, and experiments.",+ "pro-description": "Built for teams creating production-ready applications.",+ "enterprise-description": "Scale your business securely while staying compliant.",+ "see-comparison": "Xem so sánh tính năng chi tiết",+ "accept-terms-prefix": "Tôi chấp nhận",+ "terms-of-service": "Điều khoản dịch vụ",+ "and": "và",+ "privacy-policy": "Chính sách bảo mật",+ "pending-title": "Đang hoàn tất giao dịch...",+ "pending-description": "Vui lòng đợi trong khi chúng tôi xác nhận thanh toán. Thường chỉ mất vài giây.",+ "payment-info": "Thông tin thanh toán",+ "total-price": "Tổng giá",+ "billing-period": "Kỳ thanh toán",+ "manage-invoices": "Quản lý hóa đơn"}},"sheet": {diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 5ce4d21deb..566f6bde58 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -2394,6 +2394,36 @@"title": "企业版"},"try": "免费试用。"+ },+ "purchase": {+ "subscribe": "立即订阅",+ "cancel": "取消订阅",+ "cancel-confirm": "确定要取消订阅吗?",+ "canceled": "订阅已取消",+ "update": "更新订阅",+ "cancel-pending": "您的订阅已取消,将于 {date} 到期。",+ "discount": {+ "percentage-off": "首月 {value}% 优惠",+ "month-off": "{value} 个月免费",+ "price-off": "减 ${value}"+ },+ "seats": "用户数",+ "per-user-per-month": "/ 用户 / 月",+ "custom": "自定义",+ "free-description": "适用于个人开发者、副业项目和实验。",+ "pro-description": "适用于构建生产级应用的团队。",+ "enterprise-description": "安全合规地扩展您的业务。",+ "see-comparison": "查看详细功能对比",+ "accept-terms-prefix": "我接受",+ "terms-of-service": "服务条款",+ "and": "和",+ "privacy-policy": "隐私政策",+ "pending-title": "正在完成购买...",+ "pending-description": "请稍候,我们正在确认您的付款。通常只需几秒钟。",+ "payment-info": "支付信息",+ "total-price": "总价",+ "billing-period": "账单周期",+ "manage-invoices": "管理发票"}},"sheet": {diff --git a/frontend/src/react/components/ui/button.tsx b/frontend/src/react/components/ui/button.tsxindex 655e40f88c..3034e77248 100644--- a/frontend/src/react/components/ui/button.tsx+++ b/frontend/src/react/components/ui/button.tsx@@ -4,7 +4,7 @@ import type { ComponentProps } from "react";import { cn } from "@/react/lib/utils";const buttonVariants = cva(- "inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-colors focus:outline-hidden focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",+ "inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap cursor-pointer transition-colors focus:outline-hidden focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",{variants: {variant: {diff --git a/frontend/src/react/pages/settings/PurchaseSection.tsx b/frontend/src/react/pages/settings/PurchaseSection.tsxnew file mode 100644index 0000000000..197fce654f--- /dev/null+++ b/frontend/src/react/pages/settings/PurchaseSection.tsx@@ -0,0 +1,628 @@+import { Check, Loader2, Minus, Plus } from "lucide-react";+import { useCallback, useEffect, useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import { Alert } from "@/react/components/ui/alert";+import { Button } from "@/react/components/ui/button";+import { useVueState } from "@/react/hooks/useVueState";+import { pushNotification, useSubscriptionV1Store } from "@/store";+import type { PurchasePlanAdditional } from "@/types/proto-es/v1/subscription_service_pb";+import {+ BillingInterval,+ PlanType,+ PurchaseDiscount_Type,+ PurchasePlanAdditional_Type,+} from "@/types/proto-es/v1/subscription_service_pb";+import { hasWorkspacePermissionV2 } from "@/utils";++interface PurchaseSectionProps {+ readonly onRequireEnterprise: () => void;+}++// Data model matching the Vue PlanCardData interface.+interface PlanCardData {+ type: PlanType;+ title: string;+ description: string;+ features: { text: string; bold?: boolean }[];+ selfServicePurchase: boolean;+ unitPrice: number;+ userAdditional: PurchasePlanAdditional | undefined;+ billingIntervals: BillingInterval[];+ discountDescription: string;+}++// Feature keys for i18n (display-only, not from API).+const featureKeys: Record<number, string[]> = {+ [PlanType.FREE]: [+ "limits",+ "dcm",+ "git",+ "sql-review",+ "backup",+ "sql-editor",+ "schema",+ "iam",+ "support",+ ],+ [PlanType.TEAM]: [+ "limits",+ "everything",+ "batch-query",+ "read-only",+ "query-policy",+ "sso",+ "groups",+ "db-groups",+ "audit-log",+ "support",+ ],+ [PlanType.ENTERPRISE]: [+ "limits",+ "everything",+ "custom-limits",+ "approval",+ "audit-log",+ "sso",+ "2fa",+ "masking",+ "roles",+ "scim",+ "secret",+ "branding",+ "support",+ ],+};++const planPrefix: Record<number, string> = {+ [PlanType.FREE]: "free",+ [PlanType.TEAM]: "pro",+ [PlanType.ENTERPRISE]: "enterprise",+};++export function PurchaseSection({ onRequireEnterprise }: PurchaseSectionProps) {+ const { t } = useTranslation();+ const subscriptionStore = useSubscriptionV1Store();++ const currentPlan = useVueState(() => subscriptionStore.currentPlan);+ const isFreePlan = useVueState(() => subscriptionStore.isFreePlan);+ const isExpired = useVueState(() => subscriptionStore.isExpired);+ const subscription = useVueState(() => subscriptionStore.subscription);+ const paymentInfo = useVueState(() => subscriptionStore.paymentInfo);+ const purchasePlans = useVueState(() => subscriptionStore.purchasePlans);++ const allowManage = hasWorkspacePermissionV2("bb.subscription.manage");++ const [seats, setSeats] = useState(1);+ const [loading, setLoading] = useState(false);+ const [canceling, setCanceling] = useState(false);+ const [checkPolicy, setCheckPolicy] = useState(false);+ const [pendingPayment, setPendingPayment] = useState(false);++ // Sync state from subscription when it changes.+ useEffect(() => {+ if (subscription && currentPlan !== PlanType.FREE && !isExpired) {+ setSeats(Math.max(1, subscription.seats));+ setCheckPolicy(true);+ }+ }, [subscription, currentPlan, isExpired]);++ // Fetch plans on mount.+ useEffect(() => {+ subscriptionStore.fetchPurchasePlans();+ }, []);++ // Handle session_id polling on mount (covers both new purchase and plan update fallback).+ useEffect(() => {+ const params = new URLSearchParams(window.location.search);+ const sessionId = params.get("session_id");+ if (!sessionId || !allowManage) return;++ let cancelled = false;+ (async () => {+ try {+ const status = await subscriptionStore.verifyCheckoutSession(sessionId);+ if (status !== "complete" || cancelled) return;++ // Poll without updating the store to avoid UI flash.+ // On first check, if subscription is already non-FREE (webhook arrived before page load),+ // we update the store and skip polling immediately.+ setPendingPayment(true);+ for (let i = 0; i < 30; i++) {+ if (cancelled) break;+ const sub = await subscriptionStore.fetchSubscription(false);+ if (sub && sub.plan !== PlanType.FREE) {+ subscriptionStore.setSubscription(sub);+ break;+ }+ await new Promise((r) => setTimeout(r, 2000));+ }+ setPendingPayment(false);+ } catch (e) {+ console.error("failed to verify checkout session", e);+ }+ // Clean up query params.+ window.history.replaceState({}, "", window.location.pathname);+ })();++ return () => {+ cancelled = true;+ };+ }, []);++ // Fetch payment info for active subscriptions.+ useEffect(() => {+ if (!isFreePlan && !isExpired) {+ subscriptionStore.fetchPaymentInfo();+ }+ }, [isFreePlan, isExpired]);++ const isCurrentPlan = useCallback(+ (plan: PlanType) => currentPlan === plan && !isExpired,+ [currentPlan, isExpired]+ );++ // Helpers matching Vue computed functions.+ const planTitle = (type: PlanType): string => {+ switch (type) {+ case PlanType.FREE:+ return t("subscription.plan.free.title");+ case PlanType.TEAM:+ return t("subscription.plan.team.title");+ case PlanType.ENTERPRISE:+ return t("subscription.plan.enterprise.title");+ default:+ return "";+ }+ };++ const planDescription = (type: PlanType): string => {+ switch (type) {+ case PlanType.FREE:+ return t("subscription.purchase.free-description");+ case PlanType.TEAM:+ return t("subscription.purchase.pro-description");+ case PlanType.ENTERPRISE:+ return t("subscription.purchase.enterprise-description");+ default:+ return "";+ }+ };++ const getFeaturesForPlan = (type: PlanType) =>+ (featureKeys[type] || []).map((key) => ({+ text: t(+ `dynamic.subscription.purchase.features.${planPrefix[type]}.${key}`+ ),+ bold: key === "everything",+ }));++ // Build planCards matching the Vue computed.+ const planCards = useMemo((): PlanCardData[] => {+ if (purchasePlans.length === 0) return [];++ const cards: PlanCardData[] = [+ {+ type: PlanType.FREE,+ title: planTitle(PlanType.FREE),+ description: planDescription(PlanType.FREE),+ features: getFeaturesForPlan(PlanType.FREE),+ selfServicePurchase: false,+ unitPrice: 0,+ userAdditional: undefined,+ billingIntervals: [],+ discountDescription: "",+ },+ ];++ for (const plan of purchasePlans) {+ const userAdditional = plan.additionals.find(+ (a) => a.type === PurchasePlanAdditional_Type.USER+ );+ const discount = plan.billingMethods.find((bm) => bm.discount)?.discount;+ let discountDescription = "";+ if (discount) {+ switch (discount.type) {+ case PurchaseDiscount_Type.PERCENTAGE_OFF:+ discountDescription = t(+ "subscription.purchase.discount.percentage-off",+ { value: discount.value }+ );+ break;+ case PurchaseDiscount_Type.FIXED_MONTH_OFF:+ discountDescription = t(+ "subscription.purchase.discount.month-off",+ { value: discount.value }+ );+ break;+ case PurchaseDiscount_Type.FIXED_PRICE_OFF:+ discountDescription = t(+ "subscription.purchase.discount.price-off",+ { value: discount.value }+ );+ break;+ default:+ break;+ }+ }++ cards.push({+ type: plan.type,+ title: planTitle(plan.type),+ description: planDescription(plan.type),+ features: getFeaturesForPlan(plan.type),+ selfServicePurchase: plan.selfServicePurchase,+ unitPrice: userAdditional?.unitPrice ?? 0,+ userAdditional,+ billingIntervals: plan.billingMethods.map((bm) => bm.interval),+ discountDescription,+ });+ }++ return cards;+ }, [purchasePlans, t]);++ const isPlanConfigChanged = (card: PlanCardData): boolean => {+ if (!isCurrentPlan(card.type)) return false;+ return seats !== (subscription?.seats ?? 0);+ };++ const purchaseButtonDisabled = (card: PlanCardData): boolean => {+ if (loading) return true;+ if (!checkPolicy) return true;+ if (isCurrentPlan(card.type) && !isPlanConfigChanged(card)) return true;+ return false;+ };++ const purchaseButtonText = (card: PlanCardData): string => {+ if (isPlanConfigChanged(card)) return t("subscription.purchase.update");+ if (isCurrentPlan(card.type)) return t("subscription.current");+ const label = t("subscription.purchase.subscribe");+ return card.discountDescription+ ? `${label} (${card.discountDescription})`+ : label;+ };++ const handlePurchase = async (card: PlanCardData) => {+ if (purchaseButtonDisabled(card)) return;++ const interval = card.billingIntervals[0] ?? BillingInterval.MONTH;+ setLoading(true);+ try {+ let paymentUrl: string;+ if (isPlanConfigChanged(card)) {+ paymentUrl = await subscriptionStore.updatePurchase(+ card.type,+ interval,+ seats,+ subscription?.etag ?? ""+ );+ } else {+ paymentUrl = await subscriptionStore.createPurchase(+ card.type,+ interval,+ seats+ );+ }+ if (paymentUrl) {+ window.location.href = paymentUrl;+ } else {+ // Direct update — poll without updating store to avoid UI flashing.+ setPendingPayment(true);+ for (let i = 0; i < 30; i++) {+ const sub = await subscriptionStore.fetchSubscription(false);+ if (sub && sub.plan !== PlanType.FREE && sub.seats === seats) {+ subscriptionStore.setSubscription(sub);+ break;+ }+ await new Promise((r) => setTimeout(r, 2000));+ }+ setPendingPayment(false);+ }+ } catch (e) {+ console.error(e);+ } finally {+ setLoading(false);+ }+ };++ const handleCancel = async () => {+ if (!confirm(t("subscription.purchase.cancel-confirm"))) return;+ setCanceling(true);+ try {+ await subscriptionStore.cancelPurchase();+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("subscription.purchase.canceled"),+ });+ } catch (e) {+ console.error(e);+ } finally {+ setCanceling(false);+ }+ };++ // Pending payment overlay.+ if (pendingPayment) {+ return (+ <div className="flex flex-col items-center justify-center py-16 gap-y-4">+ <Loader2 className="h-8 w-8 animate-spin text-accent" />+ <div className="text-lg font-medium">+ {t("subscription.purchase.pending-title")}+ </div>+ <div className="text-sm text-control-placeholder">+ {t("subscription.purchase.pending-description")}+ </div>+ </div>+ );+ }++ return (+ <div className="w-full">+ {/* Active Subscription Management */}+ {!isFreePlan && !isExpired && (+ <>+ {paymentInfo && (+ <div className="space-y-2">+ <div className="text-lg font-medium">+ {t("subscription.purchase.payment-info")}+ </div>+ <div className="grid grid-cols-2 gap-4 text-sm">+ <div>+ <span className="text-control-placeholder">+ {t("subscription.purchase.total-price")}+ </span>+ <div className="flex items-center gap-x-2">+ <div className="font-medium">+ ${(Number(paymentInfo.totalPrice) / 100).toFixed(2)}{" "}+ {paymentInfo.currency.toUpperCase()}+ </div>+ {paymentInfo.invoiceUrl && (+ <a+ href={paymentInfo.invoiceUrl}+ target="_blank"+ rel="noopener noreferrer"+ className="text-accent hover:underline text-sm"+ >+ {t("subscription.purchase.manage-invoices")}+ </a>+ )}+ </div>+ </div>+ <div>+ <span className="text-control-placeholder">+ {t("subscription.purchase.billing-period")}+ </span>+ <div className="font-medium">+ {paymentInfo.periodStart} - {paymentInfo.periodEnd}+ </div>+ </div>+ </div>+ </div>+ )}+ {paymentInfo?.cancelAtPeriodEnd ? (+ <Alert variant="warning" className="my-2">+ {t("subscription.purchase.cancel-pending", {+ date: paymentInfo.periodEnd,+ })}+ </Alert>+ ) : (+ allowManage && (+ <div className="mt-4">+ <Button+ variant="destructive"+ disabled={canceling}+ onClick={handleCancel}+ >+ {canceling && (+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />+ )}+ {t("subscription.purchase.cancel")}+ </Button>+ </div>+ )+ )}+ <hr className="my-6 border-t border-block-border" />+ </>+ )}++ {/* Plan Cards */}+ {planCards.length > 0 && (+ <>+ <div className="grid gap-8 grid-cols-1 lg:grid-cols-3">+ {planCards.map((card) => (+ <PlanCard+ key={card.type}+ title={card.title}+ description={card.description}+ features={card.features}+ highlighted={isCurrentPlan(card.type)}+ pricing={+ card.type === PlanType.FREE ? (+ <span className="text-4xl font-extrabold">$0</span>+ ) : card.unitPrice > 0 ? (+ <>+ <span className="text-4xl font-extrabold">+ ${card.unitPrice / 100}+ </span>+ <span className="ml-2 text-control-placeholder">+ {t("subscription.purchase.per-user-per-month")}+ </span>+ </>+ ) : (+ <span className="text-3xl font-extrabold">+ {t("subscription.purchase.custom")}+ </span>+ )+ }+ config={+ allowManage && card.userAdditional ? (+ <div className="flex items-center">+ <span className="text-main">+ {t("subscription.purchase.seats")}+ </span>+ <div className="ml-auto flex items-center h-7 rounded-lg bg-gray-200 text-gray-600">+ <button+ type="button"+ className="px-2 h-full rounded-l hover:bg-gray-300 disabled:opacity-50 cursor-pointer"+ disabled={+ seats <= (card.userAdditional.minimumCount || 1)+ }+ onClick={() =>+ setSeats(+ Math.max(+ card.userAdditional!.minimumCount || 1,+ seats - 1+ )+ )+ }+ >+ <Minus className="h-3 w-3" />+ </button>+ <span className="w-8 text-center text-sm">{seats}</span>+ <button+ type="button"+ className="px-2 h-full rounded-r hover:bg-gray-300 disabled:opacity-50 cursor-pointer"+ disabled={+ card.userAdditional.maximumCount > 0 &&+ seats >= card.userAdditional.maximumCount+ }+ onClick={() => setSeats(seats + 1)}+ >+ <Plus className="h-3 w-3" />+ </button>+ </div>+ </div>+ ) : undefined+ }+ action={+ allowManage ? (+ card.type === PlanType.FREE ? (+ isCurrentPlan(PlanType.FREE) ? (+ <Button+ variant="outline"+ className="w-full"+ disabled={isCurrentPlan(PlanType.FREE)}+ >+ {t("subscription.current")}+ </Button>+ ) : undefined+ ) : card.selfServicePurchase ? (+ <>+ <label className="mt-3 flex items-start gap-x-2 text-sm text-control-placeholder cursor-pointer">+ <input+ type="checkbox"+ checked={checkPolicy}+ onChange={(e) => setCheckPolicy(e.target.checked)}+ className="mt-0.5"+ />+ <span>+ {t("subscription.purchase.accept-terms-prefix")}{" "}+ <a+ href="https://www.bytebase.com/terms"+ target="_blank"+ rel="noopener noreferrer"+ className="underline hover:text-main"+ >+ {t("subscription.purchase.terms-of-service")}+ </a>{" "}+ {t("subscription.purchase.and")}{" "}+ <a+ href="https://www.bytebase.com/privacy"+ target="_blank"+ rel="noopener noreferrer"+ className="underline hover:text-main"+ >+ {t("subscription.purchase.privacy-policy")}+ </a>+ </span>+ </label>+ <Button+ className="mt-3 w-full"+ disabled={purchaseButtonDisabled(card)}+ onClick={() => handlePurchase(card)}+ >+ {loading && (+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />+ )}+ {purchaseButtonText(card)}+ </Button>+ </>+ ) : (+ <Button+ variant="outline"+ className="w-full"+ onClick={onRequireEnterprise}+ >+ {t("subscription.contact-us")}+ </Button>+ )+ ) : undefined+ }+ />+ ))}+ </div>++ {/* Footer */}+ <div className="pt-4 pb-2 text-center">+ <a+ className="text-sm text-control-placeholder hover:text-main underline"+ href="https://www.bytebase.com/pricing?source=console"+ target="_blank"+ rel="noopener noreferrer"+ >+ {t("subscription.purchase.see-comparison")}+ </a>+ </div>+ </>+ )}+ </div>+ );+}++// Plan card component matching Vue's PlanCard.vue.+function PlanCard({+ title,+ description,+ features,+ highlighted,+ pricing,+ config,+ action,+}: {+ title: string;+ description: string;+ features: { text: string; bold?: boolean }[];+ highlighted: boolean;+ pricing: React.ReactNode;+ config?: React.ReactNode;+ action?: React.ReactNode;+}) {+ return (+ <div+ className={`h-full flex flex-col rounded-lg p-5 border-2 ${highlighted ? "shadow-lg border-accent" : "border-block-border"}`}+ >+ <h3 className="text-3xl font-semibold text-main">{title}</h3>+ <p className="text-control-placeholder mt-1 text-sm">{description}</p>+ <div className="mt-4 mb-2 flex items-baseline">{pricing}</div>+ <div className="mb-4 space-y-1 text-sm">+ {features.map((f, i) => (+ <div key={i} className="flex items-start">+ <Check className="h-3.5 w-3.5 text-control-light mr-2 mt-0.5 shrink-0" />+ <span+ className={+ f.bold+ ? "font-semibold text-main leading-5"+ : "text-main leading-5"+ }+ >+ {f.text}+ </span>+ </div>+ ))}+ </div>+ <div className="flex-1">{config}</div>+ {action && <div className="mt-3">{action}</div>}+ </div>+ );+}diff --git a/frontend/src/react/pages/settings/SubscriptionPage.tsx b/frontend/src/react/pages/settings/SubscriptionPage.tsxindex cc6b93c14a..7e2cc60501 100644--- a/frontend/src/react/pages/settings/SubscriptionPage.tsx+++ b/frontend/src/react/pages/settings/SubscriptionPage.tsx@@ -14,6 +14,7 @@ import {} from "@/store";import { PlanType } from "@/types/proto-es/v1/subscription_service_pb";import { hasWorkspacePermissionV2 } from "@/utils";+import { PurchaseSection } from "./PurchaseSection";interface SubscriptionPageProps {onRequireEnterprise: () => void;@@ -28,15 +29,16 @@ export function SubscriptionPage({const subscriptionStore = useSubscriptionV1Store();const actuatorStore = useActuatorV1Store();- const allowEdit = hasWorkspacePermissionV2("bb.settings.set");+ const allowManage = hasWorkspacePermissionV2("bb.subscription.manage");const allowManageInstanceLicenses =- allowEdit && hasWorkspacePermissionV2("bb.instances.list");+ allowManage && hasWorkspacePermissionV2("bb.instances.list");// Subscribe to Vue reactive stateconst currentPlan = useVueState(() => subscriptionStore.currentPlan);const isFreePlan = useVueState(() => subscriptionStore.isFreePlan);const isTrialing = useVueState(() => subscriptionStore.isTrialing);const isExpired = useVueState(() => subscriptionStore.isExpired);+ const isSaaSMode = useVueState(() => actuatorStore.isSaaSMode);const isSelfHostLicense = useVueState(() => subscriptionStore.isSelfHostLicense);@@ -88,7 +90,7 @@ export function SubscriptionPage({if (disabled) return;setLoading(true);try {- await subscriptionStore.patchSubscription(license);+ await subscriptionStore.uploadLicense(license);pushNotification({module: "bytebase",style: "SUCCESS",@@ -151,7 +153,7 @@ export function SubscriptionPage({)}{/* Free trial */}- {showTrial && allowEdit && (+ {showTrial && allowManage && (<div className="flex flex-col text-left"><div className="text-main">{t("subscription.try-for-free")}</div><div className="mt-1">@@ -205,38 +207,50 @@ export function SubscriptionPage({{/* Divider */}<hr className="my-6 border-t border-block-border" />- {/* Workspace ID */}- <div>- <label className="flex items-center gap-x-2">- <span className="text-main">- {t("settings.general.workspace.id")}- </span>- </label>- <div className="mb-3 text-sm text-control-placeholder">- {t("settings.general.workspace.id-description")}- </div>- <div className="mb-4 flex items-center gap-x-2">- <Input- readOnly- value={workspaceId}- onClick={(e) => (e.target as HTMLInputElement).select()}- />- <Button- variant="ghost"- size="icon"- onClick={handleCopy}- title={t("common.copy")}- >- <Copy className="h-4 w-4" />- </Button>- {copied && (- <span className="text-sm text-success">{t("common.copied")}</span>- )}- </div>- </div>+ {/* Workspace ID (self-hosted only) */}+ {!isSaaSMode && (+ <>+ <div>+ <label className="flex items-center gap-x-2">+ <span className="text-main">+ {t("settings.general.workspace.id")}+ </span>+ </label>+ <div className="mb-3 text-sm text-control-placeholder">+ {t("settings.general.workspace.id-description")}+ </div>+ <div className="mb-4 flex items-center gap-x-2">+ <Input+ readOnly+ value={workspaceId}+ onClick={(e) => (e.target as HTMLInputElement).select()}+ />+ <Button+ variant="ghost"+ size="icon"+ onClick={handleCopy}+ title={t("common.copy")}+ >+ <Copy className="h-4 w-4" />+ </Button>+ {copied && (+ <span className="text-sm text-success">+ {t("common.copied")}+ </span>+ )}+ </div>+ </div>+ <hr className="my-6 border-t border-block-border" />+ </>+ )}++ {/* SaaS: Purchase UI */}+ {isSaaSMode && (+ <PurchaseSection onRequireEnterprise={onRequireEnterprise} />+ )}- {/* Upload license */}- {isSelfHostLicense && (+ {/* Self-hosted: Upload license */}+ {!isSaaSMode && isSelfHostLicense && (<div className="w-full mt-4 flex flex-col"><label className="flex items-center gap-x-2"><span className="text-main">@@ -253,7 +267,7 @@ export function SubscriptionPage({>{t("common.learn-more")} ></a>- {showTrial && allowEdit && (+ {showTrial && allowManage && (<Buttonvariant="link"size="sm"@@ -269,12 +283,12 @@ export function SubscriptionPage({onChange={(e: ChangeEvent<HTMLTextAreaElement>) =>setLicense(e.target.value)}- disabled={!allowEdit}+ disabled={!allowManage}placeholder={t("common.sensitive-placeholder")}/><div className="ml-auto mt-3"><Button- disabled={disabled || !allowEdit}+ disabled={disabled || !allowManage}onClick={handleUpload}className="capitalize">diff --git a/frontend/src/store/modules/v1/subscription.ts b/frontend/src/store/modules/v1/subscription.tsindex 2b77543787..5132b56036 100644--- a/frontend/src/store/modules/v1/subscription.ts+++ b/frontend/src/store/modules/v1/subscription.ts@@ -17,12 +17,23 @@ import type {Instance,InstanceResource,} from "@/types/proto-es/v1/instance_service_pb";-import type { Subscription } from "@/types/proto-es/v1/subscription_service_pb";+import type {+ PaymentInfo,+ PurchasePlan,+ Subscription,+} from "@/types/proto-es/v1/subscription_service_pb";import {+ BillingInterval,+ CancelPurchaseRequestSchema,+ CreatePurchaseRequestSchema,+ GetPaymentInfoRequestSchema,GetSubscriptionRequestSchema,+ ListPurchasePlansRequestSchema,PlanFeature,PlanType,- UpdateSubscriptionRequestSchema,+ UpdatePurchaseRequestSchema,+ UploadLicenseRequestSchema,+ VerifyCheckoutSessionRequestSchema,} from "@/types/proto-es/v1/subscription_service_pb";import { formatAbsoluteDateTime } from "@/utils/datetime";@@ -34,6 +45,8 @@ export const useSubscriptionV1Store = defineStore("subscription_v1", () => {// Stateconst subscription = ref<Subscription | undefined>(undefined);const trialingDays = ref(14);+ const paymentInfo = ref<PaymentInfo | undefined>(undefined);+ const purchasePlans = ref<PurchasePlan[]>([]);// Gettersconst currentPlan = computed(() => {@@ -202,32 +215,109 @@ export const useSubscriptionV1Store = defineStore("subscription_v1", () => {return hasFeature(feature) && !instance.activation;};- const fetchSubscription = async () => {+ // Fetch subscription. When cache=false, returns the result without updating the store.+ // Useful for polling during plan changes to avoid UI flashing (PAID → FREE → PAID).+ const fetchSubscription = async (cache = true) => {try {const request = create(GetSubscriptionRequestSchema, {});const sub =await subscriptionServiceClientConnect.getSubscription(request);- setSubscription(sub);+ if (cache) {+ setSubscription(sub);+ }return sub;} catch (e) {console.error(e);}};- const patchSubscription = async (license: string) => {- const request = create(UpdateSubscriptionRequestSchema, {+ const uploadLicense = async (license: string) => {+ const request = create(UploadLicenseRequestSchema, {license,});- const sub =- await subscriptionServiceClientConnect.updateSubscription(request);+ const sub = await subscriptionServiceClientConnect.uploadLicense(request);setSubscription(sub);return sub;};+ // Purchase actions (SaaS only)+ const createPurchase = async (+ plan: PlanType,+ interval: BillingInterval,+ seats: number+ ): Promise<string> => {+ const request = create(CreatePurchaseRequestSchema, {+ plan,+ interval,+ seats,+ });+ const response =+ await subscriptionServiceClientConnect.createPurchase(request);+ return response.paymentUrl;+ };++ const updatePurchase = async (+ plan: PlanType,+ interval: BillingInterval,+ seats: number,+ etag: string+ ): Promise<string> => {+ const request = create(UpdatePurchaseRequestSchema, {+ plan,+ interval,+ seats,+ etag,+ });+ const response =+ await subscriptionServiceClientConnect.updatePurchase(request);+ return response.paymentUrl;+ };++ const cancelPurchase = async () => {+ const request = create(CancelPurchaseRequestSchema, {});+ await subscriptionServiceClientConnect.cancelPurchase(request);+ await fetchSubscription();+ };++ const fetchPaymentInfo = async () => {+ try {+ const request = create(GetPaymentInfoRequestSchema, {});+ const info =+ await subscriptionServiceClientConnect.getPaymentInfo(request);+ paymentInfo.value = info;+ return info;+ } catch (e) {+ console.error(e);+ }+ };++ const verifyCheckoutSession = async (sessionId: string): Promise<string> => {+ const request = create(VerifyCheckoutSessionRequestSchema, {+ sessionId,+ });+ const response =+ await subscriptionServiceClientConnect.verifyCheckoutSession(request);+ return response.status;+ };++ const fetchPurchasePlans = async () => {+ try {+ const request = create(ListPurchasePlansRequestSchema, {});+ const response =+ await subscriptionServiceClientConnect.listPurchasePlans(request);+ purchasePlans.value = response.plans;+ return response.plans;+ } catch (e) {+ console.error(e);+ }+ };+return {// Statesubscription,trialingDays,+ paymentInfo,+ purchasePlans,// GetterscurrentPlan,isFreePlan,@@ -248,7 +338,15 @@ export const useSubscriptionV1Store = defineStore("subscription_v1", () => {instanceMissingLicense,getMinimumRequiredPlan,fetchSubscription,- patchSubscription,+ uploadLicense,+ setSubscription,+ // Purchase actions (SaaS)+ createPurchase,+ updatePurchase,+ cancelPurchase,+ verifyCheckoutSession,+ fetchPaymentInfo,+ fetchPurchasePlans,};});diff --git a/frontend/src/types/proto-es/v1/subscription_service_pb.d.ts b/frontend/src/types/proto-es/v1/subscription_service_pb.d.tsindex d360062be6..d7fc652ff0 100644--- a/frontend/src/types/proto-es/v1/subscription_service_pb.d.ts+++ b/frontend/src/types/proto-es/v1/subscription_service_pb.d.ts@@ -24,28 +24,20 @@ export declare type GetSubscriptionRequest = Message<"bytebase.v1.GetSubscriptioexport declare const GetSubscriptionRequestSchema: GenMessage<GetSubscriptionRequest>;/**- * @generated from message bytebase.v1.UpdateSubscriptionRequest+ * @generated from message bytebase.v1.UploadLicenseRequest*/-export declare type UpdateSubscriptionRequest = Message<"bytebase.v1.UpdateSubscriptionRequest"> & {+export declare type UploadLicenseRequest = Message<"bytebase.v1.UploadLicenseRequest"> & {/*** @generated from field: string license = 1;*/license: string;-- /**- * If set to true, and the subscription is not found, a new subscription will be created.- * In this situation, `update_mask` is ignored.- *- * @generated from field: bool allow_missing = 2;- */- allowMissing: boolean;};/**- * Describes the message bytebase.v1.UpdateSubscriptionRequest.- * Use `create(UpdateSubscriptionRequestSchema)` to create a new message.+ * Describes the message bytebase.v1.UploadLicenseRequest.+ * Use `create(UploadLicenseRequestSchema)` to create a new message.*/-export declare const UpdateSubscriptionRequestSchema: GenMessage<UpdateSubscriptionRequest>;+export declare const UploadLicenseRequestSchema: GenMessage<UploadLicenseRequest>;/*** @generated from message bytebase.v1.CreatePurchaseRequest@@ -74,22 +66,64 @@ export declare type CreatePurchaseRequest = Message<"bytebase.v1.CreatePurchaseRexport declare const CreatePurchaseRequestSchema: GenMessage<CreatePurchaseRequest>;/**- * @generated from message bytebase.v1.CreatePurchaseResponse+ * @generated from message bytebase.v1.PurchaseResponse*/-export declare type CreatePurchaseResponse = Message<"bytebase.v1.CreatePurchaseResponse"> & {+export declare type PurchaseResponse = Message<"bytebase.v1.PurchaseResponse"> & {/**- * Stripe Checkout URL for the user to complete payment.+ * If set, redirect to this Stripe Checkout URL.+ * If empty, the update was applied directly using the existing payment method.** @generated from field: string payment_url = 1;*/paymentUrl: string;++ /**+ * Stripe Checkout Session ID. Used to verify the session after redirect.+ *+ * @generated from field: string session_id = 2;+ */+ sessionId: string;+};++/**+ * Describes the message bytebase.v1.PurchaseResponse.+ * Use `create(PurchaseResponseSchema)` to create a new message.+ */+export declare const PurchaseResponseSchema: GenMessage<PurchaseResponse>;++/**+ * @generated from message bytebase.v1.VerifyCheckoutSessionRequest+ */+export declare type VerifyCheckoutSessionRequest = Message<"bytebase.v1.VerifyCheckoutSessionRequest"> & {+ /**+ * @generated from field: string session_id = 1;+ */+ sessionId: string;+};++/**+ * Describes the message bytebase.v1.VerifyCheckoutSessionRequest.+ * Use `create(VerifyCheckoutSessionRequestSchema)` to create a new message.+ */+export declare const VerifyCheckoutSessionRequestSchema: GenMessage<VerifyCheckoutSessionRequest>;++/**+ * @generated from message bytebase.v1.VerifyCheckoutSessionResponse+ */+export declare type VerifyCheckoutSessionResponse = Message<"bytebase.v1.VerifyCheckoutSessionResponse"> & {+ /**+ * Stripe Checkout Session status: "complete", "expired", or "open".+ *+ * @generated from field: string status = 1;+ */+ status: string;};/**- * Describes the message bytebase.v1.CreatePurchaseResponse.- * Use `create(CreatePurchaseResponseSchema)` to create a new message.+ * Describes the message bytebase.v1.VerifyCheckoutSessionResponse.+ * Use `create(VerifyCheckoutSessionResponseSchema)` to create a new message.*/-export declare const CreatePurchaseResponseSchema: GenMessage<CreatePurchaseResponse>;+export declare const VerifyCheckoutSessionResponseSchema: GenMessage<VerifyCheckoutSessionResponse>;/*** @generated from message bytebase.v1.UpdatePurchaseRequest@@ -122,25 +156,6 @@ export declare type UpdatePurchaseRequest = Message<"bytebase.v1.UpdatePurchaseR*/export declare const UpdatePurchaseRequestSchema: GenMessage<UpdatePurchaseRequest>;-/**- * @generated from message bytebase.v1.UpdatePurchaseResponse- */-export declare type UpdatePurchaseResponse = Message<"bytebase.v1.UpdatePurchaseResponse"> & {- /**- * If set, redirect to this Stripe Checkout URL.- * If empty, the update was applied directly using the existing payment method.- *- * @generated from field: string payment_url = 1;- */- paymentUrl: string;-};--/**- * Describes the message bytebase.v1.UpdatePurchaseResponse.- * Use `create(UpdatePurchaseResponseSchema)` to create a new message.- */-export declare const UpdatePurchaseResponseSchema: GenMessage<UpdatePurchaseResponse>;-/*** @generated from message bytebase.v1.CancelPurchaseRequest*/@@ -153,18 +168,6 @@ export declare type CancelPurchaseRequest = Message<"bytebase.v1.CancelPurchaseR*/export declare const CancelPurchaseRequestSchema: GenMessage<CancelPurchaseRequest>;-/**- * @generated from message bytebase.v1.CancelPurchaseResponse- */-export declare type CancelPurchaseResponse = Message<"bytebase.v1.CancelPurchaseResponse"> & {-};--/**- * Describes the message bytebase.v1.CancelPurchaseResponse.- * Use `create(CancelPurchaseResponseSchema)` to create a new message.- */-export declare const CancelPurchaseResponseSchema: GenMessage<CancelPurchaseResponse>;-/*** @generated from message bytebase.v1.GetPaymentInfoRequest*/@@ -207,6 +210,13 @@ export declare type PaymentInfo = Message<"bytebase.v1.PaymentInfo"> & {* @generated from field: string invoice_url = 5;*/invoiceUrl: string;++ /**+ * Whether the subscription is scheduled to cancel at the end of the current billing period.+ *+ * @generated from field: bool cancel_at_period_end = 6;+ */+ cancelAtPeriodEnd: boolean;};/**@@ -332,14 +342,14 @@ export declare const PurchaseBillingMethodSchema: GenMessage<PurchaseBillingMeth*/export declare type PurchaseDiscount = Message<"bytebase.v1.PurchaseDiscount"> & {/**- * @generated from field: string description = 1;+ * @generated from field: bytebase.v1.PurchaseDiscount.Type type = 1;*/- description: string;+ type: PurchaseDiscount_Type;/**- * @generated from field: string promotion_code = 2;+ * @generated from field: int32 value = 2;*/- promotionCode: string;+ value: number;};/**@@ -348,6 +358,36 @@ export declare type PurchaseDiscount = Message<"bytebase.v1.PurchaseDiscount"> &*/export declare const PurchaseDiscountSchema: GenMessage<PurchaseDiscount>;+/**+ * @generated from enum bytebase.v1.PurchaseDiscount.Type+ */+export enum PurchaseDiscount_Type {+ /**+ * @generated from enum value: TYPE_UNSPECIFIED = 0;+ */+ TYPE_UNSPECIFIED = 0,++ /**+ * @generated from enum value: PERCENTAGE_OFF = 1;+ */+ PERCENTAGE_OFF = 1,++ /**+ * @generated from enum value: FIXED_MONTH_OFF = 2;+ */+ FIXED_MONTH_OFF = 2,++ /**+ * @generated from enum value: FIXED_PRICE_OFF = 3;+ */+ FIXED_PRICE_OFF = 3,+}++/**+ * Describes the enum bytebase.v1.PurchaseDiscount.Type.+ */+export declare const PurchaseDiscount_TypeSchema: GenEnum<PurchaseDiscount_Type>;+/*** @generated from message bytebase.v1.ListPurchasePlansRequest*/@@ -421,6 +461,13 @@ export declare type Subscription = Message<"bytebase.v1.Subscription"> & {* @generated from field: bool ha = 8;*/ha: boolean;++ /**+ * Etag for optimistic concurrency on purchase updates. Only set in SaaS mode.+ *+ * @generated from field: string etag = 9;+ */+ etag: string;};/**@@ -938,7 +985,6 @@ export declare const SubscriptionService: GenService<{* GetSubscription returns the current subscription.* If there is no license, we will return a free plan subscription without expiration time.* If there is expired license, we will return a free plan subscription with the expiration time of the expired license.- * Permissions required: None** @generated from rpc bytebase.v1.SubscriptionService.GetSubscription*/@@ -948,14 +994,13 @@ export declare const SubscriptionService: GenService<{output: typeof SubscriptionSchema;},/**- * Updates the enterprise license subscription (self-hosted only).- * Permissions required: bb.settings.set+ * Uploads an enterprise license (self-hosted only).*- * @generated from rpc bytebase.v1.SubscriptionService.UpdateSubscription+ * @generated from rpc bytebase.v1.SubscriptionService.UploadLicense*/- updateSubscription: {+ uploadLicense: {methodKind: "unary";- input: typeof UpdateSubscriptionRequestSchema;+ input: typeof UploadLicenseRequestSchema;output: typeof SubscriptionSchema;},/**@@ -967,7 +1012,7 @@ export declare const SubscriptionService: GenService<{createPurchase: {methodKind: "unary";input: typeof CreatePurchaseRequestSchema;- output: typeof CreatePurchaseResponseSchema;+ output: typeof PurchaseResponseSchema;},/*** UpdatePurchase updates an existing subscription (SaaS only).@@ -978,7 +1023,7 @@ export declare const SubscriptionService: GenService<{updatePurchase: {methodKind: "unary";input: typeof UpdatePurchaseRequestSchema;- output: typeof UpdatePurchaseResponseSchema;+ output: typeof PurchaseResponseSchema;},/*** CancelPurchase cancels an active subscription (SaaS only).@@ -988,7 +1033,7 @@ export declare const SubscriptionService: GenService<{cancelPurchase: {methodKind: "unary";input: typeof CancelPurchaseRequestSchema;- output: typeof CancelPurchaseResponseSchema;+ output: typeof PurchaseResponseSchema;},/*** GetPaymentInfo returns payment details for the current subscription (SaaS only).@@ -1000,6 +1045,16 @@ export declare const SubscriptionService: GenService<{input: typeof GetPaymentInfoRequestSchema;output: typeof PaymentInfoSchema;},+ /**+ * VerifyCheckoutSession verifies a Stripe Checkout Session status (SaaS only).+ *+ * @generated from rpc bytebase.v1.SubscriptionService.VerifyCheckoutSession+ */+ verifyCheckoutSession: {+ methodKind: "unary";+ input: typeof VerifyCheckoutSessionRequestSchema;+ output: typeof VerifyCheckoutSessionResponseSchema;+ },/*** ListPurchasePlans returns available plans for self-service purchase.*diff --git a/frontend/src/types/proto-es/v1/subscription_service_pb.js b/frontend/src/types/proto-es/v1/subscription_service_pb.jsindex 475f161db0..74c9207dde 100644--- a/frontend/src/types/proto-es/v1/subscription_service_pb.js+++ b/frontend/src/types/proto-es/v1/subscription_service_pb.js@@ -13,7 +13,7 @@ import { file_v1_annotation } from "./annotation_pb";* Describes the file v1/subscription_service.proto.*/export const file_v1_subscription_service = /*@__PURE__*/- fileDesc("Ch12MS9zdWJzY3JpcHRpb25fc2VydmljZS5wcm90bxILYnl0ZWJhc2UudjEiGAoWR2V0U3Vic2NyaXB0aW9uUmVxdWVzdCJDChlVcGRhdGVTdWJzY3JpcHRpb25SZXF1ZXN0Eg8KB2xpY2Vuc2UYASABKAkSFQoNYWxsb3dfbWlzc2luZxgCIAEoCCJ7ChVDcmVhdGVQdXJjaGFzZVJlcXVlc3QSIwoEcGxhbhgBIAEoDjIVLmJ5dGViYXNlLnYxLlBsYW5UeXBlEi4KCGludGVydmFsGAIgASgOMhwuYnl0ZWJhc2UudjEuQmlsbGluZ0ludGVydmFsEg0KBXNlYXRzGAMgASgFIi0KFkNyZWF0ZVB1cmNoYXNlUmVzcG9uc2USEwoLcGF5bWVudF91cmwYASABKAkiiQEKFVVwZGF0ZVB1cmNoYXNlUmVxdWVzdBIjCgRwbGFuGAEgASgOMhUuYnl0ZWJhc2UudjEuUGxhblR5cGUSLgoIaW50ZXJ2YWwYAiABKA4yHC5ieXRlYmFzZS52MS5CaWxsaW5nSW50ZXJ2YWwSDQoFc2VhdHMYAyABKAUSDAoEZXRhZxgEIAEoCSItChZVcGRhdGVQdXJjaGFzZVJlc3BvbnNlEhMKC3BheW1lbnRfdXJsGAEgASgJIhcKFUNhbmNlbFB1cmNoYXNlUmVxdWVzdCIYChZDYW5jZWxQdXJjaGFzZVJlc3BvbnNlIhcKFUdldFBheW1lbnRJbmZvUmVxdWVzdCJzCgtQYXltZW50SW5mbxITCgt0b3RhbF9wcmljZRgBIAEoCRIQCghjdXJyZW5jeRgCIAEoCRIUCgxwZXJpb2Rfc3RhcnQYAyABKAkSEgoKcGVyaW9kX2VuZBgEIAEoCRITCgtpbnZvaWNlX3VybBgFIAEoCSLJAQoMUHVyY2hhc2VQbGFuEiMKBHR5cGUYASABKA4yFS5ieXRlYmFzZS52MS5QbGFuVHlwZRIdChVzZWxmX3NlcnZpY2VfcHVyY2hhc2UYAiABKAgSOAoLYWRkaXRpb25hbHMYAyADKAsyIy5ieXRlYmFzZS52MS5QdXJjaGFzZVBsYW5BZGRpdGlvbmFsEjsKD2JpbGxpbmdfbWV0aG9kcxgEIAMoCzIiLmJ5dGViYXNlLnYxLlB1cmNoYXNlQmlsbGluZ01ldGhvZCLOAQoWUHVyY2hhc2VQbGFuQWRkaXRpb25hbBI2CgR0eXBlGAEgASgOMiguYnl0ZWJhc2UudjEuUHVyY2hhc2VQbGFuQWRkaXRpb25hbC5UeXBlEhIKCnVuaXRfcHJpY2UYAiABKAUSEgoKZnJlZV9jb3VudBgDIAEoBRIVCg1taW5pbXVtX2NvdW50GAQgASgFEhUKDW1heGltdW1fY291bnQYBSABKAUiJgoEVHlwZRIUChBUWVBFX1VOU1BFQ0lGSUVEEAASCAoEVVNFUhABIngKFVB1cmNoYXNlQmlsbGluZ01ldGhvZBIuCghpbnRlcnZhbBgBIAEoDjIcLmJ5dGViYXNlLnYxLkJpbGxpbmdJbnRlcnZhbBIvCghkaXNjb3VudBgCIAEoCzIdLmJ5dGViYXNlLnYxLlB1cmNoYXNlRGlzY291bnQiPwoQUHVyY2hhc2VEaXNjb3VudBITCgtkZXNjcmlwdGlvbhgBIAEoCRIWCg5wcm9tb3Rpb25fY29kZRgCIAEoCSIaChhMaXN0UHVyY2hhc2VQbGFuc1JlcXVlc3QiRQoZTGlzdFB1cmNoYXNlUGxhbnNSZXNwb25zZRIoCgVwbGFucxgBIAMoCzIZLmJ5dGViYXNlLnYxLlB1cmNoYXNlUGxhbiL5AQoMU3Vic2NyaXB0aW9uEigKBHBsYW4YASABKA4yFS5ieXRlYmFzZS52MS5QbGFuVHlwZUID4EEDEhIKBXNlYXRzGAIgASgFQgPgQQMSFgoJaW5zdGFuY2VzGAMgASgFQgPgQQMSHQoQYWN0aXZlX2luc3RhbmNlcxgEIAEoBUID4EEDEjUKDGV4cGlyZXNfdGltZRgFIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXBCA+BBAxIVCgh0cmlhbGluZxgGIAEoCEID4EEDEhUKCG9yZ19uYW1lGAcgASgJQgPgQQMSDwoCaGEYCCABKAhCA+BBAyJuCgpQbGFuQ29uZmlnEisKBXBsYW5zGAEgAygLMhwuYnl0ZWJhc2UudjEuUGxhbkxpbWl0Q29uZmlnEjMKEWluc3RhbmNlX2ZlYXR1cmVzGAIgAygOMhguYnl0ZWJhc2UudjEuUGxhbkZlYXR1cmUingEKD1BsYW5MaW1pdENvbmZpZxIjCgR0eXBlGAEgASgOMhUuYnl0ZWJhc2UudjEuUGxhblR5cGUSHgoWbWF4aW11bV9pbnN0YW5jZV9jb3VudBgCIAEoBRIaChJtYXhpbXVtX3NlYXRfY291bnQYAyABKAUSKgoIZmVhdHVyZXMYBCADKA4yGC5ieXRlYmFzZS52MS5QbGFuRmVhdHVyZSpICg9CaWxsaW5nSW50ZXJ2YWwSIAocQklMTElOR19JTlRFUlZBTF9VTlNQRUNJRklFRBAAEgkKBU1PTlRIEAESCAoEWUVBUhACKkkKCFBsYW5UeXBlEhkKFVBMQU5fVFlQRV9VTlNQRUNJRklFRBAAEggKBEZSRUUQARIICgRURUFNEAISDgoKRU5URVJQUklTRRADKuESCgtQbGFuRmVhdHVyZRIXChNGRUFUVVJFX1VOU1BFQ0lGSUVEEAASGwoXRkVBVFVSRV9EQVRBQkFTRV9DSEFOR0UQARIsCihGRUFUVVJFX0dJVF9CQVNFRF9TQ0hFTUFfVkVSU0lPTl9DT05UUk9MEAISKAokRkVBVFVSRV9ERUNMQVJBVElWRV9TQ0hFTUFfTUlHUkFUSU9OEAMSIwofRkVBVFVSRV9DT01QQVJFX0FORF9TWU5DX1NDSEVNQRAEEiAKHEZFQVRVUkVfT05MSU5FX1NDSEVNQV9DSEFOR0UQBRIlCiFGRUFUVVJFX1BSRV9ERVBMT1lNRU5UX1NRTF9SRVZJRVcQBhIwCixGRUFUVVJFX0FVVE9NQVRJQ19CQUNLVVBfQkVGT1JFX0RBVEFfQ0hBTkdFUxAHEiMKH0ZFQVRVUkVfT05FX0NMSUNLX0RBVEFfUk9MTEJBQ0sQCBIoCiRGRUFUVVJFX01VTFRJX0RBVEFCQVNFX0JBVENIX0NIQU5HRVMQCRIuCipGRUFUVVJFX1BST0dSRVNTSVZFX0VOVklST05NRU5UX0RFUExPWU1FTlQQChIiCh5GRUFUVVJFX1NDSEVEVUxFRF9ST0xMT1VUX1RJTUUQCxIeChpGRUFUVVJFX0RBVEFCQVNFX0NIQU5HRUxPRxAMEiIKHkZFQVRVUkVfU0NIRU1BX0RSSUZUX0RFVEVDVElPThANEhoKFkZFQVRVUkVfUk9MTE9VVF9QT0xJQ1kQDhIgChxGRUFUVVJFX1dFQl9CQVNFRF9TUUxfRURJVE9SEA8SIQodRkVBVFVSRV9TUUxfRURJVE9SX0FETUlOX01PREUQEBIjCh9GRUFUVVJFX05BVFVSQUxfTEFOR1VBR0VfVE9fU1FMEBESIAocRkVBVFVSRV9BSV9RVUVSWV9FWFBMQU5BVElPThASEiAKHEZFQVRVUkVfQUlfUVVFUllfU1VHR0VTVElPTlMQExIZChVGRUFUVVJFX0FVVE9fQ09NUExFVEUQFBIaChZGRUFUVVJFX1NDSEVNQV9ESUFHUkFNEBUSGQoVRkVBVFVSRV9TQ0hFTUFfRURJVE9SEBYSFwoTRkVBVFVSRV9EQVRBX0VYUE9SVBAXEh8KG0ZFQVRVUkVfREFUQV9PRkZMSU5FX0VYUE9SVBAYEhkKFUZFQVRVUkVfUVVFUllfSElTVE9SWRAZEigKJEZFQVRVUkVfU0FWRURfQU5EX1NIQVJFRF9TUUxfU0NSSVBUUxAaEhcKE0ZFQVRVUkVfQkFUQ0hfUVVFUlkQGxIpCiVGRUFUVVJFX0lOU1RBTkNFX1JFQURfT05MWV9DT05ORUNUSU9OEBwSGAoURkVBVFVSRV9RVUVSWV9QT0xJQ1kQHRIhCh1GRUFUVVJFX1JFU1RSSUNUX0NPUFlJTkdfREFUQRAeEg8KC0ZFQVRVUkVfSUFNEB8SIwofRkVBVFVSRV9JTlNUQU5DRV9TU0xfQ09OTkVDVElPThAgEi8KK0ZFQVRVUkVfSU5TVEFOQ0VfQ09OTkVDVElPTl9PVkVSX1NTSF9UVU5ORUwQIRIyCi5GRUFUVVJFX0lOU1RBTkNFX0NPTk5FQ1RJT05fSUFNX0FVVEhFTlRJQ0FUSU9OECISIQodRkVBVFVSRV9HT09HTEVfQU5EX0dJVEhVQl9TU08QIxIXChNGRUFUVVJFX1VTRVJfR1JPVVBTECQSKAokRkVBVFVSRV9ESVNBTExPV19TRUxGX1NFUlZJQ0VfU0lHTlVQECUSJQohRkVBVFVSRV9DVVNUT01fSU5TVEFOQ0VfU1lOQ19USU1FECYSLAooRkVBVFVSRV9DVVNUT01fSU5TVEFOQ0VfQ09OTkVDVElPTl9MSU1JVBAnEhsKF0ZFQVRVUkVfUklTS19BU1NFU1NNRU5UECgSHQoZRkVBVFVSRV9BUFBST1ZBTF9XT1JLRkxPVxApEhUKEUZFQVRVUkVfQVVESVRfTE9HECoSGgoWRkVBVFVSRV9FTlRFUlBSSVNFX1NTTxArEhIKDkZFQVRVUkVfVFdPX0ZBECwSIQodRkVBVFVSRV9QQVNTV09SRF9SRVNUUklDVElPTlMQLRIkCiBGRUFUVVJFX0RJU0FMTE9XX1BBU1NXT1JEX1NJR05JThAuEhgKFEZFQVRVUkVfQ1VTVE9NX1JPTEVTEC8SIQodRkVBVFVSRV9SRVFVRVNUX1JPTEVfV09SS0ZMT1cQMBIPCgtGRUFUVVJFX0pJVBAxEhgKFEZFQVRVUkVfREFUQV9NQVNLSU5HEDISHwobRkVBVFVSRV9EQVRBX0NMQVNTSUZJQ0FUSU9OEDMSEAoMRkVBVFVSRV9TQ0lNEDQSGgoWRkVBVFVSRV9ESVJFQ1RPUllfU1lOQxA1EiIKHkZFQVRVUkVfVE9LRU5fRFVSQVRJT05fQ09OVFJPTBA2EiMKH0ZFQVRVUkVfRVhURVJOQUxfU0VDUkVUX01BTkFHRVIQNxIpCiVGRUFUVVJFX1VTRVJfRU1BSUxfRE9NQUlOX1JFU1RSSUNUSU9OEDgSHgoaRkVBVFVSRV9QUk9KRUNUX01BTkFHRU1FTlQQORIiCh5GRUFUVVJFX0VOVklST05NRU5UX01BTkFHRU1FTlQQOhIcChhGRUFUVVJFX0lNX05PVElGSUNBVElPTlMQOxIeChpGRUFUVVJFX1RFUlJBRk9STV9QUk9WSURFUhA8EhsKF0ZFQVRVUkVfREFUQUJBU0VfR1JPVVBTED0SHQoZRkVBVFVSRV9FTlZJUk9OTUVOVF9USUVSUxA+EiIKHkZFQVRVUkVfREFTSEJPQVJEX0FOTk9VTkNFTUVOVBA/EiQKIEZFQVRVUkVfQVBJX0lOVEVHUkFUSU9OX0dVSURBTkNFEEASFwoTRkVBVFVSRV9DVVNUT01fTE9HTxBBEhUKEUZFQVRVUkVfV0FURVJNQVJLEEISIgoeRkVBVFVSRV9ST0FETUFQX1BSSU9SSVRJWkFUSU9OEEMSFgoSRkVBVFVSRV9DVVNUT01fTVNBEEQSHQoZRkVBVFVSRV9DT01NVU5JVFlfU1VQUE9SVBBFEhkKFUZFQVRVUkVfRU1BSUxfU1VQUE9SVBBGEiYKIkZFQVRVUkVfREVESUNBVEVEX1NVUFBPUlRfV0lUSF9TTEEQRzKvCAoTU3Vic2NyaXB0aW9uU2VydmljZRJyCg9HZXRTdWJzY3JpcHRpb24SIy5ieXRlYmFzZS52MS5HZXRTdWJzY3JpcHRpb25SZXF1ZXN0GhkuYnl0ZWJhc2UudjEuU3Vic2NyaXB0aW9uIh/aQQCA6jABgtPkkwISEhAvdjEvc3Vic2NyaXB0aW9uEpkBChJVcGRhdGVTdWJzY3JpcHRpb24SJi5ieXRlYmFzZS52MS5VcGRhdGVTdWJzY3JpcHRpb25SZXF1ZXN0GhkuYnl0ZWJhc2UudjEuU3Vic2NyaXB0aW9uIkDaQQVwYXRjaIrqMA9iYi5zZXR0aW5ncy5zZXSQ6jABgtPkkwIbOgdsaWNlbnNlMhAvdjEvc3Vic2NyaXB0aW9uEp0BCg5DcmVhdGVQdXJjaGFzZRIiLmJ5dGViYXNlLnYxLkNyZWF0ZVB1cmNoYXNlUmVxdWVzdBojLmJ5dGViYXNlLnYxLkNyZWF0ZVB1cmNoYXNlUmVzcG9uc2UiQorqMBZiYi5zdWJzY3JpcHRpb24ubWFuYWdlkOowAYLT5JMCHjoBKiIZL3YxL3N1YnNjcmlwdGlvbjpwdXJjaGFzZRKjAQoOVXBkYXRlUHVyY2hhc2USIi5ieXRlYmFzZS52MS5VcGRhdGVQdXJjaGFzZVJlcXVlc3QaIy5ieXRlYmFzZS52MS5VcGRhdGVQdXJjaGFzZVJlc3BvbnNlIkiK6jAWYmIuc3Vic2NyaXB0aW9uLm1hbmFnZZDqMAGC0+STAiQ6ASoiHy92MS9zdWJzY3JpcHRpb246dXBkYXRlUHVyY2hhc2USowEKDkNhbmNlbFB1cmNoYXNlEiIuYnl0ZWJhc2UudjEuQ2FuY2VsUHVyY2hhc2VSZXF1ZXN0GiMuYnl0ZWJhc2UudjEuQ2FuY2VsUHVyY2hhc2VSZXNwb25zZSJIiuowFmJiLnN1YnNjcmlwdGlvbi5tYW5hZ2WQ6jABgtPkkwIkOgEqIh8vdjEvc3Vic2NyaXB0aW9uOmNhbmNlbFB1cmNoYXNlEpIBCg5HZXRQYXltZW50SW5mbxIiLmJ5dGViYXNlLnYxLkdldFBheW1lbnRJbmZvUmVxdWVzdBoYLmJ5dGViYXNlLnYxLlBheW1lbnRJbmZvIkKK6jAWYmIuc3Vic2NyaXB0aW9uLm1hbmFnZZDqMAGC0+STAh4SHC92MS9zdWJzY3JpcHRpb24vcGF5bWVudEluZm8ShgEKEUxpc3RQdXJjaGFzZVBsYW5zEiUuYnl0ZWJhc2UudjEuTGlzdFB1cmNoYXNlUGxhbnNSZXF1ZXN0GiYuYnl0ZWJhc2UudjEuTGlzdFB1cmNoYXNlUGxhbnNSZXNwb25zZSIigOowAYLT5JMCGBIWL3YxL3N1YnNjcmlwdGlvbi9wbGFuc0KuAQoPY29tLmJ5dGViYXNlLnYxQhhTdWJzY3JpcHRpb25TZXJ2aWNlUHJvdG9QAVo0Z2l0aHViLmNvbS9ieXRlYmFzZS9ieXRlYmFzZS9iYWNrZW5kL2dlbmVyYXRlZC1nby92MaICA0JYWKoCC0J5dGViYXNlLlYxygILQnl0ZWJhc2VcVjHiAhdCeXRlYmFzZVxWMVxHUEJNZXRhZGF0YeoCDEJ5dGViYXNlOjpWMWIGcHJvdG8z", [file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_protobuf_timestamp, file_v1_annotation]);+ fileDesc("Ch12MS9zdWJzY3JpcHRpb25fc2VydmljZS5wcm90bxILYnl0ZWJhc2UudjEiGAoWR2V0U3Vic2NyaXB0aW9uUmVxdWVzdCInChRVcGxvYWRMaWNlbnNlUmVxdWVzdBIPCgdsaWNlbnNlGAEgASgJInsKFUNyZWF0ZVB1cmNoYXNlUmVxdWVzdBIjCgRwbGFuGAEgASgOMhUuYnl0ZWJhc2UudjEuUGxhblR5cGUSLgoIaW50ZXJ2YWwYAiABKA4yHC5ieXRlYmFzZS52MS5CaWxsaW5nSW50ZXJ2YWwSDQoFc2VhdHMYAyABKAUiOwoQUHVyY2hhc2VSZXNwb25zZRITCgtwYXltZW50X3VybBgBIAEoCRISCgpzZXNzaW9uX2lkGAIgASgJIjIKHFZlcmlmeUNoZWNrb3V0U2Vzc2lvblJlcXVlc3QSEgoKc2Vzc2lvbl9pZBgBIAEoCSIvCh1WZXJpZnlDaGVja291dFNlc3Npb25SZXNwb25zZRIOCgZzdGF0dXMYASABKAkiiQEKFVVwZGF0ZVB1cmNoYXNlUmVxdWVzdBIjCgRwbGFuGAEgASgOMhUuYnl0ZWJhc2UudjEuUGxhblR5cGUSLgoIaW50ZXJ2YWwYAiABKA4yHC5ieXRlYmFzZS52MS5CaWxsaW5nSW50ZXJ2YWwSDQoFc2VhdHMYAyABKAUSDAoEZXRhZxgEIAEoCSIXChVDYW5jZWxQdXJjaGFzZVJlcXVlc3QiFwoVR2V0UGF5bWVudEluZm9SZXF1ZXN0IpEBCgtQYXltZW50SW5mbxITCgt0b3RhbF9wcmljZRgBIAEoCRIQCghjdXJyZW5jeRgCIAEoCRIUCgxwZXJpb2Rfc3RhcnQYAyABKAkSEgoKcGVyaW9kX2VuZBgEIAEoCRITCgtpbnZvaWNlX3VybBgFIAEoCRIcChRjYW5jZWxfYXRfcGVyaW9kX2VuZBgGIAEoCCLJAQoMUHVyY2hhc2VQbGFuEiMKBHR5cGUYASABKA4yFS5ieXRlYmFzZS52MS5QbGFuVHlwZRIdChVzZWxmX3NlcnZpY2VfcHVyY2hhc2UYAiABKAgSOAoLYWRkaXRpb25hbHMYAyADKAsyIy5ieXRlYmFzZS52MS5QdXJjaGFzZVBsYW5BZGRpdGlvbmFsEjsKD2JpbGxpbmdfbWV0aG9kcxgEIAMoCzIiLmJ5dGViYXNlLnYxLlB1cmNoYXNlQmlsbGluZ01ldGhvZCLOAQoWUHVyY2hhc2VQbGFuQWRkaXRpb25hbBI2CgR0eXBlGAEgASgOMiguYnl0ZWJhc2UudjEuUHVyY2hhc2VQbGFuQWRkaXRpb25hbC5UeXBlEhIKCnVuaXRfcHJpY2UYAiABKAUSEgoKZnJlZV9jb3VudBgDIAEoBRIVCg1taW5pbXVtX2NvdW50GAQgASgFEhUKDW1heGltdW1fY291bnQYBSABKAUiJgoEVHlwZRIUChBUWVBFX1VOU1BFQ0lGSUVEEAASCAoEVVNFUhABIngKFVB1cmNoYXNlQmlsbGluZ01ldGhvZBIuCghpbnRlcnZhbBgBIAEoDjIcLmJ5dGViYXNlLnYxLkJpbGxpbmdJbnRlcnZhbBIvCghkaXNjb3VudBgCIAEoCzIdLmJ5dGViYXNlLnYxLlB1cmNoYXNlRGlzY291bnQirwEKEFB1cmNoYXNlRGlzY291bnQSMAoEdHlwZRgBIAEoDjIiLmJ5dGViYXNlLnYxLlB1cmNoYXNlRGlzY291bnQuVHlwZRINCgV2YWx1ZRgCIAEoBSJaCgRUeXBlEhQKEFRZUEVfVU5TUEVDSUZJRUQQABISCg5QRVJDRU5UQUdFX09GRhABEhMKD0ZJWEVEX01PTlRIX09GRhACEhMKD0ZJWEVEX1BSSUNFX09GRhADIhoKGExpc3RQdXJjaGFzZVBsYW5zUmVxdWVzdCJFChlMaXN0UHVyY2hhc2VQbGFuc1Jlc3BvbnNlEigKBXBsYW5zGAEgAygLMhkuYnl0ZWJhc2UudjEuUHVyY2hhc2VQbGFuIowCCgxTdWJzY3JpcHRpb24SKAoEcGxhbhgBIAEoDjIVLmJ5dGViYXNlLnYxLlBsYW5UeXBlQgPgQQMSEgoFc2VhdHMYAiABKAVCA+BBAxIWCglpbnN0YW5jZXMYAyABKAVCA+BBAxIdChBhY3RpdmVfaW5zdGFuY2VzGAQgASgFQgPgQQMSNQoMZXhwaXJlc190aW1lGAUgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEID4EEDEhUKCHRyaWFsaW5nGAYgASgIQgPgQQMSFQoIb3JnX25hbWUYByABKAlCA+BBAxIPCgJoYRgIIAEoCEID4EEDEhEKBGV0YWcYCSABKAlCA+BBAyJuCgpQbGFuQ29uZmlnEisKBXBsYW5zGAEgAygLMhwuYnl0ZWJhc2UudjEuUGxhbkxpbWl0Q29uZmlnEjMKEWluc3RhbmNlX2ZlYXR1cmVzGAIgAygOMhguYnl0ZWJhc2UudjEuUGxhbkZlYXR1cmUingEKD1BsYW5MaW1pdENvbmZpZxIjCgR0eXBlGAEgASgOMhUuYnl0ZWJhc2UudjEuUGxhblR5cGUSHgoWbWF4aW11bV9pbnN0YW5jZV9jb3VudBgCIAEoBRIaChJtYXhpbXVtX3NlYXRfY291bnQYAyABKAUSKgoIZmVhdHVyZXMYBCADKA4yGC5ieXRlYmFzZS52MS5QbGFuRmVhdHVyZSpICg9CaWxsaW5nSW50ZXJ2YWwSIAocQklMTElOR19JTlRFUlZBTF9VTlNQRUNJRklFRBAAEgkKBU1PTlRIEAESCAoEWUVBUhACKkkKCFBsYW5UeXBlEhkKFVBMQU5fVFlQRV9VTlNQRUNJRklFRBAAEggKBEZSRUUQARIICgRURUFNEAISDgoKRU5URVJQUklTRRADKuESCgtQbGFuRmVhdHVyZRIXChNGRUFUVVJFX1VOU1BFQ0lGSUVEEAASGwoXRkVBVFVSRV9EQVRBQkFTRV9DSEFOR0UQARIsCihGRUFUVVJFX0dJVF9CQVNFRF9TQ0hFTUFfVkVSU0lPTl9DT05UUk9MEAISKAokRkVBVFVSRV9ERUNMQVJBVElWRV9TQ0hFTUFfTUlHUkFUSU9OEAMSIwofRkVBVFVSRV9DT01QQVJFX0FORF9TWU5DX1NDSEVNQRAEEiAKHEZFQVRVUkVfT05MSU5FX1NDSEVNQV9DSEFOR0UQBRIlCiFGRUFUVVJFX1BSRV9ERVBMT1lNRU5UX1NRTF9SRVZJRVcQBhIwCixGRUFUVVJFX0FVVE9NQVRJQ19CQUNLVVBfQkVGT1JFX0RBVEFfQ0hBTkdFUxAHEiMKH0ZFQVRVUkVfT05FX0NMSUNLX0RBVEFfUk9MTEJBQ0sQCBIoCiRGRUFUVVJFX01VTFRJX0RBVEFCQVNFX0JBVENIX0NIQU5HRVMQCRIuCipGRUFUVVJFX1BST0dSRVNTSVZFX0VOVklST05NRU5UX0RFUExPWU1FTlQQChIiCh5GRUFUVVJFX1NDSEVEVUxFRF9ST0xMT1VUX1RJTUUQCxIeChpGRUFUVVJFX0RBVEFCQVNFX0NIQU5HRUxPRxAMEiIKHkZFQVRVUkVfU0NIRU1BX0RSSUZUX0RFVEVDVElPThANEhoKFkZFQVRVUkVfUk9MTE9VVF9QT0xJQ1kQDhIgChxGRUFUVVJFX1dFQl9CQVNFRF9TUUxfRURJVE9SEA8SIQodRkVBVFVSRV9TUUxfRURJVE9SX0FETUlOX01PREUQEBIjCh9GRUFUVVJFX05BVFVSQUxfTEFOR1VBR0VfVE9fU1FMEBESIAocRkVBVFVSRV9BSV9RVUVSWV9FWFBMQU5BVElPThASEiAKHEZFQVRVUkVfQUlfUVVFUllfU1VHR0VTVElPTlMQExIZChVGRUFUVVJFX0FVVE9fQ09NUExFVEUQFBIaChZGRUFUVVJFX1NDSEVNQV9ESUFHUkFNEBUSGQoVRkVBVFVSRV9TQ0hFTUFfRURJVE9SEBYSFwoTRkVBVFVSRV9EQVRBX0VYUE9SVBAXEh8KG0ZFQVRVUkVfREFUQV9PRkZMSU5FX0VYUE9SVBAYEhkKFUZFQVRVUkVfUVVFUllfSElTVE9SWRAZEigKJEZFQVRVUkVfU0FWRURfQU5EX1NIQVJFRF9TUUxfU0NSSVBUUxAaEhcKE0ZFQVRVUkVfQkFUQ0hfUVVFUlkQGxIpCiVGRUFUVVJFX0lOU1RBTkNFX1JFQURfT05MWV9DT05ORUNUSU9OEBwSGAoURkVBVFVSRV9RVUVSWV9QT0xJQ1kQHRIhCh1GRUFUVVJFX1JFU1RSSUNUX0NPUFlJTkdfREFUQRAeEg8KC0ZFQVRVUkVfSUFNEB8SIwofRkVBVFVSRV9JTlNUQU5DRV9TU0xfQ09OTkVDVElPThAgEi8KK0ZFQVRVUkVfSU5TVEFOQ0VfQ09OTkVDVElPTl9PVkVSX1NTSF9UVU5ORUwQIRIyCi5GRUFUVVJFX0lOU1RBTkNFX0NPTk5FQ1RJT05fSUFNX0FVVEhFTlRJQ0FUSU9OECISIQodRkVBVFVSRV9HT09HTEVfQU5EX0dJVEhVQl9TU08QIxIXChNGRUFUVVJFX1VTRVJfR1JPVVBTECQSKAokRkVBVFVSRV9ESVNBTExPV19TRUxGX1NFUlZJQ0VfU0lHTlVQECUSJQohRkVBVFVSRV9DVVNUT01fSU5TVEFOQ0VfU1lOQ19USU1FECYSLAooRkVBVFVSRV9DVVNUT01fSU5TVEFOQ0VfQ09OTkVDVElPTl9MSU1JVBAnEhsKF0ZFQVRVUkVfUklTS19BU1NFU1NNRU5UECgSHQoZRkVBVFVSRV9BUFBST1ZBTF9XT1JLRkxPVxApEhUKEUZFQVRVUkVfQVVESVRfTE9HECoSGgoWRkVBVFVSRV9FTlRFUlBSSVNFX1NTTxArEhIKDkZFQVRVUkVfVFdPX0ZBECwSIQodRkVBVFVSRV9QQVNTV09SRF9SRVNUUklDVElPTlMQLRIkCiBGRUFUVVJFX0RJU0FMTE9XX1BBU1NXT1JEX1NJR05JThAuEhgKFEZFQVRVUkVfQ1VTVE9NX1JPTEVTEC8SIQodRkVBVFVSRV9SRVFVRVNUX1JPTEVfV09SS0ZMT1cQMBIPCgtGRUFUVVJFX0pJVBAxEhgKFEZFQVRVUkVfREFUQV9NQVNLSU5HEDISHwobRkVBVFVSRV9EQVRBX0NMQVNTSUZJQ0FUSU9OEDMSEAoMRkVBVFVSRV9TQ0lNEDQSGgoWRkVBVFVSRV9ESVJFQ1RPUllfU1lOQxA1EiIKHkZFQVRVUkVfVE9LRU5fRFVSQVRJT05fQ09OVFJPTBA2EiMKH0ZFQVRVUkVfRVhURVJOQUxfU0VDUkVUX01BTkFHRVIQNxIpCiVGRUFUVVJFX1VTRVJfRU1BSUxfRE9NQUlOX1JFU1RSSUNUSU9OEDgSHgoaRkVBVFVSRV9QUk9KRUNUX01BTkFHRU1FTlQQORIiCh5GRUFUVVJFX0VOVklST05NRU5UX01BTkFHRU1FTlQQOhIcChhGRUFUVVJFX0lNX05PVElGSUNBVElPTlMQOxIeChpGRUFUVVJFX1RFUlJBRk9STV9QUk9WSURFUhA8EhsKF0ZFQVRVUkVfREFUQUJBU0VfR1JPVVBTED0SHQoZRkVBVFVSRV9FTlZJUk9OTUVOVF9USUVSUxA+EiIKHkZFQVRVUkVfREFTSEJPQVJEX0FOTk9VTkNFTUVOVBA/EiQKIEZFQVRVUkVfQVBJX0lOVEVHUkFUSU9OX0dVSURBTkNFEEASFwoTRkVBVFVSRV9DVVNUT01fTE9HTxBBEhUKEUZFQVRVUkVfV0FURVJNQVJLEEISIgoeRkVBVFVSRV9ST0FETUFQX1BSSU9SSVRJWkFUSU9OEEMSFgoSRkVBVFVSRV9DVVNUT01fTVNBEEQSHQoZRkVBVFVSRV9DT01NVU5JVFlfU1VQUE9SVBBFEhkKFUZFQVRVUkVfRU1BSUxfU1VQUE9SVBBGEiYKIkZFQVRVUkVfREVESUNBVEVEX1NVUFBPUlRfV0lUSF9TTEEQRzLSCQoTU3Vic2NyaXB0aW9uU2VydmljZRJuCg9HZXRTdWJzY3JpcHRpb24SIy5ieXRlYmFzZS52MS5HZXRTdWJzY3JpcHRpb25SZXF1ZXN0GhkuYnl0ZWJhc2UudjEuU3Vic2NyaXB0aW9uIhvaQQCC0+STAhISEC92MS9zdWJzY3JpcHRpb24SkAEKDVVwbG9hZExpY2Vuc2USIS5ieXRlYmFzZS52MS5VcGxvYWRMaWNlbnNlUmVxdWVzdBoZLmJ5dGViYXNlLnYxLlN1YnNjcmlwdGlvbiJBiuowFmJiLnN1YnNjcmlwdGlvbi5tYW5hZ2WQ6jABgtPkkwIdOgEqMhgvdjEvc3Vic2NyaXB0aW9uL2xpY2Vuc2USlwEKDkNyZWF0ZVB1cmNoYXNlEiIuYnl0ZWJhc2UudjEuQ3JlYXRlUHVyY2hhc2VSZXF1ZXN0Gh0uYnl0ZWJhc2UudjEuUHVyY2hhc2VSZXNwb25zZSJCiuowFmJiLnN1YnNjcmlwdGlvbi5tYW5hZ2WQ6jABgtPkkwIeOgEqIhkvdjEvc3Vic2NyaXB0aW9uOnB1cmNoYXNlEp0BCg5VcGRhdGVQdXJjaGFzZRIiLmJ5dGViYXNlLnYxLlVwZGF0ZVB1cmNoYXNlUmVxdWVzdBodLmJ5dGViYXNlLnYxLlB1cmNoYXNlUmVzcG9uc2UiSIrqMBZiYi5zdWJzY3JpcHRpb24ubWFuYWdlkOowAYLT5JMCJDoBKiIfL3YxL3N1YnNjcmlwdGlvbjp1cGRhdGVQdXJjaGFzZRKdAQoOQ2FuY2VsUHVyY2hhc2USIi5ieXRlYmFzZS52MS5DYW5jZWxQdXJjaGFzZVJlcXVlc3QaHS5ieXRlYmFzZS52MS5QdXJjaGFzZVJlc3BvbnNlIkiK6jAWYmIuc3Vic2NyaXB0aW9uLm1hbmFnZZDqMAGC0+STAiQ6ASoiHy92MS9zdWJzY3JpcHRpb246Y2FuY2VsUHVyY2hhc2USkgEKDkdldFBheW1lbnRJbmZvEiIuYnl0ZWJhc2UudjEuR2V0UGF5bWVudEluZm9SZXF1ZXN0GhguYnl0ZWJhc2UudjEuUGF5bWVudEluZm8iQorqMBZiYi5zdWJzY3JpcHRpb24ubWFuYWdlkOowAYLT5JMCHhIcL3YxL3N1YnNjcmlwdGlvbi9wYXltZW50SW5mbxLDAQoVVmVyaWZ5Q2hlY2tvdXRTZXNzaW9uEikuYnl0ZWJhc2UudjEuVmVyaWZ5Q2hlY2tvdXRTZXNzaW9uUmVxdWVzdBoqLmJ5dGViYXNlLnYxLlZlcmlmeUNoZWNrb3V0U2Vzc2lvblJlc3BvbnNlIlOK6jAWYmIuc3Vic2NyaXB0aW9uLm1hbmFnZZDqMAGC0+STAi8SLS92MS9zdWJzY3JpcHRpb24vY2hlY2tvdXRTZXNzaW9uL3tzZXNzaW9uX2lkfRKCAQoRTGlzdFB1cmNoYXNlUGxhbnMSJS5ieXRlYmFzZS52MS5MaXN0UHVyY2hhc2VQbGFuc1JlcXVlc3QaJi5ieXRlYmFzZS52MS5MaXN0UHVyY2hhc2VQbGFuc1Jlc3BvbnNlIh6C0+STAhgSFi92MS9zdWJzY3JpcHRpb24vcGxhbnNCrgEKD2NvbS5ieXRlYmFzZS52MUIYU3Vic2NyaXB0aW9uU2VydmljZVByb3RvUAFaNGdpdGh1Yi5jb20vYnl0ZWJhc2UvYnl0ZWJhc2UvYmFja2VuZC9nZW5lcmF0ZWQtZ28vdjGiAgNCWFiqAgtCeXRlYmFzZS5WMcoCC0J5dGViYXNlXFYx4gIXQnl0ZWJhc2VcVjFcR1BCTWV0YWRhdGHqAgxCeXRlYmFzZTo6VjFiBnByb3RvMw", [file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_protobuf_timestamp, file_v1_annotation]);/*** Describes the message bytebase.v1.GetSubscriptionRequest.@@ -23,10 +23,10 @@ export const GetSubscriptionRequestSchema = /*@__PURE__*/messageDesc(file_v1_subscription_service, 0);/**- * Describes the message bytebase.v1.UpdateSubscriptionRequest.- * Use `create(UpdateSubscriptionRequestSchema)` to create a new message.+ * Describes the message bytebase.v1.UploadLicenseRequest.+ * Use `create(UploadLicenseRequestSchema)` to create a new message.*/-export const UpdateSubscriptionRequestSchema = /*@__PURE__*/+export const UploadLicenseRequestSchema = /*@__PURE__*/messageDesc(file_v1_subscription_service, 1);/**@@ -37,38 +37,38 @@ export const CreatePurchaseRequestSchema = /*@__PURE__*/messageDesc(file_v1_subscription_service, 2);/**- * Describes the message bytebase.v1.CreatePurchaseResponse.- * Use `create(CreatePurchaseResponseSchema)` to create a new message.+ * Describes the message bytebase.v1.PurchaseResponse.+ * Use `create(PurchaseResponseSchema)` to create a new message.*/-export const CreatePurchaseResponseSchema = /*@__PURE__*/+export const PurchaseResponseSchema = /*@__PURE__*/messageDesc(file_v1_subscription_service, 3);/**- * Describes the message bytebase.v1.UpdatePurchaseRequest.- * Use `create(UpdatePurchaseRequestSchema)` to create a new message.+ * Describes the message bytebase.v1.VerifyCheckoutSessionRequest.+ * Use `create(VerifyCheckoutSessionRequestSchema)` to create a new message.*/-export const UpdatePurchaseRequestSchema = /*@__PURE__*/+export const VerifyCheckoutSessionRequestSchema = /*@__PURE__*/messageDesc(file_v1_subscription_service, 4);/**- * Describes the message bytebase.v1.UpdatePurchaseResponse.- * Use `create(UpdatePurchaseResponseSchema)` to create a new message.+ * Describes the message bytebase.v1.VerifyCheckoutSessionResponse.+ * Use `create(VerifyCheckoutSessionResponseSchema)` to create a new message.*/-export const UpdatePurchaseResponseSchema = /*@__PURE__*/+export const VerifyCheckoutSessionResponseSchema = /*@__PURE__*/messageDesc(file_v1_subscription_service, 5);/**- * Describes the message bytebase.v1.CancelPurchaseRequest.- * Use `create(CancelPurchaseRequestSchema)` to create a new message.+ * Describes the message bytebase.v1.UpdatePurchaseRequest.+ * Use `create(UpdatePurchaseRequestSchema)` to create a new message.*/-export const CancelPurchaseRequestSchema = /*@__PURE__*/+export const UpdatePurchaseRequestSchema = /*@__PURE__*/messageDesc(file_v1_subscription_service, 6);/**- * Describes the message bytebase.v1.CancelPurchaseResponse.- * Use `create(CancelPurchaseResponseSchema)` to create a new message.+ * Describes the message bytebase.v1.CancelPurchaseRequest.+ * Use `create(CancelPurchaseRequestSchema)` to create a new message.*/-export const CancelPurchaseResponseSchema = /*@__PURE__*/+export const CancelPurchaseRequestSchema = /*@__PURE__*/messageDesc(file_v1_subscription_service, 7);/**@@ -125,6 +125,18 @@ export const PurchaseBillingMethodSchema = /*@__PURE__*/export const PurchaseDiscountSchema = /*@__PURE__*/messageDesc(file_v1_subscription_service, 13);+/**+ * Describes the enum bytebase.v1.PurchaseDiscount.Type.+ */+export const PurchaseDiscount_TypeSchema = /*@__PURE__*/+ enumDesc(file_v1_subscription_service, 13, 0);++/**+ * @generated from enum bytebase.v1.PurchaseDiscount.Type+ */+export const PurchaseDiscount_Type = /*@__PURE__*/+ tsEnum(PurchaseDiscount_TypeSchema);+/*** Describes the message bytebase.v1.ListPurchasePlansRequest.* Use `create(ListPurchasePlansRequestSchema)` to create a new message.diff --git a/frontend/src/views/SettingWorkspaceSubscription.vue b/frontend/src/views/SettingWorkspaceSubscription.vuedeleted file mode 100644index 63c1be8203..0000000000--- a/frontend/src/views/SettingWorkspaceSubscription.vue+++ /dev/null@@ -1,252 +0,0 @@-<template>- <div class="w-full px-4 py-4 mx-auto">- <div- class="w-full grid grid-cols-2 gap-6 lg:grid-cols-3 3xl:grid-cols-4 my-4"- >- <div class="flex flex-col text-left">- <div class="flex text-main">- {{ $t("subscription.current") }}- <span- v-if="isExpired"- class="ml-2 inline-flex items-center px-3 py-0.5 rounded-full text-base font-sm bg-red-100 text-red-800 h-6"- >- {{ $t("subscription.expired") }}- </span>- <span- v-else-if="isTrialing"- class="ml-2 inline-flex items-center px-3 py-0.5 rounded-full text-base font-sm bg-indigo-100 text-indigo-800 h-6"- >- {{ $t("subscription.trialing") }}- </span>- </div>- <div class="text-indigo-600 mt-1 text-3xl lg:text-4xl">- {{ currentPlan }}- </div>- </div>- <div v-if="!subscriptionStore.isFreePlan" class="flex flex-col text-left">- <div class="text-main">- {{ $t("subscription.expires-at") }}- </div>- <dd class="mt-1 text-3xl lg:text-4xl">{{ expireAt || "N/A" }}</dd>- </div>- <div- v-if="subscriptionStore.showTrial && allowEdit"- class="flex flex-col text-left"- >- <div class="text-main">- {{ $t("subscription.try-for-free") }}- </div>- <div class="mt-1">- <RequireEnterpriseButton type="primary" size="large">- {{- $t("subscription.enterprise-free-trial", {- days: subscriptionStore.trialingDays,- })- }}- </RequireEnterpriseButton>- </div>- </div>- <div- v-if="- subscriptionStore.isTrialing &&- subscriptionStore.currentPlan == PlanType.ENTERPRISE- "- class="flex flex-col text-left"- >- <div class="text-main">- {{ $t("subscription.inquire-enterprise-plan") }}- </div>- <div class="mt-1 ml-auto">- <RequireEnterpriseButton type="primary" size="large">- {{ $t("subscription.contact-us") }}- </RequireEnterpriseButton>- </div>- </div>- <WorkspaceInstanceLicenseStats v-if="allowManageInstanceLicenses" />- <div class="flex flex-col text-left">- <div class="text-main">- {{ $t("subscription.instance-assignment.used-and-total-user") }}- </div>- <div class="mt-1 text-4xl flex items-center gap-2">- {{ activeUserCountWithoutBot }}- <span class="font-mono text-gray-500">/</span>- {{ userLimit }}- </div>- </div>- </div>- <NDivider />- <div>- <label class="flex items-center gap-x-2">- <span class="text-main">- {{ $t("settings.general.workspace.id") }}- </span>- </label>- <div class="mb-3 text-sm text-gray-400">- {{ $t("settings.general.workspace.id-description") }}- </div>- <div class="mb-4 flex items-center gap-x-2">- <NInput- ref="workspaceIdField"- class="w-full"- readonly- :value="workspaceId"- @click="selectWorkspaceId"- />- <CopyButton- quaternary- :text="false"- :size="'small'"- :content="workspaceId"- />- </div>- </div>- <!-- TODO(ed): disable upload license when we support the purchase in the SaaS -->- <div- v-if="- subscriptionStore.isSelfHostLicense- "- class="w-full mt-4 flex flex-col"- >- <label class="flex items-center gap-x-2">- <span class="text-main">- {{ $t("subscription.upload-license") }}- </span>- </label>- <div class="mb-3 text-sm text-gray-400">- {{ $t("subscription.description") }}- {{ $t("subscription.plan-compare") }}- <LearnMoreLink url="https://www.bytebase.com/pricing?source=console" />- <div class="ml-1 inline-block">- <RequireEnterpriseButton- v-if="subscriptionStore.showTrial && allowEdit"- text- type="primary"- size="small"- >- {{ $t("subscription.plan.try") }}- </RequireEnterpriseButton>- </div>- </div>-- <NInput- v-model:value="state.license"- type="textarea"- :disabled="!allowEdit"- :placeholder="$t('common.sensitive-placeholder')"- />- <div class="ml-auto mt-3">- <NButton- type="primary"- class="capitalize"- :disabled="disabled || !allowEdit"- @click="uploadLicense"- >- {{ $t("subscription.upload-license") }}- </NButton>- </div>- </div>- </div>-</template>--<script lang="ts" setup>-import { NButton, NDivider, NInput } from "naive-ui";-import { storeToRefs } from "pinia";-import { computed, reactive, ref } from "vue";-import { useI18n } from "vue-i18n";-import LearnMoreLink from "@/components/LearnMoreLink.vue";-import RequireEnterpriseButton from "@/components/RequireEnterpriseButton.vue";-import { CopyButton } from "@/components/v2";-import WorkspaceInstanceLicenseStats from "@/components/WorkspaceInstanceLicenseStats.vue";-import {- getWorkspaceId,- pushNotification,- useActuatorV1Store,- useSubscriptionV1Store,-} from "@/store";-import { PlanType } from "@/types/proto-es/v1/subscription_service_pb";-import { hasWorkspacePermissionV2 } from "@/utils";--interface LocalState {- loading: boolean;- license: string;-}--const props = defineProps<{- allowEdit: boolean;-}>();--const { t } = useI18n();-const subscriptionStore = useSubscriptionV1Store();-const actuatorStore = useActuatorV1Store();--const state = reactive<LocalState>({- loading: false,- license: "",-});--const disabled = computed((): boolean => {- return state.loading || !state.license;-});--const activeUserCountWithoutBot = computed(() => actuatorStore.activeUserCount);--const userLimit = computed((): string => {- if (subscriptionStore.userCountLimit === Number.MAX_VALUE) {- return t("common.unlimited");- }- return `${subscriptionStore.userCountLimit}`;-});--const workspaceIdField = ref<HTMLInputElement | null>(null);--const workspaceId = computed(() => {- return getWorkspaceId(actuatorStore.workspaceResourceName);-});--const selectWorkspaceId = () => {- workspaceIdField.value?.select();-};--const uploadLicense = async () => {- if (disabled.value) return;- state.loading = true;-- try {- await subscriptionStore.patchSubscription(state.license);- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("subscription.update.success.title"),- description: t("subscription.update.success.description"),- });- } catch {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("subscription.update.failure.title"),- description: t("subscription.update.failure.description"),- });- } finally {- state.loading = false;- state.license = "";- }-};--const { expireAt, isTrialing, isExpired } = storeToRefs(subscriptionStore);--const allowManageInstanceLicenses = computed(() => {- return props.allowEdit && hasWorkspacePermissionV2("bb.instances.list");-});--const currentPlan = computed((): string => {- const plan = subscriptionStore.currentPlan;- switch (plan) {- case PlanType.TEAM:- return t("subscription.plan.team.title");- case PlanType.ENTERPRISE:- return t("subscription.plan.enterprise.title");- default:- return t("subscription.plan.free.title");- }-});-</script>diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yamlindex d4e7638fc6..a62a192fda 100644--- a/proto/gen/grpc-doc/openapi.yaml+++ b/proto/gen/grpc-doc/openapi.yaml@@ -14105,7 +14105,6 @@ paths:GetSubscription returns the current subscription.If there is no license, we will return a free plan subscription without expiration time.If there is expired license, we will return a free plan subscription with the expiration time of the expired license.- Permissions required: NoneoperationId: SubscriptionService_GetSubscriptionresponses:"200":@@ -14114,32 +14113,40 @@ paths:application/json:schema:$ref: '#/components/schemas/bytebase.v1.Subscription'- patch:+ /v1/subscription/checkoutSession/{session_id}:+ get:tags:- SubscriptionService- summary: UpdateSubscription- description: |-- Updates the enterprise license subscription (self-hosted only).- Permissions required: bb.settings.set- operationId: SubscriptionService_UpdateSubscription+ summary: VerifyCheckoutSession+ description: VerifyCheckoutSession verifies a Stripe Checkout Session status (SaaS only).+ operationId: SubscriptionService_VerifyCheckoutSessionparameters:- - name: allowMissing- in: query- description: |-- If set to true, and the subscription is not found, a new subscription will be created.- In this situation, `update_mask` is ignored.+ - name: session_id+ in: path+ required: trueschema:- type: boolean- title: allow_missing- description: |-- If set to true, and the subscription is not found, a new subscription will be created.- In this situation, `update_mask` is ignored.+ type: string+ title: session_id+ responses:+ "200":+ description: Success+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/bytebase.v1.VerifyCheckoutSessionResponse'+ /v1/subscription/license:+ patch:+ tags:+ - SubscriptionService+ summary: UploadLicense+ description: Uploads an enterprise license (self-hosted only).+ operationId: SubscriptionService_UploadLicenserequestBody:content:application/json:schema:- type: string- title: license+ $ref: '#/components/schemas/bytebase.v1.UploadLicenseRequest'+ required: trueresponses:"200":description: Success@@ -14194,7 +14201,7 @@ paths:content:application/json:schema:- $ref: '#/components/schemas/bytebase.v1.CancelPurchaseResponse'+ $ref: '#/components/schemas/bytebase.v1.PurchaseResponse'/v1/subscription:purchase:post:tags:@@ -14216,7 +14223,7 @@ paths:content:application/json:schema:- $ref: '#/components/schemas/bytebase.v1.CreatePurchaseResponse'+ $ref: '#/components/schemas/bytebase.v1.PurchaseResponse'/v1/subscription:updatePurchase:post:tags:@@ -14238,7 +14245,7 @@ paths:content:application/json:schema:- $ref: '#/components/schemas/bytebase.v1.UpdatePurchaseResponse'+ $ref: '#/components/schemas/bytebase.v1.PurchaseResponse'/v1/users:get:tags:@@ -17901,10 +17908,6 @@ components:type: objecttitle: CancelPurchaseRequestadditionalProperties: false- bytebase.v1.CancelPurchaseResponse:- type: object- title: CancelPurchaseResponse- additionalProperties: falsebytebase.v1.Changelog:type: objectproperties:@@ -18442,15 +18445,6 @@ components:format: int32title: CreatePurchaseRequestadditionalProperties: false- bytebase.v1.CreatePurchaseResponse:- type: object- properties:- paymentUrl:- type: string- title: payment_url- description: Stripe Checkout URL for the user to complete payment.- title: CreatePurchaseResponse- additionalProperties: falsebytebase.v1.CreateReleaseRequest:type: objectproperties:@@ -23522,6 +23516,10 @@ components:type: stringtitle: invoice_urldescription: Stripe Billing Portal URL for invoice management.+ cancelAtPeriodEnd:+ type: boolean+ title: cancel_at_period_end+ description: Whether the subscription is scheduled to cancel at the end of the current billing period.title: PaymentInfoadditionalProperties: falsebytebase.v1.PermissionDeniedDetail:@@ -24349,14 +24347,23 @@ components:bytebase.v1.PurchaseDiscount:type: objectproperties:- description:- type: string- title: description- promotionCode:- type: string- title: promotion_code+ type:+ title: type+ $ref: '#/components/schemas/bytebase.v1.PurchaseDiscount.Type'+ value:+ type: integer+ title: value+ format: int32title: PurchaseDiscountadditionalProperties: false+ bytebase.v1.PurchaseDiscount.Type:+ type: string+ title: Type+ enum:+ - TYPE_UNSPECIFIED+ - PERCENTAGE_OFF+ - FIXED_MONTH_OFF+ - FIXED_PRICE_OFFbytebase.v1.PurchasePlan:type: objectproperties:@@ -24410,6 +24417,21 @@ components:enum:- TYPE_UNSPECIFIED- USER+ bytebase.v1.PurchaseResponse:+ type: object+ properties:+ paymentUrl:+ type: string+ title: payment_url+ description: |-+ If set, redirect to this Stripe Checkout URL.+ If empty, the update was applied directly using the existing payment method.+ sessionId:+ type: string+ title: session_id+ description: Stripe Checkout Session ID. Used to verify the session after redirect.+ title: PurchaseResponse+ additionalProperties: falsebytebase.v1.QueryDataPolicy:type: objectproperties:@@ -26779,6 +26801,11 @@ components:title: hadescription: Whether high availability (multiple replicas) is enabled.readOnly: true+ etag:+ type: string+ title: etag+ description: Etag for optimistic concurrency on purchase updates. Only set in SaaS mode.+ readOnly: truetitle: SubscriptionadditionalProperties: falsebytebase.v1.SwitchWorkspaceRequest:@@ -28493,17 +28520,6 @@ components:title: etagtitle: UpdatePurchaseRequestadditionalProperties: false- bytebase.v1.UpdatePurchaseResponse:- type: object- properties:- paymentUrl:- type: string- title: payment_url- description: |-- If set, redirect to this Stripe Checkout URL.- If empty, the update was applied directly using the existing payment method.- title: UpdatePurchaseResponse- additionalProperties: falsebytebase.v1.UpdateReleaseRequest:type: objectproperties:@@ -28610,20 +28626,6 @@ components:- settingadditionalProperties: falsedescription: The request message for updating or creating a setting.- bytebase.v1.UpdateSubscriptionRequest:- type: object- properties:- license:- type: string- title: license- allowMissing:- type: boolean- title: allow_missing- description: |-- If set to true, and the subscription is not found, a new subscription will be created.- In this situation, `update_mask` is ignored.- title: UpdateSubscriptionRequest- additionalProperties: falsebytebase.v1.UpdateUserRequest:type: objectproperties:@@ -28777,6 +28779,14 @@ components:required:- workspaceadditionalProperties: false+ bytebase.v1.UploadLicenseRequest:+ type: object+ properties:+ license:+ type: string+ title: license+ title: UploadLicenseRequest+ additionalProperties: falsebytebase.v1.User:type: objectproperties:@@ -28883,6 +28893,23 @@ components:- BITBUCKET- AZURE_DEVOPSdescription: Version control system type.+ bytebase.v1.VerifyCheckoutSessionRequest:+ type: object+ properties:+ sessionId:+ type: string+ title: session_id+ title: VerifyCheckoutSessionRequest+ additionalProperties: false+ bytebase.v1.VerifyCheckoutSessionResponse:+ type: object+ properties:+ status:+ type: string+ title: status+ description: 'Stripe Checkout Session status: "complete", "expired", or "open".'+ title: VerifyCheckoutSessionResponse+ additionalProperties: falsebytebase.v1.ViewMetadata:type: objectproperties:diff --git a/proto/gen/grpc-doc/store/README.md b/proto/gen/grpc-doc/store/README.mdindex 4292fa41b1..25fda6dc72 100644--- a/proto/gen/grpc-doc/store/README.md+++ b/proto/gen/grpc-doc/store/README.md@@ -4773,10 +4773,9 @@ Serialized as JSONB in the subscription table's payload column.| Name | Number | Description || ---- | ------ | ----------- || STATUS_UNSPECIFIED | 0 | |-| PENDING | 1 | |-| ACTIVE | 2 | |-| PAUSED | 3 | |-| CANCELED | 4 | |+| ACTIVE | 1 | |+| PAUSED | 2 | |+| CANCELED | 3 | |diff --git a/proto/gen/grpc-doc/store/index.html b/proto/gen/grpc-doc/store/index.htmlindex 66e5878f71..c1f1ffc555 100644--- a/proto/gen/grpc-doc/store/index.html+++ b/proto/gen/grpc-doc/store/index.html@@ -13021,27 +13021,21 @@ Default to this mode.</p></td><td><p></p></td></tr>- <tr>- <td>PENDING</td>- <td>1</td>- <td><p></p></td>- </tr>-<tr><td>ACTIVE</td>- <td>2</td>+ <td>1</td><td><p></p></td></tr><tr><td>PAUSED</td>- <td>3</td>+ <td>2</td><td><p></p></td></tr><tr><td>CANCELED</td>- <td>4</td>+ <td>3</td><td><p></p></td></tr>diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.mdindex c455d9a3e4..6d7727f071 100644--- a/proto/gen/grpc-doc/v1/README.md+++ b/proto/gen/grpc-doc/v1/README.md@@ -669,9 +669,7 @@- [v1/subscription_service.proto](#v1_subscription_service-proto)- [CancelPurchaseRequest](#bytebase-v1-CancelPurchaseRequest)- - [CancelPurchaseResponse](#bytebase-v1-CancelPurchaseResponse)- [CreatePurchaseRequest](#bytebase-v1-CreatePurchaseRequest)- - [CreatePurchaseResponse](#bytebase-v1-CreatePurchaseResponse)- [GetPaymentInfoRequest](#bytebase-v1-GetPaymentInfoRequest)- [GetSubscriptionRequest](#bytebase-v1-GetSubscriptionRequest)- [ListPurchasePlansRequest](#bytebase-v1-ListPurchasePlansRequest)@@ -683,14 +681,17 @@- [PurchaseDiscount](#bytebase-v1-PurchaseDiscount)- [PurchasePlan](#bytebase-v1-PurchasePlan)- [PurchasePlanAdditional](#bytebase-v1-PurchasePlanAdditional)+ - [PurchaseResponse](#bytebase-v1-PurchaseResponse)- [Subscription](#bytebase-v1-Subscription)- [UpdatePurchaseRequest](#bytebase-v1-UpdatePurchaseRequest)- - [UpdatePurchaseResponse](#bytebase-v1-UpdatePurchaseResponse)- - [UpdateSubscriptionRequest](#bytebase-v1-UpdateSubscriptionRequest)+ - [UploadLicenseRequest](#bytebase-v1-UploadLicenseRequest)+ - [VerifyCheckoutSessionRequest](#bytebase-v1-VerifyCheckoutSessionRequest)+ - [VerifyCheckoutSessionResponse](#bytebase-v1-VerifyCheckoutSessionResponse)- [BillingInterval](#bytebase-v1-BillingInterval)- [PlanFeature](#bytebase-v1-PlanFeature)- [PlanType](#bytebase-v1-PlanType)+ - [PurchaseDiscount.Type](#bytebase-v1-PurchaseDiscount-Type)- [PurchasePlanAdditional.Type](#bytebase-v1-PurchasePlanAdditional-Type)- [SubscriptionService](#bytebase-v1-SubscriptionService)@@ -10832,16 +10833,6 @@ SheetService manages SQL scripts and saved queries.-<a name="bytebase-v1-CancelPurchaseResponse"></a>--### CancelPurchaseResponse-------<a name="bytebase-v1-CreatePurchaseRequest"></a>### CreatePurchaseRequest@@ -10859,21 +10850,6 @@ SheetService manages SQL scripts and saved queries.-<a name="bytebase-v1-CreatePurchaseResponse"></a>--### CreatePurchaseResponse----| Field | Type | Label | Description |-| ----- | ---- | ----- | ----------- |-| payment_url | [string](#string) | | Stripe Checkout URL for the user to complete payment. |------<a name="bytebase-v1-GetPaymentInfoRequest"></a>### GetPaymentInfoRequest@@ -10932,6 +10908,7 @@ SheetService manages SQL scripts and saved queries.| period_start | [string](#string) | | || period_end | [string](#string) | | || invoice_url | [string](#string) | | Stripe Billing Portal URL for invoice management. |+| cancel_at_period_end | [bool](#bool) | | Whether the subscription is scheduled to cancel at the end of the current billing period. |@@ -10996,8 +10973,8 @@ PlanLimitConfig represents a single plan's configuration| Field | Type | Label | Description || ----- | ---- | ----- | ----------- |-| description | [string](#string) | | |-| promotion_code | [string](#string) | | |+| type | [PurchaseDiscount.Type](#bytebase-v1-PurchaseDiscount-Type) | | |+| value | [int32](#int32) | | |@@ -11041,6 +11018,22 @@ PlanLimitConfig represents a single plan's configuration+<a name="bytebase-v1-PurchaseResponse"></a>++### PurchaseResponse++++| Field | Type | Label | Description |+| ----- | ---- | ----- | ----------- |+| payment_url | [string](#string) | | If set, redirect to this Stripe Checkout URL. If empty, the update was applied directly using the existing payment method. |+| session_id | [string](#string) | | Stripe Checkout Session ID. Used to verify the session after redirect. |++++++<a name="bytebase-v1-Subscription"></a>### Subscription@@ -11057,6 +11050,7 @@ PlanLimitConfig represents a single plan's configuration| trialing | [bool](#bool) | | || org_name | [string](#string) | | || ha | [bool](#bool) | | Whether high availability (multiple replicas) is enabled. |+| etag | [string](#string) | | Etag for optimistic concurrency on purchase updates. Only set in SaaS mode. |@@ -11081,31 +11075,45 @@ PlanLimitConfig represents a single plan's configuration-<a name="bytebase-v1-UpdatePurchaseResponse"></a>+<a name="bytebase-v1-UploadLicenseRequest"></a>-### UpdatePurchaseResponse+### UploadLicenseRequest| Field | Type | Label | Description || ----- | ---- | ----- | ----------- |-| payment_url | [string](#string) | | If set, redirect to this Stripe Checkout URL. If empty, the update was applied directly using the existing payment method. |+| license | [string](#string) | | |-<a name="bytebase-v1-UpdateSubscriptionRequest"></a>+<a name="bytebase-v1-VerifyCheckoutSessionRequest"></a>-### UpdateSubscriptionRequest+### VerifyCheckoutSessionRequest| Field | Type | Label | Description || ----- | ---- | ----- | ----------- |-| license | [string](#string) | | |-| allow_missing | [bool](#bool) | | If set to true, and the subscription is not found, a new subscription will be created. In this situation, `update_mask` is ignored. |+| session_id | [string](#string) | | |+++++++<a name="bytebase-v1-VerifyCheckoutSessionResponse"></a>++### VerifyCheckoutSessionResponse++++| Field | Type | Label | Description |+| ----- | ---- | ----- | ----------- |+| status | [string](#string) | | Stripe Checkout Session status: "complete", "expired", or "open". |@@ -11223,6 +11231,20 @@ PlanFeature represents the available features in Bytebase+<a name="bytebase-v1-PurchaseDiscount-Type"></a>++### PurchaseDiscount.Type+++| Name | Number | Description |+| ---- | ------ | ----------- |+| TYPE_UNSPECIFIED | 0 | |+| PERCENTAGE_OFF | 1 | |+| FIXED_MONTH_OFF | 2 | |+| FIXED_PRICE_OFF | 3 | |+++<a name="bytebase-v1-PurchasePlanAdditional-Type"></a>### PurchasePlanAdditional.Type@@ -11246,12 +11268,13 @@ SubscriptionService manages enterprise subscriptions and licensing.| Method Name | Request Type | Response Type | Description || ----------- | ------------ | ------------- | ------------|-| GetSubscription | [GetSubscriptionRequest](#bytebase-v1-GetSubscriptionRequest) | [Subscription](#bytebase-v1-Subscription) | GetSubscription returns the current subscription. If there is no license, we will return a free plan subscription without expiration time. If there is expired license, we will return a free plan subscription with the expiration time of the expired license. Permissions required: None |-| UpdateSubscription | [UpdateSubscriptionRequest](#bytebase-v1-UpdateSubscriptionRequest) | [Subscription](#bytebase-v1-Subscription) | Updates the enterprise license subscription (self-hosted only). Permissions required: bb.settings.set |-| CreatePurchase | [CreatePurchaseRequest](#bytebase-v1-CreatePurchaseRequest) | [CreatePurchaseResponse](#bytebase-v1-CreatePurchaseResponse) | CreatePurchase creates a new subscription purchase (SaaS only). Returns a Stripe Checkout URL for the user to complete payment. |-| UpdatePurchase | [UpdatePurchaseRequest](#bytebase-v1-UpdatePurchaseRequest) | [UpdatePurchaseResponse](#bytebase-v1-UpdatePurchaseResponse) | UpdatePurchase updates an existing subscription (SaaS only). May return a Stripe Checkout URL if payment method change is needed. |-| CancelPurchase | [CancelPurchaseRequest](#bytebase-v1-CancelPurchaseRequest) | [CancelPurchaseResponse](#bytebase-v1-CancelPurchaseResponse) | CancelPurchase cancels an active subscription (SaaS only). |+| GetSubscription | [GetSubscriptionRequest](#bytebase-v1-GetSubscriptionRequest) | [Subscription](#bytebase-v1-Subscription) | GetSubscription returns the current subscription. If there is no license, we will return a free plan subscription without expiration time. If there is expired license, we will return a free plan subscription with the expiration time of the expired license. |+| UploadLicense | [UploadLicenseRequest](#bytebase-v1-UploadLicenseRequest) | [Subscription](#bytebase-v1-Subscription) | Uploads an enterprise license (self-hosted only). |+| CreatePurchase | [CreatePurchaseRequest](#bytebase-v1-CreatePurchaseRequest) | [PurchaseResponse](#bytebase-v1-PurchaseResponse) | CreatePurchase creates a new subscription purchase (SaaS only). Returns a Stripe Checkout URL for the user to complete payment. |+| UpdatePurchase | [UpdatePurchaseRequest](#bytebase-v1-UpdatePurchaseRequest) | [PurchaseResponse](#bytebase-v1-PurchaseResponse) | UpdatePurchase updates an existing subscription (SaaS only). May return a Stripe Checkout URL if payment method change is needed. |+| CancelPurchase | [CancelPurchaseRequest](#bytebase-v1-CancelPurchaseRequest) | [PurchaseResponse](#bytebase-v1-PurchaseResponse) | CancelPurchase cancels an active subscription (SaaS only). || GetPaymentInfo | [GetPaymentInfoRequest](#bytebase-v1-GetPaymentInfoRequest) | [PaymentInfo](#bytebase-v1-PaymentInfo) | GetPaymentInfo returns payment details for the current subscription (SaaS only). |+| VerifyCheckoutSession | [VerifyCheckoutSessionRequest](#bytebase-v1-VerifyCheckoutSessionRequest) | [VerifyCheckoutSessionResponse](#bytebase-v1-VerifyCheckoutSessionResponse) | VerifyCheckoutSession verifies a Stripe Checkout Session status (SaaS only). || ListPurchasePlans | [ListPurchasePlansRequest](#bytebase-v1-ListPurchasePlansRequest) | [ListPurchasePlansResponse](#bytebase-v1-ListPurchasePlansResponse) | ListPurchasePlans returns available plans for self-service purchase. |diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.htmlindex 6753aeff9f..7fe45a92bd 100644--- a/proto/gen/grpc-doc/v1/index.html+++ b/proto/gen/grpc-doc/v1/index.html@@ -2728,18 +2728,10 @@<a href="#bytebase.v1.CancelPurchaseRequest"><span class="badge">M</span>CancelPurchaseRequest</a></li>- <li>- <a href="#bytebase.v1.CancelPurchaseResponse"><span class="badge">M</span>CancelPurchaseResponse</a>- </li>-<li><a href="#bytebase.v1.CreatePurchaseRequest"><span class="badge">M</span>CreatePurchaseRequest</a></li>- <li>- <a href="#bytebase.v1.CreatePurchaseResponse"><span class="badge">M</span>CreatePurchaseResponse</a>- </li>-<li><a href="#bytebase.v1.GetPaymentInfoRequest"><span class="badge">M</span>GetPaymentInfoRequest</a></li>@@ -2784,6 +2776,10 @@<a href="#bytebase.v1.PurchasePlanAdditional"><span class="badge">M</span>PurchasePlanAdditional</a></li>+ <li>+ <a href="#bytebase.v1.PurchaseResponse"><span class="badge">M</span>PurchaseResponse</a>+ </li>+<li><a href="#bytebase.v1.Subscription"><span class="badge">M</span>Subscription</a></li>@@ -2793,11 +2789,15 @@</li><li>- <a href="#bytebase.v1.UpdatePurchaseResponse"><span class="badge">M</span>UpdatePurchaseResponse</a>+ <a href="#bytebase.v1.UploadLicenseRequest"><span class="badge">M</span>UploadLicenseRequest</a></li><li>- <a href="#bytebase.v1.UpdateSubscriptionRequest"><span class="badge">M</span>UpdateSubscriptionRequest</a>+ <a href="#bytebase.v1.VerifyCheckoutSessionRequest"><span class="badge">M</span>VerifyCheckoutSessionRequest</a>+ </li>++ <li>+ <a href="#bytebase.v1.VerifyCheckoutSessionResponse"><span class="badge">M</span>VerifyCheckoutSessionResponse</a></li>@@ -2813,6 +2813,10 @@<a href="#bytebase.v1.PlanType"><span class="badge">E</span>PlanType</a></li>+ <li>+ <a href="#bytebase.v1.PurchaseDiscount.Type"><span class="badge">E</span>PurchaseDiscount.Type</a>+ </li>+<li><a href="#bytebase.v1.PurchasePlanAdditional.Type"><span class="badge">E</span>PurchasePlanAdditional.Type</a></li>@@ -30517,13 +30521,6 @@ Permissions required: bb.sheets.get</p></td>- <h3 id="bytebase.v1.CancelPurchaseResponse">CancelPurchaseResponse</h3>- <p></p>-----<h3 id="bytebase.v1.CreatePurchaseRequest">CreatePurchaseRequest</h3><p></p>@@ -30562,30 +30559,6 @@ Permissions required: bb.sheets.get</p></td>- <h3 id="bytebase.v1.CreatePurchaseResponse">CreatePurchaseResponse</h3>- <p></p>--- <table class="field-table">- <thead>- <tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr>- </thead>- <tbody>-- <tr>- <td>payment_url</td>- <td><a href="#string">string</a></td>- <td></td>- <td><p>Stripe Checkout URL for the user to complete payment. </p></td>- </tr>-- </tbody>- </table>-----<h3 id="bytebase.v1.GetPaymentInfoRequest">GetPaymentInfoRequest</h3><p></p>@@ -30676,6 +30649,13 @@ Permissions required: bb.sheets.get</p></td><td><p>Stripe Billing Portal URL for invoice management. </p></td></tr>+ <tr>+ <td>cancel_at_period_end</td>+ <td><a href="#bool">bool</a></td>+ <td></td>+ <td><p>Whether the subscription is scheduled to cancel at the end of the current billing period. </p></td>+ </tr>+</tbody></table>@@ -30801,15 +30781,15 @@ Permissions required: bb.sheets.get</p></td><tbody><tr>- <td>description</td>- <td><a href="#string">string</a></td>+ <td>type</td>+ <td><a href="#bytebase.v1.PurchaseDiscount.Type">PurchaseDiscount.Type</a></td><td></td><td><p> </p></td></tr><tr>- <td>promotion_code</td>- <td><a href="#string">string</a></td>+ <td>value</td>+ <td><a href="#int32">int32</a></td><td></td><td><p> </p></td></tr>@@ -30918,6 +30898,38 @@ Permissions required: bb.sheets.get</p></td>+ <h3 id="bytebase.v1.PurchaseResponse">PurchaseResponse</h3>+ <p></p>+++ <table class="field-table">+ <thead>+ <tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr>+ </thead>+ <tbody>++ <tr>+ <td>payment_url</td>+ <td><a href="#string">string</a></td>+ <td></td>+ <td><p>If set, redirect to this Stripe Checkout URL.+If empty, the update was applied directly using the existing payment method. </p></td>+ </tr>++ <tr>+ <td>session_id</td>+ <td><a href="#string">string</a></td>+ <td></td>+ <td><p>Stripe Checkout Session ID. Used to verify the session after redirect. </p></td>+ </tr>++ </tbody>+ </table>+++++<h3 id="bytebase.v1.Subscription">Subscription</h3><p></p>@@ -30984,6 +30996,13 @@ Permissions required: bb.sheets.get</p></td><td><p>Whether high availability (multiple replicas) is enabled. </p></td></tr>+ <tr>+ <td>etag</td>+ <td><a href="#string">string</a></td>+ <td></td>+ <td><p>Etag for optimistic concurrency on purchase updates. Only set in SaaS mode. </p></td>+ </tr>+</tbody></table>@@ -31036,7 +31055,7 @@ Permissions required: bb.sheets.get</p></td>- <h3 id="bytebase.v1.UpdatePurchaseResponse">UpdatePurchaseResponse</h3>+ <h3 id="bytebase.v1.UploadLicenseRequest">UploadLicenseRequest</h3><p></p>@@ -31047,11 +31066,10 @@ Permissions required: bb.sheets.get</p></td><tbody><tr>- <td>payment_url</td>+ <td>license</td><td><a href="#string">string</a></td><td></td>- <td><p>If set, redirect to this Stripe Checkout URL.-If empty, the update was applied directly using the existing payment method. </p></td>+ <td><p> </p></td></tr></tbody>@@ -31061,7 +31079,7 @@ If empty, the update was applied directly using the existing payment method. </p- <h3 id="bytebase.v1.UpdateSubscriptionRequest">UpdateSubscriptionRequest</h3>+ <h3 id="bytebase.v1.VerifyCheckoutSessionRequest">VerifyCheckoutSessionRequest</h3><p></p>@@ -31072,18 +31090,34 @@ If empty, the update was applied directly using the existing payment method. </p<tbody><tr>- <td>license</td>+ <td>session_id</td><td><a href="#string">string</a></td><td></td><td><p> </p></td></tr>+ </tbody>+ </table>++++++ <h3 id="bytebase.v1.VerifyCheckoutSessionResponse">VerifyCheckoutSessionResponse</h3>+ <p></p>+++ <table class="field-table">+ <thead>+ <tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr>+ </thead>+ <tbody>+<tr>- <td>allow_missing</td>- <td><a href="#bool">bool</a></td>+ <td>status</td>+ <td><a href="#string">string</a></td><td></td>- <td><p>If set to true, and the subscription is not found, a new subscription will be created.-In this situation, `update_mask` is ignored. </p></td>+ <td><p>Stripe Checkout Session status: "complete", "expired", or "open". </p></td></tr></tbody>@@ -31602,6 +31636,41 @@ In this situation, `update_mask` is ignored. </p></td></tbody></table>+ <h3 id="bytebase.v1.PurchaseDiscount.Type">PurchaseDiscount.Type</h3>+ <p></p>+ <table class="enum-table">+ <thead>+ <tr><td>Name</td><td>Number</td><td>Description</td></tr>+ </thead>+ <tbody>++ <tr>+ <td>TYPE_UNSPECIFIED</td>+ <td>0</td>+ <td><p></p></td>+ </tr>++ <tr>+ <td>PERCENTAGE_OFF</td>+ <td>1</td>+ <td><p></p></td>+ </tr>++ <tr>+ <td>FIXED_MONTH_OFF</td>+ <td>2</td>+ <td><p></p></td>+ </tr>++ <tr>+ <td>FIXED_PRICE_OFF</td>+ <td>3</td>+ <td><p></p></td>+ </tr>++ </tbody>+ </table>+<h3 id="bytebase.v1.PurchasePlanAdditional.Type">PurchasePlanAdditional.Type</h3><p></p><table class="enum-table">@@ -31643,22 +31712,20 @@ In this situation, `update_mask` is ignored. </p></td><td><a href="#bytebase.v1.Subscription">Subscription</a></td><td><p>GetSubscription returns the current subscription.If there is no license, we will return a free plan subscription without expiration time.-If there is expired license, we will return a free plan subscription with the expiration time of the expired license.-Permissions required: None</p></td>+If there is expired license, we will return a free plan subscription with the expiration time of the expired license.</p></td></tr><tr>- <td>UpdateSubscription</td>- <td><a href="#bytebase.v1.UpdateSubscriptionRequest">UpdateSubscriptionRequest</a></td>+ <td>UploadLicense</td>+ <td><a href="#bytebase.v1.UploadLicenseRequest">UploadLicenseRequest</a></td><td><a href="#bytebase.v1.Subscription">Subscription</a></td>- <td><p>Updates the enterprise license subscription (self-hosted only).-Permissions required: bb.settings.set</p></td>+ <td><p>Uploads an enterprise license (self-hosted only).</p></td></tr><tr><td>CreatePurchase</td><td><a href="#bytebase.v1.CreatePurchaseRequest">CreatePurchaseRequest</a></td>- <td><a href="#bytebase.v1.CreatePurchaseResponse">CreatePurchaseResponse</a></td>+ <td><a href="#bytebase.v1.PurchaseResponse">PurchaseResponse</a></td><td><p>CreatePurchase creates a new subscription purchase (SaaS only).Returns a Stripe Checkout URL for the user to complete payment.</p></td></tr>@@ -31666,7 +31733,7 @@ Returns a Stripe Checkout URL for the user to complete payment.</p></td><tr><td>UpdatePurchase</td><td><a href="#bytebase.v1.UpdatePurchaseRequest">UpdatePurchaseRequest</a></td>- <td><a href="#bytebase.v1.UpdatePurchaseResponse">UpdatePurchaseResponse</a></td>+ <td><a href="#bytebase.v1.PurchaseResponse">PurchaseResponse</a></td><td><p>UpdatePurchase updates an existing subscription (SaaS only).May return a Stripe Checkout URL if payment method change is needed.</p></td></tr>@@ -31674,7 +31741,7 @@ May return a Stripe Checkout URL if payment method change is needed.</p></td><tr><td>CancelPurchase</td><td><a href="#bytebase.v1.CancelPurchaseRequest">CancelPurchaseRequest</a></td>- <td><a href="#bytebase.v1.CancelPurchaseResponse">CancelPurchaseResponse</a></td>+ <td><a href="#bytebase.v1.PurchaseResponse">PurchaseResponse</a></td><td><p>CancelPurchase cancels an active subscription (SaaS only).</p></td></tr>@@ -31685,6 +31752,13 @@ May return a Stripe Checkout URL if payment method change is needed.</p></td><td><p>GetPaymentInfo returns payment details for the current subscription (SaaS only).</p></td></tr>+ <tr>+ <td>VerifyCheckoutSession</td>+ <td><a href="#bytebase.v1.VerifyCheckoutSessionRequest">VerifyCheckoutSessionRequest</a></td>+ <td><a href="#bytebase.v1.VerifyCheckoutSessionResponse">VerifyCheckoutSessionResponse</a></td>+ <td><p>VerifyCheckoutSession verifies a Stripe Checkout Session status (SaaS only).</p></td>+ </tr>+<tr><td>ListPurchasePlans</td><td><a href="#bytebase.v1.ListPurchasePlansRequest">ListPurchasePlansRequest</a></td>@@ -31723,10 +31797,10 @@ May return a Stripe Checkout URL if payment method change is needed.</p></td><tr>- <td>UpdateSubscription</td>+ <td>UploadLicense</td><td>PATCH</td>- <td>/v1/subscription</td>- <td>license</td>+ <td>/v1/subscription/license</td>+ <td>*</td></tr>@@ -31772,6 +31846,16 @@ May return a Stripe Checkout URL if payment method change is needed.</p></td>+ <tr>+ <td>VerifyCheckoutSession</td>+ <td>GET</td>+ <td>/v1/subscription/checkoutSession/{session_id}</td>+ <td></td>+ </tr>++++<tr><td>ListPurchasePlans</td><td>GET</td>diff --git a/proto/store/store/subscription.proto b/proto/store/store/subscription.protoindex 85e412e8ad..34d38b1eb6 100644--- a/proto/store/store/subscription.proto+++ b/proto/store/store/subscription.proto@@ -11,10 +11,9 @@ option go_package = "generated-go/store";message SubscriptionPayload {enum Status {STATUS_UNSPECIFIED = 0;- PENDING = 1;- ACTIVE = 2;- PAUSED = 3;- CANCELED = 4;+ ACTIVE = 1;+ PAUSED = 2;+ CANCELED = 3;}enum Plan {diff --git a/proto/v1/v1/subscription_service.proto b/proto/v1/v1/subscription_service.protoindex f04e2e1a40..1e4a2d122a 100644--- a/proto/v1/v1/subscription_service.proto+++ b/proto/v1/v1/subscription_service.proto@@ -15,28 +15,24 @@ service SubscriptionService {// GetSubscription returns the current subscription.// If there is no license, we will return a free plan subscription without expiration time.// If there is expired license, we will return a free plan subscription with the expiration time of the expired license.- // Permissions required: Nonerpc GetSubscription(GetSubscriptionRequest) returns (Subscription) {option (google.api.http) = {get: "/v1/subscription"};option (google.api.method_signature) = "";- option (bytebase.v1.allow_without_credential) = true;}- // Updates the enterprise license subscription (self-hosted only).- // Permissions required: bb.settings.set- rpc UpdateSubscription(UpdateSubscriptionRequest) returns (Subscription) {+ // Uploads an enterprise license (self-hosted only).+ rpc UploadLicense(UploadLicenseRequest) returns (Subscription) {option (google.api.http) = {- patch: "/v1/subscription"- body: "license"+ patch: "/v1/subscription/license"+ body: "*"};- option (google.api.method_signature) = "patch";- option (bytebase.v1.permission) = "bb.settings.set";+ option (bytebase.v1.permission) = "bb.subscription.manage";option (bytebase.v1.auth_method) = IAM;}// CreatePurchase creates a new subscription purchase (SaaS only).// Returns a Stripe Checkout URL for the user to complete payment.- rpc CreatePurchase(CreatePurchaseRequest) returns (CreatePurchaseResponse) {+ rpc CreatePurchase(CreatePurchaseRequest) returns (PurchaseResponse) {option (google.api.http) = {post: "/v1/subscription:purchase"body: "*"@@ -47,7 +43,7 @@ service SubscriptionService {// UpdatePurchase updates an existing subscription (SaaS only).// May return a Stripe Checkout URL if payment method change is needed.- rpc UpdatePurchase(UpdatePurchaseRequest) returns (UpdatePurchaseResponse) {+ rpc UpdatePurchase(UpdatePurchaseRequest) returns (PurchaseResponse) {option (google.api.http) = {post: "/v1/subscription:updatePurchase"body: "*"@@ -57,7 +53,7 @@ service SubscriptionService {}// CancelPurchase cancels an active subscription (SaaS only).- rpc CancelPurchase(CancelPurchaseRequest) returns (CancelPurchaseResponse) {+ rpc CancelPurchase(CancelPurchaseRequest) returns (PurchaseResponse) {option (google.api.http) = {post: "/v1/subscription:cancelPurchase"body: "*"@@ -73,21 +69,23 @@ service SubscriptionService {option (bytebase.v1.auth_method) = IAM;}+ // VerifyCheckoutSession verifies a Stripe Checkout Session status (SaaS only).+ rpc VerifyCheckoutSession(VerifyCheckoutSessionRequest) returns (VerifyCheckoutSessionResponse) {+ option (google.api.http) = {get: "/v1/subscription/checkoutSession/{session_id}"};+ option (bytebase.v1.permission) = "bb.subscription.manage";+ option (bytebase.v1.auth_method) = IAM;+ }+// ListPurchasePlans returns available plans for self-service purchase.rpc ListPurchasePlans(ListPurchasePlansRequest) returns (ListPurchasePlansResponse) {option (google.api.http) = {get: "/v1/subscription/plans"};- option (bytebase.v1.allow_without_credential) = true;}}message GetSubscriptionRequest {}-message UpdateSubscriptionRequest {+message UploadLicenseRequest {string license = 1;-- // If set to true, and the subscription is not found, a new subscription will be created.- // In this situation, `update_mask` is ignored.- bool allow_missing = 2;}// Purchase messages@@ -98,9 +96,21 @@ message CreatePurchaseRequest {int32 seats = 3;}-message CreatePurchaseResponse {- // Stripe Checkout URL for the user to complete payment.+message PurchaseResponse {+ // If set, redirect to this Stripe Checkout URL.+ // If empty, the update was applied directly using the existing payment method.string payment_url = 1;+ // Stripe Checkout Session ID. Used to verify the session after redirect.+ string session_id = 2;+}++message VerifyCheckoutSessionRequest {+ string session_id = 1;+}++message VerifyCheckoutSessionResponse {+ // Stripe Checkout Session status: "complete", "expired", or "open".+ string status = 1;}message UpdatePurchaseRequest {@@ -110,16 +120,8 @@ message UpdatePurchaseRequest {string etag = 4;}-message UpdatePurchaseResponse {- // If set, redirect to this Stripe Checkout URL.- // If empty, the update was applied directly using the existing payment method.- string payment_url = 1;-}-message CancelPurchaseRequest {}-message CancelPurchaseResponse {}-message GetPaymentInfoRequest {}message PaymentInfo {@@ -129,6 +131,8 @@ message PaymentInfo {string period_end = 4;// Stripe Billing Portal URL for invoice management.string invoice_url = 5;+ // Whether the subscription is scheduled to cancel at the end of the current billing period.+ bool cancel_at_period_end = 6;}enum BillingInterval {@@ -164,8 +168,14 @@ message PurchaseBillingMethod {}message PurchaseDiscount {- string description = 1;- string promotion_code = 2;+ enum Type {+ TYPE_UNSPECIFIED = 0;+ PERCENTAGE_OFF = 1;+ FIXED_MONTH_OFF = 2;+ FIXED_PRICE_OFF = 3;+ }+ Type type = 1;+ int32 value = 2;}message ListPurchasePlansRequest {}@@ -207,6 +217,9 @@ message Subscription {// Whether high availability (multiple replicas) is enabled.bool ha = 8 [(google.api.field_behavior) = OUTPUT_ONLY];++ // Etag for optimistic concurrency on purchase updates. Only set in SaaS mode.+ string etag = 9 [(google.api.field_behavior) = OUTPUT_ONLY];}// PlanFeature represents the available features in Bytebase