-
Notifications
You must be signed in to change notification settings - Fork 170
Expand file tree
/
Copy pathbilling.go
More file actions
1281 lines (1123 loc) · 45.6 KB
/
billing.go
File metadata and controls
1281 lines (1123 loc) · 45.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package server
import (
"context"
"errors"
"fmt"
"math"
"strings"
"time"
"github.com/rilldata/rill/admin/billing"
"github.com/rilldata/rill/admin/database"
"github.com/rilldata/rill/admin/server/auth"
adminv1 "github.com/rilldata/rill/proto/gen/rill/admin/v1"
"github.com/rilldata/rill/runtime"
"github.com/rilldata/rill/runtime/pkg/email"
"github.com/rilldata/rill/runtime/pkg/observability"
runtimeauth "github.com/rilldata/rill/runtime/server/auth"
"go.opentelemetry.io/otel/attribute"
"go.uber.org/zap"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
)
func (s *Server) GetBillingSubscription(ctx context.Context, req *adminv1.GetBillingSubscriptionRequest) (*adminv1.GetBillingSubscriptionResponse, error) {
observability.AddRequestAttributes(ctx, attribute.String("args.org", req.Org))
org, err := s.admin.DB.FindOrganizationByName(ctx, req.Org)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
claims := auth.GetClaims(ctx)
forceAccess := claims.Superuser(ctx) && req.SuperuserForceAccess
if !claims.OrganizationPermissions(ctx, org.ID).ManageOrg && !forceAccess {
return nil, status.Error(codes.PermissionDenied, "not allowed to read org subscriptions")
}
if org.BillingCustomerID == "" {
return &adminv1.GetBillingSubscriptionResponse{Organization: s.organizationToDTO(org, true)}, nil
}
sub, org, err := s.getSubscriptionAndUpdateOrg(ctx, org)
if err != nil {
return nil, err
}
if sub == nil {
return &adminv1.GetBillingSubscriptionResponse{Organization: s.organizationToDTO(org, true)}, nil
}
return &adminv1.GetBillingSubscriptionResponse{
Organization: s.organizationToDTO(org, true),
Subscription: subscriptionToDTO(sub),
BillingPortalUrl: sub.Customer.PortalURL,
}, nil
}
func (s *Server) UpdateBillingSubscription(ctx context.Context, req *adminv1.UpdateBillingSubscriptionRequest) (*adminv1.UpdateBillingSubscriptionResponse, error) {
observability.AddRequestAttributes(ctx, attribute.String("args.org", req.Org))
observability.AddRequestAttributes(ctx, attribute.String("args.plan_name", req.PlanName))
org, err := s.admin.DB.FindOrganizationByName(ctx, req.Org)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
claims := auth.GetClaims(ctx)
forceAccess := claims.Superuser(ctx) && req.SuperuserForceAccess
if !claims.OrganizationPermissions(ctx, org.ID).ManageOrg && !forceAccess {
return nil, status.Error(codes.PermissionDenied, "not allowed to update org billing plan")
}
if req.PlanName == "" {
return nil, status.Error(codes.InvalidArgument, "plan name must be provided")
}
if org.BillingCustomerID == "" {
return nil, status.Error(codes.FailedPrecondition, "billing not yet initialized for the organization")
}
bisc, err := s.admin.DB.FindBillingIssueByTypeForOrg(ctx, org.ID, database.BillingIssueTypeSubscriptionCancelled)
if err != nil {
if !errors.Is(err, database.ErrNotFound) {
return nil, err
}
}
if bisc != nil {
return nil, status.Errorf(codes.FailedPrecondition, "plan cannot be changed on existing subscription as it was cancelled, please renew the subscription")
}
plan, err := s.admin.Biller.GetPlanByName(ctx, req.PlanName)
if err != nil {
if errors.Is(err, billing.ErrNotFound) {
return nil, status.Error(codes.NotFound, "plan not found")
}
return nil, err
}
// if its a trial plan, start trial only if its a new org
if plan.Default {
bi, err := s.admin.DB.FindBillingIssueByTypeForOrg(ctx, org.ID, database.BillingIssueTypeNeverSubscribed)
if err != nil {
if errors.Is(err, database.ErrNotFound) {
return nil, status.Errorf(codes.FailedPrecondition, "only new organizations can subscribe to the trial plan %s", plan.Name)
}
return nil, err
}
if bi != nil {
// check against trial orgs quota, skip for superusers
if org.CreatedByUserID != nil && !claims.Superuser(ctx) {
u, err := s.admin.DB.FindUser(ctx, *org.CreatedByUserID)
if err != nil {
return nil, err
}
if u.QuotaTrialOrgs >= 0 && u.CurrentTrialOrgsCount >= u.QuotaTrialOrgs {
return nil, status.Errorf(codes.FailedPrecondition, "trial orgs quota of %d reached for user %s", u.QuotaTrialOrgs, u.Email)
}
}
updatedOrg, sub, err := s.admin.StartTrial(ctx, org)
if err != nil {
return nil, err
}
// send trial started email
err = s.admin.Email.SendTrialStarted(&email.TrialStarted{
ToEmail: org.BillingEmail,
ToName: org.Name,
OrgName: org.Name,
FrontendURL: s.admin.URLs.Frontend(),
TrialEndDate: sub.TrialEndDate,
})
if err != nil {
s.logger.Named("billing").Error("failed to send trial started email", zap.String("org_name", org.Name), zap.String("org_id", org.ID), zap.String("billing_email", org.BillingEmail), zap.Error(err))
}
return &adminv1.UpdateBillingSubscriptionResponse{
Organization: s.organizationToDTO(updatedOrg, true),
Subscription: subscriptionToDTO(sub),
}, nil
}
}
if !plan.Public && !forceAccess {
return nil, status.Errorf(codes.FailedPrecondition, "cannot assign a private plan %q", plan.Name)
}
// check for validation errors if not forced
if !forceAccess {
err = s.planChangeValidationChecks(ctx, org)
if err != nil {
return nil, err
}
}
if planDowngrade(plan, org) {
if !forceAccess {
return nil, status.Errorf(codes.FailedPrecondition, "plan downgrade not supported")
}
s.logger.Named("billing").Warn("plan downgrade request", zap.String("org_id", org.ID), zap.String("org_name", org.Name), zap.String("plan_name", plan.Name))
}
sub, err := s.admin.Biller.GetActiveSubscription(ctx, org.BillingCustomerID)
if err != nil {
if !errors.Is(err, billing.ErrNotFound) {
return nil, err
}
}
planChange := false
if sub == nil {
// create new subscription
sub, err = s.admin.Biller.CreateSubscription(ctx, org.BillingCustomerID, plan)
if err != nil {
return nil, err
}
planChange = true
s.logger.Named("billing").Info("new subscription created",
zap.String("org_id", org.ID),
zap.String("org_name", org.Name),
zap.String("plan_id", sub.Plan.ID),
zap.String("plan_name", sub.Plan.Name),
)
} else {
// schedule plan change
oldPlan := sub.Plan
if oldPlan.ID != plan.ID {
sub, err = s.admin.Biller.ChangeSubscriptionPlan(ctx, sub.ID, plan)
if err != nil {
return nil, err
}
planChange = true
s.logger.Named("billing").Info("plan changed",
zap.String("org_id", org.ID),
zap.String("org_name", org.Name),
zap.String("old_plan_id", oldPlan.ID),
zap.String("old_plan_name", oldPlan.Name),
zap.String("new_plan_id", sub.Plan.ID),
zap.String("new_plan_name", sub.Plan.Name),
)
}
}
org, err = s.updateQuotasAndHandleBillingIssues(ctx, org, sub)
if err != nil {
return nil, err
}
if planChange {
// send plan changed email
if plan.PlanType == billing.TeamPlanType {
s.logger.Named("billing").Info("upgraded to team plan",
zap.String("org_id", org.ID),
zap.String("org_name", org.Name),
zap.String("user_email", org.BillingEmail),
zap.String("plan_id", sub.Plan.ID),
zap.String("plan_name", sub.Plan.Name),
)
// special handling for team plan to send custom email
err = s.admin.Email.SendTeamPlanStarted(&email.TeamPlan{
ToEmail: org.BillingEmail,
ToName: org.Name,
OrgName: org.Name,
FrontendURL: s.admin.URLs.Frontend(),
PlanName: plan.DisplayName,
BillingStartDate: sub.CurrentBillingCycleEndDate,
})
} else {
err = s.admin.Email.SendPlanUpdate(&email.PlanUpdate{
ToEmail: org.BillingEmail,
ToName: org.Name,
OrgName: org.Name,
PlanName: plan.DisplayName,
})
}
if err != nil {
s.logger.Named("billing").Error("failed to send plan update email", zap.String("org_name", org.Name), zap.String("org_id", org.ID), zap.String("billing_email", org.BillingEmail), zap.Error(err))
}
}
return &adminv1.UpdateBillingSubscriptionResponse{
Organization: s.organizationToDTO(org, true),
Subscription: subscriptionToDTO(sub),
}, nil
}
// CancelBillingSubscription cancels the billing subscription for the organization
func (s *Server) CancelBillingSubscription(ctx context.Context, req *adminv1.CancelBillingSubscriptionRequest) (*adminv1.CancelBillingSubscriptionResponse, error) {
observability.AddRequestAttributes(ctx, attribute.String("args.org", req.Org))
org, err := s.admin.DB.FindOrganizationByName(ctx, req.Org)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
claims := auth.GetClaims(ctx)
forceAccess := claims.Superuser(ctx) && req.SuperuserForceAccess
if !claims.OrganizationPermissions(ctx, org.ID).ManageOrg && !forceAccess {
return nil, status.Error(codes.PermissionDenied, "not allowed to cancel org subscription")
}
if org.BillingCustomerID == "" {
return nil, status.Error(codes.FailedPrecondition, "billing not yet initialized for the organization")
}
sub, err := s.admin.Biller.GetActiveSubscription(ctx, org.BillingCustomerID)
if err != nil {
return nil, err
}
endDate, err := s.admin.Biller.CancelSubscriptionsForCustomer(ctx, org.BillingCustomerID, billing.SubscriptionCancellationOptionEndOfSubscriptionTerm)
if err != nil {
return nil, err
}
if !endDate.IsZero() {
// raise a billing issue of the subscription cancellation
_, err = s.admin.DB.UpsertBillingIssue(ctx, &database.UpsertBillingIssueOptions{
OrgID: org.ID,
Type: database.BillingIssueTypeSubscriptionCancelled,
Metadata: database.BillingIssueMetadataSubscriptionCancelled{
EndDate: endDate,
},
EventTime: time.Now(),
})
if err != nil {
return nil, err
}
}
// clean up any trial related billing issues if present
err = s.admin.CleanupTrialBillingIssues(ctx, org.ID)
if err != nil {
return nil, err
}
s.logger.Named("billing").Warn("subscription cancelled", zap.String("org_id", org.ID), zap.String("org_name", org.Name))
err = s.admin.Email.SendSubscriptionCancelled(&email.SubscriptionCancelled{
ToEmail: org.BillingEmail,
ToName: org.Name,
OrgName: org.Name,
PlanName: sub.Plan.DisplayName,
EndDate: endDate,
BillingURL: s.admin.URLs.Billing(org.Name, false),
})
if err != nil {
s.logger.Named("billing").Error("failed to send subscription cancelled email", zap.String("org_name", org.Name), zap.String("org_id", org.ID), zap.String("billing_email", org.BillingEmail), zap.Error(err))
}
return &adminv1.CancelBillingSubscriptionResponse{}, nil
}
func (s *Server) RenewBillingSubscription(ctx context.Context, req *adminv1.RenewBillingSubscriptionRequest) (*adminv1.RenewBillingSubscriptionResponse, error) {
observability.AddRequestAttributes(ctx, attribute.String("args.org", req.Org))
observability.AddRequestAttributes(ctx, attribute.String("args.plan_name", req.PlanName))
org, err := s.admin.DB.FindOrganizationByName(ctx, req.Org)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
claims := auth.GetClaims(ctx)
forceAccess := claims.Superuser(ctx) && req.SuperuserForceAccess
if !claims.OrganizationPermissions(ctx, org.ID).ManageOrg && !forceAccess {
return nil, status.Error(codes.PermissionDenied, "not allowed to renew org subscription")
}
if org.BillingCustomerID == "" {
return nil, status.Error(codes.FailedPrecondition, "billing not yet initialized for the organization")
}
bisc, err := s.admin.DB.FindBillingIssueByTypeForOrg(ctx, org.ID, database.BillingIssueTypeSubscriptionCancelled)
if err != nil {
if errors.Is(err, database.ErrNotFound) {
return nil, status.Errorf(codes.FailedPrecondition, "subscription not cancelled for the organization %s", org.Name)
}
return nil, err
}
plan, err := s.admin.Biller.GetPlanByName(ctx, req.PlanName)
if err != nil {
return nil, err
}
if plan.Default {
return nil, status.Errorf(codes.FailedPrecondition, "cannot renew to trial plan %s", plan.Name)
}
if !plan.Public && !forceAccess {
return nil, status.Errorf(codes.FailedPrecondition, "cannot renew to a private plan %q", plan.Name)
}
if !forceAccess {
// check for validation errors
err = s.planChangeValidationChecks(ctx, org)
if err != nil {
return nil, err
}
}
sub, err := s.admin.Biller.GetActiveSubscription(ctx, org.BillingCustomerID)
if err != nil {
if !errors.Is(err, billing.ErrNotFound) {
return nil, err
}
}
if sub == nil {
sub, err = s.admin.Biller.CreateSubscription(ctx, org.BillingCustomerID, plan)
if err != nil {
return nil, err
}
} else if sub.EndDate.Equal(sub.CurrentBillingCycleEndDate) {
// To make request idempotent, if subscription is still on cancellation schedule, unschedule it
sub, err = s.admin.Biller.UnscheduleCancellation(ctx, sub.ID)
if err != nil {
return nil, err
}
}
if sub.Plan.ID != plan.ID {
// change the plan, won't happen for new subscriptions
sub, err = s.admin.Biller.ChangeSubscriptionPlan(ctx, sub.ID, plan)
if err != nil {
return nil, err
}
}
// update quotas
org, err = s.admin.DB.UpdateOrganization(ctx, org.ID, &database.UpdateOrganizationOptions{
Name: org.Name,
DisplayName: org.DisplayName,
Description: org.Description,
LogoAssetID: org.LogoAssetID,
LogoDarkAssetID: org.LogoDarkAssetID,
FaviconAssetID: org.FaviconAssetID,
ThumbnailAssetID: org.ThumbnailAssetID,
CustomDomain: org.CustomDomain,
DefaultProjectRoleID: org.DefaultProjectRoleID,
QuotaProjects: valOrDefault(sub.Plan.Quotas.NumProjects, org.QuotaProjects),
QuotaDeployments: valOrDefault(sub.Plan.Quotas.NumDeployments, org.QuotaDeployments),
QuotaSlotsTotal: valOrDefault(sub.Plan.Quotas.NumSlotsTotal, org.QuotaSlotsTotal),
QuotaSlotsPerDeployment: valOrDefault(sub.Plan.Quotas.NumSlotsPerDeployment, org.QuotaSlotsPerDeployment),
QuotaOutstandingInvites: valOrDefault(sub.Plan.Quotas.NumOutstandingInvites, org.QuotaOutstandingInvites),
QuotaStorageLimitBytesPerDeployment: valOrDefault(sub.Plan.Quotas.StorageLimitBytesPerDeployment, org.QuotaStorageLimitBytesPerDeployment),
BillingCustomerID: org.BillingCustomerID,
BillingPlanName: &sub.Plan.Name,
BillingPlanDisplayName: &sub.Plan.DisplayName,
PaymentCustomerID: org.PaymentCustomerID,
BillingEmail: org.BillingEmail,
CreatedByUserID: org.CreatedByUserID,
})
if err != nil {
return nil, err
}
// delete the billing issue
err = s.admin.DB.DeleteBillingIssue(ctx, bisc.ID)
if err != nil {
return nil, err
}
s.logger.Named("billing").Info("subscription renewed", zap.String("org_id", org.ID), zap.String("org_name", org.Name), zap.String("plan_id", sub.Plan.ID), zap.String("plan_name", sub.Plan.Name))
// send subscription renewed email
if sub.Plan.PlanType == billing.TeamPlanType {
// special handling for team plan to send custom email
err = s.admin.Email.SendTeamPlanRenewal(&email.TeamPlan{
ToEmail: org.BillingEmail,
ToName: org.Name,
OrgName: org.Name,
FrontendURL: s.admin.URLs.Frontend(),
PlanName: sub.Plan.DisplayName,
BillingStartDate: sub.CurrentBillingCycleEndDate,
})
s.logger.Named("billing").Info("upgraded to team plan",
zap.String("org_id", org.ID),
zap.String("org_name", org.Name),
zap.String("user_email", org.BillingEmail),
zap.String("plan_id", sub.Plan.ID),
zap.String("plan_name", sub.Plan.Name),
)
} else {
err = s.admin.Email.SendSubscriptionRenewed(&email.SubscriptionRenewed{
ToEmail: org.BillingEmail,
ToName: org.Name,
OrgName: org.Name,
PlanName: sub.Plan.DisplayName,
})
}
if err != nil {
s.logger.Named("billing").Error("failed to send subscription renewed email", zap.String("org_name", org.Name), zap.String("org_id", org.ID), zap.Error(err))
}
return &adminv1.RenewBillingSubscriptionResponse{
Organization: s.organizationToDTO(org, true),
Subscription: subscriptionToDTO(sub),
}, nil
}
func (s *Server) GetPaymentsPortalURL(ctx context.Context, req *adminv1.GetPaymentsPortalURLRequest) (*adminv1.GetPaymentsPortalURLResponse, error) {
observability.AddRequestAttributes(ctx, attribute.String("args.org", req.Org))
observability.AddRequestAttributes(ctx, attribute.String("args.return_url", req.ReturnUrl))
observability.AddRequestAttributes(ctx, attribute.Bool("args.setup", req.Setup))
org, err := s.admin.DB.FindOrganizationByName(ctx, req.Org)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
claims := auth.GetClaims(ctx)
forceAccess := claims.Superuser(ctx) && req.SuperuserForceAccess
if !claims.OrganizationPermissions(ctx, org.ID).ManageOrg && !forceAccess {
return nil, status.Error(codes.PermissionDenied, "not allowed to manage org billing")
}
if org.PaymentCustomerID == "" {
return nil, status.Error(codes.FailedPrecondition, "payment customer not initialized yet for the organization")
}
// returnUrl is mandatory so if not passed default to home page
if req.ReturnUrl == "" {
req.ReturnUrl = s.admin.URLs.Frontend()
}
url, err := s.admin.PaymentProvider.GetBillingPortalURL(ctx, org.PaymentCustomerID, req.ReturnUrl, req.Setup)
if err != nil {
return nil, err
}
return &adminv1.GetPaymentsPortalURLResponse{Url: url}, nil
}
// SudoUpdateOrganizationBillingCustomer updates the billing customer id for an organization. May be useful if customer is initialized manually in billing system
func (s *Server) SudoUpdateOrganizationBillingCustomer(ctx context.Context, req *adminv1.SudoUpdateOrganizationBillingCustomerRequest) (*adminv1.SudoUpdateOrganizationBillingCustomerResponse, error) {
observability.AddRequestAttributes(ctx,
attribute.String("args.org", req.Org),
)
if req.BillingCustomerId != nil {
observability.AddRequestAttributes(ctx, attribute.String("args.billing_customer_id", *req.BillingCustomerId))
}
if req.PaymentCustomerId != nil {
observability.AddRequestAttributes(ctx, attribute.String("args.payment_customer_id", *req.PaymentCustomerId))
}
claims := auth.GetClaims(ctx)
if !claims.Superuser(ctx) {
return nil, status.Error(codes.PermissionDenied, "only superusers can manage billing customer")
}
if req.BillingCustomerId == nil && req.PaymentCustomerId == nil {
return nil, status.Error(codes.InvalidArgument, "either or both billing and payment customer id must be provided")
}
org, err := s.admin.DB.FindOrganizationByName(ctx, req.Org)
if err != nil {
return nil, err
}
opts := &database.UpdateOrganizationOptions{
Name: org.Name,
DisplayName: org.DisplayName,
Description: org.Description,
LogoAssetID: org.LogoAssetID,
LogoDarkAssetID: org.LogoDarkAssetID,
FaviconAssetID: org.FaviconAssetID,
ThumbnailAssetID: org.ThumbnailAssetID,
CustomDomain: org.CustomDomain,
DefaultProjectRoleID: org.DefaultProjectRoleID,
QuotaProjects: org.QuotaProjects,
QuotaDeployments: org.QuotaDeployments,
QuotaSlotsTotal: org.QuotaSlotsTotal,
QuotaSlotsPerDeployment: org.QuotaSlotsPerDeployment,
QuotaOutstandingInvites: org.QuotaOutstandingInvites,
QuotaStorageLimitBytesPerDeployment: org.QuotaStorageLimitBytesPerDeployment,
BillingCustomerID: valOrDefault(req.BillingCustomerId, org.BillingCustomerID),
PaymentCustomerID: valOrDefault(req.PaymentCustomerId, org.PaymentCustomerID),
BillingEmail: org.BillingEmail,
BillingPlanName: org.BillingPlanName,
BillingPlanDisplayName: org.BillingPlanDisplayName,
CreatedByUserID: org.CreatedByUserID,
}
var sub *billing.Subscription
if req.BillingCustomerId != nil {
// get active subscriptions if present
sub, err = s.admin.Biller.GetActiveSubscription(ctx, *req.BillingCustomerId)
if err != nil {
if !errors.Is(err, billing.ErrNotFound) {
return nil, err
}
}
if sub != nil {
opts.QuotaProjects = biggerOfInt(sub.Plan.Quotas.NumProjects, org.QuotaProjects)
opts.QuotaDeployments = biggerOfInt(sub.Plan.Quotas.NumDeployments, org.QuotaDeployments)
opts.QuotaSlotsTotal = biggerOfInt(sub.Plan.Quotas.NumSlotsTotal, org.QuotaSlotsTotal)
opts.QuotaSlotsPerDeployment = biggerOfInt(sub.Plan.Quotas.NumSlotsPerDeployment, org.QuotaSlotsPerDeployment)
opts.QuotaOutstandingInvites = biggerOfInt(sub.Plan.Quotas.NumOutstandingInvites, org.QuotaOutstandingInvites)
opts.QuotaStorageLimitBytesPerDeployment = biggerOfInt64(sub.Plan.Quotas.StorageLimitBytesPerDeployment, org.QuotaStorageLimitBytesPerDeployment)
}
}
org, err = s.admin.DB.UpdateOrganization(ctx, org.ID, opts)
if err != nil {
return nil, err
}
if req.PaymentCustomerId != nil {
// fetch the customer
pc, err := s.admin.PaymentProvider.FindCustomer(ctx, *req.PaymentCustomerId)
if err != nil {
return nil, err
}
// link the payment customer to the billing customer
err = s.admin.Biller.UpdateCustomerPaymentID(ctx, org.BillingCustomerID, billing.PaymentProviderStripe, *req.PaymentCustomerId)
if err != nil {
return nil, err
}
if !pc.HasPaymentMethod {
_, err := s.admin.DB.UpsertBillingIssue(ctx, &database.UpsertBillingIssueOptions{
OrgID: org.ID,
Type: database.BillingIssueTypeNoPaymentMethod,
Metadata: &database.BillingIssueMetadataNoPaymentMethod{},
EventTime: time.Now(),
})
if err != nil {
return nil, err
}
}
if !pc.HasBillableAddress {
_, err := s.admin.DB.UpsertBillingIssue(ctx, &database.UpsertBillingIssueOptions{
OrgID: org.ID,
Type: database.BillingIssueTypeNoBillableAddress,
Metadata: &database.BillingIssueMetadataNoBillableAddress{},
EventTime: time.Now(),
})
if err != nil {
return nil, err
}
}
}
if sub == nil {
return &adminv1.SudoUpdateOrganizationBillingCustomerResponse{
Organization: s.organizationToDTO(org, true),
}, nil
}
return &adminv1.SudoUpdateOrganizationBillingCustomerResponse{
Organization: s.organizationToDTO(org, true),
Subscription: subscriptionToDTO(sub),
}, nil
}
func (s *Server) SudoExtendTrial(ctx context.Context, req *adminv1.SudoExtendTrialRequest) (*adminv1.SudoExtendTrialResponse, error) {
observability.AddRequestAttributes(ctx, attribute.String("args.org", req.Org))
days := int(req.Days)
observability.AddRequestAttributes(ctx, attribute.Int("args.days", days))
claims := auth.GetClaims(ctx)
if !claims.Superuser(ctx) {
return nil, status.Error(codes.PermissionDenied, "only superusers can extend trial")
}
org, err := s.admin.DB.FindOrganizationByName(ctx, req.Org)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
ns, err := s.admin.DB.FindBillingIssueByTypeForOrg(ctx, org.ID, database.BillingIssueTypeNeverSubscribed)
if err != nil {
if !errors.Is(err, database.ErrNotFound) {
return nil, err
}
}
if ns != nil {
return nil, status.Errorf(codes.FailedPrecondition, "organization %s never subscribed to a plan", org.Name)
}
// find existing trial end date
currentEndDate := time.Time{}
onTrial, err := s.admin.DB.FindBillingIssueByTypeForOrg(ctx, org.ID, database.BillingIssueTypeOnTrial)
if err != nil {
if !errors.Is(err, database.ErrNotFound) {
return nil, err
}
}
if onTrial != nil {
currentEndDate = onTrial.Metadata.(*database.BillingIssueMetadataOnTrial).GracePeriodEndDate
}
if currentEndDate.IsZero() {
trialEnded, err := s.admin.DB.FindBillingIssueByTypeForOrg(ctx, org.ID, database.BillingIssueTypeTrialEnded)
if err != nil {
if !errors.Is(err, database.ErrNotFound) {
return nil, err
}
}
if trialEnded != nil {
currentEndDate = trialEnded.Metadata.(*database.BillingIssueMetadataTrialEnded).GracePeriodEndDate
}
}
if currentEndDate.IsZero() {
subCancelled, err := s.admin.DB.FindBillingIssueByTypeForOrg(ctx, org.ID, database.BillingIssueTypeSubscriptionCancelled)
if err != nil {
if !errors.Is(err, database.ErrNotFound) {
return nil, err
}
}
if subCancelled != nil {
currentEndDate = subCancelled.Metadata.(*database.BillingIssueMetadataSubscriptionCancelled).EndDate
}
}
if currentEndDate.IsZero() || currentEndDate.Before(time.Now()) {
currentEndDate = time.Now().Truncate(24*time.Hour).AddDate(0, 0, 1)
}
newEndDate := currentEndDate.AddDate(0, 0, days)
// start a new trial, if already on trial plan, this will not create new subscription, if not on trial plan it will error
_, sub, err := s.admin.StartTrial(ctx, org)
if err != nil {
return nil, err
}
if sub.ID != "" {
// update on trial metadata with new end date
_, err = s.admin.DB.UpsertBillingIssue(ctx, &database.UpsertBillingIssueOptions{
OrgID: org.ID,
Type: database.BillingIssueTypeOnTrial,
Metadata: database.BillingIssueMetadataOnTrial{
SubID: sub.ID,
PlanID: sub.Plan.ID,
EndDate: newEndDate,
GracePeriodEndDate: newEndDate,
},
EventTime: time.Now(),
})
if err != nil {
return nil, err
}
// send trial extended email
err = s.admin.Email.SendTrialExtended(&email.TrialExtended{
ToEmail: org.BillingEmail,
ToName: org.Name,
OrgName: org.Name,
TrialEndDate: newEndDate,
})
if err != nil {
s.logger.Named("billing").Error("failed to send trial extended email", zap.String("org_name", org.Name), zap.String("org_id", org.ID), zap.String("billing_email", org.BillingEmail), zap.Error(err))
}
}
// if trial subscription was cancelled then unschedule the cancellation
if sub.EndDate.Equal(sub.CurrentBillingCycleEndDate) {
// if trial subscription was cancelled then unschedule the cancellation
_, err = s.admin.Biller.UnscheduleCancellation(ctx, sub.ID)
if err != nil {
return nil, err
}
}
return &adminv1.SudoExtendTrialResponse{TrialEnd: timestamppb.New(newEndDate)}, nil
}
func (s *Server) SudoTriggerBillingRepair(ctx context.Context, req *adminv1.SudoTriggerBillingRepairRequest) (*adminv1.SudoTriggerBillingRepairResponse, error) {
claims := auth.GetClaims(ctx)
if !claims.Superuser(ctx) {
return nil, status.Error(codes.PermissionDenied, "only superusers can trigger billing repair")
}
ids, err := s.admin.DB.FindOrganizationIDsWithoutBilling(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get organizations without billing id: %w", err)
}
for _, orgID := range ids {
_, err := s.admin.Jobs.RepairOrgBilling(ctx, orgID)
if err != nil {
s.logger.Named("billing").Error("failed to submit repair billing job", zap.String("org_id", orgID), zap.Error(err))
continue
}
}
return &adminv1.SudoTriggerBillingRepairResponse{}, nil
}
func (s *Server) ListPublicBillingPlans(ctx context.Context, req *adminv1.ListPublicBillingPlansRequest) (*adminv1.ListPublicBillingPlansResponse, error) {
observability.AddRequestAttributes(ctx)
// no permissions required to list public billing plans
plans, err := s.admin.Biller.GetPublicPlans(ctx)
if err != nil {
return nil, err
}
var dtos []*adminv1.BillingPlan
for _, plan := range plans {
dtos = append(dtos, billingPlanToDTO(plan))
}
return &adminv1.ListPublicBillingPlansResponse{
Plans: dtos,
}, nil
}
func (s *Server) GetBillingProjectCredentials(ctx context.Context, req *adminv1.GetBillingProjectCredentialsRequest) (*adminv1.GetBillingProjectCredentialsResponse, error) {
observability.AddRequestAttributes(ctx, attribute.String("args.org", req.Org))
org, err := s.admin.DB.FindOrganizationByName(ctx, req.Org)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
claims := auth.GetClaims(ctx)
if !claims.OrganizationPermissions(ctx, org.ID).ManageOrg {
return nil, status.Error(codes.PermissionDenied, "not allowed to get metrics for this org")
}
if s.admin.MetricsProjectID == "" {
return nil, status.Error(codes.FailedPrecondition, "metrics project not configured")
}
metricsProj, err := s.admin.DB.FindProject(ctx, s.admin.MetricsProjectID)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
if metricsProj.PrimaryDeploymentID == nil {
return nil, status.Error(codes.InvalidArgument, "project does not have a deployment")
}
prodDepl, err := s.admin.DB.FindDeployment(ctx, *metricsProj.PrimaryDeploymentID)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
// Generate JWT
jwt, err := s.issuer.NewToken(runtimeauth.TokenOptions{
AudienceURL: prodDepl.RuntimeAudience,
Subject: claims.OwnerID(),
TTL: runtimeAccessTokenDefaultTTL,
InstancePermissions: map[string][]runtime.Permission{
prodDepl.RuntimeInstanceID: {
runtime.ReadObjects,
runtime.ReadMetrics,
runtime.ReadAPI,
},
},
Attributes: map[string]any{"organization_id": org.ID, "is_embed": true},
})
if err != nil {
return nil, fmt.Errorf("could not issue jwt: %w", err)
}
s.admin.Used.Deployment(prodDepl.ID)
return &adminv1.GetBillingProjectCredentialsResponse{
RuntimeHost: prodDepl.RuntimeHost,
InstanceId: prodDepl.RuntimeInstanceID,
AccessToken: jwt,
TtlSeconds: uint32(runtimeAccessTokenDefaultTTL.Seconds()),
}, nil
}
func (s *Server) ListOrganizationBillingIssues(ctx context.Context, req *adminv1.ListOrganizationBillingIssuesRequest) (*adminv1.ListOrganizationBillingIssuesResponse, error) {
observability.AddRequestAttributes(ctx, attribute.String("args.org", req.Org))
org, err := s.admin.DB.FindOrganizationByName(ctx, req.Org)
if err != nil {
if errors.Is(err, database.ErrNotFound) {
return nil, status.Error(codes.NotFound, "org not found")
}
return nil, status.Error(codes.InvalidArgument, err.Error())
}
claims := auth.GetClaims(ctx)
forceAccess := claims.Superuser(ctx) && req.SuperuserForceAccess
if !claims.OrganizationPermissions(ctx, org.ID).ReadOrg && !forceAccess {
return nil, status.Error(codes.PermissionDenied, "not allowed to read org billing errors")
}
issues, err := s.admin.DB.FindBillingIssuesForOrg(ctx, org.ID)
if err != nil {
return nil, err
}
var dtos []*adminv1.BillingIssue
for _, i := range issues {
dtos = append(dtos, &adminv1.BillingIssue{
Org: org.Name,
Type: billingIssueTypeToDTO(i.Type),
Level: billingIssueLevelToDTO(i.Level),
Metadata: billingIssueMetadataToDTO(i.Type, i.Metadata),
EventTime: timestamppb.New(i.EventTime),
CreatedOn: timestamppb.New(i.CreatedOn),
})
}
return &adminv1.ListOrganizationBillingIssuesResponse{
Issues: dtos,
}, nil
}
func (s *Server) SudoDeleteOrganizationBillingIssue(ctx context.Context, req *adminv1.SudoDeleteOrganizationBillingIssueRequest) (*adminv1.SudoDeleteOrganizationBillingIssueResponse, error) {
observability.AddRequestAttributes(ctx, attribute.String("args.org", req.Org), attribute.String("args.type", req.Type.String()))
claims := auth.GetClaims(ctx)
if !claims.Superuser(ctx) {
return nil, status.Error(codes.PermissionDenied, "only superusers can delete billing errors")
}
org, err := s.admin.DB.FindOrganizationByName(ctx, req.Org)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
t, err := dtoBillingIssueTypeToDB(req.Type)
if err != nil {
return nil, err
}
err = s.admin.DB.DeleteBillingIssueByTypeForOrg(ctx, org.ID, t)
if err != nil {
return nil, err
}
return &adminv1.SudoDeleteOrganizationBillingIssueResponse{}, nil
}
func (s *Server) updateQuotasAndHandleBillingIssues(ctx context.Context, org *database.Organization, sub *billing.Subscription) (*database.Organization, error) {
org, err := s.admin.DB.UpdateOrganization(ctx, org.ID, &database.UpdateOrganizationOptions{
Name: org.Name,
DisplayName: org.DisplayName,
Description: org.Description,
LogoAssetID: org.LogoAssetID,
LogoDarkAssetID: org.LogoDarkAssetID,
FaviconAssetID: org.FaviconAssetID,
ThumbnailAssetID: org.ThumbnailAssetID,
CustomDomain: org.CustomDomain,
DefaultProjectRoleID: org.DefaultProjectRoleID,
QuotaProjects: valOrDefault(sub.Plan.Quotas.NumProjects, org.QuotaProjects),
QuotaDeployments: valOrDefault(sub.Plan.Quotas.NumDeployments, org.QuotaDeployments),
QuotaSlotsTotal: valOrDefault(sub.Plan.Quotas.NumSlotsTotal, org.QuotaSlotsTotal),
QuotaSlotsPerDeployment: valOrDefault(sub.Plan.Quotas.NumSlotsPerDeployment, org.QuotaSlotsPerDeployment),
QuotaOutstandingInvites: valOrDefault(sub.Plan.Quotas.NumOutstandingInvites, org.QuotaOutstandingInvites),
QuotaStorageLimitBytesPerDeployment: valOrDefault(sub.Plan.Quotas.StorageLimitBytesPerDeployment, org.QuotaStorageLimitBytesPerDeployment),
BillingCustomerID: org.BillingCustomerID,
BillingPlanName: &sub.Plan.Name,
BillingPlanDisplayName: &sub.Plan.DisplayName,
PaymentCustomerID: org.PaymentCustomerID,
BillingEmail: org.BillingEmail,
CreatedByUserID: org.CreatedByUserID,
})
if err != nil {
return nil, err
}
// delete any trial related billing issues, irrespective of the new plan.
err = s.admin.CleanupTrialBillingIssues(ctx, org.ID)
if err != nil {
return nil, fmt.Errorf("failed to cleanup trial billing errors and warnings: %w", err)
}
// delete any subscription related billing issues
err = s.admin.CleanupSubscriptionBillingIssues(ctx, org.ID)
if err != nil {
return nil, fmt.Errorf("failed to cleanup subscription cancellation errors: %w", err)
}
return org, nil
}
func (s *Server) planChangeValidationChecks(ctx context.Context, org *database.Organization) error {
// not a trial plan, check for a payment method and a valid billing address
var validationErrs []string
pc, err := s.admin.PaymentProvider.FindCustomer(ctx, org.PaymentCustomerID)
if err != nil {
return err
}
if !pc.HasPaymentMethod {
validationErrs = append(validationErrs, "no payment method found")
}
if !pc.HasBillableAddress {
validationErrs = append(validationErrs, "no billing address found")
}
be, err := s.admin.DB.FindBillingIssueByTypeForOrg(ctx, org.ID, database.BillingIssueTypePaymentFailed)
if err != nil {
if !errors.Is(err, database.ErrNotFound) {
return err
}
}
if be != nil {
validationErrs = append(validationErrs, "a previous payment is due")
}
if len(validationErrs) > 0 {
return status.Errorf(codes.FailedPrecondition, "please fix following by visiting billing portal: %s", strings.Join(validationErrs, ", "))
}
return nil
}
func (s *Server) getSubscriptionAndUpdateOrg(ctx context.Context, org *database.Organization) (*billing.Subscription, *database.Organization, error) {
sub, err := s.admin.Biller.GetActiveSubscription(ctx, org.BillingCustomerID)
if err != nil && !errors.Is(err, billing.ErrNotFound) {
return nil, nil, err
}
var planDisplayName string
var planName string
if sub == nil {
planDisplayName = ""
planName = ""
} else {
planDisplayName = sub.Plan.DisplayName
planName = sub.Plan.Name
}
// update the cached plan
if org.BillingPlanName == nil || *org.BillingPlanName != planName {
org, err = s.admin.DB.UpdateOrganization(ctx, org.ID, &database.UpdateOrganizationOptions{
Name: org.Name,