Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion billing/checkout/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,8 @@ func (s *Service) Create(ctx context.Context, ch Checkout) (Checkout, error) {
Metadata: map[string]any{
"plan_name": plan.Name,
InitiatorIDMetadataKey: currentPrincipal.ID,
"org_id": billingCustomer.OrgID,
"customer_name": billingCustomer.Name,
},
ExpireAt: utils.AsTimeFromEpoch(stripeCheckout.ExpiresAt),
})
Expand Down Expand Up @@ -477,6 +479,8 @@ func (s *Service) Create(ctx context.Context, ch Checkout) (Checkout, error) {
Metadata: map[string]any{
"product_name": chProduct.Name,
InitiatorIDMetadataKey: currentPrincipal.ID,
"org_id": billingCustomer.OrgID,
"customer_name": billingCustomer.Name,
},
ExpireAt: utils.AsTimeFromEpoch(stripeCheckout.ExpiresAt),
})
Expand Down Expand Up @@ -813,7 +817,9 @@ func (s *Service) CreateSessionForPaymentMethod(ctx context.Context, ch Checkout
State: string(stripeCheckout.Status),
ExpireAt: utils.AsTimeFromEpoch(stripeCheckout.ExpiresAt),
Metadata: map[string]any{
"mode": "setup",
"mode": "setup",
"org_id": billingCustomer.OrgID,
"customer_name": billingCustomer.Name,
},
})
}
Expand Down
4 changes: 0 additions & 4 deletions core/auditrecord/auditrecord.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,6 @@ import (
"github.com/raystack/frontier/pkg/utils"
)

var (
systemActor = "system"
)

