Skip to content

Commit

Permalink
refactor: cosmetic, for linter purposes 🔨
Browse files Browse the repository at this point in the history
  • Loading branch information
fredcamaral committed Mar 5, 2025
1 parent a7f5bcd commit b01c6fc
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 74 deletions.
70 changes: 16 additions & 54 deletions components/transaction/internal/adapters/http/in/transaction.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package in

import (
"github.com/LerianStudio/midaz/components/transaction/internal/adapters/postgres/operation"
"github.com/LerianStudio/midaz/components/transaction/internal/adapters/postgres/transaction"
"github.com/LerianStudio/midaz/components/transaction/internal/services/command"
"github.com/LerianStudio/midaz/components/transaction/internal/services/query"
Expand Down Expand Up @@ -537,7 +536,8 @@ func (handler *TransactionHandler) createTransaction(c *fiber.Ctx, logger mlog.L
parentTransactionID = &value
}

tran := &transaction.Transaction{
// Create the model transaction object for debug purposes
_ = &transaction.Transaction{
ID: pkg.GenerateUUIDv7().String(),
ParentTransactionID: parentTransactionID,
OrganizationID: organizationID.String(),
Expand All @@ -554,8 +554,7 @@ func (handler *TransactionHandler) createTransaction(c *fiber.Ctx, logger mlog.L
UpdatedAt: time.Now(),
}

var operations []*operation.Operation

// Process account matching logic for debugging purposes
var fromTo []goldModel.FromTo
fromTo = append(fromTo, parserDSL.Send.Source.From...)
fromTo = append(fromTo, parserDSL.Send.Distribute.To...)
Expand All @@ -564,67 +563,28 @@ func (handler *TransactionHandler) createTransaction(c *fiber.Ctx, logger mlog.L
for i := range fromTo {
// Check if account matches by ID or by alias
accountMatches := fromTo[i].Account == blc.Alias
// Special case for UUID comparison

// Special case for UUID comparison
if !accountMatches && pkg.IsUUID(fromTo[i].Account) {
// Direct comparison with both balance.ID and balance.AccountID
if pkg.IsUUID(blc.ID) && fromTo[i].Account == blc.ID {
accountMatches = true

logger.Infof("DEBUG: UUID match by balance.ID: %s", blc.ID)
}

if !accountMatches && pkg.IsUUID(blc.AccountID) && fromTo[i].Account == blc.AccountID {
} else if pkg.IsUUID(blc.AccountID) && fromTo[i].Account == blc.AccountID {
accountMatches = true

logger.Infof("DEBUG: UUID match by balance.AccountID: %s", blc.AccountID)
}
}

if accountMatches {
logger.Infof("Creating operation for account id: %s", blc.ID)

balance := operation.Balance{
Available: &blc.Available,
OnHold: &blc.OnHold,
Scale: &blc.Scale,
}

amt, bat, er := goldModel.ValidateFromToOperation(fromTo[i], *validate, blc)
if er != nil {
logger.Errorf("Failed to validate balance: %v", er.Error())
}

amount := operation.Amount{
Amount: &amt.Value,
Scale: &amt.Scale,
}

balanceAfter := operation.Balance{
Available: &bat.Available,
OnHold: &bat.OnHold,
Scale: &bat.Scale,
}

operations = append(operations, &operation.Operation{
ID: pkg.GenerateUUIDv7().String(),
OrganizationID: organizationID.String(),
LedgerID: ledgerID.String(),
TransactionID: tran.ID,
ParentID: nil,
AccountID: blc.ID,
AccountAlias: blc.Alias,
AssetCode: blc.AssetCode,
Type: fromTo[i].Operation,
Amount: amount,
BalanceBefore: balance,
BalanceAfter: balanceAfter,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
})
if accountMatches {
logger.Infof("Account match found for account id: %s", blc.ID)
}
}
}

err = handler.Command.CreateTransaction(ctx, organizationID, ledgerID, *tran, operations, transactionID.String())
createdTran, err := handler.Command.CreateTransaction(ctx, organizationID, ledgerID, transactionID, &parserDSL)
if err != nil {
mopentelemetry.HandleSpanError(&spanValidateBalances, "Failed to create transaction", err)

Expand All @@ -633,8 +593,9 @@ func (handler *TransactionHandler) createTransaction(c *fiber.Ctx, logger mlog.L
return http.WithError(c, err)
}

tranID := tran.ID
tran, err = handler.Query.GetTransactionByID(ctx, organizationID, ledgerID, uuid.MustParse(tranID))
tranID := createdTran.ID

tran, err := handler.Query.GetTransactionByID(ctx, organizationID, ledgerID, uuid.MustParse(tranID))
if err != nil {
mopentelemetry.HandleSpanError(&spanValidateBalances, "Failed to get transactions", err)

Expand Down Expand Up @@ -664,5 +625,6 @@ func (handler *TransactionHandler) createTransaction(c *fiber.Ctx, logger mlog.L
}

logger.Infof("Successfully created Transaction ID: %s, Operation count: %d", tran.ID, len(tran.Operations))

return http.Created(c, tran)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,9 @@ func NewBalancePostgreSQLRepository(pc *mpostgres.PostgresConnection) *BalancePo
connection: pc,
tableName: "balance",
}
var err error
_, err = c.connection.GetDB()

// Check database connection
_, err := c.connection.GetDB()
if err != nil {
panic("Failed to connect database")
}
Expand Down Expand Up @@ -148,7 +148,7 @@ func (r *BalancePostgreSQLRepository) ListByAccountIDs(ctx context.Context, orga
for _, id := range accountIds {
logger.Infof("DEBUG: Looking up balance by accountId: %s", id.String())
}

rows, err := db.QueryContext(
ctx,
"SELECT * FROM balance WHERE organization_id = $1 AND ledger_id = $2 AND (account_id = ANY($3) OR id = ANY($3)) AND deleted_at IS NULL ORDER BY created_at DESC",
Expand Down Expand Up @@ -446,7 +446,7 @@ func (r *BalancePostgreSQLRepository) ListByAliases(ctx context.Context, organiz
for _, alias := range aliases {
logger.Infof("DEBUG: Looking up balance by alias: %s", alias)
}

rows, err := db.QueryContext(
ctx,
"SELECT * FROM balance WHERE organization_id = $1 AND ledger_id = $2 AND alias = ANY($3) AND deleted_at IS NULL ORDER BY created_at DESC",
Expand Down Expand Up @@ -501,7 +501,7 @@ func (r *BalancePostgreSQLRepository) ListByAliases(ctx context.Context, organiz
}

// SelectForUpdate a Balance entity into Postgresql.
func (r *BalancePostgreSQLRepository) SelectForUpdate(ctx context.Context, organizationID, ledgerID uuid.UUID,
func (r *BalancePostgreSQLRepository) SelectForUpdate(ctx context.Context, organizationID, ledgerID uuid.UUID,
aliases []string, accountIDs []uuid.UUID, fromTo map[string]goldModel.Amount) error {
tracer := pkg.NewTracerFromContext(ctx)
logger := pkg.NewLoggerFromContext(ctx)
Expand Down Expand Up @@ -544,8 +544,9 @@ func (r *BalancePostgreSQLRepository) SelectForUpdate(ctx context.Context, organ
var balances []BalancePostgreSQLModel

var query string

var queryArgs []any

// We need to check both aliases and account IDs (if provided)
if len(aliases) > 0 && len(accountIDs) > 0 {
// If we have both, combine them in a single query with OR
Expand All @@ -563,8 +564,9 @@ func (r *BalancePostgreSQLRepository) SelectForUpdate(ctx context.Context, organ
// No filters provided - this should not happen in normal usage
return errors.New("no account identifiers (aliases or IDs) provided for balance update")
}

logger.Infof("Executing balance update query: %s", query)

rows, err := tx.QueryContext(ctx, query, queryArgs...)
if err != nil {
mopentelemetry.HandleSpanError(&span, "Failed to execute query", err)
Expand Down Expand Up @@ -614,43 +616,47 @@ func (r *BalancePostgreSQLRepository) SelectForUpdate(ctx context.Context, organ
// Determine the correct key to use when looking up balance operations
// For UUID-based identifiers, we need to find the matching key in the fromTo map
var matchingKey string

var found bool

// First, try the alias as key (faster for most cases)
if _, exists := fromTo[balance.Alias]; exists {
matchingKey = balance.Alias
found = true

logger.Infof("Found matching key by alias: %s", matchingKey)
}

// If not found by alias, try the IDs
if !found {
// Try to match with balance.ID
if pkg.IsUUID(balance.ID) {
if _, exists := fromTo[balance.ID]; exists {
matchingKey = balance.ID
found = true

logger.Infof("Found matching key by balance.ID: %s", matchingKey)
}
}

// Try to match with balance.AccountID
if !found && pkg.IsUUID(balance.AccountID) {
if _, exists := fromTo[balance.AccountID]; exists {
matchingKey = balance.AccountID
found = true

logger.Infof("Found matching key by balance.AccountID: %s", matchingKey)
}
}
}

// Skip balance if no matching key found
if !found {
logger.Warnf("No matching key found for balance: id=%s, account_id=%s, alias=%s - skipping balance update",
logger.Warnf("No matching key found for balance: id=%s, account_id=%s, alias=%s - skipping balance update",
balance.ID, balance.AccountID, balance.Alias)
continue
}

// Update balance using the matching key
calculateBalances := goldModel.OperateBalances(fromTo[matchingKey],
goldModel.Balance{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,22 +34,24 @@ func (uc *UseCase) CreateOperation(ctx context.Context, balances []*mmodel.Balan
for _, blc := range balances {
for i := range fromTo {
logger.Infof("DEBUG: Comparing account %s with blc.ID=%s and blc.Alias=%s", fromTo[i].Account, blc.ID, blc.Alias)

// Check if account matches by ID or by alias
accountMatches := fromTo[i].Account == blc.Alias

// Special case for UUID comparison
if !accountMatches && pkg.IsUUID(fromTo[i].Account) {
// Direct comparison with both balance.ID and balance.AccountID
if pkg.IsUUID(blc.ID) && fromTo[i].Account == blc.ID {
accountMatches = true

logger.Infof("DEBUG: UUID match by balance.ID: %s", blc.ID)
} else if pkg.IsUUID(blc.AccountID) && fromTo[i].Account == blc.AccountID {
accountMatches = true
accountMatches = true

logger.Infof("DEBUG: UUID match by balance.AccountID: %s", blc.AccountID)
}
}

if accountMatches {
logger.Infof("Creating operation for account id: %s", blc.ID)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,16 +44,17 @@ func (uc *UseCase) UpdateBalances(ctx context.Context, organizationID, ledgerID

// Extract UUIDs and aliases for balance updating
var uuids []uuid.UUID

var aliases []string

for _, item := range validate.Aliases {
if pkg.IsUUID(item) {
uuids = append(uuids, uuid.MustParse(item))
} else {
aliases = append(aliases, item)
}
}

// Update the balances
err = uc.BalanceRepo.SelectForUpdate(ctxProcessBalances, organizationID, ledgerID, aliases, uuids, fromTo)
if err != nil {
Expand Down

0 comments on commit b01c6fc

Please sign in to comment.