getOrCreateBalanceByIndicator retrieves a balance by its indicator and currency. If the balance does not exist, it creates a new one. It starts a tracing span, fetches or creates the balance, and records relevant events. When EnableQueuedChecks is enabled in the transaction config, it will fetch the
(ctx context.Context, indicator, currency string)
| 134 | // - *model.Balance: A pointer to the Balance model. |
| 135 | // - error: An error if the balance could not be retrieved or created. |
| 136 | func (l *LedgerForge) getOrCreateBalanceByIndicator(ctx context.Context, indicator, currency string) (*model.Balance, error) { |
| 137 | ctx, span := balanceTracer.Start(ctx, "GetOrCreateBalanceByIndicator") |
| 138 | defer span.End() |
| 139 | |
| 140 | // Get configuration to check if queued checks are enabled |
| 141 | cfg, err := config.Fetch() |
| 142 | if err != nil { |
| 143 | span.RecordError(err) |
| 144 | logrus.Errorf("failed to fetch config: %v", err) |
| 145 | return nil, err |
| 146 | } |
| 147 | |
| 148 | balance, err := l.datasource.GetBalanceByIndicator(indicator, currency) |
| 149 | if err != nil { |
| 150 | span.AddEvent("Creating new balance") |
| 151 | balance = &model.Balance{ |
| 152 | Indicator: indicator, |
| 153 | LedgerID: GeneralLedgerID, |
| 154 | Currency: currency, |
| 155 | } |
| 156 | _, err := l.CreateBalance(ctx, *balance) |
| 157 | if err != nil && !strings.Contains(err.Error(), "Balance already exist") { |
| 158 | span.RecordError(err) |
| 159 | return nil, err |
| 160 | } |
| 161 | balance, err = l.datasource.GetBalanceByIndicator(indicator, currency) |
| 162 | if err != nil { |
| 163 | span.RecordError(err) |
| 164 | return nil, err |
| 165 | } |
| 166 | span.AddEvent("New balance created", trace.WithAttributes(attribute.String("balance.id", balance.BalanceID))) |
| 167 | |
| 168 | // If queued checks are enabled, fetch the balance with queued data |
| 169 | if cfg.Transaction.EnableQueuedChecks { |
| 170 | balance, err = l.datasource.GetBalanceByID(balance.BalanceID, []string{}, true) |
| 171 | if err != nil { |
| 172 | span.RecordError(err) |
| 173 | return nil, err |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | return balance, nil |
| 178 | } |
| 179 | |
| 180 | // If queued checks are enabled, fetch the balance with queued data |
| 181 | if cfg.Transaction.EnableQueuedChecks { |
| 182 | balance, err = l.datasource.GetBalanceByID(balance.BalanceID, []string{}, true) |
| 183 | if err != nil { |
| 184 | span.RecordError(err) |
| 185 | return nil, err |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | span.AddEvent("Balance found", trace.WithAttributes(attribute.String("balance.id", balance.BalanceID))) |
| 190 | return balance, nil |
| 191 | } |
| 192 | |
| 193 | // postBalanceActions performs some actions after a balance has been created. |
no test coverage detected