type AuditRecord struct {
ID string `json:"id,omitempty"`
Event string `json:"event"`
Expand Down
5 changes: 3 additions & 2 deletions core/auditrecord/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"github.com/raystack/frontier/core/serviceuser"
userpkg "github.com/raystack/frontier/core/user"
"github.com/raystack/frontier/internal/bootstrap/schema"
"github.com/raystack/frontier/pkg/auditrecord"
"github.com/raystack/frontier/pkg/server/consts"
"github.com/raystack/salt/rql"
)
Expand Down Expand Up @@ -79,8 +80,8 @@ func (s *Service) Create(ctx context.Context, auditRecord AuditRecord) (AuditRec
// enrich actor info
switch {
case auditRecord.Actor.ID == uuid.Nil.String():
auditRecord.Actor.Type = systemActor
auditRecord.Actor.Name = systemActor
auditRecord.Actor.Type = auditrecord.SystemActor
auditRecord.Actor.Name = auditrecord.SystemActor

case auditRecord.Actor.Type == schema.UserPrincipal:
actorUUID, err := uuid.Parse(auditRecord.Actor.ID)
Expand Down
10 changes: 9 additions & 1 deletion internal/store/postgres/audit_record.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/pkg/errors"

"github.com/raystack/frontier/core/auditrecord"
pkgAuditRecord "github.com/raystack/frontier/pkg/auditrecord"
"github.com/raystack/frontier/pkg/metadata"
"github.com/raystack/frontier/pkg/server/consts"
)
Expand Down Expand Up @@ -214,7 +215,14 @@ func BuildAuditRecord(ctx context.Context, event string, resource AuditResource,
actorMetadata[consts.AuditSessionMetadataKey] = sessionMetadata
}

actorUUID, _ := uuid.Parse(actorID)
var actorUUID uuid.UUID
if actorID == "" { // cron jobs
actorUUID = uuid.Nil
actorType = pkgAuditRecord.SystemActor
actorName = pkgAuditRecord.SystemActor
} else {
actorUUID, _ = uuid.Parse(actorID)
}
orgUUID, _ := uuid.Parse(orgID)

record := AuditRecord{
Expand Down
45 changes: 43 additions & 2 deletions internal/store/postgres/billing_checkout_repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ import (
"strings"
"time"

"github.com/jmoiron/sqlx"
"github.com/raystack/frontier/billing/checkout"
"github.com/raystack/frontier/pkg/auditrecord"

"github.com/doug-martin/goqu/v9"
"github.com/jmoiron/sqlx/types"
Expand Down Expand Up @@ -160,8 +162,47 @@ func (r BillingCheckoutRepository) Create(ctx context.Context, toCreate checkout
}

var checkoutModel Checkout
if err = r.dbc.WithTimeout(ctx, TABLE_BILLING_CHECKOUTS, "Create", func(ctx context.Context) error {
return r.dbc.QueryRowxContext(ctx, query, params...).StructScan(&checkoutModel)
if err = r.dbc.WithTxn(ctx, sql.TxOptions{}, func(tx *sqlx.Tx) error {
return r.dbc.WithTimeout(ctx, TABLE_BILLING_CHECKOUTS, "Create", func(ctx context.Context) error {
if err := tx.QueryRowxContext(ctx, query, params...).StructScan(&checkoutModel); err != nil {
return err
}

metadataMap, err := unmarshalNullJSONText(checkoutModel.Metadata)
if err != nil {
return err
}
orgID := getStringFromMap(metadataMap, "org_id")
customerName := getStringFromMap(metadataMap, "customer_name")

auditRecord := BuildAuditRecord(
ctx,
auditrecord.BillingCheckoutCreatedEvent.String(),
AuditResource{
ID: checkoutModel.CustomerID,
Type: "billing_customer",
Name: customerName,
},
&AuditTarget{
ID: checkoutModel.ID,
Type: "billing_checkout",
Metadata: map[string]interface{}{
"plan_id": ptrToString(checkoutModel.PlanID),
"feature_id": ptrToString(checkoutModel.FeatureID),
"state": checkoutModel.State,
"provider_id": checkoutModel.ProviderID,
"customer_id": checkoutModel.CustomerID,
"checkout_url": checkoutModel.CheckoutUrl,
"skip_trial": checkoutModel.SubscriptionConfig.SkipTrial,
"cancel_after_trial": checkoutModel.SubscriptionConfig.CancelAfterTrial,
},
},
orgID,
nil,
checkoutModel.CreatedAt,
)
return InsertAuditRecordInTx(ctx, tx, auditRecord)
})
}); err != nil {
return checkout.Checkout{}, fmt.Errorf("%w: %s", dbErr, err)
}
Expand Down
134 changes: 121 additions & 13 deletions internal/store/postgres/billing_customer_repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@ import (
"strings"
"time"

"github.com/jmoiron/sqlx"
"github.com/raystack/frontier/pkg/utils"

"github.com/doug-martin/goqu/v9"
"github.com/jmoiron/sqlx/types"
"github.com/raystack/frontier/billing/customer"
"github.com/raystack/frontier/pkg/auditrecord"
"github.com/raystack/frontier/pkg/db"
)

Expand Down Expand Up @@ -152,8 +154,35 @@ func (r BillingCustomerRepository) Create(ctx context.Context, toCreate customer
}

var customerModel Customer
if err = r.dbc.WithTimeout(ctx, TABLE_BILLING_CUSTOMERS, "Create", func(ctx context.Context) error {
return r.dbc.QueryRowxContext(ctx, query, params...).StructScan(&customerModel)
if err = r.dbc.WithTxn(ctx, sql.TxOptions{}, func(tx *sqlx.Tx) error {
return r.dbc.WithTimeout(ctx, TABLE_BILLING_CUSTOMERS, "Create", func(ctx context.Context) error {
if err := tx.QueryRowxContext(ctx, query, params...).StructScan(&customerModel); err != nil {
return err
}

auditRecord := BuildAuditRecord(
ctx,
auditrecord.BillingCustomerCreatedEvent.String(),
AuditResource{
ID: customerModel.ID,
Type: "billing_customer",
Name: customerModel.Name,
Metadata: map[string]interface{}{
"email": customerModel.Email,
"currency": customerModel.Currency,
"address": customerModel.Address,
"credit_min": customerModel.CreditMin,
"due_in_days": customerModel.DueInDays,
"provider_id": customerModel.ProviderID,
},
},
nil,
customerModel.OrgID,
nil,
customerModel.CreatedAt,
)
return InsertAuditRecordInTx(ctx, tx, auditRecord)
})
}); err != nil {
return customer.Customer{}, fmt.Errorf("%w: %w", dbErr, err)
}
Expand Down Expand Up @@ -276,8 +305,33 @@ func (r BillingCustomerRepository) UpdateByID(ctx context.Context, toUpdate cust
}

var customerModel Customer
if err = r.dbc.WithTimeout(ctx, TABLE_BILLING_CUSTOMERS, "Update", func(ctx context.Context) error {
return r.dbc.QueryRowxContext(ctx, query, params...).StructScan(&customerModel)
if err = r.dbc.WithTxn(ctx, sql.TxOptions{}, func(tx *sqlx.Tx) error {
return r.dbc.WithTimeout(ctx, TABLE_BILLING_CUSTOMERS, "Update", func(ctx context.Context) error {
if err := tx.QueryRowxContext(ctx, query, params...).StructScan(&customerModel); err != nil {
return err
}

auditRecord := BuildAuditRecord(
ctx,
auditrecord.BillingCustomerUpdatedEvent.String(),
AuditResource{
ID: customerModel.ID,
Type: "billing_customer",
Name: customerModel.Name,
Metadata: map[string]interface{}{
"email": customerModel.Email,
"currency": customerModel.Currency,
"address": customerModel.Address,
"provider_id": customerModel.ProviderID,
},
},
nil,
customerModel.OrgID,
nil,
customerModel.UpdatedAt,
)
return InsertAuditRecordInTx(ctx, tx, auditRecord)
})
}); err != nil {
err = checkPostgresError(err)
switch {
Expand Down Expand Up @@ -376,8 +430,31 @@ func (r BillingCustomerRepository) UpdateDetailsByID(ctx context.Context, custom
}

var customerModel Customer
if err = r.dbc.WithTimeout(ctx, TABLE_BILLING_CUSTOMERS, "UpdateDetailsByID", func(ctx context.Context) error {
return r.dbc.QueryRowxContext(ctx, query, params...).StructScan(&customerModel)
if err = r.dbc.WithTxn(ctx, sql.TxOptions{}, func(tx *sqlx.Tx) error {
return r.dbc.WithTimeout(ctx, TABLE_BILLING_CUSTOMERS, "UpdateDetailsByID", func(ctx context.Context) error {
if err := tx.QueryRowxContext(ctx, query, params...).StructScan(&customerModel); err != nil {
return err
}

auditRecord := BuildAuditRecord(
ctx,
auditrecord.BillingCustomerCreditUpdatedEvent.String(),
AuditResource{
ID: customerModel.ID,
Type: "billing_customer",
Name: customerModel.Name,
Metadata: map[string]interface{}{
"credit_min": customerModel.CreditMin,
"due_in_days": customerModel.DueInDays,
},
},
nil,
customerModel.OrgID,
nil,
customerModel.UpdatedAt,
)
return InsertAuditRecordInTx(ctx, tx, auditRecord)
})
}); err != nil {
err = checkPostgresError(err)
switch {
Expand All @@ -397,17 +474,48 @@ func (r BillingCustomerRepository) UpdateDetailsByID(ctx context.Context, custom
}

func (r BillingCustomerRepository) Delete(ctx context.Context, id string) error {
stmt := dialect.Delete(TABLE_BILLING_CUSTOMERS).Where(goqu.Ex{
"id": id,
})
query, params, err := stmt.ToSQL()
query, params, err := dialect.Delete(TABLE_BILLING_CUSTOMERS).
Where(goqu.Ex{"id": id}).
Returning(&Customer{}).ToSQL()
if err != nil {
return fmt.Errorf("%w: %w", parseErr, err)
}

if err = r.dbc.WithTimeout(ctx, TABLE_BILLING_CUSTOMERS, "Delete", func(ctx context.Context) error {
_, err := r.dbc.ExecContext(ctx, query, params...)
return err
var customerModel Customer
if err = r.dbc.WithTxn(ctx, sql.TxOptions{}, func(tx *sqlx.Tx) error {
return r.dbc.WithTimeout(ctx, TABLE_BILLING_CUSTOMERS, "Delete", func(ctx context.Context) error {
if err := tx.QueryRowxContext(ctx, query, params...).StructScan(&customerModel); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return customer.ErrNotFound
}
return err
}

deletedAt := time.Now()
if customerModel.DeletedAt != nil {
deletedAt = *customerModel.DeletedAt
}

auditRecord := BuildAuditRecord(
ctx,
auditrecord.BillingCustomerDeletedEvent.String(),
AuditResource{
ID: customerModel.ID,
Type: "billing_customer",
Name: customerModel.Name,
Metadata: map[string]interface{}{
"email": customerModel.Email,
"currency": customerModel.Currency,
"address": customerModel.Address,
},
},
nil,
customerModel.OrgID,
nil,
deletedAt,
)
return InsertAuditRecordInTx(ctx, tx, auditRecord)
})
}); err != nil {
err = checkPostgresError(err)
switch {
Expand Down
50 changes: 50 additions & 0 deletions internal/store/postgres/billing_transactions_repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
"strings"
"time"

"github.com/raystack/frontier/pkg/auditrecord"

"github.com/raystack/frontier/billing/customer"

"github.com/raystack/frontier/internal/bootstrap/schema"
Expand Down Expand Up @@ -163,6 +165,54 @@ func (r BillingTransactionRepository) CreateEntry(ctx context.Context, debitEntr
if err := r.createTransactionEntry(ctx, tx, creditEntry, &creditModel); err != nil {
return fmt.Errorf("failed to create credit entry: %w", err)
}

auditCustomerID := debitEntry.CustomerID
if auditCustomerID == schema.PlatformOrgID.String() {
auditCustomerID = creditEntry.CustomerID
}

if auditCustomerID != schema.PlatformOrgID.String() {
// Determine if this is credit or debit for the customer
var eventType string
var txModel Transaction
var txEntry credit.Transaction

if debitEntry.CustomerID == auditCustomerID {
eventType = auditrecord.BillingTransactionDebitEvent.String()
txModel = debitModel
txEntry = debitEntry
} else {
eventType = auditrecord.BillingTransactionCreditEvent.String()
txModel = creditModel
txEntry = creditEntry
}

auditRecord := BuildAuditRecord(
ctx,
eventType,
AuditResource{
ID: auditCustomerID,
Type: "billing_customer",
Name: customerAcc.Name,
},
&AuditTarget{
ID: txModel.ID,
Type: "billing_transaction",
Metadata: map[string]interface{}{
"amount": txEntry.Amount,
"source": txEntry.Source,
"description": txEntry.Description,
},
},
customerAcc.OrgID,
nil,
debitModel.CreatedAt,
)
if err := InsertAuditRecordInTx(ctx, tx, auditRecord); err != nil {
return fmt.Errorf("failed to insert audit record: %w", err)
}
}

return nil
})
})
Expand Down
Loading
Loading