Skip to content

Commit 4e266f1

Browse files
authored
feat(store): billing rows are soft deleted when an org is deleted (#1983)
1 parent 4098c75 commit 4e266f1

17 files changed

Lines changed: 322 additions & 25 deletions

‎billing/checkout/service.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -788,7 +788,7 @@ func (s *Service) List(ctx context.Context, filter Filter) ([]Checkout, error) {
788788
return s.repository.List(ctx, filter)
789789
}
790790

791-
// DeleteByCustomer removes all checkout records of a billing account. Checkout
791+
// DeleteByCustomer marks every checkout of a billing account as deleted. Checkout
792792
// sessions on the billing provider are not touched as they expire on their own.
793793
func (s *Service) DeleteByCustomer(ctx context.Context, customerID string) error {
794794
return s.repository.DeleteByCustomerID(ctx, customerID)

‎billing/credit/service.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,7 @@ func (s Service) GetByID(ctx context.Context, id string) (Transaction, error) {
176176
return s.transactionRepository.GetByID(ctx, id)
177177
}
178178

179-
// DeleteByAccountID removes all credit transactions of a billing account. It is
179+
// DeleteByAccountID marks every credit transaction of a billing account as deleted. It is
180180
// meant for account teardown.
181181
func (s Service) DeleteByAccountID(ctx context.Context, accountID string) error {
182182
return s.transactionRepository.DeleteByAccountID(ctx, accountID)

‎billing/customer/errors.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,5 @@ var (
1313
ErrInvalidDetail = errors.New("invalid billing customer detail")
1414
ErrDisabled = errors.New("billing customer is disabled")
1515
ErrExistingAccountWithPendingDues = errors.New("existing account with pending dues found")
16+
ErrHasLiveRecords = errors.New("billing account still has live subscriptions, invoices or checkouts")
1617
)

‎billing/subscription/service.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1102,7 +1102,7 @@ func (s *Service) ensureCreditsForPlan(ctx context.Context, sub Subscription, su
11021102
// subscriptions are canceled on the billing provider first. A subscription
11031103
// that is already gone or canceled on the provider counts as canceled, so a
11041104
// teardown that failed midway can be run again. Offline accounts have nothing
1105-
// on the provider; only their local records are removed.
1105+
// on the provider; only their local rows are marked deleted.
11061106
func (s *Service) DeleteByCustomer(ctx context.Context, customr customer.Customer) error {
11071107
subs, err := s.List(ctx, Filter{
11081108
CustomerID: customr.ID,

‎core/deleter/service.go‎

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -442,20 +442,10 @@ func (d Service) DeleteCustomers(ctx context.Context, id string) error {
442442
// here.
443443
func (d Service) deleteCustomers(ctx context.Context, id string, customers []customer.Customer, amounts map[string]accountTokens) error {
444444
for _, c := range customers {
445-
// TODO(fix): the subscription and checkout reads here skip rows with
446-
// deleted_at. Once these deletes turn soft, a row left behind with
447-
// deleted_at set is invisible to this loop. A subscription then blocks the
448-
// customer delete on its foreign key, and a checkout is removed without
449-
// its audit record below. Make these deletes soft in the same change.
450-
// cancels active subscriptions on the billing provider and removes local records
445+
// cancels active subscriptions on the billing provider and hides the local rows
451446
if err := d.subService.DeleteByCustomer(ctx, c); err != nil {
452447
return fmt.Errorf("failed to delete org while deleting a billing account subscriptions[%s]: %w", c.ID, err)
453448
}
454-
// TODO(fix): this delete is due to become a soft delete. An invoice will
455-
// only be allowed to carry deleted_at once its customer already does,
456-
// and the customer below is deleted last, so this order gets rejected.
457-
// Delete the customer first, or run the whole loop in one transaction
458-
// with a deferred check.
459449
if err := d.invoiceService.DeleteByCustomer(ctx, c); err != nil {
460450
return fmt.Errorf("failed to delete org while deleting a billing account invoices[%s]: %w", c.ID, err)
461451
}
@@ -466,8 +456,8 @@ func (d Service) deleteCustomers(ctx context.Context, id string, customers []cus
466456
if err := d.checkoutService.DeleteByCustomer(ctx, c.ID); err != nil {
467457
return fmt.Errorf("failed to delete org while deleting a billing account checkouts[%s]: %w", c.ID, err)
468458
}
469-
// the checkout rows are gone after this; the audit records keep the
470-
// provider references so the sessions can still be found on the provider.
459+
// the checkout rows are hidden after this; the audit records say which
460+
// sessions the delete covered.
471461
// The records are only written when ctx carries the audit service (the
472462
// API path seeds it); otherwise audit.NewLogger falls back to a noop
473463
auditLogger := audit.NewLogger(ctx, id)
@@ -495,7 +485,7 @@ func (d Service) deleteCustomers(ctx context.Context, id string, customers []cus
495485
// tokens still on the account are forfeited by this delete, so
496486
// record the amount before the transactions are removed. The
497487
// purchased share goes on the record too: the transaction rows are
498-
// deleted right after, and support settles a transfer from this
488+
// hidden right after, and support settles a transfer from this
499489
// number later
500490
account, err := d.resolveAccountTokens(ctx, c.ID, amounts)
501491
if err != nil {

‎internal/api/v1beta1connect/billing_errors.go‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,8 @@ func mapBillingErrorCode(err error) *connect.Error {
6969
return connect.NewError(connect.CodeFailedPrecondition, subscription.ErrPhaseIsUpdating)
7070
case errors.Is(err, customer.ErrExistingAccountWithPendingDues):
7171
return connect.NewError(connect.CodeFailedPrecondition, customer.ErrExistingAccountWithPendingDues)
72+
case errors.Is(err, customer.ErrHasLiveRecords):
73+
return connect.NewError(connect.CodeFailedPrecondition, customer.ErrHasLiveRecords)
7274
case errors.Is(err, customer.ErrNotFound):
7375
return connect.NewError(connect.CodeNotFound, ErrCustomerNotFound)
7476
case errors.Is(err, checkout.ErrAlreadySubscribed):

‎internal/api/v1beta1connect/billing_errors_test.go‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,12 @@ func TestMapBillingError(t *testing.T) {
107107
wantCode: connect.CodeFailedPrecondition,
108108
wantMsg: customer.ErrExistingAccountWithPendingDues.Error(),
109109
},
110+
{
111+
name: "live records block the account delete",
112+
err: fmt.Errorf("DeleteBillingAccount.Delete: customer_id=x: %w", customer.ErrHasLiveRecords),
113+
wantCode: connect.CodeFailedPrecondition,
114+
wantMsg: customer.ErrHasLiveRecords.Error(),
115+
},
110116
{
111117
name: "customer not found",
112118
err: fmt.Errorf("CreateCheckout.GetBillingAccountFromOrgID: org_id=abc: %w", customer.ErrNotFound),

‎internal/store/postgres/billing_checkout_repository.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -282,7 +282,7 @@ func (r BillingCheckoutRepository) UpdateByID(ctx context.Context, toUpdate chec
282282
}
283283

284284
func (r BillingCheckoutRepository) DeleteByCustomerID(ctx context.Context, customerID string) error {
285-
query, params, err := dialect.Delete(TABLE_BILLING_CHECKOUTS).Where(goqu.Ex{
285+
query, params, err := softDelete(TABLE_BILLING_CHECKOUTS).Where(goqu.Ex{
286286
"customer_id": customerID,
287287
}).ToSQL()
288288
if err != nil {

‎internal/store/postgres/billing_checkout_repository_pg_test.go‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,3 +99,21 @@ func (s *BillingCheckoutRepositoryPGTestSuite) TestListSkipsDeleted() {
9999
func TestBillingCheckoutRepositoryPG(t *testing.T) {
100100
suite.Run(t, new(BillingCheckoutRepositoryPGTestSuite))
101101
}
102+
103+
func (s *BillingCheckoutRepositoryPGTestSuite) TestDeleteByCustomerIDKeepsTheRowsAndHidesThem() {
104+
before := scalarSQL(s.T(), s.ctx, s.client,
105+
`SELECT deleted_at::text FROM billing_checkouts WHERE provider_id = 'bch-gone-session'`)
106+
107+
s.Require().NoError(s.repository.DeleteByCustomerID(s.ctx, s.customerID()))
108+
109+
s.Equal("2", scalarSQL(s.T(), s.ctx, s.client,
110+
`SELECT count(*)::text FROM billing_checkouts WHERE customer_id = $1 AND deleted_at IS NOT NULL`, s.customerID()))
111+
s.Equal(before, scalarSQL(s.T(), s.ctx, s.client,
112+
`SELECT deleted_at::text FROM billing_checkouts WHERE provider_id = 'bch-gone-session'`),
113+
"a row deleted earlier keeps its first delete time")
114+
got, err := s.repository.List(s.ctx, checkout.Filter{CustomerID: s.customerID()})
115+
s.Require().NoError(err)
116+
s.Empty(got)
117+
_, err = s.repository.GetByID(s.ctx, s.checkoutID("bch-live-session"))
118+
s.ErrorIs(err, checkout.ErrNotFound)
119+
}

‎internal/store/postgres/billing_customer_repository.go‎

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import (
1414
"github.com/raystack/frontier/pkg/utils"
1515

1616
"github.com/doug-martin/goqu/v9"
17+
"github.com/doug-martin/goqu/v9/exp"
1718
"github.com/jmoiron/sqlx/types"
1819
"github.com/raystack/frontier/billing/customer"
1920
"github.com/raystack/frontier/pkg/auditrecord"
@@ -497,16 +498,40 @@ func (r BillingCustomerRepository) UpdateDetailsByID(ctx context.Context, custom
497498
}
498499

499500
func (r BillingCustomerRepository) Delete(ctx context.Context, id string) error {
500-
query, params, err := dialect.Delete(TABLE_BILLING_CUSTOMERS).
501+
lockQuery, lockParams, err := fromLive(TABLE_BILLING_CUSTOMERS).
502+
Select("id").
503+
Where(goqu.Ex{"id": id}).
504+
ForUpdate(exp.Wait).
505+
ToSQL()
506+
if err != nil {
507+
return fmt.Errorf("%w: %w", errParse, err)
508+
}
509+
query, params, err := softDelete(TABLE_BILLING_CUSTOMERS).
501510
Where(goqu.Ex{"id": id}).
502511
Returning(&Customer{}).ToSQL()
503512
if err != nil {
504513
return fmt.Errorf("%w: %w", errParse, err)
505514
}
515+
liveRecordsQuery, liveRecordsParams, err := liveBillingRecordsQuery(id)
516+
if err != nil {
517+
return fmt.Errorf("%w: %w", errParse, err)
518+
}
506519

507520
var customerModel Customer
508521
if err = r.dbc.WithTxn(ctx, sql.TxOptions{}, func(tx *sqlx.Tx) error {
509522
return r.dbc.WithTimeout(ctx, TABLE_BILLING_CUSTOMERS, "Delete", func(ctx context.Context) error {
523+
var lockedID string
524+
if err := tx.QueryRowxContext(ctx, lockQuery, lockParams...).Scan(&lockedID); err != nil {
525+
return err
526+
}
527+
528+
var liveRecords bool
529+
if err := tx.QueryRowxContext(ctx, liveRecordsQuery, liveRecordsParams...).Scan(&liveRecords); err != nil {
530+
return err
531+
}
532+
if liveRecords {
533+
return customer.ErrHasLiveRecords
534+
}
510535
if err := tx.QueryRowxContext(ctx, query, params...).StructScan(&customerModel); err != nil {
511536
if errors.Is(err, sql.ErrNoRows) {
512537
return customer.ErrNotFound
@@ -542,12 +567,22 @@ func (r BillingCustomerRepository) Delete(ctx context.Context, id string) error
542567
}); err != nil {
543568
err = checkPostgresError(err)
544569
switch {
545-
case errors.Is(err, sql.ErrNoRows):
570+
case errors.Is(err, customer.ErrNotFound), errors.Is(err, sql.ErrNoRows):
546571
return customer.ErrNotFound
572+
case errors.Is(err, customer.ErrHasLiveRecords):
573+
return customer.ErrHasLiveRecords
547574
default:
548575
return fmt.Errorf("%w: %w", errTxn, err)
549576
}
550577
}
551578

552579
return nil
553580
}
581+
582+
func liveBillingRecordsQuery(customerID string) (string, []any, error) {
583+
return dialect.Select(goqu.Or(
584+
goqu.L("EXISTS (SELECT 1 FROM billing_subscriptions WHERE customer_id = ? AND deleted_at IS NULL)", customerID),
585+
goqu.L("EXISTS (SELECT 1 FROM billing_invoices WHERE customer_id = ? AND deleted_at IS NULL)", customerID),
586+
goqu.L("EXISTS (SELECT 1 FROM billing_checkouts WHERE customer_id = ? AND deleted_at IS NULL)", customerID),
587+
)).ToSQL()
588+
}

0 commit comments

Comments
 (0)